gauss-ts 2.0.4 → 2.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -156,14 +156,21 @@ const c = new Agent({
156
156
  fallbackOrder: ["anthropic", "openai"],
157
157
  maxTotalCostUsd: 2.0,
158
158
  maxRequestsPerMinute: 60,
159
+ governance: {
160
+ rules: [
161
+ { type: "allow_provider", provider: "openai" },
162
+ { type: "require_tag", tag: "pci" },
163
+ ],
164
+ },
159
165
  },
160
166
  });
161
167
 
162
- // Runtime policy-router decision (availability + budget + rate)
168
+ // Runtime policy-router decision (availability + budget + rate + governance tags)
163
169
  const routed = c.withRoutingContext({
164
170
  availableProviders: ["openai"],
165
171
  estimatedCostUsd: 1.2,
166
172
  currentRequestsPerMinute: 20,
173
+ governanceTags: ["pci"],
167
174
  });
168
175
  ```
169
176
 
@@ -185,6 +192,9 @@ console.log(`Control Plane: ${url}`);
185
192
  // single event quick-check -> GET ${url}/api/stream?channel=timeline&once=1
186
193
  // multiplex channels -> GET ${url}/api/stream?channels=snapshot,timeline&once=1
187
194
  // reconnect/replay cursor -> GET ${url}/api/stream?channel=snapshot&lastEventId=42
195
+ // hosted ops capabilities -> GET ${url}/api/ops/capabilities
196
+ // hosted ops health -> GET ${url}/api/ops/health
197
+ // hosted ops dashboard -> GET ${url}/ops
188
198
  ```
189
199
 
190
200
  ---
@@ -8,11 +8,25 @@ interface RoutingCandidate {
8
8
  priority?: number;
9
9
  maxCostUsd?: number;
10
10
  }
11
+ type GovernanceRule = {
12
+ type: "require_tag";
13
+ tag: string;
14
+ } | {
15
+ type: "deny_provider";
16
+ provider: ProviderType;
17
+ } | {
18
+ type: "allow_provider";
19
+ provider: ProviderType;
20
+ };
21
+ interface GovernancePolicyPack {
22
+ rules: GovernanceRule[];
23
+ }
11
24
  interface RoutingPolicy {
12
25
  aliases?: Record<string, RoutingCandidate[]>;
13
26
  fallbackOrder?: ProviderType[];
14
27
  maxTotalCostUsd?: number;
15
28
  maxRequestsPerMinute?: number;
29
+ governance?: GovernancePolicyPack;
16
30
  }
