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/README.md +3 -1
- package/dist/index.cjs +19 -19
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +5 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +21 -21
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -213,7 +213,7 @@ const explanation = explainRoutingTarget(
|
|
|
213
213
|
"gpt-5.2",
|
|
214
214
|
{ currentHourUtc: 11, governanceTags: ["balanced"] },
|
|
215
215
|
);
|
|
216
|
-
console.log(explanation);
|
|
216
|
+
console.log(explanation.decision?.selectedBy); // "direct" | "alias:..." | "fallback:..."
|
|
217
217
|
```
|
|
218
218
|
|
|
219
219
|
### Unified Control Plane (M51 foundation)
|
|
@@ -239,6 +239,8 @@ console.log(`Control Plane: ${url}`);
|
|
|
239
239
|
// hosted ops summary -> GET ${url}/api/ops/summary
|
|
240
240
|
// hosted ops tenant breakdown -> GET ${url}/api/ops/tenants
|
|
241
241
|
// hosted policy explain -> GET ${url}/api/ops/policy/explain?provider=openai&model=gpt-5.2
|
|
242
|
+
// hosted policy explain batch -> GET ${url}/api/ops/policy/explain/batch?scenarios=[...]
|
|
243
|
+
// hosted policy simulation -> GET ${url}/api/ops/policy/explain/simulate?scenarios=[...]
|
|
242
244
|
// hosted ops dashboard -> GET ${url}/ops
|
|
243
245
|
// hosted tenant dashboard -> GET ${url}/ops/tenants
|
|
244
246
|
```
|
package/dist/index.cjs
CHANGED
|
@@ -1,28 +1,28 @@
|
|
|
1
|
-
"use strict";var ir=Object.create;var Z=Object.defineProperty;var ar=Object.getOwnPropertyDescriptor;var dr=Object.getOwnPropertyNames;var pr=Object.getPrototypeOf,lr=Object.prototype.hasOwnProperty;var cr=(n,e)=>{for(var t in e)Z(n,t,{get:e[t],enumerable:!0})},st=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of dr(e))!lr.call(n,s)&&s!==t&&Z(n,s,{get:()=>e[s],enumerable:!(r=ar(e,s))||r.enumerable});return n};var ur=(n,e,t)=>(t=n!=null?ir(pr(n)):{},st(e||!n||!n.__esModule?Z(t,"default",{value:n,enumerable:!0}):t,n)),mr=n=>st(Z({},"__esModule",{value:!0}),n);var kr={};cr(kr,{A2aClient:()=>Me,ANTHROPIC_DEFAULT:()=>je,ANTHROPIC_FAST:()=>dt,ANTHROPIC_PREMIUM:()=>pt,Agent:()=>f,AgentSpec:()=>Y,AgentStream:()=>B,ApprovalManager:()=>_e,CheckpointStore:()=>ke,ControlPlane:()=>Se,DEEPSEEK_DEFAULT:()=>Ge,DEEPSEEK_REASONING:()=>ut,DisposedError:()=>x,EvalRunner:()=>be,FIREWORKS_DEFAULT:()=>$e,GOOGLE_DEFAULT:()=>Ue,GOOGLE_IMAGE:()=>ct,GOOGLE_PREMIUM:()=>lt,GaussError:()=>I,Graph:()=>ue,GuardrailChain:()=>Te,MISTRAL_DEFAULT:()=>Fe,McpClient:()=>xe,McpServer:()=>ve,Memory:()=>le,MiddlewareChain:()=>ye,Network:()=>ge,OPENAI_DEFAULT:()=>G,OPENAI_FAST:()=>ot,OPENAI_IMAGE:()=>at,OPENAI_REASONING:()=>it,OPENROUTER_DEFAULT:()=>Le,PERPLEXITY_DEFAULT:()=>qe,PROVIDER_DEFAULTS:()=>W,PluginRegistry:()=>fe,ProviderError:()=>ee,SkillSpec:()=>De,TOGETHER_DEFAULT:()=>Je,Team:()=>he,Telemetry:()=>we,TextSplitter:()=>j,ToolExecutionError:()=>te,ToolRegistry:()=>He,ToolValidator:()=>Ae,ValidationError:()=>y,VectorStore:()=>ce,Workflow:()=>me,XAI_DEFAULT:()=>Be,agentMessage:()=>sr,applyGovernancePack:()=>ht,availableRuntimes:()=>_t,batch:()=>xt,classify:()=>Yt,clearPricing:()=>At,codeReview:()=>Wt,compose:()=>nr,countMessageTokens:()=>Ot,countTokens:()=>Dt,countTokensForModel:()=>Mt,createCircuitBreaker:()=>Ut,createFallbackProvider:()=>jt,createResilientAgent:()=>Lt,createResilientProvider:()=>Ze,createToolExecutor:()=>de,defaultModel:()=>mt,detectProvider:()=>$,discoverAgents:()=>Qt,enforceRoutingCostLimit:()=>re,enforceRoutingGovernance:()=>F,enforceRoutingRateLimit:()=>ne,enforceRoutingTimeWindow:()=>se,enterprisePreset:()=>Ve,enterpriseRun:()=>vt,estimateCost:()=>Ce,executeCode:()=>Tt,explainRoutingTarget:()=>oe,extract:()=>Xt,extractText:()=>Ie,filterAsync:()=>er,gauss:()=>ft,generateImage:()=>kt,getContextWindowSize:()=>Nt,getPricing:()=>Et,governancePolicyPack:()=>ze,isTypedTool:()=>ae,loadJson:()=>Ct,loadMarkdown:()=>Pt,loadText:()=>Qe,mapAsync:()=>tt,parseAgentConfig:()=>Gt,parsePartialJson:()=>Ft,pipe:()=>Zt,reduceAsync:()=>tr,resolveApiKey:()=>J,resolveEnv:()=>Jt,resolveFallbackProvider:()=>Ke,resolveRoutingTarget:()=>q,retryable:()=>qt,setPricing:()=>Rt,splitText:()=>wt,structured:()=>Bt,summarize:()=>Kt,tapAsync:()=>rr,taskText:()=>Oe,template:()=>L,textMessage:()=>Ne,tool:()=>ie,translate:()=>Vt,userMessage:()=>nt,version:()=>We.version,withRetry:()=>et});module.exports=mr(kr);var I=class extends Error{code;constructor(e,t){super(t),this.name="GaussError",this.code=e}},x=class extends I{resourceType;resourceName;constructor(e,t){super("RESOURCE_DISPOSED",`${e} "${t}" has been destroyed. Create a new instance.`),this.name="DisposedError",this.resourceType=e,this.resourceName=t}},ee=class extends I{provider;constructor(e,t){super("PROVIDER_ERROR",`[${e}] ${t}`),this.name="ProviderError",this.provider=e}},te=class extends I{toolName;cause;constructor(e,t,r){super("TOOL_EXECUTION_ERROR",`Tool "${e}" failed: ${t}`),this.name="ToolExecutionError",this.toolName=e,this.cause=r}},y=class extends I{field;constructor(e,t){super("VALIDATION_ERROR",t?`Invalid "${t}": ${e}`:e),this.name="ValidationError",this.field=t}};var G="gpt-5.2",ot="gpt-4.1",it="o4-mini",at="gpt-image-1",je="claude-sonnet-4-20250514",dt="claude-haiku-4-20250414",pt="claude-opus-4-20250414",Ue="gemini-2.5-flash",lt="gemini-2.5-pro",ct="gemini-2.0-flash",Le="openai/gpt-5.2",Ge="deepseek-chat",ut="deepseek-reasoner",Je="meta-llama/Llama-3.3-70B-Instruct-Turbo",$e="accounts/fireworks/models/llama-v3p1-70b-instruct",Fe="mistral-large-latest",qe="sonar-pro",Be="grok-3-beta",W={openai:G,anthropic:je,google:Ue,openrouter:Le,deepseek:Ge,groq:"llama-3.3-70b-versatile",ollama:"llama3.2",together:Je,fireworks:$e,mistral:Fe,perplexity:qe,xai:Be};function mt(n){return W[n]??G}var hr={openai:"OPENAI_API_KEY",anthropic:"ANTHROPIC_API_KEY",google:"GOOGLE_API_KEY",groq:"GROQ_API_KEY",deepseek:"DEEPSEEK_API_KEY",openrouter:"OPENROUTER_API_KEY",together:"TOGETHER_API_KEY",fireworks:"FIREWORKS_API_KEY",mistral:"MISTRAL_API_KEY",perplexity:"PERPLEXITY_API_KEY",xai:"XAI_API_KEY",ollama:""};function J(n){let e=hr[n]??"";return e?(typeof process<"u"?process.env[e]:"")??"":""}function $(){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:W[t]}}var h=require("gauss-napi");function ze(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 ht(n,e){let t=ze(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 re(n,e){if(n?.maxTotalCostUsd!==void 0&&e>n.maxTotalCostUsd)throw new Error(`routing policy rejected cost ${e}`)}function ne(n,e){if(n?.maxRequestsPerMinute!==void 0&&e>n.maxRequestsPerMinute)throw new Error(`routing policy rejected rate ${e}`)}function se(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 F(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 Ke(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 q(n,e,t,r={}){let s=r.governanceTags,o=r.currentHourUtc??new Date().getUTCHours();se(n,o),r.estimatedCostUsd!==void 0&&re(n,r.estimatedCostUsd),r.currentRequestsPerMinute!==void 0&&ne(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,H)=>(H.priority??0)-(m.priority??0)),l=r.availableProviders;if(!l||l.length===0){let m=i(p);return F(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 F(n,m.provider,s),{provider:m.provider,model:m.model,selectedBy:`alias:${t}`}}}let d=Ke(n,r.availableProviders??[]);return d&&d!==e?(F(n,d,s),{provider:d,model:t,selectedBy:`fallback:${d}`}):(F(n,e,s),{provider:e,model:t,selectedBy:"direct"})}function oe(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{se(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{re(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{ne(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=q(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)}}var gt=require("gauss-napi");function gr(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 B=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=(0,gt.agent_stream_with_tool_executor)(this.agentName,this.providerHandle,this.tools,this.messages,this.options,s,this.toolExecutor).then(i=>{this._result=gr(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 ie(n){return{name:n.name,description:n.description,parameters:n.parameters,execute:n.execute}}function ae(n){return typeof n.execute=="function"}function de(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 pe(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 f=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=$(),r=e.provider??t?.provider??"openai",s=e.model??t?.model??G;this._requestedProvider=r,this._requestedModel=s,this._routingPolicy=e.routingPolicy;let o=q(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??J(this._provider);this._providerOptions={apiKey:i,...e.providerOptions},this.providerHandle=(0,h.create_provider)(this._provider,this._model,this._providerOptions),e.tools&&(this._tools=[...e.tools]),e.middleware&&(this._middleware=e.middleware),e.guardrails&&(this._guardrails=e.guardrails),e.memory&&(this._memory=e.memory),e.sessionId&&(this._sessionId=e.sessionId),e.mcpClients&&(this._mcpClients=[...e.mcpClients]);let a=e.codeExecution,d=a===!0?{python:!0,javascript:!0,bash:!0}:a||void 0;this._options={instructions:this._instructions||void 0,temperature:e.temperature,maxSteps:e.maxSteps,topP:e.topP,maxTokens:e.maxTokens,seed:e.seed,stopOnTool:e.stopOnTool,outputSchema:e.outputSchema,thinkingBudget:e.thinkingBudget,reasoningEffort:e.reasoningEffort,cacheControl:e.cacheControl,codeExecution:d,grounding:e.grounding,nativeCodeExecution:e.nativeCodeExecution,responseModalities:e.responseModalities}}static fromEnv(e={}){return new 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(0,h.get_provider_capabilities)(this.providerHandle)}addTool(e){return this._tools.push(e),this}addTools(e){return this._tools.push(...e),this}withTool(e,t,r,s){return this._tools.push(ie({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=q(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(
|
|
1
|
+
"use strict";var ir=Object.create;var ee=Object.defineProperty;var ar=Object.getOwnPropertyDescriptor;var lr=Object.getOwnPropertyNames;var pr=Object.getPrototypeOf,dr=Object.prototype.hasOwnProperty;var cr=(n,e)=>{for(var t in e)ee(n,t,{get:e[t],enumerable:!0})},st=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of lr(e))!dr.call(n,s)&&s!==t&&ee(n,s,{get:()=>e[s],enumerable:!(r=ar(e,s))||r.enumerable});return n};var ur=(n,e,t)=>(t=n!=null?ir(pr(n)):{},st(e||!n||!n.__esModule?ee(t,"default",{value:n,enumerable:!0}):t,n)),mr=n=>st(ee({},"__esModule",{value:!0}),n);var _r={};cr(_r,{A2aClient:()=>Oe,ANTHROPIC_DEFAULT:()=>je,ANTHROPIC_FAST:()=>lt,ANTHROPIC_PREMIUM:()=>pt,Agent:()=>f,AgentSpec:()=>Y,AgentStream:()=>q,ApprovalManager:()=>ke,CheckpointStore:()=>_e,ControlPlane:()=>Se,DEEPSEEK_DEFAULT:()=>Je,DEEPSEEK_REASONING:()=>ut,DisposedError:()=>x,EvalRunner:()=>be,FIREWORKS_DEFAULT:()=>$e,GOOGLE_DEFAULT:()=>Ue,GOOGLE_IMAGE:()=>ct,GOOGLE_PREMIUM:()=>dt,GaussError:()=>I,Graph:()=>ue,GuardrailChain:()=>Te,MISTRAL_DEFAULT:()=>Fe,McpClient:()=>xe,McpServer:()=>ve,Memory:()=>de,MiddlewareChain:()=>ye,Network:()=>ge,OPENAI_DEFAULT:()=>L,OPENAI_FAST:()=>ot,OPENAI_IMAGE:()=>at,OPENAI_REASONING:()=>it,OPENROUTER_DEFAULT:()=>Le,PERPLEXITY_DEFAULT:()=>qe,PROVIDER_DEFAULTS:()=>V,PluginRegistry:()=>fe,ProviderError:()=>te,SkillSpec:()=>De,TOGETHER_DEFAULT:()=>Ge,Team:()=>he,Telemetry:()=>Pe,TextSplitter:()=>H,ToolExecutionError:()=>re,ToolRegistry:()=>He,ToolValidator:()=>Ae,ValidationError:()=>m,VectorStore:()=>ce,Workflow:()=>me,XAI_DEFAULT:()=>Be,agentMessage:()=>sr,applyGovernancePack:()=>ht,availableRuntimes:()=>kt,batch:()=>xt,classify:()=>Yt,clearPricing:()=>At,codeReview:()=>Wt,compose:()=>nr,countMessageTokens:()=>Mt,countTokens:()=>Dt,countTokensForModel:()=>Ot,createCircuitBreaker:()=>Ut,createFallbackProvider:()=>jt,createResilientAgent:()=>Lt,createResilientProvider:()=>Ze,createToolExecutor:()=>le,defaultModel:()=>mt,detectProvider:()=>G,discoverAgents:()=>Qt,enforceRoutingCostLimit:()=>ne,enforceRoutingGovernance:()=>$,enforceRoutingRateLimit:()=>se,enforceRoutingTimeWindow:()=>oe,enterprisePreset:()=>Ve,enterpriseRun:()=>vt,estimateCost:()=>Ce,executeCode:()=>Tt,explainRoutingTarget:()=>W,extract:()=>Xt,extractText:()=>Ie,filterAsync:()=>er,gauss:()=>ft,generateImage:()=>_t,getContextWindowSize:()=>Nt,getPricing:()=>Et,governancePolicyPack:()=>ze,isTypedTool:()=>ae,loadJson:()=>Ct,loadMarkdown:()=>wt,loadText:()=>Qe,mapAsync:()=>tt,parseAgentConfig:()=>Jt,parsePartialJson:()=>Ft,pipe:()=>Zt,reduceAsync:()=>tr,resolveApiKey:()=>J,resolveEnv:()=>Gt,resolveFallbackProvider:()=>Ke,resolveRoutingTarget:()=>F,retryable:()=>qt,setPricing:()=>Rt,splitText:()=>Pt,structured:()=>Bt,summarize:()=>Kt,tapAsync:()=>rr,taskText:()=>Me,template:()=>U,textMessage:()=>Ne,tool:()=>ie,translate:()=>Vt,userMessage:()=>nt,version:()=>We.version,withRetry:()=>et});module.exports=mr(_r);var I=class extends Error{code;constructor(e,t){super(t),this.name="GaussError",this.code=e}},x=class extends I{resourceType;resourceName;constructor(e,t){super("RESOURCE_DISPOSED",`${e} "${t}" has been destroyed. Create a new instance.`),this.name="DisposedError",this.resourceType=e,this.resourceName=t}},te=class extends I{provider;constructor(e,t){super("PROVIDER_ERROR",`[${e}] ${t}`),this.name="ProviderError",this.provider=e}},re=class extends I{toolName;cause;constructor(e,t,r){super("TOOL_EXECUTION_ERROR",`Tool "${e}" failed: ${t}`),this.name="ToolExecutionError",this.toolName=e,this.cause=r}},m=class extends I{field;constructor(e,t){super("VALIDATION_ERROR",t?`Invalid "${t}": ${e}`:e),this.name="ValidationError",this.field=t}};var L="gpt-5.2",ot="gpt-4.1",it="o4-mini",at="gpt-image-1",je="claude-sonnet-4-20250514",lt="claude-haiku-4-20250414",pt="claude-opus-4-20250414",Ue="gemini-2.5-flash",dt="gemini-2.5-pro",ct="gemini-2.0-flash",Le="openai/gpt-5.2",Je="deepseek-chat",ut="deepseek-reasoner",Ge="meta-llama/Llama-3.3-70B-Instruct-Turbo",$e="accounts/fireworks/models/llama-v3p1-70b-instruct",Fe="mistral-large-latest",qe="sonar-pro",Be="grok-3-beta",V={openai:L,anthropic:je,google:Ue,openrouter:Le,deepseek:Je,groq:"llama-3.3-70b-versatile",ollama:"llama3.2",together:Ge,fireworks:$e,mistral:Fe,perplexity:qe,xai:Be};function mt(n){return V[n]??L}var hr={openai:"OPENAI_API_KEY",anthropic:"ANTHROPIC_API_KEY",google:"GOOGLE_API_KEY",groq:"GROQ_API_KEY",deepseek:"DEEPSEEK_API_KEY",openrouter:"OPENROUTER_API_KEY",together:"TOGETHER_API_KEY",fireworks:"FIREWORKS_API_KEY",mistral:"MISTRAL_API_KEY",perplexity:"PERPLEXITY_API_KEY",xai:"XAI_API_KEY",ollama:""};function J(n){let e=hr[n]??"";return e?(typeof process<"u"?process.env[e]:"")??"":""}function G(){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:V[t]}}var h=require("gauss-napi");function ze(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 ht(n,e){let t=ze(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 ne(n,e){if(n?.maxTotalCostUsd!==void 0&&e>n.maxTotalCostUsd)throw new Error(`routing policy rejected cost ${e}`)}function se(n,e){if(n?.maxRequestsPerMinute!==void 0&&e>n.maxRequestsPerMinute)throw new Error(`routing policy rejected rate ${e}`)}function oe(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 $(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 Ke(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 F(n,e,t,r={}){let s=r.governanceTags,o=r.currentHourUtc??new Date().getUTCHours();oe(n,o),r.estimatedCostUsd!==void 0&&ne(n,r.estimatedCostUsd),r.currentRequestsPerMinute!==void 0&&se(n,r.currentRequestsPerMinute);let i=p=>p.length===1?p[0]:[...p].sort((d,c)=>{let y=n?.providerWeights?.[c.provider]??0,u=n?.providerWeights?.[d.provider]??0;return y!==u?y-u:(c.priority??0)-(d.priority??0)})[0],a=n?.aliases?.[t];if(a&&a.length>0){let p=[...a].sort((u,Z)=>(Z.priority??0)-(u.priority??0)),d=r.availableProviders;if(!d||d.length===0){let u=i(p);return $(n,u.provider,s),{provider:u.provider,model:u.model,selectedBy:`alias:${t}`}}let c=new Set(d),y=p.filter(u=>c.has(u.provider));if(y.length>0){let u=i(y);return $(n,u.provider,s),{provider:u.provider,model:u.model,selectedBy:`alias:${t}`}}}let l=Ke(n,r.availableProviders??[]);return l&&l!==e?($(n,l,s),{provider:l,model:t,selectedBy:`fallback:${l}`}):($(n,e,s),{provider:e,model:t,selectedBy:"direct"})}function W(n,e,t,r={}){let s=[],o=r.currentHourUtc??new Date().getUTCHours(),i=(a,l)=>{let p=l instanceof Error?l.message:String(l);return s.push({check:a,status:"failed",detail:p}),{ok:!1,checks:s,error:p}};if(n?.allowedHoursUtc&&n.allowedHoursUtc.length>0)try{oe(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{ne(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{se(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=F(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 l=a instanceof Error?a.message:String(a);return l.includes("governance")?(s.push({check:"governance",status:"failed",detail:l}),s.push({check:"selection",status:"skipped",detail:"selection aborted"}),{ok:!1,checks:s,error:l}):i("selection",a)}}var gt=require("gauss-napi");function gr(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 q=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=(0,gt.agent_stream_with_tool_executor)(this.agentName,this.providerHandle,this.tools,this.messages,this.options,s,this.toolExecutor).then(i=>{this._result=gr(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 ie(n){return{name:n.name,description:n.description,parameters:n.parameters,execute:n.execute}}function ae(n){return typeof n.execute=="function"}function le(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??{},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 pe(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 f=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=G(),r=e.provider??t?.provider??"openai",s=e.model??t?.model??L;this._requestedProvider=r,this._requestedModel=s,this._routingPolicy=e.routingPolicy;let o=F(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??J(this._provider);this._providerOptions={apiKey:i,...e.providerOptions},this.providerHandle=(0,h.create_provider)(this._provider,this._model,this._providerOptions),e.tools&&(this._tools=[...e.tools]),e.middleware&&(this._middleware=e.middleware),e.guardrails&&(this._guardrails=e.guardrails),e.memory&&(this._memory=e.memory),e.sessionId&&(this._sessionId=e.sessionId),e.mcpClients&&(this._mcpClients=[...e.mcpClients]);let a=e.codeExecution,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 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(0,h.get_provider_capabilities)(this.providerHandle)}addTool(e){return this._tools.push(e),this}addTools(e){return this._tools.push(...e),this}withTool(e,t,r,s){return this._tools.push(ie({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=F(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(l=>l.content).join(`
|
|
3
3
|
`)}`},...t])}let{toolDefs:r,executor:s}=this.resolveToolsAndExecutor(),o;if(s?o=pe(await(0,h.agent_run_with_tool_executor)(this._name,this.providerHandle,r,t,this._options,s)):o=pe(await(0,h.agent_run)(this._name,this.providerHandle,r,t,this._options)),this._memory){let i=typeof e=="string"?e:e.map(a=>a.content).join(`
|
|
4
|
-
`);await this._memory.store({id:`${Date.now()}-user`,content:i,entryType:"conversation",timestamp:new Date().toISOString(),sessionId:this._sessionId||void 0}),await this._memory.store({id:`${Date.now()}-assistant`,content:o.text,entryType:"conversation",timestamp:new Date().toISOString(),sessionId:this._sessionId||void 0})}return o}async runWithTools(e,t){this.assertNotDisposed(),await this.ensureMcpTools();let r=typeof e=="string"?[{role:"user",content:e}]:e,{toolDefs:s,executor:o}=this.resolveToolsAndExecutor(),i=async a=>{if(o){let
|
|
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 l=await o(a);if(!JSON.parse(l).error?.startsWith("Unknown tool:"))return l}return t(a)};return pe(await(0,h.agent_run_with_tool_executor)(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??yt;return pe(await(0,h.agent_stream_with_tool_executor)(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??yt;return new q(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(0,h.generate)(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(0,h.generate_with_tools)(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{(0,h.destroy_provider)(this.providerHandle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new x("Agent",this._name)}resolveToolsAndExecutor(){let e=this._tools.filter(ae),t=this._tools.map(s=>({name:s.name,description:s.description,parameters:s.parameters})),r=e.length>0?le(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}),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}}},yt=async()=>"{}";async function ft(n,e){let t=new f({name:"gauss",...e});try{return(await t.run(n)).text}finally{t.destroy()}}function Ve(n={}){let e=n.providerOptions?.maxRetries??n.retries??5;return new f({...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 vt(n,e){let t=Ve(e);try{return(await t.run(n)).text}finally{t.destroy()}}async function xt(n,e){let{concurrency:t=5,...r}=e??{},s=n.map(i=>({input:i})),o=new f({name:"batch",...r});try{let i=[...s.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{s[p].result=await o.run(d.input)}catch(c){s[p].error=c instanceof Error?c:new Error(String(c))}}});await Promise.all(a)}finally{o.destroy()}return s}var S=require("gauss-napi");var We=require("gauss-napi");async function Tt(n,e,t){return(0,S.execute_code)(n,e,t?.timeoutSecs,t?.workingDir,t?.sandbox)}async function kt(){return(0,S.available_runtimes)()}async function _t(n,e={}){let t=G(),r=e.provider??t?.provider??"openai",s=e.model??t?.model??"dall-e-3",o=e.providerOptions?.apiKey??J(r),i=(0,S.create_provider)(r,s,{apiKey:o,...e.providerOptions});try{return await(0,S.generate_image)(i,n,e.model,e.size,e.quality,e.style,e.aspectRatio,e.n,e.responseFormat)}finally{(0,S.destroy_provider)(i)}}var bt=require("crypto"),T=require("gauss-napi"),de=class{_handle;disposed=!1;constructor(){this._handle=(0,T.create_memory)()}get handle(){return this._handle}async store(e,t,r){this.assertNotDisposed();let s=typeof e=="string"?{id:(0,bt.randomUUID)(),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(0,T.memory_store)(this._handle,JSON.stringify(o))}async recall(e){this.assertNotDisposed();let t=e?JSON.stringify(e):void 0;return(0,T.memory_recall)(this._handle,t)}async clear(e){return this.assertNotDisposed(),(0,T.memory_clear)(this._handle,e)}async stats(){return this.assertNotDisposed(),(0,T.memory_stats)(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,T.destroy_memory)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Memory has been destroyed")}};var R=require("gauss-napi"),ce=class{_handle;disposed=!1;constructor(e){this._handle=(0,R.create_vector_store)()}get handle(){return this._handle}async upsert(e){this.assertNotDisposed();let t=e.map(r=>({id:r.id,document_id:r.documentId,content:r.content,index:r.index,metadata:r.metadata??{},embedding:r.embedding}));return(0,R.vector_store_upsert)(this._handle,JSON.stringify(t))}async search(e,t){return this.assertNotDisposed(),(0,R.vector_store_search)(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{(0,R.destroy_vector_store)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("VectorStore has been destroyed")}static cosineSimilarity(e,t){return(0,R.cosine_similarity)(e,t)}};var yr=[`
|
|
5
5
|
|
|
6
6
|
`,`
|
|
7
|
-
`,". "," ",""],
|
|
8
|
-
`)&&n.length<500,r,s;if(t)try{r=await(0,Ye.readFile)(n,"utf-8"),s=e.documentId??(0,Xe.basename)(n)}catch{r=n,s=e.documentId??"text-document"}else r=n,s=e.documentId??"text-document";let a=new
|
|
7
|
+
`,". "," ",""],H=class{chunkSize;chunkOverlap;separators;constructor(e={}){this.chunkSize=e.chunkSize??1e3,this.chunkOverlap=e.chunkOverlap??200,this.separators=e.separators??yr}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 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&&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 Pt(n,e){return new H(e).split(n)}var Ye=require("fs/promises"),Xe=require("path");async function Qe(n,e={}){let t=!n.includes(`
|
|
8
|
+
`)&&n.length<500,r,s;if(t)try{r=await(0,Ye.readFile)(n,"utf-8"),s=e.documentId??(0,Xe.basename)(n)}catch{r=n,s=e.documentId??"text-document"}else r=n,s=e.documentId??"text-document";let a=new H(e).split(r).map(l=>({id:`${s}-${l.index}`,documentId:s,content:l.content,index:l.index,metadata:{...e.metadata,...l.metadata}}));return{documentId:s,content:r,chunks:a,metadata:e.metadata??{}}}async function wt(n,e={}){let t=await Qe(n,{...e,separators:[`
|
|
9
9
|
## `,`
|
|
10
10
|
### `,`
|
|
11
11
|
|
|
12
12
|
`,`
|
|
13
13
|
`,". "," "]});return t.content=t.content.replace(/^---[\s\S]*?---\n?/,""),t}async function Ct(n,e={}){let t,r;if(!n.includes(`
|
|
14
|
-
`)&&n.length<500)try{t=await(0,Ye.readFile)(n,"utf-8"),r=e.documentId??(0,Xe.basename)(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((
|
|
14
|
+
`)&&n.length<500)try{t=await(0,Ye.readFile)(n,"utf-8"),r=e.documentId??(0,Xe.basename)(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((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??{}}}var k=require("gauss-napi");var ue=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=(0,k.create_graph)()}get handle(){return this._handle}addNode(e){return this.assertNotDisposed(),(0,k.graph_add_node)(this._handle,e.nodeId,e.agent.name,e.agent.handle,e.instructions,e.tools??[]),this._nodes.set(e.nodeId,{agent:e.agent,instructions:e.instructions}),this}addFork(e){return this.assertNotDisposed(),(0,k.graph_add_fork_node)(this._handle,e.nodeId,e.agents.map(t=>({agentName:t.agent.name,providerHandle:t.agent.handle,instructions:t.instructions})),e.consensus??"concat"),this}addEdge(e,t){return this.assertNotDisposed(),(0,k.graph_add_edge)(this._handle,e,t),this._edges.set(e,t),this}addConditionalEdge(e,t){return this.assertNotDisposed(),this._conditionalEdges.set(e,t),this}async run(e){return this.assertNotDisposed(),this._conditionalEdges.size===0?(0,k.graph_run)(this._handle,e):this._runWithConditionals(e)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,k.destroy_graph)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}async _runWithConditionals(e){let t=new Set([...this._edges.values()]),r=[...this._nodes.keys()].filter(p=>!t.has(p));if(r.length===0)throw new m("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 m(`Node "${o}" not found in graph`);let d=p.instructions?`${p.instructions}
|
|
15
15
|
|
|
16
|
-
${i}`:i,c=await p.agent.run(
|
|
17
|
-
`)??"Tool error";return JSON.stringify({error:p})}let
|
|
18
|
-
`)??"";return JSON.stringify({result:
|
|
16
|
+
${i}`:i,c=await p.agent.run(d),y={text:c.text,...c.structuredOutput?{structuredOutput:c.structuredOutput}:{}};s[o]=y;let u=this._conditionalEdges.get(o);u?o=await u(y):o=this._edges.get(o),i=c.text}let a=Object.keys(s),l=a[a.length-1];return{outputs:s,final_text:s[l]?.text??""}}assertNotDisposed(){if(this.disposed)throw new x("Graph","graph")}};var E=require("gauss-napi"),me=class{_handle;disposed=!1;constructor(){this._handle=(0,E.create_workflow)()}get handle(){return this._handle}addStep(e){return this.assertNotDisposed(),(0,E.workflow_add_step)(this._handle,e.stepId,e.agent.name,e.agent.handle,e.instructions,e.tools??[]),this}addDependency(e,t){return this.assertNotDisposed(),(0,E.workflow_add_dependency)(this._handle,e,t),this}async run(e){return this.assertNotDisposed(),(0,E.workflow_run)(this._handle,e)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,E.destroy_workflow)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Workflow has been destroyed")}};var A=require("gauss-napi");var he=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 f({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=(0,A.create_team)(e)}get handle(){return this._handle}add(e,t){return this.assertNotDisposed(),(0,A.team_add_agent)(this._handle,e.name,e.handle,t),this.agents.push(e),this}strategy(e){return this.assertNotDisposed(),(0,A.team_set_strategy)(this._handle,e),this}async run(e){this.assertNotDisposed();let t=JSON.stringify([{role:"user",content:[{type:"text",text:e}]}]);return(0,A.team_run)(this._handle,t)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,A.destroy_team)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new x("Team",this._name)}};var v=require("gauss-napi");var ge=class n{_handle;disposed=!1;supervisorName=null;static quick(e,t){let r=new n;for(let s of t){let o=new f({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=(0,v.create_network)()}get handle(){return this._handle}addAgent(e,t){this.assertNotDisposed();let r=typeof t=="string"?t:t?.instructions;return(0,v.network_add_agent)(this._handle,e.name,e.handle,r),this}setSupervisor(e){return this.assertNotDisposed(),this.supervisorName=e,(0,v.network_set_supervisor)(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(0,v.network_delegate)(this._handle,s,o)}async delegateWithSupervisor(e){if(this.assertNotDisposed(),!this.supervisorName)throw new Error("Network supervisor is not set. Call setSupervisor() first.");return(0,v.network_delegate)(this._handle,this.supervisorName,e)}agentCards(){return this.assertNotDisposed(),(0,v.network_agent_cards)(this._handle)}destroy(){this.disposed||(this.disposed=!0,(0,v.destroy_network)(this._handle))}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new x("Network","network")}};var D=require("gauss-napi"),ye=class{_handle;disposed=!1;constructor(){this._handle=(0,D.create_middleware_chain)()}get handle(){return this._handle}useLogging(){return this.assertNotDisposed(),(0,D.middleware_use_logging)(this._handle),this}useCaching(e){return this.assertNotDisposed(),(0,D.middleware_use_caching)(this._handle,e),this}useRateLimit(e,t){return this.assertNotDisposed(),(0,D.middleware_use_rate_limit)(this._handle,e,t),this}destroy(){if(!this.disposed){this.disposed=!0;try{(0,D.destroy_middleware_chain)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("MiddlewareChain has been destroyed")}};var _=require("gauss-napi"),fe=class{_handle;disposed=!1;constructor(){this._handle=(0,_.create_plugin_registry)()}get handle(){return this._handle}addTelemetry(){return this.assertNotDisposed(),(0,_.plugin_registry_add_telemetry)(this._handle),this}addMemory(){return this.assertNotDisposed(),(0,_.plugin_registry_add_memory)(this._handle),this}list(){return this.assertNotDisposed(),(0,_.plugin_registry_list)(this._handle)}emit(e){this.assertNotDisposed(),(0,_.plugin_registry_emit)(this._handle,JSON.stringify(e))}destroy(){if(!this.disposed){this.disposed=!0;try{(0,_.destroy_plugin_registry)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("PluginRegistry has been destroyed")}};var b=require("gauss-napi"),ve=class{_handle;disposed=!1;constructor(e,t){this._handle=(0,b.create_mcp_server)(e,t)}get handle(){return this._handle}addTool(e){this.assertNotDisposed();let t={name:e.name,description:e.description,inputSchema:e.parameters??{type:"object"}};return(0,b.mcp_server_add_tool)(this._handle,JSON.stringify(t)),this}addResource(e){return this.assertNotDisposed(),(0,b.mcpServerAddResource)(this._handle,JSON.stringify(e)),this}addPrompt(e){return this.assertNotDisposed(),(0,b.mcpServerAddPrompt)(this._handle,JSON.stringify(e)),this}async handleMessage(e){return this.assertNotDisposed(),(0,b.mcp_server_handle)(this._handle,JSON.stringify(e))}destroy(){if(!this.disposed){this.disposed=!0;try{(0,b.destroy_mcp_server)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("McpServer has been destroyed")}};var St=require("child_process"),xe=class{config;process=null;connected=!1;closed=!1;nextId=1;pending=new Map;buffer="";serverCapabilities={};cachedTools=null;constructor(e){this.config=e}async connect(){if(this.connected)return;if(this.closed)throw new Error("McpClient has been closed");let e=this.config.timeoutMs??1e4;this.process=(0,St.spawn)(this.config.command,this.config.args??[],{stdio:["pipe","pipe","pipe"],env:{...process.env,...this.config.env}}),this.process.stdout.on("data",r=>this.onData(r)),this.process.stderr.on("data",()=>{}),this.process.on("error",r=>this.onProcessError(r)),this.process.on("close",()=>this.onProcessClose());let t=await this.request("initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"gauss-mcp-client",version:"1.2.0"}},e);this.serverCapabilities=t?.capabilities??{},this.notify("notifications/initialized",{}),this.connected=!0}async listTools(){if(this.assertConnected(),this.cachedTools)return this.cachedTools;let t=((await this.request("tools/list",{}))?.tools??[]).map(r=>({name:r.name,description:r.description??"",parameters:r.inputSchema}));return this.cachedTools=t,t}async callTool(e,t={}){return this.assertConnected(),await this.request("tools/call",{name:e,arguments:t})}async getToolsWithExecutor(){return{tools:await this.listTools(),executor:async r=>{let 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(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 s=this.nextId++,o={jsonrpc:"2.0",id:s,method:e,params:t};return new Promise((i,a)=>{let l=setTimeout(()=>{this.pending.delete(s),a(new Error(`MCP request "${e}" timed out after ${r}ms`))},r);this.pending.set(s,{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.")}};var g=require("gauss-napi"),Te=class{_handle;disposed=!1;constructor(){this._handle=(0,g.create_guardrail_chain)()}get handle(){return this._handle}addContentModeration(e,t=[]){return this.assertNotDisposed(),(0,g.guardrail_chain_add_content_moderation)(this._handle,e,t),this}addPiiDetection(e){return this.assertNotDisposed(),(0,g.guardrail_chain_add_pii_detection)(this._handle,e),this}addTokenLimit(e,t){return this.assertNotDisposed(),(0,g.guardrail_chain_add_token_limit)(this._handle,e,t),this}addRegexFilter(e,t=[]){return this.assertNotDisposed(),(0,g.guardrail_chain_add_regex_filter)(this._handle,e,t),this}addSchema(e){return this.assertNotDisposed(),(0,g.guardrail_chain_add_schema)(this._handle,JSON.stringify(e)),this}list(){return this.assertNotDisposed(),(0,g.guardrail_chain_list)(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,g.destroy_guardrail_chain)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("GuardrailChain has been destroyed")}};var w=require("gauss-napi"),_e=class{_handle;disposed=!1;constructor(){this._handle=(0,w.create_approval_manager)()}get handle(){return this._handle}request(e,t,r){return this.assertNotDisposed(),(0,w.approval_request)(this._handle,e,JSON.stringify(t),r)}approve(e,t){this.assertNotDisposed(),(0,w.approval_approve)(this._handle,e,t?JSON.stringify(t):void 0)}deny(e,t){this.assertNotDisposed(),(0,w.approval_deny)(this._handle,e,t)}listPending(){return this.assertNotDisposed(),(0,w.approval_list_pending)(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,w.destroy_approval_manager)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("ApprovalManager has been destroyed")}};var M=require("gauss-napi"),ke=class{_handle;disposed=!1;constructor(){this._handle=(0,M.create_checkpoint_store)()}get handle(){return this._handle}async save(e){return this.assertNotDisposed(),(0,M.checkpoint_save)(this._handle,JSON.stringify(e))}async load(e){return this.assertNotDisposed(),(0,M.checkpoint_load)(this._handle,e)}async loadLatest(e){return this.assertNotDisposed(),(0,M.checkpoint_load_latest)(this._handle,e)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,M.destroy_checkpoint_store)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("CheckpointStore has been destroyed")}};var O=require("gauss-napi"),be=class{_handle;disposed=!1;constructor(e){this._handle=(0,O.create_eval_runner)(e)}get handle(){return this._handle}addScorer(e){return this.assertNotDisposed(),(0,O.eval_add_scorer)(this._handle,e),this}destroy(){if(!this.disposed){this.disposed=!0;try{(0,O.destroy_eval_runner)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("EvalRunner has been destroyed")}static loadDatasetJsonl(e){return(0,O.load_dataset_jsonl)(e)}static loadDatasetJson(e){return(0,O.load_dataset_json)(e)}};var P=require("gauss-napi"),we=class{_handle;disposed=!1;constructor(){this._handle=(0,P.create_telemetry)()}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;(0,P.telemetry_record_span)(this._handle,JSON.stringify(s))}exportSpans(){return this.assertNotDisposed(),(0,P.telemetry_export_spans)(this._handle)}exportMetrics(){return this.assertNotDisposed(),(0,P.telemetry_export_metrics)(this._handle)}clear(){this.assertNotDisposed(),(0,P.telemetry_clear)(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,P.destroy_telemetry)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Telemetry has been destroyed")}};var Re=require("fs"),It=require("http"),Ht=require("path");var N=require("gauss-napi"),Pe=new Map;function Rt(n,e){Pe.set(n,e)}function Et(n){return Pe.get(n)}function At(){Pe.clear()}function Dt(n){return(0,N.count_tokens)(n)}function Mt(n,e){return(0,N.count_tokens_for_model)(n,e)}function Ot(n){return(0,N.count_message_tokens)(n)}function Nt(n){return(0,N.get_context_window_size)(n)}function Ce(n,e){let t=Pe.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=(0,N.estimate_cost)(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 U=class extends Error{},fr=["openai","anthropic","google","groq","ollama","deepseek","openrouter","together","fireworks","mistral","perplexity","xai"],Se=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=Ce(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=(0,It.createServer)((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 or of p)this.assertChannelAllowed(or);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),H=()=>clearInterval(m);s.on("close",H),s.on("aborted",H);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 U){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&&((0,Re.mkdirSync)((0,Ht.dirname)(this.persistPath),{recursive:!0}),(0,Re.appendFileSync)(this.persistPath,`${JSON.stringify(e)}
|
|
21
|
-
`,"utf8")),e}parseSection(e){if(e==="spans"||e==="metrics"||e==="pendingApprovals"||e==="latestCost")return e;throw new
|
|
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.")}};var g=require("gauss-napi"),Te=class{_handle;disposed=!1;constructor(){this._handle=(0,g.create_guardrail_chain)()}get handle(){return this._handle}addContentModeration(e,t=[]){return this.assertNotDisposed(),(0,g.guardrail_chain_add_content_moderation)(this._handle,e,t),this}addPiiDetection(e){return this.assertNotDisposed(),(0,g.guardrail_chain_add_pii_detection)(this._handle,e),this}addTokenLimit(e,t){return this.assertNotDisposed(),(0,g.guardrail_chain_add_token_limit)(this._handle,e,t),this}addRegexFilter(e,t=[]){return this.assertNotDisposed(),(0,g.guardrail_chain_add_regex_filter)(this._handle,e,t),this}addSchema(e){return this.assertNotDisposed(),(0,g.guardrail_chain_add_schema)(this._handle,JSON.stringify(e)),this}list(){return this.assertNotDisposed(),(0,g.guardrail_chain_list)(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,g.destroy_guardrail_chain)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("GuardrailChain has been destroyed")}};var P=require("gauss-napi"),ke=class{_handle;disposed=!1;constructor(){this._handle=(0,P.create_approval_manager)()}get handle(){return this._handle}request(e,t,r){return this.assertNotDisposed(),(0,P.approval_request)(this._handle,e,JSON.stringify(t),r)}approve(e,t){this.assertNotDisposed(),(0,P.approval_approve)(this._handle,e,t?JSON.stringify(t):void 0)}deny(e,t){this.assertNotDisposed(),(0,P.approval_deny)(this._handle,e,t)}listPending(){return this.assertNotDisposed(),(0,P.approval_list_pending)(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,P.destroy_approval_manager)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("ApprovalManager has been destroyed")}};var O=require("gauss-napi"),_e=class{_handle;disposed=!1;constructor(){this._handle=(0,O.create_checkpoint_store)()}get handle(){return this._handle}async save(e){return this.assertNotDisposed(),(0,O.checkpoint_save)(this._handle,JSON.stringify(e))}async load(e){return this.assertNotDisposed(),(0,O.checkpoint_load)(this._handle,e)}async loadLatest(e){return this.assertNotDisposed(),(0,O.checkpoint_load_latest)(this._handle,e)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,O.destroy_checkpoint_store)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("CheckpointStore has been destroyed")}};var M=require("gauss-napi"),be=class{_handle;disposed=!1;constructor(e){this._handle=(0,M.create_eval_runner)(e)}get handle(){return this._handle}addScorer(e){return this.assertNotDisposed(),(0,M.eval_add_scorer)(this._handle,e),this}destroy(){if(!this.disposed){this.disposed=!0;try{(0,M.destroy_eval_runner)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("EvalRunner has been destroyed")}static loadDatasetJsonl(e){return(0,M.load_dataset_jsonl)(e)}static loadDatasetJson(e){return(0,M.load_dataset_json)(e)}};var w=require("gauss-napi"),Pe=class{_handle;disposed=!1;constructor(){this._handle=(0,w.create_telemetry)()}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;(0,w.telemetry_record_span)(this._handle,JSON.stringify(s))}exportSpans(){return this.assertNotDisposed(),(0,w.telemetry_export_spans)(this._handle)}exportMetrics(){return this.assertNotDisposed(),(0,w.telemetry_export_metrics)(this._handle)}clear(){this.assertNotDisposed(),(0,w.telemetry_clear)(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,w.destroy_telemetry)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Telemetry has been destroyed")}};var Re=require("fs"),It=require("http"),Ht=require("path");var N=require("gauss-napi"),we=new Map;function Rt(n,e){we.set(n,e)}function Et(n){return we.get(n)}function At(){we.clear()}function Dt(n){return(0,N.count_tokens)(n)}function Ot(n,e){return(0,N.count_tokens_for_model)(n,e)}function Mt(n){return(0,N.count_message_tokens)(n)}function Nt(n){return(0,N.get_context_window_size)(n)}function Ce(n,e){let t=we.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),l=(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:l,totalCostUsd:s+o+i+a+l}}let r=(0,N.estimate_cost)(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 j=class extends Error{},fr=["openai","anthropic","google","groq","ollama","deepseek","openrouter","together","fireworks","mistral","perplexity","xai"],Se=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=Ce(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=(0,It.createServer)((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 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 or of p)this.assertChannelAllowed(or);let d=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 y=this.replayStreamEvents(o,p,l,c);if(d&&y>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),Z=()=>clearInterval(u);s.on("close",Z),s.on("aborted",Z);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 j){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((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&&((0,Re.mkdirSync)((0,Ht.dirname)(this.persistPath),{recursive:!0}),(0,Re.appendFileSync)(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(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 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(!fr.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",s=Array.isArray(e.available)?e.available:typeof e.available=="string"?e.available.split(","):[],o=s.length>0?s.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((s,o)=>{if(typeof s!="object"||s===null)throw new m(`Scenario ${o} must be an object`,"scenarios");return this.parsePolicyExplainScenario(s)})}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}
|
|
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(
|
|
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],s=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(s)?s.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 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 W(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:W(this.routingPolicy,o.provider,o.model,o.options)})),s=r.filter(o=>o.explanation.ok).length;return{ok:!0,total:r.length,passed:s,failed:r.length-s,results:r}}opsPolicyExplainSimulation(e){return this.opsPolicyExplainBatch(e)}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 j(`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 j("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 j("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 j("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>
|
|
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>`}};var
|
|
166
|
+
</html>`}};var B=require("gauss-napi");function jt(n){return(0,B.create_fallback_provider)(n)}function Ut(n,e,t){return(0,B.create_circuit_breaker)(n,e,t)}function Ze(n,e,t){return(0,B.create_resilient_provider)(n,e,t)}function Lt(n,e,t=!0){return Ze(n.handle,e.map(r=>r.handle),t)}var Ee=require("gauss-napi");function Jt(n){return(0,Ee.agent_config_from_json)(n)}function Gt(n){return(0,Ee.agent_config_resolve_env)(n)}var z=require("gauss-napi"),Ae=class{_handle;disposed=!1;constructor(e){this._handle=(0,z.create_tool_validator)(e)}get handle(){return this._handle}validate(e,t){return this.assertNotDisposed(),JSON.parse((0,z.tool_validator_validate)(this._handle,JSON.stringify(e),JSON.stringify(t)))}destroy(){if(!this.disposed){this.disposed=!0;try{(0,z.destroy_tool_validator)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("ToolValidator has been destroyed")}};var $t=require("gauss-napi");function Ft(n){return(0,$t.parse_partial_json)(n)}function vr(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 xr(n){return new Promise(e=>setTimeout(e,n))}async function et(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,l=e?.onRetry,p;for(let d=0;d<=t;d++)try{return await n()}catch(c){if(p=c instanceof Error?c:new Error(String(c)),d===t||a&&!a(p,d+1))break;let y=vr({backoff:r,baseDelayMs:s,maxDelayMs:o,jitter:i},d+1);l?.(p,d+1,y),await xr(y)}throw p}function qt(n,e){return t=>et(()=>n.run(t),e)}function Tr(n,e){let t=JSON.stringify(e,null,2);return`${n}
|
|
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
|
|
171
|
+
Do not include any text outside the JSON object.`}function kr(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,l=!1,p=!1;for(let d=s;d<n.length;d++){let c=n[d];if(p){p=!1;continue}if(c==="\\"){p=!0;continue}if(c==='"'){l=!l;continue}if(!l&&(c===n[s]&&a++,c===i&&(a--,a===0)))return n.slice(s,d+1)}return n.slice(s)}async function Bt(n,e,t){let r=t.maxParseRetries??2,s=typeof e=="string"?Tr(e,t.schema):e,o;for(let i=0;i<=r;i++){let a=i===0?s:typeof s=="string"?`${s}
|
|
172
172
|
|
|
173
|
-
Previous attempt failed: ${o?.message}. Please output ONLY valid JSON.`:s,
|
|
173
|
+
Previous attempt failed: ${o?.message}. Please output ONLY valid JSON.`:s,l=await n.run(a);try{let p=kr(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 zt=/\{\{(\w+)\}\}/g;function U(n){let e=[...new Set(Array.from(n.matchAll(zt),r=>r[1]))],t=r=>n.replace(zt,(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 Kt=U(`Summarize the following {{format}} in {{style}}:
|
|
174
174
|
|
|
175
|
-
{{text}}`),Vt=
|
|
175
|
+
{{text}}`),Vt=U(`Translate the following text to {{language}}:
|
|
176
176
|
|
|
177
|
-
{{text}}`),Wt=
|
|
177
|
+
{{text}}`),Wt=U("Review this {{language}} code for bugs, security issues, and best practices:\n\n```{{language}}\n{{code}}\n```"),Yt=U(`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.`),Xt=
|
|
181
|
+
Respond with only the category name.`),Xt=U(`Extract the following information from the text: {{fields}}
|
|
182
182
|
|
|
183
183
|
Text: {{text}}
|
|
184
184
|
|
|
185
|
-
Respond as JSON.`);var
|
|
185
|
+
Respond as JSON.`);var K=require("gauss-napi"),Y=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=(0,K.parseAgentsMd)(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}}}},De=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=(0,K.parseSkillMd)(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 Qt(n){let e=(0,K.discoverAgents)(n);return(typeof e=="string"?JSON.parse(e):e).map(r=>Object.assign(Object.create(Y.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 Zt(n,...e){let t=n;for(let r of e)t=await r(t);return t}async function tt(n,e,t){let r=t?.concurrency??n.length,s=new Array(n.length),o=n.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;s[a.index]=await e(a.item,a.index)}});return await Promise.all(i),s}async function er(n,e,t){let r=await tt(n,e,t);return n.filter((s,o)=>r[o])}async function tr(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 rr(n,e){for(let t=0;t<n.length;t++)await e(n[t],t);return n}function nr(...n){return async e=>{let t=e;for(let r of n)t=await r(t);return t}}var rt=ur(require("gauss-napi"),1);function X(n){let e=rt[n];if(typeof e=="function")return e;let t=rt.default?.[n];if(typeof t=="function")return t;throw new TypeError(`gauss-napi is missing ${n}`)}function Q(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 Oe=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 X("a2aDiscover")(this.baseUrl,this.authToken??void 0)}catch(e){if(!Q(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 X("a2aSendMessage")(this.baseUrl,this.authToken??void 0,JSON.stringify(e),t?JSON.stringify(t):void 0)}catch(i){if(!Q(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 X("a2aAsk")(this.baseUrl,this.authToken??void 0,e)}catch(t){if(!Q(t))throw t;let r=await this.sendMessage(nt(e));if(r.type==="message")return Ie(r.message);let s=Me(r.task);if(s)return s;let o=await this.getTask(r.task.id);return Me(o)??""}}async getTask(e,t){try{return await X("a2aGetTask")(this.baseUrl,this.authToken??void 0,e,t??void 0)}catch(r){if(!Q(r))throw r;return this.rpc("tasks/get",{id:e,historyLength:t??void 0})}}async cancelTask(e){try{return await X("a2aCancelTask")(this.baseUrl,this.authToken??void 0,e)}catch(t){if(!Q(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 Ne(n,e){return{role:n,parts:[{type:"text",text:e}]}}function nt(n){return Ne("user",n)}function sr(n){return Ne("agent",n)}function Ie(n){return n.parts.filter(e=>e.type==="text"&&e.text).map(e=>e.text).join("")}function Me(n){if(n.status.message)return Ie(n.status.message)}var C=require("gauss-napi"),He=class{_handle;disposed=!1;constructor(){this._handle=(0,C.createToolRegistry)()}get handle(){return this._handle}add(e){return this.assertNotDisposed(),(0,C.toolRegistryAdd)(this._handle,JSON.stringify(e)),this}search(e){return this.assertNotDisposed(),(0,C.toolRegistrySearch)(this._handle,e)}byTag(e){return this.assertNotDisposed(),(0,C.toolRegistryByTag)(this._handle,e)}list(){return this.assertNotDisposed(),(0,C.toolRegistryList)(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,C.destroyToolRegistry)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("ToolRegistry has been destroyed")}};0&&(module.exports={A2aClient,ANTHROPIC_DEFAULT,ANTHROPIC_FAST,ANTHROPIC_PREMIUM,Agent,AgentSpec,AgentStream,ApprovalManager,CheckpointStore,ControlPlane,DEEPSEEK_DEFAULT,DEEPSEEK_REASONING,DisposedError,EvalRunner,FIREWORKS_DEFAULT,GOOGLE_DEFAULT,GOOGLE_IMAGE,GOOGLE_PREMIUM,GaussError,Graph,GuardrailChain,MISTRAL_DEFAULT,McpClient,McpServer,Memory,MiddlewareChain,Network,OPENAI_DEFAULT,OPENAI_FAST,OPENAI_IMAGE,OPENAI_REASONING,OPENROUTER_DEFAULT,PERPLEXITY_DEFAULT,PROVIDER_DEFAULTS,PluginRegistry,ProviderError,SkillSpec,TOGETHER_DEFAULT,Team,Telemetry,TextSplitter,ToolExecutionError,ToolRegistry,ToolValidator,ValidationError,VectorStore,Workflow,XAI_DEFAULT,agentMessage,applyGovernancePack,availableRuntimes,batch,classify,clearPricing,codeReview,compose,countMessageTokens,countTokens,countTokensForModel,createCircuitBreaker,createFallbackProvider,createResilientAgent,createResilientProvider,createToolExecutor,defaultModel,detectProvider,discoverAgents,enforceRoutingCostLimit,enforceRoutingGovernance,enforceRoutingRateLimit,enforceRoutingTimeWindow,enterprisePreset,enterpriseRun,estimateCost,executeCode,explainRoutingTarget,extract,extractText,filterAsync,gauss,generateImage,getContextWindowSize,getPricing,governancePolicyPack,isTypedTool,loadJson,loadMarkdown,loadText,mapAsync,parseAgentConfig,parsePartialJson,pipe,reduceAsync,resolveApiKey,resolveEnv,resolveFallbackProvider,resolveRoutingTarget,retryable,setPricing,splitText,structured,summarize,tapAsync,taskText,template,textMessage,tool,translate,userMessage,version,withRetry});
|
|
186
186
|
//# sourceMappingURL=index.cjs.map
|