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/dist/index.d.cts
CHANGED
|
@@ -303,11 +303,14 @@ interface ControlPlanePolicyDriftAlert {
|
|
|
303
303
|
ok: boolean;
|
|
304
304
|
alert: boolean;
|
|
305
305
|
generatedAt: string;
|
|
306
|
+
window: ControlPlanePolicyDriftWindow;
|
|
306
307
|
baselineVersionId: string | null;
|
|
307
308
|
candidateVersionId: string | null;
|
|
308
309
|
diff: PolicyDiffSummary;
|
|
309
310
|
guardrails: PolicyRolloutGateResult;
|
|
311
|
+
sinksTriggered: string[];
|
|
310
312
|
}
|
|
313
|
+
type ControlPlanePolicyDriftWindow = "custom" | "last_1h" | "last_24h" | "last_7d";
|
|
311
314
|
interface ControlPlaneOpsSummary {
|
|
312
315
|
status: "ok";
|
|
313
316
|
generatedAt: string;
|
|
@@ -349,6 +352,10 @@ declare class ControlPlane implements Disposable {
|
|
|
349
352
|
private nextExplainTraceId;
|
|
350
353
|
private latestExplainTraceId;
|
|
351
354
|
private readonly policyDriftAlertHooks;
|
|
355
|
+
private readonly policyDriftSinks;
|
|
356
|
+
private policyDriftScheduleConfig;
|
|
357
|
+
private readonly policyDriftRuns;
|
|
358
|
+
private nextPolicyDriftRunId;
|
|
352
359
|
private readonly policyLifecycleVersions;
|
|
353
360
|
private nextPolicyLifecycleVersion;
|
|
354
361
|
private activePolicyVersionId;
|
|
@@ -360,6 +367,7 @@ declare class ControlPlane implements Disposable {
|
|
|
360
367
|
withAuthClaims(claims?: ControlPlaneAuthClaims): this;
|
|
361
368
|
withContext(context: ControlPlaneContext): this;
|
|
362
369
|
onPolicyDriftAlert(hook: (alert: ControlPlanePolicyDriftAlert) => void): () => void;
|
|
370
|
+
registerPolicyDriftSink(sinkId: string): this;
|
|
363
371
|
setCostUsage(usage: ControlPlaneUsage): this;
|
|
364
372
|
snapshot(): ControlPlaneSnapshot;
|
|
365
373
|
snapshot(section: ControlPlaneSection): Record<string, unknown>;
|
|
@@ -395,6 +403,7 @@ declare class ControlPlane implements Disposable {
|
|
|
395
403
|
private parseLifecyclePolicy;
|
|
396
404
|
private parseOptionalPolicyFromQuery;
|
|
397
405
|
private parsePolicyDriftGuardrails;
|
|
406
|
+
private parsePolicyDriftWindow;
|
|
398
407
|
private cloneRoutingPolicy;
|
|
399
408
|
private summarizeLifecycleVersion;
|
|
400
409
|
private findLifecycleVersion;
|
|
@@ -417,6 +426,9 @@ declare class ControlPlane implements Disposable {
|
|
|
417
426
|
private buildPolicyExplainBatchResponse;
|
|
418
427
|
private opsPolicyExplainSimulation;
|
|
419
428
|
private opsPolicyExplainDiff;
|
|
429
|
+
private opsPolicyDriftScheduleSet;
|
|
430
|
+
private opsPolicyDriftSchedule;
|
|
431
|
+
private opsPolicyDriftScheduleRun;
|
|
420
432
|
private opsPolicyDrift;
|
|
421
433
|
private opsPolicyExplainTraces;
|
|
422
434
|
private emitStreamBatch;
|
package/dist/index.d.ts
CHANGED
|
@@ -303,11 +303,14 @@ interface ControlPlanePolicyDriftAlert {
|
|
|
303
303
|
ok: boolean;
|
|
304
304
|
alert: boolean;
|
|
305
305
|
generatedAt: string;
|
|
306
|
+
window: ControlPlanePolicyDriftWindow;
|
|
306
307
|
baselineVersionId: string | null;
|
|
307
308
|
candidateVersionId: string | null;
|
|
308
309
|
diff: PolicyDiffSummary;
|
|
309
310
|
guardrails: PolicyRolloutGateResult;
|
|
311
|
+
sinksTriggered: string[];
|
|
310
312
|
}
|
|
313
|
+
type ControlPlanePolicyDriftWindow = "custom" | "last_1h" | "last_24h" | "last_7d";
|
|
311
314
|
interface ControlPlaneOpsSummary {
|
|
312
315
|
status: "ok";
|
|
313
316
|
generatedAt: string;
|
|
@@ -349,6 +352,10 @@ declare class ControlPlane implements Disposable {
|
|
|
349
352
|
private nextExplainTraceId;
|
|
350
353
|
private latestExplainTraceId;
|
|
351
354
|
private readonly policyDriftAlertHooks;
|
|
355
|
+
private readonly policyDriftSinks;
|
|
356
|
+
private policyDriftScheduleConfig;
|
|
357
|
+
private readonly policyDriftRuns;
|
|
358
|
+
private nextPolicyDriftRunId;
|
|
352
359
|
private readonly policyLifecycleVersions;
|
|
353
360
|
private nextPolicyLifecycleVersion;
|
|
354
361
|
private activePolicyVersionId;
|
|
@@ -360,6 +367,7 @@ declare class ControlPlane implements Disposable {
|
|
|
360
367
|
withAuthClaims(claims?: ControlPlaneAuthClaims): this;
|
|
361
368
|
withContext(context: ControlPlaneContext): this;
|
|
362
369
|
onPolicyDriftAlert(hook: (alert: ControlPlanePolicyDriftAlert) => void): () => void;
|
|
370
|
+
registerPolicyDriftSink(sinkId: string): this;
|
|
363
371
|
setCostUsage(usage: ControlPlaneUsage): this;
|
|
364
372
|
snapshot(): ControlPlaneSnapshot;
|
|
365
373
|
snapshot(section: ControlPlaneSection): Record<string, unknown>;
|
|
@@ -395,6 +403,7 @@ declare class ControlPlane implements Disposable {
|
|
|
395
403
|
private parseLifecyclePolicy;
|
|
396
404
|
private parseOptionalPolicyFromQuery;
|
|
397
405
|
private parsePolicyDriftGuardrails;
|
|
406
|
+
private parsePolicyDriftWindow;
|
|
398
407
|
private cloneRoutingPolicy;
|
|
399
408
|
private summarizeLifecycleVersion;
|
|
400
409
|
private findLifecycleVersion;
|
|
@@ -417,6 +426,9 @@ declare class ControlPlane implements Disposable {
|
|
|
417
426
|
private buildPolicyExplainBatchResponse;
|
|
418
427
|
private opsPolicyExplainSimulation;
|
|
419
428
|
private opsPolicyExplainDiff;
|
|
429
|
+
private opsPolicyDriftScheduleSet;
|
|
430
|
+
private opsPolicyDriftSchedule;
|
|
431
|
+
private opsPolicyDriftScheduleRun;
|
|
420
432
|
private opsPolicyDrift;
|
|
421
433
|
private opsPolicyExplainTraces;
|
|
422
434
|
private emitStreamBatch;
|
package/dist/index.js
CHANGED
|
@@ -1,28 +1,28 @@
|
|
|
1
|
-
var v=class extends Error{code;constructor(e,t){super(t),this.name="GaussError",this.code=e}},y=class extends v{resourceType;resourceName;constructor(e,t){super("RESOURCE_DISPOSED",`${e} "${t}" has been destroyed. Create a new instance.`),this.name="DisposedError",this.resourceType=e,this.resourceName=t}},L=class extends v{provider;constructor(e,t){super("PROVIDER_ERROR",`[${e}] ${t}`),this.name="ProviderError",this.provider=e}},H=class extends v{toolName;cause;constructor(e,t,r){super("TOOL_EXECUTION_ERROR",`Tool "${e}" failed: ${t}`),this.name="ToolExecutionError",this.toolName=e,this.cause=r}},u=class extends v{field;constructor(e,t){super("VALIDATION_ERROR",t?`Invalid "${t}": ${e}`:e),this.name="ValidationError",this.field=t}};var T="gpt-5.2",Je="gpt-4.1",Be="o4-mini",$e="gpt-image-1",fe="claude-sonnet-4-20250514",Ve="claude-haiku-4-20250414",qe="claude-opus-4-20250414",ve="gemini-2.5-flash",Fe="gemini-2.5-pro",ze="gemini-2.0-flash",xe="openai/gpt-5.2",Pe="deepseek-chat",Ke="deepseek-reasoner",be="meta-llama/Llama-3.3-70B-Instruct-Turbo",Te="accounts/fireworks/models/llama-v3p1-70b-instruct",ke="mistral-large-latest",we="sonar-pro",_e="grok-3-beta",D={openai:T,anthropic:fe,google:ve,openrouter:xe,deepseek:Pe,groq:"llama-3.3-70b-versatile",ollama:"llama3.2",together:be,fireworks:Te,mistral:ke,perplexity:we,xai:_e};function We(o){return D[o]??T}var Ye={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 k(o){let e=Ye[o]??"";return e?(typeof process<"u"?process.env[e]:"")??"":""}function w(){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:D[t]}}import{create_provider as et,destroy_provider as tt,agent_run as rt,agent_run_with_tool_executor as Se,agent_stream_with_tool_executor as nt,generate as st,generate_with_tools as ot,get_provider_capabilities as it}from"gauss-napi";function Ce(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 Qe(o,e){let t=Ce(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 j(o,e){if(o?.maxTotalCostUsd!==void 0&&e>o.maxTotalCostUsd)throw new Error(`routing policy rejected cost ${e}`)}function U(o,e){if(o?.maxRequestsPerMinute!==void 0&&e>o.maxRequestsPerMinute)throw new Error(`routing policy rejected rate ${e}`)}function G(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 Re(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 C(o,e,t,r={}){let n=r.governanceTags,s=r.currentHourUtc??new Date().getUTCHours();G(o,s),r.estimatedCostUsd!==void 0&&j(o,r.estimatedCostUsd),r.currentRequestsPerMinute!==void 0&&U(o,r.currentRequestsPerMinute);let i=d=>d.length===1?d[0]:[...d].sort((p,c)=>{let h=o?.providerWeights?.[c.provider]??0,m=o?.providerWeights?.[p.provider]??0;return h!==m?h-m:(c.priority??0)-(p.priority??0)})[0],a=o?.aliases?.[t];if(a&&a.length>0){let d=[...a].sort((m,A)=>(A.priority??0)-(m.priority??0)),p=r.availableProviders;if(!p||p.length===0){let m=i(d);return _(o,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 _(o,m.provider,n),{provider:m.provider,model:m.model,selectedBy:`alias:${t}`}}}let l=Re(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 x(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{G(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{j(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{U(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=C(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 J(o,e){let t=e.map(s=>x(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 O(o,e,t=void 0){let r=e.map((s,i)=>{let a=x(t,s.provider,s.model,s.options??{}),l=x(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 B(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}}import{agent_stream_with_tool_executor as Xe}from"gauss-napi";function Ze(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 R=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=Xe(this.agentName,this.providerHandle,this.tools,this.messages,this.options,n,this.toolExecutor).then(i=>{this._result=Ze(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 $(o){return{name:o.name,description:o.description,parameters:o.parameters,execute:o.execute}}function V(o){return typeof o.execute=="function"}function q(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 I(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 g=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=w(),r=e.provider??t?.provider??"openai",n=e.model??t?.model??T;this._requestedProvider=r,this._requestedModel=n,this._routingPolicy=e.routingPolicy;let s=C(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??k(this._provider);this._providerOptions={apiKey:i,...e.providerOptions},this.providerHandle=et(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 it(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($({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=C(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:
|
|
1
|
+
var v=class extends Error{code;constructor(e,t){super(t),this.name="GaussError",this.code=e}},y=class extends v{resourceType;resourceName;constructor(e,t){super("RESOURCE_DISPOSED",`${e} "${t}" has been destroyed. Create a new instance.`),this.name="DisposedError",this.resourceType=e,this.resourceName=t}},L=class extends v{provider;constructor(e,t){super("PROVIDER_ERROR",`[${e}] ${t}`),this.name="ProviderError",this.provider=e}},H=class extends v{toolName;cause;constructor(e,t,r){super("TOOL_EXECUTION_ERROR",`Tool "${e}" failed: ${t}`),this.name="ToolExecutionError",this.toolName=e,this.cause=r}},u=class extends v{field;constructor(e,t){super("VALIDATION_ERROR",t?`Invalid "${t}": ${e}`:e),this.name="ValidationError",this.field=t}};var w="gpt-5.2",Ve="gpt-4.1",Je="o4-mini",Be="gpt-image-1",fe="claude-sonnet-4-20250514",$e="claude-haiku-4-20250414",qe="claude-opus-4-20250414",ve="gemini-2.5-flash",Fe="gemini-2.5-pro",ze="gemini-2.0-flash",Pe="openai/gpt-5.2",xe="deepseek-chat",We="deepseek-reasoner",be="meta-llama/Llama-3.3-70B-Instruct-Turbo",Te="accounts/fireworks/models/llama-v3p1-70b-instruct",we="mistral-large-latest",ke="sonar-pro",Ce="grok-3-beta",D={openai:w,anthropic:fe,google:ve,openrouter:Pe,deepseek:xe,groq:"llama-3.3-70b-versatile",ollama:"llama3.2",together:be,fireworks:Te,mistral:we,perplexity:ke,xai:Ce};function Ke(o){return D[o]??w}var Ye={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 k(o){let e=Ye[o]??"";return e?(typeof process<"u"?process.env[e]:"")??"":""}function C(){let o=[{env:"OPENAI_API_KEY",provider:"openai"},{env:"ANTHROPIC_API_KEY",provider:"anthropic"},{env:"GOOGLE_API_KEY",provider:"google"},{env:"GROQ_API_KEY",provider:"groq"},{env:"DEEPSEEK_API_KEY",provider:"deepseek"},{env:"OPENROUTER_API_KEY",provider:"openrouter"},{env:"TOGETHER_API_KEY",provider:"together"},{env:"FIREWORKS_API_KEY",provider:"fireworks"},{env:"MISTRAL_API_KEY",provider:"mistral"},{env:"PERPLEXITY_API_KEY",provider:"perplexity"},{env:"XAI_API_KEY",provider:"xai"}];for(let{env:e,provider:t}of o)if(typeof process<"u"&&process.env[e])return{provider:t,model:D[t]}}import{create_provider as et,destroy_provider as tt,agent_run as rt,agent_run_with_tool_executor as _e,agent_stream_with_tool_executor as nt,generate as st,generate_with_tools as ot,get_provider_capabilities as it}from"gauss-napi";function Re(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 Qe(o,e){let t=Re(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 j(o,e){if(o?.maxTotalCostUsd!==void 0&&e>o.maxTotalCostUsd)throw new Error(`routing policy rejected cost ${e}`)}function U(o,e){if(o?.maxRequestsPerMinute!==void 0&&e>o.maxRequestsPerMinute)throw new Error(`routing policy rejected rate ${e}`)}function G(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 R(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 Se(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 S(o,e,t,r={}){let n=r.governanceTags,s=r.currentHourUtc??new Date().getUTCHours();G(o,s),r.estimatedCostUsd!==void 0&&j(o,r.estimatedCostUsd),r.currentRequestsPerMinute!==void 0&&U(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,x)=>(x.priority??0)-(h.priority??0)),c=r.availableProviders;if(!c||c.length===0){let h=i(d);return R(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 R(o,h.provider,n),{provider:h.provider,model:h.model,selectedBy:`alias:${t}`}}}let l=Se(o,r.availableProviders??[]);return l&&l!==e?(R(o,l,n),{provider:l,model:t,selectedBy:`fallback:${l}`}):(R(o,e,n),{provider:e,model:t,selectedBy:"direct"})}function P(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{G(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{j(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{U(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=S(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 V(o,e){let t=e.map(s=>P(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 I(o,e,t=void 0){let r=e.map((s,i)=>{let a=P(t,s.provider,s.model,s.options??{}),l=P(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 J(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}}import{agent_stream_with_tool_executor as Xe}from"gauss-napi";function Ze(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 _=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=Xe(this.agentName,this.providerHandle,this.tools,this.messages,this.options,n,this.toolExecutor).then(i=>{this._result=Ze(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 B(o){return{name:o.name,description:o.description,parameters:o.parameters,execute:o.execute}}function $(o){return typeof o.execute=="function"}function q(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 O(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 g=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=C(),r=e.provider??t?.provider??"openai",n=e.model??t?.model??w;this._requestedProvider=r,this._requestedModel=n,this._routingPolicy=e.routingPolicy;let s=S(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??k(this._provider);this._providerOptions={apiKey:i,...e.providerOptions},this.providerHandle=et(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 it(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(B({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=S(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(),s;if(n?s=
|
|
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
|
|
3
|
+
`)}`},...t])}let{toolDefs:r,executor:n}=this.resolveToolsAndExecutor(),s;if(n?s=O(await _e(this._name,this.providerHandle,r,t,this._options,n)):s=O(await rt(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 O(await _e(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??Ee;return O(await nt(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??Ee;return new _(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 st(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 ot(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{tt(this.providerHandle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new y("Agent",this._name)}resolveToolsAndExecutor(){let e=this._tools.filter($),t=this._tools.map(n=>({name:n.name,description:n.description,parameters:n.parameters})),r=e.length>0?q(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}}},Ee=async()=>"{}";async function at(o,e){let t=new g({name:"gauss",...e});try{return(await t.run(o)).text}finally{t.destroy()}}function Ae(o={}){let e=o.providerOptions?.maxRetries??o.retries??5;return new g({...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 lt(o,e){let t=Ae(e);try{return(await t.run(o)).text}finally{t.destroy()}}async function dt(o,e){let{concurrency:t=5,...r}=e??{},n=o.map(i=>({input:i})),s=new g({name:"batch",...r});try{let i=[...n.entries()],a=Array.from({length:Math.min(t,i.length)},async()=>{for(;i.length>0;){let l=i.shift();if(!l)break;let[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}import{create_provider as ct,destroy_provider as pt,execute_code as ut,available_runtimes as ht,generate_image as mt}from"gauss-napi";import{version as vt}from"gauss-napi";async function gt(o,e,t){return ut(o,e,t?.timeoutSecs,t?.workingDir,t?.sandbox)}async function yt(){return ht()}async function ft(o,e={}){let t=C(),r=e.provider??t?.provider??"openai",n=e.model??t?.model??"dall-e-3",s=e.providerOptions?.apiKey??k(r),i=ct(r,n,{apiKey:s,...e.providerOptions});try{return await mt(i,o,e.model,e.size,e.quality,e.style,e.aspectRatio,e.n,e.responseFormat)}finally{pt(i)}}import{randomUUID as Pt}from"crypto";import{create_memory as xt,memory_store as bt,memory_recall as Tt,memory_clear as wt,memory_stats as kt,destroy_memory as Ct}from"gauss-napi";var F=class{_handle;disposed=!1;constructor(){this._handle=xt()}get handle(){return this._handle}async store(e,t,r){this.assertNotDisposed();let n=typeof e=="string"?{id:Pt(),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 bt(this._handle,JSON.stringify(s))}async recall(e){this.assertNotDisposed();let t=e?JSON.stringify(e):void 0;return Tt(this._handle,t)}async clear(e){return this.assertNotDisposed(),wt(this._handle,e)}async stats(){return this.assertNotDisposed(),kt(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{Ct(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Memory has been destroyed")}};import{create_vector_store as Rt,vector_store_upsert as St,vector_store_search as _t,destroy_vector_store as Et,cosine_similarity as At}from"gauss-napi";var z=class{_handle;disposed=!1;constructor(e){this._handle=Rt()}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 St(this._handle,JSON.stringify(t))}async search(e,t){return this.assertNotDisposed(),_t(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{Et(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("VectorStore has been destroyed")}static cosineSimilarity(e,t){return At(e,t)}};var Dt=[`
|
|
5
5
|
|
|
6
6
|
`,`
|
|
7
|
-
`,". "," ",""],
|
|
8
|
-
`)&&o.length<500,r,n;if(t)try{r=await De(o,"utf-8"),n=e.documentId??
|
|
7
|
+
`,". "," ",""],b=class{chunkSize;chunkOverlap;separators;constructor(e={}){this.chunkSize=e.chunkSize??1e3,this.chunkOverlap=e.chunkOverlap??200,this.separators=e.separators??Dt}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 It(o,e){return new b(e).split(o)}import{readFile as De}from"fs/promises";import{basename as Ie}from"path";async function Oe(o,e={}){let t=!o.includes(`
|
|
8
|
+
`)&&o.length<500,r,n;if(t)try{r=await De(o,"utf-8"),n=e.documentId??Ie(o)}catch{r=o,n=e.documentId??"text-document"}else r=o,n=e.documentId??"text-document";let a=new b(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 Ot(o,e={}){let t=await Oe(o,{...e,separators:[`
|
|
9
9
|
## `,`
|
|
10
10
|
### `,`
|
|
11
11
|
|
|
12
12
|
`,`
|
|
13
13
|
`,". "," "]});return t.content=t.content.replace(/^---[\s\S]*?---\n?/,""),t}async function Mt(o,e={}){let t,r;if(!o.includes(`
|
|
14
|
-
`)&&o.length<500)try{t=await De(o,"utf-8"),r=e.documentId??
|
|
14
|
+
`)&&o.length<500)try{t=await De(o,"utf-8"),r=e.documentId??Ie(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??{}}}import{create_graph as Nt,graph_add_node as Lt,graph_add_edge as Ht,graph_add_fork_node as jt,graph_run as Ut,destroy_graph as Gt}from"gauss-napi";var W=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=Nt()}get handle(){return this._handle}addNode(e){return this.assertNotDisposed(),Lt(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(),jt(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(),Ht(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?Ut(this._handle,e):this._runWithConditionals(e)}destroy(){if(!this.disposed){this.disposed=!0;try{Gt(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 y("Graph","graph")}};import{create_workflow as Vt,workflow_add_step as Jt,workflow_add_dependency as Bt,workflow_run as $t,destroy_workflow as qt}from"gauss-napi";var K=class{_handle;disposed=!1;constructor(){this._handle=Vt()}get handle(){return this._handle}addStep(e){return this.assertNotDisposed(),Jt(this._handle,e.stepId,e.agent.name,e.agent.handle,e.instructions,e.tools??[]),this}addDependency(e,t){return this.assertNotDisposed(),Bt(this._handle,e,t),this}async run(e){return this.assertNotDisposed(),$t(this._handle,e)}destroy(){if(!this.disposed){this.disposed=!0;try{qt(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Workflow has been destroyed")}};import{create_team as Ft,team_add_agent as zt,team_set_strategy as Wt,team_run as Kt,destroy_team as Yt}from"gauss-napi";var Y=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 g({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=Ft(e)}get handle(){return this._handle}add(e,t){return this.assertNotDisposed(),zt(this._handle,e.name,e.handle,t),this.agents.push(e),this}strategy(e){return this.assertNotDisposed(),Wt(this._handle,e),this}async run(e){this.assertNotDisposed();let t=JSON.stringify([{role:"user",content:[{type:"text",text:e}]}]);return Kt(this._handle,t)}destroy(){if(!this.disposed){this.disposed=!0;try{Yt(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new y("Team",this._name)}};import{create_network as Qt,network_add_agent as Xt,network_set_supervisor as Zt,network_delegate as Me,network_agent_cards as er,destroy_network as tr}from"gauss-napi";var Q=class o{_handle;disposed=!1;supervisorName=null;static quick(e,t){let r=new o;for(let n of t){let s=new g({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=Qt()}get handle(){return this._handle}addAgent(e,t){this.assertNotDisposed();let r=typeof t=="string"?t:t?.instructions;return Xt(this._handle,e.name,e.handle,r),this}setSupervisor(e){return this.assertNotDisposed(),this.supervisorName=e,Zt(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 Me(this._handle,n,s)}async delegateWithSupervisor(e){if(this.assertNotDisposed(),!this.supervisorName)throw new Error("Network supervisor is not set. Call setSupervisor() first.");return Me(this._handle,this.supervisorName,e)}agentCards(){return this.assertNotDisposed(),er(this._handle)}destroy(){this.disposed||(this.disposed=!0,tr(this._handle))}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new y("Network","network")}};import{create_middleware_chain as rr,middleware_use_logging as nr,middleware_use_caching as sr,middleware_use_rate_limit as or,destroy_middleware_chain as ir}from"gauss-napi";var X=class{_handle;disposed=!1;constructor(){this._handle=rr()}get handle(){return this._handle}useLogging(){return this.assertNotDisposed(),nr(this._handle),this}useCaching(e){return this.assertNotDisposed(),sr(this._handle,e),this}useRateLimit(e,t){return this.assertNotDisposed(),or(this._handle,e,t),this}destroy(){if(!this.disposed){this.disposed=!0;try{ir(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("MiddlewareChain has been destroyed")}};import{create_plugin_registry as ar,plugin_registry_add_telemetry as lr,plugin_registry_add_memory as dr,plugin_registry_list as cr,plugin_registry_emit as pr,destroy_plugin_registry as ur}from"gauss-napi";var Z=class{_handle;disposed=!1;constructor(){this._handle=ar()}get handle(){return this._handle}addTelemetry(){return this.assertNotDisposed(),lr(this._handle),this}addMemory(){return this.assertNotDisposed(),dr(this._handle),this}list(){return this.assertNotDisposed(),cr(this._handle)}emit(e){this.assertNotDisposed(),pr(this._handle,JSON.stringify(e))}destroy(){if(!this.disposed){this.disposed=!0;try{ur(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("PluginRegistry has been destroyed")}};import{create_mcp_server as hr,mcp_server_add_tool as mr,mcpServerAddResource as gr,mcpServerAddPrompt as yr,mcp_server_handle as fr,destroy_mcp_server as vr}from"gauss-napi";var ee=class{_handle;disposed=!1;constructor(e,t){this._handle=hr(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 mr(this._handle,JSON.stringify(t)),this}addResource(e){return this.assertNotDisposed(),gr(this._handle,JSON.stringify(e)),this}addPrompt(e){return this.assertNotDisposed(),yr(this._handle,JSON.stringify(e)),this}async handleMessage(e){return this.assertNotDisposed(),fr(this._handle,JSON.stringify(e))}destroy(){if(!this.disposed){this.disposed=!0;try{vr(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("McpServer has been destroyed")}};import{spawn as Pr}from"child_process";var 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=Pr(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
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: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.")}};import{create_guardrail_chain as Pr,guardrail_chain_add_content_moderation as br,guardrail_chain_add_pii_detection as Tr,guardrail_chain_add_token_limit as kr,guardrail_chain_add_regex_filter as wr,guardrail_chain_add_schema as _r,guardrail_chain_list as Cr,destroy_guardrail_chain as Rr}from"gauss-napi";var re=class{_handle;disposed=!1;constructor(){this._handle=Pr()}get handle(){return this._handle}addContentModeration(e,t=[]){return this.assertNotDisposed(),br(this._handle,e,t),this}addPiiDetection(e){return this.assertNotDisposed(),Tr(this._handle,e),this}addTokenLimit(e,t){return this.assertNotDisposed(),kr(this._handle,e,t),this}addRegexFilter(e,t=[]){return this.assertNotDisposed(),wr(this._handle,e,t),this}addSchema(e){return this.assertNotDisposed(),_r(this._handle,JSON.stringify(e)),this}list(){return this.assertNotDisposed(),Cr(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{Rr(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("GuardrailChain has been destroyed")}};import{create_approval_manager as Sr,approval_request as Er,approval_approve as Ar,approval_deny as Dr,approval_list_pending as Or,destroy_approval_manager as Ir}from"gauss-napi";var ne=class{_handle;disposed=!1;constructor(){this._handle=Sr()}get handle(){return this._handle}request(e,t,r){return this.assertNotDisposed(),Er(this._handle,e,JSON.stringify(t),r)}approve(e,t){this.assertNotDisposed(),Ar(this._handle,e,t?JSON.stringify(t):void 0)}deny(e,t){this.assertNotDisposed(),Dr(this._handle,e,t)}listPending(){return this.assertNotDisposed(),Or(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{Ir(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("ApprovalManager has been destroyed")}};import{create_checkpoint_store as Mr,checkpoint_save as Nr,checkpoint_load as Lr,checkpoint_load_latest as Hr,destroy_checkpoint_store as jr}from"gauss-napi";var se=class{_handle;disposed=!1;constructor(){this._handle=Mr()}get handle(){return this._handle}async save(e){return this.assertNotDisposed(),Nr(this._handle,JSON.stringify(e))}async load(e){return this.assertNotDisposed(),Lr(this._handle,e)}async loadLatest(e){return this.assertNotDisposed(),Hr(this._handle,e)}destroy(){if(!this.disposed){this.disposed=!0;try{jr(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("CheckpointStore has been destroyed")}};import{create_eval_runner as Ur,eval_add_scorer as Gr,load_dataset_jsonl as Jr,load_dataset_json as Br,destroy_eval_runner as $r}from"gauss-napi";var oe=class{_handle;disposed=!1;constructor(e){this._handle=Ur(e)}get handle(){return this._handle}addScorer(e){return this.assertNotDisposed(),Gr(this._handle,e),this}destroy(){if(!this.disposed){this.disposed=!0;try{$r(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("EvalRunner has been destroyed")}static loadDatasetJsonl(e){return Jr(e)}static loadDatasetJson(e){return Br(e)}};import{create_telemetry as Vr,telemetry_record_span as qr,telemetry_export_spans as Fr,telemetry_export_metrics as zr,telemetry_clear as Kr,destroy_telemetry as Wr}from"gauss-napi";var ie=class{_handle;disposed=!1;constructor(){this._handle=Vr()}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;qr(this._handle,JSON.stringify(n))}exportSpans(){return this.assertNotDisposed(),Fr(this._handle)}exportMetrics(){return this.assertNotDisposed(),zr(this._handle)}clear(){this.assertNotDisposed(),Kr(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{Wr(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Telemetry has been destroyed")}};import{appendFileSync as dn,mkdirSync as pn}from"fs";import{createServer as cn}from"http";import{dirname as un}from"path";import{count_tokens as Yr,count_tokens_for_model as Qr,count_message_tokens as Xr,get_context_window_size as Zr,estimate_cost as en}from"gauss-napi";var M=new Map;function tn(o,e){M.set(o,e)}function rn(o){return M.get(o)}function nn(){M.clear()}function sn(o){return Yr(o)}function on(o,e){return Qr(o,e)}function an(o){return Xr(o)}function ln(o){return Zr(o)}function ae(o,e){let t=M.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=en(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 f=class extends Error{},mn=["openai","anthropic","google","groq","ollama","deepseek","openrouter","together","fireworks","mistral","perplexity","xai"],le=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=ae(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=cn((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"){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 Ge of d)this.assertChannelAllowed(Ge);let p=i.searchParams.get("once")==="1",c=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 h=this.replayStreamEvents(s,d,l,c);if(p&&h>0){s.end();return}if(this.emitStreamBatch(s,d,l),p){s.end();return}let m=setInterval(()=>{s.writableEnded||s.destroyed||this.emitStreamBatch(s,d,l)},1e3),A=()=>clearInterval(m);n.on("close",A),n.on("aborted",A);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 f){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&&(pn(un(this.persistPath),{recursive:!0}),dn(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(!
|
|
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.")}};import{create_guardrail_chain as xr,guardrail_chain_add_content_moderation as br,guardrail_chain_add_pii_detection as Tr,guardrail_chain_add_token_limit as wr,guardrail_chain_add_regex_filter as kr,guardrail_chain_add_schema as Cr,guardrail_chain_list as Rr,destroy_guardrail_chain as Sr}from"gauss-napi";var re=class{_handle;disposed=!1;constructor(){this._handle=xr()}get handle(){return this._handle}addContentModeration(e,t=[]){return this.assertNotDisposed(),br(this._handle,e,t),this}addPiiDetection(e){return this.assertNotDisposed(),Tr(this._handle,e),this}addTokenLimit(e,t){return this.assertNotDisposed(),wr(this._handle,e,t),this}addRegexFilter(e,t=[]){return this.assertNotDisposed(),kr(this._handle,e,t),this}addSchema(e){return this.assertNotDisposed(),Cr(this._handle,JSON.stringify(e)),this}list(){return this.assertNotDisposed(),Rr(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{Sr(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("GuardrailChain has been destroyed")}};import{create_approval_manager as _r,approval_request as Er,approval_approve as Ar,approval_deny as Dr,approval_list_pending as Ir,destroy_approval_manager as Or}from"gauss-napi";var ne=class{_handle;disposed=!1;constructor(){this._handle=_r()}get handle(){return this._handle}request(e,t,r){return this.assertNotDisposed(),Er(this._handle,e,JSON.stringify(t),r)}approve(e,t){this.assertNotDisposed(),Ar(this._handle,e,t?JSON.stringify(t):void 0)}deny(e,t){this.assertNotDisposed(),Dr(this._handle,e,t)}listPending(){return this.assertNotDisposed(),Ir(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{Or(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("ApprovalManager has been destroyed")}};import{create_checkpoint_store as Mr,checkpoint_save as Nr,checkpoint_load as Lr,checkpoint_load_latest as Hr,destroy_checkpoint_store as jr}from"gauss-napi";var se=class{_handle;disposed=!1;constructor(){this._handle=Mr()}get handle(){return this._handle}async save(e){return this.assertNotDisposed(),Nr(this._handle,JSON.stringify(e))}async load(e){return this.assertNotDisposed(),Lr(this._handle,e)}async loadLatest(e){return this.assertNotDisposed(),Hr(this._handle,e)}destroy(){if(!this.disposed){this.disposed=!0;try{jr(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("CheckpointStore has been destroyed")}};import{create_eval_runner as Ur,eval_add_scorer as Gr,load_dataset_jsonl as Vr,load_dataset_json as Jr,destroy_eval_runner as Br}from"gauss-napi";var oe=class{_handle;disposed=!1;constructor(e){this._handle=Ur(e)}get handle(){return this._handle}addScorer(e){return this.assertNotDisposed(),Gr(this._handle,e),this}destroy(){if(!this.disposed){this.disposed=!0;try{Br(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("EvalRunner has been destroyed")}static loadDatasetJsonl(e){return Vr(e)}static loadDatasetJson(e){return Jr(e)}};import{create_telemetry as $r,telemetry_record_span as qr,telemetry_export_spans as Fr,telemetry_export_metrics as zr,telemetry_clear as Wr,destroy_telemetry as Kr}from"gauss-napi";var ie=class{_handle;disposed=!1;constructor(){this._handle=$r()}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;qr(this._handle,JSON.stringify(n))}exportSpans(){return this.assertNotDisposed(),Fr(this._handle)}exportMetrics(){return this.assertNotDisposed(),zr(this._handle)}clear(){this.assertNotDisposed(),Wr(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{Kr(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Telemetry has been destroyed")}};import{appendFileSync as dn,mkdirSync as cn}from"fs";import{createServer as pn}from"http";import{dirname as un}from"path";import{count_tokens as Yr,count_tokens_for_model as Qr,count_message_tokens as Xr,get_context_window_size as Zr,estimate_cost as en}from"gauss-napi";var M=new Map;function tn(o,e){M.set(o,e)}function rn(o){return M.get(o)}function nn(){M.clear()}function sn(o){return Yr(o)}function on(o,e){return Qr(o,e)}function an(o){return Xr(o)}function ln(o){return Zr(o)}function ae(o,e){let t=M.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=en(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 f=class extends Error{},hn=["openai","anthropic","google","groq","ollama","deepseek","openrouter","together","fireworks","mistral","perplexity","xai"],le=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=ae(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=pn((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 Ge of d)this.assertChannelAllowed(Ge);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),x=()=>clearInterval(h);n.on("close",x),n.on("aborted",x);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 f){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&&(cn(un(this.persistPath),{recursive:!0}),dn(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(!hn.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 f(`Forbidden lifecycle role "${s}"`);if(s&&!t.includes(s))throw new f(`Forbidden lifecycle action "${e}"`);let d=s??i.find(m=>t.includes(m));if(!d)throw new f(`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 f(`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=V(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,s=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(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=x(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:x(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=O(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}}opsPolicyDrift(e){let t=this.parsePolicyExplainBatchScenarios(e),r=e.get("baselineVersion"),n=e.get("candidateVersion"),s=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")??s,l=this.parseOptionalPolicyFromQuery(e,"candidatePolicy")??i??this.routingPolicy,d=O(l,t,a),p=B(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 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 f(`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 f("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 f("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 f("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>
|
|
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=P(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:P(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=I(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=I(d,t,l),p=J(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 x of this.policyDriftAlertHooks)x(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 f(`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 f("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 f("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 f("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,24 +163,24 @@ ${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>`}};import{create_fallback_provider as
|
|
166
|
+
</html>`}};import{create_fallback_provider as mn,create_circuit_breaker as gn,create_resilient_provider as yn}from"gauss-napi";function fn(o){return mn(o)}function vn(o,e,t){return gn(o,e,t)}function Ne(o,e,t){return yn(o,e,t)}function Pn(o,e,t=!0){return Ne(o.handle,e.map(r=>r.handle),t)}import{agent_config_from_json as xn,agent_config_resolve_env as bn}from"gauss-napi";function Tn(o){return xn(o)}function wn(o){return bn(o)}import{create_tool_validator as kn,tool_validator_validate as Cn,destroy_tool_validator as Rn}from"gauss-napi";var de=class{_handle;disposed=!1;constructor(e){this._handle=kn(e)}get handle(){return this._handle}validate(e,t){return this.assertNotDisposed(),JSON.parse(Cn(this._handle,JSON.stringify(e),JSON.stringify(t)))}destroy(){if(!this.disposed){this.disposed=!0;try{Rn(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("ToolValidator has been destroyed")}};import{parse_partial_json as Sn}from"gauss-napi";function _n(o){return Sn(o)}function En(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 An(o){return new Promise(e=>setTimeout(e,o))}async function Le(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=En({backoff:r,baseDelayMs:n,maxDelayMs:s,jitter:i},c+1);l?.(d,c+1,m),await An(m)}throw d}function Dn(o,e){return t=>Le(()=>o.run(t),e)}function In(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 On(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 Mn(o,e,t){let r=t.maxParseRetries??2,n=typeof e=="string"?In(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: ${s?.message}. Please output ONLY valid JSON.`:n,l=await o.run(a);try{let d=
|
|
173
|
+
Previous attempt failed: ${s?.message}. Please output ONLY valid JSON.`:n,l=await o.run(a);try{let d=On(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 He=/\{\{(\w+)\}\}/g;function T(o){let e=[...new Set(Array.from(o.matchAll(He),r=>r[1]))],t=r=>o.replace(He,(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 Nn=T(`Summarize the following {{format}} in {{style}}:
|
|
174
174
|
|
|
175
|
-
{{text}}`),Ln=
|
|
175
|
+
{{text}}`),Ln=T(`Translate the following text to {{language}}:
|
|
176
176
|
|
|
177
|
-
{{text}}`),Hn=
|
|
177
|
+
{{text}}`),Hn=T("Review this {{language}} code for bugs, security issues, and best practices:\n\n```{{language}}\n{{code}}\n```"),jn=T(`Classify the following text into one of these categories: {{categories}}
|
|
178
178
|
|
|
179
179
|
Text: {{text}}
|
|
180
180
|
|
|
181
|
-
Respond with only the category name.`),Un=
|
|
181
|
+
Respond with only the category name.`),Un=T(`Extract the following information from the text: {{fields}}
|
|
182
182
|
|
|
183
183
|
Text: {{text}}
|
|
184
184
|
|
|
185
|
-
Respond as JSON.`);import{parseAgentsMd as Gn,discoverAgents as
|
|
185
|
+
Respond as JSON.`);import{parseAgentsMd as Gn,discoverAgents as Vn,parseSkillMd as Jn}from"gauss-napi";var N=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=Gn(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}}}},ce=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=Jn(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 Bn(o){let e=Vn(o);return(typeof e=="string"?JSON.parse(e):e).map(r=>Object.assign(Object.create(N.prototype),{name:r.name,description:r.description,model:r.model??void 0,provider:r.provider??void 0,instructions:r.instructions??void 0,tools:Object.freeze([...r.tools]),skills:Object.freeze([...r.skills]),capabilities:Object.freeze([...r.capabilities]),environment:new Map(r.environment),metadata:Object.freeze({...r.metadata})}))}async function $n(o,...e){let t=o;for(let r of e)t=await r(t);return t}async function je(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 qn(o,e,t){let r=await je(o,e,t);return o.filter((n,s)=>r[s])}async function Fn(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 zn(o,e){for(let t=0;t<o.length;t++)await e(o[t],t);return o}function Wn(...o){return async e=>{let t=e;for(let r of o)t=await r(t);return t}}import*as he from"gauss-napi";function E(o){let e=he[o];if(typeof e=="function")return e;let t=he.default?.[o];if(typeof t=="function")return t;throw new TypeError(`gauss-napi is missing ${o}`)}function A(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 pe=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 E("a2aDiscover")(this.baseUrl,this.authToken??void 0)}catch(e){if(!A(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 E("a2aSendMessage")(this.baseUrl,this.authToken??void 0,JSON.stringify(e),t?JSON.stringify(t):void 0)}catch(i){if(!A(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 E("a2aAsk")(this.baseUrl,this.authToken??void 0,e)}catch(t){if(!A(t))throw t;let r=await this.sendMessage(Ue(e));if(r.type==="message")return ge(r.message);let n=ue(r.task);if(n)return n;let s=await this.getTask(r.task.id);return ue(s)??""}}async getTask(e,t){try{return await E("a2aGetTask")(this.baseUrl,this.authToken??void 0,e,t??void 0)}catch(r){if(!A(r))throw r;return this.rpc("tasks/get",{id:e,historyLength:t??void 0})}}async cancelTask(e){try{return await E("a2aCancelTask")(this.baseUrl,this.authToken??void 0,e)}catch(t){if(!A(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 me(o,e){return{role:o,parts:[{type:"text",text:e}]}}function Ue(o){return me("user",o)}function Kn(o){return me("agent",o)}function ge(o){return o.parts.filter(e=>e.type==="text"&&e.text).map(e=>e.text).join("")}function ue(o){if(o.status.message)return ge(o.status.message)}import{createToolRegistry as Yn,toolRegistryAdd as Qn,toolRegistrySearch as Xn,toolRegistryByTag as Zn,toolRegistryList as es,destroyToolRegistry as ts}from"gauss-napi";var ye=class{_handle;disposed=!1;constructor(){this._handle=Yn()}get handle(){return this._handle}add(e){return this.assertNotDisposed(),Qn(this._handle,JSON.stringify(e)),this}search(e){return this.assertNotDisposed(),Xn(this._handle,e)}byTag(e){return this.assertNotDisposed(),Zn(this._handle,e)}list(){return this.assertNotDisposed(),es(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{ts(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("ToolRegistry has been destroyed")}};export{pe as A2aClient,fe as ANTHROPIC_DEFAULT,$e as ANTHROPIC_FAST,qe as ANTHROPIC_PREMIUM,g as Agent,N as AgentSpec,_ as AgentStream,ne as ApprovalManager,se as CheckpointStore,le as ControlPlane,xe as DEEPSEEK_DEFAULT,We as DEEPSEEK_REASONING,y as DisposedError,oe as EvalRunner,Te as FIREWORKS_DEFAULT,ve as GOOGLE_DEFAULT,ze as GOOGLE_IMAGE,Fe as GOOGLE_PREMIUM,v as GaussError,W as Graph,re as GuardrailChain,we as MISTRAL_DEFAULT,te as McpClient,ee as McpServer,F as Memory,X as MiddlewareChain,Q as Network,w as OPENAI_DEFAULT,Ve as OPENAI_FAST,Be as OPENAI_IMAGE,Je as OPENAI_REASONING,Pe as OPENROUTER_DEFAULT,ke as PERPLEXITY_DEFAULT,D as PROVIDER_DEFAULTS,Z as PluginRegistry,L as ProviderError,ce as SkillSpec,be as TOGETHER_DEFAULT,Y as Team,ie as Telemetry,b as TextSplitter,H as ToolExecutionError,ye as ToolRegistry,de as ToolValidator,u as ValidationError,z as VectorStore,K as Workflow,Ce as XAI_DEFAULT,Kn as agentMessage,Qe as applyGovernancePack,yt as availableRuntimes,dt as batch,jn as classify,nn as clearPricing,Hn as codeReview,Wn as compose,an as countMessageTokens,sn as countTokens,on as countTokensForModel,vn as createCircuitBreaker,fn as createFallbackProvider,Pn as createResilientAgent,Ne as createResilientProvider,q as createToolExecutor,Ke as defaultModel,C as detectProvider,Bn as discoverAgents,j as enforceRoutingCostLimit,R as enforceRoutingGovernance,U as enforceRoutingRateLimit,G as enforceRoutingTimeWindow,Ae as enterprisePreset,lt as enterpriseRun,ae as estimateCost,I as evaluatePolicyDiff,V as evaluatePolicyGate,J as evaluatePolicyRolloutGuardrails,gt as executeCode,P as explainRoutingTarget,Un as extract,ge as extractText,qn as filterAsync,at as gauss,ft as generateImage,ln as getContextWindowSize,rn as getPricing,Re as governancePolicyPack,$ as isTypedTool,Mt as loadJson,Ot as loadMarkdown,Oe as loadText,je as mapAsync,Tn as parseAgentConfig,_n as parsePartialJson,$n as pipe,Fn as reduceAsync,k as resolveApiKey,wn as resolveEnv,Se as resolveFallbackProvider,S as resolveRoutingTarget,Dn as retryable,tn as setPricing,It as splitText,Mn as structured,Nn as summarize,zn as tapAsync,ue as taskText,T as template,me as textMessage,B as tool,Ln as translate,Ue as userMessage,vt as version,Le as withRetry};
|
|
186
186
|
//# sourceMappingURL=index.js.map
|