gauss-ts 2.0.0 → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,7 @@
1
- "use strict";var y=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var x=Object.getOwnPropertyNames;var b=Object.prototype.hasOwnProperty;var C=(n,t)=>{for(var e in t)y(n,e,{get:t[e],enumerable:!0})},R=(n,t,e,h)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of x(t))!b.call(n,o)&&o!==e&&y(n,o,{get:()=>t[o],enumerable:!(h=D(t,o))||h.enumerable});return n};var S=n=>R(y({},"__esModule",{value:!0}),n);var T={};C(T,{Graph:()=>g,Network:()=>m,Team:()=>_,Workflow:()=>u});module.exports=S(T);var s=require("gauss-napi"),g=class{_handle;disposed=!1;_nodes=new Map;_edges=new Map;_conditionalEdges=new Map;constructor(){this._handle=(0,s.create_graph)()}get handle(){return this._handle}addNode(t){return this.assertNotDisposed(),(0,s.graph_add_node)(this._handle,t.nodeId,t.agent.name,t.agent.handle,t.instructions,t.tools??[]),this._nodes.set(t.nodeId,{agent:t.agent,instructions:t.instructions}),this}addFork(t){return this.assertNotDisposed(),(0,s.graph_add_fork_node)(this._handle,t.nodeId,t.agents.map(e=>({agentName:e.agent.name,providerHandle:e.agent.handle,instructions:e.instructions})),t.consensus??"concat"),this}addEdge(t,e){return this.assertNotDisposed(),(0,s.graph_add_edge)(this._handle,t,e),this._edges.set(t,e),this}addConditionalEdge(t,e){return this.assertNotDisposed(),this._conditionalEdges.set(t,e),this}async run(t){return this.assertNotDisposed(),this._conditionalEdges.size===0?(0,s.graph_run)(this._handle,t):this._runWithConditionals(t)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,s.destroy_graph)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}async _runWithConditionals(t){let e=new Set([...this._edges.values()]),h=[...this._nodes.keys()].filter(p=>!e.has(p));if(h.length===0)throw new Error("Graph has no entry node (every node has an incoming edge)");let o={},a=h[0],c=t;for(;a;){let p=this._nodes.get(a);if(!p)throw new Error(`Node "${a}" not found in graph`);let N=p.instructions?`${p.instructions}
1
+ "use strict";var R=Object.defineProperty;var L=Object.getOwnPropertyDescriptor;var U=Object.getOwnPropertyNames;var F=Object.prototype.hasOwnProperty;var Y=(o,e)=>{for(var t in e)R(o,t,{get:e[t],enumerable:!0})},j=(o,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of U(e))!F.call(o,r)&&r!==t&&R(o,r,{get:()=>e[r],enumerable:!(s=L(e,r))||s.enumerable});return o};var $=o=>j(R({},"__esModule",{value:!0}),o);var se={};Y(se,{Graph:()=>x,Network:()=>b,Team:()=>k,Workflow:()=>T});module.exports=$(se);var l=require("gauss-napi");var f=class extends Error{code;constructor(e,t){super(t),this.name="GaussError",this.code=e}},g=class extends f{resourceType;resourceName;constructor(e,t){super("RESOURCE_DISPOSED",`${e} "${t}" has been destroyed. Create a new instance.`),this.name="DisposedError",this.resourceType=e,this.resourceName=t}};var y=class extends f{field;constructor(e,t){super("VALIDATION_ERROR",t?`Invalid "${t}": ${e}`:e),this.name="ValidationError",this.field=t}};var x=class o{static pipeline(e){let t=new o;for(let s of e)t.addNode(s);for(let s=0;s<e.length-1;s++)t.addEdge(e[s].nodeId,e[s+1].nodeId);return t}_handle;disposed=!1;_nodes=new Map;_edges=new Map;_conditionalEdges=new Map;constructor(){this._handle=(0,l.create_graph)()}get handle(){return this._handle}addNode(e){return this.assertNotDisposed(),(0,l.graph_add_node)(this._handle,e.nodeId,e.agent.name,e.agent.handle,e.instructions,e.tools??[]),this._nodes.set(e.nodeId,{agent:e.agent,instructions:e.instructions}),this}addFork(e){return this.assertNotDisposed(),(0,l.graph_add_fork_node)(this._handle,e.nodeId,e.agents.map(t=>({agentName:t.agent.name,providerHandle:t.agent.handle,instructions:t.instructions})),e.consensus??"concat"),this}addEdge(e,t){return this.assertNotDisposed(),(0,l.graph_add_edge)(this._handle,e,t),this._edges.set(e,t),this}addConditionalEdge(e,t){return this.assertNotDisposed(),this._conditionalEdges.set(e,t),this}async run(e){return this.assertNotDisposed(),this._conditionalEdges.size===0?(0,l.graph_run)(this._handle,e):this._runWithConditionals(e)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,l.destroy_graph)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}async _runWithConditionals(e){let t=new Set([...this._edges.values()]),s=[...this._nodes.keys()].filter(h=>!t.has(h));if(s.length===0)throw new y("Graph has no entry node (every node has an incoming edge)");let r={},n=s[0],i=e;for(;n;){let h=this._nodes.get(n);if(!h)throw new y(`Node "${n}" not found in graph`);let K=h.instructions?`${h.instructions}
2
2
 
3
- ${c}`:c,l=await p.agent.run(N),w={text:l.text,...l.structuredOutput?{structuredOutput:l.structuredOutput}:{}};o[a]=w;let k=this._conditionalEdges.get(a);k?a=await k(w):a=this._edges.get(a),c=l.text}let f=Object.keys(o),v=f[f.length-1];return{outputs:o,final_text:o[v]?.text??""}}assertNotDisposed(){if(this.disposed)throw new Error("Graph has been destroyed")}};var i=require("gauss-napi"),u=class{_handle;disposed=!1;constructor(){this._handle=(0,i.create_workflow)()}get handle(){return this._handle}addStep(t){return this.assertNotDisposed(),(0,i.workflow_add_step)(this._handle,t.stepId,t.agent.name,t.agent.handle,t.instructions,t.tools??[]),this}addDependency(t,e){return this.assertNotDisposed(),(0,i.workflow_add_dependency)(this._handle,t,e),this}async run(t){return this.assertNotDisposed(),(0,i.workflow_run)(this._handle,t)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,i.destroy_workflow)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Workflow has been destroyed")}};var d=require("gauss-napi"),_=class{_handle;disposed=!1;agents=[];constructor(t){this._handle=(0,d.create_team)(t)}get handle(){return this._handle}add(t,e){return this.assertNotDisposed(),(0,d.team_add_agent)(this._handle,t.name,t.handle,e),this.agents.push(t),this}strategy(t){return this.assertNotDisposed(),(0,d.team_set_strategy)(this._handle,t),this}async run(t){this.assertNotDisposed();let e=JSON.stringify([{role:"user",content:[{type:"text",text:t}]}]);return(0,d.team_run)(this._handle,e)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,d.destroy_team)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Team has been destroyed")}};var r=require("gauss-napi"),m=class{_handle;disposed=!1;constructor(){this._handle=(0,r.create_network)()}get handle(){return this._handle}addAgent(t,e){return this.assertNotDisposed(),(0,r.network_add_agent)(this._handle,t.name,t.handle,e),this}setSupervisor(t){return this.assertNotDisposed(),(0,r.network_set_supervisor)(this._handle,t),this}async delegate(t,e,h){return this.assertNotDisposed(),(0,r.network_delegate)(this._handle,t,e,h)}agentCards(){return this.assertNotDisposed(),(0,r.network_agent_cards)(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,r.destroy_network)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Network has been destroyed")}};0&&(module.exports={Graph,Network,Team,Workflow});
3
+ ${i}`:i,_=await h.agent.run(K),A={text:_.text,..._.structuredOutput?{structuredOutput:_.structuredOutput}:{}};r[n]=A;let D=this._conditionalEdges.get(n);D?n=await D(A):n=this._edges.get(n),i=_.text}let a=Object.keys(r),p=a[a.length-1];return{outputs:r,final_text:r[p]?.text??""}}assertNotDisposed(){if(this.disposed)throw new g("Graph","graph")}};var c=require("gauss-napi"),T=class{_handle;disposed=!1;constructor(){this._handle=(0,c.create_workflow)()}get handle(){return this._handle}addStep(e){return this.assertNotDisposed(),(0,c.workflow_add_step)(this._handle,e.stepId,e.agent.name,e.agent.handle,e.instructions,e.tools??[]),this}addDependency(e,t){return this.assertNotDisposed(),(0,c.workflow_add_dependency)(this._handle,e,t),this}async run(e){return this.assertNotDisposed(),(0,c.workflow_run)(this._handle,e)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,c.destroy_workflow)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Workflow has been destroyed")}};var m=require("gauss-napi");var d=require("gauss-napi");var P="gpt-5.2";var J="claude-sonnet-4-20250514";var W="gemini-2.5-flash";var X="openai/gpt-5.2",q="deepseek-chat";var B="meta-llama/Llama-3.3-70B-Instruct-Turbo",V="accounts/fireworks/models/llama-v3p1-70b-instruct",z="mistral-large-latest",Q="sonar-pro",Z="grok-3-beta",O={openai:P,anthropic:J,google:W,openrouter:X,deepseek:q,groq:"llama-3.3-70b-versatile",ollama:"llama3.2",together:B,fireworks:V,mistral:z,perplexity:Q,xai:Z};var ee={openai:"OPENAI_API_KEY",anthropic:"ANTHROPIC_API_KEY",google:"GOOGLE_API_KEY",groq:"GROQ_API_KEY",deepseek:"DEEPSEEK_API_KEY",openrouter:"OPENROUTER_API_KEY",together:"TOGETHER_API_KEY",fireworks:"FIREWORKS_API_KEY",mistral:"MISTRAL_API_KEY",perplexity:"PERPLEXITY_API_KEY",xai:"XAI_API_KEY",ollama:""};function I(o){let e=ee[o]??"";return e?(typeof process<"u"?process.env[e]:"")??"":""}function C(){let o=[{env:"OPENAI_API_KEY",provider:"openai"},{env:"ANTHROPIC_API_KEY",provider:"anthropic"},{env:"GOOGLE_API_KEY",provider:"google"},{env:"GROQ_API_KEY",provider:"groq"},{env:"DEEPSEEK_API_KEY",provider:"deepseek"},{env:"OPENROUTER_API_KEY",provider:"openrouter"},{env:"TOGETHER_API_KEY",provider:"together"},{env:"FIREWORKS_API_KEY",provider:"fireworks"},{env:"MISTRAL_API_KEY",provider:"mistral"},{env:"PERPLEXITY_API_KEY",provider:"perplexity"},{env:"XAI_API_KEY",provider:"xai"}];for(let{env:e,provider:t}of o)if(typeof process<"u"&&process.env[e])return{provider:t,model:O[t]}}var S=require("gauss-napi");function te(o){return{...o,citations:o.citations?.map(e=>({type:e.citationType??e.type,citedText:e.citedText,documentTitle:e.documentTitle,start:e.start,end:e.end}))}}var v=class{constructor(e,t,s,r,n,i){this.agentName=e;this.providerHandle=t;this.tools=s;this.messages=r;this.options=n;this.toolExecutor=i}_result;get result(){return this._result}async*[Symbol.asyncIterator](){let e=[],t,s=!1,r=i=>{try{e.push(JSON.parse(i))}catch{e.push({type:"raw",text:i})}t?.()},n=(0,S.agent_stream_with_tool_executor)(this.agentName,this.providerHandle,this.tools,this.messages,this.options,r,this.toolExecutor).then(i=>{this._result=te(i),s=!0,t?.()});for(;!s||e.length>0;)e.length>0?yield e.shift():s||await new Promise(i=>{t=i});await n}};function N(o){return{name:o.name,description:o.description,parameters:o.parameters,execute:o.execute}}function M(o){return typeof o.execute=="function"}function G(o,e){let t=new Map(o.map(s=>[s.name,s]));return async s=>{let r;try{r=JSON.parse(s)}catch{return JSON.stringify({error:"Invalid tool call JSON"})}let n=r.tool??r.name??"",i=t.get(n);if(!i)return e?e(s):JSON.stringify({error:`Unknown tool: ${n}`});try{let a=r.args??r.arguments??{},p=await i.execute(a);return typeof p=="string"?p:JSON.stringify(p)}catch(a){let p=a instanceof Error?a.message:String(a);return JSON.stringify({error:`Tool "${n}" failed: ${p}`})}}}function E(o){return{...o,citations:o.citations?.map(e=>({type:e.citationType??e.type??"unknown",citedText:e.citedText,documentTitle:e.documentTitle,start:e.start,end:e.end}))}}var w=class o{providerHandle;_name;_provider;_model;_providerOptions;_instructions;_tools=[];_options={};disposed=!1;_middleware=null;_guardrails=null;_memory=null;_sessionId="";_mcpClients=[];_mcpToolsLoaded=!1;constructor(e={}){let t=C();this._provider=e.provider??t?.provider??"openai",this._model=e.model??t?.model??P,this._name=e.name??"agent",this._instructions=e.instructions??"";let s=e.providerOptions?.apiKey??I(this._provider);this._providerOptions={apiKey:s,...e.providerOptions},this.providerHandle=(0,d.create_provider)(this._provider,this._model,this._providerOptions),e.tools&&(this._tools=[...e.tools]),e.middleware&&(this._middleware=e.middleware),e.guardrails&&(this._guardrails=e.guardrails),e.memory&&(this._memory=e.memory),e.sessionId&&(this._sessionId=e.sessionId),e.mcpClients&&(this._mcpClients=[...e.mcpClients]);let r=e.codeExecution,n=r===!0?{python:!0,javascript:!0,bash:!0}:r||void 0;this._options={instructions:this._instructions||void 0,temperature:e.temperature,maxSteps:e.maxSteps,topP:e.topP,maxTokens:e.maxTokens,seed:e.seed,stopOnTool:e.stopOnTool,outputSchema:e.outputSchema,thinkingBudget:e.thinkingBudget,reasoningEffort:e.reasoningEffort,cacheControl:e.cacheControl,codeExecution:n,grounding:e.grounding,nativeCodeExecution:e.nativeCodeExecution,responseModalities:e.responseModalities}}static fromEnv(e={}){return new o(e)}get name(){return this._name}get provider(){return this._provider}get model(){return this._model}get instructions(){return this._instructions}get handle(){return this.providerHandle}get capabilities(){return(0,d.get_provider_capabilities)(this.providerHandle)}addTool(e){return this._tools.push(e),this}addTools(e){return this._tools.push(...e),this}withTool(e,t,s,r){return this._tools.push(N({name:e,description:t,parameters:r??{},execute:s})),this}setOptions(e){return this._options={...this._options,...e},this}withModel(e){return this.assertNotDisposed(),new o({...this.toConfig(),model:e})}withMiddleware(e){return this._middleware=e,this}withGuardrails(e){return this._guardrails=e,this}withMemory(e,t){return this._memory=e,t&&(this._sessionId=t),this}useMcpServer(e){return this._mcpClients.push(e),this._mcpToolsLoaded=!1,this}async run(e){this.assertNotDisposed(),await this.ensureMcpTools();let t=typeof e=="string"?[{role:"user",content:e}]:[...e];if(this._memory){let i=await this._memory.recall(this._sessionId?{sessionId:this._sessionId}:void 0);i.length>0&&(t=[{role:"system",content:`Previous context:
4
+ ${i.map(p=>p.content).join(`
5
+ `)}`},...t])}let{toolDefs:s,executor:r}=this.resolveToolsAndExecutor(),n;if(r?n=E(await(0,d.agent_run_with_tool_executor)(this._name,this.providerHandle,s,t,this._options,r)):n=E(await(0,d.agent_run)(this._name,this.providerHandle,s,t,this._options)),this._memory){let i=typeof e=="string"?e:e.map(a=>a.content).join(`
6
+ `);await this._memory.store({id:`${Date.now()}-user`,content:i,entryType:"conversation",timestamp:new Date().toISOString(),sessionId:this._sessionId||void 0}),await this._memory.store({id:`${Date.now()}-assistant`,content:n.text,entryType:"conversation",timestamp:new Date().toISOString(),sessionId:this._sessionId||void 0})}return n}async runWithTools(e,t){this.assertNotDisposed(),await this.ensureMcpTools();let s=typeof e=="string"?[{role:"user",content:e}]:e,{toolDefs:r,executor:n}=this.resolveToolsAndExecutor(),i=async a=>{if(n){let p=await n(a);if(!JSON.parse(p).error?.startsWith("Unknown tool:"))return p}return t(a)};return E(await(0,d.agent_run_with_tool_executor)(this._name,this.providerHandle,r,s,this._options,i))}async stream(e,t,s){this.assertNotDisposed(),await this.ensureMcpTools();let r=typeof e=="string"?[{role:"user",content:e}]:e,{toolDefs:n,executor:i}=this.resolveToolsAndExecutor(),a=s??i??H;return E(await(0,d.agent_stream_with_tool_executor)(this._name,this.providerHandle,n,r,this._options,t,a))}streamIter(e,t){this.assertNotDisposed();let s=typeof e=="string"?[{role:"user",content:e}]:e,{toolDefs:r,executor:n}=this.resolveToolsAndExecutor(),i=t??n??H;return new v(this._name,this.providerHandle,r,s,this._options,i)}async streamText(e,t,s){this.assertNotDisposed();let r=this.streamIter(e,s),n="";for await(let i of r){if(i.type!=="text_delta")continue;let a=typeof i.text=="string"?i.text:typeof i.delta=="string"?i.delta:"";a&&(n+=a,t?.(a))}return r.result?.text??n}async generate(e,t){this.assertNotDisposed();let s=typeof e=="string"?[{role:"user",content:e}]:e;return(0,d.generate)(this.providerHandle,s,t?.temperature,t?.maxTokens)}async generateWithTools(e,t,s){this.assertNotDisposed();let r=typeof e=="string"?[{role:"user",content:e}]:e;return(0,d.generate_with_tools)(this.providerHandle,r,t,s?.temperature,s?.maxTokens)}destroy(){if(!this.disposed){this.disposed=!0;for(let e of this._mcpClients)try{e.close()}catch{}try{(0,d.destroy_provider)(this.providerHandle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new g("Agent",this._name)}resolveToolsAndExecutor(){let e=this._tools.filter(M),t=this._tools.map(r=>({name:r.name,description:r.description,parameters:r.parameters})),s=e.length>0?G(e):null;return{toolDefs:t,executor:s}}async ensureMcpTools(){if(!(this._mcpToolsLoaded||this._mcpClients.length===0)){for(let e of this._mcpClients){let{tools:t,executor:s}=await e.getToolsWithExecutor();for(let r of t){let n={...r,execute:async i=>{let a=JSON.stringify({tool:r.name,args:i}),p=await s(a);return JSON.parse(p)}};this._tools.push(n)}}this._mcpToolsLoaded=!0}}toConfig(){return{name:this._name,provider:this._provider,model:this._model,providerOptions:{...this._providerOptions},instructions:this._instructions||void 0,tools:[...this._tools],middleware:this._middleware??void 0,guardrails:this._guardrails??void 0,memory:this._memory??void 0,sessionId:this._sessionId||void 0,mcpClients:[...this._mcpClients],temperature:this._options.temperature,maxSteps:this._options.maxSteps,topP:this._options.topP,maxTokens:this._options.maxTokens,seed:this._options.seed,stopOnTool:this._options.stopOnTool,outputSchema:this._options.outputSchema,thinkingBudget:this._options.thinkingBudget,reasoningEffort:this._options.reasoningEffort,cacheControl:this._options.cacheControl,codeExecution:this._options.codeExecution,grounding:this._options.grounding,nativeCodeExecution:this._options.nativeCodeExecution,responseModalities:this._options.responseModalities}}},H=async()=>"{}";var k=class o{_handle;_name;disposed=!1;agents=[];static quick(e,t,s){let r=new o(e);for(let n of s){let i=new w({name:n.name,provider:n.provider??"openai",model:n.model??"gpt-4o",instructions:n.instructions});r.add(i)}return r.strategy(t),r}constructor(e){this._name=e,this._handle=(0,m.create_team)(e)}get handle(){return this._handle}add(e,t){return this.assertNotDisposed(),(0,m.team_add_agent)(this._handle,e.name,e.handle,t),this.agents.push(e),this}strategy(e){return this.assertNotDisposed(),(0,m.team_set_strategy)(this._handle,e),this}async run(e){this.assertNotDisposed();let t=JSON.stringify([{role:"user",content:[{type:"text",text:e}]}]);return(0,m.team_run)(this._handle,t)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,m.destroy_team)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new g("Team",this._name)}};var u=require("gauss-napi"),b=class{_handle;disposed=!1;constructor(){this._handle=(0,u.create_network)()}get handle(){return this._handle}addAgent(e,t){return this.assertNotDisposed(),(0,u.network_add_agent)(this._handle,e.name,e.handle,t),this}setSupervisor(e){return this.assertNotDisposed(),(0,u.network_set_supervisor)(this._handle,e),this}async delegate(e,t,s){return this.assertNotDisposed(),(0,u.network_delegate)(this._handle,e,t,s)}agentCards(){return this.assertNotDisposed(),(0,u.network_agent_cards)(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,u.destroy_network)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Network has been destroyed")}};0&&(module.exports={Graph,Network,Team,Workflow});
4
7
  //# sourceMappingURL=orchestration.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/orchestration.ts","../src/sdk/graph.ts","../src/sdk/workflow.ts","../src/sdk/team.ts","../src/sdk/network.ts"],"sourcesContent":["export { Graph } from \"./sdk/graph.js\";\nexport type { GraphNodeConfig, ForkNodeConfig, ConsensusStrategy, RouterFn } from \"./sdk/graph.js\";\nexport { Workflow } from \"./sdk/workflow.js\";\nexport type { WorkflowStepConfig } from \"./sdk/workflow.js\";\nexport { Team } from \"./sdk/team.js\";\nexport type { TeamStrategy, TeamResult } from \"./sdk/team.js\";\nexport { Network } from \"./sdk/network.js\";\n","/**\n * Graph — DAG-based multi-agent execution backed by Rust core.\n *\n * @example\n * const researcher = new Agent({ name: \"researcher\", instructions: \"Research topics\" });\n * const writer = new Agent({ name: \"writer\", instructions: \"Write articles\" });\n *\n * const graph = new Graph()\n * .addNode({ nodeId: \"research\", agent: researcher })\n * .addNode({ nodeId: \"write\", agent: writer })\n * .addEdge(\"research\", \"write\");\n *\n * const result = await graph.run(\"Write about quantum computing\");\n * graph.destroy();\n */\nimport {\n create_graph,\n graph_add_node,\n graph_add_edge,\n graph_add_fork_node,\n graph_run,\n destroy_graph,\n} from \"gauss-napi\";\n\nimport type { Handle, Disposable, ToolDef } from \"./types.js\";\nimport type { Agent } from \"./agent.js\";\n\n/** Router function invoked at runtime to decide the next node. */\nexport type RouterFn = (result: Record<string, unknown>) => string | Promise<string>;\n\nexport interface GraphNodeConfig {\n nodeId: string;\n agent: Agent;\n instructions?: string;\n tools?: ToolDef[];\n}\n\nexport type ConsensusStrategy = \"first\" | \"concat\";\n\nexport interface ForkNodeConfig {\n nodeId: string;\n agents: Array<{ agent: Agent; instructions?: string }>;\n consensus?: ConsensusStrategy;\n}\n\nexport class Graph implements Disposable {\n private readonly _handle: Handle;\n private disposed = false;\n\n /** Node registry for SDK-level stepping. */\n private readonly _nodes = new Map<string, { agent: Agent; instructions?: string }>();\n /** Regular edges tracked locally for SDK-level stepping. */\n private readonly _edges = new Map<string, string>();\n /** Conditional edges: source node → router function. */\n private readonly _conditionalEdges = new Map<string, RouterFn>();\n\n constructor() {\n this._handle = create_graph();\n }\n\n get handle(): Handle {\n return this._handle;\n }\n\n addNode(config: GraphNodeConfig): this {\n this.assertNotDisposed();\n graph_add_node(\n this._handle,\n config.nodeId,\n config.agent.name,\n config.agent.handle,\n config.instructions,\n config.tools ?? []\n );\n this._nodes.set(config.nodeId, {\n agent: config.agent,\n instructions: config.instructions,\n });\n return this;\n }\n\n /** Add a fork node — runs multiple agents in parallel, merging via consensus. */\n addFork(config: ForkNodeConfig): this {\n this.assertNotDisposed();\n graph_add_fork_node(\n this._handle,\n config.nodeId,\n config.agents.map(a => ({\n agentName: a.agent.name,\n providerHandle: a.agent.handle,\n instructions: a.instructions,\n })),\n config.consensus ?? \"concat\"\n );\n return this;\n }\n\n addEdge(from: string, to: string): this {\n this.assertNotDisposed();\n graph_add_edge(this._handle, from, to);\n this._edges.set(from, to);\n return this;\n }\n\n /**\n * Add a conditional edge — at runtime the router function receives the\n * source node's result and returns the ID of the next node to execute.\n */\n addConditionalEdge(from: string, router: RouterFn): this {\n this.assertNotDisposed();\n this._conditionalEdges.set(from, router);\n return this;\n }\n\n async run(prompt: string): Promise<Record<string, unknown>> {\n this.assertNotDisposed();\n\n // Fast path: no conditional edges → delegate entirely to Rust core.\n if (this._conditionalEdges.size === 0) {\n return graph_run(this._handle, prompt) as Promise<Record<string, unknown>>;\n }\n\n return this._runWithConditionals(prompt);\n }\n\n destroy(): void {\n if (!this.disposed) {\n this.disposed = true;\n try { destroy_graph(this._handle); } catch { /* ok */ }\n }\n }\n\n [Symbol.dispose](): void {\n this.destroy();\n }\n\n // ── Private ──────────────────────────────────────────────────────\n\n /** SDK-level step-through execution when conditional edges are present. */\n private async _runWithConditionals(prompt: string): Promise<Record<string, unknown>> {\n // Determine entry node: a node with no incoming edges.\n const targets = new Set<string>([\n ...this._edges.values(),\n ]);\n const entryNodes = [...this._nodes.keys()].filter(n => !targets.has(n));\n if (entryNodes.length === 0) {\n throw new Error(\"Graph has no entry node (every node has an incoming edge)\");\n }\n\n const outputs: Record<string, Record<string, unknown>> = {};\n let currentNodeId: string | undefined = entryNodes[0];\n let currentPrompt = prompt;\n\n while (currentNodeId) {\n const nodeCfg = this._nodes.get(currentNodeId);\n if (!nodeCfg) {\n throw new Error(`Node \"${currentNodeId}\" not found in graph`);\n }\n\n const agentInput = nodeCfg.instructions\n ? `${nodeCfg.instructions}\\n\\n${currentPrompt}`\n : currentPrompt;\n\n const result = await nodeCfg.agent.run(agentInput);\n const nodeOutput: Record<string, unknown> = {\n text: result.text,\n ...(result.structuredOutput ? { structuredOutput: result.structuredOutput } : {}),\n };\n outputs[currentNodeId] = nodeOutput;\n\n // Decide next node.\n const router = this._conditionalEdges.get(currentNodeId);\n if (router) {\n currentNodeId = await router(nodeOutput);\n } else {\n currentNodeId = this._edges.get(currentNodeId);\n }\n\n // Feed previous output as prompt for the next node.\n currentPrompt = result.text;\n }\n\n // Build result envelope matching graph_run shape.\n const nodeIds = Object.keys(outputs);\n const lastNodeId = nodeIds[nodeIds.length - 1];\n return {\n outputs,\n final_text: (outputs[lastNodeId]?.text as string) ?? \"\",\n };\n }\n\n private assertNotDisposed(): void {\n if (this.disposed) throw new Error(\"Graph has been destroyed\");\n }\n}\n","/**\n * Workflow SDK wrapper — dependency-based step execution backed by Rust core.\n */\nimport {\n create_workflow,\n workflow_add_step,\n workflow_add_dependency,\n workflow_run,\n destroy_workflow,\n} from \"gauss-napi\";\n\nimport type { Handle, Disposable, ToolDef } from \"./types.js\";\nimport type { Agent } from \"./agent.js\";\n\nexport interface WorkflowStepConfig {\n stepId: string;\n agent: Agent;\n instructions?: string;\n tools?: ToolDef[];\n}\n\nexport class Workflow implements Disposable {\n private readonly _handle: Handle;\n private disposed = false;\n\n constructor() {\n this._handle = create_workflow();\n }\n\n get handle(): Handle {\n return this._handle;\n }\n\n addStep(config: WorkflowStepConfig): this {\n this.assertNotDisposed();\n workflow_add_step(\n this._handle,\n config.stepId,\n config.agent.name,\n config.agent.handle,\n config.instructions,\n config.tools ?? []\n );\n return this;\n }\n\n addDependency(stepId: string, dependsOn: string): this {\n this.assertNotDisposed();\n workflow_add_dependency(this._handle, stepId, dependsOn);\n return this;\n }\n\n async run(prompt: string): Promise<Record<string, unknown>> {\n this.assertNotDisposed();\n return workflow_run(this._handle, prompt) as Promise<\n Record<string, unknown>\n >;\n }\n\n destroy(): void {\n if (!this.disposed) {\n this.disposed = true;\n try {\n destroy_workflow(this._handle);\n } catch {\n // Already destroyed.\n }\n }\n }\n\n [Symbol.dispose](): void {\n this.destroy();\n }\n\n private assertNotDisposed(): void {\n if (this.disposed) {\n throw new Error(\"Workflow has been destroyed\");\n }\n }\n}\n","/**\n * Team — multi-agent coordination backed by Rust core.\n *\n * @example\n * const researcher = new Agent({ name: \"researcher\", instructions: \"Research topics\" });\n * const writer = new Agent({ name: \"writer\", instructions: \"Write summaries\" });\n *\n * const team = new Team(\"content-team\")\n * .add(researcher)\n * .add(writer)\n * .strategy(\"sequential\");\n *\n * const result = await team.run(\"Explain quantum computing\");\n * console.log(result.finalText);\n * team.destroy();\n */\nimport {\n create_team,\n team_add_agent,\n team_set_strategy,\n team_run,\n destroy_team,\n} from \"gauss-napi\";\n\nimport type { Handle, Disposable } from \"./types.js\";\nimport type { Agent } from \"./agent.js\";\n\nexport type TeamStrategy = \"sequential\" | \"parallel\";\n\nexport interface TeamResult {\n finalText: string;\n results: Array<{\n text: string;\n steps: number;\n inputTokens: number;\n outputTokens: number;\n }>;\n}\n\nexport class Team implements Disposable {\n private readonly _handle: Handle;\n private disposed = false;\n private agents: Agent[] = [];\n\n constructor(name: string) {\n this._handle = create_team(name);\n }\n\n get handle(): Handle {\n return this._handle;\n }\n\n /** Add an agent to the team. */\n add(agent: Agent, instructions?: string): this {\n this.assertNotDisposed();\n team_add_agent(this._handle, agent.name, agent.handle, instructions);\n this.agents.push(agent);\n return this;\n }\n\n /** Set the team coordination strategy. */\n strategy(s: TeamStrategy): this {\n this.assertNotDisposed();\n team_set_strategy(this._handle, s);\n return this;\n }\n\n /** Run the team with a prompt or messages. */\n async run(prompt: string): Promise<TeamResult> {\n this.assertNotDisposed();\n const messages = JSON.stringify([\n { role: \"user\", content: [{ type: \"text\", text: prompt }] },\n ]);\n return team_run(this._handle, messages) as Promise<TeamResult>;\n }\n\n destroy(): void {\n if (!this.disposed) {\n this.disposed = true;\n try {\n destroy_team(this._handle);\n } catch {\n /* ok */\n }\n }\n }\n\n [Symbol.dispose](): void {\n this.destroy();\n }\n\n private assertNotDisposed(): void {\n if (this.disposed) throw new Error(\"Team has been destroyed\");\n }\n}\n","/**\n * Network SDK wrapper — multi-agent delegation backed by Rust core.\n */\nimport {\n create_network,\n network_add_agent,\n network_set_supervisor,\n network_delegate,\n network_agent_cards,\n destroy_network,\n} from \"gauss-napi\";\n\nimport type { Handle, Disposable } from \"./types.js\";\nimport type { Agent } from \"./agent.js\";\n\nexport class Network implements Disposable {\n private readonly _handle: Handle;\n private disposed = false;\n\n constructor() {\n this._handle = create_network();\n }\n\n get handle(): Handle {\n return this._handle;\n }\n\n addAgent(agent: Agent, instructions?: string): this {\n this.assertNotDisposed();\n network_add_agent(\n this._handle,\n agent.name,\n agent.handle,\n instructions\n );\n return this;\n }\n\n setSupervisor(agentName: string): this {\n this.assertNotDisposed();\n network_set_supervisor(this._handle, agentName);\n return this;\n }\n\n async delegate(\n fromAgent: string,\n toAgent: string,\n prompt: string\n ): Promise<unknown> {\n this.assertNotDisposed();\n return network_delegate(this._handle, fromAgent, toAgent, prompt);\n }\n\n agentCards(): unknown {\n this.assertNotDisposed();\n return network_agent_cards(this._handle);\n }\n\n destroy(): void {\n if (!this.disposed) {\n this.disposed = true;\n try {\n destroy_network(this._handle);\n } catch {\n // Already destroyed.\n }\n }\n }\n\n [Symbol.dispose](): void {\n this.destroy();\n }\n\n private assertNotDisposed(): void {\n if (this.disposed) {\n throw new Error(\"Network has been destroyed\");\n }\n }\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,WAAAE,EAAA,YAAAC,EAAA,SAAAC,EAAA,aAAAC,IAAA,eAAAC,EAAAN,GCeA,IAAAO,EAOO,sBAuBMC,EAAN,KAAkC,CACtB,QACT,SAAW,GAGF,OAAS,IAAI,IAEb,OAAS,IAAI,IAEb,kBAAoB,IAAI,IAEzC,aAAc,CACZ,KAAK,WAAU,gBAAa,CAC9B,CAEA,IAAI,QAAiB,CACnB,OAAO,KAAK,OACd,CAEA,QAAQC,EAA+B,CACrC,YAAK,kBAAkB,KACvB,kBACE,KAAK,QACLA,EAAO,OACPA,EAAO,MAAM,KACbA,EAAO,MAAM,OACbA,EAAO,aACPA,EAAO,OAAS,CAAC,CACnB,EACA,KAAK,OAAO,IAAIA,EAAO,OAAQ,CAC7B,MAAOA,EAAO,MACd,aAAcA,EAAO,YACvB,CAAC,EACM,IACT,CAGA,QAAQA,EAA8B,CACpC,YAAK,kBAAkB,KACvB,uBACE,KAAK,QACLA,EAAO,OACPA,EAAO,OAAO,IAAIC,IAAM,CACtB,UAAWA,EAAE,MAAM,KACnB,eAAgBA,EAAE,MAAM,OACxB,aAAcA,EAAE,YAClB,EAAE,EACFD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EA,MAAM,SACJC,EACAC,EACAC,EACkB,CAClB,YAAK,kBAAkB,KAChB,oBAAiB,KAAK,QAASF,EAAWC,EAASC,CAAM,CAClE,CAEA,YAAsB,CACpB,YAAK,kBAAkB,KAChB,uBAAoB,KAAK,OAAO,CACzC,CAEA,SAAgB,CACd,GAAI,CAAC,KAAK,SAAU,CAClB,KAAK,SAAW,GAChB,GAAI,IACF,mBAAgB,KAAK,OAAO,CAC9B,MAAQ,CAER,CACF,CACF,CAEA,CAAC,OAAO,OAAO,GAAU,CACvB,KAAK,QAAQ,CACf,CAEQ,mBAA0B,CAChC,GAAI,KAAK,SACP,MAAM,IAAI,MAAM,4BAA4B,CAEhD,CACF","names":["orchestration_exports","__export","Graph","Network","Team","Workflow","__toCommonJS","import_gauss_napi","Graph","config","a","from","to","router","prompt","targets","entryNodes","n","outputs","currentNodeId","currentPrompt","nodeCfg","agentInput","result","nodeOutput","nodeIds","lastNodeId","import_gauss_napi","Workflow","config","stepId","dependsOn","prompt","import_gauss_napi","Team","name","agent","instructions","s","prompt","messages","import_gauss_napi","Network","agent","instructions","agentName","fromAgent","toAgent","prompt"]}
