agents 0.11.4 → 0.11.6

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.
Files changed (44) hide show
  1. package/README.md +44 -1
  2. package/dist/browser/ai.js +1 -1
  3. package/dist/browser/index.js +1 -1
  4. package/dist/browser/tanstack-ai.js +1 -1
  5. package/dist/browser/tanstack-ai.js.map +1 -1
  6. package/dist/chat/index.d.ts +169 -23
  7. package/dist/chat/index.js +232 -1
  8. package/dist/chat/index.js.map +1 -1
  9. package/dist/{classPrivateFieldGet2-DAZNVUKb.js → classPrivateFieldGet2-Bqby-AHD.js} +5 -5
  10. package/dist/{client-B_xdiZbn.js → client-D1kFXo80.js} +9 -1
  11. package/dist/{client-B_xdiZbn.js.map → client-D1kFXo80.js.map} +1 -1
  12. package/dist/client.d.ts +1 -1
  13. package/dist/client.js +2 -2
  14. package/dist/client.js.map +1 -1
  15. package/dist/compaction-helpers-C_cN3z55.js.map +1 -1
  16. package/dist/email.js.map +1 -1
  17. package/dist/experimental/memory/session/index.js.map +1 -1
  18. package/dist/{index-D9qo_Inc.d.ts → index-BM7Nk0QD.d.ts} +378 -21
  19. package/dist/index.d.ts +12 -2
  20. package/dist/index.js +329 -30
  21. package/dist/index.js.map +1 -1
  22. package/dist/mcp/client.d.ts +1 -1
  23. package/dist/mcp/client.js +1 -1
  24. package/dist/mcp/do-oauth-client-provider.js.map +1 -1
  25. package/dist/mcp/index.d.ts +1 -1
  26. package/dist/mcp/index.js +1 -1
  27. package/dist/mcp/index.js.map +1 -1
  28. package/dist/mcp/x402.js.map +1 -1
  29. package/dist/react.d.ts +53 -5
  30. package/dist/react.js +47 -7
  31. package/dist/react.js.map +1 -1
  32. package/dist/{retries-JlwH9mnV.d.ts → retries-fLD8cGNf.d.ts} +1 -1
  33. package/dist/retries.d.ts +1 -1
  34. package/dist/{shared-BovR6hRc.js → shared-mfBbxjS1.js} +3 -3
  35. package/dist/{shared-BovR6hRc.js.map → shared-mfBbxjS1.js.map} +1 -1
  36. package/dist/sub-routing.d.ts +14 -0
  37. package/dist/sub-routing.js +171 -0
  38. package/dist/sub-routing.js.map +1 -0
  39. package/dist/utils.d.ts +21 -1
  40. package/dist/utils.js +36 -1
  41. package/dist/utils.js.map +1 -1
  42. package/dist/workflows.d.ts +1 -1
  43. package/dist/workflows.js.map +1 -1
  44. package/package.json +6 -19
