agents 0.5.1 → 0.7.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.
@@ -1,5 +1,5 @@
1
- import { t as MCPObservabilityEvent } from "../mcp-DA0kDE7K.js";
2
- import { t as AgentObservabilityEvent } from "../agent-B4_kEsdK.js";
1
+ import { n as MCPObservabilityEvent, t as AgentObservabilityEvent } from "../agent-DnmmRjyv.js";
2
+ import { Channel } from "node:diagnostics_channel";
3
3
 
4
4
  //#region src/observability/index.d.ts
5
5
  /**
@@ -10,14 +10,80 @@ interface Observability {
10
10
  /**
11
11
  * Emit an event for the Agent's observability implementation to handle.
12
12
  * @param event - The event to emit
13
- * @param ctx - The execution context of the invocation (optional)
14
13
  */
15
- emit(event: ObservabilityEvent, ctx?: DurableObjectState): void;
14
+ emit(event: ObservabilityEvent): void;
16
15
  }
17
16
  /**
18
- * A generic observability implementation that logs events to the console.
17
+ * Diagnostics channels for agent observability.
18
+ *
19
+ * Events are published to named channels using the Node.js diagnostics_channel API.
20
+ * By default, publishing to a channel with no subscribers is a no-op (zero overhead).
21
+ *
22
+ * To observe events, subscribe to the channels you care about:
23
+ * ```ts
24
+ * import { subscribe } from "node:diagnostics_channel";
25
+ * subscribe("agents:rpc", (event) => console.log(event));
26
+ * ```
27
+ *
28
+ * In production, all published messages are automatically forwarded to
29
+ * Tail Workers via `event.diagnosticsChannelEvents` — no subscription needed.
30
+ */
31
+ declare const channels: {
32
+ readonly state: Channel<unknown, unknown>;
33
+ readonly rpc: Channel<unknown, unknown>;
34
+ readonly message: Channel<unknown, unknown>;
35
+ readonly schedule: Channel<unknown, unknown>;
36
+ readonly lifecycle: Channel<unknown, unknown>;
37
+ readonly workflow: Channel<unknown, unknown>;
38
+ readonly mcp: Channel<unknown, unknown>;
39
+ };
40
+ /**
41
+ * The default observability implementation.
42
+ *
43
+ * Publishes events to diagnostics_channel. Events are silent unless
44
+ * a subscriber is registered or a Tail Worker is attached.
19
45
  */
20
46
  declare const genericObservability: Observability;
47
+ /**
48
+ * Maps each channel key to the observability events it carries.
49
+ */
50
+ type ChannelEventMap = {
51
+ state: Extract<ObservabilityEvent, {
52
+ type: `state:${string}`;
53
+ }>;
54
+ rpc: Extract<ObservabilityEvent, {
55
+ type: "rpc" | `rpc:${string}`;
56
+ }>;
57
+ message: Extract<ObservabilityEvent, {
58
+ type: `message:${string}` | `tool:${string}`;
59
+ }>;
60
+ schedule: Extract<ObservabilityEvent, {
61
+ type: `schedule:${string}` | `queue:${string}`;
62
+ }>;
63
+ lifecycle: Extract<ObservabilityEvent, {
64
+ type: "connect" | "destroy";
65
+ }>;
66
+ workflow: Extract<ObservabilityEvent, {
67
+ type: `workflow:${string}`;
68
+ }>;
69
+ mcp: Extract<ObservabilityEvent, {
70
+ type: `mcp:${string}`;
71
+ }>;
72
+ };
73
+ /**
74
+ * Subscribe to a typed observability channel.
75
+ *
76
+ * ```ts
77
+ * import { subscribe } from "agents/observability";
78
+ *
79
+ * const unsub = subscribe("rpc", (event) => {
80
+ * console.log(event.payload.method); // fully typed
81
+ * });
82
+ * ```
83
+ *
84
+ * @returns A function that unsubscribes the callback.
85
+ */
86
+ declare function subscribe<K extends keyof ChannelEventMap>(channelKey: K, callback: (event: ChannelEventMap[K]) => void): () => void;
21
87
  //#endregion
22
- export { Observability, ObservabilityEvent, genericObservability };
88
+ export { ChannelEventMap, Observability, ObservabilityEvent, channels, genericObservability, subscribe };
23
89
  //# sourceMappingURL=index.d.ts.map
@@ -1,26 +1,71 @@
1
- import "../client-connection-CGMuV62J.js";
2
- import { getCurrentAgent } from "../index.js";
1
+ import { channel, subscribe as subscribe$1, unsubscribe } from "node:diagnostics_channel";
3
2
 
4
3
  //#region src/observability/index.ts
5
4
  /**
6
- * A generic observability implementation that logs events to the console.
5
+ * Diagnostics channels for agent observability.
6
+ *
7
+ * Events are published to named channels using the Node.js diagnostics_channel API.
8
+ * By default, publishing to a channel with no subscribers is a no-op (zero overhead).
9
+ *
10
+ * To observe events, subscribe to the channels you care about:
11
+ * ```ts
12
+ * import { subscribe } from "node:diagnostics_channel";
13
+ * subscribe("agents:rpc", (event) => console.log(event));
14
+ * ```
15
+ *
16
+ * In production, all published messages are automatically forwarded to
17
+ * Tail Workers via `event.diagnosticsChannelEvents` — no subscription needed.
18
+ */
19
+ const channels = {
20
+ state: channel("agents:state"),
21
+ rpc: channel("agents:rpc"),
22
+ message: channel("agents:message"),
23
+ schedule: channel("agents:schedule"),
24
+ lifecycle: channel("agents:lifecycle"),
25
+ workflow: channel("agents:workflow"),
26
+ mcp: channel("agents:mcp")
27
+ };
28
+ /**
29
+ * Map event type prefixes to their diagnostics channel.
30
+ */
31
+ function getChannel(type) {
32
+ if (type.startsWith("mcp:")) return channels.mcp;
33
+ if (type.startsWith("workflow:")) return channels.workflow;
34
+ if (type.startsWith("schedule:") || type.startsWith("queue:")) return channels.schedule;
35
+ if (type.startsWith("message:") || type.startsWith("tool:")) return channels.message;
36
+ if (type === "rpc" || type.startsWith("rpc:")) return channels.rpc;
37
+ if (type.startsWith("state:")) return channels.state;
38
+ return channels.lifecycle;
39
+ }
40
+ /**
41
+ * The default observability implementation.
42
+ *
43
+ * Publishes events to diagnostics_channel. Events are silent unless
44
+ * a subscriber is registered or a Tail Worker is attached.
7
45
  */
8
46
  const genericObservability = { emit(event) {
9
- if (isLocalMode()) {
10
- console.log(event.displayMessage);
11
- return;
12
- }
13
- console.log(event);
47
+ getChannel(event.type).publish(event);
14
48
  } };
