experimental-ash 0.22.2 → 0.23.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.
- package/CHANGELOG.md +14 -0
- package/dist/docs/public/faqs.md +67 -0
- package/dist/docs/public/meta.json +1 -0
- package/dist/docs/public/schedules.md +11 -0
- package/dist/docs/public/session-context.md +46 -89
- package/dist/docs/public/skills.md +13 -0
- package/dist/docs/public/subagents.md +12 -6
- package/dist/docs/public/tools.md +9 -13
- package/dist/docs/public/typescript-api.md +2 -2
- package/dist/src/chunks/{client-CKsU8Li3.js → client-nshDsWNF.js} +1 -1
- package/dist/src/chunks/{dev-authored-source-watcher-BLzYWh05.js → dev-authored-source-watcher-d_35Mp8T.js} +1 -1
- package/dist/src/chunks/{host-DREC8e8Z.js → host-tji7W0Nn.js} +2 -2
- package/dist/src/chunks/paths-YoCQlavu.js +89 -0
- package/dist/src/chunks/{prewarm-hz8p2jlZ.js → prewarm-6duWvvb5.js} +1 -1
- package/dist/src/cli/commands/info.js +1 -1
- package/dist/src/cli/dev/repl.js +2 -2
- package/dist/src/cli/run.js +1 -1
- package/dist/src/client/session.js +8 -0
- package/dist/src/client/types.d.ts +12 -1
- package/dist/src/compiled/.vendor-stamp.json +1 -1
- package/dist/src/compiled/@workflow/core/_ms.d.ts +4 -0
- package/dist/src/compiled/@workflow/core/_workflow-serde.d.ts +5 -0
- package/dist/src/compiled/@workflow/core/_workflow-utils.d.ts +8 -0
- package/dist/src/compiled/@workflow/core/_workflow-world.d.ts +59 -0
- package/dist/src/compiled/@workflow/core/capabilities.d.ts +45 -0
- package/dist/src/compiled/@workflow/core/capture-stack.d.ts +16 -0
- package/dist/src/compiled/@workflow/core/class-serialization.d.ts +31 -0
- package/dist/src/compiled/@workflow/core/classify-error.d.ts +19 -0
- package/dist/src/compiled/@workflow/core/context-errors.d.ts +27 -0
- package/dist/src/compiled/@workflow/core/context-violation-error.d.ts +97 -0
- package/dist/src/compiled/@workflow/core/create-hook.d.ts +179 -0
- package/dist/src/compiled/@workflow/core/define-hook.d.ts +68 -0
- package/dist/src/compiled/@workflow/core/describe-error.d.ts +70 -0
- package/dist/src/compiled/@workflow/core/encryption.d.ts +45 -0
- package/dist/src/compiled/@workflow/core/events-consumer.d.ts +64 -0
- package/dist/src/compiled/@workflow/core/flushable-stream.d.ts +82 -0
- package/dist/src/compiled/@workflow/core/global.d.ts +48 -0
- package/dist/src/compiled/@workflow/core/index.d.ts +19 -38
- package/dist/src/compiled/@workflow/core/log-format.d.ts +25 -0
- package/dist/src/compiled/@workflow/core/logger.d.ts +29 -0
- package/dist/src/compiled/@workflow/core/private.d.ts +59 -10
- package/dist/src/compiled/@workflow/core/runtime/constants.d.ts +4 -0
- package/dist/src/compiled/@workflow/core/runtime/get-port-lazy.d.ts +10 -0
- package/dist/src/compiled/@workflow/core/runtime/get-world-lazy.d.ts +32 -0
- package/dist/src/compiled/@workflow/core/runtime/helpers.d.ts +97 -0
- package/dist/src/compiled/@workflow/core/runtime/resume-hook.d.ts +77 -0
- package/dist/src/compiled/@workflow/core/runtime/run.d.ts +134 -0
- package/dist/src/compiled/@workflow/core/runtime/runs.d.ts +50 -0
- package/dist/src/compiled/@workflow/core/runtime/start.d.ts +59 -0
- package/dist/src/compiled/@workflow/core/runtime/step-executor.d.ts +40 -0
- package/dist/src/compiled/@workflow/core/runtime/step-handler.d.ts +2 -0
- package/dist/src/compiled/@workflow/core/runtime/suspension-handler.d.ts +42 -0
- package/dist/src/compiled/@workflow/core/runtime/world-init.d.ts +75 -0
- package/dist/src/compiled/@workflow/core/runtime/world.d.ts +32 -0
- package/dist/src/compiled/@workflow/core/runtime.d.ts +22 -67
- package/dist/src/compiled/@workflow/core/schemas.d.ts +15 -0
- package/dist/src/compiled/@workflow/core/serialization/client.d.ts +17 -0
- package/dist/src/compiled/@workflow/core/serialization/codec-devalue.d.ts +14 -0
- package/dist/src/compiled/@workflow/core/serialization/codec.d.ts +90 -0
- package/dist/src/compiled/@workflow/core/serialization/encryption.d.ts +32 -0
- package/dist/src/compiled/@workflow/core/serialization/errors.d.ts +21 -0
- package/dist/src/compiled/@workflow/core/serialization/format.d.ts +60 -0
- package/dist/src/compiled/@workflow/core/serialization/index.d.ts +18 -0
- package/dist/src/compiled/@workflow/core/serialization/reducers/class.d.ts +11 -0
- package/dist/src/compiled/@workflow/core/serialization/reducers/common.d.ts +16 -0
- package/dist/src/compiled/@workflow/core/serialization/reducers/step-function.d.ts +35 -0
- package/dist/src/compiled/@workflow/core/serialization/step.d.ts +17 -0
- package/dist/src/compiled/@workflow/core/serialization/types.d.ts +201 -0
- package/dist/src/compiled/@workflow/core/serialization/workflow.d.ts +29 -0
- package/dist/src/compiled/@workflow/core/serialization-format.d.ts +171 -0
- package/dist/src/compiled/@workflow/core/serialization.d.ts +329 -0
- package/dist/src/compiled/@workflow/core/sleep.d.ts +33 -0
- package/dist/src/compiled/@workflow/core/source-map.d.ts +10 -0
- package/dist/src/compiled/@workflow/core/step/context-storage.d.ts +13 -0
- package/dist/src/compiled/@workflow/core/step/get-closure-vars.d.ts +9 -0
- package/dist/src/compiled/@workflow/core/step/get-step-metadata.d.ts +42 -0
- package/dist/src/compiled/@workflow/core/step/get-workflow-metadata.d.ts +7 -0
- package/dist/src/compiled/@workflow/core/step/writable-stream.d.ts +22 -0
- package/dist/src/compiled/@workflow/core/step.d.ts +4 -0
- package/dist/src/compiled/@workflow/core/symbols.d.ts +20 -0
- package/dist/src/compiled/@workflow/core/telemetry/semantic-conventions.d.ts +283 -0
- package/dist/src/compiled/@workflow/core/telemetry.d.ts +53 -0
- package/dist/src/compiled/@workflow/core/types.d.ts +14 -0
- package/dist/src/compiled/@workflow/core/util.d.ts +40 -0
- package/dist/src/compiled/@workflow/core/version.d.ts +2 -0
- package/dist/src/compiled/@workflow/core/vm/index.d.ts +17 -0
- package/dist/src/compiled/@workflow/core/vm/uint8array-base64.d.ts +21 -0
- package/dist/src/compiled/@workflow/core/vm/uuid.d.ts +10 -0
- package/dist/src/compiled/@workflow/core/workflow/abort-controller.d.ts +65 -0
- package/dist/src/compiled/@workflow/core/workflow/create-hook.d.ts +7 -0
- package/dist/src/compiled/@workflow/core/workflow/define-hook.d.ts +10 -0
- package/dist/src/compiled/@workflow/core/workflow/get-workflow-metadata.d.ts +32 -0
- package/dist/src/compiled/@workflow/core/workflow/hook.d.ts +4 -0
- package/dist/src/compiled/@workflow/core/workflow/index.d.ts +11 -0
- package/dist/src/compiled/@workflow/core/workflow/sleep.d.ts +4 -0
- package/dist/src/compiled/@workflow/core/workflow/world-init-stub.d.ts +15 -0
- package/dist/src/compiled/@workflow/core/workflow/writable-stream.d.ts +3 -0
- package/dist/src/compiled/@workflow/core/workflow.d.ts +1 -38
- package/dist/src/evals/cli/eval.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/protocol/message.d.ts +6 -1
- package/dist/src/public/channels/ash.js +50 -3
- package/dist/src/public/context/index.d.ts +4 -7
- package/dist/src/public/context/index.js +4 -5
- package/dist/src/public/definitions/state.d.ts +33 -0
- package/dist/src/public/definitions/state.js +34 -0
- package/dist/src/public/next/index.d.ts +7 -0
- package/dist/src/public/next/index.js +2 -0
- package/dist/src/public/next/vercel-json.d.ts +1 -0
- package/dist/src/public/next/vercel-json.js +1 -0
- package/dist/src/react/index.d.ts +1 -1
- package/dist/src/react/use-ash-agent.d.ts +8 -0
- package/dist/src/react/use-ash-agent.js +26 -4
- package/dist/src/services/dev-client.d.ts +4 -1
- package/dist/src/services/dev-client.js +1 -0
- package/package.json +1 -1
- package/dist/src/chunks/paths-C6sp4T2U.js +0 -88
|
@@ -1,88 +0,0 @@
|
|
|
1
|
-
import{i as e}from"./chunk-8L7ocgPr.js";import{t}from"./gray-matter-BxS7ZG-J.js";import{c as n,d as r,f as i,l as a,o,p as s,s as c,t as l,u}from"./authored-module-loader-XcFLnl49.js";import{n as d,t as f}from"./guards-CjJ3lmju.js";import{t as p}from"./errors-DsO9xmQL.js";import{n as m,o as h,r as g,t as _}from"./package-DmsQgn4v.js";import{a as v,b as ee,i as te,n as ne,o as re,r as ie,s as ae,t as oe,u as se,y as ce}from"./types-MZUhN0Zy.js";import{t as le}from"./runtime-model-BWu6M_hq.js";import{z as y}from"#compiled/zod/index.js";import{basename as ue,dirname as b,join as x,posix as de,relative as fe,resolve as S,sep as pe}from"node:path";import{access as me,cp as he,mkdir as C,readFile as ge,readdir as _e,rm as ve,stat as ye,writeFile as w}from"node:fs/promises";import{createHash as be}from"node:crypto";import{existsSync as xe,readFileSync as Se,readdirSync as Ce,rmSync as we}from"node:fs";import{pathToFileURL as Te}from"node:url";import{Buffer as Ee}from"node:buffer";import"#compiled/@workflow/errors/index.js";import{resumeHook as De}from"#compiled/@workflow/core/runtime.js";import{AsyncLocalStorage as Oe}from"node:async_hooks";import{SpanStatusCode as ke,trace as Ae}from"#compiled/@opentelemetry/api/index.js";import{getErrorMessage as je}from"#compiled/@ai-sdk/provider/index.js";import{inspect as Me}from"node:util";import{fromError as Ne}from"#compiled/zod-validation-error/index.js";import{createRemoteJWKSet as Pe,decodeJwt as Fe,jwtVerify as Ie}from"#compiled/jose/index.js";import Le from"#compiled/turndown/index.js";const Re=y.union([y.literal(`error`),y.literal(`warning`)]);y.object({code:y.string(),message:y.string(),severity:Re,sourcePath:y.string()}).strict();const ze=y.object({errors:y.number().finite(),warnings:y.number().finite()}).strict();function Be(e){return e}function T(e){return Be({...e,severity:`error`})}function Ve(e){return Be({...e,severity:`warning`})}function He(e){return e.reduce((e,t)=>(t.severity===`error`?e.errors+=1:e.warnings+=1,e),{errors:0,warnings:0})}function Ue(e){return e.some(e=>e.severity===`error`)}const We=[`.cts`,`.mts`,`.cjs`,`.mjs`,`.ts`,`.js`],Ge=[`package.json`,`vercel.json`],Ke=[`agent.ts`,`agent.cts`,`agent.mts`,`agent.js`,`agent.cjs`,`agent.mjs`,`instructions.md`,`instructions.ts`,`instructions.cts`,`instructions.mts`,`instructions.js`,`instructions.cjs`,`instructions.mjs`,`system.md`,`system.ts`,`system.cts`,`system.mts`,`system.js`,`system.cjs`,`system.mjs`],qe=[`channels`,`connections`,`hooks`,`lib`,`sandbox`,`skills`,`tools`,`schedules`,`subagents`],Je=[`agent.ts`,`agent.cts`,`agent.mts`,`agent.js`,`agent.cjs`,`agent.mjs`,`instructions.md`,`instructions.ts`,`instructions.cts`,`instructions.mts`,`instructions.js`,`instructions.cjs`,`instructions.mjs`,`system.md`,`system.ts`,`system.cts`,`system.mts`,`system.js`,`system.cjs`,`system.mjs`],Ye=[`hooks`,`lib`,`sandbox`,`skills`,`tools`,`subagents`],Xe=[`SKILL.md`],Ze=[`scripts`,`references`,`assets`],Qe=new Set(Ge);new Set(Ke),new Set(qe),new Set(Je),new Set(Ye),new Set(Xe),new Set(Ze);function E(e){return e.isDirectory()?`directory`:e.isFile()?`file`:`other`}function $e(e,t){return t===`file`&&Qe.has(e)}function et(e,t){if(t===`file`)return k(e,`agent`)?`agent-config-module`:e===`instructions.md`?`instructions-markdown`:k(e,`instructions`)?`instructions-module`:e===`system.md`?`system-markdown`:k(e,`system`)?`system-module`:`unknown`;if(t===`directory`){if(e===`channels`)return`channels-directory`;if(e===`connections`)return`connections-directory`;if(e===`hooks`)return`hooks-directory`;if(e===`lib`)return`lib-directory`;if(e===`skills`)return`skills-directory`;if(e===`sandbox`)return`sandbox-directory`;if(e===`tools`)return`tools-directory`;if(e===`schedules`)return`schedules-directory`;if(e===`subagents`)return`subagents-directory`}return`unknown`}function tt(e,t){if(t===`file`)return k(e,`agent`)?`agent-config-module`:e===`instructions.md`?`instructions-markdown`:k(e,`instructions`)?`instructions-module`:e===`system.md`?`system-markdown`:k(e,`system`)?`system-module`:`unknown`;if(t===`directory`){if(e===`connections`)return`connections-directory`;if(e===`hooks`)return`hooks-directory`;if(e===`lib`)return`lib-directory`;if(e===`sandbox`)return`sandbox-directory`;if(e===`skills`)return`skills-directory`;if(e===`tools`)return`tools-directory`;if(e===`subagents`)return`subagents-directory`;if(e===`schedules`)return`invalid-schedules-directory`}return`unknown`}function nt(e,t){if(t===`file`)return e===`SKILL.md`?`skill-markdown`:`skill-resource`;if(t===`directory`){if(e===`scripts`)return`skill-scripts-directory`;if(e===`references`)return`skill-references-directory`;if(e===`assets`)return`skill-assets-directory`}return`skill-resource`}function rt(e,t){if(t===`directory`)return`skill-package-directory`;if(t===`file`){if(e.endsWith(`.md`))return`flat-skill-markdown`;if(O(e)!==null)return`flat-skill-module`}return`unknown`}function D(e){return e.replaceAll(pe,`/`).replace(/^\.\//,``).replace(/^\/+/,``)}function O(e){for(let t of We)if(e.endsWith(t)&&e.length>t.length)return e.slice(0,-t.length);return null}function k(e,t){return O(e)===t}function A(e){let t=D(e),n=t.lastIndexOf(`/`),r=t.lastIndexOf(`.`);return r===-1||r<n?t:t.slice(0,r)}var it=e(t(),1);function at(e,t){let r=c(e,t);if(n(r,[`build`,`compaction`,`description`,`metadata`,`model`,`modelContextWindowTokens`,`modelOptions`],t),r.model===void 0)throw Error(`${t} The "model" field is required.`);let a={model:r.model};r.description!==void 0&&(a.description=u(r.description,t));let o=i(r,`metadata`,t);return o!==void 0&&(a.metadata=o),r.compaction!==void 0&&(a.compaction=lt(r.compaction,t)),r.build!==void 0&&(a.build=st(r.build,t)),r.modelOptions!==void 0&&(a.modelOptions=ct(r.modelOptions,t)),r.modelContextWindowTokens!==void 0&&(a.modelContextWindowTokens=ot(r.modelContextWindowTokens,t)),a}function ot(e,t){if(typeof e!=`number`||!Number.isInteger(e)||e<=0)throw Error(t);return e}function st(e,t){let r=c(e,t);n(r,[`externalDependencies`],t);let i={};if(r.externalDependencies!==void 0){if(!Array.isArray(r.externalDependencies))throw Error(t);i.externalDependencies=Object.freeze(r.externalDependencies.map(e=>u(e,t)))}return i}function ct(e,t){let r=c(e,t);n(r,[`providerOptions`],t);let i=r.providerOptions;return i===void 0?{}:{providerOptions:a(i,t)}}function lt(e,t){let r=c(e,t);n(r,[`model`,`modelContextWindowTokens`,`thresholdPercent`],t);let i={};if(r.model!==void 0&&(i.model=r.model),r.modelContextWindowTokens!==void 0&&(i.modelContextWindowTokens=ot(r.modelContextWindowTokens,t)),r.thresholdPercent!==void 0){let e=r.thresholdPercent;if(typeof e!=`number`||!Number.isFinite(e)||e<0||e>1)throw Error(t);i.thresholdPercent=e}return i}function ut(e,t){let r=c(e,t);return n(r,[`markdown`],t),{markdown:u(r.markdown,t)}}function dt(e,t){let r=c(e,t);n(r,[`description`,`files`,`license`,`markdown`,`metadata`],t);let a={description:u(r.description,t),markdown:u(r.markdown,t)},o=r.license,s=i(r,`metadata`,t);return o!==void 0&&(a.license=u(o,t)),s!==void 0&&(a.metadata=s),r.files!==void 0&&(a.files=ft(r.files,t)),a}function ft(e,t){let n=c(e,t),r={};for(let[e,i]of Object.entries(n)){if(typeof i==`string`||i instanceof Uint8Array){r[e]=i;continue}throw Error(`${t} Expected skill file "${e}" to be a string or Uint8Array.`)}return r}function pt(e,t){let r=c(e,t);n(r,[`cron`,`markdown`,`run`],t);let i=u(r.cron,t),a=r.markdown!==void 0,s=r.run!==void 0;if(a&&s)throw Error(`${t} Pass either "markdown" (fire-and-forget) or "run" (handler) — not both.`);if(!a&&!s)throw Error(`${t} Must provide either "markdown" (fire-and-forget) or "run" (handler).`);let l={cron:i};return a?l.markdown=u(r.markdown,t):l.run=o(r.run,t),l}function mt(e){return e}function ht(e){return e}function gt(e){return e}const _t=/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/;function vt(e){if(!it.default.test(e))return{hasFrontmatter:!1,frontmatter:{},markdown:e};let t;try{t=(0,it.default)(e)}catch(t){throw St(e)&&!Ct(e)?Error(`Markdown frontmatter is missing a closing delimiter.`):t}if(!d(t.data))throw Error(`Markdown frontmatter must parse to an object.`);return{hasFrontmatter:!0,frontmatter:t.data,markdown:wt(t.content)}}function yt(e){return gt(ut({markdown:e},`Expected authored instructions markdown to match the public Ash shape.`))}function bt(e){let t=vt(e);if(!t.hasFrontmatter)throw Error(`Schedule markdown must start with YAML frontmatter declaring "cron".`);if(`run`in t.frontmatter)throw Error('Markdown-form schedules do not support the "run" frontmatter key. Use a TypeScript schedule (`<name>.ts`) to author a handler.');return mt(pt({...t.frontmatter,markdown:t.markdown},`Expected authored schedule markdown to match the public Ash shape.`))}function xt(e,t={}){let n=vt(e),r=t.slug;if(r===void 0&&!n.hasFrontmatter)throw Error(`Skill markdown must start with YAML frontmatter.`);let i=Dt(n.frontmatter),a=Ot(i.description,`description`),o=r===void 0?kt(i.description,`description`):a??t.description??jt(n.markdown,r),s={...i,description:o,markdown:n.markdown};return Tt(s,i),ht(dt(s,`Expected authored skill markdown to match the public Ash shape.`))}function St(e){return e.startsWith(`---
|
|
2
|
-
`)||e.startsWith(`---\r
|
|
3
|
-
`)}function Ct(e){return _t.test(e)}function wt(e){return e.replace(/^\r?\n/u,``)}function Tt(e,t){let n=Ot(t.license,`license`);n!==void 0&&(e.license=n);let r=At(t.metadata,`metadata`);r!==void 0&&(e.metadata=r)}const Et=[`name`];function Dt(e){let t={...e};for(let e of Et)delete t[e];return t}function Ot(e,t){if(e!=null){if(typeof e!=`string`)throw Error(`Expected "${t}" frontmatter to be a string.`);return e}}function kt(e,t){let n=Ot(e,t);if(n===void 0)throw Error(`Missing required "${t}" frontmatter.`);return n}function At(e,t){if(e==null)return;if(!d(e))throw Error(`Expected "${t}" frontmatter to be an object.`);let n=Object.entries(e).map(([e,n])=>{if(typeof n!=`string`)throw Error(`Expected "${t}.${e}" frontmatter to be a string.`);return[e,n]});return Object.fromEntries(n)}function jt(e,t){let n=e.split(/\r?\n/u).map(e=>e.trim()).find(e=>e!==``&&!e.startsWith("```"));return n===void 0?`Instructions for the ${t} skill.`:n.replace(/^[#>*\-\s]+/u,``).trim()||`Instructions for the ${t} skill.`}function Mt(e){let t=S(e.appRoot),n=S(e.agentRoot),r={agentId:e.agentId??Nt(t,n,e.packageName),agentRoot:n,appRoot:t,channels:[...e.channels??[]],connections:[...e.connections??[]],diagnosticsSummary:He(e.diagnostics??[]),hooks:[...e.hooks??[]],lib:[...e.lib??[]],kind:`ash-agent-discovery-manifest`,sandbox:e.sandbox??null,sandboxWorkspaces:[...e.sandboxWorkspaces??[]],schedules:[...e.schedules??[]],skills:[...e.skills??[]],tools:[...e.tools??[]],version:12,subagents:[...e.subagents??[]]};return e.configModule!==void 0&&(r.configModule=e.configModule),e.instructions!==void 0&&(r.instructions=e.instructions),r}function Nt(e,t,n){let r=D(fe(e,t));return r===``||r===`.`||r===`agent`?n??ue(e):ue(t)}function j(e){return D(e)}function M(e){let t=D(e.logicalPath),n={sourceKind:`module`,logicalPath:t,sourceId:e.sourceId??j(t)};return e.exportName!==void 0&&(n.exportName=e.exportName),n}function Pt(e){return{...M(e),connectionName:e.connectionName}}function Ft(e){let t=D(e.logicalPath);return{entryPath:e.entryPath,logicalPath:t,manifest:e.manifest,rootPath:e.rootPath,sourceId:e.sourceId??j(t),subagentId:e.subagentId}}function It(e){let t={description:e.description,sourceKind:`skill-package`,logicalPath:D(e.logicalPath),markdown:e.markdown,name:e.name,rootPath:e.rootPath,skillFilePath:e.skillFilePath,skillId:e.skillId,sourceId:e.sourceId};return e.assetsPath!==void 0&&(t.assetsPath=e.assetsPath),e.license!==void 0&&(t.license=e.license),e.metadata!==void 0&&(t.metadata={...e.metadata}),e.referencesPath!==void 0&&(t.referencesPath=e.referencesPath),e.scriptsPath!==void 0&&(t.scriptsPath=e.scriptsPath),t}async function Lt(e){let t=D(e.logicalPath);return{definition:e.lower(await e.source.readTextFile(e.sourcePath),{name:A(t)}),sourceKind:`markdown`,logicalPath:t,sourceId:j(t)}}function Rt(e,t){let n={moduleFileNames:[]};for(let r of e)if(r.isFile()){if(t.markdownFileName!==void 0&&r.name===t.markdownFileName){n.markdownFileName=r.name;continue}t.moduleBaseName!==void 0&&O(r.name)===t.moduleBaseName&&n.moduleFileNames.push(r.name)}return n.moduleFileNames.sort((e,t)=>e.localeCompare(t)),n}function zt(e,t){let n=new Map;for(let r of e){if(!r.isFile())continue;let e=t.allowMarkdown?Bt(r.name):null,i=t.allowModules?O(r.name):null,a=e??i;if(a===null)continue;let o=n.get(a);if(o===void 0&&(o={moduleFileNames:[],slotName:a},n.set(a,o)),e!==null){o.markdownFileName=r.name;continue}i!==null&&o.moduleFileNames.push(r.name)}return[...n.values()].map(e=>(e.moduleFileNames.sort((e,t)=>e.localeCompare(t)),e)).sort((e,t)=>e.slotName.localeCompare(t.slotName))}function Bt(e){return!e.endsWith(`.md`)||e.length<=3?null:e.slice(0,-3)}async function N(e){let t=x(e.rootPath,e.directoryName),n=e.rootEntries.find(t=>t.name===e.directoryName);if(n===void 0)return{diagnostics:[],sources:[]};if(!n.isDirectory())return{diagnostics:[T({code:e.invalidDirectoryCode,message:e.invalidDirectoryMessage,sourcePath:t})],sources:[]};let r=[],i=[];return await Vt({allowMarkdown:e.allowMarkdown===!0,diagnostics:r,markdownLowerer:e.allowMarkdown===!0?e.markdownLowerer:void 0,projectSource:e.source,recursive:e.recursive,relativeDirectory:e.directoryName,rootDirectoryPath:t,sources:i,subdirectoryRelative:``,unsupportedEntryCode:e.unsupportedEntryCode,unsupportedEntryMessage:e.unsupportedEntryMessage,unsupportedFileCode:e.unsupportedFileCode,unsupportedFileMessage:e.unsupportedFileMessage,validateSegment:e.validateSegment}),{diagnostics:r,sources:i}}async function Vt(e){let t=e.subdirectoryRelative===``?e.rootDirectoryPath:x(e.rootDirectoryPath,e.subdirectoryRelative),n=await P(e.projectSource,t);e.recursive&&await Ht(e,n,t),(e.unsupportedFileCode!==void 0||e.unsupportedEntryCode!==void 0)&&Ut(e,n,t),await Wt(e,n,t)}async function Ht(e,t,n){for(let r of t){if(!r.isDirectory())continue;let t=x(n,r.name);if(e.validateSegment!==void 0){let n=e.validateSegment(r.name,t);if(n!==null){e.diagnostics.push(n);continue}}await Vt({allowMarkdown:e.allowMarkdown,diagnostics:e.diagnostics,markdownLowerer:e.markdownLowerer,projectSource:e.projectSource,recursive:e.recursive,relativeDirectory:e.relativeDirectory,rootDirectoryPath:e.rootDirectoryPath,sources:e.sources,subdirectoryRelative:e.subdirectoryRelative===``?r.name:x(e.subdirectoryRelative,r.name),unsupportedEntryCode:e.unsupportedEntryCode,unsupportedEntryMessage:e.unsupportedEntryMessage,unsupportedFileCode:e.unsupportedFileCode,unsupportedFileMessage:e.unsupportedFileMessage,validateSegment:e.validateSegment})}}function Ut(e,t,n){for(let r of t){let t=E(r),i=x(n,r.name);if(t===`directory`)continue;if(t===`other`){e.unsupportedEntryCode!==void 0&&e.diagnostics.push(T({code:e.unsupportedEntryCode,message:e.unsupportedEntryMessage?.(i,e.relativeDirectory)??`Expected "${i}" to be a regular file or directory within "${e.relativeDirectory}/".`,sourcePath:i}));continue}if(e.unsupportedFileCode===void 0)continue;let a=O(r.name)!==null,o=e.allowMarkdown&&r.name.endsWith(`.md`);a||o||e.diagnostics.push(T({code:e.unsupportedFileCode,message:e.unsupportedFileMessage?.(i,e.relativeDirectory)??`Expected "${i}" to be a supported authored source within "${e.relativeDirectory}/".`,sourcePath:i}))}}async function Wt(e,t,n){for(let r of zt(t,{allowMarkdown:e.allowMarkdown,allowModules:!0})){let t=e.subdirectoryRelative===``?r.slotName:x(e.subdirectoryRelative,r.slotName),i=D(x(e.relativeDirectory,t));if(e.validateSegment!==void 0){let t=r.markdownFileName??r.moduleFileNames[0]??r.slotName,i=e.validateSegment(r.slotName,x(n,t));if(i!==null){e.diagnostics.push(i);continue}}if(r.markdownFileName!==void 0&&r.moduleFileNames.length>0){e.diagnostics.push(on(n,i,[r.markdownFileName,...r.moduleFileNames]));continue}if(r.moduleFileNames.length>1){e.diagnostics.push(sn(n,i,r.moduleFileNames));continue}if(r.markdownFileName!==void 0){let t=e.subdirectoryRelative===``?r.markdownFileName:x(e.subdirectoryRelative,r.markdownFileName),n=D(x(e.relativeDirectory,t));if(e.markdownLowerer===void 0)continue;let i=await Lt({logicalPath:n,lower:e.markdownLowerer,source:e.projectSource,sourcePath:x(e.rootDirectoryPath,t)});e.sources.push(i);continue}let[a]=r.moduleFileNames;if(a===void 0)continue;let o=e.subdirectoryRelative===``?a:x(e.subdirectoryRelative,a);e.sources.push(M({logicalPath:D(x(e.relativeDirectory,o))}))}}const Gt=`discover/module-slot-collision`,Kt=`discover/tools-directory-invalid`,qt=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,Jt=/^[a-z][a-z0-9-]{0,63}$/,Yt=/^(\.?[a-z][a-z0-9-]{0,63}|\[[a-zA-Z][a-zA-Z0-9_]{0,63}\])$/,Xt=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/;async function P(e,t){let n=[...await e.readDirectory(t)];return n.sort((e,t)=>e.name.localeCompare(t.name)),n}async function Zt(e){let t=await Qt({markdownFileName:`instructions.md`,moduleBaseName:`instructions`,rootEntries:e.rootEntries,rootPath:e.rootPath,slotLabel:`instructions`,source:e.source});if(t.diagnostics.length>0||t.source!==void 0)return{diagnostics:t.diagnostics,instructions:t.source};let n=await Qt({markdownFileName:`system.md`,moduleBaseName:`system`,rootEntries:e.rootEntries,rootPath:e.rootPath,slotLabel:`system`,source:e.source});if(n.source!==void 0){let t=n.source.sourceKind===`markdown`?`system.md`:n.source.logicalPath;return{diagnostics:[Ve({code:`discover/deprecated-system-slot`,message:`The "${t}" slot is deprecated. Rename it to "${t.replace(/^system/,`instructions`)}" — the runtime still loads the legacy slot for now, but support will be removed in a future release.`,sourcePath:x(e.rootPath,t)}),...n.diagnostics],instructions:n.source}}return n.diagnostics.length>0?{diagnostics:n.diagnostics}:{diagnostics:[T({code:`discover/required-instructions-missing`,message:`Expected one authored instructions prompt source at "instructions.md", "instructions.ts", "instructions.cts", "instructions.mts", "instructions.js", "instructions.cjs", or "instructions.mjs".`,sourcePath:e.rootPath})]}}async function Qt(e){let t=Rt(e.rootEntries,{markdownFileName:e.markdownFileName,moduleBaseName:e.moduleBaseName});if(t.markdownFileName!==void 0&&t.moduleFileNames.length>0)return{diagnostics:[on(e.rootPath,e.slotLabel,[t.markdownFileName,...t.moduleFileNames])]};if(t.moduleFileNames.length>1)return{diagnostics:[sn(e.rootPath,e.slotLabel,t.moduleFileNames)]};if(t.markdownFileName!==void 0)return{diagnostics:[],source:await Lt({logicalPath:e.markdownFileName,lower:yt,source:e.source,sourcePath:x(e.rootPath,t.markdownFileName)})};let[n]=t.moduleFileNames;return n===void 0?{diagnostics:[]}:{diagnostics:[],source:M({logicalPath:n})}}function $t(e){let t=Rt(e.rootEntries,{moduleBaseName:e.slotName});if(t.moduleFileNames.length>1)return{diagnostics:[sn(e.rootPath,e.slotName,t.moduleFileNames)]};let[n]=t.moduleFileNames;return n===void 0?e.missingDiagnostic===void 0?{diagnostics:[]}:{diagnostics:[T({code:e.missingDiagnostic.code,message:e.missingDiagnostic.message,sourcePath:e.rootPath})]}:{diagnostics:[],module:M({logicalPath:n})}}function en(e,t){return qt.test(e)?null:T({code:`discover/tool-name-invalid`,message:`Tool filename "${e}" is not a legal tool name. Expected ASCII letters, digits, underscores, and dashes only, starting with a letter, up to 64 characters.`,sourcePath:t})}function tn(e,t){return Jt.test(e)?null:T({code:`discover/connection-name-invalid`,message:`Connection filename "${e}" is not a legal connection name. Expected lowercase ASCII letters, digits, and dashes only, starting with a letter, up to 64 characters.`,sourcePath:t})}function nn(e,t){return Yt.test(e)?null:T({code:`discover/channel-name-invalid`,message:`Channel path segment "${e}" is not a legal channel name. Expected lowercase kebab-case (\`my-channel\`), optionally with a leading dot (\`.well-known\`), or a path parameter form (\`[sessionId]\`).`,sourcePath:t})}function rn(e,t){return Xt.test(e)?null:T({code:`discover/hook-name-invalid`,message:`Hook path segment "${e}" is not a legal hook name. Expected ASCII letters, digits, underscores, and dashes only, starting with a letter, up to 64 characters.`,sourcePath:t})}function an(e){return e.rootEntries.flatMap(t=>!t.isDirectory()||e.classifyEntry(t.name,E(t))!==`unknown`?[]:[Ve({code:`discover/unsupported-directory`,message:e.createUnsupportedDirectoryMessage(t.name),sourcePath:x(e.rootPath,t.name)})])}function on(e,t,n){return T({code:`discover/slot-collision`,message:`Found conflicting authored sources for "${t}": ${cn(n)}.`,sourcePath:e})}function sn(e,t,n){return T({code:Gt,message:`Found multiple authored module sources for "${t}": ${cn(n)}.`,sourcePath:e})}function cn(e){return e.map(e=>`"${e}"`).join(`, `)}async function ln(e){let t=`connections`,n=x(e.rootPath,t),r=e.rootEntries.find(e=>e.name===t);if(r===void 0)return{connections:[],diagnostics:[]};if(!r.isDirectory())return{connections:[],diagnostics:[T({code:`discover/connections-directory-invalid`,message:`Expected "${n}" to be a directory of authored connections.`,sourcePath:n})]};let i=await P(e.source,n),a=[],o=[],s=new Set;for(let e of zt(i,{allowMarkdown:!1,allowModules:!0})){let r=D(x(t,e.slotName));if(e.moduleFileNames.length>1){s.add(e.slotName),o.push(sn(n,r,e.moduleFileNames));continue}let[i]=e.moduleFileNames;if(i===void 0)continue;s.add(e.slotName);let c=tn(e.slotName,x(n,i));if(c!==null){o.push(c);continue}a.push(Pt({connectionName:e.slotName,logicalPath:x(t,i)}))}for(let r of i){if(!r.isDirectory())continue;let i=r.name,c=x(n,i);if(s.has(i)){o.push(T({code:`discover/connection-file-folder-collision`,message:`Connection "${i}" is defined twice. Found both file-form "connections/${i}.ts" and folder-form "connections/${i}/". Use one form, not both.`,sourcePath:c}));let e=a.findIndex(e=>e.connectionName===i);e!==-1&&a.splice(e,1);continue}let l=tn(i,c);if(l!==null){o.push(l);continue}let u=un(await P(e.source,c));if(u.length>1){o.push(T({code:Gt,message:`Found multiple connection definition modules inside "${D(x(t,i))}": `+u.map(e=>`"${e}"`).join(`, `),sourcePath:c}));continue}let[d]=u;if(d===void 0){o.push(T({code:`discover/connection-folder-empty`,message:`Connection folder "connections/${i}/" contains no "connection.ts" definition. Add "connections/${i}/connection.ts" or use the file form "connections/${i}.ts".`,sourcePath:c}));continue}a.push(Pt({connectionName:i,logicalPath:x(t,i,d)}))}return{connections:a,diagnostics:o}}function un(e){let t=e.filter(e=>e.isFile()),n=[];for(let e of zt(t,{allowMarkdown:!1,allowModules:!0}))e.slotName===`connection`&&n.push(...e.moduleFileNames);return n}const dn=`discover/lib-entry-unsupported`;async function fn(e){let t=await N({directoryName:`lib`,invalidDirectoryCode:`discover/lib-directory-invalid`,invalidDirectoryMessage:`Expected "${e.agentRoot}/lib" to be a directory of authored helper modules.`,recursive:!0,rootEntries:e.rootEntries,rootPath:e.agentRoot,source:e.source,unsupportedEntryCode:dn,unsupportedEntryMessage:e=>`Expected "${e}" to be a supported authored module within "lib/".`,unsupportedFileCode:dn,unsupportedFileMessage:e=>`Expected "${e}" to be a supported authored module within "lib/".`});return{diagnostics:t.diagnostics,lib:t.sources}}function F(){return{kind:`disk`,async readDirectory(e){return await _e(e,{withFileTypes:!0})},async readTextFile(e){return await ge(e,`utf8`)},async stat(e){try{let t=await ye(e);return t.isDirectory()?`directory`:t.isFile()?`file`:`other`}catch{return`missing`}}}}const I=`sandbox`,pn=`workspace`,mn=`sandbox`;async function hn(e){let t=[],n=e.rootEntries.find(e=>e.name===I);if(n===void 0)return gn({diagnostics:t,rootEntries:e.rootEntries,rootPath:e.rootPath});let r=x(e.rootPath,I);if(!n.isDirectory())return t.push(T({code:`discover/sandbox-directory-invalid`,message:`Expected "${r}" to be the sandbox folder.`,sourcePath:r})),{diagnostics:t,sandbox:null,sandboxWorkspace:null};let i=await P(e.source,r),a=_n(i),o=i.find(e=>e.name===pn&&e.isDirectory());if(a.length>1)return t.push(T({code:Gt,message:`Found multiple sandbox definition modules inside "${D(I)}": `+a.map(e=>`"${e}"`).join(`, `),sourcePath:r})),{diagnostics:t,sandbox:null,sandboxWorkspace:null};let[s]=a,c=s!==void 0,l=o!==void 0;if(!c&&!l)return t.push(T({code:`discover/sandbox-folder-empty`,message:`Sandbox folder "sandbox/" contains neither a "sandbox.<ext>" definition nor a "workspace/" subdirectory. Add one or the other, or remove the folder.`,sourcePath:r})),{diagnostics:t,sandbox:null,sandboxWorkspace:null};let u=null;c&&(u=M({logicalPath:x(I,s)}));let d=null;if(l){let n=x(r,pn),i=D(x(I,pn)),a=await yn(e.source,n);a===null?d={logicalPath:i,rootEntries:await vn(e.source,n),sourceId:j(i),sourcePath:n}:t.push(a)}return{diagnostics:t,sandbox:u,sandboxWorkspace:d}}function gn(e){let t=Rt(e.rootEntries,{moduleBaseName:mn});if(t.moduleFileNames.length>1)return e.diagnostics.push(T({code:Gt,message:`Found multiple top-level sandbox definition modules: `+t.moduleFileNames.map(e=>`"${e}"`).join(`, `),sourcePath:e.rootPath})),{diagnostics:e.diagnostics,sandbox:null,sandboxWorkspace:null};let[n]=t.moduleFileNames;return n===void 0?{diagnostics:e.diagnostics,sandbox:null,sandboxWorkspace:null}:{diagnostics:e.diagnostics,sandbox:M({logicalPath:n}),sandboxWorkspace:null}}function _n(e){let t=e.filter(e=>e.isFile()),n=[];for(let e of zt(t,{allowMarkdown:!1,allowModules:!0}))e.slotName===mn&&n.push(...e.moduleFileNames);return n}async function vn(e,t){let n=await P(e,t),r=[];for(let e of n){if(e.isDirectory()){r.push(`${e.name}/`);continue}e.isFile()&&r.push(e.name)}return r}async function yn(e,t){return(await P(e,t)).find(e=>e.name===`skills`)===void 0?null:T({code:`discover/sandbox-workspace-skills-reserved`,message:`"sandbox/workspace/skills/" is reserved for the framework skill discovery. Move skill files under "agent/skills/" instead, or rename the subtree.`,sourcePath:x(t,`skills`)})}const bn=`discover/skill-frontmatter-invalid`;async function xn(e){let t=e.source??F(),n=S(e.agentRoot),r=S(e.skillsDirectoryPath??x(n,`skills`)),i=D(e.skillsLogicalPath??fe(n,r)),a=await t.stat(r);if(a===`missing`)return{diagnostics:[],skills:[]};if(a!==`directory`)return{diagnostics:[T({code:`discover/skills-directory-invalid`,message:`Expected "${r}" to be a directory of authored skills.`,sourcePath:r})],skills:[]};let o=[],s=new Set,c=new Map,l=await P(t,r);for(let e of l){let n=await Sn({entryName:e.name,entryType:E(e),skillsDirectoryPath:r,skillsLogicalPath:i,source:t});if(o.push(...n.diagnostics),n.skill===null||n.skillId===null||s.has(n.skillId))continue;let a=c.get(n.skillId);if(a!==void 0){o.push(T({code:`discover/skill-collision`,message:`Found conflicting authored skill sources for "${n.skillId}": "${a.logicalPath}" and "${n.logicalPath}".`,sourcePath:x(r,n.skillId)})),s.add(n.skillId),c.delete(n.skillId);continue}c.set(n.skillId,{logicalPath:n.logicalPath,skill:n.skill})}return{diagnostics:o,skills:[...c.values()].map(e=>e.skill)}}async function Sn(e){let t=x(e.skillsDirectoryPath,e.entryName);switch(rt(e.entryName,e.entryType)){case`skill-package-directory`:return Cn({logicalSkillsPath:e.skillsLogicalPath,skillId:e.entryName,skillRootPath:t,source:e.source});case`flat-skill-markdown`:return wn({logicalSkillsPath:e.skillsLogicalPath,skillFileName:e.entryName,skillFilePath:t,source:e.source});case`flat-skill-module`:return Tn({logicalSkillsPath:e.skillsLogicalPath,skillFileName:e.entryName});default:return{diagnostics:[T({code:`discover/skill-entry-not-directory`,message:`Expected "${t}" to be a skill directory containing SKILL.md or a flat ".md", ".ts", ".cts", ".mts", ".js", ".cjs", or ".mjs" skill file.`,sourcePath:t})],logicalPath:D(x(e.skillsLogicalPath,e.entryName)),skill:null,skillId:null}}}async function Cn(e){let t=x(e.skillRootPath,`SKILL.md`),n=D(x(e.logicalSkillsPath,e.skillId,`SKILL.md`));if(await e.source.stat(t)!==`file`)return{diagnostics:[T({code:`discover/skill-markdown-missing`,message:`Expected "${t}" to exist for the "${e.skillId}" skill.`,sourcePath:e.skillRootPath})],logicalPath:n,skill:null,skillId:null};let r;try{r=xt(await e.source.readTextFile(t))}catch(e){return{diagnostics:[T({code:bn,message:Dn(t,e),sourcePath:t})],logicalPath:n,skill:null,skillId:null}}let i=await En(e.source,e.skillRootPath),a={description:r.description,logicalPath:n,markdown:r.markdown,name:e.skillId,rootPath:e.skillRootPath,skillFilePath:t,skillId:e.skillId,sourceId:j(n)};return i.assetsPath!==void 0&&(a.assetsPath=i.assetsPath),r.license!==void 0&&(a.license=r.license),r.metadata!==void 0&&(a.metadata=r.metadata),i.referencesPath!==void 0&&(a.referencesPath=i.referencesPath),i.scriptsPath!==void 0&&(a.scriptsPath=i.scriptsPath),{diagnostics:[],logicalPath:n,skill:It(a),skillId:e.skillId}}async function wn(e){let t=On(e.skillFileName),n=D(x(e.logicalSkillsPath,e.skillFileName)),r;try{r=xt(await e.source.readTextFile(e.skillFilePath),{slug:t})}catch(t){return{diagnostics:[T({code:bn,message:Dn(e.skillFilePath,t),sourcePath:e.skillFilePath})],logicalPath:n,skill:null,skillId:null}}return{diagnostics:[],logicalPath:n,skill:{definition:r,sourceKind:`markdown`,logicalPath:n,sourceId:j(n)},skillId:t}}async function Tn(e){let t=O(e.skillFileName),n=D(x(e.logicalSkillsPath,e.skillFileName));return t===null?{diagnostics:[],logicalPath:n,skill:null,skillId:null}:{diagnostics:[],logicalPath:n,skill:M({logicalPath:n}),skillId:t}}async function En(e,t){let n=await e.readDirectory(t),r={};for(let e of n)if(e.isDirectory())switch(nt(e.name,E(e))){case`skill-assets-directory`:r.assetsPath=x(t,e.name);break;case`skill-references-directory`:r.referencesPath=x(t,e.name);break;case`skill-scripts-directory`:r.scriptsPath=x(t,e.name);break;default:break}return r}function Dn(e,t){return`Invalid authored skill frontmatter in "${e}": ${p(t)}`}function On(e){return e.endsWith(`.md`)?e.slice(0,-3):e}async function kn(e){let t=e.source??F(),n=S(e.agentRoot),r=S(e.subagentsDirectoryPath??x(n,`subagents`)),i=D(e.subagentsLogicalPath??fe(n,r)),a=await t.stat(r);if(a===`missing`)return{diagnostics:[],subagents:[]};if(a!==`directory`)return{diagnostics:[T({code:`discover/subagents-directory-invalid`,message:`Expected "${r}" to be a directory of authored subagents.`,sourcePath:r})],subagents:[]};let o=await P(t,r),s=[],c=[];for(let n of o){if(!n.isDirectory())continue;let a=await An({appRoot:e.appRoot,source:t,subagentId:n.name,subagentLogicalPath:x(i,n.name),subagentRoot:x(r,n.name)});s.push(...a.diagnostics),c.push(a.subagent)}return{diagnostics:s,subagents:c}}async function An(e){let t=[],n=await P(e.source,e.subagentRoot);t.push(...an({classifyEntry:tt,createUnsupportedDirectoryMessage(e){return`Ignoring unsupported directory "${e}/" in the local subagent root.`},rootEntries:n,rootPath:e.subagentRoot}));let r=await Zt({rootEntries:n,rootPath:e.subagentRoot,source:e.source});t.push(...r.diagnostics);let i=$t({missingDiagnostic:{code:`discover/required-subagent-config-module-missing`,message:`Expected one authored subagent config module at "agent.ts", "agent.cts", "agent.mts", "agent.js", "agent.cjs", or "agent.mjs".`},rootEntries:n,rootPath:e.subagentRoot,slotName:`agent`});t.push(...i.diagnostics);let a=await ln({rootEntries:n,rootPath:e.subagentRoot,source:e.source});t.push(...a.diagnostics);let o=await hn({rootEntries:n,rootPath:e.subagentRoot,source:e.source});t.push(...o.diagnostics);let s=await N({directoryName:`tools`,invalidDirectoryCode:Kt,invalidDirectoryMessage:`Expected "${x(e.subagentRoot,`tools`)}" to be a directory of authored tools.`,recursive:!0,rootEntries:n,rootPath:e.subagentRoot,source:e.source,validateSegment:en});t.push(...s.diagnostics);let c=await N({directoryName:`hooks`,invalidDirectoryCode:Nn,invalidDirectoryMessage:`Expected "${x(e.subagentRoot,`hooks`)}" to be a directory of authored hooks.`,recursive:!0,rootEntries:n,rootPath:e.subagentRoot,source:e.source,validateSegment:rn});t.push(...c.diagnostics);let l=await fn({agentRoot:e.subagentRoot,rootEntries:n,source:e.source});t.push(...l.diagnostics),t.push(...jn(e.subagentRoot,n));let u=await xn({agentRoot:e.subagentRoot,source:e.source});t.push(...u.diagnostics);let d=await kn({agentRoot:e.subagentRoot,appRoot:e.appRoot,source:e.source});t.push(...d.diagnostics);let f={agentRoot:e.subagentRoot,appRoot:e.appRoot,connections:a.connections,diagnostics:t,hooks:c.sources,lib:l.lib,instructions:r.instructions,sandbox:o.sandbox,sandboxWorkspaces:o.sandboxWorkspace===null?[]:[o.sandboxWorkspace],skills:u.skills,tools:s.sources,subagents:d.subagents};i.module!==void 0&&(f.configModule=i.module);let p=Mt(f);return{diagnostics:t,subagent:Ft({entryPath:e.subagentRoot,logicalPath:e.subagentLogicalPath,manifest:p,rootPath:e.subagentRoot,subagentId:e.subagentId})}}function jn(e,t){return t.flatMap(t=>tt(t.name,E(t))===`invalid-schedules-directory`?[T({code:`discover/local-subagent-schedules-invalid`,message:`Local subagent packages cannot define schedules at "${x(e,t.name)}".`,sourcePath:x(e,t.name)})]:[])}async function Mn(e){let t=await N({allowMarkdown:!0,directoryName:`schedules`,invalidDirectoryCode:`discover/schedules-directory-invalid`,invalidDirectoryMessage:`Expected "${x(e.agentRoot,`schedules`)}" to be a directory of authored schedules.`,markdownLowerer:e=>bt(e),recursive:!0,rootEntries:e.rootEntries,rootPath:e.agentRoot,source:e.source,unsupportedFileCode:`discover/schedule-file-unsupported`,unsupportedFileMessage:e=>`Expected "${e}" to be a TypeScript or markdown schedule file within "schedules/".`});return{diagnostics:t.diagnostics,schedules:t.sources}}const Nn=`discover/hooks-directory-invalid`;async function Pn(e){let t=e.source??F(),n=S(e.appRoot),r=S(e.agentRoot),i=[],a=await Fn(t,n),o=await P(t,r);i.push(...an({classifyEntry:et,createUnsupportedDirectoryMessage(e){return`Ignoring unsupported directory "${e}/" in the agent root.`},rootEntries:o,rootPath:r}));let s=await Zt({rootEntries:o,rootPath:r,source:t});i.push(...s.diagnostics);let c=$t({rootEntries:o,rootPath:r,slotName:`agent`});i.push(...c.diagnostics);let l=await N({directoryName:`channels`,invalidDirectoryCode:`discover/channels-directory-invalid`,invalidDirectoryMessage:`Expected "${x(r,`channels`)}" to be a directory of authored channels.`,recursive:!0,rootEntries:o,rootPath:r,source:t,validateSegment:nn});i.push(...l.diagnostics);let u=await fn({agentRoot:r,rootEntries:o,source:t});i.push(...u.diagnostics);let d=await Mn({agentRoot:r,rootEntries:o,source:t});i.push(...d.diagnostics);let f=await ln({rootEntries:o,rootPath:r,source:t});i.push(...f.diagnostics);let p=await hn({rootEntries:o,rootPath:r,source:t});i.push(...p.diagnostics);let m=await N({directoryName:`tools`,invalidDirectoryCode:Kt,invalidDirectoryMessage:`Expected "${x(r,`tools`)}" to be a directory of authored tools.`,recursive:!0,rootEntries:o,rootPath:r,source:t,validateSegment:en});i.push(...m.diagnostics);let h=await N({directoryName:`hooks`,invalidDirectoryCode:Nn,invalidDirectoryMessage:`Expected "${x(r,`hooks`)}" to be a directory of authored hooks.`,recursive:!0,rootEntries:o,rootPath:r,source:t,validateSegment:rn});i.push(...h.diagnostics);let g=await xn({agentRoot:r,source:t});i.push(...g.diagnostics);let _=await kn({agentRoot:r,appRoot:n,source:t});i.push(..._.diagnostics);let v={agentRoot:r,appRoot:n,channels:l.sources,connections:f.connections,packageName:a,diagnostics:i,hooks:h.sources,lib:u.lib,instructions:s.instructions,sandbox:p.sandbox,sandboxWorkspaces:p.sandboxWorkspace===null?[]:[p.sandboxWorkspace],schedules:d.schedules,skills:g.skills,tools:m.sources,subagents:_.subagents};return c.module!==void 0&&(v.configModule=c.module),{diagnostics:i,manifest:Mt(v)}}async function Fn(e,t){try{let n=x(t,`package.json`),r=JSON.parse(await e.readTextFile(n)).name;if(typeof r!=`string`||r.length===0)return;let i=r.lastIndexOf(`/`);return i===-1?r:r.slice(i+1)}catch{return}}var In=class extends Error{diagnostic;constructor(e){super(e.message),this.name=`DiscoveryProjectResolutionError`,this.diagnostic=e}};async function Ln(e=process.cwd(),t={}){let n=t.source??F(),r=await Rn(n,e),i=r;for(;;){let e=await zn(n,i);if(e!==null)return e;let t=await Bn(n,i);if(t!==null)return t;if(await Vn(n,i))return{agentRoot:i,appRoot:i,layout:`flat`};let r=b(i);if(r===i)break;i=r}throw new In(T({code:`discover/project-not-found`,message:`Could not resolve an Ash agent root from "${r}".`,sourcePath:r}))}async function Rn(e,t){let n=S(t);return await e.stat(n)===`directory`?n:b(n)}async function zn(e,t){if(ue(t)!==`agent`)return null;let n=b(t);return await Hn(e,n)?{agentRoot:t,appRoot:n,layout:`nested`}:null}async function Bn(e,t){if(!await Hn(e,t))return null;let n=x(t,`agent`);return await Wn(e,n)?{agentRoot:n,appRoot:t,layout:`nested`}:null}async function Vn(e,t){let n=await Un(e,t);return Array.from(n.entries()).some(([e,t])=>{let n=et(e,t);return n!==`unknown`&&n!==`lib-directory`})}async function Hn(e,t){let n=await Un(e,t);return Array.from(n.entries()).some(([e,t])=>$e(e,t))}async function Un(e,t){if(await e.stat(t)!==`directory`)return new Map;let n=await e.readDirectory(t);return new Map(n.map(e=>[e.name,E(e)]))}async function Wn(e,t){return await e.stat(t)===`directory`}const Gn=`ash-agent-compiled-manifest`,L=`__root__`,Kn=y.object({exportName:y.string().optional(),sourceKind:y.literal(`module`),logicalPath:y.string(),sourceId:y.string()}).strict(),qn=y.union([y.literal(`GET`),y.literal(`POST`),y.literal(`PUT`),y.literal(`DELETE`),y.literal(`PATCH`)]),Jn=y.object({kind:y.literal(`channel`),name:y.string(),logicalPath:y.string(),method:qn,urlPath:y.string(),sourceId:y.string(),sourceKind:y.literal(`module`),exportName:y.string().optional(),adapterKind:y.string().optional()}).strict(),Yn=y.object({kind:y.literal(`disabled`),name:y.string(),logicalPath:y.string()}).strict(),Xn=y.union([Jn,Yn]),Zn=y.object({contextWindowTokens:y.number().int().positive().optional(),id:y.string(),source:Kn.optional(),providerOptions:ce.optional()}).strict(),Qn=y.object({externalDependencies:y.array(y.string()).optional()}).strict(),$n=y.object({model:Zn.optional(),thresholdPercent:y.number().finite().min(0).max(1).optional()}).strict(),er=y.object({build:Qn.optional(),compaction:$n.optional(),description:y.string().optional(),metadata:y.record(y.string(),y.string()),model:Zn,name:y.string(),source:Kn.optional()}).strict(),tr=y.object({name:y.string(),logicalPath:y.string(),markdown:y.string(),sourceId:y.string(),sourceKind:y.union([y.literal(`markdown`),y.literal(`module`)])}).strict(),nr={name:y.string(),description:y.string(),license:y.string().optional(),markdown:y.string(),metadata:y.record(y.string(),y.string()).optional(),sourceId:y.string(),logicalPath:y.string()},rr=y.discriminatedUnion(`sourceKind`,[y.object({...nr,sourceKind:y.literal(`markdown`)}).strict(),y.object({...nr,sourceKind:y.literal(`module`),exportName:y.string().optional()}).strict(),y.object({...nr,sourceKind:y.literal(`skill-package`),skillId:y.string(),skillFilePath:y.string(),rootPath:y.string(),assetsPath:y.string().optional(),referencesPath:y.string().optional(),scriptsPath:y.string().optional()}).strict()]),ir=y.object({cron:y.string(),hasRun:y.boolean(),name:y.string(),logicalPath:y.string(),markdown:y.string().optional(),sourceId:y.string(),sourceKind:y.union([y.literal(`markdown`),y.literal(`module`)])}).strict(),ar=y.object({description:y.string().optional(),exportName:y.string().optional(),logicalPath:y.string(),sourceId:y.string(),sourceKind:y.literal(`module`)}).strict(),or=y.object({logicalPath:y.string(),rootEntries:y.array(y.string()).readonly(),sourceId:y.string(),sourcePath:y.string()}).strict(),sr=y.object({logicalPath:y.string(),rootEntries:y.array(y.string()).readonly()}).strict(),cr=y.object({connectionName:y.string(),description:y.string(),exportName:y.string().optional(),logicalPath:y.string(),sourceId:y.string(),sourceKind:y.literal(`module`),url:y.string(),vercelConnect:y.object({connector:y.string()}).strict().optional()}).strict(),lr=y.object({description:y.string(),exportName:y.string().optional(),inputSchema:ce.nullable(),logicalPath:y.string(),name:y.string(),sourceId:y.string(),sourceKind:y.literal(`module`)}).strict(),ur=y.object({exportName:y.string().optional(),logicalPath:y.string(),slug:y.string(),sourceId:y.string(),sourceKind:y.literal(`module`)}).strict(),dr=y.object({agentRoot:y.string(),appRoot:y.string(),channels:y.array(Xn),config:er,connections:y.array(cr),diagnosticsSummary:ze,disabledFrameworkTools:y.array(y.string()).readonly(),hooks:y.array(ur),sandbox:ar.nullable(),sandboxWorkspaces:y.array(or),schedules:y.array(ir),skills:y.array(rr).readonly(),instructions:tr.optional(),tools:y.array(lr),workspaceResourceRoot:sr}).strict(),fr=y.object({agent:dr,description:y.string(),entryPath:y.string(),logicalPath:y.string(),name:y.string(),nodeId:y.string(),rootPath:y.string(),sourceId:y.string(),sourceKind:y.literal(`module`),exportName:y.string().optional()}).strict(),pr=y.object({childNodeId:y.string(),parentNodeId:y.string()}).strict(),mr=y.object({agentRoot:y.string(),appRoot:y.string(),channels:y.array(Xn),config:er,connections:y.array(cr),diagnosticsSummary:ze,disabledFrameworkTools:y.array(y.string()).readonly(),hooks:y.array(ur),kind:y.literal(Gn),sandbox:ar.nullable(),sandboxWorkspaces:y.array(or),schedules:y.array(ir),skills:y.array(rr).readonly(),subagentEdges:y.array(pr),subagents:y.array(fr),instructions:tr.optional(),tools:y.array(lr),version:y.literal(22),workspaceResourceRoot:sr}).strict();function hr(e){let t={agentRoot:e.agentRoot,appRoot:e.appRoot,channels:[...e.channels??[]],connections:[...e.connections??[]],config:{build:e.config.build===void 0?void 0:{externalDependencies:e.config.build.externalDependencies===void 0?void 0:[...e.config.build.externalDependencies]},compaction:{model:e.config.compaction?.model===void 0?void 0:yr(e.config.compaction.model),thresholdPercent:e.config.compaction?.thresholdPercent},description:e.config.description,metadata:{...e.config.metadata},model:yr(e.config.model),name:e.config.name,source:e.config.source===void 0?void 0:{...e.config.source}},diagnosticsSummary:e.diagnosticsSummary??{errors:0,warnings:0},disabledFrameworkTools:[...e.disabledFrameworkTools??[]],hooks:[...e.hooks??[]],sandbox:e.sandbox??null,sandboxWorkspaces:[...e.sandboxWorkspaces??[]],schedules:[...e.schedules??[]],skills:[...e.skills??[]],tools:[...e.tools??[]],workspaceResourceRoot:e.workspaceResourceRoot??{logicalPath:``,rootEntries:gr({sandboxWorkspaces:e.sandboxWorkspaces,skills:e.skills})}};return e.instructions!==void 0&&(t.instructions=e.instructions),t}function gr(e){let t=new Set;(e.skills??[]).length>0&&t.add(`skills/`);for(let n of e.sandboxWorkspaces??[])for(let e of n.rootEntries)t.add(e);return[...t].sort((e,t)=>e.localeCompare(t))}function _r(e,t){return e===`__root__`?t:`${e}::${t}`}function vr(e){return{...hr(e),kind:Gn,subagentEdges:[...e.subagentEdges??[]],subagents:[...e.subagents??[]],version:22}}function yr(e){return e.contextWindowTokens===void 0&&e.source===void 0&&e.providerOptions===void 0?{id:e.id}:e.source===void 0?e.providerOptions===void 0?{contextWindowTokens:e.contextWindowTokens,id:e.id}:{contextWindowTokens:e.contextWindowTokens,id:e.id,providerOptions:{...e.providerOptions}}:e.contextWindowTokens===void 0&&e.providerOptions===void 0?{id:e.id,source:{...e.source}}:{contextWindowTokens:e.contextWindowTokens,id:e.id,providerOptions:e.providerOptions===void 0?void 0:{...e.providerOptions},source:{...e.source}}}const br=/^\/?[A-Za-z]:[\\/]/,xr=/^\\\\[^\\]/,Sr=/(\b(?:from|import)\s*(?:\(\s*)?)(["'])([A-Za-z]:[\\/][^"'\n\r]*)\2/g;function Cr(e){return br.test(e)||xr.test(e)}function wr(e){let t=e.replaceAll(`\\`,`/`);return t.startsWith(`//`)?new URL(`file:${t}`).href:(/^\/[A-Za-z]:\//.test(t)&&(t=t.slice(1)),new URL(`file:///${t}`).href)}function Tr(e){let t=e.indexOf(`?`),n=e.indexOf(`#`),r=t===-1?n:n===-1?t:Math.min(t,n);return r===-1?{path:e,suffix:``}:{path:e.slice(0,r),suffix:e.slice(r)}}function Er(e){if(e.startsWith(`file://`))return e;let{path:t,suffix:n}=Tr(e);return Cr(t)?`${wr(t)}${n}`:e.replaceAll(`\\`,`/`)}function Dr(e){return JSON.stringify(Er(e))}function Or(e){return e.replace(Sr,(e,t,n,r)=>`${t}${n}${Er(r)}${n}`)}const kr=y.object({modules:y.record(y.string(),y.object({}).passthrough())}).strict(),Ar=y.object({nodes:y.record(y.string(),kr)}).strict();function jr(e){let t=Lr(e.moduleMapPath),n=e.importSpecifierStyle??`relative`,r=0,i=[Mr({agentRoot:e.manifest.agentRoot,importSpecifierStyle:n,manifest:e.manifest,moduleMapDirectory:t,nextBindingName(){return`module_${r++}`},nodeId:L}),...[...e.manifest.subagents].sort((e,t)=>e.nodeId.localeCompare(t.nodeId)).map(e=>Mr({agentRoot:e.agent.agentRoot,importSpecifierStyle:n,manifest:e.agent,moduleMapDirectory:t,nextBindingName(){return`module_${r++}`},nodeId:e.nodeId}))],a=i.flatMap(e=>e.modules.map(e=>`import * as ${e.bindingName} from ${JSON.stringify(e.importSpecifier)};`));return[`// Generated by Ash. Do not edit by hand.`,``,...a,...a.length>0?[``]:[],`export const moduleMap = ${Fr(i)};`,``,`export default moduleMap;`,``].join(`
|
|
4
|
-
`)}function Mr(e){return{modules:Nr(e.manifest).sort((e,t)=>e.sourceId.localeCompare(t.sourceId)).map(t=>({bindingName:e.nextBindingName(),importSpecifier:Pr({fromDirectory:e.moduleMapDirectory,importSpecifierStyle:e.importSpecifierStyle,targetPath:Rr(e.agentRoot,t.logicalPath)}),sourceId:t.sourceId})),nodeId:e.nodeId}}function Nr(e){let t=new Map;e.config.source!==void 0&&t.set(e.config.source.sourceId,e.config.source),e.config.model.source!==void 0&&t.set(e.config.model.source.sourceId,e.config.model.source);for(let n of e.channels)n.kind!==`disabled`&&t.set(n.sourceId,{exportName:n.exportName,sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId});for(let n of e.connections)t.set(n.sourceId,{exportName:n.exportName,sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId});for(let n of e.tools)t.set(n.sourceId,{exportName:n.exportName,sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId});for(let n of e.hooks)t.set(n.sourceId,{exportName:n.exportName,sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId});for(let n of e.schedules)n.sourceKind!==`module`||!n.hasRun||t.set(n.sourceId,{sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId});return e.sandbox!==null&&t.set(e.sandbox.sourceId,{exportName:e.sandbox.exportName,sourceKind:`module`,logicalPath:e.sandbox.logicalPath,sourceId:e.sandbox.sourceId}),[...t.values()]}function Pr(e){if(e.importSpecifierStyle===`absolute`)return Er(Br(e.targetPath));let t=zr(e.fromDirectory,e.targetPath);return t.startsWith(`.`)?t:`./${t}`}function Fr(e){return Ir([{key:`nodes`,value:Ir(e.map(e=>({key:e.nodeId,value:Ir([{key:`modules`,value:Ir(e.modules.map(e=>({key:e.sourceId,value:e.bindingName})))}],3)})))}],0)}function Ir(e,t=1){if(e.length===0)return`Object.freeze({})`;let n=` `.repeat(t),r=` `.repeat(t+1);return[`Object.freeze({`,e.map(e=>`${r}${JSON.stringify(e.key)}: ${e.value.replaceAll(`
|
|
5
|
-
`,`\n${r}`)}`).join(`,
|
|
6
|
-
`),`${n}})`].join(`
|
|
7
|
-
`)}function Lr(e){let t=R(e);return t.segments.length===0?t.root.length===0?`.`:t.root:Vr(t.root,t.segments.slice(0,-1))}function Rr(e,t){let n=R(e),r=R(t);return r.root.length>0?Vr(r.root,r.segments):Vr(n.root,[...n.segments,...r.segments])}function zr(e,t){let n=R(e),r=R(t);if(n.root!==r.root)return Br(t);let i=0;for(;i<n.segments.length&&i<r.segments.length&&n.segments[i]===r.segments[i];)i+=1;let a=[...Array.from({length:n.segments.length-i},()=>`..`),...r.segments.slice(i)];return a.length===0?`.`:a.join(`/`)}function Br(e){let t=R(e);return Vr(t.root,t.segments)}function R(e){let t=e.replaceAll(`\\`,`/`),n=``,r=t,i=t.match(/^[A-Za-z]:/);i===null?t.startsWith(`/`)&&(n=`/`,r=t.slice(1)):(n=i[0],r=t.slice(n.length),r.startsWith(`/`)&&(n=`${n}/`,r=r.slice(1)));let a=[];for(let e of r.split(`/`))if(!(e.length===0||e===`.`)){if(e===`..`){if(a.length>0&&a[a.length-1]!==`..`){a.pop();continue}n.length===0&&a.push(e);continue}a.push(e)}return{root:n,segments:a}}function Vr(e,t){return e===`/`?t.length===0?`/`:`/${t.join(`/`)}`:e.endsWith(`/`)?t.length===0?e:`${e}${t.join(`/`)}`:e.length>0?t.length===0?e:`${e}/${t.join(`/`)}`:t.length===0?`.`:t.join(`/`)}const Hr=`ash-model-catalog-cache`,Ur=y.object({provider:y.string().min(1),providerModelId:y.string().min(1),contextWindowTokens:y.number().int().nonnegative().optional(),maxOutputTokens:y.number().int().nonnegative().optional()}).passthrough(),Wr=y.object({slug:y.string().min(1),providers:y.array(Ur).min(1)}).passthrough(),Gr=y.object({models:y.array(Wr),providerAliases:y.record(y.string(),y.string())}).passthrough();y.object({contextWindowTokens:y.number().int().positive(),maxOutputTokens:y.number().int().positive().optional()}).strict();const Kr=y.object({fetchedAt:y.string(),kind:y.literal(Hr),models:y.array(Wr),providerAliases:y.record(y.string(),y.string()),version:y.literal(2)}).strict(),qr=new Map([[`anthropic/claude-opus-4.7`,{contextWindowTokens:2e5,maxOutputTokens:32e3}],[`openai/gpt-5.4`,{contextWindowTokens:4e5,maxOutputTokens:128e3}],[`openai/gpt-5.4-mini`,{contextWindowTokens:4e5,maxOutputTokens:128e3}]]);function Jr(e){return x(e,`.ash`,`cache`,`model-catalog.json`)}function Yr(e){let t=null,n=null,r=null,i=async()=>(t??=Zr(e),await t),a=async()=>{if(n!==null)throw n;if(r!==null)return await r;r=Xr(e).then(e=>(t=Promise.resolve(e),e));try{return await r}catch(e){throw n=e,e}},o=async()=>{let e=await i();if(e!==null&&ei(e))return e;try{return await a()}catch{return e===null?null:e}};return{async getModelLimits(e){let t=ti(e),n=await o();if(n!==null){let e=Qr(n.models,t);if(e)for(let t of e.providers){let e=$r(t);if(e!==null)return e}}return qr.get(t)??null},async getByProviderModelId(e,t){let n=await o();if(n===null)return null;let r=e.split(`.`)[0],i=n.providerAliases[r]??r,a=ti(t);for(let e of n.models)for(let t of e.providers)if(t.provider===i&&ti(t.providerModelId)===a){let n=$r(t);if(n!==null)return{slug:e.slug,limits:n}}return null}}}async function Xr(e){let t=await fetch(`https://ai-gateway.vercel.sh/v1/models/catalog`);if(!t.ok)throw Error(`AI Gateway model catalog request failed with HTTP ${t.status} ${t.statusText}.`);let n=Gr.safeParse(await t.json());if(!n.success)throw Error(`AI Gateway model catalog response did not match the expected schema.`);let r={fetchedAt:new Date().toISOString(),kind:Hr,models:n.data.models,providerAliases:n.data.providerAliases,version:2};try{let t=Jr(e);await C(x(e,`.ash`,`cache`),{recursive:!0}),await w(t,`${JSON.stringify(r,null,2)}\n`,`utf8`)}catch{}return r}async function Zr(e){try{let t=await ge(Jr(e),`utf8`),n=Kr.safeParse(JSON.parse(t));return n.success?n.data:null}catch(e){return e instanceof Error&&`code`in e&&typeof e.code==`string`&&e.code,null}}function Qr(e,t){return e.find(e=>e.slug===t)}function $r(e){return e.contextWindowTokens===void 0||e.contextWindowTokens<=0?null:{contextWindowTokens:e.contextWindowTokens,...e.maxOutputTokens!==void 0&&e.maxOutputTokens>0&&{maxOutputTokens:e.maxOutputTokens}}}function ei(e){let t=Date.parse(e.fetchedAt);return Number.isFinite(t)?Date.now()-t<=864e5:!1}function ti(e){return e.endsWith(`-thinking`)?e.slice(0,-9):e}async function z(e){let t=r(await l(x(e.agentRoot,e.source.logicalPath)),e.source);try{return await s(t)}catch(t){throw Error(`Failed to execute the ${e.kind} export "${e.source.exportName??`default`}" from "${e.source.logicalPath}": ${p(t)}`)}}var ni=class extends Error{agentId;constructor(e){super(`Agent "${e}" does not have an agent.ts config module. The "model" field is required.`),this.name=`MissingAgentConfigModuleError`,this.agentId=e}};async function ri(e,t){if(e.configModule===void 0)throw new ni(e.agentId);let n=at(await z({agentRoot:e.agentRoot,kind:`agent config`,source:e.configModule}),`Expected the agent config export "${e.configModule.exportName??`default`}" from "${e.configModule.logicalPath}" to match the public Ash shape.`),r=await ii({modelCatalog:t.modelCatalog,purpose:`the primary compaction trigger model`,requireContextWindowTokens:!0,contextWindowTokens:n.modelContextWindowTokens,providerOptions:n.modelOptions?.providerOptions,source:e.configModule,value:n.model}),i={},a={compaction:i,metadata:n.metadata??{},model:r,name:e.agentId};return n.description!==void 0&&(a.description=n.description),n.build!==void 0&&(a.build={externalDependencies:n.build.externalDependencies===void 0?void 0:[...n.build.externalDependencies]}),a.source={exportName:e.configModule.exportName,sourceKind:`module`,logicalPath:e.configModule.logicalPath,sourceId:e.configModule.sourceId},n.compaction?.model!==void 0&&(i.model=await ii({modelCatalog:t.modelCatalog,purpose:`the compaction summary model`,requireContextWindowTokens:!0,contextWindowTokens:n.compaction.modelContextWindowTokens,providerOptions:n.modelOptions?.providerOptions,source:e.configModule,value:n.compaction.model})),n.compaction?.thresholdPercent!==void 0&&(i.thresholdPercent=n.compaction.thresholdPercent),a}async function ii(e){if(typeof e.value==`string`)return await ai({id:le(e.value),providerOptions:e.providerOptions===void 0?void 0:ee(e.providerOptions)},e);let t=e.source;if(t===void 0)throw Error(`Expected ${e.purpose} to provide a valid AI SDK language model reference.`);let n=e.value,r=n.specificationVersion;if(r!==`v2`&&r!==`v3`&&r!==`v4`||typeof n.provider!=`string`||typeof n.modelId!=`string`||typeof n.doGenerate!=`function`||typeof n.doStream!=`function`)throw Error(`Expected the authored agent config export "${t.exportName??`default`}" from "${t.logicalPath}" to provide a valid AI SDK language model.`);let i={id:le(n),source:{exportName:t.exportName,sourceKind:`module`,logicalPath:t.logicalPath,sourceId:t.sourceId},providerOptions:e.providerOptions===void 0?void 0:ee(e.providerOptions)};if(e.contextWindowTokens===void 0){let t=await e.modelCatalog.getByProviderModelId(n.provider,n.modelId);if(t)return{...i,id:t.slug,contextWindowTokens:t.limits.contextWindowTokens}}return await ai(i,e)}async function ai(e,t){if(t.contextWindowTokens!==void 0)return{...e,contextWindowTokens:t.contextWindowTokens};let n;try{n=await t.modelCatalog.getModelLimits(e.id)}catch(n){if(!t.requireContextWindowTokens)return e;throw Error(`Failed to load AI Gateway model metadata for ${t.purpose} "${e.id}". ${p(n)}`)}if(n===null){if(!t.requireContextWindowTokens)return e;throw Error(`Cannot compile agent compaction because ${t.purpose} "${e.id}" does not have known AI Gateway context window metadata.`)}return{...e,contextWindowTokens:n.contextWindowTokens}}function oi(e){return typeof e==`object`&&!!e&&e.__kind===`ash:channel`}function si(e,t){if(!oi(e))throw Error(`${t} Use \`defineChannel({ routes, ... })\` (or a wrapper like \`slackChannel\` / \`ashChannel\`) — bare \`{ fetch, receive? }\` channel objects are no longer supported.`);return e}function ci(e){return typeof e==`object`&&!!e&&e.kind===`ash:disabled-channel`}async function li(e,t){let n=await z({agentRoot:e,kind:`channel`,source:t}),r=A(t.logicalPath).replace(/^channels\//,``);if(ci(n))return{kind:`disabled`,name:r,logicalPath:t.logicalPath};let i=si(n,`Expected the channel export "${t.exportName??`default`}" from "${t.logicalPath}" to match the public Ash shape.`);return i.routes.map(e=>({kind:`channel`,name:r,logicalPath:t.logicalPath,method:e.method.toUpperCase(),urlPath:e.path,sourceId:t.sourceId,sourceKind:`module`,exportName:t.exportName,adapterKind:ui(i.adapter)}))}function ui(e){if(typeof e!=`object`||!e)return;let t=e.kind;return typeof t==`string`&&t.length>0?t:void 0}function di(e,t=`auth`){if(typeof e!=`object`||!e)return`The "${t}" field must be an object with a "getToken" method.`;let n=e;if(typeof n.getToken!=`function`)return`The "${t}.getToken" field must be a function returning Promise<{ token }>.`;let r=n.startAuthorization!==void 0,i=n.completeAuthorization!==void 0;if(!r&&!i&&n.principalType!==void 0&&n.principalType!==`app`&&n.principalType!==`user`)return`The "${t}.principalType" field must be "app" or "user".`;if(r!==i)return`The "${t}" field must provide either both "startAuthorization" and "completeAuthorization" (interactive OAuth) or neither (getToken-only). Got only "${r?`startAuthorization`:`completeAuthorization`}".`;if(r&&typeof n.startAuthorization!=`function`)return`The "${t}.startAuthorization" field must be a function when provided.`;if(i&&typeof n.completeAuthorization!=`function`)return`The "${t}.completeAuthorization" field must be a function when provided.`;if(r&&n.principalType!==`user`)return`Interactive authorization (startAuthorization + completeAuthorization) is restricted to "principalType": "user" in v1. See D10 of research/connections/connection-principal-model.md for the rationale.`}function fi(e,t,n=`auth`){let r=di(e,n);if(r!==void 0)throw Error(`${t} ${r}`);let i=e,a=pi(i.vercelConnect);if(i.startAuthorization!==void 0&&i.completeAuthorization!==void 0){let e={completeAuthorization:i.completeAuthorization,getToken:i.getToken,principalType:`user`,startAuthorization:i.startAuthorization};return a===void 0?e:{...e,vercelConnect:a}}let o={getToken:i.getToken,principalType:i.principalType??`app`};return a===void 0?o:{...o,vercelConnect:a}}function pi(e){if(typeof e!=`object`||!e)return;let t=e.connector;if(!(typeof t!=`string`||t.length===0))return{connector:t}}const mi=[`approval`,`auth`,`description`,`headers`,`tools`,`url`],hi=[`completeAuthorization`,`getToken`,`principalType`,`startAuthorization`,`vercelConnect`];function gi(e,t){let r=c(e,t);n(r,mi,t),_i(r,t),vi(r,t);let i=yi(r,t),a=bi(r,t),o=xi(r,t);if(i!==void 0&&a!==void 0&&typeof a!=`function`&&Object.keys(a).some(e=>e.toLowerCase()===`authorization`))throw Error(`${t} "headers" must not include an "Authorization" key when "auth" is also provided.`);let s={description:r.description,url:r.url};if(i!==void 0&&(s.auth=i),a!==void 0&&(s.headers=a),o!==void 0&&(s.tools=o),r.approval!==void 0){if(typeof r.approval!=`function`)throw Error(`${t} The "approval" field must be a function when provided.`);s.approval=r.approval}return s}function _i(e,t){if(typeof e.url!=`string`||!URL.canParse(e.url))throw Error(`${t} The "url" field must be a valid URL.`);let n=new URL(e.url);if(n.protocol!==`https:`&&n.protocol!==`http:`)throw Error(`${t} The "url" field must use the http or https protocol, got "${n.protocol}".`)}function vi(e,t){if(typeof e.description!=`string`||e.description.length===0)throw Error(`${t} The "description" field must be a non-empty string.`)}function yi(e,t){if(e.auth===void 0)return;let r=c(e.auth,`${t} The "auth" field must be an object with a "getToken" method.`);return n(r,hi,`${t} The "auth" field`),fi(r,t)}function bi(e,t){if(e.headers===void 0)return;if(typeof e.headers==`function`)return e.headers;if(typeof e.headers!=`object`||e.headers===null||Array.isArray(e.headers))throw Error(`${t} The "headers" field must be a plain object or a function.`);let n=e.headers;for(let[e,r]of Object.entries(n)){let n=typeof r;if(n!==`string`&&n!==`function`&&n!==`object`||n===`object`&&(r===null||typeof r.then!=`function`))throw Error(`${t} The "headers.${e}" value must be a string, Promise, or function.`)}return n}function xi(e,t){if(e.tools===void 0)return;if(typeof e.tools!=`object`||e.tools===null||Array.isArray(e.tools))throw Error(`${t} The "tools" field must specify either "allow" or "block".`);let n=e.tools,r=`allow`in n,i=`block`in n;if(r&&i)throw Error(`${t} The "tools" field must specify either "allow" or "block", not both.`);if(!r&&!i)throw Error(`${t} The "tools" field must specify either "allow" or "block".`);return r?(Si(n.allow,`${t} The "tools.allow"`),{allow:n.allow}):(Si(n.block,`${t} The "tools.block"`),{block:n.block})}function Si(e,t){if(!Array.isArray(e))throw Error(`${t} field must be an array of strings.`);for(let n=0;n<e.length;n++)if(typeof e[n]!=`string`)throw Error(`${t}[${n}] must be a string.`)}async function Ci(e,t){let n=gi(await z({agentRoot:e,kind:`connection`,source:t}),`Expected the connection export "${t.exportName??`default`}" from "${t.logicalPath}" to match the public Ash shape.`),r={connectionName:t.connectionName,description:n.description,exportName:t.exportName,logicalPath:t.logicalPath,sourceId:t.sourceId,sourceKind:`module`,url:n.url},i=wi(n.auth);return i!==void 0&&(r.vercelConnect=i),r}function wi(e){if(typeof e!=`object`||!e)return;let t=e.vercelConnect;if(typeof t!=`object`||!t)return;let n=t.connector;if(!(typeof n!=`string`||n.length===0))return{connector:n}}function Ti(e){return{exportName:e.exportName,logicalPath:e.logicalPath,slug:A(e.logicalPath).replace(/^hooks\//,``),sourceId:e.sourceId,sourceKind:`module`}}function Ei(e){let t;function n(){return t===void 0&&(t=e()),t}return{get name(){return n().name},create(e){return n().create(e)},async prewarm(e){await n().prewarm(e)}}}function Di(e,t){let r=c(e,t);n(r,[`backend`,`bootstrap`,`description`,`onSession`],t);let i={};if(r.backend!==void 0&&(i.backend=Oi(r.backend,t)),r.description!==void 0){if(typeof r.description!=`string`)throw Error(`${t} The "description" field must be a string when set.`);i.description=r.description}return r.bootstrap!==void 0&&(i.bootstrap=o(r.bootstrap,t)),r.onSession!==void 0&&(i.onSession=o(r.onSession,t)),i}function Oi(e,t){if(typeof e==`function`)return Ei(e);let n=c(e,`${t} The "backend" field must be a SandboxBackend value (use vercelBackend(), localBackend(), or your own factory) or a zero-arg function returning one.`);if(typeof n.name!=`string`||n.name.length===0)throw Error(`${t} The "backend" value must expose a non-empty string "name" identifier.`);if(typeof n.create!=`function`)throw Error(`${t} The "backend" value must expose a "create" function.`);if(n.prewarm!==void 0&&typeof n.prewarm!=`function`)throw Error(`${t} The "backend.prewarm" property must be a function when set.`);return n}async function ki(e,t){return{description:Di(await z({agentRoot:e,kind:`sandbox`,source:t}),`Expected the sandbox export "${t.exportName??`default`}" from "${t.logicalPath}" to match the public Ash shape.`).description,exportName:t.exportName,logicalPath:t.logicalPath,sourceId:t.sourceId,sourceKind:`module`}}async function Ai(e,t){let n=t.sourceKind===`markdown`?ut(t.definition,`Expected the compiled instructions definition at "${t.logicalPath}" to match the public Ash shape.`):ut(await z({agentRoot:e,kind:`instructions`,source:t}),`Expected the instructions export "${t.exportName??`default`}" from "${t.logicalPath}" to match the public Ash shape.`);return{name:A(t.logicalPath),logicalPath:t.logicalPath,markdown:n.markdown,sourceId:t.sourceId,sourceKind:t.sourceKind}}async function ji(e,t){let n=t.sourceKind===`markdown`?pt(t.definition,`Expected the compiled schedule definition at "${t.logicalPath}" to match the public Ash shape.`):pt(await z({agentRoot:e,kind:`schedule`,source:t}),`Expected the schedule export "${t.exportName??`default`}" from "${t.logicalPath}" to match the public Ash shape.`),r={cron:n.cron,hasRun:n.run!==void 0,logicalPath:t.logicalPath,name:Mi(t.logicalPath),sourceId:t.sourceId,sourceKind:t.sourceKind};return n.markdown===void 0?r:{...r,markdown:n.markdown.trim()}}function Mi(e){return A(e).replace(/^schedules\//,``)}async function Ni(e,t){if(t.sourceKind===`skill-package`)return Pi(t);let n=t.sourceKind===`markdown`?dt(t.definition,`Expected the compiled skill definition at "${t.logicalPath}" to match the public Ash shape.`):dt(await z({agentRoot:e,kind:`skill`,source:t}),`Expected the skill export "${t.exportName??`default`}" from "${t.logicalPath}" to match the public Ash shape.`),r={description:n.description,license:n.license,logicalPath:t.logicalPath,markdown:n.markdown,metadata:n.metadata===void 0?void 0:{...n.metadata},name:A(t.logicalPath).replace(/^skills\//,``),sourceId:t.sourceId,sourceKind:t.sourceKind};return n.files!==void 0&&(r.files=n.files),r}function Pi(e){return{assetsPath:e.assetsPath,description:e.description,license:e.license,logicalPath:e.logicalPath,markdown:e.markdown,metadata:e.metadata===void 0?void 0:{...e.metadata},name:e.name,referencesPath:e.referencesPath,rootPath:e.rootPath,scriptsPath:e.scriptsPath,skillId:e.skillId,skillFilePath:e.skillFilePath,sourceId:e.sourceId,sourceKind:`skill-package`}}async function Fi(e){let t=[],n=[];for(let r of e.subagents){let i=await Ii({appRoot:e.appRoot,compileAgentNodeManifest:e.compileAgentNodeManifest,context:e.context,parentNodeId:e.parentNodeId,source:r});t.push(i.node,...i.descendants.nodes),n.push({childNodeId:i.node.nodeId,parentNodeId:e.parentNodeId},...i.descendants.edges)}return{edges:n,nodes:t}}async function Ii(e){let t=_r(e.parentNodeId,e.source.sourceId),n=e.source.subagentId,r=await e.compileAgentNodeManifest({...e.source.manifest,appRoot:e.appRoot},e.context),i=r.config.description;if(!i)throw Error(`Local subagent "${e.source.logicalPath}" is missing a "description" field on its agent config. Add \`description\` to \`defineAgent({ ... })\` so the parent agent can decide when to delegate to this subagent.`);return{descendants:await Fi({appRoot:e.appRoot,compileAgentNodeManifest:e.compileAgentNodeManifest,context:e.context,parentNodeId:t,subagents:e.source.manifest.subagents}),node:{agent:r,description:i,entryPath:e.source.entryPath,logicalPath:e.source.logicalPath,name:n,nodeId:t,rootPath:e.source.rootPath,sourceId:e.source.sourceId,sourceKind:`module`}}}const Li=Symbol.for(`experimental-ash.definition-source-registry`),Ri=globalThis;Ri[Li]===void 0&&(Ri[Li]=new Map);const zi=Ri[Li];function Bi(e,t){zi.set(e,t)}function Vi(e){return typeof e==`object`&&!!e&&e.kind===`ash:disabled-tool`}function Hi(e){return e&&typeof e==`object`&&`~standard`in e?e[`~standard`].jsonSchema.input({target:`draft-07`}):JSON.parse(JSON.stringify(e))}function Ui(e,t){if(Vi(e))return{kind:`disabled`};let r=c(e,t);n(r,[`description`,`execute`,`inputSchema`,`needsApproval`,`onCompact`,`retentionPolicy`,`toModelOutput`],t);let i=r.inputSchema===void 0?null:Hi(r.inputSchema),a={description:u(r.description,t),execute:o(r.execute,t),inputSchema:i};if(r.onCompact!==void 0&&o(r.onCompact,t),r.needsApproval!==void 0&&o(r.needsApproval,t),r.retentionPolicy!==void 0){let e=r.retentionPolicy;if(e!==`auto`&&e!==`keep`&&typeof e!=`function`)throw Error(`${t} Expected \`retentionPolicy\` to be "auto", "keep", or a function.`)}return r.toModelOutput!==void 0&&o(r.toModelOutput,t),{kind:`tool`,definition:a}}async function Wi(e,t){let n=Ui(await z({agentRoot:e,kind:`tool`,source:t}),`Expected the tool export "${t.exportName??`default`}" from "${t.logicalPath}" to match the public Ash shape.`),r=A(t.logicalPath).replace(/^tools\//,``).replaceAll(`/`,`-`);return n.kind===`disabled`?{kind:`disabled`,name:r}:{kind:`tool`,definition:{description:n.definition.description,exportName:t.exportName,inputSchema:n.definition.inputSchema??null,logicalPath:t.logicalPath,name:r,sourceId:t.sourceId,sourceKind:`module`}}}async function Gi(e){let t={modelCatalog:Yr(e.appRoot)},[n,r]=await Promise.all([Ki(e,t),Fi({appRoot:e.appRoot,compileAgentNodeManifest:Ki,context:t,parentNodeId:L,subagents:e.subagents})]);return vr({...n,subagentEdges:r.edges,subagents:r.nodes})}async function Ki(e,t){let n=await Promise.all(e.tools.map(t=>Wi(e.agentRoot,t))),r=[],i=[];for(let e of n)e.kind===`tool`?r.push(e.definition):i.push(e.name);let a=(await Promise.all(e.channels.map(t=>li(e.agentRoot,t)))).flat();return hr({agentRoot:e.agentRoot,appRoot:e.appRoot,channels:a,config:await ri(e,t),connections:await Promise.all(e.connections.map(t=>Ci(e.agentRoot,t))),diagnosticsSummary:e.diagnosticsSummary,disabledFrameworkTools:i,hooks:e.hooks.map(e=>Ti(e)),sandbox:e.sandbox===null?null:await ki(e.agentRoot,e.sandbox),sandboxWorkspaces:e.sandboxWorkspaces.map(e=>({logicalPath:e.logicalPath,rootEntries:[...e.rootEntries],sourceId:e.sourceId,sourcePath:e.sourcePath})),schedules:await Promise.all(e.schedules.map(t=>ji(e.agentRoot,t))),skills:await Promise.all(e.skills.map(t=>Ni(e.agentRoot,t))),instructions:e.instructions===void 0?void 0:await Ai(e.agentRoot,e.instructions),tools:r})}function qi(e){Yi(e.name);let t=[{content:Ee.from(e.markdown,`utf8`),relativePath:`SKILL.md`}];for(let[n,r]of Object.entries(e.files??{}))Xi(n),t.push({content:Zi(r),relativePath:n});return t.sort((e,t)=>Qi(e.relativePath,t.relativePath)),{description:e.description,files:t,license:e.license,markdown:e.markdown,metadata:e.metadata===void 0?void 0:{...e.metadata},name:e.name}}async function Ji(e){for(let t of e.skill.files){let n=x(e.rootPath,`skills`,e.skill.name,t.relativePath);await C(b(n),{recursive:!0}),await w(n,t.content)}}function Yi(e){if(e.length===0||e.trim()!==e||e.startsWith(`.`)||e.includes(`/`)||e.includes(`\\`)||e.includes(`..`)||/^[A-Za-z]:/.test(e))throw Error(`Expected skill name to be a non-empty safe path segment without whitespace, separators, "." prefix, or "..".`)}function Xi(e){if(e===`SKILL.md`)throw Error(`Skill package files must not include "SKILL.md"; Ash generates it.`);if(e.length===0||e.startsWith(`/`)||e.includes(`\\`)||/^[A-Za-z]:/.test(e)||e.split(`/`).some(e=>e.length===0||e===`.`||e===`..`))throw Error(`Expected skill package file paths to be relative POSIX paths.`)}function Zi(e){return typeof e==`string`?Ee.from(e,`utf8`):Ee.from(e)}function Qi(e,t){return e<t?-1:+(e>t)}const $i=`workspace-resources`;async function ea(e){let t=x(e.compileDirectoryPath,$i);await ve(t,{force:!0,recursive:!0});let n=await na({nodeId:L,resourcesRoot:t,manifest:e.manifest}),r=await Promise.all(e.manifest.subagents.map(async e=>({...e,agent:await na({nodeId:e.nodeId,resourcesRoot:t,manifest:e.agent})})));return{...n,kind:e.manifest.kind,subagentEdges:e.manifest.subagentEdges,subagents:r,version:e.manifest.version}}function ta(e,t){return{logicalPath:D(x($i,t)),rootEntries:gr({sandboxWorkspaces:e.sandboxWorkspaces,skills:e.skills})}}async function na(e){for(let t of e.manifest.sandboxWorkspaces)if(t.rootEntries.some(e=>e===`skills/`||e===`skills`))throw Error(`Sandbox workspace "${t.logicalPath}" cannot define "skills" because Ash manages that workspace entry.`);let t=x(e.resourcesRoot,e.nodeId);await C(t,{recursive:!0});for(let n of e.manifest.sandboxWorkspaces)await he(n.sourcePath,t,{recursive:!0});for(let n of e.manifest.skills)await ra({nodeRoot:t,skill:n});return{...e.manifest,skills:e.manifest.skills.map(ia),workspaceResourceRoot:ta(e.manifest,e.nodeId)}}async function ra(e){let t=x(e.nodeRoot,`skills`,e.skill.name);if(e.skill.sourceKind===`skill-package`){await he(e.skill.rootPath,t,{recursive:!0});return}await Ji({rootPath:e.nodeRoot,skill:qi(e.skill)})}function ia(e){let{files:t,...n}=e;return n}function aa(e){let t=S(e),n=x(t,`.ash`,`discovery`),r=x(t,`.ash`,`compile`);return{appRoot:t,compiledManifestPath:x(r,`compiled-agent-manifest.json`),compileDirectoryPath:r,compileMetadataPath:x(r,`compile-metadata.json`),diagnosticsPath:x(n,`diagnostics.json`),discoveryManifestPath:x(n,`agent-discovery-manifest.json`),discoveryDirectoryPath:n,moduleMapPath:x(r,`module-map.mjs`)}}function oa(e){return{diagnostics:[...e],kind:`ash-discovery-diagnostics`,summary:He(e),version:1}}function sa(e){let t=_(),n=la(e.discoveryManifestJson),r=la(e.diagnosticsArtifactJson),i=la(e.moduleMapSource);return{compile:{moduleMap:{path:da(e.appRoot,e.paths.moduleMapPath),sha256:i}},discovery:{diagnostics:{path:da(e.appRoot,e.paths.diagnosticsPath),sha256:r},manifest:{path:da(e.appRoot,e.paths.discoveryManifestPath),sha256:n},sourceGraphHash:la(`${n}:${r}:${i}`),summary:e.diagnosticsSummary},generator:{name:t.name,version:t.version},kind:`ash-compile-metadata`,status:e.diagnosticsSummary.errors>0?`failed`:`ready`,version:5}}async function ca(e){let t=aa(e.appRoot),n=oa(e.diagnostics),r=await ea({compileDirectoryPath:t.compileDirectoryPath,manifest:await Gi(e.manifest)}),i=ua(r),a=ua(e.manifest),o=ua(n),s=jr({manifest:r,moduleMapPath:t.moduleMapPath}),c=sa({appRoot:e.appRoot,diagnosticsArtifactJson:o,diagnosticsSummary:n.summary,discoveryManifestJson:a,moduleMapSource:s,paths:t}),l=ua(c);return await C(t.discoveryDirectoryPath,{recursive:!0}),await C(t.compileDirectoryPath,{recursive:!0}),await Promise.all([w(t.compiledManifestPath,i),w(t.diagnosticsPath,o),w(t.discoveryManifestPath,a),w(t.moduleMapPath,s),w(t.compileMetadataPath,l)]),{compiledManifest:r,diagnosticsArtifact:n,metadata:c,moduleMapSource:s,paths:t}}function la(e){return be(`sha256`).update(e).digest(`hex`)}function ua(e){return`${JSON.stringify(e,null,2)}\n`}function da(e,t){return D(fe(S(e),t))}var fa=class extends Error{result;constructor(e){super(ha({diagnostics:e.diagnostics,diagnosticsPath:e.paths.diagnosticsPath})),this.name=`CompileAgentError`,this.result=e}};async function pa(e={}){let t=e.source??F(),n=await Ln(e.startPath,{source:t}),r=await Pn({...n,source:t}),i=await ca({appRoot:n.appRoot,diagnostics:r.diagnostics,manifest:r.manifest}),a={diagnostics:r.diagnostics,manifest:i.compiledManifest,metadata:i.metadata,paths:i.paths,project:n};if(Ue(r.diagnostics))throw new fa(a);return ma(r.diagnostics),a}function ma(e){let t=e.filter(e=>e.severity===`warning`);if(t.length!==0)for(let e of t)console.warn(`Warning [${e.code}]: ${e.message}\n source: ${e.sourcePath}`)}function ha(e){let t=He(e.diagnostics),n=[`Discovery failed with ${t.errors} error(s) and ${t.warnings} warning(s).`];if(e.diagnosticsPath!==void 0&&n.push(`Diagnostics artifact: ${e.diagnosticsPath}`),e.diagnostics.length===0)return n.join(`
|
|
8
|
-
`);n.push(`Discovery diagnostics:`);for(let t of e.diagnostics)n.push(`- ${ga(t.severity)}: ${t.message}`),n.push(` source: ${t.sourcePath}`);return n.join(`
|
|
9
|
-
`)}function ga(e){return e===`error`?`Error`:`Warning`}const _a=Symbol.for(`experimental-ash.context-key-registry`),va=globalThis;va[_a]===void 0&&(va[_a]=new Map);const ya=va[_a];var B=class{name;codec;constructor(e,t={}){this.name=e,this.codec=t.codec,ya.set(e,this)}};const ba=Symbol.for(`experimental-ash.context-storage`),xa=globalThis;xa[ba]===void 0&&(xa[ba]=new Oe);const Sa=xa[ba];function V(){let e=Sa.getStore();if(e===void 0)throw Error(`No active Ash context. Call this function only from authored runtime code such as tools, steps, and model callbacks.`);return e}function Ca(e){return{debug(t,n){ka(`debug`,e,t,n)},info(t,n){ka(`info`,e,t,n)},warn(t,n){ka(`warn`,e,t,n)},error(t,n){ka(`error`,e,t,n),ja(t,n)}}}function wa(){return crypto.randomUUID()}function Ta(e,t){let n={errorId:t??wa(),message:Da(e)},r=Ea(e);return r!==void 0&&(n.name=r),n.detail=Ma(e),n}function Ea(e){if(e instanceof Error)return e.name===`Error`?void 0:e.name;if(d(e)&&f(e.name)&&e.name!==`Error`)return e.name}function Da(e){return d(e)&&!(e instanceof Error)&&typeof e.message==`string`?e.message:je(e)}function Oa(e,t){let n=t instanceof Error?t.message:je(t),r=t instanceof Error?t.name:`Error`;e.setStatus({code:ke.ERROR,message:n}),e.recordException({message:n,name:r,stack:Ma(t)})}function ka(e,t,n,r){let i=e===`error`?console.error:e===`warn`?console.warn:console.log,a=`[ash:${t}] ${n}`;if(r===void 0){i(a);return}i(a,Aa(r))}function Aa(e){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0){if(r instanceof Error){t[n]=Ta(r);continue}t[n]=r}return t}function ja(e,t){let n=Ae.getActiveSpan();if(n===void 0)return;let r=t?.error;if(r instanceof Error){Oa(n,r);return}n.addEvent(e,t?Aa(t):void 0)}function Ma(e){return Na(Me(e,{breakLength:1/0,compact:!1,depth:10,maxStringLength:8192}),16384)}function Na(e,t){if(Buffer.byteLength(e,`utf8`)<=t)return e;let n=e.slice(0,t);for(;Buffer.byteLength(n,`utf8`)>t&&n.length>0;)n=n.slice(0,-1);return`${n}<…truncated>`}function Pa(e){if(e.message!==void 0)return{inputResponses:e.inputResponses,message:e.message,modelContext:e.modelContext};if(e.inputResponses!==void 0&&e.inputResponses.length>0)return{inputResponses:e.inputResponses,modelContext:e.modelContext};if(e.modelContext!==void 0&&e.modelContext.length>0)return{modelContext:e.modelContext}}function Fa(e){return e.kind??`unknown`}const Ia={kind:`http`};new B(`ash.auth`),new B(`ash.initiatorAuth`);const La=new B(`ash.sessionId`),Ra=new B(`ash.continuationToken`);new B(`ash.mode`),new B(`ash.parentSession`),new B(`ash.capabilities`),new B(`ash.sessionPrepared`);const za={kind:`schedule`},Ba=Ca(`execution.subagent-adapter`),Va=new Map;function Ha(e){return Va.get(e)}function Ua(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.callId==`string`&&t.callId.length>0&&typeof t.parentContinuationToken==`string`&&t.parentContinuationToken.length>0&&typeof t.parentSessionId==`string`&&typeof t.subagentName==`string`&&t.subagentName.length>0}const Wa={kind:`subagent`,async"input.requested"(e,t){let n=t.state;Ua(n)&&await Ga({hookPayload:{callId:n.callId,childContinuationToken:t.ctx.require(Ra),childSessionId:t.ctx.require(La),event:{requests:e.requests,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},kind:`subagent-input-request`,subagentName:n.subagentName},parentContinuationToken:n.parentContinuationToken})}};async function Ga(e){"use step";let t=Ha(e.hookPayload.childContinuationToken);try{if(t!==void 0){t(e.hookPayload);return}await De(e.parentContinuationToken,e.hookPayload)}catch(t){let n=wa();throw Ba.warn(`failed to forward proxied HITL batch to parent`,{callId:e.hookPayload.callId,childContinuationToken:e.hookPayload.childContinuationToken,childSessionId:e.hookPayload.childSessionId,errorId:n,parentContinuationToken:e.parentContinuationToken,subagentName:e.hookPayload.subagentName,error:t}),t}}var H=class extends Error{registry;entryName;logicalPath;sourceId;constructor(e,t,n={}){super(t),this.name=`RuntimeRegistryError`,this.registry=e,n.entryName!==void 0&&(this.entryName=n.entryName),n.logicalPath!==void 0&&(this.logicalPath=n.logicalPath),n.sourceId!==void 0&&(this.sourceId=n.sourceId)}},Ka=class{registry;_entries=new Map;_reserved;constructor(e,t=[]){this.registry=e,this._reserved=new Set(t)}get size(){return this._entries.size}has(e){return this._entries.has(e)}get(e){return this._entries.get(e)??null}asMap(){return this._entries}register(e,t,n={}){if(this._entries.has(e))throw new H(this.registry,n.duplicateMessage??`Duplicate ${this.registry} name "${e}".`,{...n.location,entryName:e});if(this._reserved.has(e))throw new H(this.registry,n.reservedMessage??`${qa(this.registry)} "${e}" collides with another runtime-visible name.`,{...n.location,entryName:e});this._entries.set(e,t),this._reserved.add(e)}set(e,t){this._entries.set(e,t),this._reserved.add(e)}};function qa(e){return e.length===0?e:e.charAt(0).toUpperCase()+e.slice(1)}const Ja=[Ia,Wa,za],Ya=new Set([`kind`,`state`,`deliver`,`contextProviders`,`createAdapterContext`,`fetchFile`]);function Xa(e){let t=new Map,n=new Set;for(let e of Ja){let r=Qa(e);n.add(r),t.set(r,e)}for(let r of e.channels){if(r.adapter===void 0)continue;let e={logicalPath:r.logicalPath,sourceId:r.sourceId},i=r.adapter,a=Qa(i,e);if(n.has(a)){if($a(i))throw new H(`adapter`,`Channel adapter kind "${a}" is reserved by the framework. A route-declared adapter may share a framework kind only as a pass-through with no \`deliver\` hook, event handlers, \`attachments\` resolver, \`contextProviders\`, or \`createAdapterContext\` factory. Use a custom \`kind\` to add channel-specific behavior.`,{...e,entryName:a});continue}t.set(a,i)}return{adaptersByKind:t}}function Za(e,t){let n=t,r=e.adaptersByKind.get(n.kind);if(r===void 0)throw Error(`Unknown adapter kind: "${n.kind}". Declare the adapter on the route that starts this session so the runtime can rehydrate it.`);return{...r,state:n.state}}function Qa(e,t){let n=Fa(e);if(n===`unknown`)throw new H(`adapter`,"Adapters must declare a non-empty `kind` field.",{entryName:`unknown`,logicalPath:t?.logicalPath,sourceId:t?.sourceId});return n}function $a(e){if(e.deliver!==void 0||e.fetchFile!==void 0||e.createAdapterContext!==void 0||e.contextProviders!==void 0&&e.contextProviders.length>0)return!0;for(let[t,n]of Object.entries(e))if(!Ya.has(t)&&typeof n==`function`)return!0;return!1}function eo(e,t={}){return t.moduleMapLoadMode!==void 0||t.moduleMapLoaderPath!==void 0?{appRoot:e,kind:`disk`,moduleMapLoaderPath:t.moduleMapLoaderPath,moduleMapLoadMode:t.moduleMapLoadMode}:{appRoot:e,kind:`disk`}}function to(e){return e.kind===`disk`?e.appRoot:void 0}function no(e){return e.kind===`disk`?e.moduleMapLoadMode===void 0?`disk:${e.appRoot}`:e.moduleMapLoaderPath===void 0?`disk:${e.appRoot}:${e.moduleMapLoadMode}`:`disk:${e.appRoot}:${e.moduleMapLoadMode}:${e.moduleMapLoaderPath}`:`bundled`}function U(e){let t=ro(e),n=`${t}/.ash/discovery`,r=`${t}/.ash/compile`;return{appRoot:t,compiledManifestPath:`${r}/compiled-agent-manifest.json`,compileDirectoryPath:r,compileMetadataPath:`${r}/compile-metadata.json`,diagnosticsPath:`${n}/diagnostics.json`,discoveryDirectoryPath:n,discoveryManifestPath:`${n}/agent-discovery-manifest.json`,moduleMapPath:`${r}/module-map.mjs`}}function ro(e){let t=e.replaceAll(`\\`,`/`);return t===`/`?t:t.replace(/\/+$/,``)}function io(e){return Ne(e,{prefix:void 0}).message}function ao(e=`test-session`){return{bundleCache:new Map,bundleCacheKeyBySourceKey:new Map,compiledArtifacts:null,id:e}}const oo=Symbol.for(`experimental-ash.runtime-session-storage`),so=Symbol.for(`experimental-ash.runtime-session-default`),W=globalThis;W[oo]===void 0&&(W[oo]=new Oe);const co=W[oo];function lo(){return W[so]===void 0&&(W[so]=ao(`process-default`)),W[so]}function uo(){return co.getStore()??lo()}function fo(){return uo().compiledArtifacts}const po=y.object({path:y.string(),sha256:y.string()}).strict(),mo=y.object({compile:y.object({moduleMap:po}).strict(),discovery:y.object({diagnostics:po,manifest:po,sourceGraphHash:y.string(),summary:y.object({errors:y.number().finite(),warnings:y.number().finite()}).strict()}).strict(),generator:y.object({name:y.string(),version:y.string()}).strict(),kind:y.literal(`ash-compile-metadata`),status:y.union([y.literal(`failed`),y.literal(`ready`)]),version:y.literal(5)}).strict();var ho=class extends Error{metadataPath;constructor(e,t){super(e),this.name=`LoadCompileMetadataError`,t!==void 0&&(this.metadataPath=t)}};async function go(e){let t=e.metadataPath??(e.compiledArtifactsSource.kind===`disk`?U(e.compiledArtifactsSource.appRoot).compileMetadataPath:void 0);if(t!==void 0){let{readFile:e}=await import(`node:fs/promises`),n;try{n=JSON.parse(await e(t,`utf8`))}catch(e){throw new ho(vo(e),t)}return _o(n,t)}let n=fo()?.metadata;return n===void 0?null:_o(n,`bundled compile metadata`)}function _o(e,t){let n=mo.safeParse(e);if(!n.success)throw new ho(`Expected "${t}" to contain valid Ash compile metadata. ${io(n.error)}`,t);return n.data}function vo(e){return e instanceof Error?e.message:`Unknown compile metadata load failure.`}async function yo(e){let t=no(e),n=await bo(e);try{let r=(await go({compiledArtifactsSource:e}))?.discovery.sourceGraphHash;return r===void 0||r.length===0?n===void 0?t:`${t}:mtime-${xo(n)}`:n===void 0?`${t}:${r}`:`${t}:${r}:mtime-${xo(n)}`}catch{return n===void 0?t:`${t}:mtime-${xo(n)}`}}async function bo(e){if(e.kind!==`disk`)return;let{stat:t}=await import(`node:fs/promises`),{compileMetadataPath:n}=U(e.appRoot);try{return(await t(n)).mtimeMs}catch{return}}function xo(e){return Math.floor(e).toString(36)}const So=`__root__`;function Co(e,t){if(t===void 0||t===`__root__`)return e.root;let n=e.nodesByNodeId.get(t);if(n===void 0)throw Error(`Missing runtime agent node for node id "${t}".`);return n}const wo=`bundled compiled manifest`;var To=class extends Error{manifestPath;constructor(e,t){super(e),this.name=`LoadCompiledManifestError`,t!==void 0&&(this.manifestPath=t)}};async function Eo(e){let t=e.manifestPath??(e.compiledArtifactsSource.kind===`disk`?U(e.compiledArtifactsSource.appRoot).compiledManifestPath:void 0);if(t!==void 0){let{readFile:e}=await import(`node:fs/promises`),n;try{n=JSON.parse(await e(t,`utf8`))}catch(e){throw new To(Oo(e),t)}return Do(n,t)}let n=fo();if(n!==null)return Do(n.manifest,wo);throw new To(`Compiled manifest is unavailable without an app root or bundled compiled artifacts.`,wo)}function Do(e,t){let n=mr.safeParse(e);if(!n.success)throw new To(`Expected "${t}" to contain a valid compiled Ash agent manifest. ${io(n.error)}`,t);return n.data}function Oo(e){return e instanceof Error?e.message:`Unknown manifest load failure.`}const ko=`bundled compiled module map`;var Ao=class extends Error{moduleMapPath;constructor(e,t){super(e),this.name=`LoadCompiledModuleMapError`,t!==void 0&&(this.moduleMapPath=t)}};async function jo(e){let t=e.moduleMapPath??(e.compiledArtifactsSource.kind===`disk`?U(e.compiledArtifactsSource.appRoot).moduleMapPath:void 0);if(t!==void 0){let e=Po(t);try{let n=await import(e);return Mo(n.moduleMap??n.default,t)}catch(e){throw new Ao(No(e),t)}}let n=fo();if(n!==null)return Mo(n.moduleMap,ko);throw new Ao(`Compiled module map is unavailable without an app root or bundled compiled artifacts.`,ko)}function Mo(e,t){let n=Ar.safeParse(e);if(!n.success)throw new Ao(`Expected "${t}" to export a valid compiled Ash module map. ${io(n.error)}`,t);return n.data}function No(e){return e instanceof Error?e.message:`Unknown module-map load failure.`}function Po(e){let t=e.replaceAll(`\\`,`/`);return/^[A-Za-z]:\//.test(t)?`file:///${encodeURI(t)}`:t.startsWith(`/`)?`file://${encodeURI(t)}`:t}const G=`/workspace`;function Fo(e){return e.length===0?null:[`Available skills`,`Listed skills are available in this run. Do not claim a listed skill is inaccessible unless activation or workspace inspection actually fails.`,`If the user names a skill or the request clearly matches one of the descriptions below, call load_skill before proceeding.`,`If multiple skills match, activate the minimal set that covers the task. After activation, follow the returned instructions instead of improvising around them.`,`If activation fails, say so briefly and continue with the best fallback. Packaged sibling files under a skill path can be inspected with bash or read_file when needed.`,...e.map(e=>Io(e))].join(`
|
|
10
|
-
`)}function Io(e){return`- ${e.name}: ${e.description} (path: ${G}/skills/${e.name}/SKILL.md)`}function Lo(e){if(e.rootEntries.length!==0)return[`Workspace`,`- You have access to authored files mounted at the workspace root for this run.`,`- The live workspace root visible to \`bash\` in this run is \`${G}\`.`,`- Root entries under ${G}/:`,...e.rootEntries.map(e=>` - ${e}`),`- Treat \`${G}\` as the workspace root for this run unless a \`bash\` call shows otherwise.`,"- For questions about workspace paths or file availability, verify with `bash` first using commands like `pwd`, `ls`, and `find`.","- Use the `bash` tool with `ls`, `find`, and `rg` to inspect deeper contents when needed.",`- Do not claim these files are unavailable unless a workspace or tool call actually fails.`].join(`
|
|
11
|
-
`)}function Ro(e){return e instanceof Error&&e.name===`ConnectionAuthorizationRequiredError`}function zo(e){return e instanceof Error&&e.name===`ConnectionAuthorizationFailedError`}function Bo(e){return e?.startAuthorization!==void 0}const Vo=Object.freeze({__ashPlaceholder:`connection-authorization`}),Ho=new B(`ash.pendingConnectionToolCalls`);function Uo(e,t){if(t.length===0)return e??[];let n=new Set,r=e??[];for(let e of r)n.add(e.toolCallId);let i=[...r];for(let e of t)n.has(e.toolCallId)||(n.add(e.toolCallId),i.push(e));return i}function Wo(e,t){return`${e}__${t}`}const Go=Ca(`framework.connection-search`),Ko=new B(`ash.connectionRegistry`),qo=new B(`ash.pendingConnectionAuthorizations`),Jo=new B(`ash.discoveredConnectionTools`),Yo={description:`Search for tools across your connections. Discovered tools become directly callable by their qualified name (e.g. linear__list_issues) in your next response.`,execute:async(e,t)=>{let n=typeof t==`object`&&t&&`toolCallId`in t?t.toolCallId:void 0;return Xo(e,{toolCallId:typeof n==`string`?n:void 0})},inputSchema:{additionalProperties:!1,properties:{connection:{description:`Optional: limit search to a specific connection name.`,type:`string`},limit:{description:`Max results to return. Default 10.`,type:`number`},keywords:{description:`Search keywords and expanded aliases. Distill intent into keywords; avoid stop words like 'a', 'the', 'in'.`,type:`string`}},required:[`keywords`],type:`object`},logicalPath:`ash:framework/connection-search`,name:`connection_search`,onCompact({ctx:e}){return e.set(Jo,{byConnection:{}}),e.set(qo,[]),e.set(Ho,[]),{}},sourceId:`ash:connection-search-tool`,sourceKind:`module`};async function Xo(e,t){let n=V(),r=n.get(Ko);if(r===void 0)return[];let i=e.limit??10,a=Zo(e.keywords),o=[],s=[],c=e.connection!==void 0&&e.connection!==``?r.getConnections().filter(t=>t.connectionName===e.connection):r.getConnections(),l={...n.get(Jo)?.byConnection},u=[];for(let e of c){let t;try{t=await r.getClient(e.connectionName).getToolMetadata()}catch(t){if(Ro(t)){u.push({connectionName:e.connectionName,description:e.description}),s.push({connection:e.connectionName,description:e.description,needsAuthorization:!0});continue}if(zo(t)){Go.warn(`connection authorization failed`,{connection:e.connectionName,reason:t.reason,retryable:t.retryable,error:t}),s.push({connection:e.connectionName,description:e.description,error:`Authorization failed for ${e.connectionName}: ${t.message}`});continue}let n=t instanceof Error?t.message:`unknown error`;Go.warn(`failed to load connection tools`,{connection:e.connectionName,error:t instanceof Error?t:Error(n)}),s.push({connection:e.connectionName,description:e.description,error:`Failed to load tools for "${e.connectionName}": ${n}`});continue}l[e.connectionName]=t;for(let n of t){let t=Qo(a,n);t>0&&o.push({item:{connection:e.connectionName,description:n.description,inputSchema:n.inputSchema,qualifiedName:Wo(e.connectionName,n.name),tool:n.name},score:t})}}n.set(Jo,{byConnection:l});let d=[];if(u.length>0){for(let e of u)es(n,e);d=u.map(e=>e.connectionName).filter(e=>$o(r,e))}if(d.length>0&&t?.toolCallId!==void 0){let r=n.get(Ho);return n.set(Ho,Uo(r,[{args:e,connectionNames:d,kind:`connection-discover`,toolCallId:t.toolCallId,toolName:`connection_search`}])),Vo}o.sort((e,t)=>t.score-e.score);let f=o.slice(0,i).map(e=>e.item);return f.length>0?[...f,...s]:c.map(e=>s.find(t=>t.connection===e.connectionName)||{connection:e.connectionName,description:e.description})}function Zo(e){return e.toLowerCase().split(/[\s_\-./]+/).filter(e=>e.length>1)}function Qo(e,t){let n=Zo(t.name),r=Zo(t.description),i=0;for(let t of e){for(let e of n)(e.includes(t)||t.includes(e))&&(i+=3);for(let e of r)(e.includes(t)||t.includes(e))&&(i+=1)}return i}function $o(e,t){return e===void 0?!1:Bo(e.getConnections().find(e=>e.connectionName===t)?.authorization)}function es(e,t){let n=e.get(qo)??[];n.some(e=>e.connectionName===t.connectionName)||e.set(qo,[...n,t])}const ts=Yo.name;function ns(e){return[`## Connections`,``,`You have direct access to the following external services through connected MCP servers.`,`When the user's request relates to any of these services, use them instead of web search or general knowledge.`,``,`Available connections:`,...e.map(e=>`- ${e.connectionName}: ${e.description}`),``,`Use ${ts} to discover specific tools within a connection. Discovered tools become directly callable by their qualified name (e.g. linear__list_issues) in your next response.`].join(`
|
|
12
|
-
`)}function rs(e){return[...is(e.instructions),...as(e.workspaceSpec),...e.toolsAvailable?[`Tool execution
|
|
13
|
-
A single tool or subagent call runs as one serial action. If you call multiple independent tools or subagents in one response, Ash treats that batch as parallel work. Only batch work that is independent and does not rely on another call in the same response.`]:[],...os(e.connections),...ss(e.skills)]}function is(e){if(e===void 0)return[];let t=e.markdown.trim();return t.length===0?[]:[`Instructions (${e.name})\n${t}`]}function as(e){if(e===void 0)return[];let t=Lo(e);return t===void 0?[]:[t]}function os(e){return!e||e.length===0?[]:[ns(e)]}function ss(e){if(!e||e.length===0)return[];let t=Fo(e);return t===null?[]:[t]}function cs(e){let t=e.agent,n=ls(t);return{id:t.config.name,instructions:rs({connections:t.connections,instructions:t.instructions,skills:t.skills,toolsAvailable:e.tools.length>0,workspaceSpec:t.workspaceSpec}),compactionModel:t.config.compaction?.model,model:t.config.model,nodeId:e.nodeId,turnMetadata:n,tools:[...e.tools],workspaceSpec:t.workspaceSpec}}function ls(e){let t={};return Object.keys(e.config.metadata).length>0&&(t.configMetadata={...e.config.metadata}),e.instructions!==void 0&&(t.instructionsName=e.instructions.name),e.skills.length>0&&(t.skillNames=e.skills.map(e=>e.name)),Object.keys(t).length>0?t:void 0}const us=new Set([`aud`,`exp`,`iat`,`iss`,`jti`,`nbf`,`sub`]);function ds(e){let t={};for(let[n,r]of Object.entries(e)){if(typeof r==`string`){t[n]=r;continue}Array.isArray(r)&&r.every(e=>typeof e==`string`)&&(t[n]=Object.freeze([...r]))}return Object.freeze(t)}function fs(e){let t=ds(e);return Object.freeze(Object.fromEntries(Object.entries(t).filter(([e])=>!us.has(e))))}function ps(e,t){let n=ds(e);if(t.subjects!==void 0){let n=typeof e.sub==`string`?e.sub:null;if(n===null||!t.subjects.some(e=>hs(e,n)))return!1}return t.claims===void 0?!0:Object.entries(t.claims).every(([e,t])=>{let r=n[e];return r===void 0?!1:typeof r==`string`?t.includes(r):r.some(e=>t.includes(e))})}function ms(e){let t=typeof e.payload.iss==`string`?e.payload.iss:void 0,n=typeof e.payload.sub==`string`?e.payload.sub:void 0;if(t===void 0||n===void 0)throw Error(`Expected verified JWT payloads to include string iss and sub claims.`);let r=ds(e.payload);return{attributes:fs(e.payload),authenticator:e.authenticator,claims:r,issuer:t,principalId:`${t}:${n}`,principalType:e.principalType,subject:n}}function hs(e,t){if(!e.includes(`*`))return e===t;let n=e.replaceAll(/[.+?^${}()|[\]\\]/g,`\\$&`).replaceAll(`*`,`.*`);return RegExp(`^${n}$`).test(t)}const gs=y.object({issuer:y.string().optional(),jwks_uri:y.string().url()}).passthrough(),_s=new Map,vs=new Map;async function ys(e){let t;try{t=await bs(e.strategy)}catch(e){return{kind:`misconfigured`,message:`Failed to load OIDC discovery metadata. ${e instanceof Error?e.message:`Unknown discovery failure.`}`}}try{let n=await Ie(e.token,t,{audience:[...e.strategy.audiences],clockTolerance:e.strategy.clockSkewSeconds,issuer:e.strategy.issuer});if(typeof n.payload.sub!=`string`||n.payload.sub.length===0)return{kind:`not-authenticated`};let r=e.strategy.acceptCurrentVercelProject&&Ss({issuer:e.strategy.issuer,payload:n.payload}),i=r&&Cs({payload:n.payload});return!r&&!ps(n.payload,e.strategy)?{kind:`caller-not-allowed`}:{kind:`authenticated`,principal:ms({authenticator:`oidc`,payload:n.payload,principalType:i?`runtime`:`service`})}}catch{return{kind:`not-authenticated`}}}async function bs(e){let t=await xs(e.discoveryUrl),n=vs.get(t.jwks_uri);if(n!==void 0)return n;let r=Pe(new URL(t.jwks_uri));return vs.set(t.jwks_uri,r),r}async function xs(e){let t=_s.get(e);if(t!==void 0)return await t;let n=fetch(e,{headers:{accept:`application/json`}}).then(async e=>{if(!e.ok)throw Error(`Discovery route returned HTTP ${e.status}.`);return gs.parse(await e.json())}).catch(t=>{throw _s.delete(e),t});return _s.set(e,n),await n}function Ss(e){if(!e.issuer.startsWith(`https://oidc.vercel.com`))return!1;let t=process.env.VERCEL_PROJECT_ID?.trim();return t===void 0||t.length===0?!1:typeof e.payload.project_id==`string`&&e.payload.project_id===t}function Cs(e){let t=(process.env.VERCEL_TARGET_ENV?.trim()??process.env.VERCEL_ENV?.trim())?.trim();return t===void 0||t.length===0?!1:typeof e.payload.environment==`string`&&e.payload.environment===t}function ws(e){return{attributes:e.attributes,authenticator:e.authenticator,issuer:e.issuer,principalId:e.principalId,principalType:e.principalType,subject:e.subject}}const K=Ca(`auth.vercel-oidc`);async function Ts(e,t){return e===null||e.length===0?{kind:`not-authenticated`}:await ys({strategy:{acceptCurrentVercelProject:t.acceptCurrentVercelProject,audiences:[...t.audiences],clockSkewSeconds:t.clockSkewSeconds??30,discoveryUrl:t.discoveryUrl??`${t.issuer.replace(/\/$/,``)}/.well-known/openid-configuration`,issuer:t.issuer,kind:`oidc`,...t.claims===void 0?{}:{claims:t.claims},...t.subjects===void 0?{}:{subjects:t.subjects}},token:e})}function Es(e){if(e===null)return null;let t=/^Bearer\s+(.+)$/i.exec(e)?.[1]?.trim();return t===void 0||t.length===0?null:t}function Ds(e={}){let t=e.status??401,n=e.code??(t===403?`forbidden`:`unauthorized`),r=e.message??(t===403?`Forbidden.`:`Authorization is required for this route.`),i=e.challenges??[],a=new Headers({"cache-control":`no-store`});for(let e of i)a.append(`www-authenticate`,Os(e));return Response.json({code:n,error:r,ok:!1},{headers:a,status:t})}function Os(e){if(e.parameters===void 0||Object.keys(e.parameters).length===0)return e.scheme;let t=Object.entries(e.parameters).map(([e,t])=>`${e}="${ks(t)}"`).join(`, `);return`${e.scheme} ${t}`}function ks(e){return e.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`)}function As(){return()=>void 0}async function js(e,t={}){if(e===null||e.length===0)return K.debug(`Rejected request without a bearer token.`),{ok:!1};let n=Ns(e);if(n===null)return K.debug(`Rejected token that failed to decode as a JWT.`),{ok:!1};if(!n.issuer.startsWith(`https://oidc.vercel.com/`))return K.debug(`Rejected token whose issuer is not a Vercel OIDC issuer.`,{issuer:n.issuer}),{ok:!1};if(n.audiences.length===0)return K.debug(`Rejected token with no audience claim.`,{issuer:n.issuer}),{ok:!1};let r=await Ts(e,{acceptCurrentVercelProject:!0,audiences:n.audiences,issuer:n.issuer,subjects:t.subjects??[]});return r.kind===`authenticated`?(K.debug(`Accepted Vercel OIDC token.`,{issuer:n.issuer,principalType:r.principal.principalType,subject:r.principal.subject}),{ok:!0,sessionAuth:ws(r.principal)}):(K.debug(`Rejected Vercel OIDC token after verification.`,{audiences:n.audiences,issuer:n.issuer,reason:r.kind,subjectsConfigured:(t.subjects??[]).length>0,...r.kind===`misconfigured`?{detail:r.message}:{}}),{ok:!1})}function Ms(e={}){return async t=>{let n=await js(Es(t.headers.get(`authorization`)),e);return n.ok?n.sessionAuth:null}}function Ns(e){let t;try{t=Fe(e)}catch{return null}return typeof t.iss!=`string`||t.iss.length===0?null:{audiences:typeof t.aud==`string`?[t.aud]:Array.isArray(t.aud)?t.aud.filter(e=>typeof e==`string`):[],issuer:t.iss}}function Ps(e){return Number.isFinite(e)&&Number.isInteger(e)&&e>=0}function Fs(e){if(e.protocol!==`ash-attachment:`)throw Error(`AttachmentRef URL must use scheme "ash-attachment:". Got: "${e.protocol}".`);let t=e.searchParams.get(`v`);if(t!==`1`)throw Error(`AttachmentRef wire format version must be "1". Got: ${t===null?`missing`:JSON.stringify(t)}.`);let n=e.searchParams.get(`p`);if(n===null||n===``)throw Error(`AttachmentRef URL is missing the required "p" payload query param.`);let r;try{let e=Buffer.from(n,`base64url`).toString(`utf8`);r=JSON.parse(e)}catch(e){throw Error(`AttachmentRef payload is not valid base64url-encoded JSON: ${p(e)}`)}if(typeof r!=`object`||!r||Array.isArray(r))throw Error(`AttachmentRef payload must decode to a JSON object.`);let i=r;if(!(`params`in i))throw Error(`AttachmentRef payload is missing the required "params" field.`);let a=i.params;if(!(`size`in i))return{params:a};let o=i.size;if(typeof o!=`number`||!Ps(o))throw Error(`AttachmentRef payload "size" must be a non-negative integer. Got: ${JSON.stringify(o)}.`);return{params:a,size:o}}function Is(e){return e instanceof URL&&e.protocol===`ash-attachment:`}function Ls(e){return typeof Buffer<`u`&&Buffer.isBuffer(e)||e instanceof Uint8Array||e instanceof ArrayBuffer?e.byteLength:typeof e==`string`?Rs(e):Is(e)?Fs(e).size??null:e instanceof URL&&e.protocol===`data:`?Rs(e.href):null}function Rs(e){if(e.startsWith(`data:`)){let t=e.indexOf(`,`);if(t===-1)return null;let n=e.slice(5,t),r=e.slice(t+1);if(n.endsWith(`;base64`))return zs(r);try{return Buffer.byteLength(decodeURIComponent(r),`utf8`)}catch{return Buffer.byteLength(r,`utf8`)}}return/^https?:\/\//.test(e)?null:zs(e)}function zs(e){let t=e.trimEnd();if(t.length===0)return 0;let n=0;return t.endsWith(`==`)?n=2:t.endsWith(`=`)&&(n=1),Math.max(0,Math.floor(t.length*3/4)-n)}const Bs=Object.freeze({allowedMediaTypes:`*`,maxBytes:25*1024*1024});function Vs(e,t=Bs){if(e===`disabled`)return`disabled`;if(e===void 0)return t;let n=e.maxBytes??t.maxBytes,r=e.allowedMediaTypes??t.allowedMediaTypes;if(n<0||!Number.isFinite(n))throw RangeError(`UploadPolicy.maxBytes must be a non-negative finite number. Received: ${String(n)}.`);return{allowedMediaTypes:r,maxBytes:n}}function Hs(e,t){if(t===`disabled`)return!1;if(t.allowedMediaTypes===`*`)return!0;let n=e.toLowerCase();for(let e of t.allowedMediaTypes){let t=e.toLowerCase();if(t===n)return!0;if(t.endsWith(`/*`)){let e=t.slice(0,-1);if(n.startsWith(e))return!0}}return!1}function Us(e,t){if(t===`disabled`||!Hs(e.mediaType,t)){let n={allowedMediaTypes:t===`disabled`||t.allowedMediaTypes===`*`?[]:[...t.allowedMediaTypes],kind:`disallowed-media-type`,mediaType:e.mediaType};return e.filename===void 0?n:{...n,filename:e.filename}}let n=Ls(e.data);if(n!==null&&n>t.maxBytes){let r={byteLength:n,kind:`too-large`,limit:t.maxBytes,mediaType:e.mediaType};return e.filename===void 0?r:{...r,filename:e.filename}}return null}function Ws(e,t){if(typeof e==`string`)return[];let n=[];for(let r of e){if(r.type!==`file`)continue;let e=Us(r,t);e!==null&&n.push(e)}return n}function Gs(e){let t=e.filename??e.mediaType;if(e.kind===`too-large`)return`${t} (${e.byteLength} bytes) exceeds the ${e.limit}-byte upload limit.`;let n=e.allowedMediaTypes.length>0?` Allowed: ${e.allowedMediaTypes.join(`, `)}.`:``;return`${t} has media type "${e.mediaType}" which is not allowed by this route.${n}`}function Ks(e,t){return{method:`POST`,path:e,handler:t}}function qs(e,t){return{method:`GET`,path:e,handler:t}}function Js(e){let t=Ys(e);return{__kind:`ash:channel`,routes:e.routes,adapter:t,receive:e.receive}}function Ys(e){let t=e.state!=null,n=e.context!=null,r=e.fetchFile!==void 0,i=t||n,a={},o=!1,s=[`turn.started`,`actions.requested`,`action.result`,`message.completed`,`message.appended`,`input.requested`,`turn.failed`,`turn.completed`,`session.failed`,`session.completed`,`session.waiting`,`connection.authorization_required`,`connection.authorization_pending`,`connection.authorization_completed`],c=e.events;for(let e of s){let t=c?.[e];t&&(o=!0,a[e]=(e,n)=>t(e,n))}return!i&&!o&&!r?{kind:e.kindHint??`http`}:{kind:e.kindHint??`defineChannel`,state:t?{...e.state}:{},fetchFile:e.fetchFile,createAdapterContext(t){let r=t.state,i=t.session;return{...n?e.context(r,i):{},state:r,ctx:t.ctx,session:i}},deliver(e){return Pa(e)},...a}}function Xs(e){let t=Vs(e.uploadPolicy);return Js({routes:[Ks(`/ash/v1/session`,async(n,{send:r})=>{let i=await Zs(e.auth,n);if(i instanceof Response)return i;let a=i,o;try{o=await n.json()}catch{return Response.json({error:`Invalid JSON body.`,ok:!1},{status:400})}if(typeof o!=`object`||!o)return Response.json({error:`Expected a JSON object.`,ok:!1},{status:400});let s=Qs(o);if(s instanceof Response)return s;let c=nc(s,t);if(c!==null)return c;let l=`ash:${crypto.randomUUID()}`,u=await r(s.message,{auth:a,continuationToken:l});return Response.json({continuationToken:u.continuationToken,ok:!0,sessionId:u.id},{headers:{"cache-control":`no-store`,[v]:u.id},status:202})}),Ks(`/ash/v1/session/:sessionId`,async(n,{send:r,getSession:i,params:a})=>{let o=await Zs(e.auth,n);if(o instanceof Response)return o;let s=o,c=a.sessionId;if(!c)return Response.json({error:`Missing session id.`,ok:!1},{status:400});try{i(c)}catch{return Response.json({error:`Session not found.`,ok:!1},{status:404})}let l;try{l=await n.json()}catch{return Response.json({error:`Invalid JSON body.`,ok:!1},{status:400})}if(typeof l!=`object`||!l)return Response.json({error:`Expected a JSON object.`,ok:!1},{status:400});let u=$s(l);if(u instanceof Response)return u;let d=nc(u,t);if(d!==null)return d;let f=await r({inputResponses:u.inputResponses,message:u.message},{auth:s,continuationToken:u.continuationToken});return Response.json({ok:!0,sessionId:f.id},{headers:{"cache-control":`no-store`,[v]:f.id},status:200})}),qs(`/ash/v1/session/:sessionId/stream`,async(t,{getSession:n,params:r})=>{let i=await Zs(e.auth,t);if(i instanceof Response)return i;let a=r.sessionId;if(!a)return Response.json({error:`Missing session id.`,ok:!1},{status:400});let o=ic(t);if(o instanceof Response)return o;try{let e=ac(await n(a).getEventStream({startIndex:o}));return new Response(e,{headers:{"cache-control":`no-store`,"content-type":ie,[v]:a,[re]:te,[ae]:`14`}})}catch{return Response.json({error:`Session not found.`,ok:!1},{status:404})}})]})}async function Zs(e,t){let n=await e(t);return n===null?Ds({challenges:[{scheme:`Bearer`}]}):n??null}function Qs(e){let t=ec(e.message);return t instanceof Response?t:t===void 0?Response.json({error:`Missing or empty 'message' field.`,ok:!1},{status:400}):{message:t}}function $s(e){let t=typeof e.continuationToken==`string`&&e.continuationToken.length>0?e.continuationToken:void 0;if(t===void 0)return Response.json({error:`Missing or empty 'continuationToken' field.`,ok:!1},{status:400});let n=ec(e.message);if(n instanceof Response)return n;let r=rc(e.inputResponses);return r instanceof Response?r:n===void 0&&r===void 0?Response.json({error:`Expected a non-empty 'message', a non-empty 'inputResponses' array, or both.`,ok:!1},{status:400}):{message:n,continuationToken:t,inputResponses:r}}function ec(e){if(e===void 0)return;if(typeof e==`string`)return e.length>0?e:void 0;if(!Array.isArray(e))return Response.json({error:`Expected 'message' to be a string or an array of text/file parts.`,ok:!1},{status:400});if(e.length===0)return;let t=[];for(let n of e){let e=tc(n);if(e instanceof Response)return e;t.push(e)}return t}function tc(e){if(typeof e!=`object`||!e)return Response.json({error:`Expected each message part to be an object.`,ok:!1},{status:400});let t=e;if(t.type===`text`)return typeof t.text!=`string`||t.text.length===0?Response.json({error:`Text parts require a non-empty 'text' string.`,ok:!1},{status:400}):{type:`text`,text:t.text};if(t.type===`file`){if(typeof t.mediaType!=`string`||t.mediaType.length===0)return Response.json({error:`File parts require a non-empty 'mediaType' string.`,ok:!1},{status:400});if(typeof t.data!=`string`)return Response.json({error:`File parts require a 'data' string (base64, data URL, or URL).`,ok:!1},{status:400});let e={type:`file`,mediaType:t.mediaType,data:t.data};return typeof t.filename==`string`&&t.filename.length>0&&(e.filename=t.filename),e}return Response.json({error:`Unsupported message part type "${String(t.type)}". Use 'text' or 'file'.`,ok:!1},{status:400})}function nc(e,t){if(!e.message)return null;let n=Ws(e.message,t);if(n.length===0)return null;let[r]=n;if(!r)return null;let i=r.kind===`too-large`?413:415;return Response.json({error:Gs(r),ok:!1,violations:n.map(e=>e.kind===`too-large`?{byteLength:e.byteLength,filename:e.filename,kind:e.kind,limit:e.limit,mediaType:e.mediaType}:{allowedMediaTypes:e.allowedMediaTypes,filename:e.filename,kind:e.kind,mediaType:e.mediaType})},{status:i})}function rc(e){if(e===void 0)return;if(!Array.isArray(e)||e.length===0)return Response.json({error:`Expected 'inputResponses' to be a non-empty array.`,ok:!1},{status:400});let t=e.filter(ne);return t.length===e.length?t:Response.json({error:`Expected every 'inputResponses' entry to match the HITL response schema.`,ok:!1},{status:400})}function ic(e){let t=new URL(e.url).searchParams.get(`startIndex`);if(t===null)return;let n=Number.parseInt(t,10);return!Number.isSafeInteger(n)||n<0?Response.json({error:`Expected startIndex to be a non-negative integer.`,ok:!1},{status:400}):n}function ac(e){let t=new TextEncoder;return e.pipeThrough(new TransformStream({transform(e,n){n.enqueue(t.encode(`${JSON.stringify(e)}\n`))}}))}function oc(){return new Response(`<!doctype html>
|
|
14
|
-
<html lang="en">
|
|
15
|
-
<head>
|
|
16
|
-
<meta charset="utf-8" />
|
|
17
|
-
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
18
|
-
<title>Authorization complete</title>
|
|
19
|
-
<style>
|
|
20
|
-
:root {
|
|
21
|
-
color-scheme: light dark;
|
|
22
|
-
--bg: #fafafa;
|
|
23
|
-
--fg: #111111;
|
|
24
|
-
--muted: #525252;
|
|
25
|
-
--card-bg: #ffffff;
|
|
26
|
-
--card-border: #e5e5e5;
|
|
27
|
-
}
|
|
28
|
-
@media (prefers-color-scheme: dark) {
|
|
29
|
-
:root {
|
|
30
|
-
--bg: #0a0a0a;
|
|
31
|
-
--fg: #fafafa;
|
|
32
|
-
--muted: #a3a3a3;
|
|
33
|
-
--card-bg: #171717;
|
|
34
|
-
--card-border: #262626;
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
body {
|
|
38
|
-
margin: 0;
|
|
39
|
-
min-height: 100vh;
|
|
40
|
-
display: grid;
|
|
41
|
-
place-items: center;
|
|
42
|
-
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif;
|
|
43
|
-
background: var(--bg);
|
|
44
|
-
color: var(--fg);
|
|
45
|
-
}
|
|
46
|
-
.card {
|
|
47
|
-
max-width: 28rem;
|
|
48
|
-
padding: 2rem 2.25rem;
|
|
49
|
-
border: 1px solid var(--card-border);
|
|
50
|
-
border-radius: 12px;
|
|
51
|
-
background: var(--card-bg);
|
|
52
|
-
color: var(--fg);
|
|
53
|
-
text-align: center;
|
|
54
|
-
}
|
|
55
|
-
h1 { font-size: 1.25rem; margin: 0 0 0.5rem; color: var(--fg); }
|
|
56
|
-
p { margin: 0; color: var(--muted); line-height: 1.5; }
|
|
57
|
-
</style>
|
|
58
|
-
</head>
|
|
59
|
-
<body>
|
|
60
|
-
<main class="card">
|
|
61
|
-
<h1>Authorization complete</h1>
|
|
62
|
-
<p>You can close this tab and return to your app.</p>
|
|
63
|
-
</main>
|
|
64
|
-
</body>
|
|
65
|
-
</html>`,{headers:{"cache-control":`no-store`,"content-type":`text/html; charset=utf-8`},status:200})}const sc=[`GET`,`POST`];function cc(){return sc.map(e=>uc(e))}function lc(){return new Set(sc.map(dc))}function uc(e){let t=dc(e);return{name:t,method:e,urlPath:se,fetch:fc,logicalPath:`framework://channels/${t}`,sourceId:`ash:framework:connection-callback-${e.toLowerCase()}`,sourceKind:`module`}}function dc(e){return`.well-known/ash/v1/connections/callback/${e.toLowerCase()}`}async function fc(e,t){let n=t.params.name,r=t.params.token;if(typeof n!=`string`||n.length===0)return Response.json({error:`Missing connection name.`,ok:!1},{status:400});if(typeof r!=`string`||r.length===0)return Response.json({error:`Missing callback token.`,ok:!1},{status:400});let i=await pc(e);try{await De(r,i)}catch{return Response.json({error:`Connection callback not pending.`,ok:!1},{status:404})}return oc()}async function pc(e){let t={};e.headers.forEach((e,n)=>{t[n]=e});let n=``;if(e.method!==`GET`&&e.method!==`HEAD`)try{n=await e.text()}catch{n=``}return{body:n,headers:t,method:e.method,url:e.url}}function mc(){let e=Xs({auth:gc()}),t=[];for(let n of e.routes)t.push({name:`ash`,method:n.method.toUpperCase(),urlPath:n.path,fetch:async(e,t)=>n.handler(e,t),handler:n.handler,adapter:e.adapter,logicalPath:`framework://channels/${n.path}`,sourceId:`ash:framework:${n.method.toLowerCase()}-${n.path}`,sourceKind:`module`});return t.push(...cc()),t}function hc(){return new Set([`ash`,...lc()])}function gc(){return process.env.VERCEL?Ms():As()}const _c=oe.omit({action:!0,display:!0,requestId:!0}),{$schema:vc,...yc}=y.toJSONSchema(_c),bc={description:`Ask the user a question and wait for their response before continuing. Use this when you need clarification or a choice from the user.`,inputSchema:yc,logicalPath:`ash:framework/ask-question`,name:`ask_question`,sourceId:`ash:ask-question-tool`,sourceKind:`module`};async function q(){let e=V().get(gd);if(e===void 0)throw Error(`This tool requires sandbox access on the runtime context. Ensure the step is running inside a managed runtime context with sandbox support.`);let t=await e.get();if(t===null)throw Error(`The sandbox is not available in the current runtime context.`);return t}function xc(e){if(!e.startsWith(`/`))throw Error(`filePath must be an absolute path. Received: "${e}". Use an absolute path such as /workspace/foo.ts.`)}function Sc(e){return wc(e,`head`)}function Cc(e){return wc(e,`tail`)}function wc(e,t){let n=e.split(`
|
|
66
|
-
`),r=Ec(n),i=t===`head`,a=[],o=0,s=i?0:n.length-1,c=i?1:-1;for(let e=s;e>=0&&e<n.length&&a.length<2e3;e+=c){let t=Tc(n[e]??``),r=Buffer.byteLength(t,`utf8`)+1;if(o+r>51200&&a.length>0)break;a.push(t),o+=r}return i||a.reverse(),{output:a.join(`
|
|
67
|
-
`),outputLines:a.length,totalLines:r,truncated:a.length<r}}function Tc(e){return e.length<=2e3?e:e.slice(0,2e3)+` [truncated]`}function Ec(e){return e.length>0&&e[e.length-1]===``?e.length-1:e.length}async function Dc(e){let t=await(await q()).runCommand({command:e.command}),n=Cc(t.stdout),r=Cc(t.stderr),i=n.truncated||r.truncated,a=n.output;n.truncated&&(a=`[stdout truncated: showing last ${n.outputLines} of ${n.totalLines} lines]\n`+a);let o=r.output;return r.truncated&&(o=`[stderr truncated: showing last ${r.outputLines} of ${r.totalLines} lines]\n`+o),{exitCode:t.exitCode,stderr:o,stdout:a,truncated:i}}const Oc={additionalProperties:!1,properties:{command:{description:`The shell command to execute.`,type:`string`}},required:[`command`],type:`object`};async function kc(e){return Dc(e)}const Ac={description:`Execute a shell command in the shared workspace environment.`,execute:kc,inputSchema:Oc,logicalPath:`ash:framework/bash`,name:`bash`,sourceId:`ash:bash-tool`,sourceKind:`module`},jc=new B(`ash.readFile`);function J(e){return de.normalize(e)}function Mc(e){return e}function Nc(e){let t=be(`sha256`).update(e.content,`utf8`).digest(`hex`);return{byteLength:Buffer.byteLength(e.content,`utf8`),contentHash:t,filePath:e.filePath}}function Pc(e,t,n){let r=e.ensure(jc,()=>({byTarget:{}}));e.set(jc,{byTarget:{...r.byTarget,[t]:n}})}function Fc(e){e.set(jc,{byTarget:{}})}const Ic=new Map;async function Lc(e){let t=Ic.get(e.id);if(t!==void 0)return t;let n=Rc(e);Ic.set(e.id,n);try{return await n}catch{return Ic.delete(e.id),!1}}async function Rc(e){return(await e.runCommand({command:`command -v rg >/dev/null 2>&1`})).exitCode===0}function Y(e){return`'${e.replace(/'/g,`'\\''`)}'`}async function zc(e){let t=e.path??`/workspace`;xc(t);let n=J(t),r=Math.min(Math.max(1,e.limit??100),1e3),i=await q(),a=await Lc(i)?Bc({normalizedPath:n,pattern:e.pattern}):Vc({normalizedPath:n,pattern:e.pattern}),o=await i.runCommand({command:a});if(o.exitCode!==0&&o.exitCode!==1)throw Uc(a,o.exitCode,o.stderr);let s=o.stdout.split(`
|
|
68
|
-
`).filter(e=>e.length>0),c=s.length>r,l=c?s.slice(0,r):s,u=[],d=0,f=!1;for(let e of l){let t=J(e),n=Buffer.byteLength(t,`utf8`)+1;if(d+n>51200&&u.length>0){f=!0;break}u.push(t),d+=n}if(u.length===0)return{content:`No files found`,count:0,path:n,truncated:!1};let p=c||f,m=[...u];return p&&(m.push(``),m.push(`(Results truncated: showing first ${u.length} results out of more. Use a more specific path or pattern to narrow results.)`)),{content:m.join(`
|
|
69
|
-
`),count:u.length,path:n,truncated:p}}function Bc(e){return[`rg --files --hidden`,`--glob '!.git/*'`,`--glob ${Y(e.pattern)}`,`-- ${Y(e.normalizedPath)}`].join(` `)}function Vc(e){let t=Hc(e.pattern),n=t.includes(`/`)?`-path ${Y(`*/${t}`)}`:`-name ${Y(t)}`;return[`find ${Y(e.normalizedPath)}`,`-type f`,`-not -path '*/.git/*'`,n].join(` `)}function Hc(e){let t=e.replaceAll(`**`,`*`);for(;t.startsWith(`*/`);)t=t.slice(2);return t}function Uc(e,t,n){let r=n.trim(),i=r.length>0?r:`no stderr output`;return Error(`glob failed (exit ${t}): ${i}\nCommand: ${e}`)}const Wc={additionalProperties:!1,properties:{limit:{description:`Maximum number of results to return. Defaults to 100.`,maximum:1e3,minimum:1,type:`integer`},path:{description:`The directory to search in. Defaults to /workspace. Must be an absolute path. Omit to use the default.`,type:`string`},pattern:{description:`The glob pattern to match files against (e.g. "**/*.ts", "src/**/*.js").`,type:`string`}},required:[`pattern`],type:`object`};async function Gc(e){return zc(e)}const Kc={description:[`Fast file pattern matching tool that works with any codebase size.`,``,`Usage:`,`- Supports glob patterns like "**/*.js" or "src/**/*.ts".`,`- Returns matching file paths.`,`- Use this tool when you need to find files by name patterns.`,`- If you are unsure of the correct file path, use the glob tool to look up filenames by glob pattern.`,`- Use the grep tool instead if you need to search file contents.`,`- Call this tool in parallel when you know there are multiple patterns to search for.`].join(`
|
|
70
|
-
`),execute:Gc,inputSchema:Wc,logicalPath:`ash:framework/glob`,name:`glob`,sourceId:`ash:glob-tool`,sourceKind:`module`};async function qc(e){let t=e.path??`/workspace`;xc(t);let n=J(t),r=Math.min(Math.max(1,e.limit??100),1e3),i=e.context!==void 0&&e.context>0?e.context:0,a=await q(),o=await Lc(a)?Jc({contextLines:i,effectiveLimit:r,glob:e.glob,ignoreCase:e.ignoreCase??!1,literal:e.literal??!1,normalizedPath:n,pattern:e.pattern}):Yc({contextLines:i,effectiveLimit:r,glob:e.glob,ignoreCase:e.ignoreCase??!1,literal:e.literal??!1,normalizedPath:n,pattern:e.pattern}),s=await a.runCommand({command:o});if(s.exitCode!==0&&s.exitCode!==1)throw Zc(o,s.exitCode,s.stderr);let c=s.stdout;return c.trim().length===0?{content:`No matches found`,matchCount:0,path:n,truncated:!1}:Xc({effectiveLimit:r,normalizedPath:n,stdout:c})}function Jc(e){let t=[`rg`,`--line-number`,`--color=never`,`--hidden`,`--glob '!.git/*'`];return e.ignoreCase&&t.push(`--ignore-case`),e.literal&&t.push(`--fixed-strings`),e.glob!==void 0&&t.push(`--glob ${Y(e.glob)}`),e.contextLines>0&&t.push(`--context ${e.contextLines}`),t.push(`--max-count ${e.effectiveLimit}`),t.push(`--`),t.push(Y(e.pattern)),t.push(Y(e.normalizedPath)),t.join(` `)}function Yc(e){let t=[`grep`,`-r`,`-n`,`--color=never`,`--exclude-dir=.git`];return e.ignoreCase&&t.push(`-i`),e.literal?t.push(`-F`):t.push(`-E`),e.glob!==void 0&&t.push(`--include=${Y(e.glob)}`),e.contextLines>0&&t.push(`-C ${e.contextLines}`),t.push(`-m ${e.effectiveLimit}`),t.push(`--`),t.push(Y(e.pattern)),t.push(Y(e.normalizedPath)),t.join(` `)}function Xc(e){let t=e.stdout.split(`
|
|
71
|
-
`),n=[],r=0,i=0,a=!1;for(let e of t){if(e.length===0&&t.indexOf(e)===t.length-1)continue;e!==`--`&&e.length>0&&/^.+:\d+:/.test(e)&&i++;let o=Tc(e),s=Buffer.byteLength(o,`utf8`)+1;if(r+s>51200&&n.length>0){a=!0;break}n.push(o),r+=s}let o=a||i>=e.effectiveLimit,s=n.join(`
|
|
72
|
-
`);if(o){let t=[];i>=e.effectiveLimit&&t.push(`Match limit reached (${e.effectiveLimit}). Use a larger limit or more specific pattern.`),a&&t.push(`Output truncated due to size. Use a more specific path or pattern.`),s+=`\n\n[${t.join(` `)}]`}return{content:s,matchCount:i,path:e.normalizedPath,truncated:o}}function Zc(e,t,n){let r=n.trim(),i=r.length>0?r:`no stderr output`;return Error(`grep failed (exit ${t}): ${i}\nCommand: ${e}`)}const Qc={additionalProperties:!1,properties:{context:{description:`Number of surrounding context lines to include before and after each match. Defaults to 0.`,minimum:0,type:`integer`},glob:{description:`Filter files by glob pattern (e.g. "*.ts", "*.{ts,tsx}").`,type:`string`},ignoreCase:{description:`Perform case-insensitive search. Defaults to false.`,type:`boolean`},limit:{description:`Maximum number of matches to return per file. Defaults to 100.`,maximum:1e3,minimum:1,type:`integer`},literal:{description:`Treat the pattern as a literal string instead of a regular expression. Defaults to false.`,type:`boolean`},path:{description:`The directory or file to search in. Defaults to /workspace. Must be an absolute path. Omit to use the default.`,type:`string`},pattern:{description:`The regex pattern to search for in file contents (e.g. "log.*Error", "function\\s+\\w+").`,type:`string`}},required:[`pattern`],type:`object`};async function $c(e){return qc(e)}const el={description:[`Fast content search tool that works with any codebase size.`,``,`Usage:`,`- Searches file contents using regular expressions.`,`- Supports full regex syntax (e.g. "log.*Error", "function\\s+\\w+").`,`- Filter files by pattern with the glob parameter (e.g. "*.js", "*.{ts,tsx}").`,`- Returns matching lines with file paths and line numbers.`,`- Use this tool when you need to find files containing specific patterns.`,`- Use the glob tool instead if you only need to find files by name.`,`- Call this tool in parallel when you have multiple independent searches.`,`- Any line longer than 2000 characters is truncated.`].join(`
|
|
73
|
-
`),execute:$c,inputSchema:Qc,logicalPath:`ash:framework/grep`,name:`grep`,sourceId:`ash:grep-tool`,sourceKind:`module`};async function tl(e){let{filePath:t,offset:n,limit:r}=e;xc(t);let i=await q(),a=J(t),o=n??1,s=r??2e3;if(o<1)throw Error(`offset must be >= 1. Received: ${o}.`);let c=await i.readTextFile({path:t});if(c===null)throw Error(`File not found: ${t}. Verify the path exists and is accessible in the sandbox.`);if(c.includes(`\0`))throw Error(`File "${t}" contains NUL bytes and appears to be a binary file. read_file only supports text files.`);let l=c.split(`
|
|
74
|
-
`),u=l.length>0&&l[l.length-1]===``?l.length-1:l.length;if(u===0){if(o>1)throw Error(`offset ${o} is past the end of the file (0 lines). Use the default offset to read an empty file.`);return{content:``,path:a,totalLines:0,truncated:!1}}if(o>u)throw Error(`offset ${o} is past the end of the file (${u} lines).`);let d=Nc({content:c,filePath:a}),f=Mc(a);Pc(V(),f,d);let p=o-1,m=Math.min(p+s,u),h=l.slice(p,m),g=[],_=0,v=!1;for(let e=0;e<h.length;e++){let t=`${o+e}: ${Tc(h[e]??``)}`,n=Buffer.byteLength(t,`utf8`)+1;if(_+n>51200&&g.length>0){v=!0;break}g.push(t),_+=n}let ee=g.join(`
|
|
75
|
-
`),te=o+g.length-1;return te<u||v?{content:ee,nextOffset:te+1,path:a,totalLines:u,truncated:!0}:{content:ee,path:a,totalLines:u,truncated:!1}}const nl={additionalProperties:!1,properties:{filePath:{description:`The absolute path to the file to read.`,type:`string`},limit:{description:`Maximum number of lines to return. Defaults to 2000.`,minimum:1,type:`integer`},offset:{description:`1-based line number to start from. Defaults to 1.`,minimum:1,type:`integer`}},required:[`filePath`],type:`object`};async function rl(e){return tl(e)}const il={description:[`Read a file from the local filesystem. If the path does not exist, an error is returned.`,``,`Usage:`,`- The filePath parameter should be an absolute path.`,`- By default, this tool returns up to 2000 lines from the start of the file.`,`- The offset parameter is the line number to start from (1-indexed).`,`- To read later sections, call this tool again with a larger offset.`,`- Use the grep tool to find specific content in large files or files with long lines.`,`- If you are unsure of the correct file path, use the glob tool to look up filenames by glob pattern.`,'- Contents are returned with each line prefixed by its line number as `<line>: <content>`. For example, if a file has contents "foo\\n", you will receive "1: foo\\n".',`- Any line longer than 2000 characters is truncated.`,`- Call this tool in parallel when you know there are multiple files you want to read.`,`- Avoid tiny repeated slices (30 line chunks). If you need more context, read a larger window.`].join(`
|
|
76
|
-
`),execute:rl,inputSchema:nl,logicalPath:`ash:framework/read-file`,name:`read_file`,onCompact({ctx:e}){return Fc(e),{}},sourceId:`ash:read-file-tool`,sourceKind:`module`},al=/^---\r?\n[\s\S]*?\r?\n---\r?\n?/;function ol(e){if(e.length===0||e.trim()!==e||e.startsWith(`.`)||e.includes(`/`)||e.includes(`\\`)||e.includes(`..`)||/^[A-Za-z]:/.test(e))throw Error(`Expected skill id to be a non-empty safe path segment without whitespace, separators, "." prefix, or "..".`)}async function sl(e,t){ol(t);let n=await cl(e),r=ll(t,`SKILL.md`),i=await n.readTextFile({path:r});if(i===null)throw Error(`No skill named "${t}" at ${r}.`);return i.replace(al,``)}async function cl(e){let t=await e.get();if(t===null)throw Error(`The sandbox is not available in the current authored runtime context.`);return t}function ll(e,t){return`${G}/skills/${e}/${t}`}async function ul(e){let t=V().get(gd);if(t===void 0)throw Error(`The load_skill tool requires sandbox access on the runtime context. Ensure the step is running inside a managed runtime context with sandbox support.`);let{skill:n}=e;return await sl(t,n)}const dl={description:[`Load the full instructions for one available skill by name or id.`,`Use this tool when the request clearly matches a listed skill description or when the user explicitly asks for that skill.`,`Loading adds the skill instructions to the current turn.`,`Choose the "skill" value from the Available skills block.`].join(` `),execute:e=>ul(e),inputSchema:{additionalProperties:!1,properties:{skill:{description:`Available skill name or id.`,type:`string`}},required:[`skill`],type:`object`},logicalPath:`ash:framework/load-skill`,name:`load_skill`,retentionPolicy:`keep`,sourceId:`ash:load-skill-tool`,sourceKind:`module`},fl=new B(`ash.todo`);function pl(e){if(e.items.length!==0)return`[Your task list was preserved across context compaction]\n${e.items.map(e=>`- [${e.status===`completed`?`x`:e.status===`cancelled`?`-`:` `}] [${e.priority}] ${e.content}`).join(`
|
|
77
|
-
`)}`}function ml(e){let{items:t}=e,n={cancelled:0,completed:0,in_progress:0,pending:0,total:t.length};for(let e of t)n[e.status]++;return{counts:n,todos:t}}function hl(e){let t=V(),{todos:n}=e??{};if(n!==void 0){let e={items:[...n]};return t.set(fl,e),ml(e)}return ml(t.ensure(fl,()=>({items:[]})))}const gl={description:[`Use this tool to create and manage a structured task list for the current session.`,`This helps you track progress, organize complex tasks, and demonstrate thoroughness.`,``,`When to use:`,`- Complex multistep tasks requiring 3 or more distinct steps`,`- When the user provides multiple tasks or a numbered list`,`- After receiving new instructions, to capture requirements`,`- After completing a task, to mark it complete and add follow-ups`,``,`When NOT to use:`,`- Single, straightforward tasks that need no tracking`,`- Purely conversational or informational requests`,``,`Usage:`,"- Call with `todos` to replace the entire list (full replacement write)","- Call without `todos` to read the current list",`- Both return the full current list with status counts`,`- Mark tasks in_progress when you start, completed when done`,`- Only have ONE task in_progress at a time`].join(`
|
|
78
|
-
`),execute:async e=>hl(e??{}),inputSchema:{additionalProperties:!1,properties:{todos:{description:`The updated todo list. Omit to read the current list without modifying it.`,items:{additionalProperties:!1,properties:{content:{description:`Brief description of the task.`,type:`string`},priority:{description:`Priority level of the task.`,enum:[`high`,`medium`,`low`],type:`string`},status:{description:`Current status of the task.`,enum:[`pending`,`in_progress`,`completed`,`cancelled`],type:`string`}},required:[`content`,`status`,`priority`],type:`object`},type:`array`}},type:`object`},logicalPath:`ash:framework/todo`,name:`todo`,onCompact({ctx:e}){let t=e.get(fl);if(t===void 0||t.items.length===0)return{};let n=pl(t);return n===void 0?{}:{messages:[{content:n,role:`user`}]}},sourceId:`ash:todo-tool`,sourceKind:`module`};function _l(e){let t=new Le({bulletListMarker:`-`,codeBlockStyle:`fenced`,emDelimiter:`*`,headingStyle:`atx`,hr:`---`});return t.remove([`script`,`style`,`meta`,`link`]),t.turndown(e)}function vl(e){let t=e;return t=t.replace(/<(script|style|noscript)\b[^>]*>[\s\S]*?<\/\1>/gi,``),t=t.replace(/<\/(p|div|br|h[1-6]|li|tr|blockquote|pre|section|article|header|footer|nav|aside|main|figure|figcaption|details|summary)>/gi,`
|
|
79
|
-
`),t=t.replace(/<br\s*\/?>/gi,`
|
|
80
|
-
`),t=t.replace(/<[^>]+>/g,``),t=xl(t),t=t.split(`
|
|
81
|
-
`).map(e=>e.replace(/[ \t]+/g,` `).trim()).join(`
|
|
82
|
-
`).replace(/\n{3,}/g,`
|
|
83
|
-
|
|
84
|
-
`).trim(),t}const yl={"&":`&`,">":`>`,"<":`<`," ":` `,""":`"`,"'":`'`,"'":`'`,"/":`/`},bl=new RegExp(Object.keys(yl).join(`|`),`gi`);function xl(e){return e.replace(bl,e=>yl[e.toLowerCase()]??e)}const Sl=5*1024*1024;async function Cl(e){let{url:t,format:n=`markdown`,timeout:r}=e;if(!t.startsWith(`http://`)&&!t.startsWith(`https://`))throw Error(`URL must start with http:// or https://`);let i=Math.min(r===void 0?3e4:r*1e3,12e4),a=AbortSignal.timeout(i),o=wl(n),s=await fetch(t,{headers:o,signal:a}),c=s.status===403&&s.headers.get(`cf-mitigated`)===`challenge`?await fetch(t,{headers:{...o,"User-Agent":h},signal:a}):s;if(!c.ok)throw Error(`Request failed with status code: ${c.status}`);let l=c.headers.get(`content-length`);if(l!==null&&parseInt(l,10)>Sl)throw Error(`Response too large (exceeds 5 MB limit).`);let u=await c.arrayBuffer();if(u.byteLength>Sl)throw Error(`Response too large (exceeds 5 MB limit).`);let d=c.headers.get(`content-type`)??``,f=d.includes(`text/html`),p=new TextDecoder().decode(u),m;m=n===`markdown`&&f?_l(p):n===`text`&&f?vl(p):p;let{output:g,truncated:_}=Sc(m);return{content:g,contentType:d,truncated:_,url:t}}function wl(e){let t;return t=e===`markdown`?`text/markdown;q=1.0, text/x-markdown;q=0.9, text/plain;q=0.8, text/html;q=0.7, */*;q=0.1`:e===`text`?`text/plain;q=1.0, text/markdown;q=0.9, text/html;q=0.8, */*;q=0.1`:`text/html;q=1.0, application/xhtml+xml;q=0.9, text/plain;q=0.8, text/markdown;q=0.7, */*;q=0.1`,{Accept:t,"Accept-Language":`en-US,en;q=0.9`,"User-Agent":`Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36`}}async function Tl(e){return Cl(e)}const El={description:[`Fetch a webpage and return its content in the requested format. Use this to retrieve and analyze content from URLs.`,``,`Usage notes:`,`- The URL must be a fully-formed valid URL starting with http:// or https://`,`- HTML responses are automatically converted to markdown or plain text based on the requested format`,`- Format options: "markdown" (default), "text", or "html"`,`- Default timeout is 30 seconds (max 120 seconds)`,`- Maximum response size is 5 MB; content is further capped at the shared tool-output budget (50 KB / 2000 lines)`,`- This tool is read-only and does not modify any files`].join(`
|
|
85
|
-
`),execute:Tl,inputSchema:{additionalProperties:!1,properties:{format:{description:`The format to return the content in (text, markdown, or html). HTML responses are automatically converted to the requested format. Defaults to "markdown".`,enum:[`markdown`,`text`,`html`],type:`string`},timeout:{description:`Optional timeout in seconds. Defaults to 30, max 120.`,type:`number`},url:{description:`The fully-formed URL to fetch content from. Must start with http:// or https://.`,type:`string`}},required:[`url`],type:`object`},logicalPath:`ash:framework/web-fetch`,name:`web_fetch`,sourceId:`ash:web-fetch-tool`,sourceKind:`module`},Dl={description:`Search the web for real-time information. Use this to find up-to-date information about current events, recent developments, or topics that may have changed since the knowledge cutoff.`,inputSchema:null,logicalPath:`ash:framework/web-search`,name:`web_search`,sourceId:`ash:web-search-tool`,sourceKind:`module`};async function Ol(e){let{filePath:t,content:n}=e;xc(t);let r=await q(),i=V(),a=J(t),o=Mc(a),s=await r.readTextFile({path:t});if(s===null)return await r.writeTextFile({content:n,path:t}),Pc(i,o,Nc({content:n,filePath:a})),{existed:!1,path:a};let c=i.ensure(jc,()=>({byTarget:{}})).byTarget[o];if(c===void 0)throw Error(`You must read file ${t} before overwriting it. Use the read_file tool first.`);let l=Nc({content:s,filePath:a});if(l.contentHash!==c.contentHash||l.byteLength!==c.byteLength)throw Error(`File ${t} has been modified since it was last read. Please read the file again before modifying it.`);return await r.writeTextFile({content:n,path:t}),Pc(i,o,Nc({content:n,filePath:a})),{existed:!0,path:a}}const kl={additionalProperties:!1,properties:{content:{description:`Complete replacement file contents.`,type:`string`},filePath:{description:`The absolute path to the file to write (must be absolute, not relative).`,type:`string`}},required:[`filePath`,`content`],type:`object`};async function Al(e){return Ol(e)}const jl=[bc,Ac,Kc,el,il,{description:[`Writes a file to the local filesystem.`,``,`Usage:`,`- This tool will overwrite the existing file if there is one at the provided path.`,`- If this is an existing file, you MUST use the read_file tool first to read the file's contents. This tool will fail if you did not read the file first.`,`- ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required.`,`- NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested by the User.`,`- Only use emojis if the user explicitly requests it. Avoid writing emojis to files unless asked.`].join(`
|
|
86
|
-
`),execute:Al,inputSchema:kl,logicalPath:`ash:framework/write-file`,name:`write_file`,sourceId:`ash:write-file-tool`,sourceKind:`module`},gl,El,Dl,dl,Yo],Ml=new Map([[Yo,e=>e.hasConnections]]);function Nl(e){return jl.filter(t=>{let n=Ml.get(t);return n===void 0||n(e)})}function Pl(){return new Set(jl.map(e=>e.name))}function Fl(e){let t=[],n=[],r=new Map,i=[];for(let a of e){let e=a.lifecycle.session;e!==void 0&&t.push({slug:a.slug,handler:e});let o=a.lifecycle.turn;o!==void 0&&n.push({slug:a.slug,handler:o});for(let[e,t]of Object.entries(a.events)){let n={slug:a.slug,handler:t,eventType:e};if(e===`*`)i.push(n);else{let t=r.get(e)??[];t.push(n),r.set(e,t)}}}return{session:t,turn:n,streamEventsByType:r,streamEventsWildcard:i}}var X=class extends Error{logicalPath;sourceId;constructor(e,t={}){super(e),this.name=`ResolveAgentError`,t.logicalPath!==void 0&&(this.logicalPath=t.logicalPath),t.sourceId!==void 0&&(this.sourceId=t.sourceId)}};function Il(e){return{exportName:e.exportName,logicalPath:e.logicalPath,sourceId:e.sourceId,sourceKind:`module`}}async function Z(e){let t=e.nodeId??`__root__`,n=e.moduleMap.nodes[t]?.modules[e.definition.sourceId];if(n===void 0)throw new X(`Missing compiled module namespace for ${e.kindLabel} source "${e.definition.sourceId}" in node "${t}".`,{logicalPath:e.definition.logicalPath,sourceId:e.definition.sourceId});return await s(r(c(n,`Missing compiled module namespace for ${e.kindLabel} source "${e.definition.sourceId}" in node "${t}".`),{exportName:e.definition.exportName,logicalPath:e.definition.logicalPath}))}async function Ll(e,t,n){try{let r=si(await Z({definition:e,kindLabel:`channel`,moduleMap:t,nodeId:n}),`Expected the channel export "${e.exportName??`default`}" from "${e.logicalPath}" to match the public Ash shape.`),i=Il({exportName:e.exportName,logicalPath:e.logicalPath,sourceId:e.sourceId}),a=r.routes.find(t=>t.method.toUpperCase()===e.method.toUpperCase()&&t.path===e.urlPath),o=r.adapter;return o&&o.kind!==`http`&&(o.kind=`channel:${e.name}`),{name:e.name,method:e.method,urlPath:e.urlPath,fetch:async(e,t)=>a?a.handler(e,t):Response.json({error:`No matching route handler.`,ok:!1},{status:404}),handler:a?.handler,receive:r.receive,definition:r,adapter:o,...i}}catch(t){throw t instanceof X?t:new X(`Failed to attach the channel definition from "${e.logicalPath}": ${p(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}async function Rl(e,t,n){try{let r=c(await Z({definition:e,kindLabel:`connection`,moduleMap:t,nodeId:n}),`Expected the connection export "${e.exportName??`default`}" from "${e.logicalPath}" to return an object.`);Bi(`connection:${r.url}`,{kind:`connection`,name:e.connectionName});let i=r.auth!==void 0,a=r.headers!==void 0,o={connectionName:e.connectionName,description:e.description,exportName:e.exportName,logicalPath:e.logicalPath,sourceId:e.sourceId,sourceKind:`module`,url:e.url};if(i)try{o.authorization=fi(r.auth,`Connection "${e.connectionName}" at "${e.logicalPath}":`)}catch(t){throw new X(p(t),{logicalPath:e.logicalPath,sourceId:e.sourceId})}return a&&(o.headers=r.headers),r.tools!==void 0&&(o.tools=r.tools),typeof r.approval==`function`&&(o.approval=r.approval),o}catch(t){throw t instanceof X?t:new X(`Failed to resolve connection "${e.connectionName}" from "${e.logicalPath}": ${p(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}async function zl(e,t,n){try{let r=c(await Z({definition:e,kindLabel:`hook`,moduleMap:t,nodeId:n}),Q(e,`to return an object`)),i={},a={},s=r.lifecycle;if(s!==void 0){let t=c(s,Q(e,"to expose `lifecycle` as an object"));for(let n of[`session`,`turn`]){let r=t[n];r!==void 0&&(i[n]=o(r,Q(e,`to provide a function for "lifecycle.${n}"`)))}}let l=r.events;if(l!==void 0){let t=c(l,Q(e,"to expose `events` as an object"));for(let[n,r]of Object.entries(t))r!==void 0&&(a[n]=o(r,Q(e,`to provide a function for "events.${n}"`)))}return{events:a,exportName:e.exportName,lifecycle:i,logicalPath:e.logicalPath,slug:e.slug,sourceId:e.sourceId,sourceKind:`module`}}catch(t){throw t instanceof X?t:new X(`Failed to attach hook handlers from "${e.logicalPath}": ${p(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}function Q(e,t){return`Expected the hook export "${e.exportName??`default`}" from "${e.logicalPath}" ${t}.`}var Bl=class e extends Error{backendName;templateKey;constructor(e){super(`Sandbox template "${e.templateKey}" is not provisioned for backend "${e.backendName}". Run \`ash build\` or invoke \`prewarmAppSandboxes()\` before serving traffic.`),this.name=`SandboxTemplateNotProvisionedError`,this.backendName=e.backendName,this.templateKey=e.templateKey}static is(t){return t instanceof e}};async function Vl(e){let t=[];for await(let n of e)t.push(n);return Buffer.concat(t)}function Hl(e){return new ReadableStream({start(t){t.enqueue(e),t.close()}})}function Ul(e){return{id:e.id,resolvePath(t){return e.resolvePath(t)},async runCommand(t){return await e.runCommand(t)},async readFile(t){return await e.readFile({abortSignal:t.abortSignal,path:e.resolvePath(t.path)})},async readBinaryFile(t){let n=await e.readFile({abortSignal:t.abortSignal,path:e.resolvePath(t.path)});return n===null?null:await Vl(n)},async readTextFile(t){Wl(t);let n=await e.readFile({abortSignal:t.abortSignal,path:e.resolvePath(t.path)});return n===null?null:Kl(ql(await Vl(n),t.encoding??`utf-8`),t)},async writeFile(t){await e.writeFile({abortSignal:t.abortSignal,content:t.content,path:e.resolvePath(t.path)})},async writeBinaryFile(t){await e.writeFile({abortSignal:t.abortSignal,content:Hl(t.content),path:e.resolvePath(t.path)})},async writeTextFile(t){let n=Jl(t.content,t.encoding??`utf-8`);await e.writeFile({abortSignal:t.abortSignal,content:Hl(n),path:e.resolvePath(t.path)})}}}function Wl(e){let{startLine:t,endLine:n}=e;if(t!==void 0&&(!Number.isInteger(t)||t<1))throw Error(`startLine must be a positive integer (1-based).`);if(n!==void 0&&(!Number.isInteger(n)||n<1))throw Error(`endLine must be a positive integer (1-based).`);if(t!==void 0&&n!==void 0&&t>n)throw Error(`startLine must not be greater than endLine.`)}function Gl(e){let t=[],n=0;for(let r=0;r<e.length;r++)e[r]===`\r`?r+1<e.length&&e[r+1]===`
|
|
87
|
-
`?(t.push(e.slice(n,r+2)),n=r+2,r++):(t.push(e.slice(n,r+1)),n=r+1):e[r]===`
|
|
88
|
-
`&&(t.push(e.slice(n,r+1)),n=r+1);return n<e.length&&t.push(e.slice(n)),t}function Kl(e,t){if(t.startLine===void 0&&t.endLine===void 0)return e;let n=Gl(e),r=n.length,i=t.startLine??1,a=Math.min(t.endLine??r,r);return i>r?``:n.slice(i-1,a).join(``)}function ql(e,t){return t===`utf-8`||t===`utf8`?new TextDecoder(`utf-8`,{fatal:!0}).decode(e):Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(t)}function Jl(e,t){return t===`utf-8`||t===`utf8`?new TextEncoder().encode(e):Buffer.from(e,t)}function Yl(e={}){return{name:`local`,async prewarm(e){let t=tu(Ed(e.runtimeContext.appRoot),e.templateKey);if(await lu(t))return;let n=await Xl({sessionKey:e.templateKey,snapshotPath:t}),r=Ul(Ql(n));try{e.bootstrap!==void 0&&await e.bootstrap({use:async()=>r});for(let t of e.seedFiles)typeof t.content==`string`?await r.writeTextFile({content:t.content,path:t.path}):await r.writeBinaryFile({content:t.content,path:t.path});if(await n.captureSnapshot()===null)throw Error(`Failed to capture local sandbox template state for "${e.templateKey}".`)}finally{await n.dispose()}},async create(e){let t=Ed(e.runtimeContext.appRoot),n=await su(tu(t,e.templateKey));if(n===null)throw new Bl({backendName:`local`,templateKey:e.templateKey});let r=uu(e.existingMetadata)??nu(t,e.sessionKey);return await lu(r)||await cu(r,n),Zl(await Xl({sessionKey:e.sessionKey,snapshotPath:r}))}}}async function Xl(e){let{Bash:t,InMemoryFs:n}=await import(`#compiled/just-bash/index.js`),r=await su(e.snapshotPath),i=new n(ru(r));await iu(i),await au(i,r?.entries??[]);let a=new t({cwd:G,env:r?.env,fs:i,network:{dangerouslyAllowFullInternetAccess:!0}});return{async captureSnapshot(){let t=await ou({filesystem:i,sandbox:a});return await cu(e.snapshotPath,t),{snapshotPath:e.snapshotPath}},async dispose(){await a.dispose?.()},async executeCommand(e){if(e.abortSignal?.aborted)throw new DOMException(`The operation was aborted.`,`AbortError`);let t=e.workingDirectory===void 0?e.command:`( cd ${Y(e.workingDirectory)} && ${e.command} )`,n=a.exec(t),r=e.abortSignal?await $l(n,e.abortSignal):await n;return{exitCode:r.exitCode,stderr:r.stderr,stdout:r.stdout}},async readFileBytes(e){let t;try{t=await i.readFileBuffer(e)}catch{return null}return Buffer.from(t)},async readFileText(e){let t;try{t=await i.readFileBuffer(e)}catch{return null}return new TextDecoder(`utf-8`,{fatal:!0}).decode(t)},sessionKey:e.sessionKey,snapshotPath:e.snapshotPath,async writeFiles(e){for(let t of e){let e=b(t.path);await i.mkdir(e,{recursive:!0}),await i.writeFile(t.path,t.content)}}}}function Zl(e){let t=Ul(Ql(e));return{session:t,useSessionFn:async()=>t,async captureState(){return{backendName:`local`,metadata:await e.captureSnapshot()??{},sessionKey:e.sessionKey}},async dispose(){await e.dispose()}}}function Ql(e){return{id:e.sessionKey,resolvePath:eu,async runCommand(t){return await e.executeCommand(t)},async readFile(t){let n=await e.readFileBytes(t.path);return n===null?null:Hl(n)},async writeFile(t){let n=await Vl(t.content);await e.writeFiles([{content:n,path:t.path}])}}}async function $l(e,t){return await new Promise((n,r)=>{let i=()=>{r(new DOMException(`The operation was aborted.`,`AbortError`))};if(t.aborted){i();return}t.addEventListener(`abort`,i,{once:!0}),e.then(e=>{t.removeEventListener(`abort`,i),n(e)},e=>{t.removeEventListener(`abort`,i),r(e)})})}function eu(e){return e.startsWith(`/`)?e:`${G}/${e}`}function tu(e,t){return x(e,`local`,`templates`,`${t}.json`)}function nu(e,t){return x(e,`local`,`sessions`,`${t}.json`)}function ru(e){let t={};for(let n of e?.entries??[])n.kind===`file`&&(t[n.path]=Buffer.from(n.contentBase64,`base64`));return t}async function iu(e){await e.mkdir(G,{recursive:!0})}async function au(e,t){let n=t.filter(e=>e.kind===`directory`).map(e=>e.path).sort((e,t)=>e.localeCompare(t));for(let t of n)t!==`/workspace`&&await e.mkdir(t,{recursive:!0})}async function ou(e){let t=[],n=e.filesystem.getAllPaths().sort((e,t)=>e.localeCompare(t));for(let r of n){let n=await e.filesystem.stat(r);if(n.isSymbolicLink)continue;if(n.isDirectory){t.push({kind:`directory`,path:r});continue}if(!n.isFile)continue;let i=await e.filesystem.readFileBuffer(r);t.push({contentBase64:Buffer.from(i).toString(`base64`),kind:`file`,path:r})}return{entries:t,env:{...e.sandbox.getEnv()},version:1}}async function su(e){if(!await lu(e))return null;let t=JSON.parse(await ge(e,`utf8`));return t.version===1?t:null}async function cu(e,t){await C(b(e),{recursive:!0}),await w(e,`${JSON.stringify(t,null,2)}\n`)}async function lu(e){try{return await me(e),!0}catch{return!1}}function uu(e){let t=e?.snapshotPath;return typeof t==`string`?t:void 0}function du(e){return Yl({createOptions:e})}function fu(e={}){let t=e.loadSandboxModule??(async()=>await import(`#compiled/@vercel/sandbox/index.js`)),n={timeout:Au,...e.createOptions},r=new Map;return{name:`vercel`,async create(e){let i=Eu(n.tags,e.tags),a;try{a=await pu({loadSandboxModule:t,prewarmedTemplates:r,templateKey:e.templateKey})}catch(t){throw Bl.is(t)?t:Error(`Failed to read sandbox template "${e.templateKey}": ${ku(t)}`,{cause:t})}let o;try{o=await hu({createOptions:n,existingMetadata:e.existingMetadata,sandboxModule:await t(),sessionKey:e.sessionKey,snapshotId:a.snapshotId,tags:i})}catch(t){throw Error(`Failed to create sandbox session "${e.sessionKey}": ${ku(t)}`,{cause:t})}return gu(o,e.sessionKey)},async prewarm(e){let i;try{i=await mu({bootstrap:e.bootstrap,createOptions:n,loadSandboxModule:t,seedFiles:e.seedFiles,templateKey:e.templateKey})}catch(t){throw Error(`Failed to prewarm Vercel sandbox template "${e.templateKey}": ${ku(t)}. Run \`vercel login\` and \`vercel link\` so the SDK can authenticate, or set VERCEL_TOKEN.`,{cause:t})}r.set(e.templateKey,i)}}}async function pu(e){let t=e.prewarmedTemplates.get(e.templateKey);if(t!==void 0)return t;let n=await Su(await e.loadSandboxModule(),e.templateKey);if(n===null||typeof n.currentSnapshotId!=`string`)throw new Bl({backendName:`vercel`,templateKey:e.templateKey});return{sandboxName:n.name,snapshotId:n.currentSnapshotId,templateKey:e.templateKey}}async function mu(e){let t=await e.loadSandboxModule(),n=await Su(t,e.templateKey),r=Eu(e.createOptions.tags,e.tags);if(n===null){let i={...e.createOptions,name:e.templateKey,persistent:!1};r!==void 0&&(i.tags=r),n=await t.Sandbox.create(i)}else await Du(n,r);let i=wu(e.createOptions);if(typeof n.currentSnapshotId==`string`&&n.currentSnapshotId.length>0&&n.currentSnapshotId!==i)return{sandboxName:n.name,snapshotId:n.currentSnapshotId,templateKey:e.templateKey};await yu(n,e.createOptions);let a=Ul(_u(n,e.templateKey));e.bootstrap!==void 0&&await e.bootstrap({use:async e=>(e!==void 0&&await n.update(e),a)});for(let t of e.seedFiles)typeof t.content==`string`?await a.writeTextFile({content:t.content,path:t.path}):await a.writeBinaryFile({content:t.content,path:t.path});let o=await n.snapshot();return{sandboxName:n.name,snapshotId:o.snapshotId,templateKey:e.templateKey}}async function hu(e){let t=Tu(e.existingMetadata)??e.sessionKey,n=await Su(e.sandboxModule,t);if(n!==null)return await Du(n,e.tags),n;let{runtime:r,source:i,...a}=e.createOptions,o={...a,name:t,persistent:!0,source:{snapshotId:e.snapshotId,type:`snapshot`}};return e.tags!==void 0&&(o.tags=e.tags),await e.sandboxModule.Sandbox.create(o)}function gu(e,t){return{session:Ul(_u(e,t)),useSessionFn:async n=>(n!==void 0&&await e.update(n),Ul(_u(e,t))),async captureState(){return{backendName:`vercel`,metadata:{sandboxName:e.name},sessionKey:t}},async dispose(){}}}function _u(e,t){return{id:t,resolvePath:vu,async runCommand(t){let n=await e.runCommand({args:[`-lc`,t.command],cmd:`bash`,cwd:t.workingDirectory??`/workspace`,signal:t.abortSignal}),[r,i]=await Promise.all([n.stdout(),n.stderr()]);return{exitCode:n.exitCode,stderr:i,stdout:r}},async readFile(t){return await e.readFile({path:t.path})??null},async writeFile(t){let n=await Vl(t.content);await e.writeFiles([{content:n,path:t.path}])}}}function vu(e){return e.startsWith(`/`)?e:`${G}/${e}`}async function yu(e,t){await bu(e,{failureMessage:`Failed to initialize Vercel sandbox workspace.`,script:`mkdir -p ${G} && chown ${xu}:${xu} ${G}`}),t.networkPolicy!==`deny-all`&&await bu(e,{failureMessage:`Failed to install ripgrep in Vercel sandbox.`,script:`command -v rg >/dev/null 2>&1 || { dnf install -y spal-release && dnf install -y ripgrep; }`})}async function bu(e,t){let n=await e.runCommand({args:[`-lc`,t.script],cmd:`bash`,sudo:!0});if(n.exitCode!==0){let e=await n.stderr();throw Error(`${t.failureMessage} ${e}`.trim())}}const xu=`vercel-sandbox`;async function Su(e,t){try{return await e.Sandbox.get({name:t})}catch(e){if(Cu(e))return null;throw Error(`Failed to look up Vercel sandbox "${t}": ${ku(e)}`,{cause:e})}}function Cu(e){return e instanceof Error?(e.response?.status??e.cause?.response?.status)===404:!1}function wu(e){let t=e.source;if(t?.type===`snapshot`&&typeof t.snapshotId==`string`)return t.snapshotId}function Tu(e){let t=e?.sandboxName;return typeof t==`string`?t:void 0}function Eu(e,t){let n={};if(e!==void 0)for(let[t,r]of Object.entries(e))n[t]=r;if(t!==void 0)for(let[e,r]of Object.entries(t))n[e]=r;let r=Object.keys(n).length;if(r!==0){if(r>ju)throw Error(`Vercel Sandbox supports at most ${ju} tags. Ash reserves "agent", "channel", and "sessionId"; remove or consolidate custom tags passed to vercelBackend().`);return n}}async function Du(e,t){t===void 0||Ou(e.tags,t)||await e.update({tags:t})}function Ou(e,t){let n=e??{},r=Object.entries(n),i=Object.entries(t);return r.length===i.length?i.every(([e,t])=>n[e]===t):!1}function ku(e){return e instanceof Error?e.message:String(e)}const Au=1800*1e3,ju=5;function Mu(e){return fu({createOptions:e})}function Nu(e){return Ei(()=>process.env.VERCEL?Mu(e?.vercel):du(e?.local))}async function Pu(e,t,n){try{let r=c(await Z({definition:e,kindLabel:`sandbox`,moduleMap:t,nodeId:n}),`Expected the sandbox export "${e.exportName??`default`}" from "${e.logicalPath}" to return an object.`);return{backend:Fu(r.backend,e.logicalPath),bootstrap:r.bootstrap,description:e.description,exportName:e.exportName,logicalPath:e.logicalPath,onSession:r.onSession,sourceId:e.sourceId,sourceKind:`module`}}catch(t){throw t instanceof X?t:new X(`Failed to attach the sandbox lifecycle handlers from "${e.logicalPath}": ${p(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}function Fu(e,t){if(e===void 0)return Nu();if(typeof e==`function`)return Ei(e);if(typeof e!=`object`||!e)throw new X(`Sandbox "${t}" exposed a non-object "backend" field. Use vercelBackend(), localBackend(), another factory that returns a SandboxBackend value, or a zero-arg callback returning one.`,{logicalPath:t});let n=e;if(typeof n.name!=`string`||n.name.length===0)throw new X(`Sandbox "${t}" backend is missing a non-empty string "name" identifier.`,{logicalPath:t});if(typeof n.create!=`function`)throw new X(`Sandbox "${t}" backend is missing a "create" function.`,{logicalPath:t});return n}async function Iu(e,t,n){try{let r=c(await Z({definition:e,kindLabel:`tool`,moduleMap:t,nodeId:n}),$(e,`to return an object`));Bi(`tool:${r.description}`,{kind:`tool`,name:e.name});let i=o(r.execute,$(e,`to provide an execute function`));return{description:e.description,execute:i,exportName:e.exportName,inputSchema:e.inputSchema,logicalPath:e.logicalPath,name:e.name,sourceId:e.sourceId,sourceKind:`module`,...Lu(r,e)}}catch(t){throw t instanceof X?t:new X(`Failed to attach the tool execute function from "${e.logicalPath}": ${p(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}function Lu(e,t){let n={};e.onCompact!==void 0&&(n.onCompact=o(e.onCompact,$(t,`to provide an onCompact function`))),e.needsApproval!==void 0&&(n.needsApproval=o(e.needsApproval,$(t,`to provide a needsApproval function`)));let r=Ru(e,t);return r!==void 0&&(n.retentionPolicy=r),e.toModelOutput!==void 0&&(n.toModelOutput=o(e.toModelOutput,$(t,`to provide a toModelOutput function`))),e.inputSchema!==void 0&&zu(e.inputSchema)&&(n.inputStandardSchema=e.inputSchema),n}function Ru(e,t){let n=e.retentionPolicy;if(n!==void 0){if(n===`auto`||n===`keep`||typeof n==`function`)return n;throw new X($(t,`to set retentionPolicy to "auto", "keep", or a function`),{logicalPath:t.logicalPath,sourceId:t.sourceId})}}function $(e,t){return`Expected the tool export "${e.exportName??`default`}" from "${e.logicalPath}" ${t}.`}function zu(e){return typeof e==`object`&&!!e&&`~standard`in e&&typeof e[`~standard`]==`object`}async function Bu(e){let t=e.manifest.skills.map(e=>({...e,metadata:e.metadata===void 0?void 0:{...e.metadata}})),n=[],r=[];for(let t of e.manifest.channels){if(t.kind===`disabled`){r.push(t.name);continue}n.push(await Ll(t,e.moduleMap,e.nodeId))}let i=await Promise.all(e.manifest.tools.map(t=>Iu(t,e.moduleMap,e.nodeId))),a=await Promise.all(e.manifest.hooks.map(t=>zl(t,e.moduleMap,e.nodeId))),o=await Promise.all(e.manifest.connections.map(t=>Rl(t,e.moduleMap,e.nodeId))),s=e.manifest.sandbox===null?null:await Pu(e.manifest.sandbox,e.moduleMap,e.nodeId),c=Vu(e.manifest.instructions),l=e.manifest.workspaceResourceRoot,u={channels:n,config:Hu(e.manifest),connections:o,disabledFrameworkChannels:r,disabledFrameworkTools:[...e.manifest.disabledFrameworkTools],hooks:a,metadata:{agentRoot:e.manifest.agentRoot,appRoot:e.manifest.appRoot,diagnosticsSummary:e.manifest.diagnosticsSummary},sandbox:s,workspaceResourceRoot:l,skills:t,tools:i,workspaceSpec:{rootEntries:[...l.rootEntries]}};return c===void 0?u:{...u,instructions:c}}function Vu(e){if(e!==void 0)return{name:e.name,logicalPath:e.logicalPath,markdown:e.markdown,sourceId:e.sourceId,sourceKind:e.sourceKind}}function Hu(e){let t={metadata:{...e.config.metadata},model:e.config.model.source===void 0?{id:e.config.model.id,contextWindowTokens:e.config.model.contextWindowTokens,providerOptions:e.config.model.providerOptions}:{contextWindowTokens:e.config.model.contextWindowTokens,id:e.config.model.id,providerOptions:e.config.model.providerOptions,source:{exportName:e.config.model.source.exportName,sourceKind:`module`,logicalPath:e.config.model.source.logicalPath,sourceId:e.config.model.source.sourceId}},name:e.config.name};if(e.config.compaction!==void 0){let n={};e.config.compaction.model!==void 0&&(n.model=e.config.compaction.model.source===void 0?{contextWindowTokens:e.config.compaction.model.contextWindowTokens,id:e.config.compaction.model.id,providerOptions:e.config.compaction.model.providerOptions}:{contextWindowTokens:e.config.compaction.model.contextWindowTokens,id:e.config.compaction.model.id,providerOptions:e.config.compaction.model.providerOptions,source:{exportName:e.config.compaction.model.source.exportName,sourceKind:`module`,logicalPath:e.config.compaction.model.source.logicalPath,sourceId:e.config.compaction.model.source.sourceId}}),e.config.compaction.thresholdPercent!==void 0&&(n.thresholdPercent=e.config.compaction.thresholdPercent),t.compaction=n}return e.config.source!==void 0&&(t.source=Il(e.config.source)),t}function Uu(e){return{sandbox:{definition:e.authoredSandbox??Wu(),workspaceResourceRoot:e.workspaceResourceRoot}}}function Wu(){return{backend:Nu(),logicalPath:`ash:framework/default-sandbox`,sourceId:`ash:default-sandbox`,sourceKind:`module`}}const Gu=`load_skill`,Ku=Object.freeze({type:`object`,properties:Object.freeze({message:Object.freeze({type:`string`,description:`The message to send to the subagent. Provide all context the subagent needs to complete the task; the subagent does not see the parent's history.`})}),required:Object.freeze([`message`]),additionalProperties:!1});function qu(e){let t=[],n=new Ka(`subagent`,e.reservedToolNames??[]),r=new Map;for(let i of e.subagents){let e={logicalPath:i.logicalPath,sourceId:i.sourceId};if(r.has(i.nodeId))throw new H(`subagent`,`Found multiple runtime subagents mapped to node id "${i.nodeId}".`,{...e,entryName:i.name});let a=Ju(i),o={definition:i,prepared:a};n.register(i.name,o,{location:e,duplicateMessage:`Found multiple subagents named "${i.name}". Subagent names must be unique at runtime.`,reservedMessage:`Subagent "${i.name}" collides with another runtime-visible tool name.`}),t.push(a),r.set(i.nodeId,o)}return{preparedTools:t,subagentsByName:n.asMap(),subagentsByNodeId:r}}function Ju(e){return{description:e.description,inputSchema:Ku,kind:`subagent`,logicalPath:e.logicalPath,name:e.name,nodeId:e.nodeId,sourceId:e.sourceId}}async function Yu(e,t={}){let n=[],r=new Ka(`tool`,t.reservedToolNames??[]);for(let t of e.tools){let e=await Xu(t);r.register(t.name,{definition:t,prepared:e},{location:{logicalPath:t.logicalPath,sourceId:t.sourceId},duplicateMessage:`Found multiple authored tools named "${t.name}". Tool names must be unique at runtime.`,reservedMessage:`Tool "${t.name}" collides with another runtime-visible tool name.`}),n.push(e)}return{preparedTools:n,toolsByName:r.asMap()}}async function Xu(e){return{description:e.description,inputSchema:await Zu(e),kind:`authored-tool`,logicalPath:e.logicalPath,name:e.name,sourceId:e.sourceId}}async function Zu(e){return e.inputSchema}var Qu=class extends Error{logicalPath;nodeId;sourceId;constructor(e,t={}){super(e),this.name=`ResolveRuntimeAgentGraphError`,t.logicalPath!==void 0&&(this.logicalPath=t.logicalPath),t.nodeId!==void 0&&(this.nodeId=t.nodeId),t.sourceId!==void 0&&(this.sourceId=t.sourceId)}};async function $u(e){let t=new Map,n=rd(e.manifest),r=new Map(e.manifest.subagents.map(e=>[e.nodeId,e]));return{nodesByNodeId:t,root:await ed({childNodeIdsByParentNodeId:n,manifest:e.manifest,moduleMap:e.moduleMap,nodeId:L,nodesByNodeId:t,subagentNodesById:r})}}async function ed(e){let t=id(e.nodeId);if(e.nodesByNodeId.has(t))throw new Qu(`Found multiple runtime agent nodes for node id "${t}".`,{nodeId:t,sourceId:e.sourceId});let n=await Bu({manifest:e.manifest,moduleMap:e.moduleMap,nodeId:e.nodeId}),r=n.connections.length>0,i=Nl({hasConnections:r}),a=r?od(i,n.connections):i,o=new Set(a.map(e=>e.name)),s=Pl(),c=new Set(n.tools.map(e=>e.name));for(let r of n.disabledFrameworkTools)if(!s.has(r))throw new Qu(`agent/tools/${r}.ts exports disableTool() but "${r}" is not a framework tool. Rename the file to one of: ${[...s].sort().join(`, `)}.`,{nodeId:t,sourceId:e.sourceId});let l=new Set(n.disabledFrameworkTools),u=await Yu({tools:[...a.filter(e=>!c.has(e.name)&&!l.has(e.name)),...n.tools]},{reservedToolNames:o.has(`load_skill`)||c.has(`load_skill`)?[]:[Gu]}),d=new Set(n.channels.map(e=>e.name)),f=hc();for(let r of n.disabledFrameworkChannels)if(!f.has(r))throw new Qu(`agent/channels/${r}.ts exports disableRoute() but "${r}" is not a framework channel. Rename the file to one of: ${[...f].sort().join(`, `)}.`,{nodeId:t,sourceId:e.sourceId});let p=new Set(n.disabledFrameworkChannels),m=[...mc().filter(e=>!d.has(e.name)&&!p.has(e.name)),...n.channels],h=Uu({authoredSandbox:n.sandbox,workspaceResourceRoot:n.workspaceResourceRoot}),g=qu({reservedToolNames:[Gu,...u.preparedTools.map(e=>e.name)],subagents:await td({childNodeIdsByParentNodeId:e.childNodeIdsByParentNodeId,moduleMap:e.moduleMap,nodesByNodeId:e.nodesByNodeId,parentNodeId:e.nodeId,subagentNodesById:e.subagentNodesById})}),_={agent:n,channels:m,hookRegistry:Fl(n.hooks),nodeId:t,sandboxRegistry:h,sourceId:e.sourceId,subagentRegistry:g,toolRegistry:u,turnAgent:cs({agent:n,nodeId:t,tools:[...u.preparedTools,...g.preparedTools]})};return e.nodesByNodeId.set(t,_),_}async function td(e){let t=[],n=e.childNodeIdsByParentNodeId.get(e.parentNodeId)??[];for(let r of n){let n=e.subagentNodesById.get(r);if(n===void 0)throw new Qu(`Missing compiled subagent node "${r}" while resolving runtime subagents.`,{nodeId:id(e.parentNodeId),sourceId:r});t.push(await nd({childNodeIdsByParentNodeId:e.childNodeIdsByParentNodeId,moduleMap:e.moduleMap,nodesByNodeId:e.nodesByNodeId,sourceRef:n,subagentNodesById:e.subagentNodesById}))}return t}async function nd(e){let t={description:e.sourceRef.description,logicalPath:e.sourceRef.logicalPath,name:e.sourceRef.name,nodeId:id(e.sourceRef.nodeId),sourceId:e.sourceRef.sourceId,sourceKind:`module`};return await ed({childNodeIdsByParentNodeId:e.childNodeIdsByParentNodeId,manifest:e.sourceRef.agent,moduleMap:e.moduleMap,nodeId:e.sourceRef.nodeId,nodesByNodeId:e.nodesByNodeId,sourceId:e.sourceRef.sourceId,subagentNodesById:e.subagentNodesById}),t}function rd(e){let t=new Map;for(let n of e.subagentEdges){let e=t.get(n.parentNodeId);if(e===void 0){t.set(n.parentNodeId,[n.childNodeId]);continue}e.push(n.childNodeId)}return t}function id(e){return e===`__root__`?So:e}const ad=Yo.name;function od(e,t){let n=t.map(e=>e.connectionName).join(`, `);return e.map(e=>e.name===ad?{...e,description:`${e.description} Available connections: ${n}.`}:e)}const sd=process.env.ASH_DISABLE_AGENT_CACHE===`1`;async function cd(e){let[t,n]=await Promise.all([Eo({compiledArtifactsSource:e}),ld(e)]),r=await $u({manifest:t,moduleMap:n}),i=r.root;return{adapterRegistry:Xa({channels:md(r)}),compiledArtifactsSource:e,graph:r,hookRegistry:i.hookRegistry,moduleMap:n,resolvedAgent:i.agent,subagentRegistry:i.subagentRegistry,toolRegistry:i.toolRegistry,turnAgent:i.turnAgent}}async function ld(e){return e.kind===`disk`&&e.moduleMapLoadMode===`authored-source`?await ud(e):await jo({compiledArtifactsSource:e})}async function ud(e){if(e.moduleMapLoaderPath===void 0)throw Error(`Authored-source module map loading requires "moduleMapLoaderPath" in the compiled artifacts source.`);return await(await import(Te(e.moduleMapLoaderPath).href)).loadCompiledModuleMapFromAuthoredSource({compiledArtifactsSource:e})}async function dd(e){if(sd)return cd(e);let t=uo(),n=no(e),r=await yo(e),i=t.bundleCacheKeyBySourceKey.get(n);i!==void 0&&i!==r&&t.bundleCache.delete(i),t.bundleCacheKeyBySourceKey.set(n,r);let a=t.bundleCache.get(r);if(a!==void 0)return a;let o=cd(e).catch(e=>{throw t.bundleCache.delete(r),t.bundleCacheKeyBySourceKey.get(n)===r&&t.bundleCacheKeyBySourceKey.delete(n),e});return t.bundleCache.set(r,o),o}async function fd(e){let t=await dd(e.compiledArtifactsSource);if(e.nodeId===void 0)return t;let n=Co(t.graph,e.nodeId);return{adapterRegistry:t.adapterRegistry,compiledArtifactsSource:t.compiledArtifactsSource,graph:{nodesByNodeId:t.graph.nodesByNodeId,root:n},hookRegistry:n.hookRegistry,moduleMap:t.moduleMap,nodeId:e.nodeId,resolvedAgent:n.agent,subagentRegistry:n.subagentRegistry,toolRegistry:n.toolRegistry,turnAgent:n.turnAgent}}function pd(){let e=uo();e.bundleCache.clear(),e.bundleCacheKeyBySourceKey.clear()}function md(e){let t=new Map;for(let n of e.nodesByNodeId.values())for(let e of n.channels)t.set(`${e.sourceId}:${e.name}`,e);return[...t.values()]}new B(`ash.channel`,{codec:{serialize(e){return{kind:Fa(e),state:e.state?{...e.state}:{}}},deserialize(e,t){let n=t.get(hd);if(n===void 0)throw Error(`Cannot deserialize "ash.channel" before "ash.bundle". The runtime bundle must be present in context.`);return Za(n.adapterRegistry,e)}}});const hd=new B(`ash.bundle`,{codec:{serialize:e=>({nodeId:e.nodeId,source:e.compiledArtifactsSource}),deserialize:e=>{let{source:t,nodeId:n}=e;return fd({compiledArtifactsSource:t,nodeId:n})}}});new B(`ash.session`);const gd=new B(`ash.sandbox`),_d=_(),vd={workflowId:`workflow//${_d.name}@${_d.version}//workflowEntry`};function yd(e=process.cwd()){return S(e)}function bd(e){return be(`sha256`).update(e).digest(`hex`).slice(0,12)}function xd(){return!!process.env.VERCEL}function Sd(e,t=`all`){let n=x(e,`.ash`,`nitro`);return t===`all`?n:x(n,t)}function Cd(e,t){return x(e,`.ash`,`nitro-output`,t)}function wd(e){let t=x(m(),`.ash`,`workflow-cache`);return Td(t),x(t,bd(e))}function Td(e){if(!xe(e))return;let t=_().version,n;try{n=Ce(e)}catch{return}for(let r of n){let n=x(e,r),i=x(n,`ash-cache.json`);if(xe(i))try{let e=JSON.parse(Se(i,`utf8`));typeof e.ashVersion==`string`&&e.ashVersion!==t&&we(n,{force:!0,recursive:!0})}catch{}}}function Ed(e){return x(e,`.ash`,`sandbox-cache`)}function Dd(e){return xd()?x(e,`.vercel`,`output`):x(e,`.output`)}function Od(e){return{appRoot:e,outputDir:Dd(e),workflowId:vd.workflowId,workflowBuildDir:wd(e),workflowSourceDir:g(`src/execution`)}}export{Er as C,In as D,L as E,jr as S,Dr as T,no as _,wd as a,ni as b,hc as c,Eo as d,So as f,to as g,eo as h,Cd as i,mc as l,U as m,yd as n,pd as o,go as p,Sd as r,$u as s,Od as t,G as u,fa as v,Or as w,Nr as x,pa as y};
|