gauss-ts 2.0.0 → 2.0.2

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.
@@ -412,6 +412,7 @@ declare class Agent implements Disposable {
412
412
  private readonly _name;
413
413
  private readonly _provider;
414
414
  private readonly _model;
415
+ private readonly _providerOptions;
415
416
  private readonly _instructions;
416
417
  private _tools;
417
418
  private _options;
@@ -440,6 +441,20 @@ declare class Agent implements Disposable {
440
441
  * @since 1.0.0
441
442
  */
442
443
  constructor(config?: AgentConfig);
444
+ /**
445
+ * Create an agent using provider/model auto-detection from environment variables.
446
+ *
447
+ * @description Equivalent to `new Agent(config)`, but clearer in intent for env-driven setup.
448
+ *
449
+ * @param config - Optional partial configuration overrides.
450
+ * @returns A new {@link Agent} instance.
451
+ *
452
+ * @example
453
+ * ```ts
454
+ * const agent = Agent.fromEnv({ instructions: "Be concise." });
455
+ * ```
456
+ */
457
+ static fromEnv(config?: AgentConfig): Agent;
443
458
  /**
444
459
  * @description The agent's name.
445
460
  * @since 1.0.0
@@ -507,6 +522,17 @@ declare class Agent implements Disposable {
507
522
  * @since 1.0.0
508
523
  */
509
524
  addTools(tools: (ToolDef | TypedToolDef)[]): this;
525
+ /**
526
+ * Inline tool shortcut — define and attach a tool in one step.
527
+ *
528
+ * @example
529
+ * ```ts
530
+ * const result = await agent
531
+ * .withTool("get_weather", "Get weather for a city", async ({ city }) => ({ temp: 72 }))
532
+ * .run("Weather in Paris?");
533
+ * ```
534
+ */
535
+ withTool<TParams = Record<string, unknown>, TResult = unknown>(name: string, description: string, execute: (params: TParams) => TResult | Promise<TResult>, parameters?: Record<string, unknown>): this;
510
536
  /**
511
537
  * Merge additional agent options into the current configuration. Chainable.
512
538
  *
@@ -523,6 +549,16 @@ declare class Agent implements Disposable {
523
549
  * @since 1.0.0
524
550
  */
525
551
  setOptions(options: Partial<AgentOptions>): this;
552
+ /**
553
+ * Clone this agent with a different model.
554
+ *
555
+ * @description Returns a **new** agent instance preserving tools and integrations,
556
+ * but using the provided model identifier.
557
+ *
558
+ * @param model - Target model identifier.
559
+ * @returns A new {@link Agent} configured with the selected model.
560
+ */
561
+ withModel(model: string): Agent;
526
562
  /**
527
563
  * Attach a middleware chain (logging, caching, rate limiting). Chainable.
528
564
  *
@@ -686,6 +722,18 @@ declare class Agent implements Disposable {
686
722
  * @since 1.0.0
687
723
  */
688
724
  streamIter(input: string | Message[], toolExecutor?: ToolExecutor): AgentStream;
725
+ /**
726
+ * Stream only text deltas with a tiny DX helper.
727
+ *
728
+ * @description Aggregates all streamed text deltas into a final string and optionally
729
+ * invokes `onDelta` for each chunk as it arrives.
730
+ *
731
+ * @param input - A string prompt or an array of {@link Message} objects.
732
+ * @param onDelta - Optional callback invoked for each text delta.
733
+ * @param toolExecutor - Optional async callback for handling tool invocations.
734
+ * @returns The final response text.
735
+ */
736
+ streamText(input: string | Message[], onDelta?: (delta: string) => void, toolExecutor?: ToolExecutor): Promise<string>;
689
737
  /**
690
738
  * Perform a single raw LLM call without the agentic loop.
691
739
  *
@@ -772,6 +820,8 @@ declare class Agent implements Disposable {
772
820
  * @internal
773
821
  */
774
822
  private ensureMcpTools;
823
+ /** Snapshot current agent configuration for cloning helpers. */
824
+ private toConfig;
775
825
  }
776
826
  /**
777
827
  * One-liner convenience function — create an agent, run a prompt, and return the text.
@@ -412,6 +412,7 @@ declare class Agent implements Disposable {
412
412
  private readonly _name;
413
413
  private readonly _provider;
414
414
  private readonly _model;
415
+ private readonly _providerOptions;
415
416
  private readonly _instructions;
416
417
  private _tools;
417
418
  private _options;
@@ -440,6 +441,20 @@ declare class Agent implements Disposable {
440
441
  * @since 1.0.0
441
442
  */
442
443
  constructor(config?: AgentConfig);
444
+ /**
445
+ * Create an agent using provider/model auto-detection from environment variables.
446
+ *
447
+ * @description Equivalent to `new Agent(config)`, but clearer in intent for env-driven setup.
448
+ *
449
+ * @param config - Optional partial configuration overrides.
450
+ * @returns A new {@link Agent} instance.
451
+ *
452
+ * @example
453
+ * ```ts
454
+ * const agent = Agent.fromEnv({ instructions: "Be concise." });
455
+ * ```
456
+ */
457
+ static fromEnv(config?: AgentConfig): Agent;
443
458
  /**
444
459
  * @description The agent's name.
445
460
  * @since 1.0.0
@@ -507,6 +522,17 @@ declare class Agent implements Disposable {
507
522
  * @since 1.0.0
508
523
  */
509
524
  addTools(tools: (ToolDef | TypedToolDef)[]): this;
525
+ /**
526
+ * Inline tool shortcut — define and attach a tool in one step.
527
+ *
528
+ * @example
529
+ * ```ts
530
+ * const result = await agent
531
+ * .withTool("get_weather", "Get weather for a city", async ({ city }) => ({ temp: 72 }))
532
+ * .run("Weather in Paris?");
533
+ * ```
534
+ */
535
+ withTool<TParams = Record<string, unknown>, TResult = unknown>(name: string, description: string, execute: (params: TParams) => TResult | Promise<TResult>, parameters?: Record<string, unknown>): this;
510
536
  /**
511
537
  * Merge additional agent options into the current configuration. Chainable.
512
538
  *
@@ -523,6 +549,16 @@ declare class Agent implements Disposable {
523
549
  * @since 1.0.0
524
550
  */
525
551
  setOptions(options: Partial<AgentOptions>): this;
552
+ /**
553
+ * Clone this agent with a different model.
554
+ *
555
+ * @description Returns a **new** agent instance preserving tools and integrations,
556
+ * but using the provided model identifier.
557
+ *
558
+ * @param model - Target model identifier.
559
+ * @returns A new {@link Agent} configured with the selected model.
560
+ */
561
+ withModel(model: string): Agent;
526
562
  /**
527
563
  * Attach a middleware chain (logging, caching, rate limiting). Chainable.
528
564
  *
@@ -686,6 +722,18 @@ declare class Agent implements Disposable {
686
722
  * @since 1.0.0
687
723
  */
688
724
  streamIter(input: string | Message[], toolExecutor?: ToolExecutor): AgentStream;
725
+ /**
726
+ * Stream only text deltas with a tiny DX helper.
727
+ *
728
+ * @description Aggregates all streamed text deltas into a final string and optionally
729
+ * invokes `onDelta` for each chunk as it arrives.
730
+ *
731
+ * @param input - A string prompt or an array of {@link Message} objects.
732
+ * @param onDelta - Optional callback invoked for each text delta.
733
+ * @param toolExecutor - Optional async callback for handling tool invocations.
734
+ * @returns The final response text.
735
+ */
736
+ streamText(input: string | Message[], onDelta?: (delta: string) => void, toolExecutor?: ToolExecutor): Promise<string>;
689
737
  /**
690
738
  * Perform a single raw LLM call without the agentic loop.
691
739
  *
@@ -772,6 +820,8 @@ declare class Agent implements Disposable {
772
820
  * @internal
773
821
  */
774
822
  private ensureMcpTools;
823
+ /** Snapshot current agent configuration for cloning helpers. */
824
+ private toConfig;
775
825
  }