1
+ {"version":3,"sources":["../src/orchestration.ts","../src/sdk/graph.ts","../src/sdk/errors.ts","../src/sdk/workflow.ts","../src/sdk/team.ts","../src/sdk/agent.ts","../src/sdk/models.ts","../src/sdk/types.ts","../src/sdk/stream-iter.ts","../src/sdk/tool.ts","../src/sdk/network.ts"],"sourcesContent":["export { Graph } from \"./sdk/graph.js\";\nexport type { GraphNodeConfig, ForkNodeConfig, ConsensusStrategy, RouterFn } from \"./sdk/graph.js\";\nexport { Workflow } from \"./sdk/workflow.js\";\nexport type { WorkflowStepConfig } from \"./sdk/workflow.js\";\nexport { Team } from \"./sdk/team.js\";\nexport type { TeamStrategy, TeamResult } from \"./sdk/team.js\";\nexport { Network } from \"./sdk/network.js\";\n","/**\n * Graph — DAG-based multi-agent execution backed by Rust core.\n *\n * @example\n * const researcher = new Agent({ name: \"researcher\", instructions: \"Research topics\" });\n * const writer = new Agent({ name: \"writer\", instructions: \"Write articles\" });\n *\n * const graph = new Graph()\n * .addNode({ nodeId: \"research\", agent: researcher })\n * .addNode({ nodeId: \"write\", agent: writer })\n * .addEdge(\"research\", \"write\");\n *\n * const result = await graph.run(\"Write about quantum computing\");\n * graph.destroy();\n */\nimport {\n create_graph,\n graph_add_node,\n graph_add_edge,\n graph_add_fork_node,\n graph_run,\n destroy_graph,\n} from \"gauss-napi\";\n\nimport type { Handle, Disposable, ToolDef } from \"./types.js\";\nimport type { Agent } from \"./agent.js\";\nimport { DisposedError, ValidationError } from \"./errors.js\";\n\n/** Router function invoked at runtime to decide the next node. */\nexport type RouterFn = (result: Record<string, unknown>) => string | Promise<string>;\n\nexport interface GraphNodeConfig {\n nodeId: string;\n agent: Agent;\n instructions?: string;\n tools?: ToolDef[];\n}\n\nexport type ConsensusStrategy = \"first\" | \"concat\";\n\nexport interface ForkNodeConfig {\n nodeId: string;\n agents: Array<{ agent: Agent; instructions?: string }>;\n consensus?: ConsensusStrategy;\n}\n\nexport class Graph implements Disposable {\n /**\n * Quick graph builder — create a linear pipeline from agents.\n *\n * @example\n * ```ts\n * const result = await Graph.pipeline([\n * { nodeId: \"research\", agent: researcher },\n * { nodeId: \"write\", agent: writer },\n * ]).run(\"Explain quantum computing\");\n * ```\n */\n static pipeline(nodes: GraphNodeConfig[]): Graph {\n const graph = new Graph();\n for (const node of nodes) {\n graph.addNode(node);\n }\n for (let i = 0; i < nodes.length - 1; i++) {\n graph.addEdge(nodes[i].nodeId, nodes[i + 1].nodeId);\n }\n return graph;\n }\n\n private readonly _handle: Handle;\n private disposed = false;\n\n /** Node registry for SDK-level stepping. */\n private readonly _nodes = new Map<string, { agent: Agent; instructions?: string }>();\n /** Regular edges tracked locally for SDK-level stepping. */\n private readonly _edges = new Map<string, string>();\n /** Conditional edges: source node → router function. */\n private readonly _conditionalEdges = new Map<string, RouterFn>();\n\n constructor() {\n this._handle = create_graph();\n }\n\n get handle(): Handle {\n return this._handle;\n }\n\n addNode(config: GraphNodeConfig): this {\n this.assertNotDisposed();\n graph_add_node(\n this._handle,\n config.nodeId,\n config.agent.name,\n config.agent.handle,\n config.instructions,\n config.tools ?? []\n );\n this._nodes.set(config.nodeId, {\n agent: config.agent,\n instructions: config.instructions,\n });\n return this;\n }\n\n /** Add a fork node — runs multiple agents in parallel, merging via consensus. */\n addFork(config: ForkNodeConfig): this {\n this.assertNotDisposed();\n graph_add_fork_node(\n this._handle,\n config.nodeId,\n config.agents.map(a => ({\n agentName: a.agent.name,\n providerHandle: a.agent.handle,\n instructions: a.instructions,\n })),\n config.consensus ?? \"concat\"\n );\n return this;\n }\n\n addEdge(from: string, to: string): this {\n this.assertNotDisposed();\n graph_add_edge(this._handle, from, to);\n this._edges.set(from, to);\n return this;\n }\n\n /**\n * Add a conditional edge — at runtime the router function receives the\n * source node's result and returns the ID of the next node to execute.\n */\n addConditionalEdge(from: string, router: RouterFn): this {\n this.assertNotDisposed();\n this._conditionalEdges.set(from, router);\n return this;\n }\n\n async run(prompt: string): Promise<Record<string, unknown>> {\n this.assertNotDisposed();\n\n // Fast path: no conditional edges → delegate entirely to Rust core.\n if (this._conditionalEdges.size === 0) {\n return graph_run(this._handle, prompt) as Promise<Record<string, unknown>>;\n }\n\n return this._runWithConditionals(prompt);\n }\n\n destroy(): void {\n if (!this.disposed) {\n this.disposed = true;\n try { destroy_graph(this._handle); } catch { /* ok */ }\n }\n }\n\n [Symbol.dispose](): void {\n this.destroy();\n }\n\n // ── Private ──────────────────────────────────────────────────────\n\n /** SDK-level step-through execution when conditional edges are present. */\n private async _runWithConditionals(prompt: string): Promise<Record<string, unknown>> {\n // Determine entry node: a node with no incoming edges.\n const targets = new Set<string>([\n ...this._edges.values(),\n ]);\n const entryNodes = [...this._nodes.keys()].filter(n => !targets.has(n));\n if (entryNodes.length === 0) {\n throw new ValidationError(\"Graph has no entry node (every node has an incoming edge)\");\n }\n\n const outputs: Record<string, Record<string, unknown>> = {};\n let currentNodeId: string | undefined = entryNodes[0];\n let currentPrompt = prompt;\n\n while (currentNodeId) {\n const nodeCfg = this._nodes.get(currentNodeId);\n if (!nodeCfg) {\n throw new ValidationError(`Node \"${currentNodeId}\" not found in graph`);\n }\n\n const agentInput = nodeCfg.instructions\n ? `${nodeCfg.instructions}\\n\\n${currentPrompt}`\n : currentPrompt;\n\n const result = await nodeCfg.agent.run(agentInput);\n const nodeOutput: Record<string, unknown> = {\n text: result.text,\n ...(result.structuredOutput ? { structuredOutput: result.structuredOutput } : {}),\n };\n outputs[currentNodeId] = nodeOutput;\n\n // Decide next node.\n const router = this._conditionalEdges.get(currentNodeId);\n if (router) {\n currentNodeId = await router(nodeOutput);\n } else {\n currentNodeId = this._edges.get(currentNodeId);\n }\n\n // Feed previous output as prompt for the next node.\n currentPrompt = result.text;\n }\n\n // Build result envelope matching graph_run shape.\n const nodeIds = Object.keys(outputs);\n const lastNodeId = nodeIds[nodeIds.length - 1];\n return {\n outputs,\n final_text: (outputs[lastNodeId]?.text as string) ?? \"\",\n };\n }\n\n private assertNotDisposed(): void {\n if (this.disposed) throw new DisposedError(\"Graph\", \"graph\");\n }\n}\n","/**\n * Structured error hierarchy for Gauss SDK.\n *\n * All Gauss errors extend {@link GaussError} to enable type-safe catch blocks:\n *\n * ```ts\n * try {\n * await agent.run(\"hello\");\n * } catch (e) {\n * if (e instanceof AgentDisposedError) { ... }\n * if (e instanceof ProviderError) { ... }\n * }\n * ```\n *\n * @module errors\n * @since 2.1.0\n */\n\n/** Base error for all Gauss SDK errors. Includes an error code for programmatic matching. */\nexport class GaussError extends Error {\n readonly code: string;\n constructor(code: string, message: string) {\n super(message);\n this.name = \"GaussError\";\n this.code = code;\n }\n}\n\n/** Thrown when an operation is attempted on a destroyed Agent/Team/Graph. */\nexport class DisposedError extends GaussError {\n readonly resourceType: string;\n readonly resourceName: string;\n constructor(resourceType: string, resourceName: string) {\n super(\"RESOURCE_DISPOSED\", `${resourceType} \"${resourceName}\" has been destroyed. Create a new instance.`);\n this.name = \"DisposedError\";\n this.resourceType = resourceType;\n this.resourceName = resourceName;\n }\n}\n\n/** Thrown when provider initialization or communication fails. */\nexport class ProviderError extends GaussError {\n readonly provider: string;\n constructor(provider: string, message: string) {\n super(\"PROVIDER_ERROR\", `[${provider}] ${message}`);\n this.name = \"ProviderError\";\n this.provider = provider;\n }\n}\n\n/** Thrown when tool execution fails. */\nexport class ToolExecutionError extends GaussError {\n readonly toolName: string;\n readonly cause?: Error;\n constructor(toolName: string, message: string, cause?: Error) {\n super(\"TOOL_EXECUTION_ERROR\", `Tool \"${toolName}\" failed: ${message}`);\n this.name = \"ToolExecutionError\";\n this.toolName = toolName;\n this.cause = cause;\n }\n}\n\n/** Thrown when configuration validation fails. */\nexport class ValidationError extends GaussError {\n readonly field?: string;\n constructor(message: string, field?: string) {\n super(\"VALIDATION_ERROR\", field ? `Invalid \"${field}\": ${message}` : message);\n this.name = \"ValidationError\";\n this.field = field;\n }\n}\n","/**\n * Workflow SDK wrapper — dependency-based step execution backed by Rust core.\n */\nimport {\n create_workflow,\n workflow_add_step,\n workflow_add_dependency,\n workflow_run,\n destroy_workflow,\n} from \"gauss-napi\";\n\nimport type { Handle, Disposable, ToolDef } from \"./types.js\";\nimport type { Agent } from \"./agent.js\";\n\nexport interface WorkflowStepConfig {\n stepId: string;\n agent: Agent;\n instructions?: string;\n tools?: ToolDef[];\n}\n\nexport class Workflow implements Disposable {\n private readonly _handle: Handle;\n private disposed = false;\n\n constructor() {\n this._handle = create_workflow();\n }\n\n get handle(): Handle {\n return this._handle;\n }\n\n addStep(config: WorkflowStepConfig): this {\n this.assertNotDisposed();\n workflow_add_step(\n this._handle,\n config.stepId,\n config.agent.name,\n config.agent.handle,\n config.instructions,\n config.tools ?? []\n );\n return this;\n }\n\n addDependency(stepId: string, dependsOn: string): this {\n this.assertNotDisposed();\n workflow_add_dependency(this._handle, stepId, dependsOn);\n return this;\n }\n\n async run(prompt: string): Promise<Record<string, unknown>> {\n this.assertNotDisposed();\n return workflow_run(this._handle, prompt) as Promise<\n Record<string, unknown>\n >;\n }\n\n destroy(): void {\n if (!this.disposed) {\n this.disposed = true;\n try {\n destroy_workflow(this._handle);\n } catch {\n // Already destroyed.\n }\n }\n }\n\n [Symbol.dispose](): void {\n this.destroy();\n }\n\n private assertNotDisposed(): void {\n if (this.disposed) {\n throw new Error(\"Workflow has been destroyed\");\n }\n }\n}\n","/**\n * Team — multi-agent coordination backed by Rust core.\n *\n * @example\n * const researcher = new Agent({ name: \"researcher\", instructions: \"Research topics\" });\n * const writer = new Agent({ name: \"writer\", instructions: \"Write summaries\" });\n *\n * const team = new Team(\"content-team\")\n * .add(researcher)\n * .add(writer)\n * .strategy(\"sequential\");\n *\n * const result = await team.run(\"Explain quantum computing\");\n * console.log(result.finalText);\n * team.destroy();\n */\nimport {\n create_team,\n team_add_agent,\n team_set_strategy,\n team_run,\n destroy_team,\n} from \"gauss-napi\";\n\nimport type { Handle, Disposable, ProviderType } from \"./types.js\";\nimport { Agent } from \"./agent.js\";\nimport { DisposedError } from \"./errors.js\";\n\nexport type TeamStrategy = \"sequential\" | \"parallel\";\n\nexport interface TeamResult {\n finalText: string;\n results: Array<{\n text: string;\n steps: number;\n inputTokens: number;\n outputTokens: number;\n }>;\n}\n\nexport class Team implements Disposable {\n private readonly _handle: Handle;\n private readonly _name: string;\n private disposed = false;\n private agents: Agent[] = [];\n\n /**\n * Quick team builder — create a team from role descriptions.\n *\n * @example\n * ```ts\n * const result = await Team.quick(\"content-team\", \"sequential\", [\n * { name: \"researcher\", instructions: \"Research topics\" },\n * { name: \"writer\", instructions: \"Write summaries\" }\n * ]).run(\"Explain quantum computing\");\n * ```\n */\n static quick(\n teamName: string,\n strategy: TeamStrategy,\n agents: Array<{ name: string; provider?: string; model?: string; instructions?: string }>\n ): Team {\n const team = new Team(teamName);\n for (const spec of agents) {\n const agent = new Agent({\n name: spec.name,\n provider: (spec.provider as ProviderType) ?? \"openai\",\n model: spec.model ?? \"gpt-4o\",\n instructions: spec.instructions,\n });\n team.add(agent);\n }\n team.strategy(strategy);\n return team;\n }\n\n constructor(name: string) {\n this._name = name;\n this._handle = create_team(name);\n }\n\n get handle(): Handle {\n return this._handle;\n }\n\n /** Add an agent to the team. */\n add(agent: Agent, instructions?: string): this {\n this.assertNotDisposed();\n team_add_agent(this._handle, agent.name, agent.handle, instructions);\n this.agents.push(agent);\n return this;\n }\n\n /** Set the team coordination strategy. */\n strategy(s: TeamStrategy): this {\n this.assertNotDisposed();\n team_set_strategy(this._handle, s);\n return this;\n }\n\n /** Run the team with a prompt or messages. */\n async run(prompt: string): Promise<TeamResult> {\n this.assertNotDisposed();\n const messages = JSON.stringify([\n { role: \"user\", content: [{ type: \"text\", text: prompt }] },\n ]);\n return team_run(this._handle, messages) as Promise<TeamResult>;\n }\n\n destroy(): void {\n if (!this.disposed) {\n this.disposed = true;\n try {\n destroy_team(this._handle);\n } catch {\n /* ok */\n }\n }\n }\n\n [Symbol.dispose](): void {\n this.destroy();\n }\n\n private assertNotDisposed(): void {\n if (this.disposed) throw new DisposedError(\"Team\", this._name);\n }\n}\n","/**\n * Agent — the heart of Gauss.\n *\n * Quick start:\n * const agent = new Agent({ instructions: \"You are a helpful assistant.\" });\n * const result = await agent.run(\"What is the meaning of life?\");\n *\n * Full control:\n * const agent = new Agent({\n * name: \"researcher\",\n * provider: \"anthropic\",\n * model: \"claude-sonnet-4-20250514\",\n * providerOptions: { apiKey: \"sk-...\" },\n * instructions: \"You are a research assistant.\",\n * tools: [{ name: \"search\", description: \"Search the web\", parameters: { query: { type: \"string\" } } }],\n * temperature: 0.7,\n * maxSteps: 10,\n * });\n */\nimport {\n create_provider,\n destroy_provider,\n agent_run,\n agent_run_with_tool_executor,\n agent_stream_with_tool_executor,\n generate,\n generate_with_tools,\n get_provider_capabilities,\n} from \"gauss-napi\";\n\nimport type {\n ProviderOptions,\n ProviderType,\n ToolDef,\n Message,\n AgentOptions,\n AgentResult,\n ToolExecutor,\n StreamCallback,\n Handle,\n Disposable,\n MemoryEntry,\n GroundingMetadata,\n} from \"./types.js\";\n\nimport { DisposedError } from \"./errors.js\";\n\nimport { resolveApiKey, detectProvider } from \"./types.js\";\nimport { OPENAI_DEFAULT } from \"./models.js\";\nimport { AgentStream } from \"./stream-iter.js\";\nimport { tool as toolFn, isTypedTool, createToolExecutor, type TypedToolDef } from \"./tool.js\";\nimport type { MiddlewareChain } from \"./middleware.js\";\nimport type { GuardrailChain } from \"./guardrail.js\";\nimport type { Memory } from \"./memory.js\";\nimport type { McpClient } from \"./mcp-client.js\";\n\n/**\n * Transform a raw NAPI result into the public {@link AgentResult} shape.\n *\n * @description Normalises citation field names returned by different native providers\n * into the unified SDK format.\n *\n * @param raw - Raw result object from the NAPI layer.\n * @returns Normalised {@link AgentResult}.\n * @internal\n */\ninterface RawNapiResult {\n text: string;\n steps: number;\n inputTokens: number;\n outputTokens: number;\n messages?: Message[];\n tool_calls?: Array<{ name: string; arguments: Record<string, unknown> }>;\n thinking?: string;\n structuredOutput?: Record<string, unknown>;\n groundingMetadata?: GroundingMetadata[];\n citations?: Array<{\n citationType?: string;\n type?: string;\n citedText?: string;\n documentTitle?: string;\n start?: number;\n end?: number;\n }>;\n}\n\nfunction toSdkResult(raw: RawNapiResult): AgentResult {\n return {\n ...raw,\n citations: raw.citations?.map((c) => ({\n type: c.citationType ?? c.type ?? \"unknown\",\n citedText: c.citedText,\n documentTitle: c.documentTitle,\n start: c.start,\n end: c.end,\n })),\n };\n}\n\n// ─── Config ────────────────────────────────────────────────────────\n\n/**\n * Configuration object for creating an {@link Agent} instance.\n *\n * @description All fields are optional — sensible defaults are applied and the provider is auto-detected from environment variables when omitted.\n *\n * @example\n * ```ts\n * const config: AgentConfig = {\n * provider: \"anthropic\",\n * model: \"claude-sonnet-4-20250514\",\n * instructions: \"You are a helpful assistant.\",\n * temperature: 0.7,\n * };\n * const agent = new Agent(config);\n * ```\n *\n * @since 1.0.0\n */\nexport interface AgentConfig {\n /** Agent name (default: `\"agent\"`). Used for logging and identification. */\n name?: string;\n\n /** LLM provider. Auto-detected from env if omitted. */\n provider?: ProviderType;\n\n /** Model identifier (e.g. `\"gpt-4o\"`, `\"claude-sonnet-4-20250514\"`). Auto-selected if omitted. */\n model?: string;\n\n /** Provider connection options. API key auto-resolved from env if omitted. */\n providerOptions?: ProviderOptions;\n\n /** System instructions prepended to every conversation. */\n instructions?: string;\n\n /** Tool definitions available to the agent. Accepts both raw ToolDef and typed tools with execute callbacks. */\n tools?: (ToolDef | TypedToolDef)[];\n\n /** Middleware chain to apply (logging, caching, rate limiting). */\n middleware?: MiddlewareChain;\n\n /** Guardrail chain to apply (PII, content moderation, schema validation). */\n guardrails?: GuardrailChain;\n\n /** Memory instance for automatic conversation history. */\n memory?: Memory;\n\n /** Session ID for memory scoping (default: auto-generated). */\n sessionId?: string;\n\n /** MCP clients to consume tools from external MCP servers. */\n mcpClients?: McpClient[];\n\n /** Sampling temperature (0–2). Higher values produce more creative output. */\n temperature?: number;\n\n /** Maximum number of agentic loop iterations before stopping. */\n maxSteps?: number;\n\n /** Top-p (nucleus) sampling threshold. */\n topP?: number;\n\n /** Maximum number of output tokens per response. */\n maxTokens?: number;\n\n /** Deterministic seed for reproducible outputs. */\n seed?: number;\n\n /** Stop the agentic loop when this tool name is called. */\n stopOnTool?: string;\n\n /** JSON schema for structured output. The model will conform its response to this schema. */\n outputSchema?: Record<string, unknown>;\n\n /** Extended thinking budget (Anthropic). Number of tokens for internal reasoning. */\n thinkingBudget?: number;\n\n /** Reasoning effort for OpenAI o-series models. Controls how much reasoning to use. */\n reasoningEffort?: \"low\" | \"medium\" | \"high\";\n\n /** Enable prompt caching (Anthropic). Auto-annotates system messages and tools. */\n cacheControl?: boolean;\n\n /** Enable code execution runtimes. Pass `true` for all defaults, or configure individually. */\n codeExecution?: boolean | import(\"./types.js\").CodeExecutionOptions;\n\n /** Enable Google Search grounding (Gemini only). */\n grounding?: boolean;\n\n /** Enable native code execution / Gemini code interpreter. */\n nativeCodeExecution?: boolean;\n\n /** Response modalities (e.g. `[\"TEXT\", \"IMAGE\"]` for Gemini image generation). */\n responseModalities?: string[];\n}\n\n// ─── Agent Class ───────────────────────────────────────────────────\n\n/**\n * Core agent class that wraps a native LLM provider and manages the agentic loop.\n *\n * @description `Agent` is the primary entry-point for interacting with language models in Gauss.\n * It supports single-shot completions, multi-step tool-use loops, streaming, and raw generation.\n * Each instance owns a native provider handle that **must** be released via {@link Agent.destroy}\n * (or the `using` pattern) to avoid resource leaks.\n *\n * @example\n * ```ts\n * const agent = new Agent({\n * provider: \"openai\",\n * model: \"gpt-4o\",\n * instructions: \"You are a helpful assistant.\",\n * });\n * const result = await agent.run(\"What is the meaning of life?\");\n * console.log(result.text);\n * agent.destroy();\n * ```\n *\n * @since 1.0.0\n */\nexport class Agent implements Disposable {\n private readonly providerHandle: Handle;\n private readonly _name: string;\n private readonly _provider: ProviderType;\n private readonly _model: string;\n private readonly _providerOptions: ProviderOptions & { apiKey: string };\n private readonly _instructions: string;\n private _tools: (ToolDef | TypedToolDef)[] = [];\n private _options: AgentOptions = {};\n private disposed = false;\n\n // ─── Integration Glue (M35) ──────────────────────────────────────\n private _middleware: MiddlewareChain | null = null;\n private _guardrails: GuardrailChain | null = null;\n private _memory: Memory | null = null;\n private _sessionId: string = \"\";\n private _mcpClients: McpClient[] = [];\n private _mcpToolsLoaded = false;\n\n /**\n * Create a new Agent.\n *\n * @description Initialises the native provider connection and configures the agentic\n * loop options. The provider and model are auto-detected from environment variables\n * when not explicitly set.\n *\n * @param config - Agent configuration. All fields are optional.\n * @throws {Error} If the native provider cannot be created (e.g. invalid API key).\n *\n * @example\n * ```ts\n * const agent = new Agent({ instructions: \"Be concise.\" });\n * ```\n *\n * @since 1.0.0\n */\n constructor(config: AgentConfig = {}) {\n const detected = detectProvider();\n this._provider = config.provider ?? detected?.provider ?? \"openai\";\n this._model = config.model ?? detected?.model ?? OPENAI_DEFAULT;\n this._name = config.name ?? \"agent\";\n this._instructions = config.instructions ?? \"\";\n\n const apiKey =\n config.providerOptions?.apiKey ?? resolveApiKey(this._provider);\n this._providerOptions = {\n apiKey,\n ...config.providerOptions,\n } as ProviderOptions & { apiKey: string };\n this.providerHandle = create_provider(this._provider, this._model, this._providerOptions);\n\n if (config.tools) this._tools = [...config.tools];\n\n // Integration glue (M35)\n if (config.middleware) this._middleware = config.middleware;\n if (config.guardrails) this._guardrails = config.guardrails;\n if (config.memory) this._memory = config.memory;\n if (config.sessionId) this._sessionId = config.sessionId;\n if (config.mcpClients) this._mcpClients = [...config.mcpClients];\n\n const ceOpt = config.codeExecution;\n const codeExecution = ceOpt === true\n ? { python: true, javascript: true, bash: true }\n : ceOpt || undefined;\n\n this._options = {\n instructions: this._instructions || undefined,\n temperature: config.temperature,\n maxSteps: config.maxSteps,\n topP: config.topP,\n maxTokens: config.maxTokens,\n seed: config.seed,\n stopOnTool: config.stopOnTool,\n outputSchema: config.outputSchema,\n thinkingBudget: config.thinkingBudget,\n reasoningEffort: config.reasoningEffort,\n cacheControl: config.cacheControl,\n codeExecution,\n grounding: config.grounding,\n nativeCodeExecution: config.nativeCodeExecution,\n responseModalities: config.responseModalities,\n };\n }\n\n /**\n * Create an agent using provider/model auto-detection from environment variables.\n *\n * @description Equivalent to `new Agent(config)`, but clearer in intent for env-driven setup.\n *\n * @param config - Optional partial configuration overrides.\n * @returns A new {@link Agent} instance.\n *\n * @example\n * ```ts\n * const agent = Agent.fromEnv({ instructions: \"Be concise.\" });\n * ```\n */\n static fromEnv(config: AgentConfig = {}): Agent {\n return new Agent(config);\n }\n\n // ─── Accessors ──────────────────────────────────────────────────\n\n /**\n * @description The agent's name.\n * @since 1.0.0\n */\n get name(): string { return this._name; }\n\n /**\n * @description The resolved LLM provider type.\n * @since 1.0.0\n */\n get provider(): ProviderType { return this._provider; }\n\n /**\n * @description The resolved model identifier.\n * @since 1.0.0\n */\n get model(): string { return this._model; }\n\n /**\n * @description The system instructions string.\n * @since 1.0.0\n */\n get instructions(): string { return this._instructions; }\n\n /**\n * @description Native provider handle. Used internally by Network, Graph, and other subsystems.\n * @since 1.0.0\n * @internal\n */\n get handle(): Handle { return this.providerHandle; }\n\n /**\n * @description Query what features this provider/model combination supports.\n * @returns The capability flags for the current provider and model.\n * @since 1.0.0\n */\n get capabilities(): import(\"./types.js\").ProviderCapabilities {\n return get_provider_capabilities(this.providerHandle);\n }\n\n // ─── Fluent Configuration ───────────────────────────────────────\n\n /**\n * Register a single tool definition. Chainable.\n *\n * @description Appends a tool to the agent's tool list so the LLM can invoke it during the agentic loop.\n *\n * @param tool - The tool definition to add.\n * @returns `this` for fluent chaining.\n *\n * @example\n * ```ts\n * agent.addTool({ name: \"search\", description: \"Web search\", parameters: { query: { type: \"string\" } } });\n * ```\n *\n * @since 1.0.0\n */\n addTool(tool: ToolDef | TypedToolDef): this {\n this._tools.push(tool);\n return this;\n }\n\n /**\n * Register multiple tool definitions at once. Chainable.\n *\n * @description Appends all provided tools to the agent's tool list.\n *\n * @param tools - Array of tool definitions to add.\n * @returns `this` for fluent chaining.\n *\n * @example\n * ```ts\n * agent.addTools([\n * { name: \"search\", description: \"Web search\", parameters: { query: { type: \"string\" } } },\n * { name: \"calculate\", description: \"Math calculator\", parameters: { expr: { type: \"string\" } } },\n * ]);\n * ```\n *\n * @since 1.0.0\n */\n addTools(tools: (ToolDef | TypedToolDef)[]): this {\n this._tools.push(...tools);\n return this;\n }\n\n /**\n * Inline tool shortcut — define and attach a tool in one step.\n *\n * @example\n * ```ts\n * const result = await agent\n * .withTool(\"get_weather\", \"Get weather for a city\", async ({ city }) => ({ temp: 72 }))\n * .run(\"Weather in Paris?\");\n * ```\n */\n withTool<TParams = Record<string, unknown>, TResult = unknown>(\n name: string,\n description: string,\n execute: (params: TParams) => TResult | Promise<TResult>,\n parameters?: Record<string, unknown>\n ): this {\n this._tools.push(toolFn({ name, description, parameters: parameters ?? {}, execute }));\n return this;\n }\n\n /**\n * Merge additional agent options into the current configuration. Chainable.\n *\n * @description Shallow-merges the provided options with the existing ones. Later calls override earlier values.\n *\n * @param options - Partial agent options to merge.\n * @returns `this` for fluent chaining.\n *\n * @example\n * ```ts\n * agent.setOptions({ temperature: 0.5, maxTokens: 1024 });\n * ```\n *\n * @since 1.0.0\n */\n setOptions(options: Partial<AgentOptions>): this {\n this._options = { ...this._options, ...options };\n return this;\n }\n\n /**\n * Clone this agent with a different model.\n *\n * @description Returns a **new** agent instance preserving tools and integrations,\n * but using the provided model identifier.\n *\n * @param model - Target model identifier.\n * @returns A new {@link Agent} configured with the selected model.\n */\n withModel(model: string): Agent {\n this.assertNotDisposed();\n return new Agent({\n ...this.toConfig(),\n model,\n });\n }\n\n // ─── Integration Glue (M35) ────────────────────────────────────\n\n /**\n * Attach a middleware chain (logging, caching, rate limiting). Chainable.\n *\n * @param chain - A configured {@link MiddlewareChain} instance.\n * @returns `this` for fluent chaining.\n *\n * @example\n * ```ts\n * agent.withMiddleware(\n * new MiddlewareChain().useLogging().useCaching(60000).useRateLimit(100)\n * );\n * ```\n *\n * @since 1.2.0\n */\n withMiddleware(chain: MiddlewareChain): this {\n this._middleware = chain;\n return this;\n }\n\n /**\n * Attach a guardrail chain (content moderation, PII, schema validation). Chainable.\n *\n * @param chain - A configured {@link GuardrailChain} instance.\n * @returns `this` for fluent chaining.\n *\n * @example\n * ```ts\n * agent.withGuardrails(\n * new GuardrailChain().addPiiDetection(\"redact\").addContentModeration([\"violence\"], [])\n * );\n * ```\n *\n * @since 1.2.0\n */\n withGuardrails(chain: GuardrailChain): this {\n this._guardrails = chain;\n return this;\n }\n\n /**\n * Attach memory for automatic conversation history. Chainable.\n *\n * @description When memory is attached, the agent automatically:\n * - Recalls recent entries before each run (prepended as context)\n * - Stores the conversation (input + output) after each run\n *\n * @param memory - A {@link Memory} instance.\n * @param sessionId - Optional session ID for scoping memory entries.\n * @returns `this` for fluent chaining.\n *\n * @example\n * ```ts\n * const memory = new Memory();\n * agent.withMemory(memory, \"session-123\");\n * await agent.run(\"Hello!\"); // stored in memory\n * await agent.run(\"What did I just say?\"); // recalls previous context\n * ```\n *\n * @since 1.2.0\n */\n withMemory(memory: Memory, sessionId?: string): this {\n this._memory = memory;\n if (sessionId) this._sessionId = sessionId;\n return this;\n }\n\n /**\n * Consume tools from an external MCP server. Chainable.\n *\n * @description Registers an MCP client whose tools will be loaded\n * and made available to the agent on the first run.\n *\n * @param client - A connected {@link McpClient} instance.\n * @returns `this` for fluent chaining.\n *\n * @example\n * ```ts\n * const mcp = new McpClient({ command: \"npx\", args: [\"-y\", \"@mcp/server-fs\"] });\n * await mcp.connect();\n * agent.useMcpServer(mcp);\n * ```\n *\n * @since 1.2.0\n */\n useMcpServer(client: McpClient): this {\n this._mcpClients.push(client);\n this._mcpToolsLoaded = false;\n return this;\n }\n\n // ─── Execution ──────────────────────────────────────────────────\n\n /**\n * Run the agentic loop to completion.\n *\n * @description Sends the input through the full agentic loop (tool calls, multi-step reasoning)\n * and returns the final result. Accepts either a plain string prompt or a pre-built message array.\n *\n * @param input - A string prompt or an array of {@link Message} objects.\n * @returns The completed {@link AgentResult} containing the response text, token counts, and optional structured output.\n * @throws {Error} If the agent has been destroyed.\n *\n * @example\n * ```ts\n * const result = await agent.run(\"Explain quantum computing\");\n * console.log(result.text);\n * console.log(`Tokens: ${result.inputTokens} in / ${result.outputTokens} out`);\n * ```\n *\n * @since 1.0.0\n */\n async run(input: string | Message[]): Promise<AgentResult> {\n this.assertNotDisposed();\n\n // Load MCP tools if needed\n await this.ensureMcpTools();\n\n let messages = typeof input === \"string\"\n ? [{ role: \"user\" as const, content: input }]\n : [...input];\n\n // Memory recall: inject context\n if (this._memory) {\n const recalled = await this._memory.recall(\n this._sessionId ? { sessionId: this._sessionId } : undefined\n );\n if (recalled.length > 0) {\n const contextText = recalled.map(e => e.content).join(\"\\n\");\n messages = [\n { role: \"system\" as const, content: `Previous context:\\n${contextText}` },\n ...messages,\n ];\n }\n }\n\n // Extract tool definitions (strip execute callbacks for NAPI)\n const { toolDefs, executor } = this.resolveToolsAndExecutor();\n\n let result: AgentResult;\n if (executor) {\n result = toSdkResult(await agent_run_with_tool_executor(\n this._name,\n this.providerHandle,\n toolDefs,\n messages,\n this._options,\n executor\n ));\n } else {\n result = toSdkResult(await agent_run(\n this._name,\n this.providerHandle,\n toolDefs,\n messages,\n this._options\n ));\n }\n\n // Memory store: save conversation\n if (this._memory) {\n const userText = typeof input === \"string\" ? input : input.map(m => m.content).join(\"\\n\");\n await this._memory.store({\n id: `${Date.now()}-user`,\n content: userText,\n entryType: \"conversation\",\n timestamp: new Date().toISOString(),\n sessionId: this._sessionId || undefined,\n });\n await this._memory.store({\n id: `${Date.now()}-assistant`,\n content: result.text,\n entryType: \"conversation\",\n timestamp: new Date().toISOString(),\n sessionId: this._sessionId || undefined,\n });\n }\n\n return result;\n }\n\n /**\n * Run the agentic loop with a JavaScript-side tool executor.\n *\n * @description Like {@link Agent.run}, but delegates tool invocations to the provided\n * `toolExecutor` callback. Use this when tools need access to the Node.js runtime\n * (file system, network, databases, etc.).\n *\n * @param input - A string prompt or an array of {@link Message} objects.\n * @param toolExecutor - Async callback that receives a JSON-encoded tool call and returns a JSON-encoded result.\n * @returns The completed {@link AgentResult}.\n * @throws {Error} If the agent has been destroyed.\n *\n * @example\n * ```ts\n * const result = await agent.runWithTools(\"Search for cats\", async (callJson) => {\n * const call = JSON.parse(callJson);\n * return JSON.stringify({ results: [\"cat1\", \"cat2\"] });\n * });\n * ```\n *\n * @since 1.0.0\n */\n async runWithTools(\n input: string | Message[],\n toolExecutor: ToolExecutor\n ): Promise<AgentResult> {\n this.assertNotDisposed();\n\n await this.ensureMcpTools();\n\n const messages = typeof input === \"string\"\n ? [{ role: \"user\" as const, content: input }]\n : input;\n\n const { toolDefs, executor: typedExecutor } = this.resolveToolsAndExecutor();\n\n // Compose typed tool executor with user-provided executor\n const composedExecutor: ToolExecutor = async (callJson: string) => {\n // Try typed tools first, then fall back to user executor\n if (typedExecutor) {\n const result = await typedExecutor(callJson);\n const parsed = JSON.parse(result);\n if (!parsed.error?.startsWith(\"Unknown tool:\")) return result;\n }\n return toolExecutor(callJson);\n };\n\n return toSdkResult(await agent_run_with_tool_executor(\n this._name,\n this.providerHandle,\n toolDefs,\n messages,\n this._options,\n composedExecutor\n ));\n }\n\n /**\n * Stream agent responses with real-time events via a callback.\n *\n * @description Runs the agentic loop while invoking `onEvent` for each streaming event\n * (text deltas, tool calls, etc.). Returns the final aggregated result after the stream ends.\n *\n * @param input - A string prompt or an array of {@link Message} objects.\n * @param onEvent - Callback invoked with each JSON-encoded stream event.\n * @param toolExecutor - Optional async callback for handling tool invocations.\n * @returns The completed {@link AgentResult}.\n * @throws {Error} If the agent has been destroyed.\n *\n * @example\n * ```ts\n * const result = await agent.stream(\"Tell me a joke\", (eventJson) => {\n * const event = JSON.parse(eventJson);\n * if (event.type === \"text_delta\") process.stdout.write(event.text ?? \"\");\n * });\n * ```\n *\n * @since 1.0.0\n */\n async stream(\n input: string | Message[],\n onEvent: StreamCallback,\n toolExecutor?: ToolExecutor\n ): Promise<AgentResult> {\n this.assertNotDisposed();\n\n await this.ensureMcpTools();\n\n const messages = typeof input === \"string\"\n ? [{ role: \"user\" as const, content: input }]\n : input;\n\n const { toolDefs, executor: typedExecutor } = this.resolveToolsAndExecutor();\n const finalExecutor = toolExecutor ?? typedExecutor ?? NOOP_TOOL_EXECUTOR;\n\n return toSdkResult(await agent_stream_with_tool_executor(\n this._name,\n this.providerHandle,\n toolDefs,\n messages,\n this._options,\n onEvent,\n finalExecutor\n ));\n }\n\n /**\n * Stream as an async iterable — use with `for await`.\n *\n * @description Returns an {@link AgentStream} that yields {@link StreamEvent} objects.\n * After iteration completes, the final {@link AgentResult} is available via\n * `stream.result`.\n *\n * @param input - A string prompt or an array of {@link Message} objects.\n * @param toolExecutor - Optional async callback for handling tool invocations.\n * @returns An {@link AgentStream} async iterable of {@link StreamEvent} objects.\n * @throws {Error} If the agent has been destroyed.\n *\n * @example\n * ```ts\n * const stream = agent.streamIter(\"Tell me a story\");\n * for await (const event of stream) {\n * if (event.type === \"text_delta\") process.stdout.write(event.text ?? \"\");\n * }\n * console.log(stream.result?.text);\n * ```\n *\n * @since 1.0.0\n */\n streamIter(\n input: string | Message[],\n toolExecutor?: ToolExecutor\n ): AgentStream {\n this.assertNotDisposed();\n const messages = typeof input === \"string\"\n ? [{ role: \"user\" as const, content: input }]\n : input;\n\n const { toolDefs, executor: typedExecutor } = this.resolveToolsAndExecutor();\n const finalExecutor = toolExecutor ?? typedExecutor ?? NOOP_TOOL_EXECUTOR;\n\n return new AgentStream(\n this._name,\n this.providerHandle,\n toolDefs,\n messages,\n this._options,\n finalExecutor\n );\n }\n\n /**\n * Stream only text deltas with a tiny DX helper.\n *\n * @description Aggregates all streamed text deltas into a final string and optionally\n * invokes `onDelta` for each chunk as it arrives.\n *\n * @param input - A string prompt or an array of {@link Message} objects.\n * @param onDelta - Optional callback invoked for each text delta.\n * @param toolExecutor - Optional async callback for handling tool invocations.\n * @returns The final response text.\n */\n async streamText(\n input: string | Message[],\n onDelta?: (delta: string) => void,\n toolExecutor?: ToolExecutor\n ): Promise<string> {\n this.assertNotDisposed();\n const stream = this.streamIter(input, toolExecutor);\n let aggregated = \"\";\n\n for await (const event of stream) {\n if (event.type !== \"text_delta\") continue;\n const delta = typeof event.text === \"string\"\n ? event.text\n : (typeof event.delta === \"string\" ? event.delta : \"\");\n if (!delta) continue;\n aggregated += delta;\n onDelta?.(delta);\n }\n\n return stream.result?.text ?? aggregated;\n }\n\n /**\n * Perform a single raw LLM call without the agentic loop.\n *\n * @description Bypasses the multi-step agent loop and sends the input directly to the model\n * for a one-shot completion. Useful when you need a simple generation without tool use.\n *\n * @param input - A string prompt or an array of {@link Message} objects.\n * @param options - Optional generation parameters.\n * @param options.temperature - Sampling temperature override.\n * @param options.maxTokens - Maximum output tokens override.\n * @returns The raw provider response.\n *\n * @example\n * ```ts\n * const response = await agent.generate(\"Translate 'hello' to French\", { temperature: 0 });\n * ```\n *\n * @since 1.0.0\n */\n async generate(\n input: string | Message[],\n options?: { temperature?: number; maxTokens?: number }\n ): Promise<unknown> {\n this.assertNotDisposed();\n const messages = typeof input === \"string\"\n ? [{ role: \"user\" as const, content: input }]\n : input;\n return generate(\n this.providerHandle,\n messages,\n options?.temperature,\n options?.maxTokens\n );\n }\n\n /**\n * Perform a single raw LLM call with tool definitions (no agentic loop).\n *\n * @description Like {@link Agent.generate}, but also passes tool definitions to the model.\n * The model may return tool-call requests in its response, but the caller is responsible\n * for executing them — no automatic loop is performed.\n *\n * @param input - A string prompt or an array of {@link Message} objects.\n * @param tools - Tool definitions to make available to the model.\n * @param options - Optional generation parameters.\n * @param options.temperature - Sampling temperature override.\n * @param options.maxTokens - Maximum output tokens override.\n * @returns The raw provider response, potentially containing tool call requests.\n *\n * @example\n * ```ts\n * const response = await agent.generateWithTools(\n * \"What's the weather?\",\n * [{ name: \"get_weather\", description: \"Get weather\", parameters: { city: { type: \"string\" } } }],\n * );\n * ```\n *\n * @since 1.0.0\n */\n async generateWithTools(\n input: string | Message[],\n tools: ToolDef[],\n options?: { temperature?: number; maxTokens?: number }\n ): Promise<unknown> {\n this.assertNotDisposed();\n const messages = typeof input === \"string\"\n ? [{ role: \"user\" as const, content: input }]\n : input;\n return generate_with_tools(\n this.providerHandle,\n messages,\n tools,\n options?.temperature,\n options?.maxTokens\n );\n }\n\n // ─── Lifecycle ──────────────────────────────────────────────────\n\n /**\n * Release all native resources held by this agent.\n *\n * @description Destroys the underlying native provider handle. Safe to call multiple times;\n * subsequent calls are no-ops. After calling `destroy()`, any further method calls on this\n * agent will throw.\n *\n * @since 1.0.0\n */\n destroy(): void {\n if (!this.disposed) {\n this.disposed = true;\n // Close MCP clients\n for (const client of this._mcpClients) {\n try { client.close(); } catch { /* ignore */ }\n }\n try {\n destroy_provider(this.providerHandle);\n } catch {\n // Already destroyed — safe to ignore.\n }\n }\n }\n\n /**\n * Alias for {@link Agent.destroy} — enables the TC39 `using` pattern.\n *\n * @example\n * ```ts\n * {\n * using agent = new Agent({ instructions: \"Be helpful.\" });\n * const result = await agent.run(\"Hi!\");\n * } // agent is automatically destroyed here\n * ```\n *\n * @since 1.0.0\n */\n [Symbol.dispose](): void {\n this.destroy();\n }\n\n private assertNotDisposed(): void {\n if (this.disposed) {\n throw new DisposedError(\"Agent\", this._name);\n }\n }\n\n /**\n * Resolve typed tools into plain ToolDefs + a ToolExecutor.\n * @internal\n */\n private resolveToolsAndExecutor(): { toolDefs: ToolDef[]; executor: ToolExecutor | null } {\n const typedTools = this._tools.filter(isTypedTool);\n\n // Strip execute callbacks for the NAPI layer\n const toolDefs: ToolDef[] = this._tools.map(t => ({\n name: t.name,\n description: t.description,\n parameters: t.parameters,\n }));\n\n const executor = typedTools.length > 0\n ? createToolExecutor(typedTools)\n : null;\n\n return { toolDefs, executor };\n }\n\n /**\n * Load tools from all connected MCP clients (lazy, once).\n * @internal\n */\n private async ensureMcpTools(): Promise<void> {\n if (this._mcpToolsLoaded || this._mcpClients.length === 0) return;\n\n for (const client of this._mcpClients) {\n const { tools, executor } = await client.getToolsWithExecutor();\n // Add MCP tools as typed tools with the MCP executor as their execute callback\n for (const t of tools) {\n const mcpTool: TypedToolDef = {\n ...t,\n execute: async (params: Record<string, unknown>) => {\n const callJson = JSON.stringify({ tool: t.name, args: params });\n const resultJson = await executor(callJson);\n return JSON.parse(resultJson);\n },\n };\n this._tools.push(mcpTool);\n }\n }\n\n this._mcpToolsLoaded = true;\n }\n\n /** Snapshot current agent configuration for cloning helpers. */\n private toConfig(): AgentConfig {\n return {\n name: this._name,\n provider: this._provider,\n model: this._model,\n providerOptions: { ...this._providerOptions },\n instructions: this._instructions || undefined,\n tools: [...this._tools],\n middleware: this._middleware ?? undefined,\n guardrails: this._guardrails ?? undefined,\n memory: this._memory ?? undefined,\n sessionId: this._sessionId || undefined,\n mcpClients: [...this._mcpClients],\n temperature: this._options.temperature,\n maxSteps: this._options.maxSteps,\n topP: this._options.topP,\n maxTokens: this._options.maxTokens,\n seed: this._options.seed,\n stopOnTool: this._options.stopOnTool,\n outputSchema: this._options.outputSchema,\n thinkingBudget: this._options.thinkingBudget,\n reasoningEffort: this._options.reasoningEffort,\n cacheControl: this._options.cacheControl,\n codeExecution: this._options.codeExecution,\n grounding: this._options.grounding,\n nativeCodeExecution: this._options.nativeCodeExecution,\n responseModalities: this._options.responseModalities,\n };\n }\n}\n\n/** No-op tool executor — used when no tools are registered. */\nconst NOOP_TOOL_EXECUTOR: ToolExecutor = async () => \"{}\";\n\n/**\n * One-liner convenience function — create an agent, run a prompt, and return the text.\n *\n * @description Creates a temporary {@link Agent}, sends the prompt through the agentic loop,\n * and returns just the response text. The agent is automatically destroyed after the call.\n * Ideal for quick, single-turn interactions.\n *\n * @param prompt - The user prompt to send to the agent.\n * @param config - Optional agent configuration (everything except `name`).\n * @returns The agent's response text.\n * @throws {Error} If the provider cannot be initialised or the call fails.\n *\n * @example\n * ```ts\n * import { gauss } from \"gauss-ts\";\n * const answer = await gauss(\"What is the meaning of life?\");\n * console.log(answer);\n * ```\n *\n * @since 1.0.0\n */\nexport async function gauss(\n prompt: string,\n config?: Omit<AgentConfig, \"name\">\n): Promise<string> {\n const agent = new Agent({ name: \"gauss\", ...config });\n try {\n const result = await agent.run(prompt);\n return result.text;\n } finally {\n agent.destroy();\n }\n}\n","/**\n * Model Constants — Single Source of Truth\n *\n * Update these when new model versions are released.\n * All examples, tests, and defaults reference this file.\n */\n\n// ─── OpenAI ──────────────────────────────────────────\nexport const OPENAI_DEFAULT = \"gpt-5.2\";\nexport const OPENAI_FAST = \"gpt-4.1\";\nexport const OPENAI_REASONING = \"o4-mini\";\nexport const OPENAI_IMAGE = \"gpt-image-1\";\n\n// ─── Anthropic ───────────────────────────────────────\nexport const ANTHROPIC_DEFAULT = \"claude-sonnet-4-20250514\";\nexport const ANTHROPIC_FAST = \"claude-haiku-4-20250414\";\nexport const ANTHROPIC_PREMIUM = \"claude-opus-4-20250414\";\n\n// ─── Google ──────────────────────────────────────────\nexport const GOOGLE_DEFAULT = \"gemini-2.5-flash\";\nexport const GOOGLE_PREMIUM = \"gemini-2.5-pro\";\nexport const GOOGLE_IMAGE = \"gemini-2.0-flash\";\n\n// ─── OpenRouter ──────────────────────────────────────\nexport const OPENROUTER_DEFAULT = \"openai/gpt-5.2\";\n\n// ─── DeepSeek ────────────────────────────────────────\nexport const DEEPSEEK_DEFAULT = \"deepseek-chat\";\nexport const DEEPSEEK_REASONING = \"deepseek-reasoner\";\n\n// ─── Enterprise OpenAI-Compatible Providers ─────────\nexport const TOGETHER_DEFAULT = \"meta-llama/Llama-3.3-70B-Instruct-Turbo\";\nexport const FIREWORKS_DEFAULT = \"accounts/fireworks/models/llama-v3p1-70b-instruct\";\nexport const MISTRAL_DEFAULT = \"mistral-large-latest\";\nexport const PERPLEXITY_DEFAULT = \"sonar-pro\";\nexport const XAI_DEFAULT = \"grok-3-beta\";\n\n// ─── Provider Defaults Map ───────────────────────────\nexport const PROVIDER_DEFAULTS: Record<string, string> = {\n openai: OPENAI_DEFAULT,\n anthropic: ANTHROPIC_DEFAULT,\n google: GOOGLE_DEFAULT,\n openrouter: OPENROUTER_DEFAULT,\n deepseek: DEEPSEEK_DEFAULT,\n groq: \"llama-3.3-70b-versatile\",\n ollama: \"llama3.2\",\n together: TOGETHER_DEFAULT,\n fireworks: FIREWORKS_DEFAULT,\n mistral: MISTRAL_DEFAULT,\n perplexity: PERPLEXITY_DEFAULT,\n xai: XAI_DEFAULT,\n};\n\n/** Get the default model for a provider */\nexport function defaultModel(provider: string): string {\n return PROVIDER_DEFAULTS[provider] ?? OPENAI_DEFAULT;\n}\n","/**\n * Gauss SDK — Shared types.\n *\n * Design principles:\n * - Every option has a sensible default\n * - Minimal required fields — only what's truly mandatory\n * - String unions over enums for JS-friendliness\n * - Record<string, unknown> for extensibility\n */\n\n// ─── Provider ──────────────────────────────────────────────────────\n\nexport type ProviderType =\n | \"openai\"\n | \"anthropic\"\n | \"google\"\n | \"groq\"\n | \"ollama\"\n | \"deepseek\"\n | \"openrouter\"\n | \"together\"\n | \"fireworks\"\n | \"mistral\"\n | \"perplexity\"\n | \"xai\";\n\nexport interface ProviderOptions {\n /** API key. Auto-resolved from environment if omitted. */\n apiKey?: string;\n baseUrl?: string;\n timeoutMs?: number;\n maxRetries?: number;\n organization?: string;\n}\n\n// ─── Messages ──────────────────────────────────────────────────────\n\nexport type MessageRole = \"system\" | \"user\" | \"assistant\" | \"tool\";\n\nexport interface Message {\n role: MessageRole;\n content: string;\n}\n\n/** @deprecated Use `Message` instead. */\nexport type JsMessage = Message;\n\n// ─── Tools ─────────────────────────────────────────────────────────\n\nexport interface ToolDef {\n name: string;\n description: string;\n parameters?: Record<string, unknown>;\n}\n\nexport type ToolExecutor = (callJson: string) => Promise<string>;\nexport type StreamCallback = (eventJson: string) => void;\n\n// ─── Agent ─────────────────────────────────────────────────────────\n\nexport interface AgentOptions {\n instructions?: string;\n maxSteps?: number;\n temperature?: number;\n topP?: number;\n maxTokens?: number;\n seed?: number;\n stopOnTool?: string;\n outputSchema?: Record<string, unknown>;\n thinkingBudget?: number;\n /** Reasoning effort for OpenAI o-series models: \"low\", \"medium\", or \"high\". */\n reasoningEffort?: \"low\" | \"medium\" | \"high\";\n cacheControl?: boolean;\n codeExecution?: CodeExecutionOptions;\n /** Enable Google Search grounding (Gemini only). */\n grounding?: boolean;\n /** Enable native code execution / Gemini code interpreter. */\n nativeCodeExecution?: boolean;\n /** Response modalities (e.g. [\"TEXT\", \"IMAGE\"] for Gemini image generation). */\n responseModalities?: string[];\n}\n\n/** A citation reference from document-aware responses. */\nexport interface Citation {\n /** Citation type: char_location, page_location, content_block_location. */\n type: string;\n /** The cited text from the document. */\n citedText?: string;\n /** Title of the source document. */\n documentTitle?: string;\n /** Start index (character, page, or block depending on type). */\n start?: number;\n /** End index (character, page, or block depending on type). */\n end?: number;\n}\n\nexport interface AgentResult {\n text: string;\n steps: number;\n inputTokens: number;\n outputTokens: number;\n structuredOutput?: Record<string, unknown>;\n /** Extended thinking output (Anthropic). */\n thinking?: string;\n /** Citations from document-aware responses (Anthropic). */\n citations?: Citation[];\n /** Grounding metadata from Google Search grounding. */\n groundingMetadata?: GroundingMetadata[];\n}\n\n// ─── Grounding ──────────────────────────────────────────────────────\n\n/** Metadata from Google Search grounding. */\nexport interface GroundingMetadata {\n /** Search queries generated by the model. */\n searchQueries: string[];\n /** Grounding chunks (web results). */\n groundingChunks: GroundingChunk[];\n /** Rendered HTML search entry point widget. */\n searchEntryPoint?: string;\n}\n\n/** A single grounding chunk (web search result). */\nexport interface GroundingChunk {\n /** URL of the web result. */\n url?: string;\n /** Title of the web result. */\n title?: string;\n}\n\n// ─── Image Generation ───────────────────────────────────────────────\n\n/** Configuration for image generation. */\nexport interface ImageGenerationConfig {\n /** Image model (e.g. \"dall-e-3\", \"gemini-2.0-flash\"). */\n model?: string;\n /** Desired size (e.g. \"1024x1024\"). */\n size?: string;\n /** Quality level (e.g. \"standard\", \"hd\"). */\n quality?: string;\n /** Style (e.g. \"vivid\", \"natural\"). */\n style?: string;\n /** Aspect ratio for Gemini (e.g. \"16:9\", \"1:1\"). */\n aspectRatio?: string;\n /** Number of images to generate. */\n n?: number;\n /** Response format (\"url\" or \"b64_json\"). */\n responseFormat?: string;\n}\n\n/** Result of image generation. */\nexport interface ImageGenerationResult {\n /** Generated images. */\n images: GeneratedImageData[];\n /** Revised prompt (DALL-E 3 rewrites prompts). */\n revisedPrompt?: string;\n}\n\n/** A single generated image. */\nexport interface GeneratedImageData {\n /** URL to the generated image (temporary). */\n url?: string;\n /** Base64-encoded image data. */\n base64?: string;\n /** MIME type. */\n mimeType?: string;\n}\n\n// ─── Provider Capabilities ──────────────────────────────────────────\n\n/** Feature capabilities of a provider/model combination. */\nexport interface ProviderCapabilities {\n streaming: boolean;\n toolUse: boolean;\n vision: boolean;\n audio: boolean;\n extendedThinking: boolean;\n citations: boolean;\n cacheControl: boolean;\n structuredOutput: boolean;\n reasoningEffort: boolean;\n imageGeneration: boolean;\n grounding: boolean;\n codeExecution: boolean;\n webSearch: boolean;\n}\n\nexport interface CostEstimate {\n model: string;\n normalizedModel: string;\n currency: string;\n inputTokens: number;\n outputTokens: number;\n reasoningTokens: number;\n cacheReadTokens: number;\n cacheCreationTokens: number;\n inputCostUsd: number;\n outputCostUsd: number;\n reasoningCostUsd: number;\n cacheReadCostUsd: number;\n cacheCreationCostUsd: number;\n totalCostUsd: number;\n}\n\n// ─── Code Execution (PTC) ──────────────────────────────────────────\n\n/** Configuration for programmatic code execution runtimes. */\nexport interface CodeExecutionOptions {\n /** Enable Python runtime (default: true). */\n python?: boolean;\n /** Enable JavaScript/Node.js runtime (default: true). */\n javascript?: boolean;\n /** Enable Bash runtime (default: true). */\n bash?: boolean;\n /** Timeout in seconds per execution (default: 30). */\n timeoutSecs?: number;\n /** Working directory for subprocesses. */\n workingDir?: string;\n /** Sandbox mode: \"default\" | \"strict\" | \"permissive\" (default: \"default\"). */\n sandbox?: \"default\" | \"strict\" | \"permissive\";\n /** Use a single unified execute_code tool instead of per-language tools. */\n unified?: boolean;\n}\n\n/** Result of a code execution. */\nexport interface CodeExecutionResult {\n stdout: string;\n stderr: string;\n exitCode: number;\n timedOut: boolean;\n runtime: string;\n success: boolean;\n}\n\n// ─── Memory ────────────────────────────────────────────────────────\n\nexport type MemoryEntryType = \"conversation\" | \"fact\" | \"preference\" | \"task\" | \"summary\";\nexport type MemoryTier = \"core\" | \"active\" | \"background\" | \"archive\";\n\nexport interface MemoryEntry {\n id: string;\n content: string;\n entryType: MemoryEntryType;\n timestamp: string;\n tier?: MemoryTier;\n metadata?: Record<string, unknown>;\n importance?: number;\n sessionId?: string;\n embedding?: number[];\n}\n\nexport interface RecallOptions {\n sessionId?: string;\n limit?: number;\n}\n\nexport interface MemoryStats {\n totalEntries: number;\n [key: string]: unknown;\n}\n\n// ─── RAG / Vector Store ────────────────────────────────────────────\n\nexport interface VectorChunk {\n id: string;\n documentId: string;\n content: string;\n index: number;\n metadata?: Record<string, unknown>;\n embedding?: number[];\n}\n\nexport interface SearchResult {\n id: string;\n text: string;\n score: number;\n metadata?: Record<string, unknown>;\n}\n\n// ─── Guardrails ────────────────────────────────────────────────────\n\nexport type PiiAction = \"block\" | \"warn\" | \"redact\";\n\n// ─── Tool Validator ────────────────────────────────────────────────\n\nexport type CoercionStrategy =\n | \"null_to_default\"\n | \"type_cast\"\n | \"json_parse\"\n | \"strip_null\";\n\n// ─── Eval ──────────────────────────────────────────────────────────\n\nexport type EvalScorerType = \"exact_match\" | \"contains\" | \"length_ratio\";\n\n// ─── Core ──────────────────────────────────────────────────────────\n\n/** Opaque handle returned by NAPI resource constructors. */\nexport type Handle = number;\n\n/** Any SDK resource that owns native memory. */\nexport interface Disposable {\n destroy(): void;\n}\n\n// ─── Environment helpers ───────────────────────────────────────────\n\nimport { PROVIDER_DEFAULTS } from \"./models.js\";\n\nconst ENV_KEYS: Record<string, string> = {\n openai: \"OPENAI_API_KEY\",\n anthropic: \"ANTHROPIC_API_KEY\",\n google: \"GOOGLE_API_KEY\",\n groq: \"GROQ_API_KEY\",\n deepseek: \"DEEPSEEK_API_KEY\",\n openrouter: \"OPENROUTER_API_KEY\",\n together: \"TOGETHER_API_KEY\",\n fireworks: \"FIREWORKS_API_KEY\",\n mistral: \"MISTRAL_API_KEY\",\n perplexity: \"PERPLEXITY_API_KEY\",\n xai: \"XAI_API_KEY\",\n ollama: \"\",\n};\n\n/** Resolve an API key from environment for the given provider. */\nexport function resolveApiKey(provider: ProviderType): string {\n const key = ENV_KEYS[provider] ?? \"\";\n if (!key) return \"\"; // ollama doesn't need a key\n return (typeof process !== \"undefined\" ? process.env[key] : \"\") ?? \"\";\n}\n\n/** Auto-detect the best available provider from environment variables. */\nexport function detectProvider(): { provider: ProviderType; model: string } | undefined {\n const checks: Array<{ env: string; provider: ProviderType }> = [\n { env: \"OPENAI_API_KEY\", provider: \"openai\" },\n { env: \"ANTHROPIC_API_KEY\", provider: \"anthropic\" },\n { env: \"GOOGLE_API_KEY\", provider: \"google\" },\n { env: \"GROQ_API_KEY\", provider: \"groq\" },\n { env: \"DEEPSEEK_API_KEY\", provider: \"deepseek\" },\n { env: \"OPENROUTER_API_KEY\", provider: \"openrouter\" },\n { env: \"TOGETHER_API_KEY\", provider: \"together\" },\n { env: \"FIREWORKS_API_KEY\", provider: \"fireworks\" },\n { env: \"MISTRAL_API_KEY\", provider: \"mistral\" },\n { env: \"PERPLEXITY_API_KEY\", provider: \"perplexity\" },\n { env: \"XAI_API_KEY\", provider: \"xai\" },\n ];\n for (const { env, provider } of checks) {\n if (typeof process !== \"undefined\" && process.env[env]) {\n return { provider, model: PROVIDER_DEFAULTS[provider] };\n }\n }\n return undefined;\n}\n","/**\n * AgentStream — Async iterable wrapper over native streaming.\n *\n * @example\n * for await (const event of agent.streamIter(\"Tell me a story\", executor)) {\n * if (event.type === \"text_delta\") process.stdout.write(event.text ?? \"\");\n * }\n * // Access final result after iteration:\n * console.log(stream.result?.text);\n */\nimport { agent_stream_with_tool_executor } from \"gauss-napi\";\n\nimport type {\n ToolDef,\n Message,\n AgentOptions,\n AgentResult,\n ToolExecutor,\n Handle,\n} from \"./types.js\";\n\n/**\n * Transform a raw NAPI result into the public {@link AgentResult} shape.\n *\n * @param raw - Raw result object from the NAPI layer.\n * @returns Normalised {@link AgentResult}.\n * @internal\n */\nfunction toSdkResult(raw: any): AgentResult {\n return {\n ...raw,\n citations: raw.citations?.map((c: any) => ({\n type: c.citationType ?? c.type,\n citedText: c.citedText,\n documentTitle: c.documentTitle,\n start: c.start,\n end: c.end,\n })),\n };\n}\n\n/**\n * A single event emitted during agent streaming.\n *\n * @description Represents a parsed streaming event such as a text delta, tool call,\n * or other provider-specific event. The `type` field discriminates the event kind.\n *\n * @example\n * ```ts\n * const event: StreamEvent = { type: \"text_delta\", text: \"Hello\" };\n * if (event.type === \"text_delta\") process.stdout.write(event.text ?? \"\");\n * ```\n *\n * @since 1.0.0\n */\nexport interface StreamEvent {\n /** The event type discriminator (e.g. `\"text_delta\"`, `\"tool_call\"`, `\"raw\"`). */\n type: string;\n /** Text content for text-delta events. */\n text?: string;\n /** Tool call payload for tool-call events. */\n toolCall?: { name: string; arguments: string };\n /** Additional provider-specific fields. */\n [key: string]: unknown;\n}\n\n/**\n * Async iterable wrapper over the native agent streaming callback.\n *\n * @description Bridges the native callback-based streaming API into an `AsyncIterable<StreamEvent>`.\n * Use with `for await ... of` to consume events as they arrive. After iteration completes,\n * the final {@link AgentResult} is available via the {@link AgentStream.result} getter.\n *\n * @example\n * ```ts\n * const stream = agent.streamIter(\"Tell me a story\");\n * for await (const event of stream) {\n * if (event.type === \"text_delta\") process.stdout.write(event.text ?? \"\");\n * }\n * console.log(stream.result?.text);\n * ```\n *\n * @since 1.0.0\n */\nexport class AgentStream implements AsyncIterable<StreamEvent> {\n private _result: AgentResult | undefined;\n\n /**\n * Create a new `AgentStream`.\n *\n * @description Typically not called directly — use {@link Agent.streamIter} instead.\n *\n * @param agentName - Name of the agent for logging/identification.\n * @param providerHandle - Native provider handle.\n * @param tools - Tool definitions available during the stream.\n * @param messages - Conversation messages to send.\n * @param options - Agent options for the agentic loop.\n * @param toolExecutor - Async callback for executing tool calls.\n *\n * @since 1.0.0\n */\n constructor(\n private readonly agentName: string,\n private readonly providerHandle: Handle,\n private readonly tools: ToolDef[],\n private readonly messages: Message[],\n private readonly options: AgentOptions,\n private readonly toolExecutor: ToolExecutor,\n ) {}\n\n /**\n * The final aggregated result, available after async iteration completes.\n *\n * @description Returns `undefined` while iteration is still in progress. Once the\n * `for await` loop finishes, this contains the full {@link AgentResult} with response\n * text, token counts, and other metadata.\n *\n * @returns The completed {@link AgentResult} or `undefined` if iteration hasn't finished.\n *\n * @example\n * ```ts\n * const stream = agent.streamIter(\"Hello\");\n * for await (const event of stream) { /* consume events *\\/ }\n * console.log(stream.result?.text);\n * ```\n *\n * @since 1.0.0\n */\n get result(): AgentResult | undefined { return this._result; }\n\n /**\n * Async iterator implementation — yields {@link StreamEvent} objects as they arrive.\n *\n * @description Starts the native streaming call and yields parsed events. The iterator\n * completes when the underlying stream finishes and all buffered events have been yielded.\n *\n * @returns An async iterator of {@link StreamEvent} objects.\n *\n * @since 1.0.0\n */\n async *[Symbol.asyncIterator](): AsyncIterator<StreamEvent> {\n const buffer: StreamEvent[] = [];\n let resolve: (() => void) | undefined;\n let done = false;\n\n const onEvent = (json: string) => {\n try {\n buffer.push(JSON.parse(json) as StreamEvent);\n } catch {\n buffer.push({ type: \"raw\", text: json });\n }\n resolve?.();\n };\n\n const runPromise = agent_stream_with_tool_executor(\n this.agentName,\n this.providerHandle,\n this.tools,\n this.messages,\n this.options,\n onEvent,\n this.toolExecutor\n ).then((r) => {\n this._result = toSdkResult(r);\n done = true;\n resolve?.();\n });\n\n while (!done || buffer.length > 0) {\n if (buffer.length > 0) {\n yield buffer.shift()!;\n } else if (!done) {\n await new Promise<void>((r) => { resolve = r; });\n }\n }\n\n await runPromise;\n }\n}\n","/**\n * Typed Tool System — define tools with inline execute callbacks.\n *\n * Quick start:\n * const weather = tool({\n * name: \"get_weather\",\n * description: \"Get current weather for a city\",\n * parameters: { city: { type: \"string\", description: \"City name\" } },\n * execute: async ({ city }) => ({ temp: 72, unit: \"F\", city }),\n * });\n * agent.addTools([weather]);\n *\n * The tool() helper creates a TypedToolDef that the agent auto-wires\n * into a ToolExecutor when it detects typed tools with execute callbacks.\n *\n * @since 1.2.0\n */\n\nimport type { ToolDef, ToolExecutor } from \"./types.js\";\n\n// ─── Typed Tool Interface ────────────────────────────────────────────\n\n/**\n * A tool definition with a typed execute callback.\n *\n * @typeParam TParams - The shape of the tool's input parameters.\n * @typeParam TResult - The shape of the tool's return value.\n */\nexport interface TypedToolDef<TParams = Record<string, unknown>, TResult = unknown> extends ToolDef {\n /** The function to execute when the LLM invokes this tool. */\n execute: (params: TParams) => Promise<TResult> | TResult;\n}\n\n// ─── tool() Helper ──────────────────────────────────────────────────\n\n/**\n * Create a typed tool with an inline execute callback.\n *\n * @description Defines a tool that the agent can invoke during the agentic loop.\n * When the LLM calls this tool, the `execute` callback is automatically invoked\n * with the parsed parameters and the return value is sent back to the model.\n *\n * @param config - Tool configuration with name, description, parameters schema, and execute callback.\n * @returns A {@link TypedToolDef} that can be passed to `agent.addTool()` or `agent.addTools()`.\n *\n * @example\n * ```ts\n * const calculator = tool({\n * name: \"calculate\",\n * description: \"Evaluate a math expression\",\n * parameters: {\n * expression: { type: \"string\", description: \"Math expression to evaluate\" },\n * },\n * execute: async ({ expression }) => {\n * return { result: eval(expression) };\n * },\n * });\n *\n * const agent = new Agent({ instructions: \"You can do math.\" });\n * agent.addTools([calculator]);\n * const result = await agent.run(\"What is 2+2?\");\n * ```\n *\n * @since 1.2.0\n */\nexport function tool<TParams = Record<string, unknown>, TResult = unknown>(config: {\n name: string;\n description: string;\n parameters?: Record<string, unknown>;\n execute: (params: TParams) => Promise<TResult> | TResult;\n}): TypedToolDef<TParams, TResult> {\n return {\n name: config.name,\n description: config.description,\n parameters: config.parameters,\n execute: config.execute,\n };\n}\n\n// ─── Tool Executor Builder ──────────────────────────────────────────\n\n/**\n * Check if a tool definition has an execute callback (is a TypedToolDef).\n */\nexport function isTypedTool(t: ToolDef): t is TypedToolDef {\n return typeof (t as TypedToolDef).execute === \"function\";\n}\n\n/**\n * Build a {@link ToolExecutor} from an array of typed tools.\n *\n * @description Creates a single async function that dispatches tool calls\n * to the correct typed tool's execute callback based on the tool name.\n *\n * @param tools - Array of typed tool definitions with execute callbacks.\n * @param fallback - Optional fallback executor for tools without execute callbacks.\n * @returns A {@link ToolExecutor} that can be passed to `agent.runWithTools()`.\n *\n * @since 1.2.0\n */\nexport function createToolExecutor(\n tools: TypedToolDef<any, any>[],\n fallback?: ToolExecutor\n): ToolExecutor {\n const toolMap = new Map(tools.map(t => [t.name, t]));\n\n return async (callJson: string): Promise<string> => {\n let call: { tool?: string; name?: string; args?: unknown; arguments?: unknown };\n try {\n call = JSON.parse(callJson);\n } catch {\n return JSON.stringify({ error: \"Invalid tool call JSON\" });\n }\n\n const toolName = call.tool ?? call.name ?? \"\";\n const toolDef = toolMap.get(toolName);\n\n if (!toolDef) {\n if (fallback) return fallback(callJson);\n return JSON.stringify({ error: `Unknown tool: ${toolName}` });\n }\n\n try {\n const params = (call.args ?? call.arguments ?? {}) as Record<string, unknown>;\n const result = await toolDef.execute(params);\n return typeof result === \"string\" ? result : JSON.stringify(result);\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : String(err);\n return JSON.stringify({ error: `Tool \"${toolName}\" failed: ${message}` });\n }\n };\n}\n","/**\n * Network SDK wrapper — multi-agent delegation backed by Rust core.\n */\nimport {\n create_network,\n network_add_agent,\n network_set_supervisor,\n network_delegate,\n network_agent_cards,\n destroy_network,\n} from \"gauss-napi\";\n\nimport type { Handle, Disposable } from \"./types.js\";\nimport type { Agent } from \"./agent.js\";\n\nexport class Network implements Disposable {\n private readonly _handle: Handle;\n private disposed = false;\n\n constructor() {\n this._handle = create_network();\n }\n\n get handle(): Handle {\n return this._handle;\n }\n\n addAgent(agent: Agent, instructions?: string): this {\n this.assertNotDisposed();\n network_add_agent(\n this._handle,\n agent.name,\n agent.handle,\n instructions\n );\n return this;\n }\n\n setSupervisor(agentName: string): this {\n this.assertNotDisposed();\n network_set_supervisor(this._handle, agentName);\n return this;\n }\n\n async delegate(\n fromAgent: string,\n toAgent: string,\n prompt: string\n ): Promise<unknown> {\n this.assertNotDisposed();\n return network_delegate(this._handle, fromAgent, toAgent, prompt);\n }\n\n agentCards(): unknown {\n this.assertNotDisposed();\n return network_agent_cards(this._handle);\n }\n\n destroy(): void {\n if (!this.disposed) {\n this.disposed = true;\n try {\n destroy_network(this._handle);\n } catch {\n // Already destroyed.\n }\n }\n }\n\n [Symbol.dispose](): void {\n this.destroy();\n }\n\n private assertNotDisposed(): void {\n if (this.disposed) {\n throw new Error(\"Network has been destroyed\");\n }\n }\n}\n"],"mappings":"yaAAA,IAAAA,GAAA,GAAAC,EAAAD,GAAA,WAAAE,EAAA,YA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D,SAAO,YAAS,KAAK,QAASC,CAAQ,CACxC,CAEA,SAAgB,CACd,GAAI,CAAC,KAAK,SAAU,CAClB,KAAK,SAAW,GAChB,GAAI,IACF,gBAAa,KAAK,OAAO,CAC3B,MAAQ,CAER,CACF,CACF,CAEA,CAAC,OAAO,OAAO,GAAU,CACvB,KAAK,QAAQ,CACf,CAEQ,mBAA0B,CAChC,GAAI,KAAK,SAAU,MAAM,IAAIC,EAAc,OAAQ,KAAK,KAAK,CAC/D,CACF,EM5HA,IAAAC,EAOO,sBAKMC,EAAN,KAAoC,CACxB,QACT,SAAW,GAEnB,aAAc,CACZ,KAAK,WAAU,kBAAe,CAChC,CAEA,IAAI,QAAiB,CACnB,OAAO,KAAK,OACd,CAEA,SAASC,EAAcC,EAA6B,CAClD,YAAK,kBAAkB,KACvB,qBACE,KAAK,QACLD,EAAM,KACNA,EAAM,OACNC,CACF,EACO,IACT,CAEA,cAAcC,EAAyB,CACrC,YAAK,kBAAkB,KACvB,0BAAuB,KAAK,QAASA,CAAS,EACvC,IACT,CAEA,MAAM,SACJC,EACAC,EACAC,EACkB,CAClB,YAAK,kBAAkB,KAChB,oBAAiB,KAAK,QAASF,EAAWC,EAASC,CAAM,CAClE,CAEA,YAAsB,CACpB,YAAK,kBAAkB,KAChB,uBAAoB,KAAK,OAAO,CACzC,CAEA,SAAgB,CACd,GAAI,CAAC,KAAK,SAAU,CAClB,KAAK,SAAW,GAChB,GAAI,IACF,mBAAgB,KAAK,OAAO,CAC9B,MAAQ,CAER,CACF,CACF,CAEA,CAAC,OAAO,OAAO,GAAU,CACvB,KAAK,QAAQ,CACf,CAEQ,mBAA0B,CAChC,GAAI,KAAK,SACP,MAAM,IAAI,MAAM,4BAA4B,CAEhD,CACF","names":["orchestration_exports","__export","Graph","Network","Team","Workflow","__toCommonJS","import_gauss_napi","GaussError","code","message","DisposedError","resourceType","resourceName","ValidationError","GaussError","message","field","Graph","_Graph","nodes","graph","node","i","config","a","from","to","router","prompt","targets","entryNodes","n","ValidationError","outputs","currentNodeId","currentPrompt","nodeCfg","agentInput","result","nodeOutput","nodeIds","lastNodeId","DisposedError","import_gauss_napi","Workflow","config","stepId","dependsOn","prompt","import_gauss_napi","import_gauss_napi","OPENAI_DEFAULT","ANTHROPIC_DEFAULT","GOOGLE_DEFAULT","OPENROUTER_DEFAULT","DEEPSEEK_DEFAULT","TOGETHER_DEFAULT","FIREWORKS_DEFAULT","MISTRAL_DEFAULT","PERPLEXITY_DEFAULT","XAI_DEFAULT","PROVIDER_DEFAULTS","OPENAI_DEFAULT","ANTHROPIC_DEFAULT","GOOGLE_DEFAULT","OPENROUTER_DEFAULT","DEEPSEEK_DEFAULT","ENV_KEYS","resolveApiKey","provider","key","detectProvider","checks","env","PROVIDER_DEFAULTS","import_gauss_napi","toSdkResult","raw","c","AgentStream","agentName","providerHandle","tools","messages","options","toolExecutor","buffer","resolve","done","onEvent","json","runPromise","r","tool","config","isTypedTool","t","createToolExecutor","tools","fallback","toolMap","callJson","call","toolName","toolDef","params","result","err","message","toSdkResult","raw","c","Agent","_Agent","config","detected","detectProvider","OPENAI_DEFAULT","apiKey","resolveApiKey","ceOpt","codeExecution","tool","tools","name","description","execute","parameters","options","model","chain","memory","sessionId","client","input","messages","recalled","e","toolDefs","executor","result","userText","m","toolExecutor","typedExecutor","composedExecutor","callJson","onEvent","finalExecutor","NOOP_TOOL_EXECUTOR","AgentStream","onDelta","stream","aggregated","event","delta","DisposedError","typedTools","isTypedTool","t","createToolExecutor","mcpTool","params","resultJson","Team","_Team","teamName","strategy","agents","team","spec","agent","Agent","name","instructions","s","prompt","messages","DisposedError","import_gauss_napi","Network","agent","instructions","agentName","fromAgent","toAgent","prompt"]}
@@ -1,5 +1,5 @@
1
- import { D as Disposable, H as Handle, T as ToolDef } from './types-BayYAhZL.cjs';
2
- import { a as Agent } from './agent-DXZT4Hd-.cjs';
1
+ import { D as Disposable, T as ToolDef, H as Handle } from './types-BayYAhZL.cjs';
2
+ import { a as Agent } from './agent-U5pITdVk.cjs';
3
3
  import './guardrail-BGqhOeWA.cjs';