17
31
  interface ResolvedRoutingTarget {
18
32
  provider: ProviderType;
@@ -23,9 +37,11 @@ interface ResolveRoutingTargetOptions {
23
37
  availableProviders?: ProviderType[];
24
38
  estimatedCostUsd?: number;
25
39
  currentRequestsPerMinute?: number;
40
+ governanceTags?: string[];
26
41
  }
27
42
  declare function enforceRoutingCostLimit(policy: RoutingPolicy | undefined, costUsd: number): void;
28
43
  declare function enforceRoutingRateLimit(policy: RoutingPolicy | undefined, requestsPerMinute: number): void;
44
+ declare function enforceRoutingGovernance(policy: RoutingPolicy | undefined, provider: ProviderType, tags?: string[]): void;
29
45
  declare function resolveFallbackProvider(policy: RoutingPolicy | undefined, availableProviders: ProviderType[]): ProviderType | null;
30
46
  declare function resolveRoutingTarget(policy: RoutingPolicy | undefined, provider: ProviderType, model: string, options?: ResolveRoutingTargetOptions): ResolvedRoutingTarget;
31
47
 
@@ -885,4 +901,4 @@ declare class Agent implements Disposable {
885
901
  */
886
902
  declare function gauss(prompt: string, config?: Omit<AgentConfig, "name">): Promise<string>;
887
903
 
888
- export { type AgentConfig as A, McpClient as M, type ResolveRoutingTargetOptions as R, type StreamEvent as S, type TypedToolDef as T, Agent as a, AgentStream as b, type McpClientConfig as c, type McpToolDef as d, type McpToolResult as e, type ResolvedRoutingTarget as f, type RoutingCandidate as g, type RoutingPolicy as h, createToolExecutor as i, enforceRoutingCostLimit as j, enforceRoutingRateLimit as k, gauss as l, isTypedTool as m, resolveRoutingTarget as n, resolveFallbackProvider as r, tool as t };
904
+ export { type AgentConfig as A, type GovernancePolicyPack as G, McpClient as M, type ResolveRoutingTargetOptions as R, type StreamEvent as S, type TypedToolDef as T, Agent as a, AgentStream as b, type GovernanceRule as c, type McpClientConfig as d, type McpToolDef as e, type McpToolResult as f, type ResolvedRoutingTarget as g, type RoutingCandidate as h, type RoutingPolicy as i, createToolExecutor as j, enforceRoutingCostLimit as k, enforceRoutingGovernance as l, enforceRoutingRateLimit as m, gauss as n, isTypedTool as o, resolveRoutingTarget as p, resolveFallbackProvider as r, tool as t };
@@ -8,11 +8,25 @@ interface RoutingCandidate {
8
8
  priority?: number;
9
9
  maxCostUsd?: number;
10
10
  }
11
+ type GovernanceRule = {
12
+ type: "require_tag";
13
+ tag: string;
14
+ } | {
15
+ type: "deny_provider";
16
+ provider: ProviderType;
17
+ } | {
18
+ type: "allow_provider";
19
+ provider: ProviderType;
20
+ };
21
+ interface GovernancePolicyPack {
22
+ rules: GovernanceRule[];
23
+ }
11
24
  interface RoutingPolicy {
12
25
  aliases?: Record<string, RoutingCandidate[]>;
13
26
  fallbackOrder?: ProviderType[];
14
27
  maxTotalCostUsd?: number;
15
28
  maxRequestsPerMinute?: number;
29
+ governance?: GovernancePolicyPack;
16
30
  }
17
31
  interface ResolvedRoutingTarget {
18
32
  provider: ProviderType;
@@ -23,9 +37,11 @@ interface ResolveRoutingTargetOptions {
23
37
  availableProviders?: ProviderType[];
24
38
  estimatedCostUsd?: number;
25
39
  currentRequestsPerMinute?: number;
40
+ governanceTags?: string[];
26
41
  }
27
42
  declare function enforceRoutingCostLimit(policy: RoutingPolicy | undefined, costUsd: number): void;
28
43
  declare function enforceRoutingRateLimit(policy: RoutingPolicy | undefined, requestsPerMinute: number): void;
44
+ declare function enforceRoutingGovernance(policy: RoutingPolicy | undefined, provider: ProviderType, tags?: string[]): void;
29
45
  declare function resolveFallbackProvider(policy: RoutingPolicy | undefined, availableProviders: ProviderType[]): ProviderType | null;
30
46
  declare function resolveRoutingTarget(policy: RoutingPolicy | undefined, provider: ProviderType, model: string, options?: ResolveRoutingTargetOptions): ResolvedRoutingTarget;
31
47
 
@@ -885,4 +901,4 @@ declare class Agent implements Disposable {
885
901
  */
886
902
  declare function gauss(prompt: string, config?: Omit<AgentConfig, "name">): Promise<string>;
887
903
 
888
- export { type AgentConfig as A, McpClient as M, type ResolveRoutingTargetOptions as R, type StreamEvent as S, type TypedToolDef as T, Agent as a, AgentStream as b, type McpClientConfig as c, type McpToolDef as d, type McpToolResult as e, type ResolvedRoutingTarget as f, type RoutingCandidate as g, type RoutingPolicy as h, createToolExecutor as i, enforceRoutingCostLimit as j, enforceRoutingRateLimit as k, gauss as l, isTypedTool as m, resolveRoutingTarget as n, resolveFallbackProvider as r, tool as t };
904
+ export { type AgentConfig as A, type GovernancePolicyPack as G, McpClient as M, type ResolveRoutingTargetOptions as R, type StreamEvent as S, type TypedToolDef as T, Agent as a, AgentStream as b, type GovernanceRule as c, type McpClientConfig as d, type McpToolDef as e, type McpToolResult as f, type ResolvedRoutingTarget as g, type RoutingCandidate as h, type RoutingPolicy as i, createToolExecutor as j, enforceRoutingCostLimit as k, enforceRoutingGovernance as l, enforceRoutingRateLimit as m, gauss as n, isTypedTool as o, resolveRoutingTarget as p, resolveFallbackProvider as r, tool as t };
package/dist/agent.cjs CHANGED
@@ -1,5 +1,5 @@
1
- "use strict";var T=Object.defineProperty;var K=Object.getOwnPropertyDescriptor;var G=Object.getOwnPropertyNames;var U=Object.prototype.hasOwnProperty;var L=(r,e)=>{for(var t in e)T(r,t,{get:e[t],enumerable:!0})},H=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of G(e))!U.call(r,o)&&o!==t&&T(r,o,{get:()=>e[o],enumerable:!(n=K(e,o))||n.enumerable});return r};var Y=r=>H(T({},"__esModule",{value:!0}),r);var re={};L(re,{Agent:()=>c,AgentStream:()=>m,availableRuntimes:()=>S,batch:()=>M,executeCode:()=>D,gauss:()=>k,generateImage:()=>N,version:()=>R.version});module.exports=Y(re);var l=require("gauss-napi");var _=class extends Error{code;constructor(e,t){super(t),this.name="GaussError",this.code=e}},y=class extends _{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}};var E="gpt-5.2";var j="claude-sonnet-4-20250514";var q="gemini-2.5-flash";var F="openai/gpt-5.2",$="deepseek-chat";var B="meta-llama/Llama-3.3-70B-Instruct-Turbo",J="accounts/fireworks/models/llama-v3p1-70b-instruct",X="mistral-large-latest",W="sonar-pro",V="grok-3-beta",b={openai:E,anthropic:j,google:q,openrouter:F,deepseek:$,groq:"llama-3.3-70b-versatile",ollama:"llama3.2",together:B,fireworks:J,mistral:X,perplexity:W,xai:V};var z={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 f(r){let e=z[r]??"";return e?(typeof process<"u"?process.env[e]:"")??"":""}function v(){let r=[{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 r)if(typeof process<"u"&&process.env[e])return{provider:t,model:b[t]}}function Q(r,e){if(r?.maxTotalCostUsd!==void 0&&e>r.maxTotalCostUsd)throw new Error(`routing policy rejected cost ${e}`)}function Z(r,e){if(r?.maxRequestsPerMinute!==void 0&&e>r.maxRequestsPerMinute)throw new Error(`routing policy rejected rate ${e}`)}function ee(r,e){let t=r?.fallbackOrder;if(!t||t.length===0||e.length===0)return null;let n=new Set(e);for(let o of t)if(n.has(o))return o;return null}function P(r,e,t,n={}){n.estimatedCostUsd!==void 0&&Q(r,n.estimatedCostUsd),n.currentRequestsPerMinute!==void 0&&Z(r,n.currentRequestsPerMinute);let o=r?.aliases?.[t];if(o&&o.length>0){let s=[...o].sort((g,h)=>(h.priority??0)-(g.priority??0)),a=n.availableProviders;if(!a||a.length===0)return{provider:s[0].provider,model:s[0].model,selectedBy:`alias:${t}`};let d=new Set(a),u=s.find(g=>d.has(g.provider));if(u)return{provider:u.provider,model:u.model,selectedBy:`alias:${t}`}}let i=ee(r,n.availableProviders??[]);return i&&i!==e?{provider:i,model:t,selectedBy:`fallback:${i}`}:{provider:e,model:t,selectedBy:"direct"}}var O=require("gauss-napi");function te(r){return{...r,citations:r.citations?.map(e=>({type:e.citationType??e.type,citedText:e.citedText,documentTitle:e.documentTitle,start:e.start,end:e.end}))}}var m=class{constructor(e,t,n,o,i,s){this.agentName=e;this.providerHandle=t;this.tools=n;this.messages=o;this.options=i;this.toolExecutor=s}_result;get result(){return this._result}async*[Symbol.asyncIterator](){let e=[],t,n=!1,o=s=>{try{e.push(JSON.parse(s))}catch{e.push({type:"raw",text:s})}t?.()},i=(0,O.agent_stream_with_tool_executor)(this.agentName,this.providerHandle,this.tools,this.messages,this.options,o,this.toolExecutor).then(s=>{this._result=te(s),n=!0,t?.()});for(;!n||e.length>0;)e.length>0?yield e.shift():n||await new Promise(s=>{t=s});await i}};function w(r){return{name:r.name,description:r.description,parameters:r.parameters,execute:r.execute}}function A(r){return typeof r.execute=="function"}function C(r,e){let t=new Map(r.map(n=>[n.name,n]));return async n=>{let o;try{o=JSON.parse(n)}catch{return JSON.stringify({error:"Invalid tool call JSON"})}let i=o.tool??o.name??"",s=t.get(i);if(!s)return e?e(n):JSON.stringify({error:`Unknown tool: ${i}`});try{let a=o.args??o.arguments??{},d=await s.execute(a);return typeof d=="string"?d:JSON.stringify(d)}catch(a){let d=a instanceof Error?a.message:String(a);return JSON.stringify({error:`Tool "${i}" failed: ${d}`})}}}function x(r){return{...r,citations:r.citations?.map(e=>({type:e.citationType??e.type??"unknown",citedText:e.citedText,documentTitle:e.documentTitle,start:e.start,end:e.end}))}}var c=class r{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=v(),n=e.provider??t?.provider??"openai",o=e.model??t?.model??E;this._requestedProvider=n,this._requestedModel=o,this._routingPolicy=e.routingPolicy;let i=P(this._routingPolicy,n,o);this._provider=i.provider,this._model=i.model,this._name=e.name??"agent",this._instructions=e.instructions??"";let s=e.providerOptions?.apiKey??f(this._provider);this._providerOptions={apiKey:s,...e.providerOptions},this.providerHandle=(0,l.create_provider)(this._provider,this._model,this._providerOptions),e.tools&&(this._tools=[...e.tools]),e.middleware&&(this._middleware=e.middleware),e.guardrails&&(this._guardrails=e.guardrails),e.memory&&(this._memory=e.memory),e.sessionId&&(this._sessionId=e.sessionId),e.mcpClients&&(this._mcpClients=[...e.mcpClients]);let a=e.codeExecution,d=a===!0?{python:!0,javascript:!0,bash:!0}:a||void 0;this._options={instructions:this._instructions||void 0,temperature:e.temperature,maxSteps:e.maxSteps,topP:e.topP,maxTokens:e.maxTokens,seed:e.seed,stopOnTool:e.stopOnTool,outputSchema:e.outputSchema,thinkingBudget:e.thinkingBudget,reasoningEffort:e.reasoningEffort,cacheControl:e.cacheControl,codeExecution:d,grounding:e.grounding,nativeCodeExecution:e.nativeCodeExecution,responseModalities:e.responseModalities}}static fromEnv(e={}){return new r(e)}get name(){return this._name}get provider(){return this._provider}get model(){return this._model}get instructions(){return this._instructions}get handle(){return this.providerHandle}get capabilities(){return(0,l.get_provider_capabilities)(this.providerHandle)}addTool(e){return this._tools.push(e),this}addTools(e){return this._tools.push(...e),this}withTool(e,t,n,o){return this._tools.push(w({name:e,description:t,parameters:o??{},execute:n})),this}setOptions(e){return this._options={...this._options,...e},this}withModel(e){return this.assertNotDisposed(),new r({...this.toConfig(),model:e})}withRoutingContext(e){this.assertNotDisposed();let t=P(this._routingPolicy,this._requestedProvider,this._requestedModel,e);return new r({...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 s=await this._memory.recall(this._sessionId?{sessionId:this._sessionId}:void 0);s.length>0&&(t=[{role:"system",content:`Previous context:
1
+ "use strict";var _=Object.defineProperty;var U=Object.getOwnPropertyDescriptor;var L=Object.getOwnPropertyNames;var H=Object.prototype.hasOwnProperty;var j=(r,e)=>{for(var t in e)_(r,t,{get:e[t],enumerable:!0})},Y=(r,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of L(e))!H.call(r,n)&&n!==t&&_(r,n,{get:()=>e[n],enumerable:!(o=U(e,n))||o.enumerable});return r};var q=r=>Y(_({},"__esModule",{value:!0}),r);var ne={};j(ne,{Agent:()=>c,AgentStream:()=>g,availableRuntimes:()=>N,batch:()=>D,executeCode:()=>S,gauss:()=>M,generateImage:()=>G,version:()=>b.version});module.exports=q(ne);var l=require("gauss-napi");var E=class extends Error{code;constructor(e,t){super(t),this.name="GaussError",this.code=e}},y=class extends E{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}};var P="gpt-5.2";var $="claude-sonnet-4-20250514";var F="gemini-2.5-flash";var B="openai/gpt-5.2",J="deepseek-chat";var X="meta-llama/Llama-3.3-70B-Instruct-Turbo",W="accounts/fireworks/models/llama-v3p1-70b-instruct",V="mistral-large-latest",z="sonar-pro",Q="grok-3-beta",w={openai:P,anthropic:$,google:F,openrouter:B,deepseek:J,groq:"llama-3.3-70b-versatile",ollama:"llama3.2",together:X,fireworks:W,mistral:V,perplexity:z,xai:Q};var Z={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 v(r){let e=Z[r]??"";return e?(typeof process<"u"?process.env[e]:"")??"":""}function f(){let r=[{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 r)if(typeof process<"u"&&process.env[e])return{provider:t,model:w[t]}}function ee(r,e){if(r?.maxTotalCostUsd!==void 0&&e>r.maxTotalCostUsd)throw new Error(`routing policy rejected cost ${e}`)}function te(r,e){if(r?.maxRequestsPerMinute!==void 0&&e>r.maxRequestsPerMinute)throw new Error(`routing policy rejected rate ${e}`)}function x(r,e,t){let o=r?.governance?.rules??[];if(o.length===0)return;let n=o.filter(i=>i.type==="allow_provider").map(i=>i.provider);if(n.length>0&&!n.includes(e))throw new Error(`routing policy governance rejected provider ${e}`);for(let i of o){if(i.type==="deny_provider"&&i.provider===e)throw new Error(`routing policy governance rejected provider ${e}`);if(i.type==="require_tag"&&t!==void 0&&!t.includes(i.tag))throw new Error(`routing policy governance missing tag ${i.tag}`)}}function re(r,e){let t=r?.fallbackOrder;if(!t||t.length===0||e.length===0)return null;let o=new Set(e);for(let n of t)if(o.has(n))return n;return null}function R(r,e,t,o={}){let n=o.governanceTags;o.estimatedCostUsd!==void 0&&ee(r,o.estimatedCostUsd),o.currentRequestsPerMinute!==void 0&&te(r,o.currentRequestsPerMinute);let i=r?.aliases?.[t];if(i&&i.length>0){let a=[...i].sort((u,K)=>(K.priority??0)-(u.priority??0)),d=o.availableProviders;if(!d||d.length===0)return x(r,a[0].provider,n),{provider:a[0].provider,model:a[0].model,selectedBy:`alias:${t}`};let h=new Set(d),m=a.find(u=>h.has(u.provider));if(m)return x(r,m.provider,n),{provider:m.provider,model:m.model,selectedBy:`alias:${t}`}}let s=re(r,o.availableProviders??[]);return s&&s!==e?(x(r,s,n),{provider:s,model:t,selectedBy:`fallback:${s}`}):(x(r,e,n),{provider:e,model:t,selectedBy:"direct"})}var O=require("gauss-napi");function oe(r){return{...r,citations:r.citations?.map(e=>({type:e.citationType??e.type,citedText:e.citedText,documentTitle:e.documentTitle,start:e.start,end:e.end}))}}var g=class{constructor(e,t,o,n,i,s){this.agentName=e;this.providerHandle=t;this.tools=o;this.messages=n;this.options=i;this.toolExecutor=s}_result;get result(){return this._result}async*[Symbol.asyncIterator](){let e=[],t,o=!1,n=s=>{try{e.push(JSON.parse(s))}catch{e.push({type:"raw",text:s})}t?.()},i=(0,O.agent_stream_with_tool_executor)(this.agentName,this.providerHandle,this.tools,this.messages,this.options,n,this.toolExecutor).then(s=>{this._result=oe(s),o=!0,t?.()});for(;!o||e.length>0;)e.length>0?yield e.shift():o||await new Promise(s=>{t=s});await i}};function A(r){return{name:r.name,description:r.description,parameters:r.parameters,execute:r.execute}}function C(r){return typeof r.execute=="function"}function k(r,e){let t=new Map(r.map(o=>[o.name,o]));return async o=>{let n;try{n=JSON.parse(o)}catch{return JSON.stringify({error:"Invalid tool call JSON"})}let i=n.tool??n.name??"",s=t.get(i);if(!s)return e?e(o):JSON.stringify({error:`Unknown tool: ${i}`});try{let a=n.args??n.arguments??{},d=await s.execute(a);return typeof d=="string"?d:JSON.stringify(d)}catch(a){let d=a instanceof Error?a.message:String(a);return JSON.stringify({error:`Tool "${i}" failed: ${d}`})}}}function T(r){return{...r,citations:r.citations?.map(e=>({type:e.citationType??e.type??"unknown",citedText:e.citedText,documentTitle:e.documentTitle,start:e.start,end:e.end}))}}var c=class r{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=f(),o=e.provider??t?.provider??"openai",n=e.model??t?.model??P;this._requestedProvider=o,this._requestedModel=n,this._routingPolicy=e.routingPolicy;let i=R(this._routingPolicy,o,n);this._provider=i.provider,this._model=i.model,this._name=e.name??"agent",this._instructions=e.instructions??"";let s=e.providerOptions?.apiKey??v(this._provider);this._providerOptions={apiKey:s,...e.providerOptions},this.providerHandle=(0,l.create_provider)(this._provider,this._model,this._providerOptions),e.tools&&(this._tools=[...e.tools]),e.middleware&&(this._middleware=e.middleware),e.guardrails&&(this._guardrails=e.guardrails),e.memory&&(this._memory=e.memory),e.sessionId&&(this._sessionId=e.sessionId),e.mcpClients&&(this._mcpClients=[...e.mcpClients]);let a=e.codeExecution,d=a===!0?{python:!0,javascript:!0,bash:!0}:a||void 0;this._options={instructions:this._instructions||void 0,temperature:e.temperature,maxSteps:e.maxSteps,topP:e.topP,maxTokens:e.maxTokens,seed:e.seed,stopOnTool:e.stopOnTool,outputSchema:e.outputSchema,thinkingBudget:e.thinkingBudget,reasoningEffort:e.reasoningEffort,cacheControl:e.cacheControl,codeExecution:d,grounding:e.grounding,nativeCodeExecution:e.nativeCodeExecution,responseModalities:e.responseModalities}}static fromEnv(e={}){return new r(e)}get name(){return this._name}get provider(){return this._provider}get model(){return this._model}get instructions(){return this._instructions}get handle(){return this.providerHandle}get capabilities(){return(0,l.get_provider_capabilities)(this.providerHandle)}addTool(e){return this._tools.push(e),this}addTools(e){return this._tools.push(...e),this}withTool(e,t,o,n){return this._tools.push(A({name:e,description:t,parameters:n??{},execute:o})),this}setOptions(e){return this._options={...this._options,...e},this}withModel(e){return this.assertNotDisposed(),new r({...this.toConfig(),model:e})}withRoutingContext(e){this.assertNotDisposed();let t=R(this._routingPolicy,this._requestedProvider,this._requestedModel,e);return new r({...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 s=await this._memory.recall(this._sessionId?{sessionId:this._sessionId}:void 0);s.length>0&&(t=[{role:"system",content:`Previous context:
2
2
  ${s.map(d=>d.content).join(`
3
- `)}`},...t])}let{toolDefs:n,executor:o}=this.resolveToolsAndExecutor(),i;if(o?i=x(await(0,l.agent_run_with_tool_executor)(this._name,this.providerHandle,n,t,this._options,o)):i=x(await(0,l.agent_run)(this._name,this.providerHandle,n,t,this._options)),this._memory){let s=typeof e=="string"?e:e.map(a=>a.content).join(`
4
- `);await this._memory.store({id:`${Date.now()}-user`,content:s,entryType:"conversation",timestamp:new Date().toISOString(),sessionId:this._sessionId||void 0}),await this._memory.store({id:`${Date.now()}-assistant`,content:i.text,entryType:"conversation",timestamp:new Date().toISOString(),sessionId:this._sessionId||void 0})}return i}async runWithTools(e,t){this.assertNotDisposed(),await this.ensureMcpTools();let n=typeof e=="string"?[{role:"user",content:e}]:e,{toolDefs:o,executor:i}=this.resolveToolsAndExecutor(),s=async a=>{if(i){let d=await i(a);if(!JSON.parse(d).error?.startsWith("Unknown tool:"))return d}return t(a)};return x(await(0,l.agent_run_with_tool_executor)(this._name,this.providerHandle,o,n,this._options,s))}async stream(e,t,n){this.assertNotDisposed(),await this.ensureMcpTools();let o=typeof e=="string"?[{role:"user",content:e}]:e,{toolDefs:i,executor:s}=this.resolveToolsAndExecutor(),a=n??s??I;return x(await(0,l.agent_stream_with_tool_executor)(this._name,this.providerHandle,i,o,this._options,t,a))}streamIter(e,t){this.assertNotDisposed();let n=typeof e=="string"?[{role:"user",content:e}]:e,{toolDefs:o,executor:i}=this.resolveToolsAndExecutor(),s=t??i??I;return new m(this._name,this.providerHandle,o,n,this._options,s)}async streamText(e,t,n){this.assertNotDisposed();let o=this.streamIter(e,n),i="";for await(let s of o){if(s.type!=="text_delta")continue;let a=typeof s.text=="string"?s.text:typeof s.delta=="string"?s.delta:"";a&&(i+=a,t?.(a))}return o.result?.text??i}async generate(e,t){this.assertNotDisposed();let n=typeof e=="string"?[{role:"user",content:e}]:e;return(0,l.generate)(this.providerHandle,n,t?.temperature,t?.maxTokens)}async generateWithTools(e,t,n){this.assertNotDisposed();let o=typeof e=="string"?[{role:"user",content:e}]:e;return(0,l.generate_with_tools)(this.providerHandle,o,t,n?.temperature,n?.maxTokens)}destroy(){if(!this.disposed){this.disposed=!0;for(let e of this._mcpClients)try{e.close()}catch{}try{(0,l.destroy_provider)(this.providerHandle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new y("Agent",this._name)}resolveToolsAndExecutor(){let e=this._tools.filter(A),t=this._tools.map(o=>({name:o.name,description:o.description,parameters:o.parameters})),n=e.length>0?C(e):null;return{toolDefs:t,executor:n}}async ensureMcpTools(){if(!(this._mcpToolsLoaded||this._mcpClients.length===0)){for(let e of this._mcpClients){let{tools:t,executor:n}=await e.getToolsWithExecutor();for(let o of t){let i={...o,execute:async s=>{let a=JSON.stringify({tool:o.name,args:s}),d=await n(a);return JSON.parse(d)}};this._tools.push(i)}}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}}},I=async()=>"{}";async function k(r,e){let t=new c({name:"gauss",...e});try{return(await t.run(r)).text}finally{t.destroy()}}async function M(r,e){let{concurrency:t=5,...n}=e??{},o=r.map(s=>({input:s})),i=new c({name:"batch",...n});try{let s=[...o.entries()],a=Array.from({length:Math.min(t,s.length)},async()=>{for(;s.length>0;){let d=s.shift();if(!d)break;let[u,g]=d;try{o[u].result=await i.run(g.input)}catch(h){o[u].error=h instanceof Error?h:new Error(String(h))}}});await Promise.all(a)}finally{i.destroy()}return o}var p=require("gauss-napi");var R=require("gauss-napi");async function D(r,e,t){return(0,p.execute_code)(r,e,t?.timeoutSecs,t?.workingDir,t?.sandbox)}async function S(){return(0,p.available_runtimes)()}async function N(r,e={}){let t=v(),n=e.provider??t?.provider??"openai",o=e.model??t?.model??"dall-e-3",i=e.providerOptions?.apiKey??f(n),s=(0,p.create_provider)(n,o,{apiKey:i,...e.providerOptions});try{return await(0,p.generate_image)(s,r,e.model,e.size,e.quality,e.style,e.aspectRatio,e.n,e.responseFormat)}finally{(0,p.destroy_provider)(s)}}0&&(module.exports={Agent,AgentStream,availableRuntimes,batch,executeCode,gauss,generateImage,version});
3
+ `)}`},...t])}let{toolDefs:o,executor:n}=this.resolveToolsAndExecutor(),i;if(n?i=T(await(0,l.agent_run_with_tool_executor)(this._name,this.providerHandle,o,t,this._options,n)):i=T(await(0,l.agent_run)(this._name,this.providerHandle,o,t,this._options)),this._memory){let s=typeof e=="string"?e:e.map(a=>a.content).join(`
4
+ `);await this._memory.store({id:`${Date.now()}-user`,content:s,entryType:"conversation",timestamp:new Date().toISOString(),sessionId:this._sessionId||void 0}),await this._memory.store({id:`${Date.now()}-assistant`,content:i.text,entryType:"conversation",timestamp:new Date().toISOString(),sessionId:this._sessionId||void 0})}return i}async runWithTools(e,t){this.assertNotDisposed(),await this.ensureMcpTools();let o=typeof e=="string"?[{role:"user",content:e}]:e,{toolDefs:n,executor:i}=this.resolveToolsAndExecutor(),s=async a=>{if(i){let d=await i(a);if(!JSON.parse(d).error?.startsWith("Unknown tool:"))return d}return t(a)};return T(await(0,l.agent_run_with_tool_executor)(this._name,this.providerHandle,n,o,this._options,s))}async stream(e,t,o){this.assertNotDisposed(),await this.ensureMcpTools();let n=typeof e=="string"?[{role:"user",content:e}]:e,{toolDefs:i,executor:s}=this.resolveToolsAndExecutor(),a=o??s??I;return T(await(0,l.agent_stream_with_tool_executor)(this._name,this.providerHandle,i,n,this._options,t,a))}streamIter(e,t){this.assertNotDisposed();let o=typeof e=="string"?[{role:"user",content:e}]:e,{toolDefs:n,executor:i}=this.resolveToolsAndExecutor(),s=t??i??I;return new g(this._name,this.providerHandle,n,o,this._options,s)}async streamText(e,t,o){this.assertNotDisposed();let n=this.streamIter(e,o),i="";for await(let s of n){if(s.type!=="text_delta")continue;let a=typeof s.text=="string"?s.text:typeof s.delta=="string"?s.delta:"";a&&(i+=a,t?.(a))}return n.result?.text??i}async generate(e,t){this.assertNotDisposed();let o=typeof e=="string"?[{role:"user",content:e}]:e;return(0,l.generate)(this.providerHandle,o,t?.temperature,t?.maxTokens)}async generateWithTools(e,t,o){this.assertNotDisposed();let n=typeof e=="string"?[{role:"user",content:e}]:e;return(0,l.generate_with_tools)(this.providerHandle,n,t,o?.temperature,o?.maxTokens)}destroy(){if(!this.disposed){this.disposed=!0;for(let e of this._mcpClients)try{e.close()}catch{}try{(0,l.destroy_provider)(this.providerHandle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new y("Agent",this._name)}resolveToolsAndExecutor(){let e=this._tools.filter(C),t=this._tools.map(n=>({name:n.name,description:n.description,parameters:n.parameters})),o=e.length>0?k(e):null;return{toolDefs:t,executor:o}}async ensureMcpTools(){if(!(this._mcpToolsLoaded||this._mcpClients.length===0)){for(let e of this._mcpClients){let{tools:t,executor:o}=await e.getToolsWithExecutor();for(let n of t){let i={...n,execute:async s=>{let a=JSON.stringify({tool:n.name,args:s}),d=await o(a);return JSON.parse(d)}};this._tools.push(i)}}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}}},I=async()=>"{}";async function M(r,e){let t=new c({name:"gauss",...e});try{return(await t.run(r)).text}finally{t.destroy()}}async function D(r,e){let{concurrency:t=5,...o}=e??{},n=r.map(s=>({input:s})),i=new c({name:"batch",...o});try{let s=[...n.entries()],a=Array.from({length:Math.min(t,s.length)},async()=>{for(;s.length>0;){let d=s.shift();if(!d)break;let[h,m]=d;try{n[h].result=await i.run(m.input)}catch(u){n[h].error=u instanceof Error?u:new Error(String(u))}}});await Promise.all(a)}finally{i.destroy()}return n}var p=require("gauss-napi");var b=require("gauss-napi");async function S(r,e,t){return(0,p.execute_code)(r,e,t?.timeoutSecs,t?.workingDir,t?.sandbox)}async function N(){return(0,p.available_runtimes)()}async function G(r,e={}){let t=f(),o=e.provider??t?.provider??"openai",n=e.model??t?.model??"dall-e-3",i=e.providerOptions?.apiKey??v(o),s=(0,p.create_provider)(o,n,{apiKey:i,...e.providerOptions});try{return await(0,p.generate_image)(s,r,e.model,e.size,e.quality,e.style,e.aspectRatio,e.n,e.responseFormat)}finally{(0,p.destroy_provider)(s)}}0&&(module.exports={Agent,AgentStream,availableRuntimes,batch,executeCode,gauss,generateImage,version});
5
5
  //# sourceMappingURL=agent.cjs.map