15
- let localMode = false;
16
- function isLocalMode() {
17
- if (localMode) return true;
18
- const { request } = getCurrentAgent();
19
- if (!request) return false;
20
- localMode = new URL(request.url).hostname === "localhost";
21
- return localMode;
49
+ /**
50
+ * Subscribe to a typed observability channel.
51
+ *
52
+ * ```ts
53
+ * import { subscribe } from "agents/observability";
54
+ *
55
+ * const unsub = subscribe("rpc", (event) => {
56
+ * console.log(event.payload.method); // fully typed
57
+ * });
58
+ * ```
59
+ *
60
+ * @returns A function that unsubscribes the callback.
61
+ */
62
+ function subscribe(channelKey, callback) {
63
+ const name = `agents:${channelKey}`;
64
+ const handler = (message, _name) => callback(message);
65
+ subscribe$1(name, handler);
66
+ return () => unsubscribe(name, handler);
22
67
  }
23
68
 
24
69
  //#endregion
25
- export { genericObservability };
70
+ export { channels, genericObservability, subscribe };
26
71
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/observability/index.ts"],"sourcesContent":["import { getCurrentAgent } from \"../index\";\nimport type { AgentObservabilityEvent } from \"./agent\";\nimport type { MCPObservabilityEvent } from \"./mcp\";\n\n/**\n * Union of all observability event types from different domains\n */\nexport type ObservabilityEvent =\n | AgentObservabilityEvent\n | MCPObservabilityEvent;\n\nexport interface Observability {\n /**\n * Emit an event for the Agent's observability implementation to handle.\n * @param event - The event to emit\n * @param ctx - The execution context of the invocation (optional)\n */\n emit(event: ObservabilityEvent, ctx?: DurableObjectState): void;\n}\n\n/**\n * A generic observability implementation that logs events to the console.\n */\nexport const genericObservability: Observability = {\n emit(event) {\n // In local mode, we display a pretty-print version of the event for easier debugging.\n if (isLocalMode()) {\n console.log(event.displayMessage);\n return;\n }\n\n console.log(event);\n }\n};\n\nlet localMode = false;\n\nfunction isLocalMode() {\n if (localMode) {\n return true;\n }\n const { request } = getCurrentAgent();\n if (!request) {\n return false;\n }\n\n const url = new URL(request.url);\n localMode = url.hostname === \"localhost\";\n return localMode;\n}\n"],"mappings":";;;;;;;AAuBA,MAAa,uBAAsC,EACjD,KAAK,OAAO;AAEV,KAAI,aAAa,EAAE;AACjB,UAAQ,IAAI,MAAM,eAAe;AACjC;;AAGF,SAAQ,IAAI,MAAM;GAErB;AAED,IAAI,YAAY;AAEhB,SAAS,cAAc;AACrB,KAAI,UACF,QAAO;CAET,MAAM,EAAE,YAAY,iBAAiB;AACrC,KAAI,CAAC,QACH,QAAO;AAIT,aADY,IAAI,IAAI,QAAQ,IAAI,CAChB,aAAa;AAC7B,QAAO"}
1
+ {"version":3,"file":"index.js","names":["dcUnsubscribe"],"sources":["../../src/observability/index.ts"],"sourcesContent":["import {\n channel,\n subscribe as dcSubscribe,\n unsubscribe as dcUnsubscribe,\n type Channel\n} from \"node:diagnostics_channel\";\nimport type { AgentObservabilityEvent } from \"./agent\";\nimport type { MCPObservabilityEvent } from \"./mcp\";\n\n/**\n * Union of all observability event types from different domains\n */\nexport type ObservabilityEvent =\n | AgentObservabilityEvent\n | MCPObservabilityEvent;\n\nexport interface Observability {\n /**\n * Emit an event for the Agent's observability implementation to handle.\n * @param event - The event to emit\n */\n emit(event: ObservabilityEvent): void;\n}\n\n/**\n * Diagnostics channels for agent observability.\n *\n * Events are published to named channels using the Node.js diagnostics_channel API.\n * By default, publishing to a channel with no subscribers is a no-op (zero overhead).\n *\n * To observe events, subscribe to the channels you care about:\n * ```ts\n * import { subscribe } from \"node:diagnostics_channel\";\n * subscribe(\"agents:rpc\", (event) => console.log(event));\n * ```\n *\n * In production, all published messages are automatically forwarded to\n * Tail Workers via `event.diagnosticsChannelEvents` — no subscription needed.\n */\nexport const channels = {\n state: channel(\"agents:state\"),\n rpc: channel(\"agents:rpc\"),\n message: channel(\"agents:message\"),\n schedule: channel(\"agents:schedule\"),\n lifecycle: channel(\"agents:lifecycle\"),\n workflow: channel(\"agents:workflow\"),\n mcp: channel(\"agents:mcp\")\n} as const;\n\n/**\n * Map event type prefixes to their diagnostics channel.\n */\nfunction getChannel(type: string): Channel {\n if (type.startsWith(\"mcp:\")) return channels.mcp;\n if (type.startsWith(\"workflow:\")) return channels.workflow;\n if (type.startsWith(\"schedule:\") || type.startsWith(\"queue:\"))\n return channels.schedule;\n if (type.startsWith(\"message:\") || type.startsWith(\"tool:\"))\n return channels.message;\n if (type === \"rpc\" || type.startsWith(\"rpc:\")) return channels.rpc;\n if (type.startsWith(\"state:\")) return channels.state;\n // connect, destroy\n return channels.lifecycle;\n}\n\n/**\n * The default observability implementation.\n *\n * Publishes events to diagnostics_channel. Events are silent unless\n * a subscriber is registered or a Tail Worker is attached.\n */\nexport const genericObservability: Observability = {\n emit(event) {\n getChannel(event.type).publish(event);\n }\n};\n\n/**\n * Maps each channel key to the observability events it carries.\n */\nexport type ChannelEventMap = {\n state: Extract<ObservabilityEvent, { type: `state:${string}` }>;\n rpc: Extract<ObservabilityEvent, { type: \"rpc\" | `rpc:${string}` }>;\n message: Extract<\n ObservabilityEvent,\n { type: `message:${string}` | `tool:${string}` }\n >;\n schedule: Extract<\n ObservabilityEvent,\n { type: `schedule:${string}` | `queue:${string}` }\n >;\n lifecycle: Extract<ObservabilityEvent, { type: \"connect\" | \"destroy\" }>;\n workflow: Extract<ObservabilityEvent, { type: `workflow:${string}` }>;\n mcp: Extract<ObservabilityEvent, { type: `mcp:${string}` }>;\n};\n\n/**\n * Subscribe to a typed observability channel.\n *\n * ```ts\n * import { subscribe } from \"agents/observability\";\n *\n * const unsub = subscribe(\"rpc\", (event) => {\n * console.log(event.payload.method); // fully typed\n * });\n * ```\n *\n * @returns A function that unsubscribes the callback.\n */\nexport function subscribe<K extends keyof ChannelEventMap>(\n channelKey: K,\n callback: (event: ChannelEventMap[K]) => void\n): () => void {\n const name = `agents:${channelKey}`;\n const handler = (message: unknown, _name: string | symbol) =>\n callback(message as ChannelEventMap[K]);\n dcSubscribe(name, handler);\n return () => dcUnsubscribe(name, handler);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAuCA,MAAa,WAAW;CACtB,OAAO,QAAQ,eAAe;CAC9B,KAAK,QAAQ,aAAa;CAC1B,SAAS,QAAQ,iBAAiB;CAClC,UAAU,QAAQ,kBAAkB;CACpC,WAAW,QAAQ,mBAAmB;CACtC,UAAU,QAAQ,kBAAkB;CACpC,KAAK,QAAQ,aAAa;CAC3B;;;;AAKD,SAAS,WAAW,MAAuB;AACzC,KAAI,KAAK,WAAW,OAAO,CAAE,QAAO,SAAS;AAC7C,KAAI,KAAK,WAAW,YAAY,CAAE,QAAO,SAAS;AAClD,KAAI,KAAK,WAAW,YAAY,IAAI,KAAK,WAAW,SAAS,CAC3D,QAAO,SAAS;AAClB,KAAI,KAAK,WAAW,WAAW,IAAI,KAAK,WAAW,QAAQ,CACzD,QAAO,SAAS;AAClB,KAAI,SAAS,SAAS,KAAK,WAAW,OAAO,CAAE,QAAO,SAAS;AAC/D,KAAI,KAAK,WAAW,SAAS,CAAE,QAAO,SAAS;AAE/C,QAAO,SAAS;;;;;;;;AASlB,MAAa,uBAAsC,EACjD,KAAK,OAAO;AACV,YAAW,MAAM,KAAK,CAAC,QAAQ,MAAM;GAExC;;;;;;;;;;;;;;AAkCD,SAAgB,UACd,YACA,UACY;CACZ,MAAM,OAAO,UAAU;CACvB,MAAM,WAAW,SAAkB,UACjC,SAAS,QAA8B;AACzC,aAAY,MAAM,QAAQ;AAC1B,cAAaA,YAAc,MAAM,QAAQ"}
package/dist/react.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { Method, RPCMethod } from "./serializable.js";
2
2
  import { StreamOptions } from "./client.js";
3
- import "./client-storage-D633wI1S.js";
3
+ import "./client-storage-tusTuoSF.js";
4
4
  import { Agent, MCPServersState } from "./index.js";
5
5
  import { PartySocket } from "partysocket";
6
6
  import { usePartySocket } from "partysocket/react";
@@ -1,4 +1,4 @@
1
- import "./client-storage-D633wI1S.js";
1
+ import "./client-storage-tusTuoSF.js";
2
2
  import {
3
3
  AgentWorkflowEvent,
4
4
  AgentWorkflowParams,
@@ -57,6 +57,12 @@ declare class AgentWorkflow<
57
57
  * Used when a subclass calls super.run() after its own run() was wrapped.
58
58
  */
59
59
  private __agentInitCalled;
60
+ /**
61
+ * Guard to prevent double error notification.
62
+ * Set to true when reportError() is called explicitly, so the automatic
63
+ * error catch in the run() wrapper doesn't send a duplicate notification.
64
+ */
65
+ private _errorReported;
60
66
  constructor(ctx: ExecutionContext, env: Env);
61
67
  /**
62
68
  * Initialize the Agent stub from workflow params.
@@ -91,6 +97,14 @@ declare class AgentWorkflow<
91
97
  * Get the workflow binding name
92
98
  */
93
99
  get workflowName(): string;
100
+ /**
101
+ * Automatically report an unhandled error to the Agent.
102
+ * Skipped if reportError() was already called (prevents double notification).
103
+ * Best-effort: notification failures are swallowed so the original error propagates.
104
+ *
105
+ * @param err - The caught error
106
+ */
107
+ private _autoReportError;
94
108
  /**
95
109
  * Send a notification to the Agent via RPC.
96
110
  *
package/dist/workflows.js CHANGED
@@ -1,4 +1,4 @@
1
- import "./client-connection-CGMuV62J.js";
1
+ import "./client-connection-D3Wcd6Q6.js";
2
2
  import { getAgentByName } from "./index.js";
3
3
  import { WorkflowRejectedError } from "./workflow-types.js";
4
4
  import { WorkflowEntrypoint } from "cloudflare:workers";
@@ -55,6 +55,7 @@ var AgentWorkflow = class extends WorkflowEntrypoint {
55
55
  constructor(ctx, env) {
56
56
  super(ctx, env);
57
57
  this.__agentInitCalled = false;
58
+ this._errorReported = false;
58
59
  const proto = Object.getPrototypeOf(this);
59
60
  if (Object.hasOwn(proto, "run") && !wrappedPrototypes.has(proto)) {
60
61
  const originalRun = proto.run;
@@ -68,9 +69,19 @@ var AgentWorkflow = class extends WorkflowEntrypoint {
68
69
  payload: userParams
69
70
  };
70
71
  const wrappedStep = this._wrapStep(step);
71
- return originalRun.call(this, cleanedEvent, wrappedStep);
72
+ try {
73
+ return await originalRun.call(this, cleanedEvent, wrappedStep);
74
+ } catch (err) {
75
+ await this._autoReportError(err);
76
+ throw err;
77
+ }
78
+ }
79
+ try {
80
+ return await originalRun.call(this, event, step);
81
+ } catch (err) {
82
+ await this._autoReportError(err);
83
+ throw err;
72
84
  }
73
- return originalRun.call(this, event, step);
74
85
  };
75
86
  wrappedPrototypes.add(proto);
76
87
  }
@@ -110,6 +121,7 @@ var AgentWorkflow = class extends WorkflowEntrypoint {
110
121
  };
111
122
  wrappedStep.reportError = async (error) => {
112
123
  const errorMessage = error instanceof Error ? error.message : error;
124
+ this._errorReported = true;
113
125
  await step.do(`__agent_reportError_${stepCounter++}`, async () => {
114
126
  await this.notifyAgent({
115
127
  workflowName: this._workflowName,
@@ -176,6 +188,27 @@ var AgentWorkflow = class extends WorkflowEntrypoint {
176
188
  return this._workflowName;
177
189
  }
178
190
  /**
191
+ * Automatically report an unhandled error to the Agent.
192
+ * Skipped if reportError() was already called (prevents double notification).
193
+ * Best-effort: notification failures are swallowed so the original error propagates.
194
+ *
195
+ * @param err - The caught error
196
+ */
197
+ async _autoReportError(err) {
198
+ if (this._errorReported) return;
199
+ this._errorReported = true;
200
+ const errorMessage = err instanceof Error ? err.message : String(err);
201
+ try {
202
+ await this.notifyAgent({
203
+ workflowName: this._workflowName,
204
+ workflowId: this._workflowId,
205
+ type: "error",
206
+ error: errorMessage,
207
+ timestamp: Date.now()
208
+ });
209
+ } catch (_notifyErr) {}
210
+ }
211
+ /**
179
212
  * Send a notification to the Agent via RPC.
180
213
  *
181
214
  * @param callback - Callback payload to send
@@ -1 +1 @@
1
- {"version":3,"file":"workflows.js","names":[],"sources":["../src/workflows.ts"],"sourcesContent":["/**\n * AgentWorkflow - Base class for Workflows that integrate with Agents\n *\n * Extends Cloudflare's WorkflowEntrypoint to provide seamless access to\n * the Agent that started the workflow, enabling bidirectional communication.\n *\n * @example\n * ```typescript\n * import { AgentWorkflow } from 'agents/workflows';\n * import type { MyAgent } from './agent';\n *\n * type TaskParams = { taskId: string; data: string };\n *\n * export class ProcessingWorkflow extends AgentWorkflow<MyAgent, TaskParams> {\n * async run(event: AgentWorkflowEvent<TaskParams>, step: WorkflowStep) {\n * // Access the originating Agent via typed RPC\n * await this.agent.updateTaskStatus(event.payload.taskId, 'processing');\n *\n * const result = await step.do('process', async () => {\n * // ... processing logic\n * return { processed: true };\n * });\n *\n * // Report progress to Agent (typed)\n * await this.reportProgress({ step: 'process', status: 'complete', percent: 0.5 });\n *\n * // Broadcast to connected clients\n * await this.broadcastToClients({ type: 'progress', data: result });\n *\n * return result;\n * }\n * }\n * ```\n */\n\nimport { WorkflowEntrypoint } from \"cloudflare:workers\";\nimport type { WorkflowEvent, WorkflowStep } from \"cloudflare:workers\";\nimport { getAgentByName, type Agent } from \"./index\";\nimport type {\n AgentWorkflowParams,\n AgentWorkflowStep,\n WorkflowCallback,\n DefaultProgress,\n WaitForApprovalOptions\n} from \"./workflow-types\";\nimport { WorkflowRejectedError } from \"./workflow-types\";\n\n/**\n * WeakSet to track which prototypes have been wrapped.\n * This prevents re-wrapping on subsequent instantiations of the same class.\n */\nconst wrappedPrototypes = new WeakSet<object>();\n\n/**\n * Base class for Workflows that need access to their originating Agent.\n *\n * @template AgentType - The Agent class type (for typed RPC access)\n * @template Params - User-defined params passed to the workflow (optional)\n * @template ProgressType - Type for progress reporting (defaults to DefaultProgress)\n * @template Env - Environment type (defaults to Cloudflare.Env)\n */\nexport class AgentWorkflow<\n AgentType extends Agent = Agent,\n Params = unknown,\n ProgressType = DefaultProgress,\n Env extends Cloudflare.Env = Cloudflare.Env\n> extends WorkflowEntrypoint<Env, AgentWorkflowParams<Params>> {\n /**\n * The Agent stub - initialized before run() is called.\n * Use this.agent to access the Agent's RPC methods.\n */\n private _agent!: DurableObjectStub<AgentType>;\n\n /**\n * Workflow instance ID\n */\n private _workflowId!: string;\n\n /**\n * Workflow binding name (for callbacks)\n */\n private _workflowName!: string;\n\n /**\n * Instance-level guard to prevent double initialization.\n * Used when a subclass calls super.run() after its own run() was wrapped.\n */\n private __agentInitCalled = false;\n\n constructor(ctx: ExecutionContext, env: Env) {\n super(ctx, env);\n\n const proto = Object.getPrototypeOf(this);\n\n // Only wrap if:\n // 1. This prototype defines its own run method (hasOwnProperty)\n // 2. It hasn't been wrapped yet (WeakSet check)\n // This prevents double-wrapping inherited methods and ensures each subclass\n // that defines run() gets wrapped exactly once.\n if (Object.hasOwn(proto, \"run\") && !wrappedPrototypes.has(proto)) {\n const originalRun = proto.run as (\n event: WorkflowEvent<Params>,\n step: AgentWorkflowStep\n ) => Promise<unknown>;\n\n // Replace the prototype's run method with a wrapper that initializes\n // the agent before calling the user's implementation\n proto.run = async function (\n this: AgentWorkflow<AgentType, Params, ProgressType, Env>,\n event: WorkflowEvent<AgentWorkflowParams<Params>>,\n step: WorkflowStep\n ) {\n // Instance-level guard: only init once per instance\n // (prevents double init if super.run() is called from a subclass)\n if (!this.__agentInitCalled) {\n const { __agentName, __agentBinding, __workflowName, ...userParams } =\n event.payload;\n\n // Initialize agent connection\n await this._initAgent(\n __agentName,\n __agentBinding,\n __workflowName,\n event.instanceId\n );\n this.__agentInitCalled = true;\n\n // Pass cleaned event and wrapped step to user's implementation\n const cleanedEvent = {\n ...event,\n payload: userParams as Params\n } as WorkflowEvent<Params>;\n\n const wrappedStep = this._wrapStep(step);\n\n return originalRun.call(this, cleanedEvent, wrappedStep);\n }\n\n // If already initialized (e.g., called via super.run()),\n // just call the original with the event as-is\n return originalRun.call(\n this,\n event as WorkflowEvent<Params>,\n step as AgentWorkflowStep\n );\n };\n\n wrappedPrototypes.add(proto);\n }\n }\n\n /**\n * Initialize the Agent stub from workflow params.\n * Called automatically before run() executes.\n */\n private async _initAgent(\n agentName: string | undefined,\n agentBinding: string | undefined,\n workflowName: string | undefined,\n instanceId: string\n ): Promise<void> {\n if (!agentName || !agentBinding || !workflowName) {\n throw new Error(\n \"AgentWorkflow requires __agentName, __agentBinding, and __workflowName in params. \" +\n \"Use agent.runWorkflow() to start workflows with proper agent context.\"\n );\n }\n\n this._workflowId = instanceId;\n this._workflowName = workflowName;\n\n // Get the Agent namespace from env\n const namespace = (this.env as Record<string, unknown>)[\n agentBinding\n ] as DurableObjectNamespace<AgentType>;\n\n if (!namespace) {\n throw new Error(\n `Agent binding '${agentBinding}' not found in environment`\n );\n }\n\n // Get the Agent stub by name\n this._agent = await getAgentByName<Cloudflare.Env, AgentType>(\n namespace,\n agentName\n );\n }\n\n /**\n * Wrap WorkflowStep with durable Agent communication methods.\n * Methods added to the wrapped step are idempotent and won't repeat on retry.\n *\n * Note: We add methods directly to the step object to preserve instanceof checks\n * that Cloudflare's runtime may perform on the WorkflowStep class.\n */\n private _wrapStep(step: WorkflowStep): AgentWorkflowStep {\n let stepCounter = 0;\n\n // Cast step to our extended type and add methods directly\n // This preserves the original object identity and instanceof relationship\n const wrappedStep = step as AgentWorkflowStep;\n\n // Add durable Agent methods directly to the step object\n wrappedStep.reportComplete = async <T>(result?: T): Promise<void> => {\n await step.do(`__agent_reportComplete_${stepCounter++}`, async () => {\n await this.notifyAgent({\n workflowName: this._workflowName,\n workflowId: this._workflowId,\n type: \"complete\",\n result,\n timestamp: Date.now()\n });\n });\n };\n\n wrappedStep.reportError = async (error: Error | string): Promise<void> => {\n const errorMessage = error instanceof Error ? error.message : error;\n await step.do(`__agent_reportError_${stepCounter++}`, async () => {\n await this.notifyAgent({\n workflowName: this._workflowName,\n workflowId: this._workflowId,\n type: \"error\",\n error: errorMessage,\n timestamp: Date.now()\n });\n });\n };\n\n wrappedStep.sendEvent = async <T>(event: T): Promise<void> => {\n await step.do(`__agent_sendEvent_${stepCounter++}`, async () => {\n await this.notifyAgent({\n workflowName: this._workflowName,\n workflowId: this._workflowId,\n type: \"event\",\n event,\n timestamp: Date.now()\n });\n });\n };\n\n wrappedStep.updateAgentState = async (state: unknown): Promise<void> => {\n await step.do(`__agent_updateState_${stepCounter++}`, async () => {\n this.agent._workflow_updateState(\"set\", state);\n });\n };\n\n wrappedStep.mergeAgentState = async (\n partialState: Record<string, unknown>\n ): Promise<void> => {\n await step.do(`__agent_mergeState_${stepCounter++}`, async () => {\n this.agent._workflow_updateState(\"merge\", partialState);\n });\n };\n\n wrappedStep.resetAgentState = async (): Promise<void> => {\n await step.do(`__agent_resetState_${stepCounter++}`, async () => {\n this.agent._workflow_updateState(\"reset\");\n });\n };\n\n return wrappedStep;\n }\n\n /**\n * Get the Agent stub for RPC calls.\n * Provides typed access to the Agent's methods.\n *\n * @example\n * ```typescript\n * // Call any public method on the Agent\n * await this.agent.updateStatus('processing');\n * const data = await this.agent.getData();\n * ```\n */\n get agent(): DurableObjectStub<AgentType> {\n if (!this._agent) {\n throw new Error(\n \"Agent not initialized. Ensure you're accessing this.agent inside run().\"\n );\n }\n return this._agent;\n }\n\n /**\n * Get the workflow instance ID\n */\n get workflowId(): string {\n return this._workflowId;\n }\n\n /**\n * Get the workflow binding name\n */\n get workflowName(): string {\n return this._workflowName;\n }\n\n /**\n * Send a notification to the Agent via RPC.\n *\n * @param callback - Callback payload to send\n */\n protected async notifyAgent(callback: WorkflowCallback): Promise<void> {\n await this.agent._workflow_handleCallback(callback);\n }\n\n /**\n * Report progress to the Agent with typed progress data.\n * Triggers onWorkflowProgress() on the Agent.\n *\n * @param progress - Typed progress data\n *\n * @example\n * ```typescript\n * // Using default progress type\n * await this.reportProgress({ step: 'fetch', status: 'running' });\n * await this.reportProgress({ step: 'fetch', status: 'complete', percent: 0.5 });\n *\n * // With custom progress type\n * await this.reportProgress({ stage: 'extract', recordsProcessed: 100 });\n * ```\n */\n protected async reportProgress(progress: ProgressType): Promise<void> {\n await this.notifyAgent({\n workflowName: this._workflowName,\n workflowId: this._workflowId,\n type: \"progress\",\n progress: progress as DefaultProgress,\n timestamp: Date.now()\n });\n }\n\n /**\n * Broadcast a message to all connected WebSocket clients via the Agent.\n * This is non-durable and may repeat on workflow retry.\n *\n * @param message - Message to broadcast (will be JSON-stringified)\n */\n protected broadcastToClients(message: unknown): void {\n this.agent._workflow_broadcast(message);\n }\n\n /**\n * Wait for approval from the Agent.\n * Handles rejection by reporting error (durably) and throwing WorkflowRejectedError.\n *\n * @param step - AgentWorkflowStep object\n * @param options - Wait options (timeout, eventType, stepName)\n * @returns Approval payload (throws WorkflowRejectedError if rejected)\n *\n * @example\n * ```typescript\n * const approval = await this.waitForApproval(step, { timeout: '7 days' });\n * // approval contains the payload from approveWorkflow()\n * ```\n */\n protected async waitForApproval<T = unknown>(\n step: AgentWorkflowStep,\n options?: WaitForApprovalOptions\n ): Promise<T> {\n const stepName = options?.stepName ?? \"wait-for-approval\";\n const eventType = options?.eventType ?? \"approval\";\n const timeout = options?.timeout;\n\n // Wait for the approval event\n // Note: Call reportProgress() before this method if you want to update progress\n const event = await step.waitForEvent(stepName, {\n type: eventType,\n timeout\n });\n\n // Cast the payload to our expected type\n const payload = event.payload as {\n approved: boolean;\n reason?: string;\n metadata?: T;\n };\n\n // Check if rejected\n if (!payload.approved) {\n const reason = payload.reason;\n await step.reportError(reason ?? \"Workflow rejected\");\n throw new WorkflowRejectedError(reason, this._workflowId);\n }\n\n // Return the approval metadata as the result\n return payload.metadata as T;\n }\n}\n\n// Re-export types for convenience\nexport type {\n AgentWorkflowEvent,\n AgentWorkflowStep,\n WorkflowCallback,\n WorkflowCallbackType,\n WorkflowProgressCallback,\n WorkflowCompleteCallback,\n WorkflowErrorCallback,\n WorkflowEventCallback,\n DefaultProgress,\n WaitForApprovalOptions,\n ApprovalEventPayload,\n WorkflowStatus,\n WorkflowTrackingRow,\n RunWorkflowOptions,\n WorkflowEventPayload,\n WorkflowInfo,\n WorkflowQueryCriteria,\n WorkflowPage\n} from \"./workflow-types\";\n\nexport { WorkflowRejectedError } from \"./workflow-types\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDA,MAAM,oCAAoB,IAAI,SAAiB;;;;;;;;;AAU/C,IAAa,gBAAb,cAKU,mBAAqD;CAuB7D,YAAY,KAAuB,KAAU;AAC3C,QAAM,KAAK,IAAI;2BAHW;EAK1B,MAAM,QAAQ,OAAO,eAAe,KAAK;AAOzC,MAAI,OAAO,OAAO,OAAO,MAAM,IAAI,CAAC,kBAAkB,IAAI,MAAM,EAAE;GAChE,MAAM,cAAc,MAAM;AAO1B,SAAM,MAAM,eAEV,OACA,MACA;AAGA,QAAI,CAAC,KAAK,mBAAmB;KAC3B,MAAM,EAAE,aAAa,gBAAgB,gBAAgB,GAAG,eACtD,MAAM;AAGR,WAAM,KAAK,WACT,aACA,gBACA,gBACA,MAAM,WACP;AACD,UAAK,oBAAoB;KAGzB,MAAM,eAAe;MACnB,GAAG;MACH,SAAS;MACV;KAED,MAAM,cAA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\n * AgentWorkflow - Base class for Workflows that integrate with Agents\n *\n * Extends Cloudflare's WorkflowEntrypoint to provide seamless access to\n * the Agent that started the workflow, enabling bidirectional communication.\n *\n * @example\n * ```typescript\n * import { AgentWorkflow } from 'agents/workflows';\n * import type { MyAgent } from './agent';\n *\n * type TaskParams = { taskId: string; data: string };\n *\n * export class ProcessingWorkflow extends AgentWorkflow<MyAgent, TaskParams> {\n * async run(event: AgentWorkflowEvent<TaskParams>, step: WorkflowStep) {\n * // Access the originating Agent via typed RPC\n * await this.agent.updateTaskStatus(event.payload.taskId, 'processing');\n *\n * const result = await step.do('process', async () => {\n * // ... processing logic\n * return { processed: true };\n * });\n *\n * // Report progress to Agent (typed)\n * await this.reportProgress({ step: 'process', status: 'complete', percent: 0.5 });\n *\n * // Broadcast to connected clients\n * await this.broadcastToClients({ type: 'progress', data: result });\n *\n * return result;\n * }\n * }\n * ```\n */\n\nimport { WorkflowEntrypoint } from \"cloudflare:workers\";\nimport type { WorkflowEvent, WorkflowStep } from \"cloudflare:workers\";\nimport { getAgentByName, type Agent } from \"./index\";\nimport type {\n AgentWorkflowParams,\n AgentWorkflowStep,\n WorkflowCallback,\n DefaultProgress,\n WaitForApprovalOptions\n} from \"./workflow-types\";\nimport { WorkflowRejectedError } from \"./workflow-types\";\n\n/**\n * WeakSet to track which prototypes have been wrapped.\n * This prevents re-wrapping on subsequent instantiations of the same class.\n */\nconst wrappedPrototypes = new WeakSet<object>();\n\n/**\n * Base class for Workflows that need access to their originating Agent.\n *\n * @template AgentType - The Agent class type (for typed RPC access)\n * @template Params - User-defined params passed to the workflow (optional)\n * @template ProgressType - Type for progress reporting (defaults to DefaultProgress)\n * @template Env - Environment type (defaults to Cloudflare.Env)\n */\nexport class AgentWorkflow<\n AgentType extends Agent = Agent,\n Params = unknown,\n ProgressType = DefaultProgress,\n Env extends Cloudflare.Env = Cloudflare.Env\n> extends WorkflowEntrypoint<Env, AgentWorkflowParams<Params>> {\n /**\n * The Agent stub - initialized before run() is called.\n * Use this.agent to access the Agent's RPC methods.\n */\n private _agent!: DurableObjectStub<AgentType>;\n\n /**\n * Workflow instance ID\n */\n private _workflowId!: string;\n\n /**\n * Workflow binding name (for callbacks)\n */\n private _workflowName!: string;\n\n /**\n * Instance-level guard to prevent double initialization.\n * Used when a subclass calls super.run() after its own run() was wrapped.\n */\n private __agentInitCalled = false;\n\n /**\n * Guard to prevent double error notification.\n * Set to true when reportError() is called explicitly, so the automatic\n * error catch in the run() wrapper doesn't send a duplicate notification.\n */\n private _errorReported = false;\n\n constructor(ctx: ExecutionContext, env: Env) {\n super(ctx, env);\n\n const proto = Object.getPrototypeOf(this);\n\n // Only wrap if:\n // 1. This prototype defines its own run method (hasOwnProperty)\n // 2. It hasn't been wrapped yet (WeakSet check)\n // This prevents double-wrapping inherited methods and ensures each subclass\n // that defines run() gets wrapped exactly once.\n if (Object.hasOwn(proto, \"run\") && !wrappedPrototypes.has(proto)) {\n const originalRun = proto.run as (\n event: WorkflowEvent<Params>,\n step: AgentWorkflowStep\n ) => Promise<unknown>;\n\n // Replace the prototype's run method with a wrapper that initializes\n // the agent before calling the user's implementation\n proto.run = async function (\n this: AgentWorkflow<AgentType, Params, ProgressType, Env>,\n event: WorkflowEvent<AgentWorkflowParams<Params>>,\n step: WorkflowStep\n ) {\n // Instance-level guard: only init once per instance\n // (prevents double init if super.run() is called from a subclass)\n if (!this.__agentInitCalled) {\n const { __agentName, __agentBinding, __workflowName, ...userParams } =\n event.payload;\n\n // Initialize agent connection\n await this._initAgent(\n __agentName,\n __agentBinding,\n __workflowName,\n event.instanceId\n );\n this.__agentInitCalled = true;\n\n // Pass cleaned event and wrapped step to user's implementation\n const cleanedEvent = {\n ...event,\n payload: userParams as Params\n } as WorkflowEvent<Params>;\n\n const wrappedStep = this._wrapStep(step);\n\n try {\n return await originalRun.call(this, cleanedEvent, wrappedStep);\n } catch (err) {\n await this._autoReportError(err);\n throw err;\n }\n }\n\n // If already initialized (e.g., called via super.run()),\n // just call the original with the event as-is\n try {\n return await originalRun.call(\n this,\n event as WorkflowEvent<Params>,\n step as AgentWorkflowStep\n );\n } catch (err) {\n await this._autoReportError(err);\n throw err;\n }\n };\n\n wrappedPrototypes.add(proto);\n }\n }\n\n /**\n * Initialize the Agent stub from workflow params.\n * Called automatically before run() executes.\n */\n private async _initAgent(\n agentName: string | undefined,\n agentBinding: string | undefined,\n workflowName: string | undefined,\n instanceId: string\n ): Promise<void> {\n if (!agentName || !agentBinding || !workflowName) {\n throw new Error(\n \"AgentWorkflow requires __agentName, __agentBinding, and __workflowName in params. \" +\n \"Use agent.runWorkflow() to start workflows with proper agent context.\"\n );\n }\n\n this._workflowId = instanceId;\n this._workflowName = workflowName;\n\n // Get the Agent namespace from env\n const namespace = (this.env as Record<string, unknown>)[\n agentBinding\n ] as DurableObjectNamespace<AgentType>;\n\n if (!namespace) {\n throw new Error(\n `Agent binding '${agentBinding}' not found in environment`\n );\n }\n\n // Get the Agent stub by name\n this._agent = await getAgentByName<Cloudflare.Env, AgentType>(\n namespace,\n agentName\n );\n }\n\n /**\n * Wrap WorkflowStep with durable Agent communication methods.\n * Methods added to the wrapped step are idempotent and won't repeat on retry.\n *\n * Note: We add methods directly to the step object to preserve instanceof checks\n * that Cloudflare's runtime may perform on the WorkflowStep class.\n */\n private _wrapStep(step: WorkflowStep): AgentWorkflowStep {\n let stepCounter = 0;\n\n // Cast step to our extended type and add methods directly\n // This preserves the original object identity and instanceof relationship\n const wrappedStep = step as AgentWorkflowStep;\n\n // Add durable Agent methods directly to the step object\n wrappedStep.reportComplete = async <T>(result?: T): Promise<void> => {\n await step.do(`__agent_reportComplete_${stepCounter++}`, async () => {\n await this.notifyAgent({\n workflowName: this._workflowName,\n workflowId: this._workflowId,\n type: \"complete\",\n result,\n timestamp: Date.now()\n });\n });\n };\n\n wrappedStep.reportError = async (error: Error | string): Promise<void> => {\n const errorMessage = error instanceof Error ? error.message : error;\n this._errorReported = true;\n await step.do(`__agent_reportError_${stepCounter++}`, async () => {\n await this.notifyAgent({\n workflowName: this._workflowName,\n workflowId: this._workflowId,\n type: \"error\",\n error: errorMessage,\n timestamp: Date.now()\n });\n });\n };\n\n wrappedStep.sendEvent = async <T>(event: T): Promise<void> => {\n await step.do(`__agent_sendEvent_${stepCounter++}`, async () => {\n await this.notifyAgent({\n workflowName: this._workflowName,\n workflowId: this._workflowId,\n type: \"event\",\n event,\n timestamp: Date.now()\n });\n });\n };\n\n wrappedStep.updateAgentState = async (state: unknown): Promise<void> => {\n await step.do(`__agent_updateState_${stepCounter++}`, async () => {\n this.agent._workflow_updateState(\"set\", state);\n });\n };\n\n wrappedStep.mergeAgentState = async (\n partialState: Record<string, unknown>\n ): Promise<void> => {\n await step.do(`__agent_mergeState_${stepCounter++}`, async () => {\n this.agent._workflow_updateState(\"merge\", partialState);\n });\n };\n\n wrappedStep.resetAgentState = async (): Promise<void> => {\n await step.do(`__agent_resetState_${stepCounter++}`, async () => {\n this.agent._workflow_updateState(\"reset\");\n });\n };\n\n return wrappedStep;\n }\n\n /**\n * Get the Agent stub for RPC calls.\n * Provides typed access to the Agent's methods.\n *\n * @example\n * ```typescript\n * // Call any public method on the Agent\n * await this.agent.updateStatus('processing');\n * const data = await this.agent.getData();\n * ```\n */\n get agent(): DurableObjectStub<AgentType> {\n if (!this._agent) {\n throw new Error(\n \"Agent not initialized. Ensure you're accessing this.agent inside run().\"\n );\n }\n return this._agent;\n }\n\n /**\n * Get the workflow instance ID\n */\n get workflowId(): string {\n return this._workflowId;\n }\n\n /**\n * Get the workflow binding name\n */\n get workflowName(): string {\n return this._workflowName;\n }\n\n /**\n * Automatically report an unhandled error to the Agent.\n * Skipped if reportError() was already called (prevents double notification).\n * Best-effort: notification failures are swallowed so the original error propagates.\n *\n * @param err - The caught error\n */\n private async _autoReportError(err: unknown): Promise<void> {\n if (this._errorReported) {\n return;\n }\n this._errorReported = true;\n const errorMessage = err instanceof Error ? err.message : String(err);\n try {\n await this.notifyAgent({\n workflowName: this._workflowName,\n workflowId: this._workflowId,\n type: \"error\",\n error: errorMessage,\n timestamp: Date.now()\n });\n } catch (_notifyErr) {\n // Best-effort: don't mask the original error\n }\n }\n\n /**\n * Send a notification to the Agent via RPC.\n *\n * @param callback - Callback payload to send\n */\n protected async notifyAgent(callback: WorkflowCallback): Promise<void> {\n await this.agent._workflow_handleCallback(callback);\n }\n\n /**\n * Report progress to the Agent with typed progress data.\n * Triggers onWorkflowProgress() on the Agent.\n *\n * @param progress - Typed progress data\n *\n * @example\n * ```typescript\n * // Using default progress type\n * await this.reportProgress({ step: 'fetch', status: 'running' });\n * await this.reportProgress({ step: 'fetch', status: 'complete', percent: 0.5 });\n *\n * // With custom progress type\n * await this.reportProgress({ stage: 'extract', recordsProcessed: 100 });\n * ```\n */\n protected async reportProgress(progress: ProgressType): Promise<void> {\n await this.notifyAgent({\n workflowName: this._workflowName,\n workflowId: this._workflowId,\n type: \"progress\",\n progress: progress as DefaultProgress,\n timestamp: Date.now()\n });\n }\n\n /**\n * Broadcast a message to all connected WebSocket clients via the Agent.\n * This is non-durable and may repeat on workflow retry.\n *\n * @param message - Message to broadcast (will be JSON-stringified)\n */\n protected broadcastToClients(message: unknown): void {\n this.agent._workflow_broadcast(message);\n }\n\n /**\n * Wait for approval from the Agent.\n * Handles rejection by reporting error (durably) and throwing WorkflowRejectedError.\n *\n * @param step - AgentWorkflowStep object\n * @param options - Wait options (timeout, eventType, stepName)\n * @returns Approval payload (throws WorkflowRejectedError if rejected)\n *\n * @example\n * ```typescript\n * const approval = await this.waitForApproval(step, { timeout: '7 days' });\n * // approval contains the payload from approveWorkflow()\n * ```\n */\n protected async waitForApproval<T = unknown>(\n step: AgentWorkflowStep,\n options?: WaitForApprovalOptions\n ): Promise<T> {\n const stepName = options?.stepName ?? \"wait-for-approval\";\n const eventType = options?.eventType ?? \"approval\";\n const timeout = options?.timeout;\n\n // Wait for the approval event\n // Note: Call reportProgress() before this method if you want to update progress\n const event = await step.waitForEvent(stepName, {\n type: eventType,\n timeout\n });\n\n // Cast the payload to our expected type\n const payload = event.payload as {\n approved: boolean;\n reason?: string;\n metadata?: T;\n };\n\n // Check if rejected\n if (!payload.approved) {\n const reason = payload.reason;\n await step.reportError(reason ?? \"Workflow rejected\");\n throw new WorkflowRejectedError(reason, this._workflowId);\n }\n\n // Return the approval metadata as the result\n return payload.metadata as T;\n }\n}\n\n// Re-export types for convenience\nexport type {\n AgentWorkflowEvent,\n AgentWorkflowStep,\n WorkflowCallback,\n WorkflowCallbackType,\n WorkflowProgressCallback,\n WorkflowCompleteCallback,\n WorkflowErrorCallback,\n WorkflowEventCallback,\n DefaultProgress,\n WaitForApprovalOptions,\n ApprovalEventPayload,\n WorkflowStatus,\n WorkflowTrackingRow,\n RunWorkflowOptions,\n WorkflowEventPayload,\n WorkflowInfo,\n WorkflowQueryCriteria,\n WorkflowPage\n} from \"./workflow-types\";\n\nexport { WorkflowRejectedError } from \"./workflow-types\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDA,MAAM,oCAAoB,IAAI,SAAiB;;;;;;;;;AAU/C,IAAa,gBAAb,cAKU,mBAAqD;CA8B7D,YAAY,KAAuB,KAAU;AAC3C,QAAM,KAAK,IAAI;2BAVW;wBAOH;EAKvB,MAAM,QAAQ,OAAO,eAAe,KAAK;AAOzC,MAAI,OAAO,OAAO,OAAO,MAAM,IAAI,CAAC,kBAAkB,IAAI,MAAM,EAAE;GAChE,MAAM,cAAc,MAAM;AAO1B,SAAM,MAAM,eAEV,OACA,MACA;AAGA,QAAI,CAAC,KAAK,mBAAmB;KAC3B,MAAM,EAAE,aAAa,gBAAgB,gBAAgB,GAAG,eACtD,MAAM;AAGR,WAAM,KAAK,WACT,aACA,gBACA,gBACA,MAAM,WACP;AACD,UAAK,oBAAoB;KAGzB,MAAM,eAAe;MACnB,GAAG;MACH,SAAS;MACV;KAED,MAAM,cAAc,KAAK,UAAU,KAAK;AAExC,SAAI;AACF,aAAO,MAAM,YAAY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EACZ,MAAM,WAAW,SAAS,YAAY;EACtC,MAAM,YAAY,SAAS,aAAa;EACxC,MAAM,UAAU,SAAS;EAUzB,MAAM,WANQ,MAAM,KAAK,aAAa,UAAU;GAC9C,MAAM;GACN;GACD,CAAC,EAGoB;AAOtB,MAAI,CAAC,QAAQ,UAAU;GACrB,MAAM,SAAS,QAAQ;AACvB,SAAM,KAAK,YAAY,UAAU,oBAAoB;AACrD,SAAM,IAAI,sBAAsB,QAAQ,KAAK,YAAY;;AAI3D,SAAO,QAAQ"}
package/package.json CHANGED
@@ -9,7 +9,7 @@
9
9
  "durable objects"
10
10
  ],
