experimental-ash 0.11.1 → 0.12.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 +161 -0
- package/dist/docs/public/channels/README.md +29 -14
- package/dist/docs/public/channels/slack.md +52 -28
- package/dist/docs/public/session-context.md +9 -6
- package/dist/docs/public/typescript-api.md +14 -5
- package/dist/src/chunks/{dev-authored-source-watcher-Dli96TWx.js → dev-authored-source-watcher-DA6pewzf.js} +1 -1
- package/dist/src/chunks/{host-Cp4XhAAX.js → host-D_hajFPO.js} +2 -2
- package/dist/src/chunks/paths-BYaK6-t0.js +88 -0
- package/dist/src/chunks/{prewarm-DIMA-oZ6.js → prewarm-QPhmJIsB.js} +1 -1
- package/dist/src/cli/commands/info.js +1 -1
- package/dist/src/cli/run.js +1 -1
- package/dist/src/compiler/manifest.d.ts +19 -0
- package/dist/src/compiler/manifest.js +14 -0
- package/dist/src/compiler/normalize-channel.js +8 -0
- package/dist/src/compiler/normalize-connection.js +31 -1
- package/dist/src/evals/cli/eval.js +1 -1
- package/dist/src/execution/sandbox/bindings/local.js +18 -7
- package/dist/src/execution/sandbox/bindings/vercel.js +16 -20
- package/dist/src/execution/sandbox/read-file-tool.js +1 -1
- package/dist/src/execution/sandbox/session.d.ts +6 -29
- package/dist/src/execution/sandbox/session.js +55 -15
- package/dist/src/execution/sandbox/stream-utils.d.ts +9 -0
- package/dist/src/execution/sandbox/stream-utils.js +22 -0
- package/dist/src/execution/sandbox/write-file-tool.js +3 -3
- package/dist/src/execution/workflow-steps.js +1 -1
- package/dist/src/harness/attachment-staging.js +2 -2
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/nitro/host/build-application.js +11 -1
- package/dist/src/internal/nitro/host/build-vercel-agent-summary.d.ts +40 -0
- package/dist/src/internal/nitro/host/build-vercel-agent-summary.js +139 -0
- package/dist/src/protocol/vercel-agent-summary.d.ts +201 -0
- package/dist/src/protocol/vercel-agent-summary.js +72 -0
- package/dist/src/public/channels/slack/api.d.ts +309 -18
- package/dist/src/public/channels/slack/api.js +361 -26
- package/dist/src/public/channels/slack/attachments.d.ts +11 -10
- package/dist/src/public/channels/slack/attachments.js +42 -26
- package/dist/src/public/channels/slack/blocks.d.ts +45 -0
- package/dist/src/public/channels/slack/blocks.js +243 -0
- package/dist/src/public/channels/slack/defaults.d.ts +14 -7
- package/dist/src/public/channels/slack/defaults.js +41 -53
- package/dist/src/public/channels/slack/inbound.d.ts +127 -20
- package/dist/src/public/channels/slack/inbound.js +104 -30
- package/dist/src/public/channels/slack/index.d.ts +13 -3
- package/dist/src/public/channels/slack/index.js +9 -1
- package/dist/src/public/channels/slack/interactions.d.ts +2 -7
- package/dist/src/public/channels/slack/interactions.js +14 -19
- package/dist/src/public/channels/slack/slackChannel.d.ts +69 -55
- package/dist/src/public/channels/slack/slackChannel.js +162 -183
- package/dist/src/public/channels/slack/verify.d.ts +48 -0
- package/dist/src/public/channels/slack/verify.js +70 -0
- package/dist/src/public/definitions/defineChannel.d.ts +12 -0
- package/dist/src/public/definitions/defineChannel.js +2 -2
- package/dist/src/public/definitions/sandbox.d.ts +1 -1
- package/dist/src/public/sandbox/index.d.ts +1 -1
- package/dist/src/runtime/skills/sandbox-access.js +3 -3
- package/dist/src/shared/sandbox-session.d.ts +96 -26
- package/package.json +1 -1
- package/dist/src/chunks/paths-CWTvKBbf.js +0 -88
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{n as e}from"./chunk-8L7ocgPr.js";import{C as t,T as n,i as r,r as i,w as a}from"./paths-
|
|
1
|
+
import{n as e}from"./chunk-8L7ocgPr.js";import{C as t,T as n,i as r,r as i,w as a}from"./paths-BYaK6-t0.js";import{a as o,i as s,o as c,r as l}from"./authored-module-loader-Pt_g8xX2.js";import{a as u,i as d,n as f,o as p,r as m,t as h}from"./package-DmsQgn4v.js";import{g,m as ee,p as te}from"./types-MZUhN0Zy.js";import{a as ne,c as re,n as ie,o as ae,r as oe,t as se}from"./prewarm-QPhmJIsB.js";import{builtinModules as ce}from"node:module";import{dirname as _,extname as le,isAbsolute as ue,join as v,relative as y,resolve as b,sep as de}from"node:path";import{cp as x,mkdir as S,readFile as C,readdir as fe,realpath as pe,rename as me,rm as w,writeFile as T}from"node:fs/promises";import{randomUUID as he}from"node:crypto";import{existsSync as ge,readFileSync as _e}from"node:fs";import{fileURLToPath as ve}from"node:url";import{build as ye,copyPublicAssets as be,createDevServer as xe,createNitro as Se,prepare as Ce,prerender as we}from"nitro/builder";import{Buffer as Te}from"node:buffer";const Ee=`ash-cache.json`;async function E(e){let t=await Oe(e),n=h().version;t!==null&&t===n||await w(e,{force:!0,recursive:!0})}async function De(e){await S(e,{recursive:!0}),await T(v(e,Ee),`${JSON.stringify({ashVersion:h().version},null,2)}\n`)}async function Oe(e){try{let t=JSON.parse(await C(v(e,Ee),`utf8`));return typeof t.ashVersion==`string`?t.ashVersion:null}catch(e){return e instanceof Error&&`code`in e&&e.code,null}}const ke=new Set([`__builtin_response_array_buffer`,`__builtin_response_json`,`__builtin_response_text`]);async function Ae(e){if(e.mode===!1)return{code:e.source,workflowManifest:{}};let t=await je(e.filename,e.source),n=Ne(t);if(n.length===0)return{code:e.source,workflowManifest:{}};let r=e.moduleSpecifier??`./${Je(e.filename)}`,i={},a=[],o=[],s=!1;for(let t of n){if(t.directive===`use step`){let n=Ye(r,t.name);i.steps??={};let c=i.steps[e.filename]??={};if(c[t.name]={stepId:n},e.mode===`workflow`){let e=t.exportPrefix.length>0?`export `:``;a.push({end:t.rangeEnd,start:t.rangeStart,text:`${e}var ${t.name} = globalThis[Symbol.for("WORKFLOW_USE_STEP")](${JSON.stringify(n)});`})}else a.push({end:t.directiveEnd,start:t.directiveStart,text:``}),e.mode===`step`?(s=!0,o.push(`registerStepFunction(${JSON.stringify(n)}, ${t.name});`)):o.push(`${t.name}.stepId = ${JSON.stringify(n)};`);continue}let n=`workflow//${r}//${t.name}`;i.workflows??={};let c=i.workflows[e.filename]??={};c[t.name]={workflowId:n},e.mode===`workflow`?(a.push({end:t.directiveEnd,start:t.directiveStart,text:``}),o.push(`${t.name}.workflowId = ${JSON.stringify(n)};`),o.push(`globalThis.__private_workflows.set(${JSON.stringify(n)}, ${t.name});`)):(a.push({end:t.directiveEnd,start:t.directiveStart,text:`throw new Error(${JSON.stringify(`You attempted to execute workflow ${t.name} function directly. To start a workflow, use start(${t.name}) from workflow/api`)});`}),o.push(`${t.name}.workflowId = ${JSON.stringify(n)};`))}let c=`/**__internal_workflows${JSON.stringify(i)}*/;`,l=n.some(e=>e.directive===`use workflow`);if(e.mode===`workflow`&&!l)return{code:`${c}\n${Me(e.source,t,n,r)}`,workflowManifest:i};let u=Re(e.source,a),d=e.mode===`workflow`?await ze(e.filename,u):u;return{code:`${s?`import { registerStepFunction } from "workflow/internal/private";\n${c}\n`:`${c}\n`}${d}${o.length>0?`\n${o.join(`
|
|
2
2
|
`)}\n`:``}`,workflowManifest:i}}async function je(e,t){let{parseAst:n}=await c();return n(t,{astType:`ts`,lang:qe(e),range:!0,sourceType:`module`},e)}function Me(e,t,n,r){let i=Be(e,t),a=n.filter(e=>e.directive===`use step`).map(e=>{let t=e.exportPrefix.length>0?`export `:``,n=Ye(r,e.name);return`${t}var ${e.name} = globalThis[Symbol.for("WORKFLOW_USE_STEP")](${JSON.stringify(n)});`}),o=[...i,...a];return o.length>0?`${o.join(`
|
|
3
3
|
`)}\n`:``}function Ne(e){let t=[];for(let n of e.body??[]){let e=Pe(n);if(e===null)continue;let r=e.fn,i=r.id?.name,a=Ie(r.body);if(r.async!==!0||i===void 0||a===void 0)continue;let o=Le(a[0]);o!==null&&t.push({directive:o.value,directiveEnd:o.end,directiveStart:o.start,exportPrefix:e.exported?`export `:``,name:i,rangeEnd:e.end,rangeStart:e.start})}return t}function Pe(e){return e.type===`FunctionDeclaration`?Fe(e,!1,e):e.type!==`ExportNamedDeclaration`||e.declaration?.type!==`FunctionDeclaration`?null:Fe(e.declaration,!0,e)}function Fe(e,t,n){return e.start===void 0||e.end===void 0||n.start===void 0||n.end===void 0?null:{end:n.end,exported:t,fn:e,start:n.start}}function Ie(e){return e===void 0||Array.isArray(e)?e:e.body}function Le(e){let t=e?.directive??(e?.type===`ExpressionStatement`&&e.expression?.type===`Literal`?e.expression.value:void 0);return t!==`use workflow`&&t!==`use step`||e?.start===void 0||e.end===void 0?null:{end:e.end,start:e.start,value:t}}function Re(e,t){let n=``,r=0;for(let i of[...t].sort((e,t)=>e.start-t.start))n+=e.slice(r,i.start),n+=i.text,r=i.end;return n+e.slice(r)}async function ze(e,t){let n=await je(e,t),r=We(n),i=[];for(let e of n.body??[]){if(e.type!==`ImportDeclaration`||e.start===void 0||e.end===void 0)continue;let n=Ue(e);n.length>0&&n.every(e=>!r.has(e))&&i.push({end:Ke(t,e.end),start:e.start,text:``})}return i.length>0?Re(t,i):t}function Be(e,t){let n=[];for(let r of t.body??[])r.type===`ExportNamedDeclaration`&&r.declaration?.type===`VariableDeclaration`&&r.declaration.kind===`const`&&r.start!==void 0&&r.end!==void 0&&(r.declaration.declarations??[]).every(Ve)&&n.push(e.slice(r.start,r.end).trim());return n}function Ve(e){return He(e.init)}function He(e){return e==null?!1:e.type===`Literal`?e.value===null||typeof e.value==`boolean`||typeof e.value==`number`||typeof e.value==`string`:e.type===`TSAsExpression`||e.type===`TSSatisfiesExpression`||e.type===`TSNonNullExpression`||e.type===`TSTypeAssertion`?He(e.expression):e.type===`UnaryExpression`&&e.argument?.type===`Literal`?typeof e.argument.value==`number`:!1}function Ue(e){return e.importKind===`type`?[]:(e.specifiers??[]).filter(e=>e.importKind!==`type`).map(e=>e.local?.name).filter(e=>e!==void 0)}function We(e){let t=new Set;return D(e,e=>{e.type===`Identifier`&&typeof e.name==`string`&&t.add(e.name)}),t}function D(e,t){if(!(e.type===`ImportDeclaration`||e.type?.startsWith(`TS`))){t(e);for(let n of Object.values(e))if(Array.isArray(n))for(let e of n)Ge(e)&&D(e,t);else Ge(n)&&D(n,t)}}function Ge(e){return typeof e==`object`&&!!e&&typeof e.type==`string`}function Ke(e,t){let n=t;for(;n<e.length&&(e[n]===` `||e[n]===` `);)n+=1;return e[n]===`\r`&&e[n+1]===`
|
|
4
4
|
`?n+2:e[n]===`
|
|
@@ -19,4 +19,4 @@ export const POST = workflowEntrypoint(workflowCode);`);if(n===-1||r===-1||r<=n)
|
|
|
19
19
|
`):null},resolveId(e){return an.test(e)?rn:null}}}function sn(e){return e===`all`||e===`app`}function cn(e){return z(e)}function z(e){return e===`all`||e===`flow`}function B(e,t){let r=`#ash-route-handler/${t.method??`ALL`} ${t.route}`,i=n(t.handlerPath);e.options.handlers.push({handler:r,method:t.method,route:t.route}),e.options.virtual[r]=[`import handler from ${i};`,`export default handler;`].join(`
|
|
20
20
|
`)}function V(e){return v(e.options.buildDir,`workflow`)}function ln(e,t){let n=y(e,t).replaceAll(`\\`,`/`);return n.startsWith(`.`)?n:`./${n}`}async function un(e,t){let n=v(V(e),`${t.bundleName}-handler.mjs`),r=_(n),i=ln(r,t.bundlePath),a=(t.directHandlers??[]).map(e=>{let t=ln(r,e.bundlePath);return{importSpecifier:t,isOwnBundle:t===i,queuePrefix:e.queuePrefix}});await S(r,{recursive:!0}),await T(n,dn({bundlePath:i,directHandlers:a,runtimeImportSpecifier:t.runtimeImportSpecifier})),e.options.handlers.push({handler:n,route:t.route})}function dn(e){let t=[`// Generated by Ash. Do not edit by hand.`,`import { POST } from ${JSON.stringify(e.bundlePath)};`];if(e.directHandlers.length>0&&e.runtimeImportSpecifier!==void 0){let n=0,r=e.directHandlers.map(e=>{if(e.isOwnBundle)return{...e,binding:`POST`};let t=`__ashWorkflowDirectHandler${n}`;return n+=1,{...e,binding:t}});for(let e of r)e.isOwnBundle||t.push(`import { POST as ${e.binding} } from ${JSON.stringify(e.importSpecifier)};`);t.push(`import { getWorld as __ashGetWorkflowWorld } from ${JSON.stringify(e.runtimeImportSpecifier)};`,``,`try {`,` const __ashWorkflowWorld = __ashGetWorkflowWorld();`,` if (typeof __ashWorkflowWorld?.registerHandler === "function") {`);for(let e of r)t.push(` __ashWorkflowWorld.registerHandler(${JSON.stringify(e.queuePrefix)}, ${e.binding});`);t.push(` }`,`} catch (err) {`,` console.warn("[ash] Failed to register direct workflow queue handlers:", err);`,`}`)}return t.push(``,`export default async ({ req }) => {`,` return await POST(req);`,`};`,``),t.join(`
|
|
21
21
|
`)}function fn(e,t){let r=`#ash-route${t.route}`,i=n(t.modulePath);e.options.handlers.push({handler:r,method:t.method,route:t.route}),e.options.virtual[r]=[`import { ${t.handlerExport} } from ${i};`,`export default async (event) => ${t.handlerExport}(${t.args}, event.req);`].join(`
|
|
22
|
-
`)}async function pn(e,n,r){if(cn(r.surface)){let t=f(),i=new Kt({appRoot:n.appRoot,compiledArtifactsBootstrapPath:n.compiledArtifacts.bootstrapPath,outDir:n.workflowBuildDir,rootDir:t,watch:e.options.dev}),a=Promise.resolve(),o=async()=>{await i.build({nitroStepOutfile:z(r.surface)?v(V(e),`steps.mjs`):void 0,nitroWorkflowOutfile:e.options.dev&&z(r.surface)?v(V(e),`workflows.mjs`):void 0})},s=async()=>{let e=a.then(o);a=e.catch(()=>{}),await e},c=!0;await s(),e.hooks.hook(`build:before`,async()=>{if(c){c=!1;return}await s()}),e.options.dev&&e.hooks.hook(`dev:reload`,async()=>{await s()})}let i=re({appRoot:n.appRoot,dev:e.options.dev});sn(r.surface)&&(B(e,{handlerPath:d(`src/internal/nitro/routes/index.ts`),method:`GET`,route:`/`}),B(e,{handlerPath:d(`src/internal/nitro/routes/health.ts`),method:`GET`,route:te}),fn(e,{args:JSON.stringify({appRoot:i.appRoot}),handlerExport:`handleAgentInfoRequest`,method:`GET`,modulePath:d(`src/internal/nitro/routes/info.ts`),route:ee}),B(e,{handlerPath:d(`src/internal/nitro/routes/workflow-runs.ts`),method:`GET`,route:`/api/runs`}),B(e,{handlerPath:d(`src/internal/nitro/routes/workflow-run.ts`),method:`GET`,route:`/api/runs/:runId`}),B(e,{handlerPath:d(`src/internal/nitro/routes/workflow-run-steps.ts`),method:`GET`,route:`/api/runs/:runId/steps`}),B(e,{handlerPath:d(`src/internal/nitro/routes/workflow-run-events.ts`),method:`GET`,route:`/api/runs/:runId/events`}),ae(e,{artifactsConfig:i,registrations:ne(n)}));let a=V(e),o=z(r.surface)?e.options.dev?v(a,`workflows.mjs`):v(n.workflowBuildDir,`workflows.mjs`):void 0,s=e.options.dev&&o!==void 0?[{bundlePath:o,queuePrefix:`__wkf_workflow_`}]:[],c=s.length>0?t(u(`workflow/runtime`)):void 0;o&&await un(e,{bundleName:`workflows`,bundlePath:o,directHandlers:s,route:`/.well-known/workflow/v1/flow`,runtimeImportSpecifier:c}),e.routing.sync()}function mn(){return`${g}/cron/${he()}`}function hn(e){e.options.vercel!==void 0&&(e.options.vercel.cronHandlerRoute=mn())}function gn(e){return{plugins:[l(),...e]}}function _n(e){e.hooks.hook(`rollup:before`,(e,t)=>{Array.isArray(t.plugins)&&t.plugins.unshift({name:`ash:nitro-routing-import-specifiers`,transform(e,t){if(t!==`#nitro/virtual/routing`&&t!==`#nitro/virtual/routing-meta`)return null;let n=a(e);return n===e?null:{code:n,map:null}}})})}const vn=`@alinea/generated.@appsignal/nodejs.@aws-sdk/client-s3.@aws-sdk/s3-presigned-post.@blockfrost/blockfrost-js.@highlight-run/node.@huggingface/transformers.@jpg-store/lucid-cardano.@libsql/client.@mikro-orm/core.@mikro-orm/knex.@node-rs/argon2.@node-rs/bcrypt.@prisma/client.@react-pdf/renderer.@sentry/profiling-node.@sparticuz/chromium.@sparticuz/chromium-min.@statsig/statsig-node-core.@swc/core.@xenova/transformers.@zenstackhq/runtime.argon2.autoprefixer.aws-crt.bcrypt.better-sqlite3.canvas.chromadb-default-embed.config.cpu-features.cypress.dd-trace.eslint.express.firebase-admin.htmlrewriter.import-in-the-middle.isolated-vm.jest.jsdom.keyv.libsql.mdx-bundler.mongodb.mongoose.newrelic.next-mdx-remote.next-seo.node-cron.node-pty.node-web-audio-api.onnxruntime-node.oslo.pg.pino.pino-pretty.pino-roll.playwright.playwright-core.postcss.prettier.prisma.puppeteer.puppeteer-core.ravendb.require-in-the-middle.rimraf.sharp.shiki.sqlite3.thread-stream.ts-morph.ts-node.typescript.vscode-oniguruma.webpack.websocket.zeromq`.split(`.`);function yn(e){if(e)return{config:{version:3,framework:{version:h().version}}}}const bn=[`workflow`,`workflow/api`,`workflow/errors`,`workflow/internal/builtins`,`workflow/internal/private`,`workflow/runtime`],xn=Symbol(`ash.workflow-transform-patched`),Sn=[`@napi-rs/keyring`];function Cn(){let e={};for(let t of bn)e[t]=u(t);return e}function wn(e){if(!e&&process.env.VERCEL)return`vercel`}function Tn(e){return e===`all`||e===`app`}function H(e){return e===`all`||e===`flow`}function U(e){return H(e)}function En(e,t){return e.options.dev?v(e.options.buildDir,`workflow`,`steps.mjs`):v(t.workflowBuildDir,`steps.mjs`)}function Dn(e){let t=e.compileResult.manifest.config.build;return[...new Set([...Sn,...vn,...t?.externalDependencies??[]])].filter(e=>e!==p)}function W(e){return e.replaceAll(`\\`,`/`)}function G(e){let t=e.indexOf(`?`),n=e.indexOf(`#`),r=t===-1?n:n===-1?t:Math.min(t,n);return r===-1?e:e.slice(0,r)}function K(e){return e.startsWith(`/@fs/`)?e.slice(4):e}function q(e,t){return t.startsWith(`file://`)?W(K(G(ve(t)))):ue(t)?W(K(G(t))):W(K(G(b(e,t))))}function On(e,t){let n=W(e);return n.startsWith(t)||n.includes(`/.ash/workflow-cache/`)}function J(e){let t=W(e);return process.platform===`win32`?t.toLowerCase():t}function kn(e){let t=/^\s*import\s+(?:.+?\s+from\s+)?["']([^"']+)["'];?\s*$/gm,n=[];for(let r of e.matchAll(t)){let e=r[1];e!==void 0&&n.push(e)}return n}function An(e,t,n){return t.startsWith(`workflow`)?u(t):t.startsWith(`.`)||t.startsWith(`/`)||t.startsWith(`file://`)?q(n===void 0?e:_(q(e,n)),t):null}async function Y(e,t){let n=await C(e,`utf8`),r=new Set;for(let i of kn(n)){let n=An(t,i,e);n!==null&&r.add(J(n))}return r}async function jn(e,t){if(e.options.noExternals===!0)return;let n;try{n=await Y(t,e.options.rootDir)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}let r=Array.isArray(e.options.noExternals)?[...e.options.noExternals]:[];e.options.noExternals=[...new Set([...r,...n])]}function Mn(e,t){let n=W(e).replace(/\/$/,``),r=W(t),i=n.toLowerCase(),a=r.toLowerCase();if(a.startsWith(`${i}/`))return r.slice(n.length+1);if(a===i)return`.`;let o=y(n,r).replaceAll(`\\`,`/`);if(o.startsWith(`../`)&&(o=o.split(`/`).filter(e=>e!==`..`).join(`/`)),o.includes(`:`)||o.startsWith(`/`)){let e=r.split(`/`).pop();return e===void 0||e.length===0?`unknown.ts`:e}return o}function Nn(e,t){let n=[t,v(e.options.buildDir,`workflow`)].map(t=>q(e.options.rootDir,t));e.hooks.hook(`rollup:before`,(t,r)=>{Array.isArray(r.plugins)&&r.plugins.unshift({name:`ash:workflow-module-side-effects`,resolveId(t,r){let i=An(e.options.rootDir,t,r)??q(e.options.rootDir,t);return n.some(e=>On(i,e))?{id:i,moduleSideEffects:`no-treeshake`}:null}})})}function Pn(e,t){let n=null,r=async()=>(n===null&&(n=await Y(t.stepEntrypointPath,e.options.rootDir)),n);e.hooks.hook(`build:before`,()=>{n=null}),e.options.dev&&e.hooks.hook(`dev:reload`,()=>{n=null}),e.hooks.hook(`rollup:before`,(t,n)=>{Array.isArray(n.plugins)&&n.plugins.unshift({name:`ash:workflow-step-module-side-effects`,async resolveId(t,n){let i=An(e.options.rootDir,t,n);return i===null||!(await r()).has(J(i))?null:{id:i,moduleSideEffects:`no-treeshake`}}})})}function Fn(e,t){let n=null,r=async()=>(n===null&&(n=await Y(t.stepEntrypointPath,e.options.rootDir)),n);e.hooks.hook(`build:before`,()=>{n=null}),e.options.dev&&e.hooks.hook(`dev:reload`,()=>{n=null}),e.hooks.hook(`rollup:before`,(t,n)=>{Array.isArray(n.plugins)&&n.plugins.unshift({async transform(t,n){let i=await r(),a=q(e.options.rootDir,n);return i.has(J(a))?{code:(await k(Mn(e.options.rootDir,a),t,`step`,a,e.options.rootDir)).code,map:null}:null},name:`ash:workflow-step-transform`})})}function In(e,t){let n=W(t);e.hooks.hook(`rollup:before`,(e,t)=>{Array.isArray(t.plugins)&&t.plugins.unshift({name:`ash:instrumentation-module-side-effects`,resolveId(e){return W(e)===n?{id:e,moduleSideEffects:`no-treeshake`}:null}})})}function Ln(e,t){let n=W(t);e.hooks.hook(`rollup:before`,(e,t)=>{if(Array.isArray(t.plugins))for(let e of t.plugins){if(typeof e!=`object`||!e)continue;let t=e;if(t.name!==`workflow:transform`||t[xn]===!0||typeof t.transform!=`function`)continue;let r=t.transform;t.transform=function(e,t,...i){return On(t,n)?null:r.call(this,e,t,...i)},t[xn]=!0}})}async function X(e,t,n={}){let r=n.surface??`all`,a=(!t||n.schedules===!0)&&Tn(r)&&e.scheduleRegistrations.length>0,o=wn(t),s=o===`vercel`?on():null,c=s===null?[]:[s],l=gn(c),u=gn(c),f=Dn(e),p=i(e.appRoot,r),h=e.compiledArtifacts.instrumentationPluginPath===void 0?[e.compiledArtifacts.bootstrapPath]:[e.compiledArtifacts.instrumentationPluginPath,e.compiledArtifacts.bootstrapPath];await E(p);let g=await Se({_cli:{command:t?`dev`:`build`},buildDir:p,dev:t,logLevel:t?1:void 0,output:n.outputDir===void 0?void 0:{dir:n.outputDir},preset:o,plugins:h,publicAssets:[],scanDirs:U(r)?[m(`src/execution`)]:void 0,rolldownConfig:l,rollupConfig:u,rootDir:e.appRoot,serverDir:!1,traceDeps:f,vercel:yn(o===`vercel`&&Tn(r))},t?{watch:!0}:void 0);if(await De(p),_n(g),H(r)){let t=Cn();for(let[e,n]of Object.entries(t))g.options.alias[e]=n;Nn(g,e.workflowBuildDir),Ln(g,e.workflowBuildDir)}if(U(r)){let t=En(g,e);Pn(g,{stepEntrypointPath:t}),Fn(g,{stepEntrypointPath:t})}if(e.compiledArtifacts.instrumentationSourcePath!==void 0&&In(g,e.compiledArtifacts.instrumentationSourcePath),t&&H(r)){let t=e.workflowBuildDir,n=new Set([W(v(t,`workflows.mjs`))]);g.hooks.hook(`rollup:before`,(e,t)=>{let r=t.external;t.external=(e,...t)=>{if(n.has(W(e)))return!0;if(typeof r==`function`)return r(e,...t)}})}return a&&(hn(g),oe(g,{artifactsConfig:re({appRoot:e.appRoot,dev:g.options.dev}),dispatchModulePath:d(`src/internal/nitro/routes/schedule-task.ts`),registrations:e.scheduleRegistrations})),await pn(g,e,{surface:r}),U(r)&&await jn(g,En(g,e)),g}function Rn(){let e=process.env.VERCEL?.trim(),t=process.env.VERCEL_DEPLOYMENT_ID?.trim();return typeof e==`string`&&e.length>0&&typeof t==`string`&&t.length>0}async function zn(e){return Rn()?(await se(e),!0):!1}function Bn(e){return e.replace(/[\\/]+$/,``)}async function Vn(e){try{return JSON.parse(await C(v(e,`functions`,`__server.func`,`.vc-config.json`),`utf8`)).runtime}catch{return}}async function Hn(e){let t=new Kt({appRoot:e.appRoot,compiledArtifactsBootstrapPath:e.compiledArtifactsBootstrapPath,outDir:e.workflowBuildDir,rootDir:f(),watch:!1}),n=await Vn(e.outputDir);await t.buildVercelOutput({flowNitroOutputDir:e.flowNitroOutputDir,outputDir:e.outputDir,runtime:n})}async function Un(e){let t=Bn(e.options.output.dir);return await E(t),await Ce(e),await be(e),await we(e),await ye(e),await De(t),t}async function Wn(e,t){let n=await X(e,!1,{outputDir:r(e.appRoot,t),surface:t});try{return await Un(n)}finally{await n.close()}}async function Gn(e){let t=await ie(e);if(!process.env.VERCEL){let e=await X(t,!1);try{return await Un(e)}finally{await e.close()}}let n=await X(t,!1,{surface:`app`});try{let e=await Un(n);await zn({appRoot:t.appRoot,log(e){console.log(e)}});let r=await Wn(t,`flow`);return await Hn({appRoot:t.appRoot,compiledArtifactsBootstrapPath:t.compiledArtifacts.bootstrapPath,flowNitroOutputDir:r,outputDir:e,workflowBuildDir:t.workflowBuildDir}),e}finally{await n.close()}}const Z=65535,Q=`WORKFLOW_LOCAL_BASE_URL`,$=`PORT`,Kn=new Set([`[::]`,`::`,`0.0.0.0`]);function qn(e){let t=new URL(e);return Kn.has(t.hostname)?(t.hostname=`127.0.0.1`,t.toString()):e}function Jn(e){return e instanceof Error&&`code`in e&&e.code===`EADDRINUSE`}function Yn(e){let t=typeof e==`string`?Number(e):e??3e3;if(!Number.isInteger(t)||t<0||t>Z)throw Error(`Invalid development server port "${String(e)}". Expected an integer between 0 and ${Z}.`);return t}function Xn(){let e=process.env[$];if(e===void 0||e.trim()===``)return;let t=Number(e);if(!Number.isInteger(t)||t<0||t>Z)throw Error(`Invalid ${$} environment variable "${e}". Expected an integer between 0 and ${Z}.`);return t}function Zn(e){let t=Yn(e.port);if(t===0||!e.retryOnAddressInUse)return[t];let n=[];for(let e=0;e<10;e+=1){let r=t+e;if(r>65535)break;n.push(r)}return n}function Qn(e){let t=process.env[Q],n=process.env[$],r=new URL(qn(e));return process.env[Q]=r.origin,r.port&&(process.env[$]=r.port),()=>{t===void 0?delete process.env[Q]:process.env[Q]=t,n===void 0?delete process.env[$]:process.env[$]=n}}function $n(e){let t=()=>{};return e.once(`error`,t),()=>{e.off(`error`,t)}}function er(e){let t=e.upgrade.bind(e);e.upgrade=async(e,n,r)=>{let i=$n(n);try{await t(e,n,r)}catch{n.destroyed||n.destroy()}finally{i()}}}async function tr(e){let t=Zn({port:e.port,retryOnAddressInUse:e.retryOnAddressInUse}),n;for(let r of t){let t=e.devServer.listen({hostname:e.host,port:r,silent:!0});try{return await t.ready(),t}catch(r){if(n=r,await t.close().catch(()=>{}),!Jn(r)||!e.retryOnAddressInUse)throw r}}throw Error(`Failed to start Nitro dev server after ${t.length} attempts. Tried ports ${t.join(`, `)}.`,{cause:n})}async function nr(e,t={}){let n=t.schedules===!0,r=await ie(e);await se({appRoot:r.appRoot,log:e=>console.log(e)});let i=await X(r,!0,{schedules:n}),a=xe(i);er(a);let o=t.host??i.options.devServer.hostname,s=t.port??Xn(),c=s??i.options.devServer.port,l=s===void 0,u;try{let e=await tr({devServer:a,host:o,port:c,retryOnAddressInUse:l});if(!e.url)throw Error(`Nitro dev server did not expose a URL.`);u=Qn(e.url),await Ce(i),await ye(i);let{startAuthoredSourceWatcher:t}=await import(`./dev-authored-source-watcher-Dli96TWx.js`),s=await t({nitro:i,preparedHost:r,schedulesEnabled:n}),d=u;if(d===void 0)throw Error(`Workflow local queue environment was not initialized.`);return{async close(){try{await s.close(),await a.close(),await i.close()}finally{d()}},url:qn(e.url)}}catch(e){throw u?.(),await a.close().catch(()=>{}),await i.close().catch(()=>{}),e}}var rr=e({buildHost:()=>ir,startHost:()=>ar});async function ir(e){return await Gn(e)}async function ar(e,t={}){return await nr(e,t)}export{ar as n,rr as t};
|
|
22
|
+
`)}async function pn(e,n,r){if(cn(r.surface)){let t=f(),i=new Kt({appRoot:n.appRoot,compiledArtifactsBootstrapPath:n.compiledArtifacts.bootstrapPath,outDir:n.workflowBuildDir,rootDir:t,watch:e.options.dev}),a=Promise.resolve(),o=async()=>{await i.build({nitroStepOutfile:z(r.surface)?v(V(e),`steps.mjs`):void 0,nitroWorkflowOutfile:e.options.dev&&z(r.surface)?v(V(e),`workflows.mjs`):void 0})},s=async()=>{let e=a.then(o);a=e.catch(()=>{}),await e},c=!0;await s(),e.hooks.hook(`build:before`,async()=>{if(c){c=!1;return}await s()}),e.options.dev&&e.hooks.hook(`dev:reload`,async()=>{await s()})}let i=re({appRoot:n.appRoot,dev:e.options.dev});sn(r.surface)&&(B(e,{handlerPath:d(`src/internal/nitro/routes/index.ts`),method:`GET`,route:`/`}),B(e,{handlerPath:d(`src/internal/nitro/routes/health.ts`),method:`GET`,route:te}),fn(e,{args:JSON.stringify({appRoot:i.appRoot}),handlerExport:`handleAgentInfoRequest`,method:`GET`,modulePath:d(`src/internal/nitro/routes/info.ts`),route:ee}),B(e,{handlerPath:d(`src/internal/nitro/routes/workflow-runs.ts`),method:`GET`,route:`/api/runs`}),B(e,{handlerPath:d(`src/internal/nitro/routes/workflow-run.ts`),method:`GET`,route:`/api/runs/:runId`}),B(e,{handlerPath:d(`src/internal/nitro/routes/workflow-run-steps.ts`),method:`GET`,route:`/api/runs/:runId/steps`}),B(e,{handlerPath:d(`src/internal/nitro/routes/workflow-run-events.ts`),method:`GET`,route:`/api/runs/:runId/events`}),ae(e,{artifactsConfig:i,registrations:ne(n)}));let a=V(e),o=z(r.surface)?e.options.dev?v(a,`workflows.mjs`):v(n.workflowBuildDir,`workflows.mjs`):void 0,s=e.options.dev&&o!==void 0?[{bundlePath:o,queuePrefix:`__wkf_workflow_`}]:[],c=s.length>0?t(u(`workflow/runtime`)):void 0;o&&await un(e,{bundleName:`workflows`,bundlePath:o,directHandlers:s,route:`/.well-known/workflow/v1/flow`,runtimeImportSpecifier:c}),e.routing.sync()}function mn(){return`${g}/cron/${he()}`}function hn(e){e.options.vercel!==void 0&&(e.options.vercel.cronHandlerRoute=mn())}function gn(e){return{plugins:[l(),...e]}}function _n(e){e.hooks.hook(`rollup:before`,(e,t)=>{Array.isArray(t.plugins)&&t.plugins.unshift({name:`ash:nitro-routing-import-specifiers`,transform(e,t){if(t!==`#nitro/virtual/routing`&&t!==`#nitro/virtual/routing-meta`)return null;let n=a(e);return n===e?null:{code:n,map:null}}})})}const vn=`@alinea/generated.@appsignal/nodejs.@aws-sdk/client-s3.@aws-sdk/s3-presigned-post.@blockfrost/blockfrost-js.@highlight-run/node.@huggingface/transformers.@jpg-store/lucid-cardano.@libsql/client.@mikro-orm/core.@mikro-orm/knex.@node-rs/argon2.@node-rs/bcrypt.@prisma/client.@react-pdf/renderer.@sentry/profiling-node.@sparticuz/chromium.@sparticuz/chromium-min.@statsig/statsig-node-core.@swc/core.@xenova/transformers.@zenstackhq/runtime.argon2.autoprefixer.aws-crt.bcrypt.better-sqlite3.canvas.chromadb-default-embed.config.cpu-features.cypress.dd-trace.eslint.express.firebase-admin.htmlrewriter.import-in-the-middle.isolated-vm.jest.jsdom.keyv.libsql.mdx-bundler.mongodb.mongoose.newrelic.next-mdx-remote.next-seo.node-cron.node-pty.node-web-audio-api.onnxruntime-node.oslo.pg.pino.pino-pretty.pino-roll.playwright.playwright-core.postcss.prettier.prisma.puppeteer.puppeteer-core.ravendb.require-in-the-middle.rimraf.sharp.shiki.sqlite3.thread-stream.ts-morph.ts-node.typescript.vscode-oniguruma.webpack.websocket.zeromq`.split(`.`);function yn(e){if(e)return{config:{version:3,framework:{version:h().version}}}}const bn=[`workflow`,`workflow/api`,`workflow/errors`,`workflow/internal/builtins`,`workflow/internal/private`,`workflow/runtime`],xn=Symbol(`ash.workflow-transform-patched`),Sn=[`@napi-rs/keyring`];function Cn(){let e={};for(let t of bn)e[t]=u(t);return e}function wn(e){if(!e&&process.env.VERCEL)return`vercel`}function Tn(e){return e===`all`||e===`app`}function H(e){return e===`all`||e===`flow`}function U(e){return H(e)}function En(e,t){return e.options.dev?v(e.options.buildDir,`workflow`,`steps.mjs`):v(t.workflowBuildDir,`steps.mjs`)}function Dn(e){let t=e.compileResult.manifest.config.build;return[...new Set([...Sn,...vn,...t?.externalDependencies??[]])].filter(e=>e!==p)}function W(e){return e.replaceAll(`\\`,`/`)}function G(e){let t=e.indexOf(`?`),n=e.indexOf(`#`),r=t===-1?n:n===-1?t:Math.min(t,n);return r===-1?e:e.slice(0,r)}function K(e){return e.startsWith(`/@fs/`)?e.slice(4):e}function q(e,t){return t.startsWith(`file://`)?W(K(G(ve(t)))):ue(t)?W(K(G(t))):W(K(G(b(e,t))))}function On(e,t){let n=W(e);return n.startsWith(t)||n.includes(`/.ash/workflow-cache/`)}function J(e){let t=W(e);return process.platform===`win32`?t.toLowerCase():t}function kn(e){let t=/^\s*import\s+(?:.+?\s+from\s+)?["']([^"']+)["'];?\s*$/gm,n=[];for(let r of e.matchAll(t)){let e=r[1];e!==void 0&&n.push(e)}return n}function An(e,t,n){return t.startsWith(`workflow`)?u(t):t.startsWith(`.`)||t.startsWith(`/`)||t.startsWith(`file://`)?q(n===void 0?e:_(q(e,n)),t):null}async function Y(e,t){let n=await C(e,`utf8`),r=new Set;for(let i of kn(n)){let n=An(t,i,e);n!==null&&r.add(J(n))}return r}async function jn(e,t){if(e.options.noExternals===!0)return;let n;try{n=await Y(t,e.options.rootDir)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}let r=Array.isArray(e.options.noExternals)?[...e.options.noExternals]:[];e.options.noExternals=[...new Set([...r,...n])]}function Mn(e,t){let n=W(e).replace(/\/$/,``),r=W(t),i=n.toLowerCase(),a=r.toLowerCase();if(a.startsWith(`${i}/`))return r.slice(n.length+1);if(a===i)return`.`;let o=y(n,r).replaceAll(`\\`,`/`);if(o.startsWith(`../`)&&(o=o.split(`/`).filter(e=>e!==`..`).join(`/`)),o.includes(`:`)||o.startsWith(`/`)){let e=r.split(`/`).pop();return e===void 0||e.length===0?`unknown.ts`:e}return o}function Nn(e,t){let n=[t,v(e.options.buildDir,`workflow`)].map(t=>q(e.options.rootDir,t));e.hooks.hook(`rollup:before`,(t,r)=>{Array.isArray(r.plugins)&&r.plugins.unshift({name:`ash:workflow-module-side-effects`,resolveId(t,r){let i=An(e.options.rootDir,t,r)??q(e.options.rootDir,t);return n.some(e=>On(i,e))?{id:i,moduleSideEffects:`no-treeshake`}:null}})})}function Pn(e,t){let n=null,r=async()=>(n===null&&(n=await Y(t.stepEntrypointPath,e.options.rootDir)),n);e.hooks.hook(`build:before`,()=>{n=null}),e.options.dev&&e.hooks.hook(`dev:reload`,()=>{n=null}),e.hooks.hook(`rollup:before`,(t,n)=>{Array.isArray(n.plugins)&&n.plugins.unshift({name:`ash:workflow-step-module-side-effects`,async resolveId(t,n){let i=An(e.options.rootDir,t,n);return i===null||!(await r()).has(J(i))?null:{id:i,moduleSideEffects:`no-treeshake`}}})})}function Fn(e,t){let n=null,r=async()=>(n===null&&(n=await Y(t.stepEntrypointPath,e.options.rootDir)),n);e.hooks.hook(`build:before`,()=>{n=null}),e.options.dev&&e.hooks.hook(`dev:reload`,()=>{n=null}),e.hooks.hook(`rollup:before`,(t,n)=>{Array.isArray(n.plugins)&&n.plugins.unshift({async transform(t,n){let i=await r(),a=q(e.options.rootDir,n);return i.has(J(a))?{code:(await k(Mn(e.options.rootDir,a),t,`step`,a,e.options.rootDir)).code,map:null}:null},name:`ash:workflow-step-transform`})})}function In(e,t){let n=W(t);e.hooks.hook(`rollup:before`,(e,t)=>{Array.isArray(t.plugins)&&t.plugins.unshift({name:`ash:instrumentation-module-side-effects`,resolveId(e){return W(e)===n?{id:e,moduleSideEffects:`no-treeshake`}:null}})})}function Ln(e,t){let n=W(t);e.hooks.hook(`rollup:before`,(e,t)=>{if(Array.isArray(t.plugins))for(let e of t.plugins){if(typeof e!=`object`||!e)continue;let t=e;if(t.name!==`workflow:transform`||t[xn]===!0||typeof t.transform!=`function`)continue;let r=t.transform;t.transform=function(e,t,...i){return On(t,n)?null:r.call(this,e,t,...i)},t[xn]=!0}})}async function X(e,t,n={}){let r=n.surface??`all`,a=(!t||n.schedules===!0)&&Tn(r)&&e.scheduleRegistrations.length>0,o=wn(t),s=o===`vercel`?on():null,c=s===null?[]:[s],l=gn(c),u=gn(c),f=Dn(e),p=i(e.appRoot,r),h=e.compiledArtifacts.instrumentationPluginPath===void 0?[e.compiledArtifacts.bootstrapPath]:[e.compiledArtifacts.instrumentationPluginPath,e.compiledArtifacts.bootstrapPath];await E(p);let g=await Se({_cli:{command:t?`dev`:`build`},buildDir:p,dev:t,logLevel:t?1:void 0,output:n.outputDir===void 0?void 0:{dir:n.outputDir},preset:o,plugins:h,publicAssets:[],scanDirs:U(r)?[m(`src/execution`)]:void 0,rolldownConfig:l,rollupConfig:u,rootDir:e.appRoot,serverDir:!1,traceDeps:f,vercel:yn(o===`vercel`&&Tn(r))},t?{watch:!0}:void 0);if(await De(p),_n(g),H(r)){let t=Cn();for(let[e,n]of Object.entries(t))g.options.alias[e]=n;Nn(g,e.workflowBuildDir),Ln(g,e.workflowBuildDir)}if(U(r)){let t=En(g,e);Pn(g,{stepEntrypointPath:t}),Fn(g,{stepEntrypointPath:t})}if(e.compiledArtifacts.instrumentationSourcePath!==void 0&&In(g,e.compiledArtifacts.instrumentationSourcePath),t&&H(r)){let t=e.workflowBuildDir,n=new Set([W(v(t,`workflows.mjs`))]);g.hooks.hook(`rollup:before`,(e,t)=>{let r=t.external;t.external=(e,...t)=>{if(n.has(W(e)))return!0;if(typeof r==`function`)return r(e,...t)}})}return a&&(hn(g),oe(g,{artifactsConfig:re({appRoot:e.appRoot,dev:g.options.dev}),dispatchModulePath:d(`src/internal/nitro/routes/schedule-task.ts`),registrations:e.scheduleRegistrations})),await pn(g,e,{surface:r}),U(r)&&await jn(g,En(g,e)),g}function Rn(e){if(typeof e!=`string`||e.length===0)return`unknown`;let t=e.toLowerCase();return t===`slack`||t.includes(`slack`)?`slack`:t===`http`?`http`:t.includes(`webhook`)?`webhook`:`unknown`}function zn(e){let{manifest:t}=e;return{kind:`vercel-ash-agent-summary`,schemaVersion:1,generatorVersion:e.generatorVersion??h().version,agent:{name:t.config.name,description:t.config.description,modelId:t.config.model.id},instructions:t.instructions?Hn(t.instructions):null,schedules:t.schedules.map(Un),tools:t.tools.map(Wn),skills:t.skills.map(Gn),connections:t.connections.map(Kn),channels:t.channels.filter(Vn).map(qn),sandbox:t.sandbox===null?null:{logicalPath:t.sandbox.logicalPath},subagents:t.subagents.map(Jn),diagnostics:{errors:t.diagnosticsSummary.errors,warnings:t.diagnosticsSummary.warnings}}}async function Bn(e){let t=zn({generatorVersion:e.generatorVersion,manifest:e.manifest}),n=v(e.appRoot,`.ash/agent-summary.json`);return await S(_(n),{recursive:!0}),await T(n,`${JSON.stringify(t,null,2)}\n`),n}function Vn(e){return e.kind===`channel`}function Hn(e){return{logicalPath:e.logicalPath,sourceKind:e.sourceKind,markdown:e.markdown}}function Un(e){return{name:e.name,cron:e.cron,logicalPath:e.logicalPath}}function Wn(e){return{name:e.name,description:e.description,logicalPath:e.logicalPath}}function Gn(e){return{name:e.name,description:e.description,logicalPath:e.logicalPath,sourceKind:e.sourceKind}}function Kn(e){let t={name:e.connectionName,description:e.description,url:e.url,logicalPath:e.logicalPath};return e.vercelConnect===void 0?t:{...t,vercelConnect:{connector:e.vercelConnect.connector}}}function qn(e){let t={name:e.name,method:e.method,urlPath:e.urlPath,type:Rn(e.adapterKind),logicalPath:e.logicalPath};return e.adapterKind===void 0?t:{...t,adapterKind:e.adapterKind}}function Jn(e){return{name:e.name,description:e.description,logicalPath:e.logicalPath}}function Yn(){let e=process.env.VERCEL?.trim(),t=process.env.VERCEL_DEPLOYMENT_ID?.trim();return typeof e==`string`&&e.length>0&&typeof t==`string`&&t.length>0}async function Xn(e){return Yn()?(await se(e),!0):!1}function Zn(e){return e.replace(/[\\/]+$/,``)}async function Qn(e){try{return JSON.parse(await C(v(e,`functions`,`__server.func`,`.vc-config.json`),`utf8`)).runtime}catch{return}}async function $n(e){let t=new Kt({appRoot:e.appRoot,compiledArtifactsBootstrapPath:e.compiledArtifactsBootstrapPath,outDir:e.workflowBuildDir,rootDir:f(),watch:!1}),n=await Qn(e.outputDir);await t.buildVercelOutput({flowNitroOutputDir:e.flowNitroOutputDir,outputDir:e.outputDir,runtime:n})}async function er(e){let t=Zn(e.options.output.dir);return await E(t),await Ce(e),await be(e),await we(e),await ye(e),await De(t),t}async function tr(e,t){let n=await X(e,!1,{outputDir:r(e.appRoot,t),surface:t});try{return await er(n)}finally{await n.close()}}async function nr(e){let t=await ie(e);if(!process.env.VERCEL){let e=await X(t,!1);try{let n=await er(e);return await Bn({manifest:t.compileResult.manifest,appRoot:t.appRoot}),n}finally{await e.close()}}let n=await X(t,!1,{surface:`app`});try{let e=await er(n);await Xn({appRoot:t.appRoot,log(e){console.log(e)}});let r=await tr(t,`flow`);return await $n({appRoot:t.appRoot,compiledArtifactsBootstrapPath:t.compiledArtifacts.bootstrapPath,flowNitroOutputDir:r,outputDir:e,workflowBuildDir:t.workflowBuildDir}),await Bn({manifest:t.compileResult.manifest,appRoot:t.appRoot}),e}finally{await n.close()}}const Z=65535,Q=`WORKFLOW_LOCAL_BASE_URL`,$=`PORT`,rr=new Set([`[::]`,`::`,`0.0.0.0`]);function ir(e){let t=new URL(e);return rr.has(t.hostname)?(t.hostname=`127.0.0.1`,t.toString()):e}function ar(e){return e instanceof Error&&`code`in e&&e.code===`EADDRINUSE`}function or(e){let t=typeof e==`string`?Number(e):e??3e3;if(!Number.isInteger(t)||t<0||t>Z)throw Error(`Invalid development server port "${String(e)}". Expected an integer between 0 and ${Z}.`);return t}function sr(){let e=process.env[$];if(e===void 0||e.trim()===``)return;let t=Number(e);if(!Number.isInteger(t)||t<0||t>Z)throw Error(`Invalid ${$} environment variable "${e}". Expected an integer between 0 and ${Z}.`);return t}function cr(e){let t=or(e.port);if(t===0||!e.retryOnAddressInUse)return[t];let n=[];for(let e=0;e<10;e+=1){let r=t+e;if(r>65535)break;n.push(r)}return n}function lr(e){let t=process.env[Q],n=process.env[$],r=new URL(ir(e));return process.env[Q]=r.origin,r.port&&(process.env[$]=r.port),()=>{t===void 0?delete process.env[Q]:process.env[Q]=t,n===void 0?delete process.env[$]:process.env[$]=n}}function ur(e){let t=()=>{};return e.once(`error`,t),()=>{e.off(`error`,t)}}function dr(e){let t=e.upgrade.bind(e);e.upgrade=async(e,n,r)=>{let i=ur(n);try{await t(e,n,r)}catch{n.destroyed||n.destroy()}finally{i()}}}async function fr(e){let t=cr({port:e.port,retryOnAddressInUse:e.retryOnAddressInUse}),n;for(let r of t){let t=e.devServer.listen({hostname:e.host,port:r,silent:!0});try{return await t.ready(),t}catch(r){if(n=r,await t.close().catch(()=>{}),!ar(r)||!e.retryOnAddressInUse)throw r}}throw Error(`Failed to start Nitro dev server after ${t.length} attempts. Tried ports ${t.join(`, `)}.`,{cause:n})}async function pr(e,t={}){let n=t.schedules===!0,r=await ie(e);await se({appRoot:r.appRoot,log:e=>console.log(e)});let i=await X(r,!0,{schedules:n}),a=xe(i);dr(a);let o=t.host??i.options.devServer.hostname,s=t.port??sr(),c=s??i.options.devServer.port,l=s===void 0,u;try{let e=await fr({devServer:a,host:o,port:c,retryOnAddressInUse:l});if(!e.url)throw Error(`Nitro dev server did not expose a URL.`);u=lr(e.url),await Ce(i),await ye(i);let{startAuthoredSourceWatcher:t}=await import(`./dev-authored-source-watcher-DA6pewzf.js`),s=await t({nitro:i,preparedHost:r,schedulesEnabled:n}),d=u;if(d===void 0)throw Error(`Workflow local queue environment was not initialized.`);return{async close(){try{await s.close(),await a.close(),await i.close()}finally{d()}},url:ir(e.url)}}catch(e){throw u?.(),await a.close().catch(()=>{}),await i.close().catch(()=>{}),e}}var mr=e({buildHost:()=>hr,startHost:()=>gr});async function hr(e){return await nr(e)}async function gr(e,t={}){return await pr(e,t)}export{gr as n,mr as t};
|
|
@@ -0,0 +1,88 @@
|
|
|
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,m as o,n as s,p as c,s as l,t as u,u as d}from"./authored-module-loader-Pt_g8xX2.js";import{n as f,t as p}from"./guards-CjJ3lmju.js";import{t as m}from"./errors-DsO9xmQL.js";import{n as h,o as g,r as _,t as v}from"./package-DmsQgn4v.js";import{a as y,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 b}from"#compiled/zod/index.js";import{basename as ue,dirname as x,join as S,posix as de,relative as fe,resolve as C,sep as pe}from"node:path";import{access as me,cp as he,mkdir as w,readFile as ge,readdir as _e,rm as ve,stat as ye,writeFile as T}from"node:fs/promises";import{createHash as be}from"node:crypto";import{pathToFileURL as xe}from"node:url";import{resumeHook as Se}from"#compiled/@workflow/core/runtime.js";import{AsyncLocalStorage as Ce}from"node:async_hooks";import{SpanStatusCode as we,trace as Te}from"#compiled/@opentelemetry/api/index.js";import{getErrorMessage as Ee}from"#compiled/@ai-sdk/provider/index.js";import{inspect as De}from"node:util";import{fromError as Oe}from"#compiled/zod-validation-error/index.js";import{createRemoteJWKSet as ke,decodeJwt as Ae,jwtVerify as je}from"#compiled/jose/index.js";import Me from"#compiled/turndown/index.js";const Ne=b.union([b.literal(`error`),b.literal(`warning`)]);b.object({code:b.string(),message:b.string(),severity:Ne,sourcePath:b.string()}).strict();const Pe=b.object({errors:b.number().finite(),warnings:b.number().finite()}).strict();function Fe(e){return e}function E(e){return Fe({...e,severity:`error`})}function Ie(e){return Fe({...e,severity:`warning`})}function Le(e){return e.reduce((e,t)=>(t.severity===`error`?e.errors+=1:e.warnings+=1,e),{errors:0,warnings:0})}function Re(e){return e.some(e=>e.severity===`error`)}const ze=[`.cts`,`.mts`,`.cjs`,`.mjs`,`.ts`,`.js`],Be=[`package.json`,`vercel.json`],Ve=[`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`],He=[`channels`,`connections`,`hooks`,`lib`,`sandbox`,`skills`,`tools`,`schedules`,`subagents`],Ue=[`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`],We=[`hooks`,`lib`,`sandbox`,`skills`,`tools`,`subagents`],Ge=[`SKILL.md`],Ke=[`scripts`,`references`,`assets`],qe=new Set(Be);new Set(Ve),new Set(He),new Set(Ue),new Set(We),new Set(Ge),new Set(Ke);function D(e){return e.isDirectory()?`directory`:e.isFile()?`file`:`other`}function Je(e,t){return t===`file`&&qe.has(e)}function Ye(e,t){if(t===`file`)return A(e,`agent`)?`agent-config-module`:e===`instructions.md`?`instructions-markdown`:A(e,`instructions`)?`instructions-module`:e===`system.md`?`system-markdown`:A(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 Xe(e,t){if(t===`file`)return A(e,`agent`)?`agent-config-module`:e===`instructions.md`?`instructions-markdown`:A(e,`instructions`)?`instructions-module`:e===`system.md`?`system-markdown`:A(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 Ze(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 Qe(e,t){if(t===`directory`)return`skill-package-directory`;if(t===`file`){if(e.endsWith(`.md`))return`flat-skill-markdown`;if(k(e)!==null)return`flat-skill-module`}return`unknown`}function O(e){return e.replaceAll(pe,`/`).replace(/^\.\//,``).replace(/^\/+/,``)}function k(e){for(let t of ze)if(e.endsWith(t)&&e.length>t.length)return e.slice(0,-t.length);return null}function A(e,t){return k(e)===t}function j(e){let t=O(e),n=t.lastIndexOf(`/`),r=t.lastIndexOf(`.`);return r===-1||r<n?t:t.slice(0,r)}var $e=e(t(),1);function et(e,t){let i=n(e,t);if(a(i,[`build`,`compaction`,`description`,`metadata`,`model`,`modelContextWindowTokens`,`modelOptions`],t),i.model===void 0)throw Error(`${t} The "model" field is required.`);let o={model:i.model};i.description!==void 0&&(o.description=r(i.description,t));let s=c(i,`metadata`,t);return s!==void 0&&(o.metadata=s),i.compaction!==void 0&&(o.compaction=it(i.compaction,t)),i.build!==void 0&&(o.build=nt(i.build,t)),i.modelOptions!==void 0&&(o.modelOptions=rt(i.modelOptions,t)),i.modelContextWindowTokens!==void 0&&(o.modelContextWindowTokens=tt(i.modelContextWindowTokens,t)),o}function tt(e,t){if(typeof e!=`number`||!Number.isInteger(e)||e<=0)throw Error(t);return e}function nt(e,t){let i=n(e,t);a(i,[`externalDependencies`],t);let o={};if(i.externalDependencies!==void 0){if(!Array.isArray(i.externalDependencies))throw Error(t);o.externalDependencies=Object.freeze(i.externalDependencies.map(e=>r(e,t)))}return o}function rt(e,t){let r=n(e,t);a(r,[`providerOptions`],t);let i=r.providerOptions;return i===void 0?{}:{providerOptions:d(i,t)}}function it(e,t){let r=n(e,t);a(r,[`model`,`modelContextWindowTokens`,`thresholdPercent`],t);let i={};if(r.model!==void 0&&(i.model=r.model),r.modelContextWindowTokens!==void 0&&(i.modelContextWindowTokens=tt(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 at(e,t){let i=n(e,t);return a(i,[`markdown`],t),{markdown:r(i.markdown,t)}}function ot(e,t){let i=n(e,t);a(i,[`description`,`license`,`markdown`,`metadata`],t);let o={description:r(i.description,t),markdown:r(i.markdown,t)},s=i.license,l=c(i,`metadata`,t);return s!==void 0&&(o.license=r(s,t)),l!==void 0&&(o.metadata=l),o}function st(e,t){let i=n(e,t);a(i,[`channel`,`cron`,`markdown`],t);let o={cron:r(i.cron,t),markdown:r(i.markdown,t)};return i.channel!==void 0&&i.channel!==null&&(o.channel=i.channel),o}function ct(e){return e}function lt(e){return e}function ut(e){return e}const dt=/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/;function ft(e){if(!$e.default.test(e))return{hasFrontmatter:!1,frontmatter:{},markdown:e};let t;try{t=(0,$e.default)(e)}catch(t){throw gt(e)&&!_t(e)?Error(`Markdown frontmatter is missing a closing delimiter.`):t}if(!f(t.data))throw Error(`Markdown frontmatter must parse to an object.`);return{hasFrontmatter:!0,frontmatter:t.data,markdown:vt(t.content)}}function pt(e){return ut(at({markdown:e},`Expected authored instructions markdown to match the public Ash shape.`))}function mt(e){let t=ft(e);if(!t.hasFrontmatter)throw Error(`Schedule markdown must start with YAML frontmatter declaring "cron".`);if(`channel`in t.frontmatter)throw Error('Markdown-form schedules do not support the "channel" frontmatter key. Use a TypeScript schedule (`<name>.ts`) to deliver to a channel.');return ct(st({...t.frontmatter,markdown:t.markdown},`Expected authored schedule markdown to match the public Ash shape.`))}function ht(e,t={}){let n=ft(e),r=t.slug;if(r===void 0&&!n.hasFrontmatter)throw Error(`Skill markdown must start with YAML frontmatter.`);let i=xt(n.frontmatter),a=St(i.description,`description`),o=r===void 0?Ct(i.description,`description`):a??t.description??Tt(n.markdown,r),s={...i,description:o,markdown:n.markdown};return yt(s,i),lt(ot(s,`Expected authored skill markdown to match the public Ash shape.`))}function gt(e){return e.startsWith(`---
|
|
2
|
+
`)||e.startsWith(`---\r
|
|
3
|
+
`)}function _t(e){return dt.test(e)}function vt(e){return e.replace(/^\r?\n/u,``)}function yt(e,t){let n=St(t.license,`license`);n!==void 0&&(e.license=n);let r=wt(t.metadata,`metadata`);r!==void 0&&(e.metadata=r)}const bt=[`name`];function xt(e){let t={...e};for(let e of bt)delete t[e];return t}function St(e,t){if(e!=null){if(typeof e!=`string`)throw Error(`Expected "${t}" frontmatter to be a string.`);return e}}function Ct(e,t){let n=St(e,t);if(n===void 0)throw Error(`Missing required "${t}" frontmatter.`);return n}function wt(e,t){if(e==null)return;if(!f(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 Tt(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 Et(e){let t=C(e.appRoot),n=C(e.agentRoot),r={agentId:e.agentId??Dt(t,n,e.packageName),agentRoot:n,appRoot:t,channels:[...e.channels??[]],connections:[...e.connections??[]],diagnosticsSummary:Le(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 Dt(e,t,n){let r=O(fe(e,t));return r===``||r===`.`||r===`agent`?n??ue(e):ue(t)}function M(e){return O(e)}function N(e){let t=O(e.logicalPath),n={sourceKind:`module`,logicalPath:t,sourceId:e.sourceId??M(t)};return e.exportName!==void 0&&(n.exportName=e.exportName),n}function Ot(e){return{...N(e),connectionName:e.connectionName}}function kt(e){let t=O(e.logicalPath);return{entryPath:e.entryPath,logicalPath:t,manifest:e.manifest,rootPath:e.rootPath,sourceId:e.sourceId??M(t),subagentId:e.subagentId}}function At(e){let t={description:e.description,sourceKind:`skill-package`,logicalPath:O(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 jt(e){let t=O(e.logicalPath);return{definition:e.lower(await e.source.readTextFile(e.sourcePath),{name:j(t)}),sourceKind:`markdown`,logicalPath:t,sourceId:M(t)}}function Mt(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&&k(r.name)===t.moduleBaseName&&n.moduleFileNames.push(r.name)}return n.moduleFileNames.sort((e,t)=>e.localeCompare(t)),n}function Nt(e,t){let n=new Map;for(let r of e){if(!r.isFile())continue;let e=t.allowMarkdown?Pt(r.name):null,i=t.allowModules?k(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 Pt(e){return!e.endsWith(`.md`)||e.length<=3?null:e.slice(0,-3)}async function P(e){let t=S(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:[E({code:e.invalidDirectoryCode,message:e.invalidDirectoryMessage,sourcePath:t})],sources:[]};let r=[],i=[];return await Ft({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 Ft(e){let t=e.subdirectoryRelative===``?e.rootDirectoryPath:S(e.rootDirectoryPath,e.subdirectoryRelative),n=await F(e.projectSource,t);e.recursive&&await It(e,n,t),(e.unsupportedFileCode!==void 0||e.unsupportedEntryCode!==void 0)&&Lt(e,n,t),await Rt(e,n,t)}async function It(e,t,n){for(let r of t){if(!r.isDirectory())continue;let t=S(n,r.name);if(e.validateSegment!==void 0){let n=e.validateSegment(r.name,t);if(n!==null){e.diagnostics.push(n);continue}}await Ft({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:S(e.subdirectoryRelative,r.name),unsupportedEntryCode:e.unsupportedEntryCode,unsupportedEntryMessage:e.unsupportedEntryMessage,unsupportedFileCode:e.unsupportedFileCode,unsupportedFileMessage:e.unsupportedFileMessage,validateSegment:e.validateSegment})}}function Lt(e,t,n){for(let r of t){let t=D(r),i=S(n,r.name);if(t===`directory`)continue;if(t===`other`){e.unsupportedEntryCode!==void 0&&e.diagnostics.push(E({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=k(r.name)!==null,o=e.allowMarkdown&&r.name.endsWith(`.md`);a||o||e.diagnostics.push(E({code:e.unsupportedFileCode,message:e.unsupportedFileMessage?.(i,e.relativeDirectory)??`Expected "${i}" to be a supported authored source within "${e.relativeDirectory}/".`,sourcePath:i}))}}async function Rt(e,t,n){for(let r of Nt(t,{allowMarkdown:e.allowMarkdown,allowModules:!0})){let t=e.subdirectoryRelative===``?r.slotName:S(e.subdirectoryRelative,r.slotName),i=O(S(e.relativeDirectory,t));if(e.validateSegment!==void 0){let t=r.markdownFileName??r.moduleFileNames[0]??r.slotName,i=e.validateSegment(r.slotName,S(n,t));if(i!==null){e.diagnostics.push(i);continue}}if(r.markdownFileName!==void 0&&r.moduleFileNames.length>0){e.diagnostics.push($t(n,i,[r.markdownFileName,...r.moduleFileNames]));continue}if(r.moduleFileNames.length>1){e.diagnostics.push(en(n,i,r.moduleFileNames));continue}if(r.markdownFileName!==void 0){let t=e.subdirectoryRelative===``?r.markdownFileName:S(e.subdirectoryRelative,r.markdownFileName),n=O(S(e.relativeDirectory,t));if(e.markdownLowerer===void 0)continue;let i=await jt({logicalPath:n,lower:e.markdownLowerer,source:e.projectSource,sourcePath:S(e.rootDirectoryPath,t)});e.sources.push(i);continue}let[a]=r.moduleFileNames;if(a===void 0)continue;let o=e.subdirectoryRelative===``?a:S(e.subdirectoryRelative,a);e.sources.push(N({logicalPath:O(S(e.relativeDirectory,o))}))}}const zt=`discover/module-slot-collision`,Bt=`discover/tools-directory-invalid`,Vt=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,Ht=/^[a-z][a-z0-9-]{0,63}$/,Ut=/^(\.?[a-z][a-z0-9-]{0,63}|\[[a-zA-Z][a-zA-Z0-9_]{0,63}\])$/,Wt=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/;async function F(e,t){let n=[...await e.readDirectory(t)];return n.sort((e,t)=>e.name.localeCompare(t.name)),n}async function Gt(e){let t=await Kt({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 Kt({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:[Ie({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:S(e.rootPath,t)}),...n.diagnostics],instructions:n.source}}return n.diagnostics.length>0?{diagnostics:n.diagnostics}:{diagnostics:[E({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 Kt(e){let t=Mt(e.rootEntries,{markdownFileName:e.markdownFileName,moduleBaseName:e.moduleBaseName});if(t.markdownFileName!==void 0&&t.moduleFileNames.length>0)return{diagnostics:[$t(e.rootPath,e.slotLabel,[t.markdownFileName,...t.moduleFileNames])]};if(t.moduleFileNames.length>1)return{diagnostics:[en(e.rootPath,e.slotLabel,t.moduleFileNames)]};if(t.markdownFileName!==void 0)return{diagnostics:[],source:await jt({logicalPath:e.markdownFileName,lower:pt,source:e.source,sourcePath:S(e.rootPath,t.markdownFileName)})};let[n]=t.moduleFileNames;return n===void 0?{diagnostics:[]}:{diagnostics:[],source:N({logicalPath:n})}}function qt(e){let t=Mt(e.rootEntries,{moduleBaseName:e.slotName});if(t.moduleFileNames.length>1)return{diagnostics:[en(e.rootPath,e.slotName,t.moduleFileNames)]};let[n]=t.moduleFileNames;return n===void 0?e.missingDiagnostic===void 0?{diagnostics:[]}:{diagnostics:[E({code:e.missingDiagnostic.code,message:e.missingDiagnostic.message,sourcePath:e.rootPath})]}:{diagnostics:[],module:N({logicalPath:n})}}function Jt(e,t){return Vt.test(e)?null:E({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 Yt(e,t){return Ht.test(e)?null:E({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 Xt(e,t){return Ut.test(e)?null:E({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 Zt(e,t){return Wt.test(e)?null:E({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 Qt(e){return e.rootEntries.flatMap(t=>!t.isDirectory()||e.classifyEntry(t.name,D(t))!==`unknown`?[]:[Ie({code:`discover/unsupported-directory`,message:e.createUnsupportedDirectoryMessage(t.name),sourcePath:S(e.rootPath,t.name)})])}function $t(e,t,n){return E({code:`discover/slot-collision`,message:`Found conflicting authored sources for "${t}": ${tn(n)}.`,sourcePath:e})}function en(e,t,n){return E({code:zt,message:`Found multiple authored module sources for "${t}": ${tn(n)}.`,sourcePath:e})}function tn(e){return e.map(e=>`"${e}"`).join(`, `)}async function nn(e){let t=`connections`,n=S(e.rootPath,t),r=e.rootEntries.find(e=>e.name===t);if(r===void 0)return{connections:[],diagnostics:[]};if(!r.isDirectory())return{connections:[],diagnostics:[E({code:`discover/connections-directory-invalid`,message:`Expected "${n}" to be a directory of authored connections.`,sourcePath:n})]};let i=await F(e.source,n),a=[],o=[],s=new Set;for(let e of Nt(i,{allowMarkdown:!1,allowModules:!0})){let r=O(S(t,e.slotName));if(e.moduleFileNames.length>1){s.add(e.slotName),o.push(en(n,r,e.moduleFileNames));continue}let[i]=e.moduleFileNames;if(i===void 0)continue;s.add(e.slotName);let c=Yt(e.slotName,S(n,i));if(c!==null){o.push(c);continue}a.push(Ot({connectionName:e.slotName,logicalPath:S(t,i)}))}for(let r of i){if(!r.isDirectory())continue;let i=r.name,c=S(n,i);if(s.has(i)){o.push(E({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=Yt(i,c);if(l!==null){o.push(l);continue}let u=rn(await F(e.source,c));if(u.length>1){o.push(E({code:zt,message:`Found multiple connection definition modules inside "${O(S(t,i))}": `+u.map(e=>`"${e}"`).join(`, `),sourcePath:c}));continue}let[d]=u;if(d===void 0){o.push(E({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(Ot({connectionName:i,logicalPath:S(t,i,d)}))}return{connections:a,diagnostics:o}}function rn(e){let t=e.filter(e=>e.isFile()),n=[];for(let e of Nt(t,{allowMarkdown:!1,allowModules:!0}))e.slotName===`connection`&&n.push(...e.moduleFileNames);return n}const an=`discover/lib-entry-unsupported`;async function on(e){let t=await P({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:an,unsupportedEntryMessage:e=>`Expected "${e}" to be a supported authored module within "lib/".`,unsupportedFileCode:an,unsupportedFileMessage:e=>`Expected "${e}" to be a supported authored module within "lib/".`});return{diagnostics:t.diagnostics,lib:t.sources}}function I(){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 sn=`sandbox`,cn=`workspace`,ln=`sandbox`;async function un(e){let t=[],n=e.rootEntries.find(e=>e.name===sn);if(n===void 0)return dn({diagnostics:t,rootEntries:e.rootEntries,rootPath:e.rootPath});let r=S(e.rootPath,sn);if(!n.isDirectory())return t.push(E({code:`discover/sandbox-directory-invalid`,message:`Expected "${r}" to be the sandbox folder.`,sourcePath:r})),{diagnostics:t,sandbox:null,sandboxWorkspace:null};let i=await F(e.source,r),a=fn(i),o=i.find(e=>e.name===cn&&e.isDirectory());if(a.length>1)return t.push(E({code:zt,message:`Found multiple sandbox definition modules inside "${O(sn)}": `+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(E({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=N({logicalPath:S(sn,s)}));let d=null;if(l){let n=S(r,cn),i=O(S(sn,cn)),a=await mn(e.source,n);a===null?d={logicalPath:i,rootEntries:await pn(e.source,n),sourceId:M(i),sourcePath:n}:t.push(a)}return{diagnostics:t,sandbox:u,sandboxWorkspace:d}}function dn(e){let t=Mt(e.rootEntries,{moduleBaseName:ln});if(t.moduleFileNames.length>1)return e.diagnostics.push(E({code:zt,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:N({logicalPath:n}),sandboxWorkspace:null}}function fn(e){let t=e.filter(e=>e.isFile()),n=[];for(let e of Nt(t,{allowMarkdown:!1,allowModules:!0}))e.slotName===ln&&n.push(...e.moduleFileNames);return n}async function pn(e,t){let n=await F(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 mn(e,t){return(await F(e,t)).find(e=>e.name===`skills`)===void 0?null:E({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:S(t,`skills`)})}const hn=`discover/skill-frontmatter-invalid`;async function gn(e){let t=e.source??I(),n=C(e.agentRoot),r=C(e.skillsDirectoryPath??S(n,`skills`)),i=O(e.skillsLogicalPath??fe(n,r)),a=await t.stat(r);if(a===`missing`)return{diagnostics:[],skills:[]};if(a!==`directory`)return{diagnostics:[E({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 F(t,r);for(let e of l){let n=await _n({entryName:e.name,entryType:D(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(E({code:`discover/skill-collision`,message:`Found conflicting authored skill sources for "${n.skillId}": "${a.logicalPath}" and "${n.logicalPath}".`,sourcePath:S(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 _n(e){let t=S(e.skillsDirectoryPath,e.entryName);switch(Qe(e.entryName,e.entryType)){case`skill-package-directory`:return vn({logicalSkillsPath:e.skillsLogicalPath,skillId:e.entryName,skillRootPath:t,source:e.source});case`flat-skill-markdown`:return yn({logicalSkillsPath:e.skillsLogicalPath,skillFileName:e.entryName,skillFilePath:t,source:e.source});case`flat-skill-module`:return bn({logicalSkillsPath:e.skillsLogicalPath,skillFileName:e.entryName});default:return{diagnostics:[E({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:O(S(e.skillsLogicalPath,e.entryName)),skill:null,skillId:null}}}async function vn(e){let t=S(e.skillRootPath,`SKILL.md`),n=O(S(e.logicalSkillsPath,e.skillId,`SKILL.md`));if(await e.source.stat(t)!==`file`)return{diagnostics:[E({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=ht(await e.source.readTextFile(t))}catch(e){return{diagnostics:[E({code:hn,message:Sn(t,e),sourcePath:t})],logicalPath:n,skill:null,skillId:null}}let i=await xn(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:M(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:At(a),skillId:e.skillId}}async function yn(e){let t=Cn(e.skillFileName),n=O(S(e.logicalSkillsPath,e.skillFileName)),r;try{r=ht(await e.source.readTextFile(e.skillFilePath),{slug:t})}catch(t){return{diagnostics:[E({code:hn,message:Sn(e.skillFilePath,t),sourcePath:e.skillFilePath})],logicalPath:n,skill:null,skillId:null}}return{diagnostics:[],logicalPath:n,skill:{definition:r,sourceKind:`markdown`,logicalPath:n,sourceId:M(n)},skillId:t}}async function bn(e){let t=k(e.skillFileName),n=O(S(e.logicalSkillsPath,e.skillFileName));return t===null?{diagnostics:[],logicalPath:n,skill:null,skillId:null}:{diagnostics:[],logicalPath:n,skill:N({logicalPath:n}),skillId:t}}async function xn(e,t){let n=await e.readDirectory(t),r={};for(let e of n)if(e.isDirectory())switch(Ze(e.name,D(e))){case`skill-assets-directory`:r.assetsPath=S(t,e.name);break;case`skill-references-directory`:r.referencesPath=S(t,e.name);break;case`skill-scripts-directory`:r.scriptsPath=S(t,e.name);break;default:break}return r}function Sn(e,t){return`Invalid authored skill frontmatter in "${e}": ${m(t)}`}function Cn(e){return e.endsWith(`.md`)?e.slice(0,-3):e}async function wn(e){let t=e.source??I(),n=C(e.agentRoot),r=C(e.subagentsDirectoryPath??S(n,`subagents`)),i=O(e.subagentsLogicalPath??fe(n,r)),a=await t.stat(r);if(a===`missing`)return{diagnostics:[],subagents:[]};if(a!==`directory`)return{diagnostics:[E({code:`discover/subagents-directory-invalid`,message:`Expected "${r}" to be a directory of authored subagents.`,sourcePath:r})],subagents:[]};let o=await F(t,r),s=[],c=[];for(let n of o){if(!n.isDirectory())continue;let a=await Tn({appRoot:e.appRoot,source:t,subagentId:n.name,subagentLogicalPath:S(i,n.name),subagentRoot:S(r,n.name)});s.push(...a.diagnostics),c.push(a.subagent)}return{diagnostics:s,subagents:c}}async function Tn(e){let t=[],n=await F(e.source,e.subagentRoot);t.push(...Qt({classifyEntry:Xe,createUnsupportedDirectoryMessage(e){return`Ignoring unsupported directory "${e}/" in the local subagent root.`},rootEntries:n,rootPath:e.subagentRoot}));let r=await Gt({rootEntries:n,rootPath:e.subagentRoot,source:e.source});t.push(...r.diagnostics);let i=qt({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 nn({rootEntries:n,rootPath:e.subagentRoot,source:e.source});t.push(...a.diagnostics);let o=await un({rootEntries:n,rootPath:e.subagentRoot,source:e.source});t.push(...o.diagnostics);let s=await P({directoryName:`tools`,invalidDirectoryCode:Bt,invalidDirectoryMessage:`Expected "${S(e.subagentRoot,`tools`)}" to be a directory of authored tools.`,recursive:!0,rootEntries:n,rootPath:e.subagentRoot,source:e.source,validateSegment:Jt});t.push(...s.diagnostics);let c=await P({directoryName:`hooks`,invalidDirectoryCode:On,invalidDirectoryMessage:`Expected "${S(e.subagentRoot,`hooks`)}" to be a directory of authored hooks.`,recursive:!0,rootEntries:n,rootPath:e.subagentRoot,source:e.source,validateSegment:Zt});t.push(...c.diagnostics);let l=await on({agentRoot:e.subagentRoot,rootEntries:n,source:e.source});t.push(...l.diagnostics),t.push(...En(e.subagentRoot,n));let u=await gn({agentRoot:e.subagentRoot,source:e.source});t.push(...u.diagnostics);let d=await wn({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=Et(f);return{diagnostics:t,subagent:kt({entryPath:e.subagentRoot,logicalPath:e.subagentLogicalPath,manifest:p,rootPath:e.subagentRoot,subagentId:e.subagentId})}}function En(e,t){return t.flatMap(t=>Xe(t.name,D(t))===`invalid-schedules-directory`?[E({code:`discover/local-subagent-schedules-invalid`,message:`Local subagent packages cannot define schedules at "${S(e,t.name)}".`,sourcePath:S(e,t.name)})]:[])}async function Dn(e){let t=await P({allowMarkdown:!0,directoryName:`schedules`,invalidDirectoryCode:`discover/schedules-directory-invalid`,invalidDirectoryMessage:`Expected "${S(e.agentRoot,`schedules`)}" to be a directory of authored schedules.`,markdownLowerer:e=>mt(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 On=`discover/hooks-directory-invalid`;async function kn(e){let t=e.source??I(),n=C(e.appRoot),r=C(e.agentRoot),i=[],a=await An(t,n),o=await F(t,r);i.push(...Qt({classifyEntry:Ye,createUnsupportedDirectoryMessage(e){return`Ignoring unsupported directory "${e}/" in the agent root.`},rootEntries:o,rootPath:r}));let s=await Gt({rootEntries:o,rootPath:r,source:t});i.push(...s.diagnostics);let c=qt({rootEntries:o,rootPath:r,slotName:`agent`});i.push(...c.diagnostics);let l=await P({directoryName:`channels`,invalidDirectoryCode:`discover/channels-directory-invalid`,invalidDirectoryMessage:`Expected "${S(r,`channels`)}" to be a directory of authored channels.`,recursive:!0,rootEntries:o,rootPath:r,source:t,validateSegment:Xt});i.push(...l.diagnostics);let u=await on({agentRoot:r,rootEntries:o,source:t});i.push(...u.diagnostics);let d=await Dn({agentRoot:r,rootEntries:o,source:t});i.push(...d.diagnostics);let f=await nn({rootEntries:o,rootPath:r,source:t});i.push(...f.diagnostics);let p=await un({rootEntries:o,rootPath:r,source:t});i.push(...p.diagnostics);let m=await P({directoryName:`tools`,invalidDirectoryCode:Bt,invalidDirectoryMessage:`Expected "${S(r,`tools`)}" to be a directory of authored tools.`,recursive:!0,rootEntries:o,rootPath:r,source:t,validateSegment:Jt});i.push(...m.diagnostics);let h=await P({directoryName:`hooks`,invalidDirectoryCode:On,invalidDirectoryMessage:`Expected "${S(r,`hooks`)}" to be a directory of authored hooks.`,recursive:!0,rootEntries:o,rootPath:r,source:t,validateSegment:Zt});i.push(...h.diagnostics);let g=await gn({agentRoot:r,source:t});i.push(...g.diagnostics);let _=await wn({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:Et(v)}}async function An(e,t){try{let n=S(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 jn=class extends Error{diagnostic;constructor(e){super(e.message),this.name=`DiscoveryProjectResolutionError`,this.diagnostic=e}};async function Mn(e=process.cwd(),t={}){let n=t.source??I(),r=await Nn(n,e),i=r;for(;;){let e=await Pn(n,i);if(e!==null)return e;let t=await Fn(n,i);if(t!==null)return t;if(await In(n,i))return{agentRoot:i,appRoot:i,layout:`flat`};let r=x(i);if(r===i)break;i=r}throw new jn(E({code:`discover/project-not-found`,message:`Could not resolve an Ash agent root from "${r}".`,sourcePath:r}))}async function Nn(e,t){let n=C(t);return await e.stat(n)===`directory`?n:x(n)}async function Pn(e,t){if(ue(t)!==`agent`)return null;let n=x(t);return await Ln(e,n)?{agentRoot:t,appRoot:n,layout:`nested`}:null}async function Fn(e,t){if(!await Ln(e,t))return null;let n=S(t,`agent`);return await zn(e,n)?{agentRoot:n,appRoot:t,layout:`nested`}:null}async function In(e,t){let n=await Rn(e,t);return Array.from(n.entries()).some(([e,t])=>{let n=Ye(e,t);return n!==`unknown`&&n!==`lib-directory`})}async function Ln(e,t){let n=await Rn(e,t);return Array.from(n.entries()).some(([e,t])=>Je(e,t))}async function Rn(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,D(e)]))}async function zn(e,t){return await e.stat(t)===`directory`}const Bn=`ash-agent-compiled-manifest`,L=`__root__`,Vn=b.object({exportName:b.string().optional(),sourceKind:b.literal(`module`),logicalPath:b.string(),sourceId:b.string()}).strict(),Hn=b.union([b.literal(`GET`),b.literal(`POST`),b.literal(`PUT`),b.literal(`DELETE`),b.literal(`PATCH`)]),Un=b.object({kind:b.literal(`channel`),name:b.string(),logicalPath:b.string(),method:Hn,urlPath:b.string(),sourceId:b.string(),sourceKind:b.literal(`module`),exportName:b.string().optional(),adapterKind:b.string().optional()}).strict(),Wn=b.object({kind:b.literal(`disabled`),name:b.string(),logicalPath:b.string()}).strict(),Gn=b.union([Un,Wn]),Kn=b.object({contextWindowTokens:b.number().int().positive().optional(),id:b.string(),source:Vn.optional(),providerOptions:ce.optional()}).strict(),qn=b.object({externalDependencies:b.array(b.string()).optional()}).strict(),Jn=b.object({model:Kn.optional(),thresholdPercent:b.number().finite().min(0).max(1).optional()}).strict(),Yn=b.object({build:qn.optional(),compaction:Jn.optional(),description:b.string().optional(),metadata:b.record(b.string(),b.string()),model:Kn,name:b.string(),source:Vn.optional()}).strict(),Xn=b.object({name:b.string(),logicalPath:b.string(),markdown:b.string(),sourceId:b.string(),sourceKind:b.union([b.literal(`markdown`),b.literal(`module`)])}).strict(),Zn={name:b.string(),description:b.string(),license:b.string().optional(),markdown:b.string(),metadata:b.record(b.string(),b.string()).optional(),sourceId:b.string(),logicalPath:b.string()},Qn=b.discriminatedUnion(`sourceKind`,[b.object({...Zn,sourceKind:b.literal(`markdown`)}).strict(),b.object({...Zn,sourceKind:b.literal(`module`),exportName:b.string().optional()}).strict(),b.object({...Zn,sourceKind:b.literal(`skill-package`),skillId:b.string(),skillFilePath:b.string(),rootPath:b.string(),assetsPath:b.string().optional(),referencesPath:b.string().optional(),scriptsPath:b.string().optional()}).strict()]),$n=b.object({name:b.string(),args:b.record(b.string(),b.unknown())}).strict(),er=b.object({channel:$n.optional(),cron:b.string(),name:b.string(),logicalPath:b.string(),markdown:b.string(),sourceId:b.string(),sourceKind:b.union([b.literal(`markdown`),b.literal(`module`)])}).strict(),tr=b.object({description:b.string().optional(),exportName:b.string().optional(),logicalPath:b.string(),sourceId:b.string(),sourceKind:b.literal(`module`)}).strict(),nr=b.object({logicalPath:b.string(),rootEntries:b.array(b.string()).readonly(),sourceId:b.string(),sourcePath:b.string()}).strict(),rr=b.object({logicalPath:b.string(),rootEntries:b.array(b.string()).readonly()}).strict(),ir=b.object({connectionName:b.string(),description:b.string(),exportName:b.string().optional(),logicalPath:b.string(),sourceId:b.string(),sourceKind:b.literal(`module`),url:b.string(),vercelConnect:b.object({connector:b.string()}).strict().optional()}).strict(),ar=b.object({description:b.string(),exportName:b.string().optional(),inputSchema:ce.nullable(),logicalPath:b.string(),name:b.string(),sourceId:b.string(),sourceKind:b.literal(`module`)}).strict(),or=b.object({exportName:b.string().optional(),logicalPath:b.string(),slug:b.string(),sourceId:b.string(),sourceKind:b.literal(`module`)}).strict(),sr=b.object({agentRoot:b.string(),appRoot:b.string(),channels:b.array(Gn),config:Yn,connections:b.array(ir),diagnosticsSummary:Pe,disabledFrameworkTools:b.array(b.string()).readonly(),hooks:b.array(or),sandbox:tr.nullable(),sandboxWorkspaces:b.array(nr),schedules:b.array(er),skills:b.array(Qn).readonly(),instructions:Xn.optional(),tools:b.array(ar),workspaceResourceRoot:rr}).strict(),cr=b.object({agent:sr,description:b.string(),entryPath:b.string(),logicalPath:b.string(),name:b.string(),nodeId:b.string(),rootPath:b.string(),sourceId:b.string(),sourceKind:b.literal(`module`),exportName:b.string().optional()}).strict(),lr=b.object({childNodeId:b.string(),parentNodeId:b.string()}).strict(),ur=b.object({agentRoot:b.string(),appRoot:b.string(),channels:b.array(Gn),config:Yn,connections:b.array(ir),diagnosticsSummary:Pe,disabledFrameworkTools:b.array(b.string()).readonly(),hooks:b.array(or),kind:b.literal(Bn),sandbox:tr.nullable(),sandboxWorkspaces:b.array(nr),schedules:b.array(er),skills:b.array(Qn).readonly(),subagentEdges:b.array(lr),subagents:b.array(cr),instructions:Xn.optional(),tools:b.array(ar),version:b.literal(22),workspaceResourceRoot:rr}).strict();function dr(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:hr(e.config.compaction.model),thresholdPercent:e.config.compaction?.thresholdPercent},description:e.config.description,metadata:{...e.config.metadata},model:hr(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:fr({sandboxWorkspaces:e.sandboxWorkspaces,skills:e.skills})}};return e.instructions!==void 0&&(t.instructions=e.instructions),t}function fr(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 pr(e,t){return e===`__root__`?t:`${e}::${t}`}function mr(e){return{...dr(e),kind:Bn,subagentEdges:[...e.subagentEdges??[]],subagents:[...e.subagents??[]],version:22}}function hr(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 gr=/^\/?[A-Za-z]:[\\/]/,_r=/^\\\\[^\\]/,vr=/(\b(?:from|import)\s*(?:\(\s*)?)(["'])([A-Za-z]:[\\/][^"'\n\r]*)\2/g;function yr(e){return gr.test(e)||_r.test(e)}function br(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 xr(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 Sr(e){if(e.startsWith(`file://`))return e;let{path:t,suffix:n}=xr(e);return yr(t)?`${br(t)}${n}`:e.replaceAll(`\\`,`/`)}function Cr(e){return JSON.stringify(Sr(e))}function wr(e){return e.replace(vr,(e,t,n,r)=>`${t}${n}${Sr(r)}${n}`)}const Tr=b.object({modules:b.record(b.string(),b.object({}).passthrough())}).strict(),Er=b.object({nodes:b.record(b.string(),Tr)}).strict();function Dr(e){let t=Nr(e.moduleMapPath),n=e.importSpecifierStyle??`relative`,r=0,i=[Or({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=>Or({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 = ${jr(i)};`,``,`export default moduleMap;`,``].join(`
|
|
4
|
+
`)}function Or(e){return{modules:kr(e.manifest).sort((e,t)=>e.sourceId.localeCompare(t.sourceId)).map(t=>({bindingName:e.nextBindingName(),importSpecifier:Ar({fromDirectory:e.moduleMapDirectory,importSpecifierStyle:e.importSpecifierStyle,targetPath:Pr(e.agentRoot,t.logicalPath)}),sourceId:t.sourceId})),nodeId:e.nodeId}}function kr(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});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 Ar(e){if(e.importSpecifierStyle===`absolute`)return Sr(Ir(e.targetPath));let t=Fr(e.fromDirectory,e.targetPath);return t.startsWith(`.`)?t:`./${t}`}function jr(e){return Mr([{key:`nodes`,value:Mr(e.map(e=>({key:e.nodeId,value:Mr([{key:`modules`,value:Mr(e.modules.map(e=>({key:e.sourceId,value:e.bindingName})))}],3)})))}],0)}function Mr(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 Nr(e){let t=R(e);return t.segments.length===0?t.root.length===0?`.`:t.root:Lr(t.root,t.segments.slice(0,-1))}function Pr(e,t){let n=R(e),r=R(t);return r.root.length>0?Lr(r.root,r.segments):Lr(n.root,[...n.segments,...r.segments])}function Fr(e,t){let n=R(e),r=R(t);if(n.root!==r.root)return Ir(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 Ir(e){let t=R(e);return Lr(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 Lr(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 Rr=`ash-model-catalog-cache`,zr=b.object({provider:b.string().min(1),providerModelId:b.string().min(1),contextWindowTokens:b.number().int().nonnegative().optional(),maxOutputTokens:b.number().int().nonnegative().optional()}).passthrough(),Br=b.object({slug:b.string().min(1),providers:b.array(zr).min(1)}).passthrough(),Vr=b.object({models:b.array(Br),providerAliases:b.record(b.string(),b.string())}).passthrough();b.object({contextWindowTokens:b.number().int().positive(),maxOutputTokens:b.number().int().positive().optional()}).strict();const Hr=b.object({fetchedAt:b.string(),kind:b.literal(Rr),models:b.array(Br),providerAliases:b.record(b.string(),b.string()),version:b.literal(2)}).strict(),Ur=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 Wr(e){return S(e,`.ash`,`cache`,`model-catalog.json`)}function Gr(e){let t=null,n=null,r=null,i=async()=>(t??=qr(e),await t),a=async()=>{if(n!==null)throw n;if(r!==null)return await r;r=Kr(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&&Xr(e))return e;try{return await a()}catch{return e===null?null:e}};return{async getModelLimits(e){let t=Zr(e),n=await o();if(n!==null){let e=Jr(n.models,t);if(e)for(let t of e.providers){let e=Yr(t);if(e!==null)return e}}return Ur.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=Zr(t);for(let e of n.models)for(let t of e.providers)if(t.provider===i&&Zr(t.providerModelId)===a){let n=Yr(t);if(n!==null)return{slug:e.slug,limits:n}}return null}}}async function Kr(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=Vr.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:Rr,models:n.data.models,providerAliases:n.data.providerAliases,version:2};try{let t=Wr(e);await w(S(e,`.ash`,`cache`),{recursive:!0}),await T(t,`${JSON.stringify(r,null,2)}\n`,`utf8`)}catch{}return r}async function qr(e){try{let t=await ge(Wr(e),`utf8`),n=Hr.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 Jr(e,t){return e.find(e=>e.slug===t)}function Yr(e){return e.contextWindowTokens===void 0||e.contextWindowTokens<=0?null:{contextWindowTokens:e.contextWindowTokens,...e.maxOutputTokens!==void 0&&e.maxOutputTokens>0&&{maxOutputTokens:e.maxOutputTokens}}}function Xr(e){let t=Date.parse(e.fetchedAt);return Number.isFinite(t)?Date.now()-t<=864e5:!1}function Zr(e){return e.endsWith(`-thinking`)?e.slice(0,-9):e}async function z(e){let t=i(await u(S(e.agentRoot,e.source.logicalPath)),e.source);try{return await o(t)}catch(t){throw Error(`Failed to execute the ${e.kind} export "${e.source.exportName??`default`}" from "${e.source.logicalPath}": ${m(t)}`)}}var Qr=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 $r(e,t){if(e.configModule===void 0)throw new Qr(e.agentId);let n=et(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 ei({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 ei({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 ei(e){if(typeof e.value==`string`)return await ti({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 ti(i,e)}async function ti(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}". ${m(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 ni(e){return typeof e==`object`&&!!e&&e.__kind===`ash:channel`}function ri(e,t){if(!ni(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 ii(e){return typeof e==`object`&&!!e&&e.kind===`ash:disabled-channel`}async function ai(e,t){let n=await z({agentRoot:e,kind:`channel`,source:t}),r=j(t.logicalPath).replace(/^channels\//,``);if(ii(n))return{kind:`disabled`,name:r,logicalPath:t.logicalPath};let i=ri(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:oi(i.adapter)}))}function oi(e){if(typeof e!=`object`||!e)return;let t=e.kind;return typeof t==`string`&&t.length>0?t:void 0}async function si(e,t){let n=new Map;for(let r of t){let t=await z({agentRoot:e,kind:`channel`,source:r});if(ii(t))continue;let i=j(r.logicalPath).replace(/^channels\//,``);typeof t==`object`&&t&&(n.set(t,i),s(C(S(e,r.logicalPath)),t))}return n}function ci(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 li(e,t,n=`auth`){let r=ci(e,n);if(r!==void 0)throw Error(`${t} ${r}`);let i=e,a=ui(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 ui(e){if(typeof e!=`object`||!e)return;let t=e.connector;if(!(typeof t!=`string`||t.length===0))return{connector:t}}const di=[`approval`,`auth`,`description`,`headers`,`tools`,`url`],fi=[`completeAuthorization`,`getToken`,`principalType`,`startAuthorization`,`vercelConnect`];function pi(e,t){let r=n(e,t);a(r,di,t),mi(r,t),hi(r,t);let i=gi(r,t),o=_i(r,t),s=vi(r,t);if(i!==void 0&&o!==void 0&&typeof o!=`function`&&Object.keys(o).some(e=>e.toLowerCase()===`authorization`))throw Error(`${t} "headers" must not include an "Authorization" key when "auth" is also provided.`);let c={description:r.description,url:r.url};if(i!==void 0&&(c.auth=i),o!==void 0&&(c.headers=o),s!==void 0&&(c.tools=s),r.approval!==void 0){if(typeof r.approval!=`function`)throw Error(`${t} The "approval" field must be a function when provided.`);c.approval=r.approval}return c}function mi(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 hi(e,t){if(typeof e.description!=`string`||e.description.length===0)throw Error(`${t} The "description" field must be a non-empty string.`)}function gi(e,t){if(e.auth===void 0)return;let r=n(e.auth,`${t} The "auth" field must be an object with a "getToken" method.`);return a(r,fi,`${t} The "auth" field`),li(r,t)}function _i(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 vi(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?(yi(n.allow,`${t} The "tools.allow"`),{allow:n.allow}):(yi(n.block,`${t} The "tools.block"`),{block:n.block})}function yi(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 bi(e,t){let n=pi(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=xi(n.auth);return i!==void 0&&(r.vercelConnect=i),r}function xi(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 Si(e){return{exportName:e.exportName,logicalPath:e.logicalPath,slug:j(e.logicalPath).replace(/^hooks\//,``),sourceId:e.sourceId,sourceKind:`module`}}function Ci(e,t){let r=n(e,t);a(r,[`backend`,`bootstrap`,`description`,`onSession`],t);let i={};if(r.backend!==void 0&&(i.backend=wi(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=l(r.bootstrap,t)),r.onSession!==void 0&&(i.onSession=l(r.onSession,t)),i}function wi(e,t){let r=n(e,`${t} The "backend" field must be a SandboxBackend value (use vercelBackend(), localBackend(), or your own factory).`);if(typeof r.name!=`string`||r.name.length===0)throw Error(`${t} The "backend" value must expose a non-empty string "name" identifier.`);if(typeof r.create!=`function`)throw Error(`${t} The "backend" value must expose a "create" function.`);if(r.prewarm!==void 0&&typeof r.prewarm!=`function`)throw Error(`${t} The "backend.prewarm" property must be a function when set.`);return r}async function Ti(e,t){return{description:Ci(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 Ei(e,t){let n=t.sourceKind===`markdown`?at(t.definition,`Expected the compiled instructions definition at "${t.logicalPath}" to match the public Ash shape.`):at(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:j(t.logicalPath),logicalPath:t.logicalPath,markdown:n.markdown,sourceId:t.sourceId,sourceKind:t.sourceKind}}async function Di(e,t,n){let r=t.sourceKind===`markdown`?st(t.definition,`Expected the compiled schedule definition at "${t.logicalPath}" to match the public Ash shape.`):st(await z({agentRoot:e,kind:`schedule`,source:t}),`Expected the schedule export "${t.exportName??`default`}" from "${t.logicalPath}" to match the public Ash shape.`),i={cron:r.cron,logicalPath:t.logicalPath,markdown:r.markdown.trim(),name:ki(t.logicalPath),sourceId:t.sourceId,sourceKind:t.sourceKind};return r.channel!==void 0&&(i.channel=Oi({channel:r.channel,channelIdentityMap:n,logicalPath:t.logicalPath})),i}function Oi(e){let t=e.channel,n=t.__route??t,r=t.args??{},i=e.channelIdentityMap.get(n);if(!i&&typeof t.name==`string`&&(i=t.name),!i)throw Error(`Schedule at "${e.logicalPath}" references a channel that was not discovered in agent/channels/. Import a channel module or pass { name: "<channel-name>", args: { ... } } as the channel field.`);return{name:i,args:r}}function ki(e){return j(e).replace(/^schedules\//,``)}async function Ai(e,t){if(t.sourceKind===`skill-package`)return ji(t);let n=t.sourceKind===`markdown`?ot(t.definition,`Expected the compiled skill definition at "${t.logicalPath}" to match the public Ash shape.`):ot(await z({agentRoot:e,kind:`skill`,source:t}),`Expected the skill export "${t.exportName??`default`}" from "${t.logicalPath}" to match the public Ash shape.`);return{description:n.description,license:n.license,logicalPath:t.logicalPath,markdown:n.markdown,metadata:n.metadata===void 0?void 0:{...n.metadata},name:j(t.logicalPath).replace(/^skills\//,``),sourceId:t.sourceId,sourceKind:t.sourceKind}}function ji(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 Mi(e){let t=[],n=[];for(let r of e.subagents){let i=await Ni({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 Ni(e){let t=pr(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 Mi({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`}}}function Pi(e){return typeof e==`object`&&!!e&&e.kind===`ash:disabled-tool`}function Fi(e){return e&&typeof e==`object`&&`~standard`in e?e[`~standard`].jsonSchema.input({target:`draft-07`}):JSON.parse(JSON.stringify(e))}function Ii(e,t){if(Pi(e))return{kind:`disabled`};let i=n(e,t);a(i,[`description`,`execute`,`inputSchema`,`needsApproval`,`onCompact`],t);let o=i.inputSchema===void 0?null:Fi(i.inputSchema),s={description:r(i.description,t),execute:l(i.execute,t),inputSchema:o};return i.onCompact!==void 0&&l(i.onCompact,t),i.needsApproval!==void 0&&l(i.needsApproval,t),{kind:`tool`,definition:s}}async function Li(e,t){let n=Ii(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=j(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 Ri(e){let t={modelCatalog:Gr(e.appRoot)},[n,r]=await Promise.all([zi(e,t),Mi({appRoot:e.appRoot,compileAgentNodeManifest:zi,context:t,parentNodeId:L,subagents:e.subagents})]);return mr({...n,subagentEdges:r.edges,subagents:r.nodes})}async function zi(e,t){let n=await Promise.all(e.tools.map(t=>Li(e.agentRoot,t))),r=[],i=[];for(let e of n)e.kind===`tool`?r.push(e.definition):i.push(e.name);let[a,o]=await Promise.all([Promise.all(e.channels.map(t=>ai(e.agentRoot,t))),si(e.agentRoot,e.channels)]),s=a.flat();return dr({agentRoot:e.agentRoot,appRoot:e.appRoot,channels:s,config:await $r(e,t),connections:await Promise.all(e.connections.map(t=>bi(e.agentRoot,t))),diagnosticsSummary:e.diagnosticsSummary,disabledFrameworkTools:i,hooks:e.hooks.map(e=>Si(e)),sandbox:e.sandbox===null?null:await Ti(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=>Di(e.agentRoot,t,o))),skills:await Promise.all(e.skills.map(t=>Ai(e.agentRoot,t))),instructions:e.instructions===void 0?void 0:await Ei(e.agentRoot,e.instructions),tools:r})}const Bi=`workspace-resources`;async function Vi(e){let t=S(e.compileDirectoryPath,Bi);await ve(t,{force:!0,recursive:!0});let n=await Ui({nodeId:L,resourcesRoot:t,manifest:e.manifest}),r=await Promise.all(e.manifest.subagents.map(async e=>({...e,agent:await Ui({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 Hi(e,t){return{logicalPath:O(S(Bi,t)),rootEntries:fr({sandboxWorkspaces:e.sandboxWorkspaces,skills:e.skills})}}async function Ui(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=S(e.resourcesRoot,e.nodeId);await w(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 Wi({nodeRoot:t,skill:n});return{...e.manifest,workspaceResourceRoot:Hi(e.manifest,e.nodeId)}}async function Wi(e){let t=S(e.nodeRoot,`skills`,e.skill.name);if(e.skill.sourceKind===`skill-package`){await he(e.skill.rootPath,t,{recursive:!0});return}let n=S(t,`SKILL.md`);await w(x(n),{recursive:!0}),await T(n,e.skill.markdown)}function Gi(e){let t=C(e),n=S(t,`.ash`,`discovery`),r=S(t,`.ash`,`compile`);return{appRoot:t,compiledManifestPath:S(r,`compiled-agent-manifest.json`),compileDirectoryPath:r,compileMetadataPath:S(r,`compile-metadata.json`),diagnosticsPath:S(n,`diagnostics.json`),discoveryManifestPath:S(n,`agent-discovery-manifest.json`),discoveryDirectoryPath:n,moduleMapPath:S(r,`module-map.mjs`)}}function Ki(e){return{diagnostics:[...e],kind:`ash-discovery-diagnostics`,summary:Le(e),version:1}}function qi(e){let t=v(),n=Yi(e.discoveryManifestJson),r=Yi(e.diagnosticsArtifactJson),i=Yi(e.moduleMapSource);return{compile:{moduleMap:{path:Zi(e.appRoot,e.paths.moduleMapPath),sha256:i}},discovery:{diagnostics:{path:Zi(e.appRoot,e.paths.diagnosticsPath),sha256:r},manifest:{path:Zi(e.appRoot,e.paths.discoveryManifestPath),sha256:n},sourceGraphHash:Yi(`${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 Ji(e){let t=Gi(e.appRoot),n=Ki(e.diagnostics),r=await Vi({compileDirectoryPath:t.compileDirectoryPath,manifest:await Ri(e.manifest)}),i=Xi(r),a=Xi(e.manifest),o=Xi(n),s=Dr({manifest:r,moduleMapPath:t.moduleMapPath}),c=qi({appRoot:e.appRoot,diagnosticsArtifactJson:o,diagnosticsSummary:n.summary,discoveryManifestJson:a,moduleMapSource:s,paths:t}),l=Xi(c);return await w(t.discoveryDirectoryPath,{recursive:!0}),await w(t.compileDirectoryPath,{recursive:!0}),await Promise.all([T(t.compiledManifestPath,i),T(t.diagnosticsPath,o),T(t.discoveryManifestPath,a),T(t.moduleMapPath,s),T(t.compileMetadataPath,l)]),{compiledManifest:r,diagnosticsArtifact:n,metadata:c,moduleMapSource:s,paths:t}}function Yi(e){return be(`sha256`).update(e).digest(`hex`)}function Xi(e){return`${JSON.stringify(e,null,2)}\n`}function Zi(e,t){return O(fe(C(e),t))}var Qi=class extends Error{result;constructor(e){super(ta({diagnostics:e.diagnostics,diagnosticsPath:e.paths.diagnosticsPath})),this.name=`CompileAgentError`,this.result=e}};async function $i(e={}){let t=e.source??I(),n=await Mn(e.startPath,{source:t}),r=await kn({...n,source:t}),i=await Ji({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(Re(r.diagnostics))throw new Qi(a);return ea(r.diagnostics),a}function ea(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 ta(e){let t=Le(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(`- ${na(t.severity)}: ${t.message}`),n.push(` source: ${t.sourcePath}`);return n.join(`
|
|
9
|
+
`)}function na(e){return e===`error`?`Error`:`Warning`}const ra=new Map;var B=class{name;codec;constructor(e,t={}){this.name=e,this.codec=t.codec,ra.set(e,this)}};const ia=Symbol.for(`experimental-ash.context-storage`),aa=globalThis;aa[ia]===void 0&&(aa[ia]=new Ce);const oa=aa[ia];function V(){let e=oa.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 sa(e){return{debug(t,n){pa(`debug`,e,t,n)},info(t,n){pa(`info`,e,t,n)},warn(t,n){pa(`warn`,e,t,n)},error(t,n){pa(`error`,e,t,n),ha(t,n)}}}function ca(){return crypto.randomUUID()}function la(e,t){let n={errorId:t??ca(),message:da(e)},r=ua(e);return r!==void 0&&(n.name=r),n.detail=ga(e),n}function ua(e){if(e instanceof Error)return e.name===`Error`?void 0:e.name;if(f(e)&&p(e.name)&&e.name!==`Error`)return e.name}function da(e){return f(e)&&!(e instanceof Error)&&typeof e.message==`string`?e.message:Ee(e)}function fa(e,t){let n=t instanceof Error?t.message:Ee(t),r=t instanceof Error?t.name:`Error`;e.setStatus({code:we.ERROR,message:n}),e.recordException({message:n,name:r,stack:ga(t)})}function pa(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,ma(r))}function ma(e){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0){if(r instanceof Error){t[n]=la(r);continue}t[n]=r}return t}function ha(e,t){let n=Te.getActiveSpan();if(n===void 0)return;let r=t?.error;if(r instanceof Error){fa(n,r);return}n.addEvent(e,t?ma(t):void 0)}function ga(e){return _a(De(e,{breakLength:1/0,compact:!1,depth:10,maxStringLength:8192}),16384)}function _a(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 va(e){if(e.message!==void 0)return{inputResponses:e.inputResponses,message:e.message};if(e.inputResponses!==void 0&&e.inputResponses.length>0)return{inputResponses:e.inputResponses}}function ya(e){return e.kind??`unknown`}const ba={kind:`http`},xa={kind:`schedule`};new B(`ash.auth`),new B(`ash.initiatorAuth`);const Sa=new B(`ash.sessionId`),Ca=new B(`ash.continuationToken`);new B(`ash.mode`),new B(`ash.parentSession`),new B(`ash.capabilities`),new B(`ash.sessionPrepared`);const wa=sa(`execution.subagent-adapter`),Ta=new Map;function Ea(e){return Ta.get(e)}function Da(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 Oa={kind:`subagent`,async"input.requested"(e,t){let n=t.state;Da(n)&&await ka({hookPayload:{callId:n.callId,childContinuationToken:t.ctx.require(Ca),childSessionId:t.ctx.require(Sa),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 ka(e){"use step";let t=Ea(e.hookPayload.childContinuationToken);try{if(t!==void 0){t(e.hookPayload);return}await Se(e.parentContinuationToken,e.hookPayload)}catch(t){let n=ca();throw wa.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)}},Aa=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??`${ja(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 ja(e){return e.length===0?e:e.charAt(0).toUpperCase()+e.slice(1)}const Ma=[ba,Oa,xa],Na=new Set([`kind`,`state`,`deliver`,`contextProviders`,`createAdapterContext`,`fetchFile`]);function Pa(e){let t=new Map,n=new Set;for(let e of Ma){let r=Ia(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=Ia(i,e);if(n.has(a)){if(La(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 Fa(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 Ia(e,t){let n=ya(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 La(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(!Na.has(t)&&typeof n==`function`)return!0;return!1}function Ra(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 za(e){return e.kind===`disk`?e.appRoot:void 0}function Ba(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=Va(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 Va(e){let t=e.replaceAll(`\\`,`/`);return t===`/`?t:t.replace(/\/+$/,``)}function Ha(e){return Oe(e,{prefix:void 0}).message}function Ua(e=`test-session`){return{bundleCache:new Map,bundleCacheKeyBySourceKey:new Map,compiledArtifacts:null,id:e}}const Wa=Symbol.for(`experimental-ash.runtime-session-storage`),Ga=Symbol.for(`experimental-ash.runtime-session-default`),W=globalThis;W[Wa]===void 0&&(W[Wa]=new Ce);const Ka=W[Wa];function qa(){return W[Ga]===void 0&&(W[Ga]=Ua(`process-default`)),W[Ga]}function Ja(){return Ka.getStore()??qa()}function Ya(){return Ja().compiledArtifacts}const Xa=b.object({path:b.string(),sha256:b.string()}).strict(),Za=b.object({compile:b.object({moduleMap:Xa}).strict(),discovery:b.object({diagnostics:Xa,manifest:Xa,sourceGraphHash:b.string(),summary:b.object({errors:b.number().finite(),warnings:b.number().finite()}).strict()}).strict(),generator:b.object({name:b.string(),version:b.string()}).strict(),kind:b.literal(`ash-compile-metadata`),status:b.union([b.literal(`failed`),b.literal(`ready`)]),version:b.literal(5)}).strict();var Qa=class extends Error{metadataPath;constructor(e,t){super(e),this.name=`LoadCompileMetadataError`,t!==void 0&&(this.metadataPath=t)}};async function $a(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 Qa(to(e),t)}return eo(n,t)}let n=Ya()?.metadata;return n===void 0?null:eo(n,`bundled compile metadata`)}function eo(e,t){let n=Za.safeParse(e);if(!n.success)throw new Qa(`Expected "${t}" to contain valid Ash compile metadata. ${Ha(n.error)}`,t);return n.data}function to(e){return e instanceof Error?e.message:`Unknown compile metadata load failure.`}async function no(e){let t=Ba(e),n=await ro(e);try{let r=(await $a({compiledArtifactsSource:e}))?.discovery.sourceGraphHash;return r===void 0||r.length===0?n===void 0?t:`${t}:mtime-${io(n)}`:n===void 0?`${t}:${r}`:`${t}:${r}:mtime-${io(n)}`}catch{return n===void 0?t:`${t}:mtime-${io(n)}`}}async function ro(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 io(e){return Math.floor(e).toString(36)}const ao=`__root__`;function oo(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 so=`bundled compiled manifest`;var co=class extends Error{manifestPath;constructor(e,t){super(e),this.name=`LoadCompiledManifestError`,t!==void 0&&(this.manifestPath=t)}};async function lo(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 co(fo(e),t)}return uo(n,t)}let n=Ya();if(n!==null)return uo(n.manifest,so);throw new co(`Compiled manifest is unavailable without an app root or bundled compiled artifacts.`,so)}function uo(e,t){let n=ur.safeParse(e);if(!n.success)throw new co(`Expected "${t}" to contain a valid compiled Ash agent manifest. ${Ha(n.error)}`,t);return n.data}function fo(e){return e instanceof Error?e.message:`Unknown manifest load failure.`}const po=`bundled compiled module map`;var mo=class extends Error{moduleMapPath;constructor(e,t){super(e),this.name=`LoadCompiledModuleMapError`,t!==void 0&&(this.moduleMapPath=t)}};async function ho(e){let t=e.moduleMapPath??(e.compiledArtifactsSource.kind===`disk`?U(e.compiledArtifactsSource.appRoot).moduleMapPath:void 0);if(t!==void 0){let e=vo(t);try{let n=await import(e);return go(n.moduleMap??n.default,t)}catch(e){throw new mo(_o(e),t)}}let n=Ya();if(n!==null)return go(n.moduleMap,po);throw new mo(`Compiled module map is unavailable without an app root or bundled compiled artifacts.`,po)}function go(e,t){let n=Er.safeParse(e);if(!n.success)throw new mo(`Expected "${t}" to export a valid compiled Ash module map. ${Ha(n.error)}`,t);return n.data}function _o(e){return e instanceof Error?e.message:`Unknown module-map load failure.`}function vo(e){let t=e.replaceAll(`\\`,`/`);return/^[A-Za-z]:\//.test(t)?`file:///${encodeURI(t)}`:t.startsWith(`/`)?`file://${encodeURI(t)}`:t}const G=`/workspace`;function yo(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=>bo(e))].join(`
|
|
10
|
+
`)}function bo(e){return`- ${e.name}: ${e.description} (path: ${G}/skills/${e.name}/SKILL.md)`}function xo(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 So(e){return e instanceof Error&&e.name===`ConnectionAuthorizationRequiredError`}function Co(e){return e instanceof Error&&e.name===`ConnectionAuthorizationFailedError`}function wo(e){return e?.startAuthorization!==void 0}const To=Object.freeze({__ashPlaceholder:`connection-authorization`}),Eo=new B(`ash.pendingConnectionToolCalls`);function Do(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 Oo(e,t){return`${e}__${t}`}const ko=sa(`framework.connection-search`),Ao=new B(`ash.connectionRegistry`),jo=new B(`ash.pendingConnectionAuthorizations`),Mo=new B(`ash.discoveredConnectionTools`),No={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 Po(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(Mo,{byConnection:{}}),e.set(jo,[]),e.set(Eo,[]),{}},sourceId:`ash:connection-search-tool`,sourceKind:`module`};async function Po(e,t){let n=V(),r=n.get(Ao);if(r===void 0)return[];let i=e.limit??10,a=Fo(e.keywords),o=[],s=[],c=e.connection!==void 0&&e.connection!==``?r.getConnections().filter(t=>t.connectionName===e.connection):r.getConnections(),l={...n.get(Mo)?.byConnection},u=[];for(let e of c){let t;try{t=await r.getClient(e.connectionName).getToolMetadata()}catch(t){if(So(t)){u.push({connectionName:e.connectionName,description:e.description}),s.push({connection:e.connectionName,description:e.description,needsAuthorization:!0});continue}if(Co(t)){ko.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`;ko.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=Io(a,n);t>0&&o.push({item:{connection:e.connectionName,description:n.description,inputSchema:n.inputSchema,qualifiedName:Oo(e.connectionName,n.name),tool:n.name},score:t})}}n.set(Mo,{byConnection:l});let d=[];if(u.length>0){for(let e of u)Ro(n,e);d=u.map(e=>e.connectionName).filter(e=>Lo(r,e))}if(d.length>0&&t?.toolCallId!==void 0){let r=n.get(Eo);return n.set(Eo,Do(r,[{args:e,connectionNames:d,kind:`connection-discover`,toolCallId:t.toolCallId,toolName:`connection_search`}])),To}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 Fo(e){return e.toLowerCase().split(/[\s_\-./]+/).filter(e=>e.length>1)}function Io(e,t){let n=Fo(t.name),r=Fo(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 Lo(e,t){return e===void 0?!1:wo(e.getConnections().find(e=>e.connectionName===t)?.authorization)}function Ro(e,t){let n=e.get(jo)??[];n.some(e=>e.connectionName===t.connectionName)||e.set(jo,[...n,t])}const zo=No.name;function Bo(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 ${zo} 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 Vo(e){return[...Ho(e.instructions),...Uo(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.`]:[],...Wo(e.connections),...Go(e.skills)]}function Ho(e){if(e===void 0)return[];let t=e.markdown.trim();return t.length===0?[]:[`Instructions (${e.name})\n${t}`]}function Uo(e){if(e===void 0)return[];let t=xo(e);return t===void 0?[]:[t]}function Wo(e){return!e||e.length===0?[]:[Bo(e)]}function Go(e){if(!e||e.length===0)return[];let t=yo(e);return t===null?[]:[t]}function Ko(e){let t=e.agent,n=qo(t);return{id:t.config.name,instructions:Vo({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 qo(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 Jo=new Set([`aud`,`exp`,`iat`,`iss`,`jti`,`nbf`,`sub`]);function Yo(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 Xo(e){let t=Yo(e);return Object.freeze(Object.fromEntries(Object.entries(t).filter(([e])=>!Jo.has(e))))}function Zo(e,t){let n=Yo(e);if(t.subjects!==void 0){let n=typeof e.sub==`string`?e.sub:null;if(n===null||!t.subjects.some(e=>$o(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 Qo(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=Yo(e.payload);return{attributes:Xo(e.payload),authenticator:e.authenticator,claims:r,issuer:t,principalId:`${t}:${n}`,principalType:e.principalType,subject:n}}function $o(e,t){if(!e.includes(`*`))return e===t;let n=e.replaceAll(/[.+?^${}()|[\]\\]/g,`\\$&`).replaceAll(`*`,`.*`);return RegExp(`^${n}$`).test(t)}const es=b.object({issuer:b.string().optional(),jwks_uri:b.string().url()}).passthrough(),ts=new Map,ns=new Map;async function rs(e){let t;try{t=await is(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 je(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&&os({issuer:e.strategy.issuer,payload:n.payload}),i=r&&ss({payload:n.payload});return!r&&!Zo(n.payload,e.strategy)?{kind:`caller-not-allowed`}:{kind:`authenticated`,principal:Qo({authenticator:`oidc`,payload:n.payload,principalType:i?`runtime`:`service`})}}catch{return{kind:`not-authenticated`}}}async function is(e){let t=await as(e.discoveryUrl),n=ns.get(t.jwks_uri);if(n!==void 0)return n;let r=ke(new URL(t.jwks_uri));return ns.set(t.jwks_uri,r),r}async function as(e){let t=ts.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 es.parse(await e.json())}).catch(t=>{throw ts.delete(e),t});return ts.set(e,n),await n}function os(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 ss(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 cs(e){return{attributes:e.attributes,authenticator:e.authenticator,issuer:e.issuer,principalId:e.principalId,principalType:e.principalType,subject:e.subject}}const K=sa(`auth.vercel-oidc`);async function ls(e,t){return e===null||e.length===0?{kind:`not-authenticated`}:await rs({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 us(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`,fs(e));return Response.json({code:n,error:r,ok:!1},{headers:a,status:t})}function fs(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}="${ps(t)}"`).join(`, `);return`${e.scheme} ${t}`}function ps(e){return e.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`)}function ms(){return()=>void 0}async function hs(e,t={}){if(e===null||e.length===0)return K.debug(`Rejected request without a bearer token.`),{ok:!1};let n=_s(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 ls(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:cs(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 gs(e={}){return async t=>{let n=await hs(us(t.headers.get(`authorization`)),e);return n.ok?n.sessionAuth:null}}function _s(e){let t;try{t=Ae(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 vs(e){return Number.isFinite(e)&&Number.isInteger(e)&&e>=0}function ys(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: ${m(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`||!vs(o))throw Error(`AttachmentRef payload "size" must be a non-negative integer. Got: ${JSON.stringify(o)}.`);return{params:a,size:o}}function bs(e){return e instanceof URL&&e.protocol===`ash-attachment:`}function xs(e){return typeof Buffer<`u`&&Buffer.isBuffer(e)||e instanceof Uint8Array||e instanceof ArrayBuffer?e.byteLength:typeof e==`string`?Ss(e):bs(e)?ys(e).size??null:e instanceof URL&&e.protocol===`data:`?Ss(e.href):null}function Ss(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 Cs(r);try{return Buffer.byteLength(decodeURIComponent(r),`utf8`)}catch{return Buffer.byteLength(r,`utf8`)}}return/^https?:\/\//.test(e)?null:Cs(e)}function Cs(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 ws=Object.freeze({allowedMediaTypes:`*`,maxBytes:25*1024*1024});function Ts(e,t=ws){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 Es(e,t){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 Ds(e,t){if(!Es(e.mediaType,t)){let n={allowedMediaTypes:t.allowedMediaTypes===`*`?[]:[...t.allowedMediaTypes],kind:`disallowed-media-type`,mediaType:e.mediaType};return e.filename===void 0?n:{...n,filename:e.filename}}let n=xs(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 Os(e,t){if(typeof e==`string`)return[];let n=[];for(let r of e){if(r.type!==`file`)continue;let e=Ds(r,t);e!==null&&n.push(e)}return n}function ks(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 As(e,t){return{method:`POST`,path:e,handler:t}}function js(e,t){return{method:`GET`,path:e,handler:t}}function Ms(e){let t=Ns(e);return{__kind:`ash:channel`,routes:e.routes,adapter:t,receive:e.receive}}function Ns(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;return{...n?e.context(r):{},state:r,ctx:t.ctx,session:{id:``,continuationToken:``,auth:null,initiatorAuth:null,setContinuationToken(e){}}}},deliver(e){return va(e)},...a}}function Ps(e){let t=Ts(e.uploadPolicy);return Ms({routes:[As(`/ash/v1/session`,async(n,{send:r})=>{let i=await Fs(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=Is(o);if(s instanceof Response)return s;let c=Bs(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`,[y]:u.id},status:202})}),As(`/ash/v1/session/:sessionId`,async(n,{send:r,getSession:i,params:a})=>{let o=await Fs(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=Ls(l);if(u instanceof Response)return u;let d=Bs(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`,[y]:f.id},status:200})}),js(`/ash/v1/session/:sessionId/stream`,async(t,{getSession:n,params:r})=>{let i=await Fs(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=Hs(t);if(o instanceof Response)return o;try{let e=Us(await n(a).getEventStream({startIndex:o}));return new Response(e,{headers:{"cache-control":`no-store`,"content-type":ie,[y]:a,[re]:te,[ae]:`14`}})}catch{return Response.json({error:`Session not found.`,ok:!1},{status:404})}})]})}async function Fs(e,t){let n=await e(t);return n===null?ds({challenges:[{scheme:`Bearer`}]}):n??null}function Is(e){let t=Rs(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 Ls(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=Rs(e.message);if(n instanceof Response)return n;let r=Vs(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 Rs(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=zs(n);if(e instanceof Response)return e;t.push(e)}return t}function zs(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 Bs(e,t){if(!e.message)return null;let n=Os(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:ks(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 Vs(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 Hs(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 Us(e){let t=new TextEncoder;return e.pipeThrough(new TransformStream({transform(e,n){n.enqueue(t.encode(`${JSON.stringify(e)}\n`))}}))}function Ws(){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 Gs=[`GET`,`POST`];function Ks(){return Gs.map(e=>Js(e))}function qs(){return new Set(Gs.map(Ys))}function Js(e){let t=Ys(e);return{name:t,method:e,urlPath:se,fetch:Xs,logicalPath:`framework://channels/${t}`,sourceId:`ash:framework:connection-callback-${e.toLowerCase()}`,sourceKind:`module`}}function Ys(e){return`.well-known/ash/v1/connections/callback/${e.toLowerCase()}`}async function Xs(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 Zs(e);try{await Se(r,i)}catch{return Response.json({error:`Connection callback not pending.`,ok:!1},{status:404})}return Ws()}async function Zs(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 Qs(){let e=Ps({auth:ec()}),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(...Ks()),t}function $s(){return new Set([`ash`,...qs()])}function ec(){return process.env.VERCEL?gs():ms()}const tc=oe.omit({action:!0,display:!0,requestId:!0}),{$schema:nc,...rc}=b.toJSONSchema(tc),ic={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:rc,logicalPath:`ash:framework/ask-question`,name:`ask_question`,sourceId:`ash:ask-question-tool`,sourceKind:`module`};async function q(){let e=V().get(ed);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 ac(e){if(!e.startsWith(`/`))throw Error(`filePath must be an absolute path. Received: "${e}". Use an absolute path such as /workspace/foo.ts.`)}function oc(e){return cc(e,`head`)}function sc(e){return cc(e,`tail`)}function cc(e,t){let n=e.split(`
|
|
66
|
+
`),r=uc(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=lc(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 lc(e){return e.length<=2e3?e:e.slice(0,2e3)+` [truncated]`}function uc(e){return e.length>0&&e[e.length-1]===``?e.length-1:e.length}async function dc(e){let t=await(await q()).runCommand(e.command),n=sc(t.stdout),r=sc(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 fc={additionalProperties:!1,properties:{command:{description:`The shell command to execute.`,type:`string`}},required:[`command`],type:`object`};async function pc(e){return dc(e)}const mc={description:`Execute a shell command in the shared workspace environment.`,execute:pc,inputSchema:fc,logicalPath:`ash:framework/bash`,name:`bash`,sourceId:`ash:bash-tool`,sourceKind:`module`},hc=new B(`ash.readFile`);function J(e){return de.normalize(e)}function gc(e){return e}function _c(e){let t=be(`sha256`).update(e.content,`utf8`).digest(`hex`);return{byteLength:Buffer.byteLength(e.content,`utf8`),contentHash:t,filePath:e.filePath}}function vc(e,t,n){let r=e.ensure(hc,()=>({byTarget:{}}));e.set(hc,{byTarget:{...r.byTarget,[t]:n}})}function yc(e){e.set(hc,{byTarget:{}})}const bc=new Map;async function xc(e){let t=bc.get(e.id);if(t!==void 0)return t;let n=Sc(e);bc.set(e.id,n);try{return await n}catch{return bc.delete(e.id),!1}}async function Sc(e){return(await e.runCommand(`command -v rg >/dev/null 2>&1`)).exitCode===0}function Y(e){return`'${e.replace(/'/g,`'\\''`)}'`}async function Cc(e){let t=e.path??`/workspace`;ac(t);let n=J(t),r=Math.min(Math.max(1,e.limit??100),1e3),i=await q(),a=await xc(i)?wc({normalizedPath:n,pattern:e.pattern}):Tc({normalizedPath:n,pattern:e.pattern}),o=await i.runCommand(a);if(o.exitCode!==0&&o.exitCode!==1)throw Dc(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 wc(e){return[`rg --files --hidden`,`--glob '!.git/*'`,`--glob ${Y(e.pattern)}`,`-- ${Y(e.normalizedPath)}`].join(` `)}function Tc(e){let t=Ec(e.pattern),n=t.includes(`/`)?`-path ${Y(`*/${t}`)}`:`-name ${Y(t)}`;return[`find ${Y(e.normalizedPath)}`,`-type f`,`-not -path '*/.git/*'`,n].join(` `)}function Ec(e){let t=e.replaceAll(`**`,`*`);for(;t.startsWith(`*/`);)t=t.slice(2);return t}function Dc(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 Oc={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 kc(e){return Cc(e)}const Ac={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:kc,inputSchema:Oc,logicalPath:`ash:framework/glob`,name:`glob`,sourceId:`ash:glob-tool`,sourceKind:`module`};async function jc(e){let t=e.path??`/workspace`;ac(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 xc(a)?Mc({contextLines:i,effectiveLimit:r,glob:e.glob,ignoreCase:e.ignoreCase??!1,literal:e.literal??!1,normalizedPath:n,pattern:e.pattern}):Nc({contextLines:i,effectiveLimit:r,glob:e.glob,ignoreCase:e.ignoreCase??!1,literal:e.literal??!1,normalizedPath:n,pattern:e.pattern}),s=await a.runCommand(o);if(s.exitCode!==0&&s.exitCode!==1)throw Fc(o,s.exitCode,s.stderr);let c=s.stdout;return c.trim().length===0?{content:`No matches found`,matchCount:0,path:n,truncated:!1}:Pc({effectiveLimit:r,normalizedPath:n,stdout:c})}function Mc(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 Nc(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 Pc(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=lc(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 Fc(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 Ic={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 Lc(e){return jc(e)}const Rc={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:Lc,inputSchema:Ic,logicalPath:`ash:framework/grep`,name:`grep`,sourceId:`ash:grep-tool`,sourceKind:`module`};async function zc(e){let{filePath:t,offset:n,limit:r}=e;ac(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(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=_c({content:c,filePath:a}),f=gc(a);vc(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}: ${lc(h[e]??``)}`,n=Buffer.byteLength(t,`utf8`)+1;if(_+n>51200&&g.length>0){v=!0;break}g.push(t),_+=n}let y=g.join(`
|
|
75
|
+
`),ee=o+g.length-1;return ee<u||v?{content:y,nextOffset:ee+1,path:a,totalLines:u,truncated:!0}:{content:y,path:a,totalLines:u,truncated:!1}}const Bc={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 Vc(e){return zc(e)}const Hc={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:Vc,inputSchema:Bc,logicalPath:`ash:framework/read-file`,name:`read_file`,onCompact({ctx:e}){return yc(e),{}},sourceId:`ash:read-file-tool`,sourceKind:`module`},Uc=/^---\r?\n[\s\S]*?\r?\n---\r?\n?/;function Wc(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 Gc(e,t){Wc(t);let n=await Kc(e),r=qc(t,`SKILL.md`),i=await n.readTextFile(r);if(i===null)throw Error(`No skill named "${t}" at ${r}.`);return i.replace(Uc,``)}async function Kc(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 qc(e,t){return`${G}/skills/${e}/${t}`}async function Jc(e){let t=V().get(ed);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 Gc(t,n)}const Yc={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=>Jc(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`},Xc=new B(`ash.todo`);function Zc(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 Qc(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 $c(e){let t=V(),{todos:n}=e??{};if(n!==void 0){let e={items:[...n]};return t.set(Xc,e),Qc(e)}return Qc(t.ensure(Xc,()=>({items:[]})))}const el={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=>$c(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(Xc);if(t===void 0||t.items.length===0)return{};let n=Zc(t);return n===void 0?{}:{messages:[{content:n,role:`user`}]}},sourceId:`ash:todo-tool`,sourceKind:`module`};function tl(e){let t=new Me({bulletListMarker:`-`,codeBlockStyle:`fenced`,emDelimiter:`*`,headingStyle:`atx`,hr:`---`});return t.remove([`script`,`style`,`meta`,`link`]),t.turndown(e)}function nl(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=al(t),t=t.split(`
|
|
81
|
+
`).map(e=>e.replace(/[ \t]+/g,` `).trim()).join(`
|
|
82
|
+
`).replace(/\n{3,}/g,`
|
|
83
|
+
|
|
84
|
+
`).trim(),t}const rl={"&":`&`,">":`>`,"<":`<`," ":` `,""":`"`,"'":`'`,"'":`'`,"/":`/`},il=new RegExp(Object.keys(rl).join(`|`),`gi`);function al(e){return e.replace(il,e=>rl[e.toLowerCase()]??e)}const ol=5*1024*1024;async function sl(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=cl(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":g},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)>ol)throw Error(`Response too large (exceeds 5 MB limit).`);let u=await c.arrayBuffer();if(u.byteLength>ol)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?tl(p):n===`text`&&f?nl(p):p;let{output:h,truncated:_}=oc(m);return{content:h,contentType:d,truncated:_,url:t}}function cl(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 ll(e){return sl(e)}const ul={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:ll,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 fl(e){let{filePath:t,content:n}=e;ac(t);let r=await q(),i=V(),a=J(t),o=gc(a),s=await r.readTextFile(t);if(s===null)return await r.writeTextFile(t,n),vc(i,o,_c({content:n,filePath:a})),{existed:!1,path:a};let c=i.ensure(hc,()=>({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=_c({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(t,n),vc(i,o,_c({content:n,filePath:a})),{existed:!0,path:a}}const pl={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 ml(e){return fl(e)}const hl=[ic,mc,Ac,Rc,Hc,{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:ml,inputSchema:pl,logicalPath:`ash:framework/write-file`,name:`write_file`,sourceId:`ash:write-file-tool`,sourceKind:`module`},el,ul,dl,Yc,No],gl=new Map([[No,e=>e.hasConnections]]);function _l(e){return hl.filter(t=>{let n=gl.get(t);return n===void 0||n(e)})}function vl(){return new Set(hl.map(e=>e.name))}function yl(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 bl(e){return{exportName:e.exportName,logicalPath:e.logicalPath,sourceId:e.sourceId,sourceKind:`module`}}async function Z(e){let t=e.nodeId??`__root__`,r=e.moduleMap.nodes[t]?.modules[e.definition.sourceId];if(r===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 o(i(n(r,`Missing compiled module namespace for ${e.kindLabel} source "${e.definition.sourceId}" in node "${t}".`),{exportName:e.definition.exportName,logicalPath:e.definition.logicalPath}))}async function xl(e,t,n){try{let r=ri(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=bl({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,adapter:o,...i}}catch(t){throw t instanceof X?t:new X(`Failed to attach the channel definition from "${e.logicalPath}": ${m(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}async function Sl(e,t,r){try{let i=n(await Z({definition:e,kindLabel:`connection`,moduleMap:t,nodeId:r}),`Expected the connection export "${e.exportName??`default`}" from "${e.logicalPath}" to return an object.`),a=i.auth!==void 0,o=i.headers!==void 0,s={connectionName:e.connectionName,description:e.description,exportName:e.exportName,logicalPath:e.logicalPath,sourceId:e.sourceId,sourceKind:`module`,url:e.url};if(a)try{s.authorization=li(i.auth,`Connection "${e.connectionName}" at "${e.logicalPath}":`)}catch(t){throw new X(m(t),{logicalPath:e.logicalPath,sourceId:e.sourceId})}return o&&(s.headers=i.headers),i.tools!==void 0&&(s.tools=i.tools),typeof i.approval==`function`&&(s.approval=i.approval),s}catch(t){throw t instanceof X?t:new X(`Failed to resolve connection "${e.connectionName}" from "${e.logicalPath}": ${m(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}async function Cl(e,t,r){try{let i=n(await Z({definition:e,kindLabel:`hook`,moduleMap:t,nodeId:r}),Q(e,`to return an object`)),a={},o={},s=i.lifecycle;if(s!==void 0){let t=n(s,Q(e,"to expose `lifecycle` as an object"));for(let n of[`session`,`turn`]){let r=t[n];r!==void 0&&(a[n]=l(r,Q(e,`to provide a function for "lifecycle.${n}"`)))}}let c=i.events;if(c!==void 0){let t=n(c,Q(e,"to expose `events` as an object"));for(let[n,r]of Object.entries(t))r!==void 0&&(o[n]=l(r,Q(e,`to provide a function for "events.${n}"`)))}return{events:o,exportName:e.exportName,lifecycle:a,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}": ${m(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}function Q(e,t){return`Expected the hook export "${e.exportName??`default`}" from "${e.logicalPath}" ${t}.`}var wl=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 Tl(e){let t=[];for await(let n of e)t.push(n);return Buffer.concat(t)}function El(e){return new ReadableStream({start(t){t.enqueue(e),t.close()}})}function $(e){return{id:e.id,async readFile(t){return await e.readFile(e.resolvePath(t))},async readBinaryFile(t){let n=await e.readFile(e.resolvePath(t));return n===null?null:await Tl(n)},async readTextFile(t,n){Dl(n);let r=await e.readFile(e.resolvePath(t));return r===null?null:kl(Al(await Tl(r),n?.encoding??`utf-8`),n)},resolvePath(t){return e.resolvePath(t)},async runCommand(t,n){return await e.runCommand(t,n)},async writeFile(t,n){await e.writeFile(e.resolvePath(t),n)},async writeBinaryFile(t,n){await e.writeFile(e.resolvePath(t),El(n))},async writeTextFile(t,n,r){let i=jl(n,r?.encoding??`utf-8`);await e.writeFile(e.resolvePath(t),El(i))}}}function Dl(e){if(e===void 0)return;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 Ol(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=Ol(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 Al(e,t){return t===`utf-8`||t===`utf8`?new TextDecoder(`utf-8`,{fatal:!0}).decode(e):e.toString(t)}function jl(e,t){return t===`utf-8`||t===`utf8`?Buffer.from(new TextEncoder().encode(e)):Buffer.from(e,t)}function Ml(){return{name:`local`,async prewarm(e){let t=Rl(ld(e.runtimeContext.appRoot),e.templateKey);if(await Kl(t))return;let n=await Nl({sessionKey:e.templateKey,snapshotPath:t}),r=$(Fl(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(t.path,t.content):await r.writeBinaryFile(t.path,t.content);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=ld(e.runtimeContext.appRoot),n=await Wl(Rl(t,e.templateKey));if(n===null)throw new wl({backendName:`local`,templateKey:e.templateKey});let r=ql(e.existingMetadata)??zl(t,e.sessionKey);return await Kl(r)||await Gl(r,n),Pl(await Nl({sessionKey:e.sessionKey,snapshotPath:r}))}}}async function Nl(e){let{Bash:t,InMemoryFs:n}=await import(`#compiled/just-bash/index.js`),r=await Wl(e.snapshotPath),i=new n(Bl(r));await Vl(i),await Hl(i,r?.entries??[]);let a=new t({cwd:G,env:r?.env,fs:i,network:{dangerouslyAllowFullInternetAccess:!0}});return{async captureSnapshot(){let t=await Ul({filesystem:i,sandbox:a});return await Gl(e.snapshotPath,t),{snapshotPath:e.snapshotPath}},async dispose(){await a.dispose?.()},async executeCommand(e,t){if(t?.abortSignal?.aborted)throw new DOMException(`The operation was aborted.`,`AbortError`);let n=t?.workingDirectory===void 0?e:`( cd ${Y(t.workingDirectory)} && ${e} )`,r=a.exec(n),i=t?.abortSignal?await Il(r,t.abortSignal):await r;return{exitCode:i.exitCode,stderr:i.stderr,stdout:i.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=x(t.path);await i.mkdir(e,{recursive:!0}),await i.writeFile(t.path,t.content)}}}}function Pl(e){let t=$(Fl(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 Fl(e){return{id:e.sessionKey,async readFile(t){let n=await e.readFileBytes(t);return n===null?null:El(n)},resolvePath:Ll,runCommand:(t,n)=>e.executeCommand(t,n),async writeFile(t,n){let r=await Tl(n);await e.writeFiles([{path:t,content:r}])}}}async function Il(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 Ll(e){return e.startsWith(`/`)?e:`${G}/${e}`}function Rl(e,t){return S(e,`local`,`templates`,`${t}.json`)}function zl(e,t){return S(e,`local`,`sessions`,`${t}.json`)}function Bl(e){let t={};for(let n of e?.entries??[])n.kind===`file`&&(t[n.path]=Buffer.from(n.contentBase64,`base64`));return t}async function Vl(e){await e.mkdir(G,{recursive:!0})}async function Hl(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 Ul(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 Wl(e){if(!await Kl(e))return null;let t=JSON.parse(await ge(e,`utf8`));return t.version===1?t:null}async function Gl(e,t){await w(x(e),{recursive:!0}),await T(e,`${JSON.stringify(t,null,2)}\n`)}async function Kl(e){try{return await me(e),!0}catch{return!1}}function ql(e){let t=e?.snapshotPath;return typeof t==`string`?t:void 0}function Jl(){return Ml()}function Yl(e={}){let t=e.loadSandboxModule??(async()=>await import(`#compiled/@vercel/sandbox/index.js`)),n={timeout:pu},r=new Map;return{name:`vercel`,async create(e){let i=lu(n.tags,e.tags),a;try{a=await Xl({loadSandboxModule:t,prewarmedTemplates:r,templateKey:e.templateKey})}catch(t){throw wl.is(t)?t:Error(`Failed to read sandbox template "${e.templateKey}": ${fu(t)}`,{cause:t})}let o;try{o=await Ql({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}": ${fu(t)}`,{cause:t})}return $l(o,e.sessionKey)},async prewarm(e){let i;try{i=await Zl({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}": ${fu(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 Xl(e){let t=e.prewarmedTemplates.get(e.templateKey);if(t!==void 0)return t;let n=await ou(await e.loadSandboxModule(),e.templateKey);if(n===null||typeof n.currentSnapshotId!=`string`)throw new wl({backendName:`vercel`,templateKey:e.templateKey});return{sandboxName:n.name,snapshotId:n.currentSnapshotId,templateKey:e.templateKey}}async function Zl(e){let t=await e.loadSandboxModule(),n=await ou(t,e.templateKey),r=lu(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 uu(n,r);if(typeof n.currentSnapshotId==`string`&&n.currentSnapshotId.length>0)return{sandboxName:n.name,snapshotId:n.currentSnapshotId,templateKey:e.templateKey};await ru(n,e.createOptions);let i=$(tu(n,e.templateKey));e.bootstrap!==void 0&&await e.bootstrap({use:async()=>i});for(let t of e.seedFiles)typeof t.content==`string`?await i.writeTextFile(t.path,t.content):await i.writeBinaryFile(t.path,t.content);let a=await n.snapshot();return{sandboxName:n.name,snapshotId:a.snapshotId,templateKey:e.templateKey}}async function Ql(e){let t=cu(e.existingMetadata)??e.sessionKey,n=await ou(e.sandboxModule,t);if(n!==null)return await uu(n,e.tags),n;let r={...e.createOptions,name:t,persistent:!0,source:{snapshotId:e.snapshotId,type:`snapshot`}};return e.tags!==void 0&&(r.tags=e.tags),await e.sandboxModule.Sandbox.create(r)}function $l(e,t){return{session:$(tu(e,t)),useSessionFn:async n=>(n!==void 0&&await e.update(n),eu(e,t)),async captureState(){return{backendName:`vercel`,metadata:{sandboxName:e.name},sessionKey:t}},async dispose(){}}}function eu(e,t){return{...$(tu(e,t)),get name(){return e.name},get persistent(){return e.persistent},get status(){return e.status},get networkPolicy(){return e.networkPolicy},get tags(){return e.tags},async update(t){await e.update(t)},async stop(t){await e.stop(t)},async snapshot(t){return await e.snapshot(t)},domain(t){return e.domain(t)}}}function tu(e,t){return{id:t,async readFile(t){return await e.readFile({path:t})??null},resolvePath:nu,async runCommand(t,n){let r=await e.runCommand({args:[`-lc`,t],cmd:`bash`,cwd:n?.workingDirectory??`/workspace`,signal:n?.abortSignal}),[i,a]=await Promise.all([r.stdout(),r.stderr()]);return{exitCode:r.exitCode,stderr:a,stdout:i}},async writeFile(t,n){let r=await Tl(n);await e.writeFiles([{content:r,path:t}])}}}function nu(e){return e.startsWith(`/`)?e:`${G}/${e}`}async function ru(e,t){await iu(e,{failureMessage:`Failed to initialize Vercel sandbox workspace.`,script:`mkdir -p ${G} && chown ${au}:${au} ${G}`}),t.networkPolicy!==`deny-all`&&await iu(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 iu(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 au=`vercel-sandbox`;async function ou(e,t){try{return await e.Sandbox.get({name:t})}catch(e){if(su(e))return null;throw Error(`Failed to look up Vercel sandbox "${t}": ${fu(e)}`,{cause:e})}}function su(e){return e instanceof Error?(e.response?.status??e.cause?.response?.status)===404:!1}function cu(e){let t=e?.sandboxName;return typeof t==`string`?t:void 0}function lu(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>mu)throw Error(`Vercel Sandbox supports at most ${mu} tags. Ash reserves "agent", "channel", and "sessionId"; remove or consolidate custom tags passed to vercelBackend().`);return n}}async function uu(e,t){t===void 0||du(e.tags,t)||await e.update({tags:t})}function du(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 fu(e){return e instanceof Error?e.message:String(e)}const pu=1800*1e3,mu=5;function hu(){return Yl()}function gu(){let e;function t(){return e===void 0&&(e=process.env.VERCEL?hu():Jl()),e}return{get name(){return t().name},create(e){return t().create(e)},async prewarm(e){await t().prewarm(e)}}}async function _u(e,t,r){try{let i=n(await Z({definition:e,kindLabel:`sandbox`,moduleMap:t,nodeId:r}),`Expected the sandbox export "${e.exportName??`default`}" from "${e.logicalPath}" to return an object.`);return{backend:vu(i.backend,e.logicalPath),bootstrap:i.bootstrap,description:e.description,exportName:e.exportName,logicalPath:e.logicalPath,onSession:i.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}": ${m(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}function vu(e,t){if(e===void 0)return gu();if(typeof e!=`object`||!e)throw new X(`Sandbox "${t}" exposed a non-object "backend" field. Use vercelBackend(), localBackend(), or another factory that returns a SandboxBackend value.`,{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 yu(e,t,r){try{let i=n(await Z({definition:e,kindLabel:`tool`,moduleMap:t,nodeId:r}),Su(e,`to return an object`)),a=l(i.execute,Su(e,`to provide an execute function`));return{description:e.description,execute:a,exportName:e.exportName,inputSchema:e.inputSchema,logicalPath:e.logicalPath,name:e.name,sourceId:e.sourceId,sourceKind:`module`,...bu(i,e)}}catch(t){throw t instanceof X?t:new X(`Failed to attach the tool execute function from "${e.logicalPath}": ${m(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}function bu(e,t){let n={};e.onCompact!==void 0&&(n.onCompact=l(e.onCompact,Su(t,`to provide an onCompact function`))),e.needsApproval!==void 0&&(n.needsApproval=l(e.needsApproval,Su(t,`to provide a needsApproval function`)));let r=xu(e,t);return r!==void 0&&(n.retentionPolicy=r),e.inputSchema!==void 0&&Cu(e.inputSchema)&&(n.inputStandardSchema=e.inputSchema),n}function xu(e,t){let n=e.retentionPolicy;if(n!==void 0){if(n===`auto`||n===`keep`||typeof n==`function`)return n;throw new X(Su(t,`to set retentionPolicy to "auto", "keep", or a function`),{logicalPath:t.logicalPath,sourceId:t.sourceId})}}function Su(e,t){return`Expected the tool export "${e.exportName??`default`}" from "${e.logicalPath}" ${t}.`}function Cu(e){return typeof e==`object`&&!!e&&`~standard`in e&&typeof e[`~standard`]==`object`}async function wu(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 xl(t,e.moduleMap,e.nodeId))}let i=await Promise.all(e.manifest.tools.map(t=>yu(t,e.moduleMap,e.nodeId))),a=await Promise.all(e.manifest.hooks.map(t=>Cl(t,e.moduleMap,e.nodeId))),o=await Promise.all(e.manifest.connections.map(t=>Sl(t,e.moduleMap,e.nodeId))),s=e.manifest.sandbox===null?null:await _u(e.manifest.sandbox,e.moduleMap,e.nodeId),c=Tu(e.manifest.instructions),l=e.manifest.workspaceResourceRoot,u={channels:n,config:Eu(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 Tu(e){if(e!==void 0)return{name:e.name,logicalPath:e.logicalPath,markdown:e.markdown,sourceId:e.sourceId,sourceKind:e.sourceKind}}function Eu(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=bl(e.config.source)),t}function Du(e){return{sandbox:{definition:e.authoredSandbox??Ou(),workspaceResourceRoot:e.workspaceResourceRoot}}}function Ou(){return{backend:gu(),logicalPath:`ash:framework/default-sandbox`,sourceId:`ash:default-sandbox`,sourceKind:`module`}}const ku=`load_skill`,Au=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 ju(e){let t=[],n=new Aa(`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=Mu(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 Mu(e){return{description:e.description,inputSchema:Au,kind:`subagent`,logicalPath:e.logicalPath,name:e.name,nodeId:e.nodeId,sourceId:e.sourceId}}async function Nu(e,t={}){let n=[],r=new Aa(`tool`,t.reservedToolNames??[]);for(let t of e.tools){let e=await Pu(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 Pu(e){return{description:e.description,inputSchema:await Fu(e),kind:`authored-tool`,logicalPath:e.logicalPath,name:e.name,sourceId:e.sourceId}}async function Fu(e){return e.inputSchema}var Iu=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 Lu(e){let t=new Map,n=Vu(e.manifest),r=new Map(e.manifest.subagents.map(e=>[e.nodeId,e]));return{nodesByNodeId:t,root:await Ru({childNodeIdsByParentNodeId:n,manifest:e.manifest,moduleMap:e.moduleMap,nodeId:L,nodesByNodeId:t,subagentNodesById:r})}}async function Ru(e){let t=Hu(e.nodeId);if(e.nodesByNodeId.has(t))throw new Iu(`Found multiple runtime agent nodes for node id "${t}".`,{nodeId:t,sourceId:e.sourceId});let n=await wu({manifest:e.manifest,moduleMap:e.moduleMap,nodeId:e.nodeId}),r=n.connections.length>0,i=_l({hasConnections:r}),a=r?Wu(i,n.connections):i,o=new Set(a.map(e=>e.name)),s=vl(),c=new Set(n.tools.map(e=>e.name));for(let r of n.disabledFrameworkTools)if(!s.has(r))throw new Iu(`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 Nu({tools:[...a.filter(e=>!c.has(e.name)&&!l.has(e.name)),...n.tools]},{reservedToolNames:o.has(`load_skill`)||c.has(`load_skill`)?[]:[ku]}),d=new Set(n.channels.map(e=>e.name)),f=$s();for(let r of n.disabledFrameworkChannels)if(!f.has(r))throw new Iu(`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=[...Qs().filter(e=>!d.has(e.name)&&!p.has(e.name)),...n.channels],h=Du({authoredSandbox:n.sandbox,workspaceResourceRoot:n.workspaceResourceRoot}),g=ju({reservedToolNames:[ku,...u.preparedTools.map(e=>e.name)],subagents:await zu({childNodeIdsByParentNodeId:e.childNodeIdsByParentNodeId,moduleMap:e.moduleMap,nodesByNodeId:e.nodesByNodeId,parentNodeId:e.nodeId,subagentNodesById:e.subagentNodesById})}),_={agent:n,channels:m,hookRegistry:yl(n.hooks),nodeId:t,sandboxRegistry:h,sourceId:e.sourceId,subagentRegistry:g,toolRegistry:u,turnAgent:Ko({agent:n,nodeId:t,tools:[...u.preparedTools,...g.preparedTools]})};return e.nodesByNodeId.set(t,_),_}async function zu(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 Iu(`Missing compiled subagent node "${r}" while resolving runtime subagents.`,{nodeId:Hu(e.parentNodeId),sourceId:r});t.push(await Bu({childNodeIdsByParentNodeId:e.childNodeIdsByParentNodeId,moduleMap:e.moduleMap,nodesByNodeId:e.nodesByNodeId,sourceRef:n,subagentNodesById:e.subagentNodesById}))}return t}async function Bu(e){let t={description:e.sourceRef.description,logicalPath:e.sourceRef.logicalPath,name:e.sourceRef.name,nodeId:Hu(e.sourceRef.nodeId),sourceId:e.sourceRef.sourceId,sourceKind:`module`};return await Ru({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 Vu(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 Hu(e){return e===`__root__`?ao:e}const Uu=No.name;function Wu(e,t){let n=t.map(e=>e.connectionName).join(`, `);return e.map(e=>e.name===Uu?{...e,description:`${e.description} Available connections: ${n}.`}:e)}const Gu=process.env.ASH_DISABLE_AGENT_CACHE===`1`;async function Ku(e){let[t,n]=await Promise.all([lo({compiledArtifactsSource:e}),qu(e)]),r=await Lu({manifest:t,moduleMap:n}),i=r.root;return{adapterRegistry:Pa({channels:Qu(r)}),compiledArtifactsSource:e,graph:r,hookRegistry:i.hookRegistry,moduleMap:n,resolvedAgent:i.agent,subagentRegistry:i.subagentRegistry,toolRegistry:i.toolRegistry,turnAgent:i.turnAgent}}async function qu(e){return e.kind===`disk`&&e.moduleMapLoadMode===`authored-source`?await Ju(e):await ho({compiledArtifactsSource:e})}async function Ju(e){if(e.moduleMapLoaderPath===void 0)throw Error(`Authored-source module map loading requires "moduleMapLoaderPath" in the compiled artifacts source.`);return await(await import(xe(e.moduleMapLoaderPath).href)).loadCompiledModuleMapFromAuthoredSource({compiledArtifactsSource:e})}async function Yu(e){if(Gu)return Ku(e);let t=Ja(),n=Ba(e),r=await no(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=Ku(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 Xu(e){let t=await Yu(e.compiledArtifactsSource);if(e.nodeId===void 0)return t;let n=oo(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 Zu(){let e=Ja();e.bundleCache.clear(),e.bundleCacheKeyBySourceKey.clear()}function Qu(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:ya(e),state:e.state?{...e.state}:{}}},deserialize(e,t){let n=t.get($u);if(n===void 0)throw Error(`Cannot deserialize "ash.channel" before "ash.bundle". The runtime bundle must be present in context.`);return Fa(n.adapterRegistry,e)}}});const $u=new B(`ash.bundle`,{codec:{serialize:e=>({nodeId:e.nodeId,source:e.compiledArtifactsSource}),deserialize:e=>{let{source:t,nodeId:n}=e;return Xu({compiledArtifactsSource:t,nodeId:n})}}});new B(`ash.session`);const ed=new B(`ash.sandbox`),td=v(),nd={workflowId:`workflow//${td.name}@${td.version}//workflowEntry`};function rd(e=process.cwd()){return C(e)}function id(e){return be(`sha256`).update(e).update(`\0`).update(nd.workflowId).digest(`hex`).slice(0,12)}function ad(){return!!process.env.VERCEL}function od(e,t=`all`){let n=S(e,`.ash`,`nitro`);return t===`all`?n:S(n,t)}function sd(e,t){return S(e,`.ash`,`nitro-output`,t)}function cd(e){return S(h(),`.ash`,`workflow-cache`,id(e))}function ld(e){return S(e,`.ash`,`sandbox-cache`)}function ud(e){return ad()?S(e,`.vercel`,`output`):S(e,`.output`)}function dd(e){return{appRoot:e,outputDir:ud(e),workflowId:nd.workflowId,workflowBuildDir:cd(e),workflowSourceDir:_(`src/execution`)}}export{Sr as C,jn as D,L as E,Dr as S,Cr as T,Ba as _,cd as a,Qr as b,$s as c,lo as d,ao as f,za as g,Ra as h,sd as i,Qs as l,U as m,rd as n,Zu as o,$a as p,od as r,Lu as s,dd as t,G as u,Qi as v,wr as w,kr as x,$i as y};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{E as e,S as t,T as n,_ as r,a as i,c as a,d as o,g as s,h as c,l,m as u,p as ee,s as te,u as d,x as f,y as p}from"./paths-
|
|
1
|
+
import{E as e,S as t,T as n,_ as r,a as i,c as a,d as o,g as s,h as c,l,m as u,p as ee,s as te,u as d,x as f,y as p}from"./paths-BYaK6-t0.js";import{t as m}from"./authored-module-loader-Pt_g8xX2.js";import{t as h}from"./errors-DsO9xmQL.js";import{i as g,t as _}from"./package-DmsQgn4v.js";import{join as v,posix as y}from"node:path";import{mkdir as ne,readFile as re,readdir as ie,realpath as b,writeFile as x}from"node:fs/promises";import{createHash as S}from"node:crypto";import{existsSync as C}from"node:fs";function w(e){return e.dev?{appRoot:e.appRoot,dev:e.dev,moduleMapLoaderPath:g(`src/internal/authored-module-map-loader.ts`)}:{appRoot:e.appRoot,dev:e.dev}}const T=`#ash-channel/`;function E(e){let t=e.compileResult.manifest.channels,n=new Set,r=[],i=new Set,o=a();for(let e of t){if(e.kind===`disabled`){if(!o.has(e.name))throw Error(`agent/channels/${e.name}.ts exports disableRoute() but "${e.name}" is not a framework channel. Rename the file to one of: ${[...o].sort().join(`, `)}.`);i.add(e.name);continue}n.add(e.name),r.push({method:e.method,route:e.urlPath})}let s=l().filter(e=>!n.has(e.name)&&!i.has(e.name)).map(e=>({method:e.method,route:e.urlPath})),c=new Set,u=[];for(let e of[...s,...r]){let t=k(e);c.has(t)||(c.add(t),u.push(e))}return u}function D(e,t){for(let n of t.registrations)A(e,{artifactsConfig:t.artifactsConfig,method:n.method,route:n.route})}function O(e,t){return N(t.previous,t.next)?!1:(j(e),D(e,{artifactsConfig:t.artifactsConfig,registrations:t.next}),e.routing.sync(),!0)}function k(e){return`${e.method.toUpperCase()} ${e.route}`}function A(e,t){let r=k(t),i=`${T}${r}`,a=n(g(`src/internal/nitro/routes/channel-dispatch.ts`));e.options.handlers.push({handler:i,method:t.method,route:t.route}),e.options.virtual[i]=[`import { dispatchChannelRequest } from ${a};`,`const config = ${JSON.stringify(t.artifactsConfig)};`,`export default (event) => dispatchChannelRequest(event, ${JSON.stringify(r)}, config);`].join(`
|
|
2
2
|
`)}function j(e){for(let t=e.options.handlers.length-1;t>=0;--t){let n=e.options.handlers[t];n!==void 0&&M(n)&&e.options.handlers.splice(t,1)}for(let t of Object.keys(e.options.virtual))t.startsWith(T)&&delete e.options.virtual[t]}function M(e){return e.handler.startsWith(T)}function N(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(r===void 0||i===void 0||r.method!==i.method||r.route!==i.route)return!1}return!0}const P=`ash.schedule.`;var F=class extends Error{scheduleId;sourceId;taskName;constructor(e,t={}){super(e),this.name=`ScheduleRegistrationError`,t.scheduleId!==void 0&&(this.scheduleId=t.scheduleId),t.sourceId!==void 0&&(this.sourceId=t.sourceId),t.taskName!==void 0&&(this.taskName=t.taskName)}};function I(e){let t=e.map(e=>({cron:e.cron,description:`Run Ash schedule "${e.name}" from "${e.logicalPath}".`,logicalPath:e.logicalPath,scheduleId:e.name,sourceId:e.sourceId,taskName:R(e.sourceId)})).sort((e,t)=>e.sourceId.localeCompare(t.sourceId));return L(t),t}function L(e){let t=new Map;for(let n of e){let e=t.get(n.scheduleId);if(e===void 0){t.set(n.scheduleId,n);continue}throw new F(`Duplicate authored schedule id "${n.scheduleId}" found in "${e.logicalPath}" and "${n.logicalPath}".`,{scheduleId:n.scheduleId,sourceId:n.sourceId,taskName:n.taskName})}}function R(e){return`${P}${Buffer.from(e,`utf8`).toString(`base64url`)}`}const z=`#ash-schedule-task/`;function B(e,t){if(t.registrations.length!==0){e.options.experimental.tasks=!0;for(let n of t.registrations)U(e,{artifactsConfig:t.artifactsConfig,dispatchModulePath:t.dispatchModulePath,registration:n})}}function V(e,t){let n=!G(t.previous,t.next);return H(e),B(e,{artifactsConfig:t.artifactsConfig,dispatchModulePath:t.dispatchModulePath,registrations:t.next}),n}function H(e){for(let t of Object.keys(e.options.tasks))t.startsWith(`ash.schedule.`)&&delete e.options.tasks[t];for(let t of Object.keys(e.options.virtual))t.startsWith(z)&&delete e.options.virtual[t];for(let[t,n]of Object.entries(e.options.scheduledTasks)){let r=W(n).filter(e=>!e.startsWith(P));if(r.length===0){delete e.options.scheduledTasks[t];continue}if(r.length===1){let[n]=r;n!==void 0&&(e.options.scheduledTasks[t]=n);continue}e.options.scheduledTasks[t]=r}}function U(e,t){let r=`${z}${t.registration.taskName}`,i=n(t.dispatchModulePath);e.options.tasks[t.registration.taskName]={description:t.registration.description,handler:r},e.options.virtual[r]=[`import { dispatchScheduleTask } from ${i};`,`const config = ${JSON.stringify(t.artifactsConfig)};`,`export default {`,` meta: { description: ${JSON.stringify(t.registration.description)} },`,` async run(event) {`,` return { result: await dispatchScheduleTask(event.name, config) };`,` },`,`};`].join(`
|
|
3
3
|
`),ae(e,t.registration.cron,t.registration.taskName)}function ae(e,t,n){let r=e.options.scheduledTasks[t];if(r===void 0){e.options.scheduledTasks[t]=n;return}if(typeof r==`string`){e.options.scheduledTasks[t]=[r,n];return}r.includes(n)||r.push(n)}function W(e){return typeof e==`string`?[e]:[...e]}function G(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(r===void 0||i===void 0||r.cron!==i.cron||r.description!==i.description||r.logicalPath!==i.logicalPath||r.scheduleId!==i.scheduleId||r.sourceId!==i.sourceId||r.taskName!==i.taskName)return!1}return!0}async function K(e){return[...e.manifest.schedules].map(e=>{let t={cron:e.cron,logicalPath:e.logicalPath,markdown:e.markdown,name:e.name,sourceId:e.sourceId,sourceKind:e.sourceKind};return e.channel===void 0?t:{...t,channel:e.channel}})}async function q(e){return await K({manifest:await o({compiledArtifactsSource:e.compiledArtifactsSource})})}async function J(e){let t=v(e.outDir,`compiled-artifacts-bootstrap.mjs`),n=v(e.outDir,`compiled-artifacts-instrumentation.mjs`),r=se(e.compileResult.manifest.agentRoot);await ne(e.outDir,{recursive:!0}),await x(t,await le({compileResult:e.compileResult,installModulePath:g(`src/runtime/loaders/bundled-artifacts.ts`),moduleMapPath:t,metadata:e.compileResult.metadata})),r!==void 0&&await x(n,ue({agentName:e.compileResult.manifest.config.name,instrumentationPath:r,registerConfigPath:g(`src/harness/instrumentation-config.ts`)}));let i={bootstrapPath:t};return r!==void 0&&(i.instrumentationPluginPath=n,i.instrumentationSourcePath=r),i}const oe=[`.ts`,`.mts`,`.js`,`.mjs`];function se(e){for(let t of oe){let n=v(e,`instrumentation${t}`);if(C(n))return n}}function ce(e){return e.replace(/^export const moduleMap = /m,`const moduleMap = `).replace(/\nexport default moduleMap;\n?$/,`
|
|
4
4
|
`)}async function le(e){let r=ce(t({importSpecifierStyle:`absolute`,manifest:e.compileResult.manifest,moduleMapPath:e.moduleMapPath})).trim();return[`// Generated by Ash. Do not edit by hand.`,`import { installBundledCompiledArtifacts } from ${n(e.installModulePath)};`,``,r,``,`const metadata = ${JSON.stringify(e.metadata,null,2)};`,``,`const manifest = ${JSON.stringify(e.compileResult.manifest,null,2)};`,``,`export function installCompiledArtifactsBootstrap() {`,` installBundledCompiledArtifacts({`,` manifest,`,` metadata,`,` moduleMap,`,` });`,`}`,``,`installCompiledArtifactsBootstrap();`,``,`// Default export satisfies the Nitro plugin contract so this file`,`// can be used directly as a Nitro plugin without a separate wrapper.`,`export default function installCompiledArtifactsPlugin() {`,` // Already installed on import above.`,`}`,``,`export async function __ashInstallCompiledArtifactsStep() {`,` "use step";`,` return null;`,`}`,``].join(`
|