helios-ai-sdk 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,43 @@
1
+ # Helios SDK
2
+
3
+ The official SDK for embedding the **Helios AI-native runtime** into your JavaScript or TypeScript applications.
4
+
5
+ ## Features
6
+ - **Seamless AI Integration**: Native support for Gemini, WebLLM, OpenAI, and Anthropic.
7
+ - **Embedded Agentic Workflows**: Build complex AI-driven workflows directly in code.
8
+ - **First-Class TypeScript Support**: Full type definitions are included for excellent developer experience.
9
+
10
+ ## Installation
11
+
12
+ ```bash
13
+ npm install helios-ai-sdk @google/genai @mlc-ai/web-llm
14
+ ```
15
+
16
+ *(Note: peer dependencies like `@google/genai` are required depending on the provider you use)*
17
+
18
+ ## Usage
19
+
20
+ ```typescript
21
+ import { Helios, HeliosAgent } from 'helios-ai-sdk';
22
+
23
+ const helios = new Helios({
24
+ provider: 'gemini', // Ensure GEMINI_API_KEY is in your environment
25
+ model: 'gemini-3-flash-preview',
26
+ });
27
+
28
+ async function run() {
29
+ const investigator = new HeliosAgent(helios, 'investigator', {
30
+ prompt: 'You are an investigator.',
31
+ model: 'gemini-3-flash-preview',
32
+ });
33
+
34
+ await investigator.register();
35
+ const response = await investigator.delegate("What is your mission?");
36
+ console.log(response);
37
+ }
38
+
39
+ run();
40
+ ```
41
+
42
+ ## Documentation
43
+ For more advanced usage see the internal configuration interface or visit our GitHub repository.
package/dist/sdk.cjs ADDED
@@ -0,0 +1,173 @@
1
+ "use strict";var Ge=Object.defineProperty;var Xe=Object.getOwnPropertyDescriptor;var Ze=Object.getOwnPropertyNames;var Qe=Object.prototype.hasOwnProperty;var et=(u,e)=>{for(var t in e)Ge(u,t,{get:e[t],enumerable:!0})},tt=(u,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Ze(e))!Qe.call(u,n)&&n!==t&&Ge(u,n,{get:()=>e[n],enumerable:!(s=Xe(e,n))||s.enumerable});return u};var st=u=>tt(Ge({},"__esModule",{value:!0}),u);var at={};et(at,{Helios:()=>pe,HeliosAgent:()=>We,HeliosBuilder:()=>Ye,HeliosCancelledError:()=>ue,HeliosConfigError:()=>De,HeliosExecutionError:()=>He,HeliosMemory:()=>Be,HeliosSDKError:()=>oe,HeliosSession:()=>qe,createHelios:()=>it,helios:()=>ot});module.exports=st(at);var re=class extends Error{constructor(e,t,s,n,r=null,a=null){super(e),this.name="HeliosError",this.line=t,this.col=s,this.phase=n,this.suggestion=r,this.source=a}format(e=null){let t=this.source||e,s=this.line!==void 0&&this.col!==void 0?` at ${this.line}:${this.col}`:"",n=`[${this.phase} Error]${s}: ${this.message}`;if(t&&this.line!==void 0){let a=t.split(`
2
+ `)[this.line-1];if(a!==void 0&&(n+=`
3
+
4
+ ${this.line} | ${a}`,this.col!==void 0)){let m=" ".repeat(String(this.line).length+3+this.col-1);n+=`
5
+ ${m}^`}}return this.suggestion&&(n+=`
6
+
7
+ Suggestion: ${this.suggestion}`),n}},q=class extends re{constructor(e,t,s,n=null,r=null){super(e,t,s,"Parsing",n,r),this.name="HeliosSyntaxError"}},ae=class extends re{constructor(e,t,s,n=null,r=null){super(e,t,s,"Lexing",n,r),this.name="HeliosLexicalError"}},_=class extends re{constructor(e,t,s,n=null,r=null){super(e,t,s,"TypeChecking",n,r),this.name="HeliosTypeError"}},k=class extends re{constructor(e,t,s,n=null,r=null){super(e,t,s,"Evaluation",n,r),this.name="HeliosRuntimeError"}};var g={KEYWORD:"KEYWORD",IDENTIFIER:"IDENTIFIER",NUMBER:"NUMBER",STRING:"STRING",OPERATOR:"OPERATOR",DELIMITER:"DELIMITER",ANNOTATION:"ANNOTATION",EOF:"EOF"},nt=new Set(["export","fn","let","var","type","opaque","wrapping","enum","struct","trait","impl","match","if","else","while","for","in","from","loop","return","uses","prompt","as","fallback","retries","timeout","model","using","schema","pipeline","stage","test","ai","import","comptime","new","unsafe","Result","Option","true","false","null","Unit","Int","Float","Bool","String","Char","Byte","Never","UUID","Date","async","await","with","tools"]),Je=["->","=>","==","!=","<=",">=","|>","=","+","-","*","/","&&","||","!","?",".",":",",",";","|","&","<",">"],rt=["(",")","{","}","[","]"],Y=class{constructor(e,t,s,n){this.type=e,this.value=t,this.line=s,this.col=n}},ee=class{constructor(e){this.source=e,this.pos=0,this.line=1,this.col=1}peek(){return this.source[this.pos]}advance(){let e=this.source[this.pos++];return e===`
8
+ `?(this.line++,this.col=1):this.col++,e}skipWhitespace(){for(;this.pos<this.source.length;){let e=this.peek();if(/\s/.test(e))this.advance();else if(e==="/"&&this.source[this.pos+1]==="/")for(;this.pos<this.source.length&&this.peek()!==`
9
+ `;)this.advance();else if(e==="/"&&this.source[this.pos+1]==="*")for(this.advance(),this.advance();this.pos<this.source.length;){if(this.peek()==="*"&&this.source[this.pos+1]==="/"){this.advance(),this.advance();break}this.advance()}else break}}nextToken(){if(this.skipWhitespace(),this.pos>=this.source.length)return new Y(g.EOF,null,this.line,this.col);let e=this.peek(),t=this.line,s=this.col;if(e==="@"){this.advance();let n="";for(;this.pos<this.source.length&&/[a-zA-Z0-9_]/.test(this.peek());)n+=this.advance();return new Y(g.ANNOTATION,n,t,s)}if(/[a-zA-Z_]/.test(e)){let n="";for(;this.pos<this.source.length&&/[a-zA-Z0-9_]/.test(this.peek());)n+=this.advance();return nt.has(n)?new Y(g.KEYWORD,n,t,s):new Y(g.IDENTIFIER,n,t,s)}if(/[0-9]/.test(e)){let n="";for(;this.pos<this.source.length&&/[0-9.]/.test(this.peek());)n+=this.advance();return new Y(g.NUMBER,n,t,s)}if(e==='"'||e==="'"){let n=this.advance(),r="";for(;this.pos<this.source.length&&this.peek()!==n;)if(this.peek()==="\\"){this.advance();let a=this.advance();switch(a){case"n":r+=`
10
+ `;break;case"r":r+="\r";break;case"t":r+=" ";break;case"\\":r+="\\";break;case'"':r+='"';break;case"'":r+="'";break;default:r+=a;break}}else r+=this.advance();if(this.pos>=this.source.length)throw new ae("Unterminated string literal",t,s,`Add a closing ${n} to end the string.`,this.source);return this.advance(),new Y(g.STRING,r,t,s)}for(let n of Je.filter(r=>r.length>1))if(this.source.startsWith(n,this.pos))return this.pos+=n.length,this.col+=n.length,new Y(g.OPERATOR,n,t,s);if(Je.includes(e))return new Y(g.OPERATOR,this.advance(),t,s);if(rt.includes(e))return new Y(g.DELIMITER,this.advance(),t,s);throw new ae(`Unexpected character: ${e}`,this.line,this.col,null,this.source)}tokenize(){let e=[],t;do t=this.nextToken(),e.push(t);while(t.type!==g.EOF);return e}};var j=class{constructor(e,t,s){this.type=e,this.line=t,this.col=s}},he=class extends j{constructor(e,t,s){super("Program",t,s),this.body=e}},fe=class extends j{constructor(e,t,s=!1,n=[],r,a){super("ImportDeclaration",r,a),this.source=e,this.specifiers=t,this.isExternal=s,this.uses=n}},me=class extends j{constructor(e,t,s,n,r,a=[],m=!1,w=!1,v=[],T,M){super("FunctionDeclaration",T,M),this.name=e,this.params=t,this.returnType=s,this.effects=n,this.body=r,this.annotations=a,this.isExported=m,this.isAsync=w,this.typeParameters=v}},de=class extends j{constructor(e,t,s=null,n,r){super("Parameter",n,r),this.name=e,this.typeAnnotation=t,this.defaultValue=s}},ge=class extends j{constructor(e,t,s,n,r,a){super("VariableDeclaration",r,a),this.kind=e,this.pattern=t,this.typeAnnotation=s,this.init=n}},ye=class extends j{constructor(e,t,s,n){super("AssignmentExpression",s,n),this.left=e,this.value=t}},we=class extends j{constructor(e,t,s){super("ArrayLiteral",t,s),this.elements=e}},xe=class extends j{constructor(e,t,s){super("ObjectLiteral",t,s),this.properties=e}},le=class extends j{constructor(e,t,s,n){super("MemberExpression",s,n),this.object=e,this.property=t}},be=class extends j{constructor(e,t,s=[],n,r){super("TypeDeclaration",n,r),this.name=e,this.value=t,this.typeParams=s}};var ke=class extends j{constructor(e,t,s,n,r,a,m,w,v,T,M,O,$){super("PromptExpression",O,$),this.template=e,this.asType=t,this.schema=s,this.fallback=n,this.retries=r,this.timeout=a,this.guardrails=m,this.model=w,this.tools=v,this.history=T,this.contexts=M}},ve=class extends j{constructor(e,t,s,n){super("WithContextStatement",s,n),this.context=e,this.body=t}},Ee=class extends j{constructor(e,t,s,n){super("MatchExpression",s,n),this.discriminant=e,this.arms=t}},Te=class extends j{constructor(e,t,s,n,r){super("MatchArm",n,r),this.pattern=e,this.guard=t,this.body=s}},Se=class extends j{constructor(e,t,s,n,r){super("IfExpression",n,r),this.condition=e,this.consequent=t,this.alternate=s}},Ie=class extends j{constructor(e,t,s,n){super("WhileStatement",s,n),this.condition=e,this.body=t}},Ae=class extends j{constructor(e,t,s,n,r){super("ForStatement",n,r),this.iterator=e,this.iterable=t,this.body=s}},Me=class extends j{constructor(e,t,s){super("ComptimeBlock",t,s),this.body=e}},Oe=class extends j{constructor(e,t,s,n,r){super("BinaryExpression",n,r),this.left=e,this.operator=t,this.right=s}},Re=class extends j{constructor(e,t,s=[],n,r){super("CallExpression",n,r),this.callee=e,this.arguments=t,this.typeArguments=s}},Pe=class extends j{constructor(e,t,s,n){super("NewExpression",s,n),this.callee=e,this.arguments=t}},$e=class extends j{constructor(e,t,s){super("ReturnStatement",t,s),this.argument=e}},Ne=class extends j{constructor(e,t,s,n){super("UnaryExpression",s,n),this.operator=e,this.argument=t}},Ce=class extends j{constructor(e,t,s){super("AwaitExpression",t,s),this.argument=e}},z=class extends j{constructor(e,t,s,n){super("Literal",s,n),this.value=e,this.kind=t}},ie=class extends j{constructor(e,t,s){super("Identifier",t,s),this.name=e}};var te=class{constructor(e,t=null){this.tokens=e,this.source=t,this.pos=0}peek(){return this.tokens[this.pos]||{type:g.EOF}}advance(){return this.tokens[this.pos++]||{type:g.EOF}}expect(e,t=null){let s=this.peek();if(s.type!==e||t!==null&&s.value!==t){let n=t?`'${t}'`:e,r=s.type===g.EOF?"end of file":`'${s.value}'`,a=`Try adding ${n} before ${r} or check for typos.`;throw new q(`Expected ${n}, but found ${s.type} ${r}`,s.line,s.col,a,this.source)}return this.advance()}parse(){let e=this.peek(),t=[];for(;this.peek().type!==g.EOF;)t.push(this.parseTopLevel());return new he(t,e.line,e.col)}parseTopLevel(){let e=this.peek(),t=[];for(;this.peek().type===g.ANNOTATION;)t.push(this.parseAnnotation());let s=!1;this.peek().type===g.KEYWORD&&this.peek().value==="export"&&(this.advance(),s=!0);let n=!1;this.peek().type===g.KEYWORD&&this.peek().value==="async"&&(this.advance(),n=!0);let r=this.peek();if(r.type===g.KEYWORD){if(r.value==="fn")return this.parseFunctionDeclaration(t,s,n,e.line,e.col);if(r.value==="import")return this.parseImportDeclaration()}try{let a=this.parseStatement();return a&&s&&(a.isExported=!0),a}catch(a){throw a instanceof q?a:new q(`Unexpected token in top-level: ${r.type} '${r.value}'`,r.line,r.col,null,this.source)}}parseImportDeclaration(){let e=this.expect(g.KEYWORD,"import"),t=[];if(this.peek().value==="{"){for(this.advance();this.peek().value!=="}"&&this.peek().type!==g.EOF;){let m=this.expect(g.IDENTIFIER).value,w=null;this.peek().value==="as"&&(this.advance(),w=this.expect(g.IDENTIFIER).value),t.push({name:m,alias:w}),this.peek().value===","&&this.advance()}this.expect(g.DELIMITER,"}"),this.expect(g.KEYWORD,"from")}let s=this.peek(),n;if(s.type===g.STRING)n=this.advance().value;else if(s.type===g.IDENTIFIER||s.type===g.KEYWORD)n=this.advance().value;else throw new q(`Expected String, Identifier, or Keyword for import source, found ${s.type} '${s.value}'`,s.line,s.col,null,this.source);let r=n.startsWith("npm:")||n.startsWith("http"),a=[];if(this.peek().value==="uses"){for(this.advance(),this.expect(g.DELIMITER,"[");this.peek().value!=="]"&&this.peek().type!==g.EOF;)a.push(this.advance().value),this.peek().value===","&&this.advance();this.expect(g.DELIMITER,"]"),r=!0}return new fe(n,t,r,a,e.line,e.col)}parseAnnotation(){let e=this.expect(g.ANNOTATION).value,t=null;if(this.peek().value==="("){this.advance(),t="";let s=1;for(;s>0&&this.peek().type!==g.EOF;){let n=this.advance();if(n.value==="("&&s++,n.value===")"&&s--,s>0)t+=n.value;else if(n.value===")")break}}return{name:e,args:t}}parseFunctionDeclaration(e,t,s,n,r){this.expect(g.KEYWORD,"fn");let a=this.expect(g.IDENTIFIER),m=a.value,w=[];this.peek().value==="<"&&(w=this.parseTypeParameters()),this.expect(g.DELIMITER,"(");let v=[];if(this.peek().value!==")")do if(v.push(this.parseParameter()),this.peek().value===",")this.advance();else break;while(this.peek().value!==")"&&this.peek().type!==g.EOF);this.expect(g.DELIMITER,")");let T=null;this.peek().value==="->"&&(this.advance(),T=this.parseType());let M=[];if(s&&!M.includes("async")&&M.push("async"),this.peek().value==="uses"){for(this.advance(),this.expect(g.DELIMITER,"[");this.peek().value!=="]"&&this.peek().type!==g.EOF;){let $=this.advance().value;M.includes($)||M.push($),this.peek().value===","&&this.advance()}this.expect(g.DELIMITER,"]")}let O=this.parseBlock();return new me(m,v,T,M,O,e,t,s,w,n||a.line,r||a.col)}parseTypeParameters(){this.expect(g.OPERATOR,"<");let e=[];do if(e.push(this.expect(g.IDENTIFIER).value),this.peek().value===",")this.advance();else break;while(this.peek().value!==">"&&this.peek().type!==g.EOF);return this.expect(g.OPERATOR,">"),e}parseParameter(){let e=this.expect(g.IDENTIFIER),t=e.value;this.expect(g.OPERATOR,":");let s=this.parseType();return new de(t,s,null,e.line,e.col)}parseTypeDeclaration(){let e=this.expect(g.KEYWORD,"type"),t=this.expect(g.IDENTIFIER).value,s=[];this.peek().value==="<"&&(s=this.parseTypeParameters()),this.expect(g.OPERATOR,"=");let n=this.parseType();return new be(t,n,s,e.line,e.col)}parseType(){let e=this.peek();if(e.value==="["){this.advance();let t=this.parseType();return this.expect(g.DELIMITER,"]"),{type:"ArrayType",elementType:t}}if(e.value==="{"){this.advance();let t={};for(;this.peek().value!=="}"&&this.peek().type!==g.EOF;){let s=this.peek(),n;if(s.type===g.IDENTIFIER||s.type===g.STRING||s.type===g.KEYWORD)n=this.advance().value;else throw new q(`Expected Identifier, String, or Keyword for object key, found ${s.type} '${s.value}'`,s.line,s.col,null,this.source);if(this.expect(g.OPERATOR,":"),t[n]=this.parseType(),this.peek().value===",")this.advance();else break}return this.expect(g.DELIMITER,"}"),{type:"ObjectType",fields:t}}if(e.type===g.KEYWORD||e.type===g.IDENTIFIER){let t=this.advance().value;if(this.peek().value==="<"){this.advance();let s=[];do if(s.push(this.parseType()),this.peek().value===",")this.advance();else break;while(this.peek().value!==">"&&this.peek().type!==g.EOF);return this.expect(g.OPERATOR,">"),{type:"TypeReference",name:t,typeArguments:s}}return t}throw new q(`Expected type (Keyword or Identifier), found ${e.type} '${e.value}'`,e.line,e.col,null,this.source)}parseBlock(){this.expect(g.DELIMITER,"{");let e=[];for(;this.peek().value!=="}"&&this.peek().type!==g.EOF;)e.push(this.parseStatement()),this.peek().value===";"&&this.advance();return this.expect(g.DELIMITER,"}"),e}parseStatement(){let e=this.peek();if(e.value===";")return this.advance(),null;let t;if(e.type===g.KEYWORD)if(e.value==="let"||e.value==="var")t=this.parseVariableDeclaration();else if(e.value==="return"){let s=this.advance(),n=null;this.peek().value!==";"&&this.peek().value!=="}"&&(n=this.parseExpression()),t=new $e(n,s.line,s.col)}else e.value==="if"?t=this.parseIfExpression():e.value==="while"?t=this.parseWhileStatement():e.value==="for"?t=this.parseForStatement():e.value==="type"?t=this.parseTypeDeclaration():e.value==="with"?t=this.parseWithContextStatement():e.value==="comptime"?t=this.parseComptimeBlock():t=this.parseExpression();else t=this.parseExpression();return this.peek().value===";"&&this.advance(),t}parseComptimeBlock(){let e=this.expect(g.KEYWORD,"comptime"),t=this.parseBlock();return new Me(t,e.line,e.col)}parseWithContextStatement(){let e=this.expect(g.KEYWORD,"with");this.expect(g.IDENTIFIER,"context"),this.expect(g.DELIMITER,"(");let t=[];if(this.peek().value!==")")do if(t.push(this.parseExpression()),this.peek().value===",")this.advance();else break;while(this.peek().value!==")"&&this.peek().type!==g.EOF);this.expect(g.DELIMITER,")");let s=this.parseBlock();return new ve(t,s,e.line,e.col)}parseWhileStatement(){let e=this.expect(g.KEYWORD,"while"),t=this.parseExpression(),s=this.parseBlock();return new Ie(t,s,e.line,e.col)}parseIfExpression(){let e=this.expect(g.KEYWORD,"if"),t=this.parseExpression(),s=this.parseBlock(),n=null;return this.peek().type===g.KEYWORD&&this.peek().value==="else"&&(this.advance(),this.peek().type===g.KEYWORD&&this.peek().value==="if"?n=this.parseIfExpression():n=this.parseBlock()),new Se(t,s,n,e.line,e.col)}parseMatchExpression(){let e=this.expect(g.KEYWORD,"match"),t=this.parseExpression();this.expect(g.DELIMITER,"{");let s=[];for(;this.peek().value!=="}"&&this.peek().type!==g.EOF;)s.push(this.parseMatchArm()),this.peek().value===","&&this.advance();return this.expect(g.DELIMITER,"}"),new Ee(t,s,e.line,e.col)}parseMatchArm(){let e=this.parseExpression(),t=null;this.peek().type===g.KEYWORD&&this.peek().value==="if"&&(this.advance(),t=this.parseExpression()),this.expect(g.OPERATOR,"=>");let s;return this.peek().value==="{"?s=this.parseBlock():s=this.parseExpression(),new Te(e,t,s,e.line,e.col)}parseNewExpression(){let e=this.expect(g.KEYWORD,"new"),t=this.peek(),s;if(t.type===g.IDENTIFIER||t.type===g.KEYWORD)s=new ie(this.advance().value,t.line,t.col);else throw new q("Expected identifier or type after 'new'",t.line,t.col,null,this.source);let n=[];if(this.peek().value==="("){if(this.advance(),this.peek().value!==")")do if(n.push(this.parseExpression()),this.peek().value===",")this.advance();else break;while(this.peek().value!==")"&&this.peek().type!==g.EOF);this.expect(g.DELIMITER,")")}return new Pe(s,n,e.line,e.col)}parseForStatement(){let e=this.expect(g.KEYWORD,"for"),t=this.expect(g.IDENTIFIER).value;this.expect(g.KEYWORD,"in");let s=this.parseExpression(),n=this.parseBlock();return new Ae(t,s,n,e.line,e.col)}parseVariableDeclaration(){let e=this.advance(),t=e.value,n=this.expect(g.IDENTIFIER).value,r=null;this.peek().value===":"&&(this.advance(),r=this.parseType()),this.expect(g.OPERATOR,"=");let a=this.parseExpression();return new ge(t,n,r,a,e.line,e.col)}parseExpression(){let e=this.parseBinaryExpression();if(this.peek()?.value==="="){let t=this.advance(),s=this.parseExpression();return new ye(e,s,t.line,t.col)}return e}parseBinaryExpression(){let e=this.parseUnaryExpression();for(;this.peek()?.type===g.OPERATOR&&["+","-","*","/","==","!=","<",">","<=",">=","|>","&&","||"].includes(this.peek().value);){let t=this.advance(),s=t.value,n=this.parseUnaryExpression();e=new Oe(e,s,n,t.line,t.col)}return e}parseUnaryExpression(){let e=this.peek();if(e.type===g.OPERATOR&&(e.value==="-"||e.value==="!")){let t=this.advance(),s=this.parseUnaryExpression();return new Ne(t.value,s,t.line,t.col)}if(e.type===g.KEYWORD&&e.value==="await"){let t=this.advance(),s=this.parseUnaryExpression();return new Ce(s,t.line,t.col)}return this.parsePostfixExpression()}parsePostfixExpression(){let e=this.parsePrimaryExpression();for(;;)if(this.peek()?.value==="["){let t=this.advance(),s=this.parseExpression();this.expect(g.DELIMITER,"]"),e=new le(e,s,t.line,t.col)}else if(this.peek()?.value==="."){let t=this.advance(),s=this.expect(g.IDENTIFIER),n=new z(s.value,"String",s.line,s.col);e=new le(e,n,t.line,t.col)}else if(this.peek()?.value==="("||e.type==="Identifier"&&this.lookaheadIsGeneric()){let t=[];if(this.peek().value==="<"){this.advance();do if(t.push(this.parseType()),this.peek().value===",")this.advance();else break;while(this.peek().value!==">"&&this.peek().type!==g.EOF);this.expect(g.OPERATOR,">")}if(this.peek().value==="("){let s=this.advance(),n=[];if(this.peek().value!==")")do if(n.push(this.parseExpression()),this.peek().value===",")this.advance();else break;while(this.peek().value!==")"&&this.peek().type!==g.EOF);this.expect(g.DELIMITER,")"),e=new Re(e,n,t,s.line,s.col)}else if(t.length>0)throw new q("Expected '(' after type arguments in call",this.peek().line,this.peek().col,null,this.source)}else break;return e}lookaheadIsGeneric(){if(this.peek()?.value!=="<")return!1;let e=this.pos+1,t=1;for(;e<this.tokens.length&&t>0;){let s=this.tokens[e];if(!s)break;if(s.value==="<")t++;else if(s.value===">")t--;else if(s.value==="("||s.value==="{"||s.value===";"||s.type===g.EOF)break;e++}return t===0?this.tokens[e]?.value==="(":!1}parsePrimaryExpression(){let e=this.peek();if(e.type===g.NUMBER)return new z(this.advance().value,"Number",e.line,e.col);if(e.type===g.STRING)return new z(this.advance().value,"String",e.line,e.col);if(e.type===g.IDENTIFIER)return new ie(this.advance().value,e.line,e.col);if(e.type===g.KEYWORD){if(e.value==="true")return this.advance(),new z(!0,"Boolean",e.line,e.col);if(e.value==="false")return this.advance(),new z(!1,"Boolean",e.line,e.col);if(e.value==="null")return this.advance(),new z(null,"Null",e.line,e.col);if(e.value==="prompt")return this.parsePromptExpression();if(e.value==="if")return this.parseIfExpression();if(e.value==="match")return this.parseMatchExpression();if(e.value==="new")return this.parseNewExpression();if(["Int","Float","String","Bool","Date","UUID","Unit","Result","Option"].includes(e.value))return new ie(this.advance().value,e.line,e.col)}if(e.value==="[")return this.parseArrayLiteral();if(e.value==="{")return this.parseObjectLiteral();if(e.value==="("){this.advance();let t=this.parseExpression();return this.expect(g.DELIMITER,")"),t}throw new q(`Unexpected token in expression: ${e.type} '${e.value}'`,e.line,e.col,null,this.source)}parseArrayLiteral(){let e=this.expect(g.DELIMITER,"["),t=[];if(this.peek().value!=="]")do if(t.push(this.parseExpression()),this.peek().value===",")this.advance();else break;while(this.peek().value!=="]"&&this.peek().type!==g.EOF);return this.expect(g.DELIMITER,"]"),new we(t,e.line,e.col)}parseObjectLiteral(){let e=this.expect(g.DELIMITER,"{"),t=[];if(this.peek().value!=="}")do{let s=this.peek(),n;if(s.type===g.IDENTIFIER||s.type===g.STRING||s.type===g.KEYWORD)n=this.advance().value;else throw new q(`Expected Identifier, String, or Keyword for object key, found ${s.type} '${s.value}'`,s.line,s.col,null,this.source);this.expect(g.OPERATOR,":");let r=this.parseExpression();if(t.push({key:n,value:r}),this.peek().value===",")this.advance();else break}while(this.peek().value!=="}"&&this.peek().type!==g.EOF);return this.expect(g.DELIMITER,"}"),new xe(t,e.line,e.col)}parsePromptExpression(){let e=this.expect(g.KEYWORD,"prompt");this.expect(g.DELIMITER,"(");let t=this.parseExpression();this.expect(g.DELIMITER,")");let s=null,n=null,r=null,a=null,m=null,w=null,v=null,T=null,M=[];for(;;){let O=this.peek();if(O.value==="as")this.advance(),s=this.parseType();else if(O.value==="with"){this.advance();let $=this.peek();if($.value==="schema")this.advance(),n=this.parseType();else if($.value==="context")this.advance(),this.expect(g.DELIMITER,"("),M.push(this.parseExpression()),this.expect(g.DELIMITER,")");else throw new q(`Expected 'schema' or 'context' after 'with', found ${$.type} '${$.value}'`,$.line,$.col,null,this.source)}else if(O.value==="fallback")this.advance(),r=this.parseExpression();else if(O.value==="retries")this.advance(),a=this.parseExpression();else if(O.value==="timeout")this.advance(),m=this.parseExpression();else if(O.value==="using")if(this.advance(),this.peek().value==="tools"){for(this.advance(),this.expect(g.DELIMITER,"["),v=[];this.peek().value!=="]"&&this.peek().type!==g.EOF;)v.push(this.expect(g.IDENTIFIER).value),this.peek().value===","&&this.advance();this.expect(g.DELIMITER,"]")}else w=this.parseExpression();else if(O.value==="history")this.advance(),T=this.parseExpression();else if(O.value==="tools"){for(this.advance(),this.expect(g.DELIMITER,"["),v=[];this.peek().value!=="]"&&this.peek().type!==g.EOF;)v.push(this.expect(g.IDENTIFIER).value),this.peek().value===","&&this.advance();this.expect(g.DELIMITER,"]")}else break}return new ke(t,s,n,r,a,m,null,w,v,T,M,e.line,e.col)}};var b=class u{constructor(e,t=[],s=[],n=[]){this.name=e,this.params=t,this.effects=s,this.typeParams=n}equals(e){if(!e)return!1;if(this.name==="Float"&&e.name==="Int")return!0;if(this.name!==e.name||this.params.length!==e.params.length)return!1;for(let t=0;t<this.params.length;t++)if(!this.params[t].equals(e.params[t]))return!1;return!0}substitute(e){if(e.has(this.name)&&this.params.length===0)return e.get(this.name);if(this.name==="Object"&&this.fields){let s={};for(let[n,r]of Object.entries(this.fields))s[n]=r.substitute(e);return new J(s)}let t=this.params.map(s=>s.substitute(e));return new u(this.name,t,this.effects,this.typeParams)}toString(){if(this.name==="Function"){let e=this.params.slice(0,-1).map(n=>n.toString()).join(", "),t=this.params[this.params.length-1].toString(),s=this.effects.length>0?` uses [${this.effects.join(", ")}]`:"";return`(${e}) -> ${t}${s}`}return this.params.length>0?`${this.name}<${this.params.map(e=>e.toString()).join(", ")}>`:this.name}},J=class extends b{constructor(e){super("Object"),this.fields=e}equals(e){if(!e||e.name!=="Object")return!1;let t=Object.keys(this.fields),s=Object.keys(e.fields);if(t.length!==s.length)return!1;for(let n of t)if(!e.fields[n]||!this.fields[n].equals(e.fields[n]))return!1;return!0}toString(){return`{ ${Object.entries(this.fields).map(([t,s])=>`${t}: ${s.toString()}`).join(", ")} }`}},c={Int:new b("Int"),Float:new b("Float"),Bool:new b("Bool"),String:new b("String"),Unit:new b("Unit"),Unknown:new b("Unknown")},U=class{constructor(e=null){this.types=new Map,this.parent=e}define(e,t){this.types.set(e,t)}get(e){return this.types.has(e)?this.types.get(e):this.parent?this.parent.get(e):null}},Fe=class{constructor(e={}){if(this.globalEnv=new U,this.modules=new Map,this.setupBuiltins(),this.currentFunction=null,e.tools)for(let[t,s]of Object.entries(e.tools))if(typeof s=="function")this.globalEnv.define(t,new b("Function",[c.Unknown],[],[]));else if(s&&s.signature){let n=(s.signature.params||[]).map(m=>c[m]||new b(m)),r=c[s.signature.returnType]||new b(s.signature.returnType||"Unknown"),a=s.signature.effects||[];this.globalEnv.define(t,new b("Function",[...n,r],a,[]))}else this.globalEnv.define(t,new b("Function",[c.Unknown],[],[]));if(e.modules)for(let[t,s]of Object.entries(e.modules)){let n=new U;if(s&&typeof s=="object")for(let r of Object.keys(s))n.define(r,c.Unknown);this.modules.set(t,n)}}setupBuiltins(){this.globalEnv.define("print",new b("Function",[c.Unknown,c.Unit],["io"])),this.globalEnv.define("length",new b("Function",[c.Unknown,c.Int])),this.globalEnv.define("typeof",new b("Function",[c.Unknown,c.String])),this.globalEnv.define("toString",new b("Function",[c.Unknown,c.String])),this.globalEnv.define("parseInt",new b("Function",[c.String,c.Int])),this.globalEnv.define("parseFloat",new b("Function",[c.String,c.Float])),this.globalEnv.define("Date",c.Unknown),this.globalEnv.define("UUID",new b("Function",[c.String])),this.globalEnv.define("Unit",c.Unit),this.modules.set("math",new U);let e=this.modules.get("math");e.define("PI",c.Float),e.define("abs",new b("Function",[c.Float,c.Float])),this.modules.set("fs",new U);let t=this.modules.get("fs");t.define("read",new b("Function",[c.String,c.String],["io"])),t.define("write",new b("Function",[c.String,c.String,c.Bool],["io"])),t.define("exists",new b("Function",[c.String,c.Bool],["io"])),t.define("list",new b("Function",[new b("Array",[c.String])],["io"])),t.define("delete",new b("Function",[c.String,c.Bool],["io"])),this.modules.set("json",new U);let s=this.modules.get("json");s.define("parse",new b("Function",[c.String,c.Unknown])),s.define("stringify",new b("Function",[c.Unknown,c.String])),this.modules.set("csv",new U);let n=this.modules.get("csv");n.define("parse",new b("Function",[c.String,new b("Array",[c.Unknown])])),n.define("stringify",new b("Function",[new b("Array",[c.Unknown]),c.String])),this.modules.set("xml",new U);let r=this.modules.get("xml");r.define("parse",new b("Function",[c.String,c.Unknown])),r.define("stringify",new b("Function",[c.Unknown,c.String,c.String])),this.modules.set("web",new U);let a=this.modules.get("web");a.define("fetch",new b("Function",[c.String,c.Unknown],["net"])),a.define("search",new b("Function",[c.String,c.String],["net"])),a.define("maps",new b("Function",[c.String,c.String],["net"])),this.modules.set("http",new U);let m=this.modules.get("http");m.define("get",new b("Function",[c.String,c.Unknown],["net"])),m.define("post",new b("Function",[c.String,c.Unknown,c.Unknown],["net"])),m.define("request",new b("Function",[c.Unknown,c.Unknown],["net"])),this.modules.set("storage",new U);let w=this.modules.get("storage");w.define("get",new b("Function",[c.String,c.Unknown],["io"])),w.define("set",new b("Function",[c.String,c.Unknown,c.Bool],["io"])),this.modules.set("context",new U);let v=this.modules.get("context");v.define("add",new b("Function",[c.Unknown,c.Bool])),v.define("clear",new b("Function",[],c.Bool)),v.define("requestInput",new b("Function",[c.String,c.String],["io"])),this.modules.set("swarm",new U);let T=this.modules.get("swarm");T.define("createAgent",new b("Function",[c.String,c.String,c.Bool])),T.define("setAgentModel",new b("Function",[c.String,c.String,c.Bool])),T.define("delegate",new b("Function",[c.String,c.String,c.String],["async"])),T.define("broadcast",new b("Function",[c.String,c.Bool])),T.define("readBlackboard",new b("Function",[new b("Array",[new J({sender:c.String,message:c.String,timestamp:c.Int})])])),T.define("addTool",new b("Function",[c.String,c.String,c.Bool])),T.define("removeTool",new b("Function",[c.String,c.String,c.Bool])),T.define("listTools",new b("Function",[c.String,new b("Array",[c.String])])),this.modules.set("mcp",new U);let M=this.modules.get("mcp"),O=new b("Function",[c.String,c.String,c.Bool],["net"]),$=new b("Function",[c.String,new b("Array",[new J({name:c.String,description:c.String,inputSchema:c.Unknown})])],["net"]),D=new b("Function",[c.String,c.String,c.Unknown,c.Unknown],["net"]);M.define("connect",O),M.define("listTools",$),M.define("callTool",D),this.globalEnv.define("mcp",new J({connect:O,listTools:$,callTool:D})),this.modules.set("memory",new U);let N=this.modules.get("memory");N.define("store",new b("Function",[c.String,c.String,c.Bool],["io"])),N.define("search",new b("Function",[c.String,c.Int,new b("Array",[new J({text:c.String,score:c.Float})])],["io"])),this.modules.set("ai",new U);let L=this.modules.get("ai");L.define("generateCode",new b("Function",[c.String,c.String],["ai"])),L.define("extract",new b("Function",[c.String,new b("T"),new b("T")],["ai"],["T"])),L.define("sentiment",new b("Function",[c.String,c.String],["ai"])),this.modules.set("ui",new U);let H=this.modules.get("ui");H.define("button",new b("Function",[c.String,c.String,c.String],["io"])),H.define("input",new b("Function",[c.String,c.String,c.String],["io"])),H.define("card",new b("Function",[c.String,c.String,c.Bool],["io"])),H.define("image",new b("Function",[c.String,c.String,c.Bool],["io"])),H.define("chart",new b("Function",[c.String,new b("Array",[new b("T")]),c.Unknown,c.Bool],["io"],["T"])),H.define("table",new b("Function",[new b("Array",[new b("T")]),new b("Array",[c.String]),c.Bool],["io"],["T"])),H.define("progress",new b("Function",[c.Float,c.Float,c.String,c.Bool],["io"]))}check(e,t=this.globalEnv){switch(e.type){case"Program":for(let s of e.body)this.check(s,t);return c.Unit;case"ImportDeclaration":{let n=(typeof e.source=="string"?e.source:e.source?.value||String(e.source)).replace(/['"]/g,"");if(e.isExternal||n.startsWith("npm:")||e.uses&&(e.uses.includes("js")||e.uses.length>0)){for(let a of e.specifiers)t.define(a.alias||a.name,c.Unknown);return c.Unit}let r=this.modules.get(n);if(!r)throw new _(`Module not found: ${n}`,e.line,e.col,"Check if the module name is correct or if it's available in the current environment.");for(let a of e.specifiers){let m=r.get(a.name);if(!m)throw new _(`Symbol ${a.name} not found in module ${e.source}`,e.line,e.col,`Ensure ${a.name} is exported from ${e.source}.`);t.define(a.alias||a.name,m)}return c.Unit}case"VariableDeclaration":{let s=this.check(e.init,t),n=e.typeAnnotation?this.resolveType(e.typeAnnotation,t):null;if(n&&!n.equals(s)&&n.name!=="Unknown"&&s.name!=="Unknown")throw new _(`Type mismatch: cannot assign ${s} to ${n}`,e.line,e.col,`The initial value type (${s}) must match the declared type (${n}).`);let r=n||s;return t.define(e.pattern,r),r}case"AssignmentExpression":{let s;if(e.left.type==="Identifier"){if(s=t.get(e.left.name),!s)throw new _(`Undefined identifier: ${e.left.name}`,e.line,e.col,`Make sure '${e.left.name}' is defined before use.`)}else if(e.left.type==="MemberExpression"){let r=this.check(e.left.object,t);if(r.name==="Array"){let a=this.check(e.left.property,t);if(a.name!=="Int")throw new _(`Array index must be Int, found ${a}`,e.line,e.col,"Ensure the index expression evaluates to an integer.");s=r.params[0]||c.Unknown}else if(r.name==="Object"){if(e.left.property.type!=="Literal"||e.left.property.kind!=="String")throw new _("Object property access requires string literal",e.line,e.col,"Use dot notation or a string literal for property access.");let a=e.left.property.value;if(s=r.fields[a],!s)throw new _(`Property '${a}' does not exist on object`,e.line,e.col,"Check for typos or ensure the property is defined on the object.")}else throw new _(`Cannot assign to member of type ${r}`,e.line,e.col)}else throw new _("Invalid assignment target",e.line,e.col);let n=this.check(e.value,t);if(!s.equals(n)&&s.name!=="Unknown"&&n.name!=="Unknown")throw new _(`Type mismatch: cannot assign ${n} to ${s}`,e.line,e.col,"Ensure the assigned value matches the variable's type.");return s}case"FunctionDeclaration":{let s=new U(t);e.typeParameters&&e.typeParameters.forEach(w=>s.define(w,new b(w)));let n=e.params.map(w=>this.resolveType(w.typeAnnotation,s)),r=e.returnType?this.resolveType(e.returnType,s):c.Unit,a=new b("Function",[...n,r],e.effects,e.typeParameters||[]);t.define(e.name,a),e.params.forEach((w,v)=>s.define(w.name,n[v]));let m=this.currentFunction;return this.currentFunction=e,this.checkBlock(e.body,s),this.currentFunction=m,a}case"AwaitExpression":{if(this.currentFunction&&!this.currentFunction.effects.includes("async"))throw new _("'await' can only be used in 'async' functions or functions with 'async' effect",e.line,e.col,"Mark the function as 'async' or add 'async' to its 'uses' clause.");return this.check(e.argument,t)}case"Literal":switch(e.kind){case"Number":return e.value.includes(".")?c.Float:c.Int;case"String":return c.String;case"Bool":return c.Bool;default:return c.Unknown}case"Identifier":{let s=t.get(e.name);if(!s){let n=this.modules.get(e.name);if(n){let r={};for(let[a,m]of n.types.entries())r[a]=m;s=new J(r)}}if(!s)throw new _(`Undefined identifier: ${e.name}`,e.line,e.col,`Check for typos or ensure '${e.name}' is defined in the current scope.`);return s}case"BinaryExpression":{let s=this.check(e.left,t);if(e.operator==="|>")if(e.right.type==="CallExpression"){let r=this.check(e.right.callee,t),a=[s];for(let m of e.right.arguments)a.push(this.check(m,t));return this.checkFunctionCall(e.right,r,a,t)}else{let r=this.check(e.right,t);return this.checkFunctionCall(e,r,[s],t)}let n=this.check(e.right,t);if(e.operator==="+"&&(s.name==="String"||n.name==="String"))return c.String;if(!s.equals(n)&&!n.equals(s)&&s.name!=="Unknown"&&n.name!=="Unknown")throw new _(`Binary operator ${e.operator} requires compatible types, found ${s} and ${n}`,e.line,e.col,"Convert one of the operands to match the other's type.");if(["+","-","*","/"].includes(e.operator)){if(s.name!=="Int"&&s.name!=="Float"&&s.name!=="Unknown")throw new _(`Arithmetic operator ${e.operator} requires numeric types, found ${s}`,e.line,e.col,"Ensure both operands are Int or Float.");return s.name==="Float"||n.name==="Float"?c.Float:s}return["==","!=","<",">","<=",">="].includes(e.operator)?c.Bool:s}case"UnaryExpression":{let s=this.check(e.argument,t);if(e.operator==="-"){if(s.name!=="Int"&&s.name!=="Float")throw new _(`Unary operator - requires numeric type, found ${s}`,e.line,e.col);return s}if(e.operator==="!"){if(s.name!=="Bool")throw new _(`Unary operator ! requires Bool type, found ${s}`,e.line,e.col);return c.Bool}return s}case"CallExpression":{let s=this.check(e.callee,t),n=e.arguments.map(r=>this.check(r,t));return this.checkFunctionCall(e,s,n,t)}case"NewExpression":{let s=this.check(e.callee,t),n=e.arguments.map(r=>this.check(r,t));return s.name==="Unknown"?c.Unknown:s}case"ArrayLiteral":{if(e.elements.length===0)return new b("Array",[c.Unknown]);let s=e.elements.map(r=>this.check(r,t)),n=s[0];for(let r=1;r<s.length;r++){let a=s[r];if(a.name!=="Unknown"){if(n.name==="Unknown"){n=a;continue}if(!n.equals(a))if(a.equals(n))n=a;else throw new _(`Array elements must have consistent types, found ${n} and ${a}`,e.line,e.col)}}return new b("Array",[n])}case"ObjectLiteral":{let s={};for(let n of e.properties)s[n.key]=this.check(n.value,t);return new J(s)}case"MemberExpression":{let s=this.check(e.object,t);if(s.name==="Array"){if(e.property.type==="Literal"&&e.property.kind==="String"){let r=e.property.value;if(r==="length")return c.Int;if(r==="push"){let a=s.params[0]||c.Unknown;return new b("Function",[a,c.Unit])}if(r==="pop"){let a=s.params[0]||c.Unknown;return new b("Function",[a])}if(r==="shift"){let a=s.params[0]||c.Unknown;return new b("Function",[a])}if(r==="unshift"){let a=s.params[0]||c.Unknown;return new b("Function",[a,c.Unit])}if(r==="join")return new b("Function",[c.String,c.String])}let n=this.check(e.property,t);if(n.name!=="Int")throw new _(`Array index must be Int, found ${n}`,e.line,e.col);return s.params[0]||c.Unknown}else if(s.name==="Object"){if(e.property.type!=="Literal"||e.property.kind!=="String")throw new _("Object property access requires string literal",e.line,e.col);let n=e.property.value,r=s.fields[n];if(!r)throw new _(`Property '${n}' does not exist on object`,e.line,e.col);return r}else if(s.name==="String"){if(e.property.type==="Literal"&&e.property.kind==="String"){let n=e.property.value;if(n==="length")return c.Int;if(n==="split")return new b("Function",[c.String,new b("Array",[c.String])]);if(n==="trim")return new b("Function",[c.String]);if(n==="toLowerCase")return new b("Function",[c.String]);if(n==="toUpperCase")return new b("Function",[c.String]);if(n==="includes")return new b("Function",[c.String,c.Bool])}throw new _(`Property '${e.property.value}' does not exist on type String`,e.line,e.col)}else if(s.name==="Int"||s.name==="Float"){if(e.property.type==="Literal"&&e.property.kind==="String"&&e.property.value==="toString")return new b("Function",[c.String]);throw new _(`Property '${e.property.value}' does not exist on type ${s.name}`,e.line,e.col)}else{if(s.name==="Unknown")return c.Unknown;throw new _(`Cannot access member of type ${s}`,e.line,e.col)}}case"PromptExpression":{if(e.schema){let s=this.resolveType(e.schema,t);if(e.asType){let n=this.resolveType(e.asType,t);if(!s.equals(n))throw new _(`Prompt schema type ${s} does not match 'as' type ${n}`,e.line,e.col)}return s}return e.asType?this.resolveType(e.asType,t):c.String}case"WhileStatement":{let s=this.check(e.condition,t);if(!s.equals(c.Bool))throw new _(`While condition must be Bool, found ${s}`,e.line,e.col);return this.checkBlock(e.body,new U(t)),c.Unit}case"IfExpression":{let s=this.check(e.condition,t);if(!s.equals(c.Bool))throw new _(`If condition must be Bool, found ${s}`,e.line,e.col);let n=this.checkBlock(e.consequent,new U(t));if(e.alternate){let r=Array.isArray(e.alternate)?this.checkBlock(e.alternate,new U(t)):this.check(e.alternate,t);if(n.equals(r))return n;if(r.equals(n))return r}return c.Unit}case"ForStatement":{let s=this.check(e.iterable,t),n=c.Unknown;s.equals(c.Int)?n=c.Int:s.name==="Array"&&(n=s.params[0]||c.Unknown);let r=new U(t);return r.define(e.iterator,n),this.checkBlock(e.body,r),c.Unit}case"WithContextStatement":{let s=new U(t);return e.context.forEach(n=>this.check(n,t)),this.checkBlock(e.body,s),c.Unit}case"TypeDeclaration":{let s=new U(t);e.typeParams&&e.typeParams.forEach(r=>s.define(r,new b(r)));let n=this.resolveType(e.value,s);return n.typeParams=e.typeParams,t.define(e.name,n),c.Unit}case"ReturnStatement":return this.check(e.argument,t);default:return c.Unknown}}checkFunctionCall(e,t,s,n){if(!t){let m=e.callee&&e.callee.type==="Identifier"?e.callee.name:"Expression";throw new _(`${m} is undefined`,e.line,e.col)}if(t.name==="Unknown")return c.Unknown;if(t.name!=="Function"){let m=e.callee&&e.callee.type==="Identifier"?e.callee.name:"Expression";throw new _(`${m} is not a function`,e.line,e.col,"Ensure you're calling a function and not another type.")}if(t.typeParams&&t.typeParams.length>0){let m=e.typeArguments?e.typeArguments.map(w=>this.resolveType(w,n)):[];if(m.length>0){if(m.length!==t.typeParams.length)throw new _(`Generic function expects ${t.typeParams.length} type arguments, got ${m.length}`,e.line,e.col);let w=new Map;t.typeParams.forEach((v,T)=>w.set(v,m[T])),t=t.substitute(w)}else{let w=new Map;t.typeParams.forEach(T=>w.set(T,c.Unknown));let v=t.params.slice(0,-1);for(let T=0;T<Math.min(s.length,v.length);T++)this.inferTypes(v[T],s[T],w);t=t.substitute(w)}}let r=t.params.slice(0,-1),a=t.params[t.params.length-1];if(e.callee&&e.callee.type==="Identifier"&&e.callee.name==="print")return a;if(s.length!==r.length){let m=e.callee&&e.callee.type==="Identifier"?e.callee.name:"Expression";throw new _(`Function ${m} expects ${r.length} arguments, got ${s.length}`,e.line,e.col,"Check the function signature for the correct number of arguments.")}for(let m=0;m<s.length;m++)if(!r[m].equals(s[m])&&r[m].name!=="Unknown"){let w=e.callee&&e.callee.type==="Identifier"?e.callee.name:"Expression";throw new _(`Argument ${m+1} to ${w} expected ${r[m]}, got ${s[m]}`,e.line,e.col,"Provide an argument of the correct type.")}return a}checkBlock(e,t){let s=c.Unit;for(let n of e)s=this.check(n,t);return s}resolveType(e,t=this.globalEnv){if(typeof e=="string")return c[e]||t.get(e)||new b(e);if(e&&e.type==="TypeReference"){let s=this.resolveType(e.name,t),n=e.typeArguments.map(r=>this.resolveType(r,t));if(s.typeParams&&s.typeParams.length>0){let r=new Map;return s.typeParams.forEach((a,m)=>{r.set(a,n[m]||c.Unknown)}),s.substitute(r)}return new b(s.name,n,s.effects)}if(e&&e.type==="ArrayType"){let s=this.resolveType(e.elementType,t);return new b("Array",[s])}if(e&&e.type==="ObjectType"){let s={};for(let[n,r]of Object.entries(e.fields))s[n]=this.resolveType(r,t);return new J(s)}return c.Unknown}inferTypes(e,t,s){if(!(!e||!t)){if(s.has(e.name)&&e.params.length===0){s.get(e.name).name==="Unknown"&&s.set(e.name,t);return}if(e.name===t.name&&e.params.length===t.params.length)for(let n=0;n<e.params.length;n++)this.inferTypes(e.params[n],t.params[n],s);if(e.name==="Object"&&t.name==="Object"&&e.fields&&t.fields)for(let n in e.fields)t.fields[n]&&this.inferTypes(e.fields[n],t.fields[n],s)}}};var _e=class{constructor(e,t){this.url=e,this.ws=null,this.onPrint=t,this.pendingRequests=new Map,this.requestId=0,this.capabilities={},this.serverInfo={},this.isConnected=!1}async connect(){return new Promise((e,t)=>{try{this.ws=new WebSocket(this.url)}catch(s){return t(s)}this.ws.onopen=async()=>{this.isConnected=!0,this.onPrint(`[MCP] WebSocket connected to ${this.url}`);try{let s=await this.request("initialize",{protocolVersion:"2024-11-05",capabilities:{roots:{listChanged:!0}},clientInfo:{name:"helios-client",version:"1.0.0"}});this.capabilities=s.capabilities,this.serverInfo=s.serverInfo,this.notify("notifications/initialized"),this.onPrint(`[MCP] Handshake complete. Server: ${this.serverInfo.name} v${this.serverInfo.version}`),e(!0)}catch(s){t(s)}},this.ws.onmessage=s=>{try{let n=JSON.parse(s.data);if(n.id!==void 0){let r=this.pendingRequests.get(n.id);r&&(n.error?r.reject(new Error(n.error.message)):r.resolve(n.result),this.pendingRequests.delete(n.id))}}catch(n){console.error("[MCP] Error parsing message:",n)}},this.ws.onerror=s=>{this.isConnected||t(new Error("WebSocket connection failed")),console.error("[MCP] WebSocket error:",s)},this.ws.onclose=()=>{this.isConnected=!1,this.onPrint(`[MCP] Disconnected from ${this.url}`)}})}send(e,t){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("Not connected");let s={jsonrpc:"2.0",method:e,params:t};this.ws.send(JSON.stringify(s))}notify(e,t){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return;let s={jsonrpc:"2.0",method:e,params:t};this.ws.send(JSON.stringify(s))}request(e,t){return new Promise((s,n)=>{if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return n(new Error("Not connected"));let r=this.requestId++,a={jsonrpc:"2.0",id:r,method:e,params:t};this.pendingRequests.set(r,{resolve:s,reject:n}),this.ws.send(JSON.stringify(a)),setTimeout(()=>{this.pendingRequests.has(r)&&(this.pendingRequests.get(r).reject(new Error("Request timed out")),this.pendingRequests.delete(r))},1e4)})}};var Ue=require("@google/genai");var Le=class{constructor(e){this.evaluator=e,this.store=[]}cosineSimilarity(e,t){let s=0,n=0,r=0;for(let a=0;a<e.length;a++)s+=e[a]*t[a],n+=e[a]*e[a],r+=t[a]*t[a];return n=Math.sqrt(n),r=Math.sqrt(r),n===0||r===0?0:s/(n*r)}async getEmbedding(e){let t=this.evaluator.ai;return t&&t.embedContent?await t.embedContent(e):(console.warn("[Memory] No embedding provider found. Using mock embedding."),this.mockEmbedding(e))}mockEmbedding(e){let t=new Array(10).fill(0);for(let n=0;n<e.length;n++)t[n%10]+=e.charCodeAt(n);let s=Math.sqrt(t.reduce((n,r)=>n+r*r,0));return t.map(n=>n/s)}async add(e,t,s={}){let n=await this.getEmbedding(t);return this.store=this.store.filter(r=>r.id!==e),this.store.push({id:e,text:t,embedding:n,metadata:s,timestamp:Date.now()}),!0}async search(e,t=3){let s=await this.getEmbedding(e),n=this.store.map(r=>({...r,score:this.cosineSimilarity(s,r.embedding)}));return n.sort((r,a)=>a.score-r.score),n.slice(0,t)}clear(){this.store=[]}dump(){return this.store}load(e){this.store=e}};function Ke(u){u.memory||(u.memory=new Le(u)),u.modules.set("swarm",new u.globalEnv.constructor);let e=u.modules.get("swarm");u.agents=u.agents||new Map,e.define("createAgent",async i=>{let o=i[0],l=i[1];return u.agents.set(o,{name:o,prompt:l,tools:[],model:null}),!0}),e.define("setAgentModel",async i=>{let o=i[0],l=i[1],f=u.agents.get(o);return f&&(f.model=l),!0}),e.define("addTool",async i=>{let o=i[0],l=i[1],f=u.agents.get(o);return f&&!f.tools.includes(l)&&f.tools.push(l),!0}),e.define("delegate",async i=>{let o=i[0],l=i[1],f=u.agents.get(o),y=f?`You are ${o}. ${f.prompt}
11
+
12
+ Task:
13
+ ${l}`:`Task:
14
+ ${l}`,x=f&&f.model?f.model:u.options.model||"gemini-3-flash-preview",E=f?f.tools.map(A=>u.options.tools[A]).filter(Boolean):[],S=await u.callAI(x,[{role:"user",parts:[{text:y}]}],{tools:E});return u.onPrint({type:"agent_delegate",from:"Helios",to:o,task:l,result:S.text}),S.text});let t=u.modules.get("math");t.define("sin",async i=>Math.sin(i[0])),t.define("cos",async i=>Math.cos(i[0])),t.define("tan",async i=>Math.tan(i[0])),t.define("pow",async i=>Math.pow(i[0],i[1])),t.define("sqrt",async i=>Math.sqrt(i[0])),t.define("log",async i=>Math.log(i[0])),t.define("exp",async i=>Math.exp(i[0])),u.modules.set("date",new u.globalEnv.constructor);let s=u.modules.get("date");s.define("now",async()=>new Date().toISOString()),s.define("format",async i=>{let o=new Date(i[0]),l=i[1]||"iso";return l==="iso"?o.toISOString():l==="local"?o.toLocaleString():l==="date"?o.toLocaleDateString():l==="time"?o.toLocaleTimeString():o.toISOString()}),s.define("diff",async i=>{let o=new Date(i[0]),l=new Date(i[1]),f=i[2]||"ms",y=o.getTime()-l.getTime();return f==="ms"?y:f==="s"?y/1e3:f==="m"?y/(1e3*60):f==="h"?y/(1e3*60*60):f==="d"?y/(1e3*60*60*24):y}),s.define("add",async i=>{let o=new Date(i[0]),l=i[1],f=i[2]||"ms";return f==="ms"&&o.setMilliseconds(o.getMilliseconds()+l),f==="s"&&o.setSeconds(o.getSeconds()+l),f==="m"&&o.setMinutes(o.getMinutes()+l),f==="h"&&o.setHours(o.getHours()+l),f==="d"&&o.setDate(o.getDate()+l),o.toISOString()});let n=u.modules.get("fs"),r="helios_vfs_";n.define("list",async i=>{let o=i[0]||"/",l=[];for(let f=0;f<localStorage.length;f++){let y=localStorage.key(f);if(y.startsWith(r)){let x=y.slice(r.length);x.startsWith(o==="/"?"":o)&&l.push(x)}}return l}),n.define("read",async i=>{let o=i[0],l=localStorage.getItem(r+o);if(l===null)throw new k(`File not found: ${o}`);return l}),n.define("write",async i=>{let o=i[0],l=String(i[1]);return localStorage.setItem(r+o,l),!0}),n.define("exists",async i=>localStorage.getItem(r+i[0])!==null),n.define("delete",async i=>(localStorage.removeItem(r+i[0]),!0));let a=u.modules.get("json");a.define("parse",async i=>JSON.parse(i[0])),a.define("stringify",async i=>JSON.stringify(i[0],null,i[1]||0)),u.modules.set("sys",new u.globalEnv.constructor);let m=u.modules.get("sys");m.define("sleep",async i=>{let o=i[0]||1e3;return new Promise(l=>setTimeout(l,o))}),m.define("uuid",async()=>crypto.randomUUID()),m.define("env",async i=>{let o=i[0];return process.env[o]}),u.modules.set("str",new u.globalEnv.constructor);let w=u.modules.get("str");w.define("split",async i=>i[0].split(i[1])),w.define("join",async i=>i[0].join(i[1])),w.define("replace",async i=>i[0].replace(i[1],i[2])),w.define("trim",async i=>i[0].trim()),w.define("includes",async i=>i[0].includes(i[1])),w.define("lower",async i=>i[0].toLowerCase()),w.define("upper",async i=>i[0].toUpperCase());let v=u.modules.get("list");v.define("push",async i=>{let o=i[0],l=i[1];if(!Array.isArray(o))throw new k("First argument to list.push must be a list");return o.push(l),o}),v.define("pop",async i=>{let o=i[0];if(!Array.isArray(o))throw new k("Argument to list.pop must be a list");return o.pop()}),v.define("shift",async i=>{let o=i[0];if(!Array.isArray(o))throw new k("Argument to list.shift must be a list");return o.shift()}),v.define("unshift",async i=>{let o=i[0],l=i[1];if(!Array.isArray(o))throw new k("First argument to list.unshift must be a list");return o.unshift(l),o}),v.define("slice",async i=>{let o=i[0],l=i[1]||0,f=i[2];if(!Array.isArray(o))throw new k("First argument to list.slice must be a list");return o.slice(l,f)}),v.define("splice",async i=>{let o=i[0],l=i[1],f=i[2]||0,y=i.slice(3);if(!Array.isArray(o))throw new k("First argument to list.splice must be a list");return o.splice(l,f,...y)}),v.define("reverse",async i=>{let o=i[0];if(!Array.isArray(o))throw new k("Argument to list.reverse must be a list");return[...o].reverse()}),v.define("sort",async i=>{let o=i[0];if(!Array.isArray(o))throw new k("Argument to list.sort must be a list");return[...o].sort()}),v.define("contains",async i=>{let o=i[0],l=i[1];if(!Array.isArray(o))throw new k("First argument to list.contains must be a list");return o.includes(l)}),v.define("join",async i=>{let o=i[0],l=i[1]||",";if(!Array.isArray(o))throw new k("First argument to list.join must be a list");return o.join(l)}),v.define("range",async i=>{let o=i[0],l=i[1],f=i[2]||1,y=[];for(let x=o;x<l;x+=f)y.push(x);return y});let T=u.modules.get("obj");T.define("keys",async i=>{let o=i[0];if(typeof o!="object"||o===null)throw new k("Argument to obj.keys must be an object");return Object.keys(o)}),T.define("values",async i=>{let o=i[0];if(typeof o!="object"||o===null)throw new k("Argument to obj.values must be an object");return Object.values(o)}),T.define("entries",async i=>{let o=i[0];if(typeof o!="object"||o===null)throw new k("Argument to obj.entries must be an object");return Object.entries(o)}),T.define("has",async i=>{let o=i[0],l=i[1];if(typeof o!="object"||o===null)throw new k("First argument to obj.has must be an object");return Object.prototype.hasOwnProperty.call(o,l)}),T.define("merge",async i=>{let o=i[0],l=i[1];if(typeof o!="object"||o===null)throw new k("First argument to obj.merge must be an object");if(typeof l!="object"||l===null)throw new k("Second argument to obj.merge must be an object");return{...o,...l}}),u.modules.set("http",new u.globalEnv.constructor);let M=u.modules.get("http");M.define("get",async i=>{let o=i[0],l=i[1]||{},f=await fetch(o,{method:"GET",headers:l}),y=f.headers.get("content-type");return y&&y.includes("application/json")?await f.json():await f.text()}),M.define("post",async i=>{let o=i[0],l=i[1],y={method:"POST",headers:{"Content-Type":"application/json",...i[2]||{}},body:typeof l=="object"?JSON.stringify(l):l},x=await fetch(o,y),E=x.headers.get("content-type");return E&&E.includes("application/json")?await x.json():await x.text()}),M.define("request",async i=>{let o=i[0]||{},l=o.url;if(!l)throw new k("HTTP request requires a URL");let f={method:o.method||"GET",headers:o.headers||{},body:o.body?typeof o.body=="object"?JSON.stringify(o.body):o.body:void 0},y=await fetch(l,f),x=y.headers.get("content-type"),E={status:y.status,statusText:y.statusText,headers:Object.fromEntries(y.headers.entries()),ok:y.ok};return x&&x.includes("application/json")?E.data=await y.json():E.data=await y.text(),E});let O=u.modules.get("ui");O.define("button",async i=>{let o=i[0],l=i[1]||o;return u.onPrint({type:"ui_button",label:o,value:l}),await u.onInputRequest(o,{type:"ui_button",value:l})}),O.define("input",async i=>{let o=i[0],l=i[1]||"";return await u.onInputRequest(o,{type:"ui_input",placeholder:l})}),O.define("card",async i=>{let o=i[0],l=i[1];return u.onPrint({type:"ui_card",title:o,content:l}),!0}),O.define("image",async i=>{let o=i[0],l=i[1]||"Image";return u.onPrint({type:"ui_image",src:o,alt:l}),!0}),O.define("chart",async i=>{let o=i[0],l=i[1],f=i[2]||{};if(!Array.isArray(l))throw new k("Second argument to ui.chart must be a list of objects");return u.onPrint({type:"ui_chart",chartType:o,data:l,config:f}),!0}),O.define("table",async i=>{let o=i[0],l=i[1]||[];if(!Array.isArray(o))throw new k("First argument to ui.table must be a list of objects");return u.onPrint({type:"ui_table",data:o,columns:l}),!0}),O.define("progress",async i=>{let o=i[0],l=i[1]||100,f=i[2]||"";return u.onPrint({type:"ui_progress",value:o,max:l,label:f}),!0});let $=u.modules.get("memory");$.define("store",async i=>{let o=i[0],l=i[1],f=i[2]||{};return await u.memory.add(o,l,f),!0}),$.define("search",async i=>{let o=i[0],l=i[1]||3;return await u.memory.search(o,l)}),$.define("clear",async()=>(u.memory.clear(),!0));let D=u.modules.get("text");D.define("chunk",async i=>{let o=i[0],l=i[1]||1e3,f=i[2]||0;if(typeof o!="string")throw new k("First argument to text.chunk must be a string");let y=[],x=0;for(;x<o.length;)y.push(o.slice(x,x+l)),x+=l-f;return y}),D.define("tokenize",async i=>{let o=i[0];return typeof o!="string"?[]:o.split(/\s+/).filter(l=>l.length>0)}),D.define("lines",async i=>{let o=i[0];return typeof o!="string"?[]:o.split(/\r?\n/)}),u.modules.get("web").define("scrape",async i=>{let o=i[0];try{let f=await(await fetch(o)).text(),y=new DOMParser().parseFromString(f,"text/html");return y.querySelectorAll("script, style").forEach(E=>E.remove()),y.body.textContent||""}catch(l){throw new k(`Failed to scrape ${o}: ${l.message}`)}});let L=u.modules.get("agent");L.define("think",async i=>{let o=i[0];return u.onPrint({type:"ui_card",title:"Thinking",content:o}),!0}),L.define("plan",async i=>{let o=i[0];if(!Array.isArray(o))throw new k("agent.plan expects a list of steps");return u.onPrint({type:"ui_progress",value:0,max:o.length,label:"Executing Plan"}),!0});let H=u.modules.get("csv");H.define("parse",async i=>{let o=i[0];if(typeof o!="string")return[];let l=o.trim().split(/\r?\n/);if(l.length===0)return[];let f=l[0].split(",").map(x=>x.trim()),y=[];for(let x=1;x<l.length;x++){let E=l[x].split(",").map(A=>A.trim()),S={};f.forEach((A,I)=>{S[A]=E[I]||null}),y.push(S)}return y}),H.define("stringify",async i=>{let o=i[0];if(!Array.isArray(o)||o.length===0)return"";let l=Object.keys(o[0]),f=[l.join(",")];for(let y of o){let x=l.map(E=>{let S=y[E];return S==null?"":String(S)});f.push(x.join(","))}return f.join(`
15
+ `)}),u.modules.get("xml").define("parse",async i=>{let o=i[0];if(typeof o!="string")return{};try{let x=function(E){if(E.nodeType===3)return E.nodeValue.trim();let S={};if(E.attributes&&E.attributes.length>0){S["@attributes"]={};for(let A=0;A<E.attributes.length;A++){let I=E.attributes.item(A);S["@attributes"][I.nodeName]=I.nodeValue}}if(E.hasChildNodes()){let A=!0;for(let I=0;I<E.childNodes.length;I++)if(E.childNodes.item(I).nodeName!=="#text"){A=!1;break}if(A&&E.childNodes.length===1)return E.textContent.trim();for(let I=0;I<E.childNodes.length;I++){let C=E.childNodes.item(I),F=C.nodeName;if(F==="#text")continue;let B=x(C);typeof S[F]>"u"?S[F]=B:(Array.isArray(S[F])||(S[F]=[S[F]]),S[F].push(B))}}return S};var l=x;let y=new DOMParser().parseFromString(o,"text/xml");return x(y.documentElement)}catch(f){throw new k(`Failed to parse XML: ${f.message}`)}});let W=u.modules.get("crypto");W.define("hash",async i=>{let o=i[0],l=i[1]||"SHA-256";if(typeof o!="string")throw new k("First argument to crypto.hash must be a string");let f=new TextEncoder().encode(o),y=await crypto.subtle.digest(l,f);return Array.from(new Uint8Array(y)).map(S=>S.toString(16).padStart(2,"0")).join("")}),W.define("uuid",async()=>crypto.randomUUID());let se=u.modules.get("base64");se.define("encode",async i=>{let o=i[0];if(typeof o!="string")throw new k("Argument to base64.encode must be a string");return btoa(unescape(encodeURIComponent(o)))}),se.define("decode",async i=>{let o=i[0];if(typeof o!="string")throw new k("Argument to base64.decode must be a string");try{return decodeURIComponent(escape(atob(o)))}catch(l){throw new k(`Failed to decode base64: ${l.message}`)}});let p=u.modules.get("regex");p.define("test",async i=>{let o=i[0],l=i[1],f=i[2]||"";if(typeof o!="string"||typeof l!="string")throw new k("regex.test requires pattern and text as strings");return new RegExp(o,f).test(l)}),p.define("match",async i=>{let o=i[0],l=i[1],f=i[2]||"";if(typeof o!="string"||typeof l!="string")throw new k("regex.match requires pattern and text as strings");let y=new RegExp(o,f),x=l.match(y);return x?Array.from(x):[]}),p.define("replace",async i=>{let o=i[0],l=i[1],f=i[2],y=i[3]||"g";if(typeof o!="string"||typeof l!="string"||typeof f!="string")throw new k("regex.replace requires pattern, text, and replacement as strings");let x=new RegExp(o,y);return l.replace(x,f)});let h=u.modules.get("url");h.define("parse",async i=>{let o=i[0];if(typeof o!="string")throw new k("Argument to url.parse must be a string");try{let l=new URL(o),f={};for(let[y,x]of l.searchParams.entries())f[y]=x;return{href:l.href,origin:l.origin,protocol:l.protocol,host:l.host,hostname:l.hostname,port:l.port,pathname:l.pathname,search:l.search,hash:l.hash,params:f}}catch{throw new k(`Invalid URL: ${o}`)}}),h.define("build",async i=>{let o=i[0],l=i[1]||{};if(typeof o!="string")throw new k("First argument to url.build must be a string");if(typeof l!="object")throw new k("Second argument to url.build must be an object");try{let f=new URL(o);for(let[y,x]of Object.entries(l))f.searchParams.append(y,String(x));return f.toString()}catch{throw new k(`Invalid base URL: ${o}`)}});let d=u.modules.get("workflow");d.define("pipeline",async i=>{let o=i[0],l=i[1];if(!Array.isArray(o))throw new k("workflow.pipeline expects a list of agent names");let f=l;u.onPrint({type:"ui_card",title:"Workflow: Pipeline",content:`Starting pipeline with ${o.length} agents.`});for(let y=0;y<o.length;y++){let x=o[y];u.onPrint({type:"ui_progress",value:y,max:o.length,label:`Agent ${y+1}/${o.length}: ${x}`});let E=`You are ${x}. Process the following input and provide the output for the next stage.
16
+
17
+ Input:
18
+ ${f}`,S=u.options.model||"gemini-3-flash-preview";f=(await u.callAI(S,[{role:"user",parts:[{text:E}]}],{})).text}return u.onPrint({type:"ui_progress",value:o.length,max:o.length,label:"Pipeline Complete"}),f}),d.define("optimize",async i=>{let o=i[0];if(typeof o!="object")throw new k("workflow.optimize expects a configuration object");let l=o.actor||"Programmer",f=o.critic||"Reviewer",y=o.task,x=o.criteria||"Ensure high quality.",E=o.max_iterations||3;if(!y)throw new k("workflow.optimize requires a task");u.onPrint({type:"ui_card",title:"Workflow: Actor-Critic",content:`Task: ${y}
19
+ Max Iterations: ${E}`});let S="",A="",I=0,C=!1;for(;I<E&&!C;){I++,u.onPrint({type:"ui_progress",value:I-1,max:E,label:`Iteration ${I}: ${l} drafting...`});let F=`You are ${l}. Your task is: ${y}.
20
+
21
+ Criteria: ${x}
22
+
23
+ ${A?`Previous Feedback to address:
24
+ ${A}
25
+
26
+ Previous Draft:
27
+ ${S}
28
+
29
+ Provide an updated draft.`:"Provide your initial draft."}`,B=u.options.model||"gemini-3-flash-preview";S=(await u.callAI(B,[{role:"user",parts:[{text:F}]}],{})).text,u.onPrint({type:"ui_progress",value:I-.5,max:E,label:`Iteration ${I}: ${f} reviewing...`});let Q=`You are ${f}. Review the following draft against these criteria: ${x}.
30
+
31
+ Draft:
32
+ ${S}
33
+
34
+ If it meets all criteria perfectly, reply with exactly "APPROVED". Otherwise, provide specific feedback on what needs to be fixed.`;A=(await u.callAI(B,[{role:"user",parts:[{text:Q}]}],{})).text,A.trim().toUpperCase()==="APPROVED"&&(C=!0,u.onPrint({type:"ui_card",title:"Workflow: Actor-Critic",content:`Approved after ${I} iterations!`}))}return C||u.onPrint({type:"ui_card",title:"Workflow: Actor-Critic",content:"Max iterations reached. Returning best effort."}),S}),d.define("map_reduce",async i=>{let o=i[0];if(typeof o!="object")throw new k("workflow.map_reduce expects a configuration object");let l=o.worker||"Worker",f=o.synthesizer||"Synthesizer",y=o.data,x=o.task||"Process this data";if(!Array.isArray(y))throw new k("workflow.map_reduce requires a data array");u.onPrint({type:"ui_card",title:"Workflow: Map-Reduce",content:`Processing ${y.length} items in parallel.`});let E=y.map(async(F,B)=>{let X=`You are ${l}. ${x}
35
+
36
+ Data item:
37
+ ${typeof F=="object"?JSON.stringify(F):F}`,Q=u.options.model||"gemini-3-flash-preview",ne=await u.callAI(Q,[{role:"user",parts:[{text:X}]}],{});return`Result ${B+1}:
38
+ ${ne.text}`}),S=await Promise.all(E);u.onPrint({type:"ui_progress",value:50,max:100,label:"Map phase complete. Synthesizing..."});let A=`You are ${f}. Synthesize the following processed results into a final cohesive summary or conclusion.
39
+
40
+ Results:
41
+ ${S.join(`
42
+
43
+ ---
44
+
45
+ `)}`,I=u.options.model||"gemini-3-flash-preview",C=await u.callAI(I,[{role:"user",parts:[{text:A}]}],{});return u.onPrint({type:"ui_progress",value:100,max:100,label:"Map-Reduce Complete"}),C.text}),d.define("route",async i=>{let o=i[0],l=i[1];if(typeof o!="string")throw new k("workflow.route requires a string input");if(typeof l!="object")throw new k("workflow.route requires a routes object");let f=Object.keys(l),y=f.map(B=>`- ${B}`).join(`
46
+ `);u.onPrint({type:"ui_card",title:"Workflow: Router",content:`Routing input to one of: ${f.join(", ")}`});let x=`You are a Router agent. Analyze the following input and determine which of the available routes is the best fit. Reply with ONLY the exact name of the route, nothing else.
47
+
48
+ Available Routes:
49
+ ${y}
50
+
51
+ Input:
52
+ ${o}`,E=u.options.model||"gemini-3-flash-preview",A=(await u.callAI(E,[{role:"user",parts:[{text:x}]}],{})).text.trim();l[A]||(A=f[0]);let I=l[A];u.onPrint({type:"ui_card",title:"Workflow: Router",content:`Routed to: ${A} (${I})`});let C=`You are ${I}. Process the following input:
53
+
54
+ ${o}`,F=await u.callAI(E,[{role:"user",parts:[{text:C}]}],{});return{route:A,agent:I,response:F.text}}),d.define("debate",async i=>{let o=i[0];if(typeof o!="object")throw new k("workflow.debate expects a configuration object");let l=o.topic,f=o.participants||["Proponent","Opponent"],y=o.judge||"Judge",x=o.rounds||2;if(!l)throw new k("workflow.debate requires a topic");if(!Array.isArray(f)||f.length<2)throw new k("workflow.debate requires at least 2 participants");u.onPrint({type:"ui_card",title:"Workflow: Debate",content:`Topic: ${l}
55
+ Participants: ${f.join(", ")}
56
+ Rounds: ${x}`});let E=`Topic: ${l}
57
+
58
+ `;for(let C=1;C<=x;C++){u.onPrint({type:"ui_progress",value:C-1,max:x,label:`Round ${C}/${x}`});for(let F of f){let B=`You are ${F} in a debate. The topic is: ${l}.
59
+
60
+ Here is the debate so far:
61
+ ${E}
62
+
63
+ Provide your next argument or rebuttal. Keep it concise and focused.`,X=u.options.model||"gemini-3-flash-preview",ne=(await u.callAI(X,[{role:"user",parts:[{text:B}]}],{})).text;E+=`**${F}**: ${ne}
64
+
65
+ `}}u.onPrint({type:"ui_progress",value:x,max:x,label:`Debate complete. ${y} is synthesizing...`});let S=`You are ${y}. Review the following debate on the topic: "${l}".
66
+
67
+ Debate Transcript:
68
+ ${E}
69
+
70
+ Synthesize the arguments and provide a final, objective conclusion or recommendation based on the points raised.`,A=u.options.model||"gemini-3-flash-preview",I=await u.callAI(A,[{role:"user",parts:[{text:S}]}],{});return{transcript:E,conclusion:I.text}}),d.define("execute_tree",async i=>{let o=i[0]||"Manager",l=i[1];if(typeof l!="string")throw new k("workflow.execute_tree requires a string goal");u.onPrint({type:"ui_card",title:"Workflow: Hierarchical Tree",content:`Manager: ${o}
71
+ Goal: ${l}`});let f=`You are ${o}. Your overall goal is: "${l}".
72
+
73
+ Break this goal down into 3-5 distinct, actionable sub-tasks. Return ONLY a JSON array of strings, where each string is a sub-task. Do not include markdown formatting or any other text.`,y=u.options.model||"gemini-3-flash-preview",x=await u.callAI(y,[{role:"user",parts:[{text:f}]}],{}),E=[];try{let C=x.text.replace(/```json/g,"").replace(/```/g,"").trim();if(E=JSON.parse(C),!Array.isArray(E))throw new Error("Not an array")}catch{u.onPrint({type:"ui_card",title:"Error",content:`Failed to parse sub-tasks. Falling back to simple split.
74
+
75
+ Raw output: ${x.text}`}),E=x.text.split(`
76
+ `).filter(F=>F.trim().length>0)}u.onPrint({type:"ui_card",title:"Sub-tasks Identified",content:E.map((C,F)=>`${F+1}. ${C}`).join(`
77
+ `)});let S=[];for(let C=0;C<E.length;C++){let F=E[C];u.onPrint({type:"ui_progress",value:C,max:E.length,label:`Executing Task ${C+1}/${E.length}`});let B=`You are a Worker agent. Your task is: "${F}".
78
+
79
+ This is part of the overall goal: "${l}".
80
+
81
+ Provide the result of your work.`,X=await u.callAI(y,[{role:"user",parts:[{text:B}]}],{});S.push(`Task: ${F}
82
+ Result:
83
+ ${X.text}`)}u.onPrint({type:"ui_progress",value:E.length,max:E.length,label:"All tasks complete. Compiling final report..."});let A=`You are ${o}. Your overall goal was: "${l}".
84
+
85
+ Your workers have completed their sub-tasks. Here are their results:
86
+
87
+ ${S.join(`
88
+
89
+ ---
90
+
91
+ `)}
92
+
93
+ Compile these results into a final, comprehensive report that achieves the original goal.`;return(await u.callAI(y,[{role:"user",parts:[{text:A}]}],{})).text})}var V=class u{static wrap(e,t={}){if(typeof e!="function")throw new k("JSBridge.wrap expects a function.");let s=function(n){try{return new.target?new e(...arguments):e(...n||[])}catch(r){throw new k(`Error in JS function '${t.name||"anonymous"}': ${r.message}`)}};return s.__helios_tool={name:t.name||e.name||"js_tool",description:t.description||`JavaScript tool: ${t.name||e.name}`,params:t.params||u.inferParams(e),returnType:t.returnType||"Unknown"},s}static inferParams(e){let t=e.toString().replace(/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg,""),s=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(/([^\s,]+)/g);return s===null?[]:s.map(n=>({name:n,type:"Unknown"}))}static async loadModule(e){try{return await import(e)}catch(t){throw new k(`Failed to load JS module from ${e}: ${t.message}`)}}};var G={GEMINI:"gemini",ANTHROPIC:"anthropic",OPENAI:"openai",WEBLLM:"webllm",CUSTOM:"custom"},R={FUNCTION_CALLING:"function_calling",VISION:"vision",JSON_MODE:"json_mode",SYSTEM_INSTRUCTIONS:"system_instructions",STREAMING:"streaming"},ze=[{id:"gemini-3-flash-preview",provider:G.GEMINI,name:"Gemini 3 Flash Preview",version:"3.0",capabilities:[R.FUNCTION_CALLING,R.VISION,R.JSON_MODE,R.SYSTEM_INSTRUCTIONS,R.STREAMING],contextWindow:1048576,recommended:!0},{id:"gemini-3.1-pro-preview",provider:G.GEMINI,name:"Gemini 3.1 Pro Preview",version:"3.1",capabilities:[R.FUNCTION_CALLING,R.VISION,R.JSON_MODE,R.SYSTEM_INSTRUCTIONS,R.STREAMING],contextWindow:2097152,recommended:!1},{id:"claude-3-5-sonnet-20240620",provider:G.ANTHROPIC,name:"Claude 3.5 Sonnet",version:"3.5",capabilities:[R.FUNCTION_CALLING,R.VISION,R.SYSTEM_INSTRUCTIONS,R.STREAMING],contextWindow:2e5,recommended:!0},{id:"claude-3-opus-20240229",provider:G.ANTHROPIC,name:"Claude 3 Opus",version:"3.0",capabilities:[R.FUNCTION_CALLING,R.VISION,R.SYSTEM_INSTRUCTIONS,R.STREAMING],contextWindow:2e5,recommended:!1},{id:"gpt-4o",provider:G.OPENAI,name:"GPT-4o",version:"4.0",capabilities:[R.FUNCTION_CALLING,R.VISION,R.JSON_MODE,R.SYSTEM_INSTRUCTIONS,R.STREAMING],contextWindow:128e3,recommended:!0},{id:"gpt-4o-mini",provider:G.OPENAI,name:"GPT-4o Mini",version:"4.0",capabilities:[R.FUNCTION_CALLING,R.VISION,R.JSON_MODE,R.SYSTEM_INSTRUCTIONS,R.STREAMING],contextWindow:128e3,recommended:!1},{id:"Hermes-3-Llama-3.1-8B-q4f32_1-MLC",provider:G.WEBLLM,name:"Hermes 3 Llama 3.1 8B",version:"3.1",capabilities:[R.FUNCTION_CALLING,R.SYSTEM_INSTRUCTIONS,R.JSON_MODE],contextWindow:8192,recommended:!0},{id:"Hermes-3-Llama-3.1-8B-q4f16_1-MLC",provider:G.WEBLLM,name:"Hermes 3 Llama 3.1 8B (Fast)",version:"3.1",capabilities:[R.FUNCTION_CALLING,R.SYSTEM_INSTRUCTIONS,R.JSON_MODE],contextWindow:8192,recommended:!1},{id:"Hermes-2-Pro-Llama-3-8B-q4f32_1-MLC",provider:G.WEBLLM,name:"Hermes 2 Pro Llama 3 8B",version:"2.0",capabilities:[R.FUNCTION_CALLING,R.SYSTEM_INSTRUCTIONS,R.JSON_MODE],contextWindow:8192,recommended:!1},{id:"Hermes-2-Pro-Llama-3-8B-q4f16_1-MLC",provider:G.WEBLLM,name:"Hermes 2 Pro Llama 3 8B (Fast)",version:"2.0",capabilities:[R.FUNCTION_CALLING,R.SYSTEM_INSTRUCTIONS,R.JSON_MODE],contextWindow:8192,recommended:!1},{id:"Hermes-2-Pro-Mistral-7B-q4f16_1-MLC",provider:G.WEBLLM,name:"Hermes 2 Pro Mistral 7B",version:"2.0",capabilities:[R.FUNCTION_CALLING,R.SYSTEM_INSTRUCTIONS,R.JSON_MODE],contextWindow:8192,recommended:!1}],ce=class{static getModelsByProvider(e){return ze.filter(t=>t.provider===e)}static getModelById(e){return ze.find(t=>t.id===e)}static getDefaultModelForProvider(e){let t=this.getModelsByProvider(e);return t.find(s=>s.recommended)||t[0]}static supportsCapability(e,t){let s=this.getModelById(e);return s?s.capabilities.includes(t):!1}};var P=class{constructor(e=null){this.values=new Map,this.parent=e}define(e,t){this.values.set(e,t)}get(e){if(this.values.has(e))return this.values.get(e);if(this.parent)return this.parent.get(e);throw new k(`Undefined variable: ${e}`)}assign(e,t){if(this.values.has(e)){this.values.set(e,t);return}if(this.parent){this.parent.assign(e,t);return}throw new k(`Undefined variable: ${e}`)}},K=class{constructor(e){this.value=e}},Ve=1e6,je=class{constructor(e=console.log,t={}){if(this.onPrint=e,this.onInputRequest=t.onInputRequest||(async s=>(console.warn(`[HITL] Input requested but no handler provided: ${s}`),"")),this.options=t,this.globalEnv=new P,this.globalTypes=new Map,this.contextStack=[],this.history=t.history||[],this.memoryLimit=t.memoryLimit||10,this.summarizeHistory=t.summarizeHistory||!1,this.trace=[],this.blackboard=[],this.systemPrompt=t.systemPrompt||"You are the Helios AI engine. If a JSON schema is provided, you MUST return a valid JSON object matching that schema exactly. Do NOT wrap the JSON in a top-level property or code blocks. If NO schema is provided, return a plain text response. Always use the provided context items to inform your response.",this.modules=new Map,this.toolMetadata=new Map,this.setupBuiltins(),t.tools)for(let[s,n]of Object.entries(t.tools))this.registerTool(s,n);if(t.modules)for(let[s,n]of Object.entries(t.modules))this.registerModule(s,n);try{if(process.env.GEMINI_API_KEY)this.ai=new Ue.GoogleGenAI({apiKey:process.env.GEMINI_API_KEY});else throw new Error("GEMINI_API_KEY environment variable is not set.")}catch(s){t.dryRun||console.warn(`[Warning] Could not initialize GoogleGenAI: ${s.message}. AI features will fail unless --dry-run is used.`)}}getTrace(){return this.trace}clearTrace(){this.trace=[]}addTrace(e){this.trace.push({timestamp:Date.now(),...e})}registerTool(e,t){if(!e||typeof e!="string")throw new k(`Invalid tool name: ${e}`);let s,n={name:e,description:`Tool: ${e}`,params:[],returnType:"Unknown"};if(typeof t=="function"){s=t;let r=this.inferParams(t);n.params=r.map(a=>({name:a,type:"Unknown"}))}else if(t&&typeof t=="object"&&t.fn){if(typeof t.fn!="function")throw new k(`Tool '${e}' must have a 'fn' property that is a function.`);s=t.fn;let r=t.signature?.params||this.inferParams(t.fn);n.params=r.map((a,m)=>a?{name:typeof a=="string"?a:a.name||`arg${m}`,type:typeof a=="string"?"Unknown":a.type||"Unknown"}:{name:`arg${m}`,type:"Unknown"}),n.description=t.description||n.description,n.returnType=t.signature?.returnType||"Unknown"}else throw new k(`Invalid tool definition for '${e}'. Expected a function or an object with a 'fn' property.`);this.globalEnv.define(e,s),this.toolMetadata.set(e,n)}inferParams(e){let t=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg,s=/([^\s,]+)/g,n=e.toString().replace(t,""),r=n.indexOf("("),a=n.indexOf(")");if(r===-1||a===-1)return[];let m=n.slice(r+1,a).match(s);return m===null?[]:m.filter(w=>w!=="async")}registerModule(e,t){if(t instanceof P)this.modules.set(e,t);else{let s=new P;if(t&&typeof t=="object")for(let[n,r]of Object.entries(t))s.define(n,r);this.modules.set(e,s)}}setupBuiltins(){this.globalEnv.define("print",async p=>(this.onPrint(...p),p[0])),this.globalEnv.define("length",async p=>{let h=p[0];if(typeof h=="string"||Array.isArray(h))return h.length;throw new k(`Cannot get length of ${typeof h}`)}),this.globalEnv.define("typeof",async p=>{let h=p[0];return Array.isArray(h)?"Array":h===null?"Null":typeof h=="object"?"Object":typeof h=="number"?Number.isInteger(h)?"Int":"Float":typeof h=="boolean"?"Bool":typeof h=="string"?"String":typeof h}),this.globalEnv.define("toString",async p=>{let h=p[0];return typeof h=="object"&&h!==null?JSON.stringify(h,null,2):String(h)}),this.globalEnv.define("parseInt",async p=>{let h=parseInt(p[0],10);if(isNaN(h))throw new k(`Cannot parse integer from "${p[0]}"`);return h}),this.globalEnv.define("parseFloat",async p=>{let h=parseFloat(p[0]);if(isNaN(h))throw new k(`Cannot parse float from "${p[0]}"`);return h}),this.registerModule("math",new P),this.registerModule("fs",new P),this.registerModule("json",new P),this.registerModule("csv",new P),this.registerModule("xml",new P),this.registerModule("list",new P),this.registerModule("obj",new P),this.registerModule("ui",new P),this.registerModule("memory",new P),this.registerModule("text",new P),this.registerModule("web",new P),this.registerModule("agent",new P),this.registerModule("crypto",new P),this.registerModule("base64",new P),this.registerModule("regex",new P),this.registerModule("url",new P),this.registerModule("workflow",new P),this.globalEnv.define("Date",Date),this.globalEnv.define("UUID",()=>crypto.randomUUID()),this.globalEnv.define("Unit",null);let e=this.modules.get("math");e.define("PI",Math.PI),e.define("abs",async p=>Math.abs(p[0])),e.define("ceil",async p=>Math.ceil(p[0])),e.define("floor",async p=>Math.floor(p[0])),e.define("round",async p=>Math.round(p[0])),Ke(this),e.define("max",async p=>Math.max(...p)),e.define("min",async p=>Math.min(...p)),e.define("random",async()=>Math.random());let t=this.modules.get("fs"),s="helios_fs_";t.define("read",async p=>{let h=p[0],d=localStorage.getItem(s+h);if(d===null)throw new k(`File not found: ${h}`);return d}),t.define("write",async p=>{let h=p[0],d=p[1];return localStorage.setItem(s+h,String(d)),!0}),t.define("exists",async p=>{let h=p[0];return localStorage.getItem(s+h)!==null}),t.define("list",async()=>{let p=[];for(let h=0;h<localStorage.length;h++){let d=localStorage.key(h);d.startsWith(s)&&p.push(d.substring(s.length))}return p}),t.define("delete",async p=>{let h=p[0];return localStorage.removeItem(s+h),!0});let n=this.modules.get("json");n.define("parse",async p=>JSON.parse(p[0])),n.define("stringify",async p=>JSON.stringify(p[0],null,2));let r=this.modules.get("csv");r.define("parse",async p=>{let h=p[0],d=p[1]||{header:!0,delimiter:","},i=h.split(`
94
+ `).filter(f=>f.trim());if(i.length===0)return[];let o=d.delimiter||",",l=f=>{let y=[],x="",E=!1;for(let S=0;S<f.length;S++){let A=f[S];A==='"'?E=!E:A===o&&!E?(y.push(x.trim()),x=""):x+=A}return y.push(x.trim()),y};if(d.header){let f=l(i[0]);return i.slice(1).map(y=>{let x=l(y),E={};return f.forEach((S,A)=>{let I=x[A]||"";!isNaN(I)&&I!==""&&(I=Number(I)),E[S]=I}),E})}return i.map(f=>l(f))}),r.define("stringify",async p=>{let h=p[0];if(!Array.isArray(h)||h.length===0)return"";let d=p[1]||{header:!0,delimiter:","},i=d.delimiter||",",o=l=>{let f=String(l);return f.includes(i)||f.includes('"')||f.includes(`
95
+ `)?`"${f.replace(/"/g,'""')}"`:f};if(d.header&&typeof h[0]=="object"&&h[0]!==null){let l=Object.keys(h[0]),f=l.join(i),y=h.map(x=>l.map(E=>o(x[E])).join(i));return[f,...y].join(`
96
+ `)}return h.map(l=>Array.isArray(l)?l.map(o).join(i):o(l)).join(`
97
+ `)});let a=this.modules.get("xml"),m=p=>{if(p.nodeType===3)return p.nodeValue.trim();if(p.nodeType!==1)return null;let h={};if(p.attributes&&p.attributes.length>0){h["@attributes"]={};for(let d=0;d<p.attributes.length;d++){let i=p.attributes[d];h["@attributes"][i.name]=i.value}}for(let d=0;d<p.childNodes.length;d++){let i=p.childNodes[d],o=m(i);if(o===null||o==="")continue;let l=i.nodeName;h[l]?(Array.isArray(h[l])||(h[l]=[h[l]]),h[l].push(o)):h[l]=o}return h};a.define("parse",async p=>{let d=new DOMParser().parseFromString(p[0],"text/xml"),i=d.querySelector("parsererror");if(i)throw new k(`XML Parse Error: ${i.textContent}`);return m(d.documentElement)});let w=(p,h)=>{if(p===null||typeof p!="object")return`<${h}>${p===null?"":p}</${h}>`;let d=`<${h}`;if(p["@attributes"])for(let[i,o]of Object.entries(p["@attributes"]))d+=` ${i}="${o}"`;d+=">";for(let[i,o]of Object.entries(p))i!=="@attributes"&&(Array.isArray(o)?o.forEach(l=>d+=typeof l=="object"&&l!==null?w(l,i):`<${i}>${l}</${i}>`):typeof o=="object"&&o!==null?d+=w(o,i):i==="#text"?d+=o:d+=`<${i}>${o}</${i}>`);return d+=`</${h}>`,d};a.define("stringify",async p=>{let h=p[0],d=p[1]||"root";return w(h,d)}),this.modules.set("web",new P);let v=this.modules.get("web"),T=async(p,h)=>(await this.callAI("gemini-3-flash-preview",[{role:"user",parts:[{text:p}]}],{temperature:0},[],[{[h]:{}}])).text,M=async p=>await T(p[0],"googleSearch");M.isGrounding=!0,M.groundingName="googleSearch",v.define("search",M);let O=async p=>await T(p[0],"googleMaps");O.isGrounding=!0,O.groundingName="googleMaps",v.define("maps",O),v.define("fetch",async p=>{let h=p[0],d=p[1]||{},i=await fetch(h,d);return d.json?await i.json():await i.text()}),this.modules.set("storage",new P);let $=this.modules.get("storage");$.define("get",async p=>{let h=p[0],d=localStorage.getItem(`helios_${h}`);try{return JSON.parse(d)}catch{return d}}),$.define("set",async p=>{let h=p[0],d=p[1];return localStorage.setItem(`helios_${h}`,typeof d=="object"?JSON.stringify(d):String(d)),!0}),$.define("delete",async p=>(localStorage.removeItem(`helios_${p[0]}`),!0)),this.modules.set("context",new P);let D=this.modules.get("context");D.define("requestInput",async p=>{let h=p[0]||"Input required:";this.addTrace({type:"hitl_request",prompt:h});let d=await this.onInputRequest(h);return this.addTrace({type:"hitl_response",prompt:h,result:d}),d}),D.define("add",async p=>(this.contextStack.push(p[0]),!0)),D.define("clear",async()=>(this.contextStack=[],!0)),D.define("getHistory",async()=>this.history),D.define("setHistory",async p=>(this.history=p[0],!0)),D.define("clearHistory",async()=>(this.history=[],!0)),D.define("setSystemPrompt",async p=>(this.systemPrompt=p[0],!0)),D.define("pruneHistory",async p=>{let d=(p[0]||this.memoryLimit||10)*2;return this.history.length>d&&(this.history=this.history.slice(-d)),!0}),this.modules.set("ai",new P);let N=this.modules.get("ai");this.modules.set("swarm",new P);let L=this.modules.get("swarm");this.subAgents=new Map,L.define("createAgent",async p=>{let h=p[0],d=p[1],i=p[2]||[],o=[...new Set([...i,"delegate","broadcast","readBlackboard"])],l=this.options.model||"gemini-3-flash-preview";return this.subAgents.set(h,{systemPrompt:d,tools:o,history:[],model:l}),!0}),L.define("setAgentModel",async p=>{let h=p[0],d=p[1],i=this.subAgents.get(h);if(!i)throw new k(`Sub-agent '${h}' not found`);return i.model=d,this.onPrint(`[Swarm] Set model for ${h} to ${d}`),!0}),L.define("broadcast",async p=>{let h=p[0],d=p[1]||"System";return this.blackboard.push({sender:d,message:h,timestamp:Date.now()}),this.onPrint(`[Swarm] ${d} broadcasted: ${h}`),!0}),L.get("broadcast").__helios_tool={description:"Broadcast a message to all agents via the shared blackboard.",params:[{name:"message",type:"string"}]},L.define("readBlackboard",async()=>this.blackboard),L.get("readBlackboard").__helios_tool={description:"Read all messages from the shared blackboard.",params:[]},L.define("addTool",async p=>{let h=p[0],d=p[1],i=this.subAgents.get(h);if(!i)throw new k(`Sub-agent '${h}' not found`);return i.tools.includes(d)||(i.tools.push(d),this.onPrint(`[Swarm] Added tool '${d}' to agent '${h}'`)),!0}),L.get("addTool").__helios_tool={description:"Add a tool to a specific agent.",params:[{name:"agentName",type:"string"},{name:"toolName",type:"string"}]},L.define("removeTool",async p=>{let h=p[0],d=p[1],i=this.subAgents.get(h);if(!i)throw new k(`Sub-agent '${h}' not found`);let o=i.tools.indexOf(d);return o!==-1&&(i.tools.splice(o,1),this.onPrint(`[Swarm] Removed tool '${d}' from agent '${h}'`)),!0}),L.get("removeTool").__helios_tool={description:"Remove a tool from a specific agent.",params:[{name:"agentName",type:"string"},{name:"toolName",type:"string"}]},L.define("listTools",async p=>{let h=p[0];if(h){let d=this.subAgents.get(h);if(!d)throw new k(`Sub-agent '${h}' not found`);return d.tools}return[]}),L.get("listTools").__helios_tool={description:"List all tools available to a specific agent.",params:[{name:"agentName",type:"string"}]},L.define("delegate",async p=>{let h=p[0],d=p[1],i=this.subAgents.get(h);if(!i)throw new k(`Sub-agent '${h}' not found`);this.onPrint(`[Swarm] Delegating to ${h}: ${d}`),this.addTrace({type:"swarm_delegate",agent:h,task:d});let o=new Map,l=[];for(let E of i.tools){let S;try{S=this.globalEnv.get(E)}catch{for(let C of this.modules.values())try{S=C.get(E);break}catch{}}let A=this.toolMetadata.get(E)||S?.__helios_tool;if(S){let I={type:"FunctionDeclaration",name:E,description:A?.description||`Executes the ${E} tool.`,params:A?.params||[],body:[]};o.set(E,I),l.push(I)}}let f=[...i.history,{role:"user",parts:[{text:d}]}],y=0,x=5;for(;y<x;){let E=await this.callAI(i.model||"gemini-3-flash-preview",f,{systemInstruction:i.systemPrompt},l),S=E.functionCalls;if(S&&S.length>0){f.push({role:"model",parts:E.parts});let A=[];for(let I of S){let C=o.get(I.name);if(C){this.onPrint(`[Swarm][${h}] Tool Call: ${I.name}`,I.args);try{let F=C.params.map(Q=>I.args[Q.name]);I.name==="broadcast"&&F.length===1&&F.push(h);let B;try{B=this.globalEnv.get(I.name)}catch{for(let ne of this.modules.values())try{B=ne.get(I.name);break}catch{}}if(!B)throw new Error(`Tool function '${I.name}' implementation not found`);let X=await this.callFunction(B,F);A.push({functionResponse:{name:I.name,response:{result:X},id:I.id}})}catch(F){A.push({functionResponse:{name:I.name,response:{error:F.message},id:I.id}})}}}f.push({role:"tool",parts:A}),y++;continue}return i.history.push({role:"user",parts:[{text:d}]}),i.history.push({role:"model",parts:E.parts}),this.addTrace({type:"swarm_response",agent:h,response:E.text}),E.text}throw new k(`Agent '${h}' exceeded max turns during delegation.`)}),this.modules.set("mcp",new P);let H=this.modules.get("mcp");this.mcpServers=new Map,H.define("connect",async p=>{let h=p[0],d=p[1];this.onPrint(`[MCP] Connecting to ${h} (${d})...`);try{let i=new _e(d,o=>this.onPrint(o));return await i.connect(),this.mcpServers.set(h,{client:i,type:"real"}),!0}catch(i){return this.onPrint(`[MCP] Connection failed: ${i.message}. Falling back to mock mode.`),this.mcpServers.set(h,{url:d,type:"mock",tools:[]}),!1}}),H.define("listTools",async p=>{let h=p[0],d=this.mcpServers.get(h);if(!d)throw new k(`MCP server '${h}' not found. Connect first.`);if(d.type==="real")try{return(await d.client.request("tools/list",{})).tools}catch(i){throw new k(`Failed to list tools: ${i.message}`)}else{let i=[];return h==="github"?i=[{name:"create_issue",description:"Create a GitHub issue",inputSchema:{type:"object",properties:{owner:{type:"string"},repo:{type:"string"},title:{type:"string"}}}},{name:"list_prs",description:"List pull requests",inputSchema:{type:"object",properties:{owner:{type:"string"},repo:{type:"string"}}}}]:h==="filesystem"?i=[{name:"read_file",description:"Read a file from host",inputSchema:{type:"object",properties:{path:{type:"string"}}}},{name:"list_dir",description:"List directory contents",inputSchema:{type:"object",properties:{path:{type:"string"}}}}]:i=[{name:"ping",description:"Ping the server",inputSchema:{}}],d.tools=i,i}}),H.define("callTool",async p=>{let h=p[0],d=p[1],i=p[2]||{},o=this.mcpServers.get(h);if(!o)throw new k(`MCP server '${h}' not found.`);if(this.onPrint(`[MCP] Calling tool '${d}' on server '${h}' with args: ${JSON.stringify(i)}`),o.type==="real")try{return await o.client.request("tools/call",{name:d,arguments:i})}catch(l){throw new k(`Tool execution failed: ${l.message}`)}else return h==="github"&&d==="create_issue"?{content:[{type:"text",text:`Created issue #123 at https://github.com/${i.owner}/${i.repo}/issues/123`}]}:h==="filesystem"&&d==="read_file"?{content:[{type:"text",text:"Content of file at "+i.path}]}:{content:[{type:"text",text:`Executed ${d} on ${h}`}]}}),this.globalEnv.define("mcp",H),this.modules.set("memory",new P);let Z=this.modules.get("memory"),W=async p=>this.options.dryRun?new Array(768).fill(0):(await this.ai.models.embedContent({model:"gemini-embedding-001",contents:[{parts:[{text:p}]}]})).embeddings[0].values,se=(p,h)=>{let d=0,i=0,o=0;for(let f=0;f<p.length;f++)d+=p[f]*h[f],i+=p[f]*p[f],o+=h[f]*h[f];let l=Math.sqrt(i)*Math.sqrt(o);return l===0?0:d/l};Z.define("store",async p=>{let h=p[0],d=p[1],i=p[2]||{},o=await W(d),l=JSON.parse(localStorage.getItem("helios_memories")||"[]");return l.push({key:h,text:d,vector:o,metadata:i,timestamp:Date.now()}),localStorage.setItem("helios_memories",JSON.stringify(l)),!0}),Z.define("search",async p=>{let h=p[0],d=p[1]||3,i=await W(h);return JSON.parse(localStorage.getItem("helios_memories")||"[]").map(f=>({...f,score:se(i,f.vector)})).sort((f,y)=>y.score-f.score).slice(0,d).map(f=>({text:f.text,metadata:f.metadata,score:f.score}))}),Z.define("clear",async()=>(localStorage.removeItem("helios_memories"),!0)),N.define("generateCode",async p=>{let h=p[0],i=(await this.callAI(this.options.model||"gemini-3-flash-preview",[{role:"user",parts:[{text:`You are a Helios code generator. Generate ONLY valid Helios code based on this request: ${h}.
98
+
99
+ Helios Syntax Rules:
100
+ - Use 'fn name(param: Type) -> ReturnType { ... }' for functions.
101
+ - Common types: 'Int', 'Float', 'String', 'Bool', 'Unknown'.
102
+ - Use 'let' or 'var' for variables.
103
+ - Use 'print(val)' for logging.
104
+ - Return types are optional but if used must follow '->'.
105
+ - Do NOT include markdown code blocks, explanations, or any other text.`}]}],{})).text.trim();return i=i.replace(/```[a-z]*\s*([\s\S]*?)\s*```/gi,"$1").trim(),i}),N.define("classify",async p=>{let h=p[0],d=p[1];if(!Array.isArray(d))throw new k("Second argument to ai.classify must be a list of labels");return(await this.callAI(this.options.model||"gemini-3-flash-preview",[{role:"user",parts:[{text:`Classify the following text into exactly one of these labels: ${d.join(", ")}.
106
+ Text: "${h}".
107
+ Return ONLY the label.`}]}],{})).text.trim()}),N.define("extract",async p=>{let h=p[0],d=p[1];if(d&&d.__type==="Type"){let o=l=>{if(!l)return"Unknown";if(l.type==="TypeReference")return l.name==="String"?"string":l.name==="Int"||l.name==="Float"?0:l.name==="Bool"?!0:l.name;if(l.type==="ObjectType"){let f={};for(let[y,x]of Object.entries(l.fields))f[y]=o(x);return f}return l.type==="ArrayType"?[o(l.elementType)]:"Unknown"};d=o(d.def)}let i=await this.callAI(this.options.model||"gemini-3-flash-preview",[{role:"user",parts:[{text:`Extract data from the text according to this schema/structure: ${JSON.stringify(d)}.
108
+ Text: "${h}".
109
+ Return ONLY valid JSON matching the structure.`}]}],{responseMimeType:"application/json"});try{return JSON.parse(i.text)}catch{return i.text}}),N.define("summarize",async p=>{let h=p[0],d=p[1]||"brief",i="briefly";return typeof d=="number"?i=`in approximately ${d} words`:d==="detailed"&&(i="in detail"),(await this.callAI(this.options.model||"gemini-3-flash-preview",[{role:"user",parts:[{text:`Summarize the following text ${i}: "${h}".`}]}],{})).text.trim()}),N.define("sentiment",async p=>{let h=p[0],i=(await this.callAI(this.options.model||"gemini-3-flash-preview",[{role:"user",parts:[{text:`Analyze the sentiment of the text below. Classify it as exactly one of: POSITIVE, NEGATIVE, NEUTRAL.
110
+
111
+ Rules:
112
+ - POSITIVE: Enthusiastic, happy, satisfied, praising, love, great, amazing.
113
+ - NEGATIVE: Angry, disappointed, complaining, sad, hate, bad, terrible.
114
+ - NEUTRAL: Factual, objective, no strong emotion, mixed but balanced.
115
+
116
+ Text: "${h}"
117
+
118
+ Return ONLY the classification label.`}]}],{})).text.trim().toUpperCase();return i.includes("POSITIVE")?"POSITIVE":i.includes("NEGATIVE")?"NEGATIVE":i.includes("NEUTRAL")?"NEUTRAL":i}),N.define("translate",async p=>{let h=p[0],d=p[1];return(await this.callAI(this.options.model||"gemini-3-flash-preview",[{role:"user",parts:[{text:`Translate the following text to ${d}. Return ONLY the translated text.
119
+ Text: "${h}".`}]}],{})).text.trim()})}async fixHeliosCode(e,t){try{return(await this.callAI(this.options.model||"gemini-3-flash-preview",[{role:"user",parts:[{text:`You are an expert in the Helios programming language.
120
+ The following code generated a syntax or runtime error. Please fix it to be valid Helios code.
121
+
122
+ ERROR: ${t}
123
+
124
+ BROKEN CODE:
125
+ ${e}
126
+
127
+ HELIOS SYNTAX CHEATSHEET:
128
+ - Declare variable: let x = 10
129
+ - Function: fn myFunc(a: Int) -> Int { return a + 1 } (Use 'fn', NOT 'function')
130
+ - NO arrow functions (=>), NO 'const', NO 'function' keyword.
131
+ - If/Else: if x > 0 { ... } else { ... }
132
+ - While: while x < 10 { ... }
133
+ - Print: print("Hello")
134
+ - String conversion: use toString(x), NOT x.toString() or x.show()
135
+ - Lists: let list = [1, 2, 3]; list.push(list, 4)
136
+ - Objects: let obj = { a: 1 };
137
+ - Comments: // comment
138
+ - Semicolons are optional but recommended to avoid ambiguity.
139
+
140
+ IMPORTANT:
141
+ - If the error is "Expression is not a function", check if a variable is being called like a function,
142
+ OR if a missing semicolon between a variable and a parenthesized expression on the next line is causing it.
143
+ - Ensure all function calls use valid function names.
144
+ - Do NOT use JavaScript syntax like 'const', '===', or 'function'. Use Helios syntax.
145
+ - Do NOT use methods on primitives (like .toString()). Use global functions (toString(x)).
146
+
147
+ Return ONLY the fixed code. Do not include markdown formatting or explanations.`}]}],{})).text.trim().replace(/```[a-z]*\s*([\s\S]*?)\s*```/gi,"$1").trim()}catch(s){return console.warn("Failed to auto-fix code:",s),e}}async evaluate(e,t=this.globalEnv){if(!e)return null;switch(e.type||console.error("Node without type:",e),e.type){case"Program":let s=null;for(let r of e.body)if(s=await this.evaluate(r,t),s instanceof K)return s.value;return s;case"ComptimeBlock":{let r=null;for(let a of e.body)if(r=await this.evaluate(a,t),r instanceof K){r=r.value;break}if(typeof r=="string"){let a=r,m=0,w=2;for(;m<w;)try{let T=new ee(a).tokenize(),O=new te(T,a).parse();return await this.evaluate(O,t)}catch(v){m++;let T=v.name==="HeliosSyntaxError"||v.name==="HeliosLexicalError";if(m<w&&this.ai){this.onPrint(`[Comptime] Error detected: ${v.message}. Attempting AI fix...`),a=await this.fixHeliosCode(a,v.message),this.onPrint(`[Comptime] AI suggested fix:
148
+ ${a}`);continue}throw T?v:new k(`Failed to parse or execute comptime injected code: ${v.message}`,e.line,e.col)}}return r}case"ImportDeclaration":{let r=this.modules.get(e.source);if(!r&&e.isExternal){let a=e.source;if(a.startsWith("npm:")&&(a=`https://esm.sh/${a.substring(4)}`),e.uses.includes("js")){this.addTrace({type:"external_import",source:a,runtime:"js"});let m=await V.loadModule(a);r=new P;for(let[w,v]of Object.entries(m))typeof v=="function"?r.define(w,V.wrap(v,{name:w})):r.define(w,v);m.default&&!m.hasOwnProperty("default")&&(typeof m.default=="function"?r.define("default",V.wrap(m.default,{name:"default"})):r.define("default",m.default)),this.modules.set(e.source,r)}}if(!r)throw new k(`Module not found: ${e.source}`,e.line,e.col);for(let a of e.specifiers)try{let m=r.get(a.name);t.define(a.alias||a.name,m)}catch{throw new k(`Module '${e.source}' does not export '${a.name}'`,e.line,e.col)}return}case"VariableDeclaration":let n=await this.evaluate(e.init,t);t.define(e.pattern,n);return;case"TypeDeclaration":this.globalTypes.set(e.name,e.value),t.define(e.name,{__type:"Type",name:e.name,def:e.value});return;case"AssignmentExpression":{let r=await this.evaluate(e.value,t);if(!e.left)throw new k("Invalid assignment target",e.line,e.col);if(e.left.type==="Identifier")t.assign(e.left.name,r);else if(e.left.type==="MemberExpression"){let a=await this.evaluate(e.left.object,t),m=await this.evaluate(e.left.property,t);if(a==null)throw new k("Cannot set property of null or undefined",e.line,e.col);a[m]=r}else throw new k("Invalid assignment target",e.line,e.col);return r}case"Literal":return e.kind==="Number"?parseFloat(e.value):e.kind==="Boolean"?e.value===!0||e.value==="true":e.kind==="Null"?null:e.value;case"Identifier":try{return t.get(e.name)}catch(r){let a=this.modules.get(e.name);if(a)return a;throw new k(r.message,e.line,e.col)}case"BinaryExpression":{let r=await this.evaluate(e.left,t);if(e.operator==="&&")return r&&await this.evaluate(e.right,t);if(e.operator==="||")return r||await this.evaluate(e.right,t);if(e.operator==="|>"){if(!e.right)throw new k("Invalid pipe target",e.line,e.col);if(e.right.type==="CallExpression"){let m=await this.evaluate(e.right.callee,t),w=[r];for(let v of e.right.arguments)w.push(await this.evaluate(v,t));return await this.callFunction(m,w,e.right)}else{let m=await this.evaluate(e.right,t);return await this.callFunction(m,[r],e)}}let a=await this.evaluate(e.right,t);switch(e.operator){case"+":return r+a;case"-":return r-a;case"*":return r*a;case"/":return r/a;case"==":return r===a;case"!=":return r!==a;case"<":return r<a;case">":return r>a;case"<=":return r<=a;case">=":return r>=a;default:throw new k(`Unknown operator: ${e.operator}`,e.line,e.col)}}case"UnaryExpression":{let r=await this.evaluate(e.argument,t);return e.operator==="-"?-r:e.operator==="!"?!r:r}case"AwaitExpression":return await this.evaluate(e.argument,t);case"ArrayLiteral":{let r=[];for(let a of e.elements)r.push(await this.evaluate(a,t));return r}case"ObjectLiteral":{let r={};for(let a of e.properties)r[a.key]=await this.evaluate(a.value,t);return r}case"MemberExpression":{let r=await this.evaluate(e.object,t),a=await this.evaluate(e.property,t);if(r==null)throw new k("Cannot read property of null or undefined",e.line,e.col);let m;if(r instanceof P)try{m=r.get(a)}catch{throw new k(`Module member '${a}' not found`,e.line,e.col)}else m=r[a];if(typeof m=="function"){let w=m.toString().includes("[native code]");if(!(r instanceof P)&&w)return T=>m.apply(r,T)}return m}case"PromptExpression":{let r=await this.evaluate(e.template,t);typeof r!="string"&&(r=String(r));let a=/\{([^}]+)\}/g,m=[...r.matchAll(a)];for(let d of m){let i=d[1];try{let l=new ee(i).tokenize(),y=new te(l,i).parseExpression(),x=await this.evaluate(y,t);r=r.replace(d[0],typeof x=="object"?JSON.stringify(x):String(x))}catch(o){console.warn(`Failed to interpolate expression "${i}" in prompt:`,o)}}let w=[];if(e.contexts)for(let d of e.contexts)w.push(await this.evaluate(d,t));let v=[...this.contextStack,...w];if(v.length>0&&(r=`CRITICAL: You MUST use the provided [CONTEXT_DATA] below to fulfill the request. Do NOT use any other information or examples.
149
+
150
+ ${v.map((i,o)=>`[CONTEXT_DATA_${o+1}]
151
+ ${typeof i=="object"?JSON.stringify(i,null,2):String(i)}`).join(`
152
+
153
+ `)}
154
+
155
+ ---
156
+
157
+ USER REQUEST: ${r}`),this.options.dryRun)return`[DRY RUN] Prompt: ${r}`;let T=e.retries?await this.evaluate(e.retries,t):0,M=e.timeout?await this.evaluate(e.timeout,t):3e4,O=e.model?await this.evaluate(e.model,t):this.options.model||(this.options.provider==="custom"?"gpt-3.5-turbo":"gemini-3-flash-preview"),$=0,D=null,N=new Map,L=[],H=[];if(e.tools)for(let d of e.tools){let i=t.get(d);if(!i)throw new k(`Tool '${d}' not found`,e.line,e.col);if(i.isGrounding)H.push({[i.groundingName]:{}});else if(typeof i=="function"||i.type==="FunctionDeclaration"||this.toolMetadata.has(d))if(i.type==="FunctionDeclaration")N.set(d,i),L.push(i);else{let o=this.toolMetadata.get(d)||i.__helios_tool,l={type:"FunctionDeclaration",name:d,description:o?.description||`Executes the ${d} tool.`,params:o?.params||[],body:[]};N.set(d,l),L.push(l)}else throw new k(`Tool '${d}' is not a valid function or grounding tool`,e.line,e.col)}let Z=e.history?await this.evaluate(e.history,t):this.history,W=[...Z],se={role:"user",parts:[{text:r}]};W.push(se),this.addTrace({type:"prompt_start",model:O,template:r,history:Z.length,context:this.contextStack.length});let p=10,h=0;for(;$<=T;)try{let d=new AbortController,i=setTimeout(()=>d.abort(),M);for(;h<p;){this.addTrace({type:"ai_call_start",turn:h,contents:JSON.parse(JSON.stringify(W))});let o=await this.callAI(O,W,{temperature:this.options.temperature??.9,topK:this.options.topK??40,topP:this.options.topP??.95,schema:e.schema,signal:d.signal},L,H);clearTimeout(i),this.addTrace({type:"ai_call_end",turn:h,response:{text:o.text,functionCalls:o.functionCalls,parts:o.parts,usage:o.usage,groundingMetadata:o.groundingMetadata}});let l=o.functionCalls;if(l&&l.length>0){W.push({role:"model",parts:o.parts});let y=[];for(let x of l){let E=N.get(x.name);if(E){this.onPrint(`[Tool] Calling ${x.name} with args:`,x.args),this.addTrace({type:"tool_call",name:x.name,args:x.args,id:x.id});try{let S=E.params.map(I=>x.args[I.name]),A=await this.callFunction(E,S,e);this.addTrace({type:"tool_response",name:x.name,result:A,id:x.id}),y.push({functionResponse:{name:x.name,response:{result:A},id:x.id}})}catch(S){this.addTrace({type:"tool_error",name:x.name,error:S.message,id:x.id}),y.push({functionResponse:{name:x.name,response:{error:S.message},id:x.id}})}}}W.push({role:"tool",parts:y}),h++;continue}let f=o.text;if(this.history.push({role:"user",parts:[{text:r}]}),this.history.push({role:"model",parts:o.parts}),await this.manageHistory(),f&&(f=f.replace(/```json\s*([\s\S]*?)\s*```/g,"$1").replace(/```\s*([\s\S]*?)\s*```/g,"$1").trim()),e.schema){if(!f)throw new Error("AI returned an empty response, but a structured schema was expected.");try{let y=JSON.parse(f),x=typeof e.schema=="string"?e.schema:e.schema.type==="TypeReference"?e.schema.name:null;if(x&&typeof y=="object"&&y!==null){let S=Object.keys(y);if(S.length===1&&S[0].toLowerCase()===x.toLowerCase())y=y[S[0]];else if(y[x])y=y[x];else{let A=S.find(I=>I.toLowerCase()===x.toLowerCase());A&&(y=y[A])}}let E=this.convertToGeminiSchema(e.schema);if(E&&E.type==="OBJECT"&&typeof y=="object"&&y!==null){let S={},A=E.properties||{};for(let I of Object.keys(y)){let C=Object.keys(A).find(F=>F.toLowerCase()===I.toLowerCase());C?S[C]=y[I]:S[I]=y[I]}y=S}return y}catch(y){throw new Error(`AI returned invalid JSON for schema: ${y.message}
158
+ Response: ${f}`)}}return f}throw new k("Max conversation turns reached during function calling.",e.line,e.col)}catch(d){D=d,$++,$<=T&&(this.onPrint(`[AI] Attempt ${$} failed, retrying...`),W=[{role:"user",parts:[{text:r}]}],h=0)}if(e.fallback)return await this.evaluate(e.fallback,t);throw new k(`Prompt failed after ${T} retries: ${D?.message}`,e.line,e.col)}case"WhileStatement":{let r,a=0,m=this.options.maxLoopIterations||Ve;for(;await this.evaluate(e.condition,t);){if(++a>m)throw new k(`Infinite loop detected: exceeded ${m} iterations`,e.line,e.col);if(r=await this.evaluateBlock(e.body,new P(t)),r instanceof K)return r}return r}case"IfExpression":return await this.evaluate(e.condition,t)?await this.evaluateBlock(e.consequent,new P(t)):e.alternate?Array.isArray(e.alternate)?await this.evaluateBlock(e.alternate,new P(t)):await this.evaluate(e.alternate,t):void 0;case"MatchExpression":{let r=await this.evaluate(e.discriminant,t);for(let a of e.arms){let m={};if(await this.matchesPattern(a.pattern,r,t,m)){let w=new P(t);for(let[v,T]of Object.entries(m))w.define(v,T);if(a.guard&&!await this.evaluate(a.guard,w))continue;return await this.evaluateInMatchBody(a.body,w)}}throw new k("No match found",e.line,e.col)}case"ForStatement":{let r=await this.evaluate(e.iterable,t),a,m=0,w=this.options.maxLoopIterations||Ve;if(Array.isArray(r))for(let v of r){if(++m>w)throw new k(`Loop iteration limit exceeded: ${w}`,e.line,e.col);let T=new P(t);if(T.define(e.iterator,v),a=await this.evaluateBlock(e.body,T),a instanceof K)return a}else if(typeof r=="number")for(let v=0;v<r;v++){if(++m>w)throw new k(`Loop iteration limit exceeded: ${w}`,e.line,e.col);let T=new P(t);if(T.define(e.iterator,v),a=await this.evaluateBlock(e.body,T),a instanceof K)return a}return a}case"WithContextStatement":{let r=[];for(let a of e.context)r.push(await this.evaluate(a,t));this.contextStack.push(...r);try{return await this.evaluateBlock(e.body,new P(t))}finally{for(let a=0;a<r.length;a++)this.contextStack.pop()}}case"FunctionDeclaration":t.define(e.name,e);return;case"CallExpression":{let r=await this.evaluate(e.callee,t),a=[];for(let m of e.arguments)a.push(await this.evaluate(m,t));return await this.callFunction(r,a,e)}case"NewExpression":{let r=await this.evaluate(e.callee,t),a=[];for(let m of e.arguments)a.push(await this.evaluate(m,t));if(typeof r=="function")return new r(...a);throw new k(`Cannot use 'new' on non-function: ${typeof r}`,e.line,e.col)}case"ReturnStatement":return new K(await this.evaluate(e.argument,t));default:return null}}async callFunction(e,t,s){if(typeof e=="function")return await e(t);if(e&&e.type==="FunctionDeclaration"){let r=e.annotations?.find(v=>v.name==="trace");r&&this.onPrint(`[Trace] Entering ${e.name}${r.args?` (${r.args})`:""} with args:`,t);let a=new P(this.globalEnv);e.params.forEach((v,T)=>{a.define(v.name,t[T])});let m=await this.evaluateBlock(e.body,a),w=m instanceof K?m.value:m;return r&&this.onPrint(`[Trace] Exiting ${e.name} with result:`,w),w}let n=s&&s.callee&&s.callee.type==="Identifier"?s.callee.name:"Expression";throw new k(`${n} is not a function`,s?s.line:0,s?s.col:0)}async evaluateBlock(e,t){let s=null;for(let n of e)if(s=await this.evaluate(n,t),s instanceof K)return s;return s}async matchesPattern(e,t,s,n){if(!e)return!1;if(e.type==="Identifier"&&e.name==="_")return!0;if(e.type==="Identifier")return n[e.name]=t,!0;if(e.type==="Literal")return await this.evaluate(e,s)===t;if(e.type==="ArrayLiteral"){if(!Array.isArray(t)||e.elements.length!==t.length)return!1;for(let r=0;r<e.elements.length;r++)if(!await this.matchesPattern(e.elements[r],t[r],s,n))return!1;return!0}if(e.type==="ObjectLiteral"){if(typeof t!="object"||t===null)return!1;for(let r of e.properties)if(!(r.key in t)||!await this.matchesPattern(r.value,t[r.key],s,n))return!1;return!0}try{let r=await this.evaluate(e,s);return typeof r=="object"&&r!==null&&typeof t=="object"&&t!==null?JSON.stringify(r)===JSON.stringify(t):r===t}catch{return!1}}async evaluateInMatchBody(e,t){let s=new P(t);return Array.isArray(e)?await this.evaluateBlock(e,s):await this.evaluate(e,s)}async callAI(e,t,s,n,r){let m=ce.getModelsByProvider(this.options.provider).some(w=>w.id===e);if(!e||!m&&this.options.provider!=="custom"){let w=ce.getDefaultModelForProvider(this.options.provider);w&&(e=w.id)}return this.options.provider==="openai"||this.options.provider==="custom"?this.callOpenAICompatible(e,t,s,n,r):this.options.provider==="anthropic"?this.callAnthropicAI(e,t,s,n,r):this.options.provider==="webllm"?this.callWebLLM(e,t,s,n,r):this.callGeminiAI(e,t,s,n,r)}async manageHistory(){this.history.length>this.memoryLimit*2&&(this.summarizeHistory&&this.ai?await this.summarizeOlderHistory():this.history=this.history.slice(-this.memoryLimit*2))}async summarizeOlderHistory(){let e=this.memoryLimit*2,t=this.history.slice(0,-e),s=this.history.slice(-e);if(t.length===0)return;this.onPrint(`[Memory] Summarizing ${Math.floor(t.length/2)} older turns to manage context...`);let n=`Summarize the following conversation history briefly but comprehensively. Focus on key facts, user preferences, and decisions made. This summary will be used as context for future turns. Keep the summary under 300 words.
159
+
160
+ `+t.map(r=>{let a=r.parts.map(m=>m.text||(m.functionCall?`[Call ${m.functionCall.name}]`:"")).join(" ");return`${r.role.toUpperCase()}: ${a}`}).join(`
161
+ `);try{let a=(await this.callAI(this.options.model||"gemini-3-flash-preview",[{role:"user",parts:[{text:n}]}],{})).text;this.history=[{role:"user",parts:[{text:`[CONVERSATION SUMMARY: ${a}]`}]},{role:"model",parts:[{text:"I have noted the summary of our previous conversation. How can I help you further?"}]},...s],this.onPrint("[Memory] History summarized successfully.")}catch(r){this.onPrint(`[Memory Warning] Summarization failed: ${r.message}. Falling back to pruning.`),this.history=s}}async callGeminiAI(e,t,s,n,r){if(!this.ai)throw new Error("GoogleGenAI is not initialized.");r?.some(w=>w.googleMaps)&&!e.startsWith("gemini-3")&&(e="gemini-3-flash-preview");let a={model:e,config:{temperature:s.temperature,topK:s.topK,topP:s.topP,systemInstruction:this.systemPrompt}};e.includes("gemini-3")&&(a.config.thinkingConfig={thinkingLevel:Ue.ThinkingLevel.LOW}),s.schema&&!r?.some(w=>w.googleMaps)&&(a.config.responseMimeType="application/json",a.config.responseSchema=this.convertToGeminiSchema(s.schema));let m=[];if(n&&n.length>0){let w=n.map(v=>this.convertToGeminiFunctionDeclaration(v));m.push({functionDeclarations:w})}r&&r.length>0&&m.push(...r),m.length>0&&(a.config.tools=m,n&&n.length>0&&(a.config.toolConfig={functionCallingConfig:{mode:"AUTO"}}));try{let w=await this.ai.models.generateContent({...a,contents:t}),v=w.text;return!v&&w.candidates?.[0]?.content?.parts&&(v=w.candidates[0].content.parts.filter(T=>T.text).map(T=>T.text).join("")),{text:v,functionCalls:w.functionCalls,parts:w.candidates?.[0]?.content?.parts||[],usage:w.usageMetadata,groundingMetadata:w.candidates?.[0]?.groundingMetadata}}catch(w){throw console.error("Gemini generateContent failed:",w),w}}async callAnthropicAI(e,t,s,n,r){if(!this.options.apiKey)throw new Error("API Key is required for Anthropic provider.");let a=[],m=this.systemPrompt||"";for(let O of t)O.role==="model"?a.push({role:"assistant",content:O.parts[0].text}):O.role==="user"?a.push({role:"user",content:O.parts[0].text}):O.role==="system"&&(m+=(m?`
162
+ `:"")+O.parts[0].text);let w={"x-api-key":this.options.apiKey,"anthropic-version":"2023-06-01","content-type":"application/json","dangerously-allow-browser":"true"},v={model:e||"claude-3-opus-20240229",messages:a,max_tokens:1024,temperature:s.temperature,system:m},T=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:w,body:JSON.stringify(v),signal:s.signal});if(!T.ok){let O=await T.text();throw new Error(`Anthropic API Error (${T.status}): ${O}`)}let M=await T.json();return{text:M.content[0].text,parts:[{text:M.content[0].text}],usage:M.usage}}async callWebLLM(e,t,s,n,r){this.webllmEngine?this.currentWebLLMModel!==e&&(this.onPrint(`[WebLLM] Switching model to: ${e}...`),await this.webllmEngine.reload(e),this.currentWebLLMModel=e):(this.onPrint(`[WebLLM] Initializing engine for model: ${e}... This may take a while to download weights.`),this.webllmEngine=await webllm.CreateMLCEngine(e,{initProgressCallback:M=>{M.progress===1&&this.onPrint("[WebLLM] Model loaded successfully.")}}),this.currentWebLLMModel=e);let a=[];s.systemInstruction&&a.push({role:"system",content:s.systemInstruction});for(let M of t)if(M.role==="user"){let O=M.parts.map($=>$.text).join(`
163
+ `);a.push({role:"user",content:O})}else if(M.role==="model"){let O=M.parts.map($=>$.text).join(`
164
+ `);a.push({role:"assistant",content:O})}let m={messages:a,temperature:s.temperature??.7,top_p:s.topP??.95};n&&n.length>0&&(m.tools=n.map(M=>({type:"function",function:this.convertToOpenAIFunctionDeclaration(M)}))),s.schema&&(m.response_format={type:"json_object",schema:this.convertToOpenAISchema(s.schema)}),this.onPrint("[WebLLM] Generating response...");let w=await this.webllmEngine.chat.completions.create(m),v=w.choices[0].message,T=null;return v.tool_calls&&v.tool_calls.length>0&&(T=v.tool_calls.map(M=>({name:M.function.name,args:JSON.parse(M.function.arguments),id:M.id}))),{text:v.content||"",functionCalls:T,parts:v.tool_calls?[{text:v.content||""},...v.tool_calls.map(M=>({functionCall:{name:M.function.name,args:JSON.parse(M.function.arguments)}}))]:[{text:v.content||""}],usage:w.usage}}async callOpenAICompatible(e,t,s,n,r){let a=this.options.baseUrl||"https://api.openai.com/v1",m=[];m.push({role:"system",content:(this.systemPrompt||"")+" You are the Helios AI engine. If a JSON schema is provided, you MUST return a valid JSON object matching that schema exactly. Do NOT wrap the JSON in a top-level property or code blocks. If NO schema is provided, return a plain text response. Always use the provided context items to inform your response."});for(let N of t)if(N.role==="model")N.parts&&N.parts[0].functionCall?m.push({role:"assistant",content:null,tool_calls:N.parts.map((L,H)=>({id:L.functionCall.id||`call_${H}_${Date.now()}`,type:"function",function:{name:L.functionCall.name,arguments:JSON.stringify(L.functionCall.args)}}))}):m.push({role:"assistant",content:N.parts[0].text});else if(N.role==="tool")for(let L of N.parts)m.push({role:"tool",tool_call_id:L.functionResponse.id||`call_0_${Date.now()}`,name:L.functionResponse.name,content:JSON.stringify(L.functionResponse.response)});else m.push({role:N.role,content:N.parts[0].text});let w={model:e||"gpt-4o",messages:m,temperature:s.temperature,top_p:s.topP};s.schema&&(w.response_format={type:"json_schema",json_schema:{name:"response",schema:this.convertToOpenAISchema(s.schema),strict:!0}}),n&&n.length>0&&(w.tools=n.map(N=>({type:"function",function:this.convertToOpenAIFunctionDeclaration(N)})));let v={"Content-Type":"application/json"};this.options.apiKey&&(v.Authorization=`Bearer ${this.options.apiKey}`);let T=await fetch(`${a}/chat/completions`,{method:"POST",headers:v,body:JSON.stringify(w),signal:s.signal});if(!T.ok){let N=await T.text();throw new Error(`OpenAI/Compatible API Error (${T.status}): ${N}`)}let M=await T.json(),$=M.choices[0].message,D;return $.tool_calls&&(D=$.tool_calls.map(N=>({name:N.function.name,args:JSON.parse(N.function.arguments),id:N.id}))),{text:$.content,functionCalls:D,parts:$.tool_calls?[{text:$.content||""},...$.tool_calls.map(N=>({functionCall:{name:N.function.name,args:JSON.parse(N.function.arguments),id:N.id}}))]:[{text:$.content||""}],usage:M.usage}}convertToOpenAISchema(e){if(!e)return{type:"string"};if(typeof e=="string"){switch(e){case"Int":return{type:"integer"};case"Float":return{type:"number"};case"Bool":return{type:"boolean"};case"String":return{type:"string"}}let t=this.globalTypes.get(e);return t?this.convertToOpenAISchema(t):{type:"string"}}if(e.type==="ArrayType")return{type:"array",items:this.convertToOpenAISchema(e.elementType)};if(e.type==="ObjectType"){let t={},s=[];for(let[n,r]of Object.entries(e.fields))t[n]=this.convertToOpenAISchema(r),s.push(n);return{type:"object",properties:t,required:s,additionalProperties:!1}}if(e.type==="TypeReference"){let t=this.globalTypes.get(e.name);return t?this.convertToOpenAISchema(t):{type:"string"}}return{type:"string"}}convertToOpenAIFunctionDeclaration(e){let t={type:"object",properties:{},required:[],additionalProperties:!1};for(let s of e.params)t.properties[s.name]=this.convertToOpenAISchema(s.typeAnnotation),t.required.push(s.name);return{name:e.name,description:`Function ${e.name}`,parameters:t,strict:!0}}convertToGeminiFunctionDeclaration(e){let t={type:"OBJECT",properties:{},required:[]};for(let s of e.params)t.properties[s.name]=this.convertToGeminiSchema(s.typeAnnotation),t.required.push(s.name);return{name:e.name,description:`Function ${e.name}`,parameters:t}}convertToGeminiSchema(e){if(!e)return{type:"STRING"};if(typeof e=="string"){switch(e){case"Int":return{type:"INTEGER"};case"Float":return{type:"NUMBER"};case"Bool":return{type:"BOOLEAN"};case"String":return{type:"STRING"}}let t=this.globalTypes.get(e);return t?this.convertToGeminiSchema(t):{type:"STRING"}}if(e.type==="ArrayType")return{type:"ARRAY",items:this.convertToGeminiSchema(e.elementType)};if(e.type==="ObjectType"){let t={},s=[];for(let[n,r]of Object.entries(e.fields))t[n]=this.convertToGeminiSchema(r),s.push(n);return{type:"OBJECT",properties:t,required:s}}if(e.type==="TypeReference"){let t=this.globalTypes.get(e.name);return t?this.convertToGeminiSchema(t):{type:"STRING",description:`Type: ${e.name}`}}return{type:"STRING"}}};var oe=class extends Error{code;constructor(e,t){super(e),this.name="HeliosSDKError",this.code=t}},De=class extends oe{constructor(e){super(e,"CONFIG_ERROR"),this.name="HeliosConfigError"}},He=class extends oe{line;col;sourceHint;constructor(e,t,s,n){super(e,"EXECUTION_ERROR"),this.name="HeliosExecutionError",this.line=t,this.col=s,this.sourceHint=n}},ue=class extends oe{constructor(){super("Operation was cancelled","CANCELLED"),this.name="HeliosCancelledError"}},Be=class{_store=new Map;async store(e,t,s){this._store.set(e,{key:e,text:t,metadata:s,timestamp:Date.now()})}async search(e,t=5){let s=[],n=e.toLowerCase();for(let r of this._store.values()){let a=r.text.toLowerCase(),m=n.split(/\s+/),w=0;for(let v of m)a.includes(v)&&w++;w>0&&s.push({key:r.key,text:r.text,score:w/m.length,metadata:r.metadata})}return s.sort((r,a)=>a.score-r.score).slice(0,t)}get(e){return this._store.get(e)}has(e){return this._store.has(e)}delete(e){return this._store.delete(e)}clear(){this._store.clear()}get size(){return this._store.size}export(){return Array.from(this._store.values())}import(e){for(let t of e)this._store.set(t.key,t)}},qe=class{id;helios;history=[];context=new Map;systemPrompt;historyLimit;abortController=null;constructor(e,t={}){if(this.id=`session_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,this.helios=e,this.systemPrompt=t.systemPrompt||e.getConfig().systemPrompt||"",this.historyLimit=t.historyLimit||e.getConfig().memoryLimit||100,t.context)for(let[s,n]of Object.entries(t.context))this.context.set(s,n)}async prompt(e,t={}){this.abortController=new AbortController,this.history.push({role:"user",content:e,timestamp:Date.now()});let s="";this.systemPrompt&&(s+=`// System: ${this.systemPrompt}
165
+ `);for(let[n,r]of this.context.entries()){let a=typeof r=="string"?`"${r}"`:JSON.stringify(r);s+=`let ${n} = ${a}
166
+ `}s+=`let __result = await prompt("${e.replace(/"/g,'\\"')}")`,t.model&&(s+=` using "${t.model}"`),s+=`
167
+ __result`;try{if(this.abortController.signal.aborted)throw new ue;let n=await this.helios.run(s),r=typeof n=="string"?n:JSON.stringify(n);return this.history.push({role:"assistant",content:r,timestamp:Date.now()}),this.trimHistory(),r}finally{this.abortController=null}}async run(e){this.abortController=new AbortController;try{if(this.abortController.signal.aborted)throw new ue;let t={};for(let[s,n]of this.context.entries())t[s]=n;return await this.helios.run(e,t)}finally{this.abortController=null}}getHistory(){return[...this.history]}clearHistory(){this.history=[]}setSystemPrompt(e){this.systemPrompt=e}addContext(e,t){this.context.set(e,t)}removeContext(e){return this.context.delete(e)}clearContext(){this.context.clear()}getContext(){let e={};for(let[t,s]of this.context.entries())e[t]=s;return e}abort(){this.abortController&&this.abortController.abort()}trimHistory(){for(;this.history.length>this.historyLimit;)this.history.shift()}},We=class{name;helios;config;tools=new Map;history=[];isRegistered=!1;constructor(e,t,s){this.name=t,this.helios=e,this.config=s}async register(){if(this.isRegistered)return;let e=this.config.tools||[],t=`
168
+ swarm.createAgent("${this.name}", "${this.config.prompt.replace(/"/g,'\\"')}")
169
+ ${this.config.model?`swarm.setAgentModel("${this.name}", "${this.config.model}")`:""}
170
+ ${e.map(s=>`swarm.addTool("${this.name}", "${s}")`).join(`
171
+ `)}
172
+ `;await this.helios.run(t),this.isRegistered=!0}async delegate(e){this.isRegistered||await this.register();let t=`await swarm.delegate("${this.name}", "${e.replace(/"/g,'\\"')}")`,s=await this.helios.run(t);return this.history.push({role:"user",content:e,timestamp:Date.now()},{role:"assistant",content:String(s),timestamp:Date.now()}),this.helios.emit("agent_delegate",{from:"sdk",to:this.name,task:e,result:String(s)}),String(s)}addTool(e,t,s){let n={name:e,description:s?.description||`Tool: ${e}`,params:s?.params||[],returnType:s?.returnType||"Unknown"};this.tools.set(e,{fn:t,metadata:n}),this.helios.registerTool(e,t,n),this.isRegistered&&this.helios.run(`swarm.addTool("${this.name}", "${e}")`).catch(()=>{})}removeTool(e){let t=this.tools.delete(e);return t&&this.isRegistered&&this.helios.run(`swarm.removeTool("${this.name}", "${e}")`).catch(()=>{}),t}listTools(){return Array.from(this.tools.keys())}setModel(e){this.config.model=e,this.isRegistered&&this.helios.run(`swarm.setAgentModel("${this.name}", "${e}")`).catch(()=>{})}getHistory(){return[...this.history]}clearHistory(){this.history=[]}getConfig(){return{...this.config}}},pe=class{config;tools={};toolMetadata=new Map;modules={};listeners=new Map;middleware=[];sessions=new Map;agents=new Map;memory;evaluator=null;constructor(e={}){this.config={provider:"gemini",maxLoopIterations:1e6,memoryLimit:100,dryRun:!1,...e},this.memory=new Be,this.middleware=e.middleware||[];let t=["print","error","trace","tool_call","agent_delegate","prompt_start","prompt_end"];for(let s of t)this.listeners.set(s,new Set)}getConfig(){return{...this.config}}updateConfig(e){this.config={...this.config,...e},this.evaluator=null}on(e,t){let s=this.listeners.get(e);return s&&s.add(t),this}off(e,t){let s=this.listeners.get(e);return s&&s.delete(t),this}removeAllListeners(e){if(e)this.listeners.get(e)?.clear();else for(let t of this.listeners.values())t.clear();return this}emit(e,t){let s=this.listeners.get(e);if(s)for(let n of s)try{n(t)}catch(r){console.error(`[Helios] Error in ${e} handler:`,r)}}use(e){return this.middleware.push(e),this}removeMiddleware(e){let t=this.middleware.findIndex(s=>s.name===e);return t>=0?(this.middleware.splice(t,1),!0):!1}async runBeforePromptMiddleware(e){let t=e;for(let s of this.middleware)if(s.beforePrompt){let n=await s.beforePrompt(t);n&&(t=n)}return t}async runAfterPromptMiddleware(e,t){let s=t;for(let n of this.middleware)if(n.afterPrompt){let r=await n.afterPrompt(e,s);r&&(s=r)}return s}async notifyToolCallMiddleware(e,t){for(let s of this.middleware)s.onToolCall&&await s.onToolCall(e,t)}async notifyErrorMiddleware(e){for(let t of this.middleware)t.onError&&await t.onError(e)}registerTool(e,t,s){let n={name:e,description:s?.description||`Tool: ${e}`,params:s?.params||V.inferParams(t).map(a=>({name:a.name,type:a.type})),returnType:s?.returnType||"Unknown"},r=async(...a)=>{await this.notifyToolCallMiddleware(e,a),this.emit("tool_call",{name:e,args:a});try{return await t(...a)}catch(m){let w=m instanceof Error?m:new Error(String(m));throw await this.notifyErrorMiddleware(w),w}};return this.tools[e]=V.wrap(r,{name:e,...s}),this.toolMetadata.set(e,n),this.evaluator=null,this}unregisterTool(e){return this.tools[e]?(delete this.tools[e],this.toolMetadata.delete(e),this.evaluator=null,!0):!1}listTools(){return Array.from(this.toolMetadata.values())}registerModule(e,t){return this.modules[e]=t,this.evaluator=null,this}unregisterModule(e){return this.modules[e]?(delete this.modules[e],this.evaluator=null,!0):!1}async run(e,t={}){try{let n=new ee(e).tokenize(),a=new te(n,e).parse();new Fe({tools:this.tools,modules:this.modules}).check(a),this.ensureEvaluator();for(let[v,T]of Object.entries(t))this.evaluator.globalEnv.define(v,T);return await this.evaluator.evaluate(a)}catch(s){let n=s instanceof Error?s:new Error(String(s));throw this.emit("error",n),await this.notifyErrorMiddleware(n),s.line!==void 0?new He(n.message,s.line,s.col,s.hint):n}}createSession(e){let t=new qe(this,e);return this.sessions.set(t.id,t),t}getSession(e){return this.sessions.get(e)}listSessions(){return Array.from(this.sessions.keys())}destroySession(e){let t=this.sessions.get(e);return t?(t.abort(),t.clearHistory(),t.clearContext(),this.sessions.delete(e)):!1}createAgent(e,t){if(this.agents.has(e))throw new De(`Agent "${e}" already exists. Use getAgent() or destroyAgent() first.`);let s=new We(this,e,t);return this.agents.set(e,s),s}getAgent(e){return this.agents.get(e)}listAgents(){return Array.from(this.agents.keys())}destroyAgent(e){let t=this.agents.get(e);return t?(t.clearHistory(),this.agents.delete(e)):!1}getMemory(){return this.memory}reset(){this.evaluator=null;for(let e of this.sessions.values())e.abort();this.sessions.clear(),this.agents.clear(),this.memory.clear()}resetRuntime(){this.evaluator=null}ensureEvaluator(){if(this.evaluator)return;this.evaluator=new je((...t)=>{t.length===1&&typeof t[0]=="object"&&t[0]!==null?this.emit("print",t[0]):this.emit("print",t.map(s=>typeof s=="object"?JSON.stringify(s):String(s)).join(" "))},{...this.config,tools:this.tools,modules:this.modules,onInputRequest:this.config.onInputRequest});let e=this.evaluator.addTrace.bind(this.evaluator);this.evaluator.addTrace=t=>{e(t),this.emit("trace",t)}}},Ye=class{config={};toolRegistrations=[];moduleRegistrations=[];middlewareStack=[];eventHandlers=[];provider(e){return this.config.provider=e,this}apiKey(e){return this.config.apiKey=e,this}model(e){return this.config.model=e,this}baseUrl(e){return this.config.baseUrl=e,this}systemPrompt(e){return this.config.systemPrompt=e,this}temperature(e){return this.config.temperature=e,this}memoryLimit(e){return this.config.memoryLimit=e,this}maxLoopIterations(e){return this.config.maxLoopIterations=e,this}dryRun(e=!0){return this.config.dryRun=e,this}onInputRequest(e){return this.config.onInputRequest=e,this}tool(e,t,s){return this.toolRegistrations.push({name:e,fn:t,metadata:s}),this}module(e,t){return this.moduleRegistrations.push({name:e,exports:t}),this}use(e){return this.middlewareStack.push(e),this}on(e,t){return this.eventHandlers.push({event:e,handler:t}),this}build(){this.config.middleware=this.middlewareStack;let e=new pe(this.config);for(let{name:t,fn:s,metadata:n}of this.toolRegistrations)e.registerTool(t,s,n);for(let{name:t,exports:s}of this.moduleRegistrations)e.registerModule(t,s);for(let{event:t,handler:s}of this.eventHandlers)e.on(t,s);return e}};function it(){return new Ye}function ot(u){return new pe(u)}0&&(module.exports={Helios,HeliosAgent,HeliosBuilder,HeliosCancelledError,HeliosConfigError,HeliosExecutionError,HeliosMemory,HeliosSDKError,HeliosSession,createHelios,helios});
173
+ //# sourceMappingURL=sdk.cjs.map