gauss-ts 1.1.0
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/LICENSE +21 -0
- package/README.md +499 -0
- package/dist/agent-CHrSUkPz.d.ts +485 -0
- package/dist/agent-CMp1wFzs.d.cts +485 -0
- package/dist/agent.cjs +2 -0
- package/dist/agent.cjs.map +1 -0
- package/dist/agent.d.cts +144 -0
- package/dist/agent.d.ts +144 -0
- package/dist/agent.js +2 -0
- package/dist/agent.js.map +1 -0
- package/dist/index.cjs +21 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +492 -0
- package/dist/index.d.ts +492 -0
- package/dist/index.js +21 -0
- package/dist/index.js.map +1 -0
- package/dist/mcp.cjs +2 -0
- package/dist/mcp.cjs.map +1 -0
- package/dist/mcp.d.cts +282 -0
- package/dist/mcp.d.ts +282 -0
- package/dist/mcp.js +2 -0
- package/dist/mcp.js.map +1 -0
- package/dist/middleware.cjs +2 -0
- package/dist/middleware.cjs.map +1 -0
- package/dist/middleware.d.cts +46 -0
- package/dist/middleware.d.ts +46 -0
- package/dist/middleware.js +2 -0
- package/dist/middleware.js.map +1 -0
- package/dist/orchestration.cjs +2 -0
- package/dist/orchestration.cjs.map +1 -0
- package/dist/orchestration.d.cts +94 -0
- package/dist/orchestration.d.ts +94 -0
- package/dist/orchestration.js +2 -0
- package/dist/orchestration.js.map +1 -0
- package/dist/rag.cjs +2 -0
- package/dist/rag.cjs.map +1 -0
- package/dist/rag.d.cts +43 -0
- package/dist/rag.d.ts +43 -0
- package/dist/rag.js +2 -0
- package/dist/rag.js.map +1 -0
- package/dist/tools.cjs +2 -0
- package/dist/tools.cjs.map +1 -0
- package/dist/tools.d.cts +48 -0
- package/dist/tools.d.ts +48 -0
- package/dist/tools.js +2 -0
- package/dist/tools.js.map +1 -0
- package/dist/types-BkwC4s1P.d.cts +239 -0
- package/dist/types-BkwC4s1P.d.ts +239 -0
- package/package.json +132 -0
package/dist/agent.d.cts
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { A as AgentConfig } from './agent-CMp1wFzs.cjs';
|
|
2
|
+
export { a as Agent, b as AgentStream, S as StreamEvent, g as gauss } from './agent-CMp1wFzs.cjs';
|
|
3
|
+
import { b as AgentResult, g as CodeExecutionResult, I as ImageGenerationConfig, P as ProviderType, c as ProviderOptions, k as ImageGenerationResult } from './types-BkwC4s1P.cjs';
|
|
4
|
+
export { version } from 'gauss-napi';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Represents a single item in a batch execution.
|
|
8
|
+
*
|
|
9
|
+
* @description Each `BatchItem` holds the original input and, after execution, either
|
|
10
|
+
* a successful {@link AgentResult} or an {@link Error}. Exactly one of `result` or `error`
|
|
11
|
+
* will be populated after the batch completes.
|
|
12
|
+
*
|
|
13
|
+
* @typeParam T - The input type (defaults to `string`).
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* ```ts
|
|
17
|
+
* const item: BatchItem = { input: "Translate: Hello", result: { text: "Bonjour", ... } };
|
|
18
|
+
* if (item.error) console.error(item.error.message);
|
|
19
|
+
* ```
|
|
20
|
+
*
|
|
21
|
+
* @since 1.0.0
|
|
22
|
+
*/
|
|
23
|
+
interface BatchItem<T = string> {
|
|
24
|
+
/** The original input prompt. */
|
|
25
|
+
input: T;
|
|
26
|
+
/** The successful agent result, if the execution succeeded. */
|
|
27
|
+
result?: AgentResult;
|
|
28
|
+
/** The error, if the execution failed. */
|
|
29
|
+
error?: Error;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Run multiple prompts through an agent in parallel with concurrency control.
|
|
33
|
+
*
|
|
34
|
+
* @description Creates a single shared {@link Agent} and dispatches all prompts through it
|
|
35
|
+
* using a worker pool. Failed prompts do not abort the batch — their errors are captured
|
|
36
|
+
* in the corresponding {@link BatchItem.error} field. The agent is automatically destroyed
|
|
37
|
+
* after all prompts complete.
|
|
38
|
+
*
|
|
39
|
+
* @param prompts - Array of string prompts to process.
|
|
40
|
+
* @param config - Optional agent configuration plus a `concurrency` field (default: `5`).
|
|
41
|
+
* @returns An array of {@link BatchItem} objects, one per prompt, in the same order.
|
|
42
|
+
* @throws {Error} If the agent cannot be created (e.g. missing API key).
|
|
43
|
+
*
|
|
44
|
+
* @example
|
|
45
|
+
* ```ts
|
|
46
|
+
* import { batch } from "gauss-ts";
|
|
47
|
+
*
|
|
48
|
+
* const results = await batch(
|
|
49
|
+
* ["Translate: Hello", "Translate: World", "Translate: Foo"],
|
|
50
|
+
* { concurrency: 2, provider: "openai" },
|
|
51
|
+
* );
|
|
52
|
+
* results.forEach(r => console.log(r.result?.text ?? r.error?.message));
|
|
53
|
+
* ```
|
|
54
|
+
*
|
|
55
|
+
* @since 1.0.0
|
|
56
|
+
*/
|
|
57
|
+
declare function batch(prompts: string[], config?: Omit<AgentConfig, "name"> & {
|
|
58
|
+
concurrency?: number;
|
|
59
|
+
}): Promise<BatchItem[]>;
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Execute code in a sandboxed runtime without creating a full Agent.
|
|
63
|
+
*
|
|
64
|
+
* @description Runs the provided code snippet in an isolated subprocess using the
|
|
65
|
+
* specified language runtime. No LLM or agent is involved — this is direct code execution.
|
|
66
|
+
*
|
|
67
|
+
* @param language - The runtime to use: `"python"`, `"javascript"`, or `"bash"`.
|
|
68
|
+
* @param code - The source code to execute.
|
|
69
|
+
* @param options - Optional execution parameters.
|
|
70
|
+
* @param options.timeoutSecs - Maximum execution time in seconds (default: 30).
|
|
71
|
+
* @param options.workingDir - Working directory for the subprocess.
|
|
72
|
+
* @param options.sandbox - Sandbox strictness level: `"default"`, `"strict"`, or `"permissive"`.
|
|
73
|
+
* @returns A {@link CodeExecutionResult} containing stdout, stderr, exit code, and timing info.
|
|
74
|
+
*
|
|
75
|
+
* @example
|
|
76
|
+
* ```ts
|
|
77
|
+
* const result = await executeCode("python", "print(2 + 2)");
|
|
78
|
+
* console.log(result.stdout); // "4\n"
|
|
79
|
+
* console.log(result.success); // true
|
|
80
|
+
* ```
|
|
81
|
+
*
|
|
82
|
+
* @since 1.0.0
|
|
83
|
+
*/
|
|
84
|
+
declare function executeCode(language: "python" | "javascript" | "bash", code: string, options?: {
|
|
85
|
+
timeoutSecs?: number;
|
|
86
|
+
workingDir?: string;
|
|
87
|
+
sandbox?: "default" | "strict" | "permissive";
|
|
88
|
+
}): Promise<CodeExecutionResult>;
|
|
89
|
+
/**
|
|
90
|
+
* Check which code execution runtimes are available on this system.
|
|
91
|
+
*
|
|
92
|
+
* @description Probes the host system for installed language runtimes (e.g. Python, Node.js, Bash)
|
|
93
|
+
* and returns the names of those that are usable with {@link executeCode}.
|
|
94
|
+
*
|
|
95
|
+
* @returns An array of available runtime names (e.g. `["python", "javascript", "bash"]`).
|
|
96
|
+
*
|
|
97
|
+
* @example
|
|
98
|
+
* ```ts
|
|
99
|
+
* const runtimes = await availableRuntimes();
|
|
100
|
+
* console.log(runtimes); // ["python", "javascript", "bash"]
|
|
101
|
+
* ```
|
|
102
|
+
*
|
|
103
|
+
* @since 1.0.0
|
|
104
|
+
*/
|
|
105
|
+
declare function availableRuntimes(): Promise<string[]>;
|
|
106
|
+
/**
|
|
107
|
+
* Generate images using a provider's image generation API.
|
|
108
|
+
*
|
|
109
|
+
* @description Creates a temporary provider connection, sends the prompt to the image generation
|
|
110
|
+
* model, and returns the result. The provider is automatically destroyed after the call.
|
|
111
|
+
* Supports OpenAI DALL-E, Google Gemini, and other providers with image generation capabilities.
|
|
112
|
+
*
|
|
113
|
+
* @param prompt - Text description of the desired image.
|
|
114
|
+
* @param options - Image generation configuration plus optional provider settings.
|
|
115
|
+
* @param options.provider - LLM provider (auto-detected from env if omitted).
|
|
116
|
+
* @param options.providerOptions - Provider connection options (API key auto-resolved if omitted).
|
|
117
|
+
* @param options.model - Image model identifier (e.g. `"dall-e-3"`).
|
|
118
|
+
* @param options.size - Desired image dimensions (e.g. `"1024x1024"`).
|
|
119
|
+
* @param options.quality - Quality level (e.g. `"standard"`, `"hd"`).
|
|
120
|
+
* @param options.style - Style preset (e.g. `"vivid"`, `"natural"`).
|
|
121
|
+
* @param options.aspectRatio - Aspect ratio for Gemini (e.g. `"16:9"`).
|
|
122
|
+
* @param options.n - Number of images to generate.
|
|
123
|
+
* @param options.responseFormat - Response format (`"url"` or `"b64_json"`).
|
|
124
|
+
* @returns An {@link ImageGenerationResult} containing generated image data and optional revised prompt.
|
|
125
|
+
* @throws {Error} If the provider cannot be initialised or image generation fails.
|
|
126
|
+
*
|
|
127
|
+
* @example
|
|
128
|
+
* ```ts
|
|
129
|
+
* const result = await generateImage("A sunset over mountains", {
|
|
130
|
+
* provider: "openai",
|
|
131
|
+
* model: "dall-e-3",
|
|
132
|
+
* size: "1024x1024",
|
|
133
|
+
* });
|
|
134
|
+
* console.log(result.images[0].url);
|
|
135
|
+
* ```
|
|
136
|
+
*
|
|
137
|
+
* @since 1.0.0
|
|
138
|
+
*/
|
|
139
|
+
declare function generateImage(prompt: string, options?: ImageGenerationConfig & {
|
|
140
|
+
provider?: ProviderType;
|
|
141
|
+
providerOptions?: ProviderOptions;
|
|
142
|
+
}): Promise<ImageGenerationResult>;
|
|
143
|
+
|
|
144
|
+
export { AgentConfig, type BatchItem, availableRuntimes, batch, executeCode, generateImage };
|
package/dist/agent.d.ts
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { A as AgentConfig } from './agent-CHrSUkPz.js';
|
|
2
|
+
export { a as Agent, b as AgentStream, S as StreamEvent, g as gauss } from './agent-CHrSUkPz.js';
|
|
3
|
+
import { b as AgentResult, g as CodeExecutionResult, I as ImageGenerationConfig, P as ProviderType, c as ProviderOptions, k as ImageGenerationResult } from './types-BkwC4s1P.js';
|
|
4
|
+
export { version } from 'gauss-napi';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Represents a single item in a batch execution.
|
|
8
|
+
*
|
|
9
|
+
* @description Each `BatchItem` holds the original input and, after execution, either
|
|
10
|
+
* a successful {@link AgentResult} or an {@link Error}. Exactly one of `result` or `error`
|
|
11
|
+
* will be populated after the batch completes.
|
|
12
|
+
*
|
|
13
|
+
* @typeParam T - The input type (defaults to `string`).
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* ```ts
|
|
17
|
+
* const item: BatchItem = { input: "Translate: Hello", result: { text: "Bonjour", ... } };
|
|
18
|
+
* if (item.error) console.error(item.error.message);
|
|
19
|
+
* ```
|
|
20
|
+
*
|
|
21
|
+
* @since 1.0.0
|
|
22
|
+
*/
|
|
23
|
+
interface BatchItem<T = string> {
|
|
24
|
+
/** The original input prompt. */
|
|
25
|
+
input: T;
|
|
26
|
+
/** The successful agent result, if the execution succeeded. */
|
|
27
|
+
result?: AgentResult;
|
|
28
|
+
/** The error, if the execution failed. */
|
|
29
|
+
error?: Error;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Run multiple prompts through an agent in parallel with concurrency control.
|
|
33
|
+
*
|
|
34
|
+
* @description Creates a single shared {@link Agent} and dispatches all prompts through it
|
|
35
|
+
* using a worker pool. Failed prompts do not abort the batch — their errors are captured
|
|
36
|
+
* in the corresponding {@link BatchItem.error} field. The agent is automatically destroyed
|
|
37
|
+
* after all prompts complete.
|
|
38
|
+
*
|
|
39
|
+
* @param prompts - Array of string prompts to process.
|
|
40
|
+
* @param config - Optional agent configuration plus a `concurrency` field (default: `5`).
|
|
41
|
+
* @returns An array of {@link BatchItem} objects, one per prompt, in the same order.
|
|
42
|
+
* @throws {Error} If the agent cannot be created (e.g. missing API key).
|
|
43
|
+
*
|
|
44
|
+
* @example
|
|
45
|
+
* ```ts
|
|
46
|
+
* import { batch } from "gauss-ts";
|
|
47
|
+
*
|
|
48
|
+
* const results = await batch(
|
|
49
|
+
* ["Translate: Hello", "Translate: World", "Translate: Foo"],
|
|
50
|
+
* { concurrency: 2, provider: "openai" },
|
|
51
|
+
* );
|
|
52
|
+
* results.forEach(r => console.log(r.result?.text ?? r.error?.message));
|
|
53
|
+
* ```
|
|
54
|
+
*
|
|
55
|
+
* @since 1.0.0
|
|
56
|
+
*/
|
|
57
|
+
declare function batch(prompts: string[], config?: Omit<AgentConfig, "name"> & {
|
|
58
|
+
concurrency?: number;
|
|
59
|
+
}): Promise<BatchItem[]>;
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Execute code in a sandboxed runtime without creating a full Agent.
|
|
63
|
+
*
|
|
64
|
+
* @description Runs the provided code snippet in an isolated subprocess using the
|
|
65
|
+
* specified language runtime. No LLM or agent is involved — this is direct code execution.
|
|
66
|
+
*
|
|
67
|
+
* @param language - The runtime to use: `"python"`, `"javascript"`, or `"bash"`.
|
|
68
|
+
* @param code - The source code to execute.
|
|
69
|
+
* @param options - Optional execution parameters.
|
|
70
|
+
* @param options.timeoutSecs - Maximum execution time in seconds (default: 30).
|
|
71
|
+
* @param options.workingDir - Working directory for the subprocess.
|
|
72
|
+
* @param options.sandbox - Sandbox strictness level: `"default"`, `"strict"`, or `"permissive"`.
|
|
73
|
+
* @returns A {@link CodeExecutionResult} containing stdout, stderr, exit code, and timing info.
|
|
74
|
+
*
|
|
75
|
+
* @example
|
|
76
|
+
* ```ts
|
|
77
|
+
* const result = await executeCode("python", "print(2 + 2)");
|
|
78
|
+
* console.log(result.stdout); // "4\n"
|
|
79
|
+
* console.log(result.success); // true
|
|
80
|
+
* ```
|
|
81
|
+
*
|
|
82
|
+
* @since 1.0.0
|
|
83
|
+
*/
|
|
84
|
+
declare function executeCode(language: "python" | "javascript" | "bash", code: string, options?: {
|
|
85
|
+
timeoutSecs?: number;
|
|
86
|
+
workingDir?: string;
|
|
87
|
+
sandbox?: "default" | "strict" | "permissive";
|
|
88
|
+
}): Promise<CodeExecutionResult>;
|
|
89
|
+
/**
|
|
90
|
+
* Check which code execution runtimes are available on this system.
|
|
91
|
+
*
|
|
92
|
+
* @description Probes the host system for installed language runtimes (e.g. Python, Node.js, Bash)
|
|
93
|
+
* and returns the names of those that are usable with {@link executeCode}.
|
|
94
|
+
*
|
|
95
|
+
* @returns An array of available runtime names (e.g. `["python", "javascript", "bash"]`).
|
|
96
|
+
*
|
|
97
|
+
* @example
|
|
98
|
+
* ```ts
|
|
99
|
+
* const runtimes = await availableRuntimes();
|
|
100
|
+
* console.log(runtimes); // ["python", "javascript", "bash"]
|
|
101
|
+
* ```
|
|
102
|
+
*
|
|
103
|
+
* @since 1.0.0
|
|
104
|
+
*/
|
|
105
|
+
declare function availableRuntimes(): Promise<string[]>;
|
|
106
|
+
/**
|
|
107
|
+
* Generate images using a provider's image generation API.
|
|
108
|
+
*
|
|
109
|
+
* @description Creates a temporary provider connection, sends the prompt to the image generation
|
|
110
|
+
* model, and returns the result. The provider is automatically destroyed after the call.
|
|
111
|
+
* Supports OpenAI DALL-E, Google Gemini, and other providers with image generation capabilities.
|
|
112
|
+
*
|
|
113
|
+
* @param prompt - Text description of the desired image.
|
|
114
|
+
* @param options - Image generation configuration plus optional provider settings.
|
|
115
|
+
* @param options.provider - LLM provider (auto-detected from env if omitted).
|
|
116
|
+
* @param options.providerOptions - Provider connection options (API key auto-resolved if omitted).
|
|
117
|
+
* @param options.model - Image model identifier (e.g. `"dall-e-3"`).
|
|
118
|
+
* @param options.size - Desired image dimensions (e.g. `"1024x1024"`).
|
|
119
|
+
* @param options.quality - Quality level (e.g. `"standard"`, `"hd"`).
|
|
120
|
+
* @param options.style - Style preset (e.g. `"vivid"`, `"natural"`).
|
|
121
|
+
* @param options.aspectRatio - Aspect ratio for Gemini (e.g. `"16:9"`).
|
|
122
|
+
* @param options.n - Number of images to generate.
|
|
123
|
+
* @param options.responseFormat - Response format (`"url"` or `"b64_json"`).
|
|
124
|
+
* @returns An {@link ImageGenerationResult} containing generated image data and optional revised prompt.
|
|
125
|
+
* @throws {Error} If the provider cannot be initialised or image generation fails.
|
|
126
|
+
*
|
|
127
|
+
* @example
|
|
128
|
+
* ```ts
|
|
129
|
+
* const result = await generateImage("A sunset over mountains", {
|
|
130
|
+
* provider: "openai",
|
|
131
|
+
* model: "dall-e-3",
|
|
132
|
+
* size: "1024x1024",
|
|
133
|
+
* });
|
|
134
|
+
* console.log(result.images[0].url);
|
|
135
|
+
* ```
|
|
136
|
+
*
|
|
137
|
+
* @since 1.0.0
|
|
138
|
+
*/
|
|
139
|
+
declare function generateImage(prompt: string, options?: ImageGenerationConfig & {
|
|
140
|
+
provider?: ProviderType;
|
|
141
|
+
providerOptions?: ProviderOptions;
|
|
142
|
+
}): Promise<ImageGenerationResult>;
|
|
143
|
+
|
|
144
|
+
export { AgentConfig, type BatchItem, availableRuntimes, batch, executeCode, generateImage };
|
package/dist/agent.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{create_provider as w,destroy_provider as D,agent_run as M,agent_run_with_tool_executor as K,agent_stream_with_tool_executor as G,generate as N,generate_with_tools as H,get_provider_capabilities as U}from"gauss-napi";var m="gpt-5.2";var _="claude-sonnet-4-20250514";var f="gemini-2.5-flash";var b="openai/gpt-5.2",T="deepseek-chat";var A="meta-llama/Llama-3.3-70B-Instruct-Turbo",P="accounts/fireworks/models/llama-v3p1-70b-instruct",O="mistral-large-latest",R="sonar-pro",I="grok-3-beta",y={openai:m,anthropic:_,google:f,openrouter:b,deepseek:T,groq:"llama-3.3-70b-versatile",ollama:"llama3.2",together:A,fireworks:P,mistral:O,perplexity:R,xai:I};var k={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 d(o){let e=k[o]??"";return e?(typeof process<"u"?process.env[e]:"")??"":""}function u(){let o=[{env:"OPENAI_API_KEY",provider:"openai"},{env:"ANTHROPIC_API_KEY",provider:"anthropic"},{env:"GOOGLE_API_KEY",provider:"google"},{env:"GROQ_API_KEY",provider:"groq"},{env:"DEEPSEEK_API_KEY",provider:"deepseek"},{env:"OPENROUTER_API_KEY",provider:"openrouter"},{env:"TOGETHER_API_KEY",provider:"together"},{env:"FIREWORKS_API_KEY",provider:"fireworks"},{env:"MISTRAL_API_KEY",provider:"mistral"},{env:"PERPLEXITY_API_KEY",provider:"perplexity"},{env:"XAI_API_KEY",provider:"xai"}];for(let{env:e,provider:t}of o)if(typeof process<"u"&&process.env[e])return{provider:t,model:y[t]}}import{agent_stream_with_tool_executor as C}from"gauss-napi";function S(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 p=class{constructor(e,t,r,n,i,s){this.agentName=e;this.providerHandle=t;this.tools=r;this.messages=n;this.options=i;this.toolExecutor=s}_result;get result(){return this._result}async*[Symbol.asyncIterator](){let e=[],t,r=!1,n=s=>{try{e.push(JSON.parse(s))}catch{e.push({type:"raw",text:s})}t?.()},i=C(this.agentName,this.providerHandle,this.tools,this.messages,this.options,n,this.toolExecutor).then(s=>{this._result=S(s),r=!0,t?.()});for(;!r||e.length>0;)e.length>0?yield e.shift():r||await new Promise(s=>{t=s});await i}};function c(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 a=class{providerHandle;_name;_provider;_model;_instructions;_tools=[];_options={};disposed=!1;constructor(e={}){let t=u();this._provider=e.provider??t?.provider??"openai",this._model=e.model??t?.model??m,this._name=e.name??"agent",this._instructions=e.instructions??"";let r=e.providerOptions?.apiKey??d(this._provider);this.providerHandle=w(this._provider,this._model,{apiKey:r,...e.providerOptions}),e.tools&&(this._tools=[...e.tools]);let n=e.codeExecution,i=n===!0?{python:!0,javascript:!0,bash:!0}:n||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 U(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}async run(e){this.assertNotDisposed();let t=typeof e=="string"?[{role:"user",content:e}]:e;return c(await M(this._name,this.providerHandle,this._tools,t,this._options))}async runWithTools(e,t){this.assertNotDisposed();let r=typeof e=="string"?[{role:"user",content:e}]:e;return c(await K(this._name,this.providerHandle,this._tools,r,this._options,t))}async stream(e,t,r){this.assertNotDisposed();let n=typeof e=="string"?[{role:"user",content:e}]:e;return c(await G(this._name,this.providerHandle,this._tools,n,this._options,t,r??E))}streamIter(e,t){this.assertNotDisposed();let r=typeof e=="string"?[{role:"user",content:e}]:e;return new p(this._name,this.providerHandle,this._tools,r,this._options,t??E)}async generate(e,t){this.assertNotDisposed();let r=typeof e=="string"?[{role:"user",content:e}]:e;return N(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 H(this.providerHandle,n,t,r?.temperature,r?.maxTokens)}destroy(){if(!this.disposed){this.disposed=!0;try{D(this.providerHandle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error(`Agent "${this._name}" has been destroyed`)}},E=async()=>"{}";async function L(o,e){let t=new a({name:"gauss",...e});try{return(await t.run(o)).text}finally{t.destroy()}}async function Y(o,e){let{concurrency:t=5,...r}=e??{},n=o.map(s=>({input:s})),i=new a({name:"batch",...r});try{let s=[...n.entries()],v=Array.from({length:Math.min(t,s.length)},async()=>{for(;s.length>0;){let g=s.shift();if(!g)break;let[h,x]=g;try{n[h].result=await i.run(x.input)}catch(l){n[h].error=l instanceof Error?l:new Error(String(l))}}});await Promise.all(v)}finally{i.destroy()}return n}import{create_provider as F,destroy_provider as j,execute_code as B,available_runtimes as q,generate_image as X}from"gauss-napi";import{version as V}from"gauss-napi";async function W(o,e,t){return B(o,e,t?.timeoutSecs,t?.workingDir,t?.sandbox)}async function z(){return q()}async function J(o,e={}){let t=u(),r=e.provider??t?.provider??"openai",n=e.model??t?.model??"dall-e-3",i=e.providerOptions?.apiKey??d(r),s=F(r,n,{apiKey:i,...e.providerOptions});try{return await X(s,o,e.model,e.size,e.quality,e.style,e.aspectRatio,e.n,e.responseFormat)}finally{j(s)}}export{a as Agent,p as AgentStream,z as availableRuntimes,Y as batch,W as executeCode,L as gauss,J as generateImage,V as version};
|
|
2
|
+
//# sourceMappingURL=agent.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/sdk/agent.ts","../src/sdk/models.ts","../src/sdk/types.ts","../src/sdk/stream-iter.ts","../src/sdk/batch.ts","../src/sdk/code-execution.ts"],"sourcesContent":["/**\n * Agent — the heart of Gauss.\n *\n * Quick start:\n * const agent = new Agent({ instructions: \"You are a helpful assistant.\" });\n * const result = await agent.run(\"What is the meaning of life?\");\n *\n * Full control:\n * const agent = new Agent({\n * name: \"researcher\",\n * provider: \"anthropic\",\n * model: \"claude-sonnet-4-20250514\",\n * providerOptions: { apiKey: \"sk-...\" },\n * instructions: \"You are a research assistant.\",\n * tools: [{ name: \"search\", description: \"Search the web\", parameters: { query: { type: \"string\" } } }],\n * temperature: 0.7,\n * maxSteps: 10,\n * });\n */\nimport {\n create_provider,\n destroy_provider,\n agent_run,\n agent_run_with_tool_executor,\n agent_stream_with_tool_executor,\n generate,\n generate_with_tools,\n get_provider_capabilities,\n} from \"gauss-napi\";\n\nimport type {\n ProviderOptions,\n ProviderType,\n ToolDef,\n Message,\n AgentOptions,\n AgentResult,\n ToolExecutor,\n StreamCallback,\n Handle,\n Disposable,\n} from \"./types.js\";\n\nimport { resolveApiKey, detectProvider } from \"./types.js\";\nimport { OPENAI_DEFAULT } from \"./models.js\";\nimport { AgentStream } from \"./stream-iter.js\";\n\n/**\n * Transform a raw NAPI result into the public {@link AgentResult} shape.\n *\n * @description Normalises citation field names returned by different native providers\n * into the unified SDK format.\n *\n * @param raw - Raw result object from the NAPI layer.\n * @returns Normalised {@link AgentResult}.\n * @internal\n */\nfunction toSdkResult(raw: any): AgentResult {\n return {\n ...raw,\n citations: raw.citations?.map((c: any) => ({\n type: c.citationType ?? c.type,\n citedText: c.citedText,\n documentTitle: c.documentTitle,\n start: c.start,\n end: c.end,\n })),\n };\n}\n\n// ─── Config ────────────────────────────────────────────────────────\n\n/**\n * Configuration object for creating an {@link Agent} instance.\n *\n * @description All fields are optional — sensible defaults are applied and the provider is auto-detected from environment variables when omitted.\n *\n * @example\n * ```ts\n * const config: AgentConfig = {\n * provider: \"anthropic\",\n * model: \"claude-sonnet-4-20250514\",\n * instructions: \"You are a helpful assistant.\",\n * temperature: 0.7,\n * };\n * const agent = new Agent(config);\n * ```\n *\n * @since 1.0.0\n */\nexport interface AgentConfig {\n /** Agent name (default: `\"agent\"`). Used for logging and identification. */\n name?: string;\n\n /** LLM provider. Auto-detected from env if omitted. */\n provider?: ProviderType;\n\n /** Model identifier (e.g. `\"gpt-4o\"`, `\"claude-sonnet-4-20250514\"`). Auto-selected if omitted. */\n model?: string;\n\n /** Provider connection options. API key auto-resolved from env if omitted. */\n providerOptions?: ProviderOptions;\n\n /** System instructions prepended to every conversation. */\n instructions?: string;\n\n /** Tool definitions available to the agent. */\n tools?: ToolDef[];\n\n /** Sampling temperature (0–2). Higher values produce more creative output. */\n temperature?: number;\n\n /** Maximum number of agentic loop iterations before stopping. */\n maxSteps?: number;\n\n /** Top-p (nucleus) sampling threshold. */\n topP?: number;\n\n /** Maximum number of output tokens per response. */\n maxTokens?: number;\n\n /** Deterministic seed for reproducible outputs. */\n seed?: number;\n\n /** Stop the agentic loop when this tool name is called. */\n stopOnTool?: string;\n\n /** JSON schema for structured output. The model will conform its response to this schema. */\n outputSchema?: Record<string, unknown>;\n\n /** Extended thinking budget (Anthropic). Number of tokens for internal reasoning. */\n thinkingBudget?: number;\n\n /** Reasoning effort for OpenAI o-series models. Controls how much reasoning to use. */\n reasoningEffort?: \"low\" | \"medium\" | \"high\";\n\n /** Enable prompt caching (Anthropic). Auto-annotates system messages and tools. */\n cacheControl?: boolean;\n\n /** Enable code execution runtimes. Pass `true` for all defaults, or configure individually. */\n codeExecution?: boolean | import(\"./types.js\").CodeExecutionOptions;\n\n /** Enable Google Search grounding (Gemini only). */\n grounding?: boolean;\n\n /** Enable native code execution / Gemini code interpreter. */\n nativeCodeExecution?: boolean;\n\n /** Response modalities (e.g. `[\"TEXT\", \"IMAGE\"]` for Gemini image generation). */\n responseModalities?: string[];\n}\n\n// ─── Agent Class ───────────────────────────────────────────────────\n\n/**\n * Core agent class that wraps a native LLM provider and manages the agentic loop.\n *\n * @description `Agent` is the primary entry-point for interacting with language models in Gauss.\n * It supports single-shot completions, multi-step tool-use loops, streaming, and raw generation.\n * Each instance owns a native provider handle that **must** be released via {@link Agent.destroy}\n * (or the `using` pattern) to avoid resource leaks.\n *\n * @example\n * ```ts\n * const agent = new Agent({\n * provider: \"openai\",\n * model: \"gpt-4o\",\n * instructions: \"You are a helpful assistant.\",\n * });\n * const result = await agent.run(\"What is the meaning of life?\");\n * console.log(result.text);\n * agent.destroy();\n * ```\n *\n * @since 1.0.0\n */\nexport class Agent implements Disposable {\n private readonly providerHandle: Handle;\n private readonly _name: string;\n private readonly _provider: ProviderType;\n private readonly _model: string;\n private readonly _instructions: string;\n private _tools: ToolDef[] = [];\n private _options: AgentOptions = {};\n private disposed = false;\n\n /**\n * Create a new Agent.\n *\n * @description Initialises the native provider connection and configures the agentic\n * loop options. The provider and model are auto-detected from environment variables\n * when not explicitly set.\n *\n * @param config - Agent configuration. All fields are optional.\n * @throws {Error} If the native provider cannot be created (e.g. invalid API key).\n *\n * @example\n * ```ts\n * const agent = new Agent({ instructions: \"Be concise.\" });\n * ```\n *\n * @since 1.0.0\n */\n constructor(config: AgentConfig = {}) {\n const detected = detectProvider();\n this._provider = config.provider ?? detected?.provider ?? \"openai\";\n this._model = config.model ?? detected?.model ?? OPENAI_DEFAULT;\n this._name = config.name ?? \"agent\";\n this._instructions = config.instructions ?? \"\";\n\n const apiKey =\n config.providerOptions?.apiKey ?? resolveApiKey(this._provider);\n this.providerHandle = create_provider(this._provider, this._model, {\n apiKey,\n ...config.providerOptions,\n });\n\n if (config.tools) this._tools = [...config.tools];\n\n const ceOpt = config.codeExecution;\n const codeExecution = ceOpt === true\n ? { python: true, javascript: true, bash: true }\n : ceOpt || undefined;\n\n this._options = {\n instructions: this._instructions || undefined,\n temperature: config.temperature,\n maxSteps: config.maxSteps,\n topP: config.topP,\n maxTokens: config.maxTokens,\n seed: config.seed,\n stopOnTool: config.stopOnTool,\n outputSchema: config.outputSchema,\n thinkingBudget: config.thinkingBudget,\n reasoningEffort: config.reasoningEffort,\n cacheControl: config.cacheControl,\n codeExecution,\n grounding: config.grounding,\n nativeCodeExecution: config.nativeCodeExecution,\n responseModalities: config.responseModalities,\n };\n }\n\n // ─── Accessors ──────────────────────────────────────────────────\n\n /**\n * @description The agent's name.\n * @since 1.0.0\n */\n get name(): string { return this._name; }\n\n /**\n * @description The resolved LLM provider type.\n * @since 1.0.0\n */\n get provider(): ProviderType { return this._provider; }\n\n /**\n * @description The resolved model identifier.\n * @since 1.0.0\n */\n get model(): string { return this._model; }\n\n /**\n * @description The system instructions string.\n * @since 1.0.0\n */\n get instructions(): string { return this._instructions; }\n\n /**\n * @description Native provider handle. Used internally by Network, Graph, and other subsystems.\n * @since 1.0.0\n * @internal\n */\n get handle(): Handle { return this.providerHandle; }\n\n /**\n * @description Query what features this provider/model combination supports.\n * @returns The capability flags for the current provider and model.\n * @since 1.0.0\n */\n get capabilities(): import(\"./types.js\").ProviderCapabilities {\n return get_provider_capabilities(this.providerHandle);\n }\n\n // ─── Fluent Configuration ───────────────────────────────────────\n\n /**\n * Register a single tool definition. Chainable.\n *\n * @description Appends a tool to the agent's tool list so the LLM can invoke it during the agentic loop.\n *\n * @param tool - The tool definition to add.\n * @returns `this` for fluent chaining.\n *\n * @example\n * ```ts\n * agent.addTool({ name: \"search\", description: \"Web search\", parameters: { query: { type: \"string\" } } });\n * ```\n *\n * @since 1.0.0\n */\n addTool(tool: ToolDef): this {\n this._tools.push(tool);\n return this;\n }\n\n /**\n * Register multiple tool definitions at once. Chainable.\n *\n * @description Appends all provided tools to the agent's tool list.\n *\n * @param tools - Array of tool definitions to add.\n * @returns `this` for fluent chaining.\n *\n * @example\n * ```ts\n * agent.addTools([\n * { name: \"search\", description: \"Web search\", parameters: { query: { type: \"string\" } } },\n * { name: \"calculate\", description: \"Math calculator\", parameters: { expr: { type: \"string\" } } },\n * ]);\n * ```\n *\n * @since 1.0.0\n */\n addTools(tools: ToolDef[]): this {\n this._tools.push(...tools);\n return this;\n }\n\n /**\n * Merge additional agent options into the current configuration. Chainable.\n *\n * @description Shallow-merges the provided options with the existing ones. Later calls override earlier values.\n *\n * @param options - Partial agent options to merge.\n * @returns `this` for fluent chaining.\n *\n * @example\n * ```ts\n * agent.setOptions({ temperature: 0.5, maxTokens: 1024 });\n * ```\n *\n * @since 1.0.0\n */\n setOptions(options: Partial<AgentOptions>): this {\n this._options = { ...this._options, ...options };\n return this;\n }\n\n // ─── Execution ──────────────────────────────────────────────────\n\n /**\n * Run the agentic loop to completion.\n *\n * @description Sends the input through the full agentic loop (tool calls, multi-step reasoning)\n * and returns the final result. Accepts either a plain string prompt or a pre-built message array.\n *\n * @param input - A string prompt or an array of {@link Message} objects.\n * @returns The completed {@link AgentResult} containing the response text, token counts, and optional structured output.\n * @throws {Error} If the agent has been destroyed.\n *\n * @example\n * ```ts\n * const result = await agent.run(\"Explain quantum computing\");\n * console.log(result.text);\n * console.log(`Tokens: ${result.inputTokens} in / ${result.outputTokens} out`);\n * ```\n *\n * @since 1.0.0\n */\n async run(input: string | Message[]): Promise<AgentResult> {\n this.assertNotDisposed();\n const messages = typeof input === \"string\"\n ? [{ role: \"user\" as const, content: input }]\n : input;\n return toSdkResult(await agent_run(\n this._name,\n this.providerHandle,\n this._tools,\n messages,\n this._options\n ));\n }\n\n /**\n * Run the agentic loop with a JavaScript-side tool executor.\n *\n * @description Like {@link Agent.run}, but delegates tool invocations to the provided\n * `toolExecutor` callback. Use this when tools need access to the Node.js runtime\n * (file system, network, databases, etc.).\n *\n * @param input - A string prompt or an array of {@link Message} objects.\n * @param toolExecutor - Async callback that receives a JSON-encoded tool call and returns a JSON-encoded result.\n * @returns The completed {@link AgentResult}.\n * @throws {Error} If the agent has been destroyed.\n *\n * @example\n * ```ts\n * const result = await agent.runWithTools(\"Search for cats\", async (callJson) => {\n * const call = JSON.parse(callJson);\n * return JSON.stringify({ results: [\"cat1\", \"cat2\"] });\n * });\n * ```\n *\n * @since 1.0.0\n */\n async runWithTools(\n input: string | Message[],\n toolExecutor: ToolExecutor\n ): Promise<AgentResult> {\n this.assertNotDisposed();\n const messages = typeof input === \"string\"\n ? [{ role: \"user\" as const, content: input }]\n : input;\n return toSdkResult(await agent_run_with_tool_executor(\n this._name,\n this.providerHandle,\n this._tools,\n messages,\n this._options,\n toolExecutor\n ));\n }\n\n /**\n * Stream agent responses with real-time events via a callback.\n *\n * @description Runs the agentic loop while invoking `onEvent` for each streaming event\n * (text deltas, tool calls, etc.). Returns the final aggregated result after the stream ends.\n *\n * @param input - A string prompt or an array of {@link Message} objects.\n * @param onEvent - Callback invoked with each JSON-encoded stream event.\n * @param toolExecutor - Optional async callback for handling tool invocations.\n * @returns The completed {@link AgentResult}.\n * @throws {Error} If the agent has been destroyed.\n *\n * @example\n * ```ts\n * const result = await agent.stream(\"Tell me a joke\", (eventJson) => {\n * const event = JSON.parse(eventJson);\n * if (event.type === \"text_delta\") process.stdout.write(event.text ?? \"\");\n * });\n * ```\n *\n * @since 1.0.0\n */\n async stream(\n input: string | Message[],\n onEvent: StreamCallback,\n toolExecutor?: ToolExecutor\n ): Promise<AgentResult> {\n this.assertNotDisposed();\n const messages = typeof input === \"string\"\n ? [{ role: \"user\" as const, content: input }]\n : input;\n return toSdkResult(await agent_stream_with_tool_executor(\n this._name,\n this.providerHandle,\n this._tools,\n messages,\n this._options,\n onEvent,\n toolExecutor ?? NOOP_TOOL_EXECUTOR\n ));\n }\n\n /**\n * Stream as an async iterable — use with `for await`.\n *\n * @description Returns an {@link AgentStream} that yields {@link StreamEvent} objects.\n * After iteration completes, the final {@link AgentResult} is available via\n * `stream.result`.\n *\n * @param input - A string prompt or an array of {@link Message} objects.\n * @param toolExecutor - Optional async callback for handling tool invocations.\n * @returns An {@link AgentStream} async iterable of {@link StreamEvent} objects.\n * @throws {Error} If the agent has been destroyed.\n *\n * @example\n * ```ts\n * const stream = agent.streamIter(\"Tell me a story\");\n * for await (const event of stream) {\n * if (event.type === \"text_delta\") process.stdout.write(event.text ?? \"\");\n * }\n * console.log(stream.result?.text);\n * ```\n *\n * @since 1.0.0\n */\n streamIter(\n input: string | Message[],\n toolExecutor?: ToolExecutor\n ): AgentStream {\n this.assertNotDisposed();\n const messages = typeof input === \"string\"\n ? [{ role: \"user\" as const, content: input }]\n : input;\n return new AgentStream(\n this._name,\n this.providerHandle,\n this._tools,\n messages,\n this._options,\n toolExecutor ?? NOOP_TOOL_EXECUTOR\n );\n }\n\n /**\n * Perform a single raw LLM call without the agentic loop.\n *\n * @description Bypasses the multi-step agent loop and sends the input directly to the model\n * for a one-shot completion. Useful when you need a simple generation without tool use.\n *\n * @param input - A string prompt or an array of {@link Message} objects.\n * @param options - Optional generation parameters.\n * @param options.temperature - Sampling temperature override.\n * @param options.maxTokens - Maximum output tokens override.\n * @returns The raw provider response.\n *\n * @example\n * ```ts\n * const response = await agent.generate(\"Translate 'hello' to French\", { temperature: 0 });\n * ```\n *\n * @since 1.0.0\n */\n async generate(\n input: string | Message[],\n options?: { temperature?: number; maxTokens?: number }\n ): Promise<unknown> {\n this.assertNotDisposed();\n const messages = typeof input === \"string\"\n ? [{ role: \"user\" as const, content: input }]\n : input;\n return generate(\n this.providerHandle,\n messages,\n options?.temperature,\n options?.maxTokens\n );\n }\n\n /**\n * Perform a single raw LLM call with tool definitions (no agentic loop).\n *\n * @description Like {@link Agent.generate}, but also passes tool definitions to the model.\n * The model may return tool-call requests in its response, but the caller is responsible\n * for executing them — no automatic loop is performed.\n *\n * @param input - A string prompt or an array of {@link Message} objects.\n * @param tools - Tool definitions to make available to the model.\n * @param options - Optional generation parameters.\n * @param options.temperature - Sampling temperature override.\n * @param options.maxTokens - Maximum output tokens override.\n * @returns The raw provider response, potentially containing tool call requests.\n *\n * @example\n * ```ts\n * const response = await agent.generateWithTools(\n * \"What's the weather?\",\n * [{ name: \"get_weather\", description: \"Get weather\", parameters: { city: { type: \"string\" } } }],\n * );\n * ```\n *\n * @since 1.0.0\n */\n async generateWithTools(\n input: string | Message[],\n tools: ToolDef[],\n options?: { temperature?: number; maxTokens?: number }\n ): Promise<unknown> {\n this.assertNotDisposed();\n const messages = typeof input === \"string\"\n ? [{ role: \"user\" as const, content: input }]\n : input;\n return generate_with_tools(\n this.providerHandle,\n messages,\n tools,\n options?.temperature,\n options?.maxTokens\n );\n }\n\n // ─── Lifecycle ──────────────────────────────────────────────────\n\n /**\n * Release all native resources held by this agent.\n *\n * @description Destroys the underlying native provider handle. Safe to call multiple times;\n * subsequent calls are no-ops. After calling `destroy()`, any further method calls on this\n * agent will throw.\n *\n * @since 1.0.0\n */\n destroy(): void {\n if (!this.disposed) {\n this.disposed = true;\n try {\n destroy_provider(this.providerHandle);\n } catch {\n // Already destroyed — safe to ignore.\n }\n }\n }\n\n /**\n * Alias for {@link Agent.destroy} — enables the TC39 `using` pattern.\n *\n * @example\n * ```ts\n * {\n * using agent = new Agent({ instructions: \"Be helpful.\" });\n * const result = await agent.run(\"Hi!\");\n * } // agent is automatically destroyed here\n * ```\n *\n * @since 1.0.0\n */\n [Symbol.dispose](): void {\n this.destroy();\n }\n\n private assertNotDisposed(): void {\n if (this.disposed) {\n throw new Error(`Agent \"${this._name}\" has been destroyed`);\n }\n }\n}\n\n/** No-op tool executor — used when no tools are registered. */\nconst NOOP_TOOL_EXECUTOR: ToolExecutor = async () => \"{}\";\n\n/**\n * One-liner convenience function — create an agent, run a prompt, and return the text.\n *\n * @description Creates a temporary {@link Agent}, sends the prompt through the agentic loop,\n * and returns just the response text. The agent is automatically destroyed after the call.\n * Ideal for quick, single-turn interactions.\n *\n * @param prompt - The user prompt to send to the agent.\n * @param config - Optional agent configuration (everything except `name`).\n * @returns The agent's response text.\n * @throws {Error} If the provider cannot be initialised or the call fails.\n *\n * @example\n * ```ts\n * import { gauss } from \"gauss-ts\";\n * const answer = await gauss(\"What is the meaning of life?\");\n * console.log(answer);\n * ```\n *\n * @since 1.0.0\n */\nexport async function gauss(\n prompt: string,\n config?: Omit<AgentConfig, \"name\">\n): Promise<string> {\n const agent = new Agent({ name: \"gauss\", ...config });\n try {\n const result = await agent.run(prompt);\n return result.text;\n } finally {\n agent.destroy();\n }\n}\n","/**\n * Model Constants — Single Source of Truth\n *\n * Update these when new model versions are released.\n * All examples, tests, and defaults reference this file.\n */\n\n// ─── OpenAI ──────────────────────────────────────────\nexport const OPENAI_DEFAULT = \"gpt-5.2\";\nexport const OPENAI_FAST = \"gpt-4.1\";\nexport const OPENAI_REASONING = \"o4-mini\";\nexport const OPENAI_IMAGE = \"gpt-image-1\";\n\n// ─── Anthropic ───────────────────────────────────────\nexport const ANTHROPIC_DEFAULT = \"claude-sonnet-4-20250514\";\nexport const ANTHROPIC_FAST = \"claude-haiku-4-20250414\";\nexport const ANTHROPIC_PREMIUM = \"claude-opus-4-20250414\";\n\n// ─── Google ──────────────────────────────────────────\nexport const GOOGLE_DEFAULT = \"gemini-2.5-flash\";\nexport const GOOGLE_PREMIUM = \"gemini-2.5-pro\";\nexport const GOOGLE_IMAGE = \"gemini-2.0-flash\";\n\n// ─── OpenRouter ──────────────────────────────────────\nexport const OPENROUTER_DEFAULT = \"openai/gpt-5.2\";\n\n// ─── DeepSeek ────────────────────────────────────────\nexport const DEEPSEEK_DEFAULT = \"deepseek-chat\";\nexport const DEEPSEEK_REASONING = \"deepseek-reasoner\";\n\n// ─── Enterprise OpenAI-Compatible Providers ─────────\nexport const TOGETHER_DEFAULT = \"meta-llama/Llama-3.3-70B-Instruct-Turbo\";\nexport const FIREWORKS_DEFAULT = \"accounts/fireworks/models/llama-v3p1-70b-instruct\";\nexport const MISTRAL_DEFAULT = \"mistral-large-latest\";\nexport const PERPLEXITY_DEFAULT = \"sonar-pro\";\nexport const XAI_DEFAULT = \"grok-3-beta\";\n\n// ─── Provider Defaults Map ───────────────────────────\nexport const PROVIDER_DEFAULTS: Record<string, string> = {\n openai: OPENAI_DEFAULT,\n anthropic: ANTHROPIC_DEFAULT,\n google: GOOGLE_DEFAULT,\n openrouter: OPENROUTER_DEFAULT,\n deepseek: DEEPSEEK_DEFAULT,\n groq: \"llama-3.3-70b-versatile\",\n ollama: \"llama3.2\",\n together: TOGETHER_DEFAULT,\n fireworks: FIREWORKS_DEFAULT,\n mistral: MISTRAL_DEFAULT,\n perplexity: PERPLEXITY_DEFAULT,\n xai: XAI_DEFAULT,\n};\n\n/** Get the default model for a provider */\nexport function defaultModel(provider: string): string {\n return PROVIDER_DEFAULTS[provider] ?? OPENAI_DEFAULT;\n}\n","/**\n * Gauss SDK — Shared types.\n *\n * Design principles:\n * - Every option has a sensible default\n * - Minimal required fields — only what's truly mandatory\n * - String unions over enums for JS-friendliness\n * - Record<string, unknown> for extensibility\n */\n\n// ─── Provider ──────────────────────────────────────────────────────\n\nexport type ProviderType =\n | \"openai\"\n | \"anthropic\"\n | \"google\"\n | \"groq\"\n | \"ollama\"\n | \"deepseek\"\n | \"openrouter\"\n | \"together\"\n | \"fireworks\"\n | \"mistral\"\n | \"perplexity\"\n | \"xai\";\n\nexport interface ProviderOptions {\n /** API key. Auto-resolved from environment if omitted. */\n apiKey?: string;\n baseUrl?: string;\n timeoutMs?: number;\n maxRetries?: number;\n organization?: string;\n}\n\n// ─── Messages ──────────────────────────────────────────────────────\n\nexport type MessageRole = \"system\" | \"user\" | \"assistant\" | \"tool\";\n\nexport interface Message {\n role: MessageRole;\n content: string;\n}\n\n/** @deprecated Use `Message` instead. */\nexport type JsMessage = Message;\n\n// ─── Tools ─────────────────────────────────────────────────────────\n\nexport interface ToolDef {\n name: string;\n description: string;\n parameters?: Record<string, unknown>;\n}\n\nexport type ToolExecutor = (callJson: string) => Promise<string>;\nexport type StreamCallback = (eventJson: string) => void;\n\n// ─── Agent ─────────────────────────────────────────────────────────\n\nexport interface AgentOptions {\n instructions?: string;\n maxSteps?: number;\n temperature?: number;\n topP?: number;\n maxTokens?: number;\n seed?: number;\n stopOnTool?: string;\n outputSchema?: Record<string, unknown>;\n thinkingBudget?: number;\n /** Reasoning effort for OpenAI o-series models: \"low\", \"medium\", or \"high\". */\n reasoningEffort?: \"low\" | \"medium\" | \"high\";\n cacheControl?: boolean;\n codeExecution?: CodeExecutionOptions;\n /** Enable Google Search grounding (Gemini only). */\n grounding?: boolean;\n /** Enable native code execution / Gemini code interpreter. */\n nativeCodeExecution?: boolean;\n /** Response modalities (e.g. [\"TEXT\", \"IMAGE\"] for Gemini image generation). */\n responseModalities?: string[];\n}\n\n/** A citation reference from document-aware responses. */\nexport interface Citation {\n /** Citation type: char_location, page_location, content_block_location. */\n type: string;\n /** The cited text from the document. */\n citedText?: string;\n /** Title of the source document. */\n documentTitle?: string;\n /** Start index (character, page, or block depending on type). */\n start?: number;\n /** End index (character, page, or block depending on type). */\n end?: number;\n}\n\nexport interface AgentResult {\n text: string;\n steps: number;\n inputTokens: number;\n outputTokens: number;\n structuredOutput?: Record<string, unknown>;\n /** Extended thinking output (Anthropic). */\n thinking?: string;\n /** Citations from document-aware responses (Anthropic). */\n citations?: Citation[];\n /** Grounding metadata from Google Search grounding. */\n groundingMetadata?: GroundingMetadata[];\n}\n\n// ─── Grounding ──────────────────────────────────────────────────────\n\n/** Metadata from Google Search grounding. */\nexport interface GroundingMetadata {\n /** Search queries generated by the model. */\n searchQueries: string[];\n /** Grounding chunks (web results). */\n groundingChunks: GroundingChunk[];\n /** Rendered HTML search entry point widget. */\n searchEntryPoint?: string;\n}\n\n/** A single grounding chunk (web search result). */\nexport interface GroundingChunk {\n /** URL of the web result. */\n url?: string;\n /** Title of the web result. */\n title?: string;\n}\n\n// ─── Image Generation ───────────────────────────────────────────────\n\n/** Configuration for image generation. */\nexport interface ImageGenerationConfig {\n /** Image model (e.g. \"dall-e-3\", \"gemini-2.0-flash\"). */\n model?: string;\n /** Desired size (e.g. \"1024x1024\"). */\n size?: string;\n /** Quality level (e.g. \"standard\", \"hd\"). */\n quality?: string;\n /** Style (e.g. \"vivid\", \"natural\"). */\n style?: string;\n /** Aspect ratio for Gemini (e.g. \"16:9\", \"1:1\"). */\n aspectRatio?: string;\n /** Number of images to generate. */\n n?: number;\n /** Response format (\"url\" or \"b64_json\"). */\n responseFormat?: string;\n}\n\n/** Result of image generation. */\nexport interface ImageGenerationResult {\n /** Generated images. */\n images: GeneratedImageData[];\n /** Revised prompt (DALL-E 3 rewrites prompts). */\n revisedPrompt?: string;\n}\n\n/** A single generated image. */\nexport interface GeneratedImageData {\n /** URL to the generated image (temporary). */\n url?: string;\n /** Base64-encoded image data. */\n base64?: string;\n /** MIME type. */\n mimeType?: string;\n}\n\n// ─── Provider Capabilities ──────────────────────────────────────────\n\n/** Feature capabilities of a provider/model combination. */\nexport interface ProviderCapabilities {\n streaming: boolean;\n toolUse: boolean;\n vision: boolean;\n audio: boolean;\n extendedThinking: boolean;\n citations: boolean;\n cacheControl: boolean;\n structuredOutput: boolean;\n reasoningEffort: boolean;\n imageGeneration: boolean;\n grounding: boolean;\n codeExecution: boolean;\n webSearch: boolean;\n}\n\nexport interface CostEstimate {\n model: string;\n normalizedModel: string;\n currency: string;\n inputTokens: number;\n outputTokens: number;\n reasoningTokens: number;\n cacheReadTokens: number;\n cacheCreationTokens: number;\n inputCostUsd: number;\n outputCostUsd: number;\n reasoningCostUsd: number;\n cacheReadCostUsd: number;\n cacheCreationCostUsd: number;\n totalCostUsd: number;\n}\n\n// ─── Code Execution (PTC) ──────────────────────────────────────────\n\n/** Configuration for programmatic code execution runtimes. */\nexport interface CodeExecutionOptions {\n /** Enable Python runtime (default: true). */\n python?: boolean;\n /** Enable JavaScript/Node.js runtime (default: true). */\n javascript?: boolean;\n /** Enable Bash runtime (default: true). */\n bash?: boolean;\n /** Timeout in seconds per execution (default: 30). */\n timeoutSecs?: number;\n /** Working directory for subprocesses. */\n workingDir?: string;\n /** Sandbox mode: \"default\" | \"strict\" | \"permissive\" (default: \"default\"). */\n sandbox?: \"default\" | \"strict\" | \"permissive\";\n /** Use a single unified execute_code tool instead of per-language tools. */\n unified?: boolean;\n}\n\n/** Result of a code execution. */\nexport interface CodeExecutionResult {\n stdout: string;\n stderr: string;\n exitCode: number;\n timedOut: boolean;\n runtime: string;\n success: boolean;\n}\n\n// ─── Memory ────────────────────────────────────────────────────────\n\nexport type MemoryEntryType = \"conversation\" | \"fact\" | \"preference\" | \"task\" | \"summary\";\nexport type MemoryTier = \"core\" | \"active\" | \"background\" | \"archive\";\n\nexport interface MemoryEntry {\n id: string;\n content: string;\n entryType: MemoryEntryType;\n timestamp: string;\n tier?: MemoryTier;\n metadata?: Record<string, unknown>;\n importance?: number;\n sessionId?: string;\n embedding?: number[];\n}\n\nexport interface RecallOptions {\n sessionId?: string;\n limit?: number;\n}\n\nexport interface MemoryStats {\n totalEntries: number;\n [key: string]: unknown;\n}\n\n// ─── RAG / Vector Store ────────────────────────────────────────────\n\nexport interface VectorChunk {\n id: string;\n documentId: string;\n content: string;\n index: number;\n metadata?: Record<string, unknown>;\n embedding?: number[];\n}\n\nexport interface SearchResult {\n id: string;\n text: string;\n score: number;\n metadata?: Record<string, unknown>;\n}\n\n// ─── Guardrails ────────────────────────────────────────────────────\n\nexport type PiiAction = \"block\" | \"warn\" | \"redact\";\n\n// ─── Tool Validator ────────────────────────────────────────────────\n\nexport type CoercionStrategy =\n | \"null_to_default\"\n | \"type_cast\"\n | \"json_parse\"\n | \"strip_null\";\n\n// ─── Eval ──────────────────────────────────────────────────────────\n\nexport type EvalScorerType = \"exact_match\" | \"contains\" | \"length_ratio\";\n\n// ─── Core ──────────────────────────────────────────────────────────\n\n/** Opaque handle returned by NAPI resource constructors. */\nexport type Handle = number;\n\n/** Any SDK resource that owns native memory. */\nexport interface Disposable {\n destroy(): void;\n}\n\n// ─── Environment helpers ───────────────────────────────────────────\n\nimport { PROVIDER_DEFAULTS } from \"./models.js\";\n\nconst ENV_KEYS: Record<string, string> = {\n openai: \"OPENAI_API_KEY\",\n anthropic: \"ANTHROPIC_API_KEY\",\n google: \"GOOGLE_API_KEY\",\n groq: \"GROQ_API_KEY\",\n deepseek: \"DEEPSEEK_API_KEY\",\n openrouter: \"OPENROUTER_API_KEY\",\n together: \"TOGETHER_API_KEY\",\n fireworks: \"FIREWORKS_API_KEY\",\n mistral: \"MISTRAL_API_KEY\",\n perplexity: \"PERPLEXITY_API_KEY\",\n xai: \"XAI_API_KEY\",\n ollama: \"\",\n};\n\n/** Resolve an API key from environment for the given provider. */\nexport function resolveApiKey(provider: ProviderType): string {\n const key = ENV_KEYS[provider] ?? \"\";\n if (!key) return \"\"; // ollama doesn't need a key\n return (typeof process !== \"undefined\" ? process.env[key] : \"\") ?? \"\";\n}\n\n/** Auto-detect the best available provider from environment variables. */\nexport function detectProvider(): { provider: ProviderType; model: string } | undefined {\n const checks: Array<{ env: string; provider: ProviderType }> = [\n { env: \"OPENAI_API_KEY\", provider: \"openai\" },\n { env: \"ANTHROPIC_API_KEY\", provider: \"anthropic\" },\n { env: \"GOOGLE_API_KEY\", provider: \"google\" },\n { env: \"GROQ_API_KEY\", provider: \"groq\" },\n { env: \"DEEPSEEK_API_KEY\", provider: \"deepseek\" },\n { env: \"OPENROUTER_API_KEY\", provider: \"openrouter\" },\n { env: \"TOGETHER_API_KEY\", provider: \"together\" },\n { env: \"FIREWORKS_API_KEY\", provider: \"fireworks\" },\n { env: \"MISTRAL_API_KEY\", provider: \"mistral\" },\n { env: \"PERPLEXITY_API_KEY\", provider: \"perplexity\" },\n { env: \"XAI_API_KEY\", provider: \"xai\" },\n ];\n for (const { env, provider } of checks) {\n if (typeof process !== \"undefined\" && process.env[env]) {\n return { provider, model: PROVIDER_DEFAULTS[provider] };\n }\n }\n return undefined;\n}\n","/**\n * AgentStream — Async iterable wrapper over native streaming.\n *\n * @example\n * for await (const event of agent.streamIter(\"Tell me a story\", executor)) {\n * if (event.type === \"text_delta\") process.stdout.write(event.text ?? \"\");\n * }\n * // Access final result after iteration:\n * console.log(stream.result?.text);\n */\nimport { agent_stream_with_tool_executor } from \"gauss-napi\";\n\nimport type {\n ToolDef,\n Message,\n AgentOptions,\n AgentResult,\n ToolExecutor,\n Handle,\n} from \"./types.js\";\n\n/**\n * Transform a raw NAPI result into the public {@link AgentResult} shape.\n *\n * @param raw - Raw result object from the NAPI layer.\n * @returns Normalised {@link AgentResult}.\n * @internal\n */\nfunction toSdkResult(raw: any): AgentResult {\n return {\n ...raw,\n citations: raw.citations?.map((c: any) => ({\n type: c.citationType ?? c.type,\n citedText: c.citedText,\n documentTitle: c.documentTitle,\n start: c.start,\n end: c.end,\n })),\n };\n}\n\n/**\n * A single event emitted during agent streaming.\n *\n * @description Represents a parsed streaming event such as a text delta, tool call,\n * or other provider-specific event. The `type` field discriminates the event kind.\n *\n * @example\n * ```ts\n * const event: StreamEvent = { type: \"text_delta\", text: \"Hello\" };\n * if (event.type === \"text_delta\") process.stdout.write(event.text ?? \"\");\n * ```\n *\n * @since 1.0.0\n */\nexport interface StreamEvent {\n /** The event type discriminator (e.g. `\"text_delta\"`, `\"tool_call\"`, `\"raw\"`). */\n type: string;\n /** Text content for text-delta events. */\n text?: string;\n /** Tool call payload for tool-call events. */\n toolCall?: { name: string; arguments: string };\n /** Additional provider-specific fields. */\n [key: string]: unknown;\n}\n\n/**\n * Async iterable wrapper over the native agent streaming callback.\n *\n * @description Bridges the native callback-based streaming API into an `AsyncIterable<StreamEvent>`.\n * Use with `for await ... of` to consume events as they arrive. After iteration completes,\n * the final {@link AgentResult} is available via the {@link AgentStream.result} getter.\n *\n * @example\n * ```ts\n * const stream = agent.streamIter(\"Tell me a story\");\n * for await (const event of stream) {\n * if (event.type === \"text_delta\") process.stdout.write(event.text ?? \"\");\n * }\n * console.log(stream.result?.text);\n * ```\n *\n * @since 1.0.0\n */\nexport class AgentStream implements AsyncIterable<StreamEvent> {\n private _result: AgentResult | undefined;\n\n /**\n * Create a new `AgentStream`.\n *\n * @description Typically not called directly — use {@link Agent.streamIter} instead.\n *\n * @param agentName - Name of the agent for logging/identification.\n * @param providerHandle - Native provider handle.\n * @param tools - Tool definitions available during the stream.\n * @param messages - Conversation messages to send.\n * @param options - Agent options for the agentic loop.\n * @param toolExecutor - Async callback for executing tool calls.\n *\n * @since 1.0.0\n */\n constructor(\n private readonly agentName: string,\n private readonly providerHandle: Handle,\n private readonly tools: ToolDef[],\n private readonly messages: Message[],\n private readonly options: AgentOptions,\n private readonly toolExecutor: ToolExecutor,\n ) {}\n\n /**\n * The final aggregated result, available after async iteration completes.\n *\n * @description Returns `undefined` while iteration is still in progress. Once the\n * `for await` loop finishes, this contains the full {@link AgentResult} with response\n * text, token counts, and other metadata.\n *\n * @returns The completed {@link AgentResult} or `undefined` if iteration hasn't finished.\n *\n * @example\n * ```ts\n * const stream = agent.streamIter(\"Hello\");\n * for await (const event of stream) { /* consume events *\\/ }\n * console.log(stream.result?.text);\n * ```\n *\n * @since 1.0.0\n */\n get result(): AgentResult | undefined { return this._result; }\n\n /**\n * Async iterator implementation — yields {@link StreamEvent} objects as they arrive.\n *\n * @description Starts the native streaming call and yields parsed events. The iterator\n * completes when the underlying stream finishes and all buffered events have been yielded.\n *\n * @returns An async iterator of {@link StreamEvent} objects.\n *\n * @since 1.0.0\n */\n async *[Symbol.asyncIterator](): AsyncIterator<StreamEvent> {\n const buffer: StreamEvent[] = [];\n let resolve: (() => void) | undefined;\n let done = false;\n\n const onEvent = (json: string) => {\n try {\n buffer.push(JSON.parse(json) as StreamEvent);\n } catch {\n buffer.push({ type: \"raw\", text: json });\n }\n resolve?.();\n };\n\n const runPromise = agent_stream_with_tool_executor(\n this.agentName,\n this.providerHandle,\n this.tools,\n this.messages,\n this.options,\n onEvent,\n this.toolExecutor\n ).then((r) => {\n this._result = toSdkResult(r);\n done = true;\n resolve?.();\n });\n\n while (!done || buffer.length > 0) {\n if (buffer.length > 0) {\n yield buffer.shift()!;\n } else if (!done) {\n await new Promise<void>((r) => { resolve = r; });\n }\n }\n\n await runPromise;\n }\n}\n","/**\n * Batch execution — run multiple prompts through an agent in parallel.\n *\n * @example\n * import { batch } from \"gauss-ts\";\n *\n * const results = await batch(\n * [\"Translate: Hello\", \"Translate: World\"],\n * { concurrency: 2, provider: \"openai\" }\n * );\n * results.forEach(r => console.log(r.result?.text ?? r.error?.message));\n */\nimport { Agent } from \"./agent.js\";\nimport type { AgentConfig } from \"./agent.js\";\nimport type { AgentResult } from \"./types.js\";\n\n/**\n * Represents a single item in a batch execution.\n *\n * @description Each `BatchItem` holds the original input and, after execution, either\n * a successful {@link AgentResult} or an {@link Error}. Exactly one of `result` or `error`\n * will be populated after the batch completes.\n *\n * @typeParam T - The input type (defaults to `string`).\n *\n * @example\n * ```ts\n * const item: BatchItem = { input: \"Translate: Hello\", result: { text: \"Bonjour\", ... } };\n * if (item.error) console.error(item.error.message);\n * ```\n *\n * @since 1.0.0\n */\nexport interface BatchItem<T = string> {\n /** The original input prompt. */\n input: T;\n /** The successful agent result, if the execution succeeded. */\n result?: AgentResult;\n /** The error, if the execution failed. */\n error?: Error;\n}\n\n/**\n * Run multiple prompts through an agent in parallel with concurrency control.\n *\n * @description Creates a single shared {@link Agent} and dispatches all prompts through it\n * using a worker pool. Failed prompts do not abort the batch — their errors are captured\n * in the corresponding {@link BatchItem.error} field. The agent is automatically destroyed\n * after all prompts complete.\n *\n * @param prompts - Array of string prompts to process.\n * @param config - Optional agent configuration plus a `concurrency` field (default: `5`).\n * @returns An array of {@link BatchItem} objects, one per prompt, in the same order.\n * @throws {Error} If the agent cannot be created (e.g. missing API key).\n *\n * @example\n * ```ts\n * import { batch } from \"gauss-ts\";\n *\n * const results = await batch(\n * [\"Translate: Hello\", \"Translate: World\", \"Translate: Foo\"],\n * { concurrency: 2, provider: \"openai\" },\n * );\n * results.forEach(r => console.log(r.result?.text ?? r.error?.message));\n * ```\n *\n * @since 1.0.0\n */\nexport async function batch(\n prompts: string[],\n config?: Omit<AgentConfig, \"name\"> & { concurrency?: number }\n): Promise<BatchItem[]> {\n const { concurrency = 5, ...agentConfig } = config ?? {};\n const items: BatchItem[] = prompts.map((input) => ({ input }));\n\n const agent = new Agent({ name: \"batch\", ...agentConfig });\n try {\n const queue = [...items.entries()];\n const workers = Array.from({ length: Math.min(concurrency, queue.length) }, async () => {\n while (queue.length > 0) {\n const entry = queue.shift();\n if (!entry) break;\n const [idx, item] = entry;\n try {\n items[idx].result = await agent.run(item.input);\n } catch (err) {\n items[idx].error = err instanceof Error ? err : new Error(String(err));\n }\n }\n });\n await Promise.all(workers);\n } finally {\n agent.destroy();\n }\n return items;\n}\n","/**\n * Code execution & image generation — static utility functions.\n *\n * These functions don't require an Agent instance.\n *\n * @example\n * import { executeCode, availableRuntimes, generateImage } from \"gauss-ts\";\n *\n * const result = await executeCode(\"python\", \"print(2 + 2)\");\n * console.log(result.stdout); // \"4\\n\"\n */\nimport {\n create_provider,\n destroy_provider,\n execute_code,\n available_runtimes,\n generate_image,\n} from \"gauss-napi\";\n\nimport type {\n ProviderType,\n ProviderOptions,\n CodeExecutionResult,\n ImageGenerationConfig,\n ImageGenerationResult,\n} from \"./types.js\";\n\nimport { resolveApiKey, detectProvider } from \"./types.js\";\n\n/**\n * Execute code in a sandboxed runtime without creating a full Agent.\n *\n * @description Runs the provided code snippet in an isolated subprocess using the\n * specified language runtime. No LLM or agent is involved — this is direct code execution.\n *\n * @param language - The runtime to use: `\"python\"`, `\"javascript\"`, or `\"bash\"`.\n * @param code - The source code to execute.\n * @param options - Optional execution parameters.\n * @param options.timeoutSecs - Maximum execution time in seconds (default: 30).\n * @param options.workingDir - Working directory for the subprocess.\n * @param options.sandbox - Sandbox strictness level: `\"default\"`, `\"strict\"`, or `\"permissive\"`.\n * @returns A {@link CodeExecutionResult} containing stdout, stderr, exit code, and timing info.\n *\n * @example\n * ```ts\n * const result = await executeCode(\"python\", \"print(2 + 2)\");\n * console.log(result.stdout); // \"4\\n\"\n * console.log(result.success); // true\n * ```\n *\n * @since 1.0.0\n */\nexport async function executeCode(\n language: \"python\" | \"javascript\" | \"bash\",\n code: string,\n options?: { timeoutSecs?: number; workingDir?: string; sandbox?: \"default\" | \"strict\" | \"permissive\" },\n): Promise<CodeExecutionResult> {\n return execute_code(language, code, options?.timeoutSecs, options?.workingDir, options?.sandbox);\n}\n\n/**\n * Check which code execution runtimes are available on this system.\n *\n * @description Probes the host system for installed language runtimes (e.g. Python, Node.js, Bash)\n * and returns the names of those that are usable with {@link executeCode}.\n *\n * @returns An array of available runtime names (e.g. `[\"python\", \"javascript\", \"bash\"]`).\n *\n * @example\n * ```ts\n * const runtimes = await availableRuntimes();\n * console.log(runtimes); // [\"python\", \"javascript\", \"bash\"]\n * ```\n *\n * @since 1.0.0\n */\nexport async function availableRuntimes(): Promise<string[]> {\n return available_runtimes();\n}\n\n/**\n * Generate images using a provider's image generation API.\n *\n * @description Creates a temporary provider connection, sends the prompt to the image generation\n * model, and returns the result. The provider is automatically destroyed after the call.\n * Supports OpenAI DALL-E, Google Gemini, and other providers with image generation capabilities.\n *\n * @param prompt - Text description of the desired image.\n * @param options - Image generation configuration plus optional provider settings.\n * @param options.provider - LLM provider (auto-detected from env if omitted).\n * @param options.providerOptions - Provider connection options (API key auto-resolved if omitted).\n * @param options.model - Image model identifier (e.g. `\"dall-e-3\"`).\n * @param options.size - Desired image dimensions (e.g. `\"1024x1024\"`).\n * @param options.quality - Quality level (e.g. `\"standard\"`, `\"hd\"`).\n * @param options.style - Style preset (e.g. `\"vivid\"`, `\"natural\"`).\n * @param options.aspectRatio - Aspect ratio for Gemini (e.g. `\"16:9\"`).\n * @param options.n - Number of images to generate.\n * @param options.responseFormat - Response format (`\"url\"` or `\"b64_json\"`).\n * @returns An {@link ImageGenerationResult} containing generated image data and optional revised prompt.\n * @throws {Error} If the provider cannot be initialised or image generation fails.\n *\n * @example\n * ```ts\n * const result = await generateImage(\"A sunset over mountains\", {\n * provider: \"openai\",\n * model: \"dall-e-3\",\n * size: \"1024x1024\",\n * });\n * console.log(result.images[0].url);\n * ```\n *\n * @since 1.0.0\n */\nexport async function generateImage(\n prompt: string,\n options: ImageGenerationConfig & {\n provider?: ProviderType;\n providerOptions?: ProviderOptions;\n } = {},\n): Promise<ImageGenerationResult> {\n const detected = detectProvider();\n const providerType = options.provider ?? detected?.provider ?? \"openai\";\n const model = options.model ?? detected?.model ?? \"dall-e-3\";\n const apiKey = options.providerOptions?.apiKey ?? resolveApiKey(providerType);\n const handle = create_provider(providerType, model, { apiKey, ...options.providerOptions });\n try {\n return await generate_image(\n handle,\n prompt,\n options.model,\n options.size,\n options.quality,\n options.style,\n options.aspectRatio,\n options.n,\n options.responseFormat,\n );\n } finally {\n destroy_provider(handle);\n }\n}\n\n/**\n * Gauss core native library version.\n * @since 1.0.0\n */\nexport { version } from \"gauss-napi\";\n"],"mappings":"AAmBA,OACE,mBAAAA,EACA,oBAAAC,EACA,aAAAC,EACA,gCAAAC,EACA,mCAAAC,EACA,YAAAC,EACA,uBAAAC,EACA,6BAAAC,MACK,aCpBA,IAAMC,EAAiB,UAMvB,IAAMC,EAAoB,2BAK1B,IAAMC,EAAiB,mBAKvB,IAAMC,EAAqB,iBAGrBC,EAAmB,gBAIzB,IAAMC,EAAmB,0CAC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,CACAe,EAAiBH,CAAM,CACzB,CACF","names":["create_provider","destroy_provider","agent_run","agent_run_with_tool_executor","agent_stream_with_tool_executor","generate","generate_with_tools","get_provider_capabilities","OPENAI_DEFAULT","ANTHROPIC_DEFAULT","GOOGLE_DEFAULT","OPENROUTER_DEFAULT","DEEPSEEK_DEFAULT","TOGETHER_DEFAULT","FIREWORKS_DEFAULT","MISTRAL_DEFAULT","PERPLEXITY_DEFAULT","XAI_DEFAULT","PROVIDER_DEFAULTS","OPENAI_DEFAULT","ANTHROPIC_DEFAULT","GOOGLE_DEFAULT","OPENROUTER_DEFAULT","DEEPSEEK_DEFAULT","ENV_KEYS","resolveApiKey","provider","key","detectProvider","checks","env","PROVIDER_DEFAULTS","agent_stream_with_tool_executor","toSdkResult","raw","c","AgentStream","agentName","providerHandle","tools","messages","options","toolExecutor","buffer","resolve","done","onEvent","json","runPromise","r","toSdkResult","raw","c","Agent","config","detected","detectProvider","OPENAI_DEFAULT","apiKey","resolveApiKey","create_provider","ceOpt","codeExecution","get_provider_capabilities","tool","tools","options","input","messages","agent_run","toolExecutor","agent_run_with_tool_executor","onEvent","agent_stream_with_tool_executor","NOOP_TOOL_EXECUTOR","AgentStream","generate","generate_with_tools","destroy_provider","gauss","prompt","agent","batch","prompts","config","concurrency","agentConfig","items","input","agent","Agent","queue","workers","entry","idx","item","err","create_provider","destroy_provider","execute_code","available_runtimes","generate_image","version","executeCode","language","code","options","execute_code","availableRuntimes","available_runtimes","generateImage","prompt","detected","detectProvider","providerType","model","apiKey","resolveApiKey","handle","create_provider","generate_image","destroy_provider"]}
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"use strict";var de=Object.defineProperty;var xt=Object.getOwnPropertyDescriptor;var vt=Object.getOwnPropertyNames;var bt=Object.prototype.hasOwnProperty;var Tt=(r,e)=>{for(var t in e)de(r,t,{get:e[t],enumerable:!0})},kt=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of vt(e))!bt.call(r,n)&&n!==t&&de(r,n,{get:()=>e[n],enumerable:!(s=xt(e,n))||s.enumerable});return r};var St=r=>kt(de({},"__esModule",{value:!0}),r);var Mt={};Tt(Mt,{A2aClient:()=>oe,ANTHROPIC_DEFAULT:()=>pe,ANTHROPIC_FAST:()=>we,ANTHROPIC_PREMIUM:()=>De,Agent:()=>M,AgentSpec:()=>L,AgentStream:()=>H,ApprovalManager:()=>Q,CheckpointStore:()=>Z,DEEPSEEK_DEFAULT:()=>ue,DEEPSEEK_REASONING:()=>Oe,EvalRunner:()=>ee,FIREWORKS_DEFAULT:()=>ge,GOOGLE_DEFAULT:()=>le,GOOGLE_IMAGE:()=>Ne,GOOGLE_PREMIUM:()=>Me,Graph:()=>Y,GuardrailChain:()=>X,MISTRAL_DEFAULT:()=>he,McpServer:()=>$,Memory:()=>F,MiddlewareChain:()=>V,Network:()=>q,OPENAI_DEFAULT:()=>O,OPENAI_FAST:()=>Ae,OPENAI_IMAGE:()=>Re,OPENAI_REASONING:()=>Pe,OPENROUTER_DEFAULT:()=>ce,PERPLEXITY_DEFAULT:()=>ye,PROVIDER_DEFAULTS:()=>J,PluginRegistry:()=>W,SkillSpec:()=>ne,TOGETHER_DEFAULT:()=>me,Team:()=>z,Telemetry:()=>te,ToolRegistry:()=>ae,ToolValidator:()=>se,VectorStore:()=>K,Workflow:()=>B,XAI_DEFAULT:()=>fe,agentMessage:()=>ft,availableRuntimes:()=>Le,batch:()=>Ge,classify:()=>dt,codeReview:()=>at,compose:()=>ht,countMessageTokens:()=>We,countTokens:()=>qe,countTokensForModel:()=>Ve,createCircuitBreaker:()=>Be,createFallbackProvider:()=>Ye,createResilientAgent:()=>ze,createResilientProvider:()=>be,defaultModel:()=>Ce,detectProvider:()=>I,discoverAgents:()=>lt,enterprisePreset:()=>xe,enterpriseRun:()=>Ue,estimateCost:()=>Xe,executeCode:()=>Je,extract:()=>pt,extractText:()=>Se,filterAsync:()=>ut,gauss:()=>je,generateImage:()=>Fe,getContextWindowSize:()=>$e,mapAsync:()=>ke,parseAgentConfig:()=>Qe,parsePartialJson:()=>tt,pipe:()=>ct,reduceAsync:()=>mt,resolveApiKey:()=>C,resolveEnv:()=>Ze,retryable:()=>rt,structured:()=>st,summarize:()=>ot,tapAsync:()=>gt,taskText:()=>_t,template:()=>N,textMessage:()=>ie,translate:()=>it,userMessage:()=>yt,version:()=>ve.version,withRetry:()=>Te});module.exports=St(Mt);var O="gpt-5.2",Ae="gpt-4.1",Pe="o4-mini",Re="gpt-image-1",pe="claude-sonnet-4-20250514",we="claude-haiku-4-20250414",De="claude-opus-4-20250414",le="gemini-2.5-flash",Me="gemini-2.5-pro",Ne="gemini-2.0-flash",ce="openai/gpt-5.2",ue="deepseek-chat",Oe="deepseek-reasoner",me="meta-llama/Llama-3.3-70B-Instruct-Turbo",ge="accounts/fireworks/models/llama-v3p1-70b-instruct",he="mistral-large-latest",ye="sonar-pro",fe="grok-3-beta",J={openai:O,anthropic:pe,google:le,openrouter:ce,deepseek:ue,groq:"llama-3.3-70b-versatile",ollama:"llama3.2",together:me,fireworks:ge,mistral:he,perplexity:ye,xai:fe};function Ce(r){return J[r]??O}var Et={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 C(r){let e=Et[r]??"";return e?(typeof process<"u"?process.env[e]:"")??"":""}function I(){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:J[t]}}var p=require("gauss-napi");var Ie=require("gauss-napi");function At(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 H=class{constructor(e,t,s,n,i,o){this.agentName=e;this.providerHandle=t;this.tools=s;this.messages=n;this.options=i;this.toolExecutor=o}_result;get result(){return this._result}async*[Symbol.asyncIterator](){let e=[],t,s=!1,n=o=>{try{e.push(JSON.parse(o))}catch{e.push({type:"raw",text:o})}t?.()},i=(0,Ie.agent_stream_with_tool_executor)(this.agentName,this.providerHandle,this.tools,this.messages,this.options,n,this.toolExecutor).then(o=>{this._result=At(o),s=!0,t?.()});for(;!s||e.length>0;)e.length>0?yield e.shift():s||await new Promise(o=>{t=o});await i}};function _e(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{providerHandle;_name;_provider;_model;_instructions;_tools=[];_options={};disposed=!1;constructor(e={}){let t=I();this._provider=e.provider??t?.provider??"openai",this._model=e.model??t?.model??O,this._name=e.name??"agent",this._instructions=e.instructions??"";let s=e.providerOptions?.apiKey??C(this._provider);this.providerHandle=(0,p.create_provider)(this._provider,this._model,{apiKey:s,...e.providerOptions}),e.tools&&(this._tools=[...e.tools]);let n=e.codeExecution,i=n===!0?{python:!0,javascript:!0,bash:!0}:n||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}async run(e){this.assertNotDisposed();let t=typeof e=="string"?[{role:"user",content:e}]:e;return _e(await(0,p.agent_run)(this._name,this.providerHandle,this._tools,t,this._options))}async runWithTools(e,t){this.assertNotDisposed();let s=typeof e=="string"?[{role:"user",content:e}]:e;return _e(await(0,p.agent_run_with_tool_executor)(this._name,this.providerHandle,this._tools,s,this._options,t))}async stream(e,t,s){this.assertNotDisposed();let n=typeof e=="string"?[{role:"user",content:e}]:e;return _e(await(0,p.agent_stream_with_tool_executor)(this._name,this.providerHandle,this._tools,n,this._options,t,s??He))}streamIter(e,t){this.assertNotDisposed();let s=typeof e=="string"?[{role:"user",content:e}]:e;return new H(this._name,this.providerHandle,this._tools,s,this._options,t??He)}async generate(e,t){this.assertNotDisposed();let s=typeof e=="string"?[{role:"user",content:e}]:e;return(0,p.generate)(this.providerHandle,s,t?.temperature,t?.maxTokens)}async generateWithTools(e,t,s){this.assertNotDisposed();let n=typeof e=="string"?[{role:"user",content:e}]:e;return(0,p.generate_with_tools)(this.providerHandle,n,t,s?.temperature,s?.maxTokens)}destroy(){if(!this.disposed){this.disposed=!0;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`)}},He=async()=>"{}";async function je(r,e){let t=new M({name:"gauss",...e});try{return(await t.run(r)).text}finally{t.destroy()}}function xe(r={}){let e=r.providerOptions?.maxRetries??r.retries??5;return new M({...r,name:r.name??"enterprise-agent",maxSteps:r.maxSteps??20,temperature:r.temperature??.2,cacheControl:r.cacheControl??!0,reasoningEffort:r.reasoningEffort??"medium",providerOptions:{...r.providerOptions,maxRetries:e}})}async function Ue(r,e){let t=xe(e);try{return(await t.run(r)).text}finally{t.destroy()}}async function Ge(r,e){let{concurrency:t=5,...s}=e??{},n=r.map(o=>({input:o})),i=new M({name:"batch",...s});try{let o=[...n.entries()],a=Array.from({length:Math.min(t,o.length)},async()=>{for(;o.length>0;){let u=o.shift();if(!u)break;let[d,c]=u;try{n[d].result=await i.run(c.input)}catch(m){n[d].error=m instanceof Error?m:new Error(String(m))}}});await Promise.all(a)}finally{i.destroy()}return n}var T=require("gauss-napi");var ve=require("gauss-napi");async function Je(r,e,t){return(0,T.execute_code)(r,e,t?.timeoutSecs,t?.workingDir,t?.sandbox)}async function Le(){return(0,T.available_runtimes)()}async function Fe(r,e={}){let t=I(),s=e.provider??t?.provider??"openai",n=e.model??t?.model??"dall-e-3",i=e.providerOptions?.apiKey??C(s),o=(0,T.create_provider)(s,n,{apiKey:i,...e.providerOptions});try{return await(0,T.generate_image)(o,r,e.model,e.size,e.quality,e.style,e.aspectRatio,e.n,e.responseFormat)}finally{(0,T.destroy_provider)(o)}}var Ke=require("crypto"),g=require("gauss-napi"),F=class{_handle;disposed=!1;constructor(){this._handle=(0,g.create_memory)()}get handle(){return this._handle}async store(e,t,s){this.assertNotDisposed();let n=typeof e=="string"?{id:(0,Ke.randomUUID)(),content:t,entryType:e||"conversation",timestamp:new Date().toISOString(),sessionId:s}:e,i={id:n.id,content:n.content,entry_type:n.entryType,timestamp:n.timestamp,tier:n.tier,metadata:n.metadata,importance:n.importance,session_id:n.sessionId,embedding:n.embedding};return(0,g.memory_store)(this._handle,JSON.stringify(i))}async recall(e){this.assertNotDisposed();let t=e?JSON.stringify(e):void 0;return(0,g.memory_recall)(this._handle,t)}async clear(e){return this.assertNotDisposed(),(0,g.memory_clear)(this._handle,e)}async stats(){return this.assertNotDisposed(),(0,g.memory_stats)(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,g.destroy_memory)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Memory has been destroyed")}};var k=require("gauss-napi"),K=class{_handle;disposed=!1;constructor(e){this._handle=(0,k.create_vector_store)()}get handle(){return this._handle}async upsert(e){this.assertNotDisposed();let t=e.map(s=>({id:s.id,document_id:s.documentId,content:s.content,index:s.index,metadata:s.metadata??{},embedding:s.embedding}));return(0,k.vector_store_upsert)(this._handle,JSON.stringify(t))}async search(e,t){return this.assertNotDisposed(),(0,k.vector_store_search)(this._handle,JSON.stringify(e),t)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,k.destroy_vector_store)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("VectorStore has been destroyed")}static cosineSimilarity(e,t){return(0,k.cosine_similarity)(e,t)}};var h=require("gauss-napi"),Y=class{_handle;disposed=!1;constructor(){this._handle=(0,h.create_graph)()}get handle(){return this._handle}addNode(e){return this.assertNotDisposed(),(0,h.graph_add_node)(this._handle,e.nodeId,e.agent.name,e.agent.handle,e.instructions,e.tools??[]),this}addFork(e){return this.assertNotDisposed(),(0,h.graph_add_fork_node)(this._handle,e.nodeId,e.agents.map(t=>({agentName:t.agent.name,providerHandle:t.agent.handle,instructions:t.instructions})),e.consensus??"concat"),this}addEdge(e,t){return this.assertNotDisposed(),(0,h.graph_add_edge)(this._handle,e,t),this}async run(e){return this.assertNotDisposed(),(0,h.graph_run)(this._handle,e)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,h.destroy_graph)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Graph has been destroyed")}};var S=require("gauss-napi"),B=class{_handle;disposed=!1;constructor(){this._handle=(0,S.create_workflow)()}get handle(){return this._handle}addStep(e){return this.assertNotDisposed(),(0,S.workflow_add_step)(this._handle,e.stepId,e.agent.name,e.agent.handle,e.instructions,e.tools??[]),this}addDependency(e,t){return this.assertNotDisposed(),(0,S.workflow_add_dependency)(this._handle,e,t),this}async run(e){return this.assertNotDisposed(),(0,S.workflow_run)(this._handle,e)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,S.destroy_workflow)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Workflow has been destroyed")}};var E=require("gauss-napi"),z=class{_handle;disposed=!1;agents=[];constructor(e){this._handle=(0,E.create_team)(e)}get handle(){return this._handle}add(e,t){return this.assertNotDisposed(),(0,E.team_add_agent)(this._handle,e.name,e.handle,t),this.agents.push(e),this}strategy(e){return this.assertNotDisposed(),(0,E.team_set_strategy)(this._handle,e),this}async run(e){this.assertNotDisposed();let t=JSON.stringify([{role:"user",content:[{type:"text",text:e}]}]);return(0,E.team_run)(this._handle,t)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,E.destroy_team)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Team has been destroyed")}};var y=require("gauss-napi"),q=class{_handle;disposed=!1;constructor(){this._handle=(0,y.create_network)()}get handle(){return this._handle}addAgent(e,t){return this.assertNotDisposed(),(0,y.network_add_agent)(this._handle,e.name,e.handle,t),this}setSupervisor(e){return this.assertNotDisposed(),(0,y.network_set_supervisor)(this._handle,e),this}async delegate(e,t,s){return this.assertNotDisposed(),(0,y.network_delegate)(this._handle,e,t,s)}agentCards(){return this.assertNotDisposed(),(0,y.network_agent_cards)(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,y.destroy_network)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Network has been destroyed")}};var A=require("gauss-napi"),V=class{_handle;disposed=!1;constructor(){this._handle=(0,A.create_middleware_chain)()}get handle(){return this._handle}useLogging(){return this.assertNotDisposed(),(0,A.middleware_use_logging)(this._handle),this}useCaching(e){return this.assertNotDisposed(),(0,A.middleware_use_caching)(this._handle,e),this}useRateLimit(e,t){return this.assertNotDisposed(),(0,A.middleware_use_rate_limit)(this._handle,e,t),this}destroy(){if(!this.disposed){this.disposed=!0;try{(0,A.destroy_middleware_chain)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("MiddlewareChain has been destroyed")}};var f=require("gauss-napi"),W=class{_handle;disposed=!1;constructor(){this._handle=(0,f.create_plugin_registry)()}get handle(){return this._handle}addTelemetry(){return this.assertNotDisposed(),(0,f.plugin_registry_add_telemetry)(this._handle),this}addMemory(){return this.assertNotDisposed(),(0,f.plugin_registry_add_memory)(this._handle),this}list(){return this.assertNotDisposed(),(0,f.plugin_registry_list)(this._handle)}emit(e){this.assertNotDisposed(),(0,f.plugin_registry_emit)(this._handle,JSON.stringify(e))}destroy(){if(!this.disposed){this.disposed=!0;try{(0,f.destroy_plugin_registry)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("PluginRegistry has been destroyed")}};var _=require("gauss-napi"),$=class{_handle;disposed=!1;constructor(e,t){this._handle=(0,_.create_mcp_server)(e,t)}get handle(){return this._handle}addTool(e){return this.assertNotDisposed(),(0,_.mcp_server_add_tool)(this._handle,JSON.stringify(e)),this}addResource(e){return this.assertNotDisposed(),(0,_.mcpServerAddResource)(this._handle,JSON.stringify(e)),this}addPrompt(e){return this.assertNotDisposed(),(0,_.mcpServerAddPrompt)(this._handle,JSON.stringify(e)),this}async handleMessage(e){return this.assertNotDisposed(),(0,_.mcp_server_handle)(this._handle,JSON.stringify(e))}destroy(){if(!this.disposed){this.disposed=!0;try{(0,_.destroy_mcp_server)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("McpServer has been destroyed")}};var l=require("gauss-napi"),X=class{_handle;disposed=!1;constructor(){this._handle=(0,l.create_guardrail_chain)()}get handle(){return this._handle}addContentModeration(e,t=[]){return this.assertNotDisposed(),(0,l.guardrail_chain_add_content_moderation)(this._handle,e,t),this}addPiiDetection(e){return this.assertNotDisposed(),(0,l.guardrail_chain_add_pii_detection)(this._handle,e),this}addTokenLimit(e,t){return this.assertNotDisposed(),(0,l.guardrail_chain_add_token_limit)(this._handle,e,t),this}addRegexFilter(e,t=[]){return this.assertNotDisposed(),(0,l.guardrail_chain_add_regex_filter)(this._handle,e,t),this}addSchema(e){return this.assertNotDisposed(),(0,l.guardrail_chain_add_schema)(this._handle,JSON.stringify(e)),this}list(){return this.assertNotDisposed(),(0,l.guardrail_chain_list)(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,l.destroy_guardrail_chain)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("GuardrailChain has been destroyed")}};var x=require("gauss-napi"),Q=class{_handle;disposed=!1;constructor(){this._handle=(0,x.create_approval_manager)()}get handle(){return this._handle}request(e,t,s){return this.assertNotDisposed(),(0,x.approval_request)(this._handle,e,JSON.stringify(t),s)}approve(e,t){this.assertNotDisposed(),(0,x.approval_approve)(this._handle,e,t?JSON.stringify(t):void 0)}deny(e,t){this.assertNotDisposed(),(0,x.approval_deny)(this._handle,e,t)}listPending(){return this.assertNotDisposed(),(0,x.approval_list_pending)(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,x.destroy_approval_manager)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("ApprovalManager has been destroyed")}};var P=require("gauss-napi"),Z=class{_handle;disposed=!1;constructor(){this._handle=(0,P.create_checkpoint_store)()}get handle(){return this._handle}async save(e){return this.assertNotDisposed(),(0,P.checkpoint_save)(this._handle,JSON.stringify(e))}async load(e){return this.assertNotDisposed(),(0,P.checkpoint_load)(this._handle,e)}async loadLatest(e){return this.assertNotDisposed(),(0,P.checkpoint_load_latest)(this._handle,e)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,P.destroy_checkpoint_store)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("CheckpointStore has been destroyed")}};var R=require("gauss-napi"),ee=class{_handle;disposed=!1;constructor(e){this._handle=(0,R.create_eval_runner)(e)}get handle(){return this._handle}addScorer(e){return this.assertNotDisposed(),(0,R.eval_add_scorer)(this._handle,e),this}destroy(){if(!this.disposed){this.disposed=!0;try{(0,R.destroy_eval_runner)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("EvalRunner has been destroyed")}static loadDatasetJsonl(e){return(0,R.load_dataset_jsonl)(e)}static loadDatasetJson(e){return(0,R.load_dataset_json)(e)}};var v=require("gauss-napi"),te=class{_handle;disposed=!1;constructor(){this._handle=(0,v.create_telemetry)()}get handle(){return this._handle}recordSpan(e,t,s){this.assertNotDisposed();let n=typeof e=="string"?{name:e,span_type:"custom",start_ms:Date.now()-(t??0),duration_ms:t??0,attributes:s??{},status:"ok",children:[]}:e;(0,v.telemetry_record_span)(this._handle,JSON.stringify(n))}exportSpans(){return this.assertNotDisposed(),(0,v.telemetry_export_spans)(this._handle)}exportMetrics(){return this.assertNotDisposed(),(0,v.telemetry_export_metrics)(this._handle)}clear(){this.assertNotDisposed(),(0,v.telemetry_clear)(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,v.destroy_telemetry)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Telemetry has been destroyed")}};var j=require("gauss-napi");function Ye(r){return(0,j.create_fallback_provider)(r)}function Be(r,e,t){return(0,j.create_circuit_breaker)(r,e,t)}function be(r,e,t){return(0,j.create_resilient_provider)(r,e,t)}function ze(r,e,t=!0){return be(r.handle,e.map(s=>s.handle),t)}var w=require("gauss-napi");function qe(r){return(0,w.count_tokens)(r)}function Ve(r,e){return(0,w.count_tokens_for_model)(r,e)}function We(r){return(0,w.count_message_tokens)(r)}function $e(r){return(0,w.get_context_window_size)(r)}function Xe(r,e){let t=(0,w.estimate_cost)(r,e.inputTokens,e.outputTokens,e.reasoningTokens,e.cacheReadTokens,e.cacheCreationTokens);return{model:String(t.model??r),normalizedModel:String(t.normalized_model??r),currency:String(t.currency??"USD"),inputTokens:Number(t.input_tokens??e.inputTokens),outputTokens:Number(t.output_tokens??e.outputTokens),reasoningTokens:Number(t.reasoning_tokens??e.reasoningTokens??0),cacheReadTokens:Number(t.cache_read_tokens??e.cacheReadTokens??0),cacheCreationTokens:Number(t.cache_creation_tokens??e.cacheCreationTokens??0),inputCostUsd:Number(t.input_cost_usd??0),outputCostUsd:Number(t.output_cost_usd??0),reasoningCostUsd:Number(t.reasoning_cost_usd??0),cacheReadCostUsd:Number(t.cache_read_cost_usd??0),cacheCreationCostUsd:Number(t.cache_creation_cost_usd??0),totalCostUsd:Number(t.total_cost_usd??0)}}var re=require("gauss-napi");function Qe(r){return(0,re.agent_config_from_json)(r)}function Ze(r){return(0,re.agent_config_resolve_env)(r)}var U=require("gauss-napi"),se=class{_handle;disposed=!1;constructor(e){this._handle=(0,U.create_tool_validator)(e)}get handle(){return this._handle}validate(e,t){return this.assertNotDisposed(),JSON.parse((0,U.tool_validator_validate)(this._handle,JSON.stringify(e),JSON.stringify(t)))}destroy(){if(!this.disposed){this.disposed=!0;try{(0,U.destroy_tool_validator)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("ToolValidator has been destroyed")}};var et=require("gauss-napi");function tt(r){return(0,et.parse_partial_json)(r)}function Pt(r,e){let t;switch(r.backoff){case"fixed":t=r.baseDelayMs;break;case"linear":t=r.baseDelayMs*e;break;case"exponential":t=r.baseDelayMs*Math.pow(2,e-1);break}let s=t*r.jitter;return t+=Math.random()*s*2-s,Math.min(Math.max(0,t),r.maxDelayMs)}function Rt(r){return new Promise(e=>setTimeout(e,r))}async function Te(r,e){let t=e?.maxRetries??3,s=e?.backoff??"exponential",n=e?.baseDelayMs??1e3,i=e?.maxDelayMs??3e4,o=e?.jitter??.1,a=e?.retryIf,u=e?.onRetry,d;for(let c=0;c<=t;c++)try{return await r()}catch(m){if(d=m instanceof Error?m:new Error(String(m)),c===t||a&&!a(d,c+1))break;let Ee=Pt({backoff:s,baseDelayMs:n,maxDelayMs:i,jitter:o},c+1);u?.(d,c+1,Ee),await Rt(Ee)}throw d}function rt(r,e){return t=>Te(()=>r.run(t),e)}function wt(r,e){let t=JSON.stringify(e,null,2);return`${r}
|
|
2
|
+
|
|
3
|
+
Respond ONLY with valid JSON matching this schema:
|
|
4
|
+
${t}
|
|
5
|
+
|
|
6
|
+
Do not include any text outside the JSON object.`}function Dt(r){let e=r.match(/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/);if(e)return e[1].trim();let t=r.indexOf("{"),s=r.indexOf("[");if(t===-1&&s===-1)return r.trim();let n=t===-1?s:s===-1?t:Math.min(t,s),o=r[n]==="["?"]":"}",a=0,u=!1,d=!1;for(let c=n;c<r.length;c++){let m=r[c];if(d){d=!1;continue}if(m==="\\"){d=!0;continue}if(m==='"'){u=!u;continue}if(!u&&(m===r[n]&&a++,m===o&&(a--,a===0)))return r.slice(n,c+1)}return r.slice(n)}async function st(r,e,t){let s=t.maxParseRetries??2,n=typeof e=="string"?wt(e,t.schema):e,i;for(let o=0;o<=s;o++){let a=o===0?n:typeof n=="string"?`${n}
|
|
7
|
+
|
|
8
|
+
Previous attempt failed: ${i?.message}. Please output ONLY valid JSON.`:n,u=await r.run(a);try{let d=Dt(u.text);return{data:JSON.parse(d),raw:t.includeRaw?u:void 0}}catch(d){i=d instanceof Error?d:new Error(String(d))}}throw new Error(`Failed to extract structured output after ${s+1} attempts: ${i?.message}`)}var nt=/\{\{(\w+)\}\}/g;function N(r){let e=[...new Set(Array.from(r.matchAll(nt),s=>s[1]))],t=s=>r.replace(nt,(n,i)=>{let o=s[i];if(o===void 0)throw new Error(`Missing template variable: {{${i}}}`);return o});return Object.defineProperty(t,"raw",{value:r,enumerable:!0}),Object.defineProperty(t,"variables",{value:e,enumerable:!0}),t}var ot=N(`Summarize the following {{format}} in {{style}}:
|
|
9
|
+
|
|
10
|
+
{{text}}`),it=N(`Translate the following text to {{language}}:
|
|
11
|
+
|
|
12
|
+
{{text}}`),at=N("Review this {{language}} code for bugs, security issues, and best practices:\n\n```{{language}}\n{{code}}\n```"),dt=N(`Classify the following text into one of these categories: {{categories}}
|
|
13
|
+
|
|
14
|
+
Text: {{text}}
|
|
15
|
+
|
|
16
|
+
Respond with only the category name.`),pt=N(`Extract the following information from the text: {{fields}}
|
|
17
|
+
|
|
18
|
+
Text: {{text}}
|
|
19
|
+
|
|
20
|
+
Respond as JSON.`);var G=require("gauss-napi"),L=class r{name;description;model;provider;instructions;tools;skills;capabilities;environment;metadata;constructor(e){this.name=e.name,this.description=e.description,this.model=e.model??void 0,this.provider=e.provider??void 0,this.instructions=e.instructions??void 0,this.tools=Object.freeze([...e.tools]),this.skills=Object.freeze([...e.skills]),this.capabilities=Object.freeze([...e.capabilities]),this.environment=new Map(e.environment),this.metadata=Object.freeze({...e.metadata})}static fromMarkdown(e){let t=(0,G.parseAgentsMd)(e),s=typeof t=="string"?JSON.parse(t):t;return new r(s)}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}}}},ne=class r{name;description;steps;inputs;outputs;constructor(e){this.name=e.name,this.description=e.description,this.steps=Object.freeze([...e.steps]),this.inputs=Object.freeze([...e.inputs]),this.outputs=Object.freeze([...e.outputs])}static fromMarkdown(e){let t=(0,G.parseSkillMd)(e),s=typeof t=="string"?JSON.parse(t):t;return new r(s)}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 lt(r){let e=(0,G.discoverAgents)(r);return(typeof e=="string"?JSON.parse(e):e).map(s=>Object.assign(Object.create(L.prototype),{name:s.name,description:s.description,model:s.model??void 0,provider:s.provider??void 0,instructions:s.instructions??void 0,tools:Object.freeze([...s.tools]),skills:Object.freeze([...s.skills]),capabilities:Object.freeze([...s.capabilities]),environment:new Map(s.environment),metadata:Object.freeze({...s.metadata})}))}async function ct(r,...e){let t=r;for(let s of e)t=await s(t);return t}async function ke(r,e,t){let s=t?.concurrency??r.length,n=new Array(r.length),i=r.map((a,u)=>({item:a,index:u})),o=Array.from({length:Math.min(s,i.length)},async()=>{for(;i.length>0;){let a=i.shift();if(!a)break;n[a.index]=await e(a.item,a.index)}});return await Promise.all(o),n}async function ut(r,e,t){let s=await ke(r,e,t);return r.filter((n,i)=>s[i])}async function mt(r,e,t){let s=t;for(let n=0;n<r.length;n++)s=await e(s,r[n],n);return s}async function gt(r,e){for(let t=0;t<r.length;t++)await e(r[t],t);return r}function ht(...r){return async e=>{let t=e;for(let s of r)t=await s(t);return t}}var D=require("gauss-napi"),oe=class{baseUrl;authToken;constructor(e){typeof e=="string"?this.baseUrl=e:(this.baseUrl=e.baseUrl,this.authToken=e.authToken)}async discover(){return await(0,D.a2aDiscover)(this.baseUrl,this.authToken??void 0)}async sendMessage(e,t){let s=await(0,D.a2aSendMessage)(this.baseUrl,this.authToken??void 0,JSON.stringify(e),t?JSON.stringify(t):void 0);if(s._type==="task"){let{_type:o,...a}=s;return{type:"task",task:a}}let{_type:n,...i}=s;return{type:"message",message:i}}async ask(e){return(0,D.a2aAsk)(this.baseUrl,this.authToken??void 0,e)}async getTask(e,t){return await(0,D.a2aGetTask)(this.baseUrl,this.authToken??void 0,e,t??void 0)}async cancelTask(e){return await(0,D.a2aCancelTask)(this.baseUrl,this.authToken??void 0,e)}};function ie(r,e){return{role:r,parts:[{type:"text",text:e}]}}function yt(r){return ie("user",r)}function ft(r){return ie("agent",r)}function Se(r){return r.parts.filter(e=>e.type==="text"&&e.text).map(e=>e.text).join("")}function _t(r){if(r.status.message)return Se(r.status.message)}var b=require("gauss-napi"),ae=class{_handle;disposed=!1;constructor(){this._handle=(0,b.createToolRegistry)()}get handle(){return this._handle}add(e){return this.assertNotDisposed(),(0,b.toolRegistryAdd)(this._handle,JSON.stringify(e)),this}search(e){return this.assertNotDisposed(),(0,b.toolRegistrySearch)(this._handle,e)}byTag(e){return this.assertNotDisposed(),(0,b.toolRegistryByTag)(this._handle,e)}list(){return this.assertNotDisposed(),(0,b.toolRegistryList)(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{(0,b.destroyToolRegistry)(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("ToolRegistry has been destroyed")}};0&&(module.exports={A2aClient,ANTHROPIC_DEFAULT,ANTHROPIC_FAST,ANTHROPIC_PREMIUM,Agent,AgentSpec,AgentStream,ApprovalManager,CheckpointStore,DEEPSEEK_DEFAULT,DEEPSEEK_REASONING,EvalRunner,FIREWORKS_DEFAULT,GOOGLE_DEFAULT,GOOGLE_IMAGE,GOOGLE_PREMIUM,Graph,GuardrailChain,MISTRAL_DEFAULT,McpServer,Memory,MiddlewareChain,Network,OPENAI_DEFAULT,OPENAI_FAST,OPENAI_IMAGE,OPENAI_REASONING,OPENROUTER_DEFAULT,PERPLEXITY_DEFAULT,PROVIDER_DEFAULTS,PluginRegistry,SkillSpec,TOGETHER_DEFAULT,Team,Telemetry,ToolRegistry,ToolValidator,VectorStore,Workflow,XAI_DEFAULT,agentMessage,availableRuntimes,batch,classify,codeReview,compose,countMessageTokens,countTokens,countTokensForModel,createCircuitBreaker,createFallbackProvider,createResilientAgent,createResilientProvider,defaultModel,detectProvider,discoverAgents,enterprisePreset,enterpriseRun,estimateCost,executeCode,extract,extractText,filterAsync,gauss,generateImage,getContextWindowSize,mapAsync,parseAgentConfig,parsePartialJson,pipe,reduceAsync,resolveApiKey,resolveEnv,retryable,structured,summarize,tapAsync,taskText,template,textMessage,translate,userMessage,version,withRetry});
|
|
21
|
+
//# sourceMappingURL=index.cjs.map
|