agents 0.14.1 → 0.14.3
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/LICENSE +21 -0
- package/dist/{agent-tool-types-BAJWu8s4.d.ts → agent-tool-types-V25Z_HcX.d.ts} +258 -115
- package/dist/agent-tool-types.d.ts +13 -11
- package/dist/{agent-tools-DYrkT-Kx.js → agent-tools-3zLG7MgA.js} +4 -2
- package/dist/{agent-tools-DYrkT-Kx.js.map → agent-tools-3zLG7MgA.js.map} +1 -1
- package/dist/{agent-tools-0R6KEert.d.ts → agent-tools-C-9s151X.d.ts} +2 -2
- package/dist/agent-tools.d.ts +13 -11
- package/dist/agent-tools.js +8 -3
- package/dist/agent-tools.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 +133 -11
- package/dist/chat/index.js +118 -29
- package/dist/chat/index.js.map +1 -1
- package/dist/chat-sdk/index.d.ts +4 -4
- package/dist/chat-sdk/index.js.map +1 -1
- package/dist/{classPrivateFieldGet2-D_obpP6O.js → classPrivateFieldGet2-Beqsfu2Z.js} +5 -5
- package/dist/{classPrivateMethodInitSpec-10iTYB7F.js → classPrivateMethodInitSpec-B5ko1s2R.js} +2 -2
- package/dist/cli/index.js.map +1 -1
- package/dist/client-FUizKzj2.js.map +1 -1
- package/dist/client.d.ts +1 -1
- package/dist/compaction-helpers-iiKMr2TQ.js.map +1 -1
- package/dist/email.js.map +1 -1
- package/dist/experimental/memory/session/index.js.map +1 -1
- package/dist/experimental/webmcp.js.map +1 -1
- package/dist/{index-RJ4OxMOe.d.ts → index-CPe1OtI0.d.ts} +17 -1
- package/dist/index.d.ts +66 -64
- package/dist/index.js +263 -76
- package/dist/index.js.map +1 -1
- package/dist/mcp/client.d.ts +14 -14
- package/dist/mcp/do-oauth-client-provider.js.map +1 -1
- package/dist/mcp/index.d.ts +30 -30
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/x402.js.map +1 -1
- package/dist/observability/index.d.ts +1 -1
- package/dist/observability/index.js.map +1 -1
- package/dist/react.d.ts +3 -3
- package/dist/react.js +1 -1
- package/dist/react.js.map +1 -1
- package/dist/schedule.js.map +1 -1
- package/dist/serializable.d.ts +1 -1
- package/dist/{shared-BIpUk4G5.js → shared-wyII629d.js} +3 -3
- package/dist/{shared-BIpUk4G5.js.map → shared-wyII629d.js.map} +1 -1
- package/dist/skills/index.js +4 -4
- package/dist/skills/index.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-CNnnGZQ3.js.map +1 -1
- package/dist/utils.js.map +1 -1
- package/dist/vite.d.ts +15 -4
- package/dist/vite.js +37 -7
- package/dist/vite.js.map +1 -1
- package/dist/workflows.d.ts +10 -2
- package/dist/workflows.js +48 -22
- package/dist/workflows.js.map +1 -1
- package/package.json +9 -17
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;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,
|
|
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,CAAC,CAAC,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,CAAC,CAAC,QAAQ,MAAM,EAAE;AACvD"}
|
package/dist/vite.d.ts
CHANGED
|
@@ -1,14 +1,25 @@
|
|
|
1
1
|
import { Plugin } from "vite";
|
|
2
2
|
|
|
3
3
|
//#region src/vite.d.ts
|
|
4
|
+
interface AgentsPluginOptions {
|
|
5
|
+
/**
|
|
6
|
+
* Replace `turndown` with an inert stub so `just-bash` (workspace bash tool /
|
|
7
|
+
* skill runner) doesn't drag turndown's `require()`-using DOM fallback into
|
|
8
|
+
* the Worker's module-init path and break deploys. Enabled by default. Set to
|
|
9
|
+
* `false` if your app uses turndown directly and needs the real
|
|
10
|
+
* implementation.
|
|
11
|
+
*/
|
|
12
|
+
stubTurndown?: boolean;
|
|
13
|
+
}
|
|
4
14
|
/**
|
|
5
15
|
* Vite plugin for Agents SDK projects.
|
|
6
16
|
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
17
|
+
* Handles TC39 decorator transforms (Oxc doesn't support them yet, oxc#9170) so
|
|
18
|
+
* `@callable()` works at runtime, the `agents:skills` import transform, and
|
|
19
|
+
* stubbing `turndown` to keep Workers deploys clean. Will grow to cover other
|
|
9
20
|
* Agents-specific build concerns as needed.
|
|
10
21
|
*/
|
|
11
|
-
declare function agents(): Plugin[];
|
|
22
|
+
declare function agents(options?: AgentsPluginOptions): Plugin[];
|
|
12
23
|
//#endregion
|
|
13
|
-
export { agents as default };
|
|
24
|
+
export { AgentsPluginOptions, agents as default };
|
|
14
25
|
//# sourceMappingURL=vite.d.ts.map
|
package/dist/vite.js
CHANGED
|
@@ -230,6 +230,30 @@ async function buildSkillsModule(dir, warn) {
|
|
|
230
230
|
};
|
|
231
231
|
return `const manifest = ${JSON.stringify(manifest)};\nexport default {\n id: manifest.id,\n fingerprint: manifest.fingerprint,\n async list() {\n return manifest.skills.map(({ body, rawContent, resources, ...skill }) => skill);\n },\n async load(name) {\n const skill = manifest.skills.find((entry) => entry.name === name);\n if (!skill) return null;\n return {\n ...skill,\n resources: skill.resources.map(({ content, ...resource }) => resource)\n };\n },\n async readResource(name, path) {\n const skill = manifest.skills.find((entry) => entry.name === name);\n const resource = skill?.resources.find((entry) => entry.path === path);\n return resource ? { ...resource } : null;\n }\n};\n`;
|
|
232
232
|
}
|
|
233
|
+
const TURNDOWN_STUB_ID = "\0agents:turndown-stub";
|
|
234
|
+
function turndownStubPlugin() {
|
|
235
|
+
return {
|
|
236
|
+
name: "agents-turndown-stub",
|
|
237
|
+
enforce: "pre",
|
|
238
|
+
resolveId(source) {
|
|
239
|
+
if (source === "turndown") return TURNDOWN_STUB_ID;
|
|
240
|
+
return null;
|
|
241
|
+
},
|
|
242
|
+
load(id) {
|
|
243
|
+
if (id !== TURNDOWN_STUB_ID) return null;
|
|
244
|
+
return `class TurndownService {
|
|
245
|
+
constructor() {}
|
|
246
|
+
use() { return this; }
|
|
247
|
+
addRule() { return this; }
|
|
248
|
+
keep() { return this; }
|
|
249
|
+
remove() { return this; }
|
|
250
|
+
turndown() { return ""; }
|
|
251
|
+
}
|
|
252
|
+
export default TurndownService;
|
|
253
|
+
`;
|
|
254
|
+
}
|
|
255
|
+
};
|
|
256
|
+
}
|
|
233
257
|
function skillsImportPlugin() {
|
|
234
258
|
return {
|
|
235
259
|
name: "agents-skills-import",
|
|
@@ -249,15 +273,21 @@ function skillsImportPlugin() {
|
|
|
249
273
|
/**
|
|
250
274
|
* Vite plugin for Agents SDK projects.
|
|
251
275
|
*
|
|
252
|
-
*
|
|
253
|
-
*
|
|
276
|
+
* Handles TC39 decorator transforms (Oxc doesn't support them yet, oxc#9170) so
|
|
277
|
+
* `@callable()` works at runtime, the `agents:skills` import transform, and
|
|
278
|
+
* stubbing `turndown` to keep Workers deploys clean. Will grow to cover other
|
|
254
279
|
* Agents-specific build concerns as needed.
|
|
255
280
|
*/
|
|
256
|
-
function agents() {
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
281
|
+
function agents(options = {}) {
|
|
282
|
+
const { stubTurndown = true } = options;
|
|
283
|
+
return [
|
|
284
|
+
...stubTurndown ? [turndownStubPlugin()] : [],
|
|
285
|
+
skillsImportPlugin(),
|
|
286
|
+
babel({ presets: [{
|
|
287
|
+
preset: () => ({ plugins: [["@babel/plugin-proposal-decorators", { version: "2023-11" }]] }),
|
|
288
|
+
rolldown: { filter: { code: "@" } }
|
|
289
|
+
}] })
|
|
290
|
+
];
|
|
261
291
|
}
|
|
262
292
|
//#endregion
|
|
263
293
|
export { agents as default };
|
package/dist/vite.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vite.js","names":["parseYaml"],"sources":["../src/vite.ts"],"sourcesContent":["import babel from \"@rolldown/plugin-babel\";\nimport { createHash } from \"node:crypto\";\nimport { readdir, readFile, stat } from \"node:fs/promises\";\nimport { basename, join, resolve } from \"node:path\";\nimport { parse as parseYaml } from \"yaml\";\nimport type { Plugin } from \"vite\";\n\nconst SKILLS_SPECIFIER = \"agents:skills\";\nconst SKILLS_VIRTUAL_PREFIX = \"\\0agents:skills:\";\nconst SKILL_RESOURCE_ROOTS = new Set([\n \"references\",\n \"scripts\",\n \"assets\",\n \"graphics\",\n \"fonts\",\n \"templates\",\n \"rendered-files\",\n \"illustrations\"\n]);\nconst SKILL_IGNORED_ROOTS = new Set([\n \".git\",\n \".hg\",\n \".svn\",\n \".DS_Store\",\n \".idea\",\n \".vscode\",\n \"dist\",\n \"build\",\n \"coverage\",\n \"node_modules\"\n]);\nconst SPEC_RESOURCE_ROOTS = new Set([\"references\", \"scripts\", \"assets\"]);\n\n// Bundled skill resources are base64-embedded into the Worker bundle, which\n// inflates them by ~1.33x and competes with app code for the bundle-size\n// budget. These heuristic thresholds (raw bytes) trigger a recommendation to\n// move large assets to an R2-backed skill source instead.\nconst SKILL_ASSET_WARN_BYTES = 256 * 1024;\nconst SKILL_BUNDLE_WARN_BYTES = 1024 * 1024;\n\nfunction formatBytes(bytes: number): string {\n if (bytes >= 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;\n if (bytes >= 1024) return `${(bytes / 1024).toFixed(0)}KB`;\n return `${bytes}B`;\n}\n\ninterface SkillFile {\n name: string;\n description: string;\n body: string;\n rawContent: string;\n compatibility?: string;\n license?: string;\n allowedTools?: string;\n metadata?: Record<string, unknown>;\n resources: Array<{\n path: string;\n kind: \"reference\" | \"script\" | \"asset\" | \"file\";\n size: number;\n encoding: \"text\" | \"base64\";\n mimeType?: string;\n content: string;\n }>;\n}\n\nfunction parseFrontmatter(raw: string): {\n data: Record<string, unknown>;\n body: string;\n} {\n const match = raw.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n?([\\s\\S]*)$/);\n if (!match) return { data: {}, body: raw };\n const parsed = parseYaml(match[1] ?? \"\");\n const data =\n parsed !== null && typeof parsed === \"object\" && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : {};\n return { data, body: match[2] ?? \"\" };\n}\n\nfunction stringField(value: unknown): string | undefined {\n return typeof value === \"string\" && value.trim() ? value.trim() : undefined;\n}\n\nfunction recordField(value: unknown): Record<string, unknown> | undefined {\n return value !== null && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\nfunction resourceKind(path: string): \"reference\" | \"script\" | \"asset\" | \"file\" {\n if (path.startsWith(\"references/\")) return \"reference\";\n if (path.startsWith(\"scripts/\")) return \"script\";\n if (\n path.startsWith(\"assets/\") ||\n path.startsWith(\"graphics/\") ||\n path.startsWith(\"fonts/\") ||\n path.startsWith(\"templates/\") ||\n path.startsWith(\"rendered-files/\") ||\n path.startsWith(\"illustrations/\")\n ) {\n return \"asset\";\n }\n return \"file\";\n}\n\nconst TEXT_EXTENSIONS = new Set([\n \".bash\",\n \".css\",\n \".csv\",\n \".html\",\n \".js\",\n \".json\",\n \".jsx\",\n \".md\",\n \".mjs\",\n \".py\",\n \".sh\",\n \".svg\",\n \".ts\",\n \".tsx\",\n \".txt\",\n \".xml\",\n \".yaml\",\n \".yml\"\n]);\n\nconst MIME_TYPES = new Map([\n [\".css\", \"text/css\"],\n [\".gif\", \"image/gif\"],\n [\".html\", \"text/html\"],\n [\".jpg\", \"image/jpeg\"],\n [\".jpeg\", \"image/jpeg\"],\n [\".js\", \"text/javascript\"],\n [\".json\", \"application/json\"],\n [\".md\", \"text/markdown\"],\n [\".mjs\", \"text/javascript\"],\n [\".pdf\", \"application/pdf\"],\n [\".png\", \"image/png\"],\n [\".py\", \"text/x-python\"],\n [\".sh\", \"text/x-shellscript\"],\n [\".svg\", \"image/svg+xml\"],\n [\".ts\", \"text/typescript\"],\n [\".tsx\", \"text/typescript\"],\n [\".txt\", \"text/plain\"],\n [\".webp\", \"image/webp\"],\n [\".woff\", \"font/woff\"],\n [\".woff2\", \"font/woff2\"],\n [\".xml\", \"application/xml\"],\n [\".yaml\", \"application/yaml\"],\n [\".yml\", \"application/yaml\"]\n]);\n\nfunction extensionOf(path: string): string {\n const file = path.split(\"/\").at(-1) ?? path;\n const index = file.lastIndexOf(\".\");\n return index === -1 ? \"\" : file.slice(index).toLowerCase();\n}\n\nfunction resourceEncoding(path: string): \"text\" | \"base64\" {\n return TEXT_EXTENSIONS.has(extensionOf(path)) ? \"text\" : \"base64\";\n}\n\nfunction resourceMimeType(path: string): string | undefined {\n return MIME_TYPES.get(extensionOf(path));\n}\n\nasync function collectFiles(\n root: string,\n relativeRoot = \"\",\n warn?: (message: string) => void\n): Promise<Array<{ path: string; absolutePath: string; size: number }>> {\n const entries = await readdir(join(root, relativeRoot), {\n withFileTypes: true\n }).catch(() => []);\n const files: Array<{ path: string; absolutePath: string; size: number }> = [];\n\n for (const entry of entries) {\n if (SKILL_IGNORED_ROOTS.has(entry.name)) continue;\n const relativePath = relativeRoot\n ? `${relativeRoot}/${entry.name}`\n : entry.name;\n const absolutePath = join(root, relativePath);\n if (entry.isDirectory()) {\n const resourceRoot = relativePath.split(\"/\")[0];\n if (!resourceRoot || SKILL_IGNORED_ROOTS.has(resourceRoot)) continue;\n if (!SKILL_RESOURCE_ROOTS.has(resourceRoot)) {\n if (!relativeRoot) {\n warn?.(\n `Ignoring skill directory \"${relativePath}\". Bundled skill resources should live under references/, scripts/, assets/, or a known asset root.`\n );\n }\n continue;\n }\n if (!SPEC_RESOURCE_ROOTS.has(resourceRoot) && !relativeRoot) {\n warn?.(\n `Bundling non-standard skill resource root \"${resourceRoot}/\". Prefer assets/ for portable Agent Skills when possible.`\n );\n }\n files.push(...(await collectFiles(root, relativePath, warn)));\n } else if (entry.isFile() && relativePath !== \"SKILL.md\") {\n const resourceRoot = relativePath.split(\"/\")[0];\n if (!resourceRoot || SKILL_IGNORED_ROOTS.has(resourceRoot)) continue;\n if (!SKILL_RESOURCE_ROOTS.has(resourceRoot)) {\n warn?.(\n `Ignoring skill file \"${relativePath}\". Bundled skill resources should live under references/, scripts/, assets/, or a known asset root.`\n );\n continue;\n }\n const info = await stat(absolutePath);\n files.push({ path: relativePath, absolutePath, size: info.size });\n }\n }\n\n return files.sort((a, b) => a.path.localeCompare(b.path));\n}\n\nasync function collectWatchTargets(\n root: string,\n relativeRoot = \"\"\n): Promise<string[]> {\n const directory = join(root, relativeRoot);\n const entries = await readdir(directory, { withFileTypes: true }).catch(\n () => []\n );\n const targets = [directory];\n\n for (const entry of entries) {\n if (SKILL_IGNORED_ROOTS.has(entry.name)) continue;\n const relativePath = relativeRoot\n ? `${relativeRoot}/${entry.name}`\n : entry.name;\n const resourceRoot = relativePath.split(\"/\")[0];\n if (!resourceRoot || SKILL_IGNORED_ROOTS.has(resourceRoot)) continue;\n\n const absolutePath = join(root, relativePath);\n targets.push(absolutePath);\n\n if (entry.isDirectory()) {\n targets.push(...(await collectWatchTargets(root, relativePath)));\n }\n }\n\n return targets;\n}\n\nasync function readSkill(\n skillDir: string,\n warn?: (message: string) => void\n): Promise<SkillFile | null> {\n const skillPath = join(skillDir, \"SKILL.md\");\n const rawContent = await readFile(skillPath, \"utf8\").catch(() => null);\n if (rawContent === null) return null;\n\n const { data, body } = parseFrontmatter(rawContent);\n const name = stringField(data.name);\n const description = stringField(data.description);\n if (!name || !description) return null;\n\n const resources = await Promise.all(\n (await collectFiles(skillDir, \"\", warn)).map(async (file) => {\n const encoding = resourceEncoding(file.path);\n const bytes = await readFile(file.absolutePath);\n return {\n path: file.path,\n kind: resourceKind(file.path),\n size: file.size,\n encoding,\n mimeType: resourceMimeType(file.path),\n content:\n encoding === \"base64\" ? bytes.toString(\"base64\") : bytes.toString()\n };\n })\n );\n\n return {\n name,\n description,\n body,\n rawContent,\n compatibility: stringField(data.compatibility),\n license: stringField(data.license),\n allowedTools: stringField(data[\"allowed-tools\"]),\n metadata: recordField(data.metadata),\n resources\n };\n}\n\nasync function buildSkillsModule(\n dir: string,\n warn?: (message: string) => void\n): Promise<string> {\n const entries = await readdir(dir, { withFileTypes: true });\n const skills: SkillFile[] = [];\n const seen = new Set<string>();\n\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n const skill = await readSkill(join(dir, entry.name), warn);\n if (!skill) continue;\n if (seen.has(skill.name)) {\n warn?.(\n `Duplicate bundled skill name \"${skill.name}\" in \"${entry.name}/\"; keeping the first occurrence and ignoring this one.`\n );\n continue;\n }\n seen.add(skill.name);\n skills.push(skill);\n }\n\n skills.sort((a, b) => a.name.localeCompare(b.name));\n\n let totalBytes = 0;\n for (const skill of skills) {\n for (const resource of skill.resources) {\n totalBytes += resource.size;\n if (resource.size > SKILL_ASSET_WARN_BYTES) {\n warn?.(\n `Bundled skill resource \"${skill.name}/${resource.path}\" is ${formatBytes(resource.size)}; large assets bloat the Worker bundle (base64, ~1.33x). Prefer an R2-backed source via skills.r2().`\n );\n }\n }\n }\n if (totalBytes > SKILL_BUNDLE_WARN_BYTES) {\n warn?.(\n `Bundled skills total ${formatBytes(totalBytes)} of embedded resources; this competes with the Worker bundle-size budget. Consider serving large skills from R2 via skills.r2().`\n );\n }\n\n const hash = createHash(\"sha256\");\n hash.update(JSON.stringify(skills));\n\n const manifest = {\n id: `bundle:${basename(dir)}`,\n fingerprint: hash.digest(\"hex\"),\n skills\n };\n\n return `const manifest = ${JSON.stringify(manifest)};\\nexport default {\\n id: manifest.id,\\n fingerprint: manifest.fingerprint,\\n async list() {\\n return manifest.skills.map(({ body, rawContent, resources, ...skill }) => skill);\\n },\\n async load(name) {\\n const skill = manifest.skills.find((entry) => entry.name === name);\\n if (!skill) return null;\\n return {\\n ...skill,\\n resources: skill.resources.map(({ content, ...resource }) => resource)\\n };\\n },\\n async readResource(name, path) {\\n const skill = manifest.skills.find((entry) => entry.name === name);\\n const resource = skill?.resources.find((entry) => entry.path === path);\\n return resource ? { ...resource } : null;\\n }\\n};\\n`;\n}\n\nfunction skillsImportPlugin(): Plugin {\n return {\n name: \"agents-skills-import\",\n async resolveId(source, importer) {\n // `agents:skills` resolves to a `./skills` directory next to the\n // importer; `agents:skills/<dir>` points at a sibling directory.\n if (\n source !== SKILLS_SPECIFIER &&\n !source.startsWith(`${SKILLS_SPECIFIER}/`)\n ) {\n return null;\n }\n if (!importer) return null;\n const relative =\n source === SKILLS_SPECIFIER\n ? \"skills\"\n : source.slice(SKILLS_SPECIFIER.length + 1);\n const resolved = resolve(importer, \"..\", relative);\n return `${SKILLS_VIRTUAL_PREFIX}${resolved}`;\n },\n async load(id) {\n if (!id.startsWith(SKILLS_VIRTUAL_PREFIX)) return null;\n const dir = id.slice(SKILLS_VIRTUAL_PREFIX.length);\n for (const target of await collectWatchTargets(dir)) {\n this.addWatchFile(target);\n }\n return buildSkillsModule(dir, (message) => this.warn(message));\n }\n };\n}\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 [\n skillsImportPlugin(),\n 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 Plug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B;CACpC,OAAO;EACL,MAAM;EACN,MAAM,UAAU,QAAQ,UAAU;GAGhC,IACE,WAAW,oBACX,CAAC,OAAO,WAAW,GAAG,iBAAiB,EAAE,GAEzC,OAAO;GAET,IAAI,CAAC,UAAU,OAAO;GAMtB,OAAO,GAAG,wBADO,QAAQ,UAAU,MAHjC,WAAW,mBACP,WACA,OAAO,MAAM,EAA2B,CAEL;EAC3C;EACA,MAAM,KAAK,IAAI;GACb,IAAI,CAAC,GAAG,WAAW,qBAAqB,GAAG,OAAO;GAClD,MAAM,MAAM,GAAG,MAAM,EAA4B;GACjD,KAAK,MAAM,UAAU,MAAM,oBAAoB,GAAG,GAChD,KAAK,aAAa,MAAM;GAE1B,OAAO,kBAAkB,MAAM,YAAY,KAAK,KAAK,OAAO,CAAC;EAC/D;CACF;AACF;;;;;;;;AASA,SAAwB,SAAmB;CACzC,OAAO,CACL,mBAAmB,GACnB,MAAM,EACJ,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,CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"vite.js","names":["parseYaml"],"sources":["../src/vite.ts"],"sourcesContent":["import babel from \"@rolldown/plugin-babel\";\nimport { createHash } from \"node:crypto\";\nimport { readdir, readFile, stat } from \"node:fs/promises\";\nimport { basename, join, resolve } from \"node:path\";\nimport { parse as parseYaml } from \"yaml\";\nimport type { Plugin } from \"vite\";\n\nconst SKILLS_SPECIFIER = \"agents:skills\";\nconst SKILLS_VIRTUAL_PREFIX = \"\\0agents:skills:\";\nconst SKILL_RESOURCE_ROOTS = new Set([\n \"references\",\n \"scripts\",\n \"assets\",\n \"graphics\",\n \"fonts\",\n \"templates\",\n \"rendered-files\",\n \"illustrations\"\n]);\nconst SKILL_IGNORED_ROOTS = new Set([\n \".git\",\n \".hg\",\n \".svn\",\n \".DS_Store\",\n \".idea\",\n \".vscode\",\n \"dist\",\n \"build\",\n \"coverage\",\n \"node_modules\"\n]);\nconst SPEC_RESOURCE_ROOTS = new Set([\"references\", \"scripts\", \"assets\"]);\n\n// Bundled skill resources are base64-embedded into the Worker bundle, which\n// inflates them by ~1.33x and competes with app code for the bundle-size\n// budget. These heuristic thresholds (raw bytes) trigger a recommendation to\n// move large assets to an R2-backed skill source instead.\nconst SKILL_ASSET_WARN_BYTES = 256 * 1024;\nconst SKILL_BUNDLE_WARN_BYTES = 1024 * 1024;\n\nfunction formatBytes(bytes: number): string {\n if (bytes >= 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;\n if (bytes >= 1024) return `${(bytes / 1024).toFixed(0)}KB`;\n return `${bytes}B`;\n}\n\ninterface SkillFile {\n name: string;\n description: string;\n body: string;\n rawContent: string;\n compatibility?: string;\n license?: string;\n allowedTools?: string;\n metadata?: Record<string, unknown>;\n resources: Array<{\n path: string;\n kind: \"reference\" | \"script\" | \"asset\" | \"file\";\n size: number;\n encoding: \"text\" | \"base64\";\n mimeType?: string;\n content: string;\n }>;\n}\n\nfunction parseFrontmatter(raw: string): {\n data: Record<string, unknown>;\n body: string;\n} {\n const match = raw.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n?([\\s\\S]*)$/);\n if (!match) return { data: {}, body: raw };\n const parsed = parseYaml(match[1] ?? \"\");\n const data =\n parsed !== null && typeof parsed === \"object\" && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : {};\n return { data, body: match[2] ?? \"\" };\n}\n\nfunction stringField(value: unknown): string | undefined {\n return typeof value === \"string\" && value.trim() ? value.trim() : undefined;\n}\n\nfunction recordField(value: unknown): Record<string, unknown> | undefined {\n return value !== null && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\nfunction resourceKind(path: string): \"reference\" | \"script\" | \"asset\" | \"file\" {\n if (path.startsWith(\"references/\")) return \"reference\";\n if (path.startsWith(\"scripts/\")) return \"script\";\n if (\n path.startsWith(\"assets/\") ||\n path.startsWith(\"graphics/\") ||\n path.startsWith(\"fonts/\") ||\n path.startsWith(\"templates/\") ||\n path.startsWith(\"rendered-files/\") ||\n path.startsWith(\"illustrations/\")\n ) {\n return \"asset\";\n }\n return \"file\";\n}\n\nconst TEXT_EXTENSIONS = new Set([\n \".bash\",\n \".css\",\n \".csv\",\n \".html\",\n \".js\",\n \".json\",\n \".jsx\",\n \".md\",\n \".mjs\",\n \".py\",\n \".sh\",\n \".svg\",\n \".ts\",\n \".tsx\",\n \".txt\",\n \".xml\",\n \".yaml\",\n \".yml\"\n]);\n\nconst MIME_TYPES = new Map([\n [\".css\", \"text/css\"],\n [\".gif\", \"image/gif\"],\n [\".html\", \"text/html\"],\n [\".jpg\", \"image/jpeg\"],\n [\".jpeg\", \"image/jpeg\"],\n [\".js\", \"text/javascript\"],\n [\".json\", \"application/json\"],\n [\".md\", \"text/markdown\"],\n [\".mjs\", \"text/javascript\"],\n [\".pdf\", \"application/pdf\"],\n [\".png\", \"image/png\"],\n [\".py\", \"text/x-python\"],\n [\".sh\", \"text/x-shellscript\"],\n [\".svg\", \"image/svg+xml\"],\n [\".ts\", \"text/typescript\"],\n [\".tsx\", \"text/typescript\"],\n [\".txt\", \"text/plain\"],\n [\".webp\", \"image/webp\"],\n [\".woff\", \"font/woff\"],\n [\".woff2\", \"font/woff2\"],\n [\".xml\", \"application/xml\"],\n [\".yaml\", \"application/yaml\"],\n [\".yml\", \"application/yaml\"]\n]);\n\nfunction extensionOf(path: string): string {\n const file = path.split(\"/\").at(-1) ?? path;\n const index = file.lastIndexOf(\".\");\n return index === -1 ? \"\" : file.slice(index).toLowerCase();\n}\n\nfunction resourceEncoding(path: string): \"text\" | \"base64\" {\n return TEXT_EXTENSIONS.has(extensionOf(path)) ? \"text\" : \"base64\";\n}\n\nfunction resourceMimeType(path: string): string | undefined {\n return MIME_TYPES.get(extensionOf(path));\n}\n\nasync function collectFiles(\n root: string,\n relativeRoot = \"\",\n warn?: (message: string) => void\n): Promise<Array<{ path: string; absolutePath: string; size: number }>> {\n const entries = await readdir(join(root, relativeRoot), {\n withFileTypes: true\n }).catch(() => []);\n const files: Array<{ path: string; absolutePath: string; size: number }> = [];\n\n for (const entry of entries) {\n if (SKILL_IGNORED_ROOTS.has(entry.name)) continue;\n const relativePath = relativeRoot\n ? `${relativeRoot}/${entry.name}`\n : entry.name;\n const absolutePath = join(root, relativePath);\n if (entry.isDirectory()) {\n const resourceRoot = relativePath.split(\"/\")[0];\n if (!resourceRoot || SKILL_IGNORED_ROOTS.has(resourceRoot)) continue;\n if (!SKILL_RESOURCE_ROOTS.has(resourceRoot)) {\n if (!relativeRoot) {\n warn?.(\n `Ignoring skill directory \"${relativePath}\". Bundled skill resources should live under references/, scripts/, assets/, or a known asset root.`\n );\n }\n continue;\n }\n if (!SPEC_RESOURCE_ROOTS.has(resourceRoot) && !relativeRoot) {\n warn?.(\n `Bundling non-standard skill resource root \"${resourceRoot}/\". Prefer assets/ for portable Agent Skills when possible.`\n );\n }\n files.push(...(await collectFiles(root, relativePath, warn)));\n } else if (entry.isFile() && relativePath !== \"SKILL.md\") {\n const resourceRoot = relativePath.split(\"/\")[0];\n if (!resourceRoot || SKILL_IGNORED_ROOTS.has(resourceRoot)) continue;\n if (!SKILL_RESOURCE_ROOTS.has(resourceRoot)) {\n warn?.(\n `Ignoring skill file \"${relativePath}\". Bundled skill resources should live under references/, scripts/, assets/, or a known asset root.`\n );\n continue;\n }\n const info = await stat(absolutePath);\n files.push({ path: relativePath, absolutePath, size: info.size });\n }\n }\n\n return files.sort((a, b) => a.path.localeCompare(b.path));\n}\n\nasync function collectWatchTargets(\n root: string,\n relativeRoot = \"\"\n): Promise<string[]> {\n const directory = join(root, relativeRoot);\n const entries = await readdir(directory, { withFileTypes: true }).catch(\n () => []\n );\n const targets = [directory];\n\n for (const entry of entries) {\n if (SKILL_IGNORED_ROOTS.has(entry.name)) continue;\n const relativePath = relativeRoot\n ? `${relativeRoot}/${entry.name}`\n : entry.name;\n const resourceRoot = relativePath.split(\"/\")[0];\n if (!resourceRoot || SKILL_IGNORED_ROOTS.has(resourceRoot)) continue;\n\n const absolutePath = join(root, relativePath);\n targets.push(absolutePath);\n\n if (entry.isDirectory()) {\n targets.push(...(await collectWatchTargets(root, relativePath)));\n }\n }\n\n return targets;\n}\n\nasync function readSkill(\n skillDir: string,\n warn?: (message: string) => void\n): Promise<SkillFile | null> {\n const skillPath = join(skillDir, \"SKILL.md\");\n const rawContent = await readFile(skillPath, \"utf8\").catch(() => null);\n if (rawContent === null) return null;\n\n const { data, body } = parseFrontmatter(rawContent);\n const name = stringField(data.name);\n const description = stringField(data.description);\n if (!name || !description) return null;\n\n const resources = await Promise.all(\n (await collectFiles(skillDir, \"\", warn)).map(async (file) => {\n const encoding = resourceEncoding(file.path);\n const bytes = await readFile(file.absolutePath);\n return {\n path: file.path,\n kind: resourceKind(file.path),\n size: file.size,\n encoding,\n mimeType: resourceMimeType(file.path),\n content:\n encoding === \"base64\" ? bytes.toString(\"base64\") : bytes.toString()\n };\n })\n );\n\n return {\n name,\n description,\n body,\n rawContent,\n compatibility: stringField(data.compatibility),\n license: stringField(data.license),\n allowedTools: stringField(data[\"allowed-tools\"]),\n metadata: recordField(data.metadata),\n resources\n };\n}\n\nasync function buildSkillsModule(\n dir: string,\n warn?: (message: string) => void\n): Promise<string> {\n const entries = await readdir(dir, { withFileTypes: true });\n const skills: SkillFile[] = [];\n const seen = new Set<string>();\n\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n const skill = await readSkill(join(dir, entry.name), warn);\n if (!skill) continue;\n if (seen.has(skill.name)) {\n warn?.(\n `Duplicate bundled skill name \"${skill.name}\" in \"${entry.name}/\"; keeping the first occurrence and ignoring this one.`\n );\n continue;\n }\n seen.add(skill.name);\n skills.push(skill);\n }\n\n skills.sort((a, b) => a.name.localeCompare(b.name));\n\n let totalBytes = 0;\n for (const skill of skills) {\n for (const resource of skill.resources) {\n totalBytes += resource.size;\n if (resource.size > SKILL_ASSET_WARN_BYTES) {\n warn?.(\n `Bundled skill resource \"${skill.name}/${resource.path}\" is ${formatBytes(resource.size)}; large assets bloat the Worker bundle (base64, ~1.33x). Prefer an R2-backed source via skills.r2().`\n );\n }\n }\n }\n if (totalBytes > SKILL_BUNDLE_WARN_BYTES) {\n warn?.(\n `Bundled skills total ${formatBytes(totalBytes)} of embedded resources; this competes with the Worker bundle-size budget. Consider serving large skills from R2 via skills.r2().`\n );\n }\n\n const hash = createHash(\"sha256\");\n hash.update(JSON.stringify(skills));\n\n const manifest = {\n id: `bundle:${basename(dir)}`,\n fingerprint: hash.digest(\"hex\"),\n skills\n };\n\n return `const manifest = ${JSON.stringify(manifest)};\\nexport default {\\n id: manifest.id,\\n fingerprint: manifest.fingerprint,\\n async list() {\\n return manifest.skills.map(({ body, rawContent, resources, ...skill }) => skill);\\n },\\n async load(name) {\\n const skill = manifest.skills.find((entry) => entry.name === name);\\n if (!skill) return null;\\n return {\\n ...skill,\\n resources: skill.resources.map(({ content, ...resource }) => resource)\\n };\\n },\\n async readResource(name, path) {\\n const skill = manifest.skills.find((entry) => entry.name === name);\\n const resource = skill?.resources.find((entry) => entry.path === path);\\n return resource ? { ...resource } : null;\\n }\\n};\\n`;\n}\n\nconst TURNDOWN_STUB_ID = \"\\0agents:turndown-stub\";\n\n// `just-bash` (pulled in by the workspace bash tool / skill runner) statically\n// depends on `turndown`, whose ESM build runs a top-level `require()` on its\n// Node DOM fallback. Workers is ESM with no global `require`, so the module\n// throws at startup — even when the bash tool is never used. turndown is only\n// needed by just-bash's niche `html-to-markdown` command, so we replace it with\n// an inert stub by default to keep Workers deploys clean. Opt out with\n// `agents({ stubTurndown: false })` if you rely on turndown elsewhere.\nfunction turndownStubPlugin(): Plugin {\n return {\n name: \"agents-turndown-stub\",\n enforce: \"pre\",\n resolveId(source) {\n if (source === \"turndown\") return TURNDOWN_STUB_ID;\n return null;\n },\n load(id) {\n if (id !== TURNDOWN_STUB_ID) return null;\n return `class TurndownService {\n constructor() {}\n use() { return this; }\n addRule() { return this; }\n keep() { return this; }\n remove() { return this; }\n turndown() { return \"\"; }\n}\nexport default TurndownService;\n`;\n }\n };\n}\n\nfunction skillsImportPlugin(): Plugin {\n return {\n name: \"agents-skills-import\",\n async resolveId(source, importer) {\n // `agents:skills` resolves to a `./skills` directory next to the\n // importer; `agents:skills/<dir>` points at a sibling directory.\n if (\n source !== SKILLS_SPECIFIER &&\n !source.startsWith(`${SKILLS_SPECIFIER}/`)\n ) {\n return null;\n }\n if (!importer) return null;\n const relative =\n source === SKILLS_SPECIFIER\n ? \"skills\"\n : source.slice(SKILLS_SPECIFIER.length + 1);\n const resolved = resolve(importer, \"..\", relative);\n return `${SKILLS_VIRTUAL_PREFIX}${resolved}`;\n },\n async load(id) {\n if (!id.startsWith(SKILLS_VIRTUAL_PREFIX)) return null;\n const dir = id.slice(SKILLS_VIRTUAL_PREFIX.length);\n for (const target of await collectWatchTargets(dir)) {\n this.addWatchFile(target);\n }\n return buildSkillsModule(dir, (message) => this.warn(message));\n }\n };\n}\n\nexport interface AgentsPluginOptions {\n /**\n * Replace `turndown` with an inert stub so `just-bash` (workspace bash tool /\n * skill runner) doesn't drag turndown's `require()`-using DOM fallback into\n * the Worker's module-init path and break deploys. Enabled by default. Set to\n * `false` if your app uses turndown directly and needs the real\n * implementation.\n */\n stubTurndown?: boolean;\n}\n\n/**\n * Vite plugin for Agents SDK projects.\n *\n * Handles TC39 decorator transforms (Oxc doesn't support them yet, oxc#9170) so\n * `@callable()` works at runtime, the `agents:skills` import transform, and\n * stubbing `turndown` to keep Workers deploys clean. Will grow to cover other\n * Agents-specific build concerns as needed.\n */\nexport default function agents(options: AgentsPluginOptions = {}): Plugin[] {\n const { stubTurndown = true } = options;\n return [\n ...(stubTurndown ? [turndownStubPlugin()] : []),\n skillsImportPlugin(),\n 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}\n"],"mappings":";;;;;;AAOA,MAAM,mBAAmB;AACzB,MAAM,wBAAwB;AAC9B,MAAM,uBAAuB,IAAI,IAAI;CACnC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,sBAAsB,IAAI,IAAI;CAClC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,sBAAsB,IAAI,IAAI;CAAC;CAAc;CAAW;AAAQ,CAAC;AAMvE,MAAM,yBAAyB,MAAM;AACrC,MAAM,0BAA0B,OAAO;AAEvC,SAAS,YAAY,OAAuB;CAC1C,IAAI,SAAS,OAAO,MAAM,OAAO,IAAI,SAAS,OAAO,MAAA,CAAO,QAAQ,CAAC,EAAE;CACvE,IAAI,SAAS,MAAM,OAAO,IAAI,QAAQ,KAAA,CAAM,QAAQ,CAAC,EAAE;CACvD,OAAO,GAAG,MAAM;AAClB;AAqBA,SAAS,iBAAiB,KAGxB;CACA,MAAM,QAAQ,IAAI,MAAM,6CAA6C;CACrE,IAAI,CAAC,OAAO,OAAO;EAAE,MAAM,CAAC;EAAG,MAAM;CAAI;CACzC,MAAM,SAASA,MAAU,MAAM,MAAM,EAAE;CAKvC,OAAO;EAAE,MAHP,WAAW,QAAQ,OAAO,WAAW,YAAY,CAAC,MAAM,QAAQ,MAAM,IACjE,SACD,CAAC;EACQ,MAAM,MAAM,MAAM;CAAG;AACtC;AAEA,SAAS,YAAY,OAAoC;CACvD,OAAO,OAAO,UAAU,YAAY,MAAM,KAAK,IAAI,MAAM,KAAK,IAAI,KAAA;AACpE;AAEA,SAAS,YAAY,OAAqD;CACxE,OAAO,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK,IACrE,QACD,KAAA;AACN;AAEA,SAAS,aAAa,MAAyD;CAC7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AACF"}
|
package/dist/workflows.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { b as Agent } from "./agent-tool-types-V25Z_HcX.js";
|
|
2
2
|
import {
|
|
3
3
|
S as WorkflowTrackingRow,
|
|
4
4
|
_ as WorkflowPage,
|
|
@@ -42,7 +42,7 @@ declare class AgentWorkflow<
|
|
|
42
42
|
* The Agent stub - initialized before run() is called.
|
|
43
43
|
* Use this.agent to access the Agent's RPC methods.
|
|
44
44
|
*/
|
|
45
|
-
private _agent
|
|
45
|
+
private _agent?;
|
|
46
46
|
/**
|
|
47
47
|
* Workflow instance ID
|
|
48
48
|
*/
|
|
@@ -68,6 +68,14 @@ declare class AgentWorkflow<
|
|
|
68
68
|
* Called automatically before run() executes.
|
|
69
69
|
*/
|
|
70
70
|
private _initAgent;
|
|
71
|
+
/**
|
|
72
|
+
* Call user workflow code and report unhandled errors to the Agent.
|
|
73
|
+
*/
|
|
74
|
+
private _runWithErrorReporting;
|
|
75
|
+
/**
|
|
76
|
+
* Dispose the Agent stub owned by this workflow run.
|
|
77
|
+
*/
|
|
78
|
+
private _disposeAgent;
|
|
71
79
|
/**
|
|
72
80
|
* Wrap WorkflowStep with durable Agent communication methods.
|
|
73
81
|
* Methods added to the wrapped step are idempotent and won't repeat on retry.
|
package/dist/workflows.js
CHANGED
|
@@ -62,24 +62,18 @@ var AgentWorkflow = class extends WorkflowEntrypoint {
|
|
|
62
62
|
const { __agentName, __agentBinding, __workflowName, ...userParams } = event.payload;
|
|
63
63
|
await this._initAgent(__agentName, __agentBinding, __workflowName, event.instanceId);
|
|
64
64
|
this.__agentInitCalled = true;
|
|
65
|
-
const cleanedEvent = {
|
|
66
|
-
...event,
|
|
67
|
-
payload: userParams
|
|
68
|
-
};
|
|
69
|
-
const wrappedStep = this.extendStep(this._wrapStep(step), cleanedEvent);
|
|
70
65
|
try {
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
66
|
+
const cleanedEvent = {
|
|
67
|
+
...event,
|
|
68
|
+
payload: userParams
|
|
69
|
+
};
|
|
70
|
+
const wrappedStep = this.extendStep(this._wrapStep(step), cleanedEvent);
|
|
71
|
+
return await this._runWithErrorReporting(originalRun, cleanedEvent, wrappedStep);
|
|
72
|
+
} finally {
|
|
73
|
+
this._disposeAgent();
|
|
75
74
|
}
|
|
76
75
|
}
|
|
77
|
-
|
|
78
|
-
return await originalRun.call(this, event, step);
|
|
79
|
-
} catch (err) {
|
|
80
|
-
await this._autoReportError(err);
|
|
81
|
-
throw err;
|
|
82
|
-
}
|
|
76
|
+
return await this._runWithErrorReporting(originalRun, event, step);
|
|
83
77
|
};
|
|
84
78
|
wrappedPrototypes.add(proto);
|
|
85
79
|
}
|
|
@@ -92,11 +86,32 @@ var AgentWorkflow = class extends WorkflowEntrypoint {
|
|
|
92
86
|
if (!agentName || !agentBinding || !workflowName) throw new Error("AgentWorkflow requires __agentName, __agentBinding, and __workflowName in params. Use agent.runWorkflow() to start workflows with proper agent context.");
|
|
93
87
|
this._workflowId = instanceId;
|
|
94
88
|
this._workflowName = workflowName;
|
|
89
|
+
this._errorReported = false;
|
|
95
90
|
const namespace = this.env[agentBinding];
|
|
96
91
|
if (!namespace) throw new Error(`Agent binding '${agentBinding}' not found in environment`);
|
|
97
92
|
this._agent = await getAgentByName(namespace, agentName);
|
|
98
93
|
}
|
|
99
94
|
/**
|
|
95
|
+
* Call user workflow code and report unhandled errors to the Agent.
|
|
96
|
+
*/
|
|
97
|
+
async _runWithErrorReporting(originalRun, event, step) {
|
|
98
|
+
try {
|
|
99
|
+
return await originalRun.call(this, event, step);
|
|
100
|
+
} catch (err) {
|
|
101
|
+
await this._autoReportError(err);
|
|
102
|
+
throw err;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Dispose the Agent stub owned by this workflow run.
|
|
107
|
+
*/
|
|
108
|
+
_disposeAgent() {
|
|
109
|
+
const agent = this._agent;
|
|
110
|
+
this._agent = void 0;
|
|
111
|
+
this.__agentInitCalled = false;
|
|
112
|
+
disposeIfPresent(agent);
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
100
115
|
* Wrap WorkflowStep with durable Agent communication methods.
|
|
101
116
|
* Methods added to the wrapped step are idempotent and won't repeat on retry.
|
|
102
117
|
*
|
|
@@ -275,18 +290,29 @@ var AgentWorkflow = class extends WorkflowEntrypoint {
|
|
|
275
290
|
const stepName = options?.stepName ?? "wait-for-approval";
|
|
276
291
|
const eventType = options?.eventType ?? "approval";
|
|
277
292
|
const timeout = options?.timeout;
|
|
278
|
-
const
|
|
293
|
+
const event = await step.waitForEvent(stepName, {
|
|
279
294
|
type: eventType,
|
|
280
295
|
timeout
|
|
281
|
-
})
|
|
282
|
-
|
|
283
|
-
const
|
|
284
|
-
|
|
285
|
-
|
|
296
|
+
});
|
|
297
|
+
try {
|
|
298
|
+
const payload = event.payload;
|
|
299
|
+
if (!payload.approved) {
|
|
300
|
+
const reason = payload.reason;
|
|
301
|
+
await step.reportError(reason ?? "Workflow rejected");
|
|
302
|
+
throw new WorkflowRejectedError(reason, this._workflowId);
|
|
303
|
+
}
|
|
304
|
+
return payload.metadata;
|
|
305
|
+
} finally {
|
|
306
|
+
disposeIfPresent(event);
|
|
286
307
|
}
|
|
287
|
-
return payload.metadata;
|
|
288
308
|
}
|
|
289
309
|
};
|
|
310
|
+
function isDisposableResource(value) {
|
|
311
|
+
return !!value && typeof value === "object" && Symbol.dispose in value && typeof value[Symbol.dispose] === "function";
|
|
312
|
+
}
|
|
313
|
+
function disposeIfPresent(value) {
|
|
314
|
+
if (isDisposableResource(value)) value[Symbol.dispose]();
|
|
315
|
+
}
|
|
290
316
|
//#endregion
|
|
291
317
|
export { AgentWorkflow, WorkflowRejectedError };
|
|
292
318
|
|
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.extendStep(\n this._wrapStep(step),\n cleanedEvent\n );\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 * Extend the Agent-aware workflow step before user code receives it.\n *\n * Subclasses can override this to add framework-specific step helpers while\n * preserving the underlying WorkflowStep object identity.\n */\n protected extendStep(\n step: AgentWorkflowStep,\n _event: WorkflowEvent<Params>\n ): AgentWorkflowStep {\n return step;\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,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jB,MAAM;IACN,OAAO;IACP,WAAW,KAAK,IAAI;GACtB,CAAC;EACH,SAAS,YAAY,CAErB;CACF;;;;;;CAOA,MAAgB,YAAY,UAA2C;EACrE,MAAM,KAAK,MAAM,yBAAyB,QAAQ;CACpD;;;;;;;;;;;;;;;;;CAkBA,MAAgB,eAAe,UAAuC;EACpE,MAAM,KAAK,YAAY;GACrB,cAAc,KAAK;GACnB,YAAY,KAAK;GACjB,MAAM;GACI;GACV,WAAW,KAAK,IAAI;EACtB,CAAC;CACH;;;;;;;CAQA,mBAA6B,SAAwB;EACnD,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"}
|
|
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 {\n WorkflowEvent,\n WorkflowStep,\n WorkflowStepEvent\n} 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 try {\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.extendStep(\n this._wrapStep(step),\n cleanedEvent\n );\n\n return await this._runWithErrorReporting(\n originalRun,\n cleanedEvent,\n wrappedStep\n );\n } finally {\n this._disposeAgent();\n }\n }\n\n // If already initialized (e.g., called via super.run()),\n // just call the original with the event as-is.\n return await this._runWithErrorReporting(\n originalRun,\n event as WorkflowEvent<Params>,\n step as AgentWorkflowStep\n );\n };\n\n wrappedPrototypes.add(proto);\n }\n }\n\n /**\n * Initialize the Agent stub from workflow params.\n * Called automatically before run() executes.\n */\n private async _initAgent(\n agentName: string | undefined,\n agentBinding: string | undefined,\n workflowName: string | undefined,\n instanceId: string\n ): Promise<void> {\n if (!agentName || !agentBinding || !workflowName) {\n throw new Error(\n \"AgentWorkflow requires __agentName, __agentBinding, and __workflowName in params. \" +\n \"Use agent.runWorkflow() to start workflows with proper agent context.\"\n );\n }\n\n this._workflowId = instanceId;\n this._workflowName = workflowName;\n this._errorReported = false;\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 * Call user workflow code and report unhandled errors to the Agent.\n */\n private async _runWithErrorReporting(\n originalRun: (\n event: WorkflowEvent<Params>,\n step: AgentWorkflowStep\n ) => Promise<unknown>,\n event: WorkflowEvent<Params>,\n step: AgentWorkflowStep\n ): Promise<unknown> {\n try {\n return await originalRun.call(this, event, step);\n } catch (err) {\n await this._autoReportError(err);\n throw err;\n }\n }\n\n /**\n * Dispose the Agent stub owned by this workflow run.\n */\n private _disposeAgent(): void {\n const agent = this._agent;\n this._agent = undefined;\n this.__agentInitCalled = false;\n disposeIfPresent(agent);\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 * Extend the Agent-aware workflow step before user code receives it.\n *\n * Subclasses can override this to add framework-specific step helpers while\n * preserving the underlying WorkflowStep object identity.\n */\n protected extendStep(\n step: AgentWorkflowStep,\n _event: WorkflowEvent<Params>\n ): AgentWorkflowStep {\n return step;\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 })) as WorkflowStepEvent<{\n approved: boolean;\n reason?: string;\n metadata?: T;\n }>;\n\n try {\n const payload = event.payload;\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 } finally {\n disposeIfPresent(event);\n }\n }\n}\n\ntype DisposableResource = {\n [Symbol.dispose](): void;\n};\n\nfunction isDisposableResource(value: unknown): value is DisposableResource {\n return (\n !!value &&\n typeof value === \"object\" &&\n Symbol.dispose in value &&\n typeof value[Symbol.dispose] === \"function\"\n );\n}\n\nfunction disposeIfPresent(value: unknown): void {\n if (isDisposableResource(value)) {\n value[Symbol.dispose]();\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuDA,MAAM,oCAAoB,IAAI,QAAgB;;;;;;;;;AAU9C,IAAa,gBAAb,cAKU,mBAAqD;CA8B7D,YAAY,KAAuB,KAAU;EAC3C,MAAM,KAAK,GAAG;EAVhB,KAAQ,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O,QAAQ;EACjB,UAAU;GACR,iBAAiB,KAAK;EACxB;CACF;AACF;AAMA,SAAS,qBAAqB,OAA6C;CACzE,OACE,CAAC,CAAC,SACF,OAAO,UAAU,YACjB,OAAO,WAAW,SAClB,OAAO,MAAM,OAAO,aAAa;AAErC;AAEA,SAAS,iBAAiB,OAAsB;CAC9C,IAAI,qBAAqB,KAAK,GAC5B,MAAM,OAAO,QAAQ,CAAC;AAE1B"}
|
package/package.json
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
"durable objects"
|
|
10
10
|
],
|
|
11
11
|
"type": "module",
|
|
12
|
-
"version": "0.14.
|
|
12
|
+
"version": "0.14.3",
|
|
13
13
|
"license": "MIT",
|
|
14
14
|
"repository": {
|
|
15
15
|
"directory": "packages/agents",
|
|
@@ -26,9 +26,11 @@
|
|
|
26
26
|
"dependencies": {
|
|
27
27
|
"@babel/plugin-proposal-decorators": "^7.29.7",
|
|
28
28
|
"@cfworker/json-schema": "^4.1.1",
|
|
29
|
+
"@cloudflare/codemode": "^0.3.8",
|
|
29
30
|
"@modelcontextprotocol/sdk": "1.29.0",
|
|
30
31
|
"@rolldown/plugin-babel": "^0.2.3",
|
|
31
32
|
"cron-schedule": "^6.0.0",
|
|
33
|
+
"just-bash": "^3.0.1",
|
|
32
34
|
"mimetext": "^3.0.28",
|
|
33
35
|
"nanoid": "^5.1.11",
|
|
34
36
|
"partyserver": "^0.5.6",
|
|
@@ -37,32 +39,29 @@
|
|
|
37
39
|
"yargs": "^18.0.0"
|
|
38
40
|
},
|
|
39
41
|
"devDependencies": {
|
|
40
|
-
"@ai-sdk/react": "^3.0.
|
|
41
|
-
"@cloudflare/codemode": "^0.3.8",
|
|
42
|
+
"@ai-sdk/react": "^3.0.198",
|
|
42
43
|
"@cloudflare/worker-bundler": "^0.2.0",
|
|
43
|
-
"@tanstack/ai": "^0.
|
|
44
|
+
"@tanstack/ai": "^0.27.0",
|
|
44
45
|
"@types/react": "^19.2.16",
|
|
45
46
|
"@types/yargs": "^17.0.35",
|
|
46
47
|
"@vitest/browser-playwright": "^4.1.8",
|
|
47
48
|
"@x402/core": "^2.14.0",
|
|
48
49
|
"@x402/evm": "^2.14.0",
|
|
49
|
-
"ai": "^6.0.
|
|
50
|
+
"ai": "^6.0.196",
|
|
50
51
|
"chat": "^4.30.0",
|
|
51
|
-
"
|
|
52
|
+
"glob": "^11.1.0",
|
|
52
53
|
"react": "^19.2.7",
|
|
53
54
|
"vitest-browser-react": "^2.2.0",
|
|
54
55
|
"zod": "^4.4.3"
|
|
55
56
|
},
|
|
56
57
|
"peerDependencies": {
|
|
57
58
|
"@cloudflare/ai-chat": ">=0.8.0 <1.0.0",
|
|
58
|
-
"@cloudflare/codemode": ">=0.3.8 <1.0.0",
|
|
59
59
|
"@cloudflare/worker-bundler": ">=0.2.0 <1.0.0",
|
|
60
60
|
"@tanstack/ai": ">=0.10.2 <1.0.0",
|
|
61
61
|
"@x402/core": "^2.0.0",
|
|
62
62
|
"@x402/evm": "^2.0.0",
|
|
63
63
|
"ai": "^6.0.0",
|
|
64
64
|
"chat": "^4.29.0",
|
|
65
|
-
"just-bash": "^3.0.0",
|
|
66
65
|
"react": "^19.0.0",
|
|
67
66
|
"vite": ">=6.0.0 <9.0.0",
|
|
68
67
|
"zod": "^4.0.0"
|
|
@@ -71,9 +70,6 @@
|
|
|
71
70
|
"@cloudflare/ai-chat": {
|
|
72
71
|
"optional": true
|
|
73
72
|
},
|
|
74
|
-
"@cloudflare/codemode": {
|
|
75
|
-
"optional": true
|
|
76
|
-
},
|
|
77
73
|
"@cloudflare/worker-bundler": {
|
|
78
74
|
"optional": true
|
|
79
75
|
},
|
|
@@ -89,9 +85,6 @@
|
|
|
89
85
|
"chat": {
|
|
90
86
|
"optional": true
|
|
91
87
|
},
|
|
92
|
-
"just-bash": {
|
|
93
|
-
"optional": true
|
|
94
|
-
},
|
|
95
88
|
"vite": {
|
|
96
89
|
"optional": true
|
|
97
90
|
}
|
|
@@ -251,8 +244,7 @@
|
|
|
251
244
|
],
|
|
252
245
|
"nx": {
|
|
253
246
|
"implicitDependencies": [
|
|
254
|
-
"!@cloudflare/ai-chat"
|
|
255
|
-
"!@cloudflare/codemode"
|
|
247
|
+
"!@cloudflare/ai-chat"
|
|
256
248
|
]
|
|
257
249
|
},
|
|
258
250
|
"scripts": {
|
|
@@ -268,4 +260,4 @@
|
|
|
268
260
|
"test:x402": "vitest --project x402",
|
|
269
261
|
"test:e2e": "vitest --run -c src/e2e-tests/vitest.config.ts"
|
|
270
262
|
}
|
|
271
|
-
}
|
|
263
|
+
}
|