776
826
  /**
777
827
  * One-liner convenience function — create an agent, run a prompt, and return the text.
package/dist/agent.cjs CHANGED
@@ -1,5 +1,5 @@
1
- "use strict";var T=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var S=Object.getOwnPropertyNames;var M=Object.prototype.hasOwnProperty;var N=(s,e)=>{for(var t in e)T(s,t,{get:e[t],enumerable:!0})},K=(s,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of S(e))!M.call(s,r)&&r!==t&&T(s,r,{get:()=>e[r],enumerable:!(o=D(e,r))||o.enumerable});return s};var G=s=>K(T({},"__esModule",{value:!0}),s);var $={};N($,{Agent:()=>u,AgentStream:()=>c,availableRuntimes:()=>w,batch:()=>R,executeCode:()=>O,gauss:()=>I,generateImage:()=>k,version:()=>_.version});module.exports=G($);var p=require("gauss-napi");var f="gpt-5.2";var L="claude-sonnet-4-20250514";var U="gemini-2.5-flash";var H="openai/gpt-5.2",Y="deepseek-chat";var j="meta-llama/Llama-3.3-70B-Instruct-Turbo",F="accounts/fireworks/models/llama-v3p1-70b-instruct",J="mistral-large-latest",B="sonar-pro",q="grok-3-beta",E={openai:f,anthropic:L,google:U,openrouter:H,deepseek:Y,groq:"llama-3.3-70b-versatile",ollama:"llama3.2",together:j,fireworks:F,mistral:J,perplexity:B,xai:q};var W={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 m(s){let e=W[s]??"";return e?(typeof process<"u"?process.env[e]:"")??"":""}function g(){let s=[{env:"OPENAI_API_KEY",provider:"openai"},{env:"ANTHROPIC_API_KEY",provider:"anthropic"},{env:"GOOGLE_API_KEY",provider:"google"},{env:"GROQ_API_KEY",provider:"groq"},{env:"DEEPSEEK_API_KEY",provider:"deepseek"},{env:"OPENROUTER_API_KEY",provider:"openrouter"},{env:"TOGETHER_API_KEY",provider:"together"},{env:"FIREWORKS_API_KEY",provider:"fireworks"},{env:"MISTRAL_API_KEY",provider:"mistral"},{env:"PERPLEXITY_API_KEY",provider:"perplexity"},{env:"XAI_API_KEY",provider:"xai"}];for(let{env:e,provider:t}of s)if(typeof process<"u"&&process.env[e])return{provider:t,model:E[t]}}var v=require("gauss-napi");function X(s){return{...s,citations:s.citations?.map(e=>({type:e.citationType??e.type,citedText:e.citedText,documentTitle:e.documentTitle,start:e.start,end:e.end}))}}var c=class{constructor(e,t,o,r,i,n){this.agentName=e;this.providerHandle=t;this.tools=o;this.messages=r;this.options=i;this.toolExecutor=n}_result;get result(){return this._result}async*[Symbol.asyncIterator](){let e=[],t,o=!1,r=n=>{try{e.push(JSON.parse(n))}catch{e.push({type:"raw",text:n})}t?.()},i=(0,v.agent_stream_with_tool_executor)(this.agentName,this.providerHandle,this.tools,this.messages,this.options,r,this.toolExecutor).then(n=>{this._result=X(n),o=!0,t?.()});for(;!o||e.length>0;)e.length>0?yield e.shift():o||await new Promise(n=>{t=n});await i}};function b(s){return typeof s.execute=="function"}function P(s,e){let t=new Map(s.map(o=>[o.name,o]));return async o=>{let r;try{r=JSON.parse(o)}catch{return JSON.stringify({error:"Invalid tool call JSON"})}let i=r.tool??r.name??"",n=t.get(i);if(!n)return e?e(o):JSON.stringify({error:`Unknown tool: ${i}`});try{let a=r.args??r.arguments??{},l=await n.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:l})}}}function h(s){return{...s,citations:s.citations?.map(e=>({type:e.citationType??e.type,citedText:e.citedText,documentTitle:e.documentTitle,start:e.start,end:e.end}))}}var u=class{providerHandle;_name;_provider;_model;_instructions;_tools=[];_options={};disposed=!1;_middleware=null;_guardrails=null;_memory=null;_sessionId="";_mcpClients=[];_mcpToolsLoaded=!1;constructor(e={}){let t=g();this._provider=e.provider??t?.provider??"openai",this._model=e.model??t?.model??f,this._name=e.name??"agent",this._instructions=e.instructions??"";let o=e.providerOptions?.apiKey??m(this._provider);this.providerHandle=(0,p.create_provider)(this._provider,this._model,{apiKey:o,...e.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 r=e.codeExecution,i=r===!0?{python:!0,javascript:!0,bash:!0}:r||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:i,grounding:e.grounding,nativeCodeExecution:e.nativeCodeExecution,responseModalities:e.responseModalities}}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,p.get_provider_capabilities)(this.providerHandle)}addTool(e){return this._tools.push(e),this}addTools(e){return this._tools.push(...e),this}setOptions(e){return this._options={...this._options,...e},this}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 n=await this._memory.recall(this._sessionId?{sessionId:this._sessionId}:void 0);n.length>0&&(t=[{role:"system",content:`Previous context:
2
- ${n.map(l=>l.content).join(`
3
- `)}`},...t])}let{toolDefs:o,executor:r}=this.resolveToolsAndExecutor(),i;if(r?i=h(await(0,p.agent_run_with_tool_executor)(this._name,this.providerHandle,o,t,this._options,r)):i=h(await(0,p.agent_run)(this._name,this.providerHandle,o,t,this._options)),this._memory){let n=typeof e=="string"?e:e.map(a=>a.content).join(`
4
- `);await this._memory.store({id:`${Date.now()}-user`,content:n,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:r,executor:i}=this.resolveToolsAndExecutor(),n=async a=>{if(i){let l=await i(a);if(!JSON.parse(l).error?.startsWith("Unknown tool:"))return l}return t(a)};return h(await(0,p.agent_run_with_tool_executor)(this._name,this.providerHandle,r,o,this._options,n))}async stream(e,t,o){this.assertNotDisposed(),await this.ensureMcpTools();let r=typeof e=="string"?[{role:"user",content:e}]:e,{toolDefs:i,executor:n}=this.resolveToolsAndExecutor(),a=o??n??A;return h(await(0,p.agent_stream_with_tool_executor)(this._name,this.providerHandle,i,r,this._options,t,a))}streamIter(e,t){this.assertNotDisposed();let o=typeof e=="string"?[{role:"user",content:e}]:e,{toolDefs:r,executor:i}=this.resolveToolsAndExecutor(),n=t??i??A;return new c(this._name,this.providerHandle,r,o,this._options,n)}async generate(e,t){this.assertNotDisposed();let o=typeof e=="string"?[{role:"user",content:e}]:e;return(0,p.generate)(this.providerHandle,o,t?.temperature,t?.maxTokens)}async generateWithTools(e,t,o){this.assertNotDisposed();let r=typeof e=="string"?[{role:"user",content:e}]:e;return(0,p.generate_with_tools)(this.providerHandle,r,t,o?.temperature,o?.maxTokens)}destroy(){if(!this.disposed){this.disposed=!0;for(let e of this._mcpClients)try{e.close()}catch{}try{(0,p.destroy_provider)(this.providerHandle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error(`Agent "${this._name}" has been destroyed`)}resolveToolsAndExecutor(){let e=this._tools.filter(b),t=this._tools.map(r=>({name:r.name,description:r.description,parameters:r.parameters})),o=e.length>0?P(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 r of t){let i={...r,execute:async n=>{let a=JSON.stringify({tool:r.name,args:n}),l=await o(a);return JSON.parse(l)}};this._tools.push(i)}}this._mcpToolsLoaded=!0}}},A=async()=>"{}";async function I(s,e){let t=new u({name:"gauss",...e});try{return(await t.run(s)).text}finally{t.destroy()}}async function R(s,e){let{concurrency:t=5,...o}=e??{},r=s.map(n=>({input:n})),i=new u({name:"batch",...o});try{let n=[...r.entries()],a=Array.from({length:Math.min(t,n.length)},async()=>{for(;n.length>0;){let l=n.shift();if(!l)break;let[y,C]=l;try{r[y].result=await i.run(C.input)}catch(x){r[y].error=x instanceof Error?x:new Error(String(x))}}});await Promise.all(a)}finally{i.destroy()}return r}var d=require("gauss-napi");var _=require("gauss-napi");async function O(s,e,t){return(0,d.execute_code)(s,e,t?.timeoutSecs,t?.workingDir,t?.sandbox)}async function w(){return(0,d.available_runtimes)()}async function k(s,e={}){let t=g(),o=e.provider??t?.provider??"openai",r=e.model??t?.model??"dall-e-3",i=e.providerOptions?.apiKey??m(o),n=(0,d.create_provider)(o,r,{apiKey:i,...e.providerOptions});try{return await(0,d.generate_image)(n,s,e.model,e.size,e.quality,e.style,e.aspectRatio,e.n,e.responseFormat)}finally{(0,d.destroy_provider)(n)}}0&&(module.exports={Agent,AgentStream,availableRuntimes,batch,executeCode,gauss,generateImage,version});
1
+ "use strict";var _=Object.defineProperty;var N=Object.getOwnPropertyDescriptor;var K=Object.getOwnPropertyNames;var G=Object.prototype.hasOwnProperty;var L=(n,e)=>{for(var t in e)_(n,t,{get:e[t],enumerable:!0})},U=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of K(e))!G.call(n,r)&&r!==t&&_(n,r,{get:()=>e[r],enumerable:!(o=N(e,r))||o.enumerable});return n};var H=n=>U(_({},"__esModule",{value:!0}),n);var Q={};L(Q,{Agent:()=>u,AgentStream:()=>c,availableRuntimes:()=>D,batch:()=>k,executeCode:()=>C,gauss:()=>I,generateImage:()=>S,version:()=>v.version});module.exports=H(Q);var p=require("gauss-napi");var f=class extends Error{code;constructor(e,t){super(t),this.name="GaussError",this.code=e}},m=class extends f{resourceType;resourceName;constructor(e,t){super("RESOURCE_DISPOSED",`${e} "${t}" has been destroyed. Create a new instance.`),this.name="DisposedError",this.resourceType=e,this.resourceName=t}};var E="gpt-5.2";var Y="claude-sonnet-4-20250514";var F="gemini-2.5-flash";var j="openai/gpt-5.2",$="deepseek-chat";var J="meta-llama/Llama-3.3-70B-Instruct-Turbo",B="accounts/fireworks/models/llama-v3p1-70b-instruct",X="mistral-large-latest",q="sonar-pro",W="grok-3-beta",b={openai:E,anthropic:Y,google:F,openrouter:j,deepseek:$,groq:"llama-3.3-70b-versatile",ollama:"llama3.2",together:J,fireworks:B,mistral:X,perplexity:q,xai:W};var V={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 g(n){let e=V[n]??"";return e?(typeof process<"u"?process.env[e]:"")??"":""}function h(){let n=[{env:"OPENAI_API_KEY",provider:"openai"},{env:"ANTHROPIC_API_KEY",provider:"anthropic"},{env:"GOOGLE_API_KEY",provider:"google"},{env:"GROQ_API_KEY",provider:"groq"},{env:"DEEPSEEK_API_KEY",provider:"deepseek"},{env:"OPENROUTER_API_KEY",provider:"openrouter"},{env:"TOGETHER_API_KEY",provider:"together"},{env:"FIREWORKS_API_KEY",provider:"fireworks"},{env:"MISTRAL_API_KEY",provider:"mistral"},{env:"PERPLEXITY_API_KEY",provider:"perplexity"},{env:"XAI_API_KEY",provider:"xai"}];for(let{env:e,provider:t}of n)if(typeof process<"u"&&process.env[e])return{provider:t,model:b[t]}}var P=require("gauss-napi");function z(n){return{...n,citations:n.citations?.map(e=>({type:e.citationType??e.type,citedText:e.citedText,documentTitle:e.documentTitle,start:e.start,end:e.end}))}}var c=class{constructor(e,t,o,r,i,s){this.agentName=e;this.providerHandle=t;this.tools=o;this.messages=r;this.options=i;this.toolExecutor=s}_result;get result(){return this._result}async*[Symbol.asyncIterator](){let e=[],t,o=!1,r=s=>{try{e.push(JSON.parse(s))}catch{e.push({type:"raw",text:s})}t?.()},i=(0,P.agent_stream_with_tool_executor)(this.agentName,this.providerHandle,this.tools,this.messages,this.options,r,this.toolExecutor).then(s=>{this._result=z(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 R(n){return{name:n.name,description:n.description,parameters:n.parameters,execute:n.execute}}function A(n){return typeof n.execute=="function"}function O(n,e){let t=new Map(n.map(o=>[o.name,o]));return async o=>{let r;try{r=JSON.parse(o)}catch{return JSON.stringify({error:"Invalid tool call JSON"})}let i=r.tool??r.name??"",s=t.get(i);if(!s)return e?e(o):JSON.stringify({error:`Unknown tool: ${i}`});try{let a=r.args??r.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 y(n){return{...n,citations:n.citations?.map(e=>({type:e.citationType??e.type??"unknown",citedText:e.citedText,documentTitle:e.documentTitle,start:e.start,end:e.end}))}}var u=class n{providerHandle;_name;_provider;_model;_providerOptions;_instructions;_tools=[];_options={};disposed=!1;_middleware=null;_guardrails=null;_memory=null;_sessionId="";_mcpClients=[];_mcpToolsLoaded=!1;constructor(e={}){let t=h();this._provider=e.provider??t?.provider??"openai",this._model=e.model??t?.model??E,this._name=e.name??"agent",this._instructions=e.instructions??"";let o=e.providerOptions?.apiKey??g(this._provider);this._providerOptions={apiKey:o,...e.providerOptions},this.providerHandle=(0,p.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 r=e.codeExecution,i=r===!0?{python:!0,javascript:!0,bash:!0}:r||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:i,grounding:e.grounding,nativeCodeExecution:e.nativeCodeExecution,responseModalities:e.responseModalities}}static fromEnv(e={}){return new n(e)}get name(){return this._name}get provider(){return this._provider}get model(){return this._model}get instructions(){return this._instructions}get handle(){return this.providerHandle}get capabilities(){return(0,p.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,r){return this._tools.push(R({name:e,description:t,parameters:r??{},execute:o})),this}setOptions(e){return this._options={...this._options,...e},this}withModel(e){return this.assertNotDisposed(),new n({...this.toConfig(),model:e})}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
+ ${s.map(d=>d.content).join(`
3
+ `)}`},...t])}let{toolDefs:o,executor:r}=this.resolveToolsAndExecutor(),i;if(r?i=y(await(0,p.agent_run_with_tool_executor)(this._name,this.providerHandle,o,t,this._options,r)):i=y(await(0,p.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:r,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 y(await(0,p.agent_run_with_tool_executor)(this._name,this.providerHandle,r,o,this._options,s))}async stream(e,t,o){this.assertNotDisposed(),await this.ensureMcpTools();let r=typeof e=="string"?[{role:"user",content:e}]:e,{toolDefs:i,executor:s}=this.resolveToolsAndExecutor(),a=o??s??w;return y(await(0,p.agent_stream_with_tool_executor)(this._name,this.providerHandle,i,r,this._options,t,a))}streamIter(e,t){this.assertNotDisposed();let o=typeof e=="string"?[{role:"user",content:e}]:e,{toolDefs:r,executor:i}=this.resolveToolsAndExecutor(),s=t??i??w;return new c(this._name,this.providerHandle,r,o,this._options,s)}async streamText(e,t,o){this.assertNotDisposed();let r=this.streamIter(e,o),i="";for await(let s of r){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 r.result?.text??i}async generate(e,t){this.assertNotDisposed();let o=typeof e=="string"?[{role:"user",content:e}]:e;return(0,p.generate)(this.providerHandle,o,t?.temperature,t?.maxTokens)}async generateWithTools(e,t,o){this.assertNotDisposed();let r=typeof e=="string"?[{role:"user",content:e}]:e;return(0,p.generate_with_tools)(this.providerHandle,r,t,o?.temperature,o?.maxTokens)}destroy(){if(!this.disposed){this.disposed=!0;for(let e of this._mcpClients)try{e.close()}catch{}try{(0,p.destroy_provider)(this.providerHandle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new m("Agent",this._name)}resolveToolsAndExecutor(){let e=this._tools.filter(A),t=this._tools.map(r=>({name:r.name,description:r.description,parameters:r.parameters})),o=e.length>0?O(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 r of t){let i={...r,execute:async s=>{let a=JSON.stringify({tool:r.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._provider,model:this._model,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}}},w=async()=>"{}";async function I(n,e){let t=new u({name:"gauss",...e});try{return(await t.run(n)).text}finally{t.destroy()}}async function k(n,e){let{concurrency:t=5,...o}=e??{},r=n.map(s=>({input:s})),i=new u({name:"batch",...o});try{let s=[...r.entries()],a=Array.from({length:Math.min(t,s.length)},async()=>{for(;s.length>0;){let d=s.shift();if(!d)break;let[x,M]=d;try{r[x].result=await i.run(M.input)}catch(T){r[x].error=T instanceof Error?T:new Error(String(T))}}});await Promise.all(a)}finally{i.destroy()}return r}var l=require("gauss-napi");var v=require("gauss-napi");async function C(n,e,t){return(0,l.execute_code)(n,e,t?.timeoutSecs,t?.workingDir,t?.sandbox)}async function D(){return(0,l.available_runtimes)()}async function S(n,e={}){let t=h(),o=e.provider??t?.provider??"openai",r=e.model??t?.model??"dall-e-3",i=e.providerOptions?.apiKey??g(o),s=(0,l.create_provider)(o,r,{apiKey:i,...e.providerOptions});try{return await(0,l.generate_image)(s,n,e.model,e.size,e.quality,e.style,e.aspectRatio,e.n,e.responseFormat)}finally{(0,l.destroy_provider)(s)}}0&&(module.exports={Agent,AgentStream,availableRuntimes,batch,executeCode,gauss,generateImage,version});
5
5
  //# sourceMappingURL=agent.cjs.map