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.
Files changed (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +499 -0
  3. package/dist/agent-CHrSUkPz.d.ts +485 -0
  4. package/dist/agent-CMp1wFzs.d.cts +485 -0
  5. package/dist/agent.cjs +2 -0
  6. package/dist/agent.cjs.map +1 -0
  7. package/dist/agent.d.cts +144 -0
  8. package/dist/agent.d.ts +144 -0
  9. package/dist/agent.js +2 -0
  10. package/dist/agent.js.map +1 -0
  11. package/dist/index.cjs +21 -0
  12. package/dist/index.cjs.map +1 -0
  13. package/dist/index.d.cts +492 -0
  14. package/dist/index.d.ts +492 -0
  15. package/dist/index.js +21 -0
  16. package/dist/index.js.map +1 -0
  17. package/dist/mcp.cjs +2 -0
  18. package/dist/mcp.cjs.map +1 -0
  19. package/dist/mcp.d.cts +282 -0
  20. package/dist/mcp.d.ts +282 -0
  21. package/dist/mcp.js +2 -0
  22. package/dist/mcp.js.map +1 -0
  23. package/dist/middleware.cjs +2 -0
  24. package/dist/middleware.cjs.map +1 -0
  25. package/dist/middleware.d.cts +46 -0
  26. package/dist/middleware.d.ts +46 -0
  27. package/dist/middleware.js +2 -0
  28. package/dist/middleware.js.map +1 -0
  29. package/dist/orchestration.cjs +2 -0
  30. package/dist/orchestration.cjs.map +1 -0
  31. package/dist/orchestration.d.cts +94 -0
  32. package/dist/orchestration.d.ts +94 -0
  33. package/dist/orchestration.js +2 -0
  34. package/dist/orchestration.js.map +1 -0
  35. package/dist/rag.cjs +2 -0
  36. package/dist/rag.cjs.map +1 -0
  37. package/dist/rag.d.cts +43 -0
  38. package/dist/rag.d.ts +43 -0
  39. package/dist/rag.js +2 -0
  40. package/dist/rag.js.map +1 -0
  41. package/dist/tools.cjs +2 -0
  42. package/dist/tools.cjs.map +1 -0
  43. package/dist/tools.d.cts +48 -0
  44. package/dist/tools.d.ts +48 -0
  45. package/dist/tools.js +2 -0
  46. package/dist/tools.js.map +1 -0
  47. package/dist/types-BkwC4s1P.d.cts +239 -0
  48. package/dist/types-BkwC4s1P.d.ts +239 -0
  49. package/package.json +132 -0
@@ -0,0 +1,492 @@
1
+ import { D as Disposable, H as Handle, E as EvalScorerType, J as JsMessage, e as CostEstimate, M as Message, b as AgentResult } from './types-BkwC4s1P.js';
2
+ export { A as AgentOptions, f as Citation, C as CodeExecutionOptions, g as CodeExecutionResult, h as CoercionStrategy, G as GeneratedImageData, i as GroundingChunk, j as GroundingMetadata, I as ImageGenerationConfig, k as ImageGenerationResult, l as MemoryEntry, m as MemoryStats, n as MessageRole, o as PiiAction, d as ProviderCapabilities, c as ProviderOptions, P as ProviderType, R as RecallOptions, p as SearchResult, S as StreamCallback, T as ToolDef, a as ToolExecutor, V as VectorChunk, q as detectProvider, r as resolveApiKey } from './types-BkwC4s1P.js';
3
+ import { A as AgentConfig, a as Agent } from './agent-CHrSUkPz.js';
4
+ export { b as AgentStream, S as StreamEvent, g as gauss } from './agent-CHrSUkPz.js';
5
+ export { BatchItem, availableRuntimes, batch, executeCode, generateImage } from './agent.js';
6
+ export { Memory, VectorStore } from './rag.js';
7
+ export { ConsensusStrategy, ForkNodeConfig, Graph, GraphNodeConfig, Network, Team, TeamResult, TeamStrategy, Workflow, WorkflowStepConfig } from './orchestration.js';
8
+ export { GuardrailChain, MiddlewareChain, PluginRegistry } from './middleware.js';
9
+ export { A2aClient, A2aClientOptions, A2aMessage, A2aMessageRole, AgentCapabilities, AgentCard, AgentSkill, Artifact, McpContent, McpModelHint, McpModelPreferences, McpPrompt, McpPromptArgument, McpPromptMessage, McpPromptResult, McpResource, McpResourceContent, McpSamplingMessage, McpSamplingRequest, McpSamplingResponse, McpServer, MessageSendConfig, Part, SendMessageResult, Task, TaskState, TaskStatus, agentMessage, extractText, taskText, textMessage, userMessage } from './mcp.js';
10
+ export { ToolExample, ToolRegistry, ToolRegistryEntry, ToolSearchResult, ToolValidator } from './tools.js';
11
+ export { version } from 'gauss-napi';
12
+
13
+ /**
14
+ * Model Constants — Single Source of Truth
15
+ *
16
+ * Update these when new model versions are released.
17
+ * All examples, tests, and defaults reference this file.
18
+ */
19
+ declare const OPENAI_DEFAULT = "gpt-5.2";
20
+ declare const OPENAI_FAST = "gpt-4.1";
21
+ declare const OPENAI_REASONING = "o4-mini";
22
+ declare const OPENAI_IMAGE = "gpt-image-1";
23
+ declare const ANTHROPIC_DEFAULT = "claude-sonnet-4-20250514";
24
+ declare const ANTHROPIC_FAST = "claude-haiku-4-20250414";
25
+ declare const ANTHROPIC_PREMIUM = "claude-opus-4-20250414";
26
+ declare const GOOGLE_DEFAULT = "gemini-2.5-flash";
27
+ declare const GOOGLE_PREMIUM = "gemini-2.5-pro";
28
+ declare const GOOGLE_IMAGE = "gemini-2.0-flash";
29
+ declare const OPENROUTER_DEFAULT = "openai/gpt-5.2";
30
+ declare const DEEPSEEK_DEFAULT = "deepseek-chat";
31
+ declare const DEEPSEEK_REASONING = "deepseek-reasoner";
32
+ declare const TOGETHER_DEFAULT = "meta-llama/Llama-3.3-70B-Instruct-Turbo";
33
+ declare const FIREWORKS_DEFAULT = "accounts/fireworks/models/llama-v3p1-70b-instruct";
34
+ declare const MISTRAL_DEFAULT = "mistral-large-latest";
35
+ declare const PERPLEXITY_DEFAULT = "sonar-pro";
36
+ declare const XAI_DEFAULT = "grok-3-beta";
37
+ declare const PROVIDER_DEFAULTS: Record<string, string>;
38
+ /** Get the default model for a provider */
39
+ declare function defaultModel(provider: string): string;
40
+
41
+ interface EnterprisePresetOptions extends AgentConfig {
42
+ retries?: number;
43
+ }
44
+ /**
45
+ * Plug-and-play enterprise preset with production-safe defaults.
46
+ */
47
+ declare function enterprisePreset(config?: EnterprisePresetOptions): Agent;
48
+ /**
49
+ * One-liner enterprise run helper.
50
+ */
51
+ declare function enterpriseRun(prompt: string, config?: EnterprisePresetOptions): Promise<string>;
52
+
53
+ declare class ApprovalManager implements Disposable {
54
+ private readonly _handle;
55
+ private disposed;
56
+ constructor();
57
+ get handle(): Handle;
58
+ request(toolName: string, args: Record<string, unknown>, sessionId: string): string;
59
+ approve(requestId: string, modifiedArgs?: Record<string, unknown>): void;
60
+ deny(requestId: string, reason?: string): void;
61
+ listPending(): unknown;
62
+ destroy(): void;
63
+ [Symbol.dispose](): void;
64
+ private assertNotDisposed;
65
+ }
66
+
67
+ declare class CheckpointStore implements Disposable {
68
+ private readonly _handle;
69
+ private disposed;
70
+ constructor();
71
+ get handle(): Handle;
72
+ save(checkpoint: Record<string, unknown>): Promise<void>;
73
+ load(checkpointId: string): Promise<unknown>;
74
+ loadLatest(sessionId: string): Promise<unknown>;
75
+ destroy(): void;
76
+ [Symbol.dispose](): void;
77
+ private assertNotDisposed;
78
+ }
79
+
80
+ declare class EvalRunner implements Disposable {
81
+ private readonly _handle;
82
+ private disposed;
83
+ constructor(threshold?: number);
84
+ get handle(): Handle;
85
+ addScorer(scorerType: EvalScorerType): this;
86
+ destroy(): void;
87
+ [Symbol.dispose](): void;
88
+ private assertNotDisposed;
89
+ static loadDatasetJsonl(jsonl: string): unknown;
90
+ static loadDatasetJson(jsonStr: string): unknown;
91
+ }
92
+
93
+ declare class Telemetry implements Disposable {
94
+ private readonly _handle;
95
+ private disposed;
96
+ constructor();
97
+ get handle(): Handle;
98
+ /** Record a span. Pass a SpanRecord object or use the convenience overload. */
99
+ recordSpan(span: Record<string, unknown>): void;
100
+ recordSpan(name: string, durationMs: number, attributes?: Record<string, unknown>): void;
101
+ exportSpans(): unknown;
102
+ exportMetrics(): unknown;
103
+ clear(): void;
104
+ destroy(): void;
105
+ [Symbol.dispose](): void;
106
+ private assertNotDisposed;
107
+ }
108
+
109
+ /**
110
+ * Create a fallback provider that tries providers in order.
111
+ * Returns a provider handle usable with Agent constructor.
112
+ */
113
+ declare function createFallbackProvider(providerHandles: Handle[]): Handle;
114
+ /**
115
+ * Wrap a provider with a circuit breaker.
116
+ * Returns a provider handle usable with Agent constructor.
117
+ */
118
+ declare function createCircuitBreaker(providerHandle: Handle, failureThreshold?: number, recoveryTimeoutMs?: number): Handle;
119
+ /**
120
+ * Create a resilient provider with retry, circuit breaker, and fallbacks.
121
+ * Returns a provider handle usable with Agent constructor.
122
+ */
123
+ declare function createResilientProvider(primaryHandle: Handle, fallbackHandles: Handle[], enableCircuitBreaker?: boolean): Handle;
124
+ /**
125
+ * Convenience: create a resilient agent by wrapping its provider.
126
+ */
127
+ declare function createResilientAgent(primary: Agent, fallbacks: Agent[], enableCircuitBreaker?: boolean): Handle;
128
+
129
+ declare function countTokens(text: string): number;
130
+ declare function countTokensForModel(text: string, model: string): number;
131
+ declare function countMessageTokens(messages: JsMessage[]): number;
132
+ declare function getContextWindowSize(model: string): number;
133
+ declare function estimateCost(model: string, usage: {
134
+ inputTokens: number;
135
+ outputTokens: number;
136
+ reasoningTokens?: number;
137
+ cacheReadTokens?: number;
138
+ cacheCreationTokens?: number;
139
+ }): CostEstimate;
140
+
141
+ declare function parseAgentConfig(jsonStr: string): string;
142
+ declare function resolveEnv(value: string): string;
143
+
144
+ declare function parsePartialJson(text: string): string | null;
145
+
146
+ /**
147
+ * Retry utilities — exponential backoff and configurable retry logic.
148
+ *
149
+ * @example
150
+ * import { withRetry, RetryConfig } from "gauss-ts";
151
+ *
152
+ * const result = await withRetry(() => agent.run("Hello"), {
153
+ * maxRetries: 3,
154
+ * backoff: "exponential",
155
+ * });
156
+ *
157
+ * // Or wrap an agent:
158
+ * const resilientRun = retryable(agent, { maxRetries: 5 });
159
+ * const result = await resilientRun("Hello");
160
+ */
161
+
162
+ interface RetryConfig {
163
+ /** Maximum number of retry attempts (default: 3). */
164
+ maxRetries?: number;
165
+ /** Backoff strategy (default: "exponential"). */
166
+ backoff?: "fixed" | "linear" | "exponential";
167
+ /** Base delay in ms (default: 1000). */
168
+ baseDelayMs?: number;
169
+ /** Maximum delay in ms (default: 30000). */
170
+ maxDelayMs?: number;
171
+ /** Jitter factor 0–1 (default: 0.1). Adds randomness to prevent thundering herd. */
172
+ jitter?: number;
173
+ /** Optional predicate — retry only if this returns true for the error. */
174
+ retryIf?: (error: Error, attempt: number) => boolean;
175
+ /** Called on each retry attempt, useful for logging. */
176
+ onRetry?: (error: Error, attempt: number, delayMs: number) => void;
177
+ }
178
+ /**
179
+ * Execute an async function with retry logic.
180
+ *
181
+ * @example
182
+ * const data = await withRetry(async () => {
183
+ * return await agent.run("Summarize this article");
184
+ * }, { maxRetries: 3, backoff: "exponential" });
185
+ */
186
+ declare function withRetry<T>(fn: () => Promise<T>, config?: RetryConfig): Promise<T>;
187
+ /**
188
+ * Wrap an agent's run method with retry logic. Returns a function
189
+ * that accepts a prompt and returns an AgentResult.
190
+ *
191
+ * @example
192
+ * const run = retryable(agent, { maxRetries: 5 });
193
+ * const result = await run("Hello");
194
+ */
195
+ declare function retryable(agent: Agent, config?: RetryConfig): (prompt: string | Message[]) => Promise<AgentResult>;
196
+
197
+ /**
198
+ * Structured Output — validate and extract typed JSON from LLM responses.
199
+ *
200
+ * @example
201
+ * import { structured, zodSchema } from "gauss-ts";
202
+ *
203
+ * const result = await structured(agent, "List 3 fruits", {
204
+ * schema: { type: "object", properties: { fruits: { type: "array", items: { type: "string" } } } },
205
+ * });
206
+ * console.log(result.data.fruits); // ["apple", "banana", "cherry"]
207
+ */
208
+
209
+ /** JSON Schema subset for structured output. */
210
+ interface JsonSchema {
211
+ type: string;
212
+ properties?: Record<string, JsonSchema>;
213
+ items?: JsonSchema;
214
+ required?: string[];
215
+ enum?: unknown[];
216
+ description?: string;
217
+ [key: string]: unknown;
218
+ }
219
+ interface StructuredConfig {
220
+ /** JSON schema the output must conform to. */
221
+ schema: JsonSchema;
222
+ /** Maximum parse retries if the model returns invalid JSON (default: 2). */
223
+ maxParseRetries?: number;
224
+ /** If true, include the raw AgentResult alongside parsed data. */
225
+ includeRaw?: boolean;
226
+ }
227
+ interface StructuredResult<T = unknown> {
228
+ /** Parsed and validated data. */
229
+ data: T;
230
+ /** Raw agent result (only if includeRaw was true). */
231
+ raw?: AgentResult;
232
+ }
233
+ /**
234
+ * Run an agent with structured output extraction.
235
+ *
236
+ * Automatically instructs the model to output JSON matching the schema,
237
+ * extracts and parses the JSON from the response, and retries on parse failure.
238
+ *
239
+ * @example
240
+ * const { data } = await structured(agent, "List 3 programming languages", {
241
+ * schema: {
242
+ * type: "object",
243
+ * properties: {
244
+ * languages: { type: "array", items: { type: "string" } }
245
+ * },
246
+ * required: ["languages"]
247
+ * }
248
+ * });
249
+ * console.log(data.languages);
250
+ */
251
+ declare function structured<T = unknown>(agent: Agent, prompt: string | Message[], config: StructuredConfig): Promise<StructuredResult<T>>;
252
+
253
+ /**
254
+ * Prompt Templates — composable, type-safe prompt construction.
255
+ *
256
+ * @example
257
+ * import { template, PromptTemplate } from "gauss-ts";
258
+ *
259
+ * const summarize = template("Summarize the following {{format}}:\n\n{{text}}");
260
+ * const prompt = summarize({ format: "article", text: "Lorem ipsum..." });
261
+ *
262
+ * // Composition:
263
+ * const withTone = template("{{base}}\n\nUse a {{tone}} tone.");
264
+ * const prompt = withTone({
265
+ * base: summarize({ format: "article", text: "..." }),
266
+ * tone: "professional",
267
+ * });
268
+ */
269
+ /** Extract variable names from a template string. */
270
+ type ExtractVars<T extends string> = T extends `${string}{{${infer Var}}}${infer Rest}` ? Var | ExtractVars<Rest> : never;
271
+ /** Variables object for a template. */
272
+ type TemplateVars<T extends string> = Record<ExtractVars<T>, string>;
273
+ /** A compiled prompt template function. */
274
+ interface PromptTemplate<T extends string = string> {
275
+ /** Render the template with variables. */
276
+ (vars: TemplateVars<T>): string;
277
+ /** The raw template string. */
278
+ readonly raw: string;
279
+ /** List of variable names in the template. */
280
+ readonly variables: string[];
281
+ }
282
+ /**
283
+ * Create a reusable prompt template with `{{variable}}` placeholders.
284
+ *
285
+ * @example
286
+ * const t = template("Hello {{name}}, you are {{age}} years old.");
287
+ * t({ name: "Alice", age: "30" }); // "Hello Alice, you are 30 years old."
288
+ * t.variables; // ["name", "age"]
289
+ */
290
+ declare function template<T extends string>(templateStr: T): PromptTemplate<T>;
291
+ /** Summarization template. */
292
+ declare const summarize: PromptTemplate<"Summarize the following {{format}} in {{style}}:\n\n{{text}}">;
293
+ /** Translation template. */
294
+ declare const translate: PromptTemplate<"Translate the following text to {{language}}:\n\n{{text}}">;
295
+ /** Code review template. */
296
+ declare const codeReview: PromptTemplate<"Review this {{language}} code for bugs, security issues, and best practices:\n\n```{{language}}\n{{code}}\n```">;
297
+ /** Classification template. */
298
+ declare const classify: PromptTemplate<"Classify the following text into one of these categories: {{categories}}\n\nText: {{text}}\n\nRespond with only the category name.">;
299
+ /** Extraction template. */
300
+ declare const extract: PromptTemplate<"Extract the following information from the text: {{fields}}\n\nText: {{text}}\n\nRespond as JSON.">;
301
+
302
+ /**
303
+ * AGENTS.MD and SKILL.MD parsers — parse agent/skill specifications from markdown.
304
+ *
305
+ * @example
306
+ * ```ts
307
+ * import { AgentSpec, SkillSpec, discoverAgents } from "gauss-ts";
308
+ *
309
+ * // Parse a single AGENTS.MD
310
+ * const spec = AgentSpec.fromMarkdown(content);
311
+ * console.log(spec.name, spec.tools);
312
+ *
313
+ * // Discover all agents in a directory tree
314
+ * const agents = await discoverAgents("./agents");
315
+ *
316
+ * // Parse a SKILL.MD
317
+ * const skill = SkillSpec.fromMarkdown(skillContent);
318
+ * console.log(skill.steps);
319
+ * ```
320
+ */
321
+ /** Tool reference within an AGENTS.MD spec. */
322
+ interface AgentToolSpec {
323
+ name: string;
324
+ description: string;
325
+ parameters?: Record<string, unknown>;
326
+ }
327
+ /** Parsed agent specification from AGENTS.MD. */
328
+ interface AgentSpecData {
329
+ name: string;
330
+ description: string;
331
+ model?: string;
332
+ provider?: string;
333
+ instructions?: string;
334
+ tools: AgentToolSpec[];
335
+ skills: string[];
336
+ capabilities: string[];
337
+ environment: Array<[string, string]>;
338
+ metadata: Record<string, unknown>;
339
+ }
340
+ /** Step within a SKILL.MD spec. */
341
+ interface SkillStep {
342
+ description: string;
343
+ action?: string;
344
+ }
345
+ /** Input or output parameter in a SKILL.MD spec. */
346
+ interface SkillParam {
347
+ name: string;
348
+ param_type: string;
349
+ description: string;
350
+ required: boolean;
351
+ }
352
+ /** Parsed skill specification from SKILL.MD. */
353
+ interface SkillSpecData {
354
+ name: string;
355
+ description: string;
356
+ steps: SkillStep[];
357
+ inputs: SkillParam[];
358
+ outputs: SkillParam[];
359
+ }
360
+ /** Immutable parsed AGENTS.MD specification with a fluent API. */
361
+ declare class AgentSpec {
362
+ readonly name: string;
363
+ readonly description: string;
364
+ readonly model?: string;
365
+ readonly provider?: string;
366
+ readonly instructions?: string;
367
+ readonly tools: readonly AgentToolSpec[];
368
+ readonly skills: readonly string[];
369
+ readonly capabilities: readonly string[];
370
+ readonly environment: ReadonlyMap<string, string>;
371
+ readonly metadata: Readonly<Record<string, unknown>>;
372
+ private constructor();
373
+ /** Parse an AGENTS.MD markdown string into an AgentSpec. */
374
+ static fromMarkdown(content: string): AgentSpec;
375
+ /** Check whether a specific tool is declared in this spec. */
376
+ hasTool(name: string): boolean;
377
+ /** Check whether a specific capability is declared. */
378
+ hasCapability(name: string): boolean;
379
+ /** Serialize back to a plain object. */
380
+ toJSON(): AgentSpecData;
381
+ }
382
+ /** Immutable parsed SKILL.MD specification with a fluent API. */
383
+ declare class SkillSpec {
384
+ readonly name: string;
385
+ readonly description: string;
386
+ readonly steps: readonly SkillStep[];
387
+ readonly inputs: readonly SkillParam[];
388
+ readonly outputs: readonly SkillParam[];
389
+ private constructor();
390
+ /** Parse a SKILL.MD markdown string into a SkillSpec. */
391
+ static fromMarkdown(content: string): SkillSpec;
392
+ /** Get the total number of steps. */
393
+ get stepCount(): number;
394
+ /** Get all required inputs. */
395
+ get requiredInputs(): readonly SkillParam[];
396
+ /** Serialize back to a plain object. */
397
+ toJSON(): SkillSpecData;
398
+ }
399
+ /** Discover all AGENTS.MD files in a directory tree and parse them. */
400
+ declare function discoverAgents(dir: string): AgentSpec[];
401
+
402
+ /**
403
+ * Pipeline — compose agent operations into clean data flows.
404
+ *
405
+ * @example
406
+ * import { pipe, map, filter, tap } from "gauss-ts";
407
+ *
408
+ * const result = await pipe(
409
+ * ["apple", "banana", "cherry"],
410
+ * map(fruit => agent.run(`Describe ${fruit}`)),
411
+ * filter(r => r.text.length > 50),
412
+ * tap(r => console.log(r.text)),
413
+ * );
414
+ */
415
+ /** An async transform step in a pipeline. */
416
+ type PipeStep<I, O> = (input: I) => Promise<O> | O;
417
+ /**
418
+ * Compose async operations into a pipeline.
419
+ *
420
+ * @example
421
+ * const result = await pipe(
422
+ * "Hello",
423
+ * (s) => agent.run(s),
424
+ * (r) => r.text.toUpperCase(),
425
+ * );
426
+ */
427
+ declare function pipe<A>(input: A): Promise<A>;
428
+ declare function pipe<A, B>(input: A, s1: PipeStep<A, B>): Promise<B>;
429
+ declare function pipe<A, B, C>(input: A, s1: PipeStep<A, B>, s2: PipeStep<B, C>): Promise<C>;
430
+ declare function pipe<A, B, C, D>(input: A, s1: PipeStep<A, B>, s2: PipeStep<B, C>, s3: PipeStep<C, D>): Promise<D>;
431
+ declare function pipe<A, B, C, D, E>(input: A, s1: PipeStep<A, B>, s2: PipeStep<B, C>, s3: PipeStep<C, D>, s4: PipeStep<D, E>): Promise<E>;
432
+ /**
433
+ * Map an async function over an array with concurrency control.
434
+ *
435
+ * @example
436
+ * const results = await mapAsync(
437
+ * ["a", "b", "c"],
438
+ * (item) => agent.run(item),
439
+ * { concurrency: 2 }
440
+ * );
441
+ */
442
+ declare function mapAsync<T, R>(items: T[], fn: (item: T, index: number) => Promise<R>, options?: {
443
+ concurrency?: number;
444
+ }): Promise<R[]>;
445
+ /**
446
+ * Filter items using an async predicate with concurrency control.
447
+ *
448
+ * @example
449
+ * const valid = await filterAsync(items, async (item) => {
450
+ * const result = await agent.run(`Is "${item}" valid?`);
451
+ * return result.text.includes("yes");
452
+ * });
453
+ */
454
+ declare function filterAsync<T>(items: T[], predicate: (item: T, index: number) => Promise<boolean>, options?: {
455
+ concurrency?: number;
456
+ }): Promise<T[]>;
457
+ /**
458
+ * Reduce items using an async reducer (sequential).
459
+ *
460
+ * @example
461
+ * const summary = await reduceAsync(
462
+ * documents,
463
+ * async (acc, doc) => {
464
+ * const result = await agent.run(`Combine: ${acc}\n\nNew: ${doc}`);
465
+ * return result.text;
466
+ * },
467
+ * ""
468
+ * );
469
+ */
470
+ declare function reduceAsync<T, R>(items: T[], reducer: (accumulator: R, item: T, index: number) => Promise<R>, initial: R): Promise<R>;
471
+ /**
472
+ * Execute a side-effect for each item (sequential). Returns input unchanged.
473
+ * Useful in pipelines for logging or monitoring.
474
+ *
475
+ * @example
476
+ * await tapAsync(results, async (r) => console.log(r.text));
477
+ */
478
+ declare function tapAsync<T>(items: T[], fn: (item: T, index: number) => Promise<void> | void): Promise<T[]>;
479
+ /**
480
+ * Compose multiple middleware-style functions into one.
481
+ *
482
+ * @example
483
+ * const enhance = compose(
484
+ * async (text) => `[System] ${text}`,
485
+ * async (text) => text.trim(),
486
+ * );
487
+ * const result = await enhance(" hello ");
488
+ * // → "[System] hello"
489
+ */
490
+ declare function compose<T>(...fns: PipeStep<T, T>[]): PipeStep<T, T>;
491
+
492
+ export { ANTHROPIC_DEFAULT, ANTHROPIC_FAST, ANTHROPIC_PREMIUM, Agent, AgentConfig, AgentResult, AgentSpec, type AgentSpecData, type AgentToolSpec, ApprovalManager, CheckpointStore, CostEstimate, DEEPSEEK_DEFAULT, DEEPSEEK_REASONING, Disposable, type EnterprisePresetOptions, EvalRunner, EvalScorerType, FIREWORKS_DEFAULT, GOOGLE_DEFAULT, GOOGLE_IMAGE, GOOGLE_PREMIUM, Handle, JsMessage, type JsonSchema, MISTRAL_DEFAULT, Message, OPENAI_DEFAULT, OPENAI_FAST, OPENAI_IMAGE, OPENAI_REASONING, OPENROUTER_DEFAULT, PERPLEXITY_DEFAULT, PROVIDER_DEFAULTS, type PipeStep, type PromptTemplate, type RetryConfig, type SkillParam, SkillSpec, type SkillSpecData, type SkillStep, type StructuredConfig, type StructuredResult, TOGETHER_DEFAULT, Telemetry, XAI_DEFAULT, classify, codeReview, compose, countMessageTokens, countTokens, countTokensForModel, createCircuitBreaker, createFallbackProvider, createResilientAgent, createResilientProvider, defaultModel, discoverAgents, enterprisePreset, enterpriseRun, estimateCost, extract, filterAsync, getContextWindowSize, mapAsync, parseAgentConfig, parsePartialJson, pipe, reduceAsync, resolveEnv, retryable, structured, summarize, tapAsync, template, translate, withRetry };
package/dist/index.js ADDED
@@ -0,0 +1,21 @@
1
+ var g="gpt-5.2",se="gpt-4.1",ne="o4-mini",oe="gpt-image-1",L="claude-sonnet-4-20250514",ie="claude-haiku-4-20250414",ae="claude-opus-4-20250414",F="gemini-2.5-flash",de="gemini-2.5-pro",pe="gemini-2.0-flash",K="openai/gpt-5.2",Y="deepseek-chat",le="deepseek-reasoner",B="meta-llama/Llama-3.3-70B-Instruct-Turbo",z="accounts/fireworks/models/llama-v3p1-70b-instruct",q="mistral-large-latest",V="sonar-pro",W="grok-3-beta",_={openai:g,anthropic:L,google:F,openrouter:K,deepseek:Y,groq:"llama-3.3-70b-versatile",ollama:"llama3.2",together:B,fireworks:z,mistral:q,perplexity:V,xai:W};function ce(r){return _[r]??g}var ue={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 h(r){let e=ue[r]??"";return e?(typeof process<"u"?process.env[e]:"")??"":""}function y(){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:_[t]}}import{create_provider as he,destroy_provider as ye,agent_run as fe,agent_run_with_tool_executor as _e,agent_stream_with_tool_executor as xe,generate as ve,generate_with_tools as be,get_provider_capabilities as Te}from"gauss-napi";import{agent_stream_with_tool_executor as me}from"gauss-napi";function ge(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 f=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=me(this.agentName,this.providerHandle,this.tools,this.messages,this.options,n,this.toolExecutor).then(o=>{this._result=ge(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 v(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 u=class{providerHandle;_name;_provider;_model;_instructions;_tools=[];_options={};disposed=!1;constructor(e={}){let t=y();this._provider=e.provider??t?.provider??"openai",this._model=e.model??t?.model??g,this._name=e.name??"agent",this._instructions=e.instructions??"";let s=e.providerOptions?.apiKey??h(this._provider);this.providerHandle=he(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 Te(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 v(await fe(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 v(await _e(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 v(await xe(this._name,this.providerHandle,this._tools,n,this._options,t,s??$))}streamIter(e,t){this.assertNotDisposed();let s=typeof e=="string"?[{role:"user",content:e}]:e;return new f(this._name,this.providerHandle,this._tools,s,this._options,t??$)}async generate(e,t){this.assertNotDisposed();let s=typeof e=="string"?[{role:"user",content:e}]:e;return ve(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 be(this.providerHandle,n,t,s?.temperature,s?.maxTokens)}destroy(){if(!this.disposed){this.disposed=!0;try{ye(this.providerHandle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error(`Agent "${this._name}" has been destroyed`)}},$=async()=>"{}";async function ke(r,e){let t=new u({name:"gauss",...e});try{return(await t.run(r)).text}finally{t.destroy()}}function X(r={}){let e=r.providerOptions?.maxRetries??r.retries??5;return new u({...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 Se(r,e){let t=X(e);try{return(await t.run(r)).text}finally{t.destroy()}}async function Ee(r,e){let{concurrency:t=5,...s}=e??{},n=r.map(o=>({input:o})),i=new u({name:"batch",...s});try{let o=[...n.entries()],a=Array.from({length:Math.min(t,o.length)},async()=>{for(;o.length>0;){let l=o.shift();if(!l)break;let[d,p]=l;try{n[d].result=await i.run(p.input)}catch(c){n[d].error=c instanceof Error?c:new Error(String(c))}}});await Promise.all(a)}finally{i.destroy()}return n}import{create_provider as Ae,destroy_provider as Pe,execute_code as Re,available_runtimes as we,generate_image as De}from"gauss-napi";import{version as Ce}from"gauss-napi";async function Me(r,e,t){return Re(r,e,t?.timeoutSecs,t?.workingDir,t?.sandbox)}async function Ne(){return we()}async function Oe(r,e={}){let t=y(),s=e.provider??t?.provider??"openai",n=e.model??t?.model??"dall-e-3",i=e.providerOptions?.apiKey??h(s),o=Ae(s,n,{apiKey:i,...e.providerOptions});try{return await De(o,r,e.model,e.size,e.quality,e.style,e.aspectRatio,e.n,e.responseFormat)}finally{Pe(o)}}import{randomUUID as Ie}from"crypto";import{create_memory as He,memory_store as je,memory_recall as Ue,memory_clear as Ge,memory_stats as Je,destroy_memory as Le}from"gauss-napi";var b=class{_handle;disposed=!1;constructor(){this._handle=He()}get handle(){return this._handle}async store(e,t,s){this.assertNotDisposed();let n=typeof e=="string"?{id:Ie(),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 je(this._handle,JSON.stringify(i))}async recall(e){this.assertNotDisposed();let t=e?JSON.stringify(e):void 0;return Ue(this._handle,t)}async clear(e){return this.assertNotDisposed(),Ge(this._handle,e)}async stats(){return this.assertNotDisposed(),Je(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{Le(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Memory has been destroyed")}};import{create_vector_store as Fe,vector_store_upsert as Ke,vector_store_search as Ye,destroy_vector_store as Be,cosine_similarity as ze}from"gauss-napi";var T=class{_handle;disposed=!1;constructor(e){this._handle=Fe()}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 Ke(this._handle,JSON.stringify(t))}async search(e,t){return this.assertNotDisposed(),Ye(this._handle,JSON.stringify(e),t)}destroy(){if(!this.disposed){this.disposed=!0;try{Be(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("VectorStore has been destroyed")}static cosineSimilarity(e,t){return ze(e,t)}};import{create_graph as qe,graph_add_node as Ve,graph_add_edge as We,graph_add_fork_node as $e,graph_run as Xe,destroy_graph as Qe}from"gauss-napi";var k=class{_handle;disposed=!1;constructor(){this._handle=qe()}get handle(){return this._handle}addNode(e){return this.assertNotDisposed(),Ve(this._handle,e.nodeId,e.agent.name,e.agent.handle,e.instructions,e.tools??[]),this}addFork(e){return this.assertNotDisposed(),$e(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(),We(this._handle,e,t),this}async run(e){return this.assertNotDisposed(),Xe(this._handle,e)}destroy(){if(!this.disposed){this.disposed=!0;try{Qe(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Graph has been destroyed")}};import{create_workflow as Ze,workflow_add_step as et,workflow_add_dependency as tt,workflow_run as rt,destroy_workflow as st}from"gauss-napi";var S=class{_handle;disposed=!1;constructor(){this._handle=Ze()}get handle(){return this._handle}addStep(e){return this.assertNotDisposed(),et(this._handle,e.stepId,e.agent.name,e.agent.handle,e.instructions,e.tools??[]),this}addDependency(e,t){return this.assertNotDisposed(),tt(this._handle,e,t),this}async run(e){return this.assertNotDisposed(),rt(this._handle,e)}destroy(){if(!this.disposed){this.disposed=!0;try{st(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Workflow has been destroyed")}};import{create_team as nt,team_add_agent as ot,team_set_strategy as it,team_run as at,destroy_team as dt}from"gauss-napi";var E=class{_handle;disposed=!1;agents=[];constructor(e){this._handle=nt(e)}get handle(){return this._handle}add(e,t){return this.assertNotDisposed(),ot(this._handle,e.name,e.handle,t),this.agents.push(e),this}strategy(e){return this.assertNotDisposed(),it(this._handle,e),this}async run(e){this.assertNotDisposed();let t=JSON.stringify([{role:"user",content:[{type:"text",text:e}]}]);return at(this._handle,t)}destroy(){if(!this.disposed){this.disposed=!0;try{dt(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Team has been destroyed")}};import{create_network as pt,network_add_agent as lt,network_set_supervisor as ct,network_delegate as ut,network_agent_cards as mt,destroy_network as gt}from"gauss-napi";var A=class{_handle;disposed=!1;constructor(){this._handle=pt()}get handle(){return this._handle}addAgent(e,t){return this.assertNotDisposed(),lt(this._handle,e.name,e.handle,t),this}setSupervisor(e){return this.assertNotDisposed(),ct(this._handle,e),this}async delegate(e,t,s){return this.assertNotDisposed(),ut(this._handle,e,t,s)}agentCards(){return this.assertNotDisposed(),mt(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{gt(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Network has been destroyed")}};import{create_middleware_chain as ht,middleware_use_logging as yt,middleware_use_caching as ft,middleware_use_rate_limit as _t,destroy_middleware_chain as xt}from"gauss-napi";var P=class{_handle;disposed=!1;constructor(){this._handle=ht()}get handle(){return this._handle}useLogging(){return this.assertNotDisposed(),yt(this._handle),this}useCaching(e){return this.assertNotDisposed(),ft(this._handle,e),this}useRateLimit(e,t){return this.assertNotDisposed(),_t(this._handle,e,t),this}destroy(){if(!this.disposed){this.disposed=!0;try{xt(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("MiddlewareChain has been destroyed")}};import{create_plugin_registry as vt,plugin_registry_add_telemetry as bt,plugin_registry_add_memory as Tt,plugin_registry_list as kt,plugin_registry_emit as St,destroy_plugin_registry as Et}from"gauss-napi";var R=class{_handle;disposed=!1;constructor(){this._handle=vt()}get handle(){return this._handle}addTelemetry(){return this.assertNotDisposed(),bt(this._handle),this}addMemory(){return this.assertNotDisposed(),Tt(this._handle),this}list(){return this.assertNotDisposed(),kt(this._handle)}emit(e){this.assertNotDisposed(),St(this._handle,JSON.stringify(e))}destroy(){if(!this.disposed){this.disposed=!0;try{Et(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("PluginRegistry has been destroyed")}};import{create_mcp_server as At,mcp_server_add_tool as Pt,mcpServerAddResource as Rt,mcpServerAddPrompt as wt,mcp_server_handle as Dt,destroy_mcp_server as Mt}from"gauss-napi";var w=class{_handle;disposed=!1;constructor(e,t){this._handle=At(e,t)}get handle(){return this._handle}addTool(e){return this.assertNotDisposed(),Pt(this._handle,JSON.stringify(e)),this}addResource(e){return this.assertNotDisposed(),Rt(this._handle,JSON.stringify(e)),this}addPrompt(e){return this.assertNotDisposed(),wt(this._handle,JSON.stringify(e)),this}async handleMessage(e){return this.assertNotDisposed(),Dt(this._handle,JSON.stringify(e))}destroy(){if(!this.disposed){this.disposed=!0;try{Mt(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("McpServer has been destroyed")}};import{create_guardrail_chain as Nt,guardrail_chain_add_content_moderation as Ot,guardrail_chain_add_pii_detection as Ct,guardrail_chain_add_token_limit as It,guardrail_chain_add_regex_filter as Ht,guardrail_chain_add_schema as jt,guardrail_chain_list as Ut,destroy_guardrail_chain as Gt}from"gauss-napi";var D=class{_handle;disposed=!1;constructor(){this._handle=Nt()}get handle(){return this._handle}addContentModeration(e,t=[]){return this.assertNotDisposed(),Ot(this._handle,e,t),this}addPiiDetection(e){return this.assertNotDisposed(),Ct(this._handle,e),this}addTokenLimit(e,t){return this.assertNotDisposed(),It(this._handle,e,t),this}addRegexFilter(e,t=[]){return this.assertNotDisposed(),Ht(this._handle,e,t),this}addSchema(e){return this.assertNotDisposed(),jt(this._handle,JSON.stringify(e)),this}list(){return this.assertNotDisposed(),Ut(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{Gt(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("GuardrailChain has been destroyed")}};import{create_approval_manager as Jt,approval_request as Lt,approval_approve as Ft,approval_deny as Kt,approval_list_pending as Yt,destroy_approval_manager as Bt}from"gauss-napi";var M=class{_handle;disposed=!1;constructor(){this._handle=Jt()}get handle(){return this._handle}request(e,t,s){return this.assertNotDisposed(),Lt(this._handle,e,JSON.stringify(t),s)}approve(e,t){this.assertNotDisposed(),Ft(this._handle,e,t?JSON.stringify(t):void 0)}deny(e,t){this.assertNotDisposed(),Kt(this._handle,e,t)}listPending(){return this.assertNotDisposed(),Yt(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{Bt(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("ApprovalManager has been destroyed")}};import{create_checkpoint_store as zt,checkpoint_save as qt,checkpoint_load as Vt,checkpoint_load_latest as Wt,destroy_checkpoint_store as $t}from"gauss-napi";var N=class{_handle;disposed=!1;constructor(){this._handle=zt()}get handle(){return this._handle}async save(e){return this.assertNotDisposed(),qt(this._handle,JSON.stringify(e))}async load(e){return this.assertNotDisposed(),Vt(this._handle,e)}async loadLatest(e){return this.assertNotDisposed(),Wt(this._handle,e)}destroy(){if(!this.disposed){this.disposed=!0;try{$t(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("CheckpointStore has been destroyed")}};import{create_eval_runner as Xt,eval_add_scorer as Qt,load_dataset_jsonl as Zt,load_dataset_json as er,destroy_eval_runner as tr}from"gauss-napi";var O=class{_handle;disposed=!1;constructor(e){this._handle=Xt(e)}get handle(){return this._handle}addScorer(e){return this.assertNotDisposed(),Qt(this._handle,e),this}destroy(){if(!this.disposed){this.disposed=!0;try{tr(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("EvalRunner has been destroyed")}static loadDatasetJsonl(e){return Zt(e)}static loadDatasetJson(e){return er(e)}};import{create_telemetry as rr,telemetry_record_span as sr,telemetry_export_spans as nr,telemetry_export_metrics as or,telemetry_clear as ir,destroy_telemetry as ar}from"gauss-napi";var C=class{_handle;disposed=!1;constructor(){this._handle=rr()}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;sr(this._handle,JSON.stringify(n))}exportSpans(){return this.assertNotDisposed(),nr(this._handle)}exportMetrics(){return this.assertNotDisposed(),or(this._handle)}clear(){this.assertNotDisposed(),ir(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{ar(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("Telemetry has been destroyed")}};import{create_fallback_provider as dr,create_circuit_breaker as pr,create_resilient_provider as lr}from"gauss-napi";function cr(r){return dr(r)}function ur(r,e,t){return pr(r,e,t)}function Q(r,e,t){return lr(r,e,t)}function mr(r,e,t=!0){return Q(r.handle,e.map(s=>s.handle),t)}import{count_tokens as gr,count_tokens_for_model as hr,count_message_tokens as yr,get_context_window_size as fr,estimate_cost as _r}from"gauss-napi";function xr(r){return gr(r)}function vr(r,e){return hr(r,e)}function br(r){return yr(r)}function Tr(r){return fr(r)}function kr(r,e){let t=_r(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)}}import{agent_config_from_json as Sr,agent_config_resolve_env as Er}from"gauss-napi";function Ar(r){return Sr(r)}function Pr(r){return Er(r)}import{create_tool_validator as Rr,tool_validator_validate as wr,destroy_tool_validator as Dr}from"gauss-napi";var I=class{_handle;disposed=!1;constructor(e){this._handle=Rr(e)}get handle(){return this._handle}validate(e,t){return this.assertNotDisposed(),JSON.parse(wr(this._handle,JSON.stringify(e),JSON.stringify(t)))}destroy(){if(!this.disposed){this.disposed=!0;try{Dr(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("ToolValidator has been destroyed")}};import{parse_partial_json as Mr}from"gauss-napi";function Nr(r){return Mr(r)}function Or(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 Cr(r){return new Promise(e=>setTimeout(e,r))}async function Z(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,l=e?.onRetry,d;for(let p=0;p<=t;p++)try{return await r()}catch(c){if(d=c instanceof Error?c:new Error(String(c)),p===t||a&&!a(d,p+1))break;let J=Or({backoff:s,baseDelayMs:n,maxDelayMs:i,jitter:o},p+1);l?.(d,p+1,J),await Cr(J)}throw d}function Ir(r,e){return t=>Z(()=>r.run(t),e)}function Hr(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 jr(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,l=!1,d=!1;for(let p=n;p<r.length;p++){let c=r[p];if(d){d=!1;continue}if(c==="\\"){d=!0;continue}if(c==='"'){l=!l;continue}if(!l&&(c===r[n]&&a++,c===o&&(a--,a===0)))return r.slice(n,p+1)}return r.slice(n)}async function Ur(r,e,t){let s=t.maxParseRetries??2,n=typeof e=="string"?Hr(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,l=await r.run(a);try{let d=jr(l.text);return{data:JSON.parse(d),raw:t.includeRaw?l: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 ee=/\{\{(\w+)\}\}/g;function m(r){let e=[...new Set(Array.from(r.matchAll(ee),s=>s[1]))],t=s=>r.replace(ee,(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 Gr=m(`Summarize the following {{format}} in {{style}}:
9
+
10
+ {{text}}`),Jr=m(`Translate the following text to {{language}}:
11
+
12
+ {{text}}`),Lr=m("Review this {{language}} code for bugs, security issues, and best practices:\n\n```{{language}}\n{{code}}\n```"),Fr=m(`Classify the following text into one of these categories: {{categories}}
13
+
14
+ Text: {{text}}
15
+
16
+ Respond with only the category name.`),Kr=m(`Extract the following information from the text: {{fields}}
17
+
18
+ Text: {{text}}
19
+
20
+ Respond as JSON.`);import{parseAgentsMd as Yr,discoverAgents as Br,parseSkillMd as zr}from"gauss-napi";var x=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=Yr(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}}}},H=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=zr(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 qr(r){let e=Br(r);return(typeof e=="string"?JSON.parse(e):e).map(s=>Object.assign(Object.create(x.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 Vr(r,...e){let t=r;for(let s of e)t=await s(t);return t}async function te(r,e,t){let s=t?.concurrency??r.length,n=new Array(r.length),i=r.map((a,l)=>({item:a,index:l})),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 Wr(r,e,t){let s=await te(r,e,t);return r.filter((n,i)=>s[i])}async function $r(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 Xr(r,e){for(let t=0;t<r.length;t++)await e(r[t],t);return r}function Qr(...r){return async e=>{let t=e;for(let s of r)t=await s(t);return t}}import{a2aDiscover as Zr,a2aSendMessage as es,a2aAsk as ts,a2aGetTask as rs,a2aCancelTask as ss}from"gauss-napi";var j=class{baseUrl;authToken;constructor(e){typeof e=="string"?this.baseUrl=e:(this.baseUrl=e.baseUrl,this.authToken=e.authToken)}async discover(){return await Zr(this.baseUrl,this.authToken??void 0)}async sendMessage(e,t){let s=await es(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 ts(this.baseUrl,this.authToken??void 0,e)}async getTask(e,t){return await rs(this.baseUrl,this.authToken??void 0,e,t??void 0)}async cancelTask(e){return await ss(this.baseUrl,this.authToken??void 0,e)}};function U(r,e){return{role:r,parts:[{type:"text",text:e}]}}function ns(r){return U("user",r)}function os(r){return U("agent",r)}function re(r){return r.parts.filter(e=>e.type==="text"&&e.text).map(e=>e.text).join("")}function is(r){if(r.status.message)return re(r.status.message)}import{createToolRegistry as as,toolRegistryAdd as ds,toolRegistrySearch as ps,toolRegistryByTag as ls,toolRegistryList as cs,destroyToolRegistry as us}from"gauss-napi";var G=class{_handle;disposed=!1;constructor(){this._handle=as()}get handle(){return this._handle}add(e){return this.assertNotDisposed(),ds(this._handle,JSON.stringify(e)),this}search(e){return this.assertNotDisposed(),ps(this._handle,e)}byTag(e){return this.assertNotDisposed(),ls(this._handle,e)}list(){return this.assertNotDisposed(),cs(this._handle)}destroy(){if(!this.disposed){this.disposed=!0;try{us(this._handle)}catch{}}}[Symbol.dispose](){this.destroy()}assertNotDisposed(){if(this.disposed)throw new Error("ToolRegistry has been destroyed")}};export{j as A2aClient,L as ANTHROPIC_DEFAULT,ie as ANTHROPIC_FAST,ae as ANTHROPIC_PREMIUM,u as Agent,x as AgentSpec,f as AgentStream,M as ApprovalManager,N as CheckpointStore,Y as DEEPSEEK_DEFAULT,le as DEEPSEEK_REASONING,O as EvalRunner,z as FIREWORKS_DEFAULT,F as GOOGLE_DEFAULT,pe as GOOGLE_IMAGE,de as GOOGLE_PREMIUM,k as Graph,D as GuardrailChain,q as MISTRAL_DEFAULT,w as McpServer,b as Memory,P as MiddlewareChain,A as Network,g as OPENAI_DEFAULT,se as OPENAI_FAST,oe as OPENAI_IMAGE,ne as OPENAI_REASONING,K as OPENROUTER_DEFAULT,V as PERPLEXITY_DEFAULT,_ as PROVIDER_DEFAULTS,R as PluginRegistry,H as SkillSpec,B as TOGETHER_DEFAULT,E as Team,C as Telemetry,G as ToolRegistry,I as ToolValidator,T as VectorStore,S as Workflow,W as XAI_DEFAULT,os as agentMessage,Ne as availableRuntimes,Ee as batch,Fr as classify,Lr as codeReview,Qr as compose,br as countMessageTokens,xr as countTokens,vr as countTokensForModel,ur as createCircuitBreaker,cr as createFallbackProvider,mr as createResilientAgent,Q as createResilientProvider,ce as defaultModel,y as detectProvider,qr as discoverAgents,X as enterprisePreset,Se as enterpriseRun,kr as estimateCost,Me as executeCode,Kr as extract,re as extractText,Wr as filterAsync,ke as gauss,Oe as generateImage,Tr as getContextWindowSize,te as mapAsync,Ar as parseAgentConfig,Nr as parsePartialJson,Vr as pipe,$r as reduceAsync,h as resolveApiKey,Pr as resolveEnv,Ir as retryable,Ur as structured,Gr as summarize,Xr as tapAsync,is as taskText,m as template,U as textMessage,Jr as translate,ns as userMessage,Ce as version,Z as withRetry};
21
+ //# sourceMappingURL=index.js.map