gauss-ts 2.0.21 → 2.0.22
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 +5 -1
- package/dist/index.cjs +16 -16
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +12 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +17 -17
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -236,7 +236,11 @@ console.log(explanation.decision?.selectedBy); // "direct" | "alias:..." | "fall
|
|
|
236
236
|
// GET /api/ops/policy/lifecycle/promote?version=policy-v1&role=promoter|operator|admin
|
|
237
237
|
// GET /api/ops/policy/lifecycle/versions
|
|
238
238
|
// Policy drift monitoring:
|
|
239
|
-
//
|
|
239
|
+
// cp.registerPolicyDriftSink("webhook://ops-audit");
|
|
240
|
+
// GET /api/ops/policy/drift?scenarios=<json>&candidatePolicy=<json>&window=last_24h&maxRegressions=0
|
|
241
|
+
// GET /api/ops/policy/drift/schedule/set?scenarios=<json>&candidatePolicy=<json>&window=last_1h&intervalMs=60000
|
|
242
|
+
// GET /api/ops/policy/drift/schedule
|
|
243
|
+
// GET /api/ops/policy/drift/schedule/run
|
|
240
244
|
```
|
|
241
245
|
|
|
242
246
|
### Unified Control Plane (M51 foundation)
|
package/dist/index.cjs
CHANGED
|
@@ -1,28 +1,28 @@
|
|
|
1
|
-
"use strict";var dr=Object.create;var te=Object.defineProperty;var pr=Object.getOwnPropertyDescriptor;var cr=Object.getOwnPropertyNames;var ur=Object.getPrototypeOf,mr=Object.prototype.hasOwnProperty;var hr=(s,e)=>{for(var t in e)te(s,t,{get:e[t],enumerable:!0})},at=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of cr(e))!mr.call(s,n)&&n!==t&&te(s,n,{get:()=>e[n],enumerable:!(r=pr(e,n))||r.enumerable});return s};var gr=(s,e,t)=>(t=s!=null?dr(ur(s)):{},at(e||!s||!s.__esModule?te(t,"default",{value:s,enumerable:!0}):t,s)),yr=s=>at(te({},"__esModule",{value:!0}),s);var _r={};hr(_r,{A2aClient:()=>Ne,ANTHROPIC_DEFAULT:()=>Ge,ANTHROPIC_FAST:()=>ct,ANTHROPIC_PREMIUM:()=>ut,Agent:()=>f,AgentSpec:()=>Q,AgentStream:()=>q,ApprovalManager:()=>we,CheckpointStore:()=>_e,ControlPlane:()=>Ae,DEEPSEEK_DEFAULT:()=>$e,DEEPSEEK_REASONING:()=>gt,DisposedError:()=>x,EvalRunner:()=>Ce,FIREWORKS_DEFAULT:()=>qe,GOOGLE_DEFAULT:()=>Je,GOOGLE_IMAGE:()=>ht,GOOGLE_PREMIUM:()=>mt,GaussError:()=>L,Graph:()=>ge,GuardrailChain:()=>ke,MISTRAL_DEFAULT:()=>Fe,McpClient:()=>Te,McpServer:()=>be,Memory:()=>me,MiddlewareChain:()=>xe,Network:()=>ve,OPENAI_DEFAULT:()=>G,OPENAI_FAST:()=>lt,OPENAI_IMAGE:()=>pt,OPENAI_REASONING:()=>dt,OPENROUTER_DEFAULT:()=>Be,PERPLEXITY_DEFAULT:()=>ze,PROVIDER_DEFAULTS:()=>W,PluginRegistry:()=>Pe,ProviderError:()=>re,SkillSpec:()=>Me,TOGETHER_DEFAULT:()=>Ve,Team:()=>fe,Telemetry:()=>Re,TextSplitter:()=>j,ToolExecutionError:()=>ne,ToolRegistry:()=>Ue,ToolValidator:()=>Ie,ValidationError:()=>u,VectorStore:()=>he,Workflow:()=>ye,XAI_DEFAULT:()=>Ke,agentMessage:()=>ar,applyGovernancePack:()=>ft,availableRuntimes:()=>wt,batch:()=>Tt,classify:()=>Zt,clearPricing:()=>It,codeReview:()=>Xt,compose:()=>ir,countMessageTokens:()=>Lt,countTokens:()=>Mt,countTokensForModel:()=>Nt,createCircuitBreaker:()=>Jt,createFallbackProvider:()=>Gt,createResilientAgent:()=>Bt,createResilientProvider:()=>rt,createToolExecutor:()=>ce,defaultModel:()=>yt,detectProvider:()=>B,discoverAgents:()=>tr,enforceRoutingCostLimit:()=>se,enforceRoutingGovernance:()=>$,enforceRoutingRateLimit:()=>oe,enforceRoutingTimeWindow:()=>ie,enterprisePreset:()=>Qe,enterpriseRun:()=>bt,estimateCost:()=>Ee,evaluatePolicyDiff:()=>Y,evaluatePolicyGate:()=>ae,evaluatePolicyRolloutGuardrails:()=>le,executeCode:()=>kt,explainRoutingTarget:()=>H,extract:()=>er,extractText:()=>je,filterAsync:()=>nr,gauss:()=>Pt,generateImage:()=>_t,getContextWindowSize:()=>Ht,getPricing:()=>Ot,governancePolicyPack:()=>We,isTypedTool:()=>pe,loadJson:()=>Et,loadMarkdown:()=>St,loadText:()=>tt,mapAsync:()=>st,parseAgentConfig:()=>$t,parsePartialJson:()=>Ft,pipe:()=>rr,reduceAsync:()=>sr,resolveApiKey:()=>J,resolveEnv:()=>Vt,resolveFallbackProvider:()=>Ye,resolveRoutingTarget:()=>V,retryable:()=>zt,setPricing:()=>Dt,splitText:()=>Rt,structured:()=>Kt,summarize:()=>Yt,tapAsync:()=>or,taskText:()=>Le,template:()=>U,textMessage:()=>He,tool:()=>de,translate:()=>Qt,userMessage:()=>it,version:()=>Xe.version,withRetry:()=>nt});module.exports=yr(_r);var L=class extends Error{code;constructor(e,t){super(t),this.name="GaussError",this.code=e}},x=class extends L{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}},re=class extends L{provider;constructor(e,t){super("PROVIDER_ERROR",`[${e}] ${t}`),this.name="ProviderError",this.provider=e}},ne=class extends L{toolName;cause;constructor(e,t,r){super("TOOL_EXECUTION_ERROR",`Tool "${e}" failed: ${t}`),this.name="ToolExecutionError",this.toolName=e,this.cause=r}},u=class extends L{field;constructor(e,t){super("VALIDATION_ERROR",t?`Invalid "${t}": ${e}`:e),this.name="ValidationError",this.field=t}};var G="gpt-5.2",lt="gpt-4.1",dt="o4-mini",pt="gpt-image-1",Ge="claude-sonnet-4-20250514",ct="claude-haiku-4-20250414",ut="claude-opus-4-20250414",Je="gemini-2.5-flash",mt="gemini-2.5-pro",ht="gemini-2.0-flash",Be="openai/gpt-5.2",$e="deepseek-chat",gt="deepseek-reasoner",Ve="meta-llama/Llama-3.3-70B-Instruct-Turbo",qe="accounts/fireworks/models/llama-v3p1-70b-instruct",Fe="mistral-large-latest",ze="sonar-pro",Ke="grok-3-beta",W={openai:G,anthropic:Ge,google:Je,openrouter:Be,deepseek:$e,groq:"llama-3.3-70b-versatile",ollama:"llama3.2",together:Ve,fireworks:qe,mistral:Fe,perplexity:ze,xai:Ke};function yt(s){return W[s]??G}var fr={openai:"OPENAI_API_KEY",anthropic:"ANTHROPIC_API_KEY",google:"GOOGLE_API_KEY",groq:"GROQ_API_KEY",deepseek:"DEEPSEEK_API_KEY",openrouter:"OPENROUTER_API_KEY",together:"TOGETHER_API_KEY",fireworks:"FIREWORKS_API_KEY",mistral:"MISTRAL_API_KEY",perplexity:"PERPLEXITY_API_KEY",xai:"XAI_API_KEY",ollama:""};function J(s){let e=fr[s]??"";return e?(typeof process<"u"?process.env[e]:"")??"":""}function B(){let s=[{env:"OPENAI_API_KEY",provider:"openai"},{env:"ANTHROPIC_API_KEY",provider:"anthropic"},{env:"GOOGLE_API_KEY",provider:"google"},{env:"GROQ_API_KEY",provider:"groq"},{env:"DEEPSEEK_API_KEY",provider:"deepseek"},{env:"OPENROUTER_API_KEY",provider:"openrouter"},{env:"TOGETHER_API_KEY",provider:"together"},{env:"FIREWORKS_API_KEY",provider:"fireworks"},{env:"MISTRAL_API_KEY",provider:"mistral"},{env:"PERPLEXITY_API_KEY",provider:"perplexity"},{env:"XAI_API_KEY",provider:"xai"}];for(let{env:e,provider:t}of s)if(typeof process<"u"&&process.env[e])return{provider:t,model:W[t]}}var g=require("gauss-napi");function We(s){switch(s){case"enterprise-strict":return{rules:[{type:"allow_provider",provider:"openai"},{type:"allow_provider",provider:"anthropic"},{type:"require_tag",tag:"pci"}]};case"eu-residency":return{rules:[{type:"deny_provider",provider:"xai"},{type:"require_tag",tag:"eu"}]};case"cost-guarded":return{rules:[{type:"allow_provider",provider:"openai"},{type:"allow_provider",provider:"deepseek"},{type:"require_tag",tag:"cost-sensitive"}],maxTotalCostUsd:.15};case"ops-business-hours":return{rules:[{type:"require_tag",tag:"ops"}],allowedHoursUtc:Array.from({length:11},(e,t)=>t+8)};case"balanced-mix":return{rules:[{type:"allow_provider",provider:"openai"},{type:"allow_provider",provider:"anthropic"},{type:"require_tag",tag:"balanced"}],providerWeights:{openai:60,anthropic:40}};case"rollout-canary":return{rules:[{type:"allow_provider",provider:"openai"},{type:"allow_provider",provider:"anthropic"},{type:"require_tag",tag:"rollout"}],maxTotalCostUsd:.1,maxRequestsPerMinute:30,fallbackOrder:["openai","anthropic"],providerWeights:{openai:70,anthropic:30}};case"rollout-strict":return{rules:[{type:"allow_provider",provider:"openai"},{type:"allow_provider",provider:"anthropic"},{type:"require_tag",tag:"rollout"},{type:"require_tag",tag:"approved"}],maxTotalCostUsd:.08,maxRequestsPerMinute:15,allowedHoursUtc:Array.from({length:9},(e,t)=>t+9),fallbackOrder:["openai","anthropic"]}}}function ft(s,e){let t=We(e),r=s?.governance?.rules??[],n=t.fallbackOrder?[...new Set([...s?.fallbackOrder??[],...t.fallbackOrder])]:s?.fallbackOrder,o=t.providerWeights?{...s?.providerWeights??{},...t.providerWeights}:s?.providerWeights;return{...s,maxTotalCostUsd:t.maxTotalCostUsd??s?.maxTotalCostUsd,maxRequestsPerMinute:t.maxRequestsPerMinute??s?.maxRequestsPerMinute,allowedHoursUtc:t.allowedHoursUtc??s?.allowedHoursUtc,fallbackOrder:n,providerWeights:o,governance:{rules:[...r,...t.rules]}}}function se(s,e){if(s?.maxTotalCostUsd!==void 0&&e>s.maxTotalCostUsd)throw new Error(`routing policy rejected cost ${e}`)}function oe(s,e){if(s?.maxRequestsPerMinute!==void 0&&e>s.maxRequestsPerMinute)throw new Error(`routing policy rejected rate ${e}`)}function ie(s,e){let t=s?.allowedHoursUtc;if(!(!t||t.length===0)&&(!Number.isInteger(e)||e<0||e>23||!t.includes(e)))throw new Error(`routing policy rejected hour ${e}`)}function $(s,e,t){let r=s?.governance?.rules??[];if(r.length===0)return;let n=r.filter(o=>o.type==="allow_provider").map(o=>o.provider);if(n.length>0&&!n.includes(e))throw new Error(`routing policy governance rejected provider ${e}`);for(let o of r){if(o.type==="deny_provider"&&o.provider===e)throw new Error(`routing policy governance rejected provider ${e}`);if(o.type==="require_tag"&&t!==void 0&&!t.includes(o.tag))throw new Error(`routing policy governance missing tag ${o.tag}`)}}function Ye(s,e){let t=s?.fallbackOrder;if(!t||t.length===0||e.length===0)return null;let r=new Set(e);for(let n of t)if(r.has(n))return n;return null}function V(s,e,t,r={}){let n=r.governanceTags,o=r.currentHourUtc??new Date().getUTCHours();ie(s,o),r.estimatedCostUsd!==void 0&&se(s,r.estimatedCostUsd),r.currentRequestsPerMinute!==void 0&&oe(s,r.currentRequestsPerMinute);let i=d=>d.length===1?d[0]:[...d].sort((p,c)=>{let h=s?.providerWeights?.[c.provider]??0,m=s?.providerWeights?.[p.provider]??0;return h!==m?h-m:(c.priority??0)-(p.priority??0)})[0],a=s?.aliases?.[t];if(a&&a.length>0){let d=[...a].sort((m,ee)=>(ee.priority??0)-(m.priority??0)),p=r.availableProviders;if(!p||p.length===0){let m=i(d);return $(s,m.provider,n),{provider:m.provider,model:m.model,selectedBy:`alias:${t}`}}let c=new Set(p),h=d.filter(m=>c.has(m.provider));if(h.length>0){let m=i(h);return $(s,m.provider,n),{provider:m.provider,model:m.model,selectedBy:`alias:${t}`}}}let l=Ye(s,r.availableProviders??[]);return l&&l!==e?($(s,l,n),{provider:l,model:t,selectedBy:`fallback:${l}`}):($(s,e,n),{provider:e,model:t,selectedBy:"direct"})}function H(s,e,t,r={}){let n=[],o=r.currentHourUtc??new Date().getUTCHours(),i=(a,l)=>{let d=l instanceof Error?l.message:String(l);return n.push({check:a,status:"failed",detail:d}),{ok:!1,checks:n,error:d}};if(s?.allowedHoursUtc&&s.allowedHoursUtc.length>0)try{ie(s,o),n.push({check:"time_window",status:"passed",detail:`hour=${o}`})}catch(a){return i("time_window",a)}else n.push({check:"time_window",status:"skipped",detail:"not configured"});if(r.estimatedCostUsd!==void 0)try{se(s,r.estimatedCostUsd),n.push({check:"cost_limit",status:"passed",detail:`cost=${r.estimatedCostUsd}`})}catch(a){return i("cost_limit",a)}else n.push({check:"cost_limit",status:"skipped",detail:"no estimate provided"});if(r.currentRequestsPerMinute!==void 0)try{oe(s,r.currentRequestsPerMinute),n.push({check:"rate_limit",status:"passed",detail:`rpm=${r.currentRequestsPerMinute}`})}catch(a){return i("rate_limit",a)}else n.push({check:"rate_limit",status:"skipped",detail:"no rpm provided"});try{let a=V(s,e,t,r);return n.push({check:"governance",status:"passed",detail:"accepted"}),n.push({check:"selection",status:"passed",detail:a.selectedBy}),{ok:!0,decision:a,checks:n}}catch(a){let l=a instanceof Error?a.message:String(a);return l.includes("governance")?(n.push({check:"governance",status:"failed",detail:l}),n.push({check:"selection",status:"skipped",detail:"selection aborted"}),{ok:!1,checks:n,error:l}):i("selection",a)}}function ae(s,e){let t=e.map(o=>H(s,o.provider,o.model,o.options??{})),r=t.map((o,i)=>({result:o,index:i})).filter(o=>!o.result.ok).map(o=>o.index),n=r.length;return{total:t.length,passed:t.length-n,failed:n,failedIndexes:r,results:t}}function Y(s,e,t=void 0){let r=e.map((o,i)=>{let a=H(t,o.provider,o.model,o.options??{}),l=H(s,o.provider,o.model,o.options??{}),d=a.ok!==l.ok||a.decision?.provider!==l.decision?.provider||a.decision?.model!==l.decision?.model||a.decision?.selectedBy!==l.decision?.selectedBy||a.error!==l.error;return{index:i,input:{provider:o.provider,model:o.model},baseline:a,candidate:l,changed:d}}),n=r.filter(o=>o.baseline.ok&&!o.candidate.ok).length;return{total:r.length,baselinePassed:r.filter(o=>o.baseline.ok).length,candidatePassed:r.filter(o=>o.candidate.ok).length,changed:r.filter(o=>o.changed).length,regressions:n,results:r}}function le(s,e={}){let t=[],r=e.maxChanged??s.total,n=e.maxRegressions??0,o=e.minCandidatePassRate??1,i=s.total===0?1:s.candidatePassed/s.total;t.push({check:"changed_budget",status:s.changed<=r?"passed":"failed",detail:`changed=${s.changed}, limit=${r}`}),t.push({check:"regression_budget",status:s.regressions<=n?"passed":"failed",detail:`regressions=${s.regressions}, limit=${n}`}),t.push({check:"candidate_pass_rate",status:i>=o?"passed":"failed",detail:`candidate_pass_rate=${i.toFixed(3)}, min=${o.toFixed(3)}`});let a=t.find(l=>l.status==="failed");return a?{ok:!1,checks:t,error:a.detail}:{ok:!0,checks:t}}var vt=require("gauss-napi");function vr(s){return{...s,citations:s.citations?.map(e=>({type:e.citationType??e.type,citedText:e.citedText,documentTitle:e.documentTitle,start:e.start,end:e.end}))}}var q=class{constructor(e,t,r,n,o,i){this.agentName=e;this.providerHandle=t;this.tools=r;this.messages=n;this.options=o;this.toolExecutor=i}_result;get result(){return this._result}async*[Symbol.asyncIterator](){let e=[],t,r=!1,n=i=>{try{e.push(JSON.parse(i))}catch{e.push({type:"raw",text:i})}t?.()},o=(0,vt.agent_stream_with_tool_executor)(this.agentName,this.providerHandle,this.tools,this.messages,this.options,n,this.toolExecutor).then(i=>{this._result=vr(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 de(s){return{name:s.name,description:s.description,parameters:s.parameters,execute:s.execute}}function pe(s){return typeof s.execute=="function"}function ce(s,e){let t=new Map(s.map(r=>[r.name,r]));return async r=>{let n;try{n=JSON.parse(r)}catch{return JSON.stringify({error:"Invalid tool call JSON"})}let o=n.tool??n.name??"",i=t.get(o);if(!i)return e?e(r):JSON.stringify({error:`Unknown tool: ${o}`});try{let a=n.args??n.arguments??{},l=await i.execute(a);return typeof l=="string"?l:JSON.stringify(l)}catch(a){let l=a instanceof Error?a.message:String(a);return JSON.stringify({error:`Tool "${o}" failed: ${l}`})}}}function ue(s){return{...s,citations:s.citations?.map(e=>({type:e.citationType??e.type??"unknown",citedText:e.citedText,documentTitle:e.documentTitle,start:e.start,end:e.end}))}}var f=class s{providerHandle;_name;_requestedProvider;_requestedModel;_provider;_model;_routingPolicy;_providerOptions;_instructions;_tools=[];_options={};disposed=!1;_middleware=null;_guardrails=null;_memory=null;_sessionId="";_mcpClients=[];_mcpToolsLoaded=!1;constructor(e={}){let t=B(),r=e.provider??t?.provider??"openai",n=e.model??t?.model??G;this._requestedProvider=r,this._requestedModel=n,this._routingPolicy=e.routingPolicy;let o=V(this._routingPolicy,r,n);this._provider=o.provider,this._model=o.model,this._name=e.name??"agent",this._instructions=e.instructions??"";let i=e.providerOptions?.apiKey??J(this._provider);this._providerOptions={apiKey:i,...e.providerOptions},this.providerHandle=(0,g.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 s(e)}get name(){return this._name}get provider(){return this._provider}get model(){return this._model}get instructions(){return this._instructions}get handle(){return this.providerHandle}get capabilities(){return(0,g.get_provider_capabilities)(this.providerHandle)}addTool(e){return this._tools.push(e),this}addTools(e){return this._tools.push(...e),this}withTool(e,t,r,n){return this._tools.push(de({name:e,description:t,parameters:n??{},execute:r})),this}setOptions(e){return this._options={...this._options,...e},this}withModel(e){return this.assertNotDisposed(),new s({...this.toConfig(),model:e})}withRoutingContext(e){this.assertNotDisposed();let t=V(this._routingPolicy,this._requestedProvider,this._requestedModel,e);return new s({...this.toConfig(),provider:t.provider,model:t.model})}withMiddleware(e){return this._middleware=e,this}withGuardrails(e){return this._guardrails=e,this}withMemory(e,t){return this._memory=e,t&&(this._sessionId=t),this}useMcpServer(e){return this._mcpClients.push(e),this._mcpToolsLoaded=!1,this}async run(e){this.assertNotDisposed(),await this.ensureMcpTools();let t=typeof e=="string"?[{role:"user",content:e}]:[...e];if(this._memory){let i=await this._memory.recall(this._sessionId?{sessionId:this._sessionId}:void 0);i.length>0&&(t=[{role:"system",content:`Previous context:
|
|
1
|
+
"use strict";var dr=Object.create;var te=Object.defineProperty;var cr=Object.getOwnPropertyDescriptor;var pr=Object.getOwnPropertyNames;var ur=Object.getPrototypeOf,hr=Object.prototype.hasOwnProperty;var mr=(o,e)=>{for(var t in e)te(o,t,{get:e[t],enumerable:!0})},at=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of pr(e))!hr.call(o,n)&&n!==t&&te(o,n,{get:()=>e[n],enumerable:!(r=cr(e,n))||r.enumerable});return o};var gr=(o,e,t)=>(t=o!=null?dr(ur(o)):{},at(e||!o||!o.__esModule?te(t,"default",{value:o,enumerable:!0}):t,o)),yr=o=>at(te({},"__esModule",{value:!0}),o);var Cr={};mr(Cr,{A2aClient:()=>Ne,ANTHROPIC_DEFAULT:()=>Ge,ANTHROPIC_FAST:()=>pt,ANTHROPIC_PREMIUM:()=>ut,Agent:()=>f,AgentSpec:()=>X,AgentStream:()=>F,ApprovalManager:()=>ke,CheckpointStore:()=>Ce,ControlPlane:()=>Ae,DEEPSEEK_DEFAULT:()=>Be,DEEPSEEK_REASONING:()=>gt,DisposedError:()=>P,EvalRunner:()=>Re,FIREWORKS_DEFAULT:()=>qe,GOOGLE_DEFAULT:()=>Ve,GOOGLE_IMAGE:()=>mt,GOOGLE_PREMIUM:()=>ht,GaussError:()=>L,Graph:()=>ge,GuardrailChain:()=>we,MISTRAL_DEFAULT:()=>Fe,McpClient:()=>Te,McpServer:()=>be,Memory:()=>he,MiddlewareChain:()=>Pe,Network:()=>ve,OPENAI_DEFAULT:()=>V,OPENAI_FAST:()=>lt,OPENAI_IMAGE:()=>ct,OPENAI_REASONING:()=>dt,OPENROUTER_DEFAULT:()=>Je,PERPLEXITY_DEFAULT:()=>ze,PROVIDER_DEFAULTS:()=>Y,PluginRegistry:()=>xe,ProviderError:()=>re,SkillSpec:()=>Me,TOGETHER_DEFAULT:()=>$e,Team:()=>fe,Telemetry:()=>Se,TextSplitter:()=>j,ToolExecutionError:()=>ne,ToolRegistry:()=>Ue,ToolValidator:()=>Oe,ValidationError:()=>u,VectorStore:()=>me,Workflow:()=>ye,XAI_DEFAULT:()=>We,agentMessage:()=>ar,applyGovernancePack:()=>ft,availableRuntimes:()=>kt,batch:()=>Tt,classify:()=>Zt,clearPricing:()=>Ot,codeReview:()=>Xt,compose:()=>ir,countMessageTokens:()=>Lt,countTokens:()=>Mt,countTokensForModel:()=>Nt,createCircuitBreaker:()=>Vt,createFallbackProvider:()=>Gt,createResilientAgent:()=>Jt,createResilientProvider:()=>rt,createToolExecutor:()=>pe,defaultModel:()=>yt,detectProvider:()=>B,discoverAgents:()=>tr,enforceRoutingCostLimit:()=>se,enforceRoutingGovernance:()=>$,enforceRoutingRateLimit:()=>oe,enforceRoutingTimeWindow:()=>ie,enterprisePreset:()=>Qe,enterpriseRun:()=>bt,estimateCost:()=>Ee,evaluatePolicyDiff:()=>Q,evaluatePolicyGate:()=>ae,evaluatePolicyRolloutGuardrails:()=>le,executeCode:()=>wt,explainRoutingTarget:()=>H,extract:()=>er,extractText:()=>je,filterAsync:()=>nr,gauss:()=>xt,generateImage:()=>Ct,getContextWindowSize:()=>Ht,getPricing:()=>It,governancePolicyPack:()=>Ke,isTypedTool:()=>ce,loadJson:()=>Et,loadMarkdown:()=>_t,loadText:()=>tt,mapAsync:()=>st,parseAgentConfig:()=>Bt,parsePartialJson:()=>Ft,pipe:()=>rr,reduceAsync:()=>sr,resolveApiKey:()=>J,resolveEnv:()=>$t,resolveFallbackProvider:()=>Ye,resolveRoutingTarget:()=>q,retryable:()=>zt,setPricing:()=>Dt,splitText:()=>St,structured:()=>Wt,summarize:()=>Yt,tapAsync:()=>or,taskText:()=>Le,template:()=>U,textMessage:()=>He,tool:()=>de,translate:()=>Qt,userMessage:()=>it,version:()=>Xe.version,withRetry:()=>nt});module.exports=yr(Cr);var L=class extends Error{code;constructor(e,t){super(t),this.name="GaussError",this.code=e}},P=class extends L{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}},re=class extends L{provider;constructor(e,t){super("PROVIDER_ERROR",`[${e}] ${t}`),this.name="ProviderError",this.provider=e}},ne=class extends L{toolName;cause;constructor(e,t,r){super("TOOL_EXECUTION_ERROR",`Tool "${e}" failed: ${t}`),this.name="ToolExecutionError",this.toolName=e,this.cause=r}},u=class extends L{field;constructor(e,t){super("VALIDATION_ERROR",t?`Invalid "${t}": ${e}`:e),this.name="ValidationError",this.field=t}};var V="gpt-5.2",lt="gpt-4.1",dt="o4-mini",ct="gpt-image-1",Ge="claude-sonnet-4-20250514",pt="claude-haiku-4-20250414",ut="claude-opus-4-20250414",Ve="gemini-2.5-flash",ht="gemini-2.5-pro",mt="gemini-2.0-flash",Je="openai/gpt-5.2",Be="deepseek-chat",gt="deepseek-reasoner",$e="meta-llama/Llama-3.3-70B-Instruct-Turbo",qe="accounts/fireworks/models/llama-v3p1-70b-instruct",Fe="mistral-large-latest",ze="sonar-pro",We="grok-3-beta",Y={openai:V,anthropic:Ge,google:Ve,openrouter:Je,deepseek:Be,groq:"llama-3.3-70b-versatile",ollama:"llama3.2",together:$e,fireworks:qe,mistral:Fe,perplexity:ze,xai:We};function yt(o){return Y[o]??V}var fr={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(o){let e=fr[o]??"";return e?(typeof process<"u"?process.env[e]:"")??"":""}function B(){let o=[{env:"OPENAI_API_KEY",provider:"openai"},{env:"ANTHROPIC_API_KEY",provider:"anthropic"},{env:"GOOGLE_API_KEY",provider:"google"},{env:"GROQ_API_KEY",provider:"groq"},{env:"DEEPSEEK_API_KEY",provider:"deepseek"},{env:"OPENROUTER_API_KEY",provider:"openrouter"},{env:"TOGETHER_API_KEY",provider:"together"},{env:"FIREWORKS_API_KEY",provider:"fireworks"},{env:"MISTRAL_API_KEY",provider:"mistral"},{env:"PERPLEXITY_API_KEY",provider:"perplexity"},{env:"XAI_API_KEY",provider:"xai"}];for(let{env:e,provider:t}of o)if(typeof process<"u"&&process.env[e])return{provider:t,model:Y[t]}}var g=require("gauss-napi");function Ke(o){switch(o){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"}],maxTotalCostUsd:.15};case"ops-business-hours":return{rules:[{type:"require_tag",tag:"ops"}],allowedHoursUtc:Array.from({length:11},(e,t)=>t+8)};case"balanced-mix":return{rules:[{type:"allow_provider",provider:"openai"},{type:"allow_provider",provider:"anthropic"},{type:"require_tag",tag:"balanced"}],providerWeights:{openai:60,anthropic:40}};case"rollout-canary":return{rules:[{type:"allow_provider",provider:"openai"},{type:"allow_provider",provider:"anthropic"},{type:"require_tag",tag:"rollout"}],maxTotalCostUsd:.1,maxRequestsPerMinute:30,fallbackOrder:["openai","anthropic"],providerWeights:{openai:70,anthropic:30}};case"rollout-strict":return{rules:[{type:"allow_provider",provider:"openai"},{type:"allow_provider",provider:"anthropic"},{type:"require_tag",tag:"rollout"},{type:"require_tag",tag:"approved"}],maxTotalCostUsd:.08,maxRequestsPerMinute:15,allowedHoursUtc:Array.from({length:9},(e,t)=>t+9),fallbackOrder:["openai","anthropic"]}}}function ft(o,e){let t=Ke(e),r=o?.governance?.rules??[],n=t.fallbackOrder?[...new Set([...o?.fallbackOrder??[],...t.fallbackOrder])]:o?.fallbackOrder,s=t.providerWeights?{...o?.providerWeights??{},...t.providerWeights}:o?.providerWeights;return{...o,maxTotalCostUsd:t.maxTotalCostUsd??o?.maxTotalCostUsd,maxRequestsPerMinute:t.maxRequestsPerMinute??o?.maxRequestsPerMinute,allowedHoursUtc:t.allowedHoursUtc??o?.allowedHoursUtc,fallbackOrder:n,providerWeights:s,governance:{rules:[...r,...t.rules]}}}function se(o,e){if(o?.maxTotalCostUsd!==void 0&&e>o.maxTotalCostUsd)throw new Error(`routing policy rejected cost ${e}`)}function oe(o,e){if(o?.maxRequestsPerMinute!==void 0&&e>o.maxRequestsPerMinute)throw new Error(`routing policy rejected rate ${e}`)}function ie(o,e){let t=o?.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 $(o,e,t){let r=o?.governance?.rules??[];if(r.length===0)return;let n=r.filter(s=>s.type==="allow_provider").map(s=>s.provider);if(n.length>0&&!n.includes(e))throw new Error(`routing policy governance rejected provider ${e}`);for(let s of r){if(s.type==="deny_provider"&&s.provider===e)throw new Error(`routing policy governance rejected provider ${e}`);if(s.type==="require_tag"&&t!==void 0&&!t.includes(s.tag))throw new Error(`routing policy governance missing tag ${s.tag}`)}}function Ye(o,e){let t=o?.fallbackOrder;if(!t||t.length===0||e.length===0)return null;let r=new Set(e);for(let n of t)if(r.has(n))return n;return null}function q(o,e,t,r={}){let n=r.governanceTags,s=r.currentHourUtc??new Date().getUTCHours();ie(o,s),r.estimatedCostUsd!==void 0&&se(o,r.estimatedCostUsd),r.currentRequestsPerMinute!==void 0&&oe(o,r.currentRequestsPerMinute);let i=d=>d.length===1?d[0]:[...d].sort((c,p)=>{let m=o?.providerWeights?.[p.provider]??0,h=o?.providerWeights?.[c.provider]??0;return m!==h?m-h:(p.priority??0)-(c.priority??0)})[0],a=o?.aliases?.[t];if(a&&a.length>0){let d=[...a].sort((h,G)=>(G.priority??0)-(h.priority??0)),c=r.availableProviders;if(!c||c.length===0){let h=i(d);return $(o,h.provider,n),{provider:h.provider,model:h.model,selectedBy:`alias:${t}`}}let p=new Set(c),m=d.filter(h=>p.has(h.provider));if(m.length>0){let h=i(m);return $(o,h.provider,n),{provider:h.provider,model:h.model,selectedBy:`alias:${t}`}}}let l=Ye(o,r.availableProviders??[]);return l&&l!==e?($(o,l,n),{provider:l,model:t,selectedBy:`fallback:${l}`}):($(o,e,n),{provider:e,model:t,selectedBy:"direct"})}function H(o,e,t,r={}){let n=[],s=r.currentHourUtc??new Date().getUTCHours(),i=(a,l)=>{let d=l instanceof Error?l.message:String(l);return n.push({check:a,status:"failed",detail:d}),{ok:!1,checks:n,error:d}};if(o?.allowedHoursUtc&&o.allowedHoursUtc.length>0)try{ie(o,s),n.push({check:"time_window",status:"passed",detail:`hour=${s}`})}catch(a){return i("time_window",a)}else n.push({check:"time_window",status:"skipped",detail:"not configured"});if(r.estimatedCostUsd!==void 0)try{se(o,r.estimatedCostUsd),n.push({check:"cost_limit",status:"passed",detail:`cost=${r.estimatedCostUsd}`})}catch(a){return i("cost_limit",a)}else n.push({check:"cost_limit",status:"skipped",detail:"no estimate provided"});if(r.currentRequestsPerMinute!==void 0)try{oe(o,r.currentRequestsPerMinute),n.push({check:"rate_limit",status:"passed",detail:`rpm=${r.currentRequestsPerMinute}`})}catch(a){return i("rate_limit",a)}else n.push({check:"rate_limit",status:"skipped",detail:"no rpm provided"});try{let a=q(o,e,t,r);return n.push({check:"governance",status:"passed",detail:"accepted"}),n.push({check:"selection",status:"passed",detail:a.selectedBy}),{ok:!0,decision:a,checks:n}}catch(a){let l=a instanceof Error?a.message:String(a);return l.includes("governance")?(n.push({check:"governance",status:"failed",detail:l}),n.push({check:"selection",status:"skipped",detail:"selection aborted"}),{ok:!1,checks:n,error:l}):i("selection",a)}}function ae(o,e){let t=e.map(s=>H(o,s.provider,s.model,s.options??{})),r=t.map((s,i)=>({result:s,index:i})).filter(s=>!s.result.ok).map(s=>s.index),n=r.length;return{total:t.length,passed:t.length-n,failed:n,failedIndexes:r,results:t}}function Q(o,e,t=void 0){let r=e.map((s,i)=>{let a=H(t,s.provider,s.model,s.options??{}),l=H(o,s.provider,s.model,s.options??{}),d=a.ok!==l.ok||a.decision?.provider!==l.decision?.provider||a.decision?.model!==l.decision?.model||a.decision?.selectedBy!==l.decision?.selectedBy||a.error!==l.error;return{index:i,input:{provider:s.provider,model:s.model},baseline:a,candidate:l,changed:d}}),n=r.filter(s=>s.baseline.ok&&!s.candidate.ok).length;return{total:r.length,baselinePassed:r.filter(s=>s.baseline.ok).length,candidatePassed:r.filter(s=>s.candidate.ok).length,changed:r.filter(s=>s.changed).length,regressions:n,results:r}}function le(o,e={}){let t=[],r=e.maxChanged??o.total,n=e.maxRegressions??0,s=e.minCandidatePassRate??1,i=o.total===0?1:o.candidatePassed/o.total;t.push({check:"changed_budget",status:o.changed<=r?"passed":"failed",detail:`changed=${o.changed}, limit=${r}`}),t.push({check:"regression_budget",status:o.regressions<=n?"passed":"failed",detail:`regressions=${o.regressions}, limit=${n}`}),t.push({check:"candidate_pass_rate",status:i>=s?"passed":"failed",detail:`candidate_pass_rate=${i.toFixed(3)}, min=${s.toFixed(3)}`});let a=t.find(l=>l.status==="failed");return a?{ok:!1,checks:t,error:a.detail}:{ok:!0,checks:t}}var vt=require("gauss-napi");function vr(o){return{...o,citations:o.citations?.map(e=>({type:e.citationType??e.type,citedText:e.citedText,documentTitle:e.documentTitle,start:e.start,end:e.end}))}}var F=class{constructor(e,t,r,n,s,i){this.agentName=e;this.providerHandle=t;this.tools=r;this.messages=n;this.options=s;this.toolExecutor=i}_result;get result(){return this._result}async*[Symbol.asyncIterator](){let e=[],t,r=!1,n=i=>{try{e.push(JSON.parse(i))}catch{e.push({type:"raw",text:i})}t?.()},s=(0,vt.agent_stream_with_tool_executor)(this.agentName,this.providerHandle,this.tools,this.messages,this.options,n,this.toolExecutor).then(i=>{this._result=vr(i),r=!0,t?.()});for(;!r||e.length>0;)e.length>0?yield e.shift():r||await new Promise(i=>{t=i});await s}};function de(o){return{name:o.name,description:o.description,parameters:o.parameters,execute:o.execute}}function ce(o){return typeof o.execute=="function"}function pe(o,e){let t=new Map(o.map(r=>[r.name,r]));return async r=>{let n;try{n=JSON.parse(r)}catch{return JSON.stringify({error:"Invalid tool call JSON"})}let s=n.tool??n.name??"",i=t.get(s);if(!i)return e?e(r):JSON.stringify({error:`Unknown tool: ${s}`});try{let a=n.args??n.arguments??{},l=await i.execute(a);return typeof l=="string"?l:JSON.stringify(l)}catch(a){let l=a instanceof Error?a.message:String(a);return JSON.stringify({error:`Tool "${s}" failed: ${l}`})}}}function ue(o){return{...o,citations:o.citations?.map(e=>({type:e.citationType??e.type??"unknown",citedText:e.citedText,documentTitle:e.documentTitle,start:e.start,end:e.end}))}}var f=class o{providerHandle;_name;_requestedProvider;_requestedModel;_provider;_model;_routingPolicy;_providerOptions;_instructions;_tools=[];_options={};disposed=!1;_middleware=null;_guardrails=null;_memory=null;_sessionId="";_mcpClients=[];_mcpToolsLoaded=!1;constructor(e={}){let t=B(),r=e.provider??t?.provider??"openai",n=e.model??t?.model??V;this._requestedProvider=r,this._requestedModel=n,this._routingPolicy=e.routingPolicy;let s=q(this._routingPolicy,r,n);this._provider=s.provider,this._model=s.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,g.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 o(e)}get name(){return this._name}get provider(){return this._provider}get model(){return this._model}get instructions(){return this._instructions}get handle(){return this.providerHandle}get capabilities(){return(0,g.get_provider_capabilities)(this.providerHandle)}addTool(e){return this._tools.push(e),this}addTools(e){return this._tools.push(...e),this}withTool(e,t,r,n){return this._tools.push(de({name:e,description:t,parameters:n??{},execute:r})),this}setOptions(e){return this._options={...this._options,...e},this}withModel(e){return this.assertNotDisposed(),new o({...this.toConfig(),model:e})}withRoutingContext(e){this.assertNotDisposed();let t=q(this._routingPolicy,this._requestedProvider,this._requestedModel,e);return new o({...this.toConfig(),provider:t.provider,model:t.model})}withMiddleware(e){return this._middleware=e,this}withGuardrails(e){return this._guardrails=e,this}withMemory(e,t){return this._memory=e,t&&(this._sessionId=t),this}useMcpServer(e){return this._mcpClients.push(e),this._mcpToolsLoaded=!1,this}async run(e){this.assertNotDisposed(),await this.ensureMcpTools();let t=typeof e=="string"?[{role:"user",content:e}]:[...e];if(this._memory){let i=await this._memory.recall(this._sessionId?{sessionId:this._sessionId}:void 0);i.length>0&&(t=[{role:"system",content:`Previous context:
|
|
2
2
|
${i.map(l=>l.content).join(`
|
|
3
|
-
`)}`},...t])}let{toolDefs:r,executor:n}=this.resolveToolsAndExecutor(),
|
|
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:
|
|
3
|
+
`)}`},...t])}let{toolDefs:r,executor:n}=this.resolveToolsAndExecutor(),s;if(n?s=ue(await(0,g.agent_run_with_tool_executor)(this._name,this.providerHandle,r,t,this._options,n)):s=ue(await(0,g.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:s.text,entryType:"conversation",timestamp:new Date().toISOString(),sessionId:this._sessionId||void 0})}return s}async runWithTools(e,t){this.assertNotDisposed(),await this.ensureMcpTools();let r=typeof e=="string"?[{role:"user",content:e}]:e,{toolDefs:n,executor:s}=this.resolveToolsAndExecutor(),i=async a=>{if(s){let l=await s(a);if(!JSON.parse(l).error?.startsWith("Unknown tool:"))return l}return t(a)};return ue(await(0,g.agent_run_with_tool_executor)(this._name,this.providerHandle,n,r,this._options,i))}async stream(e,t,r){this.assertNotDisposed(),await this.ensureMcpTools();let n=typeof e=="string"?[{role:"user",content:e}]:e,{toolDefs:s,executor:i}=this.resolveToolsAndExecutor(),a=r??i??Pt;return ue(await(0,g.agent_stream_with_tool_executor)(this._name,this.providerHandle,s,n,this._options,t,a))}streamIter(e,t){this.assertNotDisposed();let r=typeof e=="string"?[{role:"user",content:e}]:e,{toolDefs:n,executor:s}=this.resolveToolsAndExecutor(),i=t??s??Pt;return new F(this._name,this.providerHandle,n,r,this._options,i)}async streamText(e,t,r){this.assertNotDisposed();let n=this.streamIter(e,r),s="";for await(let i of n){if(i.type!=="text_delta")continue;let a=typeof i.text=="string"?i.text:typeof i.delta=="string"?i.delta:"";a&&(s+=a,t?.(a))}return n.result?.text??s}async generate(e,t){this.assertNotDisposed();let r=typeof e=="string"?[{role:"user",content:e}]:e;return(0,g.generate)(this.providerHandle,r,t?.temperature,t?.maxTokens)}async generateWithTools(e,t,r){this.assertNotDisposed();let n=typeof e=="string"?[{role:"user",content:e}]:e;return(0,g.generate_with_tools)(this.providerHandle,n,t,r?.temperature,r?.maxTokens)}destroy(){if(!this.disposed){this.disposed=!0;for(let e of this._mcpClients)try{e.close()}catch{}try{(0,g.destroy_provider)(this.providerHandle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new P("Agent",this._name)}resolveToolsAndExecutor(){let e=this._tools.filter(ce),t=this._tools.map(n=>({name:n.name,description:n.description,parameters:n.parameters})),r=e.length>0?pe(e):null;return{toolDefs:t,executor:r}}async ensureMcpTools(){if(!(this._mcpToolsLoaded||this._mcpClients.length===0)){for(let e of this._mcpClients){let{tools:t,executor:r}=await e.getToolsWithExecutor();for(let n of t){let s={...n,execute:async i=>{let a=JSON.stringify({tool:n.name,args:i}),l=await r(a);return JSON.parse(l)}};this._tools.push(s)}}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}}},Pt=async()=>"{}";async function xt(o,e){let t=new f({name:"gauss",...e});try{return(await t.run(o)).text}finally{t.destroy()}}function Qe(o={}){let e=o.providerOptions?.maxRetries??o.retries??5;return new f({...o,name:o.name??"enterprise-agent",maxSteps:o.maxSteps??20,temperature:o.temperature??.2,cacheControl:o.cacheControl??!0,reasoningEffort:o.reasoningEffort??"medium",providerOptions:{...o.providerOptions,maxRetries:e}})}async function bt(o,e){let t=Qe(e);try{return(await t.run(o)).text}finally{t.destroy()}}async function Tt(o,e){let{concurrency:t=5,...r}=e??{},n=o.map(i=>({input:i})),s=new f({name:"batch",...r});try{let i=[...n.entries()],a=Array.from({length:Math.min(t,i.length)},async()=>{for(;i.length>0;){let l=i.shift();if(!l)break;let[d,c]=l;try{n[d].result=await s.run(c.input)}catch(p){n[d].error=p instanceof Error?p:new Error(String(p))}}});await Promise.all(a)}finally{s.destroy()}return n}var _=require("gauss-napi");var Xe=require("gauss-napi");async function wt(o,e,t){return(0,_.execute_code)(o,e,t?.timeoutSecs,t?.workingDir,t?.sandbox)}async function kt(){return(0,_.available_runtimes)()}async function Ct(o,e={}){let t=B(),r=e.provider??t?.provider??"openai",n=e.model??t?.model??"dall-e-3",s=e.providerOptions?.apiKey??J(r),i=(0,_.create_provider)(r,n,{apiKey:s,...e.providerOptions});try{return await(0,_.generate_image)(i,o,e.model,e.size,e.quality,e.style,e.aspectRatio,e.n,e.responseFormat)}finally{(0,_.destroy_provider)(i)}}var Rt=require("crypto"),x=require("gauss-napi"),he=class{_handle;disposed=!1;constructor(){this._handle=(0,x.create_memory)()}get handle(){return this._handle}async store(e,t,r){this.assertNotDisposed();let n=typeof e=="string"?{id:(0,Rt.randomUUID)(),content:t,entryType:e||"conversation",timestamp:new Date().toISOString(),sessionId:r}:e,s={id:n.id,content:n.content,entry_type:n.entryType,timestamp:n.timestamp,tier:n.tier,metadata:n.metadata,importance:n.importance,session_id:n.sessionId,embedding:n.embedding};return(0,x.memory_store)(this._handle,JSON.stringify(s))}async recall(e){this.assertNotDisposed();let t=e?JSON.stringify(e):void 0;return(0,x.memory_recall)(this._handle,t)}async clear(e){return this.assertNotDisposed(),(0,x.memory_clear)(this._handle,e)}async stats(){return this.assertNotDisposed(),(0,x.memory_stats)(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,x.destroy_memory)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Memory has been destroyed")}};var E=require("gauss-napi"),me=class{_handle;disposed=!1;constructor(e){this._handle=(0,E.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,E.vector_store_upsert)(this._handle,JSON.stringify(t))}async search(e,t){return this.assertNotDisposed(),(0,E.vector_store_search)(this._handle,JSON.stringify(e),t)}async searchByText(e,t,r){this.assertNotDisposed();let n=await r(e);return this.search(n,t)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,E.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,E.cosine_similarity)(e,t)}};var Pr=[`
|
|
5
5
|
|
|
6
6
|
`,`
|
|
7
|
-
`,". "," ",""],j=class{chunkSize;chunkOverlap;separators;constructor(e={}){this.chunkSize=e.chunkSize??1e3,this.chunkOverlap=e.chunkOverlap??200,this.separators=e.separators??
|
|
8
|
-
`)&&
|
|
7
|
+
`,". "," ",""],j=class{chunkSize;chunkOverlap;separators;constructor(e={}){this.chunkSize=e.chunkSize??1e3,this.chunkOverlap=e.chunkOverlap??200,this.separators=e.separators??Pr}split(e){return this._splitRecursive(e,this.separators).map((r,n)=>({content:r,index:n}))}_splitRecursive(e,t){if(e.length<=this.chunkSize)return[e];let r=t[0]??"",n=t.slice(1),s=r?e.split(r):[...e],i=[],a="";for(let l of s){let d=a?a+r+l:l;if(d.length>this.chunkSize&&a){i.push(a);let c=Math.max(0,a.length-this.chunkOverlap);if(a=a.slice(c)+r+l,a.length>this.chunkSize&&n.length>0){let p=this._splitRecursive(a,n);a=p.pop()??"",i.push(...p)}}else a=d}return a&&i.push(a),i}};function St(o,e){return new j(e).split(o)}var Ze=require("fs/promises"),et=require("path");async function tt(o,e={}){let t=!o.includes(`
|
|
8
|
+
`)&&o.length<500,r,n;if(t)try{r=await(0,Ze.readFile)(o,"utf-8"),n=e.documentId??(0,et.basename)(o)}catch{r=o,n=e.documentId??"text-document"}else r=o,n=e.documentId??"text-document";let a=new j(e).split(r).map(l=>({id:`${n}-${l.index}`,documentId:n,content:l.content,index:l.index,metadata:{...e.metadata,...l.metadata}}));return{documentId:n,content:r,chunks:a,metadata:e.metadata??{}}}async function _t(o,e={}){let t=await tt(o,{...e,separators:[`
|
|
9
9
|
## `,`
|
|
10
10
|
### `,`
|
|
11
11
|
|
|
12
12
|
`,`
|
|
13
|
-
`,". "," "]});return t.content=t.content.replace(/^---[\s\S]*?---\n?/,""),t}async function Et(
|
|
14
|
-
`)&&
|
|
13
|
+
`,". "," "]});return t.content=t.content.replace(/^---[\s\S]*?---\n?/,""),t}async function Et(o,e={}){let t,r;if(!o.includes(`
|
|
14
|
+
`)&&o.length<500)try{t=await(0,Ze.readFile)(o,"utf-8"),r=e.documentId??(0,et.basename)(o)}catch{t=o,r=e.documentId??"json-document"}else t=o,r=e.documentId??"json-document";let s=JSON.parse(t),i=[];if(Array.isArray(s))s.forEach((l,d)=>{let c=e.textField?String(l[e.textField]??""):JSON.stringify(l);i.push({key:String(d),text:c})});else if(typeof s=="object"&&s!==null)for(let[l,d]of Object.entries(s)){let c=typeof d=="string"?d:JSON.stringify(d);i.push({key:l,text:c})}let a=i.map((l,d)=>({id:`${r}-${l.key}`,documentId:r,content:l.text,index:d,metadata:{...e.metadata,key:l.key}}));return{documentId:r,content:t,chunks:a,metadata:e.metadata??{}}}var b=require("gauss-napi");var ge=class o{static pipeline(e){let t=new o;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,b.create_graph)()}get handle(){return this._handle}addNode(e){return this.assertNotDisposed(),(0,b.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,b.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,b.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,b.graph_run)(this._handle,e):this._runWithConditionals(e)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,b.destroy_graph)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}async _runWithConditionals(e){let t=new Set([...this._edges.values()]),r=[...this._nodes.keys()].filter(d=>!t.has(d));if(r.length===0)throw new u("Graph has no entry node (every node has an incoming edge)");let n={},s=r[0],i=e;for(;s;){let d=this._nodes.get(s);if(!d)throw new u(`Node "${s}" not found in graph`);let c=d.instructions?`${d.instructions}
|
|
15
15
|
|
|
16
|
-
${i}`:i,
|
|
16
|
+
${i}`:i,p=await d.agent.run(c),m={text:p.text,...p.structuredOutput?{structuredOutput:p.structuredOutput}:{}};n[s]=m;let h=this._conditionalEdges.get(s);h?s=await h(m):s=this._edges.get(s),i=p.text}let a=Object.keys(n),l=a[a.length-1];return{outputs:n,final_text:n[l]?.text??""}}assertNotDisposed(){if(this.disposed)throw new P("Graph","graph")}};var A=require("gauss-napi"),ye=class{_handle;disposed=!1;constructor(){this._handle=(0,A.create_workflow)()}get handle(){return this._handle}addStep(e){return this.assertNotDisposed(),(0,A.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,A.workflow_add_dependency)(this._handle,e,t),this}async run(e){return this.assertNotDisposed(),(0,A.workflow_run)(this._handle,e)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,A.destroy_workflow)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Workflow has been destroyed")}};var D=require("gauss-napi");var fe=class o{_handle;_name;disposed=!1;agents=[];static quick(e,t,r){let n=new o(e);for(let s of r){let i=new f({name:s.name,provider:s.provider??"openai",model:s.model??"gpt-4o",instructions:s.instructions});n.add(i)}return n.strategy(t),n}constructor(e){this._name=e,this._handle=(0,D.create_team)(e)}get handle(){return this._handle}add(e,t){return this.assertNotDisposed(),(0,D.team_add_agent)(this._handle,e.name,e.handle,t),this.agents.push(e),this}strategy(e){return this.assertNotDisposed(),(0,D.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,D.team_run)(this._handle,t)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,D.destroy_team)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new P("Team",this._name)}};var v=require("gauss-napi");var ve=class o{_handle;disposed=!1;supervisorName=null;static quick(e,t){let r=new o;for(let n of t){let s=new f({name:n.name,provider:n.provider??"openai",model:n.model??"gpt-4o",instructions:n.instructions});r.addAgent(s,n.instructions)}return r.setSupervisor(e),r}static template(e){return e==="research-delivery"?{supervisor:"lead",agents:[{name:"lead",instructions:"Coordinate and delegate work."},{name:"researcher",instructions:"Research context and constraints."},{name:"implementer",instructions:"Implement practical solutions."}]}:e==="incident-response"?{supervisor:"incident-commander",agents:[{name:"incident-commander",instructions:"Drive response and coordination."},{name:"triage",instructions:"Assess impact and prioritize mitigation."},{name:"remediator",instructions:"Propose and execute remediation steps."}]}:e==="support-triage"?{supervisor:"support-lead",agents:[{name:"support-lead",instructions:"Coordinate support workload and escalations."},{name:"triage-bot",instructions:"Classify incoming support requests."},{name:"resolver",instructions:"Draft and validate customer resolutions."}]}:e==="fintech-risk-review"?{supervisor:"risk-lead",agents:[{name:"risk-lead",instructions:"Approve risk recommendations and report rationale."},{name:"policy-analyst",instructions:"Map events to compliance policy obligations."},{name:"fraud-scorer",instructions:"Score suspicious patterns and flag anomalies."}]}:{supervisor:"rag-ops-lead",agents:[{name:"rag-ops-lead",instructions:"Coordinate retrieval quality and index freshness."},{name:"retrieval-auditor",instructions:"Audit recall/precision and retrieval grounding."},{name:"index-maintainer",instructions:"Propose chunking and indexing improvements."}]}}static fromTemplate(e){let t=o.template(e);return o.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 n=r===void 0?e:t,s=r===void 0?t:r;return(0,v.network_delegate)(this._handle,n,s)}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 P("Network","network")}};var I=require("gauss-napi"),Pe=class{_handle;disposed=!1;constructor(){this._handle=(0,I.create_middleware_chain)()}get handle(){return this._handle}useLogging(){return this.assertNotDisposed(),(0,I.middleware_use_logging)(this._handle),this}useCaching(e){return this.assertNotDisposed(),(0,I.middleware_use_caching)(this._handle,e),this}useRateLimit(e,t){return this.assertNotDisposed(),(0,I.middleware_use_rate_limit)(this._handle,e,t),this}destroy(){if(!this.disposed){this.disposed=!0;try{(0,I.destroy_middleware_chain)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("MiddlewareChain has been destroyed")}};var T=require("gauss-napi"),xe=class{_handle;disposed=!1;constructor(){this._handle=(0,T.create_plugin_registry)()}get handle(){return this._handle}addTelemetry(){return this.assertNotDisposed(),(0,T.plugin_registry_add_telemetry)(this._handle),this}addMemory(){return this.assertNotDisposed(),(0,T.plugin_registry_add_memory)(this._handle),this}list(){return this.assertNotDisposed(),(0,T.plugin_registry_list)(this._handle)}emit(e){this.assertNotDisposed(),(0,T.plugin_registry_emit)(this._handle,JSON.stringify(e))}destroy(){if(!this.disposed){this.disposed=!0;try{(0,T.destroy_plugin_registry)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("PluginRegistry has been destroyed")}};var w=require("gauss-napi"),be=class{_handle;disposed=!1;constructor(e,t){this._handle=(0,w.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,w.mcp_server_add_tool)(this._handle,JSON.stringify(t)),this}addResource(e){return this.assertNotDisposed(),(0,w.mcpServerAddResource)(this._handle,JSON.stringify(e)),this}addPrompt(e){return this.assertNotDisposed(),(0,w.mcpServerAddPrompt)(this._handle,JSON.stringify(e)),this}async handleMessage(e){return this.assertNotDisposed(),(0,w.mcp_server_handle)(this._handle,JSON.stringify(e))}destroy(){if(!this.disposed){this.disposed=!0;try{(0,w.destroy_mcp_server)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("McpServer has been destroyed")}};var At=require("child_process"),Te=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,At.spawn)(this.config.command,this.config.args??[],{stdio:["pipe","pipe","pipe"],env:{...process.env,...this.config.env}}),this.process.stdout.on("data",r=>this.onData(r)),this.process.stderr.on("data",()=>{}),this.process.on("error",r=>this.onProcessError(r)),this.process.on("close",()=>this.onProcessClose());let t=await this.request("initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"gauss-mcp-client",version:"1.2.0"}},e);this.serverCapabilities=t?.capabilities??{},this.notify("notifications/initialized",{}),this.connected=!0}async listTools(){if(this.assertConnected(),this.cachedTools)return this.cachedTools;let t=((await this.request("tools/list",{}))?.tools??[]).map(r=>({name:r.name,description:r.description??"",parameters:r.inputSchema}));return this.cachedTools=t,t}async callTool(e,t={}){return this.assertConnected(),await this.request("tools/call",{name:e,arguments:t})}async getToolsWithExecutor(){return{tools:await this.listTools(),executor:async r=>{let n;try{n=JSON.parse(r)}catch{return JSON.stringify({error:"Invalid tool call JSON"})}let s=n.tool??n.name??"",i=n.args??n.arguments??{};try{let a=await this.callTool(s,i);if(a.isError){let d=a.content?.map(c=>c.text).filter(Boolean).join(`
|
|
17
17
|
`)??"Tool error";return JSON.stringify({error:d})}let l=a.content?.map(d=>d.text).filter(Boolean).join(`
|
|
18
|
-
`)??"";return JSON.stringify({result:l})}catch(a){let l=a instanceof Error?a.message:String(a);return JSON.stringify({error:l})}}}}close(){if(!this.closed){this.closed=!0,this.connected=!1,this.cachedTools=null;for(let[,{reject:e}]of this.pending)e(new Error("McpClient closed"));this.pending.clear(),this.process&&(this.process.stdin.end(),this.process.kill("SIGTERM"),this.process=null)}}destroy(){this.close()}[Symbol.dispose](){this.close()}get isConnected(){return this.connected}async request(e,t,r=3e4){let n=this.nextId++,
|
|
18
|
+
`)??"";return JSON.stringify({result:l})}catch(a){let l=a instanceof Error?a.message:String(a);return JSON.stringify({error:l})}}}}close(){if(!this.closed){this.closed=!0,this.connected=!1,this.cachedTools=null;for(let[,{reject:e}]of this.pending)e(new Error("McpClient closed"));this.pending.clear(),this.process&&(this.process.stdin.end(),this.process.kill("SIGTERM"),this.process=null)}}destroy(){this.close()}[Symbol.dispose](){this.close()}get isConnected(){return this.connected}async request(e,t,r=3e4){let n=this.nextId++,s={jsonrpc:"2.0",id:n,method:e,params:t};return new Promise((i,a)=>{let l=setTimeout(()=>{this.pending.delete(n),a(new Error(`MCP request "${e}" timed out after ${r}ms`))},r);this.pending.set(n,{resolve:d=>{clearTimeout(l),i(d)},reject:d=>{clearTimeout(l),a(d)}}),this.send(s)})}notify(e,t){let r={jsonrpc:"2.0",method:e,params:t};this.send(r)}send(e){if(!this.process?.stdin?.writable)throw new Error("MCP server process not available");let t=JSON.stringify(e);this.process.stdin.write(t+`
|
|
19
19
|
`)}onData(e){this.buffer+=e.toString("utf-8");let t;for(;(t=this.buffer.indexOf(`
|
|
20
|
-
`))!==-1;){let r=this.buffer.slice(0,t).trim();if(this.buffer=this.buffer.slice(t+1),!!r)try{let n=JSON.parse(r);if(n.id!==void 0&&this.pending.has(n.id)){let{resolve:o,reject:i}=this.pending.get(n.id);this.pending.delete(n.id),n.error?i(new Error(`MCP error ${n.error.code}: ${n.error.message}`)):o(n.result)}}catch{}}}onProcessError(e){for(let[,{reject:t}]of this.pending)t(new Error(`MCP process error: ${e.message}`));this.pending.clear(),this.connected=!1}onProcessClose(){this.connected=!1;for(let[,{reject:e}]of this.pending)e(new Error("MCP server process exited"));this.pending.clear()}assertConnected(){if(!this.connected)throw new Error("McpClient is not connected. Call connect() first.")}};var y=require("gauss-napi"),ke=class{_handle;disposed=!1;constructor(){this._handle=(0,y.create_guardrail_chain)()}get handle(){return this._handle}addContentModeration(e,t=[]){return this.assertNotDisposed(),(0,y.guardrail_chain_add_content_moderation)(this._handle,e,t),this}addPiiDetection(e){return this.assertNotDisposed(),(0,y.guardrail_chain_add_pii_detection)(this._handle,e),this}addTokenLimit(e,t){return this.assertNotDisposed(),(0,y.guardrail_chain_add_token_limit)(this._handle,e,t),this}addRegexFilter(e,t=[]){return this.assertNotDisposed(),(0,y.guardrail_chain_add_regex_filter)(this._handle,e,t),this}addSchema(e){return this.assertNotDisposed(),(0,y.guardrail_chain_add_schema)(this._handle,JSON.stringify(e)),this}list(){return this.assertNotDisposed(),(0,y.guardrail_chain_list)(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,y.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"),we=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 I=require("gauss-napi"),_e=class{_handle;disposed=!1;constructor(){this._handle=(0,I.create_checkpoint_store)()}get handle(){return this._handle}async save(e){return this.assertNotDisposed(),(0,I.checkpoint_save)(this._handle,JSON.stringify(e))}async load(e){return this.assertNotDisposed(),(0,I.checkpoint_load)(this._handle,e)}async loadLatest(e){return this.assertNotDisposed(),(0,I.checkpoint_load_latest)(this._handle,e)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,I.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"),Ce=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 _=require("gauss-napi"),Re=class{_handle;disposed=!1;constructor(){this._handle=(0,_.create_telemetry)()}get handle(){return this._handle}recordSpan(e,t,r){this.assertNotDisposed();let n=typeof e=="string"?{name:e,span_type:"custom",start_ms:Date.now()-(t??0),duration_ms:t??0,attributes:r??{},status:"ok",children:[]}:e;(0,_.telemetry_record_span)(this._handle,JSON.stringify(n))}exportSpans(){return this.assertNotDisposed(),(0,_.telemetry_export_spans)(this._handle)}exportMetrics(){return this.assertNotDisposed(),(0,_.telemetry_export_metrics)(this._handle)}clear(){this.assertNotDisposed(),(0,_.telemetry_clear)(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,_.destroy_telemetry)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Telemetry has been destroyed")}};var De=require("fs"),jt=require("http"),Ut=require("path");var N=require("gauss-napi"),Se=new Map;function Dt(s,e){Se.set(s,e)}function Ot(s){return Se.get(s)}function It(){Se.clear()}function Mt(s){return(0,N.count_tokens)(s)}function Nt(s,e){return(0,N.count_tokens_for_model)(s,e)}function Lt(s){return(0,N.count_message_tokens)(s)}function Ht(s){return(0,N.get_context_window_size)(s)}function Ee(s,e){let t=Se.get(s);if(t){let n=e.inputTokens*t.inputPerToken,o=e.outputTokens*t.outputPerToken,i=(e.reasoningTokens??0)*(t.reasoningPerToken??t.outputPerToken),a=(e.cacheReadTokens??0)*(t.cacheReadPerToken??t.inputPerToken*.5),l=(e.cacheCreationTokens??0)*(t.cacheCreationPerToken??t.inputPerToken*1.25);return{model:s,normalizedModel:s,currency:"USD",inputTokens:e.inputTokens,outputTokens:e.outputTokens,reasoningTokens:e.reasoningTokens??0,cacheReadTokens:e.cacheReadTokens??0,cacheCreationTokens:e.cacheCreationTokens??0,inputCostUsd:n,outputCostUsd:o,reasoningCostUsd:i,cacheReadCostUsd:a,cacheCreationCostUsd:l,totalCostUsd:n+o+i+a+l}}let r=(0,N.estimate_cost)(s,e.inputTokens,e.outputTokens,e.reasoningTokens,e.cacheReadTokens,e.cacheCreationTokens);return{model:String(r.model??s),normalizedModel:String(r.normalized_model??s),currency:String(r.currency??"USD"),inputTokens:Number(r.input_tokens??e.inputTokens),outputTokens:Number(r.output_tokens??e.outputTokens),reasoningTokens:Number(r.reasoning_tokens??e.reasoningTokens??0),cacheReadTokens:Number(r.cache_read_tokens??e.cacheReadTokens??0),cacheCreationTokens:Number(r.cache_creation_tokens??e.cacheCreationTokens??0),inputCostUsd:Number(r.input_cost_usd??0),outputCostUsd:Number(r.output_cost_usd??0),reasoningCostUsd:Number(r.reasoning_cost_usd??0),cacheReadCostUsd:Number(r.cache_read_cost_usd??0),cacheCreationCostUsd:Number(r.cache_creation_cost_usd??0),totalCostUsd:Number(r.total_cost_usd??0)}}var R=class extends Error{},Pr=["openai","anthropic","google","groq","ollama","deepseek","openrouter","together","fireworks","mistral","perplexity","xai"],Ae=class{telemetry;approvals;model;routingPolicy;authToken;authClaims;persistPath;historyLimit;streamReplayLimit;context;latestCost=null;history=[];nextStreamEventId=1;streamEvents=[];explainTraces=[];nextExplainTraceId=1;latestExplainTraceId=null;policyDriftAlertHooks=[];policyLifecycleVersions=[];nextPolicyLifecycleVersion=1;activePolicyVersionId=null;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}onPolicyDriftAlert(e){return this.policyDriftAlertHooks.push(e),()=>{let t=this.policyDriftAlertHooks.indexOf(e);t>=0&&this.policyDriftAlertHooks.splice(t,1)}}setCostUsage(e){return this.latestCost=Ee(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,latestExplainTraceId:t.latestExplainTraceId}))}getDag(e){let t=this.filterHistory(e),r=t[t.length-1];if(!r||!Array.isArray(r.spans))return{nodes:[],edges:[]};let n=r.spans.map((i,a)=>({id:String(a),label:this.spanLabel(i,a)})),o=n.slice(1).map((i,a)=>({from:String(a),to:i.id}));return{nodes:n,edges:o}}async startServer(e="127.0.0.1",t=4200){if(this.server){let n=this.server.address();return n&&typeof n!="string"?{url:`http://${e}:${n.port}`}:{url:`http://${e}:${t}`}}this.server=(0,jt.createServer)((n,o)=>{if(!n.url){o.statusCode=400,o.end("Bad request");return}let i=new URL(n.url,`http://${n.headers.host??`${e}:${t}`}`),a=i.pathname;if(a.startsWith("/api/")&&!this.isAuthorized(n,i)){o.statusCode=401,o.setHeader("Content-Type","application/json; charset=utf-8"),o.end(JSON.stringify({error:"Unauthorized"}));return}try{if(a==="/api/snapshot"){let l=i.searchParams.get("section"),d=l?this.snapshot(this.parseSection(l)):this.snapshot();o.setHeader("Content-Type","application/json; charset=utf-8"),o.end(JSON.stringify(d,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/ops/policy/explain/diff"){o.setHeader("Content-Type","application/json; charset=utf-8"),o.end(JSON.stringify(this.opsPolicyExplainDiff(i.searchParams),null,2));return}if(a==="/api/ops/policy/explain/traces"){o.setHeader("Content-Type","application/json; charset=utf-8"),o.end(JSON.stringify(this.opsPolicyExplainTraces(i.searchParams),null,2));return}if(a==="/api/ops/policy/lifecycle/draft"){o.setHeader("Content-Type","application/json; charset=utf-8"),o.end(JSON.stringify(this.opsPolicyLifecycleDraft(i.searchParams),null,2));return}if(a==="/api/ops/policy/lifecycle/validate"){o.setHeader("Content-Type","application/json; charset=utf-8"),o.end(JSON.stringify(this.opsPolicyLifecycleValidate(i.searchParams),null,2));return}if(a==="/api/ops/policy/lifecycle/approve"){o.setHeader("Content-Type","application/json; charset=utf-8"),o.end(JSON.stringify(this.opsPolicyLifecycleApprove(i.searchParams),null,2));return}if(a==="/api/ops/policy/lifecycle/promote"){o.setHeader("Content-Type","application/json; charset=utf-8"),o.end(JSON.stringify(this.opsPolicyLifecyclePromote(i.searchParams),null,2));return}if(a==="/api/ops/policy/lifecycle/versions"){o.setHeader("Content-Type","application/json; charset=utf-8"),o.end(JSON.stringify(this.opsPolicyLifecycleVersions(),null,2));return}if(a==="/api/ops/policy/drift"){o.setHeader("Content-Type","application/json; charset=utf-8"),o.end(JSON.stringify(this.opsPolicyDrift(i.searchParams),null,2));return}if(a==="/api/stream"){let l=this.applyAuthClaims(this.parseContextFilters(i.searchParams)),d=this.parseStreamChannels(i.searchParams);for(let lr of d)this.assertChannelAllowed(lr);let p=i.searchParams.get("once")==="1",c=this.parseLastEventId(n,i.searchParams);o.statusCode=200,o.setHeader("Content-Type","text/event-stream; charset=utf-8"),o.setHeader("Cache-Control","no-cache"),o.setHeader("Connection","keep-alive");let h=this.replayStreamEvents(o,d,l,c);if(p&&h>0){o.end();return}if(this.emitStreamBatch(o,d,l),p){o.end();return}let m=setInterval(()=>{o.writableEnded||o.destroyed||this.emitStreamBatch(o,d,l)},1e3),ee=()=>clearInterval(m);n.on("close",ee),n.on("aborted",ee);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 R){o.statusCode=403,o.setHeader("Content-Type","application/json; charset=utf-8"),o.end(JSON.stringify({error:l.message}));return}let d=l instanceof Error?l.message:"Internal error";o.statusCode=500,o.setHeader("Content-Type","application/json; charset=utf-8"),o.end(JSON.stringify({error:d}))}}),await new Promise((n,o)=>{this.server.once("error",o),this.server.listen(t,e,()=>n())});let r=this.server.address();return!r||typeof r=="string"?{url:`http://${e}:${t}`}:{url:`http://${e}:${r.port}`}}async stopServer(){if(!this.server)return;let e=this.server;this.server=null,await new Promise((t,r)=>{e.close(n=>n?r(n):t())})}destroy(){this.stopServer()}[Symbol.dispose](){this.destroy()}captureSnapshot(){this.assertContextAllowed(this.context);let e={generatedAt:new Date().toISOString(),context:{...this.context},spans:this.telemetry?.exportSpans()??[],metrics:this.telemetry?.exportMetrics()??{},pendingApprovals:this.approvals?.listPending()??[],latestCost:this.latestCost,latestExplainTraceId:this.latestExplainTraceId};return this.history.push(e),this.history.length>this.historyLimit&&this.history.shift(),this.persistPath&&((0,De.mkdirSync)((0,Ut.dirname)(this.persistPath),{recursive:!0}),(0,De.appendFileSync)(this.persistPath,`${JSON.stringify(e)}
|
|
21
|
-
`,"utf8")),e}parseSection(e){if(e==="spans"||e==="metrics"||e==="pendingApprovals"||e==="latestCost")return e;throw new u(`Unknown section "${e}"`,"section")}parseStreamChannel(e){if(e===null||e==="snapshot")return"snapshot";if(e==="timeline"||e==="dag")return e;throw new u(`Unknown stream channel "${e}"`,"channel")}parseStreamChannels(e){let t=e.get("channels");if(!t)return[this.parseStreamChannel(e.get("channel"))];let r=t.split(",").map(n=>n.trim()).filter(n=>n.length>0).map(n=>this.parseStreamChannel(n));return r.length===0?["snapshot"]:[...new Set(r)]}parseLastEventId(e,t){let r=t.get("lastEventId"),n=e.headers["last-event-id"],
|
|
20
|
+
`))!==-1;){let r=this.buffer.slice(0,t).trim();if(this.buffer=this.buffer.slice(t+1),!!r)try{let n=JSON.parse(r);if(n.id!==void 0&&this.pending.has(n.id)){let{resolve:s,reject:i}=this.pending.get(n.id);this.pending.delete(n.id),n.error?i(new Error(`MCP error ${n.error.code}: ${n.error.message}`)):s(n.result)}}catch{}}}onProcessError(e){for(let[,{reject:t}]of this.pending)t(new Error(`MCP process error: ${e.message}`));this.pending.clear(),this.connected=!1}onProcessClose(){this.connected=!1;for(let[,{reject:e}]of this.pending)e(new Error("MCP server process exited"));this.pending.clear()}assertConnected(){if(!this.connected)throw new Error("McpClient is not connected. Call connect() first.")}};var y=require("gauss-napi"),we=class{_handle;disposed=!1;constructor(){this._handle=(0,y.create_guardrail_chain)()}get handle(){return this._handle}addContentModeration(e,t=[]){return this.assertNotDisposed(),(0,y.guardrail_chain_add_content_moderation)(this._handle,e,t),this}addPiiDetection(e){return this.assertNotDisposed(),(0,y.guardrail_chain_add_pii_detection)(this._handle,e),this}addTokenLimit(e,t){return this.assertNotDisposed(),(0,y.guardrail_chain_add_token_limit)(this._handle,e,t),this}addRegexFilter(e,t=[]){return this.assertNotDisposed(),(0,y.guardrail_chain_add_regex_filter)(this._handle,e,t),this}addSchema(e){return this.assertNotDisposed(),(0,y.guardrail_chain_add_schema)(this._handle,JSON.stringify(e)),this}list(){return this.assertNotDisposed(),(0,y.guardrail_chain_list)(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,y.destroy_guardrail_chain)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("GuardrailChain has been destroyed")}};var k=require("gauss-napi"),ke=class{_handle;disposed=!1;constructor(){this._handle=(0,k.create_approval_manager)()}get handle(){return this._handle}request(e,t,r){return this.assertNotDisposed(),(0,k.approval_request)(this._handle,e,JSON.stringify(t),r)}approve(e,t){this.assertNotDisposed(),(0,k.approval_approve)(this._handle,e,t?JSON.stringify(t):void 0)}deny(e,t){this.assertNotDisposed(),(0,k.approval_deny)(this._handle,e,t)}listPending(){return this.assertNotDisposed(),(0,k.approval_list_pending)(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,k.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"),Ce=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"),Re=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 C=require("gauss-napi"),Se=class{_handle;disposed=!1;constructor(){this._handle=(0,C.create_telemetry)()}get handle(){return this._handle}recordSpan(e,t,r){this.assertNotDisposed();let n=typeof e=="string"?{name:e,span_type:"custom",start_ms:Date.now()-(t??0),duration_ms:t??0,attributes:r??{},status:"ok",children:[]}:e;(0,C.telemetry_record_span)(this._handle,JSON.stringify(n))}exportSpans(){return this.assertNotDisposed(),(0,C.telemetry_export_spans)(this._handle)}exportMetrics(){return this.assertNotDisposed(),(0,C.telemetry_export_metrics)(this._handle)}clear(){this.assertNotDisposed(),(0,C.telemetry_clear)(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,C.destroy_telemetry)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Telemetry has been destroyed")}};var De=require("fs"),jt=require("http"),Ut=require("path");var N=require("gauss-napi"),_e=new Map;function Dt(o,e){_e.set(o,e)}function It(o){return _e.get(o)}function Ot(){_e.clear()}function Mt(o){return(0,N.count_tokens)(o)}function Nt(o,e){return(0,N.count_tokens_for_model)(o,e)}function Lt(o){return(0,N.count_message_tokens)(o)}function Ht(o){return(0,N.get_context_window_size)(o)}function Ee(o,e){let t=_e.get(o);if(t){let n=e.inputTokens*t.inputPerToken,s=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:o,normalizedModel:o,currency:"USD",inputTokens:e.inputTokens,outputTokens:e.outputTokens,reasoningTokens:e.reasoningTokens??0,cacheReadTokens:e.cacheReadTokens??0,cacheCreationTokens:e.cacheCreationTokens??0,inputCostUsd:n,outputCostUsd:s,reasoningCostUsd:i,cacheReadCostUsd:a,cacheCreationCostUsd:l,totalCostUsd:n+s+i+a+l}}let r=(0,N.estimate_cost)(o,e.inputTokens,e.outputTokens,e.reasoningTokens,e.cacheReadTokens,e.cacheCreationTokens);return{model:String(r.model??o),normalizedModel:String(r.normalized_model??o),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 S=class extends Error{},xr=["openai","anthropic","google","groq","ollama","deepseek","openrouter","together","fireworks","mistral","perplexity","xai"],Ae=class{telemetry;approvals;model;routingPolicy;authToken;authClaims;persistPath;historyLimit;streamReplayLimit;context;latestCost=null;history=[];nextStreamEventId=1;streamEvents=[];explainTraces=[];nextExplainTraceId=1;latestExplainTraceId=null;policyDriftAlertHooks=[];policyDriftSinks=[];policyDriftScheduleConfig=null;policyDriftRuns=[];nextPolicyDriftRunId=1;policyLifecycleVersions=[];nextPolicyLifecycleVersion=1;activePolicyVersionId=null;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}onPolicyDriftAlert(e){return this.policyDriftAlertHooks.push(e),()=>{let t=this.policyDriftAlertHooks.indexOf(e);t>=0&&this.policyDriftAlertHooks.splice(t,1)}}registerPolicyDriftSink(e){let t=e.trim();if(!t)throw new u("sinkId must be a non-empty string","sinkId");return this.policyDriftSinks.includes(t)||this.policyDriftSinks.push(t),this}setCostUsage(e){return this.latestCost=Ee(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,latestExplainTraceId:t.latestExplainTraceId}))}getDag(e){let t=this.filterHistory(e),r=t[t.length-1];if(!r||!Array.isArray(r.spans))return{nodes:[],edges:[]};let n=r.spans.map((i,a)=>({id:String(a),label:this.spanLabel(i,a)})),s=n.slice(1).map((i,a)=>({from:String(a),to:i.id}));return{nodes:n,edges:s}}async startServer(e="127.0.0.1",t=4200){if(this.server){let n=this.server.address();return n&&typeof n!="string"?{url:`http://${e}:${n.port}`}:{url:`http://${e}:${t}`}}this.server=(0,jt.createServer)((n,s)=>{if(!n.url){s.statusCode=400,s.end("Bad request");return}let i=new URL(n.url,`http://${n.headers.host??`${e}:${t}`}`),a=i.pathname;if(a.startsWith("/api/")&&!this.isAuthorized(n,i)){s.statusCode=401,s.setHeader("Content-Type","application/json; charset=utf-8"),s.end(JSON.stringify({error:"Unauthorized"}));return}try{if(a==="/api/snapshot"){let l=i.searchParams.get("section"),d=l?this.snapshot(this.parseSection(l)):this.snapshot();s.setHeader("Content-Type","application/json; charset=utf-8"),s.end(JSON.stringify(d,null,2));return}if(a==="/api/history"){let l=this.applyAuthClaims(this.parseContextFilters(i.searchParams));s.setHeader("Content-Type","application/json; charset=utf-8"),s.end(JSON.stringify(this.getHistory(l),null,2));return}if(a==="/api/timeline"){let l=this.applyAuthClaims(this.parseContextFilters(i.searchParams));s.setHeader("Content-Type","application/json; charset=utf-8"),s.end(JSON.stringify(this.getTimeline(l),null,2));return}if(a==="/api/dag"){let l=this.applyAuthClaims(this.parseContextFilters(i.searchParams));s.setHeader("Content-Type","application/json; charset=utf-8"),s.end(JSON.stringify(this.getDag(l),null,2));return}if(a==="/api/ops/capabilities"){s.setHeader("Content-Type","application/json; charset=utf-8"),s.end(JSON.stringify(this.opsCapabilities(),null,2));return}if(a==="/api/ops/health"){s.setHeader("Content-Type","application/json; charset=utf-8"),s.end(JSON.stringify(this.opsHealth(),null,2));return}if(a==="/api/ops/summary"){let l=this.applyAuthClaims(this.parseContextFilters(i.searchParams));s.setHeader("Content-Type","application/json; charset=utf-8"),s.end(JSON.stringify(this.opsSummary(l),null,2));return}if(a==="/api/ops/tenants"){let l=this.applyAuthClaims(this.parseContextFilters(i.searchParams));s.setHeader("Content-Type","application/json; charset=utf-8"),s.end(JSON.stringify(this.opsTenants(l),null,2));return}if(a==="/api/ops/policy/explain"){s.setHeader("Content-Type","application/json; charset=utf-8"),s.end(JSON.stringify(this.opsPolicyExplain(i.searchParams),null,2));return}if(a==="/api/ops/policy/explain/batch"){s.setHeader("Content-Type","application/json; charset=utf-8"),s.end(JSON.stringify(this.opsPolicyExplainBatch(i.searchParams),null,2));return}if(a==="/api/ops/policy/explain/simulate"){s.setHeader("Content-Type","application/json; charset=utf-8"),s.end(JSON.stringify(this.opsPolicyExplainSimulation(i.searchParams),null,2));return}if(a==="/api/ops/policy/explain/diff"){s.setHeader("Content-Type","application/json; charset=utf-8"),s.end(JSON.stringify(this.opsPolicyExplainDiff(i.searchParams),null,2));return}if(a==="/api/ops/policy/explain/traces"){s.setHeader("Content-Type","application/json; charset=utf-8"),s.end(JSON.stringify(this.opsPolicyExplainTraces(i.searchParams),null,2));return}if(a==="/api/ops/policy/lifecycle/draft"){s.setHeader("Content-Type","application/json; charset=utf-8"),s.end(JSON.stringify(this.opsPolicyLifecycleDraft(i.searchParams),null,2));return}if(a==="/api/ops/policy/lifecycle/validate"){s.setHeader("Content-Type","application/json; charset=utf-8"),s.end(JSON.stringify(this.opsPolicyLifecycleValidate(i.searchParams),null,2));return}if(a==="/api/ops/policy/lifecycle/approve"){s.setHeader("Content-Type","application/json; charset=utf-8"),s.end(JSON.stringify(this.opsPolicyLifecycleApprove(i.searchParams),null,2));return}if(a==="/api/ops/policy/lifecycle/promote"){s.setHeader("Content-Type","application/json; charset=utf-8"),s.end(JSON.stringify(this.opsPolicyLifecyclePromote(i.searchParams),null,2));return}if(a==="/api/ops/policy/lifecycle/versions"){s.setHeader("Content-Type","application/json; charset=utf-8"),s.end(JSON.stringify(this.opsPolicyLifecycleVersions(),null,2));return}if(a==="/api/ops/policy/drift/schedule/set"){s.setHeader("Content-Type","application/json; charset=utf-8"),s.end(JSON.stringify(this.opsPolicyDriftScheduleSet(i.searchParams),null,2));return}if(a==="/api/ops/policy/drift/schedule/run"){s.setHeader("Content-Type","application/json; charset=utf-8"),s.end(JSON.stringify(this.opsPolicyDriftScheduleRun(i.searchParams),null,2));return}if(a==="/api/ops/policy/drift/schedule"){s.setHeader("Content-Type","application/json; charset=utf-8"),s.end(JSON.stringify(this.opsPolicyDriftSchedule(),null,2));return}if(a==="/api/ops/policy/drift"){s.setHeader("Content-Type","application/json; charset=utf-8"),s.end(JSON.stringify(this.opsPolicyDrift(i.searchParams),null,2));return}if(a==="/api/stream"){let l=this.applyAuthClaims(this.parseContextFilters(i.searchParams)),d=this.parseStreamChannels(i.searchParams);for(let lr of d)this.assertChannelAllowed(lr);let c=i.searchParams.get("once")==="1",p=this.parseLastEventId(n,i.searchParams);s.statusCode=200,s.setHeader("Content-Type","text/event-stream; charset=utf-8"),s.setHeader("Cache-Control","no-cache"),s.setHeader("Connection","keep-alive");let m=this.replayStreamEvents(s,d,l,p);if(c&&m>0){s.end();return}if(this.emitStreamBatch(s,d,l),c){s.end();return}let h=setInterval(()=>{s.writableEnded||s.destroyed||this.emitStreamBatch(s,d,l)},1e3),G=()=>clearInterval(h);n.on("close",G),n.on("aborted",G);return}if(a==="/"){s.setHeader("Content-Type","text/html; charset=utf-8"),s.end(this.renderDashboardHtml());return}if(a==="/ops"){s.setHeader("Content-Type","text/html; charset=utf-8"),s.end(this.renderHostedOpsHtml());return}if(a==="/ops/tenants"){s.setHeader("Content-Type","text/html; charset=utf-8"),s.end(this.renderHostedTenantOpsHtml());return}s.statusCode=404,s.end("Not found")}catch(l){if(l instanceof S){s.statusCode=403,s.setHeader("Content-Type","application/json; charset=utf-8"),s.end(JSON.stringify({error:l.message}));return}let d=l instanceof Error?l.message:"Internal error";s.statusCode=500,s.setHeader("Content-Type","application/json; charset=utf-8"),s.end(JSON.stringify({error:d}))}}),await new Promise((n,s)=>{this.server.once("error",s),this.server.listen(t,e,()=>n())});let r=this.server.address();return!r||typeof r=="string"?{url:`http://${e}:${t}`}:{url:`http://${e}:${r.port}`}}async stopServer(){if(!this.server)return;let e=this.server;this.server=null,await new Promise((t,r)=>{e.close(n=>n?r(n):t())})}destroy(){this.stopServer()}[Symbol.dispose](){this.destroy()}captureSnapshot(){this.assertContextAllowed(this.context);let e={generatedAt:new Date().toISOString(),context:{...this.context},spans:this.telemetry?.exportSpans()??[],metrics:this.telemetry?.exportMetrics()??{},pendingApprovals:this.approvals?.listPending()??[],latestCost:this.latestCost,latestExplainTraceId:this.latestExplainTraceId};return this.history.push(e),this.history.length>this.historyLimit&&this.history.shift(),this.persistPath&&((0,De.mkdirSync)((0,Ut.dirname)(this.persistPath),{recursive:!0}),(0,De.appendFileSync)(this.persistPath,`${JSON.stringify(e)}
|
|
21
|
+
`,"utf8")),e}parseSection(e){if(e==="spans"||e==="metrics"||e==="pendingApprovals"||e==="latestCost")return e;throw new u(`Unknown section "${e}"`,"section")}parseStreamChannel(e){if(e===null||e==="snapshot")return"snapshot";if(e==="timeline"||e==="dag")return e;throw new u(`Unknown stream channel "${e}"`,"channel")}parseStreamChannels(e){let t=e.get("channels");if(!t)return[this.parseStreamChannel(e.get("channel"))];let r=t.split(",").map(n=>n.trim()).filter(n=>n.length>0).map(n=>this.parseStreamChannel(n));return r.length===0?["snapshot"]:[...new Set(r)]}parseLastEventId(e,t){let r=t.get("lastEventId"),n=e.headers["last-event-id"],s=r??(typeof n=="string"?n:null);if(s===null)return null;let i=Number.parseInt(s,10);if(!Number.isFinite(i)||i<0)throw new u(`Invalid lastEventId "${s}"`,"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(!xr.includes(e))throw new u(`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 u(`Invalid ${t} "${e}"`,t);return r}parsePolicyExplainScenario(e){let t=this.parsePolicyProvider(typeof e.provider=="string"&&e.provider.trim().length>0?e.provider:"openai"),r=typeof e.model=="string"&&e.model.trim().length>0?e.model:"gpt-5.2",n=Array.isArray(e.available)?e.available:typeof e.available=="string"?e.available.split(","):[],s=n.length>0?n.map(p=>String(p).trim()).filter(p=>p.length>0).map(p=>this.parsePolicyProvider(p)):void 0,i=Array.isArray(e.tags)?e.tags:typeof e.tags=="string"?e.tags.split(","):[],a=i.length>0?i.map(p=>String(p).trim()).filter(p=>p.length>0):void 0,l=this.parseOptionalNumber(e.cost!==void 0&&e.cost!==null?String(e.cost):null,"cost"),d=this.parseOptionalNumber(e.rpm!==void 0&&e.rpm!==null?String(e.rpm):null,"rpm"),c=this.parseOptionalNumber(e.hour!==void 0&&e.hour!==null?String(e.hour):null,"hour");return{provider:t,model:r,options:{availableProviders:s,estimatedCostUsd:l,currentRequestsPerMinute:d,currentHourUtc:c,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 u("Missing scenarios query parameter","scenarios");let r;try{r=JSON.parse(t)}catch{throw new u("Invalid scenarios JSON payload","scenarios")}if(!Array.isArray(r)||r.length===0)throw new u("scenarios must be a non-empty array","scenarios");return r.map((n,s)=>{if(typeof n!="object"||n===null)throw new u(`Scenario ${s} must be an object`,"scenarios");return this.parsePolicyExplainScenario(n)})}parseLifecyclePolicy(e){let t=e.get("policy");if(!t)throw new u("Missing policy query parameter","policy");let r;try{r=JSON.parse(t)}catch{throw new u("Invalid policy JSON payload","policy")}if(!r||typeof r!="object")throw new u("policy must be a JSON object","policy");return r}parseOptionalPolicyFromQuery(e,t){let r=e.get(t);if(!r||r.trim().length===0)return;let n;try{n=JSON.parse(r)}catch{throw new u(`Invalid ${t} JSON payload`,t)}if(!n||typeof n!="object")throw new u(`${t} must be a JSON object`,t);return n}parsePolicyDriftGuardrails(e){let t=this.parseOptionalNumber(e.get("maxChanged"),"maxChanged"),r=this.parseOptionalNumber(e.get("maxRegressions"),"maxRegressions"),n=this.parseOptionalNumber(e.get("minCandidatePassRate"),"minCandidatePassRate");return{...t!==void 0?{maxChanged:t}:{},...r!==void 0?{maxRegressions:r}:{},...n!==void 0?{minCandidatePassRate:n}:{}}}parsePolicyDriftWindow(e){if(!e||e.trim().length===0)return"custom";let t=e.trim().toLowerCase();if(t==="last_1h"||t==="last_24h"||t==="last_7d"||t==="custom")return t;throw new u(`Invalid policy drift window "${e}"`,"window")}cloneRoutingPolicy(e){return JSON.parse(JSON.stringify(e))}summarizeLifecycleVersion(e){return{versionId:e.versionId,status:e.status,createdAt:e.createdAt,validatedAt:e.validatedAt,approvedAt:e.approvedAt,promotedAt:e.promotedAt,hasValidation:!!e.validation,validation:e.validation,audit:e.audit}}findLifecycleVersion(e){let t=this.policyLifecycleVersions.find(r=>r.versionId===e);if(!t)throw new u(`Unknown lifecycle version "${e}"`,"version");return t}resolveLifecycleActor(e,t,r){let s=r.get("role")?.trim().toLowerCase(),i=(this.authClaims?.roles??[]).map(d=>d.trim().toLowerCase()).filter(d=>d.length>0);if(i.length>0){if(s&&!i.includes(s))throw new S(`Forbidden lifecycle role "${s}"`);if(s&&!t.includes(s))throw new S(`Forbidden lifecycle action "${e}"`);let d=s??i.find(m=>t.includes(m));if(!d)throw new S(`Forbidden lifecycle action "${e}"`);let c=r.get("actor")?.trim()||void 0,p=r.get("comment")?.trim()||void 0;return{role:d,actor:c,comment:p}}if(s&&!t.includes(s))throw new S(`Forbidden lifecycle action "${e}"`);let a=r.get("actor")?.trim()||void 0,l=r.get("comment")?.trim()||void 0;return{role:s??t[0],actor:a,comment:l}}mergeLifecycleAudit(e,t){e.audit={...e.audit??{},...t}}opsPolicyLifecycleDraft(e){let t=this.resolveLifecycleActor("draft",["author","operator","admin"],e),r=new Date().toISOString(),n={versionId:`policy-v${this.nextPolicyLifecycleVersion++}`,status:"draft",createdAt:r,policy:this.cloneRoutingPolicy(this.parseLifecyclePolicy(e)),audit:{draftedByRole:t.role,draftedBy:t.actor,draftComment:t.comment}};return this.policyLifecycleVersions.push(n),{ok:!0,version:this.summarizeLifecycleVersion(n)}}opsPolicyLifecycleValidate(e){let t=this.resolveLifecycleActor("validate",["author","reviewer","operator","admin"],e),r=e.get("version");if(!r)throw new u("Missing version query parameter","version");let n=this.findLifecycleVersion(r),s=this.parsePolicyExplainBatchScenarios(e).map(a=>({provider:a.provider,model:a.model,options:a.options})),i=ae(n.policy,s);return n.validation=i,this.mergeLifecycleAudit(n,{validatedByRole:t.role,validatedBy:t.actor,validationComment:t.comment}),i.failed===0&&(n.status="validated",n.validatedAt=new Date().toISOString()),{ok:i.failed===0,version:this.summarizeLifecycleVersion(n),validation:i}}opsPolicyLifecycleApprove(e){let t=this.resolveLifecycleActor("approve",["reviewer","operator","admin"],e),r=e.get("version");if(!r)throw new u("Missing version query parameter","version");let n=this.findLifecycleVersion(r);return!n.validation||n.validation.failed>0||n.status!=="validated"?{ok:!1,version:this.summarizeLifecycleVersion(n),error:"version must pass validation before approval"}:(n.status="approved",n.approvedAt=new Date().toISOString(),this.mergeLifecycleAudit(n,{approvedByRole:t.role,approvedBy:t.actor,approvalComment:t.comment}),{ok:!0,version:this.summarizeLifecycleVersion(n)})}opsPolicyLifecyclePromote(e){let t=this.resolveLifecycleActor("promote",["promoter","operator","admin"],e),r=e.get("version");if(!r)throw new u("Missing version query parameter","version");let n=this.findLifecycleVersion(r);if(n.status!=="approved")return{ok:!1,activeVersionId:this.activePolicyVersionId,version:this.summarizeLifecycleVersion(n),error:"version must be approved before promotion"};for(let s of this.policyLifecycleVersions)s.versionId!==r&&s.status==="promoted"&&(s.status="approved");return n.status="promoted",n.promotedAt=new Date().toISOString(),this.mergeLifecycleAudit(n,{promotedByRole:t.role,promotedBy:t.actor,promotionComment:t.comment}),this.activePolicyVersionId=n.versionId,this.routingPolicy=this.cloneRoutingPolicy(n.policy),{ok:!0,activeVersionId:this.activePolicyVersionId,version:this.summarizeLifecycleVersion(n)}}opsPolicyLifecycleVersions(){return{ok:!0,activeVersionId:this.activePolicyVersionId,versions:this.policyLifecycleVersions.map(e=>this.summarizeLifecycleVersion(e))}}buildStreamEvent(e,t,r){let n=e==="timeline"?this.getTimeline(t):e==="dag"?this.getDag(t):this.filterHistory(t).slice(-1)[0]??r,s={id:this.nextStreamEventId++,event:e,generatedAt:r.generatedAt,context:{...r.context},payload:n};return this.streamEvents.push(s),this.streamEvents.length>this.streamReplayLimit&&this.streamEvents.shift(),s}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,supportsPolicyExplainBatch:!0,supportsPolicyExplainTraces:!0,supportsPolicyExplainDiff:!0,supportsPolicyLifecycle:!0,supportsPolicyLifecycleRbac:!0,supportsPolicyDriftMonitoring:!0,hostedDashboardPath:"/ops",hostedTenantDashboardPath:"/ops/tenants",policyExplainPath:"/api/ops/policy/explain",policyExplainBatchPath:"/api/ops/policy/explain/batch",policyExplainSimulatePath:"/api/ops/policy/explain/simulate",policyExplainTracePath:"/api/ops/policy/explain/traces",policyExplainDiffPath:"/api/ops/policy/explain/diff",policyLifecycleBasePath:"/api/ops/policy/lifecycle",policyLifecycleRoleParam:"role",policyLifecycleAuditFields:["draftedByRole","validatedByRole","approvedByRole","promotedByRole"],policyDriftPath:"/api/ops/policy/drift"}}opsHealth(){return{status:"ok",generatedAt:new Date().toISOString(),historySize:this.history.length,streamBufferSize:this.streamEvents.length}}opsSummary(e){let t=this.filterHistory(e),r=t[t.length-1],n=r?.spans,o=r?.pendingApprovals,i=e&&(e.tenantId||e.sessionId||e.runId)?this.streamEvents.filter(p=>this.matchesContext(p.context,e)).length:this.streamEvents.length,a=new Set,l=new Set,d=new Set;for(let p of t)p.context.tenantId&&a.add(p.context.tenantId),p.context.sessionId&&l.add(p.context.sessionId),p.context.runId&&d.add(p.context.runId);return{status:"ok",generatedAt:new Date().toISOString(),historySize:t.length,streamBufferSize:i,spansCount:Array.isArray(n)?n.length:0,pendingApprovalsCount:Array.isArray(o)?o.length:0,latestTotalCostUsd:r?.latestCost?.totalCostUsd??0,tenantCount:a.size,sessionCount:l.size,runCount:d.size}}opsTenants(e){let t=this.filterHistory(e),r=new Map;for(let n of t){let o=n.context.tenantId??"_unscoped",i=r.get(o)??{snapshotCount:0,spansCount:0,pendingApprovalsCount:0,latestTotalCostUsd:0,latestGeneratedAt:n.generatedAt,sessions:new Set,runs:new Set};i.snapshotCount+=1,i.spansCount+=Array.isArray(n.spans)?n.spans.length:0,i.pendingApprovalsCount+=Array.isArray(n.pendingApprovals)?n.pendingApprovals.length:0,n.latestCost?.totalCostUsd!==void 0&&(i.latestTotalCostUsd=n.latestCost.totalCostUsd),n.generatedAt>=i.latestGeneratedAt&&(i.latestGeneratedAt=n.generatedAt),n.context.sessionId&&i.sessions.add(n.context.sessionId),n.context.runId&&i.runs.add(n.context.runId),r.set(o,i)}return[...r.entries()].map(([n,o])=>({tenantId:n,snapshotCount:o.snapshotCount,spansCount:o.spansCount,pendingApprovalsCount:o.pendingApprovalsCount,latestTotalCostUsd:o.latestTotalCostUsd,sessionCount:o.sessions.size,runCount:o.runs.size,latestGeneratedAt:o.latestGeneratedAt})).sort((n,o)=>n.tenantId.localeCompare(o.tenantId))}recordPolicyExplainTrace(e,t){let r={traceId:`trace-${this.nextExplainTraceId++}`,generatedAt:new Date().toISOString(),mode:e,payload:t};return this.latestExplainTraceId=r.traceId,this.explainTraces.push(r),this.explainTraces.length>this.historyLimit&&this.explainTraces.shift(),r}opsPolicyExplain(e){let t=this.parsePolicyExplainOptions(e),r=H(this.routingPolicy,t.provider,t.model,t.options),n=this.recordPolicyExplainTrace("single",{input:{provider:t.provider,model:t.model,options:t.options},explanation:r});return{...r,traceId:n.traceId}}opsPolicyExplainBatch(e){let t=this.parsePolicyExplainBatchScenarios(e),r=this.buildPolicyExplainBatchResponse(t),n=this.recordPolicyExplainTrace("batch",r);return{...r,traceId:n.traceId}}buildPolicyExplainBatchResponse(e){let t=e.map((n,o)=>({index:o,input:{provider:n.provider,model:n.model},explanation:H(this.routingPolicy,n.provider,n.model,n.options)})),r=t.filter(n=>n.explanation.ok).length;return{ok:!0,total:t.length,passed:r,failed:t.length-r,results:t}}opsPolicyExplainSimulation(e){let t=this.parsePolicyExplainBatchScenarios(e),r=this.buildPolicyExplainBatchResponse(t),n=this.recordPolicyExplainTrace("simulate",r);return{...r,traceId:n.traceId}}opsPolicyExplainDiff(e){let t=this.parsePolicyExplainBatchScenarios(e),r=Y(this.routingPolicy,t,void 0),n={ok:!0,total:r.total,baselinePassed:r.baselinePassed,candidatePassed:r.candidatePassed,changed:r.changed,regressions:r.regressions,results:r.results},o=this.recordPolicyExplainTrace("diff",n);return{...n,traceId:o.traceId}}opsPolicyDrift(e){let t=this.parsePolicyExplainBatchScenarios(e),r=e.get("baselineVersion"),n=e.get("candidateVersion"),o=r?this.cloneRoutingPolicy(this.findLifecycleVersion(r).policy):this.activePolicyVersionId?this.cloneRoutingPolicy(this.findLifecycleVersion(this.activePolicyVersionId).policy):void 0,i=n?this.cloneRoutingPolicy(this.findLifecycleVersion(n).policy):void 0,a=this.parseOptionalPolicyFromQuery(e,"baselinePolicy")??o,l=this.parseOptionalPolicyFromQuery(e,"candidatePolicy")??i??this.routingPolicy,d=Y(l,t,a),p=le(d,this.parsePolicyDriftGuardrails(e)),c={ok:p.ok,alert:!p.ok,generatedAt:new Date().toISOString(),baselineVersionId:r??this.activePolicyVersionId??null,candidateVersionId:n??null,diff:d,guardrails:p};if(c.alert)for(let m of this.policyDriftAlertHooks)m(c);let h=this.recordPolicyExplainTrace("drift",c);return{...c,traceId:h.traceId}}opsPolicyExplainTraces(e){let t=e.get("traceId"),r=t?this.explainTraces.filter(n=>n.traceId===t):this.explainTraces;return{total:r.length,traces:r}}emitStreamBatch(e,t,r){let n=this.captureSnapshot();for(let o of t)this.writeSseEvent(e,this.buildStreamEvent(o,r,n))}replayStreamEvents(e,t,r,n){if(n===null)return 0;let o=0;for(let i of this.streamEvents)i.id<=n||t.includes(i.event)&&this.matchesContext(i.context,r)&&(this.writeSseEvent(e,i),o+=1);return o}assertChannelAllowed(e){let t=(this.authClaims?.roles??[]).map(r=>r.toLowerCase());if(t.length!==0&&!(t.includes("admin")||t.includes("operator"))&&!((e==="snapshot"||e==="timeline")&&(t.includes("viewer")||t.includes("reader"))))throw new R(`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 R("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 R("Forbidden session scope");!t.sessionId&&r.length===1&&(t.sessionId=r[0]);let n=this.authClaims.allowedRunIds??[];if(t.runId&&n.length>0&&!n.includes(t.runId))throw new R("Forbidden run scope");return!t.runId&&n.length===1&&(t.runId=n[0]),t}assertContextAllowed(e){this.authClaims&&this.applyAuthClaims(e)}filterHistory(e){return!e||!e.tenantId&&!e.sessionId&&!e.runId?[...this.history]:this.history.filter(t=>this.matchesContext(t.context,e))}matchesContext(e,t){return!(t.tenantId&&e.tenantId!==t.tenantId||t.sessionId&&e.sessionId!==t.sessionId||t.runId&&e.runId!==t.runId)}spanLabel(e,t){if(e&&typeof e=="object"){let r=e;if(typeof r.name=="string")return r.name;if(typeof r.span_name=="string")return r.span_name}return`span-${t+1}`}isAuthorized(e,t){if(!this.authToken)return!0;let r=e.headers.authorization,n=typeof r=="string"&&r===`Bearer ${this.authToken}`,o=e.headers["x-gauss-token"],i=typeof o=="string"&&o===this.authToken,a=t.searchParams.get("token")===this.authToken;return n||i||a}renderDashboardHtml(){return`<!doctype html>
|
|
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,supportsPolicyExplainTraces:!0,supportsPolicyExplainDiff:!0,supportsPolicyLifecycle:!0,supportsPolicyLifecycleRbac:!0,supportsPolicyDriftMonitoring:!0,supportsPolicyDriftScheduler:!0,supportsPolicyDriftWindows:!0,supportsPolicyDriftAlertSinks:!0,hostedDashboardPath:"/ops",hostedTenantDashboardPath:"/ops/tenants",policyExplainPath:"/api/ops/policy/explain",policyExplainBatchPath:"/api/ops/policy/explain/batch",policyExplainSimulatePath:"/api/ops/policy/explain/simulate",policyExplainTracePath:"/api/ops/policy/explain/traces",policyExplainDiffPath:"/api/ops/policy/explain/diff",policyLifecycleBasePath:"/api/ops/policy/lifecycle",policyLifecycleRoleParam:"role",policyLifecycleAuditFields:["draftedByRole","validatedByRole","approvedByRole","promotedByRole"],policyDriftPath:"/api/ops/policy/drift",policyDriftSchedulePath:"/api/ops/policy/drift/schedule",policyDriftScheduleRunPath:"/api/ops/policy/drift/schedule/run"}}opsHealth(){return{status:"ok",generatedAt:new Date().toISOString(),historySize:this.history.length,streamBufferSize:this.streamEvents.length}}opsSummary(e){let t=this.filterHistory(e),r=t[t.length-1],n=r?.spans,s=r?.pendingApprovals,i=e&&(e.tenantId||e.sessionId||e.runId)?this.streamEvents.filter(c=>this.matchesContext(c.context,e)).length:this.streamEvents.length,a=new Set,l=new Set,d=new Set;for(let c of t)c.context.tenantId&&a.add(c.context.tenantId),c.context.sessionId&&l.add(c.context.sessionId),c.context.runId&&d.add(c.context.runId);return{status:"ok",generatedAt:new Date().toISOString(),historySize:t.length,streamBufferSize:i,spansCount:Array.isArray(n)?n.length:0,pendingApprovalsCount:Array.isArray(s)?s.length:0,latestTotalCostUsd:r?.latestCost?.totalCostUsd??0,tenantCount:a.size,sessionCount:l.size,runCount:d.size}}opsTenants(e){let t=this.filterHistory(e),r=new Map;for(let n of t){let s=n.context.tenantId??"_unscoped",i=r.get(s)??{snapshotCount:0,spansCount:0,pendingApprovalsCount:0,latestTotalCostUsd:0,latestGeneratedAt:n.generatedAt,sessions:new Set,runs:new Set};i.snapshotCount+=1,i.spansCount+=Array.isArray(n.spans)?n.spans.length:0,i.pendingApprovalsCount+=Array.isArray(n.pendingApprovals)?n.pendingApprovals.length:0,n.latestCost?.totalCostUsd!==void 0&&(i.latestTotalCostUsd=n.latestCost.totalCostUsd),n.generatedAt>=i.latestGeneratedAt&&(i.latestGeneratedAt=n.generatedAt),n.context.sessionId&&i.sessions.add(n.context.sessionId),n.context.runId&&i.runs.add(n.context.runId),r.set(s,i)}return[...r.entries()].map(([n,s])=>({tenantId:n,snapshotCount:s.snapshotCount,spansCount:s.spansCount,pendingApprovalsCount:s.pendingApprovalsCount,latestTotalCostUsd:s.latestTotalCostUsd,sessionCount:s.sessions.size,runCount:s.runs.size,latestGeneratedAt:s.latestGeneratedAt})).sort((n,s)=>n.tenantId.localeCompare(s.tenantId))}recordPolicyExplainTrace(e,t){let r={traceId:`trace-${this.nextExplainTraceId++}`,generatedAt:new Date().toISOString(),mode:e,payload:t};return this.latestExplainTraceId=r.traceId,this.explainTraces.push(r),this.explainTraces.length>this.historyLimit&&this.explainTraces.shift(),r}opsPolicyExplain(e){let t=this.parsePolicyExplainOptions(e),r=H(this.routingPolicy,t.provider,t.model,t.options),n=this.recordPolicyExplainTrace("single",{input:{provider:t.provider,model:t.model,options:t.options},explanation:r});return{...r,traceId:n.traceId}}opsPolicyExplainBatch(e){let t=this.parsePolicyExplainBatchScenarios(e),r=this.buildPolicyExplainBatchResponse(t),n=this.recordPolicyExplainTrace("batch",r);return{...r,traceId:n.traceId}}buildPolicyExplainBatchResponse(e){let t=e.map((n,s)=>({index:s,input:{provider:n.provider,model:n.model},explanation:H(this.routingPolicy,n.provider,n.model,n.options)})),r=t.filter(n=>n.explanation.ok).length;return{ok:!0,total:t.length,passed:r,failed:t.length-r,results:t}}opsPolicyExplainSimulation(e){let t=this.parsePolicyExplainBatchScenarios(e),r=this.buildPolicyExplainBatchResponse(t),n=this.recordPolicyExplainTrace("simulate",r);return{...r,traceId:n.traceId}}opsPolicyExplainDiff(e){let t=this.parsePolicyExplainBatchScenarios(e),r=Q(this.routingPolicy,t,void 0),n={ok:!0,total:r.total,baselinePassed:r.baselinePassed,candidatePassed:r.candidatePassed,changed:r.changed,regressions:r.regressions,results:r.results},s=this.recordPolicyExplainTrace("diff",n);return{...n,traceId:s.traceId}}opsPolicyDriftScheduleSet(e){let t=e.get("scenarios");if(!t)throw new u("Missing scenarios query parameter","scenarios");this.parsePolicyExplainBatchScenarios(e);let r=this.parseOptionalNumber(e.get("intervalMs"),"intervalMs")??6e4;if(r<=0)throw new u("intervalMs must be > 0","intervalMs");let n=new Date().toISOString();return this.policyDriftScheduleConfig={enabled:!0,intervalMs:r,window:this.parsePolicyDriftWindow(e.get("window")),scenariosRaw:t,baselinePolicyRaw:e.get("baselinePolicy")??void 0,candidatePolicyRaw:e.get("candidatePolicy")??void 0,baselineVersionId:e.get("baselineVersion")??void 0,candidateVersionId:e.get("candidateVersion")??void 0,guardrails:this.parsePolicyDriftGuardrails(e),updatedAt:n,lastRunAt:this.policyDriftScheduleConfig?.lastRunAt},{ok:!0,schedule:{enabled:this.policyDriftScheduleConfig.enabled,intervalMs:this.policyDriftScheduleConfig.intervalMs,window:this.policyDriftScheduleConfig.window,updatedAt:this.policyDriftScheduleConfig.updatedAt,lastRunAt:this.policyDriftScheduleConfig.lastRunAt,baselineVersionId:this.policyDriftScheduleConfig.baselineVersionId,candidateVersionId:this.policyDriftScheduleConfig.candidateVersionId,hasBaselinePolicy:!!this.policyDriftScheduleConfig.baselinePolicyRaw,hasCandidatePolicy:!!this.policyDriftScheduleConfig.candidatePolicyRaw,guardrails:this.policyDriftScheduleConfig.guardrails}}}opsPolicyDriftSchedule(){return this.policyDriftScheduleConfig?{ok:!0,schedule:{enabled:this.policyDriftScheduleConfig.enabled,intervalMs:this.policyDriftScheduleConfig.intervalMs,window:this.policyDriftScheduleConfig.window,updatedAt:this.policyDriftScheduleConfig.updatedAt,lastRunAt:this.policyDriftScheduleConfig.lastRunAt,baselineVersionId:this.policyDriftScheduleConfig.baselineVersionId,candidateVersionId:this.policyDriftScheduleConfig.candidateVersionId,hasBaselinePolicy:!!this.policyDriftScheduleConfig.baselinePolicyRaw,hasCandidatePolicy:!!this.policyDriftScheduleConfig.candidatePolicyRaw,guardrails:this.policyDriftScheduleConfig.guardrails},runs:[...this.policyDriftRuns]}:{ok:!0,schedule:null,runs:[...this.policyDriftRuns]}}opsPolicyDriftScheduleRun(e){let t=new URLSearchParams(e);if(!t.get("scenarios")){if(!this.policyDriftScheduleConfig)throw new u("Missing scenarios query parameter","scenarios");t.set("scenarios",this.policyDriftScheduleConfig.scenariosRaw),t.get("window")||t.set("window",this.policyDriftScheduleConfig.window),!t.get("baselineVersion")&&this.policyDriftScheduleConfig.baselineVersionId&&t.set("baselineVersion",this.policyDriftScheduleConfig.baselineVersionId),!t.get("candidateVersion")&&this.policyDriftScheduleConfig.candidateVersionId&&t.set("candidateVersion",this.policyDriftScheduleConfig.candidateVersionId),!t.get("baselinePolicy")&&this.policyDriftScheduleConfig.baselinePolicyRaw&&t.set("baselinePolicy",this.policyDriftScheduleConfig.baselinePolicyRaw),!t.get("candidatePolicy")&&this.policyDriftScheduleConfig.candidatePolicyRaw&&t.set("candidatePolicy",this.policyDriftScheduleConfig.candidatePolicyRaw),!t.get("maxChanged")&&this.policyDriftScheduleConfig.guardrails.maxChanged!==void 0&&t.set("maxChanged",String(this.policyDriftScheduleConfig.guardrails.maxChanged)),!t.get("maxRegressions")&&this.policyDriftScheduleConfig.guardrails.maxRegressions!==void 0&&t.set("maxRegressions",String(this.policyDriftScheduleConfig.guardrails.maxRegressions)),!t.get("minCandidatePassRate")&&this.policyDriftScheduleConfig.guardrails.minCandidatePassRate!==void 0&&t.set("minCandidatePassRate",String(this.policyDriftScheduleConfig.guardrails.minCandidatePassRate))}let n={...this.opsPolicyDrift(t),runId:`drift-run-${this.nextPolicyDriftRunId++}`};return this.policyDriftRuns.push(n),this.policyDriftRuns.length>this.historyLimit&&this.policyDriftRuns.shift(),this.policyDriftScheduleConfig&&(this.policyDriftScheduleConfig.lastRunAt=n.generatedAt,this.policyDriftScheduleConfig.updatedAt=new Date().toISOString()),n}opsPolicyDrift(e){let t=this.parsePolicyExplainBatchScenarios(e),r=this.parsePolicyDriftWindow(e.get("window")),n=e.get("baselineVersion"),s=e.get("candidateVersion"),i=n?this.cloneRoutingPolicy(this.findLifecycleVersion(n).policy):this.activePolicyVersionId?this.cloneRoutingPolicy(this.findLifecycleVersion(this.activePolicyVersionId).policy):void 0,a=s?this.cloneRoutingPolicy(this.findLifecycleVersion(s).policy):void 0,l=this.parseOptionalPolicyFromQuery(e,"baselinePolicy")??i,d=this.parseOptionalPolicyFromQuery(e,"candidatePolicy")??a??this.routingPolicy,c=Q(d,t,l),p=le(c,this.parsePolicyDriftGuardrails(e)),m={ok:p.ok,alert:!p.ok,generatedAt:new Date().toISOString(),window:r,baselineVersionId:n??this.activePolicyVersionId??null,candidateVersionId:s??null,diff:c,guardrails:p,sinksTriggered:p.ok?[]:[...this.policyDriftSinks]};if(m.alert)for(let G of this.policyDriftAlertHooks)G(m);let h=this.recordPolicyExplainTrace("drift",m);return{...m,traceId:h.traceId}}opsPolicyExplainTraces(e){let t=e.get("traceId"),r=t?this.explainTraces.filter(n=>n.traceId===t):this.explainTraces;return{total:r.length,traces:r}}emitStreamBatch(e,t,r){let n=this.captureSnapshot();for(let s of t)this.writeSseEvent(e,this.buildStreamEvent(s,r,n))}replayStreamEvents(e,t,r,n){if(n===null)return 0;let s=0;for(let i of this.streamEvents)i.id<=n||t.includes(i.event)&&this.matchesContext(i.context,r)&&(this.writeSseEvent(e,i),s+=1);return s}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 S(`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 S("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 S("Forbidden session scope");!t.sessionId&&r.length===1&&(t.sessionId=r[0]);let n=this.authClaims.allowedRunIds??[];if(t.runId&&n.length>0&&!n.includes(t.runId))throw new S("Forbidden run scope");return!t.runId&&n.length===1&&(t.runId=n[0]),t}assertContextAllowed(e){this.authClaims&&this.applyAuthClaims(e)}filterHistory(e){return!e||!e.tenantId&&!e.sessionId&&!e.runId?[...this.history]:this.history.filter(t=>this.matchesContext(t.context,e))}matchesContext(e,t){return!(t.tenantId&&e.tenantId!==t.tenantId||t.sessionId&&e.sessionId!==t.sessionId||t.runId&&e.runId!==t.runId)}spanLabel(e,t){if(e&&typeof e=="object"){let r=e;if(typeof r.name=="string")return r.name;if(typeof r.span_name=="string")return r.span_name}return`span-${t+1}`}isAuthorized(e,t){if(!this.authToken)return!0;let r=e.headers.authorization,n=typeof r=="string"&&r===`Bearer ${this.authToken}`,s=e.headers["x-gauss-token"],i=typeof s=="string"&&s===this.authToken,a=t.searchParams.get("token")===this.authToken;return n||i||a}renderDashboardHtml(){return`<!doctype html>
|
|
26
26
|
<html lang="en">
|
|
27
27
|
<head>
|
|
28
28
|
<meta charset="utf-8" />
|
|
@@ -163,14 +163,14 @@ ${i}`:i,c=await d.agent.run(p),h={text:c.text,...c.structuredOutput?{structuredO
|
|
|
163
163
|
refresh();
|
|
164
164
|
</script>
|
|
165
165
|
</body>
|
|
166
|
-
</html>`}};var
|
|
166
|
+
</html>`}};var z=require("gauss-napi");function Gt(o){return(0,z.create_fallback_provider)(o)}function Vt(o,e,t){return(0,z.create_circuit_breaker)(o,e,t)}function rt(o,e,t){return(0,z.create_resilient_provider)(o,e,t)}function Jt(o,e,t=!0){return rt(o.handle,e.map(r=>r.handle),t)}var Ie=require("gauss-napi");function Bt(o){return(0,Ie.agent_config_from_json)(o)}function $t(o){return(0,Ie.agent_config_resolve_env)(o)}var W=require("gauss-napi"),Oe=class{_handle;disposed=!1;constructor(e){this._handle=(0,W.create_tool_validator)(e)}get handle(){return this._handle}validate(e,t){return this.assertNotDisposed(),JSON.parse((0,W.tool_validator_validate)(this._handle,JSON.stringify(e),JSON.stringify(t)))}destroy(){if(!this.disposed){this.disposed=!0;try{(0,W.destroy_tool_validator)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("ToolValidator has been destroyed")}};var qt=require("gauss-napi");function Ft(o){return(0,qt.parse_partial_json)(o)}function br(o,e){let t;switch(o.backoff){case"fixed":t=o.baseDelayMs;break;case"linear":t=o.baseDelayMs*e;break;case"exponential":t=o.baseDelayMs*Math.pow(2,e-1);break}let r=t*o.jitter;return t+=Math.random()*r*2-r,Math.min(Math.max(0,t),o.maxDelayMs)}function Tr(o){return new Promise(e=>setTimeout(e,o))}async function nt(o,e){let t=e?.maxRetries??3,r=e?.backoff??"exponential",n=e?.baseDelayMs??1e3,s=e?.maxDelayMs??3e4,i=e?.jitter??.1,a=e?.retryIf,l=e?.onRetry,d;for(let c=0;c<=t;c++)try{return await o()}catch(p){if(d=p instanceof Error?p:new Error(String(p)),c===t||a&&!a(d,c+1))break;let m=br({backoff:r,baseDelayMs:n,maxDelayMs:s,jitter:i},c+1);l?.(d,c+1,m),await Tr(m)}throw d}function zt(o,e){return t=>nt(()=>o.run(t),e)}function wr(o,e){let t=JSON.stringify(e,null,2);return`${o}
|
|
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(o){let e=o.match(/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/);if(e)return e[1].trim();let t=o.indexOf("{"),r=o.indexOf("[");if(t===-1&&r===-1)return o.trim();let n=t===-1?r:r===-1?t:Math.min(t,r),i=o[n]==="["?"]":"}",a=0,l=!1,d=!1;for(let c=n;c<o.length;c++){let p=o[c];if(d){d=!1;continue}if(p==="\\"){d=!0;continue}if(p==='"'){l=!l;continue}if(!l&&(p===o[n]&&a++,p===i&&(a--,a===0)))return o.slice(n,c+1)}return o.slice(n)}async function Wt(o,e,t){let r=t.maxParseRetries??2,n=typeof e=="string"?wr(e,t.schema):e,s;for(let i=0;i<=r;i++){let a=i===0?n:typeof n=="string"?`${n}
|
|
172
172
|
|
|
173
|
-
Previous attempt failed: ${
|
|
173
|
+
Previous attempt failed: ${s?.message}. Please output ONLY valid JSON.`:n,l=await o.run(a);try{let d=kr(l.text);return{data:JSON.parse(d),raw:t.includeRaw?l:void 0}}catch(d){s=d instanceof Error?d:new Error(String(d))}}throw new Error(`Failed to extract structured output after ${r+1} attempts: ${s?.message}`)}var Kt=/\{\{(\w+)\}\}/g;function U(o){let e=[...new Set(Array.from(o.matchAll(Kt),r=>r[1]))],t=r=>o.replace(Kt,(n,s)=>{let i=r[s];if(i===void 0)throw new Error(`Missing template variable: {{${s}}}`);return i});return Object.defineProperty(t,"raw",{value:o,enumerable:!0}),Object.defineProperty(t,"variables",{value:e,enumerable:!0}),t}var Yt=U(`Summarize the following {{format}} in {{style}}:
|
|
174
174
|
|
|
175
175
|
{{text}}`),Qt=U(`Translate the following text to {{language}}:
|
|
176
176
|
|
|
@@ -182,5 +182,5 @@ Respond with only the category name.`),er=U(`Extract the following information f
|
|
|
182
182
|
|
|
183
183
|
Text: {{text}}
|
|
184
184
|
|
|
185
|
-
Respond as JSON.`);var K=require("gauss-napi"),
|
|
185
|
+
Respond as JSON.`);var K=require("gauss-napi"),X=class o{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 o(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}}}},Me=class o{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 o(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 tr(o){let e=(0,K.discoverAgents)(o);return(typeof e=="string"?JSON.parse(e):e).map(r=>Object.assign(Object.create(X.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 rr(o,...e){let t=o;for(let r of e)t=await r(t);return t}async function st(o,e,t){let r=t?.concurrency??o.length,n=new Array(o.length),s=o.map((a,l)=>({item:a,index:l})),i=Array.from({length:Math.min(r,s.length)},async()=>{for(;s.length>0;){let a=s.shift();if(!a)break;n[a.index]=await e(a.item,a.index)}});return await Promise.all(i),n}async function nr(o,e,t){let r=await st(o,e,t);return o.filter((n,s)=>r[s])}async function sr(o,e,t){let r=t;for(let n=0;n<o.length;n++)r=await e(r,o[n],n);return r}async function or(o,e){for(let t=0;t<o.length;t++)await e(o[t],t);return o}function ir(...o){return async e=>{let t=e;for(let r of o)t=await r(t);return t}}var ot=gr(require("gauss-napi"),1);function Z(o){let e=ot[o];if(typeof e=="function")return e;let t=ot.default?.[o];if(typeof t=="function")return t;throw new TypeError(`gauss-napi is missing ${o}`)}function ee(o){let e=o instanceof Error?o.message:String(o);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 Ne=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 Z("a2aDiscover")(this.baseUrl,this.authToken??void 0)}catch(e){if(!ee(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 Z("a2aSendMessage")(this.baseUrl,this.authToken??void 0,JSON.stringify(e),t?JSON.stringify(t):void 0)}catch(i){if(!ee(i))throw i;r=await this.rpc("message/send",{message:e,config:t})}if(r._type==="task"){let{_type:i,...a}=r;return{type:"task",task:a}}let{_type:n,...s}=r;return{type:"message",message:s}}async ask(e){try{return await Z("a2aAsk")(this.baseUrl,this.authToken??void 0,e)}catch(t){if(!ee(t))throw t;let r=await this.sendMessage(it(e));if(r.type==="message")return je(r.message);let n=Le(r.task);if(n)return n;let s=await this.getTask(r.task.id);return Le(s)??""}}async getTask(e,t){try{return await Z("a2aGetTask")(this.baseUrl,this.authToken??void 0,e,t??void 0)}catch(r){if(!ee(r))throw r;return this.rpc("tasks/get",{id:e,historyLength:t??void 0})}}async cancelTask(e){try{return await Z("a2aCancelTask")(this.baseUrl,this.authToken??void 0,e)}catch(t){if(!ee(t))throw t;return this.rpc("tasks/cancel",{id:e})}}buildHeaders(){let e={Accept:"application/json"};return this.authToken&&(e.Authorization=`Bearer ${this.authToken}`),e}async rpc(e,t){let r=await fetch(this.baseUrl,{method:"POST",headers:{...this.buildHeaders(),"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:++this.rpcId,method:e,params:t})});if(!r.ok)throw new Error(`A2A request failed (${r.status})`);let n=await r.json();if(n.error)throw new Error(n.error.message??`A2A RPC error (${n.error.code??"unknown"})`);return n.result}};function He(o,e){return{role:o,parts:[{type:"text",text:e}]}}function it(o){return He("user",o)}function ar(o){return He("agent",o)}function je(o){return o.parts.filter(e=>e.type==="text"&&e.text).map(e=>e.text).join("")}function Le(o){if(o.status.message)return je(o.status.message)}var R=require("gauss-napi"),Ue=class{_handle;disposed=!1;constructor(){this._handle=(0,R.createToolRegistry)()}get handle(){return this._handle}add(e){return this.assertNotDisposed(),(0,R.toolRegistryAdd)(this._handle,JSON.stringify(e)),this}search(e){return this.assertNotDisposed(),(0,R.toolRegistrySearch)(this._handle,e)}byTag(e){return this.assertNotDisposed(),(0,R.toolRegistryByTag)(this._handle,e)}list(){return this.assertNotDisposed(),(0,R.toolRegistryList)(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,R.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,evaluatePolicyDiff,evaluatePolicyGate,evaluatePolicyRolloutGuardrails,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
|