agents 0.12.4 → 0.13.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -8
- package/dist/{agent-tool-types-CM_50fcV.d.ts → agent-tool-types-Dn9n-3SI.d.ts} +234 -85
- package/dist/agent-tool-types.d.ts +1 -1
- package/dist/{agent-tools-BylX6WXG.d.ts → agent-tools-B1ttU-pq.d.ts} +2 -2
- package/dist/agent-tools-BAdX1vdI.js.map +1 -1
- package/dist/agent-tools.d.ts +1 -1
- package/dist/agent-tools.js.map +1 -1
- package/dist/ai-chat-agent.js.map +1 -1
- package/dist/ai-chat-v5-migration.js.map +1 -1
- package/dist/ai-react.js.map +1 -1
- package/dist/ai-types.js.map +1 -1
- package/dist/browser/ai.js +1 -1
- package/dist/browser/ai.js.map +1 -1
- package/dist/browser/index.js +1 -1
- package/dist/browser/tanstack-ai.js +1 -1
- package/dist/browser/tanstack-ai.js.map +1 -1
- package/dist/chat/index.d.ts +2 -2
- package/dist/chat/index.js.map +1 -1
- package/dist/{classPrivateFieldGet2-CS51BNGR.js → classPrivateFieldGet2-Evpt0SEr.js} +5 -5
- package/dist/cli/index.js.map +1 -1
- package/dist/client-D1kFXo80.js.map +1 -1
- package/dist/client.d.ts +1 -1
- package/dist/client.js.map +1 -1
- package/dist/codemode/ai.js.map +1 -1
- package/dist/{compaction-helpers-bYvP1o2S.d.ts → compaction-helpers-DAe-xiVY.d.ts} +33 -15
- package/dist/compaction-helpers-DvcZnvQ1.js.map +1 -1
- package/dist/email.d.ts +1 -1
- package/dist/email.js.map +1 -1
- package/dist/experimental/memory/session/index.d.ts +247 -34
- package/dist/experimental/memory/session/index.js +540 -135
- package/dist/experimental/memory/session/index.js.map +1 -1
- package/dist/experimental/memory/utils/index.d.ts +1 -1
- package/dist/experimental/memory/utils/index.js.map +1 -1
- package/dist/experimental/webmcp.js.map +1 -1
- package/dist/index.d.ts +71 -57
- package/dist/index.js +583 -45
- package/dist/index.js.map +1 -1
- package/dist/internal_context.js.map +1 -1
- package/dist/mcp/client.d.ts +12 -12
- package/dist/mcp/do-oauth-client-provider.js.map +1 -1
- package/dist/mcp/index.d.ts +40 -40
- package/dist/mcp/index.js +21 -45
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/x402.js.map +1 -1
- package/dist/observability/index.js.map +1 -1
- package/dist/react.d.ts +3 -3
- package/dist/react.js.map +1 -1
- package/dist/retries.js.map +1 -1
- package/dist/schedule.js.map +1 -1
- package/dist/serializable.d.ts +1 -1
- package/dist/{shared-DzJYHisH.js → shared-CiKaIK4h.js} +4 -5
- package/dist/{shared-DzJYHisH.js.map → shared-CiKaIK4h.js.map} +1 -1
- package/dist/sub-routing.d.ts +6 -6
- package/dist/sub-routing.js.map +1 -1
- package/dist/tool-output-truncation-CH-khbZ3.js.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/utils.js.map +1 -1
- package/dist/vite.js.map +1 -1
- package/dist/workflow-types.js.map +1 -1
- package/dist/workflows.d.ts +1 -1
- package/dist/workflows.js.map +1 -1
- package/package.json +6 -6
package/dist/sub-routing.js.map
CHANGED
|
@@ -1 +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 forwardUrl =\n options?.fromPath !== undefined\n ? rewritePathname(req.url, options.fromPath)\n : req.url;\n const forwardInit: RequestInit = {\n method: req.method,\n headers: new Headers(req.headers)\n };\n if (req.body && req.method !== \"GET\" && req.method !== \"HEAD\") {\n forwardInit.body = await req.arrayBuffer();\n }\n const forwardReq = new Request(forwardUrl, forwardInit);\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;CAQjD,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;EACrC,IAAI,MAAM,OAAA,OAAmB;EAC7B,IAAI,IAAI,KAAK,MAAM,QAAQ;EAE3B,MAAM,eAAe,MAAM,IAAI;EAC/B,MAAM,cAAc,MAAM,IAAI;EAE9B,MAAM,aAAa,iBAAiB,cAAc,SAAS,aAAa;EACxE,IAAI,CAAC,YAAY;EAEjB,IAAI;EACJ,IAAI;GACF,YAAY,mBAAmB,YAAY;UACrC;GACN;;EAGF,MAAM,iBAAiB,MAAM,MAAM,IAAI,EAAE;EACzC,MAAM,gBACJ,eAAe,SAAS,IAAI,MAAM,eAAe,KAAK,IAAI,GAAG;EAE/D,OAAO;GAAE;G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;;;;;;;;;;;;;;AA6C7B,eAAsB,kBACpB,QACA,KACA,MAC0B;CAC1B,IAAI,KAAK,SAAS,KAAK,EACrB,MAAM,IAAI,MACR,mEACD;CAGH,MAAM,SAAS;CACf,MAAM,YAAY,KAAK;CACvB,IAAI,CAAC,WACH,MAAM,IAAI,MACR,0DAA0D,IAAI,2HAE/D;CAGH,OAAO,IAAI,MACT,EAAE,EACF,EACE,IAAI,SAAS,MAAM;EAQjB,IAAI,qBAAqB,KAAK,EAAE,OAAO,KAAA;EACvC,IAAI,OAAO,SAAS,UAAU,OAAO,KAAA;EAGrC,IAAI,SAAS,SACX,aAAa;GACX,MAAM,IAAI,MACR,yLAID;;EAGL,OAAO,OAAO,GAAG,SACf,OAAO,mBAAmB,WAAW,MAAM,MAAM,KAAK;IAE3D,CACF"}
|
|
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 forwardUrl =\n options?.fromPath !== undefined\n ? rewritePathname(req.url, options.fromPath)\n : req.url;\n const forwardInit: RequestInit = {\n method: req.method,\n headers: new Headers(req.headers)\n };\n if (req.body && req.method !== \"GET\" && req.method !== \"HEAD\") {\n forwardInit.body = await req.arrayBuffer();\n }\n const forwardReq = new Request(forwardUrl, forwardInit);\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,GAAG,EAAE,SACP,MAAM,GAAG,EAAE,OAAO,OAAO;CAQhD,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;EACrC,IAAI,MAAM,OAAA,OAAmB;EAC7B,IAAI,IAAI,KAAK,MAAM,QAAQ;EAE3B,MAAM,eAAe,MAAM,IAAI;EAC/B,MAAM,cAAc,MAAM,IAAI;EAE9B,MAAM,aAAa,iBAAiB,cAAc,SAAS,YAAY;EACvE,IAAI,CAAC,YAAY;EAEjB,IAAI;EACJ,IAAI;GACF,YAAY,mBAAmB,WAAW;EAC5C,QAAQ;GACN;EACF;EAEA,MAAM,iBAAiB,MAAM,MAAM,IAAI,CAAC;EACxC,MAAM,gBACJ,eAAe,SAAS,IAAI,MAAM,eAAe,KAAK,GAAG,IAAI;EAE/D,OAAO;GAAE;GAAY;GAAW;EAAc;CAChD;CAEA,OAAO;AACT;;;;;;AAOA,SAAS,iBACP,SACA,cACe;CACf,IAAI,cAIF,OAHc,aAAa,MACxB,SAAS,qBAAqB,IAAI,MAAM,OAEhC,KAAK;CAElB,OAAO,QACJ,MAAM,GAAG,EACT,KAAK,MAAM,EAAE,OAAO,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AI,MACR,0DAA0D,IAAI,0HAEhE;CAGF,OAAO,IAAI,MACT,CAAC,GACD,EACE,IAAI,SAAS,MAAM;EAQjB,IAAI,qBAAqB,IAAI,GAAG,OAAO,KAAA;EACvC,IAAI,OAAO,SAAS,UAAU,OAAO,KAAA;EAGrC,IAAI,SAAS,SACX,aAAa;GACX,MAAM,IAAI,MACR,wLAIF;EACF;EAEF,OAAO,OAAO,GAAG,SACf,OAAO,mBAAmB,WAAW,MAAM,MAAM,IAAI;CACzD,EACF,CACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-output-truncation-CH-khbZ3.js","names":[],"sources":["../src/chat/tool-output-truncation.ts"],"sourcesContent":["export interface TruncatedToolOutput {\n output: unknown;\n truncated: boolean;\n originalLength: number;\n}\n\nconst DEFAULT_MAX_DEPTH = 8;\nconst TRUNCATED_FLAG = \"__truncated\";\nconst TRUNCATED_CHARS = \"__truncatedChars\";\n\nexport function truncateToolOutput(\n output: unknown,\n maxChars: number\n): TruncatedToolOutput {\n const original = stringifyForLength(output);\n if (original.length <= maxChars) {\n return { output, truncated: false, originalLength: original.length };\n }\n\n return {\n output: truncateValue(output, maxChars, original.length, 0),\n truncated: true,\n originalLength: original.length\n };\n}\n\nexport function truncatedSuffix(originalLength: number): string {\n return `... [truncated ${originalLength} chars]`;\n}\n\nfunction truncateValue(\n value: unknown,\n maxChars: number,\n originalLength: number,\n depth: number\n): unknown {\n if (typeof value === \"string\") {\n return truncateString(value, maxChars, value.length);\n }\n\n if (value === null || typeof value !== \"object\") {\n return value;\n }\n\n if (depth >= DEFAULT_MAX_DEPTH) {\n return `[Nested output omitted ${truncatedSuffix(originalLength)}]`;\n }\n\n if (Array.isArray(value)) {\n return truncateArray(value, maxChars, originalLength, depth);\n }\n\n return truncateObject(\n value as Record<string, unknown>,\n maxChars,\n originalLength,\n depth\n );\n}\n\nfunction truncateArray(\n value: unknown[],\n maxChars: number,\n originalLength: number,\n depth: number\n): unknown[] {\n const childBudget = childMaxChars(maxChars, value.length);\n const result = value.map((item) =>\n truncateValue(item, childBudget, stringifyForLength(item).length, depth + 1)\n );\n\n while (result.length > 1 && stringifyForLength(result).length > maxChars) {\n result.pop();\n }\n\n if (result.length < value.length) {\n result.push(`Array output truncated ${truncatedSuffix(originalLength)}`);\n }\n\n if (stringifyForLength(result).length > maxChars) {\n return compactArrayMarker(maxChars, originalLength);\n }\n\n return result;\n}\n\nfunction truncateObject(\n value: Record<string, unknown>,\n maxChars: number,\n originalLength: number,\n depth: number\n): Record<string, unknown> {\n const entries = Object.entries(value);\n const childBudget = childMaxChars(maxChars, entries.length);\n const result: Record<string, unknown> = {};\n\n for (const [key, entryValue] of entries) {\n result[key] = truncateValue(\n entryValue,\n childBudget,\n stringifyForLength(entryValue).length,\n depth + 1\n );\n }\n\n const resultLength = stringifyForLength(result).length;\n if (resultLength <= maxChars) {\n return result;\n }\n\n shrinkStringFields(result, maxChars);\n const shrunkLength = stringifyForLength(result).length;\n if (shrunkLength > maxChars) {\n result[TRUNCATED_FLAG] = true;\n result[TRUNCATED_CHARS] = resultLength;\n }\n\n if (stringifyForLength(result).length > maxChars) {\n return compactObjectMarker(maxChars, originalLength);\n }\n\n return result;\n}\n\nfunction shrinkStringFields(\n value: Record<string, unknown>,\n maxChars: number\n): void {\n const stringEntries = Object.entries(value)\n .filter((entry): entry is [string, string] => typeof entry[1] === \"string\")\n .sort((a, b) => b[1].length - a[1].length);\n\n for (const [key, str] of stringEntries) {\n if (stringifyForLength(value).length <= maxChars) {\n return;\n }\n\n value[key] = truncateString(\n str,\n Math.max(0, Math.floor(maxChars / 4)),\n str.length\n );\n }\n}\n\nfunction truncateString(\n value: string,\n maxChars: number,\n originalLength: number\n): string {\n if (value.length <= maxChars) {\n return value;\n }\n\n const suffix = truncatedSuffix(originalLength);\n if (maxChars <= suffix.length) {\n return suffix.slice(0, maxChars);\n }\n\n return `${value.slice(0, maxChars - suffix.length)}${suffix}`;\n}\n\nfunction compactObjectMarker(\n maxChars: number,\n originalLength: number\n): Record<string, unknown> {\n const marker = {\n [TRUNCATED_FLAG]: true,\n [TRUNCATED_CHARS]: originalLength,\n note: \"Tool output omitted because it was too large to preserve structurally.\"\n };\n\n if (stringifyForLength(marker).length <= maxChars) {\n return marker;\n }\n\n return {\n [TRUNCATED_FLAG]: true,\n [TRUNCATED_CHARS]: originalLength\n };\n}\n\nfunction compactArrayMarker(\n maxChars: number,\n originalLength: number\n): unknown[] {\n const structuredMarker = compactObjectMarker(maxChars, originalLength);\n if (stringifyForLength([structuredMarker]).length <= maxChars) {\n return [structuredMarker];\n }\n\n const marker = [\n `Array output omitted because it was too large to preserve structurally ${truncatedSuffix(originalLength)}`\n ];\n\n if (stringifyForLength(marker).length <= maxChars) {\n return marker;\n }\n\n return [truncatedSuffix(originalLength).slice(0, maxChars)];\n}\n\nfunction childMaxChars(maxChars: number, childCount: number): number {\n if (childCount <= 1) {\n return maxChars;\n }\n\n return Math.max(80, Math.floor(maxChars / Math.min(childCount, 10)));\n}\n\nfunction stringifyForLength(value: unknown): string {\n try {\n if (typeof value === \"string\") {\n return value;\n }\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n}\n"],"mappings":";AAMA,MAAM,oBAAoB;AAC1B,MAAM,iBAAiB;AACvB,MAAM,kBAAkB;AAExB,SAAgB,mBACd,QACA,UACqB;CACrB,MAAM,WAAW,mBAAmB,
|
|
1
|
+
{"version":3,"file":"tool-output-truncation-CH-khbZ3.js","names":[],"sources":["../src/chat/tool-output-truncation.ts"],"sourcesContent":["export interface TruncatedToolOutput {\n output: unknown;\n truncated: boolean;\n originalLength: number;\n}\n\nconst DEFAULT_MAX_DEPTH = 8;\nconst TRUNCATED_FLAG = \"__truncated\";\nconst TRUNCATED_CHARS = \"__truncatedChars\";\n\nexport function truncateToolOutput(\n output: unknown,\n maxChars: number\n): TruncatedToolOutput {\n const original = stringifyForLength(output);\n if (original.length <= maxChars) {\n return { output, truncated: false, originalLength: original.length };\n }\n\n return {\n output: truncateValue(output, maxChars, original.length, 0),\n truncated: true,\n originalLength: original.length\n };\n}\n\nexport function truncatedSuffix(originalLength: number): string {\n return `... [truncated ${originalLength} chars]`;\n}\n\nfunction truncateValue(\n value: unknown,\n maxChars: number,\n originalLength: number,\n depth: number\n): unknown {\n if (typeof value === \"string\") {\n return truncateString(value, maxChars, value.length);\n }\n\n if (value === null || typeof value !== \"object\") {\n return value;\n }\n\n if (depth >= DEFAULT_MAX_DEPTH) {\n return `[Nested output omitted ${truncatedSuffix(originalLength)}]`;\n }\n\n if (Array.isArray(value)) {\n return truncateArray(value, maxChars, originalLength, depth);\n }\n\n return truncateObject(\n value as Record<string, unknown>,\n maxChars,\n originalLength,\n depth\n );\n}\n\nfunction truncateArray(\n value: unknown[],\n maxChars: number,\n originalLength: number,\n depth: number\n): unknown[] {\n const childBudget = childMaxChars(maxChars, value.length);\n const result = value.map((item) =>\n truncateValue(item, childBudget, stringifyForLength(item).length, depth + 1)\n );\n\n while (result.length > 1 && stringifyForLength(result).length > maxChars) {\n result.pop();\n }\n\n if (result.length < value.length) {\n result.push(`Array output truncated ${truncatedSuffix(originalLength)}`);\n }\n\n if (stringifyForLength(result).length > maxChars) {\n return compactArrayMarker(maxChars, originalLength);\n }\n\n return result;\n}\n\nfunction truncateObject(\n value: Record<string, unknown>,\n maxChars: number,\n originalLength: number,\n depth: number\n): Record<string, unknown> {\n const entries = Object.entries(value);\n const childBudget = childMaxChars(maxChars, entries.length);\n const result: Record<string, unknown> = {};\n\n for (const [key, entryValue] of entries) {\n result[key] = truncateValue(\n entryValue,\n childBudget,\n stringifyForLength(entryValue).length,\n depth + 1\n );\n }\n\n const resultLength = stringifyForLength(result).length;\n if (resultLength <= maxChars) {\n return result;\n }\n\n shrinkStringFields(result, maxChars);\n const shrunkLength = stringifyForLength(result).length;\n if (shrunkLength > maxChars) {\n result[TRUNCATED_FLAG] = true;\n result[TRUNCATED_CHARS] = resultLength;\n }\n\n if (stringifyForLength(result).length > maxChars) {\n return compactObjectMarker(maxChars, originalLength);\n }\n\n return result;\n}\n\nfunction shrinkStringFields(\n value: Record<string, unknown>,\n maxChars: number\n): void {\n const stringEntries = Object.entries(value)\n .filter((entry): entry is [string, string] => typeof entry[1] === \"string\")\n .sort((a, b) => b[1].length - a[1].length);\n\n for (const [key, str] of stringEntries) {\n if (stringifyForLength(value).length <= maxChars) {\n return;\n }\n\n value[key] = truncateString(\n str,\n Math.max(0, Math.floor(maxChars / 4)),\n str.length\n );\n }\n}\n\nfunction truncateString(\n value: string,\n maxChars: number,\n originalLength: number\n): string {\n if (value.length <= maxChars) {\n return value;\n }\n\n const suffix = truncatedSuffix(originalLength);\n if (maxChars <= suffix.length) {\n return suffix.slice(0, maxChars);\n }\n\n return `${value.slice(0, maxChars - suffix.length)}${suffix}`;\n}\n\nfunction compactObjectMarker(\n maxChars: number,\n originalLength: number\n): Record<string, unknown> {\n const marker = {\n [TRUNCATED_FLAG]: true,\n [TRUNCATED_CHARS]: originalLength,\n note: \"Tool output omitted because it was too large to preserve structurally.\"\n };\n\n if (stringifyForLength(marker).length <= maxChars) {\n return marker;\n }\n\n return {\n [TRUNCATED_FLAG]: true,\n [TRUNCATED_CHARS]: originalLength\n };\n}\n\nfunction compactArrayMarker(\n maxChars: number,\n originalLength: number\n): unknown[] {\n const structuredMarker = compactObjectMarker(maxChars, originalLength);\n if (stringifyForLength([structuredMarker]).length <= maxChars) {\n return [structuredMarker];\n }\n\n const marker = [\n `Array output omitted because it was too large to preserve structurally ${truncatedSuffix(originalLength)}`\n ];\n\n if (stringifyForLength(marker).length <= maxChars) {\n return marker;\n }\n\n return [truncatedSuffix(originalLength).slice(0, maxChars)];\n}\n\nfunction childMaxChars(maxChars: number, childCount: number): number {\n if (childCount <= 1) {\n return maxChars;\n }\n\n return Math.max(80, Math.floor(maxChars / Math.min(childCount, 10)));\n}\n\nfunction stringifyForLength(value: unknown): string {\n try {\n if (typeof value === \"string\") {\n return value;\n }\n return JSON.stringify(value)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GT,OAAO;GACJ,iBAAiB;GACjB,kBAAkB;CACrB;AACF;AAEA,SAAS,mBACP,UACA,gBACW;CACX,MAAM,mBAAmB,oBAAoB,UAAU,cAAc;CACrE,IAAI,mBAAmB,CAAC,gBAAgB,CAAC,EAAE,UAAU,UACnD,OAAO,CAAC,gBAAgB;CAG1B,MAAM,SAAS,CACb,0EAA0E,gBAAgB,cAAc,GAC1G;CAEA,IAAI,mBAAmB,MAAM,EAAE,UAAU,UACvC,OAAO;CAGT,OAAO,CAAC,gBAAgB,cAAc,EAAE,MAAM,GAAG,QAAQ,CAAC;AAC5D;AAEA,SAAS,cAAc,UAAkB,YAA4B;CACnE,IAAI,cAAc,GAChB,OAAO;CAGT,OAAO,KAAK,IAAI,IAAI,KAAK,MAAM,WAAW,KAAK,IAAI,YAAY,EAAE,CAAC,CAAC;AACrE;AAEA,SAAS,mBAAmB,OAAwB;CAClD,IAAI;EACF,IAAI,OAAO,UAAU,UACnB,OAAO;EAET,OAAO,KAAK,UAAU,KAAK,KAAK,OAAO,KAAK;CAC9C,QAAQ;EACN,OAAO,OAAO,KAAK;CACrB;AACF"}
|
package/dist/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","names":[],"sources":["../src/types.ts"],"sourcesContent":["/**\n * Enum for message types to improve type safety and maintainability\n */\nexport enum MessageType {\n CF_AGENT_MCP_SERVERS = \"cf_agent_mcp_servers\",\n CF_MCP_AGENT_EVENT = \"cf_mcp_agent_event\",\n CF_AGENT_STATE = \"cf_agent_state\",\n CF_AGENT_STATE_ERROR = \"cf_agent_state_error\",\n CF_AGENT_IDENTITY = \"cf_agent_identity\",\n CF_AGENT_SESSION = \"cf_agent_session\",\n CF_AGENT_SESSION_ERROR = \"cf_agent_session_error\",\n RPC = \"rpc\"\n}\n"],"mappings":";;;;AAGA,IAAY,cAAL,yBAAA,aAAA;CACL,YAAA,0BAAA;CACA,YAAA,wBAAA;CACA,YAAA,oBAAA;CACA,YAAA,0BAAA;CACA,YAAA,uBAAA;CACA,YAAA,sBAAA;CACA,YAAA,4BAAA;CACA,YAAA,SAAA;;
|
|
1
|
+
{"version":3,"file":"types.js","names":[],"sources":["../src/types.ts"],"sourcesContent":["/**\n * Enum for message types to improve type safety and maintainability\n */\nexport enum MessageType {\n CF_AGENT_MCP_SERVERS = \"cf_agent_mcp_servers\",\n CF_MCP_AGENT_EVENT = \"cf_mcp_agent_event\",\n CF_AGENT_STATE = \"cf_agent_state\",\n CF_AGENT_STATE_ERROR = \"cf_agent_state_error\",\n CF_AGENT_IDENTITY = \"cf_agent_identity\",\n CF_AGENT_SESSION = \"cf_agent_session\",\n CF_AGENT_SESSION_ERROR = \"cf_agent_session_error\",\n RPC = \"rpc\"\n}\n"],"mappings":";;;;AAGA,IAAY,cAAL,yBAAA,aAAA;CACL,YAAA,0BAAA;CACA,YAAA,wBAAA;CACA,YAAA,oBAAA;CACA,YAAA,0BAAA;CACA,YAAA,uBAAA;CACA,YAAA,sBAAA;CACA,YAAA,4BAAA;CACA,YAAA,SAAA;;AACF,EAAA,CAAA,CAAA"}
|
package/dist/utils.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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;
|
|
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;AACF,CAAC;;;;;;;;AASD,SAAgB,qBAAqB,MAAgC;CACnE,OAAO,OAAO,SAAS,YAAY,uBAAuB,IAAI,IAAI;AACpE;;;;;;AAOA,SAAgB,qBAAqB,KAAqB;CAExD,IAAI,QAAQ,IAAI,YAAY,KAAK,QAAQ,IAAI,YAAY,GACvD,OAAO,IAAI,YAAY,EAAE,QAAQ,MAAM,GAAG;CAI5C,IAAI,aAAa,IAAI,QACnB,WACC,WAAW,IAAI,OAAO,YAAY,GACrC;CACA,aAAa,WAAW,WAAW,GAAG,IAAI,WAAW,MAAM,CAAC,IAAI;CAEhE,OAAO,WAAW,QAAQ,MAAM,GAAG,EAAE,QAAQ,MAAM,EAAE;AACvD"}
|
package/dist/vite.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vite.js","names":[],"sources":["../src/vite.ts"],"sourcesContent":["import babel from \"@rolldown/plugin-babel\";\nimport type { Plugin } from \"vite\";\n\n/**\n * Vite plugin for Agents SDK projects.\n *\n * Currently handles TC39 decorator transforms (Oxc doesn't support them yet,\n * oxc#9170) so `@callable()` works at runtime. Will grow to cover other\n * Agents-specific build concerns as needed.\n */\nexport default function agents(): Plugin {\n return babel({\n presets: [\n {\n preset: () => ({\n plugins: [\n [\"@babel/plugin-proposal-decorators\", { version: \"2023-11\" }]\n ]\n }),\n rolldown: { filter: { code: \"@\" } }\n }\n ]\n }) as unknown as Plugin;\n}\n"],"mappings":";;;;;;;;;AAUA,SAAwB,SAAiB;CACvC,OAAO,MAAM,EACX,SAAS,CACP;EACE,eAAe,EACb,SAAS,CACP,CAAC,qCAAqC,EAAE,SAAS,
|
|
1
|
+
{"version":3,"file":"vite.js","names":[],"sources":["../src/vite.ts"],"sourcesContent":["import babel from \"@rolldown/plugin-babel\";\nimport type { Plugin } from \"vite\";\n\n/**\n * Vite plugin for Agents SDK projects.\n *\n * Currently handles TC39 decorator transforms (Oxc doesn't support them yet,\n * oxc#9170) so `@callable()` works at runtime. Will grow to cover other\n * Agents-specific build concerns as needed.\n */\nexport default function agents(): Plugin {\n return babel({\n presets: [\n {\n preset: () => ({\n plugins: [\n [\"@babel/plugin-proposal-decorators\", { version: \"2023-11\" }]\n ]\n }),\n rolldown: { filter: { code: \"@\" } }\n }\n ]\n }) as unknown as Plugin;\n}\n"],"mappings":";;;;;;;;;AAUA,SAAwB,SAAiB;CACvC,OAAO,MAAM,EACX,SAAS,CACP;EACE,eAAe,EACb,SAAS,CACP,CAAC,qCAAqC,EAAE,SAAS,UAAU,CAAC,CAC9D,EACF;EACA,UAAU,EAAE,QAAQ,EAAE,MAAM,IAAI,EAAE;CACpC,CACF,EACF,CAAC;AACH"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workflow-types.js","names":[],"sources":["../src/workflow-types.ts"],"sourcesContent":["/**\n * Workflow integration types for Agents\n *\n * These types provide seamless integration between Cloudflare Agents\n * and Cloudflare Workflows for durable, multi-step background processing.\n *\n * Note: This file is kept separate from workflows.ts to avoid circular dependencies.\n * Both index.ts (Agent class) and workflows.ts (AgentWorkflow class) import from here.\n */\n\nimport type {\n WorkflowEvent,\n WorkflowStep,\n WorkflowSleepDuration\n} from \"cloudflare:workers\";\n\n/**\n * Type alias for WorkflowEvent in AgentWorkflow context.\n * Identical to WorkflowEvent - provided for naming consistency with AgentWorkflowStep.\n */\nexport type AgentWorkflowEvent<Params = unknown> = WorkflowEvent<Params>;\n\n/**\n * Extended WorkflowStep with durable Agent communication methods.\n * All added methods on this interface are durable - they're idempotent and won't\n * repeat on workflow retry.\n */\nexport interface AgentWorkflowStep extends WorkflowStep {\n /**\n * Report successful completion to the Agent (durable).\n * Triggers onWorkflowComplete() on the Agent.\n * @param result - Optional result data\n */\n reportComplete<T = unknown>(result?: T): Promise<void>;\n\n /**\n * Report an error to the Agent (durable).\n * Triggers onWorkflowError() on the Agent.\n * @param error - Error or error message\n */\n reportError(error: Error | string): Promise<void>;\n\n /**\n * Send a custom event to the Agent (durable).\n * Triggers onWorkflowEvent() on the Agent.\n * @param event - Custom event payload\n */\n sendEvent<T = unknown>(event: T): Promise<void>;\n\n /**\n * Update the Agent's state entirely (durable).\n * This will replace the Agent's state and broadcast to all connected clients.\n * @param state - New state to set\n */\n updateAgentState(state: unknown): Promise<void>;\n\n /**\n * Merge partial state into the Agent's existing state (durable).\n * Performs a shallow merge and broadcasts to all connected clients.\n * @param partialState - Partial state to merge\n */\n mergeAgentState(partialState: Record<string, unknown>): Promise<void>;\n\n /**\n * Reset the Agent's state to its initialState (durable).\n * Broadcasts the reset state to all connected clients.\n */\n resetAgentState(): Promise<void>;\n}\n\n/**\n * Internal parameters injected by runWorkflow() to identify the originating Agent\n */\nexport type AgentWorkflowInternalParams = {\n /** Name/ID of the Agent that started this workflow */\n __agentName: string;\n /** Environment binding name for the Agent's namespace */\n __agentBinding: string;\n /** Workflow binding name (for callbacks) */\n __workflowName: string;\n};\n\n/**\n * Combined workflow params: user params + internal agent params\n */\nexport type AgentWorkflowParams<T = unknown> = T & AgentWorkflowInternalParams;\n\n/**\n * Workflow callback types for Agent-Workflow communication\n */\nexport type WorkflowCallbackType = \"progress\" | \"complete\" | \"error\" | \"event\";\n\n/**\n * Base callback structure sent from Workflow to Agent\n */\nexport type WorkflowCallbackBase = {\n /** Workflow binding name */\n workflowName: string;\n /** ID of the workflow instance */\n workflowId: string;\n /** Type of callback */\n type: WorkflowCallbackType;\n /** Timestamp when callback was sent */\n timestamp: number;\n};\n\n/**\n * Default progress type - covers common use cases.\n * Developers can define their own progress type for domain-specific needs.\n */\nexport type DefaultProgress = {\n /** Current step name */\n step?: string;\n /** Step/overall status */\n status?: \"pending\" | \"running\" | \"complete\" | \"error\";\n /** Human-readable message */\n message?: string;\n /** Progress percentage (0-1) */\n percent?: number;\n /** Allow additional custom fields */\n [key: string]: unknown;\n};\n\n/**\n * Progress callback - reports workflow progress with typed payload\n */\nexport type WorkflowProgressCallback<P = DefaultProgress> =\n WorkflowCallbackBase & {\n type: \"progress\";\n /** Typed progress data */\n progress: P;\n };\n\n/**\n * Complete callback - workflow finished successfully\n */\nexport type WorkflowCompleteCallback = WorkflowCallbackBase & {\n type: \"complete\";\n /** Result of the workflow */\n result?: unknown;\n};\n\n/**\n * Error callback - workflow encountered an error\n */\nexport type WorkflowErrorCallback = WorkflowCallbackBase & {\n type: \"error\";\n /** Error message */\n error: string;\n};\n\n/**\n * Event callback - custom event from workflow\n */\nexport type WorkflowEventCallback = WorkflowCallbackBase & {\n type: \"event\";\n /** Custom event payload */\n event: unknown;\n};\n\n/**\n * Union of all callback types\n */\nexport type WorkflowCallback<P = DefaultProgress> =\n | WorkflowProgressCallback<P>\n | WorkflowCompleteCallback\n | WorkflowErrorCallback\n | WorkflowEventCallback;\n\n/**\n * Workflow status values - derived from Cloudflare's InstanceStatus\n */\nexport type WorkflowStatus = InstanceStatus[\"status\"];\n\n/**\n * Row structure for cf_agents_workflows tracking table\n */\nexport type WorkflowTrackingRow = {\n /** Internal row ID (UUID) */\n id: string;\n /** Cloudflare Workflow instance ID */\n workflow_id: string;\n /** Workflow binding name */\n workflow_name: string;\n /** Current workflow status */\n status: WorkflowStatus;\n /** JSON-serialized metadata for querying */\n metadata: string | null;\n /** Error name if workflow failed */\n error_name: string | null;\n /** Error message if workflow failed */\n error_message: string | null;\n /** Unix timestamp when workflow was created */\n created_at: number;\n /** Unix timestamp when workflow was last updated */\n updated_at: number;\n /** Unix timestamp when workflow completed (null if not complete) */\n completed_at: number | null;\n};\n\n/**\n * Options for runWorkflow()\n */\nexport type RunWorkflowOptions = {\n /** Custom workflow instance ID (auto-generated if not provided) */\n id?: string;\n /** Optional metadata for querying (stored as JSON) */\n metadata?: Record<string, unknown>;\n /** Agent binding name (auto-detected from class name if not provided) */\n agentBinding?: string;\n};\n\n/**\n * Event payload for sendWorkflowEvent()\n */\nexport type WorkflowEventPayload = {\n /** Event type name */\n type: string;\n /** Event payload data */\n payload: unknown;\n};\n\n/**\n * Parsed workflow tracking info returned by getWorkflow()\n */\nexport type WorkflowInfo = {\n /** Internal row ID */\n id: string;\n /** Cloudflare Workflow instance ID */\n workflowId: string;\n /** Workflow binding name */\n workflowName: string;\n /** Current workflow status */\n status: WorkflowStatus;\n /** Metadata (parsed from JSON) */\n metadata: Record<string, unknown> | null;\n /** Error info if workflow failed */\n error: { name: string; message: string } | null;\n /** When workflow was created */\n createdAt: Date;\n /** When workflow was last updated */\n updatedAt: Date;\n /** When workflow completed (null if not complete) */\n completedAt: Date | null;\n};\n\n/**\n * Criteria for querying tracked workflows\n */\nexport type WorkflowQueryCriteria = {\n /** Filter by status */\n status?: WorkflowStatus | WorkflowStatus[];\n /** Filter by workflow binding name */\n workflowName?: string;\n /** Filter by metadata key-value pairs (exact match) */\n metadata?: Record<string, string | number | boolean>;\n /** Limit number of results (default 50, max 100) */\n limit?: number;\n /** Order by created_at */\n orderBy?: \"asc\" | \"desc\";\n /** Cursor for pagination (from previous WorkflowPage.nextCursor) */\n cursor?: string;\n};\n\n/**\n * Paginated result from getWorkflows()\n */\nexport type WorkflowPage = {\n /** Workflows for this page */\n workflows: WorkflowInfo[];\n /** Total count of workflows matching the criteria (ignoring pagination) */\n total: number;\n /** Cursor for next page, or null if no more pages */\n nextCursor: string | null;\n};\n\n/**\n * Standard approval event payload used by approveWorkflow/rejectWorkflow\n */\nexport type ApprovalEventPayload = {\n /** Whether the workflow was approved */\n approved: boolean;\n /** Optional reason for approval/rejection */\n reason?: string;\n /** Optional additional metadata */\n metadata?: Record<string, unknown>;\n};\n\n/**\n * Options for waitForApproval()\n */\nexport type WaitForApprovalOptions = {\n /** Step name for waitForEvent (default: \"wait-for-approval\") */\n stepName?: string;\n /** Timeout duration (e.g., \"7 days\") */\n timeout?: WorkflowSleepDuration;\n /** Event type to wait for (default: \"approval\") */\n eventType?: string;\n};\n\n/**\n * Error thrown when a workflow is rejected via rejectWorkflow()\n */\nexport class WorkflowRejectedError extends Error {\n constructor(\n public readonly reason?: string,\n public readonly workflowId?: string\n ) {\n super(reason ? `Workflow rejected: ${reason}` : \"Workflow rejected\");\n this.name = \"WorkflowRejectedError\";\n }\n}\n"],"mappings":";;;;AA+SA,IAAa,wBAAb,cAA2C,MAAM;CAC/C,YACE,QACA,YACA;EACA,MAAM,SAAS,sBAAsB,WAAW,
|
|
1
|
+
{"version":3,"file":"workflow-types.js","names":[],"sources":["../src/workflow-types.ts"],"sourcesContent":["/**\n * Workflow integration types for Agents\n *\n * These types provide seamless integration between Cloudflare Agents\n * and Cloudflare Workflows for durable, multi-step background processing.\n *\n * Note: This file is kept separate from workflows.ts to avoid circular dependencies.\n * Both index.ts (Agent class) and workflows.ts (AgentWorkflow class) import from here.\n */\n\nimport type {\n WorkflowEvent,\n WorkflowStep,\n WorkflowSleepDuration\n} from \"cloudflare:workers\";\n\n/**\n * Type alias for WorkflowEvent in AgentWorkflow context.\n * Identical to WorkflowEvent - provided for naming consistency with AgentWorkflowStep.\n */\nexport type AgentWorkflowEvent<Params = unknown> = WorkflowEvent<Params>;\n\n/**\n * Extended WorkflowStep with durable Agent communication methods.\n * All added methods on this interface are durable - they're idempotent and won't\n * repeat on workflow retry.\n */\nexport interface AgentWorkflowStep extends WorkflowStep {\n /**\n * Report successful completion to the Agent (durable).\n * Triggers onWorkflowComplete() on the Agent.\n * @param result - Optional result data\n */\n reportComplete<T = unknown>(result?: T): Promise<void>;\n\n /**\n * Report an error to the Agent (durable).\n * Triggers onWorkflowError() on the Agent.\n * @param error - Error or error message\n */\n reportError(error: Error | string): Promise<void>;\n\n /**\n * Send a custom event to the Agent (durable).\n * Triggers onWorkflowEvent() on the Agent.\n * @param event - Custom event payload\n */\n sendEvent<T = unknown>(event: T): Promise<void>;\n\n /**\n * Update the Agent's state entirely (durable).\n * This will replace the Agent's state and broadcast to all connected clients.\n * @param state - New state to set\n */\n updateAgentState(state: unknown): Promise<void>;\n\n /**\n * Merge partial state into the Agent's existing state (durable).\n * Performs a shallow merge and broadcasts to all connected clients.\n * @param partialState - Partial state to merge\n */\n mergeAgentState(partialState: Record<string, unknown>): Promise<void>;\n\n /**\n * Reset the Agent's state to its initialState (durable).\n * Broadcasts the reset state to all connected clients.\n */\n resetAgentState(): Promise<void>;\n}\n\n/**\n * Internal parameters injected by runWorkflow() to identify the originating Agent\n */\nexport type AgentWorkflowInternalParams = {\n /** Name/ID of the Agent that started this workflow */\n __agentName: string;\n /** Environment binding name for the Agent's namespace */\n __agentBinding: string;\n /** Workflow binding name (for callbacks) */\n __workflowName: string;\n};\n\n/**\n * Combined workflow params: user params + internal agent params\n */\nexport type AgentWorkflowParams<T = unknown> = T & AgentWorkflowInternalParams;\n\n/**\n * Workflow callback types for Agent-Workflow communication\n */\nexport type WorkflowCallbackType = \"progress\" | \"complete\" | \"error\" | \"event\";\n\n/**\n * Base callback structure sent from Workflow to Agent\n */\nexport type WorkflowCallbackBase = {\n /** Workflow binding name */\n workflowName: string;\n /** ID of the workflow instance */\n workflowId: string;\n /** Type of callback */\n type: WorkflowCallbackType;\n /** Timestamp when callback was sent */\n timestamp: number;\n};\n\n/**\n * Default progress type - covers common use cases.\n * Developers can define their own progress type for domain-specific needs.\n */\nexport type DefaultProgress = {\n /** Current step name */\n step?: string;\n /** Step/overall status */\n status?: \"pending\" | \"running\" | \"complete\" | \"error\";\n /** Human-readable message */\n message?: string;\n /** Progress percentage (0-1) */\n percent?: number;\n /** Allow additional custom fields */\n [key: string]: unknown;\n};\n\n/**\n * Progress callback - reports workflow progress with typed payload\n */\nexport type WorkflowProgressCallback<P = DefaultProgress> =\n WorkflowCallbackBase & {\n type: \"progress\";\n /** Typed progress data */\n progress: P;\n };\n\n/**\n * Complete callback - workflow finished successfully\n */\nexport type WorkflowCompleteCallback = WorkflowCallbackBase & {\n type: \"complete\";\n /** Result of the workflow */\n result?: unknown;\n};\n\n/**\n * Error callback - workflow encountered an error\n */\nexport type WorkflowErrorCallback = WorkflowCallbackBase & {\n type: \"error\";\n /** Error message */\n error: string;\n};\n\n/**\n * Event callback - custom event from workflow\n */\nexport type WorkflowEventCallback = WorkflowCallbackBase & {\n type: \"event\";\n /** Custom event payload */\n event: unknown;\n};\n\n/**\n * Union of all callback types\n */\nexport type WorkflowCallback<P = DefaultProgress> =\n | WorkflowProgressCallback<P>\n | WorkflowCompleteCallback\n | WorkflowErrorCallback\n | WorkflowEventCallback;\n\n/**\n * Workflow status values - derived from Cloudflare's InstanceStatus\n */\nexport type WorkflowStatus = InstanceStatus[\"status\"];\n\n/**\n * Row structure for cf_agents_workflows tracking table\n */\nexport type WorkflowTrackingRow = {\n /** Internal row ID (UUID) */\n id: string;\n /** Cloudflare Workflow instance ID */\n workflow_id: string;\n /** Workflow binding name */\n workflow_name: string;\n /** Current workflow status */\n status: WorkflowStatus;\n /** JSON-serialized metadata for querying */\n metadata: string | null;\n /** Error name if workflow failed */\n error_name: string | null;\n /** Error message if workflow failed */\n error_message: string | null;\n /** Unix timestamp when workflow was created */\n created_at: number;\n /** Unix timestamp when workflow was last updated */\n updated_at: number;\n /** Unix timestamp when workflow completed (null if not complete) */\n completed_at: number | null;\n};\n\n/**\n * Options for runWorkflow()\n */\nexport type RunWorkflowOptions = {\n /** Custom workflow instance ID (auto-generated if not provided) */\n id?: string;\n /** Optional metadata for querying (stored as JSON) */\n metadata?: Record<string, unknown>;\n /** Agent binding name (auto-detected from class name if not provided) */\n agentBinding?: string;\n};\n\n/**\n * Event payload for sendWorkflowEvent()\n */\nexport type WorkflowEventPayload = {\n /** Event type name */\n type: string;\n /** Event payload data */\n payload: unknown;\n};\n\n/**\n * Parsed workflow tracking info returned by getWorkflow()\n */\nexport type WorkflowInfo = {\n /** Internal row ID */\n id: string;\n /** Cloudflare Workflow instance ID */\n workflowId: string;\n /** Workflow binding name */\n workflowName: string;\n /** Current workflow status */\n status: WorkflowStatus;\n /** Metadata (parsed from JSON) */\n metadata: Record<string, unknown> | null;\n /** Error info if workflow failed */\n error: { name: string; message: string } | null;\n /** When workflow was created */\n createdAt: Date;\n /** When workflow was last updated */\n updatedAt: Date;\n /** When workflow completed (null if not complete) */\n completedAt: Date | null;\n};\n\n/**\n * Criteria for querying tracked workflows\n */\nexport type WorkflowQueryCriteria = {\n /** Filter by status */\n status?: WorkflowStatus | WorkflowStatus[];\n /** Filter by workflow binding name */\n workflowName?: string;\n /** Filter by metadata key-value pairs (exact match) */\n metadata?: Record<string, string | number | boolean>;\n /** Limit number of results (default 50, max 100) */\n limit?: number;\n /** Order by created_at */\n orderBy?: \"asc\" | \"desc\";\n /** Cursor for pagination (from previous WorkflowPage.nextCursor) */\n cursor?: string;\n};\n\n/**\n * Paginated result from getWorkflows()\n */\nexport type WorkflowPage = {\n /** Workflows for this page */\n workflows: WorkflowInfo[];\n /** Total count of workflows matching the criteria (ignoring pagination) */\n total: number;\n /** Cursor for next page, or null if no more pages */\n nextCursor: string | null;\n};\n\n/**\n * Standard approval event payload used by approveWorkflow/rejectWorkflow\n */\nexport type ApprovalEventPayload = {\n /** Whether the workflow was approved */\n approved: boolean;\n /** Optional reason for approval/rejection */\n reason?: string;\n /** Optional additional metadata */\n metadata?: Record<string, unknown>;\n};\n\n/**\n * Options for waitForApproval()\n */\nexport type WaitForApprovalOptions = {\n /** Step name for waitForEvent (default: \"wait-for-approval\") */\n stepName?: string;\n /** Timeout duration (e.g., \"7 days\") */\n timeout?: WorkflowSleepDuration;\n /** Event type to wait for (default: \"approval\") */\n eventType?: string;\n};\n\n/**\n * Error thrown when a workflow is rejected via rejectWorkflow()\n */\nexport class WorkflowRejectedError extends Error {\n constructor(\n public readonly reason?: string,\n public readonly workflowId?: string\n ) {\n super(reason ? `Workflow rejected: ${reason}` : \"Workflow rejected\");\n this.name = \"WorkflowRejectedError\";\n }\n}\n"],"mappings":";;;;AA+SA,IAAa,wBAAb,cAA2C,MAAM;CAC/C,YACE,QACA,YACA;EACA,MAAM,SAAS,sBAAsB,WAAW,mBAAmB;EAHnD,KAAA,SAAA;EACA,KAAA,aAAA;EAGhB,KAAK,OAAO;CACd;AACF"}
|
package/dist/workflows.d.ts
CHANGED
package/dist/workflows.js.map
CHANGED
|
@@ -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 \"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AAI,MACR,0EACD;EAEH,OAAO,KAAK;;;;;CAMd,IAAI,aAAqB;EACvB,OAAO,KAAK;;;;;CAMd,IAAI,eAAuB;EACzB,OAAO,KAAK;;;;;;;;;CAUd,MAAc,iBAAiB,KAA6B;EAC1D,IAAI,KAAK,gBACP;EAEF,KAAK,iBAAiB;EACtB,MAAM,eAAe,eAAe,QAAQ,IAAI,UAAU,OAAO,IAAI;EACrE,IAAI;GACF,MAAM,KAAK,YAAY;IACrB,cAAc,KAAK;IACnB,YAAY,KAAK;IACjB,MAAM;IACN,OAAO;IACP,WAAW,KAAK,KAAK;IACtB,CAAC;WACK,YAAY;;;;;;;CAUvB,MAAgB,YAAY,UAA2C;EACrE,MAAM,KAAK,MAAM,yBAAyB,SAAS;;;;;;;;;;;;;;;;;;CAmBrD,MAAgB,eAAe,UAAuC;EACpE,MAAM,KAAK,YAAY;GACrB,cAAc,KAAK;GACnB,YAAY,KAAK;GACjB,MAAM;GACI;GACV,WAAW,KAAK,KAAK;GACtB,CAAC;;;;;;;;CASJ,mBAA6B,SAAwB;EACnD,KAAK,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;EAOtB,IAAI,CAAC,QAAQ,UAAU;GACrB,MAAM,SAAS,QAAQ;GACvB,MAAM,KAAK,YAAY,UAAU,oBAAoB;GACrD,MAAM,IAAI,sBAAsB,QAAQ,KAAK,YAAY;;EAI3D,OAAO,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,QAAgB;;;;;;;;;AAU9C,IAAa,gBAAb,cAKU,mBAAqD;CA8B7D,YAAY,KAAuB,KAAU;EAC3C,MAAM,KAAK,GAAG;EAVhB,KAAQ,oBAAoB;EAO5B,KAAQ,iBAAiB;EAKvB,MAAM,QAAQ,OAAO,eAAe,IAAI;EAOxC,IAAI,OAAO,OAAO,OAAO,KAAK,KAAK,CAAC,kBAAkB,IAAI,KAAK,GAAG;GAChE,MAAM,cAAc,MAAM;GAO1B,MAAM,MAAM,eAEV,OACA,MACA;IAGA,IAAI,CAAC,KAAK,mBAAmB;KAC3B,MAAM,EAAE,aAAa,gBAAgB,gBAAgB,GAAG,eACtD,MAAM;KAGR,MAAM,KAAK,WACT,aACA,gBACA,gBACA,MAAM,UACR;KACA,KAAK,oBAAoB;KAGzB,MAAM,eAAe;MACnB,GAAG;MACH,SAAS;KACX;KAEA,MAAM,cAAc,KAAK,UAAU,IAAI;KAEvC,IAAI;MACF,OAAO,MAAM,YAAY,KAAK,MAAM,cAAc,WAAW;KAC/D,SAAS,KAAK;MACZ,MAAM,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,KAAK,MAAM,oBAAoB,OAAO;CACxC;;;;;;;;;;;;;;;CAgBA,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;EACF,CAAC,GAGqB;EAOtB,IAAI,CAAC,QAAQ,UAAU;GACrB,MAAM,SAAS,QAAQ;GACvB,MAAM,KAAK,YAAY,UAAU,mBAAmB;GACpD,MAAM,IAAI,sBAAsB,QAAQ,KAAK,WAAW;EAC1D;EAGA,OAAO,QAAQ;CACjB;AACF"}
|
package/package.json
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
"durable objects"
|
|
10
10
|
],
|
|
11
11
|
"type": "module",
|
|
12
|
-
"version": "0.
|
|
12
|
+
"version": "0.13.1",
|
|
13
13
|
"license": "MIT",
|
|
14
14
|
"repository": {
|
|
15
15
|
"directory": "packages/agents",
|
|
@@ -36,14 +36,14 @@
|
|
|
36
36
|
"yargs": "^18.0.0"
|
|
37
37
|
},
|
|
38
38
|
"devDependencies": {
|
|
39
|
-
"@ai-sdk/react": "^3.0.
|
|
40
|
-
"@tanstack/ai": "^0.
|
|
39
|
+
"@ai-sdk/react": "^3.0.187",
|
|
40
|
+
"@tanstack/ai": "^0.18.0",
|
|
41
41
|
"@types/react": "^19.2.14",
|
|
42
42
|
"@types/yargs": "^17.0.35",
|
|
43
43
|
"@vitest/browser-playwright": "^4.1.6",
|
|
44
|
-
"@x402/core": "^2.
|
|
45
|
-
"@x402/evm": "^2.
|
|
46
|
-
"ai": "^6.0.
|
|
44
|
+
"@x402/core": "^2.12.0",
|
|
45
|
+
"@x402/evm": "^2.12.0",
|
|
46
|
+
"ai": "^6.0.185",
|
|
47
47
|
"react": "^19.2.6",
|
|
48
48
|
"vitest-browser-react": "^2.2.0",
|
|
49
49
|
"zod": "^4.4.3"
|