@@ -0,0 +1,14 @@
1
+ import {
2
+ _t as parseSubAgentPath,
3
+ gt as getSubAgentByName,
4
+ ht as SubAgentPathMatch,
5
+ mt as SUB_PREFIX,
6
+ vt as routeSubAgentRequest
7
+ } from "./index-BM7Nk0QD.js";
8
+ export {
9
+ SUB_PREFIX,
10
+ SubAgentPathMatch,
11
+ getSubAgentByName,
12
+ parseSubAgentPath,
13
+ routeSubAgentRequest
14
+ };
@@ -0,0 +1,171 @@
1
+ import { camelCaseToKebabCase, isInternalJsStubProp } from "./utils.js";
2
+ //#region src/sub-routing.ts
3
+ /**
4
+ * Sub-agent routing primitives — external addressability for facets.
5
+ *
6
+ * The public surface:
7
+ * - `routeSubAgentRequest(req, parent, options?)` — the sub-agent
8
+ * analog of `routeAgentRequest`. Use in custom fetch handlers.
9
+ * - `getSubAgentByName(parent, Cls, name)` — the sub-agent analog
10
+ * of `getAgentByName`. Returns a typed RPC stub that proxies
11
+ * method calls through the parent. No `.fetch()` support —
12
+ * external HTTP/WS routing goes through `routeSubAgentRequest`.
13
+ *
14
+ * Internal:
15
+ * - `parseSubAgentPath(url)` — URL → `{ childClass, childName, remainingPath }`.
16
+ * - `forwardToFacet(req, parent, match)` — resolves `ctx.facets.get(...)`
17
+ * on the parent and returns `facetStub.fetch(rewrittenReq)`.
18
+ *
19
+ * @experimental The API surface may change before stabilizing.
20
+ */
21
+ /**
22
+ * URL segment marking a parent↔child boundary.
23
+ *
24
+ * Exposed as a constant so callers can build URLs symbolically, but
25
+ * not configurable — the routing layer matches on the literal `sub`
26
+ * token everywhere (parent fetch, client, helpers).
27
+ */
28
+ const SUB_PREFIX = "sub";
29
+ /**
30
+ * Parse a URL and extract the first `/sub/{class}/{name}` segment,
31
+ * if any. Recursive nesting is handled naturally: callers parse one
32
+ * level at a time; the child then parses its own URL (which still
33
+ * contains any deeper `/sub/...` markers).
34
+ *
35
+ * Names are URL-decoded. Classes are kebab-to-CamelCase converted
36
+ * via a best-effort match against a provided lookup — pass
37
+ * `ctx.exports` keys to get exact CamelCase; pass `undefined` for
38
+ * a tolerant conversion without validation.
39
+ *
40
+ * Returns `null` when the URL doesn't contain the marker at a
41
+ * recognized position, or when the marker has no following
42
+ * class+name pair.
43
+ */
44
+ function parseSubAgentPath(url, options) {
45
+ const parts = new URL(url).pathname.split("/").filter(Boolean);
46
+ for (let i = 0; i < parts.length; i++) {
47
+ if (parts[i] !== "sub") continue;
48
+ if (i + 2 >= parts.length) continue;
49
+ const classSegment = parts[i + 1];
50
+ const nameSegment = parts[i + 2];
51
+ const childClass = resolveClassName(classSegment, options?.knownClasses);
52
+ if (!childClass) continue;
53
+ let childName;
54
+ try {
55
+ childName = decodeURIComponent(nameSegment);
56
+ } catch {
57
+ continue;
58
+ }
59
+ const remainingParts = parts.slice(i + 3);
60
+ const remainingPath = remainingParts.length > 0 ? "/" + remainingParts.join("/") : "/";
61
+ return {
62
+ childClass,
63
+ childName,
64
+ remainingPath
65
+ };
66
+ }
67
+ return null;
68
+ }
69
+ /**
70
+ * Best-effort kebab-to-CamelCase match. If `knownClasses` is
71
+ * provided, returns the matching CamelCase entry (or null if no
72
+ * match). If not, performs a naive kebab→CamelCase conversion.
73
+ */
74
+ function resolveClassName(segment, knownClasses) {
75
+ if (knownClasses) return knownClasses.find((name) => camelCaseToKebabCase(name) === segment) ?? null;
76
+ return segment.split("-").map((s) => s.charAt(0).toUpperCase() + s.slice(1)).join("");
77
+ }
78
+ /**
79
+ * Route a request into a sub-agent via its parent DO.
80
+ *
81
+ * Use this in a custom fetch handler when your URL shape doesn't
82
+ * match the `/agents/{class}/{name}` default — you identify and
83
+ * fetch the parent yourself, then let this helper parse the
84
+ * `/sub/{child}/...` tail and forward it.
85
+ *
86
+ * Runs `onBeforeSubAgent` on the parent DO (authorization / request
87
+ * mutation / short-circuit response).
88
+ *
89
+ * For the default `/agents/...` URL shape, use `routeAgentRequest`
90
+ * instead — it handles the parent lookup and this dispatch in one
91
+ * call.
92
+ *
93
+ * @example
94
+ * ```ts
95
+ * export default {
96
+ * async fetch(req, env) {
97
+ * const { parentName, rest } = myCustomParse(req.url);
98
+ * const parent = await getAgentByName(env.Inbox, parentName);
99
+ * return routeSubAgentRequest(req, parent, { fromPath: rest });
100
+ * }
101
+ * };
102
+ * ```
103
+ *
104
+ * @experimental The API surface may change before stabilizing.
105
+ */
106
+ async function routeSubAgentRequest(req, parent, options) {
107
+ if (!parseSubAgentPath(options?.fromPath ? `http://placeholder${options.fromPath.startsWith("/") ? "" : "/"}${options.fromPath}` : req.url)) return new Response("Sub-agent path not found in request URL", { status: 400 });
108
+ const forwardReq = options?.fromPath !== void 0 ? new Request(rewritePathname(req.url, options.fromPath), req) : req;
109
+ return parent.fetch(forwardReq);
110
+ }
111
+ /**
112
+ * Replace a URL's pathname (and optionally its search) while
113
+ * preserving every other component. Matches how `_cf_forwardToFacet`
114
+ * forwards requests — pathname is the only thing that changes by
115
+ * default; if the replacement path carries its own query string,
116
+ * that wins.
117
+ */
118
+ function rewritePathname(url, fromPath) {
119
+ const normalized = fromPath.startsWith("/") ? fromPath : `/${fromPath}`;
120
+ const queryIdx = normalized.indexOf("?");
121
+ const pathOnly = queryIdx >= 0 ? normalized.slice(0, queryIdx) : normalized;
122
+ const querySuffix = queryIdx >= 0 ? normalized.slice(queryIdx) : "";
123
+ const rewritten = new URL(url);
124
+ rewritten.pathname = pathOnly;
125
+ if (querySuffix) rewritten.search = querySuffix;
126
+ return rewritten.toString();
127
+ }
128
+ /**
129
+ * Get a typed RPC stub for a sub-agent from outside the parent DO.
130
+ *
131
+ * The returned stub proxies method calls through the parent via a
132
+ * stateless per-call bridge (caller → parent → facet), so each
133
+ * method invocation costs one extra RPC hop. Works across parent
134
+ * hibernation — no cached references to go stale.
135
+ *
136
+ * Limitations:
137
+ * - RPC methods only. `.fetch()` is not supported (will throw).
138
+ * Use `routeSubAgentRequest` for external HTTP/WS.
139
+ * - Arguments and return values must be structured-cloneable,
140
+ * same as any DO RPC call.
141
+ * - Does not run `onBeforeSubAgent` on the parent — analogous to
142
+ * `getAgentByName` not running `onBeforeConnect`. The caller is
143
+ * assumed to have performed whatever access checks are needed.
144
+ *
145
+ * @example
146
+ * ```ts
147
+ * const inbox = await getAgentByName(env.MyInbox, userId);
148
+ * const chat = await getSubAgentByName(inbox, MyChat, chatId);
149
+ * await chat.addMessage({ role: "user", content: "hi" });
150
+ * ```
151
+ *
152
+ * @experimental The API surface may change before stabilizing.
153
+ */
154
+ async function getSubAgentByName(parent, cls, name) {
155
+ if (name.includes("\0")) throw new Error(`Sub-agent name contains null character (\\0), which is reserved.`);
156
+ const bridge = parent;
157
+ const className = cls?.name;
158
+ if (!className) throw new Error(`getSubAgentByName: could not determine class name from ${cls}. Ensure you are passing the class constructor (e.g. getSubAgentByName(parent, MyChat, name)), not a string or undefined.`);
159
+ return new Proxy({}, { get(_target, prop) {
160
+ if (isInternalJsStubProp(prop)) return void 0;
161
+ if (typeof prop !== "string") return void 0;
162
+ if (prop === "fetch") return () => {
163
+ throw new Error("getSubAgentByName returns an RPC-only stub — .fetch() is not supported. Use routeSubAgentRequest() or the /agents/{parent}/{name}/sub/{child}/{name} URL for external HTTP/WS routing.");
164
+ };
165
+ return async (...args) => bridge._cf_invokeSubAgent(className, name, prop, args);
166
+ } });
167
+ }
168
+ //#endregion
169
+ export { SUB_PREFIX, getSubAgentByName, parseSubAgentPath, routeSubAgentRequest };
170
+
171
+ //# sourceMappingURL=sub-routing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sub-routing.js","names":[],"sources":["../src/sub-routing.ts"],"sourcesContent":["/**\n * Sub-agent routing primitives — external addressability for facets.\n *\n * The public surface:\n * - `routeSubAgentRequest(req, parent, options?)` — the sub-agent\n * analog of `routeAgentRequest`. Use in custom fetch handlers.\n * - `getSubAgentByName(parent, Cls, name)` — the sub-agent analog\n * of `getAgentByName`. Returns a typed RPC stub that proxies\n * method calls through the parent. No `.fetch()` support —\n * external HTTP/WS routing goes through `routeSubAgentRequest`.\n *\n * Internal:\n * - `parseSubAgentPath(url)` — URL → `{ childClass, childName, remainingPath }`.\n * - `forwardToFacet(req, parent, match)` — resolves `ctx.facets.get(...)`\n * on the parent and returns `facetStub.fetch(rewrittenReq)`.\n *\n * @experimental The API surface may change before stabilizing.\n */\n\nimport { camelCaseToKebabCase, isInternalJsStubProp } from \"./utils\";\nimport type { Agent, SubAgentClass, SubAgentStub } from \"./index\";\n\n/**\n * URL segment marking a parent↔child boundary.\n *\n * Exposed as a constant so callers can build URLs symbolically, but\n * not configurable — the routing layer matches on the literal `sub`\n * token everywhere (parent fetch, client, helpers).\n */\nexport const SUB_PREFIX = \"sub\";\n\nexport interface SubAgentPathMatch {\n /** CamelCase class name of the child, as it appears in `ctx.exports`. */\n childClass: string;\n /** URL-decoded child name. */\n childName: string;\n /**\n * Request path to forward to the child, with the\n * `/sub/{class}/{name}` segment stripped. Always begins with `/`;\n * may itself contain further `/sub/...` markers when a\n * recursively nested sub-agent is being routed.\n */\n remainingPath: string;\n}\n\n/**\n * Parse a URL and extract the first `/sub/{class}/{name}` segment,\n * if any. Recursive nesting is handled naturally: callers parse one\n * level at a time; the child then parses its own URL (which still\n * contains any deeper `/sub/...` markers).\n *\n * Names are URL-decoded. Classes are kebab-to-CamelCase converted\n * via a best-effort match against a provided lookup — pass\n * `ctx.exports` keys to get exact CamelCase; pass `undefined` for\n * a tolerant conversion without validation.\n *\n * Returns `null` when the URL doesn't contain the marker at a\n * recognized position, or when the marker has no following\n * class+name pair.\n */\nexport function parseSubAgentPath(\n url: string,\n options?: {\n /** CamelCase class names to match against (usually `ctx.exports` keys). */\n knownClasses?: readonly string[];\n }\n): SubAgentPathMatch | null {\n const pathname = new URL(url).pathname;\n const parts = pathname.split(\"/\").filter(Boolean);\n\n // Walk every occurrence of the `sub` segment — a plain\n // `indexOf(SUB_PREFIX)` would mis-match when the literal token\n // appears earlier in the URL (parent instance name == \"sub\", a\n // `basePath` segment that happens to be \"sub\", etc). We return\n // the first position where `parts[i+1]` resolves to a valid\n // class, which pins the real parent↔child boundary.\n for (let i = 0; i < parts.length; i++) {\n if (parts[i] !== SUB_PREFIX) continue;\n if (i + 2 >= parts.length) continue;\n\n const classSegment = parts[i + 1];\n const nameSegment = parts[i + 2];\n\n const childClass = resolveClassName(classSegment, options?.knownClasses);\n if (!childClass) continue;\n\n let childName: string;\n try {\n childName = decodeURIComponent(nameSegment);\n } catch {\n continue;\n }\n\n const remainingParts = parts.slice(i + 3);\n const remainingPath =\n remainingParts.length > 0 ? \"/\" + remainingParts.join(\"/\") : \"/\";\n\n return { childClass, childName, remainingPath };\n }\n\n return null;\n}\n\n/**\n * Best-effort kebab-to-CamelCase match. If `knownClasses` is\n * provided, returns the matching CamelCase entry (or null if no\n * match). If not, performs a naive kebab→CamelCase conversion.\n */\nfunction resolveClassName(\n segment: string,\n knownClasses?: readonly string[]\n): string | null {\n if (knownClasses) {\n const match = knownClasses.find(\n (name) => camelCaseToKebabCase(name) === segment\n );\n return match ?? null;\n }\n return segment\n .split(\"-\")\n .map((s) => s.charAt(0).toUpperCase() + s.slice(1))\n .join(\"\");\n}\n\n// ── routeSubAgentRequest ───────────────────────────────────────────\n\n/**\n * Minimal parent-side shape that `routeSubAgentRequest` relies on:\n * something fetchable (a DO stub, a sub-agent stub, etc.).\n *\n * @internal\n */\ninterface FetchableParent {\n fetch(req: Request): Promise<Response>;\n}\n\n/**\n * Route a request into a sub-agent via its parent DO.\n *\n * Use this in a custom fetch handler when your URL shape doesn't\n * match the `/agents/{class}/{name}` default — you identify and\n * fetch the parent yourself, then let this helper parse the\n * `/sub/{child}/...` tail and forward it.\n *\n * Runs `onBeforeSubAgent` on the parent DO (authorization / request\n * mutation / short-circuit response).\n *\n * For the default `/agents/...` URL shape, use `routeAgentRequest`\n * instead — it handles the parent lookup and this dispatch in one\n * call.\n *\n * @example\n * ```ts\n * export default {\n * async fetch(req, env) {\n * const { parentName, rest } = myCustomParse(req.url);\n * const parent = await getAgentByName(env.Inbox, parentName);\n * return routeSubAgentRequest(req, parent, { fromPath: rest });\n * }\n * };\n * ```\n *\n * @experimental The API surface may change before stabilizing.\n */\nexport async function routeSubAgentRequest(\n req: Request,\n parent: unknown,\n options?: {\n /**\n * Path to route on. Defaults to `req.url`'s pathname. Useful\n * when your outer URL is custom (e.g. `/api/v1/...`) and you\n * want to route the sub-agent tail without rewriting the\n * Request first.\n */\n fromPath?: string;\n }\n): Promise<Response> {\n // We don't know the parent's ctx.exports from here, so parse with\n // a permissive resolver. If the class doesn't exist, the parent's\n // bridge will 404. This lets us keep the helper self-contained.\n const pathForParsing = options?.fromPath\n ? `http://placeholder${options.fromPath.startsWith(\"/\") ? \"\" : \"/\"}${options.fromPath}`\n : req.url;\n\n const match = parseSubAgentPath(pathForParsing);\n if (!match) {\n return new Response(\"Sub-agent path not found in request URL\", {\n status: 400\n });\n }\n\n // Hand the request to the parent so `onBeforeSubAgent` fires in\n // the parent's isolate. The parent's `fetch` handler recognizes\n // the marker internally — we preserve the original request URL\n // (possibly rewritten by `fromPath`) so the parent's parse sees\n // the same match.\n //\n // Key subtlety: when rewriting the pathname via `fromPath`, we\n // mutate the *original* URL's pathname instead of constructing a\n // new URL from scratch. `new URL(\"/path\", baseWithQuery)` discards\n // the base's search; we want the caller's query params (e.g. auth\n // tokens, PartySocket's `_pk=...` handshake key) to survive.\n // Mirrors how `_cf_forwardToFacet` rewrites only pathname when\n // handing off to the child facet. If `fromPath` itself contains a\n // `?query` segment, that overrides the original.\n const forwardReq =\n options?.fromPath !== undefined\n ? new Request(rewritePathname(req.url, options.fromPath), req)\n : req;\n\n return (parent as FetchableParent).fetch(forwardReq);\n}\n\n/**\n * Replace a URL's pathname (and optionally its search) while\n * preserving every other component. Matches how `_cf_forwardToFacet`\n * forwards requests — pathname is the only thing that changes by\n * default; if the replacement path carries its own query string,\n * that wins.\n */\nfunction rewritePathname(url: string, fromPath: string): string {\n const normalized = fromPath.startsWith(\"/\") ? fromPath : `/${fromPath}`;\n const queryIdx = normalized.indexOf(\"?\");\n const pathOnly = queryIdx >= 0 ? normalized.slice(0, queryIdx) : normalized;\n const querySuffix = queryIdx >= 0 ? normalized.slice(queryIdx) : \"\";\n\n const rewritten = new URL(url);\n rewritten.pathname = pathOnly;\n if (querySuffix) {\n rewritten.search = querySuffix; // URL setter keeps the `?` prefix\n }\n return rewritten.toString();\n}\n\n// ── getSubAgentByName ──────────────────────────────────────────────\n\n/**\n * Parent-side RPC bridge shape that `getSubAgentByName` relies on.\n *\n * @internal\n */\ninterface SubAgentInvokeEndpoint {\n _cf_invokeSubAgent(\n className: string,\n name: string,\n method: string,\n args: unknown[]\n ): Promise<unknown>;\n}\n\n/**\n * Get a typed RPC stub for a sub-agent from outside the parent DO.\n *\n * The returned stub proxies method calls through the parent via a\n * stateless per-call bridge (caller → parent → facet), so each\n * method invocation costs one extra RPC hop. Works across parent\n * hibernation — no cached references to go stale.\n *\n * Limitations:\n * - RPC methods only. `.fetch()` is not supported (will throw).\n * Use `routeSubAgentRequest` for external HTTP/WS.\n * - Arguments and return values must be structured-cloneable,\n * same as any DO RPC call.\n * - Does not run `onBeforeSubAgent` on the parent — analogous to\n * `getAgentByName` not running `onBeforeConnect`. The caller is\n * assumed to have performed whatever access checks are needed.\n *\n * @example\n * ```ts\n * const inbox = await getAgentByName(env.MyInbox, userId);\n * const chat = await getSubAgentByName(inbox, MyChat, chatId);\n * await chat.addMessage({ role: \"user\", content: \"hi\" });\n * ```\n *\n * @experimental The API surface may change before stabilizing.\n */\nexport async function getSubAgentByName<T extends Agent>(\n parent: unknown,\n cls: SubAgentClass<T>,\n name: string\n): Promise<SubAgentStub<T>> {\n if (name.includes(\"\\0\")) {\n throw new Error(\n `Sub-agent name contains null character (\\\\0), which is reserved.`\n );\n }\n\n const bridge = parent as SubAgentInvokeEndpoint;\n const className = cls?.name;\n if (!className) {\n throw new Error(\n `getSubAgentByName: could not determine class name from ${cls}. ` +\n `Ensure you are passing the class constructor (e.g. getSubAgentByName(parent, MyChat, name)), not a string or undefined.`\n );\n }\n\n return new Proxy(\n {},\n {\n get(_target, prop) {\n // JS / runtime / test-framework probes (thenable check,\n // serialization, inspection, matcher duck-typing) must NOT\n // dispatch an RPC — returning `undefined` is the contract\n // the inner `createStubProxy` uses for `useAgent` stubs.\n // Without this guard, `JSON.stringify(stub)`, `console.log`,\n // Vitest matchers, and `await stub` would all trigger bogus\n // `_cf_invokeSubAgent` calls that fail with \"Method not found\".\n if (isInternalJsStubProp(prop)) return undefined;\n if (typeof prop !== \"string\") return undefined;\n // `.fetch` gets a dedicated error so users who try to use\n // the stub for HTTP/WS get a helpful pointer.\n if (prop === \"fetch\") {\n return () => {\n throw new Error(\n `getSubAgentByName returns an RPC-only stub — .fetch() is ` +\n `not supported. Use routeSubAgentRequest() or the ` +\n `/agents/{parent}/{name}/sub/{child}/{name} URL for ` +\n `external HTTP/WS routing.`\n );\n };\n }\n return async (...args: unknown[]) =>\n bridge._cf_invokeSubAgent(className, name, prop, args);\n }\n }\n ) as SubAgentStub<T>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,MAAa,aAAa;;;;;;;;;;;;;;;;AA+B1B,SAAgB,kBACd,KACA,SAI0B;CAE1B,MAAM,QADW,IAAI,IAAI,IAAI,CAAC,SACP,MAAM,IAAI,CAAC,OAAO,QAAQ;AAQjD,MAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACrC,MAAI,MAAM,OAAA,MAAmB;AAC7B,MAAI,IAAI,KAAK,MAAM,OAAQ;EAE3B,MAAM,eAAe,MAAM,IAAI;EAC/B,MAAM,cAAc,MAAM,IAAI;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B,KAAI,YACF,WAAU,SAAS;AAErB,QAAO,UAAU,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6C7B,eAAsB,kBACpB,QACA,KACA,MAC0B;AAC1B,KAAI,KAAK,SAAS,KAAK,CACrB,OAAM,IAAI,MACR,mEACD;CAGH,MAAM,SAAS;CACf,MAAM,YAAY,KAAK;AACvB,KAAI,CAAC,UACH,OAAM,IAAI,MACR,0DAA0D,IAAI,2HAE/D;AAGH,QAAO,IAAI,MACT,EAAE,EACF,EACE,IAAI,SAAS,MAAM;AAQjB,MAAI,qBAAqB,KAAK,CAAE,QAAO,KAAA;AACvC,MAAI,OAAO,SAAS,SAAU,QAAO,KAAA;AAGrC,MAAI,SAAS,QACX,cAAa;AACX,SAAM,IAAI,MACR,yLAID;;AAGL,SAAO,OAAO,GAAG,SACf,OAAO,mBAAmB,WAAW,MAAM,MAAM,KAAK;IAE3D,CACF"}
package/dist/utils.d.ts CHANGED
@@ -1,4 +1,24 @@
1
1
  //#region src/utils.d.ts
