agents 0.31.0 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/dist/{agent-routing-wS1TimZ_.d.ts → agent-routing-vVMA7m8Y.d.ts} +6 -6
  2. package/dist/agent-routing.d.ts +1 -1
  3. package/dist/agent-tool-types.d.ts +1 -1
  4. package/dist/{agent-tools-Bamxxb6Y.d.ts → agent-tools-gGXXkf1z.d.ts} +2 -2
  5. package/dist/agent-tools.d.ts +1 -1
  6. package/dist/agent-tools.js +0 -1
  7. package/dist/agent-tools.js.map +1 -1
  8. package/dist/browser/ai.js +1 -1
  9. package/dist/browser/tools/ai-sdk.d.ts +66 -1
  10. package/dist/browser/tools/ai-sdk.js +2 -2
  11. package/dist/browser/tools/pi.js +2 -2
  12. package/dist/browser/tools/tanstack-ai.d.ts +2 -2
  13. package/dist/browser/tools/tanstack-ai.js +2 -2
  14. package/dist/browser/tools/tanstack-ai.js.map +1 -1
  15. package/dist/{browser-tool-lGnvEBLJ.js → browser-tool-DRan7Lk6.js} +2 -2
  16. package/dist/{browser-tool-lGnvEBLJ.js.map → browser-tool-DRan7Lk6.js.map} +1 -1
  17. package/dist/catalog-BpOejOsE.js +239 -0
  18. package/dist/catalog-BpOejOsE.js.map +1 -0
  19. package/dist/catalog-BpiVV1OF.d.ts +173 -0
  20. package/dist/chat/index.d.ts +2 -2
  21. package/dist/chat-sdk/index.d.ts +1 -1
  22. package/dist/chat-sdk/index.js +1 -1
  23. package/dist/{client-wn4-yqGz.d.ts → client-eSfgYvd3.d.ts} +2 -2
  24. package/dist/client.d.ts +1 -1
  25. package/dist/{cloudflare-Dzvc7V2N.js → cloudflare-CUUm_9q9.js} +26 -4
  26. package/dist/cloudflare-CUUm_9q9.js.map +1 -0
  27. package/dist/{do-oauth-client-provider-DfsUcpc3.d.ts → do-oauth-client-provider-DtNqv7oj.d.ts} +26 -2
  28. package/dist/{index-YSKgfgg9.d.ts → emitter-BJZtCVjQ.d.ts} +6 -140
  29. package/dist/emitter-DPOVcCln.js +15 -0
  30. package/dist/emitter-DPOVcCln.js.map +1 -0
  31. package/dist/experimental/channels/web/index.js +1 -1
  32. package/dist/harness/container/index.js +0 -1
  33. package/dist/harness/container/index.js.map +1 -1
  34. package/dist/harness/container/runtime/index.js +2 -2
  35. package/dist/harness/opencode/index.js +0 -1
  36. package/dist/harness/opencode/index.js.map +1 -1
  37. package/dist/harness/pi/index.d.ts +11 -4
  38. package/dist/harness/pi/index.js +43 -141
  39. package/dist/harness/pi/index.js.map +1 -1
  40. package/dist/index.d.ts +2 -3
  41. package/dist/index.js +2 -2
  42. package/dist/markdown-BZ-VLtA1.js +86 -0
  43. package/dist/markdown-BZ-VLtA1.js.map +1 -0
  44. package/dist/mcp/client/do-oauth-client-provider.d.ts +4 -2
  45. package/dist/mcp/client/do-oauth-client-provider.js +15 -1
  46. package/dist/mcp/client/do-oauth-client-provider.js.map +1 -1
  47. package/dist/mcp/client/index.d.ts +1 -1
  48. package/dist/mcp/index.d.ts +1 -1
  49. package/dist/mcp/index.js +1 -1
  50. package/dist/models/pi-ai/index.js +129 -2
  51. package/dist/models/pi-ai/index.js.map +1 -1
  52. package/dist/observability/ai/index.js +1 -2
  53. package/dist/observability/ai/index.js.map +1 -1
  54. package/dist/observability/index.d.ts +170 -9
  55. package/dist/observability/index.js +386 -11
  56. package/dist/observability/index.js.map +1 -1
  57. package/dist/react.d.ts +2 -2
  58. package/dist/resource-B59OV2a2.js +325 -0
  59. package/dist/resource-B59OV2a2.js.map +1 -0
  60. package/dist/routing/index.d.ts +1 -1
  61. package/dist/script-CFDLTk5b.d.ts +91 -0
  62. package/dist/script-workspace-BpdAYq1R.d.ts +41 -0
  63. package/dist/serializable.d.ts +1 -1
  64. package/dist/skill-DRBcIBjC.d.ts +221 -0
  65. package/dist/skills/index.d.ts +275 -36
  66. package/dist/skills/index.js +265 -1534
  67. package/dist/skills/index.js.map +1 -1
  68. package/dist/skills/runner.d.ts +37 -0
  69. package/dist/skills/runner.js +912 -0
  70. package/dist/skills/runner.js.map +1 -0
  71. package/dist/skills/tools/ai-sdk.d.ts +36 -0
  72. package/dist/skills/tools/ai-sdk.js +94 -0
  73. package/dist/skills/tools/ai-sdk.js.map +1 -0
  74. package/dist/source-9RQzlEhM.d.ts +112 -0
  75. package/dist/{src-BGolXG_H.js → src-DoGNJ4Ud.js} +4 -5
  76. package/dist/src-DoGNJ4Ud.js.map +1 -0
  77. package/dist/sub-routing.d.ts +1 -1
  78. package/dist/tool-CxKsvxjm.js.map +1 -1
  79. package/dist/tool-DkT_DJBm.js.map +1 -1
  80. package/dist/{tool-helpers-BodWi4gd.js → tool-helpers-BI7ifO2S.js} +1 -2
  81. package/dist/{tool-helpers-BodWi4gd.js.map → tool-helpers-BI7ifO2S.js.map} +1 -1
  82. package/dist/vite.d.ts +2 -2
  83. package/dist/vite.js +10 -258
  84. package/dist/vite.js.map +1 -1
  85. package/dist/voice/index.d.ts +1 -1
  86. package/dist/websockets/index.js +1 -1
  87. package/dist/{websockets-CyoeosdO.js → websockets-C6SJtWCJ.js} +1 -2
  88. package/dist/{websockets-CyoeosdO.js.map → websockets-C6SJtWCJ.js.map} +1 -1
  89. package/dist/workflow-types.d.ts +1 -1
  90. package/dist/workflows.d.ts +1 -1
  91. package/dist/workflows.js +0 -1
  92. package/dist/workflows.js.map +1 -1
  93. package/docs/harnesses/pi.md +9 -3
  94. package/docs/mcp-client.md +23 -1
  95. package/docs/mcp-servers.md +2 -2
  96. package/docs/observability.md +5 -3
  97. package/package.json +24 -15
  98. package/dist/ai-sdk-hW3vntnk.d.ts +0 -72
  99. package/dist/cloudflare-Dzvc7V2N.js.map +0 -1
  100. package/dist/index-iv9FTXX9.d.ts +0 -311
  101. package/dist/skills/compile.d.ts +0 -40
  102. package/dist/skills/compile.js +0 -65
  103. package/dist/skills/compile.js.map +0 -1
  104. package/dist/src-BGolXG_H.js.map +0 -1
  105. package/skills-module.d.ts +0 -22
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["parseYaml","extensionOf"],"sources":["../../src/skills/frontmatter.ts","../../src/skills/types.ts","../../src/skills/manifest.ts","../../src/skills/r2.ts","../../src/skills/workspace.ts","../../src/skills/runner.ts","../../src/skills/registry.ts"],"sourcesContent":["import { parse as parseYaml } from \"yaml\";\n\nexport interface ParsedSkillMarkdown {\n data: Record<string, unknown>;\n body: string;\n}\n\nexport function parseSkillFrontmatter(raw: string): ParsedSkillMarkdown {\n const match = raw.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n?([\\s\\S]*)$/);\n if (!match) return { data: {}, body: raw };\n\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\n return { data, body: match[2] ?? \"\" };\n}\n\nfunction optionalString(value: unknown): string | undefined {\n return typeof value === \"string\" && value.trim() ? value.trim() : undefined;\n}\n\nfunction optionalRecord(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\nexport function parseSkillMarkdown(raw: string): {\n name: string;\n description: string;\n body: string;\n compatibility?: string;\n license?: string;\n allowedTools?: string;\n metadata?: Record<string, unknown>;\n} | null {\n const { data, body } = parseSkillFrontmatter(raw);\n const name = optionalString(data.name);\n const description = optionalString(data.description);\n\n if (!name || !description) return null;\n\n return {\n name,\n description,\n body,\n compatibility: optionalString(data.compatibility),\n license: optionalString(data.license),\n allowedTools: optionalString(data[\"allowed-tools\"]),\n metadata: optionalRecord(data.metadata)\n };\n}\n","export interface SkillDescriptor {\n name: string;\n description: string;\n compatibility?: string;\n license?: string;\n allowedTools?: string;\n metadata?: Record<string, unknown>;\n sourceId?: string;\n version?: string;\n}\n\nexport interface SkillContent extends SkillDescriptor {\n body: string;\n rawContent?: string;\n resources?: SkillResourceDescriptor[];\n}\n\nexport interface SkillResourceDescriptor {\n path: string;\n kind: \"reference\" | \"script\" | \"asset\" | \"file\";\n size?: number;\n encoding?: \"text\" | \"base64\";\n mimeType?: string;\n /**\n * Set when a script resource was compiled to a self-contained JavaScript\n * module ahead of time — by the Agents Vite plugin for bundled skills, or via\n * `compileSkillScript` from `agents/skills/compile` for R2/dynamic skills. The\n * runtime runs precompiled scripts directly; the runtime ships no in-Worker\n * bundler, so non-precompiled TypeScript or multi-file scripts cannot run.\n */\n precompiled?: boolean;\n}\n\nexport interface SkillResource extends SkillResourceDescriptor {\n content: string;\n}\n\nexport interface SkillScriptContext {\n skill: SkillDescriptor;\n}\n\n/**\n * The `ctx` object passed as the second argument to function-style JS/TS\n * skill scripts (`export default async function run(input, ctx)`).\n *\n * Capabilities are gated by the runner: `workspace` throws unless workspace\n * access is enabled, and `tools` only resolves tools the runner was given.\n */\nexport interface SkillRunContext {\n /** Metadata for the skill that owns this script. */\n skill: SkillDescriptor;\n /** Text bundled resources by relative path (e.g. `references/style-guide.md`). */\n files: Record<string, string>;\n /** Workspace access, gated by the runner's `workspace` permission. */\n workspace: {\n readFile(path: string): Promise<string | null>;\n listFiles(path?: string): Promise<unknown>;\n glob(pattern: string): Promise<unknown>;\n stat(path: string): Promise<{ type: string; size: number } | null>;\n writeFile(path: string, content: string): Promise<void>;\n };\n /** Explicitly granted tools: `tools.call(name, input)` or `tools.<name>(input)`. */\n tools: {\n call(name: string, input?: unknown): Promise<unknown>;\n } & Record<string, (input?: unknown) => Promise<unknown>>;\n /** Scratch artifacts returned to the model as `outputFiles`. */\n output: {\n writeFile(name: string, content: string): Promise<void>;\n };\n}\n\nexport interface SkillScriptRequest {\n skill: SkillContent;\n path: string;\n source: string;\n input: unknown;\n resources?: SkillResource[];\n}\n\nexport interface SkillScriptRunner {\n run(request: SkillScriptRequest): Promise<unknown>;\n}\n\nexport interface SkillSource {\n id: string;\n fingerprint: string;\n list(): Promise<SkillDescriptor[]>;\n load(name: string): Promise<SkillContent | null>;\n readResource?(name: string, path: string): Promise<SkillResource | null>;\n refresh?(): Promise<void>;\n}\n\nexport interface SkillManifestResource extends SkillResourceDescriptor {\n content: string;\n}\n\nexport interface SkillManifestEntry {\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 version?: string;\n resources?: SkillManifestResource[];\n}\n\nexport interface SkillManifest {\n id: string;\n fingerprint: string;\n skills: SkillManifestEntry[];\n}\n\nexport interface SkillRegistrySnapshot {\n fingerprint: string;\n catalogPrompt: string | null;\n}\n\nexport function validateSkillResourcePath(path: string): string | null {\n if (\n path.startsWith(\"/\") ||\n path.includes(\"\\0\") ||\n path.split(\"/\").some((part) => part === \"\" || part === \".\" || part === \"..\")\n ) {\n return `Skill resource path must be a normalized relative path: ${path}`;\n }\n return null;\n}\n","import type {\n SkillContent,\n SkillDescriptor,\n SkillManifest,\n SkillManifestEntry,\n SkillResource,\n SkillSource\n} from \"./types\";\nimport { validateSkillResourcePath } from \"./types\";\n\nfunction descriptorFromEntry(\n sourceId: string,\n entry: SkillManifestEntry\n): SkillDescriptor {\n return {\n name: entry.name,\n description: entry.description,\n compatibility: entry.compatibility,\n license: entry.license,\n allowedTools: entry.allowedTools,\n metadata: entry.metadata,\n sourceId,\n version: entry.version\n };\n}\n\nfunction contentFromEntry(\n sourceId: string,\n entry: SkillManifestEntry\n): SkillContent {\n return {\n ...descriptorFromEntry(sourceId, entry),\n body: entry.body,\n rawContent: entry.rawContent,\n resources: entry.resources\n ?.filter((resource) => validateSkillResourcePath(resource.path) === null)\n .map(({ content: _content, ...resource }) => ({\n ...resource\n }))\n };\n}\n\nexport function fromManifest(manifest: SkillManifest): SkillSource {\n const byName = new Map(manifest.skills.map((skill) => [skill.name, skill]));\n\n return {\n id: manifest.id,\n fingerprint: manifest.fingerprint,\n async list() {\n return manifest.skills.map((skill) =>\n descriptorFromEntry(manifest.id, skill)\n );\n },\n async load(name: string) {\n const skill = byName.get(name);\n return skill ? contentFromEntry(manifest.id, skill) : null;\n },\n async readResource(\n name: string,\n path: string\n ): Promise<SkillResource | null> {\n const skill = byName.get(name);\n if (validateSkillResourcePath(path) !== null) return null;\n const resource = skill?.resources?.find((entry) => entry.path === path);\n if (resource && validateSkillResourcePath(resource.path) !== null) {\n return null;\n }\n return resource ? { ...resource } : null;\n }\n };\n}\n","import { parseSkillMarkdown } from \"./frontmatter\";\nimport type {\n SkillContent,\n SkillDescriptor,\n SkillResource,\n SkillResourceDescriptor,\n SkillSource\n} from \"./types\";\nimport { validateSkillResourcePath } from \"./types\";\n\nexport interface R2SkillSourceOptions {\n prefix?: string;\n skills?: string[];\n id?: string;\n fingerprint?: \"metadata\" | \"content\";\n refreshIntervalMs?: number;\n}\n\ntype ListedObject = Pick<R2Object, \"key\" | \"etag\" | \"size\" | \"uploaded\">;\n\ninterface IndexedSkill {\n descriptor: SkillDescriptor;\n content: SkillContent;\n directory: string;\n}\n\nfunction normalizePrefix(prefix: string | undefined): string {\n if (!prefix) return \"\";\n return prefix.endsWith(\"/\") ? prefix : `${prefix}/`;\n}\n\nfunction resourceKind(path: string): SkillResourceDescriptor[\"kind\"] {\n if (path.startsWith(\"references/\")) return \"reference\";\n if (path.startsWith(\"scripts/\")) return \"script\";\n if (path.startsWith(\"assets/\")) return \"asset\";\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\nfunction base64Encode(bytes: ArrayBuffer): string {\n let binary = \"\";\n const view = new Uint8Array(bytes);\n for (let i = 0; i < view.length; i++) {\n binary += String.fromCharCode(view[i]!);\n }\n return btoa(binary);\n}\n\nasync function readObjectFingerprint(\n bucket: R2Bucket,\n key: string,\n path: string\n): Promise<string | null> {\n const object = await bucket.get(key);\n if (!object) return null;\n const encoding = resourceEncoding(path);\n const content =\n encoding === \"base64\"\n ? base64Encode(await object.arrayBuffer())\n : await object.text();\n return `${encoding}:${content}`;\n}\n\nfunction stableHash(parts: string[]): string {\n let hash = 0x811c9dc5;\n for (const part of parts) {\n for (let i = 0; i < part.length; i++) {\n hash ^= part.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193);\n }\n // Fold a boundary between parts so that, e.g., [\"ab\", \"cd\"] and [\"abcd\"]\n // hash differently (otherwise the concatenated char stream is identical).\n hash ^= 0xff;\n hash = Math.imul(hash, 0x01000193);\n }\n return (hash >>> 0).toString(36);\n}\n\nfunction objectFingerprintPart(object: ListedObject): string {\n return [\n object.key,\n String(object.size),\n object.etag,\n object.uploaded?.toISOString() ?? \"\"\n ].join(\":\");\n}\n\nasync function listAllObjects(\n bucket: R2Bucket,\n prefix: string\n): Promise<ListedObject[]> {\n const objects: ListedObject[] = [];\n let cursor: string | undefined;\n let truncated = true;\n\n while (truncated) {\n const listed = await bucket.list({ prefix, cursor });\n objects.push(...listed.objects);\n truncated = listed.truncated;\n cursor = listed.truncated ? listed.cursor : undefined;\n }\n\n return objects.sort((a, b) => a.key.localeCompare(b.key));\n}\n\nasync function readObject(\n bucket: R2Bucket,\n key: string\n): Promise<string | null> {\n const object = await bucket.get(key);\n return object ? object.text() : null;\n}\n\nasync function readResourceObject(\n bucket: R2Bucket,\n key: string,\n descriptor: SkillResourceDescriptor\n): Promise<SkillResource | null> {\n const object = await bucket.get(key);\n if (!object) return null;\n\n const encoding = descriptor.encoding ?? resourceEncoding(descriptor.path);\n const content =\n encoding === \"base64\"\n ? base64Encode(await object.arrayBuffer())\n : await object.text();\n\n return {\n ...descriptor,\n encoding,\n content\n };\n}\n\nexport function r2(\n bucket: R2Bucket,\n options: R2SkillSourceOptions = {}\n): SkillSource {\n const prefix = normalizePrefix(options.prefix);\n const id = options.id ?? `r2:${prefix || \"/\"}`;\n const allowedSkills = options.skills?.length ? new Set(options.skills) : null;\n const fingerprintMode = options.fingerprint ?? \"metadata\";\n const refreshIntervalMs = options.refreshIntervalMs ?? 60_000;\n let fingerprint = id;\n let loaded = false;\n let indexedAt = 0;\n let byName = new Map<string, IndexedSkill>();\n let resourcesByName = new Map<string, SkillResourceDescriptor[]>();\n\n async function refreshIndex(force = false): Promise<void> {\n if (loaded && !force && Date.now() - indexedAt < refreshIntervalMs) {\n return;\n }\n\n const objects = await listAllObjects(bucket, prefix);\n const objectsByKey = new Map(objects.map((object) => [object.key, object]));\n const skillDirectories = objects\n .map((object) => object.key.slice(prefix.length))\n .filter((key) => key.endsWith(\"/SKILL.md\"))\n .map((key) => key.slice(0, -\"SKILL.md\".length - 1))\n .filter((directory) => directory && !directory.includes(\"/\"));\n\n const nextByName = new Map<string, IndexedSkill>();\n const nextResourcesByName = new Map<string, SkillResourceDescriptor[]>();\n const fingerprintParts: string[] = [];\n\n for (const directory of skillDirectories) {\n const skillKey = `${prefix}${directory}/SKILL.md`;\n const rawContent = await readObject(bucket, skillKey);\n if (!rawContent) continue;\n\n const parsed = parseSkillMarkdown(rawContent);\n if (!parsed || allowedSkills?.has(parsed.name) === false) continue;\n\n const resourceKeys = objects\n .map((object) => object.key)\n .filter(\n (key) => key.startsWith(`${prefix}${directory}/`) && key !== skillKey\n )\n .filter(\n (key) =>\n validateSkillResourcePath(\n key.slice(`${prefix}${directory}/`.length)\n ) === null\n );\n const resources: SkillResourceDescriptor[] = [];\n\n for (const key of resourceKeys) {\n const path = key.slice(`${prefix}${directory}/`.length);\n const listedResource = objectsByKey.get(key);\n\n resources.push({\n path,\n kind: resourceKind(path),\n size: listedResource?.size,\n encoding: resourceEncoding(path),\n mimeType: resourceMimeType(path)\n });\n }\n\n const descriptor: SkillDescriptor = {\n name: parsed.name,\n description: parsed.description,\n compatibility: parsed.compatibility,\n license: parsed.license,\n allowedTools: parsed.allowedTools,\n metadata: parsed.metadata,\n sourceId: id\n };\n const content: SkillContent = {\n ...descriptor,\n body: parsed.body,\n rawContent,\n resources: resources.map((resource) => ({ ...resource }))\n };\n\n if (!nextByName.has(parsed.name)) {\n nextByName.set(parsed.name, { descriptor, content, directory });\n nextResourcesByName.set(parsed.name, resources);\n }\n\n const skillObjects = [skillKey, ...resourceKeys]\n .map((key) => objectsByKey.get(key))\n .filter((object): object is ListedObject => Boolean(object));\n if (fingerprintMode === \"content\") {\n fingerprintParts.push(rawContent);\n for (const key of resourceKeys) {\n const path = key.slice(`${prefix}${directory}/`.length);\n fingerprintParts.push(\n (await readObjectFingerprint(bucket, key, path)) ?? \"\"\n );\n }\n } else {\n fingerprintParts.push(...skillObjects.map(objectFingerprintPart));\n }\n }\n\n byName = nextByName;\n resourcesByName = nextResourcesByName;\n fingerprint = `${id}:${stableHash(fingerprintParts)}`;\n loaded = true;\n indexedAt = Date.now();\n }\n\n return {\n id,\n get fingerprint() {\n return fingerprint;\n },\n async list() {\n await refreshIndex();\n return [...byName.values()].map(({ descriptor }) => ({ ...descriptor }));\n },\n async load(name: string) {\n await refreshIndex();\n const skill = byName.get(name);\n return skill ? { ...skill.content } : null;\n },\n async readResource(name: string, path: string) {\n if (validateSkillResourcePath(path) !== null) return null;\n await refreshIndex();\n const skill = byName.get(name);\n if (!skill) return null;\n\n const resource = resourcesByName\n .get(name)\n ?.find((entry) => entry.path === path);\n if (!resource) return null;\n\n return readResourceObject(\n bucket,\n `${prefix}${skill.directory}/${path}`,\n resource\n );\n },\n async refresh() {\n await refreshIndex();\n }\n };\n}\n","import type { SkillResource } from \"./types\";\n\n/**\n * The Workspace Agent Skills read and write: a `Workspace` from\n * `@cloudflare/computer`, or anything with the same `fs` methods.\n */\nexport interface SkillWorkspace {\n readonly fs: {\n stat(path: string): Promise<{ size: number; isDirectory: boolean }>;\n readFile(path: string): Promise<ReadableStream<Uint8Array>>;\n writeFile(path: string, content: Uint8Array): Promise<void>;\n mkdir(path: string, options?: { recursive?: boolean }): Promise<void>;\n readdir(\n path: string\n ): Promise<Array<{ name: string; size: number; isDirectory: boolean }>>;\n find(\n directory: string,\n pattern?: string\n ): Promise<Array<{ path: string; type: \"file\" | \"dir\" }>>;\n };\n}\n\n/** Options for projecting Agent Skills into a Workspace. */\nexport interface SkillWorkspaceSeedOptions {\n /** Destination directory. Defaults to `/workspace/.agents/skills`. */\n readonly root?: string;\n /** Existing-file policy. Default `\"preserve\"` keeps Workspace edits. */\n readonly onConflict?: \"preserve\" | \"replace\";\n}\n\n/** Summary returned after projecting Agent Skills into a Workspace. */\nexport interface SkillWorkspaceSeedResult {\n /** Files written from source content. */\n readonly written: number;\n /** Existing files preserved without a write. */\n readonly preserved: number;\n /** Files skipped because their source content could not be read or written. */\n readonly skipped: number;\n /** Non-fatal per-file diagnostics. */\n readonly warnings: readonly string[];\n /** Absolute Workspace directory containing the projected skills. */\n readonly root: string;\n}\n\n/** @internal File operations used by SkillRegistry after projection. */\nexport interface SkillWorkspaceFiles {\n readonly root: string;\n path(name: string, relativePath: string): string;\n exists(path: string): Promise<boolean>;\n readText(path: string): Promise<string | null>;\n readResource(\n path: string,\n descriptor: Omit<SkillResource, \"content\">\n ): Promise<SkillResource | null>;\n writeText(path: string, content: string): Promise<void>;\n writeResource(path: string, resource: SkillResource): Promise<void>;\n}\n\n/** Directory skill scripts and relative paths resolve against. */\nconst WORKSPACE_ROOT = \"/workspace\";\nconst TEXT_ENCODER = new TextEncoder();\nconst TEXT_DECODER = new TextDecoder();\n\n/** @internal Adapt a Workspace for projecting skills into it. */\nexport function createSkillWorkspaceFiles(\n workspace: SkillWorkspace,\n rootOverride?: string\n): SkillWorkspaceFiles {\n const root = parseRoot(rootOverride ?? `${WORKSPACE_ROOT}/.agents/skills`);\n const access = createSkillWorkspaceAccess(workspace);\n\n const readBytes = async (path: string): Promise<Uint8Array | null> => {\n try {\n return await drain(await workspace.fs.readFile(path));\n } catch (error) {\n if (isNotFound(error)) return null;\n throw error;\n }\n };\n\n return {\n root,\n path(name, relativePath) {\n const safeName = parseSkillDirectoryName(name);\n const safeRelative = parseRelativePath(relativePath);\n return `${root}/${safeName}/${safeRelative}`;\n },\n async exists(path) {\n return (await access.stat(path)) !== null;\n },\n readText: (path) => access.readFile(path),\n async readResource(path, descriptor) {\n const encoding = descriptor.encoding ?? \"text\";\n if (encoding === \"text\") {\n const content = await access.readFile(path);\n return content === null ? null : { ...descriptor, content };\n }\n const bytes = await readBytes(path);\n return bytes === null\n ? null\n : { ...descriptor, content: encodeBase64(bytes) };\n },\n writeText: (path, content) => access.writeFile(path, content),\n async writeResource(path, resource) {\n await access.writeFile(\n path,\n (resource.encoding ?? \"text\") === \"text\"\n ? resource.content\n : decodeBase64(resource.content)\n );\n }\n };\n}\n\n/** @internal File operations a skill script reaches through its host. */\nexport interface SkillWorkspaceAccess {\n /** Read UTF-8 text, or `null` when the file does not exist. */\n readFile(path: string): Promise<string | null>;\n /** List a directory. */\n listFiles(\n path: string\n ): Promise<Array<{ path: string; name: string; type: string; size: number }>>;\n /** Find paths matching a glob. */\n glob(\n pattern: string\n ): Promise<Array<{ path: string; type: string; size: number }>>;\n /** Describe a path, or `null` when it does not exist. */\n stat(path: string): Promise<{ type: string; size: number } | null>;\n /** Write a file, creating missing parent directories. */\n writeFile(path: string, content: string | Uint8Array): Promise<void>;\n}\n\n/**\n * @internal Adapt a Workspace for skill scripts. Relative paths resolve\n * against `/workspace`.\n */\nexport function createSkillWorkspaceAccess(\n workspace: SkillWorkspace\n): SkillWorkspaceAccess {\n const { fs } = workspace;\n const access: SkillWorkspaceAccess = {\n async readFile(path) {\n try {\n return TEXT_DECODER.decode(\n await drain(await fs.readFile(resolvePath(path)))\n );\n } catch (error) {\n if (isNotFound(error)) return null;\n throw error;\n }\n },\n async listFiles(path) {\n const directory = resolvePath(path);\n const entries = await fs.readdir(directory);\n return entries.map((entry) => ({\n path: `${directory.replace(/\\/$/, \"\")}/${entry.name}`,\n name: entry.name,\n type: entry.isDirectory ? \"directory\" : \"file\",\n size: entry.size\n }));\n },\n async glob(pattern) {\n const segments = resolvePath(pattern).split(\"/\").filter(Boolean);\n const firstGlob = segments.findIndex((part) => /[*?[\\]{}]/.test(part));\n if (firstGlob === -1) {\n const path = `/${segments.join(\"/\")}`;\n const found = await access.stat(path);\n return found === null ? [] : [{ path, ...found }];\n }\n let matches: Array<{ path: string; type: \"file\" | \"dir\" }>;\n try {\n matches = await fs.find(\n `/${segments.slice(0, firstGlob).join(\"/\")}`,\n segments.slice(firstGlob).join(\"/\")\n );\n } catch (error) {\n if (isNotFound(error)) return [];\n throw error;\n }\n return Promise.all(\n matches.map(async (match) =>\n match.type === \"dir\"\n ? { path: match.path, type: \"directory\", size: 0 }\n : {\n path: match.path,\n type: \"file\",\n size: (await fs.stat(match.path)).size\n }\n )\n );\n },\n async stat(path) {\n try {\n const info = await fs.stat(resolvePath(path));\n return {\n type: info.isDirectory ? \"directory\" : \"file\",\n size: info.size\n };\n } catch (error) {\n if (isNotFound(error)) return null;\n throw error;\n }\n },\n async writeFile(path, content) {\n const absolute = resolvePath(path);\n const parent = absolute.slice(0, absolute.lastIndexOf(\"/\"));\n if (parent) await fs.mkdir(parent, { recursive: true });\n await fs.writeFile(\n absolute,\n typeof content === \"string\" ? TEXT_ENCODER.encode(content) : content\n );\n }\n };\n return access;\n}\n\nfunction resolvePath(path: string): string {\n if (path.startsWith(\"/\")) return path;\n const relative = path.replace(/^\\.(\\/|$)/, \"\");\n return relative === \"\" ? WORKSPACE_ROOT : `${WORKSPACE_ROOT}/${relative}`;\n}\n\nfunction parseRoot(root: string): string {\n if (\n !root.startsWith(\"/\") ||\n root.includes(\"\\0\") ||\n root.split(\"/\").some((part) => part === \".\" || part === \"..\")\n ) {\n throw new Error(\n `Skill Workspace root must be a normalized absolute path: ${root}`\n );\n }\n const normalized = root.replace(/\\/{2,}/g, \"/\").replace(/\\/$/, \"\");\n if (!normalized) throw new Error(\"Skill Workspace root cannot be /\");\n return normalized;\n}\n\nfunction parseSkillDirectoryName(name: string): string {\n if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name)) {\n throw new Error(\n `Skill name must be a safe Workspace directory name: ${name}`\n );\n }\n return name;\n}\n\nfunction parseRelativePath(path: string): string {\n if (\n path.startsWith(\"/\") ||\n path.includes(\"\\0\") ||\n path.split(\"/\").some((part) => part === \"\" || part === \".\" || part === \"..\")\n ) {\n throw new Error(`Skill file path must be normalized and relative: ${path}`);\n }\n return path;\n}\n\nfunction isNotFound(error: unknown): boolean {\n if (!error || typeof error !== \"object\") return false;\n const record = error as { code?: unknown; message?: unknown };\n return (\n record.code === \"ENOENT\" ||\n (typeof record.message === \"string\" &&\n /ENOENT|no such file|not found/i.test(record.message))\n );\n}\n\nasync function drain(stream: ReadableStream<Uint8Array>): Promise<Uint8Array> {\n const parts: Uint8Array[] = [];\n let total = 0;\n const reader = stream.getReader();\n try {\n while (true) {\n const { value, done } = await reader.read();\n if (done) break;\n if (!value || value.byteLength === 0) continue;\n parts.push(value);\n total += value.byteLength;\n }\n } finally {\n reader.releaseLock();\n }\n if (parts.length === 1) return parts[0];\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const part of parts) {\n bytes.set(part, offset);\n offset += part.byteLength;\n }\n return bytes;\n}\n\nfunction decodeBase64(value: string): Uint8Array {\n const binary = atob(value);\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index++) {\n bytes[index] = binary.charCodeAt(index);\n }\n return bytes;\n}\n\nfunction encodeBase64(bytes: Uint8Array): string {\n const parts: string[] = [];\n for (let offset = 0; offset < bytes.byteLength; offset += 0x8000) {\n parts.push(String.fromCharCode(...bytes.subarray(offset, offset + 0x8000)));\n }\n return btoa(parts.join(\"\"));\n}\n","import { RpcTarget } from \"cloudflare:workers\";\nimport { DynamicWorkerExecutor, resolveProvider } from \"@cloudflare/codemode\";\nimport type { ToolProvider } from \"@cloudflare/codemode\";\nimport { Bash, defineCommand } from \"just-bash\";\nimport type { ToolSet } from \"ai\";\nimport type {\n SkillScriptRequest,\n SkillScriptRunner,\n SkillScriptContext\n} from \"./types\";\nimport { validateSkillResourcePath } from \"./types\";\nimport {\n createSkillWorkspaceAccess,\n type SkillWorkspace,\n type SkillWorkspaceAccess\n} from \"./workspace\";\n\n/**\n * Options for {@link runner}.\n *\n * @experimental Skill script execution is experimental and the option shape\n * may change before stabilizing.\n */\nexport interface WorkerSkillScriptRunnerOptions {\n loader: WorkerLoader;\n timeout?: number;\n network?: boolean;\n workspace?: \"none\" | \"read\" | \"read-write\";\n workspaceInstance?: SkillWorkspace;\n tools?: ToolSet | (() => ToolSet | Promise<ToolSet>);\n}\n\ntype SkillScriptRuntime = \"javascript\" | \"typescript\" | \"python\" | \"bash\";\ntype WorkspaceAccess = \"none\" | \"read\" | \"read-write\";\n\nconst DEFAULT_SCRIPT_TIMEOUT_MS = 30_000;\nconst MAX_OUTPUT_ARTIFACT_BYTES = 64_000;\nconst MAX_OUTPUT_ARTIFACTS = 20;\n\nconst SUPPORTED_SCRIPT_EXTENSIONS = new Set([\n \".js\",\n \".mjs\",\n \".ts\",\n \".tsx\",\n \".py\",\n \".sh\",\n \".bash\"\n]);\n\n// Logged once per isolate the first time a skill script actually runs.\nlet runnerExperimentalWarned = false;\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 effectiveTimeout(options: WorkerSkillScriptRunnerOptions): number {\n return options.timeout ?? DEFAULT_SCRIPT_TIMEOUT_MS;\n}\n\nfunction effectiveWorkspaceAccess(\n options: WorkerSkillScriptRunnerOptions\n): WorkspaceAccess {\n if (options.workspace) return options.workspace;\n return options.workspaceInstance ? \"read\" : \"none\";\n}\n\nexport function validateSkillScriptPath(path: string):\n | {\n ok: true;\n runtime: SkillScriptRuntime;\n }\n | {\n ok: false;\n error: string;\n } {\n if (!path.startsWith(\"scripts/\")) {\n return {\n ok: false,\n error: `Skill script path must start with \"scripts/\": ${path}`\n };\n }\n\n if (\n path.startsWith(\"/\") ||\n path.includes(\"\\0\") ||\n path.split(\"/\").some((part) => part === \"\" || part === \".\" || part === \"..\")\n ) {\n return {\n ok: false,\n error: `Skill script path must be a normalized relative path under \"scripts/\": ${path}`\n };\n }\n\n const extension = extensionOf(path);\n if (!SUPPORTED_SCRIPT_EXTENSIONS.has(extension)) {\n return {\n ok: false,\n error: `Unsupported skill script extension \"${extension || \"(none)\"}\" for ${path}. Supported extensions: ${[...SUPPORTED_SCRIPT_EXTENSIONS].join(\", \")}`\n };\n }\n\n if (extension === \".sh\" || extension === \".bash\") {\n return { ok: true, runtime: \"bash\" };\n }\n if (extension === \".py\") {\n return { ok: true, runtime: \"python\" };\n }\n if (extension === \".ts\" || extension === \".tsx\") {\n return { ok: true, runtime: \"typescript\" };\n }\n return { ok: true, runtime: \"javascript\" };\n}\n\nfunction validateMountedResourcePaths(request: SkillScriptRequest): void {\n for (const resource of request.resources ?? []) {\n const pathError = validateSkillResourcePath(resource.path);\n if (pathError) throw new Error(pathError);\n }\n}\n\nfunction skillScriptContext(request: SkillScriptRequest): SkillScriptContext {\n return {\n skill: {\n name: request.skill.name,\n description: request.skill.description,\n compatibility: request.skill.compatibility,\n license: request.skill.license,\n allowedTools: request.skill.allowedTools,\n metadata: request.skill.metadata,\n sourceId: request.skill.sourceId,\n version: request.skill.version\n }\n };\n}\n\n/**\n * Text bundled resources exposed to function-style JS/TS scripts via\n * `ctx.files`. Binary resources are omitted in v1.\n */\nfunction textFilesMap(request: SkillScriptRequest): Record<string, string> {\n const files: Record<string, string> = {};\n for (const resource of request.resources ?? []) {\n if ((resource.encoding ?? \"text\") === \"text\") {\n files[resource.path] = resource.content;\n }\n }\n return files;\n}\n\nfunction base64ToBytes(value: string): Uint8Array {\n const binary = atob(value);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n}\n\nfunction stdinText(stdin: unknown): string {\n return typeof stdin === \"string\" ? stdin : String(stdin ?? \"\");\n}\n\n// ── Python / Bash file mounting (path-based contract) ─────────────────\n\nfunction mountedFiles(request: SkillScriptRequest): Record<\n string,\n {\n content: string;\n encoding: \"text\" | \"base64\";\n }\n> {\n const files: Record<\n string,\n {\n content: string;\n encoding: \"text\" | \"base64\";\n }\n > = {\n \"/input.json\": {\n content: JSON.stringify(request.input),\n encoding: \"text\"\n },\n \"/context.json\": {\n content: JSON.stringify(skillScriptContext(request)),\n encoding: \"text\"\n },\n \"/skill/SKILL.md\": {\n content: request.skill.rawContent ?? request.skill.body,\n encoding: \"text\"\n }\n };\n\n for (const resource of request.resources ?? []) {\n const pathError = validateSkillResourcePath(resource.path);\n if (pathError) throw new Error(pathError);\n files[`/skill/${resource.path}`] = {\n content: resource.content,\n encoding: resource.encoding ?? \"text\"\n };\n }\n files[`/skill/${request.path}`] = {\n content: request.source,\n encoding: \"text\"\n };\n\n return files;\n}\n\nfunction bashFiles(\n request: SkillScriptRequest\n): Record<string, string | Uint8Array> {\n const files: Record<string, string | Uint8Array> = {\n \"/input.json\": JSON.stringify(request.input),\n \"/context.json\": JSON.stringify(skillScriptContext(request)),\n \"/skill-script.sh\": request.source,\n \"/skill/SKILL.md\": request.skill.rawContent ?? request.skill.body,\n [`/skill/${request.path}`]: request.source\n };\n\n for (const resource of request.resources ?? []) {\n const pathError = validateSkillResourcePath(resource.path);\n if (pathError) throw new Error(pathError);\n files[`/skill/${resource.path}`] =\n (resource.encoding ?? \"text\") === \"base64\"\n ? base64ToBytes(resource.content)\n : resource.content;\n }\n\n return files;\n}\n\n// ── JS/TS function-style wrapper ──────────────────────────────────────\n\n/**\n * Wrap a function-style JS/TS skill module so it runs inside the codemode\n * sandbox. The module must `export default` an async `run(input, ctx)`; we\n * rewrite the default export to a local binding, build the `ctx` capability\n * object from the host bridge proxy (`__host`), and invoke it.\n */\nfunction scriptModule(source: string, request: SkillScriptRequest): string {\n const runnableSource = stripStrayExports(\n source.replace(/^\\s*export\\s+default\\s+/m, \"const __skillRun = \")\n );\n const skillMeta = skillScriptContext(request).skill;\n\n return [\n \"async () => {\",\n ` const input = ${JSON.stringify(request.input)};`,\n ` const __skill = ${JSON.stringify(skillMeta)};`,\n ` const __files = ${JSON.stringify(textFilesMap(request))};`,\n \" const workspace = {\",\n \" readFile: (path) => __host.readFile(path),\",\n ' listFiles: (path = \".\") => __host.listFiles(path),',\n \" glob: (pattern) => __host.glob(pattern),\",\n \" stat: (path) => __host.stat(path),\",\n \" writeFile: (path, content) => __host.writeFile({ path, content })\",\n \" };\",\n \" const tools = new Proxy(\",\n \" { call: (name, input) => __host.callTool({ name, input }) },\",\n \" {\",\n \" get: (target, prop) =>\",\n \" prop in target\",\n \" ? target[prop]\",\n \" : (input) => __host.callTool({ name: String(prop), input })\",\n \" }\",\n \" );\",\n \" const output = {\",\n \" writeFile: (name, content) => __host.writeOutput({ name, content })\",\n \" };\",\n \" const ctx = { skill: __skill, files: __files, workspace, tools, output };\",\n \"\",\n runnableSource,\n \"\",\n ' if (typeof __skillRun !== \"function\") {',\n ' throw new Error(\"Skill script default export must be a function (input, ctx).\");',\n \" }\",\n \" return await __skillRun(input, ctx);\",\n \"}\"\n ].join(\"\\n\");\n}\n\n/**\n * Whether a script declares a default export, in either the raw author form\n * (`export default ...`) or the bundled form esbuild emits\n * (`export { run as default }`).\n */\nfunction hasDefaultExport(source: string): boolean {\n return (\n /^\\s*export\\s+default\\s+/m.test(source) ||\n /export\\s*\\{[^}]*\\bas\\s+default\\b[^}]*\\}/m.test(source)\n );\n}\n\n/**\n * Remove `export { ... }` blocks, which are illegal inside the function wrapper\n * the runner builds around skill scripts.\n */\nfunction stripStrayExports(source: string): string {\n return source.replace(/\\n?export\\s*\\{[\\s\\S]*?\\};?/g, \"\");\n}\n\nfunction rewriteBundledSource(source: string): string {\n // esbuild emits the default export as a binding inside an `export { ... }`\n // block, e.g. `export { run as default }` or, when the module also has named\n // exports, `export { helper, run as default }`. Extract the binding aliased\n // to `default` from anywhere in those blocks, then strip the (illegal-inside-\n // a-function) export statements and bind the captured name to `__skillRun`.\n const defaultBinding = source.match(\n /\\bexport\\s*\\{[^}]*\\b([A-Za-z_$][\\w$]*)\\s+as\\s+default\\b[^}]*\\}/m\n );\n const stripped = stripStrayExports(source);\n if (defaultBinding) {\n return `${stripped}\\nconst __skillRun = ${defaultBinding[1]};`;\n }\n return stripped;\n}\n\nasync function prepareJavaScriptSource(\n request: SkillScriptRequest,\n runtime: \"javascript\" | \"typescript\"\n): Promise<string> {\n // Skill scripts run directly in the sandbox; the runtime ships no in-Worker\n // bundler. Build-time compiled scripts (Agents Vite plugin / `compileSkillScript`\n // from \"agents/skills/compile\") arrive as self-contained ESM. Normalize\n // esbuild's `export { run as default }` (or a raw `export default`) into the\n // `__skillRun` binding the wrapper expects.\n const entryPrecompiled = (request.resources ?? []).some(\n (resource) =>\n resource.path === request.path && resource.precompiled === true\n );\n if (entryPrecompiled) return rewriteBundledSource(request.source);\n\n // Count sibling script files to detect skills that span multiple modules.\n let scriptFileCount = 1;\n for (const resource of request.resources ?? []) {\n if (resource.path === request.path) continue;\n const extension = extensionOf(resource.path);\n if (\n resource.kind === \"script\" &&\n (resource.encoding ?? \"text\") === \"text\" &&\n [\".js\", \".mjs\", \".ts\", \".tsx\"].includes(extension)\n ) {\n scriptFileCount++;\n }\n }\n\n // Plain single-file JavaScript runs as-is. Anything that needs compiling\n // (TypeScript, or a skill split across multiple modules) must be bundled\n // ahead of time — there is no runtime bundler to fall back to.\n if (runtime === \"javascript\" && scriptFileCount === 1) {\n return request.source;\n }\n\n throw new Error(\n `Skill script \"${request.path}\" must be compiled to a self-contained JavaScript module before it can run. ` +\n \"Bundled skills are compiled automatically by the Agents Vite plugin. Skills served from R2 or other dynamic \" +\n 'sources must be bundled ahead of time (e.g. with `compileSkillScript` from \"agents/skills/compile\") before upload.'\n );\n}\n\n// ── Host bridge: single capability + permission surface ───────────────\n\nasync function executeToolFromSet(\n tools: ToolSet | undefined,\n name: string,\n input: unknown\n): Promise<unknown> {\n const target = tools?.[name];\n const execute =\n target && \"execute\" in target\n ? (target.execute as ((input: unknown) => Promise<unknown>) | undefined)\n : undefined;\n\n if (!execute) throw new Error(`Tool not available: ${name}`);\n return execute(input);\n}\n\nfunction stringifyHostResult(result: unknown): string {\n return JSON.stringify({ result });\n}\n\nfunction stringifyHostError(error: unknown): string {\n return JSON.stringify({\n error: error instanceof Error ? error.message : String(error)\n });\n}\n\ninterface OutputArtifact {\n path: string;\n encoding: \"text\";\n content: string;\n}\n\n/**\n * The single source of truth for skill-script capabilities and permission\n * enforcement. Every runtime delegates here:\n *\n * - JavaScript/TypeScript reach it through a codemode `ToolProvider`.\n * - Python receives it as an RPC `RpcTarget` (JSON-marshalling methods).\n * - Bash calls it from `just-bash` custom commands.\n *\n * Construct a fresh bridge per `run()` so the per-invocation `/output`\n * artifact buffer is never shared between concurrent script runs.\n */\nclass SkillScriptHostBridge extends RpcTarget {\n readonly #tools: ToolSet | undefined;\n readonly #workspace: SkillWorkspaceAccess | undefined;\n readonly #workspaceAccess: WorkspaceAccess;\n readonly #outputs = new Map<string, OutputArtifact>();\n\n constructor(\n tools: ToolSet | undefined,\n workspace: SkillWorkspace | undefined,\n workspaceAccess: WorkspaceAccess\n ) {\n super();\n this.#tools = tools;\n this.#workspace =\n workspace === undefined\n ? undefined\n : createSkillWorkspaceAccess(workspace);\n this.#workspaceAccess = workspaceAccess;\n }\n\n // ── Introspection (host-side only) ──\n get workspaceAccess(): WorkspaceAccess {\n return this.#workspaceAccess;\n }\n\n hasTools(): boolean {\n return Boolean(this.#tools && Object.keys(this.#tools).length > 0);\n }\n\n // ── Canonical capability surface ──\n async callTool(name: string, input: unknown): Promise<unknown> {\n return executeToolFromSet(this.#tools, name, input);\n }\n\n async readFile(path: string): Promise<string | null> {\n return this.#requireWorkspace(\"read\").readFile(path);\n }\n\n async listFiles(path = \".\"): Promise<unknown> {\n return this.#requireWorkspace(\"read\").listFiles(path);\n }\n\n async glob(pattern: string): Promise<unknown> {\n return this.#requireWorkspace(\"read\").glob(pattern);\n }\n\n async stat(path: string): Promise<{ type: string; size: number } | null> {\n return this.#requireWorkspace(\"read\").stat(path);\n }\n\n async writeFile(path: string, content: string): Promise<void> {\n await this.#requireWorkspace(\"read-write\").writeFile(path, content);\n }\n\n writeOutput(name: string, content: string): void {\n const key = String(name);\n const text = typeof content === \"string\" ? content : String(content ?? \"\");\n const bytes = new TextEncoder().encode(text).byteLength;\n if (bytes > MAX_OUTPUT_ARTIFACT_BYTES) {\n throw new Error(\n `Output artifact \"${key}\" exceeds ${MAX_OUTPUT_ARTIFACT_BYTES} bytes.`\n );\n }\n if (!this.#outputs.has(key) && this.#outputs.size >= MAX_OUTPUT_ARTIFACTS) {\n throw new Error(\n `Too many skill output artifacts (max ${MAX_OUTPUT_ARTIFACTS}).`\n );\n }\n this.#outputs.set(key, { path: key, encoding: \"text\", content: text });\n }\n\n getOutputFiles(): OutputArtifact[] {\n return [...this.#outputs.values()];\n }\n\n // ── Python-facing JSON marshalling (delegates to canonical surface) ──\n async tool(name: string, inputJson = \"{}\"): Promise<string> {\n try {\n const input = inputJson.trim() ? JSON.parse(inputJson) : {};\n return stringifyHostResult(await this.callTool(name, input));\n } catch (error) {\n return stringifyHostError(error);\n }\n }\n\n async workspaceReadFile(path: string): Promise<string> {\n try {\n return stringifyHostResult(await this.readFile(path));\n } catch (error) {\n return stringifyHostError(error);\n }\n }\n\n async workspaceListFiles(path = \".\"): Promise<string> {\n try {\n return stringifyHostResult(await this.listFiles(path));\n } catch (error) {\n return stringifyHostError(error);\n }\n }\n\n async workspaceGlob(pattern: string): Promise<string> {\n try {\n return stringifyHostResult(await this.glob(pattern));\n } catch (error) {\n return stringifyHostError(error);\n }\n }\n\n async workspaceWriteFile(path: string, content: string): Promise<string> {\n try {\n await this.writeFile(path, content);\n return stringifyHostResult(null);\n } catch (error) {\n return stringifyHostError(error);\n }\n }\n\n #requireWorkspace(access: \"read\" | \"read-write\"): SkillWorkspaceAccess {\n if (!this.#workspace || this.#workspaceAccess === \"none\") {\n throw new Error(\"Workspace access is not available.\");\n }\n if (access === \"read-write\" && this.#workspaceAccess !== \"read-write\") {\n throw new Error(\"Workspace write access is not available.\");\n }\n return this.#workspace;\n }\n}\n\n/**\n * Expose the bridge to JS/TS scripts as a single codemode provider namespace\n * (`__host`). The sandbox `ctx` object wraps these calls into the friendly\n * `workspace` / `tools` / `output` surface (see {@link scriptModule}).\n */\nfunction hostProvider(bridge: SkillScriptHostBridge): ToolProvider {\n return {\n name: \"__host\",\n tools: {\n callTool: {\n execute: (a: unknown) => {\n const { name, input } = a as { name: string; input: unknown };\n return bridge.callTool(name, input);\n }\n },\n readFile: {\n execute: (a: unknown) => bridge.readFile(String(a))\n },\n listFiles: {\n execute: (a: unknown) =>\n bridge.listFiles(typeof a === \"string\" ? a : \".\")\n },\n glob: {\n execute: (a: unknown) => bridge.glob(String(a))\n },\n stat: {\n execute: (a: unknown) => bridge.stat(String(a))\n },\n writeFile: {\n execute: (a: unknown) => {\n const { path, content } = a as { path: string; content: string };\n return bridge.writeFile(path, content);\n }\n },\n writeOutput: {\n execute: async (a: unknown) => {\n const { name, content } = a as { name: string; content: string };\n bridge.writeOutput(name, content);\n return null;\n }\n }\n }\n };\n}\n\n// ── Python runtime ────────────────────────────────────────────────────\n\nfunction pythonScriptModule(request: SkillScriptRequest): string {\n const source = request.source;\n const sourceLiteral = JSON.stringify(source);\n const filesLiteral = JSON.stringify(mountedFiles(request));\n\n return String.raw`\nimport asyncio\nimport base64\nimport contextlib\nimport inspect\nimport io\nimport json\nimport os\nimport sys\nimport time\nimport types\nfrom js import Object\nfrom pyodide.ffi import to_js as pyodide_to_js\nfrom workers import WorkerEntrypoint\n\nSKILL_SOURCE = ${sourceLiteral}\nSKILL_FILES = ${filesLiteral}\n\nasync def maybe_await(value):\n if inspect.isawaitable(value):\n return await value\n return value\n\nasync def decode_host_response(raw):\n data = json.loads(str(raw))\n if \"error\" in data:\n raise Exception(data[\"error\"])\n return data.get(\"result\")\n\ndef to_js(obj):\n return pyodide_to_js(obj, dict_converter=Object.fromEntries)\n\ndef materialize_files():\n os.makedirs(\"/output\", exist_ok=True)\n for path, file in SKILL_FILES.items():\n directory = os.path.dirname(path)\n if directory:\n os.makedirs(directory, exist_ok=True)\n mode = \"wb\" if file.get(\"encoding\") == \"base64\" else \"w\"\n with open(path, mode) as handle:\n if file.get(\"encoding\") == \"base64\":\n handle.write(base64.b64decode(file.get(\"content\", \"\")))\n else:\n handle.write(file.get(\"content\", \"\"))\n\ndef collect_output_files():\n output_files = []\n if not os.path.isdir(\"/output\"):\n return output_files\n\n for root, _dirs, files in os.walk(\"/output\"):\n for name in sorted(files):\n path = os.path.join(root, name)\n with open(path, \"rb\") as handle:\n content = handle.read()\n if len(content) > ${MAX_OUTPUT_ARTIFACT_BYTES}:\n raise Exception(f\"Output artifact exceeds ${MAX_OUTPUT_ARTIFACT_BYTES} bytes: {path}\")\n try:\n output_files.append({\n \"path\": path,\n \"encoding\": \"text\",\n \"content\": content.decode(\"utf-8\")\n })\n except UnicodeDecodeError:\n output_files.append({\n \"path\": path,\n \"encoding\": \"base64\",\n \"content\": base64.b64encode(content).decode(\"ascii\")\n })\n\n return sorted(output_files, key=lambda file: file[\"path\"])\n\ndef looks_function_style(source):\n return \"def run(\" in source or \"async def run(\" in source\n\ndef timeout_trace(deadline):\n def trace(frame, event, arg):\n if time.monotonic() > deadline:\n raise TimeoutError(\"Python script execution timed out\")\n return trace\n return trace\n\nclass ToolNamespace:\n def __init__(self, host):\n self.host = host\n\n async def call(self, name, input=None):\n raw = await self.host.tool(name, json.dumps(input if input is not None else {}))\n return await decode_host_response(raw)\n\n def __getattr__(self, name):\n async def call_tool(input=None):\n return await self.call(name, input)\n return call_tool\n\nclass WorkspaceNamespace:\n def __init__(self, host):\n self.host = host\n\n async def read_file(self, path):\n raw = await self.host.workspaceReadFile(path)\n return await decode_host_response(raw)\n\n async def list_files(self, path=\".\"):\n raw = await self.host.workspaceListFiles(path)\n return await decode_host_response(raw)\n\n async def glob(self, pattern):\n raw = await self.host.workspaceGlob(pattern)\n return await decode_host_response(raw)\n\n async def write_file(self, path, content):\n raw = await self.host.workspaceWriteFile(path, content)\n return await decode_host_response(raw)\n\nclass Default(WorkerEntrypoint):\n async def evaluate(self, input, ctx, host, timeout_ms=None):\n materialize_files()\n try:\n if looks_function_style(SKILL_SOURCE):\n skill_module = types.ModuleType(\"skill_script\")\n skill_module.tools = ToolNamespace(host)\n skill_module.workspace = WorkspaceNamespace(host)\n exec(SKILL_SOURCE, skill_module.__dict__)\n if not hasattr(skill_module, \"run\") or not callable(skill_module.run):\n raise Exception(\"Python function-style skill script must define a callable run(input, ctx).\")\n execution = maybe_await(skill_module.run(input, ctx))\n previous_trace = sys.gettrace()\n if timeout_ms is not None:\n sys.settrace(timeout_trace(time.monotonic() + (timeout_ms / 1000)))\n try:\n if timeout_ms is not None:\n result = await asyncio.wait_for(execution, timeout_ms / 1000)\n else:\n result = await execution\n finally:\n sys.settrace(previous_trace)\n return to_js({\n \"result\": result,\n \"logs\": [],\n \"mode\": \"function\",\n \"outputFiles\": collect_output_files()\n })\n\n stdout = io.StringIO()\n stderr = io.StringIO()\n previous_stdin = sys.stdin\n previous_trace = sys.gettrace()\n if timeout_ms is not None:\n sys.settrace(timeout_trace(time.monotonic() + (timeout_ms / 1000)))\n sys.stdin = io.StringIO(json.dumps(input))\n try:\n namespace = {\"__name__\": \"__main__\", \"__file__\": \"/skill/script.py\"}\n with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr):\n exec(SKILL_SOURCE, namespace)\n finally:\n sys.stdin = previous_stdin\n sys.settrace(previous_trace)\n return to_js({\n \"result\": {\n \"stdout\": stdout.getvalue(),\n \"stderr\": stderr.getvalue(),\n \"exitCode\": 0\n },\n \"logs\": [],\n \"mode\": \"cli\",\n \"outputFiles\": collect_output_files()\n })\n except TimeoutError:\n return to_js({\"error\": \"Python script execution timed out\", \"logs\": []})\n except SystemExit as err:\n return to_js({\n \"result\": {\n \"stdout\": stdout.getvalue() if \"stdout\" in locals() else \"\",\n \"stderr\": stderr.getvalue() if \"stderr\" in locals() else \"\",\n \"exitCode\": int(err.code) if isinstance(err.code, int) else 1\n },\n \"logs\": [],\n \"mode\": \"cli\",\n \"outputFiles\": collect_output_files()\n })\n except asyncio.TimeoutError:\n return to_js({\"error\": \"Python script execution timed out\", \"logs\": []})\n except Exception as err:\n return to_js({\"error\": str(err), \"logs\": []})\n`;\n}\n\nasync function runPythonScript(\n request: SkillScriptRequest,\n options: WorkerSkillScriptRunnerOptions,\n bridge: SkillScriptHostBridge\n): Promise<unknown> {\n const worker = options.loader.get(\n `skill-python-${crypto.randomUUID()}`,\n () => ({\n compatibilityDate: \"2026-05-23\",\n compatibilityFlags: [\"python_workers\", \"disable_python_external_sdk\"],\n mainModule: \"skill_runner.py\",\n modules: {\n \"skill_runner.py\": pythonScriptModule(request)\n },\n globalOutbound: options.network ? undefined : null\n })\n );\n\n const entrypoint = worker.getEntrypoint() as unknown as {\n evaluate(\n input: unknown,\n ctx: SkillScriptContext,\n host: SkillScriptHostBridge,\n timeoutMs?: number\n ): Promise<{\n result?: unknown;\n error?: string;\n logs?: string[];\n mode?: \"cli\" | \"function\";\n outputFiles?: unknown[];\n }>;\n };\n\n const execution = entrypoint.evaluate(\n request.input,\n skillScriptContext(request),\n bridge,\n effectiveTimeout(options)\n );\n let timeout: ReturnType<typeof setTimeout> | null = null;\n const timeoutPromise = new Promise<never>((_, reject) => {\n timeout = setTimeout(\n () => reject(new Error(\"Python script execution timed out\")),\n effectiveTimeout(options)\n );\n });\n\n try {\n const response = await Promise.race([execution, timeoutPromise]);\n if (response.error) {\n throw new Error(response.error);\n }\n\n const outputFiles = response.outputFiles ?? [];\n\n if (response.mode === \"cli\") {\n if (\n typeof response.result === \"object\" &&\n response.result !== null &&\n outputFiles.length > 0\n ) {\n return {\n ...response.result,\n outputFiles\n };\n }\n return response.result;\n }\n\n if (response.logs?.length || outputFiles.length > 0) {\n return {\n result: response.result,\n ...(response.logs?.length ? { logs: response.logs } : {}),\n ...(outputFiles.length > 0 ? { outputFiles } : {})\n };\n }\n\n return response.result;\n } finally {\n if (timeout) clearTimeout(timeout);\n }\n}\n\n// ── Bash runtime ──────────────────────────────────────────────────────\n\nasync function runBashScript(\n request: SkillScriptRequest,\n options: WorkerSkillScriptRunnerOptions,\n bridge: SkillScriptHostBridge\n): Promise<unknown> {\n const customCommands = [];\n\n if (bridge.workspaceAccess !== \"none\") {\n customCommands.push(\n defineCommand(\"workspace-read\", async (args) => {\n const path = args[0];\n if (!path) return { stdout: \"\", stderr: \"Missing path\\n\", exitCode: 2 };\n try {\n return {\n stdout: (await bridge.readFile(path)) ?? \"\",\n stderr: \"\",\n exitCode: 0\n };\n } catch (error) {\n return {\n stdout: \"\",\n stderr: `${error instanceof Error ? error.message : String(error)}\\n`,\n exitCode: 1\n };\n }\n }),\n defineCommand(\"workspace-list\", async (args) => {\n const path = args[0] ?? \".\";\n try {\n return {\n stdout: JSON.stringify(await bridge.listFiles(path)) + \"\\n\",\n stderr: \"\",\n exitCode: 0\n };\n } catch (error) {\n return {\n stdout: \"\",\n stderr: `${error instanceof Error ? error.message : String(error)}\\n`,\n exitCode: 1\n };\n }\n }),\n defineCommand(\"workspace-glob\", async (args) => {\n const pattern = args[0];\n if (!pattern) {\n return { stdout: \"\", stderr: \"Missing pattern\\n\", exitCode: 2 };\n }\n try {\n return {\n stdout: JSON.stringify(await bridge.glob(pattern)) + \"\\n\",\n stderr: \"\",\n exitCode: 0\n };\n } catch (error) {\n return {\n stdout: \"\",\n stderr: `${error instanceof Error ? error.message : String(error)}\\n`,\n exitCode: 1\n };\n }\n })\n );\n\n if (bridge.workspaceAccess === \"read-write\") {\n customCommands.push(\n defineCommand(\"workspace-write\", async (args, ctx) => {\n const path = args[0];\n if (!path) {\n return { stdout: \"\", stderr: \"Missing path\\n\", exitCode: 2 };\n }\n try {\n await bridge.writeFile(path, stdinText(ctx.stdin));\n return { stdout: \"\", stderr: \"\", exitCode: 0 };\n } catch (error) {\n return {\n stdout: \"\",\n stderr: `${error instanceof Error ? error.message : String(error)}\\n`,\n exitCode: 1\n };\n }\n })\n );\n }\n }\n\n if (bridge.hasTools()) {\n customCommands.push(\n defineCommand(\"tool\", async (args, ctx) => {\n const name = args[0];\n if (!name) {\n return { stdout: \"\", stderr: \"Missing tool name\\n\", exitCode: 2 };\n }\n try {\n const rawInput = args[1] ?? stdinText(ctx.stdin) ?? \"{}\";\n const input = rawInput.trim() ? JSON.parse(rawInput) : {};\n const result = await bridge.callTool(name, input);\n return {\n stdout: JSON.stringify(result) + \"\\n\",\n stderr: \"\",\n exitCode: 0\n };\n } catch (error) {\n return {\n stdout: \"\",\n stderr: `${error instanceof Error ? error.message : String(error)}\\n`,\n exitCode: 1\n };\n }\n })\n );\n }\n\n const controller = new AbortController();\n const timeout = setTimeout(\n () => controller.abort(),\n effectiveTimeout(options)\n );\n\n try {\n const bash = new Bash({\n files: bashFiles(request),\n customCommands,\n defenseInDepth: true,\n network: options.network ? {} : undefined\n });\n const result = await bash.exec(\"bash /skill-script.sh\", {\n signal: controller.signal,\n stdin: JSON.stringify(request.input)\n });\n\n return {\n stdout: result.stdout,\n stderr: result.stderr,\n exitCode: result.exitCode\n };\n } finally {\n if (timeout) clearTimeout(timeout);\n }\n}\n\n// ── JavaScript / TypeScript runtime ───────────────────────────────────\n\nasync function runJavaScriptScript(\n request: SkillScriptRequest,\n options: WorkerSkillScriptRunnerOptions,\n bridge: SkillScriptHostBridge,\n runtime: \"javascript\" | \"typescript\"\n): Promise<unknown> {\n if (!hasDefaultExport(request.source)) {\n throw new Error(\n \"JS/TS skill scripts must `export default` an async run(input, ctx) function.\"\n );\n }\n\n const source = await prepareJavaScriptSource(request, runtime);\n const executor = new DynamicWorkerExecutor({\n loader: options.loader,\n timeout: effectiveTimeout(options),\n globalOutbound: options.network ? undefined : null\n });\n const result = await executor.execute(scriptModule(source, request), [\n resolveProvider(hostProvider(bridge))\n ]);\n\n if (result.error) {\n const logs = result.logs?.length\n ? `\\n\\nConsole output:\\n${result.logs.join(\"\\n\")}`\n : \"\";\n throw new Error(`${result.error}${logs}`);\n }\n\n const outputFiles = bridge.getOutputFiles();\n if (result.logs?.length || outputFiles.length > 0) {\n return {\n result: result.result,\n ...(result.logs?.length ? { logs: result.logs } : {}),\n ...(outputFiles.length > 0 ? { outputFiles } : {})\n };\n }\n\n return result.result;\n}\n\n/**\n * Create a skill script runner backed by a Worker Loader.\n *\n * Capabilities are opt-in and enforced by a single host bridge: no network and\n * no tools by default, read-only workspace access when `workspaceInstance` is\n * provided. JS/TS scripts are function-style (`export default run(input, ctx)`)\n * and receive `ctx = { skill, files, workspace, tools, output }`. Python and\n * Bash use the path-based `/skill`, `/input.json`, `/output` contract.\n *\n * @experimental Skill script execution is experimental and may change before\n * stabilizing.\n */\nexport function runner(\n options: WorkerSkillScriptRunnerOptions\n): SkillScriptRunner {\n return {\n async run(request: SkillScriptRequest) {\n if (!runnerExperimentalWarned) {\n runnerExperimentalWarned = true;\n console.warn(\n \"[think] skills.runner script execution is experimental; the API and capabilities may change.\"\n );\n }\n\n const tools =\n typeof options.tools === \"function\"\n ? await options.tools()\n : options.tools;\n const validation = validateSkillScriptPath(request.path);\n if (!validation.ok) throw new Error(validation.error);\n validateMountedResourcePaths(request);\n\n // Fresh bridge per run so /output artifacts never leak between\n // concurrent script invocations.\n const bridge = new SkillScriptHostBridge(\n tools,\n options.workspaceInstance,\n effectiveWorkspaceAccess(options)\n );\n\n if (validation.runtime === \"bash\") {\n return await runBashScript(request, options, bridge);\n }\n\n if (validation.runtime === \"python\") {\n return await runPythonScript(request, options, bridge);\n }\n\n return await runJavaScriptScript(\n request,\n options,\n bridge,\n validation.runtime\n );\n }\n };\n}\n","import { tool, type ToolSet } from \"ai\";\nimport { z } from \"zod\";\nimport type {\n SkillContent,\n SkillDescriptor,\n SkillRegistrySnapshot,\n SkillResource,\n SkillResourceDescriptor,\n SkillScriptRunner,\n SkillSource\n} from \"./types\";\nimport { validateSkillResourcePath } from \"./types\";\nimport { parseSkillMarkdown } from \"./frontmatter\";\nimport { validateSkillScriptPath } from \"./runner\";\nimport {\n createSkillWorkspaceFiles,\n type SkillWorkspace,\n type SkillWorkspaceFiles,\n type SkillWorkspaceSeedOptions,\n type SkillWorkspaceSeedResult\n} from \"./workspace\";\n\nconst SKILL_CONTEXT_LABEL = \"think_skills\";\n\nfunction stableSourceFingerprint(sources: SkillSource[]): string {\n return sources\n .map((source) => `${source.id}:${source.fingerprint}`)\n .join(\"|\");\n}\n\nfunction renderSkillMarkdown(skill: SkillContent): string {\n const lines = [\n \"---\",\n `name: ${JSON.stringify(skill.name)}`,\n `description: ${JSON.stringify(skill.description)}`\n ];\n if (skill.compatibility) {\n lines.push(`compatibility: ${JSON.stringify(skill.compatibility)}`);\n }\n if (skill.license) lines.push(`license: ${JSON.stringify(skill.license)}`);\n if (skill.allowedTools) {\n lines.push(`allowed-tools: ${JSON.stringify(skill.allowedTools)}`);\n }\n if (skill.metadata) {\n lines.push(`metadata: ${JSON.stringify(skill.metadata)}`);\n }\n lines.push(\"---\", \"\", skill.body);\n return lines.join(\"\\n\");\n}\n\nfunction wrapSkillContent(skill: SkillContent): string {\n const version = skill.version ? ` version=\"${skill.version}\"` : \"\";\n const resourceList = skill.resources?.length\n ? [\n \"\",\n \"<skill_resources>\",\n ...skill.resources.map(\n (resource) =>\n ` <file kind=\"${resource.kind}\" encoding=\"${resource.encoding ?? \"text\"}\"${resource.size === undefined ? \"\" : ` size=\"${resource.size}\"`}>${resource.path}</file>`\n ),\n \"</skill_resources>\"\n ].join(\"\\n\")\n : \"\";\n\n return [\n `<skill_content name=\"${skill.name}\"${version}>`,\n skill.body.trim(),\n resourceList,\n \"</skill_content>\"\n ].join(\"\\n\");\n}\n\nfunction renderResourceList(\n resources: SkillResourceDescriptor[] | undefined\n): string {\n if (!resources?.length) return \"No bundled resources.\";\n return resources\n .map((resource) => {\n const encoding = resource.encoding ?? \"text\";\n const size =\n resource.size === undefined ? \"\" : `, ${resource.size} bytes`;\n const mimeType = resource.mimeType ? `, ${resource.mimeType}` : \"\";\n return `- ${resource.path} (${resource.kind}, ${encoding}${mimeType}${size})`;\n })\n .join(\"\\n\");\n}\n\nfunction validateResourcePath(path: string): string | null {\n if (path.startsWith(\"../\")) {\n return `Resource paths cannot use \"../\". To read from another skill, use a qualified path like \"other-skill/references/file.md\".`;\n }\n return validateSkillResourcePath(path);\n}\n\nexport class SkillRegistry {\n readonly contextLabel = SKILL_CONTEXT_LABEL;\n\n /**\n * Non-fatal diagnostics collected during the most recent {@link load} or\n * {@link refresh} (duplicate skill names, sources that failed to list).\n * Reset on every load so it never grows unbounded across refreshes.\n */\n readonly warnings: string[] = [];\n\n private sources: SkillSource[];\n private scriptRunner: SkillScriptRunner | null;\n private descriptors = new Map<string, SkillDescriptor>();\n private sourceBySkill = new Map<string, SkillSource>();\n private loaded = false;\n private workspaceFiles: SkillWorkspaceFiles | null = null;\n private workspaceSkillNames = new Set<string>();\n private workspaceResources = new Map<\n string,\n Map<string, SkillResourceDescriptor>\n >();\n\n constructor(\n sources: SkillSource[],\n scriptRunner: SkillScriptRunner | null = null\n ) {\n this.sources = sources;\n this.scriptRunner = scriptRunner;\n }\n\n get fingerprint(): string {\n return stableSourceFingerprint(this.sources);\n }\n\n async load(): Promise<void> {\n if (this.loaded) return;\n\n this.descriptors.clear();\n this.sourceBySkill.clear();\n this.warnings.length = 0;\n\n // Skills are applied in `getSkills()` order: the first source to register\n // a name wins, and later collisions are skipped with a diagnostic. A bad\n // source must not take down the whole registry, so listing failures are\n // also recorded rather than thrown.\n for (const source of this.sources) {\n let descriptors: SkillDescriptor[];\n try {\n descriptors = await source.list();\n } catch (error) {\n this.warnings.push(\n `Skill source \"${source.id}\" failed to list skills and was skipped: ${error instanceof Error ? error.message : String(error)}`\n );\n continue;\n }\n\n for (const descriptor of descriptors) {\n const existing = this.descriptors.get(descriptor.name);\n if (existing) {\n this.warnings.push(\n `Duplicate skill \"${descriptor.name}\" from ${source.id} ignored; already registered from ${existing.sourceId}.`\n );\n continue;\n }\n this.descriptors.set(descriptor.name, {\n ...descriptor,\n sourceId: descriptor.sourceId ?? source.id\n });\n this.sourceBySkill.set(descriptor.name, source);\n }\n }\n\n this.loaded = true;\n }\n\n async refresh(): Promise<void> {\n const refreshErrors: string[] = [];\n await Promise.all(\n this.sources.map(async (source) => {\n try {\n await source.refresh?.();\n } catch (error) {\n refreshErrors.push(\n `Skill source \"${source.id}\" failed to refresh: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n })\n );\n this.loaded = false;\n await this.load();\n // `load()` reset warnings; re-append any refresh failures so they surface.\n this.warnings.push(...refreshErrors);\n }\n\n /**\n * Seed resolved Agent Skills into a Workspace.\n * Existing files are preserved by default, and become authoritative for\n * activation, resource reads, and script execution.\n */\n async seedWorkspace(\n workspace: SkillWorkspace,\n options: SkillWorkspaceSeedOptions = {}\n ): Promise<SkillWorkspaceSeedResult> {\n await this.load();\n const files = createSkillWorkspaceFiles(workspace, options.root);\n const result = {\n written: 0,\n preserved: 0,\n skipped: 0,\n warnings: [] as string[],\n root: files.root\n };\n const seeded = new Set<string>();\n const resources = new Map<string, Map<string, SkillResourceDescriptor>>();\n\n for (const descriptor of this.descriptors.values()) {\n const source = this.sourceBySkill.get(descriptor.name);\n let skill: SkillContent | null = null;\n try {\n skill = (await source?.load(descriptor.name)) ?? null;\n } catch (error) {\n result.skipped++;\n result.warnings.push(\n `Could not load skill \"${descriptor.name}\" for Workspace seeding: ${error instanceof Error ? error.message : String(error)}`\n );\n continue;\n }\n if (!skill) {\n result.skipped++;\n result.warnings.push(\n `Could not load skill \"${descriptor.name}\" for Workspace seeding.`\n );\n continue;\n }\n\n resources.set(\n descriptor.name,\n new Map(\n (skill.resources ?? []).map((resource) => [resource.path, resource])\n )\n );\n const skillPath = files.path(descriptor.name, \"SKILL.md\");\n if (\n await this.writeSeedFile(\n files,\n skillPath,\n skill.rawContent ?? renderSkillMarkdown(skill),\n options,\n result\n )\n ) {\n seeded.add(descriptor.name);\n }\n }\n\n this.workspaceFiles = files;\n this.workspaceSkillNames = seeded;\n this.workspaceResources = resources;\n return result;\n }\n\n /**\n * Route skill reads through an already-seeded Workspace without probing or\n * rewriting its files. Hosts use this when the durable source fingerprint\n * matches the recorded projection fingerprint.\n */\n async useWorkspace(\n workspace: SkillWorkspace,\n options: SkillWorkspaceSeedOptions = {}\n ): Promise<void> {\n await this.load();\n this.workspaceFiles = createSkillWorkspaceFiles(workspace, options.root);\n this.workspaceSkillNames = new Set(this.descriptors.keys());\n this.workspaceResources.clear();\n }\n\n private async writeSeedFile(\n files: SkillWorkspaceFiles,\n path: string,\n content: string,\n options: SkillWorkspaceSeedOptions,\n result: { written: number; preserved: number; skipped: number }\n ): Promise<boolean> {\n try {\n if (options.onConflict !== \"replace\" && (await files.exists(path))) {\n result.preserved++;\n return true;\n }\n await files.writeText(path, content);\n result.written++;\n return true;\n } catch {\n result.skipped++;\n return false;\n }\n }\n\n async snapshot(): Promise<SkillRegistrySnapshot> {\n await this.load();\n\n const catalog: string[] = [];\n\n for (const descriptor of this.descriptors.values()) {\n catalog.push(`- ${descriptor.name}: ${descriptor.description}`);\n }\n\n return {\n fingerprint: this.fingerprint,\n catalogPrompt: catalog.length\n ? [\n \"Available skills. When a task matches a skill, use activate_skill with its name before proceeding.\",\n ...(this.workspaceFiles\n ? [\n `Skill files are available at ${this.workspaceFiles.root}. Workspace edits affect later activations and resource reads.`\n ]\n : []),\n \"\",\n ...catalog\n ].join(\"\\n\")\n : null\n };\n }\n\n async systemPrompt(): Promise<string | null> {\n const snapshot = await this.snapshot();\n return snapshot.catalogPrompt;\n }\n\n async loadSkill(name: string): Promise<SkillContent | null> {\n await this.load();\n const source = this.sourceBySkill.get(name);\n if (!source) return null;\n const original = await source.load(name);\n if (!original) return null;\n this.workspaceResources.set(\n name,\n new Map(\n (original.resources ?? []).map((resource) => [resource.path, resource])\n )\n );\n if (!this.workspaceSkillNames.has(name)) return original;\n const rawContent = await this.workspaceFiles?.readText(\n this.workspaceFiles.path(name, \"SKILL.md\")\n );\n if (rawContent === null || rawContent === undefined) return null;\n const parsed = parseSkillMarkdown(rawContent);\n if (!parsed) return null;\n return {\n ...original,\n ...parsed,\n rawContent,\n sourceId: original.sourceId,\n version: original.version,\n resources: original.resources\n };\n }\n\n private resolveResourceTarget(\n name: string | undefined,\n path: string\n ):\n | {\n ok: true;\n name: string;\n path: string;\n }\n | {\n ok: false;\n error: string;\n } {\n const pathError = validateResourcePath(path);\n if (pathError) return { ok: false, error: pathError };\n\n if (name) return { ok: true, name, path };\n\n const [candidateName, ...rest] = path.split(\"/\");\n if (!candidateName || rest.length === 0) {\n return {\n ok: false,\n error:\n \"Resource path must include a skill name when name is omitted, for example: cloudflare-brand/references/tokens.md\"\n };\n }\n if (!this.descriptors.has(candidateName)) {\n return {\n ok: false,\n error: `Unknown skill in qualified resource path: ${candidateName}`\n };\n }\n return { ok: true, name: candidateName, path: rest.join(\"/\") };\n }\n\n private async readResource(\n name: string,\n path: string\n ): Promise<SkillResource | string> {\n const source = this.sourceBySkill.get(name);\n if (this.workspaceSkillNames.has(name) && this.workspaceFiles) {\n let descriptor = this.workspaceResources.get(name)?.get(path);\n if (!descriptor) {\n const skill = await source?.load(name);\n const resources = new Map(\n (skill?.resources ?? []).map((resource) => [resource.path, resource])\n );\n this.workspaceResources.set(name, resources);\n descriptor = resources.get(path);\n }\n if (!descriptor) return `Resource not found: ${name}/${path}`;\n const workspacePath = this.workspaceFiles.path(name, path);\n const existing = await this.workspaceFiles.readResource(\n workspacePath,\n descriptor\n );\n if (existing) return existing;\n if (!source?.readResource) {\n return `Skill \"${name}\" has no readable resources.`;\n }\n const resource = await source.readResource(name, path);\n if (!resource) return `Resource not found: ${name}/${path}`;\n await this.workspaceFiles.writeResource(workspacePath, resource);\n return resource;\n }\n if (!source?.readResource) {\n return `Skill \"${name}\" has no readable resources.`;\n }\n const resource = await source.readResource(name, path);\n return resource ?? `Resource not found: ${name}/${path}`;\n }\n\n private async readSkillResources(\n skill: SkillContent\n ): Promise<SkillResource[]> {\n const resources: SkillResource[] = [];\n for (const descriptor of skill.resources ?? []) {\n const resource = await this.readResource(skill.name, descriptor.path);\n if (typeof resource !== \"string\") resources.push(resource);\n }\n return resources;\n }\n\n tools(): ToolSet {\n const modelSkillNames = [...this.descriptors.values()].map(\n (skill) => skill.name\n );\n\n const tools: ToolSet = {};\n\n if (modelSkillNames.length > 0) {\n tools.activate_skill = tool({\n description:\n \"Activate a skill by name. Use this when the user's task matches one of the available skills.\",\n inputSchema: z.object({\n name: z.enum(modelSkillNames as [string, ...string[]])\n }),\n execute: async ({ name }: { name: string }) => {\n const skill = await this.loadSkill(name);\n if (!skill) {\n return `Skill not found: ${name}`;\n }\n return [\n wrapSkillContent(skill),\n \"\",\n \"Bundled resources:\",\n renderResourceList(skill.resources)\n ].join(\"\\n\");\n }\n });\n }\n\n if (modelSkillNames.length > 0) {\n tools.read_skill_resource = tool({\n description:\n \"Read a bundled resource from an available skill by relative path. Pass name and path, or use a qualified path like skill-name/references/file.md.\",\n inputSchema: z.object({\n name: z.enum(modelSkillNames as [string, ...string[]]).optional(),\n path: z.string().min(1)\n }),\n execute: async ({ name, path }: { name?: string; path: string }) => {\n const target = this.resolveResourceTarget(name, path);\n if (!target.ok) return target.error;\n\n const resource = await this.readResource(target.name, target.path);\n if (typeof resource === \"string\") return resource;\n\n const encoding = resource.encoding ?? \"text\";\n const mimeType = resource.mimeType\n ? ` mimeType=\"${resource.mimeType}\"`\n : \"\";\n return [\n `<skill_resource name=\"${target.name}\" path=\"${resource.path}\" kind=\"${resource.kind}\" encoding=\"${encoding}\"${mimeType}>`,\n resource.content,\n \"</skill_resource>\"\n ].join(\"\\n\");\n }\n });\n }\n\n if (modelSkillNames.length > 0 && this.scriptRunner) {\n tools.run_skill_script = tool({\n description:\n \"Run a bundled script resource from an available skill. Use only when a skill instructs you to run a script.\",\n inputSchema: z.object({\n name: z.enum(modelSkillNames as [string, ...string[]]),\n path: z.string().min(1),\n input: z.unknown().default({})\n }),\n execute: async ({\n name,\n path,\n input = {}\n }: {\n name: string;\n path: string;\n input: unknown;\n }) => {\n const validation = validateSkillScriptPath(path);\n if (!validation.ok) return validation.error;\n\n const skill = await this.loadSkill(name);\n if (!skill) return `Skill not found: ${name}`;\n\n const script = skill.resources?.find(\n (resource) => resource.path === path\n );\n if (!script) return `Script not found: ${name}/${path}`;\n if (script.kind !== \"script\") {\n return `Resource is not a script: ${name}/${path}`;\n }\n\n const resource = await this.readResource(name, path);\n if (typeof resource === \"string\") return resource;\n if ((resource.encoding ?? \"text\") !== \"text\") {\n return `Script resource must be text, got ${resource.encoding}: ${name}/${path}`;\n }\n\n try {\n return await this.scriptRunner!.run({\n skill,\n path,\n source: resource.content,\n input,\n resources: await this.readSkillResources(skill)\n });\n } catch (error) {\n return `Skill script failed: ${error instanceof Error ? error.message : String(error)}`;\n }\n }\n });\n }\n\n return tools;\n }\n}\n"],"mappings":";;;;;;;;;AAOA,SAAgB,sBAAsB,KAAkC;CACtE,MAAM,QAAQ,IAAI,MAAM,6CAA6C;CACrE,IAAI,CAAC,OAAO,OAAO;EAAE,MAAM,CAAC;EAAG,MAAM;CAAI;CAEzC,MAAM,SAASA,MAAU,MAAM,MAAM,EAAE;CAMvC,OAAO;EAAE,MAJP,WAAW,QAAQ,OAAO,WAAW,YAAY,CAAC,MAAM,QAAQ,MAAM,IACjE,SACD,CAAC;EAEQ,MAAM,MAAM,MAAM;CAAG;AACtC;AAEA,SAAS,eAAe,OAAoC;CAC1D,OAAO,OAAO,UAAU,YAAY,MAAM,KAAK,IAAI,MAAM,KAAK,IAAI,KAAA;AACpE;AAEA,SAAS,eAAe,OAAqD;CAC3E,OAAO,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK,IACrE,QACD,KAAA;AACN;AAEA,SAAgB,mBAAmB,KAQ1B;CACP,MAAM,EAAE,MAAM,SAAS,sBAAsB,GAAG;CAChD,MAAM,OAAO,eAAe,KAAK,IAAI;CACrC,MAAM,cAAc,eAAe,KAAK,WAAW;CAEnD,IAAI,CAAC,QAAQ,CAAC,aAAa,OAAO;CAElC,OAAO;EACL;EACA;EACA;EACA,eAAe,eAAe,KAAK,aAAa;EAChD,SAAS,eAAe,KAAK,OAAO;EACpC,cAAc,eAAe,KAAK,gBAAgB;EAClD,UAAU,eAAe,KAAK,QAAQ;CACxC;AACF;;;ACkEA,SAAgB,0BAA0B,MAA6B;CACrE,IACE,KAAK,WAAW,GAAG,KACnB,KAAK,SAAS,IAAI,KAClB,KAAK,MAAM,GAAG,CAAC,CAAC,MAAM,SA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B,OAAO,6BAA6B,KAAK,GAAG;IAG9C,MAAM,WAAW,MAAM,KAAK,aAAa,MAAM,IAAI;IACnD,IAAI,OAAO,aAAa,UAAU,OAAO;IACzC,KAAK,SAAS,YAAY,YAAY,QACpC,OAAO,qCAAqC,SAAS,SAAS,IAAI,KAAK,GAAG;IAG5E,IAAI;KACF,OAAO,MAAM,KAAK,aAAc,IAAI;MAClC;MACA;MACA,QAAQ,SAAS;MACjB;MACA,WAAW,MAAM,KAAK,mBAAmB,KAAK;KAChD,CAAC;IACH,SAAS,OAAO;KACd,OAAO,wBAAwB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;IACtF;GACF;EACF,CAAC;EAGH,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/skills/tree.ts","../../src/skills/workspace.ts","../../src/skills/r2.ts","../../src/skills/manifest.ts"],"sourcesContent":["import { parseSkill } from \"./markdown\";\nimport {\n describeSkillResource,\n isIgnoredSkillPath,\n parseSkillResourcePath,\n type SkillResourceInfo\n} from \"./resource\";\nimport type { SkillName } from \"./skill\";\nimport type { InvalidSkill, ListedSkill, SkillListing } from \"./source\";\n\n/** @internal A listing plus the directory each skill name was read from. */\nexport interface SkillTree {\n readonly listing: SkillListing;\n readonly directories: ReadonlyMap<SkillName, string>;\n}\n\n/** @internal One file in a tree of skill directories. */\nexport interface SkillTreeFile {\n /** Path relative to the tree root, such as `my-skill/references/a.md`. */\n readonly path: string;\n /** Size in bytes, when known from the listing. */\n readonly size?: number;\n}\n\n/**\n * @internal Turn a flat list of files under a skills root into a listing.\n *\n * Each `<directory>/SKILL.md` one level below the root is a skill; every\n * other file in that directory is one of its resources. Workspace and R2\n * sources share this so both read the same layout the same way.\n *\n * @param files - Every file under the root.\n * @param readSkillFile - Read a root-relative `SKILL.md` as text.\n * @param location - Absolute directory for a skill, when the source has one.\n * @throws Whatever `readSkillFile` throws; callers wrap it as a source error.\n */\nexport async function indexSkillTree(\n files: readonly SkillTreeFile[],\n readSkillFile: (path: string) => Promise<string | null>,\n location?: (directory: string) => string\n): Promise<SkillTree> {\n const byDirectory = new Map<string, SkillTreeFile[]>();\n for (const file of files) {\n const slash = file.path.indexOf(\"/\");\n if (slash <= 0) continue;\n const directory = file.path.slice(0, slash);\n const entries = byDirectory.get(directory) ?? [];\n entries.push(file);\n byDirectory.set(directory, entries);\n }\n\n const skills: ListedSkill[] = [];\n const invalid: InvalidSkill[] = [];\n const directories = new Map<SkillName, string>();\n for (const directory of [...byDirectory.keys()].sort()) {\n const entries = byDirectory.get(directory) ?? [];\n const skillPath = `${directory}/SKILL.md`;\n if (!entries.some((entry) => entry.path === skillPath)) continue;\n\n const markdown = await readSkillFile(skillPath);\n if (markdown === null) continue;\n const parsed = parseSkill(markdown, { directory });\n if (!parsed.ok) {\n invalid.push({ location: skillPath, error: parsed.error });\n continue;\n }\n\n const resources: SkillResourceInfo[] = [];\n for (const entry of entries) {\n if (entry.path === skillPath) continue;\n const relative = entry.path.slice(directory.length + 1);\n if (isIgnoredSkillPath(relative)) continue;\n const path = parseSkillResourcePath(relative);\n if (path.ok)\n resources.push(describeSkillResource(path.value, entry.size));\n }\n resources.sort((a, b) => a.path.localeCompare(b.path));\n\n skills.push({\n skill: parsed.value,\n resources,\n ...(location === undefined ? {} : { location: location(directory) }),\n ...(parsed.warnings.length === 0 ? {} : { warnings: parsed.warnings })\n });\n // A name may differ from its directory (a warning); resource reads need the\n // directory. The first directory to claim a name wins, as in the catalog.\n if (!directories.has(parsed.value.name)) {\n directories.set(parsed.value.name, directory);\n }\n }\n\n return { listing: { skills, invalid }, directories };\n}\n","import { err, ok } from \"./result\";\nimport {\n describeSkillResource,\n encodeSkillResourceContent,\n type SkillResource\n} from \"./resource\";\nimport {\n SkillResourceNotFoundError,\n SkillSourceError,\n type SkillSource\n} from \"./source\";\nimport type { SkillName } from \"./skill\";\nimport { indexSkillTree } from \"./tree\";\n\n/**\n * The parts of a `@cloudflare/computer` Workspace a skill source reads. A\n * local `Workspace`, a client from `getWorkspace()`, and Think's\n * `this.workspace` all fit.\n */\nexport interface SkillWorkspace {\n /** The Workspace filesystem. */\n readonly fs: {\n /** Walk a directory tree. */\n find(\n directory: string,\n pattern?: string,\n options?: { exclude?: string[] }\n ): Promise<ReadonlyArray<{ path: string; type: string }>>;\n /** Read a file's bytes. */\n readFile(path: string): Promise<ReadableStream<Uint8Array>>;\n };\n}\n\n/** Options for {@link workspace}. */\nexport interface WorkspaceSkillSourceOptions {\n /**\n * Absolute directory that holds the skill directories. Defaults to\n * `/workspace/.agents/skills`, the cross-client Agent Skills location.\n */\n readonly root?: string;\n /** Source id for diagnostics. Defaults to `workspace:<root>`. */\n readonly id?: string;\n}\n\n/** Default skills directory inside a Workspace. */\nexport const DEFAULT_WORKSPACE_SKILLS_ROOT = \"/workspace/.agents/skills\";\n\n/**\n * Create a source that reads skills from a Computer Workspace.\n *\n * Skills are plain files: every `<root>/<skill-name>/SKILL.md` is a skill,\n * and the files beside it are its resources. The Workspace is read on every\n * listing, so skills the agent or a user adds, edits, or deletes take effect\n * the next time the catalog loads. A missing root lists no skills.\n *\n * @param target - The Workspace to read.\n * @param options - Skills root and source id.\n * @returns A source backed by the Workspace.\n * @throws TypeError when `root` is not a normalized absolute path.\n */\nexport function workspace(\n target: SkillWorkspace,\n options: WorkspaceSkillSourceOptions = {}\n): SkillSource {\n const root = parseRoot(options.root ?? DEFAULT_WORKSPACE_SKILLS_ROOT);\n const id = options.id ?? `workspace:${root}`;\n const { fs } = target;\n // Skill name -> directory from the last listing. Lenient names can differ\n // from their directory, and resources live in the directory.\n let directories: ReadonlyMap<SkillName, string> = new Map();\n\n async function readBytes(path: string): Promise<Uint8Array | null> {\n try {\n return await drain(await fs.readFile(path));\n } catch (error) {\n if (isNotFound(error)) return null;\n throw error;\n }\n }\n\n return {\n id,\n async list() {\n try {\n let entries: ReadonlyArray<{ path: string; type: string }>;\n try {\n entries = await fs.find(root, undefined, {\n exclude: [\"*/node_modules/**\", \"*/.git/**\"]\n });\n } catch (error) {\n if (isNotFound(error)) return ok({ skills: [], invalid: [] });\n throw error;\n }\n const files = entries\n .filter((entry) => entry.type === \"file\")\n .map((entry) => ({ path: entry.path.slice(root.length + 1) }));\n const tree = await indexSkillTree(\n files,\n async (path) => {\n const bytes = await readBytes(`${root}/${path}`);\n return bytes === null ? null : new TextDecoder().decode(bytes);\n },\n (directory) => `${root}/${directory}`\n );\n directories = tree.directories;\n return ok(tree.listing);\n } catch (cause) {\n return err(new SkillSourceError(id, \"list\", cause));\n }\n },\n async readResource(skill, path) {\n const info = describeSkillResource(path);\n try {\n const directory = directories.get(skill) ?? skill;\n const bytes = await readBytes(`${root}/${directory}/${path}`);\n if (bytes === null) {\n return err(new SkillResourceNotFoundError(skill, path));\n }\n const resource: SkillResource = {\n ...info,\n size: bytes.byteLength,\n content: encodeSkillResourceContent(bytes, info.encoding)\n };\n return ok(resource);\n } catch (cause) {\n return err(new SkillSourceError(id, \"read-resource\", cause));\n }\n }\n };\n}\n\nfunction parseRoot(root: string): string {\n const normalized = root.replace(/\\/+$/, \"\");\n if (\n !normalized.startsWith(\"/\") ||\n normalized.includes(\"\\0\") ||\n normalized\n .slice(1)\n .split(\"/\")\n .some((part) => part === \"\" || part === \".\" || part === \"..\")\n ) {\n throw new TypeError(\n `Skills root must be a normalized absolute path: ${root}`\n );\n }\n return normalized;\n}\n\n/**\n * Computer raises `ENOENT` errors with a `code`. Over RPC only the message\n * may survive, so match that too.\n */\nfunction isNotFound(error: unknown): boolean {\n if (!(error instanceof Error)) return false;\n return (\n (\"code\" in error && error.code === \"ENOENT\") ||\n /ENOENT|no such (file|path)/i.test(error.message)\n );\n}\n\nasync function drain(stream: ReadableStream<Uint8Array>): Promise<Uint8Array> {\n const parts: Uint8Array[] = [];\n let total = 0;\n const reader = stream.getReader();\n try {\n while (true) {\n const { value, done } = await reader.read();\n if (done) break;\n parts.push(value);\n total += value.byteLength;\n }\n } finally {\n reader.releaseLock();\n }\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const part of parts) {\n bytes.set(part, offset);\n offset += part.byteLength;\n }\n return bytes;\n}\n","import { err, ok, type SkillResult } from \"./result\";\nimport {\n describeSkillResource,\n encodeSkillResourceContent,\n type SkillResource\n} from \"./resource\";\nimport {\n SkillResourceNotFoundError,\n SkillSourceError,\n type SkillListing,\n type SkillSource\n} from \"./source\";\nimport type { SkillName } from \"./skill\";\nimport { indexSkillTree, type SkillTreeFile } from \"./tree\";\n\n/** Options for {@link r2}. */\nexport interface R2SkillSourceOptions {\n /** Key prefix that holds the skill directories, such as `skills/`. */\n readonly prefix?: string;\n /** Source id for diagnostics. Defaults to `r2:<prefix>`. */\n readonly id?: string;\n /** Only serve these skill names. Serves every skill when omitted. */\n readonly skills?: readonly string[];\n /**\n * How long a bucket listing is reused before the bucket is listed again.\n * Defaults to 60 seconds; `0` lists on every call.\n */\n readonly refreshIntervalMs?: number;\n}\n\n/**\n * Create a read-only source backed by an R2 bucket.\n *\n * The bucket holds the Agent Skills layout under `prefix`:\n * `<prefix><skill-name>/SKILL.md`, plus any bundled files beside it.\n *\n * @param bucket - The R2 binding.\n * @param options - Prefix, id, name allowlist, and listing cache interval.\n * @returns A source that reads skills from the bucket.\n */\nexport function r2(\n bucket: R2Bucket,\n options: R2SkillSourceOptions = {}\n): SkillSource {\n const prefix = normalizePrefix(options.prefix);\n const id = options.id ?? `r2:${prefix || \"/\"}`;\n const allowed = options.skills?.length ? new Set(options.skills) : null;\n const refreshIntervalMs = options.refreshIntervalMs ?? 60_000;\n let cached: {\n listing: SkillListing;\n directories: ReadonlyMap<SkillName, string>;\n at: number;\n } | null = null;\n\n async function list(): Promise<SkillResult<SkillListing, SkillSourceError>> {\n if (cached && Date.now() - cached.at < refreshIntervalMs) {\n return ok(cached.listing);\n }\n try {\n const files: SkillTreeFile[] = (await listAll(bucket, prefix)).map(\n (object) => ({\n path: object.key.slice(prefix.length),\n size: object.size\n })\n );\n const { listing, directories } = await indexSkillTree(\n files,\n async (path) => {\n const object = await bucket.get(`${prefix}${path}`);\n return object ? object.text() : null;\n }\n );\n const filtered: SkillListing = allowed\n ? {\n skills: listing.skills.filter(({ skill }) =>\n allowed.has(skill.name)\n ),\n invalid: listing.invalid\n }\n : listing;\n cached = { listing: filtered, directories, at: Date.now() };\n return ok(filtered);\n } catch (cause) {\n return err(new SkillSourceError(id, \"list\", cause));\n }\n }\n\n return {\n id,\n list,\n // Reads go straight to the object. Relisting the bucket here would\n // cost a full scan per file, and `run_skill_script` reads every file\n // of a skill.\n async readResource(skill, path) {\n if (allowed && !allowed.has(skill)) {\n return err(new SkillResourceNotFoundError(skill, path));\n }\n try {\n // Lenient names can differ from their directory.\n const directory = cached?.directories.get(skill) ?? skill;\n const object = await bucket.get(`${prefix}${directory}/${path}`);\n if (!object) return err(new SkillResourceNotFoundError(skill, path));\n const info = describeSkillResource(path, object.size);\n const bytes = new Uint8Array(await object.arrayBuffer());\n const resource: SkillResource = {\n ...info,\n content: encodeSkillResourceContent(bytes, info.encoding)\n };\n return ok(resource);\n } catch (cause) {\n return err(new SkillSourceError(id, \"read-resource\", cause));\n }\n }\n };\n}\n\nfunction normalizePrefix(prefix: string | undefined): string {\n if (!prefix) return \"\";\n return prefix.endsWith(\"/\") ? prefix : `${prefix}/`;\n}\n\nasync function listAll(\n bucket: R2Bucket,\n prefix: string\n): Promise<Array<{ key: string; size: number }>> {\n const objects: Array<{ key: string; size: number }> = [];\n let cursor: string | undefined;\n do {\n const page = await bucket.list({ prefix, cursor });\n objects.push(\n ...page.objects.map((object) => ({ key: object.key, size: object.size }))\n );\n cursor = page.truncated ? page.cursor : undefined;\n } while (cursor);\n return objects;\n}\n","import { err, ok } from \"./result\";\nimport {\n describeSkillResource,\n parseSkillResourcePath,\n type SkillResource,\n type SkillResourceInfo,\n type SkillResourceKind\n} from \"./resource\";\nimport { parseSkillFrontmatter } from \"./skill\";\nimport {\n SkillResourceNotFoundError,\n type InvalidSkill,\n type ListedSkill,\n type SkillListing,\n type SkillSource\n} from \"./source\";\n\n/** Skills defined in code, for tests and small fixed sets. */\nexport interface SkillManifest {\n /** Source id used in diagnostics. */\n readonly id: string;\n /** The skills, in priority order. */\n readonly skills: readonly SkillManifestEntry[];\n /**\n * @deprecated Ignored. Catalogs fingerprint the prompt they render, so\n * sources no longer carry a fingerprint.\n */\n readonly fingerprint?: string;\n}\n\n/** One skill in a {@link SkillManifest}, written as `SKILL.md` fields. */\nexport interface SkillManifestEntry {\n /** Spec-valid skill name. */\n readonly name: string;\n /** What the skill does and when to use it. */\n readonly description: string;\n /** Markdown instructions. */\n readonly body: string;\n /** License name or bundled license file. */\n readonly license?: string;\n /** Environment requirements. */\n readonly compatibility?: string;\n /**\n * String key-value metadata. Scalar values are converted to strings, as\n * in `SKILL.md`; nested values make the entry invalid.\n */\n readonly metadata?: Readonly<Record<string, unknown>>;\n /** Space-separated pre-approved tools. */\n readonly allowedTools?: string;\n /** Files bundled with the skill. */\n readonly resources?: readonly SkillManifestResource[];\n /** @deprecated Ignored. */\n readonly version?: string;\n /** @deprecated Ignored; the entry fields define the skill. */\n readonly rawContent?: string;\n}\n\n/** A file in a {@link SkillManifestEntry}. */\nexport interface SkillManifestResource {\n /** Path relative to the skill directory. */\n readonly path: string;\n /** UTF-8 text, or base64 when `encoding` is `\"base64\"`. */\n readonly content: string;\n /** Overrides the encoding inferred from the file extension. */\n readonly encoding?: \"text\" | \"base64\";\n /** Overrides the MIME type inferred from the file extension. */\n readonly mimeType?: string;\n /** Overrides the kind inferred from the top-level directory. */\n readonly kind?: SkillResourceKind;\n /** @deprecated Ignored; the size is the content's length. */\n readonly size?: number;\n /** @deprecated Ignored; scripts are always run as stored. */\n readonly precompiled?: boolean;\n}\n\n/**\n * Create a source from skills defined in code.\n *\n * Entries pass the same checks as `SKILL.md` files from other sources:\n * broken spec rules become warnings, and entries without a usable\n * name or description are reported as invalid. Useful for tests and for small fixed skill sets\n * that do not need a Workspace or bucket.\n *\n * @param definition - The skills to serve.\n * @returns A source that always lists the same skills.\n */\nexport function manifest(definition: SkillManifest): SkillSource {\n const contents = new Map<string, Map<string, SkillResource>>();\n const skills: ListedSkill[] = [];\n const invalid: InvalidSkill[] = [];\n\n for (const entry of definition.skills) {\n const parsed = parseSkillFrontmatter(\n {\n name: entry.name,\n description: entry.description,\n license: entry.license,\n compatibility: entry.compatibility,\n metadata: entry.metadata,\n \"allowed-tools\": entry.allowedTools\n },\n entry.body\n );\n if (!parsed.ok) {\n invalid.push({\n location: `${definition.id}:${entry.name}`,\n error: parsed.error\n });\n continue;\n }\n if (contents.has(parsed.value.name)) continue;\n\n const files = new Map<string, SkillResource>();\n const resources: SkillResourceInfo[] = [];\n for (const resource of entry.resources ?? []) {\n const path = parseSkillResourcePath(resource.path);\n if (!path.ok) continue;\n const inferred = describeSkillResource(path.value);\n const info: SkillResourceInfo = {\n ...inferred,\n kind: resource.kind ?? inferred.kind,\n encoding: resource.encoding ?? inferred.encoding,\n ...(resource.mimeType === undefined\n ? {}\n : { mimeType: resource.mimeType })\n };\n resources.push(info);\n files.set(path.value, { ...info, content: resource.content });\n }\n resources.sort((a, b) => a.path.localeCompare(b.path));\n contents.set(parsed.value.name, files);\n skills.push({\n skill: parsed.value,\n resources,\n ...(parsed.warnings.length === 0 ? {} : { warnings: parsed.warnings })\n });\n }\n\n const listing: SkillListing = { skills, invalid };\n return {\n id: definition.id,\n async list() {\n return ok(listing);\n },\n async readResource(skill, path) {\n const resource = contents.get(skill)?.get(path);\n return resource\n ? ok(resource)\n : err(new SkillResourceNotFoundError(skill, path));\n }\n };\n}\n\n/**\n * Create a source from skills defined in code.\n *\n * @deprecated Use {@link manifest}.\n * @param definition - The skills to serve.\n * @returns A source that always lists the same skills.\n */\nexport const fromManifest = manifest;\n"],"mappings":";;;;;;;;;;;;;;;;AAoCA,eAAsB,eACpB,OACA,eACA,UACoB;CACpB,MAAM,8BAAc,IAAI,IAA6B;CACrD,KAAK,MAAM,QAAQ,OAAO;EACxB,MAAM,QAAQ,KAAK,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I,CAAC;EACrD;CACF;AACF;;;;;;;;AASA,MAAa,eAAe"}
@@ -0,0 +1,37 @@
1
+ import { a as SkillScriptRunner } from "../script-CFDLTk5b.js";
2
+ import { t as SkillScriptWorkspace } from "../script-workspace-BpdAYq1R.js";
3
+ import { ToolSet } from "ai";
4
+
5
+ //#region src/skills/runner.d.ts
6
+ /**
7
+ * Options for {@link runner}.
8
+ *
9
+ * @experimental Skill script execution is experimental and the option shape
10
+ * may change before stabilizing.
11
+ */
12
+ interface WorkerSkillScriptRunnerOptions {
13
+ loader: WorkerLoader;
14
+ timeout?: number;
15
+ network?: boolean;
16
+ workspace?: "none" | "read" | "read-write";
17
+ workspaceInstance?: SkillScriptWorkspace;
18
+ tools?: ToolSet | (() => ToolSet | Promise<ToolSet>);
19
+ }
20
+ /**
21
+ * Create a skill script runner backed by a Worker Loader.
22
+ *
23
+ * Capabilities are opt-in and enforced by a single host bridge: no network and
24
+ * no tools by default, read-only workspace access when `workspaceInstance` is
25
+ * provided. JS/TS scripts are function-style (`export default run(input, ctx)`)
26
+ * and receive `ctx = { skill, files, workspace, tools, output }`. Python and
27
+ * Bash use the path-based `/skill`, `/input.json`, `/output` contract.
28
+ *
29
+ * @experimental Skill script execution is experimental and may change before
30
+ * stabilizing.
31
+ */
32
+ declare function runner(
33
+ options: WorkerSkillScriptRunnerOptions
34
+ ): SkillScriptRunner;
35
+ //#endregion
36
+ export { WorkerSkillScriptRunnerOptions, runner };
37
+ //# sourceMappingURL=runner.d.ts.map