UNPKG

eve

Version:

Filesystem-first framework for durable backend AI agents that run anywhere.

2 lines 2.83 kB
import{parseWithNitroRolldownAst}from"#internal/bundler/nitro-rolldown.js";const AGENT_FACTORY=`defineAgent`;async function applyModelNameToSource(e,n){let r=await parseAgentSource(e);if(`kind`in r)return r;if((r.errors?.length??0)>0){let t=r.errors?.[0];return{kind:`bail`,reason:`agent.ts does not parse: ${t?.message??`unknown parse error`}`,line:parseErrorLine(e,t)}}let i=findDefineAgentObject(r.program??r,AGENT_FACTORY);if(i===void 0)return{kind:`bail`,reason:`no \`export default ${AGENT_FACTORY}({ ... })\` call found`,line:1};let a=findStringLiteralProperty(i,`model`);if(a===void 0)return{kind:`bail`,reason:"`model` is absent or is not a string literal (e.g. an env reference, a template, or an inlined SDK model)",line:lineAt(e,i.start??0)};let o=a.value;if(o===n)return{kind:`applied`,from:o,to:n,nextSource:e};let s=a.raw?.[0]===`'`?`'`:`"`,c=`${s}${escapeForQuote(n,s)}${s}`;return{kind:`applied`,from:o,to:n,nextSource:e.slice(0,a.start)+c+e.slice(a.end)}}async function parseAgentSource(t){try{return await parseWithNitroRolldownAst(`agent.ts`,t)}catch(e){let n=e;return{kind:`bail`,reason:`agent.ts does not parse: ${n.message??`unknown parse error`}`,line:parseErrorLine(t,n)}}}function unwrapExpression(e){let t=e;for(;t.type===`ParenthesizedExpression`||t.type===`TSAsExpression`||t.type===`TSSatisfiesExpression`;){if(t.expression===void 0||t.expression===null)return t;t=t.expression}return t}function findDefineAgentObject(e,t){for(let n of e.body??[]){if(n.type!==`ExportDefaultDeclaration`)continue;let e=n.declaration;if(e==null||e.type!==`CallExpression`&&e.type!==`ParenthesizedExpression`&&e.type!==`TSAsExpression`&&e.type!==`TSSatisfiesExpression`)continue;let r=unwrapExpression(e);if(r.type!==`CallExpression`||!isFactoryCallee(r.callee,t))continue;let i=r.arguments?.[0];if(i===void 0||i.type===`SpreadElement`)continue;let a=unwrapExpression(i);if(a.type===`ObjectExpression`)return a}}function isFactoryCallee(e,t){return e?.type===`Identifier`&&e.name===t}function findStringLiteralProperty(e,t){for(let n of e.properties){if(n.type!==`Property`||n.computed||!keyMatches(n.key,t))continue;let e=n.value;if(!isAstNode(e))continue;let r=unwrapExpression(e);return r.type===`Literal`&&typeof r.value==`string`&&r.start!==void 0&&r.end!==void 0?r:void 0}}function keyMatches(e,t){return e===void 0?!1:e.type===`Identifier`?e.name===t:e.type===`Literal`?typeof e.value==`string`&&e.value===t:!1}function isAstNode(e){return typeof e==`object`&&!!e&&typeof e.type==`string`}function parseErrorLine(e,t){return typeof t?.loc?.line==`number`?t.loc.line:lineAt(e,t?.labels?.[0]?.start??t?.start??0)}function escapeForQuote(e,t){return e.replaceAll(`\\`,`\\\\`).replaceAll(t,`\\${t}`)}function lineAt(e,t){let n=1;for(let r=0;r<t&&r<e.length;r+=1)e[r]===` `&&(n+=1);return n}export{applyModelNameToSource};