2
+ /**
3
+ * Property keys that JavaScript runtimes and test frameworks probe
4
+ * on arbitrary objects (serialization, thenable check, inspection,
5
+ * matcher duck-typing). When an RPC-stub Proxy is accessed by
6
+ * `JSON.stringify`, `console.log`, `await`, Vitest matchers, etc.,
7
+ * it hits one of these — we must return `undefined` instead of a
8
+ * call-wrapper to avoid firing a bogus RPC for a method the child
9
+ * doesn't implement.
10
+ *
11
+ * @internal
12
+ */
13
+ declare const INTERNAL_JS_STUB_PROPS: ReadonlySet<string>;
14
+ /**
15
+ * True when the property access is a JS-internal probe that must
16
+ * NOT dispatch an RPC call. Catches all symbol keys plus the named
17
+ * set above.
18
+ *
19
+ * @internal
20
+ */
21
+ declare function isInternalJsStubProp(prop: string | symbol): boolean;
2
22
  /**
3
23
  * Convert a camelCase string to a kebab-case string
4
24
  * @param str The string to convert
@@ -6,5 +26,5 @@
6
26
  */
7
27
  declare function camelCaseToKebabCase(str: string): string;
8
28
  //#endregion
9
- export { camelCaseToKebabCase };
29
+ export { INTERNAL_JS_STUB_PROPS, camelCaseToKebabCase, isInternalJsStubProp };
10
30
  //# sourceMappingURL=utils.d.ts.map
