experimental-ash 0.8.0 → 0.8.2
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 +28 -0
- package/dist/src/chunks/{dev-authored-source-watcher-BFC_yNcP.js → dev-authored-source-watcher-CDT0dQQf.js} +1 -1
- package/dist/src/chunks/{host-DMccRKcz.js → host-M56X595D.js} +2 -2
- package/dist/src/chunks/{paths-B-aiDznc.js → paths-B-Onq-sx.js} +25 -25
- package/dist/src/chunks/{prewarm-CCbReSNm.js → prewarm-DQzlGOTi.js} +1 -1
- package/dist/src/cli/commands/info.js +1 -1
- package/dist/src/cli/run.js +1 -1
- package/dist/src/evals/cli/eval.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/authored-definition/connection.js +10 -0
- package/dist/src/public/channels/ash.d.ts +8 -1
- package/dist/src/public/channels/slack/index.d.ts +1 -1
- package/dist/src/public/channels/slack/slack.js +8 -8
- package/dist/src/public/channels/slack/slackChannel.d.ts +14 -3
- package/dist/src/public/channels/slack/slackChannel.js +39 -48
- package/dist/src/runtime/connections/types.d.ts +21 -0
- package/dist/src/runtime/connections/validate-authorization.js +27 -2
- package/package.json +1 -1
|
@@ -4,13 +4,13 @@ import{i as e}from"./chunk-8L7ocgPr.js";import{t}from"./gray-matter-BxS7ZG-J.js"
|
|
|
4
4
|
`)}function Dr(e){return{modules:Or(e.manifest).sort((e,t)=>e.sourceId.localeCompare(t.sourceId)).map(t=>({bindingName:e.nextBindingName(),importSpecifier:kr({fromDirectory:e.moduleMapDirectory,importSpecifierStyle:e.importSpecifierStyle,targetPath:Nr(e.agentRoot,t.logicalPath)}),sourceId:t.sourceId})),nodeId:e.nodeId}}function Or(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 kr(e){if(e.importSpecifierStyle===`absolute`)return xr(Fr(e.targetPath));let t=Pr(e.fromDirectory,e.targetPath);return t.startsWith(`.`)?t:`./${t}`}function Ar(e){return jr([{key:`nodes`,value:jr(e.map(e=>({key:e.nodeId,value:jr([{key:`modules`,value:jr(e.modules.map(e=>({key:e.sourceId,value:e.bindingName})))}],3)})))}],0)}function jr(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
5
|
`,`\n${r}`)}`).join(`,
|
|
6
6
|
`),`${n}})`].join(`
|
|
7
|
-
`)}function Mr(e){let t=z(e);return t.segments.length===0?t.root.length===0?`.`:t.root:Ir(t.root,t.segments.slice(0,-1))}function Nr(e,t){let n=z(e),r=z(t);return r.root.length>0?Ir(r.root,r.segments):Ir(n.root,[...n.segments,...r.segments])}function Pr(e,t){let n=z(e),r=z(t);if(n.root!==r.root)return Fr(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 Fr(e){let t=z(e);return Ir(t.root,t.segments)}function z(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 Ir(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 Lr=`ash-model-catalog-cache`,Rr=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(),zr=b.object({slug:b.string().min(1),providers:b.array(Rr).min(1)}).passthrough(),Br=b.object({models:b.array(zr),providerAliases:b.record(b.string(),b.string())}).passthrough();b.object({contextWindowTokens:b.number().int().positive(),maxOutputTokens:b.number().int().positive().optional()}).strict();const Vr=b.object({fetchedAt:b.string(),kind:b.literal(Lr),models:b.array(zr),providerAliases:b.record(b.string(),b.string()),version:b.literal(2)}).strict(),Hr=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 Ur(e){return S(e,`.ash`,`cache`,`model-catalog.json`)}function Wr(e){let t=null,n=null,r=null,i=async()=>(t??=Kr(e),await t),a=async()=>{if(n!==null)throw n;if(r!==null)return await r;r=Gr(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&&Yr(e))return e;try{return await a()}catch{return e===null?null:e}};return{async getModelLimits(e){let t=Xr(e),n=await o();if(n!==null){let e=qr(n.models,t);if(e)for(let t of e.providers){let e=Jr(t);if(e!==null)return e}}return Hr.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=Xr(t);for(let e of n.models)for(let t of e.providers)if(t.provider===i&&Xr(t.providerModelId)===a){let n=Jr(t);if(n!==null)return{slug:e.slug,limits:n}}return null}}}async function Gr(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=Br.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:Lr,models:n.data.models,providerAliases:n.data.providerAliases,version:2};try{let t=Ur(e);await w(S(e,`.ash`,`cache`),{recursive:!0}),await T(t,`${JSON.stringify(r,null,2)}\n`,`utf8`)}catch{}return r}async function Kr(e){try{let t=await ge(Ur(e),`utf8`),n=Vr.safeParse(JSON.parse(t));return n.success?n.data:null}catch(e){return e instanceof Error&&`code`in e&&typeof e.code==`string`&&e.code,null}}function qr(e,t){return e.find(e=>e.slug===t)}function Jr(e){return e.contextWindowTokens===void 0||e.contextWindowTokens<=0?null:{contextWindowTokens:e.contextWindowTokens,...e.maxOutputTokens!==void 0&&e.maxOutputTokens>0&&{maxOutputTokens:e.maxOutputTokens}}}function Yr(e){let t=Date.parse(e.fetchedAt);return Number.isFinite(t)?Date.now()-t<=864e5:!1}function Xr(e){return e.endsWith(`-thinking`)?e.slice(0,-9):e}async function B(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 Zr=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 Qr(e,t){if(e.configModule===void 0)throw new Zr(e.agentId);let n=et(await B({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 $r({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 $r({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 $r(e){if(typeof e.value==`string`)return await ei({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 ei(i,e)}async function ei(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 ti(e){return typeof e==`object`&&!!e&&e.__kind===`ash:channel`}function ni(e,t){if(!ti(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 ri(e){return typeof e==`object`&&!!e&&e.kind===`ash:disabled-channel`}async function ii(e,t){let n=await B({agentRoot:e,kind:`channel`,source:t}),r=j(t.logicalPath).replace(/^channels\//,``);return ri(n)?{kind:`disabled`,name:r,logicalPath:t.logicalPath}:ni(n,`Expected the channel export "${t.exportName??`default`}" from "${t.logicalPath}" to match the public Ash shape.`).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}))}async function ai(e,t){let n=new Map;for(let r of t){let t=await B({agentRoot:e,kind:`channel`,source:r});if(ri(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 oi(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 si(e,t,n=`auth`){let r=oi(e,n);if(r!==void 0)throw Error(`${t} ${r}`);let i=e;return i.startAuthorization!==void 0&&i.completeAuthorization!==void 0?{completeAuthorization:i.completeAuthorization,getToken:i.getToken,principalType:`user`,startAuthorization:i.startAuthorization}:{getToken:i.getToken,principalType:i.principalType??`app`}}const ci=[`approval`,`auth`,`description`,`headers`,`tools`,`url`],li=[`completeAuthorization`,`getToken`,`principalType`,`startAuthorization`];function ui(e,t){let r=n(e,t);a(r,ci,t),di(r,t),fi(r,t);let i=pi(r,t),o=mi(r,t),s=hi(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 di(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 fi(e,t){if(typeof e.description!=`string`||e.description.length===0)throw Error(`${t} The "description" field must be a non-empty string.`)}function pi(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,li,`${t} The "auth" field`),si(r,t)}function mi(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 hi(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?(gi(n.allow,`${t} The "tools.allow"`),{allow:n.allow}):(gi(n.block,`${t} The "tools.block"`),{block:n.block})}function gi(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 _i(e,t){let n=ui(await B({agentRoot:e,kind:`connection`,source:t}),`Expected the connection export "${t.exportName??`default`}" from "${t.logicalPath}" to match the public Ash shape.`);return{connectionName:t.connectionName,description:n.description,exportName:t.exportName,logicalPath:t.logicalPath,sourceId:t.sourceId,sourceKind:`module`,url:n.url}}function vi(e){return{exportName:e.exportName,logicalPath:e.logicalPath,slug:j(e.logicalPath).replace(/^hooks\//,``),sourceId:e.sourceId,sourceKind:`module`}}function yi(e,t){let r=n(e,t);a(r,[`backend`,`bootstrap`,`description`,`onSession`],t);let i={};if(r.backend!==void 0&&(i.backend=bi(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 bi(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 xi(e,t){return{description:yi(await B({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 Si(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 B({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 Ci(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 B({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:Ti(t.logicalPath),sourceId:t.sourceId,sourceKind:t.sourceKind};return r.channel!==void 0&&(i.channel=wi({channel:r.channel,channelIdentityMap:n,logicalPath:t.logicalPath})),i}function wi(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 Ti(e){return j(e).replace(/^schedules\//,``)}async function Ei(e,t){if(t.sourceKind===`skill-package`)return Di(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 B({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 Di(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 Oi(e){let t=[],n=[];for(let r of e.subagents){let i=await ki({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 ki(e){let t=fr(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 Oi({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 Ai(e){return typeof e==`object`&&!!e&&e.kind===`ash:disabled-tool`}function ji(e){return e&&typeof e==`object`&&`~standard`in e?e[`~standard`].jsonSchema.input({target:`draft-07`}):JSON.parse(JSON.stringify(e))}function Mi(e,t){if(Ai(e))return{kind:`disabled`};let i=n(e,t);a(i,[`description`,`execute`,`inputSchema`,`needsApproval`,`onCompact`],t);let o=i.inputSchema===void 0?null:ji(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 Ni(e,t){let n=Mi(await B({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 Pi(e){let t={modelCatalog:Wr(e.appRoot)},[n,r]=await Promise.all([Fi(e,t),Oi({appRoot:e.appRoot,compileAgentNodeManifest:Fi,context:t,parentNodeId:R,subagents:e.subagents})]);return pr({...n,subagentEdges:r.edges,subagents:r.nodes})}async function Fi(e,t){let n=await Promise.all(e.tools.map(t=>Ni(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=>ii(e.agentRoot,t))),ai(e.agentRoot,e.channels)]),s=a.flat();return ur({agentRoot:e.agentRoot,appRoot:e.appRoot,channels:s,config:await Qr(e,t),connections:await Promise.all(e.connections.map(t=>_i(e.agentRoot,t))),diagnosticsSummary:e.diagnosticsSummary,disabledFrameworkTools:i,hooks:e.hooks.map(e=>vi(e)),sandbox:e.sandbox===null?null:await xi(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=>Ci(e.agentRoot,t,o))),skills:await Promise.all(e.skills.map(t=>Ei(e.agentRoot,t))),instructions:e.instructions===void 0?void 0:await Si(e.agentRoot,e.instructions),tools:r})}const Ii=`workspace-resources`;async function Li(e){let t=S(e.compileDirectoryPath,Ii);await ve(t,{force:!0,recursive:!0});let n=await zi({nodeId:R,resourcesRoot:t,manifest:e.manifest}),r=await Promise.all(e.manifest.subagents.map(async e=>({...e,agent:await zi({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 Ri(e,t){return{logicalPath:O(S(Ii,t)),rootEntries:dr({sandboxWorkspaces:e.sandboxWorkspaces,skills:e.skills})}}async function zi(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 Bi({nodeRoot:t,skill:n});return{...e.manifest,workspaceResourceRoot:Ri(e.manifest,e.nodeId)}}async function Bi(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 Vi(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 Hi(e){return{diagnostics:[...e],kind:`ash-discovery-diagnostics`,summary:Le(e),version:1}}function Ui(e){let t=v(),n=Gi(e.discoveryManifestJson),r=Gi(e.diagnosticsArtifactJson),i=Gi(e.moduleMapSource);return{compile:{moduleMap:{path:qi(e.appRoot,e.paths.moduleMapPath),sha256:i}},discovery:{diagnostics:{path:qi(e.appRoot,e.paths.diagnosticsPath),sha256:r},manifest:{path:qi(e.appRoot,e.paths.discoveryManifestPath),sha256:n},sourceGraphHash:Gi(`${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 Wi(e){let t=Vi(e.appRoot),n=Hi(e.diagnostics),r=await Li({compileDirectoryPath:t.compileDirectoryPath,manifest:await Pi(e.manifest)}),i=Ki(r),a=Ki(e.manifest),o=Ki(n),s=Er({manifest:r,moduleMapPath:t.moduleMapPath}),c=Ui({appRoot:e.appRoot,diagnosticsArtifactJson:o,diagnosticsSummary:n.summary,discoveryManifestJson:a,moduleMapSource:s,paths:t}),l=Ki(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 Gi(e){return be(`sha256`).update(e).digest(`hex`)}function Ki(e){return`${JSON.stringify(e,null,2)}\n`}function qi(e,t){return O(fe(C(e),t))}var Ji=class extends Error{result;constructor(e){super(Zi({diagnostics:e.diagnostics,diagnosticsPath:e.paths.diagnosticsPath})),this.name=`CompileAgentError`,this.result=e}};async function Yi(e={}){let t=e.source??I(),n=await jn(e.startPath,{source:t}),r=await On({...n,source:t}),i=await Wi({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 Ji(a);return Xi(r.diagnostics),a}function Xi(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 Zi(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(`- ${
|
|
9
|
-
`)}function Qi(e){return e===`error`?`Error`:`Warning`}const $i=new Map;var V=class{name;codec;constructor(e,t={}){this.name=e,this.codec=t.codec,$i.set(e,this)}};const ea=Symbol.for(`experimental-ash.context-storage`),ta=globalThis;ta[ea]===void 0&&(ta[ea]=new Ce);const na=ta[ea];function H(){let e=na.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 ra(e){return{debug(t,n){la(`debug`,e,t,n)},info(t,n){la(`info`,e,t,n)},warn(t,n){la(`warn`,e,t,n)},error(t,n){la(`error`,e,t,n),da(t,n)}}}function ia(){return crypto.randomUUID()}function aa(e,t){let n={errorId:t??ia(),message:sa(e)},r=oa(e);return r!==void 0&&(n.name=r),n.detail=fa(e),n}function oa(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 sa(e){return f(e)&&!(e instanceof Error)&&typeof e.message==`string`?e.message:Ee(e)}function ca(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:fa(t)})}function la(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,ua(r))}function ua(e){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0){if(r instanceof Error){t[n]=aa(r);continue}t[n]=r}return t}function da(e,t){let n=Te.getActiveSpan();if(n===void 0)return;let r=t?.error;if(r instanceof Error){ca(n,r);return}n.addEvent(e,t?ua(t):void 0)}function fa(e){return pa(De(e,{breakLength:1/0,compact:!1,depth:10,maxStringLength:8192}),16384)}function pa(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 ma(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 ha(e){return e.kind??`unknown`}const ga=`http`,_a={kind:ga},va={kind:`schedule`};new V(`ash.auth`),new V(`ash.initiatorAuth`);const ya=new V(`ash.sessionId`),ba=new V(`ash.continuationToken`);new V(`ash.mode`),new V(`ash.parentSession`),new V(`ash.capabilities`),new V(`ash.sessionPrepared`);const xa=ra(`execution.subagent-adapter`),Sa=new Map;function Ca(e){return Sa.get(e)}function wa(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 Ta={kind:`subagent`,async"input.requested"(e,t){let n=t.state;wa(n)&&await Ea({hookPayload:{callId:n.callId,childContinuationToken:t.ctx.require(ba),childSessionId:t.ctx.require(ya),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 Ea(e){"use step";let t=Ca(e.hookPayload.childContinuationToken);try{if(t!==void 0){t(e.hookPayload);return}await Se(e.parentContinuationToken,e.hookPayload)}catch(t){let n=ia();throw xa.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 U=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)}},Da=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 U(this.registry,n.duplicateMessage??`Duplicate ${this.registry} name "${e}".`,{...n.location,entryName:e});if(this._reserved.has(e))throw new U(this.registry,n.reservedMessage??`${Oa(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 Oa(e){return e.length===0?e:e.charAt(0).toUpperCase()+e.slice(1)}const ka=[_a,Ta,va],Aa=new Set([`kind`,`state`,`deliver`,`contextProviders`,`createAdapterContext`,`fetchFile`]);function ja(e){let t=new Map,n=new Set;for(let e of ka){let r=Na(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=Na(i,e);if(n.has(a)){if(Pa(i))throw new U(`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 Ma(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 Na(e,t){let n=ha(e);if(n===`unknown`)throw new U(`adapter`,"Adapters must declare a non-empty `kind` field.",{entryName:`unknown`,logicalPath:t?.logicalPath,sourceId:t?.sourceId});return n}function Pa(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(!Aa.has(t)&&typeof n==`function`)return!0;return!1}function Fa(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 Ia(e){return e.kind===`disk`?e.appRoot:void 0}function La(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 W(e){let t=Ra(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 Ra(e){let t=e.replaceAll(`\\`,`/`);return t===`/`?t:t.replace(/\/+$/,``)}function za(e){return Oe(e,{prefix:void 0}).message}function Ba(e=`test-session`){return{bundleCache:new Map,bundleCacheKeyBySourceKey:new Map,compiledArtifacts:null,id:e}}const Va=Symbol.for(`experimental-ash.runtime-session-storage`),Ha=Symbol.for(`experimental-ash.runtime-session-default`),G=globalThis;G[Va]===void 0&&(G[Va]=new Ce);const Ua=G[Va];function Wa(){return G[Ha]===void 0&&(G[Ha]=Ba(`process-default`)),G[Ha]}function Ga(){return Ua.getStore()??Wa()}function Ka(){return Ga().compiledArtifacts}const qa=b.object({path:b.string(),sha256:b.string()}).strict(),Ja=b.object({compile:b.object({moduleMap:qa}).strict(),discovery:b.object({diagnostics:qa,manifest:qa,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 Ya=class extends Error{metadataPath;constructor(e,t){super(e),this.name=`LoadCompileMetadataError`,t!==void 0&&(this.metadataPath=t)}};async function Xa(e){let t=e.metadataPath??(e.compiledArtifactsSource.kind===`disk`?W(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 Ya(Qa(e),t)}return Za(n,t)}let n=Ka()?.metadata;return n===void 0?null:Za(n,`bundled compile metadata`)}function Za(e,t){let n=Ja.safeParse(e);if(!n.success)throw new Ya(`Expected "${t}" to contain valid Ash compile metadata. ${za(n.error)}`,t);return n.data}function Qa(e){return e instanceof Error?e.message:`Unknown compile metadata load failure.`}async function $a(e){let t=La(e),n=await eo(e);try{let r=(await Xa({compiledArtifactsSource:e}))?.discovery.sourceGraphHash;return r===void 0||r.length===0?n===void 0?t:`${t}:mtime-${to(n)}`:n===void 0?`${t}:${r}`:`${t}:${r}:mtime-${to(n)}`}catch{return n===void 0?t:`${t}:mtime-${to(n)}`}}async function eo(e){if(e.kind!==`disk`)return;let{stat:t}=await import(`node:fs/promises`),{compileMetadataPath:n}=W(e.appRoot);try{return(await t(n)).mtimeMs}catch{return}}function to(e){return Math.floor(e).toString(36)}const no=`__root__`;function ro(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 io=`bundled compiled manifest`;var ao=class extends Error{manifestPath;constructor(e,t){super(e),this.name=`LoadCompiledManifestError`,t!==void 0&&(this.manifestPath=t)}};async function oo(e){let t=e.manifestPath??(e.compiledArtifactsSource.kind===`disk`?W(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 ao(co(e),t)}return so(n,t)}let n=Ka();if(n!==null)return so(n.manifest,io);throw new ao(`Compiled manifest is unavailable without an app root or bundled compiled artifacts.`,io)}function so(e,t){let n=lr.safeParse(e);if(!n.success)throw new ao(`Expected "${t}" to contain a valid compiled Ash agent manifest. ${za(n.error)}`,t);return n.data}function co(e){return e instanceof Error?e.message:`Unknown manifest load failure.`}const lo=`bundled compiled module map`;var uo=class extends Error{moduleMapPath;constructor(e,t){super(e),this.name=`LoadCompiledModuleMapError`,t!==void 0&&(this.moduleMapPath=t)}};async function fo(e){let t=e.moduleMapPath??(e.compiledArtifactsSource.kind===`disk`?W(e.compiledArtifactsSource.appRoot).moduleMapPath:void 0);if(t!==void 0){let e=ho(t);try{let n=await import(e);return po(n.moduleMap??n.default,t)}catch(e){throw new uo(mo(e),t)}}let n=Ka();if(n!==null)return po(n.moduleMap,lo);throw new uo(`Compiled module map is unavailable without an app root or bundled compiled artifacts.`,lo)}function po(e,t){let n=Tr.safeParse(e);if(!n.success)throw new uo(`Expected "${t}" to export a valid compiled Ash module map. ${za(n.error)}`,t);return n.data}function mo(e){return e instanceof Error?e.message:`Unknown module-map load failure.`}function ho(e){let t=e.replaceAll(`\\`,`/`);return/^[A-Za-z]:\//.test(t)?`file:///${encodeURI(t)}`:t.startsWith(`/`)?`file://${encodeURI(t)}`:t}const K=`/workspace`;function go(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=>_o(e))].join(`
|
|
10
|
-
`)}function
|
|
11
|
-
`)}function
|
|
12
|
-
`)}function
|
|
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.`]:[],...Vo(e.connections),...Ho(e.skills)]}function zo(e){if(e===void 0)return[];let t=e.markdown.trim();return t.length===0?[]:[`Instructions (${e.name})\n${t}`]}function Bo(e){if(e===void 0)return[];let t=vo(e);return t===void 0?[]:[t]}function Vo(e){return!e||e.length===0?[]:[Lo(e)]}function Ho(e){if(!e||e.length===0)return[];let t=go(e);return t===null?[]:[t]}function Uo(e){let t=e.agent,n=Wo(t);return{id:t.config.name,instructions:Ro({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 Wo(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 Go=new Set([`aud`,`exp`,`iat`,`iss`,`jti`,`nbf`,`sub`]);function Ko(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 qo(e){let t=Ko(e);return Object.freeze(Object.fromEntries(Object.entries(t).filter(([e])=>!Go.has(e))))}function Jo(e,t){let n=Ko(e);if(t.subjects!==void 0){let n=typeof e.sub==`string`?e.sub:null;if(n===null||!t.subjects.some(e=>Xo(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 Yo(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=Ko(e.payload);return{attributes:qo(e.payload),authenticator:e.authenticator,claims:r,issuer:t,principalId:`${t}:${n}`,principalType:e.principalType,subject:n}}function Xo(e,t){if(!e.includes(`*`))return e===t;let n=e.replaceAll(/[.+?^${}()|[\]\\]/g,`\\$&`).replaceAll(`*`,`.*`);return RegExp(`^${n}$`).test(t)}const Zo=b.object({issuer:b.string().optional(),jwks_uri:b.string().url()}).passthrough(),Qo=new Map,$o=new Map;async function es(e){let t;try{t=await ts(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&&rs({issuer:e.strategy.issuer,payload:n.payload}),i=r&&is({payload:n.payload});return!r&&!Jo(n.payload,e.strategy)?{kind:`caller-not-allowed`}:{kind:`authenticated`,principal:Yo({authenticator:`oidc`,payload:n.payload,principalType:i?`runtime`:`service`})}}catch{return{kind:`not-authenticated`}}}async function ts(e){let t=await ns(e.discoveryUrl),n=$o.get(t.jwks_uri);if(n!==void 0)return n;let r=ke(new URL(t.jwks_uri));return $o.set(t.jwks_uri,r),r}async function ns(e){let t=Qo.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 Zo.parse(await e.json())}).catch(t=>{throw Qo.delete(e),t});return Qo.set(e,n),await n}function rs(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 is(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 as(e){return{attributes:e.attributes,authenticator:e.authenticator,issuer:e.issuer,principalId:e.principalId,principalType:e.principalType,subject:e.subject}}const q=ra(`auth.vercel-oidc`);async function os(e,t){return e===null||e.length===0?{kind:`not-authenticated`}:await es({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 ss(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 cs(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`,ls(e));return Response.json({code:n,error:r,ok:!1},{headers:a,status:t})}function ls(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}="${us(t)}"`).join(`, `);return`${e.scheme} ${t}`}function us(e){return e.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`)}function ds(){return()=>void 0}async function fs(e,t={}){if(e===null||e.length===0)return q.debug(`Rejected request without a bearer token.`),{ok:!1};let n=ms(e);if(n===null)return q.debug(`Rejected token that failed to decode as a JWT.`),{ok:!1};if(!n.issuer.startsWith(`https://oidc.vercel.com/`))return q.debug(`Rejected token whose issuer is not a Vercel OIDC issuer.`,{issuer:n.issuer}),{ok:!1};if(n.audiences.length===0)return q.debug(`Rejected token with no audience claim.`,{issuer:n.issuer}),{ok:!1};let r=await os(e,{acceptCurrentVercelProject:!0,audiences:n.audiences,issuer:n.issuer,subjects:t.subjects??[]});return r.kind===`authenticated`?(q.debug(`Accepted Vercel OIDC token.`,{issuer:n.issuer,principalType:r.principal.principalType,subject:r.principal.subject}),{ok:!0,sessionAuth:as(r.principal)}):(q.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 ps(e={}){return async t=>{let n=await fs(ss(t.headers.get(`authorization`)),e);return n.ok?n.sessionAuth:null}}function ms(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 hs(e){return Number.isFinite(e)&&Number.isInteger(e)&&e>=0}function gs(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`||!hs(o))throw Error(`AttachmentRef payload "size" must be a non-negative integer. Got: ${JSON.stringify(o)}.`);return{params:a,size:o}}function _s(e){return e instanceof URL&&e.protocol===`ash-attachment:`}function vs(e){return typeof Buffer<`u`&&Buffer.isBuffer(e)||e instanceof Uint8Array||e instanceof ArrayBuffer?e.byteLength:typeof e==`string`?ys(e):_s(e)?gs(e).size??null:e instanceof URL&&e.protocol===`data:`?ys(e.href):null}function ys(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 bs(r);try{return Buffer.byteLength(decodeURIComponent(r),`utf8`)}catch{return Buffer.byteLength(r,`utf8`)}}return/^https?:\/\//.test(e)?null:bs(e)}function bs(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 xs=Object.freeze({allowedMediaTypes:`*`,maxBytes:25*1024*1024});function Ss(e,t=xs){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 Cs(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 ws(e,t){if(!Cs(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=vs(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 Ts(e,t){if(typeof e==`string`)return[];let n=[];for(let r of e){if(r.type!==`file`)continue;let e=ws(r,t);e!==null&&n.push(e)}return n}function Es(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 Ds(e,t){return{method:`POST`,path:e,handler:t}}function Os(e,t){return{method:`GET`,path:e,handler:t}}function ks(e){let t=As(e);return{__kind:`ash:channel`,routes:e.routes,adapter:t,receive:e.receive}}function As(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`],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:ga}:{kind:`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 ma(e)},...a}}function js(e){let t=Ss(e.uploadPolicy);return ks({routes:[Ds(`/ash/v1/session`,async(n,{send:r})=>{let i=await Ms(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=Ns(o);if(s instanceof Response)return s;let c=Ls(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})}),Ds(`/ash/v1/session/:sessionId`,async(n,{send:r,getSession:i,params:a})=>{let o=await Ms(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=Ps(l);if(u instanceof Response)return u;let d=Ls(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})}),Os(`/ash/v1/session/:sessionId/stream`,async(t,{getSession:n,params:r})=>{let i=await Ms(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=zs(t);if(o instanceof Response)return o;try{let e=Bs(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 Ms(e,t){let n=await e(t);return n===null?cs({challenges:[{scheme:`Bearer`}]}):n??null}function Ns(e){let t=Fs(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 Ps(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=Fs(e.message);if(n instanceof Response)return n;let r=Rs(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 Fs(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=Is(n);if(e instanceof Response)return e;t.push(e)}return t}function Is(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 Ls(e,t){if(!e.message)return null;let n=Ts(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:Es(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 Rs(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 zs(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 Bs(e){let t=new TextEncoder;return e.pipeThrough(new TransformStream({transform(e,n){n.enqueue(t.encode(`${JSON.stringify(e)}\n`))}}))}function Vs(){return new Response(`<!doctype html>
|
|
7
|
+
`)}function Mr(e){let t=z(e);return t.segments.length===0?t.root.length===0?`.`:t.root:Ir(t.root,t.segments.slice(0,-1))}function Nr(e,t){let n=z(e),r=z(t);return r.root.length>0?Ir(r.root,r.segments):Ir(n.root,[...n.segments,...r.segments])}function Pr(e,t){let n=z(e),r=z(t);if(n.root!==r.root)return Fr(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 Fr(e){let t=z(e);return Ir(t.root,t.segments)}function z(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 Ir(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 Lr=`ash-model-catalog-cache`,Rr=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(),zr=b.object({slug:b.string().min(1),providers:b.array(Rr).min(1)}).passthrough(),Br=b.object({models:b.array(zr),providerAliases:b.record(b.string(),b.string())}).passthrough();b.object({contextWindowTokens:b.number().int().positive(),maxOutputTokens:b.number().int().positive().optional()}).strict();const Vr=b.object({fetchedAt:b.string(),kind:b.literal(Lr),models:b.array(zr),providerAliases:b.record(b.string(),b.string()),version:b.literal(2)}).strict(),Hr=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 Ur(e){return S(e,`.ash`,`cache`,`model-catalog.json`)}function Wr(e){let t=null,n=null,r=null,i=async()=>(t??=Kr(e),await t),a=async()=>{if(n!==null)throw n;if(r!==null)return await r;r=Gr(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&&Yr(e))return e;try{return await a()}catch{return e===null?null:e}};return{async getModelLimits(e){let t=Xr(e),n=await o();if(n!==null){let e=qr(n.models,t);if(e)for(let t of e.providers){let e=Jr(t);if(e!==null)return e}}return Hr.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=Xr(t);for(let e of n.models)for(let t of e.providers)if(t.provider===i&&Xr(t.providerModelId)===a){let n=Jr(t);if(n!==null)return{slug:e.slug,limits:n}}return null}}}async function Gr(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=Br.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:Lr,models:n.data.models,providerAliases:n.data.providerAliases,version:2};try{let t=Ur(e);await w(S(e,`.ash`,`cache`),{recursive:!0}),await T(t,`${JSON.stringify(r,null,2)}\n`,`utf8`)}catch{}return r}async function Kr(e){try{let t=await ge(Ur(e),`utf8`),n=Vr.safeParse(JSON.parse(t));return n.success?n.data:null}catch(e){return e instanceof Error&&`code`in e&&typeof e.code==`string`&&e.code,null}}function qr(e,t){return e.find(e=>e.slug===t)}function Jr(e){return e.contextWindowTokens===void 0||e.contextWindowTokens<=0?null:{contextWindowTokens:e.contextWindowTokens,...e.maxOutputTokens!==void 0&&e.maxOutputTokens>0&&{maxOutputTokens:e.maxOutputTokens}}}function Yr(e){let t=Date.parse(e.fetchedAt);return Number.isFinite(t)?Date.now()-t<=864e5:!1}function Xr(e){return e.endsWith(`-thinking`)?e.slice(0,-9):e}async function B(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 Zr=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 Qr(e,t){if(e.configModule===void 0)throw new Zr(e.agentId);let n=et(await B({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 $r({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 $r({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 $r(e){if(typeof e.value==`string`)return await ei({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 ei(i,e)}async function ei(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 ti(e){return typeof e==`object`&&!!e&&e.__kind===`ash:channel`}function ni(e,t){if(!ti(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 ri(e){return typeof e==`object`&&!!e&&e.kind===`ash:disabled-channel`}async function ii(e,t){let n=await B({agentRoot:e,kind:`channel`,source:t}),r=j(t.logicalPath).replace(/^channels\//,``);return ri(n)?{kind:`disabled`,name:r,logicalPath:t.logicalPath}:ni(n,`Expected the channel export "${t.exportName??`default`}" from "${t.logicalPath}" to match the public Ash shape.`).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}))}async function ai(e,t){let n=new Map;for(let r of t){let t=await B({agentRoot:e,kind:`channel`,source:r});if(ri(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 oi(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 si(e,t,n=`auth`){let r=oi(e,n);if(r!==void 0)throw Error(`${t} ${r}`);let i=e,a=ci(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 ci(e){if(typeof e!=`object`||!e)return;let t=e.connector;if(!(typeof t!=`string`||t.length===0))return{connector:t}}const li=[`approval`,`auth`,`description`,`headers`,`tools`,`url`],ui=[`completeAuthorization`,`getToken`,`principalType`,`startAuthorization`,`vercelConnect`];function di(e,t){let r=n(e,t);a(r,li,t),fi(r,t),pi(r,t);let i=mi(r,t),o=hi(r,t),s=gi(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 fi(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 pi(e,t){if(typeof e.description!=`string`||e.description.length===0)throw Error(`${t} The "description" field must be a non-empty string.`)}function mi(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,ui,`${t} The "auth" field`),si(r,t)}function hi(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 gi(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?(_i(n.allow,`${t} The "tools.allow"`),{allow:n.allow}):(_i(n.block,`${t} The "tools.block"`),{block:n.block})}function _i(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 vi(e,t){let n=di(await B({agentRoot:e,kind:`connection`,source:t}),`Expected the connection export "${t.exportName??`default`}" from "${t.logicalPath}" to match the public Ash shape.`);return{connectionName:t.connectionName,description:n.description,exportName:t.exportName,logicalPath:t.logicalPath,sourceId:t.sourceId,sourceKind:`module`,url:n.url}}function yi(e){return{exportName:e.exportName,logicalPath:e.logicalPath,slug:j(e.logicalPath).replace(/^hooks\//,``),sourceId:e.sourceId,sourceKind:`module`}}function bi(e,t){let r=n(e,t);a(r,[`backend`,`bootstrap`,`description`,`onSession`],t);let i={};if(r.backend!==void 0&&(i.backend=xi(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 xi(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 Si(e,t){return{description:bi(await B({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 Ci(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 B({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 wi(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 B({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:Ei(t.logicalPath),sourceId:t.sourceId,sourceKind:t.sourceKind};return r.channel!==void 0&&(i.channel=Ti({channel:r.channel,channelIdentityMap:n,logicalPath:t.logicalPath})),i}function Ti(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 Ei(e){return j(e).replace(/^schedules\//,``)}async function Di(e,t){if(t.sourceKind===`skill-package`)return Oi(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 B({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 Oi(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 ki(e){let t=[],n=[];for(let r of e.subagents){let i=await Ai({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 Ai(e){let t=fr(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 ki({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 ji(e){return typeof e==`object`&&!!e&&e.kind===`ash:disabled-tool`}function Mi(e){return e&&typeof e==`object`&&`~standard`in e?e[`~standard`].jsonSchema.input({target:`draft-07`}):JSON.parse(JSON.stringify(e))}function Ni(e,t){if(ji(e))return{kind:`disabled`};let i=n(e,t);a(i,[`description`,`execute`,`inputSchema`,`needsApproval`,`onCompact`],t);let o=i.inputSchema===void 0?null:Mi(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 Pi(e,t){let n=Ni(await B({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 Fi(e){let t={modelCatalog:Wr(e.appRoot)},[n,r]=await Promise.all([Ii(e,t),ki({appRoot:e.appRoot,compileAgentNodeManifest:Ii,context:t,parentNodeId:R,subagents:e.subagents})]);return pr({...n,subagentEdges:r.edges,subagents:r.nodes})}async function Ii(e,t){let n=await Promise.all(e.tools.map(t=>Pi(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=>ii(e.agentRoot,t))),ai(e.agentRoot,e.channels)]),s=a.flat();return ur({agentRoot:e.agentRoot,appRoot:e.appRoot,channels:s,config:await Qr(e,t),connections:await Promise.all(e.connections.map(t=>vi(e.agentRoot,t))),diagnosticsSummary:e.diagnosticsSummary,disabledFrameworkTools:i,hooks:e.hooks.map(e=>yi(e)),sandbox:e.sandbox===null?null:await Si(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=>wi(e.agentRoot,t,o))),skills:await Promise.all(e.skills.map(t=>Di(e.agentRoot,t))),instructions:e.instructions===void 0?void 0:await Ci(e.agentRoot,e.instructions),tools:r})}const Li=`workspace-resources`;async function Ri(e){let t=S(e.compileDirectoryPath,Li);await ve(t,{force:!0,recursive:!0});let n=await Bi({nodeId:R,resourcesRoot:t,manifest:e.manifest}),r=await Promise.all(e.manifest.subagents.map(async e=>({...e,agent:await Bi({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 zi(e,t){return{logicalPath:O(S(Li,t)),rootEntries:dr({sandboxWorkspaces:e.sandboxWorkspaces,skills:e.skills})}}async function Bi(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 Vi({nodeRoot:t,skill:n});return{...e.manifest,workspaceResourceRoot:zi(e.manifest,e.nodeId)}}async function Vi(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 Hi(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 Ui(e){return{diagnostics:[...e],kind:`ash-discovery-diagnostics`,summary:Le(e),version:1}}function Wi(e){let t=v(),n=Ki(e.discoveryManifestJson),r=Ki(e.diagnosticsArtifactJson),i=Ki(e.moduleMapSource);return{compile:{moduleMap:{path:Ji(e.appRoot,e.paths.moduleMapPath),sha256:i}},discovery:{diagnostics:{path:Ji(e.appRoot,e.paths.diagnosticsPath),sha256:r},manifest:{path:Ji(e.appRoot,e.paths.discoveryManifestPath),sha256:n},sourceGraphHash:Ki(`${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 Gi(e){let t=Hi(e.appRoot),n=Ui(e.diagnostics),r=await Ri({compileDirectoryPath:t.compileDirectoryPath,manifest:await Fi(e.manifest)}),i=qi(r),a=qi(e.manifest),o=qi(n),s=Er({manifest:r,moduleMapPath:t.moduleMapPath}),c=Wi({appRoot:e.appRoot,diagnosticsArtifactJson:o,diagnosticsSummary:n.summary,discoveryManifestJson:a,moduleMapSource:s,paths:t}),l=qi(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 Ki(e){return be(`sha256`).update(e).digest(`hex`)}function qi(e){return`${JSON.stringify(e,null,2)}\n`}function Ji(e,t){return O(fe(C(e),t))}var Yi=class extends Error{result;constructor(e){super(Qi({diagnostics:e.diagnostics,diagnosticsPath:e.paths.diagnosticsPath})),this.name=`CompileAgentError`,this.result=e}};async function Xi(e={}){let t=e.source??I(),n=await jn(e.startPath,{source:t}),r=await On({...n,source:t}),i=await Gi({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 Yi(a);return Zi(r.diagnostics),a}function Zi(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 Qi(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(`- ${$i(t.severity)}: ${t.message}`),n.push(` source: ${t.sourcePath}`);return n.join(`
|
|
9
|
+
`)}function $i(e){return e===`error`?`Error`:`Warning`}const ea=new Map;var V=class{name;codec;constructor(e,t={}){this.name=e,this.codec=t.codec,ea.set(e,this)}};const ta=Symbol.for(`experimental-ash.context-storage`),na=globalThis;na[ta]===void 0&&(na[ta]=new Ce);const ra=na[ta];function H(){let e=ra.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 ia(e){return{debug(t,n){ua(`debug`,e,t,n)},info(t,n){ua(`info`,e,t,n)},warn(t,n){ua(`warn`,e,t,n)},error(t,n){ua(`error`,e,t,n),fa(t,n)}}}function aa(){return crypto.randomUUID()}function oa(e,t){let n={errorId:t??aa(),message:ca(e)},r=sa(e);return r!==void 0&&(n.name=r),n.detail=pa(e),n}function sa(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 ca(e){return f(e)&&!(e instanceof Error)&&typeof e.message==`string`?e.message:Ee(e)}function la(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:pa(t)})}function ua(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,da(r))}function da(e){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0){if(r instanceof Error){t[n]=oa(r);continue}t[n]=r}return t}function fa(e,t){let n=Te.getActiveSpan();if(n===void 0)return;let r=t?.error;if(r instanceof Error){la(n,r);return}n.addEvent(e,t?da(t):void 0)}function pa(e){return ma(De(e,{breakLength:1/0,compact:!1,depth:10,maxStringLength:8192}),16384)}function ma(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 ha(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 ga(e){return e.kind??`unknown`}const _a=`http`,va={kind:_a},ya={kind:`schedule`};new V(`ash.auth`),new V(`ash.initiatorAuth`);const ba=new V(`ash.sessionId`),xa=new V(`ash.continuationToken`);new V(`ash.mode`),new V(`ash.parentSession`),new V(`ash.capabilities`),new V(`ash.sessionPrepared`);const Sa=ia(`execution.subagent-adapter`),Ca=new Map;function wa(e){return Ca.get(e)}function Ta(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 Ea={kind:`subagent`,async"input.requested"(e,t){let n=t.state;Ta(n)&&await Da({hookPayload:{callId:n.callId,childContinuationToken:t.ctx.require(xa),childSessionId:t.ctx.require(ba),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 Da(e){"use step";let t=wa(e.hookPayload.childContinuationToken);try{if(t!==void 0){t(e.hookPayload);return}await Se(e.parentContinuationToken,e.hookPayload)}catch(t){let n=aa();throw Sa.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 U=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)}},Oa=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 U(this.registry,n.duplicateMessage??`Duplicate ${this.registry} name "${e}".`,{...n.location,entryName:e});if(this._reserved.has(e))throw new U(this.registry,n.reservedMessage??`${ka(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 ka(e){return e.length===0?e:e.charAt(0).toUpperCase()+e.slice(1)}const Aa=[va,Ea,ya],ja=new Set([`kind`,`state`,`deliver`,`contextProviders`,`createAdapterContext`,`fetchFile`]);function Ma(e){let t=new Map,n=new Set;for(let e of Aa){let r=Pa(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=Pa(i,e);if(n.has(a)){if(Fa(i))throw new U(`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 Na(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 Pa(e,t){let n=ga(e);if(n===`unknown`)throw new U(`adapter`,"Adapters must declare a non-empty `kind` field.",{entryName:`unknown`,logicalPath:t?.logicalPath,sourceId:t?.sourceId});return n}function Fa(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(!ja.has(t)&&typeof n==`function`)return!0;return!1}function Ia(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 La(e){return e.kind===`disk`?e.appRoot:void 0}function Ra(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 W(e){let t=za(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 za(e){let t=e.replaceAll(`\\`,`/`);return t===`/`?t:t.replace(/\/+$/,``)}function Ba(e){return Oe(e,{prefix:void 0}).message}function Va(e=`test-session`){return{bundleCache:new Map,bundleCacheKeyBySourceKey:new Map,compiledArtifacts:null,id:e}}const Ha=Symbol.for(`experimental-ash.runtime-session-storage`),Ua=Symbol.for(`experimental-ash.runtime-session-default`),G=globalThis;G[Ha]===void 0&&(G[Ha]=new Ce);const Wa=G[Ha];function Ga(){return G[Ua]===void 0&&(G[Ua]=Va(`process-default`)),G[Ua]}function Ka(){return Wa.getStore()??Ga()}function qa(){return Ka().compiledArtifacts}const Ja=b.object({path:b.string(),sha256:b.string()}).strict(),Ya=b.object({compile:b.object({moduleMap:Ja}).strict(),discovery:b.object({diagnostics:Ja,manifest:Ja,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 Xa=class extends Error{metadataPath;constructor(e,t){super(e),this.name=`LoadCompileMetadataError`,t!==void 0&&(this.metadataPath=t)}};async function Za(e){let t=e.metadataPath??(e.compiledArtifactsSource.kind===`disk`?W(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 Xa($a(e),t)}return Qa(n,t)}let n=qa()?.metadata;return n===void 0?null:Qa(n,`bundled compile metadata`)}function Qa(e,t){let n=Ya.safeParse(e);if(!n.success)throw new Xa(`Expected "${t}" to contain valid Ash compile metadata. ${Ba(n.error)}`,t);return n.data}function $a(e){return e instanceof Error?e.message:`Unknown compile metadata load failure.`}async function eo(e){let t=Ra(e),n=await to(e);try{let r=(await Za({compiledArtifactsSource:e}))?.discovery.sourceGraphHash;return r===void 0||r.length===0?n===void 0?t:`${t}:mtime-${no(n)}`:n===void 0?`${t}:${r}`:`${t}:${r}:mtime-${no(n)}`}catch{return n===void 0?t:`${t}:mtime-${no(n)}`}}async function to(e){if(e.kind!==`disk`)return;let{stat:t}=await import(`node:fs/promises`),{compileMetadataPath:n}=W(e.appRoot);try{return(await t(n)).mtimeMs}catch{return}}function no(e){return Math.floor(e).toString(36)}const ro=`__root__`;function io(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 ao=`bundled compiled manifest`;var oo=class extends Error{manifestPath;constructor(e,t){super(e),this.name=`LoadCompiledManifestError`,t!==void 0&&(this.manifestPath=t)}};async function so(e){let t=e.manifestPath??(e.compiledArtifactsSource.kind===`disk`?W(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 oo(lo(e),t)}return co(n,t)}let n=qa();if(n!==null)return co(n.manifest,ao);throw new oo(`Compiled manifest is unavailable without an app root or bundled compiled artifacts.`,ao)}function co(e,t){let n=lr.safeParse(e);if(!n.success)throw new oo(`Expected "${t}" to contain a valid compiled Ash agent manifest. ${Ba(n.error)}`,t);return n.data}function lo(e){return e instanceof Error?e.message:`Unknown manifest load failure.`}const uo=`bundled compiled module map`;var fo=class extends Error{moduleMapPath;constructor(e,t){super(e),this.name=`LoadCompiledModuleMapError`,t!==void 0&&(this.moduleMapPath=t)}};async function po(e){let t=e.moduleMapPath??(e.compiledArtifactsSource.kind===`disk`?W(e.compiledArtifactsSource.appRoot).moduleMapPath:void 0);if(t!==void 0){let e=go(t);try{let n=await import(e);return mo(n.moduleMap??n.default,t)}catch(e){throw new fo(ho(e),t)}}let n=qa();if(n!==null)return mo(n.moduleMap,uo);throw new fo(`Compiled module map is unavailable without an app root or bundled compiled artifacts.`,uo)}function mo(e,t){let n=Tr.safeParse(e);if(!n.success)throw new fo(`Expected "${t}" to export a valid compiled Ash module map. ${Ba(n.error)}`,t);return n.data}function ho(e){return e instanceof Error?e.message:`Unknown module-map load failure.`}function go(e){let t=e.replaceAll(`\\`,`/`);return/^[A-Za-z]:\//.test(t)?`file:///${encodeURI(t)}`:t.startsWith(`/`)?`file://${encodeURI(t)}`:t}const K=`/workspace`;function _o(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=>vo(e))].join(`
|
|
10
|
+
`)}function vo(e){return`- ${e.name}: ${e.description} (path: ${K}/skills/${e.name}/SKILL.md)`}function yo(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 \`${K}\`.`,`- Root entries under ${K}/:`,...e.rootEntries.map(e=>` - ${e}`),`- Treat \`${K}\` 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 bo(e){return e instanceof Error&&e.name===`ConnectionAuthorizationRequiredError`}function xo(e){return e instanceof Error&&e.name===`ConnectionAuthorizationFailedError`}function So(e){return e?.startAuthorization!==void 0}const Co=Object.freeze({__ashPlaceholder:`connection-authorization`}),wo=new V(`ash.pendingConnectionToolCalls`);function To(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 Eo(e,t){return`${e}__${t}`}const Do=ia(`framework.connection-search`),Oo=new V(`ash.connectionRegistry`),ko=new V(`ash.pendingConnectionAuthorizations`),Ao=new V(`ash.discoveredConnectionTools`),jo={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 Mo(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(Ao,{byConnection:{}}),e.set(ko,[]),e.set(wo,[]),{}},sourceId:`ash:connection-search-tool`,sourceKind:`module`};async function Mo(e,t){let n=H(),r=n.get(Oo);if(r===void 0)return[];let i=e.limit??10,a=No(e.keywords),o=[],s=[],c=e.connection!==void 0&&e.connection!==``?r.getConnections().filter(t=>t.connectionName===e.connection):r.getConnections(),l={...n.get(Ao)?.byConnection},u=[];for(let e of c){let t;try{t=await r.getClient(e.connectionName).getToolMetadata()}catch(t){if(bo(t)){u.push({connectionName:e.connectionName,description:e.description}),s.push({connection:e.connectionName,description:e.description,needsAuthorization:!0});continue}if(xo(t)){Do.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`;Do.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=Po(a,n);t>0&&o.push({item:{connection:e.connectionName,description:n.description,inputSchema:n.inputSchema,qualifiedName:Eo(e.connectionName,n.name),tool:n.name},score:t})}}n.set(Ao,{byConnection:l});let d=[];if(u.length>0){for(let e of u)Io(n,e);d=u.map(e=>e.connectionName).filter(e=>Fo(r,e))}if(d.length>0&&t?.toolCallId!==void 0){let r=n.get(wo);return n.set(wo,To(r,[{args:e,connectionNames:d,kind:`connection-discover`,toolCallId:t.toolCallId,toolName:`connection_search`}])),Co}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 No(e){return e.toLowerCase().split(/[\s_\-./]+/).filter(e=>e.length>1)}function Po(e,t){let n=No(t.name),r=No(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 Fo(e,t){return e===void 0?!1:So(e.getConnections().find(e=>e.connectionName===t)?.authorization)}function Io(e,t){let n=e.get(ko)??[];n.some(e=>e.connectionName===t.connectionName)||e.set(ko,[...n,t])}const Lo=jo.name;function Ro(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 ${Lo} 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 zo(e){return[...Bo(e.instructions),...Vo(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.`]:[],...Ho(e.connections),...Uo(e.skills)]}function Bo(e){if(e===void 0)return[];let t=e.markdown.trim();return t.length===0?[]:[`Instructions (${e.name})\n${t}`]}function Vo(e){if(e===void 0)return[];let t=yo(e);return t===void 0?[]:[t]}function Ho(e){return!e||e.length===0?[]:[Ro(e)]}function Uo(e){if(!e||e.length===0)return[];let t=_o(e);return t===null?[]:[t]}function Wo(e){let t=e.agent,n=Go(t);return{id:t.config.name,instructions:zo({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 Go(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 Ko=new Set([`aud`,`exp`,`iat`,`iss`,`jti`,`nbf`,`sub`]);function qo(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 Jo(e){let t=qo(e);return Object.freeze(Object.fromEntries(Object.entries(t).filter(([e])=>!Ko.has(e))))}function Yo(e,t){let n=qo(e);if(t.subjects!==void 0){let n=typeof e.sub==`string`?e.sub:null;if(n===null||!t.subjects.some(e=>Zo(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 Xo(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=qo(e.payload);return{attributes:Jo(e.payload),authenticator:e.authenticator,claims:r,issuer:t,principalId:`${t}:${n}`,principalType:e.principalType,subject:n}}function Zo(e,t){if(!e.includes(`*`))return e===t;let n=e.replaceAll(/[.+?^${}()|[\]\\]/g,`\\$&`).replaceAll(`*`,`.*`);return RegExp(`^${n}$`).test(t)}const Qo=b.object({issuer:b.string().optional(),jwks_uri:b.string().url()}).passthrough(),$o=new Map,es=new Map;async function ts(e){let t;try{t=await ns(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&&is({issuer:e.strategy.issuer,payload:n.payload}),i=r&&as({payload:n.payload});return!r&&!Yo(n.payload,e.strategy)?{kind:`caller-not-allowed`}:{kind:`authenticated`,principal:Xo({authenticator:`oidc`,payload:n.payload,principalType:i?`runtime`:`service`})}}catch{return{kind:`not-authenticated`}}}async function ns(e){let t=await rs(e.discoveryUrl),n=es.get(t.jwks_uri);if(n!==void 0)return n;let r=ke(new URL(t.jwks_uri));return es.set(t.jwks_uri,r),r}async function rs(e){let t=$o.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 Qo.parse(await e.json())}).catch(t=>{throw $o.delete(e),t});return $o.set(e,n),await n}function is(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 as(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 os(e){return{attributes:e.attributes,authenticator:e.authenticator,issuer:e.issuer,principalId:e.principalId,principalType:e.principalType,subject:e.subject}}const q=ia(`auth.vercel-oidc`);async function ss(e,t){return e===null||e.length===0?{kind:`not-authenticated`}:await ts({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 cs(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 ls(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`,us(e));return Response.json({code:n,error:r,ok:!1},{headers:a,status:t})}function us(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}="${ds(t)}"`).join(`, `);return`${e.scheme} ${t}`}function ds(e){return e.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`)}function fs(){return()=>void 0}async function ps(e,t={}){if(e===null||e.length===0)return q.debug(`Rejected request without a bearer token.`),{ok:!1};let n=hs(e);if(n===null)return q.debug(`Rejected token that failed to decode as a JWT.`),{ok:!1};if(!n.issuer.startsWith(`https://oidc.vercel.com/`))return q.debug(`Rejected token whose issuer is not a Vercel OIDC issuer.`,{issuer:n.issuer}),{ok:!1};if(n.audiences.length===0)return q.debug(`Rejected token with no audience claim.`,{issuer:n.issuer}),{ok:!1};let r=await ss(e,{acceptCurrentVercelProject:!0,audiences:n.audiences,issuer:n.issuer,subjects:t.subjects??[]});return r.kind===`authenticated`?(q.debug(`Accepted Vercel OIDC token.`,{issuer:n.issuer,principalType:r.principal.principalType,subject:r.principal.subject}),{ok:!0,sessionAuth:os(r.principal)}):(q.debug(`Rejected Vercel OIDC token after verification.`,{audiences:n.audiences,issuer:n.issuer,reason:r.kind,subjectsConfigured:(t.subjects??[]).length>0,...r.kind===`misconfigured`?{detail:r.message}:{}}),{ok:!1})}function ms(e={}){return async t=>{let n=await ps(cs(t.headers.get(`authorization`)),e);return n.ok?n.sessionAuth:null}}function hs(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 gs(e){return Number.isFinite(e)&&Number.isInteger(e)&&e>=0}function _s(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`||!gs(o))throw Error(`AttachmentRef payload "size" must be a non-negative integer. Got: ${JSON.stringify(o)}.`);return{params:a,size:o}}function vs(e){return e instanceof URL&&e.protocol===`ash-attachment:`}function ys(e){return typeof Buffer<`u`&&Buffer.isBuffer(e)||e instanceof Uint8Array||e instanceof ArrayBuffer?e.byteLength:typeof e==`string`?bs(e):vs(e)?_s(e).size??null:e instanceof URL&&e.protocol===`data:`?bs(e.href):null}function bs(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 xs(r);try{return Buffer.byteLength(decodeURIComponent(r),`utf8`)}catch{return Buffer.byteLength(r,`utf8`)}}return/^https?:\/\//.test(e)?null:xs(e)}function xs(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 Ss=Object.freeze({allowedMediaTypes:`*`,maxBytes:25*1024*1024});function Cs(e,t=Ss){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 ws(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 Ts(e,t){if(!ws(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=ys(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 Es(e,t){if(typeof e==`string`)return[];let n=[];for(let r of e){if(r.type!==`file`)continue;let e=Ts(r,t);e!==null&&n.push(e)}return n}function Ds(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 Os(e,t){return{method:`POST`,path:e,handler:t}}function ks(e,t){return{method:`GET`,path:e,handler:t}}function As(e){let t=js(e);return{__kind:`ash:channel`,routes:e.routes,adapter:t,receive:e.receive}}function js(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`],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:_a}:{kind:`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 ha(e)},...a}}function Ms(e){let t=Cs(e.uploadPolicy);return As({routes:[Os(`/ash/v1/session`,async(n,{send:r})=>{let i=await Ns(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=Ps(o);if(s instanceof Response)return s;let c=Rs(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})}),Os(`/ash/v1/session/:sessionId`,async(n,{send:r,getSession:i,params:a})=>{let o=await Ns(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=Fs(l);if(u instanceof Response)return u;let d=Rs(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})}),ks(`/ash/v1/session/:sessionId/stream`,async(t,{getSession:n,params:r})=>{let i=await Ns(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=Bs(t);if(o instanceof Response)return o;try{let e=Vs(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 Ns(e,t){let n=await e(t);return n===null?ls({challenges:[{scheme:`Bearer`}]}):n??null}function Ps(e){let t=Is(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 Fs(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=Is(e.message);if(n instanceof Response)return n;let r=zs(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 Is(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=Ls(n);if(e instanceof Response)return e;t.push(e)}return t}function Ls(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 Rs(e,t){if(!e.message)return null;let n=Es(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:Ds(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 zs(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 Bs(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 Vs(e){let t=new TextEncoder;return e.pipeThrough(new TransformStream({transform(e,n){n.enqueue(t.encode(`${JSON.stringify(e)}\n`))}}))}function Hs(){return new Response(`<!doctype html>
|
|
14
14
|
<html lang="en">
|
|
15
15
|
<head>
|
|
16
16
|
<meta charset="utf-8" />
|
|
@@ -62,27 +62,27 @@ A single tool or subagent call runs as one serial action. If you call multiple i
|
|
|
62
62
|
<p>You can close this tab and return to your app.</p>
|
|
63
63
|
</main>
|
|
64
64
|
</body>
|
|
65
|
-
</html>`,{headers:{"cache-control":`no-store`,"content-type":`text/html; charset=utf-8`},status:200})}const
|
|
66
|
-
`),r=
|
|
67
|
-
`),outputLines:a.length,totalLines:r,truncated:a.length<r}}function
|
|
65
|
+
</html>`,{headers:{"cache-control":`no-store`,"content-type":`text/html; charset=utf-8`},status:200})}const Us=[`GET`,`POST`];function Ws(){return Us.map(e=>Ks(e))}function Gs(){return new Set(Us.map(qs))}function Ks(e){let t=qs(e);return{name:t,method:e,urlPath:se,fetch:Js,logicalPath:`framework://channels/${t}`,sourceId:`ash:framework:connection-callback-${e.toLowerCase()}`,sourceKind:`module`}}function qs(e){return`.well-known/ash/v1/connections/callback/${e.toLowerCase()}`}async function Js(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 Ys(e);try{await Se(r,i)}catch{return Response.json({error:`Connection callback not pending.`,ok:!1},{status:404})}return Hs()}async function Ys(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 Xs(){let e=Ms({auth:Qs()}),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(...Ws()),t}function Zs(){return new Set([`ash`,...Gs()])}function Qs(){return process.env.VERCEL?ms():fs()}const $s=oe.omit({action:!0,display:!0,requestId:!0}),{$schema:ec,...tc}=b.toJSONSchema($s),nc={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:tc,logicalPath:`ash:framework/ask-question`,name:`ask_question`,sourceId:`ash:ask-question-tool`,sourceKind:`module`};async function J(){let e=H().get(Yu);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 rc(e){if(!e.startsWith(`/`))throw Error(`filePath must be an absolute path. Received: "${e}". Use an absolute path such as /workspace/foo.ts.`)}function ic(e){return oc(e,`head`)}function ac(e){return oc(e,`tail`)}function oc(e,t){let n=e.split(`
|
|
66
|
+
`),r=cc(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=sc(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 sc(e){return e.length<=2e3?e:e.slice(0,2e3)+` [truncated]`}function cc(e){return e.length>0&&e[e.length-1]===``?e.length-1:e.length}async function lc(e){let t=await(await J()).runCommand(e.command),n=ac(t.stdout),r=ac(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 uc={additionalProperties:!1,properties:{command:{description:`The shell command to execute.`,type:`string`}},required:[`command`],type:`object`};async function dc(e){return lc(e)}const fc={description:`Execute a shell command in the shared workspace environment.`,execute:dc,inputSchema:uc,logicalPath:`ash:framework/bash`,name:`bash`,sourceId:`ash:bash-tool`,sourceKind:`module`},pc=new V(`ash.readFile`);function Y(e){return de.normalize(e)}function mc(e){return e}function hc(e){let t=be(`sha256`).update(e.content,`utf8`).digest(`hex`);return{byteLength:Buffer.byteLength(e.content,`utf8`),contentHash:t,filePath:e.filePath}}function gc(e,t,n){let r=e.ensure(pc,()=>({byTarget:{}}));e.set(pc,{byTarget:{...r.byTarget,[t]:n}})}function _c(e){e.set(pc,{byTarget:{}})}const vc=new Map;async function yc(e){let t=vc.get(e.id);if(t!==void 0)return t;let n=bc(e);vc.set(e.id,n);try{return await n}catch{return vc.delete(e.id),!1}}async function bc(e){return(await e.runCommand(`command -v rg >/dev/null 2>&1`)).exitCode===0}function X(e){return`'${e.replace(/'/g,`'\\''`)}'`}async function xc(e){let t=e.path??`/workspace`;rc(t);let n=Y(t),r=Math.min(Math.max(1,e.limit??100),1e3),i=await J(),a=await yc(i)?Sc({normalizedPath:n,pattern:e.pattern}):Cc({normalizedPath:n,pattern:e.pattern}),o=await i.runCommand(a);if(o.exitCode!==0&&o.exitCode!==1)throw Tc(a,o.exitCode,o.stderr);let s=o.stdout.split(`
|
|
68
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=Y(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
|
|
70
|
-
`),execute:
|
|
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=
|
|
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
|
|
73
|
-
`),execute:
|
|
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=
|
|
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
|
|
76
|
-
`),execute:
|
|
77
|
-
`)}`}function
|
|
78
|
-
`),execute:async e=>
|
|
69
|
+
`),count:u.length,path:n,truncated:p}}function Sc(e){return[`rg --files --hidden`,`--glob '!.git/*'`,`--glob ${X(e.pattern)}`,`-- ${X(e.normalizedPath)}`].join(` `)}function Cc(e){let t=wc(e.pattern),n=t.includes(`/`)?`-path ${X(`*/${t}`)}`:`-name ${X(t)}`;return[`find ${X(e.normalizedPath)}`,`-type f`,`-not -path '*/.git/*'`,n].join(` `)}function wc(e){let t=e.replaceAll(`**`,`*`);for(;t.startsWith(`*/`);)t=t.slice(2);return t}function Tc(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 Ec={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 Dc(e){return xc(e)}const Oc={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:Dc,inputSchema:Ec,logicalPath:`ash:framework/glob`,name:`glob`,sourceId:`ash:glob-tool`,sourceKind:`module`};async function kc(e){let t=e.path??`/workspace`;rc(t);let n=Y(t),r=Math.min(Math.max(1,e.limit??100),1e3),i=e.context!==void 0&&e.context>0?e.context:0,a=await J(),o=await yc(a)?Ac({contextLines:i,effectiveLimit:r,glob:e.glob,ignoreCase:e.ignoreCase??!1,literal:e.literal??!1,normalizedPath:n,pattern:e.pattern}):jc({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 Nc(o,s.exitCode,s.stderr);let c=s.stdout;return c.trim().length===0?{content:`No matches found`,matchCount:0,path:n,truncated:!1}:Mc({effectiveLimit:r,normalizedPath:n,stdout:c})}function Ac(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 ${X(e.glob)}`),e.contextLines>0&&t.push(`--context ${e.contextLines}`),t.push(`--max-count ${e.effectiveLimit}`),t.push(`--`),t.push(X(e.pattern)),t.push(X(e.normalizedPath)),t.join(` `)}function jc(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=${X(e.glob)}`),e.contextLines>0&&t.push(`-C ${e.contextLines}`),t.push(`-m ${e.effectiveLimit}`),t.push(`--`),t.push(X(e.pattern)),t.push(X(e.normalizedPath)),t.join(` `)}function Mc(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=sc(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 Nc(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 Pc={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 Fc(e){return kc(e)}const Ic={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:Fc,inputSchema:Pc,logicalPath:`ash:framework/grep`,name:`grep`,sourceId:`ash:grep-tool`,sourceKind:`module`};async function Lc(e){let{filePath:t,offset:n,limit:r}=e;rc(t);let i=await J(),a=Y(t),o=n??1,s=r??2e3;if(o<1)throw Error(`offset must be >= 1. Received: ${o}.`);let c=await i.readFile(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=hc({content:c,filePath:a}),f=mc(a);gc(H(),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}: ${sc(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 Rc={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 zc(e){return Lc(e)}const Bc={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:zc,inputSchema:Rc,logicalPath:`ash:framework/read-file`,name:`read_file`,onCompact({ctx:e}){return _c(e),{}},sourceId:`ash:read-file-tool`,sourceKind:`module`},Vc=/^---\r?\n[\s\S]*?\r?\n---\r?\n?/;function Hc(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 Uc(e,t){Hc(t);let n=await Wc(e),r=Gc(t,`SKILL.md`),i=await n.readFile(r);if(i===null)throw Error(`No skill named "${t}" at ${r}.`);return i.replace(Vc,``)}async function Wc(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 Gc(e,t){return`${K}/skills/${e}/${t}`}async function Kc(e){let t=H().get(Yu);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 Uc(t,n)}const qc={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=>Kc(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`},Jc=new V(`ash.todo`);function Yc(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 Xc(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 Zc(e){let t=H(),{todos:n}=e??{};if(n!==void 0){let e={items:[...n]};return t.set(Jc,e),Xc(e)}return Xc(t.ensure(Jc,()=>({items:[]})))}const Qc={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=>Zc(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(Jc);if(t===void 0||t.items.length===0)return{};let n=Yc(t);return n===void 0?{}:{messages:[{content:n,role:`user`}]}},sourceId:`ash:todo-tool`,sourceKind:`module`};function $c(e){let t=new Me({bulletListMarker:`-`,codeBlockStyle:`fenced`,emDelimiter:`*`,headingStyle:`atx`,hr:`---`});return t.remove([`script`,`style`,`meta`,`link`]),t.turndown(e)}function el(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
79
|
`),t=t.replace(/<br\s*\/?>/gi,`
|
|
80
|
-
`),t=t.replace(/<[^>]+>/g,``),t=
|
|
80
|
+
`),t=t.replace(/<[^>]+>/g,``),t=rl(t),t=t.split(`
|
|
81
81
|
`).map(e=>e.replace(/[ \t]+/g,` `).trim()).join(`
|
|
82
82
|
`).replace(/\n{3,}/g,`
|
|
83
83
|
|
|
84
|
-
`).trim(),t}const
|
|
85
|
-
`),execute:
|
|
86
|
-
`),execute:
|
|
84
|
+
`).trim(),t}const tl={"&":`&`,">":`>`,"<":`<`," ":` `,""":`"`,"'":`'`,"'":`'`,"/":`/`},nl=new RegExp(Object.keys(tl).join(`|`),`gi`);function rl(e){return e.replace(nl,e=>tl[e.toLowerCase()]??e)}const il=5*1024*1024;async function al(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=ol(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)>il)throw Error(`Response too large (exceeds 5 MB limit).`);let u=await c.arrayBuffer();if(u.byteLength>il)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?$c(p):n===`text`&&f?el(p):p;let{output:h,truncated:_}=ic(m);return{content:h,contentType:d,truncated:_,url:t}}function ol(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 sl(e){return al(e)}const cl={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:sl,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`},ll={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 ul(e){let{filePath:t,content:n}=e;rc(t);let r=await J(),i=H(),a=Y(t),o=mc(a),s=await r.readFile(t);if(s===null)return await r.writeFile(t,n),gc(i,o,hc({content:n,filePath:a})),{existed:!1,path:a};let c=i.ensure(pc,()=>({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=hc({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.writeFile(t,n),gc(i,o,hc({content:n,filePath:a})),{existed:!0,path:a}}const dl={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 fl(e){return ul(e)}const pl=[nc,fc,Oc,Ic,Bc,{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:fl,inputSchema:dl,logicalPath:`ash:framework/write-file`,name:`write_file`,sourceId:`ash:write-file-tool`,sourceKind:`module`},Qc,cl,ll,qc,jo],ml=new Map([[jo,e=>e.hasConnections]]);function hl(e){return pl.filter(t=>{let n=ml.get(t);return n===void 0||n(e)})}function gl(){return new Set(pl.map(e=>e.name))}function _l(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 Z=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 vl(e){return{exportName:e.exportName,logicalPath:e.logicalPath,sourceId:e.sourceId,sourceKind:`module`}}async function Q(e){let t=e.nodeId??`__root__`,r=e.moduleMap.nodes[t]?.modules[e.definition.sourceId];if(r===void 0)throw new Z(`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 yl(e,t,n){try{let r=ni(await Q({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=vl({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 Z?t:new Z(`Failed to attach the channel definition from "${e.logicalPath}": ${m(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}async function bl(e,t,r){try{let i=n(await Q({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=si(i.auth,`Connection "${e.connectionName}" at "${e.logicalPath}":`)}catch(t){throw new Z(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 Z?t:new Z(`Failed to resolve connection "${e.connectionName}" from "${e.logicalPath}": ${m(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}async function xl(e,t,r){try{let i=n(await Q({definition:e,kindLabel:`hook`,moduleMap:t,nodeId:r}),Sl(e,`to return an object`)),a={},o={},s=i.lifecycle;if(s!==void 0){let t=n(s,Sl(e,"to expose `lifecycle` as an object"));for(let n of[`session`,`turn`]){let r=t[n];r!==void 0&&(a[n]=l(r,Sl(e,`to provide a function for "lifecycle.${n}"`)))}}let c=i.events;if(c!==void 0){let t=n(c,Sl(e,"to expose `events` as an object"));for(let[n,r]of Object.entries(t))r!==void 0&&(o[n]=l(r,Sl(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 Z?t:new Z(`Failed to attach hook handlers from "${e.logicalPath}": ${m(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}function Sl(e,t){return`Expected the hook export "${e.exportName??`default`}" from "${e.logicalPath}" ${t}.`}var Cl=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}};function wl(e){return{id:e.id,async readFile(t,n){Tl(n);let r=e.resolvePath(t),i=await e.readFileRaw(r);return i===null?null:Dl(i,n)},async readFileBytes(t){let n=e.resolvePath(t);return await e.readFileBytes(n)},resolvePath(t){return e.resolvePath(t)},async runCommand(t,n){return await e.runCommand(t,n)},async writeFile(t,n){let r=e.resolvePath(t);await e.writeFileRaw(r,n)}}}function Tl(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 El(e){let t=[],n=0;for(let r=0;r<e.length;r++)e[r]===`\r`?r+1<e.length&&e[r+1]===`
|
|
87
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 El(e,t){if(t?.startLine===void 0&&t?.endLine===void 0)return e;let n=Tl(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 Dl(){return{name:`local`,async prewarm(e){let t=Nl(rd(e.runtimeContext.appRoot),e.templateKey);if(await Vl(t))return;let n=await Ol({sessionKey:e.templateKey,snapshotPath:t}),r=Cl(Al(n));try{e.bootstrap!==void 0&&await e.bootstrap({use:async()=>r});for(let t of e.seedFiles)await r.writeFile(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=rd(e.runtimeContext.appRoot),n=await zl(Nl(t,e.templateKey));if(n===null)throw new Sl({backendName:`local`,templateKey:e.templateKey});let r=Hl(e.existingMetadata)??Pl(t,e.sessionKey);return await Vl(r)||await Bl(r,n),kl(await Ol({sessionKey:e.sessionKey,snapshotPath:r}))}}}async function Ol(e){let{Bash:t,InMemoryFs:n}=await import(`#compiled/just-bash/index.js`),r=await zl(e.snapshotPath),i=new n(Fl(r));await Il(i),await Ll(i,r?.entries??[]);let a=new t({cwd:K,env:r?.env,fs:i,network:{dangerouslyAllowFullInternetAccess:!0}});return{async captureSnapshot(){let t=await Rl({filesystem:i,sandbox:a});return await Bl(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 ${X(t.workingDirectory)} && ${e} )`,r=a.exec(n),i=t?.abortSignal?await jl(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 kl(e){let t=Cl(Al(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 Al(e){return{id:e.sessionKey,readFileBytes:t=>e.readFileBytes(t),readFileRaw:t=>e.readFileText(t),resolvePath:Ml,runCommand:(t,n)=>e.executeCommand(t,n),writeFileRaw:(t,n)=>e.writeFiles([{path:t,content:n}])}}async function jl(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 Ml(e){return e.startsWith(`/`)?e:`${K}/${e}`}function Nl(e,t){return S(e,`local`,`templates`,`${t}.json`)}function Pl(e,t){return S(e,`local`,`sessions`,`${t}.json`)}function Fl(e){let t={};for(let n of e?.entries??[])n.kind===`file`&&(t[n.path]=Buffer.from(n.contentBase64,`base64`));return t}async function Il(e){await e.mkdir(K,{recursive:!0})}async function Ll(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 Rl(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 zl(e){if(!await Vl(e))return null;let t=JSON.parse(await ge(e,`utf8`));return t.version===1?t:null}async function Bl(e,t){await w(x(e),{recursive:!0}),await T(e,`${JSON.stringify(t,null,2)}\n`)}async function Vl(e){try{return await me(e),!0}catch{return!1}}function Hl(e){let t=e?.snapshotPath;return typeof t==`string`?t:void 0}function Ul(){return Dl()}function Wl(e={}){let t=e.loadSandboxModule??(async()=>await import(`#compiled/@vercel/sandbox/index.js`)),n={timeout:cu},r=new Map;return{name:`vercel`,async create(e){let i=iu(n.tags,e.tags),a;try{a=await Gl({loadSandboxModule:t,prewarmedTemplates:r,templateKey:e.templateKey})}catch(t){throw Sl.is(t)?t:Error(`Failed to read sandbox template "${e.templateKey}": ${su(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}": ${su(t)}`,{cause:t})}return Jl(o,e.sessionKey)},async prewarm(e){let i;try{i=await Kl({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}": ${su(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 Gl(e){let t=e.prewarmedTemplates.get(e.templateKey);if(t!==void 0)return t;let n=await tu(await e.loadSandboxModule(),e.templateKey);if(n===null||typeof n.currentSnapshotId!=`string`)throw new Sl({backendName:`vercel`,templateKey:e.templateKey});return{sandboxName:n.name,snapshotId:n.currentSnapshotId,templateKey:e.templateKey}}async function Kl(e){let t=await e.loadSandboxModule(),n=await tu(t,e.templateKey),r=iu(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 au(n,r);if(typeof n.currentSnapshotId==`string`&&n.currentSnapshotId.length>0)return{sandboxName:n.name,snapshotId:n.currentSnapshotId,templateKey:e.templateKey};await Ql(n,e.createOptions);let i=Cl(Xl(n,e.templateKey));e.bootstrap!==void 0&&await e.bootstrap({use:async()=>i});for(let t of e.seedFiles)await i.writeFile(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=ru(e.existingMetadata)??e.sessionKey,n=await tu(e.sandboxModule,t);if(n!==null)return await au(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 Jl(e,t){return{session:Cl(Xl(e,t)),useSessionFn:async n=>(n!==void 0&&await e.update(n),Yl(e,t)),async captureState(){return{backendName:`vercel`,metadata:{sandboxName:e.name},sessionKey:t}},async dispose(){}}}function Yl(e,t){return{...Cl(Xl(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 Xl(e,t){return{id:t,async readFileBytes(t){let n=await e.readFileToBuffer({path:t});return n===null?null:Buffer.isBuffer(n)?n:Buffer.from(n)},async readFileRaw(t){let n=await e.readFileToBuffer({path:t});return n===null?null:new TextDecoder(`utf-8`,{fatal:!0}).decode(n)},resolvePath:Zl,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 writeFileRaw(t,n){let r=typeof n==`string`?Buffer.from(n,`utf8`):n;await e.writeFiles([{content:r,path:t}])}}}function Zl(e){return e.startsWith(`/`)?e:`${K}/${e}`}async function Ql(e,t){await $l(e,{failureMessage:`Failed to initialize Vercel sandbox workspace.`,script:`mkdir -p ${K} && chown ${eu}:${eu} ${K}`}),t.networkPolicy!==`deny-all`&&await $l(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 $l(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 eu=`vercel-sandbox`;async function tu(e,t){try{return await e.Sandbox.get({name:t})}catch(e){if(nu(e))return null;throw Error(`Failed to look up Vercel sandbox "${t}": ${su(e)}`,{cause:e})}}function nu(e){return e instanceof Error?(e.response?.status??e.cause?.response?.status)===404:!1}function ru(e){let t=e?.sandboxName;return typeof t==`string`?t:void 0}function iu(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>lu)throw Error(`Vercel Sandbox supports at most ${lu} tags. Ash reserves "agent", "channel", and "sessionId"; remove or consolidate custom tags passed to vercelBackend().`);return n}}async function au(e,t){t===void 0||ou(e.tags,t)||await e.update({tags:t})}function ou(e,t){let n=e??{},r=Object.entries(n),i=Object.entries(t);return r.length===i.length?i.every(([e,t])=>n[e]===t):!1}function su(e){return e instanceof Error?e.message:String(e)}const cu=1800*1e3,lu=5;function uu(){return Wl()}function du(){let e;function t(){return e===void 0&&(e=process.env.VERCEL?uu():Ul()),e}return{get name(){return t().name},create(e){return t().create(e)},async prewarm(e){await t().prewarm(e)}}}async function fu(e,t,r){try{let i=n(await Q({definition:e,kindLabel:`sandbox`,moduleMap:t,nodeId:r}),`Expected the sandbox export "${e.exportName??`default`}" from "${e.logicalPath}" to return an object.`);return{backend:pu(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 Z?t:new Z(`Failed to attach the sandbox lifecycle handlers from "${e.logicalPath}": ${m(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}function pu(e,t){if(e===void 0)return du();if(typeof e!=`object`||!e)throw new Z(`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 Z(`Sandbox "${t}" backend is missing a non-empty string "name" identifier.`,{logicalPath:t});if(typeof n.create!=`function`)throw new Z(`Sandbox "${t}" backend is missing a "create" function.`,{logicalPath:t});return n}async function mu(e,t,r){try{let i=n(await Q({definition:e,kindLabel:`tool`,moduleMap:t,nodeId:r}),$(e,`to return an object`)),a=l(i.execute,$(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`,...hu(i,e)}}catch(t){throw t instanceof Z?t:new Z(`Failed to attach the tool execute function from "${e.logicalPath}": ${m(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}function hu(e,t){let n={};e.onCompact!==void 0&&(n.onCompact=l(e.onCompact,$(t,`to provide an onCompact function`))),e.needsApproval!==void 0&&(n.needsApproval=l(e.needsApproval,$(t,`to provide a needsApproval function`)));let r=gu(e,t);return r!==void 0&&(n.retentionPolicy=r),e.inputSchema!==void 0&&_u(e.inputSchema)&&(n.inputStandardSchema=e.inputSchema),n}function gu(e,t){let n=e.retentionPolicy;if(n!==void 0){if(n===`auto`||n===`keep`||typeof n==`function`)return n;throw new Z($(t,`to set retentionPolicy to "auto", "keep", or a function`),{logicalPath:t.logicalPath,sourceId:t.sourceId})}}function $(e,t){return`Expected the tool export "${e.exportName??`default`}" from "${e.logicalPath}" ${t}.`}function _u(e){return typeof e==`object`&&!!e&&`~standard`in e&&typeof e[`~standard`]==`object`}async function vu(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 vl(t,e.moduleMap,e.nodeId))}let i=await Promise.all(e.manifest.tools.map(t=>mu(t,e.moduleMap,e.nodeId))),a=await Promise.all(e.manifest.hooks.map(t=>bl(t,e.moduleMap,e.nodeId))),o=await Promise.all(e.manifest.connections.map(t=>yl(t,e.moduleMap,e.nodeId))),s=e.manifest.sandbox===null?null:await fu(e.manifest.sandbox,e.moduleMap,e.nodeId),c=yu(e.manifest.instructions),l=e.manifest.workspaceResourceRoot,u={channels:n,config:bu(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 yu(e){if(e!==void 0)return{name:e.name,logicalPath:e.logicalPath,markdown:e.markdown,sourceId:e.sourceId,sourceKind:e.sourceKind}}function bu(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=_l(e.config.source)),t}function xu(e){return{sandbox:{definition:e.authoredSandbox??Su(),workspaceResourceRoot:e.workspaceResourceRoot}}}function Su(){return{backend:du(),logicalPath:`ash:framework/default-sandbox`,sourceId:`ash:default-sandbox`,sourceKind:`module`}}const Cu=`load_skill`,wu=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 Tu(e){let t=[],n=new Da(`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 U(`subagent`,`Found multiple runtime subagents mapped to node id "${i.nodeId}".`,{...e,entryName:i.name});let a=Eu(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 Eu(e){return{description:e.description,inputSchema:wu,kind:`subagent`,logicalPath:e.logicalPath,name:e.name,nodeId:e.nodeId,sourceId:e.sourceId}}async function Du(e,t={}){let n=[],r=new Da(`tool`,t.reservedToolNames??[]);for(let t of e.tools){let e=await Ou(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 Ou(e){return{description:e.description,inputSchema:await ku(e),kind:`authored-tool`,logicalPath:e.logicalPath,name:e.name,sourceId:e.sourceId}}async function ku(e){return e.inputSchema}var Au=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 ju(e){let t=new Map,n=Fu(e.manifest),r=new Map(e.manifest.subagents.map(e=>[e.nodeId,e]));return{nodesByNodeId:t,root:await Mu({childNodeIdsByParentNodeId:n,manifest:e.manifest,moduleMap:e.moduleMap,nodeId:R,nodesByNodeId:t,subagentNodesById:r})}}async function Mu(e){let t=Iu(e.nodeId);if(e.nodesByNodeId.has(t))throw new Au(`Found multiple runtime agent nodes for node id "${t}".`,{nodeId:t,sourceId:e.sourceId});let n=await vu({manifest:e.manifest,moduleMap:e.moduleMap,nodeId:e.nodeId}),r=n.connections.length>0,i=ml({hasConnections:r}),a=r?Ru(i,n.connections):i,o=new Set(a.map(e=>e.name)),s=hl(),c=new Set(n.tools.map(e=>e.name));for(let r of n.disabledFrameworkTools)if(!s.has(r))throw new Au(`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 Du({tools:[...a.filter(e=>!c.has(e.name)&&!l.has(e.name)),...n.tools]},{reservedToolNames:o.has(`load_skill`)||c.has(`load_skill`)?[]:[Cu]}),d=new Set(n.channels.map(e=>e.name)),f=Xs();for(let r of n.disabledFrameworkChannels)if(!f.has(r))throw new Au(`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=[...Ys().filter(e=>!d.has(e.name)&&!p.has(e.name)),...n.channels],h=xu({authoredSandbox:n.sandbox,workspaceResourceRoot:n.workspaceResourceRoot}),g=Tu({reservedToolNames:[Cu,...u.preparedTools.map(e=>e.name)],subagents:await Nu({childNodeIdsByParentNodeId:e.childNodeIdsByParentNodeId,moduleMap:e.moduleMap,nodesByNodeId:e.nodesByNodeId,parentNodeId:e.nodeId,subagentNodesById:e.subagentNodesById})}),_={agent:n,channels:m,hookRegistry:gl(n.hooks),nodeId:t,sandboxRegistry:h,sourceId:e.sourceId,subagentRegistry:g,toolRegistry:u,turnAgent:Uo({agent:n,nodeId:t,tools:[...u.preparedTools,...g.preparedTools]})};return e.nodesByNodeId.set(t,_),_}async function Nu(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 Au(`Missing compiled subagent node "${r}" while resolving runtime subagents.`,{nodeId:Iu(e.parentNodeId),sourceId:r});t.push(await Pu({childNodeIdsByParentNodeId:e.childNodeIdsByParentNodeId,moduleMap:e.moduleMap,nodesByNodeId:e.nodesByNodeId,sourceRef:n,subagentNodesById:e.subagentNodesById}))}return t}async function Pu(e){let t={description:e.sourceRef.description,logicalPath:e.sourceRef.logicalPath,name:e.sourceRef.name,nodeId:Iu(e.sourceRef.nodeId),sourceId:e.sourceRef.sourceId,sourceKind:`module`};return await Mu({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 Fu(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 Iu(e){return e===`__root__`?no:e}const Lu=Ao.name;function Ru(e,t){let n=t.map(e=>e.connectionName).join(`, `);return e.map(e=>e.name===Lu?{...e,description:`${e.description} Available connections: ${n}.`}:e)}const zu=process.env.ASH_DISABLE_AGENT_CACHE===`1`;async function Bu(e){let[t,n]=await Promise.all([oo({compiledArtifactsSource:e}),Vu(e)]),r=await ju({manifest:t,moduleMap:n}),i=r.root;return{adapterRegistry:ja({channels:Ku(r)}),compiledArtifactsSource:e,graph:r,hookRegistry:i.hookRegistry,moduleMap:n,resolvedAgent:i.agent,subagentRegistry:i.subagentRegistry,toolRegistry:i.toolRegistry,turnAgent:i.turnAgent}}async function Vu(e){return e.kind===`disk`&&e.moduleMapLoadMode===`authored-source`?await Hu(e):await fo({compiledArtifactsSource:e})}async function Hu(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 Uu(e){if(zu)return Bu(e);let t=Ga(),n=La(e),r=await $a(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=Bu(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 Wu(e){let t=await Uu(e.compiledArtifactsSource);if(e.nodeId===void 0)return t;let n=ro(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 Gu(){let e=Ga();e.bundleCache.clear(),e.bundleCacheKeyBySourceKey.clear()}function Ku(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 V(`ash.channel`,{codec:{serialize(e){return{kind:ha(e),state:e.state?{...e.state}:{}}},deserialize(e,t){let n=t.get(qu);if(n===void 0)throw Error(`Cannot deserialize "ash.channel" before "ash.bundle". The runtime bundle must be present in context.`);return Ma(n.adapterRegistry,e)}}});const qu=new V(`ash.bundle`,{codec:{serialize:e=>({nodeId:e.nodeId,source:e.compiledArtifactsSource}),deserialize:e=>{let{source:t,nodeId:n}=e;return Wu({compiledArtifactsSource:t,nodeId:n})}}});new V(`ash.session`);const Ju=new V(`ash.sandbox`),Yu=v(),Xu={workflowId:`workflow//${Yu.name}@${Yu.version}//workflowEntry`};function Zu(e=process.cwd()){return C(e)}function Qu(e){return be(`sha256`).update(e).update(`\0`).update(Xu.workflowId).digest(`hex`).slice(0,12)}function $u(){return!!process.env.VERCEL}function ed(e,t=`all`){let n=S(e,`.ash`,`nitro`);return t===`all`?n:S(n,t)}function td(e,t){return S(e,`.ash`,`nitro-output`,t)}function nd(e){return S(h(),`.ash`,`workflow-cache`,Qu(e))}function rd(e){return S(e,`.ash`,`sandbox-cache`)}function id(e){return $u()?S(e,`.vercel`,`output`):S(e,`.output`)}function ad(e){return{appRoot:e,outputDir:id(e),workflowId:Xu.workflowId,workflowBuildDir:nd(e),workflowSourceDir:_(`src/execution`)}}export{xr as C,An as D,R as E,Er as S,Sr as T,La as _,nd as a,Zr as b,Xs as c,oo as d,no as f,Ia as g,Fa as h,td as i,Ys as l,W as m,Zu as n,Gu as o,Xa as p,ed as r,ju as s,ad as t,K as u,Ji as v,Cr as w,Or as x,Yi as y};
|
|
88
|
+
`&&(t.push(e.slice(n,r+1)),n=r+1);return n<e.length&&t.push(e.slice(n)),t}function Dl(e,t){if(t?.startLine===void 0&&t?.endLine===void 0)return e;let n=El(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 Ol(){return{name:`local`,async prewarm(e){let t=Pl(id(e.runtimeContext.appRoot),e.templateKey);if(await Hl(t))return;let n=await kl({sessionKey:e.templateKey,snapshotPath:t}),r=wl(jl(n));try{e.bootstrap!==void 0&&await e.bootstrap({use:async()=>r});for(let t of e.seedFiles)await r.writeFile(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=id(e.runtimeContext.appRoot),n=await Bl(Pl(t,e.templateKey));if(n===null)throw new Cl({backendName:`local`,templateKey:e.templateKey});let r=Ul(e.existingMetadata)??Fl(t,e.sessionKey);return await Hl(r)||await Vl(r,n),Al(await kl({sessionKey:e.sessionKey,snapshotPath:r}))}}}async function kl(e){let{Bash:t,InMemoryFs:n}=await import(`#compiled/just-bash/index.js`),r=await Bl(e.snapshotPath),i=new n(Il(r));await Ll(i),await Rl(i,r?.entries??[]);let a=new t({cwd:K,env:r?.env,fs:i,network:{dangerouslyAllowFullInternetAccess:!0}});return{async captureSnapshot(){let t=await zl({filesystem:i,sandbox:a});return await Vl(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 ${X(t.workingDirectory)} && ${e} )`,r=a.exec(n),i=t?.abortSignal?await Ml(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 Al(e){let t=wl(jl(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 jl(e){return{id:e.sessionKey,readFileBytes:t=>e.readFileBytes(t),readFileRaw:t=>e.readFileText(t),resolvePath:Nl,runCommand:(t,n)=>e.executeCommand(t,n),writeFileRaw:(t,n)=>e.writeFiles([{path:t,content:n}])}}async function Ml(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 Nl(e){return e.startsWith(`/`)?e:`${K}/${e}`}function Pl(e,t){return S(e,`local`,`templates`,`${t}.json`)}function Fl(e,t){return S(e,`local`,`sessions`,`${t}.json`)}function Il(e){let t={};for(let n of e?.entries??[])n.kind===`file`&&(t[n.path]=Buffer.from(n.contentBase64,`base64`));return t}async function Ll(e){await e.mkdir(K,{recursive:!0})}async function Rl(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 zl(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 Bl(e){if(!await Hl(e))return null;let t=JSON.parse(await ge(e,`utf8`));return t.version===1?t:null}async function Vl(e,t){await w(x(e),{recursive:!0}),await T(e,`${JSON.stringify(t,null,2)}\n`)}async function Hl(e){try{return await me(e),!0}catch{return!1}}function Ul(e){let t=e?.snapshotPath;return typeof t==`string`?t:void 0}function Wl(){return Ol()}function Gl(e={}){let t=e.loadSandboxModule??(async()=>await import(`#compiled/@vercel/sandbox/index.js`)),n={timeout:lu},r=new Map;return{name:`vercel`,async create(e){let i=au(n.tags,e.tags),a;try{a=await Kl({loadSandboxModule:t,prewarmedTemplates:r,templateKey:e.templateKey})}catch(t){throw Cl.is(t)?t:Error(`Failed to read sandbox template "${e.templateKey}": ${cu(t)}`,{cause:t})}let o;try{o=await Jl({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}": ${cu(t)}`,{cause:t})}return Yl(o,e.sessionKey)},async prewarm(e){let i;try{i=await ql({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}": ${cu(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 Kl(e){let t=e.prewarmedTemplates.get(e.templateKey);if(t!==void 0)return t;let n=await nu(await e.loadSandboxModule(),e.templateKey);if(n===null||typeof n.currentSnapshotId!=`string`)throw new Cl({backendName:`vercel`,templateKey:e.templateKey});return{sandboxName:n.name,snapshotId:n.currentSnapshotId,templateKey:e.templateKey}}async function ql(e){let t=await e.loadSandboxModule(),n=await nu(t,e.templateKey),r=au(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 ou(n,r);if(typeof n.currentSnapshotId==`string`&&n.currentSnapshotId.length>0)return{sandboxName:n.name,snapshotId:n.currentSnapshotId,templateKey:e.templateKey};await $l(n,e.createOptions);let i=wl(Zl(n,e.templateKey));e.bootstrap!==void 0&&await e.bootstrap({use:async()=>i});for(let t of e.seedFiles)await i.writeFile(t.path,t.content);let a=await n.snapshot();return{sandboxName:n.name,snapshotId:a.snapshotId,templateKey:e.templateKey}}async function Jl(e){let t=iu(e.existingMetadata)??e.sessionKey,n=await nu(e.sandboxModule,t);if(n!==null)return await ou(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 Yl(e,t){return{session:wl(Zl(e,t)),useSessionFn:async n=>(n!==void 0&&await e.update(n),Xl(e,t)),async captureState(){return{backendName:`vercel`,metadata:{sandboxName:e.name},sessionKey:t}},async dispose(){}}}function Xl(e,t){return{...wl(Zl(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 Zl(e,t){return{id:t,async readFileBytes(t){let n=await e.readFileToBuffer({path:t});return n===null?null:Buffer.isBuffer(n)?n:Buffer.from(n)},async readFileRaw(t){let n=await e.readFileToBuffer({path:t});return n===null?null:new TextDecoder(`utf-8`,{fatal:!0}).decode(n)},resolvePath:Ql,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 writeFileRaw(t,n){let r=typeof n==`string`?Buffer.from(n,`utf8`):n;await e.writeFiles([{content:r,path:t}])}}}function Ql(e){return e.startsWith(`/`)?e:`${K}/${e}`}async function $l(e,t){await eu(e,{failureMessage:`Failed to initialize Vercel sandbox workspace.`,script:`mkdir -p ${K} && chown ${tu}:${tu} ${K}`}),t.networkPolicy!==`deny-all`&&await eu(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 eu(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 tu=`vercel-sandbox`;async function nu(e,t){try{return await e.Sandbox.get({name:t})}catch(e){if(ru(e))return null;throw Error(`Failed to look up Vercel sandbox "${t}": ${cu(e)}`,{cause:e})}}function ru(e){return e instanceof Error?(e.response?.status??e.cause?.response?.status)===404:!1}function iu(e){let t=e?.sandboxName;return typeof t==`string`?t:void 0}function au(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>uu)throw Error(`Vercel Sandbox supports at most ${uu} tags. Ash reserves "agent", "channel", and "sessionId"; remove or consolidate custom tags passed to vercelBackend().`);return n}}async function ou(e,t){t===void 0||su(e.tags,t)||await e.update({tags:t})}function su(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 cu(e){return e instanceof Error?e.message:String(e)}const lu=1800*1e3,uu=5;function du(){return Gl()}function fu(){let e;function t(){return e===void 0&&(e=process.env.VERCEL?du():Wl()),e}return{get name(){return t().name},create(e){return t().create(e)},async prewarm(e){await t().prewarm(e)}}}async function pu(e,t,r){try{let i=n(await Q({definition:e,kindLabel:`sandbox`,moduleMap:t,nodeId:r}),`Expected the sandbox export "${e.exportName??`default`}" from "${e.logicalPath}" to return an object.`);return{backend:mu(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 Z?t:new Z(`Failed to attach the sandbox lifecycle handlers from "${e.logicalPath}": ${m(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}function mu(e,t){if(e===void 0)return fu();if(typeof e!=`object`||!e)throw new Z(`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 Z(`Sandbox "${t}" backend is missing a non-empty string "name" identifier.`,{logicalPath:t});if(typeof n.create!=`function`)throw new Z(`Sandbox "${t}" backend is missing a "create" function.`,{logicalPath:t});return n}async function hu(e,t,r){try{let i=n(await Q({definition:e,kindLabel:`tool`,moduleMap:t,nodeId:r}),$(e,`to return an object`)),a=l(i.execute,$(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`,...gu(i,e)}}catch(t){throw t instanceof Z?t:new Z(`Failed to attach the tool execute function from "${e.logicalPath}": ${m(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}function gu(e,t){let n={};e.onCompact!==void 0&&(n.onCompact=l(e.onCompact,$(t,`to provide an onCompact function`))),e.needsApproval!==void 0&&(n.needsApproval=l(e.needsApproval,$(t,`to provide a needsApproval function`)));let r=_u(e,t);return r!==void 0&&(n.retentionPolicy=r),e.inputSchema!==void 0&&vu(e.inputSchema)&&(n.inputStandardSchema=e.inputSchema),n}function _u(e,t){let n=e.retentionPolicy;if(n!==void 0){if(n===`auto`||n===`keep`||typeof n==`function`)return n;throw new Z($(t,`to set retentionPolicy to "auto", "keep", or a function`),{logicalPath:t.logicalPath,sourceId:t.sourceId})}}function $(e,t){return`Expected the tool export "${e.exportName??`default`}" from "${e.logicalPath}" ${t}.`}function vu(e){return typeof e==`object`&&!!e&&`~standard`in e&&typeof e[`~standard`]==`object`}async function yu(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 yl(t,e.moduleMap,e.nodeId))}let i=await Promise.all(e.manifest.tools.map(t=>hu(t,e.moduleMap,e.nodeId))),a=await Promise.all(e.manifest.hooks.map(t=>xl(t,e.moduleMap,e.nodeId))),o=await Promise.all(e.manifest.connections.map(t=>bl(t,e.moduleMap,e.nodeId))),s=e.manifest.sandbox===null?null:await pu(e.manifest.sandbox,e.moduleMap,e.nodeId),c=bu(e.manifest.instructions),l=e.manifest.workspaceResourceRoot,u={channels:n,config:xu(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 bu(e){if(e!==void 0)return{name:e.name,logicalPath:e.logicalPath,markdown:e.markdown,sourceId:e.sourceId,sourceKind:e.sourceKind}}function xu(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=vl(e.config.source)),t}function Su(e){return{sandbox:{definition:e.authoredSandbox??Cu(),workspaceResourceRoot:e.workspaceResourceRoot}}}function Cu(){return{backend:fu(),logicalPath:`ash:framework/default-sandbox`,sourceId:`ash:default-sandbox`,sourceKind:`module`}}const wu=`load_skill`,Tu=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 Eu(e){let t=[],n=new Oa(`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 U(`subagent`,`Found multiple runtime subagents mapped to node id "${i.nodeId}".`,{...e,entryName:i.name});let a=Du(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 Du(e){return{description:e.description,inputSchema:Tu,kind:`subagent`,logicalPath:e.logicalPath,name:e.name,nodeId:e.nodeId,sourceId:e.sourceId}}async function Ou(e,t={}){let n=[],r=new Oa(`tool`,t.reservedToolNames??[]);for(let t of e.tools){let e=await ku(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 ku(e){return{description:e.description,inputSchema:await Au(e),kind:`authored-tool`,logicalPath:e.logicalPath,name:e.name,sourceId:e.sourceId}}async function Au(e){return e.inputSchema}var ju=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 Mu(e){let t=new Map,n=Iu(e.manifest),r=new Map(e.manifest.subagents.map(e=>[e.nodeId,e]));return{nodesByNodeId:t,root:await Nu({childNodeIdsByParentNodeId:n,manifest:e.manifest,moduleMap:e.moduleMap,nodeId:R,nodesByNodeId:t,subagentNodesById:r})}}async function Nu(e){let t=Lu(e.nodeId);if(e.nodesByNodeId.has(t))throw new ju(`Found multiple runtime agent nodes for node id "${t}".`,{nodeId:t,sourceId:e.sourceId});let n=await yu({manifest:e.manifest,moduleMap:e.moduleMap,nodeId:e.nodeId}),r=n.connections.length>0,i=hl({hasConnections:r}),a=r?zu(i,n.connections):i,o=new Set(a.map(e=>e.name)),s=gl(),c=new Set(n.tools.map(e=>e.name));for(let r of n.disabledFrameworkTools)if(!s.has(r))throw new ju(`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 Ou({tools:[...a.filter(e=>!c.has(e.name)&&!l.has(e.name)),...n.tools]},{reservedToolNames:o.has(`load_skill`)||c.has(`load_skill`)?[]:[wu]}),d=new Set(n.channels.map(e=>e.name)),f=Zs();for(let r of n.disabledFrameworkChannels)if(!f.has(r))throw new ju(`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=[...Xs().filter(e=>!d.has(e.name)&&!p.has(e.name)),...n.channels],h=Su({authoredSandbox:n.sandbox,workspaceResourceRoot:n.workspaceResourceRoot}),g=Eu({reservedToolNames:[wu,...u.preparedTools.map(e=>e.name)],subagents:await Pu({childNodeIdsByParentNodeId:e.childNodeIdsByParentNodeId,moduleMap:e.moduleMap,nodesByNodeId:e.nodesByNodeId,parentNodeId:e.nodeId,subagentNodesById:e.subagentNodesById})}),_={agent:n,channels:m,hookRegistry:_l(n.hooks),nodeId:t,sandboxRegistry:h,sourceId:e.sourceId,subagentRegistry:g,toolRegistry:u,turnAgent:Wo({agent:n,nodeId:t,tools:[...u.preparedTools,...g.preparedTools]})};return e.nodesByNodeId.set(t,_),_}async function Pu(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 ju(`Missing compiled subagent node "${r}" while resolving runtime subagents.`,{nodeId:Lu(e.parentNodeId),sourceId:r});t.push(await Fu({childNodeIdsByParentNodeId:e.childNodeIdsByParentNodeId,moduleMap:e.moduleMap,nodesByNodeId:e.nodesByNodeId,sourceRef:n,subagentNodesById:e.subagentNodesById}))}return t}async function Fu(e){let t={description:e.sourceRef.description,logicalPath:e.sourceRef.logicalPath,name:e.sourceRef.name,nodeId:Lu(e.sourceRef.nodeId),sourceId:e.sourceRef.sourceId,sourceKind:`module`};return await Nu({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 Iu(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 Lu(e){return e===`__root__`?ro:e}const Ru=jo.name;function zu(e,t){let n=t.map(e=>e.connectionName).join(`, `);return e.map(e=>e.name===Ru?{...e,description:`${e.description} Available connections: ${n}.`}:e)}const Bu=process.env.ASH_DISABLE_AGENT_CACHE===`1`;async function Vu(e){let[t,n]=await Promise.all([so({compiledArtifactsSource:e}),Hu(e)]),r=await Mu({manifest:t,moduleMap:n}),i=r.root;return{adapterRegistry:Ma({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 Hu(e){return e.kind===`disk`&&e.moduleMapLoadMode===`authored-source`?await Uu(e):await po({compiledArtifactsSource:e})}async function Uu(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 Wu(e){if(Bu)return Vu(e);let t=Ka(),n=Ra(e),r=await eo(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=Vu(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 Gu(e){let t=await Wu(e.compiledArtifactsSource);if(e.nodeId===void 0)return t;let n=io(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 Ku(){let e=Ka();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 V(`ash.channel`,{codec:{serialize(e){return{kind:ga(e),state:e.state?{...e.state}:{}}},deserialize(e,t){let n=t.get(Ju);if(n===void 0)throw Error(`Cannot deserialize "ash.channel" before "ash.bundle". The runtime bundle must be present in context.`);return Na(n.adapterRegistry,e)}}});const Ju=new V(`ash.bundle`,{codec:{serialize:e=>({nodeId:e.nodeId,source:e.compiledArtifactsSource}),deserialize:e=>{let{source:t,nodeId:n}=e;return Gu({compiledArtifactsSource:t,nodeId:n})}}});new V(`ash.session`);const Yu=new V(`ash.sandbox`),Xu=v(),Zu={workflowId:`workflow//${Xu.name}@${Xu.version}//workflowEntry`};function Qu(e=process.cwd()){return C(e)}function $u(e){return be(`sha256`).update(e).update(`\0`).update(Zu.workflowId).digest(`hex`).slice(0,12)}function ed(){return!!process.env.VERCEL}function td(e,t=`all`){let n=S(e,`.ash`,`nitro`);return t===`all`?n:S(n,t)}function nd(e,t){return S(e,`.ash`,`nitro-output`,t)}function rd(e){return S(h(),`.ash`,`workflow-cache`,$u(e))}function id(e){return S(e,`.ash`,`sandbox-cache`)}function ad(e){return ed()?S(e,`.vercel`,`output`):S(e,`.output`)}function od(e){return{appRoot:e,outputDir:ad(e),workflowId:Zu.workflowId,workflowBuildDir:rd(e),workflowSourceDir:_(`src/execution`)}}export{xr as C,An as D,R as E,Er as S,Sr as T,Ra as _,rd as a,Zr as b,Zs as c,so as d,ro as f,La as g,Ia as h,nd as i,Xs as l,W as m,Qu as n,Ku as o,Za as p,td as r,Mu as s,od as t,K as u,Yi as v,Cr as w,Or as x,Xi as y};
|