11
11
  "type": "module",
12
- "version": "0.5.1",
12
+ "version": "0.7.0",
13
13
  "license": "MIT",
14
14
  "repository": {
15
15
  "directory": "packages/agents",
@@ -31,19 +31,19 @@
31
31
  "json-schema-to-typescript": "^15.0.4",
32
32
  "mimetext": "^3.0.28",
33
33
  "nanoid": "^5.1.6",
34
- "partyserver": "^0.2.0",
35
- "partysocket": "1.1.14",
34
+ "partyserver": "^0.3.2",
35
+ "partysocket": "1.1.16",
36
36
  "yargs": "^18.0.0"
37
37
  },
38
38
  "devDependencies": {
39
- "@ai-sdk/openai": "^3.0.30",
40
- "@ai-sdk/react": "^3.0.96",
41
- "@cloudflare/workers-oauth-provider": "^0.2.3",
39
+ "@ai-sdk/openai": "^3.0.37",
40
+ "@ai-sdk/react": "^3.0.107",
41
+ "@cloudflare/workers-oauth-provider": "^0.2.4",
42
42
  "@types/react": "^19.2.14",
43
43
  "@types/yargs": "^17.0.35",
44
- "@x402/core": "^2.3.1",
45
- "@x402/evm": "^2.3.1",
46
- "ai": "^6.0.94",
44
+ "@x402/core": "^2.5.0",
45
+ "@x402/evm": "^2.5.0",
46
+ "ai": "^6.0.105",
47
47
  "react": "^19.2.4",
48
48
  "vitest-browser-react": "^1.0.1",
49
49
  "zod": "^4.3.6"
@@ -51,8 +51,8 @@
51
51
  "peerDependencies": {
52
52
  "@ai-sdk/openai": "^3.0.0",
53
53
  "@ai-sdk/react": "^3.0.0",
54
- "@cloudflare/ai-chat": "^0.1.3",
55
- "@cloudflare/codemode": "^0.1.0",
54
+ "@cloudflare/ai-chat": "^0.1.6",
55
+ "@cloudflare/codemode": "^0.1.2",
56
56
  "@x402/core": "^2.0.0",
57
57
  "@x402/evm": "^2.0.0",
58
58
  "ai": "^6.0.0",
@@ -145,6 +145,11 @@
145
145
  "import": "./dist/experimental/forever.js",
146
146
  "require": "./dist/experimental/forever.js"
147
147
  },
148
+ "./experimental/memory/session": {
149
+ "types": "./dist/experimental/memory/session/index.d.ts",
150
+ "import": "./dist/experimental/memory/session/index.js",
151
+ "require": "./dist/experimental/memory/session/index.js"
152
+ },
148
153
  "./x402": {
149
154
  "types": "./dist/mcp/x402.d.ts",
150
155
  "import": "./dist/mcp/x402.js",
@@ -1,60 +0,0 @@
1
- import { n as BaseEvent } from "./mcp-DA0kDE7K.js";
2
-
3
- //#region src/observability/agent.d.ts
4
- /**
5
- * Agent-specific observability events
6
- * These track the lifecycle and operations of an Agent
7
- */
8
- type AgentObservabilityEvent =
9
- | BaseEvent<"state:update", {}>
10
- | BaseEvent<
11
- "rpc",
12
- {
13
- method: string;
14
- streaming?: boolean;
15
- }
16
- >
17
- | BaseEvent<"message:request" | "message:response", {}>
18
- | BaseEvent<"message:clear">
19
- | BaseEvent<
20
- "schedule:create" | "schedule:execute" | "schedule:cancel",
21
- {
22
- callback: string;
23
- id: string;
24
- }
25
- >
26
- | BaseEvent<
27
- "queue:retry" | "schedule:retry",
28
- {
29
- callback: string;
30
- id: string;
31
- attempt: number;
32
- maxAttempts: number;
33
- }
34
- >
35
- | BaseEvent<"destroy">
36
- | BaseEvent<
37
- "connect",
38
- {
39
- connectionId: string;
40
- }
41
- >
42
- | BaseEvent<
43
- | "workflow:start"
44
- | "workflow:event"
45
- | "workflow:approved"
46
- | "workflow:rejected"
47
- | "workflow:terminated"
48
- | "workflow:paused"
49
- | "workflow:resumed"
50
- | "workflow:restarted",
51
- {
52
- workflowId: string;
53
- workflowName?: string;
54
- eventType?: string;
55
- reason?: string;
56
- }
57
- >;
58
- //#endregion
59
- export { AgentObservabilityEvent as t };
60
- //# sourceMappingURL=agent-B4_kEsdK.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"client-connection-CGMuV62J.js","names":[],"sources":["../src/core/events.ts","../src/mcp/errors.ts","../src/mcp/client-connection.ts"],"sourcesContent":["export interface Disposable {\n dispose(): void;\n}\n\nexport function toDisposable(fn: () => void): Disposable {\n return { dispose: fn };\n}\n\nexport class DisposableStore implements Disposable {\n private readonly _items: Disposable[] = [];\n\n add<T extends Disposable>(d: T): T {\n this._items.push(d);\n return d;\n }\n\n dispose(): void {\n while (this._items.length) {\n try {\n this._items.pop()!.dispose();\n } catch {\n // best-effort cleanup\n }\n }\n }\n}\n\nexport type Event<T> = (listener: (e: T) => void) => Disposable;\n\nexport class Emitter<T> implements Disposable {\n private _listeners: Set<(e: T) => void> = new Set();\n\n readonly event: Event<T> = (listener) => {\n this._listeners.add(listener);\n return toDisposable(() => this._listeners.delete(listener));\n };\n\n fire(data: T): void {\n for (const listener of [...this._listeners]) {\n try {\n listener(data);\n } catch (err) {\n // do not let one bad listener break others\n console.error(\"Emitter listener error:\", err);\n }\n }\n }\n\n dispose(): void {\n this._listeners.clear();\n }\n}\n","export function toErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction getErrorCode(error: unknown): number | undefined {\n if (\n error &&\n typeof error === \"object\" &&\n \"code\" in error &&\n typeof (error as { code: unknown }).code === \"number\"\n ) {\n return (error as { code: number }).code;\n }\n return undefined;\n}\n\nexport function isUnauthorized(error: unknown): boolean {\n const code = getErrorCode(error);\n if (code === 401) return true;\n\n const msg = toErrorMessage(error);\n return msg.includes(\"Unauthorized\") || msg.includes(\"401\");\n}\n\n// MCP SDK change (v1.24.0, commit 6b90e1a):\n// - Old: Error POSTing to endpoint (HTTP 404): Not Found\n// - New: StreamableHTTPError with code: 404 and message Error POSTing to endpoint: Not Found\nexport function isTransportNotImplemented(error: unknown): boolean {\n const code = getErrorCode(error);\n if (code === 404 || code === 405) return true;\n\n const msg = toErrorMessage(error);\n return (\n msg.includes(\"404\") ||\n msg.includes(\"405\") ||\n msg.includes(\"Not Implemented\") ||\n msg.includes(\"not implemented\")\n );\n}\n","import { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport {\n SSEClientTransport,\n type SSEClientTransportOptions\n} from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport {\n StreamableHTTPClientTransport,\n type StreamableHTTPClientTransportOptions\n} from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\n// Import types directly from MCP SDK\nimport type {\n Prompt,\n Resource,\n Tool\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport {\n type ClientCapabilities,\n type ElicitRequest,\n ElicitRequestSchema,\n type ElicitResult,\n type ListPromptsResult,\n type ListResourceTemplatesResult,\n type ListResourcesResult,\n type ListToolsResult,\n PromptListChangedNotificationSchema,\n ResourceListChangedNotificationSchema,\n type ResourceTemplate,\n type ServerCapabilities,\n ToolListChangedNotificationSchema\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { nanoid } from \"nanoid\";\nimport { Emitter, type Event } from \"../core/events\";\nimport type { MCPObservabilityEvent } from \"../observability/mcp\";\nimport type { AgentMcpOAuthProvider } from \"./do-oauth-client-provider\";\nimport {\n isTransportNotImplemented,\n isUnauthorized,\n toErrorMessage\n} from \"./errors\";\nimport type { BaseTransportType, TransportType } from \"./types\";\n\n/**\n * Connection state machine for MCP client connections.\n *\n * State transitions:\n * - Non-OAuth: init() → CONNECTING → DISCOVERING → READY\n * - OAuth: init() → AUTHENTICATING → (callback) → CONNECTING → DISCOVERING → READY\n * - Any state can transition to FAILED on error\n */\nexport const MCPConnectionState = {\n /** Waiting for OAuth authorization to complete */\n AUTHENTICATING: \"authenticating\",\n /** Establishing transport connection to MCP server */\n CONNECTING: \"connecting\",\n /** Transport connection established */\n CONNECTED: \"connected\",\n /** Discovering server capabilities (tools, resources, prompts) */\n DISCOVERING: \"discovering\",\n /** Fully connected and ready to use */\n READY: \"ready\",\n /** Connection failed at some point */\n FAILED: \"failed\"\n} as const;\n\n/**\n * Connection state type for MCP client connections.\n */\nexport type MCPConnectionState =\n (typeof MCPConnectionState)[keyof typeof MCPConnectionState];\n\nexport type MCPTransportOptions = (\n | SSEClientTransportOptions\n | StreamableHTTPClientTransportOptions\n) & {\n authProvider?: AgentMcpOAuthProvider;\n type?: TransportType;\n};\n\nexport type MCPClientConnectionResult = {\n state: MCPConnectionState;\n error?: Error;\n transport?: BaseTransportType;\n};\n\n/**\n * Result of a discovery operation.\n * success indicates whether discovery completed successfully.\n * error is present when success is false.\n */\nexport type MCPDiscoveryResult = {\n success: boolean;\n error?: string;\n};\n\nexport class MCPClientConnection {\n client: Client;\n connectionState: MCPConnectionState = MCPConnectionState.CONNECTING;\n connectionError: string | null = null;\n lastConnectedTransport: BaseTransportType | undefined;\n instructions?: string;\n tools: Tool[] = [];\n prompts: Prompt[] = [];\n resources: Resource[] = [];\n resourceTemplates: ResourceTemplate[] = [];\n serverCapabilities: ServerCapabilities | undefined;\n\n /** Tracks in-flight discovery to allow cancellation */\n private _discoveryAbortController: AbortController | undefined;\n\n private readonly _onObservabilityEvent = new Emitter<MCPObservabilityEvent>();\n public readonly onObservabilityEvent: Event<MCPObservabilityEvent> =\n this._onObservabilityEvent.event;\n\n constructor(\n public url: URL,\n info: ConstructorParameters<typeof Client>[0],\n public options: {\n transport: MCPTransportOptions;\n client: ConstructorParameters<typeof Client>[1];\n } = { client: {}, transport: {} }\n ) {\n const clientOptions = {\n ...options.client,\n capabilities: {\n ...options.client?.capabilities,\n elicitation: {}\n } as ClientCapabilities\n };\n\n this.client = new Client(info, clientOptions);\n }\n\n /**\n * Initialize a client connection, if authentication is required, the connection will be in the AUTHENTICATING state\n * Sets connection state based on the result and emits observability events\n *\n * @returns Error message if connection failed, undefined otherwise\n */\n async init(): Promise<string | undefined> {\n const transportType = this.options.transport.type;\n if (!transportType) {\n throw new Error(\"Transport type must be specified\");\n }\n\n const res = await this.tryConnect(transportType);\n\n // Set the connection state\n this.connectionState = res.state;\n\n // Handle the result and emit appropriate events\n if (res.state === MCPConnectionState.CONNECTED && res.transport) {\n // Set up elicitation request handler after successful connection\n this.client.setRequestHandler(\n ElicitRequestSchema,\n async (request: ElicitRequest) => {\n return await this.handleElicitationRequest(request);\n }\n );\n\n this.lastConnectedTransport = res.transport;\n\n this._onObservabilityEvent.fire({\n type: \"mcp:client:connect\",\n displayMessage: `Connected successfully using ${res.transport} transport for ${this.url.toString()}`,\n payload: {\n url: this.url.toString(),\n transport: res.transport,\n state: this.connectionState\n },\n timestamp: Date.now(),\n id: nanoid()\n });\n return undefined;\n } else if (res.state === MCPConnectionState.FAILED && res.error) {\n const errorMessage = toErrorMessage(res.error);\n this._onObservabilityEvent.fire({\n type: \"mcp:client:connect\",\n displayMessage: `Failed to connect to ${this.url.toString()}: ${errorMessage}`,\n payload: {\n url: this.url.toString(),\n transport: transportType,\n state: this.connectionState,\n error: errorMessage\n },\n timestamp: Date.now(),\n id: nanoid()\n });\n return errorMessage;\n }\n return undefined;\n }\n\n /**\n * Finish OAuth by probing transports based on configured type.\n * - Explicit: finish on that transport\n * - Auto: try streamable-http, then sse on 404/405/Not Implemented\n */\n private async finishAuthProbe(code: string): Promise<void> {\n if (!this.options.transport.authProvider) {\n throw new Error(\"No auth provider configured\");\n }\n\n const configuredType = this.options.transport.type;\n if (!configuredType) {\n throw new Error(\"Transport type must be specified\");\n }\n\n const finishAuth = async (base: BaseTransportType) => {\n const transport = this.getTransport(base);\n await transport.finishAuth(code);\n };\n\n if (configuredType === \"sse\" || configuredType === \"streamable-http\") {\n await finishAuth(configuredType);\n return;\n }\n\n // For \"auto\" mode, try streamable-http first, then fall back to SSE\n try {\n await finishAuth(\"streamable-http\");\n } catch (e) {\n if (isTransportNotImplemented(e)) {\n await finishAuth(\"sse\");\n return;\n }\n throw e;\n }\n }\n\n /**\n * Complete OAuth authorization\n */\n async completeAuthorization(code: string): Promise<void> {\n if (this.connectionState !== MCPConnectionState.AUTHENTICATING) {\n throw new Error(\n \"Connection must be in authenticating state to complete authorization\"\n );\n }\n\n try {\n // Finish OAuth by probing transports per configuration\n await this.finishAuthProbe(code);\n\n // Mark as connecting\n this.connectionState = MCPConnectionState.CONNECTING;\n } catch (error) {\n this.connectionState = MCPConnectionState.FAILED;\n throw error;\n }\n }\n\n /**\n * Discover server capabilities and register tools, resources, prompts, and templates.\n * This method does the work but does not manage connection state - that's handled by discover().\n */\n async discoverAndRegister(): Promise<void> {\n this.serverCapabilities = this.client.getServerCapabilities();\n if (!this.serverCapabilities) {\n throw new Error(\"The MCP Server failed to return server capabilities\");\n }\n\n // Build list of operations to perform based on server capabilities\n type DiscoveryResult =\n | string\n | undefined\n | Tool[]\n | Resource[]\n | Prompt[]\n | ResourceTemplate[];\n const operations: Promise<DiscoveryResult>[] = [];\n const operationNames: string[] = [];\n\n // Instructions (always try to fetch if available)\n operations.push(Promise.resolve(this.client.getInstructions()));\n operationNames.push(\"instructions\");\n\n // Only register capabilities that the server advertises\n if (this.serverCapabilities.tools) {\n operations.push(this.registerTools());\n operationNames.push(\"tools\");\n }\n\n if (this.serverCapabilities.resources) {\n operations.push(this.registerResources());\n operationNames.push(\"resources\");\n }\n\n if (this.serverCapabilities.prompts) {\n operations.push(this.registerPrompts());\n operationNames.push(\"prompts\");\n }\n\n if (this.serverCapabilities.resources) {\n operations.push(this.registerResourceTemplates());\n operationNames.push(\"resource templates\");\n }\n\n try {\n const results = await Promise.all(operations);\n for (let i = 0; i < results.length; i++) {\n const result = results[i];\n const name = operationNames[i];\n\n switch (name) {\n case \"instructions\":\n this.instructions = result as string | undefined;\n break;\n case \"tools\":\n this.tools = result as Tool[];\n break;\n case \"resources\":\n this.resources = result as Resource[];\n break;\n case \"prompts\":\n this.prompts = result as Prompt[];\n break;\n case \"resource templates\":\n this.resourceTemplates = result as ResourceTemplate[];\n break;\n }\n }\n } catch (error) {\n this._onObservabilityEvent.fire({\n type: \"mcp:client:discover\",\n displayMessage: `Failed to discover capabilities for ${this.url.toString()}: ${toErrorMessage(error)}`,\n payload: {\n url: this.url.toString(),\n error: toErrorMessage(error)\n },\n timestamp: Date.now(),\n id: nanoid()\n });\n\n throw error;\n }\n }\n\n /**\n * Discover server capabilities with timeout and cancellation support.\n * If called while a previous discovery is in-flight, the previous discovery will be aborted.\n *\n * @param options Optional configuration\n * @param options.timeoutMs Timeout in milliseconds (default: 15000)\n * @returns Result indicating success/failure with optional error message\n */\n async discover(\n options: { timeoutMs?: number } = {}\n ): Promise<MCPDiscoveryResult> {\n const { timeoutMs = 15000 } = options;\n\n // Check if state allows discovery\n if (\n this.connectionState !== MCPConnectionState.CONNECTED &&\n this.connectionState !== MCPConnectionState.READY\n ) {\n this._onObservabilityEvent.fire({\n type: \"mcp:client:discover\",\n displayMessage: `Discovery skipped for ${this.url.toString()}, state is ${this.connectionState}`,\n payload: {\n url: this.url.toString(),\n state: this.connectionState\n },\n timestamp: Date.now(),\n id: nanoid()\n });\n return {\n success: false,\n error: `Discovery skipped - connection in ${this.connectionState} state`\n };\n }\n\n // Cancel any previous in-flight discovery\n if (this._discoveryAbortController) {\n this._discoveryAbortController.abort();\n this._discoveryAbortController = undefined;\n }\n\n // Create a new AbortController for this discovery\n const abortController = new AbortController();\n this._discoveryAbortController = abortController;\n\n this.connectionState = MCPConnectionState.DISCOVERING;\n\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n\n try {\n // Create timeout promise\n const timeoutPromise = new Promise<never>((_, reject) => {\n timeoutId = setTimeout(\n () => reject(new Error(`Discovery timed out after ${timeoutMs}ms`)),\n timeoutMs\n );\n });\n\n // Check if aborted before starting\n if (abortController.signal.aborted) {\n throw new Error(\"Discovery was cancelled\");\n }\n\n // Create an abort promise that rejects when signal fires\n const abortPromise = new Promise<never>((_, reject) => {\n abortController.signal.addEventListener(\"abort\", () => {\n reject(new Error(\"Discovery was cancelled\"));\n });\n });\n\n await Promise.race([\n this.discoverAndRegister(),\n timeoutPromise,\n abortPromise\n ]);\n\n // Clear timeout on success\n if (timeoutId !== undefined) {\n clearTimeout(timeoutId);\n }\n\n // Discovery succeeded - transition to ready\n this.connectionState = MCPConnectionState.READY;\n\n this._onObservabilityEvent.fire({\n type: \"mcp:client:discover\",\n displayMessage: `Discovery completed for ${this.url.toString()}`,\n payload: {\n url: this.url.toString()\n },\n timestamp: Date.now(),\n id: nanoid()\n });\n\n return { success: true };\n } catch (e) {\n // Always clear the timeout\n if (timeoutId !== undefined) {\n clearTimeout(timeoutId);\n }\n\n // Return to CONNECTED state so user can retry discovery\n this.connectionState = MCPConnectionState.CONNECTED;\n\n const error = e instanceof Error ? e.message : String(e);\n return { success: false, error };\n } finally {\n // Clean up the abort controller\n this._discoveryAbortController = undefined;\n }\n }\n\n /**\n * Cancel any in-flight discovery operation.\n * Called when closing the connection.\n */\n cancelDiscovery(): void {\n if (this._discoveryAbortController) {\n this._discoveryAbortController.abort();\n this._discoveryAbortController = undefined;\n }\n }\n\n /**\n * Notification handler registration for tools\n * Should only be called if serverCapabilities.tools exists\n */\n async registerTools(): Promise<Tool[]> {\n if (this.serverCapabilities?.tools?.listChanged) {\n this.client.setNotificationHandler(\n ToolListChangedNotificationSchema,\n async (_notification) => {\n this.tools = await this.fetchTools();\n }\n );\n }\n\n return this.fetchTools();\n }\n\n /**\n * Notification handler registration for resources\n * Should only be called if serverCapabilities.resources exists\n */\n async registerResources(): Promise<Resource[]> {\n if (this.serverCapabilities?.resources?.listChanged) {\n this.client.setNotificationHandler(\n ResourceListChangedNotificationSchema,\n async (_notification) => {\n this.resources = await this.fetchResources();\n }\n );\n }\n\n return this.fetchResources();\n }\n\n /**\n * Notification handler registration for prompts\n * Should only be called if serverCapabilities.prompts exists\n */\n async registerPrompts(): Promise<Prompt[]> {\n if (this.serverCapabilities?.prompts?.listChanged) {\n this.client.setNotificationHandler(\n PromptListChangedNotificationSchema,\n async (_notification) => {\n this.prompts = await this.fetchPrompts();\n }\n );\n }\n\n return this.fetchPrompts();\n }\n\n async registerResourceTemplates(): Promise<ResourceTemplate[]> {\n return this.fetchResourceTemplates();\n }\n\n async fetchTools() {\n let toolsAgg: Tool[] = [];\n let toolsResult: ListToolsResult = { tools: [] };\n do {\n toolsResult = await this.client\n .listTools({\n cursor: toolsResult.nextCursor\n })\n .catch(this._capabilityErrorHandler({ tools: [] }, \"tools/list\"));\n toolsAgg = toolsAgg.concat(toolsResult.tools);\n } while (toolsResult.nextCursor);\n return toolsAgg;\n }\n\n async fetchResources() {\n let resourcesAgg: Resource[] = [];\n let resourcesResult: ListResourcesResult = { resources: [] };\n do {\n resourcesResult = await this.client\n .listResources({\n cursor: resourcesResult.nextCursor\n })\n .catch(\n this._capabilityErrorHandler({ resources: [] }, \"resources/list\")\n );\n resourcesAgg = resourcesAgg.concat(resourcesResult.resources);\n } while (resourcesResult.nextCursor);\n return resourcesAgg;\n }\n\n async fetchPrompts() {\n let promptsAgg: Prompt[] = [];\n let promptsResult: ListPromptsResult = { prompts: [] };\n do {\n promptsResult = await this.client\n .listPrompts({\n cursor: promptsResult.nextCursor\n })\n .catch(this._capabilityErrorHandler({ prompts: [] }, \"prompts/list\"));\n promptsAgg = promptsAgg.concat(promptsResult.prompts);\n } while (promptsResult.nextCursor);\n return promptsAgg;\n }\n\n async fetchResourceTemplates() {\n let templatesAgg: ResourceTemplate[] = [];\n let templatesResult: ListResourceTemplatesResult = {\n resourceTemplates: []\n };\n do {\n templatesResult = await this.client\n .listResourceTemplates({\n cursor: templatesResult.nextCursor\n })\n .catch(\n this._capabilityErrorHandler(\n { resourceTemplates: [] },\n \"resources/templates/list\"\n )\n );\n templatesAgg = templatesAgg.concat(templatesResult.resourceTemplates);\n } while (templatesResult.nextCursor);\n return templatesAgg;\n }\n\n /**\n * Handle elicitation request from server\n * Automatically uses the Agent's built-in elicitation handling if available\n */\n async handleElicitationRequest(\n _request: ElicitRequest\n ): Promise<ElicitResult> {\n // Elicitation handling must be implemented by the platform\n // For MCP servers, this should be handled by McpAgent.elicitInput()\n throw new Error(\n \"Elicitation handler must be implemented for your platform. Override handleElicitationRequest method.\"\n );\n }\n /**\n * Get the transport for the client\n * @param transportType - The transport type to get\n * @returns The transport for the client\n */\n getTransport(transportType: BaseTransportType) {\n switch (transportType) {\n case \"streamable-http\":\n return new StreamableHTTPClientTransport(\n this.url,\n this.options.transport as StreamableHTTPClientTransportOptions\n );\n case \"sse\":\n return new SSEClientTransport(\n this.url,\n this.options.transport as SSEClientTransportOptions\n );\n default:\n throw new Error(`Unsupported transport type: ${transportType}`);\n }\n }\n\n private async tryConnect(\n transportType: TransportType\n ): Promise<MCPClientConnectionResult> {\n const transports: BaseTransportType[] =\n transportType === \"auto\" ? [\"streamable-http\", \"sse\"] : [transportType];\n\n for (const currentTransportType of transports) {\n const isLastTransport =\n currentTransportType === transports[transports.length - 1];\n const hasFallback =\n transportType === \"auto\" &&\n currentTransportType === \"streamable-http\" &&\n !isLastTransport;\n\n const transport = this.getTransport(currentTransportType);\n\n try {\n await this.client.connect(transport);\n\n return {\n state: MCPConnectionState.CONNECTED,\n transport: currentTransportType\n };\n } catch (e) {\n const error = e instanceof Error ? e : new Error(String(e));\n\n if (isUnauthorized(error)) {\n return {\n state: MCPConnectionState.AUTHENTICATING\n };\n }\n\n if (isTransportNotImplemented(error) && hasFallback) {\n // Try the next transport\n continue;\n }\n\n return {\n state: MCPConnectionState.FAILED,\n error\n };\n }\n }\n\n // Should never reach here\n return {\n state: MCPConnectionState.FAILED,\n error: new Error(\"No transports available\")\n };\n }\n\n private _capabilityErrorHandler<T>(empty: T, method: string) {\n return (e: { code: number }) => {\n // server is badly behaved and returning invalid capabilities. This commonly occurs for resource templates\n if (e.code === -32601) {\n const url = this.url.toString();\n this._onObservabilityEvent.fire({\n type: \"mcp:client:discover\",\n displayMessage: `The server advertised support for the capability ${method.split(\"/\")[0]}, but returned \"Method not found\" for '${method}' for ${url}`,\n payload: {\n url,\n capability: method.split(\"/\")[0],\n error: toErrorMessage(e)\n },\n timestamp: Date.now(),\n id: nanoid()\n });\n return empty;\n }\n throw e;\n };\n }\n}\n"],"mappings":";;;;;;;AAIA,SAAgB,aAAa,IAA4B;AACvD,QAAO,EAAE,SAAS,IAAI;;AAGxB,IAAa,kBAAb,MAAmD;;gBACT,EAAE;;CAE1C,IAA0B,GAAS;AACjC,OAAK,OAAO,KAAK,EAAE;AACnB,SAAO;;CAGT,UAAgB;AACd,SAAO,KAAK,OAAO,OACjB,KAAI;AACF,QAAK,OAAO,KAAK,CAAE,SAAS;UACtB;;;AASd,IAAa,UAAb,MAA8C;;oCACF,IAAI,KAAK;gBAEvB,aAAa;AACvC,QAAK,WAAW,IAAI,SAAS;AAC7B,UAAO,mBAAmB,KAAK,WAAW,OAAO,SAAS,CAAC;;;CAG7D,KAAK,MAAe;AAClB,OAAK,MAAM,YAAY,CAAC,GAAG,KAAK,WAAW,CACzC,KAAI;AACF,YAAS,KAAK;WACP,KAAK;AAEZ,WAAQ,MAAM,2BAA2B,IAAI;;;CAKnD,UAAgB;AACd,OAAK,WAAW,OAAO;;;;;;ACjD3B,SAAgB,eAAe,OAAwB;AACrD,QAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;;AAG/D,SAAS,aAAa,OAAoC;AACxD,KACE,SACA,OAAO,UAAU,YACjB,UAAU,SACV,OAAQ,MAA4B,SAAS,SAE7C,QAAQ,MAA2B;;AAKvC,SAAgB,eAAe,OAAyB;AAEtD,KADa,aAAa,MAAM,KACnB,IAAK,QAAO;CAEzB,MAAM,MAAM,eAAe,MAAM;AACjC,QAAO,IAAI,SAAS,eAAe,IAAI,IAAI,SAAS,MAAM;;AAM5D,SAAgB,0BAA0B,OAAyB;CACjE,MAAM,OAAO,aAAa,MAAM;AAChC,KAAI,SAAS,OAAO,SAAS,IAAK,QAAO;CAEzC,MAAM,MAAM,eAAe,MAAM;AACjC,QACE,IAAI,SAAS,M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