experimental-ash 0.25.0 → 0.25.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/dist/src/channel/routes.d.ts +6 -1
- package/dist/src/channel/send.js +5 -2
- package/dist/src/channel/session-callback.d.ts +10 -0
- package/dist/src/channel/session-callback.js +65 -0
- package/dist/src/channel/types.d.ts +19 -0
- package/dist/src/chunks/{client-BShLWzR6.js → client-ZqNLLMZB.js} +3 -3
- package/dist/src/chunks/{compile-agent-75wLLW-E.js → compile-agent-C4OrJW6C.js} +1 -1
- package/dist/src/chunks/{dev-authored-source-watcher-DqoJsDup.js → dev-authored-source-watcher-PwAxalwl.js} +1 -1
- package/dist/src/chunks/host-F-DkwYJK.js +70 -0
- package/dist/src/chunks/paths-DnlVBqHu.js +85 -0
- package/dist/src/chunks/{token-BOkIxJeV.js → token-YW4VSeBB.js} +1 -1
- package/dist/src/chunks/types-BJSR0JNV.js +1 -0
- package/dist/src/cli/commands/info.js +1 -1
- package/dist/src/cli/dev/repl.js +3 -3
- package/dist/src/cli/run.js +1 -1
- package/dist/src/client/index.d.ts +1 -1
- package/dist/src/client/message-reducer.js +6 -0
- package/dist/src/context/keys.d.ts +1 -1
- package/dist/src/context/keys.js +1 -1
- package/dist/src/context/seed-keys.d.ts +5 -1
- package/dist/src/context/seed-keys.js +4 -0
- package/dist/src/evals/cli/eval.js +1 -1
- package/dist/src/execution/await-authorization-orchestrator.d.ts +0 -2
- package/dist/src/execution/await-authorization-orchestrator.js +12 -20
- package/dist/src/execution/connection-auth-steps.js +1 -4
- package/dist/src/execution/node-step.js +13 -0
- package/dist/src/execution/remote-agent-dispatch.d.ts +15 -0
- package/dist/src/execution/remote-agent-dispatch.js +79 -0
- package/dist/src/execution/runtime-context.js +4 -1
- package/dist/src/execution/session-callback-step.d.ts +16 -0
- package/dist/src/execution/session-callback-step.js +72 -0
- package/dist/src/execution/subagent-invocation.d.ts +16 -0
- package/dist/src/execution/subagent-invocation.js +16 -0
- package/dist/src/execution/subagent-tool.js +5 -8
- package/dist/src/execution/turn-workflow.js +0 -1
- package/dist/src/execution/workflow-entry.js +21 -1
- package/dist/src/execution/workflow-steps.d.ts +6 -3
- package/dist/src/execution/workflow-steps.js +79 -37
- package/dist/src/harness/execute-tool.d.ts +3 -3
- package/dist/src/harness/runtime-actions.d.ts +1 -0
- package/dist/src/harness/runtime-actions.js +18 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/protocol/message.d.ts +6 -0
- package/dist/src/protocol/message.js +1 -0
- package/dist/src/protocol/routes.d.ts +11 -0
- package/dist/src/protocol/routes.js +13 -0
- package/dist/src/public/channels/ash.js +25 -1
- package/dist/src/runtime/actions/keys.js +2 -0
- package/dist/src/runtime/actions/types.d.ts +47 -1
- package/dist/src/runtime/actions/types.js +23 -0
- package/dist/src/runtime/connections/callback-route.d.ts +1 -1
- package/dist/src/runtime/connections/callback-route.js +1 -1
- package/dist/src/runtime/connections/mcp-client.d.ts +1 -2
- package/dist/src/runtime/connections/mcp-client.js +69 -3
- package/dist/src/runtime/framework-channels/index.js +7 -2
- package/dist/src/runtime/framework-tools/connection-search.d.ts +0 -46
- package/dist/src/runtime/framework-tools/connection-search.js +3 -78
- package/dist/src/runtime/framework-tools/connection-tools.d.ts +3 -6
- package/dist/src/runtime/framework-tools/connection-tools.js +6 -13
- package/dist/src/runtime/session-callback-route.d.ts +6 -0
- package/dist/src/runtime/session-callback-route.js +87 -0
- package/package.json +1 -1
- package/dist/src/chunks/host-JVy7fewA.js +0 -70
- package/dist/src/chunks/paths-DNjq5JOy.js +0 -85
- package/dist/src/chunks/types-CjIyrcYo.js +0 -1
|
@@ -1,85 +0,0 @@
|
|
|
1
|
-
import{c as e,d as t,f as n,l as r,o as i,p as a,s as o,t as s,u as c}from"./authored-module-loader-DcCfCiBm.js";import{n as l,t as u}from"./guards-26p6sOw3.js";import{t as d}from"./errors-HYWjHxV6.js";import{a as f,d as p,i as m,l as h,n as g,o as _,r as ee,s as te,t as ne,v as re,y as ie}from"./types-CjIyrcYo.js";import{t as ae}from"./runtime-model-Dh0Nz64z.js";import{createRequire as oe}from"node:module";import{z as v}from"#compiled/zod/index.js";import{basename as se,dirname as y,join as b,posix as ce,relative as le,resolve as x,sep as ue}from"node:path";import{access as de,cp as fe,mkdir as S,readFile as pe,rm as me,writeFile as C}from"node:fs/promises";import{createHash as he}from"node:crypto";import{existsSync as w,readFileSync as ge,readdirSync as _e,realpathSync as ve,rmSync as ye}from"node:fs";import{fileURLToPath as be,pathToFileURL as xe}from"node:url";import{Buffer as Se}from"node:buffer";import"#compiled/@workflow/errors/index.js";import{resumeHook as Ce}from"#compiled/@workflow/core/runtime.js";import{AsyncLocalStorage as we}from"node:async_hooks";import{SpanStatusCode as Te,trace as Ee}from"#compiled/@opentelemetry/api/index.js";import{getErrorMessage as De}from"#compiled/@ai-sdk/provider/index.js";import{inspect as Oe}from"node:util";import{fromError as ke}from"#compiled/zod-validation-error/index.js";import{createRemoteJWKSet as Ae,decodeJwt as je,jwtVerify as Me}from"#compiled/jose/index.js";import"ai";import Ne from"#compiled/turndown/index.js";const Pe=v.union([v.literal(`error`),v.literal(`warning`)]);v.object({code:v.string(),message:v.string(),severity:Pe,sourcePath:v.string()}).strict();const Fe=v.object({errors:v.number().finite(),warnings:v.number().finite()}).strict(),Ie=`discover/project-not-found`;function Le(e){return{...e,severity:`error`}}function Re(e){return{...e,severity:`warning`}}function ze(e){return e.reduce((e,t)=>(t.severity===`error`?e.errors+=1:e.warnings+=1,e),{errors:0,warnings:0})}function Be(e){return e.some(e=>e.severity===`error`)}const Ve=[`.cts`,`.mts`,`.cjs`,`.mjs`,`.ts`,`.js`],He=new Set([`package.json`,`vercel.json`]);function Ue(e){return e.isDirectory()?`directory`:e.isFile()?`file`:`other`}function We(e,t){return t===`file`&&He.has(e)}function Ge(e,t){if(t===`file`)return E(e,`agent`)?`agent-config-module`:e===`instructions.md`?`instructions-markdown`:E(e,`instructions`)?`instructions-module`:e===`system.md`?`system-markdown`:E(e,`system`)?`system-module`:`unknown`;if(t===`directory`){if(e===`channels`)return`channels-directory`;if(e===`connections`)return`connections-directory`;if(e===`hooks`)return`hooks-directory`;if(e===`lib`)return`lib-directory`;if(e===`skills`)return`skills-directory`;if(e===`sandbox`)return`sandbox-directory`;if(e===`tools`)return`tools-directory`;if(e===`schedules`)return`schedules-directory`;if(e===`subagents`)return`subagents-directory`}return`unknown`}function Ke(e,t){if(t===`file`)return E(e,`agent`)?`agent-config-module`:e===`instructions.md`?`instructions-markdown`:E(e,`instructions`)?`instructions-module`:e===`system.md`?`system-markdown`:E(e,`system`)?`system-module`:`unknown`;if(t===`directory`){if(e===`connections`)return`connections-directory`;if(e===`hooks`)return`hooks-directory`;if(e===`lib`)return`lib-directory`;if(e===`sandbox`)return`sandbox-directory`;if(e===`skills`)return`skills-directory`;if(e===`tools`)return`tools-directory`;if(e===`subagents`)return`subagents-directory`;if(e===`schedules`)return`invalid-schedules-directory`}return`unknown`}function qe(e,t){if(t===`file`)return e===`SKILL.md`?`skill-markdown`:`skill-resource`;if(t===`directory`){if(e===`scripts`)return`skill-scripts-directory`;if(e===`references`)return`skill-references-directory`;if(e===`assets`)return`skill-assets-directory`}return`skill-resource`}function Je(e,t){if(t===`directory`)return`skill-package-directory`;if(t===`file`){if(e.endsWith(`.md`))return`flat-skill-markdown`;if(Ye(e)!==null)return`flat-skill-module`}return`unknown`}function T(e){return e.replaceAll(ue,`/`).replace(/^\.\//,``).replace(/^\/+/,``)}function Ye(e){for(let t of Ve)if(e.endsWith(t)&&e.length>t.length)return e.slice(0,-t.length);return null}function E(e,t){return Ye(e)===t}function D(e){let t=T(e),n=t.lastIndexOf(`/`),r=t.lastIndexOf(`.`);return r===-1||r<n?t:t.slice(0,r)}function Xe(t,r){let i=o(t,r);if(e(i,[`build`,`compaction`,`description`,`metadata`,`model`,`modelContextWindowTokens`,`modelOptions`],r),i.model===void 0)throw Error(`${r} The "model" field is required.`);let a={model:i.model};i.description!==void 0&&(a.description=c(i.description,r));let s=n(i,`metadata`,r);return s!==void 0&&(a.metadata=s),i.compaction!==void 0&&(a.compaction=et(i.compaction,r)),i.build!==void 0&&(a.build=Qe(i.build,r)),i.modelOptions!==void 0&&(a.modelOptions=$e(i.modelOptions,r)),i.modelContextWindowTokens!==void 0&&(a.modelContextWindowTokens=Ze(i.modelContextWindowTokens,r)),a}function Ze(e,t){if(typeof e!=`number`||!Number.isInteger(e)||e<=0)throw Error(t);return e}function Qe(t,n){let r=o(t,n);e(r,[`externalDependencies`],n);let i={};if(r.externalDependencies!==void 0){if(!Array.isArray(r.externalDependencies))throw Error(n);i.externalDependencies=Object.freeze(r.externalDependencies.map(e=>c(e,n)))}return i}function $e(t,n){let i=o(t,n);e(i,[`providerOptions`],n);let a=i.providerOptions;return a===void 0?{}:{providerOptions:r(a,n)}}function et(t,n){let r=o(t,n);e(r,[`model`,`modelContextWindowTokens`,`thresholdPercent`],n);let i={};if(r.model!==void 0&&(i.model=r.model),r.modelContextWindowTokens!==void 0&&(i.modelContextWindowTokens=Ze(r.modelContextWindowTokens,n)),r.thresholdPercent!==void 0){let e=r.thresholdPercent;if(typeof e!=`number`||!Number.isFinite(e)||e<0||e>1)throw Error(n);i.thresholdPercent=e}return i}function tt(t,n){let r=o(t,n);return e(r,[`markdown`],n),{markdown:c(r.markdown,n)}}function nt(t,r){let i=o(t,r);e(i,[`description`,`files`,`license`,`markdown`,`metadata`],r);let a={description:c(i.description,r),markdown:c(i.markdown,r)},s=i.license,l=n(i,`metadata`,r);return s!==void 0&&(a.license=c(s,r)),l!==void 0&&(a.metadata=l),i.files!==void 0&&(a.files=rt(i.files,r)),a}function rt(e,t){let n=o(e,t),r={};for(let[e,i]of Object.entries(n)){if(typeof i==`string`||i instanceof Uint8Array){r[e]=i;continue}throw Error(`${t} Expected skill file "${e}" to be a string or Uint8Array.`)}return r}function it(t,n){let r=o(t,n);e(r,[`cron`,`markdown`,`run`],n);let a=c(r.cron,n),s=r.markdown!==void 0,l=r.run!==void 0;if(s&&l)throw Error(`${n} Pass either "markdown" (fire-and-forget) or "run" (handler) — not both.`);if(!s&&!l)throw Error(`${n} Must provide either "markdown" (fire-and-forget) or "run" (handler).`);let u={cron:a};return s?u.markdown=c(r.markdown,n):u.run=i(r.run,n),u}function at(e){let t=x(e.appRoot),n=x(e.agentRoot),r={agentId:e.agentId??ot(t,n,e.packageName),agentRoot:n,appRoot:t,channels:[...e.channels??[]],connections:[...e.connections??[]],diagnosticsSummary:ze(e.diagnostics??[]),hooks:[...e.hooks??[]],lib:[...e.lib??[]],kind:`ash-agent-discovery-manifest`,sandbox:e.sandbox??null,sandboxWorkspaces:[...e.sandboxWorkspaces??[]],schedules:[...e.schedules??[]],skills:[...e.skills??[]],tools:[...e.tools??[]],version:12,subagents:[...e.subagents??[]]};return e.configModule!==void 0&&(r.configModule=e.configModule),e.instructions!==void 0&&(r.instructions=e.instructions),r}function ot(e,t,n){let r=T(le(e,t));return r===``||r===`.`||r===`agent`?n??se(e):se(t)}function O(e){return T(e)}function st(e){let t=T(e.logicalPath),n={sourceKind:`module`,logicalPath:t,sourceId:e.sourceId??O(t)};return e.exportName!==void 0&&(n.exportName=e.exportName),n}function ct(e){return{...st(e),connectionName:e.connectionName}}function lt(e){let t=T(e.logicalPath);return{entryPath:e.entryPath,logicalPath:t,manifest:e.manifest,rootPath:e.rootPath,sourceId:e.sourceId??O(t),subagentId:e.subagentId}}function ut(e){let t={description:e.description,sourceKind:`skill-package`,logicalPath:T(e.logicalPath),markdown:e.markdown,name:e.name,rootPath:e.rootPath,skillFilePath:e.skillFilePath,skillId:e.skillId,sourceId:e.sourceId};return e.assetsPath!==void 0&&(t.assetsPath=e.assetsPath),e.license!==void 0&&(t.license=e.license),e.metadata!==void 0&&(t.metadata={...e.metadata}),e.referencesPath!==void 0&&(t.referencesPath=e.referencesPath),e.scriptsPath!==void 0&&(t.scriptsPath=e.scriptsPath),t}const k=`experimental-ash`;let A;const dt={"workflow/api":`src/compiled/@workflow/core/runtime.js`,"workflow/errors":`src/compiled/@workflow/errors/index.js`,"workflow/internal/private":`src/compiled/@workflow/core/private.js`,"workflow/runtime":`src/compiled/@workflow/core/runtime.js`};function ft(){return`__ASH_PACKAGE_VERSION__`}const pt={name:k,version:ft()};function mt(){return typeof __filename==`string`?__filename:ht()}function ht(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;let e=Error().stack?.[0]?.getFileName();if(typeof e!=`string`||e.length===0)throw Error(`Failed to resolve the current module path from the stack trace.`);return e.startsWith(`file:`)?be(e):e}finally{Error.prepareStackTrace=e}}const gt=oe(mt());function _t(e){return se(e)===`dist`&&w(b(y(e),`package.json`))}function vt(){let e=y(ve(mt()));for(;;){if(_t(e))return e;let t=y(e);if(t===e)return null;e=t}}function yt(e){let t=e;for(;;){if(w(b(t,`package.json`))&&!_t(t))return t;let n=y(t);if(n===t)throw Error(`Failed to resolve package root from "${e}".`);t=n}}function j(){return yt(y(ve(mt())))}function bt(){try{return j()}catch{return}}function xt(e){return e.replace(/\.[cm]?tsx?$/,`.js`)}function St(e){let t=vt();return t===null?b(j(),e):b(t,xt(e))}function Ct(e){let t=vt();return b(t===null?j():t,e)}function wt(e){let t=vt();return t===null?b(j(),`.generated`,`compiled`,e.replace(/^src\/compiled\//,``)):b(t,e)}function Tt(e){let t=e;if(!(typeof t.name!=`string`||typeof t.version!=`string`))return{name:t.name,version:t.version}}function Et(e,t){let n=Tt(JSON.parse(ge(e,`utf8`)));if(n?.name===t)return n}function Dt(){if(A)return A;let e=bt(),t=e===void 0?void 0:Et(b(e,`package.json`),k);if(t)return A=t,A;try{let e=Et(gt.resolve(`${k}/package.json`),k);if(e)return A=e,A}catch{}return A={...pt},A}function Ot(e){if(e===`workflow`)return St(`src/internal/workflow/index.ts`);if(e===`workflow/internal/builtins`)return St(`src/internal/workflow/builtins.ts`);let t=dt[e];return t===void 0?gt.resolve(e):wt(t)}const kt=v.object({description:v.string(),entryPath:v.string(),exportName:v.string().optional(),logicalPath:v.string(),name:v.string(),nodeId:v.string(),path:v.string(),rootPath:v.string(),sourceId:v.string(),sourceKind:v.literal(`module`),url:v.string()}).strict(),At=`ash-agent-compiled-manifest`,M=`__root__`,jt=v.object({exportName:v.string().optional(),sourceKind:v.literal(`module`),logicalPath:v.string(),sourceId:v.string()}).strict(),Mt=v.union([v.literal(`GET`),v.literal(`POST`),v.literal(`PUT`),v.literal(`PATCH`),v.literal(`DELETE`)]),Nt=v.object({kind:v.literal(`channel`),name:v.string(),logicalPath:v.string(),method:Mt,urlPath:v.string(),sourceId:v.string(),sourceKind:v.literal(`module`),exportName:v.string().optional(),adapterKind:v.string().optional()}).strict(),Pt=v.object({kind:v.literal(`disabled`),name:v.string(),logicalPath:v.string()}).strict(),Ft=v.union([Nt,Pt]),It=v.object({contextWindowTokens:v.number().int().positive().optional(),id:v.string(),source:jt.optional(),providerOptions:v.record(v.string(),re).optional()}).strict(),Lt=v.object({externalDependencies:v.array(v.string()).optional()}).strict(),Rt=v.object({model:It.optional(),thresholdPercent:v.number().finite().min(0).max(1).optional()}).strict(),zt=v.object({build:Lt.optional(),compaction:Rt.optional(),description:v.string().optional(),metadata:v.record(v.string(),v.string()),model:It,name:v.string(),source:jt.optional()}).strict(),Bt=v.object({name:v.string(),logicalPath:v.string(),markdown:v.string(),sourceId:v.string(),sourceKind:v.union([v.literal(`markdown`),v.literal(`module`)])}).strict(),Vt={name:v.string(),description:v.string(),license:v.string().optional(),markdown:v.string(),metadata:v.record(v.string(),v.string()).optional(),sourceId:v.string(),logicalPath:v.string()},Ht=v.discriminatedUnion(`sourceKind`,[v.object({...Vt,sourceKind:v.literal(`markdown`)}).strict(),v.object({...Vt,sourceKind:v.literal(`module`),exportName:v.string().optional()}).strict(),v.object({...Vt,sourceKind:v.literal(`skill-package`),skillId:v.string(),skillFilePath:v.string(),rootPath:v.string(),assetsPath:v.string().optional(),referencesPath:v.string().optional(),scriptsPath:v.string().optional()}).strict()]),Ut=v.object({cron:v.string(),hasRun:v.boolean(),name:v.string(),logicalPath:v.string(),markdown:v.string().optional(),sourceId:v.string(),sourceKind:v.union([v.literal(`markdown`),v.literal(`module`)])}).strict(),Wt=v.object({description:v.string().optional(),exportName:v.string().optional(),logicalPath:v.string(),sourceId:v.string(),sourceKind:v.literal(`module`)}).strict(),Gt=v.object({logicalPath:v.string(),rootEntries:v.array(v.string()).readonly(),sourceId:v.string(),sourcePath:v.string()}).strict(),Kt=v.object({logicalPath:v.string(),rootEntries:v.array(v.string()).readonly()}).strict(),qt=v.object({connectionName:v.string(),description:v.string(),exportName:v.string().optional(),logicalPath:v.string(),sourceId:v.string(),sourceKind:v.literal(`module`),url:v.string(),vercelConnect:v.object({connector:v.string()}).strict().optional()}).strict(),Jt=v.object({description:v.string(),exportName:v.string().optional(),inputSchema:re.nullable(),logicalPath:v.string(),name:v.string(),sourceId:v.string(),sourceKind:v.literal(`module`)}).strict(),Yt=v.object({exportName:v.string().optional(),logicalPath:v.string(),slug:v.string(),sourceId:v.string(),sourceKind:v.literal(`module`)}).strict(),Xt=v.object({agentRoot:v.string(),appRoot:v.string(),channels:v.array(Ft),config:zt,connections:v.array(qt),diagnosticsSummary:Fe,disabledFrameworkTools:v.array(v.string()).readonly(),hooks:v.array(Yt),sandbox:Wt.nullable(),sandboxWorkspaces:v.array(Gt),schedules:v.array(Ut),remoteAgents:v.array(kt),skills:v.array(Ht).readonly(),instructions:Bt.optional(),tools:v.array(Jt),workspaceResourceRoot:Kt}).strict(),Zt=v.object({agent:Xt,description:v.string(),entryPath:v.string(),logicalPath:v.string(),name:v.string(),nodeId:v.string(),rootPath:v.string(),sourceId:v.string(),sourceKind:v.literal(`module`),exportName:v.string().optional()}).strict(),Qt=v.object({childNodeId:v.string(),parentNodeId:v.string()}).strict(),$t=v.object({agentRoot:v.string(),appRoot:v.string(),channels:v.array(Ft),config:zt,connections:v.array(qt),diagnosticsSummary:Fe,disabledFrameworkTools:v.array(v.string()).readonly(),hooks:v.array(Yt),kind:v.literal(At),remoteAgents:v.array(kt),sandbox:Wt.nullable(),sandboxWorkspaces:v.array(Gt),schedules:v.array(Ut),skills:v.array(Ht).readonly(),subagentEdges:v.array(Qt),subagents:v.array(Zt),instructions:Bt.optional(),tools:v.array(Jt),version:v.literal(24),workspaceResourceRoot:Kt}).strict();function en(e){let t={agentRoot:e.agentRoot,appRoot:e.appRoot,channels:[...e.channels??[]],connections:[...e.connections??[]],config:{build:e.config.build===void 0?void 0:{externalDependencies:e.config.build.externalDependencies===void 0?void 0:[...e.config.build.externalDependencies]},compaction:{model:e.config.compaction?.model===void 0?void 0:an(e.config.compaction.model),thresholdPercent:e.config.compaction?.thresholdPercent},description:e.config.description,metadata:{...e.config.metadata},model:an(e.config.model),name:e.config.name,source:e.config.source===void 0?void 0:{...e.config.source}},diagnosticsSummary:e.diagnosticsSummary??{errors:0,warnings:0},disabledFrameworkTools:[...e.disabledFrameworkTools??[]],hooks:[...e.hooks??[]],remoteAgents:[...e.remoteAgents??[]],sandbox:e.sandbox??null,sandboxWorkspaces:[...e.sandboxWorkspaces??[]],schedules:[...e.schedules??[]],skills:[...e.skills??[]],tools:[...e.tools??[]],workspaceResourceRoot:e.workspaceResourceRoot??{logicalPath:``,rootEntries:tn({sandboxWorkspaces:e.sandboxWorkspaces,skills:e.skills})}};return e.instructions!==void 0&&(t.instructions=e.instructions),t}function tn(e){let t=new Set;(e.skills??[]).length>0&&t.add(`skills/`);for(let n of e.sandboxWorkspaces??[])for(let e of n.rootEntries)t.add(e);return[...t].sort((e,t)=>e.localeCompare(t))}function nn(e,t){return e===`__root__`?t:`${e}::${t}`}function rn(e){return{...en(e),kind:At,subagentEdges:[...e.subagentEdges??[]],subagents:[...e.subagents??[]],version:24}}function an(e){return e.contextWindowTokens===void 0&&e.source===void 0&&e.providerOptions===void 0?{id:e.id}:e.source===void 0?e.providerOptions===void 0?{contextWindowTokens:e.contextWindowTokens,id:e.id}:{contextWindowTokens:e.contextWindowTokens,id:e.id,providerOptions:{...e.providerOptions}}:e.contextWindowTokens===void 0&&e.providerOptions===void 0?{id:e.id,source:{...e.source}}:{contextWindowTokens:e.contextWindowTokens,id:e.id,providerOptions:e.providerOptions===void 0?void 0:{...e.providerOptions},source:{...e.source}}}const on=/^\/?[A-Za-z]:[\\/]/,sn=/^\\\\[^\\]/,cn=/(\b(?:from|import)\s*(?:\(\s*)?)(["'])([A-Za-z]:[\\/][^"'\n\r]*)\2/g;function ln(e){return on.test(e)||sn.test(e)}function un(e){let t=e.replaceAll(`\\`,`/`);return t.startsWith(`//`)?new URL(`file:${t}`).href:(/^\/[A-Za-z]:\//.test(t)&&(t=t.slice(1)),new URL(`file:///${t}`).href)}function dn(e){let t=e.indexOf(`?`),n=e.indexOf(`#`),r=t===-1?n:n===-1?t:Math.min(t,n);return r===-1?{path:e,suffix:``}:{path:e.slice(0,r),suffix:e.slice(r)}}function fn(e){if(e.startsWith(`file://`))return e;let{path:t,suffix:n}=dn(e);return ln(t)?`${un(t)}${n}`:e.replaceAll(`\\`,`/`)}function pn(e){return JSON.stringify(fn(e))}function mn(e){return e.replace(cn,(e,t,n,r)=>`${t}${n}${fn(r)}${n}`)}const hn=v.object({modules:v.record(v.string(),v.object({}).passthrough())}).strict(),gn=v.object({nodes:v.record(v.string(),hn)}).strict();function _n(e){let t=Cn(e.moduleMapPath),n=e.importSpecifierStyle??`relative`,r=0,i=[vn({agentRoot:e.manifest.agentRoot,importSpecifierStyle:n,manifest:e.manifest,moduleMapDirectory:t,nextBindingName(){return`module_${r++}`},nodeId:M}),...[...e.manifest.subagents].sort((e,t)=>e.nodeId.localeCompare(t.nodeId)).map(e=>vn({agentRoot:e.agent.agentRoot,importSpecifierStyle:n,manifest:e.agent,moduleMapDirectory:t,nextBindingName(){return`module_${r++}`},nodeId:e.nodeId}))],a=i.flatMap(e=>e.modules.map(e=>`import * as ${e.bindingName} from ${JSON.stringify(e.importSpecifier)};`));return[`// Generated by Ash. Do not edit by hand.`,``,...a,...a.length>0?[``]:[],`export const moduleMap = ${xn(i)};`,``,`export default moduleMap;`,``].join(`
|
|
2
|
-
`)}function vn(e){return{modules:yn(e.manifest).sort((e,t)=>e.sourceId.localeCompare(t.sourceId)).map(t=>({bindingName:e.nextBindingName(),importSpecifier:bn({fromDirectory:e.moduleMapDirectory,importSpecifierStyle:e.importSpecifierStyle,targetPath:wn(e.agentRoot,t.logicalPath)}),sourceId:t.sourceId})),nodeId:e.nodeId}}function yn(e){let t=new Map;e.config.source!==void 0&&t.set(e.config.source.sourceId,e.config.source),e.config.model.source!==void 0&&t.set(e.config.model.source.sourceId,e.config.model.source);for(let n of e.channels)n.kind!==`disabled`&&t.set(n.sourceId,{exportName:n.exportName,sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId});for(let n of e.connections)t.set(n.sourceId,{exportName:n.exportName,sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId});for(let n of e.tools)t.set(n.sourceId,{exportName:n.exportName,sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId});for(let n of e.remoteAgents)t.set(n.sourceId,{exportName:n.exportName,sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId});for(let n of e.hooks)t.set(n.sourceId,{exportName:n.exportName,sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId});for(let n of e.schedules)n.sourceKind!==`module`||!n.hasRun||t.set(n.sourceId,{sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId});return e.sandbox!==null&&t.set(e.sandbox.sourceId,{exportName:e.sandbox.exportName,sourceKind:`module`,logicalPath:e.sandbox.logicalPath,sourceId:e.sandbox.sourceId}),[...t.values()]}function bn(e){if(e.importSpecifierStyle===`absolute`)return fn(En(e.targetPath));let t=Tn(e.fromDirectory,e.targetPath);return t.startsWith(`.`)?t:`./${t}`}function xn(e){return Sn([{key:`nodes`,value:Sn(e.map(e=>({key:e.nodeId,value:Sn([{key:`modules`,value:Sn(e.modules.map(e=>({key:e.sourceId,value:e.bindingName})))}],3)})))}],0)}function Sn(e,t=1){if(e.length===0)return`Object.freeze({})`;let n=` `.repeat(t),r=` `.repeat(t+1);return[`Object.freeze({`,e.map(e=>`${r}${JSON.stringify(e.key)}: ${e.value.replaceAll(`
|
|
3
|
-
`,`\n${r}`)}`).join(`,
|
|
4
|
-
`),`${n}})`].join(`
|
|
5
|
-
`)}function Cn(e){let t=N(e);return t.segments.length===0?t.root.length===0?`.`:t.root:Dn(t.root,t.segments.slice(0,-1))}function wn(e,t){let n=N(e),r=N(t);return r.root.length>0?Dn(r.root,r.segments):Dn(n.root,[...n.segments,...r.segments])}function Tn(e,t){let n=N(e),r=N(t);if(n.root!==r.root)return En(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 En(e){let t=N(e);return Dn(t.root,t.segments)}function N(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 Dn(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 On=`ash-model-catalog-cache`,kn=v.object({provider:v.string().min(1),providerModelId:v.string().min(1),contextWindowTokens:v.number().int().nonnegative().optional(),maxOutputTokens:v.number().int().nonnegative().optional()}).passthrough(),An=v.object({slug:v.string().min(1),providers:v.array(kn).min(1)}).passthrough(),jn=v.object({models:v.array(An),providerAliases:v.record(v.string(),v.string())}).passthrough();v.object({contextWindowTokens:v.number().int().positive(),maxOutputTokens:v.number().int().positive().optional()}).strict();const Mn=v.object({fetchedAt:v.string(),kind:v.literal(On),models:v.array(An),providerAliases:v.record(v.string(),v.string()),version:v.literal(2)}).strict(),Nn=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 Pn(e){return b(e,`.ash`,`cache`,`model-catalog.json`)}function Fn(e){let t=null,n=null,r=null,i=async()=>(t??=Ln(e),await t),a=async()=>{if(n!==null)throw n;if(r!==null)return await r;r=In(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&&Bn(e))return e;try{return await a()}catch{return e===null?null:e}};return{async getModelLimits(e){let t=Vn(e),n=await o();if(n!==null){let e=Rn(n.models,t);if(e)for(let t of e.providers){let e=zn(t);if(e!==null)return e}}return Nn.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=Vn(t);for(let e of n.models)for(let t of e.providers)if(t.provider===i&&Vn(t.providerModelId)===a){let n=zn(t);if(n!==null)return{slug:e.slug,limits:n}}return null}}}async function In(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=jn.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:On,models:n.data.models,providerAliases:n.data.providerAliases,version:2};try{let t=Pn(e);await S(b(e,`.ash`,`cache`),{recursive:!0}),await C(t,`${JSON.stringify(r,null,2)}\n`,`utf8`)}catch{}return r}async function Ln(e){try{let t=await pe(Pn(e),`utf8`),n=Mn.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 Rn(e,t){return e.find(e=>e.slug===t)}function zn(e){return e.contextWindowTokens===void 0||e.contextWindowTokens<=0?null:{contextWindowTokens:e.contextWindowTokens,...e.maxOutputTokens!==void 0&&e.maxOutputTokens>0&&{maxOutputTokens:e.maxOutputTokens}}}function Bn(e){let t=Date.parse(e.fetchedAt);return Number.isFinite(t)?Date.now()-t<=864e5:!1}function Vn(e){return e.endsWith(`-thinking`)?e.slice(0,-9):e}async function P(e){let n=t(await s(b(e.agentRoot,e.source.logicalPath)),e.source);try{return await a(n)}catch(t){throw Error(`Failed to execute the ${e.kind} export "${e.source.exportName??`default`}" from "${e.source.logicalPath}": ${d(t)}`)}}var Hn=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 Un(e,t){if(e.configModule===void 0)throw new Hn(e.agentId);let n=Xe(await P({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 Wn({modelCatalog:t.modelCatalog,purpose:`the primary compaction trigger model`,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 Wn({modelCatalog:t.modelCatalog,purpose:`the compaction summary model`,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 Wn(e){if(typeof e.value==`string`)return await Gn({id:ae(e.value),providerOptions:Kn(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:ae(n),source:{exportName:t.exportName,sourceKind:`module`,logicalPath:t.logicalPath,sourceId:t.sourceId},providerOptions:Kn(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 Gn(i,e)}async function Gn(e,t){if(t.contextWindowTokens!==void 0)return{...e,contextWindowTokens:t.contextWindowTokens};let n;try{n=await t.modelCatalog.getModelLimits(e.id)}catch(n){throw Error(`Failed to load AI Gateway model metadata for ${t.purpose} "${e.id}". ${d(n)}`)}if(n===null)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 Kn(e){if(e===void 0)return;let t={};for(let[n,r]of Object.entries(e))t[n]=ie(r);return t}function qn(e){return typeof e==`object`&&!!e&&e.__kind===`ash:channel`}function Jn(e,t){if(!qn(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 Yn(e){return typeof e==`object`&&!!e&&e.kind===`ash:disabled-channel`}async function Xn(e,t){let n=await P({agentRoot:e,kind:`channel`,source:t}),r=D(t.logicalPath).replace(/^channels\//,``);if(Yn(n))return{kind:`disabled`,name:r,logicalPath:t.logicalPath};let i=Jn(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:Zn(i.adapter)}))}function Zn(e){if(typeof e!=`object`||!e)return;let t=e.kind;return typeof t==`string`&&t.length>0?t:void 0}function Qn(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 $n(e,t,n=`auth`){let r=Qn(e,n);if(r!==void 0)throw Error(`${t} ${r}`);let i=e,a=er(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 er(e){if(typeof e!=`object`||!e)return;let t=e.connector;if(!(typeof t!=`string`||t.length===0))return{connector:t}}const tr=[`approval`,`auth`,`description`,`headers`,`tools`,`url`],nr=[`completeAuthorization`,`getToken`,`principalType`,`startAuthorization`,`vercelConnect`];function rr(t,n){let r=o(t,n);e(r,tr,n),ir(r,n),ar(r,n);let i=or(r,n),a=sr(r,n),s=cr(r,n);if(i!==void 0&&a!==void 0&&typeof a!=`function`&&Object.keys(a).some(e=>e.toLowerCase()===`authorization`))throw Error(`${n} "headers" must not include an "Authorization" key when "auth" is also provided.`);let c={description:r.description,url:r.url};if(i!==void 0&&(c.auth=i),a!==void 0&&(c.headers=a),s!==void 0&&(c.tools=s),r.approval!==void 0){if(typeof r.approval!=`function`)throw Error(`${n} The "approval" field must be a function when provided.`);c.approval=r.approval}return c}function ir(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 ar(e,t){if(typeof e.description!=`string`||e.description.length===0)throw Error(`${t} The "description" field must be a non-empty string.`)}function or(t,n){if(t.auth===void 0)return;let r=o(t.auth,`${n} The "auth" field must be an object with a "getToken" method.`);return e(r,nr,`${n} The "auth" field`),$n(r,n)}function sr(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 cr(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?(lr(n.allow,`${t} The "tools.allow"`),{allow:n.allow}):(lr(n.block,`${t} The "tools.block"`),{block:n.block})}function lr(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 ur(e,t){let n=rr(await P({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=dr(n.auth);return i!==void 0&&(r.vercelConnect=i),r}function dr(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 fr(e){return{exportName:e.exportName,logicalPath:e.logicalPath,slug:D(e.logicalPath).replace(/^hooks\//,``),sourceId:e.sourceId,sourceKind:`module`}}function pr(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 mr(t,n){let r=o(t,n);e(r,[`backend`,`bootstrap`,`description`,`onSession`],n);let a={};if(r.backend!==void 0&&(a.backend=hr(r.backend,n)),r.description!==void 0){if(typeof r.description!=`string`)throw Error(`${n} The "description" field must be a string when set.`);a.description=r.description}return r.bootstrap!==void 0&&(a.bootstrap=i(r.bootstrap,n)),r.onSession!==void 0&&(a.onSession=i(r.onSession,n)),a}function hr(e,t){if(typeof e==`function`)return pr(e);let n=o(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 gr(e,t){return{description:mr(await P({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 _r(e,t){let n=t.sourceKind===`markdown`?tt(t.definition,`Expected the compiled instructions definition at "${t.logicalPath}" to match the public Ash shape.`):tt(await P({agentRoot:e,kind:`instructions`,source:t}),`Expected the instructions export "${t.exportName??`default`}" from "${t.logicalPath}" to match the public Ash shape.`);return{name:D(t.logicalPath),logicalPath:t.logicalPath,markdown:n.markdown,sourceId:t.sourceId,sourceKind:t.sourceKind}}async function vr(e,t){let n=t.sourceKind===`markdown`?it(t.definition,`Expected the compiled schedule definition at "${t.logicalPath}" to match the public Ash shape.`):it(await P({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:yr(t.logicalPath),sourceId:t.sourceId,sourceKind:t.sourceKind};return n.markdown===void 0?r:{...r,markdown:n.markdown.trim()}}function yr(e){return D(e).replace(/^schedules\//,``)}async function br(e,t){if(t.sourceKind===`skill-package`)return xr(t);let n=t.sourceKind===`markdown`?nt(t.definition,`Expected the compiled skill definition at "${t.logicalPath}" to match the public Ash shape.`):nt(await P({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:D(t.logicalPath).replace(/^skills\//,``),sourceId:t.sourceId,sourceKind:t.sourceKind};return n.files!==void 0&&(r.files=n.files),r}function xr(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 Sr(e){let t=[],n=[],r=[];for(let i of e.subagents){let a=await Cr({appRoot:e.appRoot,compileAgentNodeManifest:e.compileAgentNodeManifest,context:e.context,parentNodeId:e.parentNodeId,source:i});if(a.kind===`remote`){r.push(a.node);continue}t.push(a.node,...a.descendants.nodes),n.push({childNodeId:a.node.nodeId,parentNodeId:e.parentNodeId},...a.descendants.edges)}return{edges:n,nodes:t,remoteAgents:r}}async function Cr(e){let t=e.source.manifest.configModule;if(t===void 0)throw Error(`Subagent "${e.source.logicalPath}" is missing an agent config module.`);let n=await P({agentRoot:e.source.manifest.agentRoot,kind:`subagent config`,source:t});return Or(n)===`remote`?{kind:`remote`,node:Er({source:e.source,value:n})}:{kind:`local`,...await Tr(e)}}async function wr(e){let t=nn(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.`);let a=await Sr({appRoot:e.appRoot,compileAgentNodeManifest:e.compileAgentNodeManifest,context:e.context,parentNodeId:t,subagents:e.source.manifest.subagents});return{descendants:a,node:{agent:{...r,remoteAgents:[...a.remoteAgents]},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 Tr=wr;function Er(e){let t=e.source.manifest.configModule;if(t===void 0)throw Error(`Remote agent "${e.source.logicalPath}" is missing a config module.`);Ar(e.source);let n=kr(e.value,`Expected the remote agent config export "${t.exportName??`default`}" from "${t.logicalPath}" to match the public Ash shape.`);return{...Dr(e.source,t),description:n.description,entryPath:e.source.entryPath,name:e.source.subagentId,nodeId:e.source.sourceId,path:n.path,rootPath:e.source.rootPath,url:n.url}}function Dr(e,t){let n=e.logicalPath===t.logicalPath?t.logicalPath:`${e.logicalPath}/${t.logicalPath}`,r={logicalPath:n,sourceId:O(n),sourceKind:`module`};return t.exportName!==void 0&&(r.exportName=t.exportName),r}function Or(e){return typeof e!=`object`||!e?`local`:e.kind===`remote`?`remote`:`local`}function kr(t,n){let r=o(t,n);if(e(r,[`auth`,`description`,`headers`,`kind`,`path`,`url`],n),r.kind!==`remote`)throw Error(`${n} Expected "kind" to be "remote".`);return{description:c(r.description,n),path:r.path===void 0?p:c(r.path,n),url:c(r.url,n)}}function Ar(e){let t=e.manifest,n=[t.connections.length>0?`connections/`:void 0,t.hooks.length>0?`hooks/`:void 0,t.instructions===void 0?void 0:`instructions`,t.lib.length>0?`lib/`:void 0,t.sandbox===null?void 0:`sandbox/`,t.sandboxWorkspaces.length>0?`sandbox/workspace/`:void 0,t.schedules.length>0?`schedules/`:void 0,t.skills.length>0?`skills/`:void 0,t.subagents.length>0?`subagents/`:void 0,t.tools.length>0?`tools/`:void 0].filter(e=>e!==void 0);if(n.length!==0)throw Error(`Remote subagent definition "${e.logicalPath}" cannot include local package entries. Remove unsupported entries: ${n.join(`, `)}.`)}const jr=Symbol.for(`experimental-ash.definition-source-registry`),Mr=globalThis;Mr[jr]===void 0&&(Mr[jr]=new Map);const Nr=Mr[jr];function Pr(e,t){Nr.set(e,t)}function Fr(e){return typeof e==`object`&&!!e&&e.kind===`ash:disabled-tool`}function Ir(e){return e&&typeof e==`object`&&`~standard`in e?e[`~standard`].jsonSchema.input({target:`draft-07`}):JSON.parse(JSON.stringify(e))}function Lr(t,n){if(Fr(t))return{kind:`disabled`};let r=o(t,n);e(r,[`description`,`execute`,`inputSchema`,`needsApproval`,`onCompact`,`retentionPolicy`,`toModelOutput`],n);let a=r.inputSchema===void 0?null:Ir(r.inputSchema),s={description:c(r.description,n),execute:i(r.execute,n),inputSchema:a};if(r.onCompact!==void 0&&i(r.onCompact,n),r.needsApproval!==void 0&&i(r.needsApproval,n),r.retentionPolicy!==void 0){let e=r.retentionPolicy;if(e!==`auto`&&e!==`keep`&&typeof e!=`function`)throw Error(`${n} Expected \`retentionPolicy\` to be "auto", "keep", or a function.`)}return r.toModelOutput!==void 0&&i(r.toModelOutput,n),{kind:`tool`,definition:s}}async function Rr(e,t){let n=Lr(await P({agentRoot:e,kind:`tool`,source:t}),`Expected the tool export "${t.exportName??`default`}" from "${t.logicalPath}" to match the public Ash shape.`),r=D(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 zr(e){let t={modelCatalog:Fn(e.appRoot)},[n,r]=await Promise.all([Br(e,t),Sr({appRoot:e.appRoot,compileAgentNodeManifest:Br,context:t,parentNodeId:M,subagents:e.subagents})]);return rn({...n,remoteAgents:r.remoteAgents,subagentEdges:r.edges,subagents:r.nodes})}async function Br(e,t){let n=await Promise.all(e.tools.map(t=>Rr(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=>Xn(e.agentRoot,t)))).flat();return en({agentRoot:e.agentRoot,appRoot:e.appRoot,channels:a,config:await Un(e,t),connections:await Promise.all(e.connections.map(t=>ur(e.agentRoot,t))),diagnosticsSummary:e.diagnosticsSummary,disabledFrameworkTools:i,hooks:e.hooks.map(e=>fr(e)),sandbox:e.sandbox===null?null:await gr(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=>vr(e.agentRoot,t))),skills:await Promise.all(e.skills.map(t=>br(e.agentRoot,t))),instructions:e.instructions===void 0?void 0:await _r(e.agentRoot,e.instructions),tools:r})}function Vr(e){Ur(e.name);let t=[{content:Se.from(e.markdown,`utf8`),relativePath:`SKILL.md`}];for(let[n,r]of Object.entries(e.files??{}))Wr(n),t.push({content:Gr(r),relativePath:n});return t.sort((e,t)=>Kr(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 Hr(e){for(let t of e.skill.files){let n=b(e.rootPath,`skills`,e.skill.name,t.relativePath);await S(y(n),{recursive:!0}),await C(n,t.content)}}function Ur(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 Wr(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 Gr(e){return typeof e==`string`?Se.from(e,`utf8`):Se.from(e)}function Kr(e,t){return e<t?-1:+(e>t)}const qr=`workspace-resources`;async function Jr(e){let t=b(e.compileDirectoryPath,qr);await me(t,{force:!0,recursive:!0});let n=await Xr({nodeId:M,resourcesRoot:t,manifest:e.manifest}),r=await Promise.all(e.manifest.subagents.map(async e=>({...e,agent:await Xr({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 Yr(e,t){return{logicalPath:T(b(qr,t)),rootEntries:tn({sandboxWorkspaces:e.sandboxWorkspaces,skills:e.skills})}}async function Xr(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=b(e.resourcesRoot,e.nodeId);await S(t,{recursive:!0});for(let n of e.manifest.sandboxWorkspaces)await fe(n.sourcePath,t,{recursive:!0});for(let n of e.manifest.skills)await Zr({nodeRoot:t,skill:n});return{...e.manifest,skills:e.manifest.skills.map(Qr),workspaceResourceRoot:Yr(e.manifest,e.nodeId)}}async function Zr(e){let t=b(e.nodeRoot,`skills`,e.skill.name);if(e.skill.sourceKind===`skill-package`){await fe(e.skill.rootPath,t,{recursive:!0});return}await Hr({rootPath:e.nodeRoot,skill:Vr(e.skill)})}function Qr(e){let{files:t,...n}=e;return n}const $r=`ash-compile-metadata`;function ei(e){let t=x(e),n=b(t,`.ash`,`discovery`),r=b(t,`.ash`,`compile`);return{appRoot:t,compiledManifestPath:b(r,`compiled-agent-manifest.json`),compileDirectoryPath:r,compileMetadataPath:b(r,`compile-metadata.json`),diagnosticsPath:b(n,`diagnostics.json`),discoveryManifestPath:b(n,`agent-discovery-manifest.json`),discoveryDirectoryPath:n,moduleMapPath:b(r,`module-map.mjs`)}}function ti(e){return{diagnostics:[...e],kind:`ash-discovery-diagnostics`,summary:ze(e),version:1}}function ni(e){let t=Dt(),n=ii(e.discoveryManifestJson),r=ii(e.diagnosticsArtifactJson),i=ii(e.moduleMapSource);return{compile:{moduleMap:{path:ai(e.appRoot,e.paths.moduleMapPath),sha256:i}},discovery:{diagnostics:{path:ai(e.appRoot,e.paths.diagnosticsPath),sha256:r},manifest:{path:ai(e.appRoot,e.paths.discoveryManifestPath),sha256:n},sourceGraphHash:ii(`${n}:${r}:${i}`),summary:e.diagnosticsSummary},generator:{name:t.name,version:t.version},kind:$r,status:e.diagnosticsSummary.errors>0?`failed`:`ready`,version:5}}async function ri(e){let t=ei(e.appRoot),n=ti(e.diagnostics),r=await Jr({compileDirectoryPath:t.compileDirectoryPath,manifest:await zr(e.manifest)}),i=F(r),a=F(e.manifest),o=F(n),s=_n({manifest:r,moduleMapPath:t.moduleMapPath}),c=ni({appRoot:e.appRoot,diagnosticsArtifactJson:o,diagnosticsSummary:n.summary,discoveryManifestJson:a,moduleMapSource:s,paths:t}),l=F(c);return await S(t.discoveryDirectoryPath,{recursive:!0}),await S(t.compileDirectoryPath,{recursive:!0}),await Promise.all([C(t.compiledManifestPath,i),C(t.diagnosticsPath,o),C(t.discoveryManifestPath,a),C(t.moduleMapPath,s),C(t.compileMetadataPath,l)]),{compiledManifest:r,diagnosticsArtifact:n,metadata:c,moduleMapSource:s,paths:t}}function ii(e){return he(`sha256`).update(e).digest(`hex`)}function F(e){return`${JSON.stringify(e,null,2)}\n`}function ai(e,t){return T(le(x(e),t))}const oi=Symbol.for(`experimental-ash.context-key-registry`),si=globalThis;si[oi]===void 0&&(si[oi]=new Map);const ci=si[oi];var I=class{name;codec;constructor(e,t={}){this.name=e,this.codec=t.codec,ci.set(e,this)}};const li=Symbol.for(`experimental-ash.context-storage`),ui=globalThis;ui[li]===void 0&&(ui[li]=new we);const di=ui[li];function L(){let e=di.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 fi(e){return{debug(t,n){R(`debug`,e,t,n)},info(t,n){R(`info`,e,t,n)},warn(t,n){R(`warn`,e,t,n)},error(t,n){R(`error`,e,t,n),yi(t,n)}}}function pi(){return crypto.randomUUID()}function mi(e,t){let n={errorId:t??pi(),message:gi(e)},r=hi(e);return r!==void 0&&(n.name=r),n.detail=bi(e),n}function hi(e){if(e instanceof Error)return e.name===`Error`?void 0:e.name;if(l(e)&&u(e.name)&&e.name!==`Error`)return e.name}function gi(e){return l(e)&&!(e instanceof Error)&&typeof e.message==`string`?e.message:De(e)}function _i(e,t){let n=t instanceof Error?t.message:De(t),r=t instanceof Error?t.name:`Error`;e.setStatus({code:Te.ERROR,message:n}),e.recordException({message:n,name:r,stack:bi(t)})}function R(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,vi(r))}function vi(e){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0){if(r instanceof Error){t[n]=mi(r);continue}t[n]=r}return t}function yi(e,t){let n=Ee.getActiveSpan();if(n===void 0)return;let r=t?.error;if(r instanceof Error){_i(n,r);return}n.addEvent(e,t?vi(t):void 0)}function bi(e){return xi(Oe(e,{breakLength:1/0,compact:!1,depth:10,maxStringLength:8192}),16384)}function xi(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 Si(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 Ci(e){return e.kind}const wi={kind:`http`};new I(`ash.auth`),new I(`ash.initiatorAuth`);const Ti=new I(`ash.sessionId`),Ei=new I(`ash.continuationToken`);new I(`ash.mode`),new I(`ash.parentSession`),new I(`ash.capabilities`),new I(`ash.sessionPrepared`);const Di={kind:`schedule`},Oi=fi(`execution.subagent-adapter`);function ki(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 Ai={kind:`subagent`,async"input.requested"(e,t){let n=t.state;ki(n)&&await ji({hookPayload:{callId:n.callId,childContinuationToken:t.ctx.require(Ei),childSessionId:t.ctx.require(Ti),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 ji(e){"use step";try{await Ce(e.parentContinuationToken,e.hookPayload)}catch(t){let n=pi();throw Oi.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 z=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)}},Mi=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 z(this.registry,n.duplicateMessage??`Duplicate ${this.registry} name "${e}".`,{...n.location,entryName:e});if(this._reserved.has(e))throw new z(this.registry,n.reservedMessage??`${Ni(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 Ni(e){return e.length===0?e:e.charAt(0).toUpperCase()+e.slice(1)}const Pi=[wi,Ai,Di],Fi=new Set([`kind`,`state`,`deliver`,`createAdapterContext`,`fetchFile`]);function Ii(e){let t=new Map,n=new Set;for(let e of Pi){let r=Ri(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=Ri(i,e);if(n.has(a)){if(zi(i))throw new z(`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, or \`createAdapterContext\` factory. Use a custom \`kind\` to add channel-specific behavior.`,{...e,entryName:a});continue}t.set(a,i)}return{adaptersByKind:t}}function Li(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 Ri(e,t){let n=Ci(e);if(typeof n!=`string`||n.length===0)throw new z(`adapter`,"Adapters must declare a non-empty `kind` field.",{entryName:`unknown`,logicalPath:t?.logicalPath,sourceId:t?.sourceId});return n}function zi(e){if(e.deliver!==void 0||e.fetchFile!==void 0||e.createAdapterContext!==void 0)return!0;for(let[t,n]of Object.entries(e))if(!Fi.has(t)&&typeof n==`function`)return!0;return!1}function Bi(e,t={}){return t.moduleMapLoaderPath===void 0?{appRoot:e,kind:`disk`}:{appRoot:e,kind:`disk`,moduleMapLoaderPath:t.moduleMapLoaderPath}}function Vi(e){return e.kind===`disk`?e.appRoot:void 0}function Hi(e){return e.kind===`disk`?e.moduleMapLoaderPath===void 0?`disk:${e.appRoot}`:`disk:${e.appRoot}:authored-source:${e.moduleMapLoaderPath}`:`bundled`}function B(e){let t=Ui(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 Ui(e){let t=e.replaceAll(`\\`,`/`);return t===`/`?t:t.replace(/\/+$/,``)}function Wi(e){return ke(e,{prefix:void 0}).message}function Gi(e=`test-session`){return{bundleCache:new Map,bundleCacheKeyBySourceKey:new Map,compiledArtifacts:null,id:e}}const Ki=Symbol.for(`experimental-ash.runtime-session-storage`),qi=Symbol.for(`experimental-ash.runtime-session-default`),V=globalThis;V[Ki]===void 0&&(V[Ki]=new we);const Ji=V[Ki];function Yi(){return V[qi]===void 0&&(V[qi]=Gi(`process-default`)),V[qi]}function Xi(){return Ji.getStore()??Yi()}function Zi(){return Xi().compiledArtifacts}const Qi=v.object({path:v.string(),sha256:v.string()}).strict(),$i=v.object({compile:v.object({moduleMap:Qi}).strict(),discovery:v.object({diagnostics:Qi,manifest:Qi,sourceGraphHash:v.string(),summary:v.object({errors:v.number().finite(),warnings:v.number().finite()}).strict()}).strict(),generator:v.object({name:v.string(),version:v.string()}).strict(),kind:v.literal($r),status:v.union([v.literal(`failed`),v.literal(`ready`)]),version:v.literal(5)}).strict();var ea=class extends Error{metadataPath;constructor(e,t){super(e),this.name=`LoadCompileMetadataError`,t!==void 0&&(this.metadataPath=t)}};async function ta(e){let t=e.compiledArtifactsSource.kind===`disk`?B(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 ea(ra(e),t)}return na(n,t)}let n=Zi()?.metadata;return n===void 0?null:na(n,`bundled compile metadata`)}function na(e,t){let n=$i.safeParse(e);if(!n.success)throw new ea(`Expected "${t}" to contain valid Ash compile metadata. ${Wi(n.error)}`,t);return n.data}function ra(e){return e instanceof Error?e.message:`Unknown compile metadata load failure.`}async function ia(e){let t=Hi(e),n=await aa(e);try{let r=(await ta({compiledArtifactsSource:e}))?.discovery.sourceGraphHash;return r===void 0||r.length===0?n===void 0?t:`${t}:mtime-${oa(n)}`:n===void 0?`${t}:${r}`:`${t}:${r}:mtime-${oa(n)}`}catch{return n===void 0?t:`${t}:mtime-${oa(n)}`}}async function aa(e){if(e.kind!==`disk`)return;let{stat:t}=await import(`node:fs/promises`),{compileMetadataPath:n}=B(e.appRoot);try{return(await t(n)).mtimeMs}catch{return}}function oa(e){return Math.floor(e).toString(36)}const sa=`__root__`;function ca(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 la=`bundled compiled manifest`;var ua=class extends Error{manifestPath;constructor(e,t){super(e),this.name=`LoadCompiledManifestError`,t!==void 0&&(this.manifestPath=t)}};async function da(e){let t=e.compiledArtifactsSource.kind===`disk`?B(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 ua(pa(e),t)}return fa(n,t)}let n=Zi();if(n!==null)return fa(n.manifest,la);throw new ua(`Compiled manifest is unavailable without an app root or bundled compiled artifacts.`,la)}function fa(e,t){let n=$t.safeParse(e);if(!n.success)throw new ua(`Expected "${t}" to contain a valid compiled Ash agent manifest. ${Wi(n.error)}`,t);return n.data}function pa(e){return e instanceof Error?e.message:`Unknown manifest load failure.`}const ma=`bundled compiled module map`;var ha=class extends Error{moduleMapPath;constructor(e,t){super(e),this.name=`LoadCompiledModuleMapError`,t!==void 0&&(this.moduleMapPath=t)}};async function ga(e){let t=e.compiledArtifactsSource.kind===`disk`?B(e.compiledArtifactsSource.appRoot).moduleMapPath:void 0;if(t!==void 0){let e=ya(t);try{let n=await import(e);return _a(n.moduleMap??n.default,t)}catch(e){throw new ha(va(e),t)}}let n=Zi();if(n!==null)return _a(n.moduleMap,ma);throw new ha(`Compiled module map is unavailable without an app root or bundled compiled artifacts.`,ma)}function _a(e,t){let n=gn.safeParse(e);if(!n.success)throw new ha(`Expected "${t}" to export a valid compiled Ash module map. ${Wi(n.error)}`,t);return n.data}function va(e){return e instanceof Error?e.message:`Unknown module-map load failure.`}function ya(e){let t=e.replaceAll(`\\`,`/`);return/^[A-Za-z]:\//.test(t)?`file:///${encodeURI(t)}`:t.startsWith(`/`)?`file://${encodeURI(t)}`:t}const H=`/workspace`;function ba(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=>xa(e))].join(`
|
|
6
|
-
`)}function xa(e){return`- ${e.name}: ${e.description} (path: ${H}/skills/${e.name}/SKILL.md)`}function Sa(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 \`${H}\`.`,`- Root entries under ${H}/:`,...e.rootEntries.map(e=>` - ${e}`),`- Treat \`${H}\` 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(`
|
|
7
|
-
`)}function Ca(e){return e instanceof Error&&e.name===`ConnectionAuthorizationRequiredError`}function wa(e){return e instanceof Error&&e.name===`ConnectionAuthorizationFailedError`}function Ta(e){return e?.startAuthorization!==void 0}const Ea=Object.freeze({__ashPlaceholder:`connection-authorization`}),Da=new I(`ash.pendingConnectionToolCalls`);function Oa(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 ka(e,t){return`${e}__${t}`}const Aa=fi(`framework.connection-search`),ja=new I(`ash.connectionRegistry`),Ma=new I(`ash.pendingConnectionAuthorizations`),Na=new I(`ash.discoveredConnectionTools`),U={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 Pa(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(Na,{byConnection:{}}),e.set(Ma,[]),e.set(Da,[]),{}},sourceId:`ash:connection-search-tool`,sourceKind:`module`};async function Pa(e,t){let n=L(),r=n.get(ja);if(r===void 0)return[];let i=e.limit??10,a=Fa(e.keywords),o=[],s=[],c=e.connection!==void 0&&e.connection!==``?r.getConnections().filter(t=>t.connectionName===e.connection):r.getConnections(),l={...n.get(Na)?.byConnection},u=[];for(let e of c){let t;try{t=await r.getClient(e.connectionName).getToolMetadata()}catch(t){if(Ca(t)){u.push({connectionName:e.connectionName,description:e.description}),s.push({connection:e.connectionName,description:e.description,needsAuthorization:!0});continue}if(wa(t)){Aa.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`;Aa.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=Ia(a,n);t>0&&o.push({item:{connection:e.connectionName,description:n.description,inputSchema:n.inputSchema,qualifiedName:ka(e.connectionName,n.name),tool:n.name},score:t})}}n.set(Na,{byConnection:l});let d=[];if(u.length>0){for(let e of u)Ra(n,e);d=u.map(e=>e.connectionName).filter(e=>La(r,e))}if(d.length>0&&t?.toolCallId!==void 0){let r=n.get(Da);return n.set(Da,Oa(r,[{args:e,connectionNames:d,kind:`connection-discover`,toolCallId:t.toolCallId,toolName:`connection_search`}])),Ea}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 Fa(e){return e.toLowerCase().split(/[\s_\-./]+/).filter(e=>e.length>1)}function Ia(e,t){let n=Fa(t.name),r=Fa(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 La(e,t){return e===void 0?!1:Ta(e.getConnections().find(e=>e.connectionName===t)?.authorization)}function Ra(e,t){let n=e.get(Ma)??[];n.some(e=>e.connectionName===t.connectionName)||e.set(Ma,[...n,t])}const za=U.name;function Ba(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 ${za} 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(`
|
|
8
|
-
`)}function Va(e){return[...Ha(e.instructions),...Ua(e.workspaceSpec),...e.toolsAvailable?[`Tool execution
|
|
9
|
-
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.`]:[],...Wa(e.connections),...Ga(e.skills)]}function Ha(e){if(e===void 0)return[];let t=e.markdown.trim();return t.length===0?[]:[`Instructions (${e.name})\n${t}`]}function Ua(e){if(e===void 0)return[];let t=Sa(e);return t===void 0?[]:[t]}function Wa(e){return!e||e.length===0?[]:[Ba(e)]}function Ga(e){if(!e||e.length===0)return[];let t=ba(e);return t===null?[]:[t]}function Ka(e){let t=e.agent,n=qa(t);return{id:t.config.name,instructions:Va({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 qa(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 Ja=new Set([`aud`,`exp`,`iat`,`iss`,`jti`,`nbf`,`sub`]);function Ya(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 Xa(e){let t=Ya(e);return Object.freeze(Object.fromEntries(Object.entries(t).filter(([e])=>!Ja.has(e))))}function Za(e,t){let n=Ya(e);if(t.subjects!==void 0){let n=typeof e.sub==`string`?e.sub:null;if(n===null||!t.subjects.some(e=>$a(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 Qa(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=Ya(e.payload);return{attributes:Xa(e.payload),authenticator:e.authenticator,claims:r,issuer:t,principalId:`${t}:${n}`,principalType:e.principalType,subject:n}}function $a(e,t){if(!e.includes(`*`))return e===t;let n=e.replaceAll(/[.+?^${}()|[\]\\]/g,`\\$&`).replaceAll(`*`,`.*`);return RegExp(`^${n}$`).test(t)}const eo=v.object({issuer:v.string().optional(),jwks_uri:v.string().url()}).passthrough(),to=new Map,no=new Map;async function ro(e){let t;try{t=await io(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 Me(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&&oo({issuer:e.strategy.issuer,payload:n.payload}),i=r&&so({payload:n.payload});return!r&&!Za(n.payload,e.strategy)?{kind:`caller-not-allowed`}:{kind:`authenticated`,principal:Qa({authenticator:`oidc`,payload:n.payload,principalType:i?`runtime`:`service`})}}catch{return{kind:`not-authenticated`}}}async function io(e){let t=await ao(e.discoveryUrl),n=no.get(t.jwks_uri);if(n!==void 0)return n;let r=Ae(new URL(t.jwks_uri));return no.set(t.jwks_uri,r),r}async function ao(e){let t=to.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 eo.parse(await e.json())}).catch(t=>{throw to.delete(e),t});return to.set(e,n),await n}function oo(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 so(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 co(e){return{attributes:e.attributes,authenticator:e.authenticator,issuer:e.issuer,principalId:e.principalId,principalType:e.principalType,subject:e.subject}}const W=fi(`auth.vercel-oidc`);async function lo(e,t){return e===null||e.length===0?{kind:`not-authenticated`}:await ro({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 uo(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 fo(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`,po(e));return Response.json({code:n,error:r,ok:!1},{headers:a,status:t})}function po(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}="${mo(t)}"`).join(`, `);return`${e.scheme} ${t}`}function mo(e){return e.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`)}function ho(){return()=>void 0}async function go(e,t={}){if(e===null||e.length===0)return W.debug(`Rejected request without a bearer token.`),{ok:!1};let n=vo(e);if(n===null)return W.debug(`Rejected token that failed to decode as a JWT.`),{ok:!1};if(!n.issuer.startsWith(`https://oidc.vercel.com/`))return W.debug(`Rejected token whose issuer is not a Vercel OIDC issuer.`,{issuer:n.issuer}),{ok:!1};if(n.audiences.length===0)return W.debug(`Rejected token with no audience claim.`,{issuer:n.issuer}),{ok:!1};let r=await lo(e,{acceptCurrentVercelProject:!0,audiences:n.audiences,issuer:n.issuer,subjects:t.subjects??[]});return r.kind===`authenticated`?(W.debug(`Accepted Vercel OIDC token.`,{issuer:n.issuer,principalType:r.principal.principalType,subject:r.principal.subject}),{ok:!0,sessionAuth:co(r.principal)}):(W.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 _o(e={}){return async t=>{let n=await go(uo(t.headers.get(`authorization`)),e);return n.ok?n.sessionAuth:null}}function vo(e){let t;try{t=je(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 yo(e){return Number.isFinite(e)&&Number.isInteger(e)&&e>=0}function bo(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: ${d(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`||!yo(o))throw Error(`AttachmentRef payload "size" must be a non-negative integer. Got: ${JSON.stringify(o)}.`);return{params:a,size:o}}function xo(e){return e instanceof URL&&e.protocol===`ash-attachment:`}function So(e){return typeof Buffer<`u`&&Buffer.isBuffer(e)||e instanceof Uint8Array||e instanceof ArrayBuffer?e.byteLength:typeof e==`string`?Co(e):xo(e)?bo(e).size??null:e instanceof URL&&e.protocol===`data:`?Co(e.href):null}function Co(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 wo(r);try{return Buffer.byteLength(decodeURIComponent(r),`utf8`)}catch{return Buffer.byteLength(r,`utf8`)}}return/^https?:\/\//.test(e)?null:wo(e)}function wo(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 To=Object.freeze({allowedMediaTypes:`*`,maxBytes:25*1024*1024});function Eo(e,t=To){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 Do(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 Oo(e,t){if(t===`disabled`||!Do(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=So(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 ko(e,t){if(typeof e==`string`)return[];let n=[];for(let r of e){if(r.type!==`file`)continue;let e=Oo(r,t);e!==null&&n.push(e)}return n}function Ao(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 jo(e,t){return{method:`GET`,path:e,handler:t}}function Mo(e,t){return{method:`POST`,path:e,handler:t}}function No(e){let t=Po(e);return{__kind:`ash:channel`,routes:e.routes,adapter:t,receive:e.receive}}function Po(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 Si(e)},...a}}function Fo(e){let t=Eo(e.uploadPolicy);return No({routes:[Mo(`/ash/v1/session`,async(n,{send:r})=>{let i=await Io(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=Lo(o);if(s instanceof Response)return s;let c=Ho(s,t);if(c!==null)return c;let l=`ash:${crypto.randomUUID()}`,u=await r(zo(s),{auth:a,continuationToken:l});return Response.json({continuationToken:u.continuationToken,ok:!0,sessionId:u.id},{headers:{"cache-control":`no-store`,[f]:u.id},status:202})}),Mo(`/ash/v1/session/:sessionId`,async(n,{send:r,getSession:i,params:a})=>{let o=await Io(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=Ro(l);if(u instanceof Response)return u;let d=Ho(u,t);if(d!==null)return d;let p=await r({inputResponses:u.inputResponses,message:u.message,modelContext:u.modelContext},{auth:s,continuationToken:u.continuationToken});return Response.json({ok:!0,sessionId:p.id},{headers:{"cache-control":`no-store`,[f]:p.id},status:200})}),jo(`/ash/v1/session/:sessionId/stream`,async(t,{getSession:n,params:r})=>{let i=await Io(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=Ko(t);if(o instanceof Response)return o;try{let e=qo(await n(a).getEventStream({startIndex:o}));return new Response(e,{headers:{"cache-control":`no-store`,"content-type":ee,[f]:a,[_]:m,[te]:`14`}})}catch{return Response.json({error:`Session not found.`,ok:!1},{status:404})}})]})}async function Io(e,t){let n=await e(t);return n===null?fo({challenges:[{scheme:`Bearer`}]}):n??null}function Lo(e){let t=Bo(e.message);if(t instanceof Response)return t;let n=Wo(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 Ro(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=Bo(e.message);if(n instanceof Response)return n;let r=Uo(e.inputResponses);if(r instanceof Response)return r;let i=Wo(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 zo(e){return e.modelContext===void 0?e.message:{message:e.message,modelContext:e.modelContext}}function Bo(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=Vo(n);if(e instanceof Response)return e;t.push(e)}return t}function Vo(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 Ho(e,t){if(!e.message)return null;let n=ko(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:Ao(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 Uo(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(g);return t.length===e.length?t:Response.json({error:`Expected every 'inputResponses' entry to match the HITL response schema.`,ok:!1},{status:400})}function Wo(e){if(e!==void 0){if(typeof e==`string`)return e.length>0?[Go(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=>Go(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=ie(e);return[Go(JSON.stringify(t))]}catch{return Response.json({error:`Expected 'clientContext' to be a JSON-serializable object.`,ok:!1},{status:400})}}}function Go(e){return{role:`user`,content:`Ephemeral client context:
|
|
10
|
-
${e}`}}function Ko(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 qo(e){let t=new TextEncoder;return e.pipeThrough(new TransformStream({transform(e,n){n.enqueue(t.encode(`${JSON.stringify(e)}\n`))}}))}function Jo(){return new Response(`<!doctype html>
|
|
11
|
-
<html lang="en">
|
|
12
|
-
<head>
|
|
13
|
-
<meta charset="utf-8" />
|
|
14
|
-
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
15
|
-
<title>Authorization complete</title>
|
|
16
|
-
<style>
|
|
17
|
-
:root {
|
|
18
|
-
color-scheme: light dark;
|
|
19
|
-
--bg: #fafafa;
|
|
20
|
-
--fg: #111111;
|
|
21
|
-
--muted: #525252;
|
|
22
|
-
--card-bg: #ffffff;
|
|
23
|
-
--card-border: #e5e5e5;
|
|
24
|
-
}
|
|
25
|
-
@media (prefers-color-scheme: dark) {
|
|
26
|
-
:root {
|
|
27
|
-
--bg: #0a0a0a;
|
|
28
|
-
--fg: #fafafa;
|
|
29
|
-
--muted: #a3a3a3;
|
|
30
|
-
--card-bg: #171717;
|
|
31
|
-
--card-border: #262626;
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
body {
|
|
35
|
-
margin: 0;
|
|
36
|
-
min-height: 100vh;
|
|
37
|
-
display: grid;
|
|
38
|
-
place-items: center;
|
|
39
|
-
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif;
|
|
40
|
-
background: var(--bg);
|
|
41
|
-
color: var(--fg);
|
|
42
|
-
}
|
|
43
|
-
.card {
|
|
44
|
-
max-width: 28rem;
|
|
45
|
-
padding: 2rem 2.25rem;
|
|
46
|
-
border: 1px solid var(--card-border);
|
|
47
|
-
border-radius: 12px;
|
|
48
|
-
background: var(--card-bg);
|
|
49
|
-
color: var(--fg);
|
|
50
|
-
text-align: center;
|
|
51
|
-
}
|
|
52
|
-
h1 { font-size: 1.25rem; margin: 0 0 0.5rem; color: var(--fg); }
|
|
53
|
-
p { margin: 0; color: var(--muted); line-height: 1.5; }
|
|
54
|
-
</style>
|
|
55
|
-
</head>
|
|
56
|
-
<body>
|
|
57
|
-
<main class="card">
|
|
58
|
-
<h1>Authorization complete</h1>
|
|
59
|
-
<p>You can close this tab and return to your app.</p>
|
|
60
|
-
</main>
|
|
61
|
-
</body>
|
|
62
|
-
</html>`,{headers:{"cache-control":`no-store`,"content-type":`text/html; charset=utf-8`},status:200})}const Yo=[`GET`,`POST`];function Xo(){return Yo.map(e=>Qo(e))}function Zo(){return new Set(Yo.map($o))}function Qo(e){let t=$o(e);return{name:t,method:e,urlPath:h,fetch:es,logicalPath:`framework://channels/${t}`,sourceId:`ash:framework:connection-callback-${e.toLowerCase()}`,sourceKind:`module`}}function $o(e){return`.well-known/ash/v1/connections/callback/${e.toLowerCase()}`}async function es(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 ts(e);try{await Ce(r,i)}catch{return Response.json({error:`Connection callback not pending.`,ok:!1},{status:404})}return Jo()}async function ts(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 ns(){let e=Fo({auth:is()}),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(...Xo()),t}function rs(){return new Set([`ash`,...Zo()])}function is(){return process.env.VERCEL?_o():ho()}const as=ne.omit({action:!0,display:!0,requestId:!0}),{$schema:os,...ss}=v.toJSONSchema(as),cs={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:ss,logicalPath:`ash:framework/ask-question`,name:`ask_question`,sourceId:`ash:ask-question-tool`,sourceKind:`module`};async function G(){let e=L().get(ru);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 K(e){if(!e.startsWith(`/`))throw Error(`filePath must be an absolute path. Received: "${e}". Use an absolute path such as /workspace/foo.ts.`)}function ls(e){return ds(e,`head`)}function us(e){return ds(e,`tail`)}function ds(e,t){let n=e.split(`
|
|
63
|
-
`),r=ps(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=fs(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(`
|
|
64
|
-
`),outputLines:a.length,totalLines:r,truncated:a.length<r}}function fs(e){return e.length<=2e3?e:e.slice(0,2e3)+` [truncated]`}function ps(e){return e.length>0&&e[e.length-1]===``?e.length-1:e.length}async function ms(e){let t=await(await G()).runCommand({command:e.command}),n=us(t.stdout),r=us(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 hs={additionalProperties:!1,properties:{command:{description:`The shell command to execute.`,type:`string`}},required:[`command`],type:`object`};async function gs(e){return ms(e)}const _s={description:`Execute a shell command in the shared workspace environment.`,execute:gs,inputSchema:hs,logicalPath:`ash:framework/bash`,name:`bash`,sourceId:`ash:bash-tool`,sourceKind:`module`},vs=new I(`ash.readFile`);function q(e){return ce.normalize(e)}function ys(e){return e}function bs(e){let t=he(`sha256`).update(e.content,`utf8`).digest(`hex`);return{byteLength:Buffer.byteLength(e.content,`utf8`),contentHash:t,filePath:e.filePath}}function xs(e,t,n){let r=e.ensure(vs,()=>({byTarget:{}}));e.set(vs,{byTarget:{...r.byTarget,[t]:n}})}function Ss(e){e.set(vs,{byTarget:{}})}const Cs=new Map;async function ws(e){let t=Cs.get(e.id);if(t!==void 0)return t;let n=Ts(e);Cs.set(e.id,n);try{return await n}catch{return Cs.delete(e.id),!1}}async function Ts(e){return(await e.runCommand({command:`command -v rg >/dev/null 2>&1`})).exitCode===0}function J(e){return`'${e.replace(/'/g,`'\\''`)}'`}async function Es(e){let t=e.path??`/workspace`;K(t);let n=q(t),r=Math.min(Math.max(1,e.limit??100),1e3),i=await G(),a=await ws(i)?Ds({normalizedPath:n,pattern:e.pattern}):Os({normalizedPath:n,pattern:e.pattern}),o=await i.runCommand({command:a});if(o.exitCode!==0&&o.exitCode!==1)throw As(a,o.exitCode,o.stderr);let s=o.stdout.split(`
|
|
65
|
-
`).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=q(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(`
|
|
66
|
-
`),count:u.length,path:n,truncated:p}}function Ds(e){return[`rg --files --hidden`,`--glob '!.git/*'`,`--glob ${J(e.pattern)}`,`-- ${J(e.normalizedPath)}`].join(` `)}function Os(e){let t=ks(e.pattern),n=t.includes(`/`)?`-path ${J(`*/${t}`)}`:`-name ${J(t)}`;return[`find ${J(e.normalizedPath)}`,`-type f`,`-not -path '*/.git/*'`,n].join(` `)}function ks(e){let t=e.replaceAll(`**`,`*`);for(;t.startsWith(`*/`);)t=t.slice(2);return t}function As(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 js={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 Ms(e){return Es(e)}const Ns={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(`
|
|
67
|
-
`),execute:Ms,inputSchema:js,logicalPath:`ash:framework/glob`,name:`glob`,sourceId:`ash:glob-tool`,sourceKind:`module`};async function Ps(e){let t=e.path??`/workspace`;K(t);let n=q(t),r=Math.min(Math.max(1,e.limit??100),1e3),i=e.context!==void 0&&e.context>0?e.context:0,a=await G(),o=await ws(a)?Fs({contextLines:i,effectiveLimit:r,glob:e.glob,ignoreCase:e.ignoreCase??!1,literal:e.literal??!1,normalizedPath:n,pattern:e.pattern}):Is({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 Rs(o,s.exitCode,s.stderr);let c=s.stdout;return c.trim().length===0?{content:`No matches found`,matchCount:0,path:n,truncated:!1}:Ls({effectiveLimit:r,normalizedPath:n,stdout:c})}function Fs(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 ${J(e.glob)}`),e.contextLines>0&&t.push(`--context ${e.contextLines}`),t.push(`--max-count ${e.effectiveLimit}`),t.push(`--`),t.push(J(e.pattern)),t.push(J(e.normalizedPath)),t.join(` `)}function Is(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=${J(e.glob)}`),e.contextLines>0&&t.push(`-C ${e.contextLines}`),t.push(`-m ${e.effectiveLimit}`),t.push(`--`),t.push(J(e.pattern)),t.push(J(e.normalizedPath)),t.join(` `)}function Ls(e){let t=e.stdout.split(`
|
|
68
|
-
`),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=fs(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(`
|
|
69
|
-
`);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 Rs(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 zs={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 Bs(e){return Ps(e)}const Vs={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(`
|
|
70
|
-
`),execute:Bs,inputSchema:zs,logicalPath:`ash:framework/grep`,name:`grep`,sourceId:`ash:grep-tool`,sourceKind:`module`};async function Hs(e){let{filePath:t,offset:n,limit:r}=e;K(t);let i=await G(),a=q(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(`
|
|
71
|
-
`),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=bs({content:c,filePath:a}),f=ys(a);xs(L(),f,d);let p=o-1,m=Math.min(p+s,u),h=l.slice(p,m),g=[],_=0,ee=!1;for(let e=0;e<h.length;e++){let t=`${o+e}: ${fs(h[e]??``)}`,n=Buffer.byteLength(t,`utf8`)+1;if(_+n>51200&&g.length>0){ee=!0;break}g.push(t),_+=n}let te=g.join(`
|
|
72
|
-
`),ne=o+g.length-1;return ne<u||ee?{content:te,nextOffset:ne+1,path:a,totalLines:u,truncated:!0}:{content:te,path:a,totalLines:u,truncated:!1}}const Us={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 Ws(e){return Hs(e)}const Gs={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(`
|
|
73
|
-
`),execute:Ws,inputSchema:Us,logicalPath:`ash:framework/read-file`,name:`read_file`,onCompact({ctx:e}){return Ss(e),{}},sourceId:`ash:read-file-tool`,sourceKind:`module`},Ks=/^---\r?\n[\s\S]*?\r?\n---\r?\n?/;function qs(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 Js(e,t){qs(t);let n=await Ys(e),r=Xs(t,`SKILL.md`),i=await n.readTextFile({path:r});if(i===null)throw Error(`No skill named "${t}" at ${r}.`);return i.replace(Ks,``)}async function Ys(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 Xs(e,t){return`${H}/skills/${e}/${t}`}async function Zs(e){let t=L().get(ru);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 Js(t,n)}const Qs={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=>Zs(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`},$s=new I(`ash.todo`);function ec(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(`
|
|
74
|
-
`)}`}function tc(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 nc(e){let t=L(),{todos:n}=e??{};if(n!==void 0){let e={items:[...n]};return t.set($s,e),tc(e)}return tc(t.ensure($s,()=>({items:[]})))}const rc={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(`
|
|
75
|
-
`),execute:async e=>nc(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($s);if(t===void 0||t.items.length===0)return{};let n=ec(t);return n===void 0?{}:{messages:[{content:n,role:`user`}]}},sourceId:`ash:todo-tool`,sourceKind:`module`};function ic(e){let t=new Ne({bulletListMarker:`-`,codeBlockStyle:`fenced`,emDelimiter:`*`,headingStyle:`atx`,hr:`---`});return t.remove([`script`,`style`,`meta`,`link`]),t.turndown(e)}function ac(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,`
|
|
76
|
-
`),t=t.replace(/<br\s*\/?>/gi,`
|
|
77
|
-
`),t=t.replace(/<[^>]+>/g,``),t=cc(t),t=t.split(`
|
|
78
|
-
`).map(e=>e.replace(/[ \t]+/g,` `).trim()).join(`
|
|
79
|
-
`).replace(/\n{3,}/g,`
|
|
80
|
-
|
|
81
|
-
`).trim(),t}const oc={"&":`&`,">":`>`,"<":`<`," ":` `,""":`"`,"'":`'`,"'":`'`,"/":`/`},sc=new RegExp(Object.keys(oc).join(`|`),`gi`);function cc(e){return e.replace(sc,e=>oc[e.toLowerCase()]??e)}const lc=5*1024*1024;async function uc(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=dc(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":k},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)>lc)throw Error(`Response too large (exceeds 5 MB limit).`);let u=await c.arrayBuffer();if(u.byteLength>lc)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?ic(p):n===`text`&&f?ac(p):p;let{output:h,truncated:g}=ls(m);return{content:h,contentType:d,truncated:g,url:t}}function dc(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 fc(e){return uc(e)}const pc={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(`
|
|
82
|
-
`),execute:fc,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`},mc={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 hc(e){let{filePath:t,content:n}=e;K(t);let r=await G(),i=L(),a=q(t),o=ys(a),s=await r.readTextFile({path:t});if(s===null)return await r.writeTextFile({content:n,path:t}),xs(i,o,bs({content:n,filePath:a})),{existed:!1,path:a};let c=i.ensure(vs,()=>({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=bs({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}),xs(i,o,bs({content:n,filePath:a})),{existed:!0,path:a}}const gc={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 _c(e){return hc(e)}const vc=[cs,_s,Ns,Vs,Gs,{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(`
|
|
83
|
-
`),execute:_c,inputSchema:gc,logicalPath:`ash:framework/write-file`,name:`write_file`,sourceId:`ash:write-file-tool`,sourceKind:`module`},rc,pc,mc,Qs,U],yc=new Map([[U,e=>e.hasConnections]]);function bc(e){return vc.filter(t=>{let n=yc.get(t);return n===void 0||n(e)})}function xc(){return new Set(vc.map(e=>e.name))}function Sc(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 Y=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 Cc(e){return{exportName:e.exportName,logicalPath:e.logicalPath,sourceId:e.sourceId,sourceKind:`module`}}async function X(e){let n=e.nodeId??`__root__`,r=e.moduleMap.nodes[n]?.modules[e.definition.sourceId];if(r===void 0)throw new Y(`Missing compiled module namespace for ${e.kindLabel} source "${e.definition.sourceId}" in node "${n}".`,{logicalPath:e.definition.logicalPath,sourceId:e.definition.sourceId});return await a(t(o(r,`Missing compiled module namespace for ${e.kindLabel} source "${e.definition.sourceId}" in node "${n}".`),{exportName:e.definition.exportName,logicalPath:e.definition.logicalPath}))}async function wc(e,t,n){try{let r=Jn(await X({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=Cc({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 Y?t:new Y(`Failed to attach the channel definition from "${e.logicalPath}": ${d(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}async function Tc(e,t,n){try{let r=o(await X({definition:e,kindLabel:`connection`,moduleMap:t,nodeId:n}),`Expected the connection export "${e.exportName??`default`}" from "${e.logicalPath}" to return an object.`);Pr(`connection:${r.url}`,{kind:`connection`,name:e.connectionName});let i=r.auth!==void 0,a=r.headers!==void 0,s={connectionName:e.connectionName,description:e.description,exportName:e.exportName,logicalPath:e.logicalPath,sourceId:e.sourceId,sourceKind:`module`,url:e.url};if(i)try{s.authorization=$n(r.auth,`Connection "${e.connectionName}" at "${e.logicalPath}":`)}catch(t){throw new Y(d(t),{logicalPath:e.logicalPath,sourceId:e.sourceId})}return a&&(s.headers=r.headers),r.tools!==void 0&&(s.tools=r.tools),typeof r.approval==`function`&&(s.approval=r.approval),s}catch(t){throw t instanceof Y?t:new Y(`Failed to resolve connection "${e.connectionName}" from "${e.logicalPath}": ${d(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}async function Ec(e,t,n){try{let r=o(await X({definition:e,kindLabel:`hook`,moduleMap:t,nodeId:n}),Z(e,`to return an object`)),a={},s={},c=r.lifecycle;if(c!==void 0){let t=o(c,Z(e,"to expose `lifecycle` as an object"));for(let n of[`session`,`turn`]){let r=t[n];r!==void 0&&(a[n]=i(r,Z(e,`to provide a function for "lifecycle.${n}"`)))}}let l=r.events;if(l!==void 0){let t=o(l,Z(e,"to expose `events` as an object"));for(let[n,r]of Object.entries(t))r!==void 0&&(s[n]=i(r,Z(e,`to provide a function for "events.${n}"`)))}return{events:s,exportName:e.exportName,lifecycle:a,logicalPath:e.logicalPath,slug:e.slug,sourceId:e.sourceId,sourceKind:`module`}}catch(t){throw t instanceof Y?t:new Y(`Failed to attach hook handlers from "${e.logicalPath}": ${d(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}function Z(e,t){return`Expected the hook export "${e.exportName??`default`}" from "${e.logicalPath}" ${t}.`}var Dc=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 Oc(e){let t=[];for await(let n of e)t.push(n);return Buffer.concat(t)}function kc(e){return new ReadableStream({start(t){t.enqueue(e),t.close()}})}function Q(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 Oc(n)},async readTextFile(t){Ac(t);let n=await e.readFile({abortSignal:t.abortSignal,path:e.resolvePath(t.path)});return n===null?null:Mc(Nc(await Oc(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:kc(t.content),path:e.resolvePath(t.path)})},async writeTextFile(t){let n=Pc(t.content,t.encoding??`utf-8`);await e.writeFile({abortSignal:t.abortSignal,content:kc(n),path:e.resolvePath(t.path)})}}}function Ac(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 jc(e){let t=[],n=0;for(let r=0;r<e.length;r++)e[r]===`\r`?r+1<e.length&&e[r+1]===`
|
|
84
|
-
`?(t.push(e.slice(n,r+2)),n=r+2,r++):(t.push(e.slice(n,r+1)),n=r+1):e[r]===`
|
|
85
|
-
`&&(t.push(e.slice(n,r+1)),n=r+1);return n<e.length&&t.push(e.slice(n)),t}function Mc(e,t){if(t.startLine===void 0&&t.endLine===void 0)return e;let n=jc(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 Nc(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 Pc(e,t){return t===`utf-8`||t===`utf8`?new TextEncoder().encode(e):Buffer.from(e,t)}function Fc(e={}){return{name:`local`,async prewarm(e){let t=Vc(gu(e.runtimeContext.appRoot),e.templateKey);if(await Yc(t))return;let n=await Ic({sessionKey:e.templateKey,snapshotPath:t}),r=Q(Rc(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=gu(e.runtimeContext.appRoot),n=await qc(Vc(t,e.templateKey));if(n===null)throw new Dc({backendName:`local`,templateKey:e.templateKey});let r=Xc(e.existingMetadata)??Hc(t,e.sessionKey);return await Yc(r)||await Jc(r,n),Lc(await Ic({sessionKey:e.sessionKey,snapshotPath:r}))}}}async function Ic(e){let{Bash:t,InMemoryFs:n}=await import(`#compiled/just-bash/index.js`),r=await qc(e.snapshotPath),i=new n(Uc(r));await Wc(i),await Gc(i,r?.entries??[]);let a=new t({cwd:H,env:r?.env,fs:i,network:{dangerouslyAllowFullInternetAccess:!0}});return{async captureSnapshot(){let t=await Kc({filesystem:i,sandbox:a});return await Jc(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 ${J(e.workingDirectory)} && ${e.command} )`,n=a.exec(t),r=e.abortSignal?await zc(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=y(t.path);await i.mkdir(e,{recursive:!0}),await i.writeFile(t.path,t.content)}}}}function Lc(e){let t=Q(Rc(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 Rc(e){return{id:e.sessionKey,resolvePath:Bc,async runCommand(t){return await e.executeCommand(t)},async readFile(t){let n=await e.readFileBytes(t.path);return n===null?null:kc(n)},async writeFile(t){let n=await Oc(t.content);await e.writeFiles([{content:n,path:t.path}])}}}async function zc(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 Bc(e){return e.startsWith(`/`)?e:`${H}/${e}`}function Vc(e,t){return b(e,`local`,`templates`,`${t}.json`)}function Hc(e,t){return b(e,`local`,`sessions`,`${t}.json`)}function Uc(e){let t={};for(let n of e?.entries??[])n.kind===`file`&&(t[n.path]=Buffer.from(n.contentBase64,`base64`));return t}async function Wc(e){await e.mkdir(H,{recursive:!0})}async function Gc(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 Kc(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 qc(e){if(!await Yc(e))return null;let t=JSON.parse(await pe(e,`utf8`));return t.version===1?t:null}async function Jc(e,t){await S(y(e),{recursive:!0}),await C(e,`${JSON.stringify(t,null,2)}\n`)}async function Yc(e){try{return await de(e),!0}catch{return!1}}function Xc(e){let t=e?.snapshotPath;return typeof t==`string`?t:void 0}function Zc(e){return Fc({createOptions:e})}function Qc(e={}){let t=e.loadSandboxModule??(async()=>await import(`#compiled/@vercel/sandbox/index.js`)),n={timeout:gl,...e.createOptions},r=new Map;return{name:`vercel`,async create(e){let i=fl(n.tags,e.tags),a;try{a=await $c({loadSandboxModule:t,prewarmedTemplates:r,templateKey:e.templateKey})}catch(t){throw Dc.is(t)?t:Error(`Failed to read sandbox template "${e.templateKey}": ${hl(t)}`,{cause:t})}let o;try{o=await tl({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}": ${hl(t)}`,{cause:t})}return nl(o,e.sessionKey)},async prewarm(e){let i;try{i=await el({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}": ${hl(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 $c(e){let t=e.prewarmedTemplates.get(e.templateKey);if(t!==void 0)return t;let n=await cl(await e.loadSandboxModule(),e.templateKey);if(n===null||typeof n.currentSnapshotId!=`string`)throw new Dc({backendName:`vercel`,templateKey:e.templateKey});return{sandboxName:n.name,snapshotId:n.currentSnapshotId,templateKey:e.templateKey}}async function el(e){let t=await e.loadSandboxModule(),n=await cl(t,e.templateKey),r=fl(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 pl(n,r);let i=ul(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 al(n,e.createOptions);let a=Q(rl(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 tl(e){let t=dl(e.existingMetadata)??e.sessionKey,n=await cl(e.sandboxModule,t);if(n!==null)return await pl(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 nl(e,t){return{session:Q(rl(e,t)),useSessionFn:async n=>(n!==void 0&&await e.update(n),Q(rl(e,t))),async captureState(){return{backendName:`vercel`,metadata:{sandboxName:e.name},sessionKey:t}},async dispose(){}}}function rl(e,t){return{id:t,resolvePath:il,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 Oc(t.content);await e.writeFiles([{content:n,path:t.path}])}}}function il(e){return e.startsWith(`/`)?e:`${H}/${e}`}async function al(e,t){await ol(e,{failureMessage:`Failed to initialize Vercel sandbox workspace.`,script:`mkdir -p ${H} && chown ${sl}:${sl} ${H}`}),t.networkPolicy!==`deny-all`&&await ol(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 ol(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 sl=`vercel-sandbox`;async function cl(e,t){try{return await e.Sandbox.get({name:t})}catch(e){if(ll(e))return null;throw Error(`Failed to look up Vercel sandbox "${t}": ${hl(e)}`,{cause:e})}}function ll(e){return e instanceof Error?(e.response?.status??e.cause?.response?.status)===404:!1}function ul(e){let t=e.source;if(t?.type===`snapshot`&&typeof t.snapshotId==`string`)return t.snapshotId}function dl(e){let t=e?.sandboxName;return typeof t==`string`?t:void 0}function fl(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>_l)throw Error(`Vercel Sandbox supports at most ${_l} tags. Ash reserves "agent", "channel", and "sessionId"; remove or consolidate custom tags passed to vercelBackend().`);return n}}async function pl(e,t){t===void 0||ml(e.tags,t)||await e.update({tags:t})}function ml(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 hl(e){return e instanceof Error?e.message:String(e)}const gl=1800*1e3,_l=5;function vl(e){return Qc({createOptions:e})}function yl(e){return pr(()=>process.env.VERCEL?vl(e?.vercel):Zc(e?.local))}async function bl(e,t,n){try{let r=o(await X({definition:e,kindLabel:`sandbox`,moduleMap:t,nodeId:n}),`Expected the sandbox export "${e.exportName??`default`}" from "${e.logicalPath}" to return an object.`);return{backend:xl(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 Y?t:new Y(`Failed to attach the sandbox lifecycle handlers from "${e.logicalPath}": ${d(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}function xl(e,t){if(e===void 0)return yl();if(typeof e==`function`)return pr(e);if(typeof e!=`object`||!e)throw new Y(`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 Y(`Sandbox "${t}" backend is missing a non-empty string "name" identifier.`,{logicalPath:t});if(typeof n.create!=`function`)throw new Y(`Sandbox "${t}" backend is missing a "create" function.`,{logicalPath:t});return n}async function Sl(e,t,n){try{let r=o(await X({definition:e,kindLabel:`tool`,moduleMap:t,nodeId:n}),$(e,`to return an object`));Pr(`tool:${r.description}`,{kind:`tool`,name:e.name});let a=i(r.execute,$(e,`to provide an execute function`));return{description:e.description,execute:a,exportName:e.exportName,inputSchema:e.inputSchema,logicalPath:e.logicalPath,name:e.name,sourceId:e.sourceId,sourceKind:`module`,...Cl(r,e)}}catch(t){throw t instanceof Y?t:new Y(`Failed to attach the tool execute function from "${e.logicalPath}": ${d(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}function Cl(e,t){let n={};e.onCompact!==void 0&&(n.onCompact=i(e.onCompact,$(t,`to provide an onCompact function`))),e.needsApproval!==void 0&&(n.needsApproval=i(e.needsApproval,$(t,`to provide a needsApproval function`)));let r=wl(e,t);return r!==void 0&&(n.retentionPolicy=r),e.toModelOutput!==void 0&&(n.toModelOutput=i(e.toModelOutput,$(t,`to provide a toModelOutput function`))),e.inputSchema!==void 0&&Tl(e.inputSchema)&&(n.inputStandardSchema=e.inputSchema),n}function wl(e,t){let n=e.retentionPolicy;if(n!==void 0){if(n===`auto`||n===`keep`||typeof n==`function`)return n;throw new Y($(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 Tl(e){return typeof e==`object`&&!!e&&`~standard`in e&&typeof e[`~standard`]==`object`}async function El(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 wc(t,e.moduleMap,e.nodeId))}let i=await Promise.all(e.manifest.tools.map(t=>Sl(t,e.moduleMap,e.nodeId))),a=await Promise.all(e.manifest.hooks.map(t=>Ec(t,e.moduleMap,e.nodeId))),o=await Promise.all(e.manifest.connections.map(t=>Tc(t,e.moduleMap,e.nodeId))),s=e.manifest.sandbox===null?null:await bl(e.manifest.sandbox,e.moduleMap,e.nodeId),c=Dl(e.manifest.instructions),l=e.manifest.workspaceResourceRoot,u={channels:n,config:Ol(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 Dl(e){if(e!==void 0)return{name:e.name,logicalPath:e.logicalPath,markdown:e.markdown,sourceId:e.sourceId,sourceKind:e.sourceKind}}function Ol(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=Cc(e.config.source)),t}function kl(e){return{sandbox:{definition:e.authoredSandbox??Al(),workspaceResourceRoot:e.workspaceResourceRoot}}}function Al(){return{backend:yl(),logicalPath:`ash:framework/default-sandbox`,sourceId:`ash:default-sandbox`,sourceKind:`module`}}const jl=`load_skill`,Ml=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 Nl(e){let t=[],n=new Mi(`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 z(`subagent`,`Found multiple runtime subagents mapped to node id "${i.nodeId}".`,{...e,entryName:i.name});let a=Pl(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 Pl(e){return{description:e.description,inputSchema:Ml,kind:e.kind,logicalPath:e.logicalPath,name:e.name,nodeId:e.nodeId,sourceId:e.sourceId}}async function Fl(e,t={}){let n=[],r=new Mi(`tool`,t.reservedToolNames??[]);for(let t of e.tools){let e=await Il(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 Il(e){return{description:e.description,inputSchema:e.inputSchema,kind:`authored-tool`,logicalPath:e.logicalPath,name:e.name,sourceId:e.sourceId}}var Ll=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 Rl(e){let t=new Map,n=Wl(e.manifest),r=new Map(e.manifest.subagents.map(e=>[e.nodeId,e]));return{nodesByNodeId:t,root:await zl({childNodeIdsByParentNodeId:n,manifest:e.manifest,moduleMap:e.moduleMap,nodeId:M,nodesByNodeId:t,subagentNodesById:r})}}async function zl(e){let t=Gl(e.nodeId);if(e.nodesByNodeId.has(t))throw new Ll(`Found multiple runtime agent nodes for node id "${t}".`,{nodeId:t,sourceId:e.sourceId});let n=await El({manifest:e.manifest,moduleMap:e.moduleMap,nodeId:e.nodeId}),r=n.connections.length>0,i=bc({hasConnections:r}),a=r?ql(i,n.connections):i,o=new Set(a.map(e=>e.name)),s=xc(),c=new Set(n.tools.map(e=>e.name));for(let r of n.disabledFrameworkTools)if(!s.has(r))throw new Ll(`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 Fl({tools:[...a.filter(e=>!c.has(e.name)&&!l.has(e.name)),...n.tools]},{reservedToolNames:o.has(`load_skill`)||c.has(`load_skill`)?[]:[jl]}),d=new Set(n.channels.map(e=>e.name)),f=rs();for(let r of n.disabledFrameworkChannels)if(!f.has(r))throw new Ll(`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=[...ns().filter(e=>!d.has(e.name)&&!p.has(e.name)),...n.channels],h=kl({authoredSandbox:n.sandbox,workspaceResourceRoot:n.workspaceResourceRoot}),g=Nl({reservedToolNames:[jl,...u.preparedTools.map(e=>e.name)],subagents:await Bl({childNodeIdsByParentNodeId:e.childNodeIdsByParentNodeId,manifest:e.manifest,moduleMap:e.moduleMap,nodesByNodeId:e.nodesByNodeId,parentNodeId:e.nodeId,subagentNodesById:e.subagentNodesById})}),_={agent:n,channels:m,hookRegistry:Sc(n.hooks),nodeId:t,sandboxRegistry:h,sourceId:e.sourceId,subagentRegistry:g,toolRegistry:u,turnAgent:Ka({agent:n,nodeId:t,tools:[...u.preparedTools,...g.preparedTools]})};return e.nodesByNodeId.set(t,_),_}async function Bl(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 Ll(`Missing compiled subagent node "${r}" while resolving runtime subagents.`,{nodeId:Gl(e.parentNodeId),sourceId:r});t.push(await Vl({childNodeIdsByParentNodeId:e.childNodeIdsByParentNodeId,moduleMap:e.moduleMap,nodesByNodeId:e.nodesByNodeId,sourceRef:n,subagentNodesById:e.subagentNodesById}))}for(let n of e.manifest.remoteAgents)t.push(await Hl({moduleMap:e.moduleMap,nodeScopeId:e.parentNodeId,sourceRef:n}));return t}async function Vl(e){let t={description:e.sourceRef.description,kind:`subagent`,logicalPath:e.sourceRef.logicalPath,name:e.sourceRef.name,nodeId:Gl(e.sourceRef.nodeId),sourceId:e.sourceRef.sourceId,sourceKind:`module`};return await zl({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}async function Hl(e){let t=o(await X({definition:e.sourceRef,kindLabel:`remote agent`,moduleMap:e.moduleMap,nodeId:e.nodeScopeId}),`Expected remote agent source "${e.sourceRef.logicalPath}" to export an object.`),n={description:e.sourceRef.description,kind:`remote`,logicalPath:e.sourceRef.logicalPath,name:e.sourceRef.name,nodeId:Gl(e.sourceRef.nodeId),path:e.sourceRef.path,sourceId:e.sourceRef.sourceId,sourceKind:`module`,url:e.sourceRef.url};typeof t.auth==`function`&&(n.auth=t.auth);let r=Ul(t.headers);return r!==void 0&&(n.headers=r),n}function Ul(e){if(e===void 0)return;if(typeof e==`function`)return e;if(typeof e!=`object`||!e||Array.isArray(e))return;let t={};for(let[n,r]of Object.entries(e))typeof r==`string`&&(t[n]=r);return t}function Wl(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 Gl(e){return e===`__root__`?sa:e}const Kl=U.name;function ql(e,t){let n=t.map(e=>e.connectionName).join(`, `);return e.map(e=>e.name===Kl?{...e,description:`${e.description} Available connections: ${n}.`}:e)}const Jl=process.env.ASH_DISABLE_AGENT_CACHE===`1`;async function Yl(e){let[t,n]=await Promise.all([da({compiledArtifactsSource:e}),Xl(e)]),r=await Rl({manifest:t,moduleMap:n}),i=r.root;return{adapterRegistry:Ii({channels:tu(r)}),compiledArtifactsSource:e,graph:r,hookRegistry:i.hookRegistry,moduleMap:n,resolvedAgent:i.agent,subagentRegistry:i.subagentRegistry,toolRegistry:i.toolRegistry,turnAgent:i.turnAgent}}async function Xl(e){return e.kind===`disk`&&e.moduleMapLoaderPath!==void 0?await Zl(e):await ga({compiledArtifactsSource:e})}async function Zl(e){if(e.moduleMapLoaderPath===void 0)throw Error(`Authored-source module map loading requires "moduleMapLoaderPath" in the compiled artifacts source.`);return await(await import(xe(e.moduleMapLoaderPath).href)).loadCompiledModuleMapFromAuthoredSource({compiledArtifactsSource:e})}async function Ql(e){if(Jl)return Yl(e);let t=Xi(),n=Hi(e),r=await ia(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=Yl(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 $l(e){let t=await Ql(e.compiledArtifactsSource);if(e.nodeId===void 0)return t;let n=ca(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 eu(){let e=Xi();e.bundleCache.clear(),e.bundleCacheKeyBySourceKey.clear()}function tu(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 I(`ash.channel`,{codec:{serialize(e){return{kind:Ci(e),state:e.state?{...e.state}:{}}},deserialize(e,t){let n=t.get(nu);if(n===void 0)throw Error(`Cannot deserialize "ash.channel" before "ash.bundle". The runtime bundle must be present in context.`);return Li(n.adapterRegistry,e)}}});const nu=new I(`ash.bundle`,{codec:{serialize:e=>({nodeId:e.nodeId,source:e.compiledArtifactsSource}),deserialize:e=>{let{source:t,nodeId:n}=e;return $l({compiledArtifactsSource:t,nodeId:n})}}});new I(`ash.session`);const ru=new I(`ash.sandbox`),iu=`workflowEntry`,au=Dt(),ou=new Set([iu,`turnWorkflow`]),su=au.name,cu={workflowId:`workflow//${su}//${iu}`};`${su}`;function lu(e=process.cwd()){return x(e)}function uu(e){return he(`sha256`).update(e).digest(`hex`).slice(0,12)}function du(){return!!process.env.VERCEL}function fu(e,t=`all`){let n=b(e,`.ash`,`nitro`);return t===`all`?n:b(n,t)}function pu(e,t){return b(e,`.ash`,`nitro-output`,t)}function mu(e){let t=b(j(),`.ash`,`workflow-cache`);return hu(t),b(t,uu(e))}function hu(e){if(!w(e))return;let t=Dt().version,n;try{n=_e(e)}catch{return}for(let r of n){let n=b(e,r),i=b(n,`ash-cache.json`);if(w(i))try{let e=JSON.parse(ge(i,`utf8`));typeof e.ashVersion==`string`&&e.ashVersion!==t&&ye(n,{force:!0,recursive:!0})}catch{}}}function gu(e){return b(e,`.ash`,`sandbox-cache`)}function _u(e){return du()?b(e,`.vercel`,`output`):b(e,`.output`)}function vu(e){return{appRoot:e,outputDir:_u(e),workflowId:cu.workflowId,workflowBuildDir:mu(e),workflowSourceDir:Ct(`src/execution`)}}export{Re as $,St as A,it as B,fn as C,Dt as D,M as E,lt as F,Je as G,Ge as H,st as I,We as J,Ue as K,O as L,k as M,at as N,j as O,ct as P,Le as Q,ut as R,_n as S,pn as T,Ke as U,nt as V,qe as W,D as X,T as Y,Ie as Z,Vi as _,mu as a,Hn as b,Rl as c,H as d,Be as et,da as f,Bi as g,B as h,pu as i,Ot as j,Ct as k,rs as l,ta as m,lu as n,ou as o,sa as p,Ye as q,fu as r,eu as s,vu as t,ze as tt,ns as u,Hi as v,mn as w,yn as x,ri as y,tt as z};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{z as e}from"#compiled/zod/index.js";const t=Symbol(`invalid-json-value-candidate`);function n(e){let n=i(e);if(n===t)throw TypeError(`Expected a JSON-serializable value.`);return n}function r(e){let t=n(e);if(!a(t))throw TypeError(`Expected a JSON-serializable object.`);return t}function i(e,n=new WeakSet){if(e===null||typeof e==`boolean`||typeof e==`string`)return e;if(typeof e==`number`)return Number.isFinite(e)?e:t;if(Array.isArray(e)){let r=[];for(let a of e){let e=i(a,n);if(e===t)return t;r.push(e)}return r}if(typeof e!=`object`||e===void 0||!o(e)||n.has(e))return t;n.add(e);let r={};for(let[a,o]of Object.entries(e)){if(o===void 0)continue;let e=i(o,n);if(e===t)return t;r[a]=e}return n.delete(e),r}function a(e){return e!==null&&!Array.isArray(e)&&typeof e==`object`}function o(e){let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}const s=e.unknown().transform((t,r)=>{try{return n(t)}catch(t){return r.addIssue({code:`custom`,message:l(t,`Expected a JSON-serializable value.`)}),e.NEVER}}),c=e.unknown().transform((t,n)=>{try{return r(t)}catch(t){return n.addIssue({code:`custom`,message:l(t,`Expected a JSON-serializable object.`)}),e.NEVER}});function l(e,t){return e instanceof Error?e.message:t}const u=`/ash/v1`,d=`${u}/health`,f=`${u}/info`,p=`${u}/session`,m=`${u}/session/:sessionId`,h=`${u}/session/:sessionId/stream`,g=`${u}/connections/:name/callback/:token`;function _(e){return`${u}/session/${encodeURIComponent(e)}/stream`}function v(e){return`${u}/session/${encodeURIComponent(e)}`}const y=`x-ash-session-id`,b=`x-ash-stream-format`,x=`x-ash-stream-version`,S=`application/x-ndjson; charset=utf-8`,C=`ndjson`;new TextEncoder;function w(e){return e.type===`session.completed`||e.type===`session.failed`||e.type===`session.waiting`}const T=e.object({callId:e.string(),input:c,kind:e.literal(`tool-call`),toolName:e.string()}).strict();e.object({callId:e.string(),description:e.string(),input:c,kind:e.literal(`subagent-call`),name:e.string(),nodeId:e.string(),subagentName:e.string()}).strict(),e.object({callId:e.string(),input:c,kind:e.literal(`load-skill`)}).strict(),e.object({callId:e.string(),isError:e.boolean().optional(),kind:e.literal(`tool-result`),output:s,toolName:e.string()}).strict(),e.object({callId:e.string(),isError:e.boolean().optional(),kind:e.literal(`subagent-result`),output:s,subagentName:e.string()}).strict(),e.object({callId:e.string(),isError:e.boolean().optional(),kind:e.literal(`load-skill-result`),output:s,name:e.string().optional()}).strict();const E=e.object({description:e.string().describe(`Optional additional context for this option.`).optional(),id:e.string().describe(`Stable identifier for the option.`),label:e.string().describe(`User-facing label for the option.`),style:e.enum([`primary`,`danger`,`default`]).describe(`Visual treatment hint for the option.`).optional()}).strict(),D=e.object({action:T,allowFreeform:e.boolean().describe(`Whether the user may answer with freeform text instead of selecting one of the provided options.`).optional(),display:e.enum([`confirmation`,`select`,`text`]).describe(`Rendering hint — the channel uses this to pick a UX treatment.`).optional(),options:e.array(E).describe(`Selectable answer options to present to the user.`).optional(),prompt:e.string().describe(`The prompt to present to the user.`),requestId:e.string().describe(`Stable identifier for this request.`)}).strict(),O=e.object({optionId:e.string().optional(),requestId:e.string(),text:e.string().optional()}).strict();function k(e){return O.safeParse(e).success}export{_,y as a,w as c,p as d,d as f,v as g,u as h,C as i,g as l,h as m,k as n,b as o,f as p,S as r,x as s,D as t,m as u,c as v,r as y};
|