4
4
  import './memory-BGrAWNqI.cjs';
5
5
 
@@ -21,6 +21,18 @@ interface ForkNodeConfig {
21
21
  consensus?: ConsensusStrategy;
22
22
  }
23
23
  declare class Graph implements Disposable {
24
+ /**
25
+ * Quick graph builder — create a linear pipeline from agents.
26
+ *
27
+ * @example
28
+ * ```ts
29
+ * const result = await Graph.pipeline([
30
+ * { nodeId: "research", agent: researcher },
31
+ * { nodeId: "write", agent: writer },
32
+ * ]).run("Explain quantum computing");
33
+ * ```
34
+ */
35
+ static pipeline(nodes: GraphNodeConfig[]): Graph;
24
36
  private readonly _handle;
25
37
  private disposed;
26
38
  /** Node registry for SDK-level stepping. */
@@ -79,8 +91,26 @@ interface TeamResult {
79
91
  }
80
92
  declare class Team implements Disposable {
81
93
  private readonly _handle;
94
+ private readonly _name;
82
95
  private disposed;
83
96
  private agents;
97
+ /**
98
+ * Quick team builder — create a team from role descriptions.
99
+ *
100
+ * @example
101
+ * ```ts
102
+ * const result = await Team.quick("content-team", "sequential", [
103
+ * { name: "researcher", instructions: "Research topics" },
104
+ * { name: "writer", instructions: "Write summaries" }
105
+ * ]).run("Explain quantum computing");
106
+ * ```
107
+ */
108
+ static quick(teamName: string, strategy: TeamStrategy, agents: Array<{
109
+ name: string;
110
+ provider?: string;
111
+ model?: string;
112
+ instructions?: string;
113
+ }>): Team;
84
114
  constructor(name: string);
85
115
  get handle(): Handle;
86
116
  /** Add an agent to the team. */
@@ -1,5 +1,5 @@
1
- import { D as Disposable, H as Handle, T as ToolDef } from './types-BayYAhZL.js';
2
- import { a as Agent } from './agent-nEZAfWFD.js';
1
+ import { D as Disposable, T as ToolDef, H as Handle } from './types-BayYAhZL.js';
2
+ import { a as Agent } from './agent-Da25i24I.js';
3
3
  import './guardrail-8Z_HuIIT.js';
4
4
  import './memory-U2EleSW-.js';
5
5
 
@@ -21,6 +21,18 @@ interface ForkNodeConfig {
21
21
  consensus?: ConsensusStrategy;
22
22
  }
23
23
  declare class Graph implements Disposable {
24
+ /**
25
+ * Quick graph builder — create a linear pipeline from agents.
26
+ *
27
+ * @example
28
+ * ```ts
29
+ * const result = await Graph.pipeline([
30
+ * { nodeId: "research", agent: researcher },
31
+ * { nodeId: "write", agent: writer },
32
+ * ]).run("Explain quantum computing");
33
+ * ```
34
+ */
35
+ static pipeline(nodes: GraphNodeConfig[]): Graph;
24
36
  private readonly _handle;
25
37
  private disposed;
26
38
  /** Node registry for SDK-level stepping. */
@@ -79,8 +91,26 @@ interface TeamResult {
79
91
  }
80
92
  declare class Team implements Disposable {
81
93
  private readonly _handle;
94
+ private readonly _name;
82
95
  private disposed;
83
96
  private agents;
97
+ /**
98
+ * Quick team builder — create a team from role descriptions.
99
+ *
100
+ * @example
101
+ * ```ts
102
+ * const result = await Team.quick("content-team", "sequential", [
103
+ * { name: "researcher", instructions: "Research topics" },
104
+ * { name: "writer", instructions: "Write summaries" }
105
+ * ]).run("Explain quantum computing");
106
+ * ```
107
+ */
108
+ static quick(teamName: string, strategy: TeamStrategy, agents: Array<{
109
+ name: string;
110
+ provider?: string;
111
+ model?: string;
112
+ instructions?: string;
113
+ }>): Team;
84
114
  constructor(name: string);
85
115
  get handle(): Handle;
86
116
  /** Add an agent to the team. */
@@ -1,4 +1,7 @@
1
- import{create_graph as f,graph_add_node as w,graph_add_edge as k,graph_add_fork_node as v,graph_run as N,destroy_graph as D}from"gauss-napi";var h=class{_handle;disposed=!1;_nodes=new Map;_edges=new Map;_conditionalEdges=new Map;constructor(){this._handle=f()}get handle(){return this._handle}addNode(t){return this.assertNotDisposed(),w(this._handle,t.nodeId,t.agent.name,t.agent.handle,t.instructions,t.tools??[]),this._nodes.set(t.nodeId,{agent:t.agent,instructions:t.instructions}),this}addFork(t){return this.assertNotDisposed(),v(this._handle,t.nodeId,t.agents.map(e=>({agentName:e.agent.name,providerHandle:e.agent.handle,instructions:e.instructions})),t.consensus??"concat"),this}addEdge(t,e){return this.assertNotDisposed(),k(this._handle,t,e),this._edges.set(t,e),this}addConditionalEdge(t,e){return this.assertNotDisposed(),this._conditionalEdges.set(t,e),this}async run(t){return this.assertNotDisposed(),this._conditionalEdges.size===0?N(this._handle,t):this._runWithConditionals(t)}destroy(){if(!this.disposed){this.disposed=!0;try{D(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}async _runWithConditionals(t){let e=new Set([...this._edges.values()]),n=[...this._nodes.keys()].filter(r=>!e.has(r));if(n.length===0)throw new Error("Graph has no entry node (every node has an incoming edge)");let o={},s=n[0],a=t;for(;s;){let r=this._nodes.get(s);if(!r)throw new Error(`Node "${s}" not found in graph`);let y=r.instructions?`${r.instructions}
1
+ import{create_graph as S,graph_add_node as N,graph_add_edge as M,graph_add_fork_node as G,graph_run as H,destroy_graph as K}from"gauss-napi";var m=class extends Error{code;constructor(e,t){super(t),this.name="GaussError",this.code=e}},p=class extends m{resourceType;resourceName;constructor(e,t){super("RESOURCE_DISPOSED",`${e} "${t}" has been destroyed. Create a new instance.`),this.name="DisposedError",this.resourceType=e,this.resourceName=t}};var u=class extends m{field;constructor(e,t){super("VALIDATION_ERROR",t?`Invalid "${t}": ${e}`:e),this.name="ValidationError",this.field=t}};var _=class i{static pipeline(e){let t=new i;for(let s of e)t.addNode(s);for(let s=0;s<e.length-1;s++)t.addEdge(e[s].nodeId,e[s+1].nodeId);return t}_handle;disposed=!1;_nodes=new Map;_edges=new Map;_conditionalEdges=new Map;constructor(){this._handle=S()}get handle(){return this._handle}addNode(e){return this.assertNotDisposed(),N(this._handle,e.nodeId,e.agent.name,e.agent.handle,e.instructions,e.tools??[]),this._nodes.set(e.nodeId,{agent:e.agent,instructions:e.instructions}),this}addFork(e){return this.assertNotDisposed(),G(this._handle,e.nodeId,e.agents.map(t=>({agentName:t.agent.name,providerHandle:t.agent.handle,instructions:t.instructions})),e.consensus??"concat"),this}addEdge(e,t){return this.assertNotDisposed(),M(this._handle,e,t),this._edges.set(e,t),this}addConditionalEdge(e,t){return this.assertNotDisposed(),this._conditionalEdges.set(e,t),this}async run(e){return this.assertNotDisposed(),this._conditionalEdges.size===0?H(this._handle,e):this._runWithConditionals(e)}destroy(){if(!this.disposed){this.disposed=!0;try{K(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}async _runWithConditionals(e){let t=new Set([...this._edges.values()]),s=[...this._nodes.keys()].filter(l=>!t.has(l));if(s.length===0)throw new u("Graph has no entry node (every node has an incoming edge)");let r={},o=s[0],n=e;for(;o;){let l=this._nodes.get(o);if(!l)throw new u(`Node "${o}" not found in graph`);let C=l.instructions?`${l.instructions}
2
2
 
3
- ${a}`:a,i=await r.agent.run(y),_={text:i.text,...i.structuredOutput?{structuredOutput:i.structuredOutput}:{}};o[s]=_;let m=this._conditionalEdges.get(s);m?s=await m(_):s=this._edges.get(s),a=i.text}let u=Object.keys(o),c=u[u.length-1];return{outputs:o,final_text:o[c]?.text??""}}assertNotDisposed(){if(this.disposed)throw new Error("Graph has been destroyed")}};import{create_workflow as x,workflow_add_step as b,workflow_add_dependency as C,workflow_run as R,destroy_workflow as S}from"gauss-napi";var p=class{_handle;disposed=!1;constructor(){this._handle=x()}get handle(){return this._handle}addStep(t){return this.assertNotDisposed(),b(this._handle,t.stepId,t.agent.name,t.agent.handle,t.instructions,t.tools??[]),this}addDependency(t,e){return this.assertNotDisposed(),C(this._handle,t,e),this}async run(t){return this.assertNotDisposed(),R(this._handle,t)}destroy(){if(!this.disposed){this.disposed=!0;try{S(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Workflow has been destroyed")}};import{create_team as T,team_add_agent as A,team_set_strategy as H,team_run as j,destroy_team as E}from"gauss-napi";var l=class{_handle;disposed=!1;agents=[];constructor(t){this._handle=T(t)}get handle(){return this._handle}add(t,e){return this.assertNotDisposed(),A(this._handle,t.name,t.handle,e),this.agents.push(t),this}strategy(t){return this.assertNotDisposed(),H(this._handle,t),this}async run(t){this.assertNotDisposed();let e=JSON.stringify([{role:"user",content:[{type:"text",text:t}]}]);return j(this._handle,e)}destroy(){if(!this.disposed){this.disposed=!0;try{E(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Team has been destroyed")}};import{create_network as I,network_add_agent as P,network_set_supervisor as F,network_delegate as O,network_agent_cards as W,destroy_network as G}from"gauss-napi";var g=class{_handle;disposed=!1;constructor(){this._handle=I()}get handle(){return this._handle}addAgent(t,e){return this.assertNotDisposed(),P(this._handle,t.name,t.handle,e),this}setSupervisor(t){return this.assertNotDisposed(),F(this._handle,t),this}async delegate(t,e,n){return this.assertNotDisposed(),O(this._handle,t,e,n)}agentCards(){return this.assertNotDisposed(),W(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{G(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Network has been destroyed")}};export{h as Graph,g as Network,l as Team,p as Workflow};
3
+ ${n}`:n,c=await l.agent.run(C),E={text:c.text,...c.structuredOutput?{structuredOutput:c.structuredOutput}:{}};r[o]=E;let w=this._conditionalEdges.get(o);w?o=await w(E):o=this._edges.get(o),n=c.text}let a=Object.keys(r),d=a[a.length-1];return{outputs:r,final_text:r[d]?.text??""}}assertNotDisposed(){if(this.disposed)throw new p("Graph","graph")}};import{create_workflow as L,workflow_add_step as U,workflow_add_dependency as F,workflow_run as Y,destroy_workflow as j}from"gauss-napi";var f=class{_handle;disposed=!1;constructor(){this._handle=L()}get handle(){return this._handle}addStep(e){return this.assertNotDisposed(),U(this._handle,e.stepId,e.agent.name,e.agent.handle,e.instructions,e.tools??[]),this}addDependency(e,t){return this.assertNotDisposed(),F(this._handle,e,t),this}async run(e){return this.assertNotDisposed(),Y(this._handle,e)}destroy(){if(!this.disposed){this.disposed=!0;try{j(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Workflow has been destroyed")}};import{create_team as pe,team_add_agent as le,team_set_strategy as ue,team_run as ce,destroy_team as me}from"gauss-napi";import{create_provider as se,destroy_provider as re,agent_run as oe,agent_run_with_tool_executor as O,agent_stream_with_tool_executor as ne,generate as ie,generate_with_tools as ae,get_provider_capabilities as de}from"gauss-napi";var x="gpt-5.2";var $="claude-sonnet-4-20250514";var J="gemini-2.5-flash";var W="openai/gpt-5.2",X="deepseek-chat";var q="meta-llama/Llama-3.3-70B-Instruct-Turbo",B="accounts/fireworks/models/llama-v3p1-70b-instruct",V="mistral-large-latest",z="sonar-pro",Q="grok-3-beta",k={openai:x,anthropic:$,google:J,openrouter:W,deepseek:X,groq:"llama-3.3-70b-versatile",ollama:"llama3.2",together:q,fireworks:B,mistral:V,perplexity:z,xai:Q};var Z={openai:"OPENAI_API_KEY",anthropic:"ANTHROPIC_API_KEY",google:"GOOGLE_API_KEY",groq:"GROQ_API_KEY",deepseek:"DEEPSEEK_API_KEY",openrouter:"OPENROUTER_API_KEY",together:"TOGETHER_API_KEY",fireworks:"FIREWORKS_API_KEY",mistral:"MISTRAL_API_KEY",perplexity:"PERPLEXITY_API_KEY",xai:"XAI_API_KEY",ollama:""};function b(i){let e=Z[i]??"";return e?(typeof process<"u"?process.env[e]:"")??"":""}function R(){let i=[{env:"OPENAI_API_KEY",provider:"openai"},{env:"ANTHROPIC_API_KEY",provider:"anthropic"},{env:"GOOGLE_API_KEY",provider:"google"},{env:"GROQ_API_KEY",provider:"groq"},{env:"DEEPSEEK_API_KEY",provider:"deepseek"},{env:"OPENROUTER_API_KEY",provider:"openrouter"},{env:"TOGETHER_API_KEY",provider:"together"},{env:"FIREWORKS_API_KEY",provider:"fireworks"},{env:"MISTRAL_API_KEY",provider:"mistral"},{env:"PERPLEXITY_API_KEY",provider:"perplexity"},{env:"XAI_API_KEY",provider:"xai"}];for(let{env:e,provider:t}of i)if(typeof process<"u"&&process.env[e])return{provider:t,model:k[t]}}import{agent_stream_with_tool_executor as ee}from"gauss-napi";function te(i){return{...i,citations:i.citations?.map(e=>({type:e.citationType??e.type,citedText:e.citedText,documentTitle:e.documentTitle,start:e.start,end:e.end}))}}var g=class{constructor(e,t,s,r,o,n){this.agentName=e;this.providerHandle=t;this.tools=s;this.messages=r;this.options=o;this.toolExecutor=n}_result;get result(){return this._result}async*[Symbol.asyncIterator](){let e=[],t,s=!1,r=n=>{try{e.push(JSON.parse(n))}catch{e.push({type:"raw",text:n})}t?.()},o=ee(this.agentName,this.providerHandle,this.tools,this.messages,this.options,r,this.toolExecutor).then(n=>{this._result=te(n),s=!0,t?.()});for(;!s||e.length>0;)e.length>0?yield e.shift():s||await new Promise(n=>{t=n});await o}};function P(i){return{name:i.name,description:i.description,parameters:i.parameters,execute:i.execute}}function A(i){return typeof i.execute=="function"}function D(i,e){let t=new Map(i.map(s=>[s.name,s]));return async s=>{let r;try{r=JSON.parse(s)}catch{return JSON.stringify({error:"Invalid tool call JSON"})}let o=r.tool??r.name??"",n=t.get(o);if(!n)return e?e(s):JSON.stringify({error:`Unknown tool: ${o}`});try{let a=r.args??r.arguments??{},d=await n.execute(a);return typeof d=="string"?d:JSON.stringify(d)}catch(a){let d=a instanceof Error?a.message:String(a);return JSON.stringify({error:`Tool "${o}" failed: ${d}`})}}}function h(i){return{...i,citations:i.citations?.map(e=>({type:e.citationType??e.type??"unknown",citedText:e.citedText,documentTitle:e.documentTitle,start:e.start,end:e.end}))}}var y=class i{providerHandle;_name;_provider;_model;_providerOptions;_instructions;_tools=[];_options={};disposed=!1;_middleware=null;_guardrails=null;_memory=null;_sessionId="";_mcpClients=[];_mcpToolsLoaded=!1;constructor(e={}){let t=R();this._provider=e.provider??t?.provider??"openai",this._model=e.model??t?.model??x,this._name=e.name??"agent",this._instructions=e.instructions??"";let s=e.providerOptions?.apiKey??b(this._provider);this._providerOptions={apiKey:s,...e.providerOptions},this.providerHandle=se(this._provider,this._model,this._providerOptions),e.tools&&(this._tools=[...e.tools]),e.middleware&&(this._middleware=e.middleware),e.guardrails&&(this._guardrails=e.guardrails),e.memory&&(this._memory=e.memory),e.sessionId&&(this._sessionId=e.sessionId),e.mcpClients&&(this._mcpClients=[...e.mcpClients]);let r=e.codeExecution,o=r===!0?{python:!0,javascript:!0,bash:!0}:r||void 0;this._options={instructions:this._instructions||void 0,temperature:e.temperature,maxSteps:e.maxSteps,topP:e.topP,maxTokens:e.maxTokens,seed:e.seed,stopOnTool:e.stopOnTool,outputSchema:e.outputSchema,thinkingBudget:e.thinkingBudget,reasoningEffort:e.reasoningEffort,cacheControl:e.cacheControl,codeExecution:o,grounding:e.grounding,nativeCodeExecution:e.nativeCodeExecution,responseModalities:e.responseModalities}}static fromEnv(e={}){return new i(e)}get name(){return this._name}get provider(){return this._provider}get model(){return this._model}get instructions(){return this._instructions}get handle(){return this.providerHandle}get capabilities(){return de(this.providerHandle)}addTool(e){return this._tools.push(e),this}addTools(e){return this._tools.push(...e),this}withTool(e,t,s,r){return this._tools.push(P({name:e,description:t,parameters:r??{},execute:s})),this}setOptions(e){return this._options={...this._options,...e},this}withModel(e){return this.assertNotDisposed(),new i({...this.toConfig(),model:e})}withMiddleware(e){return this._middleware=e,this}withGuardrails(e){return this._guardrails=e,this}withMemory(e,t){return this._memory=e,t&&(this._sessionId=t),this}useMcpServer(e){return this._mcpClients.push(e),this._mcpToolsLoaded=!1,this}async run(e){this.assertNotDisposed(),await this.ensureMcpTools();let t=typeof e=="string"?[{role:"user",content:e}]:[...e];if(this._memory){let n=await this._memory.recall(this._sessionId?{sessionId:this._sessionId}:void 0);n.length>0&&(t=[{role:"system",content:`Previous context:
4
+ ${n.map(d=>d.content).join(`
5
+ `)}`},...t])}let{toolDefs:s,executor:r}=this.resolveToolsAndExecutor(),o;if(r?o=h(await O(this._name,this.providerHandle,s,t,this._options,r)):o=h(await oe(this._name,this.providerHandle,s,t,this._options)),this._memory){let n=typeof e=="string"?e:e.map(a=>a.content).join(`
6
+ `);await this._memory.store({id:`${Date.now()}-user`,content:n,entryType:"conversation",timestamp:new Date().toISOString(),sessionId:this._sessionId||void 0}),await this._memory.store({id:`${Date.now()}-assistant`,content:o.text,entryType:"conversation",timestamp:new Date().toISOString(),sessionId:this._sessionId||void 0})}return o}async runWithTools(e,t){this.assertNotDisposed(),await this.ensureMcpTools();let s=typeof e=="string"?[{role:"user",content:e}]:e,{toolDefs:r,executor:o}=this.resolveToolsAndExecutor(),n=async a=>{if(o){let d=await o(a);if(!JSON.parse(d).error?.startsWith("Unknown tool:"))return d}return t(a)};return h(await O(this._name,this.providerHandle,r,s,this._options,n))}async stream(e,t,s){this.assertNotDisposed(),await this.ensureMcpTools();let r=typeof e=="string"?[{role:"user",content:e}]:e,{toolDefs:o,executor:n}=this.resolveToolsAndExecutor(),a=s??n??I;return h(await ne(this._name,this.providerHandle,o,r,this._options,t,a))}streamIter(e,t){this.assertNotDisposed();let s=typeof e=="string"?[{role:"user",content:e}]:e,{toolDefs:r,executor:o}=this.resolveToolsAndExecutor(),n=t??o??I;return new g(this._name,this.providerHandle,r,s,this._options,n)}async streamText(e,t,s){this.assertNotDisposed();let r=this.streamIter(e,s),o="";for await(let n of r){if(n.type!=="text_delta")continue;let a=typeof n.text=="string"?n.text:typeof n.delta=="string"?n.delta:"";a&&(o+=a,t?.(a))}return r.result?.text??o}async generate(e,t){this.assertNotDisposed();let s=typeof e=="string"?[{role:"user",content:e}]:e;return ie(this.providerHandle,s,t?.temperature,t?.maxTokens)}async generateWithTools(e,t,s){this.assertNotDisposed();let r=typeof e=="string"?[{role:"user",content:e}]:e;return ae(this.providerHandle,r,t,s?.temperature,s?.maxTokens)}destroy(){if(!this.disposed){this.disposed=!0;for(let e of this._mcpClients)try{e.close()}catch{}try{re(this.providerHandle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new p("Agent",this._name)}resolveToolsAndExecutor(){let e=this._tools.filter(A),t=this._tools.map(r=>({name:r.name,description:r.description,parameters:r.parameters})),s=e.length>0?D(e):null;return{toolDefs:t,executor:s}}async ensureMcpTools(){if(!(this._mcpToolsLoaded||this._mcpClients.length===0)){for(let e of this._mcpClients){let{tools:t,executor:s}=await e.getToolsWithExecutor();for(let r of t){let o={...r,execute:async n=>{let a=JSON.stringify({tool:r.name,args:n}),d=await s(a);return JSON.parse(d)}};this._tools.push(o)}}this._mcpToolsLoaded=!0}}toConfig(){return{name:this._name,provider:this._provider,model:this._model,providerOptions:{...this._providerOptions},instructions:this._instructions||void 0,tools:[...this._tools],middleware:this._middleware??void 0,guardrails:this._guardrails??void 0,memory:this._memory??void 0,sessionId:this._sessionId||void 0,mcpClients:[...this._mcpClients],temperature:this._options.temperature,maxSteps:this._options.maxSteps,topP:this._options.topP,maxTokens:this._options.maxTokens,seed:this._options.seed,stopOnTool:this._options.stopOnTool,outputSchema:this._options.outputSchema,thinkingBudget:this._options.thinkingBudget,reasoningEffort:this._options.reasoningEffort,cacheControl:this._options.cacheControl,codeExecution:this._options.codeExecution,grounding:this._options.grounding,nativeCodeExecution:this._options.nativeCodeExecution,responseModalities:this._options.responseModalities}}},I=async()=>"{}";var T=class i{_handle;_name;disposed=!1;agents=[];static quick(e,t,s){let r=new i(e);for(let o of s){let n=new y({name:o.name,provider:o.provider??"openai",model:o.model??"gpt-4o",instructions:o.instructions});r.add(n)}return r.strategy(t),r}constructor(e){this._name=e,this._handle=pe(e)}get handle(){return this._handle}add(e,t){return this.assertNotDisposed(),le(this._handle,e.name,e.handle,t),this.agents.push(e),this}strategy(e){return this.assertNotDisposed(),ue(this._handle,e),this}async run(e){this.assertNotDisposed();let t=JSON.stringify([{role:"user",content:[{type:"text",text:e}]}]);return ce(this._handle,t)}destroy(){if(!this.disposed){this.disposed=!0;try{me(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new p("Team",this._name)}};import{create_network as ge,network_add_agent as he,network_set_supervisor as ye,network_delegate as _e,network_agent_cards as fe,destroy_network as xe}from"gauss-napi";var v=class{_handle;disposed=!1;constructor(){this._handle=ge()}get handle(){return this._handle}addAgent(e,t){return this.assertNotDisposed(),he(this._handle,e.name,e.handle,t),this}setSupervisor(e){return this.assertNotDisposed(),ye(this._handle,e),this}async delegate(e,t,s){return this.assertNotDisposed(),_e(this._handle,e,t,s)}agentCards(){return this.assertNotDisposed(),fe(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{xe(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Network has been destroyed")}};export{_ as Graph,v as Network,T as Team,f as Workflow};
4
7
  //# sourceMappingURL=orchestration.js.map