gauss-ts 2.0.13 → 2.0.15

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/dist/index.d.cts CHANGED
@@ -369,7 +369,10 @@ declare class ControlPlane implements Disposable {
369
369
  private parseLastEventId;
370
370
  private parseContextFilters;
371
371
  private parsePolicyProvider;
372
+ private parseOptionalNumber;
373
+ private parsePolicyExplainScenario;
372
374
  private parsePolicyExplainOptions;
375
+ private parsePolicyExplainBatchScenarios;
373
376
  private buildStreamEvent;
374
377
  private writeSseEvent;
375
378
  private opsCapabilities;
@@ -377,6 +380,8 @@ declare class ControlPlane implements Disposable {
377
380
  private opsSummary;
378
381
  private opsTenants;
379
382
  private opsPolicyExplain;
383
+ private opsPolicyExplainBatch;
384
+ private opsPolicyExplainSimulation;
380
385
  private emitStreamBatch;
381
386
  private replayStreamEvents;
382
387
  private assertChannelAllowed;
package/dist/index.d.ts CHANGED
@@ -369,7 +369,10 @@ declare class ControlPlane implements Disposable {
369
369
  private parseLastEventId;
370
370
  private parseContextFilters;
371
371
  private parsePolicyProvider;
372
+ private parseOptionalNumber;
373
+ private parsePolicyExplainScenario;
372
374
  private parsePolicyExplainOptions;
375
+ private parsePolicyExplainBatchScenarios;
373
376
  private buildStreamEvent;
374
377
  private writeSseEvent;
375
378
  private opsCapabilities;
@@ -377,6 +380,8 @@ declare class ControlPlane implements Disposable {
377
380
  private opsSummary;
378
381
  private opsTenants;
379
382
  private opsPolicyExplain;
383
+ private opsPolicyExplainBatch;
384
+ private opsPolicyExplainSimulation;
380
385
  private emitStreamBatch;
381
386
  private replayStreamEvents;
382
387
  private assertChannelAllowed;
package/dist/index.js CHANGED
@@ -1,28 +1,28 @@
1
- var v=class extends Error{code;constructor(e,t){super(t),this.name="GaussError",this.code=e}},y=class extends v{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}},N=class extends v{provider;constructor(e,t){super("PROVIDER_ERROR",`[${e}] ${t}`),this.name="ProviderError",this.provider=e}},I=class extends v{toolName;cause;constructor(e,t,r){super("TOOL_EXECUTION_ERROR",`Tool "${e}" failed: ${t}`),this.name="ToolExecutionError",this.toolName=e,this.cause=r}},h=class extends v{field;constructor(e,t){super("VALIDATION_ERROR",t?`Invalid "${t}": ${e}`:e),this.name="ValidationError",this.field=t}};var k="gpt-5.2",Ue="gpt-4.1",Le="o4-mini",Ge="gpt-image-1",he="claude-sonnet-4-20250514",Je="claude-haiku-4-20250414",$e="claude-opus-4-20250414",ge="gemini-2.5-flash",Fe="gemini-2.5-pro",qe="gemini-2.0-flash",ye="openai/gpt-5.2",fe="deepseek-chat",Be="deepseek-reasoner",ve="meta-llama/Llama-3.3-70B-Instruct-Turbo",xe="accounts/fireworks/models/llama-v3p1-70b-instruct",Te="mistral-large-latest",_e="sonar-pro",ke="grok-3-beta",A={openai:k,anthropic:he,google:ge,openrouter:ye,deepseek:fe,groq:"llama-3.3-70b-versatile",ollama:"llama3.2",together:ve,fireworks:xe,mistral:Te,perplexity:_e,xai:ke};function ze(n){return A[n]??k}var Ke={openai:"OPENAI_API_KEY",anthropic:"ANTHROPIC_API_KEY",google:"GOOGLE_API_KEY",groq:"GROQ_API_KEY",deepseek:"DEEPSEEK_API_KEY",openrouter:"OPENROUTER_API_KEY",together:"TOGETHER_API_KEY",fireworks:"FIREWORKS_API_KEY",mistral:"MISTRAL_API_KEY",perplexity:"PERPLEXITY_API_KEY",xai:"XAI_API_KEY",ollama:""};function b(n){let e=Ke[n]??"";return e?(typeof process<"u"?process.env[e]:"")??"":""}function w(){let n=[{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 n)if(typeof process<"u"&&process.env[e])return{provider:t,model:A[t]}}import{create_provider as Xe,destroy_provider as Qe,agent_run as Ze,agent_run_with_tool_executor as Pe,agent_stream_with_tool_executor as et,generate as tt,generate_with_tools as rt,get_provider_capabilities as nt}from"gauss-napi";function be(n){switch(n){case"enterprise-strict":return{rules:[{type:"allow_provider",provider:"openai"},{type:"allow_provider",provider:"anthropic"},{type:"require_tag",tag:"pci"}]};case"eu-residency":return{rules:[{type:"deny_provider",provider:"xai"},{type:"require_tag",tag:"eu"}]};case"cost-guarded":return{rules:[{type:"allow_provider",provider:"openai"},{type:"allow_provider",provider:"deepseek"},{type:"require_tag",tag:"cost-sensitive"}]};case"ops-business-hours":return{rules:[{type:"require_tag",tag:"ops"}]};case"balanced-mix":return{rules:[{type:"allow_provider",provider:"openai"},{type:"allow_provider",provider:"anthropic"},{type:"require_tag",tag:"balanced"}]}}}function Ve(n,e){let t=be(e),r=n?.governance?.rules??[],s=e==="ops-business-hours"?Array.from({length:11},(i,a)=>a+8):n?.allowedHoursUtc,o=e==="balanced-mix"?{...n?.providerWeights??{},openai:60,anthropic:40}:n?.providerWeights;return{...n,allowedHoursUtc:s,providerWeights:o,governance:{rules:[...r,...t.rules]}}}function H(n,e){if(n?.maxTotalCostUsd!==void 0&&e>n.maxTotalCostUsd)throw new Error(`routing policy rejected cost ${e}`)}function j(n,e){if(n?.maxRequestsPerMinute!==void 0&&e>n.maxRequestsPerMinute)throw new Error(`routing policy rejected rate ${e}`)}function U(n,e){let t=n?.allowedHoursUtc;if(!(!t||t.length===0)&&(!Number.isInteger(e)||e<0||e>23||!t.includes(e)))throw new Error(`routing policy rejected hour ${e}`)}function P(n,e,t){let r=n?.governance?.rules??[];if(r.length===0)return;let s=r.filter(o=>o.type==="allow_provider").map(o=>o.provider);if(s.length>0&&!s.includes(e))throw new Error(`routing policy governance rejected provider ${e}`);for(let o of r){if(o.type==="deny_provider"&&o.provider===e)throw new Error(`routing policy governance rejected provider ${e}`);if(o.type==="require_tag"&&t!==void 0&&!t.includes(o.tag))throw new Error(`routing policy governance missing tag ${o.tag}`)}}function we(n,e){let t=n?.fallbackOrder;if(!t||t.length===0||e.length===0)return null;let r=new Set(e);for(let s of t)if(r.has(s))return s;return null}function C(n,e,t,r={}){let s=r.governanceTags,o=r.currentHourUtc??new Date().getUTCHours();U(n,o),r.estimatedCostUsd!==void 0&&H(n,r.estimatedCostUsd),r.currentRequestsPerMinute!==void 0&&j(n,r.currentRequestsPerMinute);let i=p=>p.length===1?p[0]:[...p].sort((l,c)=>{let u=n?.providerWeights?.[c.provider]??0,m=n?.providerWeights?.[l.provider]??0;return u!==m?u-m:(c.priority??0)-(l.priority??0)})[0],a=n?.aliases?.[t];if(a&&a.length>0){let p=[...a].sort((m,f)=>(f.priority??0)-(m.priority??0)),l=r.availableProviders;if(!l||l.length===0){let m=i(p);return P(n,m.provider,s),{provider:m.provider,model:m.model,selectedBy:`alias:${t}`}}let c=new Set(l),u=p.filter(m=>c.has(m.provider));if(u.length>0){let m=i(u);return P(n,m.provider,s),{provider:m.provider,model:m.model,selectedBy:`alias:${t}`}}}let d=we(n,r.availableProviders??[]);return d&&d!==e?(P(n,d,s),{provider:d,model:t,selectedBy:`fallback:${d}`}):(P(n,e,s),{provider:e,model:t,selectedBy:"direct"})}function L(n,e,t,r={}){let s=[],o=r.currentHourUtc??new Date().getUTCHours(),i=(a,d)=>{let p=d instanceof Error?d.message:String(d);return s.push({check:a,status:"failed",detail:p}),{ok:!1,checks:s,error:p}};if(n?.allowedHoursUtc&&n.allowedHoursUtc.length>0)try{U(n,o),s.push({check:"time_window",status:"passed",detail:`hour=${o}`})}catch(a){return i("time_window",a)}else s.push({check:"time_window",status:"skipped",detail:"not configured"});if(r.estimatedCostUsd!==void 0)try{H(n,r.estimatedCostUsd),s.push({check:"cost_limit",status:"passed",detail:`cost=${r.estimatedCostUsd}`})}catch(a){return i("cost_limit",a)}else s.push({check:"cost_limit",status:"skipped",detail:"no estimate provided"});if(r.currentRequestsPerMinute!==void 0)try{j(n,r.currentRequestsPerMinute),s.push({check:"rate_limit",status:"passed",detail:`rpm=${r.currentRequestsPerMinute}`})}catch(a){return i("rate_limit",a)}else s.push({check:"rate_limit",status:"skipped",detail:"no rpm provided"});try{let a=C(n,e,t,r);return s.push({check:"governance",status:"passed",detail:"accepted"}),s.push({check:"selection",status:"passed",detail:a.selectedBy}),{ok:!0,decision:a,checks:s}}catch(a){let d=a instanceof Error?a.message:String(a);return d.includes("governance")?(s.push({check:"governance",status:"failed",detail:d}),s.push({check:"selection",status:"skipped",detail:"selection aborted"}),{ok:!1,checks:s,error:d}):i("selection",a)}}import{agent_stream_with_tool_executor as We}from"gauss-napi";function Ye(n){return{...n,citations:n.citations?.map(e=>({type:e.citationType??e.type,citedText:e.citedText,documentTitle:e.documentTitle,start:e.start,end:e.end}))}}var S=class{constructor(e,t,r,s,o,i){this.agentName=e;this.providerHandle=t;this.tools=r;this.messages=s;this.options=o;this.toolExecutor=i}_result;get result(){return this._result}async*[Symbol.asyncIterator](){let e=[],t,r=!1,s=i=>{try{e.push(JSON.parse(i))}catch{e.push({type:"raw",text:i})}t?.()},o=We(this.agentName,this.providerHandle,this.tools,this.messages,this.options,s,this.toolExecutor).then(i=>{this._result=Ye(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 G(n){return{name:n.name,description:n.description,parameters:n.parameters,execute:n.execute}}function J(n){return typeof n.execute=="function"}function $(n,e){let t=new Map(n.map(r=>[r.name,r]));return async r=>{let s;try{s=JSON.parse(r)}catch{return JSON.stringify({error:"Invalid tool call JSON"})}let o=s.tool??s.name??"",i=t.get(o);if(!i)return e?e(r):JSON.stringify({error:`Unknown tool: ${o}`});try{let a=s.args??s.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 D(n){return{...n,citations:n.citations?.map(e=>({type:e.citationType??e.type??"unknown",citedText:e.citedText,documentTitle:e.documentTitle,start:e.start,end:e.end}))}}var g=class n{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=w(),r=e.provider??t?.provider??"openai",s=e.model??t?.model??k;this._requestedProvider=r,this._requestedModel=s,this._routingPolicy=e.routingPolicy;let o=C(this._routingPolicy,r,s);this._provider=o.provider,this._model=o.model,this._name=e.name??"agent",this._instructions=e.instructions??"";let i=e.providerOptions?.apiKey??b(this._provider);this._providerOptions={apiKey:i,...e.providerOptions},this.providerHandle=Xe(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 n(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 nt(this.providerHandle)}addTool(e){return this._tools.push(e),this}addTools(e){return this._tools.push(...e),this}withTool(e,t,r,s){return this._tools.push(G({name:e,description:t,parameters:s??{},execute:r})),this}setOptions(e){return this._options={...this._options,...e},this}withModel(e){return this.assertNotDisposed(),new n({...this.toConfig(),model:e})}withRoutingContext(e){this.assertNotDisposed();let t=C(this._routingPolicy,this._requestedProvider,this._requestedModel,e);return new n({...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
- ${i.map(d=>d.content).join(`
3
- `)}`},...t])}let{toolDefs:r,executor:s}=this.resolveToolsAndExecutor(),o;if(s?o=D(await Pe(this._name,this.providerHandle,r,t,this._options,s)):o=D(await Ze(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:s,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 D(await Pe(this._name,this.providerHandle,s,r,this._options,i))}async stream(e,t,r){this.assertNotDisposed(),await this.ensureMcpTools();let s=typeof e=="string"?[{role:"user",content:e}]:e,{toolDefs:o,executor:i}=this.resolveToolsAndExecutor(),a=r??i??Ce;return D(await et(this._name,this.providerHandle,o,s,this._options,t,a))}streamIter(e,t){this.assertNotDisposed();let r=typeof e=="string"?[{role:"user",content:e}]:e,{toolDefs:s,executor:o}=this.resolveToolsAndExecutor(),i=t??o??Ce;return new S(this._name,this.providerHandle,s,r,this._options,i)}async streamText(e,t,r){this.assertNotDisposed();let s=this.streamIter(e,r),o="";for await(let i of s){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 s.result?.text??o}async generate(e,t){this.assertNotDisposed();let r=typeof e=="string"?[{role:"user",content:e}]:e;return tt(this.providerHandle,r,t?.temperature,t?.maxTokens)}async generateWithTools(e,t,r){this.assertNotDisposed();let s=typeof e=="string"?[{role:"user",content:e}]:e;return rt(this.providerHandle,s,t,r?.temperature,r?.maxTokens)}destroy(){if(!this.disposed){this.disposed=!0;for(let e of this._mcpClients)try{e.close()}catch{}try{Qe(this.providerHandle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new y("Agent",this._name)}resolveToolsAndExecutor(){let e=this._tools.filter(J),t=this._tools.map(s=>({name:s.name,description:s.description,parameters:s.parameters})),r=e.length>0?$(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 s of t){let o={...s,execute:async i=>{let a=JSON.stringify({tool:s.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}}},Ce=async()=>"{}";async function st(n,e){let t=new g({name:"gauss",...e});try{return(await t.run(n)).text}finally{t.destroy()}}function Se(n={}){let e=n.providerOptions?.maxRetries??n.retries??5;return new g({...n,name:n.name??"enterprise-agent",maxSteps:n.maxSteps??20,temperature:n.temperature??.2,cacheControl:n.cacheControl??!0,reasoningEffort:n.reasoningEffort??"medium",providerOptions:{...n.providerOptions,maxRetries:e}})}async function ot(n,e){let t=Se(e);try{return(await t.run(n)).text}finally{t.destroy()}}async function it(n,e){let{concurrency:t=5,...r}=e??{},s=n.map(i=>({input:i})),o=new g({name:"batch",...r});try{let i=[...s.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{s[p].result=await o.run(l.input)}catch(c){s[p].error=c instanceof Error?c:new Error(String(c))}}});await Promise.all(a)}finally{o.destroy()}return s}import{create_provider as at,destroy_provider as dt,execute_code as pt,available_runtimes as lt,generate_image as ct}from"gauss-napi";import{version as gt}from"gauss-napi";async function ut(n,e,t){return pt(n,e,t?.timeoutSecs,t?.workingDir,t?.sandbox)}async function mt(){return lt()}async function ht(n,e={}){let t=w(),r=e.provider??t?.provider??"openai",s=e.model??t?.model??"dall-e-3",o=e.providerOptions?.apiKey??b(r),i=at(r,s,{apiKey:o,...e.providerOptions});try{return await ct(i,n,e.model,e.size,e.quality,e.style,e.aspectRatio,e.n,e.responseFormat)}finally{dt(i)}}import{randomUUID as yt}from"crypto";import{create_memory as ft,memory_store as vt,memory_recall as xt,memory_clear as Tt,memory_stats as _t,destroy_memory as kt}from"gauss-napi";var F=class{_handle;disposed=!1;constructor(){this._handle=ft()}get handle(){return this._handle}async store(e,t,r){this.assertNotDisposed();let s=typeof e=="string"?{id:yt(),content:t,entryType:e||"conversation",timestamp:new Date().toISOString(),sessionId:r}:e,o={id:s.id,content:s.content,entry_type:s.entryType,timestamp:s.timestamp,tier:s.tier,metadata:s.metadata,importance:s.importance,session_id:s.sessionId,embedding:s.embedding};return vt(this._handle,JSON.stringify(o))}async recall(e){this.assertNotDisposed();let t=e?JSON.stringify(e):void 0;return xt(this._handle,t)}async clear(e){return this.assertNotDisposed(),Tt(this._handle,e)}async stats(){return this.assertNotDisposed(),_t(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{kt(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Memory has been destroyed")}};import{create_vector_store as bt,vector_store_upsert as wt,vector_store_search as Pt,destroy_vector_store as Ct,cosine_similarity as St}from"gauss-napi";var q=class{_handle;disposed=!1;constructor(e){this._handle=bt()}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 wt(this._handle,JSON.stringify(t))}async search(e,t){return this.assertNotDisposed(),Pt(this._handle,JSON.stringify(e),t)}async searchByText(e,t,r){this.assertNotDisposed();let s=await r(e);return this.search(s,t)}destroy(){if(!this.disposed){this.disposed=!0;try{Ct(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("VectorStore has been destroyed")}static cosineSimilarity(e,t){return St(e,t)}};var Rt=[`
1
+ var f=class extends Error{code;constructor(e,t){super(t),this.name="GaussError",this.code=e}},y=class extends f{resourceType;resourceName;constructor(e,t){super("RESOURCE_DISPOSED",`${e} "${t}" has been destroyed. Create a new instance.`),this.name="DisposedError",this.resourceType=e,this.resourceName=t}},I=class extends f{provider;constructor(e,t){super("PROVIDER_ERROR",`[${e}] ${t}`),this.name="ProviderError",this.provider=e}},H=class extends f{toolName;cause;constructor(e,t,r){super("TOOL_EXECUTION_ERROR",`Tool "${e}" failed: ${t}`),this.name="ToolExecutionError",this.toolName=e,this.cause=r}},m=class extends f{field;constructor(e,t){super("VALIDATION_ERROR",t?`Invalid "${t}": ${e}`:e),this.name="ValidationError",this.field=t}};var k="gpt-5.2",Ue="gpt-4.1",Le="o4-mini",Je="gpt-image-1",he="claude-sonnet-4-20250514",Ge="claude-haiku-4-20250414",$e="claude-opus-4-20250414",ge="gemini-2.5-flash",Fe="gemini-2.5-pro",qe="gemini-2.0-flash",ye="openai/gpt-5.2",fe="deepseek-chat",Be="deepseek-reasoner",ve="meta-llama/Llama-3.3-70B-Instruct-Turbo",xe="accounts/fireworks/models/llama-v3p1-70b-instruct",Te="mistral-large-latest",ke="sonar-pro",_e="grok-3-beta",A={openai:k,anthropic:he,google:ge,openrouter:ye,deepseek:fe,groq:"llama-3.3-70b-versatile",ollama:"llama3.2",together:ve,fireworks:xe,mistral:Te,perplexity:ke,xai:_e};function ze(s){return A[s]??k}var Ke={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 _(s){let e=Ke[s]??"";return e?(typeof process<"u"?process.env[e]:"")??"":""}function b(){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:A[t]}}import{create_provider as Xe,destroy_provider as Qe,agent_run as Ze,agent_run_with_tool_executor as we,agent_stream_with_tool_executor as et,generate as tt,generate_with_tools as rt,get_provider_capabilities as nt}from"gauss-napi";function be(s){switch(s){case"enterprise-strict":return{rules:[{type:"allow_provider",provider:"openai"},{type:"allow_provider",provider:"anthropic"},{type:"require_tag",tag:"pci"}]};case"eu-residency":return{rules:[{type:"deny_provider",provider:"xai"},{type:"require_tag",tag:"eu"}]};case"cost-guarded":return{rules:[{type:"allow_provider",provider:"openai"},{type:"allow_provider",provider:"deepseek"},{type:"require_tag",tag:"cost-sensitive"}]};case"ops-business-hours":return{rules:[{type:"require_tag",tag:"ops"}]};case"balanced-mix":return{rules:[{type:"allow_provider",provider:"openai"},{type:"allow_provider",provider:"anthropic"},{type:"require_tag",tag:"balanced"}]}}}function Ve(s,e){let t=be(e),r=s?.governance?.rules??[],n=e==="ops-business-hours"?Array.from({length:11},(i,a)=>a+8):s?.allowedHoursUtc,o=e==="balanced-mix"?{...s?.providerWeights??{},openai:60,anthropic:40}:s?.providerWeights;return{...s,allowedHoursUtc:n,providerWeights:o,governance:{rules:[...r,...t.rules]}}}function j(s,e){if(s?.maxTotalCostUsd!==void 0&&e>s.maxTotalCostUsd)throw new Error(`routing policy rejected cost ${e}`)}function U(s,e){if(s?.maxRequestsPerMinute!==void 0&&e>s.maxRequestsPerMinute)throw new Error(`routing policy rejected rate ${e}`)}function L(s,e){let t=s?.allowedHoursUtc;if(!(!t||t.length===0)&&(!Number.isInteger(e)||e<0||e>23||!t.includes(e)))throw new Error(`routing policy rejected hour ${e}`)}function P(s,e,t){let r=s?.governance?.rules??[];if(r.length===0)return;let n=r.filter(o=>o.type==="allow_provider").map(o=>o.provider);if(n.length>0&&!n.includes(e))throw new Error(`routing policy governance rejected provider ${e}`);for(let o of r){if(o.type==="deny_provider"&&o.provider===e)throw new Error(`routing policy governance rejected provider ${e}`);if(o.type==="require_tag"&&t!==void 0&&!t.includes(o.tag))throw new Error(`routing policy governance missing tag ${o.tag}`)}}function Pe(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 w(s,e,t,r={}){let n=r.governanceTags,o=r.currentHourUtc??new Date().getUTCHours();L(s,o),r.estimatedCostUsd!==void 0&&j(s,r.estimatedCostUsd),r.currentRequestsPerMinute!==void 0&&U(s,r.currentRequestsPerMinute);let i=p=>p.length===1?p[0]:[...p].sort((d,c)=>{let h=s?.providerWeights?.[c.provider]??0,u=s?.providerWeights?.[d.provider]??0;return h!==u?h-u:(c.priority??0)-(d.priority??0)})[0],a=s?.aliases?.[t];if(a&&a.length>0){let p=[...a].sort((u,E)=>(E.priority??0)-(u.priority??0)),d=r.availableProviders;if(!d||d.length===0){let u=i(p);return P(s,u.provider,n),{provider:u.provider,model:u.model,selectedBy:`alias:${t}`}}let c=new Set(d),h=p.filter(u=>c.has(u.provider));if(h.length>0){let u=i(h);return P(s,u.provider,n),{provider:u.provider,model:u.model,selectedBy:`alias:${t}`}}}let l=Pe(s,r.availableProviders??[]);return l&&l!==e?(P(s,l,n),{provider:l,model:t,selectedBy:`fallback:${l}`}):(P(s,e,n),{provider:e,model:t,selectedBy:"direct"})}function D(s,e,t,r={}){let n=[],o=r.currentHourUtc??new Date().getUTCHours(),i=(a,l)=>{let p=l instanceof Error?l.message:String(l);return n.push({check:a,status:"failed",detail:p}),{ok:!1,checks:n,error:p}};if(s?.allowedHoursUtc&&s.allowedHoursUtc.length>0)try{L(s,o),n.push({check:"time_window",status:"passed",detail:`hour=${o}`})}catch(a){return i("time_window",a)}else n.push({check:"time_window",status:"skipped",detail:"not configured"});if(r.estimatedCostUsd!==void 0)try{j(s,r.estimatedCostUsd),n.push({check:"cost_limit",status:"passed",detail:`cost=${r.estimatedCostUsd}`})}catch(a){return i("cost_limit",a)}else n.push({check:"cost_limit",status:"skipped",detail:"no estimate provided"});if(r.currentRequestsPerMinute!==void 0)try{U(s,r.currentRequestsPerMinute),n.push({check:"rate_limit",status:"passed",detail:`rpm=${r.currentRequestsPerMinute}`})}catch(a){return i("rate_limit",a)}else n.push({check:"rate_limit",status:"skipped",detail:"no rpm provided"});try{let a=w(s,e,t,r);return n.push({check:"governance",status:"passed",detail:"accepted"}),n.push({check:"selection",status:"passed",detail:a.selectedBy}),{ok:!0,decision:a,checks:n}}catch(a){let l=a instanceof Error?a.message:String(a);return l.includes("governance")?(n.push({check:"governance",status:"failed",detail:l}),n.push({check:"selection",status:"skipped",detail:"selection aborted"}),{ok:!1,checks:n,error:l}):i("selection",a)}}import{agent_stream_with_tool_executor as We}from"gauss-napi";function Ye(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 C=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=We(this.agentName,this.providerHandle,this.tools,this.messages,this.options,n,this.toolExecutor).then(i=>{this._result=Ye(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 J(s){return{name:s.name,description:s.description,parameters:s.parameters,execute:s.execute}}function G(s){return typeof s.execute=="function"}function $(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??{},l=await i.execute(a);return typeof l=="string"?l:JSON.stringify(l)}catch(a){let l=a instanceof Error?a.message:String(a);return JSON.stringify({error:`Tool "${o}" failed: ${l}`})}}}function O(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 g=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=b(),r=e.provider??t?.provider??"openai",n=e.model??t?.model??k;this._requestedProvider=r,this._requestedModel=n,this._routingPolicy=e.routingPolicy;let o=w(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??_(this._provider);this._providerOptions={apiKey:i,...e.providerOptions},this.providerHandle=Xe(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,l=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:l,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 nt(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(J({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=w(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
+ ${i.map(l=>l.content).join(`
3
+ `)}`},...t])}let{toolDefs:r,executor:n}=this.resolveToolsAndExecutor(),o;if(n?o=O(await we(this._name,this.providerHandle,r,t,this._options,n)):o=O(await Ze(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 l=await o(a);if(!JSON.parse(l).error?.startsWith("Unknown tool:"))return l}return t(a)};return O(await we(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??Ce;return O(await et(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??Ce;return new C(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 tt(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 rt(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{Qe(this.providerHandle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new y("Agent",this._name)}resolveToolsAndExecutor(){let e=this._tools.filter(G),t=this._tools.map(n=>({name:n.name,description:n.description,parameters:n.parameters})),r=e.length>0?$(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}),l=await r(a);return JSON.parse(l)}};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}}},Ce=async()=>"{}";async function st(s,e){let t=new g({name:"gauss",...e});try{return(await t.run(s)).text}finally{t.destroy()}}function Se(s={}){let e=s.providerOptions?.maxRetries??s.retries??5;return new g({...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 ot(s,e){let t=Se(e);try{return(await t.run(s)).text}finally{t.destroy()}}async function it(s,e){let{concurrency:t=5,...r}=e??{},n=s.map(i=>({input:i})),o=new g({name:"batch",...r});try{let i=[...n.entries()],a=Array.from({length:Math.min(t,i.length)},async()=>{for(;i.length>0;){let l=i.shift();if(!l)break;let[p,d]=l;try{n[p].result=await o.run(d.input)}catch(c){n[p].error=c instanceof Error?c:new Error(String(c))}}});await Promise.all(a)}finally{o.destroy()}return n}import{create_provider as at,destroy_provider as lt,execute_code as pt,available_runtimes as dt,generate_image as ct}from"gauss-napi";import{version as gt}from"gauss-napi";async function ut(s,e,t){return pt(s,e,t?.timeoutSecs,t?.workingDir,t?.sandbox)}async function mt(){return dt()}async function ht(s,e={}){let t=b(),r=e.provider??t?.provider??"openai",n=e.model??t?.model??"dall-e-3",o=e.providerOptions?.apiKey??_(r),i=at(r,n,{apiKey:o,...e.providerOptions});try{return await ct(i,s,e.model,e.size,e.quality,e.style,e.aspectRatio,e.n,e.responseFormat)}finally{lt(i)}}import{randomUUID as yt}from"crypto";import{create_memory as ft,memory_store as vt,memory_recall as xt,memory_clear as Tt,memory_stats as kt,destroy_memory as _t}from"gauss-napi";var F=class{_handle;disposed=!1;constructor(){this._handle=ft()}get handle(){return this._handle}async store(e,t,r){this.assertNotDisposed();let n=typeof e=="string"?{id:yt(),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 vt(this._handle,JSON.stringify(o))}async recall(e){this.assertNotDisposed();let t=e?JSON.stringify(e):void 0;return xt(this._handle,t)}async clear(e){return this.assertNotDisposed(),Tt(this._handle,e)}async stats(){return this.assertNotDisposed(),kt(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{_t(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Memory has been destroyed")}};import{create_vector_store as bt,vector_store_upsert as Pt,vector_store_search as wt,destroy_vector_store as Ct,cosine_similarity as St}from"gauss-napi";var q=class{_handle;disposed=!1;constructor(e){this._handle=bt()}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 Pt(this._handle,JSON.stringify(t))}async search(e,t){return this.assertNotDisposed(),wt(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{Ct(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("VectorStore has been destroyed")}static cosineSimilarity(e,t){return St(e,t)}};var Rt=[`
5
5
 
6
6
  `,`
7
- `,". "," ",""],T=class{chunkSize;chunkOverlap;separators;constructor(e={}){this.chunkSize=e.chunkSize??1e3,this.chunkOverlap=e.chunkOverlap??200,this.separators=e.separators??Rt}split(e){return this._splitRecursive(e,this.separators).map((r,s)=>({content:r,index:s}))}_splitRecursive(e,t){if(e.length<=this.chunkSize)return[e];let r=t[0]??"",s=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&&s.length>0){let c=this._splitRecursive(a,s);a=c.pop()??"",i.push(...c)}}else a=p}return a&&i.push(a),i}};function Et(n,e){return new T(e).split(n)}import{readFile as Re}from"fs/promises";import{basename as Ee}from"path";async function Ae(n,e={}){let t=!n.includes(`
8
- `)&&n.length<500,r,s;if(t)try{r=await Re(n,"utf-8"),s=e.documentId??Ee(n)}catch{r=n,s=e.documentId??"text-document"}else r=n,s=e.documentId??"text-document";let a=new T(e).split(r).map(d=>({id:`${s}-${d.index}`,documentId:s,content:d.content,index:d.index,metadata:{...e.metadata,...d.metadata}}));return{documentId:s,content:r,chunks:a,metadata:e.metadata??{}}}async function At(n,e={}){let t=await Ae(n,{...e,separators:[`
7
+ `,". "," ",""],x=class{chunkSize;chunkOverlap;separators;constructor(e={}){this.chunkSize=e.chunkSize??1e3,this.chunkOverlap=e.chunkOverlap??200,this.separators=e.separators??Rt}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 l of o){let p=a?a+r+l:l;if(p.length>this.chunkSize&&a){i.push(a);let d=Math.max(0,a.length-this.chunkOverlap);if(a=a.slice(d)+r+l,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 Et(s,e){return new x(e).split(s)}import{readFile as Re}from"fs/promises";import{basename as Ee}from"path";async function Ae(s,e={}){let t=!s.includes(`
8
+ `)&&s.length<500,r,n;if(t)try{r=await Re(s,"utf-8"),n=e.documentId??Ee(s)}catch{r=s,n=e.documentId??"text-document"}else r=s,n=e.documentId??"text-document";let a=new x(e).split(r).map(l=>({id:`${n}-${l.index}`,documentId:n,content:l.content,index:l.index,metadata:{...e.metadata,...l.metadata}}));return{documentId:n,content:r,chunks:a,metadata:e.metadata??{}}}async function At(s,e={}){let t=await Ae(s,{...e,separators:[`
9
9
  ## `,`
10
10
  ### `,`
11
11
 
12
12
  `,`
13
- `,". "," "]});return t.content=t.content.replace(/^---[\s\S]*?---\n?/,""),t}async function Dt(n,e={}){let t,r;if(!n.includes(`
14
- `)&&n.length<500)try{t=await Re(n,"utf-8"),r=e.documentId??Ee(n)}catch{t=n,r=e.documentId??"json-document"}else t=n,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??{}}}import{create_graph as Mt,graph_add_node as Ot,graph_add_edge as Nt,graph_add_fork_node as It,graph_run as Ht,destroy_graph as jt}from"gauss-napi";var B=class n{static pipeline(e){let t=new n;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=Mt()}get handle(){return this._handle}addNode(e){return this.assertNotDisposed(),Ot(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(),It(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(),Nt(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?Ht(this._handle,e):this._runWithConditionals(e)}destroy(){if(!this.disposed){this.disposed=!0;try{jt(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 h("Graph has no entry node (every node has an incoming edge)");let s={},o=r[0],i=e;for(;o;){let p=this._nodes.get(o);if(!p)throw new h(`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 Dt(s,e={}){let t,r;if(!s.includes(`
14
+ `)&&s.length<500)try{t=await Re(s,"utf-8"),r=e.documentId??Ee(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((l,p)=>{let d=e.textField?String(l[e.textField]??""):JSON.stringify(l);i.push({key:String(p),text:d})});else if(typeof o=="object"&&o!==null)for(let[l,p]of Object.entries(o)){let d=typeof p=="string"?p:JSON.stringify(p);i.push({key:l,text:d})}let a=i.map((l,p)=>({id:`${r}-${l.key}`,documentId:r,content:l.text,index:p,metadata:{...e.metadata,key:l.key}}));return{documentId:r,content:t,chunks:a,metadata:e.metadata??{}}}import{create_graph as Ot,graph_add_node as Mt,graph_add_edge as Nt,graph_add_fork_node as It,graph_run as Ht,destroy_graph as jt}from"gauss-napi";var B=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=Ot()}get handle(){return this._handle}addNode(e){return this.assertNotDisposed(),Mt(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(),It(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(),Nt(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?Ht(this._handle,e):this._runWithConditionals(e)}destroy(){if(!this.disposed){this.disposed=!0;try{jt(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 m("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 m(`Node "${o}" not found in graph`);let d=p.instructions?`${p.instructions}
15
15
 
16
- ${i}`:i,c=await p.agent.run(l),u={text:c.text,...c.structuredOutput?{structuredOutput:c.structuredOutput}:{}};s[o]=u;let m=this._conditionalEdges.get(o);m?o=await m(u):o=this._edges.get(o),i=c.text}let a=Object.keys(s),d=a[a.length-1];return{outputs:s,final_text:s[d]?.text??""}}assertNotDisposed(){if(this.disposed)throw new y("Graph","graph")}};import{create_workflow as Ut,workflow_add_step as Lt,workflow_add_dependency as Gt,workflow_run as Jt,destroy_workflow as $t}from"gauss-napi";var z=class{_handle;disposed=!1;constructor(){this._handle=Ut()}get handle(){return this._handle}addStep(e){return this.assertNotDisposed(),Lt(this._handle,e.stepId,e.agent.name,e.agent.handle,e.instructions,e.tools??[]),this}addDependency(e,t){return this.assertNotDisposed(),Gt(this._handle,e,t),this}async run(e){return this.assertNotDisposed(),Jt(this._handle,e)}destroy(){if(!this.disposed){this.disposed=!0;try{$t(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Workflow has been destroyed")}};import{create_team as Ft,team_add_agent as qt,team_set_strategy as Bt,team_run as zt,destroy_team as Kt}from"gauss-napi";var K=class n{_handle;_name;disposed=!1;agents=[];static quick(e,t,r){let s=new n(e);for(let o of r){let i=new g({name:o.name,provider:o.provider??"openai",model:o.model??"gpt-4o",instructions:o.instructions});s.add(i)}return s.strategy(t),s}constructor(e){this._name=e,this._handle=Ft(e)}get handle(){return this._handle}add(e,t){return this.assertNotDisposed(),qt(this._handle,e.name,e.handle,t),this.agents.push(e),this}strategy(e){return this.assertNotDisposed(),Bt(this._handle,e),this}async run(e){this.assertNotDisposed();let t=JSON.stringify([{role:"user",content:[{type:"text",text:e}]}]);return zt(this._handle,t)}destroy(){if(!this.disposed){this.disposed=!0;try{Kt(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new y("Team",this._name)}};import{create_network as Vt,network_add_agent as Wt,network_set_supervisor as Yt,network_delegate as De,network_agent_cards as Xt,destroy_network as Qt}from"gauss-napi";var V=class n{_handle;disposed=!1;supervisorName=null;static quick(e,t){let r=new n;for(let s of t){let o=new g({name:s.name,provider:s.provider??"openai",model:s.model??"gpt-4o",instructions:s.instructions});r.addAgent(o,s.instructions)}return r.setSupervisor(e),r}static template(e){return e==="research-delivery"?{supervisor:"lead",agents:[{name:"lead",instructions:"Coordinate and delegate work."},{name:"researcher",instructions:"Research context and constraints."},{name:"implementer",instructions:"Implement practical solutions."}]}:e==="incident-response"?{supervisor:"incident-commander",agents:[{name:"incident-commander",instructions:"Drive response and coordination."},{name:"triage",instructions:"Assess impact and prioritize mitigation."},{name:"remediator",instructions:"Propose and execute remediation steps."}]}:e==="support-triage"?{supervisor:"support-lead",agents:[{name:"support-lead",instructions:"Coordinate support workload and escalations."},{name:"triage-bot",instructions:"Classify incoming support requests."},{name:"resolver",instructions:"Draft and validate customer resolutions."}]}:e==="fintech-risk-review"?{supervisor:"risk-lead",agents:[{name:"risk-lead",instructions:"Approve risk recommendations and report rationale."},{name:"policy-analyst",instructions:"Map events to compliance policy obligations."},{name:"fraud-scorer",instructions:"Score suspicious patterns and flag anomalies."}]}:{supervisor:"rag-ops-lead",agents:[{name:"rag-ops-lead",instructions:"Coordinate retrieval quality and index freshness."},{name:"retrieval-auditor",instructions:"Audit recall/precision and retrieval grounding."},{name:"index-maintainer",instructions:"Propose chunking and indexing improvements."}]}}static fromTemplate(e){let t=n.template(e);return n.quick(t.supervisor,t.agents)}constructor(){this._handle=Vt()}get handle(){return this._handle}addAgent(e,t){this.assertNotDisposed();let r=typeof t=="string"?t:t?.instructions;return Wt(this._handle,e.name,e.handle,r),this}setSupervisor(e){return this.assertNotDisposed(),this.supervisorName=e,Yt(this._handle,e),this}async delegate(e,t,r){this.assertNotDisposed();let s=r===void 0?e:t,o=r===void 0?t:r;return De(this._handle,s,o)}async delegateWithSupervisor(e){if(this.assertNotDisposed(),!this.supervisorName)throw new Error("Network supervisor is not set. Call setSupervisor() first.");return De(this._handle,this.supervisorName,e)}agentCards(){return this.assertNotDisposed(),Xt(this._handle)}destroy(){this.disposed||(this.disposed=!0,Qt(this._handle))}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new y("Network","network")}};import{create_middleware_chain as Zt,middleware_use_logging as er,middleware_use_caching as tr,middleware_use_rate_limit as rr,destroy_middleware_chain as nr}from"gauss-napi";var W=class{_handle;disposed=!1;constructor(){this._handle=Zt()}get handle(){return this._handle}useLogging(){return this.assertNotDisposed(),er(this._handle),this}useCaching(e){return this.assertNotDisposed(),tr(this._handle,e),this}useRateLimit(e,t){return this.assertNotDisposed(),rr(this._handle,e,t),this}destroy(){if(!this.disposed){this.disposed=!0;try{nr(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("MiddlewareChain has been destroyed")}};import{create_plugin_registry as sr,plugin_registry_add_telemetry as or,plugin_registry_add_memory as ir,plugin_registry_list as ar,plugin_registry_emit as dr,destroy_plugin_registry as pr}from"gauss-napi";var Y=class{_handle;disposed=!1;constructor(){this._handle=sr()}get handle(){return this._handle}addTelemetry(){return this.assertNotDisposed(),or(this._handle),this}addMemory(){return this.assertNotDisposed(),ir(this._handle),this}list(){return this.assertNotDisposed(),ar(this._handle)}emit(e){this.assertNotDisposed(),dr(this._handle,JSON.stringify(e))}destroy(){if(!this.disposed){this.disposed=!0;try{pr(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("PluginRegistry has been destroyed")}};import{create_mcp_server as lr,mcp_server_add_tool as cr,mcpServerAddResource as ur,mcpServerAddPrompt as mr,mcp_server_handle as hr,destroy_mcp_server as gr}from"gauss-napi";var X=class{_handle;disposed=!1;constructor(e,t){this._handle=lr(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 cr(this._handle,JSON.stringify(t)),this}addResource(e){return this.assertNotDisposed(),ur(this._handle,JSON.stringify(e)),this}addPrompt(e){return this.assertNotDisposed(),mr(this._handle,JSON.stringify(e)),this}async handleMessage(e){return this.assertNotDisposed(),hr(this._handle,JSON.stringify(e))}destroy(){if(!this.disposed){this.disposed=!0;try{gr(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("McpServer has been destroyed")}};import{spawn as yr}from"child_process";var Q=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=yr(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 s;try{s=JSON.parse(r)}catch{return JSON.stringify({error:"Invalid tool call JSON"})}let o=s.tool??s.name??"",i=s.args??s.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 s=this.nextId++,o={jsonrpc:"2.0",id:s,method:e,params:t};return new Promise((i,a)=>{let d=setTimeout(()=>{this.pending.delete(s),a(new Error(`MCP request "${e}" timed out after ${r}ms`))},r);this.pending.set(s,{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 p.agent.run(d),h={text:c.text,...c.structuredOutput?{structuredOutput:c.structuredOutput}:{}};n[o]=h;let u=this._conditionalEdges.get(o);u?o=await u(h):o=this._edges.get(o),i=c.text}let a=Object.keys(n),l=a[a.length-1];return{outputs:n,final_text:n[l]?.text??""}}assertNotDisposed(){if(this.disposed)throw new y("Graph","graph")}};import{create_workflow as Ut,workflow_add_step as Lt,workflow_add_dependency as Jt,workflow_run as Gt,destroy_workflow as $t}from"gauss-napi";var z=class{_handle;disposed=!1;constructor(){this._handle=Ut()}get handle(){return this._handle}addStep(e){return this.assertNotDisposed(),Lt(this._handle,e.stepId,e.agent.name,e.agent.handle,e.instructions,e.tools??[]),this}addDependency(e,t){return this.assertNotDisposed(),Jt(this._handle,e,t),this}async run(e){return this.assertNotDisposed(),Gt(this._handle,e)}destroy(){if(!this.disposed){this.disposed=!0;try{$t(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Workflow has been destroyed")}};import{create_team as Ft,team_add_agent as qt,team_set_strategy as Bt,team_run as zt,destroy_team as Kt}from"gauss-napi";var K=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 g({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=Ft(e)}get handle(){return this._handle}add(e,t){return this.assertNotDisposed(),qt(this._handle,e.name,e.handle,t),this.agents.push(e),this}strategy(e){return this.assertNotDisposed(),Bt(this._handle,e),this}async run(e){this.assertNotDisposed();let t=JSON.stringify([{role:"user",content:[{type:"text",text:e}]}]);return zt(this._handle,t)}destroy(){if(!this.disposed){this.disposed=!0;try{Kt(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new y("Team",this._name)}};import{create_network as Vt,network_add_agent as Wt,network_set_supervisor as Yt,network_delegate as De,network_agent_cards as Xt,destroy_network as Qt}from"gauss-napi";var V=class s{_handle;disposed=!1;supervisorName=null;static quick(e,t){let r=new s;for(let n of t){let o=new g({name:n.name,provider:n.provider??"openai",model:n.model??"gpt-4o",instructions:n.instructions});r.addAgent(o,n.instructions)}return r.setSupervisor(e),r}static template(e){return e==="research-delivery"?{supervisor:"lead",agents:[{name:"lead",instructions:"Coordinate and delegate work."},{name:"researcher",instructions:"Research context and constraints."},{name:"implementer",instructions:"Implement practical solutions."}]}:e==="incident-response"?{supervisor:"incident-commander",agents:[{name:"incident-commander",instructions:"Drive response and coordination."},{name:"triage",instructions:"Assess impact and prioritize mitigation."},{name:"remediator",instructions:"Propose and execute remediation steps."}]}:e==="support-triage"?{supervisor:"support-lead",agents:[{name:"support-lead",instructions:"Coordinate support workload and escalations."},{name:"triage-bot",instructions:"Classify incoming support requests."},{name:"resolver",instructions:"Draft and validate customer resolutions."}]}:e==="fintech-risk-review"?{supervisor:"risk-lead",agents:[{name:"risk-lead",instructions:"Approve risk recommendations and report rationale."},{name:"policy-analyst",instructions:"Map events to compliance policy obligations."},{name:"fraud-scorer",instructions:"Score suspicious patterns and flag anomalies."}]}:{supervisor:"rag-ops-lead",agents:[{name:"rag-ops-lead",instructions:"Coordinate retrieval quality and index freshness."},{name:"retrieval-auditor",instructions:"Audit recall/precision and retrieval grounding."},{name:"index-maintainer",instructions:"Propose chunking and indexing improvements."}]}}static fromTemplate(e){let t=s.template(e);return s.quick(t.supervisor,t.agents)}constructor(){this._handle=Vt()}get handle(){return this._handle}addAgent(e,t){this.assertNotDisposed();let r=typeof t=="string"?t:t?.instructions;return Wt(this._handle,e.name,e.handle,r),this}setSupervisor(e){return this.assertNotDisposed(),this.supervisorName=e,Yt(this._handle,e),this}async delegate(e,t,r){this.assertNotDisposed();let n=r===void 0?e:t,o=r===void 0?t:r;return De(this._handle,n,o)}async delegateWithSupervisor(e){if(this.assertNotDisposed(),!this.supervisorName)throw new Error("Network supervisor is not set. Call setSupervisor() first.");return De(this._handle,this.supervisorName,e)}agentCards(){return this.assertNotDisposed(),Xt(this._handle)}destroy(){this.disposed||(this.disposed=!0,Qt(this._handle))}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new y("Network","network")}};import{create_middleware_chain as Zt,middleware_use_logging as er,middleware_use_caching as tr,middleware_use_rate_limit as rr,destroy_middleware_chain as nr}from"gauss-napi";var W=class{_handle;disposed=!1;constructor(){this._handle=Zt()}get handle(){return this._handle}useLogging(){return this.assertNotDisposed(),er(this._handle),this}useCaching(e){return this.assertNotDisposed(),tr(this._handle,e),this}useRateLimit(e,t){return this.assertNotDisposed(),rr(this._handle,e,t),this}destroy(){if(!this.disposed){this.disposed=!0;try{nr(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("MiddlewareChain has been destroyed")}};import{create_plugin_registry as sr,plugin_registry_add_telemetry as or,plugin_registry_add_memory as ir,plugin_registry_list as ar,plugin_registry_emit as lr,destroy_plugin_registry as pr}from"gauss-napi";var Y=class{_handle;disposed=!1;constructor(){this._handle=sr()}get handle(){return this._handle}addTelemetry(){return this.assertNotDisposed(),or(this._handle),this}addMemory(){return this.assertNotDisposed(),ir(this._handle),this}list(){return this.assertNotDisposed(),ar(this._handle)}emit(e){this.assertNotDisposed(),lr(this._handle,JSON.stringify(e))}destroy(){if(!this.disposed){this.disposed=!0;try{pr(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("PluginRegistry has been destroyed")}};import{create_mcp_server as dr,mcp_server_add_tool as cr,mcpServerAddResource as ur,mcpServerAddPrompt as mr,mcp_server_handle as hr,destroy_mcp_server as gr}from"gauss-napi";var X=class{_handle;disposed=!1;constructor(e,t){this._handle=dr(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 cr(this._handle,JSON.stringify(t)),this}addResource(e){return this.assertNotDisposed(),ur(this._handle,JSON.stringify(e)),this}addPrompt(e){return this.assertNotDisposed(),mr(this._handle,JSON.stringify(e)),this}async handleMessage(e){return this.assertNotDisposed(),hr(this._handle,JSON.stringify(e))}destroy(){if(!this.disposed){this.disposed=!0;try{gr(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("McpServer has been destroyed")}};import{spawn as yr}from"child_process";var Q=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=yr(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(d=>d.text).filter(Boolean).join(`
17
+ `)??"Tool error";return JSON.stringify({error:p})}let l=a.content?.map(p=>p.text).filter(Boolean).join(`
18
+ `)??"";return JSON.stringify({result:l})}catch(a){let l=a instanceof Error?a.message:String(a);return JSON.stringify({error:l})}}}}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 l=setTimeout(()=>{this.pending.delete(n),a(new Error(`MCP request "${e}" timed out after ${r}ms`))},r);this.pending.set(n,{resolve:p=>{clearTimeout(l),i(p)},reject:p=>{clearTimeout(l),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+`
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 s=JSON.parse(r);if(s.id!==void 0&&this.pending.has(s.id)){let{resolve:o,reject:i}=this.pending.get(s.id);this.pending.delete(s.id),s.error?i(new Error(`MCP error ${s.error.code}: ${s.error.message}`)):o(s.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.")}};import{create_guardrail_chain as fr,guardrail_chain_add_content_moderation as vr,guardrail_chain_add_pii_detection as xr,guardrail_chain_add_token_limit as Tr,guardrail_chain_add_regex_filter as _r,guardrail_chain_add_schema as kr,guardrail_chain_list as br,destroy_guardrail_chain as wr}from"gauss-napi";var Z=class{_handle;disposed=!1;constructor(){this._handle=fr()}get handle(){return this._handle}addContentModeration(e,t=[]){return this.assertNotDisposed(),vr(this._handle,e,t),this}addPiiDetection(e){return this.assertNotDisposed(),xr(this._handle,e),this}addTokenLimit(e,t){return this.assertNotDisposed(),Tr(this._handle,e,t),this}addRegexFilter(e,t=[]){return this.assertNotDisposed(),_r(this._handle,e,t),this}addSchema(e){return this.assertNotDisposed(),kr(this._handle,JSON.stringify(e)),this}list(){return this.assertNotDisposed(),br(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{wr(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("GuardrailChain has been destroyed")}};import{create_approval_manager as Pr,approval_request as Cr,approval_approve as Sr,approval_deny as Rr,approval_list_pending as Er,destroy_approval_manager as Ar}from"gauss-napi";var ee=class{_handle;disposed=!1;constructor(){this._handle=Pr()}get handle(){return this._handle}request(e,t,r){return this.assertNotDisposed(),Cr(this._handle,e,JSON.stringify(t),r)}approve(e,t){this.assertNotDisposed(),Sr(this._handle,e,t?JSON.stringify(t):void 0)}deny(e,t){this.assertNotDisposed(),Rr(this._handle,e,t)}listPending(){return this.assertNotDisposed(),Er(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{Ar(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("ApprovalManager has been destroyed")}};import{create_checkpoint_store as Dr,checkpoint_save as Mr,checkpoint_load as Or,checkpoint_load_latest as Nr,destroy_checkpoint_store as Ir}from"gauss-napi";var te=class{_handle;disposed=!1;constructor(){this._handle=Dr()}get handle(){return this._handle}async save(e){return this.assertNotDisposed(),Mr(this._handle,JSON.stringify(e))}async load(e){return this.assertNotDisposed(),Or(this._handle,e)}async loadLatest(e){return this.assertNotDisposed(),Nr(this._handle,e)}destroy(){if(!this.disposed){this.disposed=!0;try{Ir(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("CheckpointStore has been destroyed")}};import{create_eval_runner as Hr,eval_add_scorer as jr,load_dataset_jsonl as Ur,load_dataset_json as Lr,destroy_eval_runner as Gr}from"gauss-napi";var re=class{_handle;disposed=!1;constructor(e){this._handle=Hr(e)}get handle(){return this._handle}addScorer(e){return this.assertNotDisposed(),jr(this._handle,e),this}destroy(){if(!this.disposed){this.disposed=!0;try{Gr(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("EvalRunner has been destroyed")}static loadDatasetJsonl(e){return Ur(e)}static loadDatasetJson(e){return Lr(e)}};import{create_telemetry as Jr,telemetry_record_span as $r,telemetry_export_spans as Fr,telemetry_export_metrics as qr,telemetry_clear as Br,destroy_telemetry as zr}from"gauss-napi";var ne=class{_handle;disposed=!1;constructor(){this._handle=Jr()}get handle(){return this._handle}recordSpan(e,t,r){this.assertNotDisposed();let s=typeof e=="string"?{name:e,span_type:"custom",start_ms:Date.now()-(t??0),duration_ms:t??0,attributes:r??{},status:"ok",children:[]}:e;$r(this._handle,JSON.stringify(s))}exportSpans(){return this.assertNotDisposed(),Fr(this._handle)}exportMetrics(){return this.assertNotDisposed(),qr(this._handle)}clear(){this.assertNotDisposed(),Br(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{zr(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Telemetry has been destroyed")}};import{appendFileSync as on,mkdirSync as an}from"fs";import{createServer as dn}from"http";import{dirname as pn}from"path";import{count_tokens as Kr,count_tokens_for_model as Vr,count_message_tokens as Wr,get_context_window_size as Yr,estimate_cost as Xr}from"gauss-napi";var M=new Map;function Qr(n,e){M.set(n,e)}function Zr(n){return M.get(n)}function en(){M.clear()}function tn(n){return Kr(n)}function rn(n,e){return Vr(n,e)}function nn(n){return Wr(n)}function sn(n){return Yr(n)}function se(n,e){let t=M.get(n);if(t){let s=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:n,normalizedModel:n,currency:"USD",inputTokens:e.inputTokens,outputTokens:e.outputTokens,reasoningTokens:e.reasoningTokens??0,cacheReadTokens:e.cacheReadTokens??0,cacheCreationTokens:e.cacheCreationTokens??0,inputCostUsd:s,outputCostUsd:o,reasoningCostUsd:i,cacheReadCostUsd:a,cacheCreationCostUsd:d,totalCostUsd:s+o+i+a+d}}let r=Xr(n,e.inputTokens,e.outputTokens,e.reasoningTokens,e.cacheReadTokens,e.cacheCreationTokens);return{model:String(r.model??n),normalizedModel:String(r.normalized_model??n),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 x=class extends Error{},ln=["openai","anthropic","google","groq","ollama","deepseek","openrouter","together","fireworks","mistral","perplexity","xai"],oe=class{telemetry;approvals;model;routingPolicy;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.routingPolicy=e.routingPolicy,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}withRoutingPolicy(e){return this.routingPolicy=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=se(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 s=r.spans.map((i,a)=>({id:String(a),label:this.spanLabel(i,a)})),o=s.slice(1).map((i,a)=>({from:String(a),to:i.id}));return{nodes:s,edges:o}}async startServer(e="127.0.0.1",t=4200){if(this.server){let s=this.server.address();return s&&typeof s!="string"?{url:`http://${e}:${s.port}`}:{url:`http://${e}:${t}`}}this.server=dn((s,o)=>{if(!s.url){o.statusCode=400,o.end("Bad request");return}let i=new URL(s.url,`http://${s.headers.host??`${e}:${t}`}`),a=i.pathname;if(a.startsWith("/api/")&&!this.isAuthorized(s,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==="/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/ops/summary"){let d=this.applyAuthClaims(this.parseContextFilters(i.searchParams));o.setHeader("Content-Type","application/json; charset=utf-8"),o.end(JSON.stringify(this.opsSummary(d),null,2));return}if(a==="/api/ops/tenants"){let d=this.applyAuthClaims(this.parseContextFilters(i.searchParams));o.setHeader("Content-Type","application/json; charset=utf-8"),o.end(JSON.stringify(this.opsTenants(d),null,2));return}if(a==="/api/ops/policy/explain"){o.setHeader("Content-Type","application/json; charset=utf-8"),o.end(JSON.stringify(this.opsPolicyExplain(i.searchParams),null,2));return}if(a==="/api/stream"){let d=this.applyAuthClaims(this.parseContextFilters(i.searchParams)),p=this.parseStreamChannels(i.searchParams);for(let je of p)this.assertChannelAllowed(je);let l=i.searchParams.get("once")==="1",c=this.parseLastEventId(s,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 u=this.replayStreamEvents(o,p,d,c);if(l&&u>0){o.end();return}if(this.emitStreamBatch(o,p,d),l){o.end();return}let m=setInterval(()=>{o.writableEnded||o.destroyed||this.emitStreamBatch(o,p,d)},1e3),f=()=>clearInterval(m);s.on("close",f),s.on("aborted",f);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}if(a==="/ops/tenants"){o.setHeader("Content-Type","text/html; charset=utf-8"),o.end(this.renderHostedTenantOpsHtml());return}o.statusCode=404,o.end("Not found")}catch(d){if(d instanceof x){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((s,o)=>{this.server.once("error",o),this.server.listen(t,e,()=>s())});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(s=>s?r(s):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&&(an(pn(this.persistPath),{recursive:!0}),on(this.persistPath,`${JSON.stringify(e)}
21
- `,"utf8")),e}parseSection(e){if(e==="spans"||e==="metrics"||e==="pendingApprovals"||e==="latestCost")return e;throw new h(`Unknown section "${e}"`,"section")}parseStreamChannel(e){if(e===null||e==="snapshot")return"snapshot";if(e==="timeline"||e==="dag")return e;throw new h(`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(s=>s.trim()).filter(s=>s.length>0).map(s=>this.parseStreamChannel(s));return r.length===0?["snapshot"]:[...new Set(r)]}parseLastEventId(e,t){let r=t.get("lastEventId"),s=e.headers["last-event-id"],o=r??(typeof s=="string"?s:null);if(o===null)return null;let i=Number.parseInt(o,10);if(!Number.isFinite(i)||i<0)throw new h(`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}}parsePolicyProvider(e){if(!ln.includes(e))throw new h(`Unknown provider "${e}"`,"provider");return e}parsePolicyExplainOptions(e){let t=this.parsePolicyProvider(e.get("provider")??"openai"),r=e.get("model")??"gpt-5.2",s=(u,m)=>{if(u===null||u.trim().length===0)return;let f=Number(u);if(!Number.isFinite(f))throw new h(`Invalid ${m} "${u}"`,m);return f},o=e.get("available"),i=o?o.split(",").map(u=>u.trim()).filter(u=>u.length>0).map(u=>this.parsePolicyProvider(u)):void 0,a=e.get("tags"),d=a?a.split(",").map(u=>u.trim()).filter(u=>u.length>0):void 0,p=s(e.get("cost"),"cost"),l=s(e.get("rpm"),"rpm"),c=s(e.get("hour"),"hour");return{provider:t,model:r,options:{availableProviders:i,estimatedCostUsd:p,currentRequestsPerMinute:l,currentHourUtc:c,governanceTags:d}}}buildStreamEvent(e,t,r){let s=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:s};return this.streamEvents.push(o),this.streamEvents.length>this.streamReplayLimit&&this.streamEvents.shift(),o}writeSseEvent(e,t){e.write(`id: ${t.id}
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.")}};import{create_guardrail_chain as fr,guardrail_chain_add_content_moderation as vr,guardrail_chain_add_pii_detection as xr,guardrail_chain_add_token_limit as Tr,guardrail_chain_add_regex_filter as kr,guardrail_chain_add_schema as _r,guardrail_chain_list as br,destroy_guardrail_chain as Pr}from"gauss-napi";var Z=class{_handle;disposed=!1;constructor(){this._handle=fr()}get handle(){return this._handle}addContentModeration(e,t=[]){return this.assertNotDisposed(),vr(this._handle,e,t),this}addPiiDetection(e){return this.assertNotDisposed(),xr(this._handle,e),this}addTokenLimit(e,t){return this.assertNotDisposed(),Tr(this._handle,e,t),this}addRegexFilter(e,t=[]){return this.assertNotDisposed(),kr(this._handle,e,t),this}addSchema(e){return this.assertNotDisposed(),_r(this._handle,JSON.stringify(e)),this}list(){return this.assertNotDisposed(),br(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{Pr(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("GuardrailChain has been destroyed")}};import{create_approval_manager as wr,approval_request as Cr,approval_approve as Sr,approval_deny as Rr,approval_list_pending as Er,destroy_approval_manager as Ar}from"gauss-napi";var ee=class{_handle;disposed=!1;constructor(){this._handle=wr()}get handle(){return this._handle}request(e,t,r){return this.assertNotDisposed(),Cr(this._handle,e,JSON.stringify(t),r)}approve(e,t){this.assertNotDisposed(),Sr(this._handle,e,t?JSON.stringify(t):void 0)}deny(e,t){this.assertNotDisposed(),Rr(this._handle,e,t)}listPending(){return this.assertNotDisposed(),Er(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{Ar(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("ApprovalManager has been destroyed")}};import{create_checkpoint_store as Dr,checkpoint_save as Or,checkpoint_load as Mr,checkpoint_load_latest as Nr,destroy_checkpoint_store as Ir}from"gauss-napi";var te=class{_handle;disposed=!1;constructor(){this._handle=Dr()}get handle(){return this._handle}async save(e){return this.assertNotDisposed(),Or(this._handle,JSON.stringify(e))}async load(e){return this.assertNotDisposed(),Mr(this._handle,e)}async loadLatest(e){return this.assertNotDisposed(),Nr(this._handle,e)}destroy(){if(!this.disposed){this.disposed=!0;try{Ir(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("CheckpointStore has been destroyed")}};import{create_eval_runner as Hr,eval_add_scorer as jr,load_dataset_jsonl as Ur,load_dataset_json as Lr,destroy_eval_runner as Jr}from"gauss-napi";var re=class{_handle;disposed=!1;constructor(e){this._handle=Hr(e)}get handle(){return this._handle}addScorer(e){return this.assertNotDisposed(),jr(this._handle,e),this}destroy(){if(!this.disposed){this.disposed=!0;try{Jr(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("EvalRunner has been destroyed")}static loadDatasetJsonl(e){return Ur(e)}static loadDatasetJson(e){return Lr(e)}};import{create_telemetry as Gr,telemetry_record_span as $r,telemetry_export_spans as Fr,telemetry_export_metrics as qr,telemetry_clear as Br,destroy_telemetry as zr}from"gauss-napi";var ne=class{_handle;disposed=!1;constructor(){this._handle=Gr()}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;$r(this._handle,JSON.stringify(n))}exportSpans(){return this.assertNotDisposed(),Fr(this._handle)}exportMetrics(){return this.assertNotDisposed(),qr(this._handle)}clear(){this.assertNotDisposed(),Br(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{zr(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Telemetry has been destroyed")}};import{appendFileSync as on,mkdirSync as an}from"fs";import{createServer as ln}from"http";import{dirname as pn}from"path";import{count_tokens as Kr,count_tokens_for_model as Vr,count_message_tokens as Wr,get_context_window_size as Yr,estimate_cost as Xr}from"gauss-napi";var M=new Map;function Qr(s,e){M.set(s,e)}function Zr(s){return M.get(s)}function en(){M.clear()}function tn(s){return Kr(s)}function rn(s,e){return Vr(s,e)}function nn(s){return Wr(s)}function sn(s){return Yr(s)}function se(s,e){let t=M.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),l=(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:l,totalCostUsd:n+o+i+a+l}}let r=Xr(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 v=class extends Error{},dn=["openai","anthropic","google","groq","ollama","deepseek","openrouter","together","fireworks","mistral","perplexity","xai"],oe=class{telemetry;approvals;model;routingPolicy;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.routingPolicy=e.routingPolicy,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}withRoutingPolicy(e){return this.routingPolicy=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=se(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=ln((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 l=i.searchParams.get("section"),p=l?this.snapshot(this.parseSection(l)):this.snapshot();o.setHeader("Content-Type","application/json; charset=utf-8"),o.end(JSON.stringify(p,null,2));return}if(a==="/api/history"){let l=this.applyAuthClaims(this.parseContextFilters(i.searchParams));o.setHeader("Content-Type","application/json; charset=utf-8"),o.end(JSON.stringify(this.getHistory(l),null,2));return}if(a==="/api/timeline"){let l=this.applyAuthClaims(this.parseContextFilters(i.searchParams));o.setHeader("Content-Type","application/json; charset=utf-8"),o.end(JSON.stringify(this.getTimeline(l),null,2));return}if(a==="/api/dag"){let l=this.applyAuthClaims(this.parseContextFilters(i.searchParams));o.setHeader("Content-Type","application/json; charset=utf-8"),o.end(JSON.stringify(this.getDag(l),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/ops/summary"){let l=this.applyAuthClaims(this.parseContextFilters(i.searchParams));o.setHeader("Content-Type","application/json; charset=utf-8"),o.end(JSON.stringify(this.opsSummary(l),null,2));return}if(a==="/api/ops/tenants"){let l=this.applyAuthClaims(this.parseContextFilters(i.searchParams));o.setHeader("Content-Type","application/json; charset=utf-8"),o.end(JSON.stringify(this.opsTenants(l),null,2));return}if(a==="/api/ops/policy/explain"){o.setHeader("Content-Type","application/json; charset=utf-8"),o.end(JSON.stringify(this.opsPolicyExplain(i.searchParams),null,2));return}if(a==="/api/ops/policy/explain/batch"){o.setHeader("Content-Type","application/json; charset=utf-8"),o.end(JSON.stringify(this.opsPolicyExplainBatch(i.searchParams),null,2));return}if(a==="/api/ops/policy/explain/simulate"){o.setHeader("Content-Type","application/json; charset=utf-8"),o.end(JSON.stringify(this.opsPolicyExplainSimulation(i.searchParams),null,2));return}if(a==="/api/stream"){let l=this.applyAuthClaims(this.parseContextFilters(i.searchParams)),p=this.parseStreamChannels(i.searchParams);for(let je of p)this.assertChannelAllowed(je);let d=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 h=this.replayStreamEvents(o,p,l,c);if(d&&h>0){o.end();return}if(this.emitStreamBatch(o,p,l),d){o.end();return}let u=setInterval(()=>{o.writableEnded||o.destroyed||this.emitStreamBatch(o,p,l)},1e3),E=()=>clearInterval(u);n.on("close",E),n.on("aborted",E);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}if(a==="/ops/tenants"){o.setHeader("Content-Type","text/html; charset=utf-8"),o.end(this.renderHostedTenantOpsHtml());return}o.statusCode=404,o.end("Not found")}catch(l){if(l instanceof v){o.statusCode=403,o.setHeader("Content-Type","application/json; charset=utf-8"),o.end(JSON.stringify({error:l.message}));return}let p=l instanceof Error?l.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&&(an(pn(this.persistPath),{recursive:!0}),on(this.persistPath,`${JSON.stringify(e)}
21
+ `,"utf8")),e}parseSection(e){if(e==="spans"||e==="metrics"||e==="pendingApprovals"||e==="latestCost")return e;throw new m(`Unknown section "${e}"`,"section")}parseStreamChannel(e){if(e===null||e==="snapshot")return"snapshot";if(e==="timeline"||e==="dag")return e;throw new m(`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 m(`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}}parsePolicyProvider(e){if(!dn.includes(e))throw new m(`Unknown provider "${e}"`,"provider");return e}parseOptionalNumber(e,t){if(e===null||e.trim().length===0)return;let r=Number(e);if(!Number.isFinite(r))throw new m(`Invalid ${t} "${e}"`,t);return r}parsePolicyExplainScenario(e){let t=this.parsePolicyProvider(typeof e.provider=="string"&&e.provider.trim().length>0?e.provider:"openai"),r=typeof e.model=="string"&&e.model.trim().length>0?e.model:"gpt-5.2",n=Array.isArray(e.available)?e.available:typeof e.available=="string"?e.available.split(","):[],o=n.length>0?n.map(c=>String(c).trim()).filter(c=>c.length>0).map(c=>this.parsePolicyProvider(c)):void 0,i=Array.isArray(e.tags)?e.tags:typeof e.tags=="string"?e.tags.split(","):[],a=i.length>0?i.map(c=>String(c).trim()).filter(c=>c.length>0):void 0,l=this.parseOptionalNumber(e.cost!==void 0&&e.cost!==null?String(e.cost):null,"cost"),p=this.parseOptionalNumber(e.rpm!==void 0&&e.rpm!==null?String(e.rpm):null,"rpm"),d=this.parseOptionalNumber(e.hour!==void 0&&e.hour!==null?String(e.hour):null,"hour");return{provider:t,model:r,options:{availableProviders:o,estimatedCostUsd:l,currentRequestsPerMinute:p,currentHourUtc:d,governanceTags:a}}}parsePolicyExplainOptions(e){return this.parsePolicyExplainScenario({provider:e.get("provider"),model:e.get("model"),available:e.get("available"),cost:e.get("cost"),rpm:e.get("rpm"),hour:e.get("hour"),tags:e.get("tags")})}parsePolicyExplainBatchScenarios(e){let t=e.get("scenarios");if(!t)throw new m("Missing scenarios query parameter","scenarios");let r;try{r=JSON.parse(t)}catch{throw new m("Invalid scenarios JSON payload","scenarios")}if(!Array.isArray(r)||r.length===0)throw new m("scenarios must be a non-empty array","scenarios");return r.map((n,o)=>{if(typeof n!="object"||n===null)throw new m(`Scenario ${o} must be an object`,"scenarios");return this.parsePolicyExplainScenario(n)})}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
22
  `),e.write(`event: ${t.event}
23
23
  `),e.write(`data: ${JSON.stringify(t)}
24
24
 
25
- `)}opsCapabilities(){return{sections:["spans","metrics","pendingApprovals","latestCost"],channels:["snapshot","timeline","dag"],supportsMultiplex:!0,supportsReplayCursor:!0,supportsChannelRbac:!0,supportsOpsSummary:!0,supportsOpsTenants:!0,supportsPolicyExplain:!0,hostedDashboardPath:"/ops",hostedTenantDashboardPath:"/ops/tenants",policyExplainPath:"/api/ops/policy/explain"}}opsHealth(){return{status:"ok",generatedAt:new Date().toISOString(),historySize:this.history.length,streamBufferSize:this.streamEvents.length}}opsSummary(e){let t=this.filterHistory(e),r=t[t.length-1],s=r?.spans,o=r?.pendingApprovals,i=e&&(e.tenantId||e.sessionId||e.runId)?this.streamEvents.filter(l=>this.matchesContext(l.context,e)).length:this.streamEvents.length,a=new Set,d=new Set,p=new Set;for(let l of t)l.context.tenantId&&a.add(l.context.tenantId),l.context.sessionId&&d.add(l.context.sessionId),l.context.runId&&p.add(l.context.runId);return{status:"ok",generatedAt:new Date().toISOString(),historySize:t.length,streamBufferSize:i,spansCount:Array.isArray(s)?s.length:0,pendingApprovalsCount:Array.isArray(o)?o.length:0,latestTotalCostUsd:r?.latestCost?.totalCostUsd??0,tenantCount:a.size,sessionCount:d.size,runCount:p.size}}opsTenants(e){let t=this.filterHistory(e),r=new Map;for(let s of t){let o=s.context.tenantId??"_unscoped",i=r.get(o)??{snapshotCount:0,spansCount:0,pendingApprovalsCount:0,latestTotalCostUsd:0,latestGeneratedAt:s.generatedAt,sessions:new Set,runs:new Set};i.snapshotCount+=1,i.spansCount+=Array.isArray(s.spans)?s.spans.length:0,i.pendingApprovalsCount+=Array.isArray(s.pendingApprovals)?s.pendingApprovals.length:0,s.latestCost?.totalCostUsd!==void 0&&(i.latestTotalCostUsd=s.latestCost.totalCostUsd),s.generatedAt>=i.latestGeneratedAt&&(i.latestGeneratedAt=s.generatedAt),s.context.sessionId&&i.sessions.add(s.context.sessionId),s.context.runId&&i.runs.add(s.context.runId),r.set(o,i)}return[...r.entries()].map(([s,o])=>({tenantId:s,snapshotCount:o.snapshotCount,spansCount:o.spansCount,pendingApprovalsCount:o.pendingApprovalsCount,latestTotalCostUsd:o.latestTotalCostUsd,sessionCount:o.sessions.size,runCount:o.runs.size,latestGeneratedAt:o.latestGeneratedAt})).sort((s,o)=>s.tenantId.localeCompare(o.tenantId))}opsPolicyExplain(e){let t=this.parsePolicyExplainOptions(e);return L(this.routingPolicy,t.provider,t.model,t.options)}emitStreamBatch(e,t,r){let s=this.captureSnapshot();for(let o of t)this.writeSseEvent(e,this.buildStreamEvent(o,r,s))}replayStreamEvents(e,t,r,s){if(s===null)return 0;let o=0;for(let i of this.streamEvents)i.id<=s||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 x(`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 x("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 x("Forbidden session scope");!t.sessionId&&r.length===1&&(t.sessionId=r[0]);let s=this.authClaims.allowedRunIds??[];if(t.runId&&s.length>0&&!s.includes(t.runId))throw new x("Forbidden run scope");return!t.runId&&s.length===1&&(t.runId=s[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,s=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 s||i||a}renderDashboardHtml(){return`<!doctype html>
25
+ `)}opsCapabilities(){return{sections:["spans","metrics","pendingApprovals","latestCost"],channels:["snapshot","timeline","dag"],supportsMultiplex:!0,supportsReplayCursor:!0,supportsChannelRbac:!0,supportsOpsSummary:!0,supportsOpsTenants:!0,supportsPolicyExplain:!0,supportsPolicyExplainBatch:!0,hostedDashboardPath:"/ops",hostedTenantDashboardPath:"/ops/tenants",policyExplainPath:"/api/ops/policy/explain",policyExplainBatchPath:"/api/ops/policy/explain/batch",policyExplainSimulatePath:"/api/ops/policy/explain/simulate"}}opsHealth(){return{status:"ok",generatedAt:new Date().toISOString(),historySize:this.history.length,streamBufferSize:this.streamEvents.length}}opsSummary(e){let t=this.filterHistory(e),r=t[t.length-1],n=r?.spans,o=r?.pendingApprovals,i=e&&(e.tenantId||e.sessionId||e.runId)?this.streamEvents.filter(d=>this.matchesContext(d.context,e)).length:this.streamEvents.length,a=new Set,l=new Set,p=new Set;for(let d of t)d.context.tenantId&&a.add(d.context.tenantId),d.context.sessionId&&l.add(d.context.sessionId),d.context.runId&&p.add(d.context.runId);return{status:"ok",generatedAt:new Date().toISOString(),historySize:t.length,streamBufferSize:i,spansCount:Array.isArray(n)?n.length:0,pendingApprovalsCount:Array.isArray(o)?o.length:0,latestTotalCostUsd:r?.latestCost?.totalCostUsd??0,tenantCount:a.size,sessionCount:l.size,runCount:p.size}}opsTenants(e){let t=this.filterHistory(e),r=new Map;for(let n of t){let o=n.context.tenantId??"_unscoped",i=r.get(o)??{snapshotCount:0,spansCount:0,pendingApprovalsCount:0,latestTotalCostUsd:0,latestGeneratedAt:n.generatedAt,sessions:new Set,runs:new Set};i.snapshotCount+=1,i.spansCount+=Array.isArray(n.spans)?n.spans.length:0,i.pendingApprovalsCount+=Array.isArray(n.pendingApprovals)?n.pendingApprovals.length:0,n.latestCost?.totalCostUsd!==void 0&&(i.latestTotalCostUsd=n.latestCost.totalCostUsd),n.generatedAt>=i.latestGeneratedAt&&(i.latestGeneratedAt=n.generatedAt),n.context.sessionId&&i.sessions.add(n.context.sessionId),n.context.runId&&i.runs.add(n.context.runId),r.set(o,i)}return[...r.entries()].map(([n,o])=>({tenantId:n,snapshotCount:o.snapshotCount,spansCount:o.spansCount,pendingApprovalsCount:o.pendingApprovalsCount,latestTotalCostUsd:o.latestTotalCostUsd,sessionCount:o.sessions.size,runCount:o.runs.size,latestGeneratedAt:o.latestGeneratedAt})).sort((n,o)=>n.tenantId.localeCompare(o.tenantId))}opsPolicyExplain(e){let t=this.parsePolicyExplainOptions(e);return D(this.routingPolicy,t.provider,t.model,t.options)}opsPolicyExplainBatch(e){let r=this.parsePolicyExplainBatchScenarios(e).map((o,i)=>({index:i,input:{provider:o.provider,model:o.model},explanation:D(this.routingPolicy,o.provider,o.model,o.options)})),n=r.filter(o=>o.explanation.ok).length;return{ok:!0,total:r.length,passed:n,failed:r.length-n,results:r}}opsPolicyExplainSimulation(e){return this.opsPolicyExplainBatch(e)}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 v(`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 v("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 v("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 v("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>
26
26
  <html lang="en">
27
27
  <head>
28
28
  <meta charset="utf-8" />
@@ -163,24 +163,24 @@ ${i}`:i,c=await p.agent.run(l),u={text:c.text,...c.structuredOutput?{structuredO
163
163
  refresh();
164
164
  </script>
165
165
  </body>
166
- </html>`}};import{create_fallback_provider as cn,create_circuit_breaker as un,create_resilient_provider as mn}from"gauss-napi";function hn(n){return cn(n)}function gn(n,e,t){return un(n,e,t)}function Me(n,e,t){return mn(n,e,t)}function yn(n,e,t=!0){return Me(n.handle,e.map(r=>r.handle),t)}import{agent_config_from_json as fn,agent_config_resolve_env as vn}from"gauss-napi";function xn(n){return fn(n)}function Tn(n){return vn(n)}import{create_tool_validator as _n,tool_validator_validate as kn,destroy_tool_validator as bn}from"gauss-napi";var ie=class{_handle;disposed=!1;constructor(e){this._handle=_n(e)}get handle(){return this._handle}validate(e,t){return this.assertNotDisposed(),JSON.parse(kn(this._handle,JSON.stringify(e),JSON.stringify(t)))}destroy(){if(!this.disposed){this.disposed=!0;try{bn(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("ToolValidator has been destroyed")}};import{parse_partial_json as wn}from"gauss-napi";function Pn(n){return wn(n)}function Cn(n,e){let t;switch(n.backoff){case"fixed":t=n.baseDelayMs;break;case"linear":t=n.baseDelayMs*e;break;case"exponential":t=n.baseDelayMs*Math.pow(2,e-1);break}let r=t*n.jitter;return t+=Math.random()*r*2-r,Math.min(Math.max(0,t),n.maxDelayMs)}function Sn(n){return new Promise(e=>setTimeout(e,n))}async function Oe(n,e){let t=e?.maxRetries??3,r=e?.backoff??"exponential",s=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 n()}catch(c){if(p=c instanceof Error?c:new Error(String(c)),l===t||a&&!a(p,l+1))break;let u=Cn({backoff:r,baseDelayMs:s,maxDelayMs:o,jitter:i},l+1);d?.(p,l+1,u),await Sn(u)}throw p}function Rn(n,e){return t=>Oe(()=>n.run(t),e)}function En(n,e){let t=JSON.stringify(e,null,2);return`${n}
166
+ </html>`}};import{create_fallback_provider as cn,create_circuit_breaker as un,create_resilient_provider as mn}from"gauss-napi";function hn(s){return cn(s)}function gn(s,e,t){return un(s,e,t)}function Oe(s,e,t){return mn(s,e,t)}function yn(s,e,t=!0){return Oe(s.handle,e.map(r=>r.handle),t)}import{agent_config_from_json as fn,agent_config_resolve_env as vn}from"gauss-napi";function xn(s){return fn(s)}function Tn(s){return vn(s)}import{create_tool_validator as kn,tool_validator_validate as _n,destroy_tool_validator as bn}from"gauss-napi";var ie=class{_handle;disposed=!1;constructor(e){this._handle=kn(e)}get handle(){return this._handle}validate(e,t){return this.assertNotDisposed(),JSON.parse(_n(this._handle,JSON.stringify(e),JSON.stringify(t)))}destroy(){if(!this.disposed){this.disposed=!0;try{bn(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("ToolValidator has been destroyed")}};import{parse_partial_json as Pn}from"gauss-napi";function wn(s){return Pn(s)}function Cn(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 Sn(s){return new Promise(e=>setTimeout(e,s))}async function Me(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,l=e?.onRetry,p;for(let d=0;d<=t;d++)try{return await s()}catch(c){if(p=c instanceof Error?c:new Error(String(c)),d===t||a&&!a(p,d+1))break;let h=Cn({backoff:r,baseDelayMs:n,maxDelayMs:o,jitter:i},d+1);l?.(p,d+1,h),await Sn(h)}throw p}function Rn(s,e){return t=>Me(()=>s.run(t),e)}function En(s,e){let t=JSON.stringify(e,null,2);return`${s}
167
167
 
168
168
  Respond ONLY with valid JSON matching this schema:
169
169
  ${t}
170
170
 
171
- Do not include any text outside the JSON object.`}function An(n){let e=n.match(/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/);if(e)return e[1].trim();let t=n.indexOf("{"),r=n.indexOf("[");if(t===-1&&r===-1)return n.trim();let s=t===-1?r:r===-1?t:Math.min(t,r),i=n[s]==="["?"]":"}",a=0,d=!1,p=!1;for(let l=s;l<n.length;l++){let c=n[l];if(p){p=!1;continue}if(c==="\\"){p=!0;continue}if(c==='"'){d=!d;continue}if(!d&&(c===n[s]&&a++,c===i&&(a--,a===0)))return n.slice(s,l+1)}return n.slice(s)}async function Dn(n,e,t){let r=t.maxParseRetries??2,s=typeof e=="string"?En(e,t.schema):e,o;for(let i=0;i<=r;i++){let a=i===0?s:typeof s=="string"?`${s}
171
+ Do not include any text outside the JSON object.`}function An(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,l=!1,p=!1;for(let d=n;d<s.length;d++){let c=s[d];if(p){p=!1;continue}if(c==="\\"){p=!0;continue}if(c==='"'){l=!l;continue}if(!l&&(c===s[n]&&a++,c===i&&(a--,a===0)))return s.slice(n,d+1)}return s.slice(n)}async function Dn(s,e,t){let r=t.maxParseRetries??2,n=typeof e=="string"?En(e,t.schema):e,o;for(let i=0;i<=r;i++){let a=i===0?n:typeof n=="string"?`${n}
172
172
 
173
- Previous attempt failed: ${o?.message}. Please output ONLY valid JSON.`:s,d=await n.run(a);try{let p=An(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 Ne=/\{\{(\w+)\}\}/g;function _(n){let e=[...new Set(Array.from(n.matchAll(Ne),r=>r[1]))],t=r=>n.replace(Ne,(s,o)=>{let i=r[o];if(i===void 0)throw new Error(`Missing template variable: {{${o}}}`);return i});return Object.defineProperty(t,"raw",{value:n,enumerable:!0}),Object.defineProperty(t,"variables",{value:e,enumerable:!0}),t}var Mn=_(`Summarize the following {{format}} in {{style}}:
173
+ Previous attempt failed: ${o?.message}. Please output ONLY valid JSON.`:n,l=await s.run(a);try{let p=An(l.text);return{data:JSON.parse(p),raw:t.includeRaw?l: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 Ne=/\{\{(\w+)\}\}/g;function T(s){let e=[...new Set(Array.from(s.matchAll(Ne),r=>r[1]))],t=r=>s.replace(Ne,(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 On=T(`Summarize the following {{format}} in {{style}}:
174
174
 
175
- {{text}}`),On=_(`Translate the following text to {{language}}:
175
+ {{text}}`),Mn=T(`Translate the following text to {{language}}:
176
176
 
177
- {{text}}`),Nn=_("Review this {{language}} code for bugs, security issues, and best practices:\n\n```{{language}}\n{{code}}\n```"),In=_(`Classify the following text into one of these categories: {{categories}}
177
+ {{text}}`),Nn=T("Review this {{language}} code for bugs, security issues, and best practices:\n\n```{{language}}\n{{code}}\n```"),In=T(`Classify the following text into one of these categories: {{categories}}
178
178
 
179
179
  Text: {{text}}
180
180
 
181
- Respond with only the category name.`),Hn=_(`Extract the following information from the text: {{fields}}
181
+ Respond with only the category name.`),Hn=T(`Extract the following information from the text: {{fields}}
182
182
 
183
183
  Text: {{text}}
184
184
 
185
- Respond as JSON.`);import{parseAgentsMd as jn,discoverAgents as Un,parseSkillMd as Ln}from"gauss-napi";var O=class n{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=jn(e),r=typeof t=="string"?JSON.parse(t):t;return new n(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}}}},ae=class n{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=Ln(e),r=typeof t=="string"?JSON.parse(t):t;return new n(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 Gn(n){let e=Un(n);return(typeof e=="string"?JSON.parse(e):e).map(r=>Object.assign(Object.create(O.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 Jn(n,...e){let t=n;for(let r of e)t=await r(t);return t}async function Ie(n,e,t){let r=t?.concurrency??n.length,s=new Array(n.length),o=n.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;s[a.index]=await e(a.item,a.index)}});return await Promise.all(i),s}async function $n(n,e,t){let r=await Ie(n,e,t);return n.filter((s,o)=>r[o])}async function Fn(n,e,t){let r=t;for(let s=0;s<n.length;s++)r=await e(r,n[s],s);return r}async function qn(n,e){for(let t=0;t<n.length;t++)await e(n[t],t);return n}function Bn(...n){return async e=>{let t=e;for(let r of n)t=await r(t);return t}}import*as le from"gauss-napi";function R(n){let e=le[n];if(typeof e=="function")return e;let t=le.default?.[n];if(typeof t=="function")return t;throw new TypeError(`gauss-napi is missing ${n}`)}function E(n){let e=n instanceof Error?n.message:String(n);return e.includes("not available in this gauss-napi build")||e.includes("gauss-napi is missing")||e.includes("Invalid response: missing field")||e.includes("Invalid task response: missing field")||e.includes("Invalid cancel response: missing field")}var de=class{baseUrl;authToken;rpcId=0;constructor(e){typeof e=="string"?this.baseUrl=e:(this.baseUrl=e.baseUrl,this.authToken=e.authToken)}async discover(){try{return await R("a2aDiscover")(this.baseUrl,this.authToken??void 0)}catch(e){if(!E(e))throw e;let t=await fetch(`${this.baseUrl.replace(/\/+$/,"")}/.well-known/agent.json`,{method:"GET",headers:this.buildHeaders()});if(!t.ok)throw new Error(`A2A discover failed (${t.status})`);return await t.json()}}async sendMessage(e,t){let r;try{r=await R("a2aSendMessage")(this.baseUrl,this.authToken??void 0,JSON.stringify(e),t?JSON.stringify(t):void 0)}catch(i){if(!E(i))throw i;r=await this.rpc("message/send",{message:e,config:t})}if(r._type==="task"){let{_type:i,...a}=r;return{type:"task",task:a}}let{_type:s,...o}=r;return{type:"message",message:o}}async ask(e){try{return await R("a2aAsk")(this.baseUrl,this.authToken??void 0,e)}catch(t){if(!E(t))throw t;let r=await this.sendMessage(He(e));if(r.type==="message")return ue(r.message);let s=pe(r.task);if(s)return s;let o=await this.getTask(r.task.id);return pe(o)??""}}async getTask(e,t){try{return await R("a2aGetTask")(this.baseUrl,this.authToken??void 0,e,t??void 0)}catch(r){if(!E(r))throw r;return this.rpc("tasks/get",{id:e,historyLength:t??void 0})}}async cancelTask(e){try{return await R("a2aCancelTask")(this.baseUrl,this.authToken??void 0,e)}catch(t){if(!E(t))throw t;return this.rpc("tasks/cancel",{id:e})}}buildHeaders(){let e={Accept:"application/json"};return this.authToken&&(e.Authorization=`Bearer ${this.authToken}`),e}async rpc(e,t){let r=await fetch(this.baseUrl,{method:"POST",headers:{...this.buildHeaders(),"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:++this.rpcId,method:e,params:t})});if(!r.ok)throw new Error(`A2A request failed (${r.status})`);let s=await r.json();if(s.error)throw new Error(s.error.message??`A2A RPC error (${s.error.code??"unknown"})`);return s.result}};function ce(n,e){return{role:n,parts:[{type:"text",text:e}]}}function He(n){return ce("user",n)}function zn(n){return ce("agent",n)}function ue(n){return n.parts.filter(e=>e.type==="text"&&e.text).map(e=>e.text).join("")}function pe(n){if(n.status.message)return ue(n.status.message)}import{createToolRegistry as Kn,toolRegistryAdd as Vn,toolRegistrySearch as Wn,toolRegistryByTag as Yn,toolRegistryList as Xn,destroyToolRegistry as Qn}from"gauss-napi";var me=class{_handle;disposed=!1;constructor(){this._handle=Kn()}get handle(){return this._handle}add(e){return this.assertNotDisposed(),Vn(this._handle,JSON.stringify(e)),this}search(e){return this.assertNotDisposed(),Wn(this._handle,e)}byTag(e){return this.assertNotDisposed(),Yn(this._handle,e)}list(){return this.assertNotDisposed(),Xn(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{Qn(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("ToolRegistry has been destroyed")}};export{de as A2aClient,he as ANTHROPIC_DEFAULT,Je as ANTHROPIC_FAST,$e as ANTHROPIC_PREMIUM,g as Agent,O as AgentSpec,S as AgentStream,ee as ApprovalManager,te as CheckpointStore,oe as ControlPlane,fe as DEEPSEEK_DEFAULT,Be as DEEPSEEK_REASONING,y as DisposedError,re as EvalRunner,xe as FIREWORKS_DEFAULT,ge as GOOGLE_DEFAULT,qe as GOOGLE_IMAGE,Fe as GOOGLE_PREMIUM,v as GaussError,B as Graph,Z as GuardrailChain,Te as MISTRAL_DEFAULT,Q as McpClient,X as McpServer,F as Memory,W as MiddlewareChain,V as Network,k as OPENAI_DEFAULT,Ue as OPENAI_FAST,Ge as OPENAI_IMAGE,Le as OPENAI_REASONING,ye as OPENROUTER_DEFAULT,_e as PERPLEXITY_DEFAULT,A as PROVIDER_DEFAULTS,Y as PluginRegistry,N as ProviderError,ae as SkillSpec,ve as TOGETHER_DEFAULT,K as Team,ne as Telemetry,T as TextSplitter,I as ToolExecutionError,me as ToolRegistry,ie as ToolValidator,h as ValidationError,q as VectorStore,z as Workflow,ke as XAI_DEFAULT,zn as agentMessage,Ve as applyGovernancePack,mt as availableRuntimes,it as batch,In as classify,en as clearPricing,Nn as codeReview,Bn as compose,nn as countMessageTokens,tn as countTokens,rn as countTokensForModel,gn as createCircuitBreaker,hn as createFallbackProvider,yn as createResilientAgent,Me as createResilientProvider,$ as createToolExecutor,ze as defaultModel,w as detectProvider,Gn as discoverAgents,H as enforceRoutingCostLimit,P as enforceRoutingGovernance,j as enforceRoutingRateLimit,U as enforceRoutingTimeWindow,Se as enterprisePreset,ot as enterpriseRun,se as estimateCost,ut as executeCode,L as explainRoutingTarget,Hn as extract,ue as extractText,$n as filterAsync,st as gauss,ht as generateImage,sn as getContextWindowSize,Zr as getPricing,be as governancePolicyPack,J as isTypedTool,Dt as loadJson,At as loadMarkdown,Ae as loadText,Ie as mapAsync,xn as parseAgentConfig,Pn as parsePartialJson,Jn as pipe,Fn as reduceAsync,b as resolveApiKey,Tn as resolveEnv,we as resolveFallbackProvider,C as resolveRoutingTarget,Rn as retryable,Qr as setPricing,Et as splitText,Dn as structured,Mn as summarize,qn as tapAsync,pe as taskText,_ as template,ce as textMessage,G as tool,On as translate,He as userMessage,gt as version,Oe as withRetry};
185
+ Respond as JSON.`);import{parseAgentsMd as jn,discoverAgents as Un,parseSkillMd as Ln}from"gauss-napi";var N=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=jn(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}}}},ae=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=Ln(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 Jn(s){let e=Un(s);return(typeof e=="string"?JSON.parse(e):e).map(r=>Object.assign(Object.create(N.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 Gn(s,...e){let t=s;for(let r of e)t=await r(t);return t}async function Ie(s,e,t){let r=t?.concurrency??s.length,n=new Array(s.length),o=s.map((a,l)=>({item:a,index:l})),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 $n(s,e,t){let r=await Ie(s,e,t);return s.filter((n,o)=>r[o])}async function Fn(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 qn(s,e){for(let t=0;t<s.length;t++)await e(s[t],t);return s}function Bn(...s){return async e=>{let t=e;for(let r of s)t=await r(t);return t}}import*as de from"gauss-napi";function S(s){let e=de[s];if(typeof e=="function")return e;let t=de.default?.[s];if(typeof t=="function")return t;throw new TypeError(`gauss-napi is missing ${s}`)}function R(s){let e=s instanceof Error?s.message:String(s);return e.includes("not available in this gauss-napi build")||e.includes("gauss-napi is missing")||e.includes("Invalid response: missing field")||e.includes("Invalid task response: missing field")||e.includes("Invalid cancel response: missing field")}var le=class{baseUrl;authToken;rpcId=0;constructor(e){typeof e=="string"?this.baseUrl=e:(this.baseUrl=e.baseUrl,this.authToken=e.authToken)}async discover(){try{return await S("a2aDiscover")(this.baseUrl,this.authToken??void 0)}catch(e){if(!R(e))throw e;let t=await fetch(`${this.baseUrl.replace(/\/+$/,"")}/.well-known/agent.json`,{method:"GET",headers:this.buildHeaders()});if(!t.ok)throw new Error(`A2A discover failed (${t.status})`);return await t.json()}}async sendMessage(e,t){let r;try{r=await S("a2aSendMessage")(this.baseUrl,this.authToken??void 0,JSON.stringify(e),t?JSON.stringify(t):void 0)}catch(i){if(!R(i))throw i;r=await this.rpc("message/send",{message:e,config:t})}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){try{return await S("a2aAsk")(this.baseUrl,this.authToken??void 0,e)}catch(t){if(!R(t))throw t;let r=await this.sendMessage(He(e));if(r.type==="message")return ue(r.message);let n=pe(r.task);if(n)return n;let o=await this.getTask(r.task.id);return pe(o)??""}}async getTask(e,t){try{return await S("a2aGetTask")(this.baseUrl,this.authToken??void 0,e,t??void 0)}catch(r){if(!R(r))throw r;return this.rpc("tasks/get",{id:e,historyLength:t??void 0})}}async cancelTask(e){try{return await S("a2aCancelTask")(this.baseUrl,this.authToken??void 0,e)}catch(t){if(!R(t))throw t;return this.rpc("tasks/cancel",{id:e})}}buildHeaders(){let e={Accept:"application/json"};return this.authToken&&(e.Authorization=`Bearer ${this.authToken}`),e}async rpc(e,t){let r=await fetch(this.baseUrl,{method:"POST",headers:{...this.buildHeaders(),"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:++this.rpcId,method:e,params:t})});if(!r.ok)throw new Error(`A2A request failed (${r.status})`);let n=await r.json();if(n.error)throw new Error(n.error.message??`A2A RPC error (${n.error.code??"unknown"})`);return n.result}};function ce(s,e){return{role:s,parts:[{type:"text",text:e}]}}function He(s){return ce("user",s)}function zn(s){return ce("agent",s)}function ue(s){return s.parts.filter(e=>e.type==="text"&&e.text).map(e=>e.text).join("")}function pe(s){if(s.status.message)return ue(s.status.message)}import{createToolRegistry as Kn,toolRegistryAdd as Vn,toolRegistrySearch as Wn,toolRegistryByTag as Yn,toolRegistryList as Xn,destroyToolRegistry as Qn}from"gauss-napi";var me=class{_handle;disposed=!1;constructor(){this._handle=Kn()}get handle(){return this._handle}add(e){return this.assertNotDisposed(),Vn(this._handle,JSON.stringify(e)),this}search(e){return this.assertNotDisposed(),Wn(this._handle,e)}byTag(e){return this.assertNotDisposed(),Yn(this._handle,e)}list(){return this.assertNotDisposed(),Xn(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{Qn(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("ToolRegistry has been destroyed")}};export{le as A2aClient,he as ANTHROPIC_DEFAULT,Ge as ANTHROPIC_FAST,$e as ANTHROPIC_PREMIUM,g as Agent,N as AgentSpec,C as AgentStream,ee as ApprovalManager,te as CheckpointStore,oe as ControlPlane,fe as DEEPSEEK_DEFAULT,Be as DEEPSEEK_REASONING,y as DisposedError,re as EvalRunner,xe as FIREWORKS_DEFAULT,ge as GOOGLE_DEFAULT,qe as GOOGLE_IMAGE,Fe as GOOGLE_PREMIUM,f as GaussError,B as Graph,Z as GuardrailChain,Te as MISTRAL_DEFAULT,Q as McpClient,X as McpServer,F as Memory,W as MiddlewareChain,V as Network,k as OPENAI_DEFAULT,Ue as OPENAI_FAST,Je as OPENAI_IMAGE,Le as OPENAI_REASONING,ye as OPENROUTER_DEFAULT,ke as PERPLEXITY_DEFAULT,A as PROVIDER_DEFAULTS,Y as PluginRegistry,I as ProviderError,ae as SkillSpec,ve as TOGETHER_DEFAULT,K as Team,ne as Telemetry,x as TextSplitter,H as ToolExecutionError,me as ToolRegistry,ie as ToolValidator,m as ValidationError,q as VectorStore,z as Workflow,_e as XAI_DEFAULT,zn as agentMessage,Ve as applyGovernancePack,mt as availableRuntimes,it as batch,In as classify,en as clearPricing,Nn as codeReview,Bn as compose,nn as countMessageTokens,tn as countTokens,rn as countTokensForModel,gn as createCircuitBreaker,hn as createFallbackProvider,yn as createResilientAgent,Oe as createResilientProvider,$ as createToolExecutor,ze as defaultModel,b as detectProvider,Jn as discoverAgents,j as enforceRoutingCostLimit,P as enforceRoutingGovernance,U as enforceRoutingRateLimit,L as enforceRoutingTimeWindow,Se as enterprisePreset,ot as enterpriseRun,se as estimateCost,ut as executeCode,D as explainRoutingTarget,Hn as extract,ue as extractText,$n as filterAsync,st as gauss,ht as generateImage,sn as getContextWindowSize,Zr as getPricing,be as governancePolicyPack,G as isTypedTool,Dt as loadJson,At as loadMarkdown,Ae as loadText,Ie as mapAsync,xn as parseAgentConfig,wn as parsePartialJson,Gn as pipe,Fn as reduceAsync,_ as resolveApiKey,Tn as resolveEnv,Pe as resolveFallbackProvider,w as resolveRoutingTarget,Rn as retryable,Qr as setPricing,Et as splitText,Dn as structured,On as summarize,qn as tapAsync,pe as taskText,T as template,ce as textMessage,J as tool,Mn as translate,He as userMessage,gt as version,Me as withRetry};
186
186
  //# sourceMappingURL=index.js.map