package/dist/utils.js CHANGED
@@ -1,5 +1,40 @@
1
1
  //#region src/utils.ts
2
2
  /**
3
+ * Property keys that JavaScript runtimes and test frameworks probe
4
+ * on arbitrary objects (serialization, thenable check, inspection,
5
+ * matcher duck-typing). When an RPC-stub Proxy is accessed by
6
+ * `JSON.stringify`, `console.log`, `await`, Vitest matchers, etc.,
7
+ * it hits one of these — we must return `undefined` instead of a
8
+ * call-wrapper to avoid firing a bogus RPC for a method the child
9
+ * doesn't implement.
10
+ *
11
+ * @internal
12
+ */
13
+ const INTERNAL_JS_STUB_PROPS = new Set([
14
+ "toJSON",
15
+ "then",
16
+ "catch",
17
+ "finally",
18
+ "valueOf",
19
+ "toString",
20
+ "constructor",
21
+ "prototype",
22
+ "$$typeof",
23
+ "@@toStringTag",
24
+ "asymmetricMatch",
25
+ "nodeType"
26
+ ]);
27
+ /**
28
+ * True when the property access is a JS-internal probe that must
29
+ * NOT dispatch an RPC call. Catches all symbol keys plus the named
30
+ * set above.
31
+ *
32
+ * @internal
33
+ */
34
+ function isInternalJsStubProp(prop) {
35
+ return typeof prop === "symbol" || INTERNAL_JS_STUB_PROPS.has(prop);
36
+ }
37
+ /**
3
38
  * Convert a camelCase string to a kebab-case string
4
39
  * @param str The string to convert
5
40
  * @returns The kebab-case string
@@ -11,6 +46,6 @@ function camelCaseToKebabCase(str) {
11
46
  return kebabified.replace(/_/g, "-").replace(/-$/, "");
12
47
  }
13
48
  //#endregion
14
- export { camelCaseToKebabCase };
49
+ export { INTERNAL_JS_STUB_PROPS, camelCaseToKebabCase, isInternalJsStubProp };
15
50
 
16
51
  //# sourceMappingURL=utils.js.map
package/dist/utils.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","names":[],"sources":["../src/utils.ts"],"sourcesContent":["/**\n * Convert a camelCase string to a kebab-case string\n * @param str The string to convert\n * @returns The kebab-case string\n */\nexport function 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"],"mappings":";;;;;;AAKA,SAAgB,qBAAqB,KAAqB;AAExD,KAAI,QAAQ,IAAI,aAAa,IAAI,QAAQ,IAAI,aAAa,CACxD,QAAO,IAAI,aAAa,CAAC,QAAQ,MAAM,IAAI;CAI7C,IAAI,aAAa,IAAI,QACnB,WACC,WAAW,IAAI,OAAO,aAAa,GACrC;AACD,cAAa,WAAW,WAAW,IAAI,GAAG,WAAW,MAAM,EAAE,GAAG;AAEhE,QAAO,WAAW,QAAQ,MAAM,IAAI,CAAC,QAAQ,MAAM,GAAG"}
1
+ {"version":3,"file":"utils.js","names":[],"sources":["../src/utils.ts"],"sourcesContent":["/**\n * Property keys that JavaScript runtimes and test frameworks probe\n * on arbitrary objects (serialization, thenable check, inspection,\n * matcher duck-typing). When an RPC-stub Proxy is accessed by\n * `JSON.stringify`, `console.log`, `await`, Vitest matchers, etc.,\n * it hits one of these — we must return `undefined` instead of a\n * call-wrapper to avoid firing a bogus RPC for a method the child\n * doesn't implement.\n *\n * @internal\n */\nexport const INTERNAL_JS_STUB_PROPS: ReadonlySet<string> = new Set([\n \"toJSON\",\n \"then\",\n \"catch\",\n \"finally\",\n \"valueOf\",\n \"toString\",\n \"constructor\",\n \"prototype\",\n \"$$typeof\",\n \"@@toStringTag\",\n \"asymmetricMatch\",\n \"nodeType\"\n]);\n\n/**\n * True when the property access is a JS-internal probe that must\n * NOT dispatch an RPC call. Catches all symbol keys plus the named\n * set above.\n *\n * @internal\n */\nexport function isInternalJsStubProp(prop: string | symbol): boolean {\n return typeof prop === \"symbol\" || INTERNAL_JS_STUB_PROPS.has(prop);\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 */\nexport function 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"],"mappings":";;;;;;;;;;;;AAWA,MAAa,yBAA8C,IAAI,IAAI;CACjE;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;;;;;;;;AASF,SAAgB,qBAAqB,MAAgC;AACnE,QAAO,OAAO,SAAS,YAAY,uBAAuB,IAAI,KAAK;;;;;;;AAQrE,SAAgB,qBAAqB,KAAqB;AAExD,KAAI,QAAQ,IAAI,aAAa,IAAI,QAAQ,IAAI,aAAa,CACxD,QAAO,IAAI,aAAa,CAAC,QAAQ,MAAM,IAAI;CAI7C,IAAI,aAAa,IAAI,QACnB,WACC,WAAW,IAAI,OAAO,aAAa,GACrC;AACD,cAAa,WAAW,WAAW,IAAI,GAAG,WAAW,MAAM,EAAE,GAAG;AAEhE,QAAO,WAAW,QAAQ,MAAM,IAAI,CAAC,QAAQ,MAAM,GAAG"}
@@ -1,4 +1,4 @@
1
- import { r as Agent } from "./index-D9qo_Inc.js";
1
+ import { r as Agent } from "./index-BM7Nk0QD.js";
2
2
  import {
3
3
  S as WorkflowTrackingRow,
4
4
  _ as WorkflowPage,
@@ -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 /**\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 await 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 await this.agent._workflow_updateState(\"merge\", partialState);\n });\n };\n\n wrappedStep.resetAgentState = async (): Promise<void> => {\n await step.do(`__agent_resetState_${stepCounter++}`, async () => {\n await 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;AAVjB,OAAQ,oBAAoB;AAO5B,OAAQ,iBAAiB;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;M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SAAwB;AACnD,OAAK,MAAM,oBAAoB,QAAQ;;;;;;;;;;;;;;;;CAiBzC,MAAgB,gBACd,MACA,SACY;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"}
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 /**\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 await 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 await this.agent._workflow_updateState(\"merge\", partialState);\n });\n };\n\n wrappedStep.resetAgentState = async (): Promise<void> => {\n await step.do(`__agent_resetState_${stepCounter++}`, async () => {\n await 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,Q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e,QAAQ,IAAI,UAAU,OAAO,IAAI;AACrE,MAAI;AACF,SAAM,KAAK,YAAY;IACrB,cAAc,KAAK;IACnB,YAAY,KAAK;IACjB,MAAM;IACN,OAAO;IACP,WAAW,KAAK,KAAK;IACtB,CAAC;WACK,YAAY;;;;;;;CAUvB,MAAgB,YAAY,UAA2C;AACrE,QAAM,KAAK,MAAM,yBAAyB,SAAS;;;;;;;;;;;;;;;;;;CAmBrD,MAAgB,eAAe,UAAuC;AACpE,QAAM,KAAK,YAAY;GACrB,cAAc,KAAK;GACnB,YAAY,KAAK;GACjB,MAAM;GACI;GACV,WAAW,KAAK,KAAK;GACtB,CAAC;;;;;;;;CASJ,mBAA6B,SAAwB;AACnD,OAAK,MAAM,oBAAoB,QAAQ;;;;;;;;;;;;;;;;CAiBzC,MAAgB,gBACd,MACA,SACY;EACZ,MAAM,WAAW,SAAS,YAAY;EACtC,MAAM,YAAY,SAAS,aAAa;EACxC,MAAM,UAAU,SAAS;EAUzB,MAAM,WAAU,MANI,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.11.4",
12
+ "version": "0.11.6",
13
13
  "license": "MIT",
14
14
  "repository": {
15
15
  "directory": "packages/agents",
@@ -29,23 +29,18 @@
29
29
  "@modelcontextprotocol/sdk": "1.29.0",
30
30
  "@rolldown/plugin-babel": "^0.2.3",
31
31
  "cron-schedule": "^6.0.0",
32
- "json-schema": "^0.4.0",
33
- "json-schema-to-typescript": "^15.0.4",
34
32
  "mimetext": "^3.0.28",
35
33
  "nanoid": "^5.1.9",
36
- "partyserver": "^0.4.1",
37
- "partysocket": "1.1.16",
38
- "picomatch": "^4.0.4",
34
+ "partyserver": "^0.5.3",
35
+ "partysocket": "1.1.18",
39
36
  "yargs": "^18.0.0"
40
37
  },
41
38
  "devDependencies": {
42
- "@ai-sdk/openai": "^3.0.53",
43
39
  "@ai-sdk/react": "^3.0.170",
44
- "@cloudflare/workers-oauth-provider": "^0.4.0",
45
- "@tanstack/ai": "^0.10.3",
40
+ "@tanstack/ai": "^0.14.0",
46
41
  "@types/react": "^19.2.14",
47
42
  "@types/yargs": "^17.0.35",
48
- "@vitest/browser-playwright": "^4.1.4",
43
+ "@vitest/browser-playwright": "^4.1.5",
49
44
  "@x402/core": "^2.10.0",
50
45
  "@x402/evm": "^2.10.0",
51
46
  "ai": "^6.0.168",
@@ -54,22 +49,17 @@
54
49
  "zod": "^4.3.6"
55
50
  },
56
51
  "peerDependencies": {
57
- "@ai-sdk/react": "^3.0.0",
58
52
  "@cloudflare/ai-chat": ">=0.0.8 <1.0.0",
59
53
  "@cloudflare/codemode": ">=0.0.7 <1.0.0",
60
- "@tanstack/ai": "^0.10.2",
54
+ "@tanstack/ai": ">=0.10.2 <1.0.0",
61
55
  "@x402/core": "^2.0.0",
62
56
  "@x402/evm": "^2.0.0",
63
57
  "ai": "^6.0.0",
64
58
  "react": "^19.0.0",
65
- "viem": ">=2.0.0",
66
59
  "vite": ">=6.0.0 <9.0.0",
67
60
  "zod": "^4.0.0"
68
61
  },
69
62
  "peerDependenciesMeta": {
70
- "@ai-sdk/react": {
71
- "optional": true
72
- },
73
63
  "@cloudflare/ai-chat": {
74
64
  "optional": true
75
65
  },
@@ -85,9 +75,6 @@
85
75
  "@x402/evm": {
86
76
  "optional": true
87
77
  },
88
- "viem": {
89
- "optional": true
90
- },
91
78
  "vite": {
92
79
  "optional": true
93
80
  }