gauss-ts 2.0.3 → 2.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -181,6 +181,13 @@ const cp = new ControlPlane({
181
181
  cp.setCostUsage({ inputTokens: 1200, outputTokens: 600 });
182
182
  const { url } = await cp.startServer("127.0.0.1", 0);
183
183
  console.log(`Control Plane: ${url}`);
184
+ // SSE stream:
185
+ // single event quick-check -> GET ${url}/api/stream?channel=timeline&once=1
186
+ // multiplex channels -> GET ${url}/api/stream?channels=snapshot,timeline&once=1
187
+ // reconnect/replay cursor -> GET ${url}/api/stream?channel=snapshot&lastEventId=42
188
+ // hosted ops capabilities -> GET ${url}/api/ops/capabilities
189
+ // hosted ops health -> GET ${url}/api/ops/health
190
+ // hosted ops dashboard -> GET ${url}/ops
184
191
  ```
185
192
 
186
193
  ---
package/dist/index.cjs CHANGED
@@ -1,24 +1,28 @@
1
- "use strict";var Re=Object.defineProperty;var Wt=Object.getOwnPropertyDescriptor;var Xt=Object.getOwnPropertyNames;var Qt=Object.prototype.hasOwnProperty;var Zt=(s,e)=>{for(var t in e)Re(s,t,{get:e[t],enumerable:!0})},er=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Xt(e))!Qt.call(s,n)&&n!==t&&Re(s,n,{get:()=>e[n],enumerable:!(r=Wt(e,n))||r.enumerable});return s};var tr=s=>er(Re({},"__esModule",{value:!0}),s);var pr={};Zt(pr,{A2aClient:()=>ke,ANTHROPIC_DEFAULT:()=>Ce,ANTHROPIC_FAST:()=>Qe,ANTHROPIC_PREMIUM:()=>Ze,Agent:()=>b,AgentSpec:()=>V,AgentStream:()=>L,ApprovalManager:()=>ue,CheckpointStore:()=>me,ControlPlane:()=>xe,DEEPSEEK_DEFAULT:()=>Ae,DEEPSEEK_REASONING:()=>rt,DisposedError:()=>k,EvalRunner:()=>he,FIREWORKS_DEFAULT:()=>Me,GOOGLE_DEFAULT:()=>Se,GOOGLE_IMAGE:()=>tt,GOOGLE_PREMIUM:()=>et,GaussError:()=>N,Graph:()=>se,GuardrailChain:()=>ce,MISTRAL_DEFAULT:()=>Oe,McpClient:()=>le,McpServer:()=>pe,Memory:()=>te,MiddlewareChain:()=>ae,Network:()=>ie,OPENAI_DEFAULT:()=>H,OPENAI_FAST:()=>Ye,OPENAI_IMAGE:()=>Xe,OPENAI_REASONING:()=>We,OPENROUTER_DEFAULT:()=>Ee,PERPLEXITY_DEFAULT:()=>Ne,PROVIDER_DEFAULTS:()=>B,PluginRegistry:()=>de,ProviderError:()=>Y,SkillSpec:()=>be,TOGETHER_DEFAULT:()=>De,Team:()=>oe,Telemetry:()=>ge,TextSplitter:()=>I,ToolExecutionError:()=>W,ToolRegistry:()=>we,ToolValidator:()=>Te,ValidationError:()=>O,VectorStore:()=>re,Workflow:()=>ne,XAI_DEFAULT:()=>Ie,agentMessage:()=>Vt,availableRuntimes:()=>lt,batch:()=>dt,classify:()=>Jt,clearPricing:()=>vt,codeReview:()=>Ut,compose:()=>Bt,countMessageTokens:()=>bt,countTokens:()=>_t,countTokensForModel:()=>Tt,createCircuitBreaker:()=>Ct,createFallbackProvider:()=>Rt,createResilientAgent:()=>St,createResilientProvider:()=>qe,createToolExecutor:()=>Z,defaultModel:()=>st,detectProvider:()=>J,discoverAgents:()=>Gt,enforceRoutingCostLimit:()=>je,enforceRoutingRateLimit:()=>He,enterprisePreset:()=>Je,enterpriseRun:()=>at,estimateCost:()=>fe,executeCode:()=>pt,extract:()=>Lt,extractText:()=>ze,filterAsync:()=>$t,gauss:()=>it,generateImage:()=>ct,getContextWindowSize:()=>kt,getPricing:()=>xt,isTypedTool:()=>Q,loadJson:()=>gt,loadMarkdown:()=>ht,loadText:()=>$e,mapAsync:()=>Be,parseAgentConfig:()=>Et,parsePartialJson:()=>Mt,pipe:()=>Ft,reduceAsync:()=>qt,resolveApiKey:()=>U,resolveEnv:()=>At,resolveFallbackProvider:()=>Ue,resolveRoutingTarget:()=>z,retryable:()=>Ot,setPricing:()=>ft,splitText:()=>mt,structured:()=>Nt,summarize:()=>jt,tapAsync:()=>Kt,taskText:()=>Yt,template:()=>j,textMessage:()=>Pe,tool:()=>X,translate:()=>Ht,userMessage:()=>zt,version:()=>Le.version,withRetry:()=>Ke});module.exports=tr(pr);var N=class extends Error{code;constructor(e,t){super(t),this.name="GaussError",this.code=e}},k=class extends N{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}},Y=class extends N{provider;constructor(e,t){super("PROVIDER_ERROR",`[${e}] ${t}`),this.name="ProviderError",this.provider=e}},W=class extends N{toolName;cause;constructor(e,t,r){super("TOOL_EXECUTION_ERROR",`Tool "${e}" failed: ${t}`),this.name="ToolExecutionError",this.toolName=e,this.cause=r}},O=class extends N{field;constructor(e,t){super("VALIDATION_ERROR",t?`Invalid "${t}": ${e}`:e),this.name="ValidationError",this.field=t}};var H="gpt-5.2",Ye="gpt-4.1",We="o4-mini",Xe="gpt-image-1",Ce="claude-sonnet-4-20250514",Qe="claude-haiku-4-20250414",Ze="claude-opus-4-20250414",Se="gemini-2.5-flash",et="gemini-2.5-pro",tt="gemini-2.0-flash",Ee="openai/gpt-5.2",Ae="deepseek-chat",rt="deepseek-reasoner",De="meta-llama/Llama-3.3-70B-Instruct-Turbo",Me="accounts/fireworks/models/llama-v3p1-70b-instruct",Oe="mistral-large-latest",Ne="sonar-pro",Ie="grok-3-beta",B={openai:H,anthropic:Ce,google:Se,openrouter:Ee,deepseek:Ae,groq:"llama-3.3-70b-versatile",ollama:"llama3.2",together:De,fireworks:Me,mistral:Oe,perplexity:Ne,xai:Ie};function st(s){return B[s]??H}var rr={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 U(s){let e=rr[s]??"";return e?(typeof process<"u"?process.env[e]:"")??"":""}function J(){let s=[{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 s)if(typeof process<"u"&&process.env[e])return{provider:t,model:B[t]}}var u=require("gauss-napi");function je(s,e){if(s?.maxTotalCostUsd!==void 0&&e>s.maxTotalCostUsd)throw new Error(`routing policy rejected cost ${e}`)}function He(s,e){if(s?.maxRequestsPerMinute!==void 0&&e>s.maxRequestsPerMinute)throw new Error(`routing policy rejected rate ${e}`)}function Ue(s,e){let t=s?.fallbackOrder;if(!t||t.length===0||e.length===0)return null;let r=new Set(e);for(let n of t)if(r.has(n))return n;return null}function z(s,e,t,r={}){r.estimatedCostUsd!==void 0&&je(s,r.estimatedCostUsd),r.currentRequestsPerMinute!==void 0&&He(s,r.currentRequestsPerMinute);let n=s?.aliases?.[t];if(n&&n.length>0){let i=[...n].sort((l,c)=>(c.priority??0)-(l.priority??0)),a=r.availableProviders;if(!a||a.length===0)return{provider:i[0].provider,model:i[0].model,selectedBy:`alias:${t}`};let d=new Set(a),p=i.find(l=>d.has(l.provider));if(p)return{provider:p.provider,model:p.model,selectedBy:`alias:${t}`}}let o=Ue(s,r.availableProviders??[]);return o&&o!==e?{provider:o,model:t,selectedBy:`fallback:${o}`}:{provider:e,model:t,selectedBy:"direct"}}var nt=require("gauss-napi");function sr(s){return{...s,citations:s.citations?.map(e=>({type:e.citationType??e.type,citedText:e.citedText,documentTitle:e.documentTitle,start:e.start,end:e.end}))}}var L=class{constructor(e,t,r,n,o,i){this.agentName=e;this.providerHandle=t;this.tools=r;this.messages=n;this.options=o;this.toolExecutor=i}_result;get result(){return this._result}async*[Symbol.asyncIterator](){let e=[],t,r=!1,n=i=>{try{e.push(JSON.parse(i))}catch{e.push({type:"raw",text:i})}t?.()},o=(0,nt.agent_stream_with_tool_executor)(this.agentName,this.providerHandle,this.tools,this.messages,this.options,n,this.toolExecutor).then(i=>{this._result=sr(i),r=!0,t?.()});for(;!r||e.length>0;)e.length>0?yield e.shift():r||await new Promise(i=>{t=i});await o}};function X(s){return{name:s.name,description:s.description,parameters:s.parameters,execute:s.execute}}function Q(s){return typeof s.execute=="function"}function Z(s,e){let t=new Map(s.map(r=>[r.name,r]));return async r=>{let n;try{n=JSON.parse(r)}catch{return JSON.stringify({error:"Invalid tool call JSON"})}let o=n.tool??n.name??"",i=t.get(o);if(!i)return e?e(r):JSON.stringify({error:`Unknown tool: ${o}`});try{let a=n.args??n.arguments??{},d=await i.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 ee(s){return{...s,citations:s.citations?.map(e=>({type:e.citationType??e.type??"unknown",citedText:e.citedText,documentTitle:e.documentTitle,start:e.start,end:e.end}))}}var b=class s{providerHandle;_name;_requestedProvider;_requestedModel;_provider;_model;_routingPolicy;_providerOptions;_instructions;_tools=[];_options={};disposed=!1;_middleware=null;_guardrails=null;_memory=null;_sessionId="";_mcpClients=[];_mcpToolsLoaded=!1;constructor(e={}){let t=J(),r=e.provider??t?.provider??"openai",n=e.model??t?.model??H;this._requestedProvider=r,this._requestedModel=n,this._routingPolicy=e.routingPolicy;let o=z(this._routingPolicy,r,n);this._provider=o.provider,this._model=o.model,this._name=e.name??"agent",this._instructions=e.instructions??"";let i=e.providerOptions?.apiKey??U(this._provider);this._providerOptions={apiKey:i,...e.providerOptions},this.providerHandle=(0,u.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 a=e.codeExecution,d=a===!0?{python:!0,javascript:!0,bash:!0}:a||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:d,grounding:e.grounding,nativeCodeExecution:e.nativeCodeExecution,responseModalities:e.responseModalities}}static fromEnv(e={}){return new s(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,u.get_provider_capabilities)(this.providerHandle)}addTool(e){return this._tools.push(e),this}addTools(e){return this._tools.push(...e),this}withTool(e,t,r,n){return this._tools.push(X({name:e,description:t,parameters:n??{},execute:r})),this}setOptions(e){return this._options={...this._options,...e},this}withModel(e){return this.assertNotDisposed(),new s({...this.toConfig(),model:e})}withRoutingContext(e){this.assertNotDisposed();let t=z(this._routingPolicy,this._requestedProvider,this._requestedModel,e);return new s({...this.toConfig(),provider:t.provider,model:t.model})}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:
1
+ "use strict";var Se=Object.defineProperty;var Qt=Object.getOwnPropertyDescriptor;var Zt=Object.getOwnPropertyNames;var er=Object.prototype.hasOwnProperty;var tr=(s,e)=>{for(var t in e)Se(s,t,{get:e[t],enumerable:!0})},rr=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Zt(e))!er.call(s,n)&&n!==t&&Se(s,n,{get:()=>e[n],enumerable:!(r=Qt(e,n))||r.enumerable});return s};var sr=s=>rr(Se({},"__esModule",{value:!0}),s);var cr={};tr(cr,{A2aClient:()=>Pe,ANTHROPIC_DEFAULT:()=>Re,ANTHROPIC_FAST:()=>Ze,ANTHROPIC_PREMIUM:()=>et,Agent:()=>k,AgentSpec:()=>V,AgentStream:()=>F,ApprovalManager:()=>me,CheckpointStore:()=>he,ControlPlane:()=>xe,DEEPSEEK_DEFAULT:()=>De,DEEPSEEK_REASONING:()=>st,DisposedError:()=>P,EvalRunner:()=>ge,FIREWORKS_DEFAULT:()=>Oe,GOOGLE_DEFAULT:()=>Ee,GOOGLE_IMAGE:()=>rt,GOOGLE_PREMIUM:()=>tt,GaussError:()=>I,Graph:()=>ne,GuardrailChain:()=>ue,MISTRAL_DEFAULT:()=>Ie,McpClient:()=>ce,McpServer:()=>pe,Memory:()=>re,MiddlewareChain:()=>de,Network:()=>ae,OPENAI_DEFAULT:()=>L,OPENAI_FAST:()=>We,OPENAI_IMAGE:()=>Qe,OPENAI_REASONING:()=>Xe,OPENROUTER_DEFAULT:()=>Ae,PERPLEXITY_DEFAULT:()=>Ne,PROVIDER_DEFAULTS:()=>K,PluginRegistry:()=>le,ProviderError:()=>W,SkillSpec:()=>ke,TOGETHER_DEFAULT:()=>Me,Team:()=>ie,Telemetry:()=>ye,TextSplitter:()=>j,ToolExecutionError:()=>X,ToolRegistry:()=>we,ToolValidator:()=>be,ValidationError:()=>b,VectorStore:()=>se,Workflow:()=>oe,XAI_DEFAULT:()=>je,agentMessage:()=>Yt,availableRuntimes:()=>ct,batch:()=>lt,classify:()=>Jt,clearPricing:()=>_t,codeReview:()=>Lt,compose:()=>zt,countMessageTokens:()=>kt,countTokens:()=>Tt,countTokensForModel:()=>bt,createCircuitBreaker:()=>Rt,createFallbackProvider:()=>St,createResilientAgent:()=>Et,createResilientProvider:()=>Be,createToolExecutor:()=>ee,defaultModel:()=>nt,detectProvider:()=>G,discoverAgents:()=>Ft,enforceRoutingCostLimit:()=>He,enforceRoutingRateLimit:()=>Ue,enterprisePreset:()=>Je,enterpriseRun:()=>dt,estimateCost:()=>ve,executeCode:()=>pt,extract:()=>Gt,extractText:()=>Ve,filterAsync:()=>qt,gauss:()=>at,generateImage:()=>ut,getContextWindowSize:()=>Pt,getPricing:()=>xt,isTypedTool:()=>Z,loadJson:()=>yt,loadMarkdown:()=>gt,loadText:()=>qe,mapAsync:()=>ze,parseAgentConfig:()=>At,parsePartialJson:()=>Ot,pipe:()=>$t,reduceAsync:()=>Bt,resolveApiKey:()=>J,resolveEnv:()=>Dt,resolveFallbackProvider:()=>Le,resolveRoutingTarget:()=>z,retryable:()=>It,setPricing:()=>vt,splitText:()=>ht,structured:()=>Nt,summarize:()=>Ht,tapAsync:()=>Kt,taskText:()=>Wt,template:()=>U,textMessage:()=>Ce,tool:()=>Q,translate:()=>Ut,userMessage:()=>Vt,version:()=>Ge.version,withRetry:()=>Ke});module.exports=sr(cr);var I=class extends Error{code;constructor(e,t){super(t),this.name="GaussError",this.code=e}},P=class extends I{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}},W=class extends I{provider;constructor(e,t){super("PROVIDER_ERROR",`[${e}] ${t}`),this.name="ProviderError",this.provider=e}},X=class extends I{toolName;cause;constructor(e,t,r){super("TOOL_EXECUTION_ERROR",`Tool "${e}" failed: ${t}`),this.name="ToolExecutionError",this.toolName=e,this.cause=r}},b=class extends I{field;constructor(e,t){super("VALIDATION_ERROR",t?`Invalid "${t}": ${e}`:e),this.name="ValidationError",this.field=t}};var L="gpt-5.2",We="gpt-4.1",Xe="o4-mini",Qe="gpt-image-1",Re="claude-sonnet-4-20250514",Ze="claude-haiku-4-20250414",et="claude-opus-4-20250414",Ee="gemini-2.5-flash",tt="gemini-2.5-pro",rt="gemini-2.0-flash",Ae="openai/gpt-5.2",De="deepseek-chat",st="deepseek-reasoner",Me="meta-llama/Llama-3.3-70B-Instruct-Turbo",Oe="accounts/fireworks/models/llama-v3p1-70b-instruct",Ie="mistral-large-latest",Ne="sonar-pro",je="grok-3-beta",K={openai:L,anthropic:Re,google:Ee,openrouter:Ae,deepseek:De,groq:"llama-3.3-70b-versatile",ollama:"llama3.2",together:Me,fireworks:Oe,mistral:Ie,perplexity:Ne,xai:je};function nt(s){return K[s]??L}var nr={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 J(s){let e=nr[s]??"";return e?(typeof process<"u"?process.env[e]:"")??"":""}function G(){let s=[{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 s)if(typeof process<"u"&&process.env[e])return{provider:t,model:K[t]}}var u=require("gauss-napi");function He(s,e){if(s?.maxTotalCostUsd!==void 0&&e>s.maxTotalCostUsd)throw new Error(`routing policy rejected cost ${e}`)}function Ue(s,e){if(s?.maxRequestsPerMinute!==void 0&&e>s.maxRequestsPerMinute)throw new Error(`routing policy rejected rate ${e}`)}function Le(s,e){let t=s?.fallbackOrder;if(!t||t.length===0||e.length===0)return null;let r=new Set(e);for(let n of t)if(r.has(n))return n;return null}function z(s,e,t,r={}){r.estimatedCostUsd!==void 0&&He(s,r.estimatedCostUsd),r.currentRequestsPerMinute!==void 0&&Ue(s,r.currentRequestsPerMinute);let n=s?.aliases?.[t];if(n&&n.length>0){let i=[...n].sort((p,c)=>(c.priority??0)-(p.priority??0)),a=r.availableProviders;if(!a||a.length===0)return{provider:i[0].provider,model:i[0].model,selectedBy:`alias:${t}`};let d=new Set(a),l=i.find(p=>d.has(p.provider));if(l)return{provider:l.provider,model:l.model,selectedBy:`alias:${t}`}}let o=Le(s,r.availableProviders??[]);return o&&o!==e?{provider:o,model:t,selectedBy:`fallback:${o}`}:{provider:e,model:t,selectedBy:"direct"}}var ot=require("gauss-napi");function or(s){return{...s,citations:s.citations?.map(e=>({type:e.citationType??e.type,citedText:e.citedText,documentTitle:e.documentTitle,start:e.start,end:e.end}))}}var F=class{constructor(e,t,r,n,o,i){this.agentName=e;this.providerHandle=t;this.tools=r;this.messages=n;this.options=o;this.toolExecutor=i}_result;get result(){return this._result}async*[Symbol.asyncIterator](){let e=[],t,r=!1,n=i=>{try{e.push(JSON.parse(i))}catch{e.push({type:"raw",text:i})}t?.()},o=(0,ot.agent_stream_with_tool_executor)(this.agentName,this.providerHandle,this.tools,this.messages,this.options,n,this.toolExecutor).then(i=>{this._result=or(i),r=!0,t?.()});for(;!r||e.length>0;)e.length>0?yield e.shift():r||await new Promise(i=>{t=i});await o}};function Q(s){return{name:s.name,description:s.description,parameters:s.parameters,execute:s.execute}}function Z(s){return typeof s.execute=="function"}function ee(s,e){let t=new Map(s.map(r=>[r.name,r]));return async r=>{let n;try{n=JSON.parse(r)}catch{return JSON.stringify({error:"Invalid tool call JSON"})}let o=n.tool??n.name??"",i=t.get(o);if(!i)return e?e(r):JSON.stringify({error:`Unknown tool: ${o}`});try{let a=n.args??n.arguments??{},d=await i.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 te(s){return{...s,citations:s.citations?.map(e=>({type:e.citationType??e.type??"unknown",citedText:e.citedText,documentTitle:e.documentTitle,start:e.start,end:e.end}))}}var k=class s{providerHandle;_name;_requestedProvider;_requestedModel;_provider;_model;_routingPolicy;_providerOptions;_instructions;_tools=[];_options={};disposed=!1;_middleware=null;_guardrails=null;_memory=null;_sessionId="";_mcpClients=[];_mcpToolsLoaded=!1;constructor(e={}){let t=G(),r=e.provider??t?.provider??"openai",n=e.model??t?.model??L;this._requestedProvider=r,this._requestedModel=n,this._routingPolicy=e.routingPolicy;let o=z(this._routingPolicy,r,n);this._provider=o.provider,this._model=o.model,this._name=e.name??"agent",this._instructions=e.instructions??"";let i=e.providerOptions?.apiKey??J(this._provider);this._providerOptions={apiKey:i,...e.providerOptions},this.providerHandle=(0,u.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 a=e.codeExecution,d=a===!0?{python:!0,javascript:!0,bash:!0}:a||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:d,grounding:e.grounding,nativeCodeExecution:e.nativeCodeExecution,responseModalities:e.responseModalities}}static fromEnv(e={}){return new s(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,u.get_provider_capabilities)(this.providerHandle)}addTool(e){return this._tools.push(e),this}addTools(e){return this._tools.push(...e),this}withTool(e,t,r,n){return this._tools.push(Q({name:e,description:t,parameters:n??{},execute:r})),this}setOptions(e){return this._options={...this._options,...e},this}withModel(e){return this.assertNotDisposed(),new s({...this.toConfig(),model:e})}withRoutingContext(e){this.assertNotDisposed();let t=z(this._routingPolicy,this._requestedProvider,this._requestedModel,e);return new s({...this.toConfig(),provider:t.provider,model:t.model})}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:
2
2
  ${i.map(d=>d.content).join(`
3
- `)}`},...t])}let{toolDefs:r,executor:n}=this.resolveToolsAndExecutor(),o;if(n?o=ee(await(0,u.agent_run_with_tool_executor)(this._name,this.providerHandle,r,t,this._options,n)):o=ee(await(0,u.agent_run)(this._name,this.providerHandle,r,t,this._options)),this._memory){let i=typeof e=="string"?e:e.map(a=>a.content).join(`
4
- `);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: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 r=typeof e=="string"?[{role:"user",content:e}]:e,{toolDefs:n,executor:o}=this.resolveToolsAndExecutor(),i=async a=>{if(o){let d=await o(a);if(!JSON.parse(d).error?.startsWith("Unknown tool:"))return d}return t(a)};return ee(await(0,u.agent_run_with_tool_executor)(this._name,this.providerHandle,n,r,this._options,i))}async stream(e,t,r){this.assertNotDisposed(),await this.ensureMcpTools();let n=typeof e=="string"?[{role:"user",content:e}]:e,{toolDefs:o,executor:i}=this.resolveToolsAndExecutor(),a=r??i??ot;return ee(await(0,u.agent_stream_with_tool_executor)(this._name,this.providerHandle,o,n,this._options,t,a))}streamIter(e,t){this.assertNotDisposed();let r=typeof e=="string"?[{role:"user",content:e}]:e,{toolDefs:n,executor:o}=this.resolveToolsAndExecutor(),i=t??o??ot;return new L(this._name,this.providerHandle,n,r,this._options,i)}async streamText(e,t,r){this.assertNotDisposed();let n=this.streamIter(e,r),o="";for await(let i of n){if(i.type!=="text_delta")continue;let a=typeof i.text=="string"?i.text:typeof i.delta=="string"?i.delta:"";a&&(o+=a,t?.(a))}return n.result?.text??o}async generate(e,t){this.assertNotDisposed();let r=typeof e=="string"?[{role:"user",content:e}]:e;return(0,u.generate)(this.providerHandle,r,t?.temperature,t?.maxTokens)}async generateWithTools(e,t,r){this.assertNotDisposed();let n=typeof e=="string"?[{role:"user",content:e}]:e;return(0,u.generate_with_tools)(this.providerHandle,n,t,r?.temperature,r?.maxTokens)}destroy(){if(!this.disposed){this.disposed=!0;for(let e of this._mcpClients)try{e.close()}catch{}try{(0,u.destroy_provider)(this.providerHandle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new k("Agent",this._name)}resolveToolsAndExecutor(){let e=this._tools.filter(Q),t=this._tools.map(n=>({name:n.name,description:n.description,parameters:n.parameters})),r=e.length>0?Z(e):null;return{toolDefs:t,executor:r}}async ensureMcpTools(){if(!(this._mcpToolsLoaded||this._mcpClients.length===0)){for(let e of this._mcpClients){let{tools:t,executor:r}=await e.getToolsWithExecutor();for(let n of t){let o={...n,execute:async i=>{let a=JSON.stringify({tool:n.name,args:i}),d=await r(a);return JSON.parse(d)}};this._tools.push(o)}}this._mcpToolsLoaded=!0}}toConfig(){return{name:this._name,provider:this._requestedProvider,model:this._requestedModel,routingPolicy:this._routingPolicy,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}}},ot=async()=>"{}";async function it(s,e){let t=new b({name:"gauss",...e});try{return(await t.run(s)).text}finally{t.destroy()}}function Je(s={}){let e=s.providerOptions?.maxRetries??s.retries??5;return new b({...s,name:s.name??"enterprise-agent",maxSteps:s.maxSteps??20,temperature:s.temperature??.2,cacheControl:s.cacheControl??!0,reasoningEffort:s.reasoningEffort??"medium",providerOptions:{...s.providerOptions,maxRetries:e}})}async function at(s,e){let t=Je(e);try{return(await t.run(s)).text}finally{t.destroy()}}async function dt(s,e){let{concurrency:t=5,...r}=e??{},n=s.map(i=>({input:i})),o=new b({name:"batch",...r});try{let i=[...n.entries()],a=Array.from({length:Math.min(t,i.length)},async()=>{for(;i.length>0;){let d=i.shift();if(!d)break;let[p,l]=d;try{n[p].result=await o.run(l.input)}catch(c){n[p].error=c instanceof Error?c:new Error(String(c))}}});await Promise.all(a)}finally{o.destroy()}return n}var P=require("gauss-napi");var Le=require("gauss-napi");async function pt(s,e,t){return(0,P.execute_code)(s,e,t?.timeoutSecs,t?.workingDir,t?.sandbox)}async function lt(){return(0,P.available_runtimes)()}async function ct(s,e={}){let t=J(),r=e.provider??t?.provider??"openai",n=e.model??t?.model??"dall-e-3",o=e.providerOptions?.apiKey??U(r),i=(0,P.create_provider)(r,n,{apiKey:o,...e.providerOptions});try{return await(0,P.generate_image)(i,s,e.model,e.size,e.quality,e.style,e.aspectRatio,e.n,e.responseFormat)}finally{(0,P.destroy_provider)(i)}}var ut=require("crypto"),h=require("gauss-napi"),te=class{_handle;disposed=!1;constructor(){this._handle=(0,h.create_memory)()}get handle(){return this._handle}async store(e,t,r){this.assertNotDisposed();let n=typeof e=="string"?{id:(0,ut.randomUUID)(),content:t,entryType:e||"conversation",timestamp:new Date().toISOString(),sessionId:r}:e,o={id:n.id,content:n.content,entry_type:n.entryType,timestamp:n.timestamp,tier:n.tier,metadata:n.metadata,importance:n.importance,session_id:n.sessionId,embedding:n.embedding};return(0,h.memory_store)(this._handle,JSON.stringify(o))}async recall(e){this.assertNotDisposed();let t=e?JSON.stringify(e):void 0;return(0,h.memory_recall)(this._handle,t)}async clear(e){return this.assertNotDisposed(),(0,h.memory_clear)(this._handle,e)}async stats(){return this.assertNotDisposed(),(0,h.memory_stats)(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,h.destroy_memory)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Memory has been destroyed")}};var w=require("gauss-napi"),re=class{_handle;disposed=!1;constructor(e){this._handle=(0,w.create_vector_store)()}get handle(){return this._handle}async upsert(e){this.assertNotDisposed();let t=e.map(r=>({id:r.id,document_id:r.documentId,content:r.content,index:r.index,metadata:r.metadata??{},embedding:r.embedding}));return(0,w.vector_store_upsert)(this._handle,JSON.stringify(t))}async search(e,t){return this.assertNotDisposed(),(0,w.vector_store_search)(this._handle,JSON.stringify(e),t)}async searchByText(e,t,r){this.assertNotDisposed();let n=await r(e);return this.search(n,t)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,w.destroy_vector_store)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("VectorStore has been destroyed")}static cosineSimilarity(e,t){return(0,w.cosine_similarity)(e,t)}};var nr=[`
3
+ `)}`},...t])}let{toolDefs:r,executor:n}=this.resolveToolsAndExecutor(),o;if(n?o=te(await(0,u.agent_run_with_tool_executor)(this._name,this.providerHandle,r,t,this._options,n)):o=te(await(0,u.agent_run)(this._name,this.providerHandle,r,t,this._options)),this._memory){let i=typeof e=="string"?e:e.map(a=>a.content).join(`
4
+ `);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: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 r=typeof e=="string"?[{role:"user",content:e}]:e,{toolDefs:n,executor:o}=this.resolveToolsAndExecutor(),i=async a=>{if(o){let d=await o(a);if(!JSON.parse(d).error?.startsWith("Unknown tool:"))return d}return t(a)};return te(await(0,u.agent_run_with_tool_executor)(this._name,this.providerHandle,n,r,this._options,i))}async stream(e,t,r){this.assertNotDisposed(),await this.ensureMcpTools();let n=typeof e=="string"?[{role:"user",content:e}]:e,{toolDefs:o,executor:i}=this.resolveToolsAndExecutor(),a=r??i??it;return te(await(0,u.agent_stream_with_tool_executor)(this._name,this.providerHandle,o,n,this._options,t,a))}streamIter(e,t){this.assertNotDisposed();let r=typeof e=="string"?[{role:"user",content:e}]:e,{toolDefs:n,executor:o}=this.resolveToolsAndExecutor(),i=t??o??it;return new F(this._name,this.providerHandle,n,r,this._options,i)}async streamText(e,t,r){this.assertNotDisposed();let n=this.streamIter(e,r),o="";for await(let i of n){if(i.type!=="text_delta")continue;let a=typeof i.text=="string"?i.text:typeof i.delta=="string"?i.delta:"";a&&(o+=a,t?.(a))}return n.result?.text??o}async generate(e,t){this.assertNotDisposed();let r=typeof e=="string"?[{role:"user",content:e}]:e;return(0,u.generate)(this.providerHandle,r,t?.temperature,t?.maxTokens)}async generateWithTools(e,t,r){this.assertNotDisposed();let n=typeof e=="string"?[{role:"user",content:e}]:e;return(0,u.generate_with_tools)(this.providerHandle,n,t,r?.temperature,r?.maxTokens)}destroy(){if(!this.disposed){this.disposed=!0;for(let e of this._mcpClients)try{e.close()}catch{}try{(0,u.destroy_provider)(this.providerHandle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new P("Agent",this._name)}resolveToolsAndExecutor(){let e=this._tools.filter(Z),t=this._tools.map(n=>({name:n.name,description:n.description,parameters:n.parameters})),r=e.length>0?ee(e):null;return{toolDefs:t,executor:r}}async ensureMcpTools(){if(!(this._mcpToolsLoaded||this._mcpClients.length===0)){for(let e of this._mcpClients){let{tools:t,executor:r}=await e.getToolsWithExecutor();for(let n of t){let o={...n,execute:async i=>{let a=JSON.stringify({tool:n.name,args:i}),d=await r(a);return JSON.parse(d)}};this._tools.push(o)}}this._mcpToolsLoaded=!0}}toConfig(){return{name:this._name,provider:this._requestedProvider,model:this._requestedModel,routingPolicy:this._routingPolicy,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}}},it=async()=>"{}";async function at(s,e){let t=new k({name:"gauss",...e});try{return(await t.run(s)).text}finally{t.destroy()}}function Je(s={}){let e=s.providerOptions?.maxRetries??s.retries??5;return new k({...s,name:s.name??"enterprise-agent",maxSteps:s.maxSteps??20,temperature:s.temperature??.2,cacheControl:s.cacheControl??!0,reasoningEffort:s.reasoningEffort??"medium",providerOptions:{...s.providerOptions,maxRetries:e}})}async function dt(s,e){let t=Je(e);try{return(await t.run(s)).text}finally{t.destroy()}}async function lt(s,e){let{concurrency:t=5,...r}=e??{},n=s.map(i=>({input:i})),o=new k({name:"batch",...r});try{let i=[...n.entries()],a=Array.from({length:Math.min(t,i.length)},async()=>{for(;i.length>0;){let d=i.shift();if(!d)break;let[l,p]=d;try{n[l].result=await o.run(p.input)}catch(c){n[l].error=c instanceof Error?c:new Error(String(c))}}});await Promise.all(a)}finally{o.destroy()}return n}var C=require("gauss-napi");var Ge=require("gauss-napi");async function pt(s,e,t){return(0,C.execute_code)(s,e,t?.timeoutSecs,t?.workingDir,t?.sandbox)}async function ct(){return(0,C.available_runtimes)()}async function ut(s,e={}){let t=G(),r=e.provider??t?.provider??"openai",n=e.model??t?.model??"dall-e-3",o=e.providerOptions?.apiKey??J(r),i=(0,C.create_provider)(r,n,{apiKey:o,...e.providerOptions});try{return await(0,C.generate_image)(i,s,e.model,e.size,e.quality,e.style,e.aspectRatio,e.n,e.responseFormat)}finally{(0,C.destroy_provider)(i)}}var mt=require("crypto"),h=require("gauss-napi"),re=class{_handle;disposed=!1;constructor(){this._handle=(0,h.create_memory)()}get handle(){return this._handle}async store(e,t,r){this.assertNotDisposed();let n=typeof e=="string"?{id:(0,mt.randomUUID)(),content:t,entryType:e||"conversation",timestamp:new Date().toISOString(),sessionId:r}:e,o={id:n.id,content:n.content,entry_type:n.entryType,timestamp:n.timestamp,tier:n.tier,metadata:n.metadata,importance:n.importance,session_id:n.sessionId,embedding:n.embedding};return(0,h.memory_store)(this._handle,JSON.stringify(o))}async recall(e){this.assertNotDisposed();let t=e?JSON.stringify(e):void 0;return(0,h.memory_recall)(this._handle,t)}async clear(e){return this.assertNotDisposed(),(0,h.memory_clear)(this._handle,e)}async stats(){return this.assertNotDisposed(),(0,h.memory_stats)(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,h.destroy_memory)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Memory has been destroyed")}};var w=require("gauss-napi"),se=class{_handle;disposed=!1;constructor(e){this._handle=(0,w.create_vector_store)()}get handle(){return this._handle}async upsert(e){this.assertNotDisposed();let t=e.map(r=>({id:r.id,document_id:r.documentId,content:r.content,index:r.index,metadata:r.metadata??{},embedding:r.embedding}));return(0,w.vector_store_upsert)(this._handle,JSON.stringify(t))}async search(e,t){return this.assertNotDisposed(),(0,w.vector_store_search)(this._handle,JSON.stringify(e),t)}async searchByText(e,t,r){this.assertNotDisposed();let n=await r(e);return this.search(n,t)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,w.destroy_vector_store)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("VectorStore has been destroyed")}static cosineSimilarity(e,t){return(0,w.cosine_similarity)(e,t)}};var ir=[`
5
5
 
6
6
  `,`
7
- `,". "," ",""],I=class{chunkSize;chunkOverlap;separators;constructor(e={}){this.chunkSize=e.chunkSize??1e3,this.chunkOverlap=e.chunkOverlap??200,this.separators=e.separators??nr}split(e){return this._splitRecursive(e,this.separators).map((r,n)=>({content:r,index:n}))}_splitRecursive(e,t){if(e.length<=this.chunkSize)return[e];let r=t[0]??"",n=t.slice(1),o=r?e.split(r):[...e],i=[],a="";for(let d of o){let p=a?a+r+d:d;if(p.length>this.chunkSize&&a){i.push(a);let l=Math.max(0,a.length-this.chunkOverlap);if(a=a.slice(l)+r+d,a.length>this.chunkSize&&n.length>0){let c=this._splitRecursive(a,n);a=c.pop()??"",i.push(...c)}}else a=p}return a&&i.push(a),i}};function mt(s,e){return new I(e).split(s)}var Ge=require("fs/promises"),Fe=require("path");async function $e(s,e={}){let t=!s.includes(`
8
- `)&&s.length<500,r,n;if(t)try{r=await(0,Ge.readFile)(s,"utf-8"),n=e.documentId??(0,Fe.basename)(s)}catch{r=s,n=e.documentId??"text-document"}else r=s,n=e.documentId??"text-document";let a=new I(e).split(r).map(d=>({id:`${n}-${d.index}`,documentId:n,content:d.content,index:d.index,metadata:{...e.metadata,...d.metadata}}));return{documentId:n,content:r,chunks:a,metadata:e.metadata??{}}}async function ht(s,e={}){let t=await $e(s,{...e,separators:[`
7
+ `,". "," ",""],j=class{chunkSize;chunkOverlap;separators;constructor(e={}){this.chunkSize=e.chunkSize??1e3,this.chunkOverlap=e.chunkOverlap??200,this.separators=e.separators??ir}split(e){return this._splitRecursive(e,this.separators).map((r,n)=>({content:r,index:n}))}_splitRecursive(e,t){if(e.length<=this.chunkSize)return[e];let r=t[0]??"",n=t.slice(1),o=r?e.split(r):[...e],i=[],a="";for(let d of o){let l=a?a+r+d:d;if(l.length>this.chunkSize&&a){i.push(a);let p=Math.max(0,a.length-this.chunkOverlap);if(a=a.slice(p)+r+d,a.length>this.chunkSize&&n.length>0){let c=this._splitRecursive(a,n);a=c.pop()??"",i.push(...c)}}else a=l}return a&&i.push(a),i}};function ht(s,e){return new j(e).split(s)}var Fe=require("fs/promises"),$e=require("path");async function qe(s,e={}){let t=!s.includes(`
8
+ `)&&s.length<500,r,n;if(t)try{r=await(0,Fe.readFile)(s,"utf-8"),n=e.documentId??(0,$e.basename)(s)}catch{r=s,n=e.documentId??"text-document"}else r=s,n=e.documentId??"text-document";let a=new j(e).split(r).map(d=>({id:`${n}-${d.index}`,documentId:n,content:d.content,index:d.index,metadata:{...e.metadata,...d.metadata}}));return{documentId:n,content:r,chunks:a,metadata:e.metadata??{}}}async function gt(s,e={}){let t=await qe(s,{...e,separators:[`
9
9
  ## `,`
10
10
  ### `,`
11
11
 
12
12
  `,`
13
- `,". "," "]});return t.content=t.content.replace(/^---[\s\S]*?---\n?/,""),t}async function gt(s,e={}){let t,r;if(!s.includes(`
14
- `)&&s.length<500)try{t=await(0,Ge.readFile)(s,"utf-8"),r=e.documentId??(0,Fe.basename)(s)}catch{t=s,r=e.documentId??"json-document"}else t=s,r=e.documentId??"json-document";let o=JSON.parse(t),i=[];if(Array.isArray(o))o.forEach((d,p)=>{let l=e.textField?String(d[e.textField]??""):JSON.stringify(d);i.push({key:String(p),text:l})});else if(typeof o=="object"&&o!==null)for(let[d,p]of Object.entries(o)){let l=typeof p=="string"?p:JSON.stringify(p);i.push({key:d,text:l})}let a=i.map((d,p)=>({id:`${r}-${d.key}`,documentId:r,content:d.text,index:p,metadata:{...e.metadata,key:d.key}}));return{documentId:r,content:t,chunks:a,metadata:e.metadata??{}}}var g=require("gauss-napi");var se=class s{static pipeline(e){let t=new s;for(let r of e)t.addNode(r);for(let r=0;r<e.length-1;r++)t.addEdge(e[r].nodeId,e[r+1].nodeId);return t}_handle;disposed=!1;_nodes=new Map;_edges=new Map;_conditionalEdges=new Map;constructor(){this._handle=(0,g.create_graph)()}get handle(){return this._handle}addNode(e){return this.assertNotDisposed(),(0,g.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,g.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,g.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,g.graph_run)(this._handle,e):this._runWithConditionals(e)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,g.destroy_graph)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}async _runWithConditionals(e){let t=new Set([...this._edges.values()]),r=[...this._nodes.keys()].filter(p=>!t.has(p));if(r.length===0)throw new O("Graph has no entry node (every node has an incoming edge)");let n={},o=r[0],i=e;for(;o;){let p=this._nodes.get(o);if(!p)throw new O(`Node "${o}" not found in graph`);let l=p.instructions?`${p.instructions}
13
+ `,". "," "]});return t.content=t.content.replace(/^---[\s\S]*?---\n?/,""),t}async function yt(s,e={}){let t,r;if(!s.includes(`
14
+ `)&&s.length<500)try{t=await(0,Fe.readFile)(s,"utf-8"),r=e.documentId??(0,$e.basename)(s)}catch{t=s,r=e.documentId??"json-document"}else t=s,r=e.documentId??"json-document";let o=JSON.parse(t),i=[];if(Array.isArray(o))o.forEach((d,l)=>{let p=e.textField?String(d[e.textField]??""):JSON.stringify(d);i.push({key:String(l),text:p})});else if(typeof o=="object"&&o!==null)for(let[d,l]of Object.entries(o)){let p=typeof l=="string"?l:JSON.stringify(l);i.push({key:d,text:p})}let a=i.map((d,l)=>({id:`${r}-${d.key}`,documentId:r,content:d.text,index:l,metadata:{...e.metadata,key:d.key}}));return{documentId:r,content:t,chunks:a,metadata:e.metadata??{}}}var g=require("gauss-napi");var ne=class s{static pipeline(e){let t=new s;for(let r of e)t.addNode(r);for(let r=0;r<e.length-1;r++)t.addEdge(e[r].nodeId,e[r+1].nodeId);return t}_handle;disposed=!1;_nodes=new Map;_edges=new Map;_conditionalEdges=new Map;constructor(){this._handle=(0,g.create_graph)()}get handle(){return this._handle}addNode(e){return this.assertNotDisposed(),(0,g.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,g.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,g.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,g.graph_run)(this._handle,e):this._runWithConditionals(e)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,g.destroy_graph)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}async _runWithConditionals(e){let t=new Set([...this._edges.values()]),r=[...this._nodes.keys()].filter(l=>!t.has(l));if(r.length===0)throw new b("Graph has no entry node (every node has an incoming edge)");let n={},o=r[0],i=e;for(;o;){let l=this._nodes.get(o);if(!l)throw new b(`Node "${o}" not found in graph`);let p=l.instructions?`${l.instructions}
15
15
 
16
- ${i}`:i,c=await p.agent.run(l),K={text:c.text,...c.structuredOutput?{structuredOutput:c.structuredOutput}:{}};n[o]=K;let Ve=this._conditionalEdges.get(o);Ve?o=await Ve(K):o=this._edges.get(o),i=c.text}let a=Object.keys(n),d=a[a.length-1];return{outputs:n,final_text:n[d]?.text??""}}assertNotDisposed(){if(this.disposed)throw new k("Graph","graph")}};var R=require("gauss-napi"),ne=class{_handle;disposed=!1;constructor(){this._handle=(0,R.create_workflow)()}get handle(){return this._handle}addStep(e){return this.assertNotDisposed(),(0,R.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,R.workflow_add_dependency)(this._handle,e,t),this}async run(e){return this.assertNotDisposed(),(0,R.workflow_run)(this._handle,e)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,R.destroy_workflow)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Workflow has been destroyed")}};var C=require("gauss-napi");var oe=class s{_handle;_name;disposed=!1;agents=[];static quick(e,t,r){let n=new s(e);for(let o of r){let i=new b({name:o.name,provider:o.provider??"openai",model:o.model??"gpt-4o",instructions:o.instructions});n.add(i)}return n.strategy(t),n}constructor(e){this._name=e,this._handle=(0,C.create_team)(e)}get handle(){return this._handle}add(e,t){return this.assertNotDisposed(),(0,C.team_add_agent)(this._handle,e.name,e.handle,t),this.agents.push(e),this}strategy(e){return this.assertNotDisposed(),(0,C.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,C.team_run)(this._handle,t)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,C.destroy_team)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new k("Team",this._name)}};var y=require("gauss-napi"),ie=class{_handle;disposed=!1;constructor(){this._handle=(0,y.create_network)()}get handle(){return this._handle}addAgent(e,t){return this.assertNotDisposed(),(0,y.network_add_agent)(this._handle,e.name,e.handle,t),this}setSupervisor(e){return this.assertNotDisposed(),(0,y.network_set_supervisor)(this._handle,e),this}async delegate(e,t,r){return this.assertNotDisposed(),(0,y.network_delegate)(this._handle,e,t,r)}agentCards(){return this.assertNotDisposed(),(0,y.network_agent_cards)(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,y.destroy_network)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Network has been destroyed")}};var S=require("gauss-napi"),ae=class{_handle;disposed=!1;constructor(){this._handle=(0,S.create_middleware_chain)()}get handle(){return this._handle}useLogging(){return this.assertNotDisposed(),(0,S.middleware_use_logging)(this._handle),this}useCaching(e){return this.assertNotDisposed(),(0,S.middleware_use_caching)(this._handle,e),this}useRateLimit(e,t){return this.assertNotDisposed(),(0,S.middleware_use_rate_limit)(this._handle,e,t),this}destroy(){if(!this.disposed){this.disposed=!0;try{(0,S.destroy_middleware_chain)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("MiddlewareChain has been destroyed")}};var f=require("gauss-napi"),de=class{_handle;disposed=!1;constructor(){this._handle=(0,f.create_plugin_registry)()}get handle(){return this._handle}addTelemetry(){return this.assertNotDisposed(),(0,f.plugin_registry_add_telemetry)(this._handle),this}addMemory(){return this.assertNotDisposed(),(0,f.plugin_registry_add_memory)(this._handle),this}list(){return this.assertNotDisposed(),(0,f.plugin_registry_list)(this._handle)}emit(e){this.assertNotDisposed(),(0,f.plugin_registry_emit)(this._handle,JSON.stringify(e))}destroy(){if(!this.disposed){this.disposed=!0;try{(0,f.destroy_plugin_registry)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("PluginRegistry has been destroyed")}};var x=require("gauss-napi"),pe=class{_handle;disposed=!1;constructor(e,t){this._handle=(0,x.create_mcp_server)(e,t)}get handle(){return this._handle}addTool(e){this.assertNotDisposed();let t={name:e.name,description:e.description,inputSchema:e.parameters??{type:"object"}};return(0,x.mcp_server_add_tool)(this._handle,JSON.stringify(t)),this}addResource(e){return this.assertNotDisposed(),(0,x.mcpServerAddResource)(this._handle,JSON.stringify(e)),this}addPrompt(e){return this.assertNotDisposed(),(0,x.mcpServerAddPrompt)(this._handle,JSON.stringify(e)),this}async handleMessage(e){return this.assertNotDisposed(),(0,x.mcp_server_handle)(this._handle,JSON.stringify(e))}destroy(){if(!this.disposed){this.disposed=!0;try{(0,x.destroy_mcp_server)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("McpServer has been destroyed")}};var yt=require("child_process"),le=class{config;process=null;connected=!1;closed=!1;nextId=1;pending=new Map;buffer="";serverCapabilities={};cachedTools=null;constructor(e){this.config=e}async connect(){if(this.connected)return;if(this.closed)throw new Error("McpClient has been closed");let e=this.config.timeoutMs??1e4;this.process=(0,yt.spawn)(this.config.command,this.config.args??[],{stdio:["pipe","pipe","pipe"],env:{...process.env,...this.config.env}}),this.process.stdout.on("data",r=>this.onData(r)),this.process.stderr.on("data",()=>{}),this.process.on("error",r=>this.onProcessError(r)),this.process.on("close",()=>this.onProcessClose());let t=await this.request("initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"gauss-mcp-client",version:"1.2.0"}},e);this.serverCapabilities=t?.capabilities??{},this.notify("notifications/initialized",{}),this.connected=!0}async listTools(){if(this.assertConnected(),this.cachedTools)return this.cachedTools;let t=((await this.request("tools/list",{}))?.tools??[]).map(r=>({name:r.name,description:r.description??"",parameters:r.inputSchema}));return this.cachedTools=t,t}async callTool(e,t={}){return this.assertConnected(),await this.request("tools/call",{name:e,arguments:t})}async getToolsWithExecutor(){return{tools:await this.listTools(),executor:async r=>{let n;try{n=JSON.parse(r)}catch{return JSON.stringify({error:"Invalid tool call JSON"})}let o=n.tool??n.name??"",i=n.args??n.arguments??{};try{let a=await this.callTool(o,i);if(a.isError){let p=a.content?.map(l=>l.text).filter(Boolean).join(`
17
- `)??"Tool error";return JSON.stringify({error:p})}let d=a.content?.map(p=>p.text).filter(Boolean).join(`
18
- `)??"";return JSON.stringify({result:d})}catch(a){let d=a instanceof Error?a.message:String(a);return JSON.stringify({error:d})}}}}close(){if(!this.closed){this.closed=!0,this.connected=!1,this.cachedTools=null;for(let[,{reject:e}]of this.pending)e(new Error("McpClient closed"));this.pending.clear(),this.process&&(this.process.stdin.end(),this.process.kill("SIGTERM"),this.process=null)}}destroy(){this.close()}[Symbol.dispose](){this.close()}get isConnected(){return this.connected}async request(e,t,r=3e4){let n=this.nextId++,o={jsonrpc:"2.0",id:n,method:e,params:t};return new Promise((i,a)=>{let d=setTimeout(()=>{this.pending.delete(n),a(new Error(`MCP request "${e}" timed out after ${r}ms`))},r);this.pending.set(n,{resolve:p=>{clearTimeout(d),i(p)},reject:p=>{clearTimeout(d),a(p)}}),this.send(o)})}notify(e,t){let r={jsonrpc:"2.0",method:e,params:t};this.send(r)}send(e){if(!this.process?.stdin?.writable)throw new Error("MCP server process not available");let t=JSON.stringify(e);this.process.stdin.write(t+`
16
+ ${i}`:i,c=await l.agent.run(p),N={text:c.text,...c.structuredOutput?{structuredOutput:c.structuredOutput}:{}};n[o]=N;let Y=this._conditionalEdges.get(o);Y?o=await Y(N):o=this._edges.get(o),i=c.text}let a=Object.keys(n),d=a[a.length-1];return{outputs:n,final_text:n[d]?.text??""}}assertNotDisposed(){if(this.disposed)throw new P("Graph","graph")}};var S=require("gauss-napi"),oe=class{_handle;disposed=!1;constructor(){this._handle=(0,S.create_workflow)()}get handle(){return this._handle}addStep(e){return this.assertNotDisposed(),(0,S.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,S.workflow_add_dependency)(this._handle,e,t),this}async run(e){return this.assertNotDisposed(),(0,S.workflow_run)(this._handle,e)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,S.destroy_workflow)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Workflow has been destroyed")}};var R=require("gauss-napi");var ie=class s{_handle;_name;disposed=!1;agents=[];static quick(e,t,r){let n=new s(e);for(let o of r){let i=new k({name:o.name,provider:o.provider??"openai",model:o.model??"gpt-4o",instructions:o.instructions});n.add(i)}return n.strategy(t),n}constructor(e){this._name=e,this._handle=(0,R.create_team)(e)}get handle(){return this._handle}add(e,t){return this.assertNotDisposed(),(0,R.team_add_agent)(this._handle,e.name,e.handle,t),this.agents.push(e),this}strategy(e){return this.assertNotDisposed(),(0,R.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,R.team_run)(this._handle,t)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,R.destroy_team)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new P("Team",this._name)}};var y=require("gauss-napi"),ae=class{_handle;disposed=!1;constructor(){this._handle=(0,y.create_network)()}get handle(){return this._handle}addAgent(e,t){return this.assertNotDisposed(),(0,y.network_add_agent)(this._handle,e.name,e.handle,t),this}setSupervisor(e){return this.assertNotDisposed(),(0,y.network_set_supervisor)(this._handle,e),this}async delegate(e,t,r){return this.assertNotDisposed(),(0,y.network_delegate)(this._handle,e,t,r)}agentCards(){return this.assertNotDisposed(),(0,y.network_agent_cards)(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,y.destroy_network)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Network has been destroyed")}};var E=require("gauss-napi"),de=class{_handle;disposed=!1;constructor(){this._handle=(0,E.create_middleware_chain)()}get handle(){return this._handle}useLogging(){return this.assertNotDisposed(),(0,E.middleware_use_logging)(this._handle),this}useCaching(e){return this.assertNotDisposed(),(0,E.middleware_use_caching)(this._handle,e),this}useRateLimit(e,t){return this.assertNotDisposed(),(0,E.middleware_use_rate_limit)(this._handle,e,t),this}destroy(){if(!this.disposed){this.disposed=!0;try{(0,E.destroy_middleware_chain)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("MiddlewareChain has been destroyed")}};var f=require("gauss-napi"),le=class{_handle;disposed=!1;constructor(){this._handle=(0,f.create_plugin_registry)()}get handle(){return this._handle}addTelemetry(){return this.assertNotDisposed(),(0,f.plugin_registry_add_telemetry)(this._handle),this}addMemory(){return this.assertNotDisposed(),(0,f.plugin_registry_add_memory)(this._handle),this}list(){return this.assertNotDisposed(),(0,f.plugin_registry_list)(this._handle)}emit(e){this.assertNotDisposed(),(0,f.plugin_registry_emit)(this._handle,JSON.stringify(e))}destroy(){if(!this.disposed){this.disposed=!0;try{(0,f.destroy_plugin_registry)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("PluginRegistry has been destroyed")}};var v=require("gauss-napi"),pe=class{_handle;disposed=!1;constructor(e,t){this._handle=(0,v.create_mcp_server)(e,t)}get handle(){return this._handle}addTool(e){this.assertNotDisposed();let t={name:e.name,description:e.description,inputSchema:e.parameters??{type:"object"}};return(0,v.mcp_server_add_tool)(this._handle,JSON.stringify(t)),this}addResource(e){return this.assertNotDisposed(),(0,v.mcpServerAddResource)(this._handle,JSON.stringify(e)),this}addPrompt(e){return this.assertNotDisposed(),(0,v.mcpServerAddPrompt)(this._handle,JSON.stringify(e)),this}async handleMessage(e){return this.assertNotDisposed(),(0,v.mcp_server_handle)(this._handle,JSON.stringify(e))}destroy(){if(!this.disposed){this.disposed=!0;try{(0,v.destroy_mcp_server)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("McpServer has been destroyed")}};var ft=require("child_process"),ce=class{config;process=null;connected=!1;closed=!1;nextId=1;pending=new Map;buffer="";serverCapabilities={};cachedTools=null;constructor(e){this.config=e}async connect(){if(this.connected)return;if(this.closed)throw new Error("McpClient has been closed");let e=this.config.timeoutMs??1e4;this.process=(0,ft.spawn)(this.config.command,this.config.args??[],{stdio:["pipe","pipe","pipe"],env:{...process.env,...this.config.env}}),this.process.stdout.on("data",r=>this.onData(r)),this.process.stderr.on("data",()=>{}),this.process.on("error",r=>this.onProcessError(r)),this.process.on("close",()=>this.onProcessClose());let t=await this.request("initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"gauss-mcp-client",version:"1.2.0"}},e);this.serverCapabilities=t?.capabilities??{},this.notify("notifications/initialized",{}),this.connected=!0}async listTools(){if(this.assertConnected(),this.cachedTools)return this.cachedTools;let t=((await this.request("tools/list",{}))?.tools??[]).map(r=>({name:r.name,description:r.description??"",parameters:r.inputSchema}));return this.cachedTools=t,t}async callTool(e,t={}){return this.assertConnected(),await this.request("tools/call",{name:e,arguments:t})}async getToolsWithExecutor(){return{tools:await this.listTools(),executor:async r=>{let n;try{n=JSON.parse(r)}catch{return JSON.stringify({error:"Invalid tool call JSON"})}let o=n.tool??n.name??"",i=n.args??n.arguments??{};try{let a=await this.callTool(o,i);if(a.isError){let l=a.content?.map(p=>p.text).filter(Boolean).join(`
17
+ `)??"Tool error";return JSON.stringify({error:l})}let d=a.content?.map(l=>l.text).filter(Boolean).join(`
18
+ `)??"";return JSON.stringify({result:d})}catch(a){let d=a instanceof Error?a.message:String(a);return JSON.stringify({error:d})}}}}close(){if(!this.closed){this.closed=!0,this.connected=!1,this.cachedTools=null;for(let[,{reject:e}]of this.pending)e(new Error("McpClient closed"));this.pending.clear(),this.process&&(this.process.stdin.end(),this.process.kill("SIGTERM"),this.process=null)}}destroy(){this.close()}[Symbol.dispose](){this.close()}get isConnected(){return this.connected}async request(e,t,r=3e4){let n=this.nextId++,o={jsonrpc:"2.0",id:n,method:e,params:t};return new Promise((i,a)=>{let d=setTimeout(()=>{this.pending.delete(n),a(new Error(`MCP request "${e}" timed out after ${r}ms`))},r);this.pending.set(n,{resolve:l=>{clearTimeout(d),i(l)},reject:l=>{clearTimeout(d),a(l)}}),this.send(o)})}notify(e,t){let r={jsonrpc:"2.0",method:e,params:t};this.send(r)}send(e){if(!this.process?.stdin?.writable)throw new Error("MCP server process not available");let t=JSON.stringify(e);this.process.stdin.write(t+`
19
19
  `)}onData(e){this.buffer+=e.toString("utf-8");let t;for(;(t=this.buffer.indexOf(`
20
- `))!==-1;){let r=this.buffer.slice(0,t).trim();if(this.buffer=this.buffer.slice(t+1),!!r)try{let n=JSON.parse(r);if(n.id!==void 0&&this.pending.has(n.id)){let{resolve:o,reject:i}=this.pending.get(n.id);this.pending.delete(n.id),n.error?i(new Error(`MCP error ${n.error.code}: ${n.error.message}`)):o(n.result)}}catch{}}}onProcessError(e){for(let[,{reject:t}]of this.pending)t(new Error(`MCP process error: ${e.message}`));this.pending.clear(),this.connected=!1}onProcessClose(){this.connected=!1;for(let[,{reject:e}]of this.pending)e(new Error("MCP server process exited"));this.pending.clear()}assertConnected(){if(!this.connected)throw new Error("McpClient is not connected. Call connect() first.")}};var m=require("gauss-napi"),ce=class{_handle;disposed=!1;constructor(){this._handle=(0,m.create_guardrail_chain)()}get handle(){return this._handle}addContentModeration(e,t=[]){return this.assertNotDisposed(),(0,m.guardrail_chain_add_content_moderation)(this._handle,e,t),this}addPiiDetection(e){return this.assertNotDisposed(),(0,m.guardrail_chain_add_pii_detection)(this._handle,e),this}addTokenLimit(e,t){return this.assertNotDisposed(),(0,m.guardrail_chain_add_token_limit)(this._handle,e,t),this}addRegexFilter(e,t=[]){return this.assertNotDisposed(),(0,m.guardrail_chain_add_regex_filter)(this._handle,e,t),this}addSchema(e){return this.assertNotDisposed(),(0,m.guardrail_chain_add_schema)(this._handle,JSON.stringify(e)),this}list(){return this.assertNotDisposed(),(0,m.guardrail_chain_list)(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,m.destroy_guardrail_chain)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("GuardrailChain has been destroyed")}};var v=require("gauss-napi"),ue=class{_handle;disposed=!1;constructor(){this._handle=(0,v.create_approval_manager)()}get handle(){return this._handle}request(e,t,r){return this.assertNotDisposed(),(0,v.approval_request)(this._handle,e,JSON.stringify(t),r)}approve(e,t){this.assertNotDisposed(),(0,v.approval_approve)(this._handle,e,t?JSON.stringify(t):void 0)}deny(e,t){this.assertNotDisposed(),(0,v.approval_deny)(this._handle,e,t)}listPending(){return this.assertNotDisposed(),(0,v.approval_list_pending)(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,v.destroy_approval_manager)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("ApprovalManager has been destroyed")}};var E=require("gauss-napi"),me=class{_handle;disposed=!1;constructor(){this._handle=(0,E.create_checkpoint_store)()}get handle(){return this._handle}async save(e){return this.assertNotDisposed(),(0,E.checkpoint_save)(this._handle,JSON.stringify(e))}async load(e){return this.assertNotDisposed(),(0,E.checkpoint_load)(this._handle,e)}async loadLatest(e){return this.assertNotDisposed(),(0,E.checkpoint_load_latest)(this._handle,e)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,E.destroy_checkpoint_store)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("CheckpointStore has been destroyed")}};var A=require("gauss-napi"),he=class{_handle;disposed=!1;constructor(e){this._handle=(0,A.create_eval_runner)(e)}get handle(){return this._handle}addScorer(e){return this.assertNotDisposed(),(0,A.eval_add_scorer)(this._handle,e),this}destroy(){if(!this.disposed){this.disposed=!0;try{(0,A.destroy_eval_runner)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("EvalRunner has been destroyed")}static loadDatasetJsonl(e){return(0,A.load_dataset_jsonl)(e)}static loadDatasetJson(e){return(0,A.load_dataset_json)(e)}};var _=require("gauss-napi"),ge=class{_handle;disposed=!1;constructor(){this._handle=(0,_.create_telemetry)()}get handle(){return this._handle}recordSpan(e,t,r){this.assertNotDisposed();let n=typeof e=="string"?{name:e,span_type:"custom",start_ms:Date.now()-(t??0),duration_ms:t??0,attributes:r??{},status:"ok",children:[]}:e;(0,_.telemetry_record_span)(this._handle,JSON.stringify(n))}exportSpans(){return this.assertNotDisposed(),(0,_.telemetry_export_spans)(this._handle)}exportMetrics(){return this.assertNotDisposed(),(0,_.telemetry_export_metrics)(this._handle)}clear(){this.assertNotDisposed(),(0,_.telemetry_clear)(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,_.destroy_telemetry)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Telemetry has been destroyed")}};var ve=require("fs"),Pt=require("http"),wt=require("path");var D=require("gauss-napi"),ye=new Map;function ft(s,e){ye.set(s,e)}function xt(s){return ye.get(s)}function vt(){ye.clear()}function _t(s){return(0,D.count_tokens)(s)}function Tt(s,e){return(0,D.count_tokens_for_model)(s,e)}function bt(s){return(0,D.count_message_tokens)(s)}function kt(s){return(0,D.get_context_window_size)(s)}function fe(s,e){let t=ye.get(s);if(t){let n=e.inputTokens*t.inputPerToken,o=e.outputTokens*t.outputPerToken,i=(e.reasoningTokens??0)*(t.reasoningPerToken??t.outputPerToken),a=(e.cacheReadTokens??0)*(t.cacheReadPerToken??t.inputPerToken*.5),d=(e.cacheCreationTokens??0)*(t.cacheCreationPerToken??t.inputPerToken*1.25);return{model:s,normalizedModel:s,currency:"USD",inputTokens:e.inputTokens,outputTokens:e.outputTokens,reasoningTokens:e.reasoningTokens??0,cacheReadTokens:e.cacheReadTokens??0,cacheCreationTokens:e.cacheCreationTokens??0,inputCostUsd:n,outputCostUsd:o,reasoningCostUsd:i,cacheReadCostUsd:a,cacheCreationCostUsd:d,totalCostUsd:n+o+i+a+d}}let r=(0,D.estimate_cost)(s,e.inputTokens,e.outputTokens,e.reasoningTokens,e.cacheReadTokens,e.cacheCreationTokens);return{model:String(r.model??s),normalizedModel:String(r.normalized_model??s),currency:String(r.currency??"USD"),inputTokens:Number(r.input_tokens??e.inputTokens),outputTokens:Number(r.output_tokens??e.outputTokens),reasoningTokens:Number(r.reasoning_tokens??e.reasoningTokens??0),cacheReadTokens:Number(r.cache_read_tokens??e.cacheReadTokens??0),cacheCreationTokens:Number(r.cache_creation_tokens??e.cacheCreationTokens??0),inputCostUsd:Number(r.input_cost_usd??0),outputCostUsd:Number(r.output_cost_usd??0),reasoningCostUsd:Number(r.reasoning_cost_usd??0),cacheReadCostUsd:Number(r.cache_read_cost_usd??0),cacheCreationCostUsd:Number(r.cache_creation_cost_usd??0),totalCostUsd:Number(r.total_cost_usd??0)}}var G=class extends Error{},xe=class{telemetry;approvals;model;authToken;authClaims;persistPath;historyLimit;context;latestCost=null;history=[];server=null;constructor(e={}){this.telemetry=e.telemetry,this.approvals=e.approvals,this.model=e.model??"gpt-5.2",this.authToken=e.authToken,this.authClaims=e.authClaims,this.persistPath=e.persistPath,this.historyLimit=e.historyLimit??200,this.context={...e.context??{}}}withModel(e){return this.model=e,this}withAuthToken(e){return this.authToken=e,this}withAuthClaims(e){return this.authClaims=e,this}withContext(e){return this.assertContextAllowed(e),this.context={...e},this}setCostUsage(e){return this.latestCost=fe(this.model,e),this}snapshot(e){let t=this.captureSnapshot();return e?{generatedAt:t.generatedAt,context:t.context,[e]:t[e]}:t}getHistory(e){return this.filterHistory(e)}getTimeline(e){return this.filterHistory(e).map(t=>({generatedAt:t.generatedAt,spanCount:Array.isArray(t.spans)?t.spans.length:0,pendingApprovalsCount:Array.isArray(t.pendingApprovals)?t.pendingApprovals.length:0,totalCostUsd:t.latestCost?.totalCostUsd??0}))}getDag(e){let t=this.filterHistory(e),r=t[t.length-1];if(!r||!Array.isArray(r.spans))return{nodes:[],edges:[]};let n=r.spans.map((i,a)=>({id:String(a),label:this.spanLabel(i,a)})),o=n.slice(1).map((i,a)=>({from:String(a),to:i.id}));return{nodes:n,edges:o}}async startServer(e="127.0.0.1",t=4200){if(this.server){let n=this.server.address();return n&&typeof n!="string"?{url:`http://${e}:${n.port}`}:{url:`http://${e}:${t}`}}this.server=(0,Pt.createServer)((n,o)=>{if(!n.url){o.statusCode=400,o.end("Bad request");return}let i=new URL(n.url,`http://${n.headers.host??`${e}:${t}`}`),a=i.pathname;if(a.startsWith("/api/")&&!this.isAuthorized(n,i)){o.statusCode=401,o.setHeader("Content-Type","application/json; charset=utf-8"),o.end(JSON.stringify({error:"Unauthorized"}));return}try{if(a==="/api/snapshot"){let d=i.searchParams.get("section"),p=d?this.snapshot(this.parseSection(d)):this.snapshot();o.setHeader("Content-Type","application/json; charset=utf-8"),o.end(JSON.stringify(p,null,2));return}if(a==="/api/history"){let d=this.applyAuthClaims(this.parseContextFilters(i.searchParams));o.setHeader("Content-Type","application/json; charset=utf-8"),o.end(JSON.stringify(this.getHistory(d),null,2));return}if(a==="/api/timeline"){let d=this.applyAuthClaims(this.parseContextFilters(i.searchParams));o.setHeader("Content-Type","application/json; charset=utf-8"),o.end(JSON.stringify(this.getTimeline(d),null,2));return}if(a==="/api/dag"){let d=this.applyAuthClaims(this.parseContextFilters(i.searchParams));o.setHeader("Content-Type","application/json; charset=utf-8"),o.end(JSON.stringify(this.getDag(d),null,2));return}if(a==="/"){o.setHeader("Content-Type","text/html; charset=utf-8"),o.end(this.renderDashboardHtml());return}o.statusCode=404,o.end("Not found")}catch(d){if(d instanceof G){o.statusCode=403,o.setHeader("Content-Type","application/json; charset=utf-8"),o.end(JSON.stringify({error:d.message}));return}let p=d instanceof Error?d.message:"Internal error";o.statusCode=500,o.setHeader("Content-Type","application/json; charset=utf-8"),o.end(JSON.stringify({error:p}))}}),await new Promise((n,o)=>{this.server.once("error",o),this.server.listen(t,e,()=>n())});let r=this.server.address();return!r||typeof r=="string"?{url:`http://${e}:${t}`}:{url:`http://${e}:${r.port}`}}async stopServer(){if(!this.server)return;let e=this.server;this.server=null,await new Promise((t,r)=>{e.close(n=>n?r(n):t())})}destroy(){this.stopServer()}[Symbol.dispose](){this.destroy()}captureSnapshot(){this.assertContextAllowed(this.context);let e={generatedAt:new Date().toISOString(),context:{...this.context},spans:this.telemetry?.exportSpans()??[],metrics:this.telemetry?.exportMetrics()??{},pendingApprovals:this.approvals?.listPending()??[],latestCost:this.latestCost};return this.history.push(e),this.history.length>this.historyLimit&&this.history.shift(),this.persistPath&&((0,ve.mkdirSync)((0,wt.dirname)(this.persistPath),{recursive:!0}),(0,ve.appendFileSync)(this.persistPath,`${JSON.stringify(e)}
21
- `,"utf8")),e}parseSection(e){if(e==="spans"||e==="metrics"||e==="pendingApprovals"||e==="latestCost")return e;throw new O(`Unknown section "${e}"`,"section")}parseContextFilters(e){return{tenantId:e.get("tenant")??void 0,sessionId:e.get("session")??void 0,runId:e.get("run")??void 0}}applyAuthClaims(e){if(!this.authClaims)return e;let t={...e};if(this.authClaims.tenantId){if(t.tenantId&&t.tenantId!==this.authClaims.tenantId)throw new G("Forbidden tenant scope");t.tenantId??=this.authClaims.tenantId}let r=this.authClaims.allowedSessionIds??[];if(t.sessionId&&r.length>0&&!r.includes(t.sessionId))throw new G("Forbidden session scope");!t.sessionId&&r.length===1&&(t.sessionId=r[0]);let n=this.authClaims.allowedRunIds??[];if(t.runId&&n.length>0&&!n.includes(t.runId))throw new G("Forbidden run scope");return!t.runId&&n.length===1&&(t.runId=n[0]),t}assertContextAllowed(e){this.authClaims&&this.applyAuthClaims(e)}filterHistory(e){return!e||!e.tenantId&&!e.sessionId&&!e.runId?[...this.history]:this.history.filter(t=>this.matchesContext(t.context,e))}matchesContext(e,t){return!(t.tenantId&&e.tenantId!==t.tenantId||t.sessionId&&e.sessionId!==t.sessionId||t.runId&&e.runId!==t.runId)}spanLabel(e,t){if(e&&typeof e=="object"){let r=e;if(typeof r.name=="string")return r.name;if(typeof r.span_name=="string")return r.span_name}return`span-${t+1}`}isAuthorized(e,t){if(!this.authToken)return!0;let r=e.headers.authorization,n=typeof r=="string"&&r===`Bearer ${this.authToken}`,o=e.headers["x-gauss-token"],i=typeof o=="string"&&o===this.authToken,a=t.searchParams.get("token")===this.authToken;return n||i||a}renderDashboardHtml(){return`<!doctype html>
20
+ `))!==-1;){let r=this.buffer.slice(0,t).trim();if(this.buffer=this.buffer.slice(t+1),!!r)try{let n=JSON.parse(r);if(n.id!==void 0&&this.pending.has(n.id)){let{resolve:o,reject:i}=this.pending.get(n.id);this.pending.delete(n.id),n.error?i(new Error(`MCP error ${n.error.code}: ${n.error.message}`)):o(n.result)}}catch{}}}onProcessError(e){for(let[,{reject:t}]of this.pending)t(new Error(`MCP process error: ${e.message}`));this.pending.clear(),this.connected=!1}onProcessClose(){this.connected=!1;for(let[,{reject:e}]of this.pending)e(new Error("MCP server process exited"));this.pending.clear()}assertConnected(){if(!this.connected)throw new Error("McpClient is not connected. Call connect() first.")}};var m=require("gauss-napi"),ue=class{_handle;disposed=!1;constructor(){this._handle=(0,m.create_guardrail_chain)()}get handle(){return this._handle}addContentModeration(e,t=[]){return this.assertNotDisposed(),(0,m.guardrail_chain_add_content_moderation)(this._handle,e,t),this}addPiiDetection(e){return this.assertNotDisposed(),(0,m.guardrail_chain_add_pii_detection)(this._handle,e),this}addTokenLimit(e,t){return this.assertNotDisposed(),(0,m.guardrail_chain_add_token_limit)(this._handle,e,t),this}addRegexFilter(e,t=[]){return this.assertNotDisposed(),(0,m.guardrail_chain_add_regex_filter)(this._handle,e,t),this}addSchema(e){return this.assertNotDisposed(),(0,m.guardrail_chain_add_schema)(this._handle,JSON.stringify(e)),this}list(){return this.assertNotDisposed(),(0,m.guardrail_chain_list)(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,m.destroy_guardrail_chain)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("GuardrailChain has been destroyed")}};var x=require("gauss-napi"),me=class{_handle;disposed=!1;constructor(){this._handle=(0,x.create_approval_manager)()}get handle(){return this._handle}request(e,t,r){return this.assertNotDisposed(),(0,x.approval_request)(this._handle,e,JSON.stringify(t),r)}approve(e,t){this.assertNotDisposed(),(0,x.approval_approve)(this._handle,e,t?JSON.stringify(t):void 0)}deny(e,t){this.assertNotDisposed(),(0,x.approval_deny)(this._handle,e,t)}listPending(){return this.assertNotDisposed(),(0,x.approval_list_pending)(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,x.destroy_approval_manager)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("ApprovalManager has been destroyed")}};var A=require("gauss-napi"),he=class{_handle;disposed=!1;constructor(){this._handle=(0,A.create_checkpoint_store)()}get handle(){return this._handle}async save(e){return this.assertNotDisposed(),(0,A.checkpoint_save)(this._handle,JSON.stringify(e))}async load(e){return this.assertNotDisposed(),(0,A.checkpoint_load)(this._handle,e)}async loadLatest(e){return this.assertNotDisposed(),(0,A.checkpoint_load_latest)(this._handle,e)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,A.destroy_checkpoint_store)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("CheckpointStore has been destroyed")}};var D=require("gauss-napi"),ge=class{_handle;disposed=!1;constructor(e){this._handle=(0,D.create_eval_runner)(e)}get handle(){return this._handle}addScorer(e){return this.assertNotDisposed(),(0,D.eval_add_scorer)(this._handle,e),this}destroy(){if(!this.disposed){this.disposed=!0;try{(0,D.destroy_eval_runner)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("EvalRunner has been destroyed")}static loadDatasetJsonl(e){return(0,D.load_dataset_jsonl)(e)}static loadDatasetJson(e){return(0,D.load_dataset_json)(e)}};var _=require("gauss-napi"),ye=class{_handle;disposed=!1;constructor(){this._handle=(0,_.create_telemetry)()}get handle(){return this._handle}recordSpan(e,t,r){this.assertNotDisposed();let n=typeof e=="string"?{name:e,span_type:"custom",start_ms:Date.now()-(t??0),duration_ms:t??0,attributes:r??{},status:"ok",children:[]}:e;(0,_.telemetry_record_span)(this._handle,JSON.stringify(n))}exportSpans(){return this.assertNotDisposed(),(0,_.telemetry_export_spans)(this._handle)}exportMetrics(){return this.assertNotDisposed(),(0,_.telemetry_export_metrics)(this._handle)}clear(){this.assertNotDisposed(),(0,_.telemetry_clear)(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,_.destroy_telemetry)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Telemetry has been destroyed")}};var _e=require("fs"),Ct=require("http"),wt=require("path");var M=require("gauss-napi"),fe=new Map;function vt(s,e){fe.set(s,e)}function xt(s){return fe.get(s)}function _t(){fe.clear()}function Tt(s){return(0,M.count_tokens)(s)}function bt(s,e){return(0,M.count_tokens_for_model)(s,e)}function kt(s){return(0,M.count_message_tokens)(s)}function Pt(s){return(0,M.get_context_window_size)(s)}function ve(s,e){let t=fe.get(s);if(t){let n=e.inputTokens*t.inputPerToken,o=e.outputTokens*t.outputPerToken,i=(e.reasoningTokens??0)*(t.reasoningPerToken??t.outputPerToken),a=(e.cacheReadTokens??0)*(t.cacheReadPerToken??t.inputPerToken*.5),d=(e.cacheCreationTokens??0)*(t.cacheCreationPerToken??t.inputPerToken*1.25);return{model:s,normalizedModel:s,currency:"USD",inputTokens:e.inputTokens,outputTokens:e.outputTokens,reasoningTokens:e.reasoningTokens??0,cacheReadTokens:e.cacheReadTokens??0,cacheCreationTokens:e.cacheCreationTokens??0,inputCostUsd:n,outputCostUsd:o,reasoningCostUsd:i,cacheReadCostUsd:a,cacheCreationCostUsd:d,totalCostUsd:n+o+i+a+d}}let r=(0,M.estimate_cost)(s,e.inputTokens,e.outputTokens,e.reasoningTokens,e.cacheReadTokens,e.cacheCreationTokens);return{model:String(r.model??s),normalizedModel:String(r.normalized_model??s),currency:String(r.currency??"USD"),inputTokens:Number(r.input_tokens??e.inputTokens),outputTokens:Number(r.output_tokens??e.outputTokens),reasoningTokens:Number(r.reasoning_tokens??e.reasoningTokens??0),cacheReadTokens:Number(r.cache_read_tokens??e.cacheReadTokens??0),cacheCreationTokens:Number(r.cache_creation_tokens??e.cacheCreationTokens??0),inputCostUsd:Number(r.input_cost_usd??0),outputCostUsd:Number(r.output_cost_usd??0),reasoningCostUsd:Number(r.reasoning_cost_usd??0),cacheReadCostUsd:Number(r.cache_read_cost_usd??0),cacheCreationCostUsd:Number(r.cache_creation_cost_usd??0),totalCostUsd:Number(r.total_cost_usd??0)}}var H=class extends Error{},xe=class{telemetry;approvals;model;authToken;authClaims;persistPath;historyLimit;streamReplayLimit;context;latestCost=null;history=[];nextStreamEventId=1;streamEvents=[];server=null;constructor(e={}){this.telemetry=e.telemetry,this.approvals=e.approvals,this.model=e.model??"gpt-5.2",this.authToken=e.authToken,this.authClaims=e.authClaims,this.persistPath=e.persistPath,this.historyLimit=e.historyLimit??200,this.streamReplayLimit=e.streamReplayLimit??500,this.context={...e.context??{}}}withModel(e){return this.model=e,this}withAuthToken(e){return this.authToken=e,this}withAuthClaims(e){return this.authClaims=e,this}withContext(e){return this.assertContextAllowed(e),this.context={...e},this}setCostUsage(e){return this.latestCost=ve(this.model,e),this}snapshot(e){let t=this.captureSnapshot();return e?{generatedAt:t.generatedAt,context:t.context,[e]:t[e]}:t}getHistory(e){return this.filterHistory(e)}getTimeline(e){return this.filterHistory(e).map(t=>({generatedAt:t.generatedAt,spanCount:Array.isArray(t.spans)?t.spans.length:0,pendingApprovalsCount:Array.isArray(t.pendingApprovals)?t.pendingApprovals.length:0,totalCostUsd:t.latestCost?.totalCostUsd??0}))}getDag(e){let t=this.filterHistory(e),r=t[t.length-1];if(!r||!Array.isArray(r.spans))return{nodes:[],edges:[]};let n=r.spans.map((i,a)=>({id:String(a),label:this.spanLabel(i,a)})),o=n.slice(1).map((i,a)=>({from:String(a),to:i.id}));return{nodes:n,edges:o}}async startServer(e="127.0.0.1",t=4200){if(this.server){let n=this.server.address();return n&&typeof n!="string"?{url:`http://${e}:${n.port}`}:{url:`http://${e}:${t}`}}this.server=(0,Ct.createServer)((n,o)=>{if(!n.url){o.statusCode=400,o.end("Bad request");return}let i=new URL(n.url,`http://${n.headers.host??`${e}:${t}`}`),a=i.pathname;if(a.startsWith("/api/")&&!this.isAuthorized(n,i)){o.statusCode=401,o.setHeader("Content-Type","application/json; charset=utf-8"),o.end(JSON.stringify({error:"Unauthorized"}));return}try{if(a==="/api/snapshot"){let d=i.searchParams.get("section"),l=d?this.snapshot(this.parseSection(d)):this.snapshot();o.setHeader("Content-Type","application/json; charset=utf-8"),o.end(JSON.stringify(l,null,2));return}if(a==="/api/history"){let d=this.applyAuthClaims(this.parseContextFilters(i.searchParams));o.setHeader("Content-Type","application/json; charset=utf-8"),o.end(JSON.stringify(this.getHistory(d),null,2));return}if(a==="/api/timeline"){let d=this.applyAuthClaims(this.parseContextFilters(i.searchParams));o.setHeader("Content-Type","application/json; charset=utf-8"),o.end(JSON.stringify(this.getTimeline(d),null,2));return}if(a==="/api/dag"){let d=this.applyAuthClaims(this.parseContextFilters(i.searchParams));o.setHeader("Content-Type","application/json; charset=utf-8"),o.end(JSON.stringify(this.getDag(d),null,2));return}if(a==="/api/ops/capabilities"){o.setHeader("Content-Type","application/json; charset=utf-8"),o.end(JSON.stringify(this.opsCapabilities(),null,2));return}if(a==="/api/ops/health"){o.setHeader("Content-Type","application/json; charset=utf-8"),o.end(JSON.stringify(this.opsHealth(),null,2));return}if(a==="/api/stream"){let d=this.applyAuthClaims(this.parseContextFilters(i.searchParams)),l=this.parseStreamChannels(i.searchParams);for(let Xt of l)this.assertChannelAllowed(Xt);let p=i.searchParams.get("once")==="1",c=this.parseLastEventId(n,i.searchParams);o.statusCode=200,o.setHeader("Content-Type","text/event-stream; charset=utf-8"),o.setHeader("Cache-Control","no-cache"),o.setHeader("Connection","keep-alive");let N=this.replayStreamEvents(o,l,d,c);if(p&&N>0){o.end();return}if(this.emitStreamBatch(o,l,d),p){o.end();return}let Y=setInterval(()=>{o.writableEnded||o.destroyed||this.emitStreamBatch(o,l,d)},1e3),Ye=()=>clearInterval(Y);n.on("close",Ye),n.on("aborted",Ye);return}if(a==="/"){o.setHeader("Content-Type","text/html; charset=utf-8"),o.end(this.renderDashboardHtml());return}if(a==="/ops"){o.setHeader("Content-Type","text/html; charset=utf-8"),o.end(this.renderHostedOpsHtml());return}o.statusCode=404,o.end("Not found")}catch(d){if(d instanceof H){o.statusCode=403,o.setHeader("Content-Type","application/json; charset=utf-8"),o.end(JSON.stringify({error:d.message}));return}let l=d instanceof Error?d.message:"Internal error";o.statusCode=500,o.setHeader("Content-Type","application/json; charset=utf-8"),o.end(JSON.stringify({error:l}))}}),await new Promise((n,o)=>{this.server.once("error",o),this.server.listen(t,e,()=>n())});let r=this.server.address();return!r||typeof r=="string"?{url:`http://${e}:${t}`}:{url:`http://${e}:${r.port}`}}async stopServer(){if(!this.server)return;let e=this.server;this.server=null,await new Promise((t,r)=>{e.close(n=>n?r(n):t())})}destroy(){this.stopServer()}[Symbol.dispose](){this.destroy()}captureSnapshot(){this.assertContextAllowed(this.context);let e={generatedAt:new Date().toISOString(),context:{...this.context},spans:this.telemetry?.exportSpans()??[],metrics:this.telemetry?.exportMetrics()??{},pendingApprovals:this.approvals?.listPending()??[],latestCost:this.latestCost};return this.history.push(e),this.history.length>this.historyLimit&&this.history.shift(),this.persistPath&&((0,_e.mkdirSync)((0,wt.dirname)(this.persistPath),{recursive:!0}),(0,_e.appendFileSync)(this.persistPath,`${JSON.stringify(e)}
21
+ `,"utf8")),e}parseSection(e){if(e==="spans"||e==="metrics"||e==="pendingApprovals"||e==="latestCost")return e;throw new b(`Unknown section "${e}"`,"section")}parseStreamChannel(e){if(e===null||e==="snapshot")return"snapshot";if(e==="timeline"||e==="dag")return e;throw new b(`Unknown stream channel "${e}"`,"channel")}parseStreamChannels(e){let t=e.get("channels");if(!t)return[this.parseStreamChannel(e.get("channel"))];let r=t.split(",").map(n=>n.trim()).filter(n=>n.length>0).map(n=>this.parseStreamChannel(n));return r.length===0?["snapshot"]:[...new Set(r)]}parseLastEventId(e,t){let r=t.get("lastEventId"),n=e.headers["last-event-id"],o=r??(typeof n=="string"?n:null);if(o===null)return null;let i=Number.parseInt(o,10);if(!Number.isFinite(i)||i<0)throw new b(`Invalid lastEventId "${o}"`,"lastEventId");return i}parseContextFilters(e){return{tenantId:e.get("tenant")??void 0,sessionId:e.get("session")??void 0,runId:e.get("run")??void 0}}buildStreamEvent(e,t,r){let n=e==="timeline"?this.getTimeline(t):e==="dag"?this.getDag(t):this.filterHistory(t).slice(-1)[0]??r,o={id:this.nextStreamEventId++,event:e,generatedAt:r.generatedAt,context:{...r.context},payload:n};return this.streamEvents.push(o),this.streamEvents.length>this.streamReplayLimit&&this.streamEvents.shift(),o}writeSseEvent(e,t){e.write(`id: ${t.id}
22
+ `),e.write(`event: ${t.event}
23
+ `),e.write(`data: ${JSON.stringify(t)}
24
+
25
+ `)}opsCapabilities(){return{sections:["spans","metrics","pendingApprovals","latestCost"],channels:["snapshot","timeline","dag"],supportsMultiplex:!0,supportsReplayCursor:!0,supportsChannelRbac:!0,hostedDashboardPath:"/ops"}}opsHealth(){return{status:"ok",generatedAt:new Date().toISOString(),historySize:this.history.length,streamBufferSize:this.streamEvents.length}}emitStreamBatch(e,t,r){let n=this.captureSnapshot();for(let o of t)this.writeSseEvent(e,this.buildStreamEvent(o,r,n))}replayStreamEvents(e,t,r,n){if(n===null)return 0;let o=0;for(let i of this.streamEvents)i.id<=n||t.includes(i.event)&&this.matchesContext(i.context,r)&&(this.writeSseEvent(e,i),o+=1);return o}assertChannelAllowed(e){let t=(this.authClaims?.roles??[]).map(r=>r.toLowerCase());if(t.length!==0&&!(t.includes("admin")||t.includes("operator"))&&!((e==="snapshot"||e==="timeline")&&(t.includes("viewer")||t.includes("reader"))))throw new H(`Forbidden stream channel "${e}"`)}applyAuthClaims(e){if(!this.authClaims)return e;let t={...e};if(this.authClaims.tenantId){if(t.tenantId&&t.tenantId!==this.authClaims.tenantId)throw new H("Forbidden tenant scope");t.tenantId??=this.authClaims.tenantId}let r=this.authClaims.allowedSessionIds??[];if(t.sessionId&&r.length>0&&!r.includes(t.sessionId))throw new H("Forbidden session scope");!t.sessionId&&r.length===1&&(t.sessionId=r[0]);let n=this.authClaims.allowedRunIds??[];if(t.runId&&n.length>0&&!n.includes(t.runId))throw new H("Forbidden run scope");return!t.runId&&n.length===1&&(t.runId=n[0]),t}assertContextAllowed(e){this.authClaims&&this.applyAuthClaims(e)}filterHistory(e){return!e||!e.tenantId&&!e.sessionId&&!e.runId?[...this.history]:this.history.filter(t=>this.matchesContext(t.context,e))}matchesContext(e,t){return!(t.tenantId&&e.tenantId!==t.tenantId||t.sessionId&&e.sessionId!==t.sessionId||t.runId&&e.runId!==t.runId)}spanLabel(e,t){if(e&&typeof e=="object"){let r=e;if(typeof r.name=="string")return r.name;if(typeof r.span_name=="string")return r.span_name}return`span-${t+1}`}isAuthorized(e,t){if(!this.authToken)return!0;let r=e.headers.authorization,n=typeof r=="string"&&r===`Bearer ${this.authToken}`,o=e.headers["x-gauss-token"],i=typeof o=="string"&&o===this.authToken,a=t.searchParams.get("token")===this.authToken;return n||i||a}renderDashboardHtml(){return`<!doctype html>
22
26
  <html lang="en">
23
27
  <head>
24
28
  <meta charset="utf-8" />
@@ -56,24 +60,80 @@ ${i}`:i,c=await p.agent.run(l),K={text:c.text,...c.structuredOutput?{structuredO
56
60
  refresh();
57
61
  </script>
58
62
  </body>
59
- </html>`}};var F=require("gauss-napi");function Rt(s){return(0,F.create_fallback_provider)(s)}function Ct(s,e,t){return(0,F.create_circuit_breaker)(s,e,t)}function qe(s,e,t){return(0,F.create_resilient_provider)(s,e,t)}function St(s,e,t=!0){return qe(s.handle,e.map(r=>r.handle),t)}var _e=require("gauss-napi");function Et(s){return(0,_e.agent_config_from_json)(s)}function At(s){return(0,_e.agent_config_resolve_env)(s)}var $=require("gauss-napi"),Te=class{_handle;disposed=!1;constructor(e){this._handle=(0,$.create_tool_validator)(e)}get handle(){return this._handle}validate(e,t){return this.assertNotDisposed(),JSON.parse((0,$.tool_validator_validate)(this._handle,JSON.stringify(e),JSON.stringify(t)))}destroy(){if(!this.disposed){this.disposed=!0;try{(0,$.destroy_tool_validator)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("ToolValidator has been destroyed")}};var Dt=require("gauss-napi");function Mt(s){return(0,Dt.parse_partial_json)(s)}function or(s,e){let t;switch(s.backoff){case"fixed":t=s.baseDelayMs;break;case"linear":t=s.baseDelayMs*e;break;case"exponential":t=s.baseDelayMs*Math.pow(2,e-1);break}let r=t*s.jitter;return t+=Math.random()*r*2-r,Math.min(Math.max(0,t),s.maxDelayMs)}function ir(s){return new Promise(e=>setTimeout(e,s))}async function Ke(s,e){let t=e?.maxRetries??3,r=e?.backoff??"exponential",n=e?.baseDelayMs??1e3,o=e?.maxDelayMs??3e4,i=e?.jitter??.1,a=e?.retryIf,d=e?.onRetry,p;for(let l=0;l<=t;l++)try{return await s()}catch(c){if(p=c instanceof Error?c:new Error(String(c)),l===t||a&&!a(p,l+1))break;let K=or({backoff:r,baseDelayMs:n,maxDelayMs:o,jitter:i},l+1);d?.(p,l+1,K),await ir(K)}throw p}function Ot(s,e){return t=>Ke(()=>s.run(t),e)}function ar(s,e){let t=JSON.stringify(e,null,2);return`${s}
63
+ </html>`}renderHostedOpsHtml(){return`<!doctype html>
64
+ <html lang="en">
65
+ <head>
66
+ <meta charset="utf-8" />
67
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
68
+ <title>Gauss Hosted Ops Console</title>
69
+ <style>
70
+ body { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; margin: 20px; background: #0b1020; color: #f5f7ff; }
71
+ .row { margin-bottom: 12px; display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
72
+ input, button { background: #111935; color: #f5f7ff; border: 1px solid #25315f; border-radius: 6px; padding: 8px; }
73
+ pre { background: #111935; border: 1px solid #25315f; padding: 12px; border-radius: 8px; max-height: 60vh; overflow: auto; }
74
+ .muted { color: #a9b4d0; }
75
+ </style>
76
+ </head>
77
+ <body>
78
+ <h1>Gauss Hosted Ops Console</h1>
79
+ <div class="muted">Live stream viewer with multiplex channels + replay cursor support.</div>
80
+ <div class="row">
81
+ <label>Token <input id="token" placeholder="optional" /></label>
82
+ <label>Last Event ID <input id="lastEventId" placeholder="optional" /></label>
83
+ <button id="connect">Connect</button>
84
+ </div>
85
+ <div class="row">
86
+ <label><input type="checkbox" class="ch" value="snapshot" checked /> snapshot</label>
87
+ <label><input type="checkbox" class="ch" value="timeline" checked /> timeline</label>
88
+ <label><input type="checkbox" class="ch" value="dag" /> dag</label>
89
+ </div>
90
+ <pre id="out">idle</pre>
91
+ <script>
92
+ let source;
93
+ const out = document.getElementById('out');
94
+ function selectedChannels() {
95
+ return [...document.querySelectorAll('.ch:checked')].map((node) => node.value);
96
+ }
97
+ function append(message) {
98
+ out.textContent = message + "\\n" + out.textContent;
99
+ }
100
+ document.getElementById('connect').addEventListener('click', () => {
101
+ if (source) source.close();
102
+ const token = document.getElementById('token').value.trim();
103
+ const lastEventId = document.getElementById('lastEventId').value.trim();
104
+ const channels = selectedChannels();
105
+ const qs = new URLSearchParams();
106
+ if (channels.length > 0) qs.set('channels', channels.join(','));
107
+ if (token) qs.set('token', token);
108
+ if (lastEventId) qs.set('lastEventId', lastEventId);
109
+ source = new EventSource('/api/stream?' + qs.toString());
110
+ source.onmessage = (event) => append(event.data);
111
+ source.onerror = () => append('stream disconnected');
112
+ append('stream connected');
113
+ });
114
+ fetch('/api/ops/capabilities')
115
+ .then((r) => r.json())
116
+ .then((j) => append('capabilities: ' + JSON.stringify(j)));
117
+ </script>
118
+ </body>
119
+ </html>`}};var $=require("gauss-napi");function St(s){return(0,$.create_fallback_provider)(s)}function Rt(s,e,t){return(0,$.create_circuit_breaker)(s,e,t)}function Be(s,e,t){return(0,$.create_resilient_provider)(s,e,t)}function Et(s,e,t=!0){return Be(s.handle,e.map(r=>r.handle),t)}var Te=require("gauss-napi");function At(s){return(0,Te.agent_config_from_json)(s)}function Dt(s){return(0,Te.agent_config_resolve_env)(s)}var q=require("gauss-napi"),be=class{_handle;disposed=!1;constructor(e){this._handle=(0,q.create_tool_validator)(e)}get handle(){return this._handle}validate(e,t){return this.assertNotDisposed(),JSON.parse((0,q.tool_validator_validate)(this._handle,JSON.stringify(e),JSON.stringify(t)))}destroy(){if(!this.disposed){this.disposed=!0;try{(0,q.destroy_tool_validator)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("ToolValidator has been destroyed")}};var Mt=require("gauss-napi");function Ot(s){return(0,Mt.parse_partial_json)(s)}function ar(s,e){let t;switch(s.backoff){case"fixed":t=s.baseDelayMs;break;case"linear":t=s.baseDelayMs*e;break;case"exponential":t=s.baseDelayMs*Math.pow(2,e-1);break}let r=t*s.jitter;return t+=Math.random()*r*2-r,Math.min(Math.max(0,t),s.maxDelayMs)}function dr(s){return new Promise(e=>setTimeout(e,s))}async function Ke(s,e){let t=e?.maxRetries??3,r=e?.backoff??"exponential",n=e?.baseDelayMs??1e3,o=e?.maxDelayMs??3e4,i=e?.jitter??.1,a=e?.retryIf,d=e?.onRetry,l;for(let p=0;p<=t;p++)try{return await s()}catch(c){if(l=c instanceof Error?c:new Error(String(c)),p===t||a&&!a(l,p+1))break;let N=ar({backoff:r,baseDelayMs:n,maxDelayMs:o,jitter:i},p+1);d?.(l,p+1,N),await dr(N)}throw l}function It(s,e){return t=>Ke(()=>s.run(t),e)}function lr(s,e){let t=JSON.stringify(e,null,2);return`${s}
60
120
 
61
121
  Respond ONLY with valid JSON matching this schema:
62
122
  ${t}
63
123
 
64
- Do not include any text outside the JSON object.`}function dr(s){let e=s.match(/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/);if(e)return e[1].trim();let t=s.indexOf("{"),r=s.indexOf("[");if(t===-1&&r===-1)return s.trim();let n=t===-1?r:r===-1?t:Math.min(t,r),i=s[n]==="["?"]":"}",a=0,d=!1,p=!1;for(let l=n;l<s.length;l++){let c=s[l];if(p){p=!1;continue}if(c==="\\"){p=!0;continue}if(c==='"'){d=!d;continue}if(!d&&(c===s[n]&&a++,c===i&&(a--,a===0)))return s.slice(n,l+1)}return s.slice(n)}async function Nt(s,e,t){let r=t.maxParseRetries??2,n=typeof e=="string"?ar(e,t.schema):e,o;for(let i=0;i<=r;i++){let a=i===0?n:typeof n=="string"?`${n}
124
+ Do not include any text outside the JSON object.`}function pr(s){let e=s.match(/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/);if(e)return e[1].trim();let t=s.indexOf("{"),r=s.indexOf("[");if(t===-1&&r===-1)return s.trim();let n=t===-1?r:r===-1?t:Math.min(t,r),i=s[n]==="["?"]":"}",a=0,d=!1,l=!1;for(let p=n;p<s.length;p++){let c=s[p];if(l){l=!1;continue}if(c==="\\"){l=!0;continue}if(c==='"'){d=!d;continue}if(!d&&(c===s[n]&&a++,c===i&&(a--,a===0)))return s.slice(n,p+1)}return s.slice(n)}async function Nt(s,e,t){let r=t.maxParseRetries??2,n=typeof e=="string"?lr(e,t.schema):e,o;for(let i=0;i<=r;i++){let a=i===0?n:typeof n=="string"?`${n}
65
125
 
66
- Previous attempt failed: ${o?.message}. Please output ONLY valid JSON.`:n,d=await s.run(a);try{let p=dr(d.text);return{data:JSON.parse(p),raw:t.includeRaw?d:void 0}}catch(p){o=p instanceof Error?p:new Error(String(p))}}throw new Error(`Failed to extract structured output after ${r+1} attempts: ${o?.message}`)}var It=/\{\{(\w+)\}\}/g;function j(s){let e=[...new Set(Array.from(s.matchAll(It),r=>r[1]))],t=r=>s.replace(It,(n,o)=>{let i=r[o];if(i===void 0)throw new Error(`Missing template variable: {{${o}}}`);return i});return Object.defineProperty(t,"raw",{value:s,enumerable:!0}),Object.defineProperty(t,"variables",{value:e,enumerable:!0}),t}var jt=j(`Summarize the following {{format}} in {{style}}:
126
+ Previous attempt failed: ${o?.message}. Please output ONLY valid JSON.`:n,d=await s.run(a);try{let l=pr(d.text);return{data:JSON.parse(l),raw:t.includeRaw?d:void 0}}catch(l){o=l instanceof Error?l:new Error(String(l))}}throw new Error(`Failed to extract structured output after ${r+1} attempts: ${o?.message}`)}var jt=/\{\{(\w+)\}\}/g;function U(s){let e=[...new Set(Array.from(s.matchAll(jt),r=>r[1]))],t=r=>s.replace(jt,(n,o)=>{let i=r[o];if(i===void 0)throw new Error(`Missing template variable: {{${o}}}`);return i});return Object.defineProperty(t,"raw",{value:s,enumerable:!0}),Object.defineProperty(t,"variables",{value:e,enumerable:!0}),t}var Ht=U(`Summarize the following {{format}} in {{style}}:
67
127
 
68
- {{text}}`),Ht=j(`Translate the following text to {{language}}:
128
+ {{text}}`),Ut=U(`Translate the following text to {{language}}:
69
129
 
70
- {{text}}`),Ut=j("Review this {{language}} code for bugs, security issues, and best practices:\n\n```{{language}}\n{{code}}\n```"),Jt=j(`Classify the following text into one of these categories: {{categories}}
130
+ {{text}}`),Lt=U("Review this {{language}} code for bugs, security issues, and best practices:\n\n```{{language}}\n{{code}}\n```"),Jt=U(`Classify the following text into one of these categories: {{categories}}
71
131
 
72
132
  Text: {{text}}
73
133
 
74
- Respond with only the category name.`),Lt=j(`Extract the following information from the text: {{fields}}
134
+ Respond with only the category name.`),Gt=U(`Extract the following information from the text: {{fields}}
75
135
 
76
136
  Text: {{text}}
77
137
 
78
- Respond as JSON.`);var q=require("gauss-napi"),V=class s{name;description;model;provider;instructions;tools;skills;capabilities;environment;metadata;constructor(e){this.name=e.name,this.description=e.description,this.model=e.model??void 0,this.provider=e.provider??void 0,this.instructions=e.instructions??void 0,this.tools=Object.freeze([...e.tools]),this.skills=Object.freeze([...e.skills]),this.capabilities=Object.freeze([...e.capabilities]),this.environment=new Map(e.environment),this.metadata=Object.freeze({...e.metadata})}static fromMarkdown(e){let t=(0,q.parseAgentsMd)(e),r=typeof t=="string"?JSON.parse(t):t;return new s(r)}hasTool(e){return this.tools.some(t=>t.name===e)}hasCapability(e){return this.capabilities.includes(e)}toJSON(){return{name:this.name,description:this.description,model:this.model,provider:this.provider,instructions:this.instructions,tools:[...this.tools],skills:[...this.skills],capabilities:[...this.capabilities],environment:[...this.environment.entries()],metadata:{...this.metadata}}}},be=class s{name;description;steps;inputs;outputs;constructor(e){this.name=e.name,this.description=e.description,this.steps=Object.freeze([...e.steps]),this.inputs=Object.freeze([...e.inputs]),this.outputs=Object.freeze([...e.outputs])}static fromMarkdown(e){let t=(0,q.parseSkillMd)(e),r=typeof t=="string"?JSON.parse(t):t;return new s(r)}get stepCount(){return this.steps.length}get requiredInputs(){return this.inputs.filter(e=>e.required)}toJSON(){return{name:this.name,description:this.description,steps:[...this.steps],inputs:[...this.inputs],outputs:[...this.outputs]}}};function Gt(s){let e=(0,q.discoverAgents)(s);return(typeof e=="string"?JSON.parse(e):e).map(r=>Object.assign(Object.create(V.prototype),{name:r.name,description:r.description,model:r.model??void 0,provider:r.provider??void 0,instructions:r.instructions??void 0,tools:Object.freeze([...r.tools]),skills:Object.freeze([...r.skills]),capabilities:Object.freeze([...r.capabilities]),environment:new Map(r.environment),metadata:Object.freeze({...r.metadata})}))}async function Ft(s,...e){let t=s;for(let r of e)t=await r(t);return t}async function Be(s,e,t){let r=t?.concurrency??s.length,n=new Array(s.length),o=s.map((a,d)=>({item:a,index:d})),i=Array.from({length:Math.min(r,o.length)},async()=>{for(;o.length>0;){let a=o.shift();if(!a)break;n[a.index]=await e(a.item,a.index)}});return await Promise.all(i),n}async function $t(s,e,t){let r=await Be(s,e,t);return s.filter((n,o)=>r[o])}async function qt(s,e,t){let r=t;for(let n=0;n<s.length;n++)r=await e(r,s[n],n);return r}async function Kt(s,e){for(let t=0;t<s.length;t++)await e(s[t],t);return s}function Bt(...s){return async e=>{let t=e;for(let r of s)t=await r(t);return t}}var M=require("gauss-napi"),ke=class{baseUrl;authToken;constructor(e){typeof e=="string"?this.baseUrl=e:(this.baseUrl=e.baseUrl,this.authToken=e.authToken)}async discover(){return await(0,M.a2aDiscover)(this.baseUrl,this.authToken??void 0)}async sendMessage(e,t){let r=await(0,M.a2aSendMessage)(this.baseUrl,this.authToken??void 0,JSON.stringify(e),t?JSON.stringify(t):void 0);if(r._type==="task"){let{_type:i,...a}=r;return{type:"task",task:a}}let{_type:n,...o}=r;return{type:"message",message:o}}async ask(e){return(0,M.a2aAsk)(this.baseUrl,this.authToken??void 0,e)}async getTask(e,t){return await(0,M.a2aGetTask)(this.baseUrl,this.authToken??void 0,e,t??void 0)}async cancelTask(e){return await(0,M.a2aCancelTask)(this.baseUrl,this.authToken??void 0,e)}};function Pe(s,e){return{role:s,parts:[{type:"text",text:e}]}}function zt(s){return Pe("user",s)}function Vt(s){return Pe("agent",s)}function ze(s){return s.parts.filter(e=>e.type==="text"&&e.text).map(e=>e.text).join("")}function Yt(s){if(s.status.message)return ze(s.status.message)}var T=require("gauss-napi"),we=class{_handle;disposed=!1;constructor(){this._handle=(0,T.createToolRegistry)()}get handle(){return this._handle}add(e){return this.assertNotDisposed(),(0,T.toolRegistryAdd)(this._handle,JSON.stringify(e)),this}search(e){return this.assertNotDisposed(),(0,T.toolRegistrySearch)(this._handle,e)}byTag(e){return this.assertNotDisposed(),(0,T.toolRegistryByTag)(this._handle,e)}list(){return this.assertNotDisposed(),(0,T.toolRegistryList)(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,T.destroyToolRegistry)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("ToolRegistry has been destroyed")}};0&&(module.exports={A2aClient,ANTHROPIC_DEFAULT,ANTHROPIC_FAST,ANTHROPIC_PREMIUM,Agent,AgentSpec,AgentStream,ApprovalManager,CheckpointStore,ControlPlane,DEEPSEEK_DEFAULT,DEEPSEEK_REASONING,DisposedError,EvalRunner,FIREWORKS_DEFAULT,GOOGLE_DEFAULT,GOOGLE_IMAGE,GOOGLE_PREMIUM,GaussError,Graph,GuardrailChain,MISTRAL_DEFAULT,McpClient,McpServer,Memory,MiddlewareChain,Network,OPENAI_DEFAULT,OPENAI_FAST,OPENAI_IMAGE,OPENAI_REASONING,OPENROUTER_DEFAULT,PERPLEXITY_DEFAULT,PROVIDER_DEFAULTS,PluginRegistry,ProviderError,SkillSpec,TOGETHER_DEFAULT,Team,Telemetry,TextSplitter,ToolExecutionError,ToolRegistry,ToolValidator,ValidationError,VectorStore,Workflow,XAI_DEFAULT,agentMessage,availableRuntimes,batch,classify,clearPricing,codeReview,compose,countMessageTokens,countTokens,countTokensForModel,createCircuitBreaker,createFallbackProvider,createResilientAgent,createResilientProvider,createToolExecutor,defaultModel,detectProvider,discoverAgents,enforceRoutingCostLimit,enforceRoutingRateLimit,enterprisePreset,enterpriseRun,estimateCost,executeCode,extract,extractText,filterAsync,gauss,generateImage,getContextWindowSize,getPricing,isTypedTool,loadJson,loadMarkdown,loadText,mapAsync,parseAgentConfig,parsePartialJson,pipe,reduceAsync,resolveApiKey,resolveEnv,resolveFallbackProvider,resolveRoutingTarget,retryable,setPricing,splitText,structured,summarize,tapAsync,taskText,template,textMessage,tool,translate,userMessage,version,withRetry});
138
+ Respond as JSON.`);var B=require("gauss-napi"),V=class s{name;description;model;provider;instructions;tools;skills;capabilities;environment;metadata;constructor(e){this.name=e.name,this.description=e.description,this.model=e.model??void 0,this.provider=e.provider??void 0,this.instructions=e.instructions??void 0,this.tools=Object.freeze([...e.tools]),this.skills=Object.freeze([...e.skills]),this.capabilities=Object.freeze([...e.capabilities]),this.environment=new Map(e.environment),this.metadata=Object.freeze({...e.metadata})}static fromMarkdown(e){let t=(0,B.parseAgentsMd)(e),r=typeof t=="string"?JSON.parse(t):t;return new s(r)}hasTool(e){return this.tools.some(t=>t.name===e)}hasCapability(e){return this.capabilities.includes(e)}toJSON(){return{name:this.name,description:this.description,model:this.model,provider:this.provider,instructions:this.instructions,tools:[...this.tools],skills:[...this.skills],capabilities:[...this.capabilities],environment:[...this.environment.entries()],metadata:{...this.metadata}}}},ke=class s{name;description;steps;inputs;outputs;constructor(e){this.name=e.name,this.description=e.description,this.steps=Object.freeze([...e.steps]),this.inputs=Object.freeze([...e.inputs]),this.outputs=Object.freeze([...e.outputs])}static fromMarkdown(e){let t=(0,B.parseSkillMd)(e),r=typeof t=="string"?JSON.parse(t):t;return new s(r)}get stepCount(){return this.steps.length}get requiredInputs(){return this.inputs.filter(e=>e.required)}toJSON(){return{name:this.name,description:this.description,steps:[...this.steps],inputs:[...this.inputs],outputs:[...this.outputs]}}};function Ft(s){let e=(0,B.discoverAgents)(s);return(typeof e=="string"?JSON.parse(e):e).map(r=>Object.assign(Object.create(V.prototype),{name:r.name,description:r.description,model:r.model??void 0,provider:r.provider??void 0,instructions:r.instructions??void 0,tools:Object.freeze([...r.tools]),skills:Object.freeze([...r.skills]),capabilities:Object.freeze([...r.capabilities]),environment:new Map(r.environment),metadata:Object.freeze({...r.metadata})}))}async function $t(s,...e){let t=s;for(let r of e)t=await r(t);return t}async function ze(s,e,t){let r=t?.concurrency??s.length,n=new Array(s.length),o=s.map((a,d)=>({item:a,index:d})),i=Array.from({length:Math.min(r,o.length)},async()=>{for(;o.length>0;){let a=o.shift();if(!a)break;n[a.index]=await e(a.item,a.index)}});return await Promise.all(i),n}async function qt(s,e,t){let r=await ze(s,e,t);return s.filter((n,o)=>r[o])}async function Bt(s,e,t){let r=t;for(let n=0;n<s.length;n++)r=await e(r,s[n],n);return r}async function Kt(s,e){for(let t=0;t<s.length;t++)await e(s[t],t);return s}function zt(...s){return async e=>{let t=e;for(let r of s)t=await r(t);return t}}var O=require("gauss-napi"),Pe=class{baseUrl;authToken;constructor(e){typeof e=="string"?this.baseUrl=e:(this.baseUrl=e.baseUrl,this.authToken=e.authToken)}async discover(){return await(0,O.a2aDiscover)(this.baseUrl,this.authToken??void 0)}async sendMessage(e,t){let r=await(0,O.a2aSendMessage)(this.baseUrl,this.authToken??void 0,JSON.stringify(e),t?JSON.stringify(t):void 0);if(r._type==="task"){let{_type:i,...a}=r;return{type:"task",task:a}}let{_type:n,...o}=r;return{type:"message",message:o}}async ask(e){return(0,O.a2aAsk)(this.baseUrl,this.authToken??void 0,e)}async getTask(e,t){return await(0,O.a2aGetTask)(this.baseUrl,this.authToken??void 0,e,t??void 0)}async cancelTask(e){return await(0,O.a2aCancelTask)(this.baseUrl,this.authToken??void 0,e)}};function Ce(s,e){return{role:s,parts:[{type:"text",text:e}]}}function Vt(s){return Ce("user",s)}function Yt(s){return Ce("agent",s)}function Ve(s){return s.parts.filter(e=>e.type==="text"&&e.text).map(e=>e.text).join("")}function Wt(s){if(s.status.message)return Ve(s.status.message)}var T=require("gauss-napi"),we=class{_handle;disposed=!1;constructor(){this._handle=(0,T.createToolRegistry)()}get handle(){return this._handle}add(e){return this.assertNotDisposed(),(0,T.toolRegistryAdd)(this._handle,JSON.stringify(e)),this}search(e){return this.assertNotDisposed(),(0,T.toolRegistrySearch)(this._handle,e)}byTag(e){return this.assertNotDisposed(),(0,T.toolRegistryByTag)(this._handle,e)}list(){return this.assertNotDisposed(),(0,T.toolRegistryList)(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,T.destroyToolRegistry)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("ToolRegistry has been destroyed")}};0&&(module.exports={A2aClient,ANTHROPIC_DEFAULT,ANTHROPIC_FAST,ANTHROPIC_PREMIUM,Agent,AgentSpec,AgentStream,ApprovalManager,CheckpointStore,ControlPlane,DEEPSEEK_DEFAULT,DEEPSEEK_REASONING,DisposedError,EvalRunner,FIREWORKS_DEFAULT,GOOGLE_DEFAULT,GOOGLE_IMAGE,GOOGLE_PREMIUM,GaussError,Graph,GuardrailChain,MISTRAL_DEFAULT,McpClient,McpServer,Memory,MiddlewareChain,Network,OPENAI_DEFAULT,OPENAI_FAST,OPENAI_IMAGE,OPENAI_REASONING,OPENROUTER_DEFAULT,PERPLEXITY_DEFAULT,PROVIDER_DEFAULTS,PluginRegistry,ProviderError,SkillSpec,TOGETHER_DEFAULT,Team,Telemetry,TextSplitter,ToolExecutionError,ToolRegistry,ToolValidator,ValidationError,VectorStore,Workflow,XAI_DEFAULT,agentMessage,availableRuntimes,batch,classify,clearPricing,codeReview,compose,countMessageTokens,countTokens,countTokensForModel,createCircuitBreaker,createFallbackProvider,createResilientAgent,createResilientProvider,createToolExecutor,defaultModel,detectProvider,discoverAgents,enforceRoutingCostLimit,enforceRoutingRateLimit,enterprisePreset,enterpriseRun,estimateCost,executeCode,extract,extractText,filterAsync,gauss,generateImage,getContextWindowSize,getPricing,isTypedTool,loadJson,loadMarkdown,loadText,mapAsync,parseAgentConfig,parsePartialJson,pipe,reduceAsync,resolveApiKey,resolveEnv,resolveFallbackProvider,resolveRoutingTarget,retryable,setPricing,splitText,structured,summarize,tapAsync,taskText,template,textMessage,tool,translate,userMessage,version,withRetry});
79
139
  //# sourceMappingURL=index.cjs.map