experimental-ash 0.23.0 → 0.24.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -0
- package/dist/docs/internals/hooks.md +13 -16
- package/dist/docs/internals/message-runtime.md +1 -1
- package/dist/docs/public/auth-and-route-protection.md +3 -3
- package/dist/docs/public/typescript-api.md +2 -2
- package/dist/src/channel/types.d.ts +10 -12
- package/dist/src/chunks/{dev-authored-source-watcher-d_35Mp8T.js → dev-authored-source-watcher-B4PaZGUr.js} +1 -1
- package/dist/src/chunks/host-DsW72Q-w.js +65 -0
- package/dist/src/chunks/{paths-YoCQlavu.js → paths-OknjaYR8.js} +24 -24
- package/dist/src/chunks/prewarm-B4YblQ5m.js +6 -0
- package/dist/src/cli/commands/info.js +1 -1
- package/dist/src/cli/run.js +1 -1
- package/dist/src/compiled/.vendor-stamp.json +2 -2
- package/dist/src/compiled/@workflow/core/classify-error.d.ts +4 -3
- package/dist/src/compiled/@workflow/core/encryption.d.ts +7 -1
- package/dist/src/compiled/@workflow/core/index.js +2 -2
- package/dist/src/compiled/@workflow/core/package.json +1 -1
- package/dist/src/compiled/@workflow/core/runtime/constants.d.ts +47 -0
- package/dist/src/compiled/@workflow/core/runtime/replay-budget.d.ts +98 -0
- package/dist/src/compiled/@workflow/core/runtime.js +27 -27
- package/dist/src/compiled/@workflow/core/serialization/types.d.ts +14 -0
- package/dist/src/compiled/@workflow/core/serialization.d.ts +8 -0
- package/dist/src/compiled/@workflow/core/symbols.d.ts +16 -0
- package/dist/src/compiled/@workflow/core/version.d.ts +1 -1
- package/dist/src/compiled/@workflow/core/workflow.js +1 -1
- package/dist/src/compiled/@workflow/errors/error-codes.d.ts +5 -1
- package/dist/src/compiled/@workflow/errors/index.d.ts +15 -1
- package/dist/src/compiled/@workflow/errors/index.js +1 -1
- package/dist/src/compiled/@workflow/errors/package.json +1 -1
- package/dist/src/compiled/_chunks/workflow/{context-errors-zbKocOyk.js → context-errors-Bbvvp-li.js} +2 -2
- package/dist/src/compiled/_chunks/workflow/{dist-0iNBqPYp.js → dist-C7wPwOI9.js} +2 -2
- package/dist/src/compiled/_chunks/workflow/{dist-D774SUM4.js → dist-C_oiE-l7.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/resume-hook-C3VWUPii.js +12 -0
- package/dist/src/compiled/_chunks/workflow/sleep-QTkC1VFe.js +1 -0
- package/dist/src/compiled/_chunks/workflow/{symbols-D-4tVV8x.js → symbols-QezhMuLg.js} +1 -1
- package/dist/src/evals/cli/eval.js +1 -1
- package/dist/src/execution/await-authorization-orchestrator.d.ts +2 -1
- package/dist/src/execution/await-authorization-orchestrator.js +4 -0
- package/dist/src/execution/connection-auth-steps.d.ts +4 -0
- package/dist/src/execution/connection-auth-steps.js +9 -11
- package/dist/src/execution/node-step.d.ts +4 -5
- package/dist/src/execution/subagent-adapter.d.ts +0 -27
- package/dist/src/execution/subagent-adapter.js +2 -66
- package/dist/src/execution/subagent-hitl-proxy.d.ts +2 -2
- package/dist/src/execution/subagent-hitl-proxy.js +2 -2
- package/dist/src/execution/task-mode.d.ts +3 -3
- package/dist/src/execution/task-mode.js +3 -3
- package/dist/src/execution/turn-workflow.d.ts +41 -0
- package/dist/src/execution/turn-workflow.js +96 -0
- package/dist/src/execution/workflow-entry.js +77 -87
- package/dist/src/execution/workflow-errors.d.ts +14 -0
- package/dist/src/execution/workflow-errors.js +54 -0
- package/dist/src/execution/workflow-runtime.d.ts +34 -3
- package/dist/src/execution/workflow-runtime.js +52 -10
- package/dist/src/execution/workflow-steps.d.ts +27 -2
- package/dist/src/execution/workflow-steps.js +31 -26
- package/dist/src/harness/instrumentation-config.js +14 -7
- package/dist/src/harness/messages.d.ts +7 -7
- package/dist/src/harness/messages.js +4 -4
- package/dist/src/harness/runtime-actions.d.ts +4 -4
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/workflow-bundle/workflow-builders.d.ts +1 -1
- package/dist/src/internal/workflow-bundle/workflow-builders.js +20 -8
- package/dist/src/internal/workflow-bundle/workflow-transformer.d.ts +13 -0
- package/dist/src/internal/workflow-bundle/workflow-transformer.js +10 -4
- package/package.json +4 -4
- package/dist/src/chunks/host-tji7W0Nn.js +0 -65
- package/dist/src/chunks/prewarm-6duWvvb5.js +0 -6
- package/dist/src/compiled/_chunks/workflow/resume-hook-CL8Ed91K.js +0 -12
- package/dist/src/compiled/_chunks/workflow/sleep-Dn3i9nxI.js +0 -1
- package/dist/src/execution/continuous-entry.d.ts +0 -59
- package/dist/src/execution/continuous-entry.js +0 -487
- package/dist/src/execution/continuous-runtime.d.ts +0 -17
- package/dist/src/execution/continuous-runtime.js +0 -123
|
@@ -6,12 +6,12 @@ import{i as e}from"./chunk-8L7ocgPr.js";import{t}from"./gray-matter-BxS7ZG-J.js"
|
|
|
6
6
|
`),`${n}})`].join(`
|
|
7
7
|
`)}function Ir(e){let t=z(e);return t.segments.length===0?t.root.length===0?`.`:t.root:Br(t.root,t.segments.slice(0,-1))}function Lr(e,t){let n=z(e),r=z(t);return r.root.length>0?Br(r.root,r.segments):Br(n.root,[...n.segments,...r.segments])}function Rr(e,t){let n=z(e),r=z(t);if(n.root!==r.root)return zr(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 zr(e){let t=z(e);return Br(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 Br(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 Vr=`ash-model-catalog-cache`,Hr=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(),Ur=b.object({slug:b.string().min(1),providers:b.array(Hr).min(1)}).passthrough(),Wr=b.object({models:b.array(Ur),providerAliases:b.record(b.string(),b.string())}).passthrough();b.object({contextWindowTokens:b.number().int().positive(),maxOutputTokens:b.number().int().positive().optional()}).strict();const Gr=b.object({fetchedAt:b.string(),kind:b.literal(Vr),models:b.array(Ur),providerAliases:b.record(b.string(),b.string()),version:b.literal(2)}).strict(),Kr=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 qr(e){return S(e,`.ash`,`cache`,`model-catalog.json`)}function Jr(e){let t=null,n=null,r=null,i=async()=>(t??=Xr(e),await t),a=async()=>{if(n!==null)throw n;if(r!==null)return await r;r=Yr(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&&$r(e))return e;try{return await a()}catch{return e===null?null:e}};return{async getModelLimits(e){let t=ei(e),n=await o();if(n!==null){let e=Zr(n.models,t);if(e)for(let t of e.providers){let e=Qr(t);if(e!==null)return e}}return Kr.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=ei(t);for(let e of n.models)for(let t of e.providers)if(t.provider===i&&ei(t.providerModelId)===a){let n=Qr(t);if(n!==null)return{slug:e.slug,limits:n}}return null}}}async function Yr(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=Wr.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:Vr,models:n.data.models,providerAliases:n.data.providerAliases,version:2};try{let t=qr(e);await w(S(e,`.ash`,`cache`),{recursive:!0}),await T(t,`${JSON.stringify(r,null,2)}\n`,`utf8`)}catch{}return r}async function Xr(e){try{let t=await he(qr(e),`utf8`),n=Gr.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 Zr(e,t){return e.find(e=>e.slug===t)}function Qr(e){return e.contextWindowTokens===void 0||e.contextWindowTokens<=0?null:{contextWindowTokens:e.contextWindowTokens,...e.maxOutputTokens!==void 0&&e.maxOutputTokens>0&&{maxOutputTokens:e.maxOutputTokens}}}function $r(e){let t=Date.parse(e.fetchedAt);return Number.isFinite(t)?Date.now()-t<=864e5:!1}function ei(e){return e.endsWith(`-thinking`)?e.slice(0,-9):e}async function B(e){let t=r(await l(S(e.agentRoot,e.source.logicalPath)),e.source);try{return await s(t)}catch(t){throw Error(`Failed to execute the ${e.kind} export "${e.source.exportName??`default`}" from "${e.source.logicalPath}": ${p(t)}`)}}var ti=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 ni(e,t){if(e.configModule===void 0)throw new ti(e.agentId);let n=it(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 ri({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 ri({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 ri(e){if(typeof e.value==`string`)return await ii({id:ce(e.value),providerOptions:e.providerOptions===void 0?void 0:y(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:ce(n),source:{exportName:t.exportName,sourceKind:`module`,logicalPath:t.logicalPath,sourceId:t.sourceId},providerOptions:e.providerOptions===void 0?void 0:y(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 ii(i,e)}async function ii(e,t){if(t.contextWindowTokens!==void 0)return{...e,contextWindowTokens:t.contextWindowTokens};let n;try{n=await t.modelCatalog.getModelLimits(e.id)}catch(n){if(!t.requireContextWindowTokens)return e;throw Error(`Failed to load AI Gateway model metadata for ${t.purpose} "${e.id}". ${p(n)}`)}if(n===null){if(!t.requireContextWindowTokens)return e;throw Error(`Cannot compile agent compaction because ${t.purpose} "${e.id}" does not have known AI Gateway context window metadata.`)}return{...e,contextWindowTokens:n.contextWindowTokens}}function ai(e){return typeof e==`object`&&!!e&&e.__kind===`ash:channel`}function oi(e,t){if(!ai(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 si(e){return typeof e==`object`&&!!e&&e.kind===`ash:disabled-channel`}async function ci(e,t){let n=await B({agentRoot:e,kind:`channel`,source:t}),r=j(t.logicalPath).replace(/^channels\//,``);if(si(n))return{kind:`disabled`,name:r,logicalPath:t.logicalPath};let i=oi(n,`Expected the channel export "${t.exportName??`default`}" from "${t.logicalPath}" to match the public Ash shape.`);return i.routes.map(e=>({kind:`channel`,name:r,logicalPath:t.logicalPath,method:e.method.toUpperCase(),urlPath:e.path,sourceId:t.sourceId,sourceKind:`module`,exportName:t.exportName,adapterKind:li(i.adapter)}))}function li(e){if(typeof e!=`object`||!e)return;let t=e.kind;return typeof t==`string`&&t.length>0?t:void 0}function ui(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 di(e,t,n=`auth`){let r=ui(e,n);if(r!==void 0)throw Error(`${t} ${r}`);let i=e,a=fi(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 fi(e){if(typeof e!=`object`||!e)return;let t=e.connector;if(!(typeof t!=`string`||t.length===0))return{connector:t}}const pi=[`approval`,`auth`,`description`,`headers`,`tools`,`url`],mi=[`completeAuthorization`,`getToken`,`principalType`,`startAuthorization`,`vercelConnect`];function hi(e,t){let r=c(e,t);n(r,pi,t),gi(r,t),_i(r,t);let i=vi(r,t),a=yi(r,t),o=bi(r,t);if(i!==void 0&&a!==void 0&&typeof a!=`function`&&Object.keys(a).some(e=>e.toLowerCase()===`authorization`))throw Error(`${t} "headers" must not include an "Authorization" key when "auth" is also provided.`);let s={description:r.description,url:r.url};if(i!==void 0&&(s.auth=i),a!==void 0&&(s.headers=a),o!==void 0&&(s.tools=o),r.approval!==void 0){if(typeof r.approval!=`function`)throw Error(`${t} The "approval" field must be a function when provided.`);s.approval=r.approval}return s}function gi(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 _i(e,t){if(typeof e.description!=`string`||e.description.length===0)throw Error(`${t} The "description" field must be a non-empty string.`)}function vi(e,t){if(e.auth===void 0)return;let r=c(e.auth,`${t} The "auth" field must be an object with a "getToken" method.`);return n(r,mi,`${t} The "auth" field`),di(r,t)}function yi(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 bi(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?(xi(n.allow,`${t} The "tools.allow"`),{allow:n.allow}):(xi(n.block,`${t} The "tools.block"`),{block:n.block})}function xi(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 Si(e,t){let n=hi(await B({agentRoot:e,kind:`connection`,source:t}),`Expected the connection export "${t.exportName??`default`}" from "${t.logicalPath}" to match the public Ash shape.`),r={connectionName:t.connectionName,description:n.description,exportName:t.exportName,logicalPath:t.logicalPath,sourceId:t.sourceId,sourceKind:`module`,url:n.url},i=Ci(n.auth);return i!==void 0&&(r.vercelConnect=i),r}function Ci(e){if(typeof e!=`object`||!e)return;let t=e.vercelConnect;if(typeof t!=`object`||!t)return;let n=t.connector;if(!(typeof n!=`string`||n.length===0))return{connector:n}}function wi(e){return{exportName:e.exportName,logicalPath:e.logicalPath,slug:j(e.logicalPath).replace(/^hooks\//,``),sourceId:e.sourceId,sourceKind:`module`}}function Ti(e){let t;function n(){return t===void 0&&(t=e()),t}return{get name(){return n().name},create(e){return n().create(e)},async prewarm(e){await n().prewarm(e)}}}function Ei(e,t){let r=c(e,t);n(r,[`backend`,`bootstrap`,`description`,`onSession`],t);let i={};if(r.backend!==void 0&&(i.backend=Di(r.backend,t)),r.description!==void 0){if(typeof r.description!=`string`)throw Error(`${t} The "description" field must be a string when set.`);i.description=r.description}return r.bootstrap!==void 0&&(i.bootstrap=o(r.bootstrap,t)),r.onSession!==void 0&&(i.onSession=o(r.onSession,t)),i}function Di(e,t){if(typeof e==`function`)return Ti(e);let n=c(e,`${t} The "backend" field must be a SandboxBackend value (use vercelBackend(), localBackend(), or your own factory) or a zero-arg function returning one.`);if(typeof n.name!=`string`||n.name.length===0)throw Error(`${t} The "backend" value must expose a non-empty string "name" identifier.`);if(typeof n.create!=`function`)throw Error(`${t} The "backend" value must expose a "create" function.`);if(n.prewarm!==void 0&&typeof n.prewarm!=`function`)throw Error(`${t} The "backend.prewarm" property must be a function when set.`);return n}async function Oi(e,t){return{description:Ei(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 ki(e,t){let n=t.sourceKind===`markdown`?lt(t.definition,`Expected the compiled instructions definition at "${t.logicalPath}" to match the public Ash shape.`):lt(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 Ai(e,t){let n=t.sourceKind===`markdown`?ft(t.definition,`Expected the compiled schedule definition at "${t.logicalPath}" to match the public Ash shape.`):ft(await B({agentRoot:e,kind:`schedule`,source:t}),`Expected the schedule export "${t.exportName??`default`}" from "${t.logicalPath}" to match the public Ash shape.`),r={cron:n.cron,hasRun:n.run!==void 0,logicalPath:t.logicalPath,name:ji(t.logicalPath),sourceId:t.sourceId,sourceKind:t.sourceKind};return n.markdown===void 0?r:{...r,markdown:n.markdown.trim()}}function ji(e){return j(e).replace(/^schedules\//,``)}async function Mi(e,t){if(t.sourceKind===`skill-package`)return Ni(t);let n=t.sourceKind===`markdown`?ut(t.definition,`Expected the compiled skill definition at "${t.logicalPath}" to match the public Ash shape.`):ut(await B({agentRoot:e,kind:`skill`,source:t}),`Expected the skill export "${t.exportName??`default`}" from "${t.logicalPath}" to match the public Ash shape.`),r={description:n.description,license:n.license,logicalPath:t.logicalPath,markdown:n.markdown,metadata:n.metadata===void 0?void 0:{...n.metadata},name:j(t.logicalPath).replace(/^skills\//,``),sourceId:t.sourceId,sourceKind:t.sourceKind};return n.files!==void 0&&(r.files=n.files),r}function Ni(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 Pi(e){let t=[],n=[];for(let r of e.subagents){let i=await Fi({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 Fi(e){let t=gr(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 Pi({appRoot:e.appRoot,compileAgentNodeManifest:e.compileAgentNodeManifest,context:e.context,parentNodeId:t,subagents:e.source.manifest.subagents}),node:{agent:r,description:i,entryPath:e.source.entryPath,logicalPath:e.source.logicalPath,name:n,nodeId:t,rootPath:e.source.rootPath,sourceId:e.source.sourceId,sourceKind:`module`}}}const Ii=Symbol.for(`experimental-ash.definition-source-registry`),Li=globalThis;Li[Ii]===void 0&&(Li[Ii]=new Map);const Ri=Li[Ii];function zi(e,t){Ri.set(e,t)}function Bi(e){return typeof e==`object`&&!!e&&e.kind===`ash:disabled-tool`}function Vi(e){return e&&typeof e==`object`&&`~standard`in e?e[`~standard`].jsonSchema.input({target:`draft-07`}):JSON.parse(JSON.stringify(e))}function Hi(e,t){if(Bi(e))return{kind:`disabled`};let r=c(e,t);n(r,[`description`,`execute`,`inputSchema`,`needsApproval`,`onCompact`,`retentionPolicy`,`toModelOutput`],t);let i=r.inputSchema===void 0?null:Vi(r.inputSchema),a={description:u(r.description,t),execute:o(r.execute,t),inputSchema:i};if(r.onCompact!==void 0&&o(r.onCompact,t),r.needsApproval!==void 0&&o(r.needsApproval,t),r.retentionPolicy!==void 0){let e=r.retentionPolicy;if(e!==`auto`&&e!==`keep`&&typeof e!=`function`)throw Error(`${t} Expected \`retentionPolicy\` to be "auto", "keep", or a function.`)}return r.toModelOutput!==void 0&&o(r.toModelOutput,t),{kind:`tool`,definition:a}}async function Ui(e,t){let n=Hi(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 Wi(e){let t={modelCatalog:Jr(e.appRoot)},[n,r]=await Promise.all([Gi(e,t),Pi({appRoot:e.appRoot,compileAgentNodeManifest:Gi,context:t,parentNodeId:R,subagents:e.subagents})]);return _r({...n,subagentEdges:r.edges,subagents:r.nodes})}async function Gi(e,t){let n=await Promise.all(e.tools.map(t=>Ui(e.agentRoot,t))),r=[],i=[];for(let e of n)e.kind===`tool`?r.push(e.definition):i.push(e.name);let a=(await Promise.all(e.channels.map(t=>ci(e.agentRoot,t)))).flat();return mr({agentRoot:e.agentRoot,appRoot:e.appRoot,channels:a,config:await ni(e,t),connections:await Promise.all(e.connections.map(t=>Si(e.agentRoot,t))),diagnosticsSummary:e.diagnosticsSummary,disabledFrameworkTools:i,hooks:e.hooks.map(e=>wi(e)),sandbox:e.sandbox===null?null:await Oi(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=>Ai(e.agentRoot,t))),skills:await Promise.all(e.skills.map(t=>Mi(e.agentRoot,t))),instructions:e.instructions===void 0?void 0:await ki(e.agentRoot,e.instructions),tools:r})}function Ki(e){Ji(e.name);let t=[{content:Te.from(e.markdown,`utf8`),relativePath:`SKILL.md`}];for(let[n,r]of Object.entries(e.files??{}))Yi(n),t.push({content:Xi(r),relativePath:n});return t.sort((e,t)=>Zi(e.relativePath,t.relativePath)),{description:e.description,files:t,license:e.license,markdown:e.markdown,metadata:e.metadata===void 0?void 0:{...e.metadata},name:e.name}}async function qi(e){for(let t of e.skill.files){let n=S(e.rootPath,`skills`,e.skill.name,t.relativePath);await w(x(n),{recursive:!0}),await T(n,t.content)}}function Ji(e){if(e.length===0||e.trim()!==e||e.startsWith(`.`)||e.includes(`/`)||e.includes(`\\`)||e.includes(`..`)||/^[A-Za-z]:/.test(e))throw Error(`Expected skill name to be a non-empty safe path segment without whitespace, separators, "." prefix, or "..".`)}function Yi(e){if(e===`SKILL.md`)throw Error(`Skill package files must not include "SKILL.md"; Ash generates it.`);if(e.length===0||e.startsWith(`/`)||e.includes(`\\`)||/^[A-Za-z]:/.test(e)||e.split(`/`).some(e=>e.length===0||e===`.`||e===`..`))throw Error(`Expected skill package file paths to be relative POSIX paths.`)}function Xi(e){return typeof e==`string`?Te.from(e,`utf8`):Te.from(e)}function Zi(e,t){return e<t?-1:+(e>t)}const Qi=`workspace-resources`;async function $i(e){let t=S(e.compileDirectoryPath,Qi);await _e(t,{force:!0,recursive:!0});let n=await ta({nodeId:R,resourcesRoot:t,manifest:e.manifest}),r=await Promise.all(e.manifest.subagents.map(async e=>({...e,agent:await ta({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 ea(e,t){return{logicalPath:O(S(Qi,t)),rootEntries:hr({sandboxWorkspaces:e.sandboxWorkspaces,skills:e.skills})}}async function ta(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 me(n.sourcePath,t,{recursive:!0});for(let n of e.manifest.skills)await na({nodeRoot:t,skill:n});return{...e.manifest,skills:e.manifest.skills.map(ra),workspaceResourceRoot:ea(e.manifest,e.nodeId)}}async function na(e){let t=S(e.nodeRoot,`skills`,e.skill.name);if(e.skill.sourceKind===`skill-package`){await me(e.skill.rootPath,t,{recursive:!0});return}await qi({rootPath:e.nodeRoot,skill:Ki(e.skill)})}function ra(e){let{files:t,...n}=e;return n}function ia(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 aa(e){return{diagnostics:[...e],kind:`ash-discovery-diagnostics`,summary:Ve(e),version:1}}function oa(e){let t=_(),n=ca(e.discoveryManifestJson),r=ca(e.diagnosticsArtifactJson),i=ca(e.moduleMapSource);return{compile:{moduleMap:{path:ua(e.appRoot,e.paths.moduleMapPath),sha256:i}},discovery:{diagnostics:{path:ua(e.appRoot,e.paths.diagnosticsPath),sha256:r},manifest:{path:ua(e.appRoot,e.paths.discoveryManifestPath),sha256:n},sourceGraphHash:ca(`${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 sa(e){let t=ia(e.appRoot),n=aa(e.diagnostics),r=await $i({compileDirectoryPath:t.compileDirectoryPath,manifest:await Wi(e.manifest)}),i=la(r),a=la(e.manifest),o=la(n),s=Ar({manifest:r,moduleMapPath:t.moduleMapPath}),c=oa({appRoot:e.appRoot,diagnosticsArtifactJson:o,diagnosticsSummary:n.summary,discoveryManifestJson:a,moduleMapSource:s,paths:t}),l=la(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 ca(e){return ye(`sha256`).update(e).digest(`hex`)}function la(e){return`${JSON.stringify(e,null,2)}\n`}function ua(e,t){return O(de(C(e),t))}var da=class extends Error{result;constructor(e){super(ma({diagnostics:e.diagnostics,diagnosticsPath:e.paths.diagnosticsPath})),this.name=`CompileAgentError`,this.result=e}};async function fa(e={}){let t=e.source??I(),n=await In(e.startPath,{source:t}),r=await Nn({...n,source:t}),i=await sa({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(He(r.diagnostics))throw new da(a);return pa(r.diagnostics),a}function pa(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 ma(e){let t=Ve(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
8
|
`);n.push(`Discovery diagnostics:`);for(let t of e.diagnostics)n.push(`- ${ha(t.severity)}: ${t.message}`),n.push(` source: ${t.sourcePath}`);return n.join(`
|
|
9
|
-
`)}function ha(e){return e===`error`?`Error`:`Warning`}const ga=Symbol.for(`experimental-ash.context-key-registry`),_a=globalThis;_a[ga]===void 0&&(_a[ga]=new Map);const va=_a[ga];var V=class{name;codec;constructor(e,t={}){this.name=e,this.codec=t.codec,va.set(e,this)}};const ya=Symbol.for(`experimental-ash.context-storage`),ba=globalThis;ba[ya]===void 0&&(ba[ya]=new De);const xa=ba[ya];function H(){let e=xa.getStore();if(e===void 0)throw Error(`No active Ash context. Call this function only from authored runtime code such as tools, steps, and model callbacks.`);return e}function Sa(e){return{debug(t,n){Oa(`debug`,e,t,n)},info(t,n){Oa(`info`,e,t,n)},warn(t,n){Oa(`warn`,e,t,n)},error(t,n){Oa(`error`,e,t,n),Aa(t,n)}}}function Ca(){return crypto.randomUUID()}function wa(e,t){let n={errorId:t??Ca(),message:Ea(e)},r=Ta(e);return r!==void 0&&(n.name=r),n.detail=ja(e),n}function Ta(e){if(e instanceof Error)return e.name===`Error`?void 0:e.name;if(d(e)&&f(e.name)&&e.name!==`Error`)return e.name}function Ea(e){return d(e)&&!(e instanceof Error)&&typeof e.message==`string`?e.message:Ae(e)}function Da(e,t){let n=t instanceof Error?t.message:Ae(t),r=t instanceof Error?t.name:`Error`;e.setStatus({code:Oe.ERROR,message:n}),e.recordException({message:n,name:r,stack:ja(t)})}function Oa(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,ka(r))}function ka(e){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0){if(r instanceof Error){t[n]=wa(r);continue}t[n]=r}return t}function Aa(e,t){let n=ke.getActiveSpan();if(n===void 0)return;let r=t?.error;if(r instanceof Error){Da(n,r);return}n.addEvent(e,t?ka(t):void 0)}function ja(e){return Ma(je(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 Na(e){if(e.message!==void 0)return{inputResponses:e.inputResponses,message:e.message,modelContext:e.modelContext};if(e.inputResponses!==void 0&&e.inputResponses.length>0)return{inputResponses:e.inputResponses,modelContext:e.modelContext};if(e.modelContext!==void 0&&e.modelContext.length>0)return{modelContext:e.modelContext}}function Pa(e){return e.kind??`unknown`}const Fa={kind:`http`};new V(`ash.auth`),new V(`ash.initiatorAuth`);const Ia=new V(`ash.sessionId`),La=new V(`ash.continuationToken`);new V(`ash.mode`),new V(`ash.parentSession`),new V(`ash.capabilities`),new V(`ash.sessionPrepared`);const Ra={kind:`schedule`},za=Sa(`execution.subagent-adapter`),Ba=new Map;function Va(e){return Ba.get(e)}function Ha(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 Ua={kind:`subagent`,async"input.requested"(e,t){let n=t.state;Ha(n)&&await Wa({hookPayload:{callId:n.callId,childContinuationToken:t.ctx.require(La),childSessionId:t.ctx.require(Ia),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 Wa(e){"use step";let t=Va(e.hookPayload.childContinuationToken);try{if(t!==void 0){t(e.hookPayload);return}await Ee(e.parentContinuationToken,e.hookPayload)}catch(t){let n=Ca();throw za.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)}},Ga=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 qa=[Fa,Ua,Ra],Ja=new Set([`kind`,`state`,`deliver`,`contextProviders`,`createAdapterContext`,`fetchFile`]);function Ya(e){let t=new Map,n=new Set;for(let e of qa){let r=Za(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=Za(i,e);if(n.has(a)){if(Qa(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 Xa(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 Za(e,t){let n=Pa(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 Qa(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 $a(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 eo(e){return e.kind===`disk`?e.appRoot:void 0}function to(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=no(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 no(e){let t=e.replaceAll(`\\`,`/`);return t===`/`?t:t.replace(/\/+$/,``)}function ro(e){return Me(e,{prefix:void 0}).message}function io(e=`test-session`){return{bundleCache:new Map,bundleCacheKeyBySourceKey:new Map,compiledArtifacts:null,id:e}}const ao=Symbol.for(`experimental-ash.runtime-session-storage`),oo=Symbol.for(`experimental-ash.runtime-session-default`),G=globalThis;G[ao]===void 0&&(G[ao]=new De);const so=G[ao];function co(){return G[oo]===void 0&&(G[oo]=io(`process-default`)),G[oo]}function lo(){return so.getStore()??co()}function uo(){return lo().compiledArtifacts}const fo=b.object({path:b.string(),sha256:b.string()}).strict(),po=b.object({compile:b.object({moduleMap:fo}).strict(),discovery:b.object({diagnostics:fo,manifest:fo,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 mo=class extends Error{metadataPath;constructor(e,t){super(e),this.name=`LoadCompileMetadataError`,t!==void 0&&(this.metadataPath=t)}};async function ho(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 mo(_o(e),t)}return go(n,t)}let n=uo()?.metadata;return n===void 0?null:go(n,`bundled compile metadata`)}function go(e,t){let n=po.safeParse(e);if(!n.success)throw new mo(`Expected "${t}" to contain valid Ash compile metadata. ${ro(n.error)}`,t);return n.data}function _o(e){return e instanceof Error?e.message:`Unknown compile metadata load failure.`}async function vo(e){let t=to(e),n=await yo(e);try{let r=(await ho({compiledArtifactsSource:e}))?.discovery.sourceGraphHash;return r===void 0||r.length===0?n===void 0?t:`${t}:mtime-${bo(n)}`:n===void 0?`${t}:${r}`:`${t}:${r}:mtime-${bo(n)}`}catch{return n===void 0?t:`${t}:mtime-${bo(n)}`}}async function yo(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 bo(e){return Math.floor(e).toString(36)}const xo=`__root__`;function So(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 Co=`bundled compiled manifest`;var wo=class extends Error{manifestPath;constructor(e,t){super(e),this.name=`LoadCompiledManifestError`,t!==void 0&&(this.manifestPath=t)}};async function To(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 wo(Do(e),t)}return Eo(n,t)}let n=uo();if(n!==null)return Eo(n.manifest,Co);throw new wo(`Compiled manifest is unavailable without an app root or bundled compiled artifacts.`,Co)}function Eo(e,t){let n=pr.safeParse(e);if(!n.success)throw new wo(`Expected "${t}" to contain a valid compiled Ash agent manifest. ${ro(n.error)}`,t);return n.data}function Do(e){return e instanceof Error?e.message:`Unknown manifest load failure.`}const Oo=`bundled compiled module map`;var ko=class extends Error{moduleMapPath;constructor(e,t){super(e),this.name=`LoadCompiledModuleMapError`,t!==void 0&&(this.moduleMapPath=t)}};async function Ao(e){let t=e.moduleMapPath??(e.compiledArtifactsSource.kind===`disk`?W(e.compiledArtifactsSource.appRoot).moduleMapPath:void 0);if(t!==void 0){let e=No(t);try{let n=await import(e);return jo(n.moduleMap??n.default,t)}catch(e){throw new ko(Mo(e),t)}}let n=uo();if(n!==null)return jo(n.moduleMap,Oo);throw new ko(`Compiled module map is unavailable without an app root or bundled compiled artifacts.`,Oo)}function jo(e,t){let n=kr.safeParse(e);if(!n.success)throw new ko(`Expected "${t}" to export a valid compiled Ash module map. ${ro(n.error)}`,t);return n.data}function Mo(e){return e instanceof Error?e.message:`Unknown module-map load failure.`}function No(e){let t=e.replaceAll(`\\`,`/`);return/^[A-Za-z]:\//.test(t)?`file:///${encodeURI(t)}`:t.startsWith(`/`)?`file://${encodeURI(t)}`:t}const K=`/workspace`;function Po(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=>Fo(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.`]:[],...as(e.connections),...os(e.skills)]}function rs(e){if(e===void 0)return[];let t=e.markdown.trim();return t.length===0?[]:[`Instructions (${e.name})\n${t}`]}function is(e){if(e===void 0)return[];let t=Io(e);return t===void 0?[]:[t]}function as(e){return!e||e.length===0?[]:[ts(e)]}function os(e){if(!e||e.length===0)return[];let t=Po(e);return t===null?[]:[t]}function ss(e){let t=e.agent,n=cs(t);return{id:t.config.name,instructions:ns({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 cs(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 ls=new Set([`aud`,`exp`,`iat`,`iss`,`jti`,`nbf`,`sub`]);function us(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 ds(e){let t=us(e);return Object.freeze(Object.fromEntries(Object.entries(t).filter(([e])=>!ls.has(e))))}function fs(e,t){let n=us(e);if(t.subjects!==void 0){let n=typeof e.sub==`string`?e.sub:null;if(n===null||!t.subjects.some(e=>ms(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 ps(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=us(e.payload);return{attributes:ds(e.payload),authenticator:e.authenticator,claims:r,issuer:t,principalId:`${t}:${n}`,principalType:e.principalType,subject:n}}function ms(e,t){if(!e.includes(`*`))return e===t;let n=e.replaceAll(/[.+?^${}()|[\]\\]/g,`\\$&`).replaceAll(`*`,`.*`);return RegExp(`^${n}$`).test(t)}const hs=b.object({issuer:b.string().optional(),jwks_uri:b.string().url()}).passthrough(),gs=new Map,_s=new Map;async function vs(e){let t;try{t=await ys(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 Fe(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&&xs({issuer:e.strategy.issuer,payload:n.payload}),i=r&&Ss({payload:n.payload});return!r&&!fs(n.payload,e.strategy)?{kind:`caller-not-allowed`}:{kind:`authenticated`,principal:ps({authenticator:`oidc`,payload:n.payload,principalType:i?`runtime`:`service`})}}catch{return{kind:`not-authenticated`}}}async function ys(e){let t=await bs(e.discoveryUrl),n=_s.get(t.jwks_uri);if(n!==void 0)return n;let r=Ne(new URL(t.jwks_uri));return _s.set(t.jwks_uri,r),r}async function bs(e){let t=gs.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 hs.parse(await e.json())}).catch(t=>{throw gs.delete(e),t});return gs.set(e,n),await n}function xs(e){if(!e.issuer.startsWith(`https://oidc.vercel.com`))return!1;let t=process.env.VERCEL_PROJECT_ID?.trim();return t===void 0||t.length===0?!1:typeof e.payload.project_id==`string`&&e.payload.project_id===t}function Ss(e){let t=(process.env.VERCEL_TARGET_ENV?.trim()??process.env.VERCEL_ENV?.trim())?.trim();return t===void 0||t.length===0?!1:typeof e.payload.environment==`string`&&e.payload.environment===t}function Cs(e){return{attributes:e.attributes,authenticator:e.authenticator,issuer:e.issuer,principalId:e.principalId,principalType:e.principalType,subject:e.subject}}const q=Sa(`auth.vercel-oidc`);async function ws(e,t){return e===null||e.length===0?{kind:`not-authenticated`}:await vs({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 Ts(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 Es(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`,Ds(e));return Response.json({code:n,error:r,ok:!1},{headers:a,status:t})}function Ds(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}="${Os(t)}"`).join(`, `);return`${e.scheme} ${t}`}function Os(e){return e.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`)}function ks(){return()=>void 0}async function As(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 ws(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:Cs(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 js(e={}){return async t=>{let n=await As(Ts(t.headers.get(`authorization`)),e);return n.ok?n.sessionAuth:null}}function Ms(e){let t;try{t=Pe(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 Ns(e){return Number.isFinite(e)&&Number.isInteger(e)&&e>=0}function Ps(e){if(e.protocol!==`ash-attachment:`)throw Error(`AttachmentRef URL must use scheme "ash-attachment:". Got: "${e.protocol}".`);let t=e.searchParams.get(`v`);if(t!==`1`)throw Error(`AttachmentRef wire format version must be "1". Got: ${t===null?`missing`:JSON.stringify(t)}.`);let n=e.searchParams.get(`p`);if(n===null||n===``)throw Error(`AttachmentRef URL is missing the required "p" payload query param.`);let r;try{let e=Buffer.from(n,`base64url`).toString(`utf8`);r=JSON.parse(e)}catch(e){throw Error(`AttachmentRef payload is not valid base64url-encoded JSON: ${p(e)}`)}if(typeof r!=`object`||!r||Array.isArray(r))throw Error(`AttachmentRef payload must decode to a JSON object.`);let i=r;if(!(`params`in i))throw Error(`AttachmentRef payload is missing the required "params" field.`);let a=i.params;if(!(`size`in i))return{params:a};let o=i.size;if(typeof o!=`number`||!Ns(o))throw Error(`AttachmentRef payload "size" must be a non-negative integer. Got: ${JSON.stringify(o)}.`);return{params:a,size:o}}function Fs(e){return e instanceof URL&&e.protocol===`ash-attachment:`}function Is(e){return typeof Buffer<`u`&&Buffer.isBuffer(e)||e instanceof Uint8Array||e instanceof ArrayBuffer?e.byteLength:typeof e==`string`?Ls(e):Fs(e)?Ps(e).size??null:e instanceof URL&&e.protocol===`data:`?Ls(e.href):null}function Ls(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 Rs(r);try{return Buffer.byteLength(decodeURIComponent(r),`utf8`)}catch{return Buffer.byteLength(r,`utf8`)}}return/^https?:\/\//.test(e)?null:Rs(e)}function Rs(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 zs=Object.freeze({allowedMediaTypes:`*`,maxBytes:25*1024*1024});function Bs(e,t=zs){if(e===`disabled`)return`disabled`;if(e===void 0)return t;let n=e.maxBytes??t.maxBytes,r=e.allowedMediaTypes??t.allowedMediaTypes;if(n<0||!Number.isFinite(n))throw RangeError(`UploadPolicy.maxBytes must be a non-negative finite number. Received: ${String(n)}.`);return{allowedMediaTypes:r,maxBytes:n}}function Vs(e,t){if(t===`disabled`)return!1;if(t.allowedMediaTypes===`*`)return!0;let n=e.toLowerCase();for(let e of t.allowedMediaTypes){let t=e.toLowerCase();if(t===n)return!0;if(t.endsWith(`/*`)){let e=t.slice(0,-1);if(n.startsWith(e))return!0}}return!1}function Hs(e,t){if(t===`disabled`||!Vs(e.mediaType,t)){let n={allowedMediaTypes:t===`disabled`||t.allowedMediaTypes===`*`?[]:[...t.allowedMediaTypes],kind:`disallowed-media-type`,mediaType:e.mediaType};return e.filename===void 0?n:{...n,filename:e.filename}}let n=Is(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 Us(e,t){if(typeof e==`string`)return[];let n=[];for(let r of e){if(r.type!==`file`)continue;let e=Hs(r,t);e!==null&&n.push(e)}return n}function Ws(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 Gs(e,t){return{method:`POST`,path:e,handler:t}}function Ks(e,t){return{method:`GET`,path:e,handler:t}}function qs(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`,`connection.authorization_pending`,`connection.authorization_completed`],c=e.events;for(let e of s){let t=c?.[e];t&&(o=!0,a[e]=(e,n)=>t(e,n))}return!i&&!o&&!r?{kind:e.kindHint??`http`}:{kind:e.kindHint??`defineChannel`,state:t?{...e.state}:{},fetchFile:e.fetchFile,createAdapterContext(t){let r=t.state,i=t.session;return{...n?e.context(r,i):{},state:r,ctx:t.ctx,session:i}},deliver(e){return Na(e)},...a}}function Ys(e){let t=Bs(e.uploadPolicy);return qs({routes:[Gs(`/ash/v1/session`,async(n,{send:r})=>{let i=await Xs(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=Zs(o);if(s instanceof Response)return s;let c=nc(s,t);if(c!==null)return c;let l=`ash:${crypto.randomUUID()}`,u=await r($s(s),{auth:a,continuationToken:l});return Response.json({continuationToken:u.continuationToken,ok:!0,sessionId:u.id},{headers:{"cache-control":`no-store`,[v]:u.id},status:202})}),Gs(`/ash/v1/session/:sessionId`,async(n,{send:r,getSession:i,params:a})=>{let o=await Xs(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=Qs(l);if(u instanceof Response)return u;let d=nc(u,t);if(d!==null)return d;let f=await r({inputResponses:u.inputResponses,message:u.message,modelContext:u.modelContext},{auth:s,continuationToken:u.continuationToken});return Response.json({ok:!0,sessionId:f.id},{headers:{"cache-control":`no-store`,[v]:f.id},status:200})}),Ks(`/ash/v1/session/:sessionId/stream`,async(t,{getSession:n,params:r})=>{let i=await Xs(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=oc(t);if(o instanceof Response)return o;try{let e=sc(await n(a).getEventStream({startIndex:o}));return new Response(e,{headers:{"cache-control":`no-store`,"content-type":re,[v]:a,[ne]:ee,[ie]:`14`}})}catch{return Response.json({error:`Session not found.`,ok:!1},{status:404})}})]})}async function Xs(e,t){let n=await e(t);return n===null?Es({challenges:[{scheme:`Bearer`}]}):n??null}function Zs(e){let t=ec(e.message);if(t instanceof Response)return t;let n=ic(e.clientContext);return n instanceof Response?n:t===void 0?Response.json({error:`Missing or empty 'message' field.`,ok:!1},{status:400}):{message:t,modelContext:n}}function Qs(e){let t=typeof e.continuationToken==`string`&&e.continuationToken.length>0?e.continuationToken:void 0;if(t===void 0)return Response.json({error:`Missing or empty 'continuationToken' field.`,ok:!1},{status:400});let n=ec(e.message);if(n instanceof Response)return n;let r=rc(e.inputResponses);if(r instanceof Response)return r;let i=ic(e.clientContext);return i instanceof Response?i: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,modelContext:i}}function $s(e){return e.modelContext===void 0?e.message:{message:e.message,modelContext:e.modelContext}}function ec(e){if(e===void 0)return;if(typeof e==`string`)return e.length>0?e:void 0;if(!Array.isArray(e))return Response.json({error:`Expected 'message' to be a string or an array of text/file parts.`,ok:!1},{status:400});if(e.length===0)return;let t=[];for(let n of e){let e=tc(n);if(e instanceof Response)return e;t.push(e)}return t}function tc(e){if(typeof e!=`object`||!e)return Response.json({error:`Expected each message part to be an object.`,ok:!1},{status:400});let t=e;if(t.type===`text`)return typeof t.text!=`string`||t.text.length===0?Response.json({error:`Text parts require a non-empty 'text' string.`,ok:!1},{status:400}):{type:`text`,text:t.text};if(t.type===`file`){if(typeof t.mediaType!=`string`||t.mediaType.length===0)return Response.json({error:`File parts require a non-empty 'mediaType' string.`,ok:!1},{status:400});if(typeof t.data!=`string`)return Response.json({error:`File parts require a 'data' string (base64, data URL, or URL).`,ok:!1},{status:400});let e={type:`file`,mediaType:t.mediaType,data:t.data};return typeof t.filename==`string`&&t.filename.length>0&&(e.filename=t.filename),e}return Response.json({error:`Unsupported message part type "${String(t.type)}". Use 'text' or 'file'.`,ok:!1},{status:400})}function nc(e,t){if(!e.message)return null;let n=Us(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:Ws(r),ok:!1,violations:n.map(e=>e.kind===`too-large`?{byteLength:e.byteLength,filename:e.filename,kind:e.kind,limit:e.limit,mediaType:e.mediaType}:{allowedMediaTypes:e.allowedMediaTypes,filename:e.filename,kind:e.kind,mediaType:e.mediaType})},{status:i})}function rc(e){if(e===void 0)return;if(!Array.isArray(e)||e.length===0)return Response.json({error:`Expected 'inputResponses' to be a non-empty array.`,ok:!1},{status:400});let t=e.filter(te);return t.length===e.length?t:Response.json({error:`Expected every 'inputResponses' entry to match the HITL response schema.`,ok:!1},{status:400})}function ic(e){if(e!==void 0){if(typeof e==`string`)return e.length>0?[ac(e)]:void 0;if(Array.isArray(e))return e.length===0?void 0:e.every(e=>typeof e==`string`&&e.length>0)?e.map(e=>ac(e)):Response.json({error:`Expected 'clientContext' array entries to be non-empty strings.`,ok:!1},{status:400});if(typeof e!=`object`||!e)return Response.json({error:`Expected 'clientContext' to be a string, string array, or JSON object.`,ok:!1},{status:400});try{let t=y(e);return[ac(JSON.stringify(t))]}catch{return Response.json({error:`Expected 'clientContext' to be a JSON-serializable object.`,ok:!1},{status:400})}}}function ac(e){return{role:`user`,content:`Ephemeral client context:
|
|
14
|
-
${e}`}}function
|
|
9
|
+
`)}function ha(e){return e===`error`?`Error`:`Warning`}const ga=Symbol.for(`experimental-ash.context-key-registry`),_a=globalThis;_a[ga]===void 0&&(_a[ga]=new Map);const va=_a[ga];var V=class{name;codec;constructor(e,t={}){this.name=e,this.codec=t.codec,va.set(e,this)}};const ya=Symbol.for(`experimental-ash.context-storage`),ba=globalThis;ba[ya]===void 0&&(ba[ya]=new De);const xa=ba[ya];function H(){let e=xa.getStore();if(e===void 0)throw Error(`No active Ash context. Call this function only from authored runtime code such as tools, steps, and model callbacks.`);return e}function Sa(e){return{debug(t,n){Oa(`debug`,e,t,n)},info(t,n){Oa(`info`,e,t,n)},warn(t,n){Oa(`warn`,e,t,n)},error(t,n){Oa(`error`,e,t,n),Aa(t,n)}}}function Ca(){return crypto.randomUUID()}function wa(e,t){let n={errorId:t??Ca(),message:Ea(e)},r=Ta(e);return r!==void 0&&(n.name=r),n.detail=ja(e),n}function Ta(e){if(e instanceof Error)return e.name===`Error`?void 0:e.name;if(d(e)&&f(e.name)&&e.name!==`Error`)return e.name}function Ea(e){return d(e)&&!(e instanceof Error)&&typeof e.message==`string`?e.message:Ae(e)}function Da(e,t){let n=t instanceof Error?t.message:Ae(t),r=t instanceof Error?t.name:`Error`;e.setStatus({code:Oe.ERROR,message:n}),e.recordException({message:n,name:r,stack:ja(t)})}function Oa(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,ka(r))}function ka(e){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0){if(r instanceof Error){t[n]=wa(r);continue}t[n]=r}return t}function Aa(e,t){let n=ke.getActiveSpan();if(n===void 0)return;let r=t?.error;if(r instanceof Error){Da(n,r);return}n.addEvent(e,t?ka(t):void 0)}function ja(e){return Ma(je(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 Na(e){if(e.message!==void 0)return{inputResponses:e.inputResponses,message:e.message,modelContext:e.modelContext};if(e.inputResponses!==void 0&&e.inputResponses.length>0)return{inputResponses:e.inputResponses,modelContext:e.modelContext};if(e.modelContext!==void 0&&e.modelContext.length>0)return{modelContext:e.modelContext}}function Pa(e){return e.kind??`unknown`}const Fa={kind:`http`};new V(`ash.auth`),new V(`ash.initiatorAuth`);const Ia=new V(`ash.sessionId`),La=new V(`ash.continuationToken`);new V(`ash.mode`),new V(`ash.parentSession`),new V(`ash.capabilities`),new V(`ash.sessionPrepared`);const Ra={kind:`schedule`},za=Sa(`execution.subagent-adapter`);function Ba(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 Va={kind:`subagent`,async"input.requested"(e,t){let n=t.state;Ba(n)&&await Ha({hookPayload:{callId:n.callId,childContinuationToken:t.ctx.require(La),childSessionId:t.ctx.require(Ia),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 Ha(e){"use step";try{await Ee(e.parentContinuationToken,e.hookPayload)}catch(t){let n=Ca();throw za.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)}},Ua=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??`${Wa(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 Wa(e){return e.length===0?e:e.charAt(0).toUpperCase()+e.slice(1)}const Ga=[Fa,Va,Ra],Ka=new Set([`kind`,`state`,`deliver`,`contextProviders`,`createAdapterContext`,`fetchFile`]);function qa(e){let t=new Map,n=new Set;for(let e of Ga){let r=Ya(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=Ya(i,e);if(n.has(a)){if(Xa(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 Ja(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 Ya(e,t){let n=Pa(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 Xa(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(!Ka.has(t)&&typeof n==`function`)return!0;return!1}function Za(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 Qa(e){return e.kind===`disk`?e.appRoot:void 0}function $a(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=eo(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 eo(e){let t=e.replaceAll(`\\`,`/`);return t===`/`?t:t.replace(/\/+$/,``)}function to(e){return Me(e,{prefix:void 0}).message}function no(e=`test-session`){return{bundleCache:new Map,bundleCacheKeyBySourceKey:new Map,compiledArtifacts:null,id:e}}const ro=Symbol.for(`experimental-ash.runtime-session-storage`),io=Symbol.for(`experimental-ash.runtime-session-default`),G=globalThis;G[ro]===void 0&&(G[ro]=new De);const ao=G[ro];function oo(){return G[io]===void 0&&(G[io]=no(`process-default`)),G[io]}function so(){return ao.getStore()??oo()}function co(){return so().compiledArtifacts}const lo=b.object({path:b.string(),sha256:b.string()}).strict(),uo=b.object({compile:b.object({moduleMap:lo}).strict(),discovery:b.object({diagnostics:lo,manifest:lo,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 fo=class extends Error{metadataPath;constructor(e,t){super(e),this.name=`LoadCompileMetadataError`,t!==void 0&&(this.metadataPath=t)}};async function po(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 fo(ho(e),t)}return mo(n,t)}let n=co()?.metadata;return n===void 0?null:mo(n,`bundled compile metadata`)}function mo(e,t){let n=uo.safeParse(e);if(!n.success)throw new fo(`Expected "${t}" to contain valid Ash compile metadata. ${to(n.error)}`,t);return n.data}function ho(e){return e instanceof Error?e.message:`Unknown compile metadata load failure.`}async function go(e){let t=$a(e),n=await _o(e);try{let r=(await po({compiledArtifactsSource:e}))?.discovery.sourceGraphHash;return r===void 0||r.length===0?n===void 0?t:`${t}:mtime-${vo(n)}`:n===void 0?`${t}:${r}`:`${t}:${r}:mtime-${vo(n)}`}catch{return n===void 0?t:`${t}:mtime-${vo(n)}`}}async function _o(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 vo(e){return Math.floor(e).toString(36)}const yo=`__root__`;function bo(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 xo=`bundled compiled manifest`;var So=class extends Error{manifestPath;constructor(e,t){super(e),this.name=`LoadCompiledManifestError`,t!==void 0&&(this.manifestPath=t)}};async function Co(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 So(To(e),t)}return wo(n,t)}let n=co();if(n!==null)return wo(n.manifest,xo);throw new So(`Compiled manifest is unavailable without an app root or bundled compiled artifacts.`,xo)}function wo(e,t){let n=pr.safeParse(e);if(!n.success)throw new So(`Expected "${t}" to contain a valid compiled Ash agent manifest. ${to(n.error)}`,t);return n.data}function To(e){return e instanceof Error?e.message:`Unknown manifest load failure.`}const Eo=`bundled compiled module map`;var Do=class extends Error{moduleMapPath;constructor(e,t){super(e),this.name=`LoadCompiledModuleMapError`,t!==void 0&&(this.moduleMapPath=t)}};async function Oo(e){let t=e.moduleMapPath??(e.compiledArtifactsSource.kind===`disk`?W(e.compiledArtifactsSource.appRoot).moduleMapPath:void 0);if(t!==void 0){let e=jo(t);try{let n=await import(e);return ko(n.moduleMap??n.default,t)}catch(e){throw new Do(Ao(e),t)}}let n=co();if(n!==null)return ko(n.moduleMap,Eo);throw new Do(`Compiled module map is unavailable without an app root or bundled compiled artifacts.`,Eo)}function ko(e,t){let n=kr.safeParse(e);if(!n.success)throw new Do(`Expected "${t}" to export a valid compiled Ash module map. ${to(n.error)}`,t);return n.data}function Ao(e){return e instanceof Error?e.message:`Unknown module-map load failure.`}function jo(e){let t=e.replaceAll(`\\`,`/`);return/^[A-Za-z]:\//.test(t)?`file:///${encodeURI(t)}`:t.startsWith(`/`)?`file://${encodeURI(t)}`:t}const K=`/workspace`;function Mo(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=>No(e))].join(`
|
|
10
|
+
`)}function No(e){return`- ${e.name}: ${e.description} (path: ${K}/skills/${e.name}/SKILL.md)`}function Po(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 Fo(e){return e instanceof Error&&e.name===`ConnectionAuthorizationRequiredError`}function Io(e){return e instanceof Error&&e.name===`ConnectionAuthorizationFailedError`}function Lo(e){return e?.startAuthorization!==void 0}const Ro=Object.freeze({__ashPlaceholder:`connection-authorization`}),zo=new V(`ash.pendingConnectionToolCalls`);function Bo(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 Vo(e,t){return`${e}__${t}`}const Ho=Sa(`framework.connection-search`),Uo=new V(`ash.connectionRegistry`),Wo=new V(`ash.pendingConnectionAuthorizations`),Go=new V(`ash.discoveredConnectionTools`),Ko={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 qo(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(Go,{byConnection:{}}),e.set(Wo,[]),e.set(zo,[]),{}},sourceId:`ash:connection-search-tool`,sourceKind:`module`};async function qo(e,t){let n=H(),r=n.get(Uo);if(r===void 0)return[];let i=e.limit??10,a=Jo(e.keywords),o=[],s=[],c=e.connection!==void 0&&e.connection!==``?r.getConnections().filter(t=>t.connectionName===e.connection):r.getConnections(),l={...n.get(Go)?.byConnection},u=[];for(let e of c){let t;try{t=await r.getClient(e.connectionName).getToolMetadata()}catch(t){if(Fo(t)){u.push({connectionName:e.connectionName,description:e.description}),s.push({connection:e.connectionName,description:e.description,needsAuthorization:!0});continue}if(Io(t)){Ho.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`;Ho.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=Yo(a,n);t>0&&o.push({item:{connection:e.connectionName,description:n.description,inputSchema:n.inputSchema,qualifiedName:Vo(e.connectionName,n.name),tool:n.name},score:t})}}n.set(Go,{byConnection:l});let d=[];if(u.length>0){for(let e of u)Zo(n,e);d=u.map(e=>e.connectionName).filter(e=>Xo(r,e))}if(d.length>0&&t?.toolCallId!==void 0){let r=n.get(zo);return n.set(zo,Bo(r,[{args:e,connectionNames:d,kind:`connection-discover`,toolCallId:t.toolCallId,toolName:`connection_search`}])),Ro}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 Jo(e){return e.toLowerCase().split(/[\s_\-./]+/).filter(e=>e.length>1)}function Yo(e,t){let n=Jo(t.name),r=Jo(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 Xo(e,t){return e===void 0?!1:Lo(e.getConnections().find(e=>e.connectionName===t)?.authorization)}function Zo(e,t){let n=e.get(Wo)??[];n.some(e=>e.connectionName===t.connectionName)||e.set(Wo,[...n,t])}const Qo=Ko.name;function $o(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 ${Qo} 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 es(e){return[...ts(e.instructions),...ns(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.`]:[],...rs(e.connections),...is(e.skills)]}function ts(e){if(e===void 0)return[];let t=e.markdown.trim();return t.length===0?[]:[`Instructions (${e.name})\n${t}`]}function ns(e){if(e===void 0)return[];let t=Po(e);return t===void 0?[]:[t]}function rs(e){return!e||e.length===0?[]:[$o(e)]}function is(e){if(!e||e.length===0)return[];let t=Mo(e);return t===null?[]:[t]}function as(e){let t=e.agent,n=os(t);return{id:t.config.name,instructions:es({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 os(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 ss=new Set([`aud`,`exp`,`iat`,`iss`,`jti`,`nbf`,`sub`]);function cs(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 ls(e){let t=cs(e);return Object.freeze(Object.fromEntries(Object.entries(t).filter(([e])=>!ss.has(e))))}function us(e,t){let n=cs(e);if(t.subjects!==void 0){let n=typeof e.sub==`string`?e.sub:null;if(n===null||!t.subjects.some(e=>fs(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 ds(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=cs(e.payload);return{attributes:ls(e.payload),authenticator:e.authenticator,claims:r,issuer:t,principalId:`${t}:${n}`,principalType:e.principalType,subject:n}}function fs(e,t){if(!e.includes(`*`))return e===t;let n=e.replaceAll(/[.+?^${}()|[\]\\]/g,`\\$&`).replaceAll(`*`,`.*`);return RegExp(`^${n}$`).test(t)}const ps=b.object({issuer:b.string().optional(),jwks_uri:b.string().url()}).passthrough(),ms=new Map,hs=new Map;async function gs(e){let t;try{t=await _s(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 Fe(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&&ys({issuer:e.strategy.issuer,payload:n.payload}),i=r&&bs({payload:n.payload});return!r&&!us(n.payload,e.strategy)?{kind:`caller-not-allowed`}:{kind:`authenticated`,principal:ds({authenticator:`oidc`,payload:n.payload,principalType:i?`runtime`:`service`})}}catch{return{kind:`not-authenticated`}}}async function _s(e){let t=await vs(e.discoveryUrl),n=hs.get(t.jwks_uri);if(n!==void 0)return n;let r=Ne(new URL(t.jwks_uri));return hs.set(t.jwks_uri,r),r}async function vs(e){let t=ms.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 ps.parse(await e.json())}).catch(t=>{throw ms.delete(e),t});return ms.set(e,n),await n}function ys(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 bs(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 xs(e){return{attributes:e.attributes,authenticator:e.authenticator,issuer:e.issuer,principalId:e.principalId,principalType:e.principalType,subject:e.subject}}const q=Sa(`auth.vercel-oidc`);async function Ss(e,t){return e===null||e.length===0?{kind:`not-authenticated`}:await gs({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 ws(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`,Ts(e));return Response.json({code:n,error:r,ok:!1},{headers:a,status:t})}function Ts(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}="${Es(t)}"`).join(`, `);return`${e.scheme} ${t}`}function Es(e){return e.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`)}function Ds(){return()=>void 0}async function Os(e,t={}){if(e===null||e.length===0)return q.debug(`Rejected request without a bearer token.`),{ok:!1};let n=As(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:xs(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 ks(e={}){return async t=>{let n=await Os(Cs(t.headers.get(`authorization`)),e);return n.ok?n.sessionAuth:null}}function As(e){let t;try{t=Pe(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 js(e){return Number.isFinite(e)&&Number.isInteger(e)&&e>=0}function Ms(e){if(e.protocol!==`ash-attachment:`)throw Error(`AttachmentRef URL must use scheme "ash-attachment:". Got: "${e.protocol}".`);let t=e.searchParams.get(`v`);if(t!==`1`)throw Error(`AttachmentRef wire format version must be "1". Got: ${t===null?`missing`:JSON.stringify(t)}.`);let n=e.searchParams.get(`p`);if(n===null||n===``)throw Error(`AttachmentRef URL is missing the required "p" payload query param.`);let r;try{let e=Buffer.from(n,`base64url`).toString(`utf8`);r=JSON.parse(e)}catch(e){throw Error(`AttachmentRef payload is not valid base64url-encoded JSON: ${p(e)}`)}if(typeof r!=`object`||!r||Array.isArray(r))throw Error(`AttachmentRef payload must decode to a JSON object.`);let i=r;if(!(`params`in i))throw Error(`AttachmentRef payload is missing the required "params" field.`);let a=i.params;if(!(`size`in i))return{params:a};let o=i.size;if(typeof o!=`number`||!js(o))throw Error(`AttachmentRef payload "size" must be a non-negative integer. Got: ${JSON.stringify(o)}.`);return{params:a,size:o}}function Ns(e){return e instanceof URL&&e.protocol===`ash-attachment:`}function Ps(e){return typeof Buffer<`u`&&Buffer.isBuffer(e)||e instanceof Uint8Array||e instanceof ArrayBuffer?e.byteLength:typeof e==`string`?Fs(e):Ns(e)?Ms(e).size??null:e instanceof URL&&e.protocol===`data:`?Fs(e.href):null}function Fs(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 Is(r);try{return Buffer.byteLength(decodeURIComponent(r),`utf8`)}catch{return Buffer.byteLength(r,`utf8`)}}return/^https?:\/\//.test(e)?null:Is(e)}function Is(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 Ls=Object.freeze({allowedMediaTypes:`*`,maxBytes:25*1024*1024});function Rs(e,t=Ls){if(e===`disabled`)return`disabled`;if(e===void 0)return t;let n=e.maxBytes??t.maxBytes,r=e.allowedMediaTypes??t.allowedMediaTypes;if(n<0||!Number.isFinite(n))throw RangeError(`UploadPolicy.maxBytes must be a non-negative finite number. Received: ${String(n)}.`);return{allowedMediaTypes:r,maxBytes:n}}function zs(e,t){if(t===`disabled`)return!1;if(t.allowedMediaTypes===`*`)return!0;let n=e.toLowerCase();for(let e of t.allowedMediaTypes){let t=e.toLowerCase();if(t===n)return!0;if(t.endsWith(`/*`)){let e=t.slice(0,-1);if(n.startsWith(e))return!0}}return!1}function Bs(e,t){if(t===`disabled`||!zs(e.mediaType,t)){let n={allowedMediaTypes:t===`disabled`||t.allowedMediaTypes===`*`?[]:[...t.allowedMediaTypes],kind:`disallowed-media-type`,mediaType:e.mediaType};return e.filename===void 0?n:{...n,filename:e.filename}}let n=Ps(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 Vs(e,t){if(typeof e==`string`)return[];let n=[];for(let r of e){if(r.type!==`file`)continue;let e=Bs(r,t);e!==null&&n.push(e)}return n}function Hs(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 Us(e,t){return{method:`POST`,path:e,handler:t}}function Ws(e,t){return{method:`GET`,path:e,handler:t}}function Gs(e){let t=Ks(e);return{__kind:`ash:channel`,routes:e.routes,adapter:t,receive:e.receive}}function Ks(e){let t=e.state!=null,n=e.context!=null,r=e.fetchFile!==void 0,i=t||n,a={},o=!1,s=[`turn.started`,`actions.requested`,`action.result`,`message.completed`,`message.appended`,`input.requested`,`turn.failed`,`turn.completed`,`session.failed`,`session.completed`,`session.waiting`,`connection.authorization_required`,`connection.authorization_pending`,`connection.authorization_completed`],c=e.events;for(let e of s){let t=c?.[e];t&&(o=!0,a[e]=(e,n)=>t(e,n))}return!i&&!o&&!r?{kind:e.kindHint??`http`}:{kind:e.kindHint??`defineChannel`,state:t?{...e.state}:{},fetchFile:e.fetchFile,createAdapterContext(t){let r=t.state,i=t.session;return{...n?e.context(r,i):{},state:r,ctx:t.ctx,session:i}},deliver(e){return Na(e)},...a}}function qs(e){let t=Rs(e.uploadPolicy);return Gs({routes:[Us(`/ash/v1/session`,async(n,{send:r})=>{let i=await Js(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=Ys(o);if(s instanceof Response)return s;let c=ec(s,t);if(c!==null)return c;let l=`ash:${crypto.randomUUID()}`,u=await r(Zs(s),{auth:a,continuationToken:l});return Response.json({continuationToken:u.continuationToken,ok:!0,sessionId:u.id},{headers:{"cache-control":`no-store`,[v]:u.id},status:202})}),Us(`/ash/v1/session/:sessionId`,async(n,{send:r,getSession:i,params:a})=>{let o=await Js(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=Xs(l);if(u instanceof Response)return u;let d=ec(u,t);if(d!==null)return d;let f=await r({inputResponses:u.inputResponses,message:u.message,modelContext:u.modelContext},{auth:s,continuationToken:u.continuationToken});return Response.json({ok:!0,sessionId:f.id},{headers:{"cache-control":`no-store`,[v]:f.id},status:200})}),Ws(`/ash/v1/session/:sessionId/stream`,async(t,{getSession:n,params:r})=>{let i=await Js(e.auth,t);if(i instanceof Response)return i;let a=r.sessionId;if(!a)return Response.json({error:`Missing session id.`,ok:!1},{status:400});let o=ic(t);if(o instanceof Response)return o;try{let e=ac(await n(a).getEventStream({startIndex:o}));return new Response(e,{headers:{"cache-control":`no-store`,"content-type":re,[v]:a,[ne]:ee,[ie]:`14`}})}catch{return Response.json({error:`Session not found.`,ok:!1},{status:404})}})]})}async function Js(e,t){let n=await e(t);return n===null?ws({challenges:[{scheme:`Bearer`}]}):n??null}function Ys(e){let t=Qs(e.message);if(t instanceof Response)return t;let n=nc(e.clientContext);return n instanceof Response?n:t===void 0?Response.json({error:`Missing or empty 'message' field.`,ok:!1},{status:400}):{message:t,modelContext:n}}function Xs(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=Qs(e.message);if(n instanceof Response)return n;let r=tc(e.inputResponses);if(r instanceof Response)return r;let i=nc(e.clientContext);return i instanceof Response?i: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,modelContext:i}}function Zs(e){return e.modelContext===void 0?e.message:{message:e.message,modelContext:e.modelContext}}function Qs(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=$s(n);if(e instanceof Response)return e;t.push(e)}return t}function $s(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 ec(e,t){if(!e.message)return null;let n=Vs(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:Hs(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 tc(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(te);return t.length===e.length?t:Response.json({error:`Expected every 'inputResponses' entry to match the HITL response schema.`,ok:!1},{status:400})}function nc(e){if(e!==void 0){if(typeof e==`string`)return e.length>0?[rc(e)]:void 0;if(Array.isArray(e))return e.length===0?void 0:e.every(e=>typeof e==`string`&&e.length>0)?e.map(e=>rc(e)):Response.json({error:`Expected 'clientContext' array entries to be non-empty strings.`,ok:!1},{status:400});if(typeof e!=`object`||!e)return Response.json({error:`Expected 'clientContext' to be a string, string array, or JSON object.`,ok:!1},{status:400});try{let t=y(e);return[rc(JSON.stringify(t))]}catch{return Response.json({error:`Expected 'clientContext' to be a JSON-serializable object.`,ok:!1},{status:400})}}}function rc(e){return{role:`user`,content:`Ephemeral client context:
|
|
14
|
+
${e}`}}function ic(e){let t=new URL(e.url).searchParams.get(`startIndex`);if(t===null)return;let n=Number.parseInt(t,10);return!Number.isSafeInteger(n)||n<0?Response.json({error:`Expected startIndex to be a non-negative integer.`,ok:!1},{status:400}):n}function ac(e){let t=new TextEncoder;return e.pipeThrough(new TransformStream({transform(e,n){n.enqueue(t.encode(`${JSON.stringify(e)}\n`))}}))}function oc(){return new Response(`<!doctype html>
|
|
15
15
|
<html lang="en">
|
|
16
16
|
<head>
|
|
17
17
|
<meta charset="utf-8" />
|
|
@@ -63,27 +63,27 @@ ${e}`}}function oc(e){let t=new URL(e.url).searchParams.get(`startIndex`);if(t==
|
|
|
63
63
|
<p>You can close this tab and return to your app.</p>
|
|
64
64
|
</main>
|
|
65
65
|
</body>
|
|
66
|
-
</html>`,{headers:{"cache-control":`no-store`,"content-type":`text/html; charset=utf-8`},status:200})}const
|
|
67
|
-
`),r=
|
|
68
|
-
`),outputLines:a.length,totalLines:r,truncated:a.length<r}}function
|
|
66
|
+
</html>`,{headers:{"cache-control":`no-store`,"content-type":`text/html; charset=utf-8`},status:200})}const sc=[`GET`,`POST`];function cc(){return sc.map(e=>uc(e))}function lc(){return new Set(sc.map(dc))}function uc(e){let t=dc(e);return{name:t,method:e,urlPath:oe,fetch:fc,logicalPath:`framework://channels/${t}`,sourceId:`ash:framework:connection-callback-${e.toLowerCase()}`,sourceKind:`module`}}function dc(e){return`.well-known/ash/v1/connections/callback/${e.toLowerCase()}`}async function fc(e,t){let n=t.params.name,r=t.params.token;if(typeof n!=`string`||n.length===0)return Response.json({error:`Missing connection name.`,ok:!1},{status:400});if(typeof r!=`string`||r.length===0)return Response.json({error:`Missing callback token.`,ok:!1},{status:400});let i=await pc(e);try{await Ee(r,i)}catch{return Response.json({error:`Connection callback not pending.`,ok:!1},{status:404})}return oc()}async function pc(e){let t={};e.headers.forEach((e,n)=>{t[n]=e});let n=``;if(e.method!==`GET`&&e.method!==`HEAD`)try{n=await e.text()}catch{n=``}return{body:n,headers:t,method:e.method,url:e.url}}function mc(){let e=qs({auth:gc()}),t=[];for(let n of e.routes)t.push({name:`ash`,method:n.method.toUpperCase(),urlPath:n.path,fetch:async(e,t)=>n.handler(e,t),handler:n.handler,adapter:e.adapter,logicalPath:`framework://channels/${n.path}`,sourceId:`ash:framework:${n.method.toLowerCase()}-${n.path}`,sourceKind:`module`});return t.push(...cc()),t}function hc(){return new Set([`ash`,...lc()])}function gc(){return process.env.VERCEL?ks():Ds()}const _c=ae.omit({action:!0,display:!0,requestId:!0}),{$schema:vc,...yc}=b.toJSONSchema(_c),bc={description:`Ask the user a question and wait for their response before continuing. Use this when you need clarification or a choice from the user.`,inputSchema:yc,logicalPath:`ash:framework/ask-question`,name:`ask_question`,sourceId:`ash:ask-question-tool`,sourceKind:`module`};async function J(){let e=H().get(_d);if(e===void 0)throw Error(`This tool requires sandbox access on the runtime context. Ensure the step is running inside a managed runtime context with sandbox support.`);let t=await e.get();if(t===null)throw Error(`The sandbox is not available in the current runtime context.`);return t}function xc(e){if(!e.startsWith(`/`))throw Error(`filePath must be an absolute path. Received: "${e}". Use an absolute path such as /workspace/foo.ts.`)}function Sc(e){return wc(e,`head`)}function Cc(e){return wc(e,`tail`)}function wc(e,t){let n=e.split(`
|
|
67
|
+
`),r=Ec(n),i=t===`head`,a=[],o=0,s=i?0:n.length-1,c=i?1:-1;for(let e=s;e>=0&&e<n.length&&a.length<2e3;e+=c){let t=Tc(n[e]??``),r=Buffer.byteLength(t,`utf8`)+1;if(o+r>51200&&a.length>0)break;a.push(t),o+=r}return i||a.reverse(),{output:a.join(`
|
|
68
|
+
`),outputLines:a.length,totalLines:r,truncated:a.length<r}}function Tc(e){return e.length<=2e3?e:e.slice(0,2e3)+` [truncated]`}function Ec(e){return e.length>0&&e[e.length-1]===``?e.length-1:e.length}async function Dc(e){let t=await(await J()).runCommand({command:e.command}),n=Cc(t.stdout),r=Cc(t.stderr),i=n.truncated||r.truncated,a=n.output;n.truncated&&(a=`[stdout truncated: showing last ${n.outputLines} of ${n.totalLines} lines]\n`+a);let o=r.output;return r.truncated&&(o=`[stderr truncated: showing last ${r.outputLines} of ${r.totalLines} lines]\n`+o),{exitCode:t.exitCode,stderr:o,stdout:a,truncated:i}}const Oc={additionalProperties:!1,properties:{command:{description:`The shell command to execute.`,type:`string`}},required:[`command`],type:`object`};async function kc(e){return Dc(e)}const Ac={description:`Execute a shell command in the shared workspace environment.`,execute:kc,inputSchema:Oc,logicalPath:`ash:framework/bash`,name:`bash`,sourceId:`ash:bash-tool`,sourceKind:`module`},jc=new V(`ash.readFile`);function Y(e){return ue.normalize(e)}function Mc(e){return e}function Nc(e){let t=ye(`sha256`).update(e.content,`utf8`).digest(`hex`);return{byteLength:Buffer.byteLength(e.content,`utf8`),contentHash:t,filePath:e.filePath}}function Pc(e,t,n){let r=e.ensure(jc,()=>({byTarget:{}}));e.set(jc,{byTarget:{...r.byTarget,[t]:n}})}function Fc(e){e.set(jc,{byTarget:{}})}const Ic=new Map;async function Lc(e){let t=Ic.get(e.id);if(t!==void 0)return t;let n=Rc(e);Ic.set(e.id,n);try{return await n}catch{return Ic.delete(e.id),!1}}async function Rc(e){return(await e.runCommand({command:`command -v rg >/dev/null 2>&1`})).exitCode===0}function X(e){return`'${e.replace(/'/g,`'\\''`)}'`}async function zc(e){let t=e.path??`/workspace`;xc(t);let n=Y(t),r=Math.min(Math.max(1,e.limit??100),1e3),i=await J(),a=await Lc(i)?Bc({normalizedPath:n,pattern:e.pattern}):Vc({normalizedPath:n,pattern:e.pattern}),o=await i.runCommand({command:a});if(o.exitCode!==0&&o.exitCode!==1)throw Uc(a,o.exitCode,o.stderr);let s=o.stdout.split(`
|
|
69
69
|
`).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(`
|
|
70
|
-
`),count:u.length,path:n,truncated:p}}function
|
|
71
|
-
`),execute:
|
|
72
|
-
`),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=
|
|
73
|
-
`);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
|
|
74
|
-
`),execute
|
|
75
|
-
`),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=
|
|
76
|
-
`),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
|
|
77
|
-
`),execute:
|
|
78
|
-
`)}`}function
|
|
79
|
-
`),execute:async e=>
|
|
70
|
+
`),count:u.length,path:n,truncated:p}}function Bc(e){return[`rg --files --hidden`,`--glob '!.git/*'`,`--glob ${X(e.pattern)}`,`-- ${X(e.normalizedPath)}`].join(` `)}function Vc(e){let t=Hc(e.pattern),n=t.includes(`/`)?`-path ${X(`*/${t}`)}`:`-name ${X(t)}`;return[`find ${X(e.normalizedPath)}`,`-type f`,`-not -path '*/.git/*'`,n].join(` `)}function Hc(e){let t=e.replaceAll(`**`,`*`);for(;t.startsWith(`*/`);)t=t.slice(2);return t}function Uc(e,t,n){let r=n.trim(),i=r.length>0?r:`no stderr output`;return Error(`glob failed (exit ${t}): ${i}\nCommand: ${e}`)}const Wc={additionalProperties:!1,properties:{limit:{description:`Maximum number of results to return. Defaults to 100.`,maximum:1e3,minimum:1,type:`integer`},path:{description:`The directory to search in. Defaults to /workspace. Must be an absolute path. Omit to use the default.`,type:`string`},pattern:{description:`The glob pattern to match files against (e.g. "**/*.ts", "src/**/*.js").`,type:`string`}},required:[`pattern`],type:`object`};async function Gc(e){return zc(e)}const Kc={description:[`Fast file pattern matching tool that works with any codebase size.`,``,`Usage:`,`- Supports glob patterns like "**/*.js" or "src/**/*.ts".`,`- Returns matching file paths.`,`- Use this tool when you need to find files by name patterns.`,`- If you are unsure of the correct file path, use the glob tool to look up filenames by glob pattern.`,`- Use the grep tool instead if you need to search file contents.`,`- Call this tool in parallel when you know there are multiple patterns to search for.`].join(`
|
|
71
|
+
`),execute:Gc,inputSchema:Wc,logicalPath:`ash:framework/glob`,name:`glob`,sourceId:`ash:glob-tool`,sourceKind:`module`};async function qc(e){let t=e.path??`/workspace`;xc(t);let n=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 Lc(a)?Jc({contextLines:i,effectiveLimit:r,glob:e.glob,ignoreCase:e.ignoreCase??!1,literal:e.literal??!1,normalizedPath:n,pattern:e.pattern}):Yc({contextLines:i,effectiveLimit:r,glob:e.glob,ignoreCase:e.ignoreCase??!1,literal:e.literal??!1,normalizedPath:n,pattern:e.pattern}),s=await a.runCommand({command:o});if(s.exitCode!==0&&s.exitCode!==1)throw Zc(o,s.exitCode,s.stderr);let c=s.stdout;return c.trim().length===0?{content:`No matches found`,matchCount:0,path:n,truncated:!1}:Xc({effectiveLimit:r,normalizedPath:n,stdout:c})}function Jc(e){let t=[`rg`,`--line-number`,`--color=never`,`--hidden`,`--glob '!.git/*'`];return e.ignoreCase&&t.push(`--ignore-case`),e.literal&&t.push(`--fixed-strings`),e.glob!==void 0&&t.push(`--glob ${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 Yc(e){let t=[`grep`,`-r`,`-n`,`--color=never`,`--exclude-dir=.git`];return e.ignoreCase&&t.push(`-i`),e.literal?t.push(`-F`):t.push(`-E`),e.glob!==void 0&&t.push(`--include=${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 Xc(e){let t=e.stdout.split(`
|
|
72
|
+
`),n=[],r=0,i=0,a=!1;for(let e of t){if(e.length===0&&t.indexOf(e)===t.length-1)continue;e!==`--`&&e.length>0&&/^.+:\d+:/.test(e)&&i++;let o=Tc(e),s=Buffer.byteLength(o,`utf8`)+1;if(r+s>51200&&n.length>0){a=!0;break}n.push(o),r+=s}let o=a||i>=e.effectiveLimit,s=n.join(`
|
|
73
|
+
`);if(o){let t=[];i>=e.effectiveLimit&&t.push(`Match limit reached (${e.effectiveLimit}). Use a larger limit or more specific pattern.`),a&&t.push(`Output truncated due to size. Use a more specific path or pattern.`),s+=`\n\n[${t.join(` `)}]`}return{content:s,matchCount:i,path:e.normalizedPath,truncated:o}}function Zc(e,t,n){let r=n.trim(),i=r.length>0?r:`no stderr output`;return Error(`grep failed (exit ${t}): ${i}\nCommand: ${e}`)}const Qc={additionalProperties:!1,properties:{context:{description:`Number of surrounding context lines to include before and after each match. Defaults to 0.`,minimum:0,type:`integer`},glob:{description:`Filter files by glob pattern (e.g. "*.ts", "*.{ts,tsx}").`,type:`string`},ignoreCase:{description:`Perform case-insensitive search. Defaults to false.`,type:`boolean`},limit:{description:`Maximum number of matches to return per file. Defaults to 100.`,maximum:1e3,minimum:1,type:`integer`},literal:{description:`Treat the pattern as a literal string instead of a regular expression. Defaults to false.`,type:`boolean`},path:{description:`The directory or file to search in. Defaults to /workspace. Must be an absolute path. Omit to use the default.`,type:`string`},pattern:{description:`The regex pattern to search for in file contents (e.g. "log.*Error", "function\\s+\\w+").`,type:`string`}},required:[`pattern`],type:`object`};async function $c(e){return qc(e)}const el={description:[`Fast content search tool that works with any codebase size.`,``,`Usage:`,`- Searches file contents using regular expressions.`,`- Supports full regex syntax (e.g. "log.*Error", "function\\s+\\w+").`,`- Filter files by pattern with the glob parameter (e.g. "*.js", "*.{ts,tsx}").`,`- Returns matching lines with file paths and line numbers.`,`- Use this tool when you need to find files containing specific patterns.`,`- Use the glob tool instead if you only need to find files by name.`,`- Call this tool in parallel when you have multiple independent searches.`,`- Any line longer than 2000 characters is truncated.`].join(`
|
|
74
|
+
`),execute:$c,inputSchema:Qc,logicalPath:`ash:framework/grep`,name:`grep`,sourceId:`ash:grep-tool`,sourceKind:`module`};async function tl(e){let{filePath:t,offset:n,limit:r}=e;xc(t);let i=await 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.readTextFile({path:t});if(c===null)throw Error(`File not found: ${t}. Verify the path exists and is accessible in the sandbox.`);if(c.includes(`\0`))throw Error(`File "${t}" contains NUL bytes and appears to be a binary file. read_file only supports text files.`);let l=c.split(`
|
|
75
|
+
`),u=l.length>0&&l[l.length-1]===``?l.length-1:l.length;if(u===0){if(o>1)throw Error(`offset ${o} is past the end of the file (0 lines). Use the default offset to read an empty file.`);return{content:``,path:a,totalLines:0,truncated:!1}}if(o>u)throw Error(`offset ${o} is past the end of the file (${u} lines).`);let d=Nc({content:c,filePath:a}),f=Mc(a);Pc(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}: ${Tc(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(`
|
|
76
|
+
`),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 nl={additionalProperties:!1,properties:{filePath:{description:`The absolute path to the file to read.`,type:`string`},limit:{description:`Maximum number of lines to return. Defaults to 2000.`,minimum:1,type:`integer`},offset:{description:`1-based line number to start from. Defaults to 1.`,minimum:1,type:`integer`}},required:[`filePath`],type:`object`};async function rl(e){return tl(e)}const il={description:[`Read a file from the local filesystem. If the path does not exist, an error is returned.`,``,`Usage:`,`- The filePath parameter should be an absolute path.`,`- By default, this tool returns up to 2000 lines from the start of the file.`,`- The offset parameter is the line number to start from (1-indexed).`,`- To read later sections, call this tool again with a larger offset.`,`- Use the grep tool to find specific content in large files or files with long lines.`,`- If you are unsure of the correct file path, use the glob tool to look up filenames by glob pattern.`,'- Contents are returned with each line prefixed by its line number as `<line>: <content>`. For example, if a file has contents "foo\\n", you will receive "1: foo\\n".',`- Any line longer than 2000 characters is truncated.`,`- Call this tool in parallel when you know there are multiple files you want to read.`,`- Avoid tiny repeated slices (30 line chunks). If you need more context, read a larger window.`].join(`
|
|
77
|
+
`),execute:rl,inputSchema:nl,logicalPath:`ash:framework/read-file`,name:`read_file`,onCompact({ctx:e}){return Fc(e),{}},sourceId:`ash:read-file-tool`,sourceKind:`module`},al=/^---\r?\n[\s\S]*?\r?\n---\r?\n?/;function ol(e){if(e.length===0||e.trim()!==e||e.startsWith(`.`)||e.includes(`/`)||e.includes(`\\`)||e.includes(`..`)||/^[A-Za-z]:/.test(e))throw Error(`Expected skill id to be a non-empty safe path segment without whitespace, separators, "." prefix, or "..".`)}async function sl(e,t){ol(t);let n=await cl(e),r=ll(t,`SKILL.md`),i=await n.readTextFile({path:r});if(i===null)throw Error(`No skill named "${t}" at ${r}.`);return i.replace(al,``)}async function cl(e){let t=await e.get();if(t===null)throw Error(`The sandbox is not available in the current authored runtime context.`);return t}function ll(e,t){return`${K}/skills/${e}/${t}`}async function ul(e){let t=H().get(_d);if(t===void 0)throw Error(`The load_skill tool requires sandbox access on the runtime context. Ensure the step is running inside a managed runtime context with sandbox support.`);let{skill:n}=e;return await sl(t,n)}const dl={description:[`Load the full instructions for one available skill by name or id.`,`Use this tool when the request clearly matches a listed skill description or when the user explicitly asks for that skill.`,`Loading adds the skill instructions to the current turn.`,`Choose the "skill" value from the Available skills block.`].join(` `),execute:e=>ul(e),inputSchema:{additionalProperties:!1,properties:{skill:{description:`Available skill name or id.`,type:`string`}},required:[`skill`],type:`object`},logicalPath:`ash:framework/load-skill`,name:`load_skill`,retentionPolicy:`keep`,sourceId:`ash:load-skill-tool`,sourceKind:`module`},fl=new V(`ash.todo`);function pl(e){if(e.items.length!==0)return`[Your task list was preserved across context compaction]\n${e.items.map(e=>`- [${e.status===`completed`?`x`:e.status===`cancelled`?`-`:` `}] [${e.priority}] ${e.content}`).join(`
|
|
78
|
+
`)}`}function ml(e){let{items:t}=e,n={cancelled:0,completed:0,in_progress:0,pending:0,total:t.length};for(let e of t)n[e.status]++;return{counts:n,todos:t}}function hl(e){let t=H(),{todos:n}=e??{};if(n!==void 0){let e={items:[...n]};return t.set(fl,e),ml(e)}return ml(t.ensure(fl,()=>({items:[]})))}const gl={description:[`Use this tool to create and manage a structured task list for the current session.`,`This helps you track progress, organize complex tasks, and demonstrate thoroughness.`,``,`When to use:`,`- Complex multistep tasks requiring 3 or more distinct steps`,`- When the user provides multiple tasks or a numbered list`,`- After receiving new instructions, to capture requirements`,`- After completing a task, to mark it complete and add follow-ups`,``,`When NOT to use:`,`- Single, straightforward tasks that need no tracking`,`- Purely conversational or informational requests`,``,`Usage:`,"- Call with `todos` to replace the entire list (full replacement write)","- Call without `todos` to read the current list",`- Both return the full current list with status counts`,`- Mark tasks in_progress when you start, completed when done`,`- Only have ONE task in_progress at a time`].join(`
|
|
79
|
+
`),execute:async e=>hl(e??{}),inputSchema:{additionalProperties:!1,properties:{todos:{description:`The updated todo list. Omit to read the current list without modifying it.`,items:{additionalProperties:!1,properties:{content:{description:`Brief description of the task.`,type:`string`},priority:{description:`Priority level of the task.`,enum:[`high`,`medium`,`low`],type:`string`},status:{description:`Current status of the task.`,enum:[`pending`,`in_progress`,`completed`,`cancelled`],type:`string`}},required:[`content`,`status`,`priority`],type:`object`},type:`array`}},type:`object`},logicalPath:`ash:framework/todo`,name:`todo`,onCompact({ctx:e}){let t=e.get(fl);if(t===void 0||t.items.length===0)return{};let n=pl(t);return n===void 0?{}:{messages:[{content:n,role:`user`}]}},sourceId:`ash:todo-tool`,sourceKind:`module`};function _l(e){let t=new Ie({bulletListMarker:`-`,codeBlockStyle:`fenced`,emDelimiter:`*`,headingStyle:`atx`,hr:`---`});return t.remove([`script`,`style`,`meta`,`link`]),t.turndown(e)}function vl(e){let t=e;return t=t.replace(/<(script|style|noscript)\b[^>]*>[\s\S]*?<\/\1>/gi,``),t=t.replace(/<\/(p|div|br|h[1-6]|li|tr|blockquote|pre|section|article|header|footer|nav|aside|main|figure|figcaption|details|summary)>/gi,`
|
|
80
80
|
`),t=t.replace(/<br\s*\/?>/gi,`
|
|
81
|
-
`),t=t.replace(/<[^>]+>/g,``),t=
|
|
81
|
+
`),t=t.replace(/<[^>]+>/g,``),t=xl(t),t=t.split(`
|
|
82
82
|
`).map(e=>e.replace(/[ \t]+/g,` `).trim()).join(`
|
|
83
83
|
`).replace(/\n{3,}/g,`
|
|
84
84
|
|
|
85
|
-
`).trim(),t}const
|
|
86
|
-
`),execute:
|
|
87
|
-
`),execute:
|
|
85
|
+
`).trim(),t}const yl={"&":`&`,">":`>`,"<":`<`," ":` `,""":`"`,"'":`'`,"'":`'`,"/":`/`},bl=new RegExp(Object.keys(yl).join(`|`),`gi`);function xl(e){return e.replace(bl,e=>yl[e.toLowerCase()]??e)}const Sl=5*1024*1024;async function Cl(e){let{url:t,format:n=`markdown`,timeout:r}=e;if(!t.startsWith(`http://`)&&!t.startsWith(`https://`))throw Error(`URL must start with http:// or https://`);let i=Math.min(r===void 0?3e4:r*1e3,12e4),a=AbortSignal.timeout(i),o=wl(n),s=await fetch(t,{headers:o,signal:a}),c=s.status===403&&s.headers.get(`cf-mitigated`)===`challenge`?await fetch(t,{headers:{...o,"User-Agent":h},signal:a}):s;if(!c.ok)throw Error(`Request failed with status code: ${c.status}`);let l=c.headers.get(`content-length`);if(l!==null&&parseInt(l,10)>Sl)throw Error(`Response too large (exceeds 5 MB limit).`);let u=await c.arrayBuffer();if(u.byteLength>Sl)throw Error(`Response too large (exceeds 5 MB limit).`);let d=c.headers.get(`content-type`)??``,f=d.includes(`text/html`),p=new TextDecoder().decode(u),m;m=n===`markdown`&&f?_l(p):n===`text`&&f?vl(p):p;let{output:g,truncated:_}=Sc(m);return{content:g,contentType:d,truncated:_,url:t}}function wl(e){let t;return t=e===`markdown`?`text/markdown;q=1.0, text/x-markdown;q=0.9, text/plain;q=0.8, text/html;q=0.7, */*;q=0.1`:e===`text`?`text/plain;q=1.0, text/markdown;q=0.9, text/html;q=0.8, */*;q=0.1`:`text/html;q=1.0, application/xhtml+xml;q=0.9, text/plain;q=0.8, text/markdown;q=0.7, */*;q=0.1`,{Accept:t,"Accept-Language":`en-US,en;q=0.9`,"User-Agent":`Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36`}}async function Tl(e){return Cl(e)}const El={description:[`Fetch a webpage and return its content in the requested format. Use this to retrieve and analyze content from URLs.`,``,`Usage notes:`,`- The URL must be a fully-formed valid URL starting with http:// or https://`,`- HTML responses are automatically converted to markdown or plain text based on the requested format`,`- Format options: "markdown" (default), "text", or "html"`,`- Default timeout is 30 seconds (max 120 seconds)`,`- Maximum response size is 5 MB; content is further capped at the shared tool-output budget (50 KB / 2000 lines)`,`- This tool is read-only and does not modify any files`].join(`
|
|
86
|
+
`),execute:Tl,inputSchema:{additionalProperties:!1,properties:{format:{description:`The format to return the content in (text, markdown, or html). HTML responses are automatically converted to the requested format. Defaults to "markdown".`,enum:[`markdown`,`text`,`html`],type:`string`},timeout:{description:`Optional timeout in seconds. Defaults to 30, max 120.`,type:`number`},url:{description:`The fully-formed URL to fetch content from. Must start with http:// or https://.`,type:`string`}},required:[`url`],type:`object`},logicalPath:`ash:framework/web-fetch`,name:`web_fetch`,sourceId:`ash:web-fetch-tool`,sourceKind:`module`},Dl={description:`Search the web for real-time information. Use this to find up-to-date information about current events, recent developments, or topics that may have changed since the knowledge cutoff.`,inputSchema:null,logicalPath:`ash:framework/web-search`,name:`web_search`,sourceId:`ash:web-search-tool`,sourceKind:`module`};async function Ol(e){let{filePath:t,content:n}=e;xc(t);let r=await J(),i=H(),a=Y(t),o=Mc(a),s=await r.readTextFile({path:t});if(s===null)return await r.writeTextFile({content:n,path:t}),Pc(i,o,Nc({content:n,filePath:a})),{existed:!1,path:a};let c=i.ensure(jc,()=>({byTarget:{}})).byTarget[o];if(c===void 0)throw Error(`You must read file ${t} before overwriting it. Use the read_file tool first.`);let l=Nc({content:s,filePath:a});if(l.contentHash!==c.contentHash||l.byteLength!==c.byteLength)throw Error(`File ${t} has been modified since it was last read. Please read the file again before modifying it.`);return await r.writeTextFile({content:n,path:t}),Pc(i,o,Nc({content:n,filePath:a})),{existed:!0,path:a}}const kl={additionalProperties:!1,properties:{content:{description:`Complete replacement file contents.`,type:`string`},filePath:{description:`The absolute path to the file to write (must be absolute, not relative).`,type:`string`}},required:[`filePath`,`content`],type:`object`};async function Al(e){return Ol(e)}const jl=[bc,Ac,Kc,el,il,{description:[`Writes a file to the local filesystem.`,``,`Usage:`,`- This tool will overwrite the existing file if there is one at the provided path.`,`- If this is an existing file, you MUST use the read_file tool first to read the file's contents. This tool will fail if you did not read the file first.`,`- ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required.`,`- NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested by the User.`,`- Only use emojis if the user explicitly requests it. Avoid writing emojis to files unless asked.`].join(`
|
|
87
|
+
`),execute:Al,inputSchema:kl,logicalPath:`ash:framework/write-file`,name:`write_file`,sourceId:`ash:write-file-tool`,sourceKind:`module`},gl,El,Dl,dl,Ko],Ml=new Map([[Ko,e=>e.hasConnections]]);function Nl(e){return jl.filter(t=>{let n=Ml.get(t);return n===void 0||n(e)})}function Pl(){return new Set(jl.map(e=>e.name))}function Fl(e){let t=[],n=[],r=new Map,i=[];for(let a of e){let e=a.lifecycle.session;e!==void 0&&t.push({slug:a.slug,handler:e});let o=a.lifecycle.turn;o!==void 0&&n.push({slug:a.slug,handler:o});for(let[e,t]of Object.entries(a.events)){let n={slug:a.slug,handler:t,eventType:e};if(e===`*`)i.push(n);else{let t=r.get(e)??[];t.push(n),r.set(e,t)}}}return{session:t,turn:n,streamEventsByType:r,streamEventsWildcard:i}}var 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 Il(e){return{exportName:e.exportName,logicalPath:e.logicalPath,sourceId:e.sourceId,sourceKind:`module`}}async function Q(e){let t=e.nodeId??`__root__`,n=e.moduleMap.nodes[t]?.modules[e.definition.sourceId];if(n===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 s(r(c(n,`Missing compiled module namespace for ${e.kindLabel} source "${e.definition.sourceId}" in node "${t}".`),{exportName:e.definition.exportName,logicalPath:e.definition.logicalPath}))}async function Ll(e,t,n){try{let r=oi(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=Il({exportName:e.exportName,logicalPath:e.logicalPath,sourceId:e.sourceId}),a=r.routes.find(t=>t.method.toUpperCase()===e.method.toUpperCase()&&t.path===e.urlPath),o=r.adapter;return o&&o.kind!==`http`&&(o.kind=`channel:${e.name}`),{name:e.name,method:e.method,urlPath:e.urlPath,fetch:async(e,t)=>a?a.handler(e,t):Response.json({error:`No matching route handler.`,ok:!1},{status:404}),handler:a?.handler,receive:r.receive,definition:r,adapter:o,...i}}catch(t){throw t instanceof Z?t:new Z(`Failed to attach the channel definition from "${e.logicalPath}": ${p(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}async function Rl(e,t,n){try{let r=c(await Q({definition:e,kindLabel:`connection`,moduleMap:t,nodeId:n}),`Expected the connection export "${e.exportName??`default`}" from "${e.logicalPath}" to return an object.`);zi(`connection:${r.url}`,{kind:`connection`,name:e.connectionName});let i=r.auth!==void 0,a=r.headers!==void 0,o={connectionName:e.connectionName,description:e.description,exportName:e.exportName,logicalPath:e.logicalPath,sourceId:e.sourceId,sourceKind:`module`,url:e.url};if(i)try{o.authorization=di(r.auth,`Connection "${e.connectionName}" at "${e.logicalPath}":`)}catch(t){throw new Z(p(t),{logicalPath:e.logicalPath,sourceId:e.sourceId})}return a&&(o.headers=r.headers),r.tools!==void 0&&(o.tools=r.tools),typeof r.approval==`function`&&(o.approval=r.approval),o}catch(t){throw t instanceof Z?t:new Z(`Failed to resolve connection "${e.connectionName}" from "${e.logicalPath}": ${p(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}async function zl(e,t,n){try{let r=c(await Q({definition:e,kindLabel:`hook`,moduleMap:t,nodeId:n}),Bl(e,`to return an object`)),i={},a={},s=r.lifecycle;if(s!==void 0){let t=c(s,Bl(e,"to expose `lifecycle` as an object"));for(let n of[`session`,`turn`]){let r=t[n];r!==void 0&&(i[n]=o(r,Bl(e,`to provide a function for "lifecycle.${n}"`)))}}let l=r.events;if(l!==void 0){let t=c(l,Bl(e,"to expose `events` as an object"));for(let[n,r]of Object.entries(t))r!==void 0&&(a[n]=o(r,Bl(e,`to provide a function for "events.${n}"`)))}return{events:a,exportName:e.exportName,lifecycle:i,logicalPath:e.logicalPath,slug:e.slug,sourceId:e.sourceId,sourceKind:`module`}}catch(t){throw t instanceof Z?t:new Z(`Failed to attach hook handlers from "${e.logicalPath}": ${p(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}function Bl(e,t){return`Expected the hook export "${e.exportName??`default`}" from "${e.logicalPath}" ${t}.`}var Vl=class e extends Error{backendName;templateKey;constructor(e){super(`Sandbox template "${e.templateKey}" is not provisioned for backend "${e.backendName}". Run \`ash build\` or invoke \`prewarmAppSandboxes()\` before serving traffic.`),this.name=`SandboxTemplateNotProvisionedError`,this.backendName=e.backendName,this.templateKey=e.templateKey}static is(t){return t instanceof e}};async function Hl(e){let t=[];for await(let n of e)t.push(n);return Buffer.concat(t)}function Ul(e){return new ReadableStream({start(t){t.enqueue(e),t.close()}})}function Wl(e){return{id:e.id,resolvePath(t){return e.resolvePath(t)},async runCommand(t){return await e.runCommand(t)},async readFile(t){return await e.readFile({abortSignal:t.abortSignal,path:e.resolvePath(t.path)})},async readBinaryFile(t){let n=await e.readFile({abortSignal:t.abortSignal,path:e.resolvePath(t.path)});return n===null?null:await Hl(n)},async readTextFile(t){Gl(t);let n=await e.readFile({abortSignal:t.abortSignal,path:e.resolvePath(t.path)});return n===null?null:ql(Jl(await Hl(n),t.encoding??`utf-8`),t)},async writeFile(t){await e.writeFile({abortSignal:t.abortSignal,content:t.content,path:e.resolvePath(t.path)})},async writeBinaryFile(t){await e.writeFile({abortSignal:t.abortSignal,content:Ul(t.content),path:e.resolvePath(t.path)})},async writeTextFile(t){let n=Yl(t.content,t.encoding??`utf-8`);await e.writeFile({abortSignal:t.abortSignal,content:Ul(n),path:e.resolvePath(t.path)})}}}function Gl(e){let{startLine:t,endLine:n}=e;if(t!==void 0&&(!Number.isInteger(t)||t<1))throw Error(`startLine must be a positive integer (1-based).`);if(n!==void 0&&(!Number.isInteger(n)||n<1))throw Error(`endLine must be a positive integer (1-based).`);if(t!==void 0&&n!==void 0&&t>n)throw Error(`startLine must not be greater than endLine.`)}function Kl(e){let t=[],n=0;for(let r=0;r<e.length;r++)e[r]===`\r`?r+1<e.length&&e[r+1]===`
|
|
88
88
|
`?(t.push(e.slice(n,r+2)),n=r+2,r++):(t.push(e.slice(n,r+1)),n=r+1):e[r]===`
|
|
89
|
-
`&&(t.push(e.slice(n,r+1)),n=r+1);return n<e.length&&t.push(e.slice(n)),t}function Yl(e,t){if(t.startLine===void 0&&t.endLine===void 0)return e;let n=Jl(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 Xl(e,t){return t===`utf-8`||t===`utf8`?new TextDecoder(`utf-8`,{fatal:!0}).decode(e):Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(t)}function Zl(e,t){return t===`utf-8`||t===`utf8`?new TextEncoder().encode(e):Buffer.from(e,t)}function Ql(e={}){return{name:`local`,async prewarm(e){let t=iu(kd(e.runtimeContext.appRoot),e.templateKey);if(await fu(t))return;let n=await $l({sessionKey:e.templateKey,snapshotPath:t}),r=Kl(tu(n));try{e.bootstrap!==void 0&&await e.bootstrap({use:async()=>r});for(let t of e.seedFiles)typeof t.content==`string`?await r.writeTextFile({content:t.content,path:t.path}):await r.writeBinaryFile({content:t.content,path:t.path});if(await n.captureSnapshot()===null)throw Error(`Failed to capture local sandbox template state for "${e.templateKey}".`)}finally{await n.dispose()}},async create(e){let t=kd(e.runtimeContext.appRoot),n=await uu(iu(t,e.templateKey));if(n===null)throw new Ul({backendName:`local`,templateKey:e.templateKey});let r=pu(e.existingMetadata)??au(t,e.sessionKey);return await fu(r)||await du(r,n),eu(await $l({sessionKey:e.sessionKey,snapshotPath:r}))}}}async function $l(e){let{Bash:t,InMemoryFs:n}=await import(`#compiled/just-bash/index.js`),r=await uu(e.snapshotPath),i=new n(ou(r));await su(i),await cu(i,r?.entries??[]);let a=new t({cwd:K,env:r?.env,fs:i,network:{dangerouslyAllowFullInternetAccess:!0}});return{async captureSnapshot(){let t=await lu({filesystem:i,sandbox:a});return await du(e.snapshotPath,t),{snapshotPath:e.snapshotPath}},async dispose(){await a.dispose?.()},async executeCommand(e){if(e.abortSignal?.aborted)throw new DOMException(`The operation was aborted.`,`AbortError`);let t=e.workingDirectory===void 0?e.command:`( cd ${X(e.workingDirectory)} && ${e.command} )`,n=a.exec(t),r=e.abortSignal?await nu(n,e.abortSignal):await n;return{exitCode:r.exitCode,stderr:r.stderr,stdout:r.stdout}},async readFileBytes(e){let t;try{t=await i.readFileBuffer(e)}catch{return null}return Buffer.from(t)},async readFileText(e){let t;try{t=await i.readFileBuffer(e)}catch{return null}return new TextDecoder(`utf-8`,{fatal:!0}).decode(t)},sessionKey:e.sessionKey,snapshotPath:e.snapshotPath,async writeFiles(e){for(let t of e){let e=x(t.path);await i.mkdir(e,{recursive:!0}),await i.writeFile(t.path,t.content)}}}}function eu(e){let t=Kl(tu(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 tu(e){return{id:e.sessionKey,resolvePath:ru,async runCommand(t){return await e.executeCommand(t)},async readFile(t){let n=await e.readFileBytes(t.path);return n===null?null:Gl(n)},async writeFile(t){let n=await Wl(t.content);await e.writeFiles([{content:n,path:t.path}])}}}async function nu(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 ru(e){return e.startsWith(`/`)?e:`${K}/${e}`}function iu(e,t){return S(e,`local`,`templates`,`${t}.json`)}function au(e,t){return S(e,`local`,`sessions`,`${t}.json`)}function ou(e){let t={};for(let n of e?.entries??[])n.kind===`file`&&(t[n.path]=Buffer.from(n.contentBase64,`base64`));return t}async function su(e){await e.mkdir(K,{recursive:!0})}async function cu(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 lu(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 uu(e){if(!await fu(e))return null;let t=JSON.parse(await he(e,`utf8`));return t.version===1?t:null}async function du(e,t){await w(x(e),{recursive:!0}),await T(e,`${JSON.stringify(t,null,2)}\n`)}async function fu(e){try{return await pe(e),!0}catch{return!1}}function pu(e){let t=e?.snapshotPath;return typeof t==`string`?t:void 0}function mu(e){return Ql({createOptions:e})}function hu(e={}){let t=e.loadSandboxModule??(async()=>await import(`#compiled/@vercel/sandbox/index.js`)),n={timeout:Nu,...e.createOptions},r=new Map;return{name:`vercel`,async create(e){let i=ku(n.tags,e.tags),a;try{a=await gu({loadSandboxModule:t,prewarmedTemplates:r,templateKey:e.templateKey})}catch(t){throw Ul.is(t)?t:Error(`Failed to read sandbox template "${e.templateKey}": ${Mu(t)}`,{cause:t})}let o;try{o=await vu({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}": ${Mu(t)}`,{cause:t})}return yu(o,e.sessionKey)},async prewarm(e){let i;try{i=await _u({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}": ${Mu(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 gu(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 Ul({backendName:`vercel`,templateKey:e.templateKey});return{sandboxName:n.name,snapshotId:n.currentSnapshotId,templateKey:e.templateKey}}async function _u(e){let t=await e.loadSandboxModule(),n=await Tu(t,e.templateKey),r=ku(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);let i=Du(e.createOptions);if(typeof n.currentSnapshotId==`string`&&n.currentSnapshotId.length>0&&n.currentSnapshotId!==i)return{sandboxName:n.name,snapshotId:n.currentSnapshotId,templateKey:e.templateKey};await Su(n,e.createOptions);let a=Kl(bu(n,e.templateKey));e.bootstrap!==void 0&&await e.bootstrap({use:async e=>(e!==void 0&&await n.update(e),a)});for(let t of e.seedFiles)typeof t.content==`string`?await a.writeTextFile({content:t.content,path:t.path}):await a.writeBinaryFile({content:t.content,path:t.path});let o=await n.snapshot();return{sandboxName:n.name,snapshotId:o.snapshotId,templateKey:e.templateKey}}async function vu(e){let t=Ou(e.existingMetadata)??e.sessionKey,n=await Tu(e.sandboxModule,t);if(n!==null)return await Au(n,e.tags),n;let{runtime:r,source:i,...a}=e.createOptions,o={...a,name:t,persistent:!0,source:{snapshotId:e.snapshotId,type:`snapshot`}};return e.tags!==void 0&&(o.tags=e.tags),await e.sandboxModule.Sandbox.create(o)}function yu(e,t){return{session:Kl(bu(e,t)),useSessionFn:async n=>(n!==void 0&&await e.update(n),Kl(bu(e,t))),async captureState(){return{backendName:`vercel`,metadata:{sandboxName:e.name},sessionKey:t}},async dispose(){}}}function bu(e,t){return{id:t,resolvePath:xu,async runCommand(t){let n=await e.runCommand({args:[`-lc`,t.command],cmd:`bash`,cwd:t.workingDirectory??`/workspace`,signal:t.abortSignal}),[r,i]=await Promise.all([n.stdout(),n.stderr()]);return{exitCode:n.exitCode,stderr:i,stdout:r}},async readFile(t){return await e.readFile({path:t.path})??null},async writeFile(t){let n=await Wl(t.content);await e.writeFiles([{content:n,path:t.path}])}}}function xu(e){return e.startsWith(`/`)?e:`${K}/${e}`}async function Su(e,t){await Cu(e,{failureMessage:`Failed to initialize Vercel sandbox workspace.`,script:`mkdir -p ${K} && chown ${wu}:${wu} ${K}`}),t.networkPolicy!==`deny-all`&&await Cu(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 Cu(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 wu=`vercel-sandbox`;async function Tu(e,t){try{return await e.Sandbox.get({name:t})}catch(e){if(Eu(e))return null;throw Error(`Failed to look up Vercel sandbox "${t}": ${Mu(e)}`,{cause:e})}}function Eu(e){return e instanceof Error?(e.response?.status??e.cause?.response?.status)===404:!1}function Du(e){let t=e.source;if(t?.type===`snapshot`&&typeof t.snapshotId==`string`)return t.snapshotId}function Ou(e){let t=e?.sandboxName;return typeof t==`string`?t:void 0}function ku(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>Pu)throw Error(`Vercel Sandbox supports at most ${Pu} 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||ju(e.tags,t)||await e.update({tags:t})}function ju(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 Mu(e){return e instanceof Error?e.message:String(e)}const Nu=1800*1e3,Pu=5;function Fu(e){return hu({createOptions:e})}function Iu(e){return Ti(()=>process.env.VERCEL?Fu(e?.vercel):mu(e?.local))}async function Lu(e,t,n){try{let r=c(await Q({definition:e,kindLabel:`sandbox`,moduleMap:t,nodeId:n}),`Expected the sandbox export "${e.exportName??`default`}" from "${e.logicalPath}" to return an object.`);return{backend:Ru(r.backend,e.logicalPath),bootstrap:r.bootstrap,description:e.description,exportName:e.exportName,logicalPath:e.logicalPath,onSession:r.onSession,sourceId:e.sourceId,sourceKind:`module`}}catch(t){throw t instanceof Z?t:new Z(`Failed to attach the sandbox lifecycle handlers from "${e.logicalPath}": ${p(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}function Ru(e,t){if(e===void 0)return Iu();if(typeof e==`function`)return Ti(e);if(typeof e!=`object`||!e)throw new Z(`Sandbox "${t}" exposed a non-object "backend" field. Use vercelBackend(), localBackend(), another factory that returns a SandboxBackend value, or a zero-arg callback returning one.`,{logicalPath:t});let n=e;if(typeof n.name!=`string`||n.name.length===0)throw new 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 zu(e,t,n){try{let r=c(await Q({definition:e,kindLabel:`tool`,moduleMap:t,nodeId:n}),$(e,`to return an object`));zi(`tool:${r.description}`,{kind:`tool`,name:e.name});let i=o(r.execute,$(e,`to provide an execute function`));return{description:e.description,execute:i,exportName:e.exportName,inputSchema:e.inputSchema,logicalPath:e.logicalPath,name:e.name,sourceId:e.sourceId,sourceKind:`module`,...Bu(r,e)}}catch(t){throw t instanceof Z?t:new Z(`Failed to attach the tool execute function from "${e.logicalPath}": ${p(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}function Bu(e,t){let n={};e.onCompact!==void 0&&(n.onCompact=o(e.onCompact,$(t,`to provide an onCompact function`))),e.needsApproval!==void 0&&(n.needsApproval=o(e.needsApproval,$(t,`to provide a needsApproval function`)));let r=Vu(e,t);return r!==void 0&&(n.retentionPolicy=r),e.toModelOutput!==void 0&&(n.toModelOutput=o(e.toModelOutput,$(t,`to provide a toModelOutput function`))),e.inputSchema!==void 0&&Hu(e.inputSchema)&&(n.inputStandardSchema=e.inputSchema),n}function Vu(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 Hu(e){return typeof e==`object`&&!!e&&`~standard`in e&&typeof e[`~standard`]==`object`}async function Uu(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 zl(t,e.moduleMap,e.nodeId))}let i=await Promise.all(e.manifest.tools.map(t=>zu(t,e.moduleMap,e.nodeId))),a=await Promise.all(e.manifest.hooks.map(t=>Vl(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 Lu(e.manifest.sandbox,e.moduleMap,e.nodeId),c=Wu(e.manifest.instructions),l=e.manifest.workspaceResourceRoot,u={channels:n,config:Gu(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 Wu(e){if(e!==void 0)return{name:e.name,logicalPath:e.logicalPath,markdown:e.markdown,sourceId:e.sourceId,sourceKind:e.sourceKind}}function Gu(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=Rl(e.config.source)),t}function Ku(e){return{sandbox:{definition:e.authoredSandbox??qu(),workspaceResourceRoot:e.workspaceResourceRoot}}}function qu(){return{backend:Iu(),logicalPath:`ash:framework/default-sandbox`,sourceId:`ash:default-sandbox`,sourceKind:`module`}}const Ju=`load_skill`,Yu=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 Xu(e){let t=[],n=new Ga(`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=Zu(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 Zu(e){return{description:e.description,inputSchema:Yu,kind:`subagent`,logicalPath:e.logicalPath,name:e.name,nodeId:e.nodeId,sourceId:e.sourceId}}async function Qu(e,t={}){let n=[],r=new Ga(`tool`,t.reservedToolNames??[]);for(let t of e.tools){let e=await $u(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 $u(e){return{description:e.description,inputSchema:await ed(e),kind:`authored-tool`,logicalPath:e.logicalPath,name:e.name,sourceId:e.sourceId}}async function ed(e){return e.inputSchema}var td=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 nd(e){let t=new Map,n=od(e.manifest),r=new Map(e.manifest.subagents.map(e=>[e.nodeId,e]));return{nodesByNodeId:t,root:await rd({childNodeIdsByParentNodeId:n,manifest:e.manifest,moduleMap:e.moduleMap,nodeId:R,nodesByNodeId:t,subagentNodesById:r})}}async function rd(e){let t=sd(e.nodeId);if(e.nodesByNodeId.has(t))throw new td(`Found multiple runtime agent nodes for node id "${t}".`,{nodeId:t,sourceId:e.sourceId});let n=await Uu({manifest:e.manifest,moduleMap:e.moduleMap,nodeId:e.nodeId}),r=n.connections.length>0,i=Fl({hasConnections:r}),a=r?ld(i,n.connections):i,o=new Set(a.map(e=>e.name)),s=Il(),c=new Set(n.tools.map(e=>e.name));for(let r of n.disabledFrameworkTools)if(!s.has(r))throw new td(`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 Qu({tools:[...a.filter(e=>!c.has(e.name)&&!l.has(e.name)),...n.tools]},{reservedToolNames:o.has(`load_skill`)||c.has(`load_skill`)?[]:[Ju]}),d=new Set(n.channels.map(e=>e.name)),f=_c();for(let r of n.disabledFrameworkChannels)if(!f.has(r))throw new td(`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=[...gc().filter(e=>!d.has(e.name)&&!p.has(e.name)),...n.channels],h=Ku({authoredSandbox:n.sandbox,workspaceResourceRoot:n.workspaceResourceRoot}),g=Xu({reservedToolNames:[Ju,...u.preparedTools.map(e=>e.name)],subagents:await id({childNodeIdsByParentNodeId:e.childNodeIdsByParentNodeId,moduleMap:e.moduleMap,nodesByNodeId:e.nodesByNodeId,parentNodeId:e.nodeId,subagentNodesById:e.subagentNodesById})}),_={agent:n,channels:m,hookRegistry:Ll(n.hooks),nodeId:t,sandboxRegistry:h,sourceId:e.sourceId,subagentRegistry:g,toolRegistry:u,turnAgent:ss({agent:n,nodeId:t,tools:[...u.preparedTools,...g.preparedTools]})};return e.nodesByNodeId.set(t,_),_}async function id(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 td(`Missing compiled subagent node "${r}" while resolving runtime subagents.`,{nodeId:sd(e.parentNodeId),sourceId:r});t.push(await ad({childNodeIdsByParentNodeId:e.childNodeIdsByParentNodeId,moduleMap:e.moduleMap,nodesByNodeId:e.nodesByNodeId,sourceRef:n,subagentNodesById:e.subagentNodesById}))}return t}async function ad(e){let t={description:e.sourceRef.description,logicalPath:e.sourceRef.logicalPath,name:e.sourceRef.name,nodeId:sd(e.sourceRef.nodeId),sourceId:e.sourceRef.sourceId,sourceKind:`module`};return await rd({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 od(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 sd(e){return e===`__root__`?xo:e}const cd=Jo.name;function ld(e,t){let n=t.map(e=>e.connectionName).join(`, `);return e.map(e=>e.name===cd?{...e,description:`${e.description} Available connections: ${n}.`}:e)}const ud=process.env.ASH_DISABLE_AGENT_CACHE===`1`;async function dd(e){let[t,n]=await Promise.all([To({compiledArtifactsSource:e}),fd(e)]),r=await nd({manifest:t,moduleMap:n}),i=r.root;return{adapterRegistry:Ya({channels:_d(r)}),compiledArtifactsSource:e,graph:r,hookRegistry:i.hookRegistry,moduleMap:n,resolvedAgent:i.agent,subagentRegistry:i.subagentRegistry,toolRegistry:i.toolRegistry,turnAgent:i.turnAgent}}async function fd(e){return e.kind===`disk`&&e.moduleMapLoadMode===`authored-source`?await pd(e):await Ao({compiledArtifactsSource:e})}async function pd(e){if(e.moduleMapLoaderPath===void 0)throw Error(`Authored-source module map loading requires "moduleMapLoaderPath" in the compiled artifacts source.`);return await(await import(we(e.moduleMapLoaderPath).href)).loadCompiledModuleMapFromAuthoredSource({compiledArtifactsSource:e})}async function md(e){if(ud)return dd(e);let t=lo(),n=to(e),r=await vo(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=dd(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 hd(e){let t=await md(e.compiledArtifactsSource);if(e.nodeId===void 0)return t;let n=So(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 gd(){let e=lo();e.bundleCache.clear(),e.bundleCacheKeyBySourceKey.clear()}function _d(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:Pa(e),state:e.state?{...e.state}:{}}},deserialize(e,t){let n=t.get(vd);if(n===void 0)throw Error(`Cannot deserialize "ash.channel" before "ash.bundle". The runtime bundle must be present in context.`);return Xa(n.adapterRegistry,e)}}});const vd=new V(`ash.bundle`,{codec:{serialize:e=>({nodeId:e.nodeId,source:e.compiledArtifactsSource}),deserialize:e=>{let{source:t,nodeId:n}=e;return hd({compiledArtifactsSource:t,nodeId:n})}}});new V(`ash.session`);const yd=new V(`ash.sandbox`),bd=_(),xd={workflowId:`workflow//${bd.name}@${bd.version}//workflowEntry`};function Sd(e=process.cwd()){return C(e)}function Cd(e){return ye(`sha256`).update(e).digest(`hex`).slice(0,12)}function wd(){return!!process.env.VERCEL}function Td(e,t=`all`){let n=S(e,`.ash`,`nitro`);return t===`all`?n:S(n,t)}function Ed(e,t){return S(e,`.ash`,`nitro-output`,t)}function Dd(e){let t=S(m(),`.ash`,`workflow-cache`);return Od(t),S(t,Cd(e))}function Od(e){if(!be(e))return;let t=_().version,n;try{n=Se(e)}catch{return}for(let r of n){let n=S(e,r),i=S(n,`ash-cache.json`);if(be(i))try{let e=JSON.parse(xe(i,`utf8`));typeof e.ashVersion==`string`&&e.ashVersion!==t&&Ce(n,{force:!0,recursive:!0})}catch{}}}function kd(e){return S(e,`.ash`,`sandbox-cache`)}function Ad(e){return wd()?S(e,`.vercel`,`output`):S(e,`.output`)}function jd(e){return{appRoot:e,outputDir:Ad(e),workflowId:xd.workflowId,workflowBuildDir:Dd(e),workflowSourceDir:g(`src/execution`)}}export{Tr as C,Fn as D,R as E,Ar as S,Er as T,to as _,Dd as a,ti as b,_c as c,To as d,xo as f,eo as g,$a as h,Ed as i,gc as l,W as m,Sd as n,gd as o,ho as p,Td as r,nd as s,jd as t,K as u,da as v,Dr as w,Mr as x,fa as y};
|
|
89
|
+
`&&(t.push(e.slice(n,r+1)),n=r+1);return n<e.length&&t.push(e.slice(n)),t}function ql(e,t){if(t.startLine===void 0&&t.endLine===void 0)return e;let n=Kl(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 Jl(e,t){return t===`utf-8`||t===`utf8`?new TextDecoder(`utf-8`,{fatal:!0}).decode(e):Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(t)}function Yl(e,t){return t===`utf-8`||t===`utf8`?new TextEncoder().encode(e):Buffer.from(e,t)}function Xl(e={}){return{name:`local`,async prewarm(e){let t=nu(jd(e.runtimeContext.appRoot),e.templateKey);if(await uu(t))return;let n=await Zl({sessionKey:e.templateKey,snapshotPath:t}),r=Wl($l(n));try{e.bootstrap!==void 0&&await e.bootstrap({use:async()=>r});for(let t of e.seedFiles)typeof t.content==`string`?await r.writeTextFile({content:t.content,path:t.path}):await r.writeBinaryFile({content:t.content,path:t.path});if(await n.captureSnapshot()===null)throw Error(`Failed to capture local sandbox template state for "${e.templateKey}".`)}finally{await n.dispose()}},async create(e){let t=jd(e.runtimeContext.appRoot),n=await cu(nu(t,e.templateKey));if(n===null)throw new Vl({backendName:`local`,templateKey:e.templateKey});let r=du(e.existingMetadata)??ru(t,e.sessionKey);return await uu(r)||await lu(r,n),Ql(await Zl({sessionKey:e.sessionKey,snapshotPath:r}))}}}async function Zl(e){let{Bash:t,InMemoryFs:n}=await import(`#compiled/just-bash/index.js`),r=await cu(e.snapshotPath),i=new n(iu(r));await au(i),await ou(i,r?.entries??[]);let a=new t({cwd:K,env:r?.env,fs:i,network:{dangerouslyAllowFullInternetAccess:!0}});return{async captureSnapshot(){let t=await su({filesystem:i,sandbox:a});return await lu(e.snapshotPath,t),{snapshotPath:e.snapshotPath}},async dispose(){await a.dispose?.()},async executeCommand(e){if(e.abortSignal?.aborted)throw new DOMException(`The operation was aborted.`,`AbortError`);let t=e.workingDirectory===void 0?e.command:`( cd ${X(e.workingDirectory)} && ${e.command} )`,n=a.exec(t),r=e.abortSignal?await eu(n,e.abortSignal):await n;return{exitCode:r.exitCode,stderr:r.stderr,stdout:r.stdout}},async readFileBytes(e){let t;try{t=await i.readFileBuffer(e)}catch{return null}return Buffer.from(t)},async readFileText(e){let t;try{t=await i.readFileBuffer(e)}catch{return null}return new TextDecoder(`utf-8`,{fatal:!0}).decode(t)},sessionKey:e.sessionKey,snapshotPath:e.snapshotPath,async writeFiles(e){for(let t of e){let e=x(t.path);await i.mkdir(e,{recursive:!0}),await i.writeFile(t.path,t.content)}}}}function Ql(e){let t=Wl($l(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 $l(e){return{id:e.sessionKey,resolvePath:tu,async runCommand(t){return await e.executeCommand(t)},async readFile(t){let n=await e.readFileBytes(t.path);return n===null?null:Ul(n)},async writeFile(t){let n=await Hl(t.content);await e.writeFiles([{content:n,path:t.path}])}}}async function eu(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 tu(e){return e.startsWith(`/`)?e:`${K}/${e}`}function nu(e,t){return S(e,`local`,`templates`,`${t}.json`)}function ru(e,t){return S(e,`local`,`sessions`,`${t}.json`)}function iu(e){let t={};for(let n of e?.entries??[])n.kind===`file`&&(t[n.path]=Buffer.from(n.contentBase64,`base64`));return t}async function au(e){await e.mkdir(K,{recursive:!0})}async function ou(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 su(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 cu(e){if(!await uu(e))return null;let t=JSON.parse(await he(e,`utf8`));return t.version===1?t:null}async function lu(e,t){await w(x(e),{recursive:!0}),await T(e,`${JSON.stringify(t,null,2)}\n`)}async function uu(e){try{return await pe(e),!0}catch{return!1}}function du(e){let t=e?.snapshotPath;return typeof t==`string`?t:void 0}function fu(e){return Xl({createOptions:e})}function pu(e={}){let t=e.loadSandboxModule??(async()=>await import(`#compiled/@vercel/sandbox/index.js`)),n={timeout:ju,...e.createOptions},r=new Map;return{name:`vercel`,async create(e){let i=Du(n.tags,e.tags),a;try{a=await mu({loadSandboxModule:t,prewarmedTemplates:r,templateKey:e.templateKey})}catch(t){throw Vl.is(t)?t:Error(`Failed to read sandbox template "${e.templateKey}": ${Au(t)}`,{cause:t})}let o;try{o=await gu({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}": ${Au(t)}`,{cause:t})}return _u(o,e.sessionKey)},async prewarm(e){let i;try{i=await hu({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}": ${Au(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 mu(e){let t=e.prewarmedTemplates.get(e.templateKey);if(t!==void 0)return t;let n=await Cu(await e.loadSandboxModule(),e.templateKey);if(n===null||typeof n.currentSnapshotId!=`string`)throw new Vl({backendName:`vercel`,templateKey:e.templateKey});return{sandboxName:n.name,snapshotId:n.currentSnapshotId,templateKey:e.templateKey}}async function hu(e){let t=await e.loadSandboxModule(),n=await Cu(t,e.templateKey),r=Du(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);let i=Tu(e.createOptions);if(typeof n.currentSnapshotId==`string`&&n.currentSnapshotId.length>0&&n.currentSnapshotId!==i)return{sandboxName:n.name,snapshotId:n.currentSnapshotId,templateKey:e.templateKey};await bu(n,e.createOptions);let a=Wl(vu(n,e.templateKey));e.bootstrap!==void 0&&await e.bootstrap({use:async e=>(e!==void 0&&await n.update(e),a)});for(let t of e.seedFiles)typeof t.content==`string`?await a.writeTextFile({content:t.content,path:t.path}):await a.writeBinaryFile({content:t.content,path:t.path});let o=await n.snapshot();return{sandboxName:n.name,snapshotId:o.snapshotId,templateKey:e.templateKey}}async function gu(e){let t=Eu(e.existingMetadata)??e.sessionKey,n=await Cu(e.sandboxModule,t);if(n!==null)return await Ou(n,e.tags),n;let{runtime:r,source:i,...a}=e.createOptions,o={...a,name:t,persistent:!0,source:{snapshotId:e.snapshotId,type:`snapshot`}};return e.tags!==void 0&&(o.tags=e.tags),await e.sandboxModule.Sandbox.create(o)}function _u(e,t){return{session:Wl(vu(e,t)),useSessionFn:async n=>(n!==void 0&&await e.update(n),Wl(vu(e,t))),async captureState(){return{backendName:`vercel`,metadata:{sandboxName:e.name},sessionKey:t}},async dispose(){}}}function vu(e,t){return{id:t,resolvePath:yu,async runCommand(t){let n=await e.runCommand({args:[`-lc`,t.command],cmd:`bash`,cwd:t.workingDirectory??`/workspace`,signal:t.abortSignal}),[r,i]=await Promise.all([n.stdout(),n.stderr()]);return{exitCode:n.exitCode,stderr:i,stdout:r}},async readFile(t){return await e.readFile({path:t.path})??null},async writeFile(t){let n=await Hl(t.content);await e.writeFiles([{content:n,path:t.path}])}}}function yu(e){return e.startsWith(`/`)?e:`${K}/${e}`}async function bu(e,t){await xu(e,{failureMessage:`Failed to initialize Vercel sandbox workspace.`,script:`mkdir -p ${K} && chown ${Su}:${Su} ${K}`}),t.networkPolicy!==`deny-all`&&await xu(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 xu(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 Su=`vercel-sandbox`;async function Cu(e,t){try{return await e.Sandbox.get({name:t})}catch(e){if(wu(e))return null;throw Error(`Failed to look up Vercel sandbox "${t}": ${Au(e)}`,{cause:e})}}function wu(e){return e instanceof Error?(e.response?.status??e.cause?.response?.status)===404:!1}function Tu(e){let t=e.source;if(t?.type===`snapshot`&&typeof t.snapshotId==`string`)return t.snapshotId}function Eu(e){let t=e?.sandboxName;return typeof t==`string`?t:void 0}function Du(e,t){let n={};if(e!==void 0)for(let[t,r]of Object.entries(e))n[t]=r;if(t!==void 0)for(let[e,r]of Object.entries(t))n[e]=r;let r=Object.keys(n).length;if(r!==0){if(r>Mu)throw Error(`Vercel Sandbox supports at most ${Mu} tags. Ash reserves "agent", "channel", and "sessionId"; remove or consolidate custom tags passed to vercelBackend().`);return n}}async function Ou(e,t){t===void 0||ku(e.tags,t)||await e.update({tags:t})}function ku(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 Au(e){return e instanceof Error?e.message:String(e)}const ju=1800*1e3,Mu=5;function Nu(e){return pu({createOptions:e})}function Pu(e){return Ti(()=>process.env.VERCEL?Nu(e?.vercel):fu(e?.local))}async function Fu(e,t,n){try{let r=c(await Q({definition:e,kindLabel:`sandbox`,moduleMap:t,nodeId:n}),`Expected the sandbox export "${e.exportName??`default`}" from "${e.logicalPath}" to return an object.`);return{backend:Iu(r.backend,e.logicalPath),bootstrap:r.bootstrap,description:e.description,exportName:e.exportName,logicalPath:e.logicalPath,onSession:r.onSession,sourceId:e.sourceId,sourceKind:`module`}}catch(t){throw t instanceof Z?t:new Z(`Failed to attach the sandbox lifecycle handlers from "${e.logicalPath}": ${p(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}function Iu(e,t){if(e===void 0)return Pu();if(typeof e==`function`)return Ti(e);if(typeof e!=`object`||!e)throw new Z(`Sandbox "${t}" exposed a non-object "backend" field. Use vercelBackend(), localBackend(), another factory that returns a SandboxBackend value, or a zero-arg callback returning one.`,{logicalPath:t});let n=e;if(typeof n.name!=`string`||n.name.length===0)throw new 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 Lu(e,t,n){try{let r=c(await Q({definition:e,kindLabel:`tool`,moduleMap:t,nodeId:n}),$(e,`to return an object`));zi(`tool:${r.description}`,{kind:`tool`,name:e.name});let i=o(r.execute,$(e,`to provide an execute function`));return{description:e.description,execute:i,exportName:e.exportName,inputSchema:e.inputSchema,logicalPath:e.logicalPath,name:e.name,sourceId:e.sourceId,sourceKind:`module`,...Ru(r,e)}}catch(t){throw t instanceof Z?t:new Z(`Failed to attach the tool execute function from "${e.logicalPath}": ${p(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}function Ru(e,t){let n={};e.onCompact!==void 0&&(n.onCompact=o(e.onCompact,$(t,`to provide an onCompact function`))),e.needsApproval!==void 0&&(n.needsApproval=o(e.needsApproval,$(t,`to provide a needsApproval function`)));let r=zu(e,t);return r!==void 0&&(n.retentionPolicy=r),e.toModelOutput!==void 0&&(n.toModelOutput=o(e.toModelOutput,$(t,`to provide a toModelOutput function`))),e.inputSchema!==void 0&&Bu(e.inputSchema)&&(n.inputStandardSchema=e.inputSchema),n}function zu(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 Bu(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 Ll(t,e.moduleMap,e.nodeId))}let i=await Promise.all(e.manifest.tools.map(t=>Lu(t,e.moduleMap,e.nodeId))),a=await Promise.all(e.manifest.hooks.map(t=>zl(t,e.moduleMap,e.nodeId))),o=await Promise.all(e.manifest.connections.map(t=>Rl(t,e.moduleMap,e.nodeId))),s=e.manifest.sandbox===null?null:await Fu(e.manifest.sandbox,e.moduleMap,e.nodeId),c=Hu(e.manifest.instructions),l=e.manifest.workspaceResourceRoot,u={channels:n,config:Uu(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 Hu(e){if(e!==void 0)return{name:e.name,logicalPath:e.logicalPath,markdown:e.markdown,sourceId:e.sourceId,sourceKind:e.sourceKind}}function Uu(e){let t={metadata:{...e.config.metadata},model:e.config.model.source===void 0?{id:e.config.model.id,contextWindowTokens:e.config.model.contextWindowTokens,providerOptions:e.config.model.providerOptions}:{contextWindowTokens:e.config.model.contextWindowTokens,id:e.config.model.id,providerOptions:e.config.model.providerOptions,source:{exportName:e.config.model.source.exportName,sourceKind:`module`,logicalPath:e.config.model.source.logicalPath,sourceId:e.config.model.source.sourceId}},name:e.config.name};if(e.config.compaction!==void 0){let n={};e.config.compaction.model!==void 0&&(n.model=e.config.compaction.model.source===void 0?{contextWindowTokens:e.config.compaction.model.contextWindowTokens,id:e.config.compaction.model.id,providerOptions:e.config.compaction.model.providerOptions}:{contextWindowTokens:e.config.compaction.model.contextWindowTokens,id:e.config.compaction.model.id,providerOptions:e.config.compaction.model.providerOptions,source:{exportName:e.config.compaction.model.source.exportName,sourceKind:`module`,logicalPath:e.config.compaction.model.source.logicalPath,sourceId:e.config.compaction.model.source.sourceId}}),e.config.compaction.thresholdPercent!==void 0&&(n.thresholdPercent=e.config.compaction.thresholdPercent),t.compaction=n}return e.config.source!==void 0&&(t.source=Il(e.config.source)),t}function Wu(e){return{sandbox:{definition:e.authoredSandbox??Gu(),workspaceResourceRoot:e.workspaceResourceRoot}}}function Gu(){return{backend:Pu(),logicalPath:`ash:framework/default-sandbox`,sourceId:`ash:default-sandbox`,sourceKind:`module`}}const Ku=`load_skill`,qu=Object.freeze({type:`object`,properties:Object.freeze({message:Object.freeze({type:`string`,description:`The message to send to the subagent. Provide all context the subagent needs to complete the task; the subagent does not see the parent's history.`})}),required:Object.freeze([`message`]),additionalProperties:!1});function Ju(e){let t=[],n=new Ua(`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=Yu(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 Yu(e){return{description:e.description,inputSchema:qu,kind:`subagent`,logicalPath:e.logicalPath,name:e.name,nodeId:e.nodeId,sourceId:e.sourceId}}async function Xu(e,t={}){let n=[],r=new Ua(`tool`,t.reservedToolNames??[]);for(let t of e.tools){let e=await Zu(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 Zu(e){return{description:e.description,inputSchema:await Qu(e),kind:`authored-tool`,logicalPath:e.logicalPath,name:e.name,sourceId:e.sourceId}}async function Qu(e){return e.inputSchema}var $u=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 ed(e){let t=new Map,n=id(e.manifest),r=new Map(e.manifest.subagents.map(e=>[e.nodeId,e]));return{nodesByNodeId:t,root:await td({childNodeIdsByParentNodeId:n,manifest:e.manifest,moduleMap:e.moduleMap,nodeId:R,nodesByNodeId:t,subagentNodesById:r})}}async function td(e){let t=ad(e.nodeId);if(e.nodesByNodeId.has(t))throw new $u(`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=Nl({hasConnections:r}),a=r?sd(i,n.connections):i,o=new Set(a.map(e=>e.name)),s=Pl(),c=new Set(n.tools.map(e=>e.name));for(let r of n.disabledFrameworkTools)if(!s.has(r))throw new $u(`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 Xu({tools:[...a.filter(e=>!c.has(e.name)&&!l.has(e.name)),...n.tools]},{reservedToolNames:o.has(`load_skill`)||c.has(`load_skill`)?[]:[Ku]}),d=new Set(n.channels.map(e=>e.name)),f=hc();for(let r of n.disabledFrameworkChannels)if(!f.has(r))throw new $u(`agent/channels/${r}.ts exports disableRoute() but "${r}" is not a framework channel. Rename the file to one of: ${[...f].sort().join(`, `)}.`,{nodeId:t,sourceId:e.sourceId});let p=new Set(n.disabledFrameworkChannels),m=[...mc().filter(e=>!d.has(e.name)&&!p.has(e.name)),...n.channels],h=Wu({authoredSandbox:n.sandbox,workspaceResourceRoot:n.workspaceResourceRoot}),g=Ju({reservedToolNames:[Ku,...u.preparedTools.map(e=>e.name)],subagents:await nd({childNodeIdsByParentNodeId:e.childNodeIdsByParentNodeId,moduleMap:e.moduleMap,nodesByNodeId:e.nodesByNodeId,parentNodeId:e.nodeId,subagentNodesById:e.subagentNodesById})}),_={agent:n,channels:m,hookRegistry:Fl(n.hooks),nodeId:t,sandboxRegistry:h,sourceId:e.sourceId,subagentRegistry:g,toolRegistry:u,turnAgent:as({agent:n,nodeId:t,tools:[...u.preparedTools,...g.preparedTools]})};return e.nodesByNodeId.set(t,_),_}async function nd(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 $u(`Missing compiled subagent node "${r}" while resolving runtime subagents.`,{nodeId:ad(e.parentNodeId),sourceId:r});t.push(await rd({childNodeIdsByParentNodeId:e.childNodeIdsByParentNodeId,moduleMap:e.moduleMap,nodesByNodeId:e.nodesByNodeId,sourceRef:n,subagentNodesById:e.subagentNodesById}))}return t}async function rd(e){let t={description:e.sourceRef.description,logicalPath:e.sourceRef.logicalPath,name:e.sourceRef.name,nodeId:ad(e.sourceRef.nodeId),sourceId:e.sourceRef.sourceId,sourceKind:`module`};return await td({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 id(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 ad(e){return e===`__root__`?yo:e}const od=Ko.name;function sd(e,t){let n=t.map(e=>e.connectionName).join(`, `);return e.map(e=>e.name===od?{...e,description:`${e.description} Available connections: ${n}.`}:e)}const cd=process.env.ASH_DISABLE_AGENT_CACHE===`1`;async function ld(e){let[t,n]=await Promise.all([Co({compiledArtifactsSource:e}),ud(e)]),r=await ed({manifest:t,moduleMap:n}),i=r.root;return{adapterRegistry:qa({channels:hd(r)}),compiledArtifactsSource:e,graph:r,hookRegistry:i.hookRegistry,moduleMap:n,resolvedAgent:i.agent,subagentRegistry:i.subagentRegistry,toolRegistry:i.toolRegistry,turnAgent:i.turnAgent}}async function ud(e){return e.kind===`disk`&&e.moduleMapLoadMode===`authored-source`?await dd(e):await Oo({compiledArtifactsSource:e})}async function dd(e){if(e.moduleMapLoaderPath===void 0)throw Error(`Authored-source module map loading requires "moduleMapLoaderPath" in the compiled artifacts source.`);return await(await import(we(e.moduleMapLoaderPath).href)).loadCompiledModuleMapFromAuthoredSource({compiledArtifactsSource:e})}async function fd(e){if(cd)return ld(e);let t=so(),n=$a(e),r=await go(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=ld(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 pd(e){let t=await fd(e.compiledArtifactsSource);if(e.nodeId===void 0)return t;let n=bo(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 md(){let e=so();e.bundleCache.clear(),e.bundleCacheKeyBySourceKey.clear()}function hd(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:Pa(e),state:e.state?{...e.state}:{}}},deserialize(e,t){let n=t.get(gd);if(n===void 0)throw Error(`Cannot deserialize "ash.channel" before "ash.bundle". The runtime bundle must be present in context.`);return Ja(n.adapterRegistry,e)}}});const gd=new V(`ash.bundle`,{codec:{serialize:e=>({nodeId:e.nodeId,source:e.compiledArtifactsSource}),deserialize:e=>{let{source:t,nodeId:n}=e;return pd({compiledArtifactsSource:t,nodeId:n})}}});new V(`ash.session`);const _d=new V(`ash.sandbox`),vd=`workflowEntry`,yd=`turnWorkflow`,bd=_(),xd=new Set([vd,yd]),Sd=bd.name,Cd={workflowId:`workflow//${Sd}//${vd}`};`${Sd}${yd}`;function wd(e=process.cwd()){return C(e)}function Td(e){return ye(`sha256`).update(e).digest(`hex`).slice(0,12)}function Ed(){return!!process.env.VERCEL}function Dd(e,t=`all`){let n=S(e,`.ash`,`nitro`);return t===`all`?n:S(n,t)}function Od(e,t){return S(e,`.ash`,`nitro-output`,t)}function kd(e){let t=S(m(),`.ash`,`workflow-cache`);return Ad(t),S(t,Td(e))}function Ad(e){if(!be(e))return;let t=_().version,n;try{n=Se(e)}catch{return}for(let r of n){let n=S(e,r),i=S(n,`ash-cache.json`);if(be(i))try{let e=JSON.parse(xe(i,`utf8`));typeof e.ashVersion==`string`&&e.ashVersion!==t&&Ce(n,{force:!0,recursive:!0})}catch{}}}function jd(e){return S(e,`.ash`,`sandbox-cache`)}function Md(e){return Ed()?S(e,`.vercel`,`output`):S(e,`.output`)}function Nd(e){return{appRoot:e,outputDir:Md(e),workflowId:Cd.workflowId,workflowBuildDir:kd(e),workflowSourceDir:g(`src/execution`)}}export{Ar as C,R as D,Er as E,Fn as O,Mr as S,Dr as T,Qa as _,kd as a,fa as b,ed as c,K as d,Co as f,Za as g,W as h,Od as i,hc as l,po as m,wd as n,xd as o,yo as p,Dd as r,md as s,Nd as t,mc as u,$a as v,Tr as w,ti as x,da as y};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{C as e,D as t,E as n,S as r,_ as i,a,b as o,c as s,d as c,f as l,g as u,h as d,l as f,m as ee,u as p,v as m}from"./paths-OknjaYR8.js";import{t as h}from"./authored-module-loader-XcFLnl49.js";import{t as g}from"./errors-DsO9xmQL.js";import{i as _,t as v}from"./package-DmsQgn4v.js";import{join as y,posix as b}from"node:path";import{mkdir as te,readFile as ne,readdir as re,realpath as ie,writeFile as x}from"node:fs/promises";import{createHash as S}from"node:crypto";import{existsSync as C}from"node:fs";function w(e){return e.dev?{appRoot:e.appRoot,dev:e.dev,moduleMapLoaderPath:_(`src/internal/authored-module-map-loader.ts`)}:{appRoot:e.appRoot,dev:e.dev}}const T=`#ash-channel/`;function E(e){let t=e.compileResult.manifest.channels,n=new Set,r=[],i=new Set,a=f();for(let e of t){if(e.kind===`disabled`){if(!a.has(e.name))throw Error(`agent/channels/${e.name}.ts exports disableRoute() but "${e.name}" is not a framework channel. Rename the file to one of: ${[...a].sort().join(`, `)}.`);i.add(e.name);continue}n.add(e.name),r.push({method:e.method,route:e.urlPath})}let o=p().filter(e=>!n.has(e.name)&&!i.has(e.name)).map(e=>({method:e.method,route:e.urlPath})),s=new Set,c=[];for(let e of[...o,...r]){let t=k(e);s.has(t)||(s.add(t),c.push(e))}return c}function D(e,t){for(let n of t.registrations)A(e,{artifactsConfig:t.artifactsConfig,method:n.method,route:n.route})}function O(e,t){return N(t.previous,t.next)?!1:(j(e),D(e,{artifactsConfig:t.artifactsConfig,registrations:t.next}),e.routing.sync(),!0)}function k(e){return`${e.method.toUpperCase()} ${e.route}`}function A(e,t){let r=k(t),i=`${T}${r}`,a=n(_(`src/internal/nitro/routes/channel-dispatch.ts`));e.options.handlers.push({handler:i,method:t.method,route:t.route}),e.options.virtual[i]=[`import { dispatchChannelRequest } from ${a};`,`const config = ${JSON.stringify(t.artifactsConfig)};`,`export default (event) => dispatchChannelRequest(event, ${JSON.stringify(r)}, config);`].join(`
|
|
2
|
+
`)}function j(e){for(let t=e.options.handlers.length-1;t>=0;--t){let n=e.options.handlers[t];n!==void 0&&M(n)&&e.options.handlers.splice(t,1)}for(let t of Object.keys(e.options.virtual))t.startsWith(T)&&delete e.options.virtual[t]}function M(e){return e.handler.startsWith(T)}function N(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(r===void 0||i===void 0||r.method!==i.method||r.route!==i.route)return!1}return!0}const P=`ash.schedule.`;var F=class extends Error{scheduleId;sourceId;taskName;constructor(e,t={}){super(e),this.name=`ScheduleRegistrationError`,t.scheduleId!==void 0&&(this.scheduleId=t.scheduleId),t.sourceId!==void 0&&(this.sourceId=t.sourceId),t.taskName!==void 0&&(this.taskName=t.taskName)}};function I(e){let t=e.map(e=>({cron:e.cron,description:`Run Ash schedule "${e.name}" from "${e.logicalPath}".`,logicalPath:e.logicalPath,scheduleId:e.name,sourceId:e.sourceId,taskName:R(e.sourceId)})).sort((e,t)=>e.sourceId.localeCompare(t.sourceId));return L(t),t}function L(e){let t=new Map;for(let n of e){let e=t.get(n.scheduleId);if(e===void 0){t.set(n.scheduleId,n);continue}throw new F(`Duplicate authored schedule id "${n.scheduleId}" found in "${e.logicalPath}" and "${n.logicalPath}".`,{scheduleId:n.scheduleId,sourceId:n.sourceId,taskName:n.taskName})}}function R(e){return`${P}${Buffer.from(e,`utf8`).toString(`base64url`)}`}const z=`#ash-schedule-task/`;function B(e,t){if(t.registrations.length!==0){e.options.experimental.tasks=!0;for(let n of t.registrations)U(e,{artifactsConfig:t.artifactsConfig,dispatchModulePath:t.dispatchModulePath,registration:n})}}function V(e,t){let n=!G(t.previous,t.next);return H(e),B(e,{artifactsConfig:t.artifactsConfig,dispatchModulePath:t.dispatchModulePath,registrations:t.next}),n}function H(e){for(let t of Object.keys(e.options.tasks))t.startsWith(`ash.schedule.`)&&delete e.options.tasks[t];for(let t of Object.keys(e.options.virtual))t.startsWith(z)&&delete e.options.virtual[t];for(let[t,n]of Object.entries(e.options.scheduledTasks)){let r=ae(n).filter(e=>!e.startsWith(P));if(r.length===0){delete e.options.scheduledTasks[t];continue}if(r.length===1){let[n]=r;n!==void 0&&(e.options.scheduledTasks[t]=n);continue}e.options.scheduledTasks[t]=r}}function U(e,t){let r=`${z}${t.registration.taskName}`,i=n(t.dispatchModulePath);e.options.tasks[t.registration.taskName]={description:t.registration.description,handler:r},e.options.virtual[r]=[`import { dispatchScheduleTask } from ${i};`,`const config = ${JSON.stringify(t.artifactsConfig)};`,`export default {`,` meta: { description: ${JSON.stringify(t.registration.description)} },`,` async run(event) {`,` return { result: await dispatchScheduleTask(event.name, config) };`,` },`,`};`].join(`
|
|
3
|
+
`),W(e,t.registration.cron,t.registration.taskName)}function W(e,t,n){let r=e.options.scheduledTasks[t];if(r===void 0){e.options.scheduledTasks[t]=n;return}if(typeof r==`string`){e.options.scheduledTasks[t]=[r,n];return}r.includes(n)||r.push(n)}function ae(e){return typeof e==`string`?[e]:[...e]}function G(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(r===void 0||i===void 0||r.cron!==i.cron||r.description!==i.description||r.logicalPath!==i.logicalPath||r.scheduleId!==i.scheduleId||r.sourceId!==i.sourceId||r.taskName!==i.taskName)return!1}return!0}async function K(e){return[...e.manifest.schedules].map(e=>{let t={cron:e.cron,hasRun:e.hasRun,logicalPath:e.logicalPath,name:e.name,sourceId:e.sourceId,sourceKind:e.sourceKind};return e.markdown===void 0?t:{...t,markdown:e.markdown}})}async function q(e){return await K({manifest:await l({compiledArtifactsSource:e.compiledArtifactsSource})})}async function J(e){let t=y(e.outDir,`compiled-artifacts-bootstrap.mjs`),n=y(e.outDir,`compiled-artifacts-instrumentation.mjs`),r=se(e.compileResult.manifest.agentRoot);await te(e.outDir,{recursive:!0}),await x(t,await le({compileResult:e.compileResult,installModulePath:_(`src/runtime/loaders/bundled-artifacts.ts`),moduleMapPath:t,metadata:e.compileResult.metadata})),r!==void 0&&await x(n,ue({agentName:e.compileResult.manifest.config.name,instrumentationPath:r,registerConfigPath:_(`src/harness/instrumentation-config.ts`)}));let i={bootstrapPath:t};return r!==void 0&&(i.instrumentationPluginPath=n,i.instrumentationSourcePath=r),i}const oe=[`.ts`,`.mts`,`.js`,`.mjs`];function se(e){for(let t of oe){let n=y(e,`instrumentation${t}`);if(C(n))return n}}function ce(e){return e.replace(/^export const moduleMap = /m,`const moduleMap = `).replace(/\nexport default moduleMap;\n?$/,`
|
|
4
|
+
`)}async function le(t){let r=ce(e({importSpecifierStyle:`absolute`,manifest:t.compileResult.manifest,moduleMapPath:t.moduleMapPath})).trim();return[`// Generated by Ash. Do not edit by hand.`,`import { installBundledCompiledArtifacts } from ${n(t.installModulePath)};`,``,r,``,`const metadata = ${JSON.stringify(t.metadata,null,2)};`,``,`const manifest = ${JSON.stringify(t.compileResult.manifest,null,2)};`,``,`export function installCompiledArtifactsBootstrap() {`,` installBundledCompiledArtifacts({`,` manifest,`,` metadata,`,` moduleMap,`,` });`,`}`,``,`installCompiledArtifactsBootstrap();`,``,`// Default export satisfies the Nitro plugin contract so this file`,`// can be used directly as a Nitro plugin without a separate wrapper.`,`export default function installCompiledArtifactsPlugin() {`,` // Already installed on import above.`,`}`,``,`export async function __ashInstallCompiledArtifactsStep() {`,` "use step";`,` return null;`,`}`,``].join(`
|
|
5
|
+
`)}function ue(e){return[`// Generated by Ash. Do not edit by hand.`,`import * as instrumentationModule from ${n(e.instrumentationPath)};`,`import { registerInstrumentationConfig } from ${n(e.registerConfigPath)};`,``,`if (instrumentationModule.default != null) {`,` registerInstrumentationConfig(instrumentationModule.default, { agentName: ${JSON.stringify(e.agentName)} });`,`}`,``,`// Default export satisfies the Nitro plugin contract so this file`,`// can be used directly as a Nitro plugin without a separate wrapper.`,`export default function installInstrumentationPlugin() {}`,``].join(`
|
|
6
|
+
`)}function Y(e){return u(e,{moduleMapLoaderPath:_(`src/internal/authored-module-map-loader.ts`),moduleMapLoadMode:`authored-source`})}async function de(e){let t=await o({startPath:e}),n=await q({compiledArtifactsSource:Y(t.project.appRoot)}),r=I(n),i=a(t.project.appRoot),s=await J({compileResult:t,outDir:t.paths.compileDirectoryPath});return{appRoot:t.project.appRoot,compileResult:t,compiledArtifacts:s,scheduleRegistrations:r,schedules:n,workflowBuildDir:i}}async function fe(e){return await pe(await l({compiledArtifactsSource:e.compiledArtifactsSource}))}async function pe(e){let n={},r=[{agentRoot:e.agentRoot,manifest:e,nodeId:t},...[...e.subagents].sort((e,t)=>e.nodeId.localeCompare(t.nodeId)).map(e=>({agentRoot:e.agent.agentRoot,manifest:e.agent,nodeId:e.nodeId}))];for(let e of r)n[e.nodeId]={modules:await me({agentRoot:e.agentRoot,manifest:e.manifest})};return{nodes:n}}async function me(e){let t=r(e.manifest).sort((e,t)=>e.sourceId.localeCompare(t.sourceId)),n={};for(let r of t){let t=y(e.agentRoot,r.logicalPath);n[r.sourceId]=await h(t)}return n}async function he(e){let t=await ge(e.backendName,e.compiledArtifactsSource),n=await _e({compiledArtifactsSource:e.compiledArtifactsSource,nodeId:e.nodeId,sourceId:e.sourceId}),r=X(`${v().version}:2:${n}`).slice(0,20);return ve(`ash-sbx-tpl-${e.backendName}-${t}-${r}`)}async function ge(e,t){if(e===`vercel`){let e=process.env.VERCEL_DEPLOYMENT_ID?.trim();if(e!==void 0&&e.length>0)return X(e).slice(0,16)}let n=i(t);return n===void 0?X(m(t)).slice(0,16):X(await ie(n)).slice(0,16)}async function _e(e){return X(`${(await ee({compiledArtifactsSource:e.compiledArtifactsSource}))?.discovery.sourceGraphHash??m(e.compiledArtifactsSource)}:${e.nodeId}:${e.sourceId}`)}function X(e){return S(`sha256`).update(e).digest(`hex`)}function ve(e){return e.replaceAll(/[^a-zA-Z0-9._-]+/g,`-`).slice(0,120)}async function ye(e){let t=[];return await Z({files:t,logicalDirectoryPath:`.`,sourceDirectoryPath:e}),t.sort((e,t)=>e.path.localeCompare(t.path)),t}async function Z(e){let t=await re(e.sourceDirectoryPath,{withFileTypes:!0});for(let n of t){if(!n.isDirectory()&&!n.isFile())continue;let t=y(e.sourceDirectoryPath,n.name),r=b.join(e.logicalDirectoryPath,n.name);if(n.isDirectory()){await Z({files:e.files,logicalDirectoryPath:r,sourceDirectoryPath:t});continue}e.files.push({content:await ne(t),path:b.join(c,r)})}}async function be(e){let t=await Q(e);if(t.length===0)return;e.log?.(`Ash: initializing ${t.length} sandbox ${$(t.length,`template`)}...`);let n=e.dispatch??(async({backend:e,input:t})=>{await e.prewarm(t)});await Promise.all(t.map(async({backend:t,label:r,input:i})=>{e.log?.(`Ash: initializing sandbox template "${r}"...`);try{await n({backend:t,input:i})}catch(n){throw e.log?.(`Ash: failed to initialize sandbox template "${r}" on backend "${t.name}": ${g(n)}`),n}e.log?.(`Ash: sandbox template "${r}" initialized.`)})),e.log?.(`Ash: initialized ${t.length} sandbox ${$(t.length,`template`)}.`)}async function xe(e){let t=Y(e.appRoot),n=await(e.loadAgentGraph??Ce)({compiledArtifactsSource:t});await be({compiledArtifactsSource:t,dispatch:e.dispatch,graph:n,log:e.log})}async function Q(e){let t=d(e.compiledArtifactsSource.appRoot).compileDirectoryPath,n={appRoot:e.compiledArtifactsSource.appRoot};return[...await Promise.all(we(e.graph).map(async({definition:r,nodeId:i,workspaceResourceRoot:a})=>{let o=await he({backendName:r.backend.name,compiledArtifactsSource:e.compiledArtifactsSource,nodeId:i,sourceId:r.sourceId});return{backend:r.backend,label:Te(i),input:{bootstrap:r.bootstrap,seedFiles:await Se({compileDirectoryPath:t,workspaceResourceRoot:a}),runtimeContext:n,templateKey:o}}}))].sort((e,t)=>e.label.localeCompare(t.label))}async function Se(e){return e.workspaceResourceRoot.rootEntries.length===0?[]:(await ye(`${e.compileDirectoryPath}/${e.workspaceResourceRoot.logicalPath}`)).map(e=>({content:e.content,path:e.path}))}async function Ce(e){let[t,n]=await Promise.all([l({compiledArtifactsSource:e.compiledArtifactsSource}),fe({compiledArtifactsSource:e.compiledArtifactsSource})]);return await s({manifest:t,moduleMap:n})}function we(e){return[...e.nodesByNodeId.entries()].flatMap(([e,t])=>{let n=t.sandboxRegistry.sandbox;return n===null?[]:[{...n,nodeId:e}]})}function $(e,t){return e===1?t:`${t}s`}function Te(e){return e===`__root__`?`root`:e}export{E as a,w as c,V as i,de as n,D as o,B as r,O as s,xe as t};
|