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,485 @@
1
+ import { H as Handle, T as ToolDef, M as Message, A as AgentOptions, a as ToolExecutor, b as AgentResult, D as Disposable, P as ProviderType, c as ProviderOptions, C as CodeExecutionOptions, d as ProviderCapabilities, S as StreamCallback } from './types-BkwC4s1P.js';
2
+
3
+ /**
4
+ * A single event emitted during agent streaming.
5
+ *
6
+ * @description Represents a parsed streaming event such as a text delta, tool call,
7
+ * or other provider-specific event. The `type` field discriminates the event kind.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * const event: StreamEvent = { type: "text_delta", text: "Hello" };
12
+ * if (event.type === "text_delta") process.stdout.write(event.text ?? "");
13
+ * ```
14
+ *
15
+ * @since 1.0.0
16
+ */
17
+ interface StreamEvent {
18
+ /** The event type discriminator (e.g. `"text_delta"`, `"tool_call"`, `"raw"`). */
19
+ type: string;
20
+ /** Text content for text-delta events. */
21
+ text?: string;
22
+ /** Tool call payload for tool-call events. */
23
+ toolCall?: {
24
+ name: string;
25
+ arguments: string;
26
+ };
27
+ /** Additional provider-specific fields. */
28
+ [key: string]: unknown;
29
+ }
30
+ /**
31
+ * Async iterable wrapper over the native agent streaming callback.
32
+ *
33
+ * @description Bridges the native callback-based streaming API into an `AsyncIterable<StreamEvent>`.
34
+ * Use with `for await ... of` to consume events as they arrive. After iteration completes,
35
+ * the final {@link AgentResult} is available via the {@link AgentStream.result} getter.
36
+ *
37
+ * @example
38
+ * ```ts
39
+ * const stream = agent.streamIter("Tell me a story");
40
+ * for await (const event of stream) {
41
+ * if (event.type === "text_delta") process.stdout.write(event.text ?? "");
42
+ * }
43
+ * console.log(stream.result?.text);
44
+ * ```
45
+ *
46
+ * @since 1.0.0
47
+ */
48
+ declare class AgentStream implements AsyncIterable<StreamEvent> {
49
+ private readonly agentName;
50
+ private readonly providerHandle;
51
+ private readonly tools;
52
+ private readonly messages;
53
+ private readonly options;
54
+ private readonly toolExecutor;
55
+ private _result;
56
+ /**
57
+ * Create a new `AgentStream`.
58
+ *
59
+ * @description Typically not called directly — use {@link Agent.streamIter} instead.
60
+ *
61
+ * @param agentName - Name of the agent for logging/identification.
62
+ * @param providerHandle - Native provider handle.
63
+ * @param tools - Tool definitions available during the stream.
64
+ * @param messages - Conversation messages to send.
65
+ * @param options - Agent options for the agentic loop.
66
+ * @param toolExecutor - Async callback for executing tool calls.
67
+ *
68
+ * @since 1.0.0
69
+ */
70
+ constructor(agentName: string, providerHandle: Handle, tools: ToolDef[], messages: Message[], options: AgentOptions, toolExecutor: ToolExecutor);
71
+ /**
72
+ * The final aggregated result, available after async iteration completes.
73
+ *
74
+ * @description Returns `undefined` while iteration is still in progress. Once the
75
+ * `for await` loop finishes, this contains the full {@link AgentResult} with response
76
+ * text, token counts, and other metadata.
77
+ *
78
+ * @returns The completed {@link AgentResult} or `undefined` if iteration hasn't finished.
79
+ *
80
+ * @example
81
+ * ```ts
82
+ * const stream = agent.streamIter("Hello");
83
+ * for await (const event of stream) { /* consume events *\/ }
84
+ * console.log(stream.result?.text);
85
+ * ```
86
+ *
87
+ * @since 1.0.0
88
+ */
89
+ get result(): AgentResult | undefined;
90
+ /**
91
+ * Async iterator implementation — yields {@link StreamEvent} objects as they arrive.
92
+ *
93
+ * @description Starts the native streaming call and yields parsed events. The iterator
94
+ * completes when the underlying stream finishes and all buffered events have been yielded.
95
+ *
96
+ * @returns An async iterator of {@link StreamEvent} objects.
97
+ *
98
+ * @since 1.0.0
99
+ */
100
+ [Symbol.asyncIterator](): AsyncIterator<StreamEvent>;
101
+ }
102
+
103
+ /**
104
+ * Configuration object for creating an {@link Agent} instance.
105
+ *
106
+ * @description All fields are optional — sensible defaults are applied and the provider is auto-detected from environment variables when omitted.
107
+ *
108
+ * @example
109
+ * ```ts
110
+ * const config: AgentConfig = {
111
+ * provider: "anthropic",
112
+ * model: "claude-sonnet-4-20250514",
113
+ * instructions: "You are a helpful assistant.",
114
+ * temperature: 0.7,
115
+ * };
116
+ * const agent = new Agent(config);
117
+ * ```
118
+ *
119
+ * @since 1.0.0
120
+ */
121
+ interface AgentConfig {
122
+ /** Agent name (default: `"agent"`). Used for logging and identification. */
123
+ name?: string;
124
+ /** LLM provider. Auto-detected from env if omitted. */
125
+ provider?: ProviderType;
126
+ /** Model identifier (e.g. `"gpt-4o"`, `"claude-sonnet-4-20250514"`). Auto-selected if omitted. */
127
+ model?: string;
128
+ /** Provider connection options. API key auto-resolved from env if omitted. */
129
+ providerOptions?: ProviderOptions;
130
+ /** System instructions prepended to every conversation. */
131
+ instructions?: string;
132
+ /** Tool definitions available to the agent. */
133
+ tools?: ToolDef[];
134
+ /** Sampling temperature (0–2). Higher values produce more creative output. */
135
+ temperature?: number;
136
+ /** Maximum number of agentic loop iterations before stopping. */
137
+ maxSteps?: number;
138
+ /** Top-p (nucleus) sampling threshold. */
139
+ topP?: number;
140
+ /** Maximum number of output tokens per response. */
141
+ maxTokens?: number;
142
+ /** Deterministic seed for reproducible outputs. */
143
+ seed?: number;
144
+ /** Stop the agentic loop when this tool name is called. */
145
+ stopOnTool?: string;
146
+ /** JSON schema for structured output. The model will conform its response to this schema. */
147
+ outputSchema?: Record<string, unknown>;
148
+ /** Extended thinking budget (Anthropic). Number of tokens for internal reasoning. */
149
+ thinkingBudget?: number;
150
+ /** Reasoning effort for OpenAI o-series models. Controls how much reasoning to use. */
151
+ reasoningEffort?: "low" | "medium" | "high";
152
+ /** Enable prompt caching (Anthropic). Auto-annotates system messages and tools. */
153
+ cacheControl?: boolean;
154
+ /** Enable code execution runtimes. Pass `true` for all defaults, or configure individually. */
155
+ codeExecution?: boolean | CodeExecutionOptions;
156
+ /** Enable Google Search grounding (Gemini only). */
157
+ grounding?: boolean;
158
+ /** Enable native code execution / Gemini code interpreter. */
159
+ nativeCodeExecution?: boolean;
160
+ /** Response modalities (e.g. `["TEXT", "IMAGE"]` for Gemini image generation). */
161
+ responseModalities?: string[];
162
+ }
163
+ /**
164
+ * Core agent class that wraps a native LLM provider and manages the agentic loop.
165
+ *
166
+ * @description `Agent` is the primary entry-point for interacting with language models in Gauss.
167
+ * It supports single-shot completions, multi-step tool-use loops, streaming, and raw generation.
168
+ * Each instance owns a native provider handle that **must** be released via {@link Agent.destroy}
169
+ * (or the `using` pattern) to avoid resource leaks.
170
+ *
171
+ * @example
172
+ * ```ts
173
+ * const agent = new Agent({
174
+ * provider: "openai",
175
+ * model: "gpt-4o",
176
+ * instructions: "You are a helpful assistant.",
177
+ * });
178
+ * const result = await agent.run("What is the meaning of life?");
179
+ * console.log(result.text);
180
+ * agent.destroy();
181
+ * ```
182
+ *
183
+ * @since 1.0.0
184
+ */
185
+ declare class Agent implements Disposable {
186
+ private readonly providerHandle;
187
+ private readonly _name;
188
+ private readonly _provider;
189
+ private readonly _model;
190
+ private readonly _instructions;
191
+ private _tools;
192
+ private _options;
193
+ private disposed;
194
+ /**
195
+ * Create a new Agent.
196
+ *
197
+ * @description Initialises the native provider connection and configures the agentic
198
+ * loop options. The provider and model are auto-detected from environment variables
199
+ * when not explicitly set.
200
+ *
201
+ * @param config - Agent configuration. All fields are optional.
202
+ * @throws {Error} If the native provider cannot be created (e.g. invalid API key).
203
+ *
204
+ * @example
205
+ * ```ts
206
+ * const agent = new Agent({ instructions: "Be concise." });
207
+ * ```
208
+ *
209
+ * @since 1.0.0
210
+ */
211
+ constructor(config?: AgentConfig);
212
+ /**
213
+ * @description The agent's name.
214
+ * @since 1.0.0
215
+ */
216
+ get name(): string;
217
+ /**
218
+ * @description The resolved LLM provider type.
219
+ * @since 1.0.0
220
+ */
221
+ get provider(): ProviderType;
222
+ /**
223
+ * @description The resolved model identifier.
224
+ * @since 1.0.0
225
+ */
226
+ get model(): string;
227
+ /**
228
+ * @description The system instructions string.
229
+ * @since 1.0.0
230
+ */
231
+ get instructions(): string;
232
+ /**
233
+ * @description Native provider handle. Used internally by Network, Graph, and other subsystems.
234
+ * @since 1.0.0
235
+ * @internal
236
+ */
237
+ get handle(): Handle;
238
+ /**
239
+ * @description Query what features this provider/model combination supports.
240
+ * @returns The capability flags for the current provider and model.
241
+ * @since 1.0.0
242
+ */
243
+ get capabilities(): ProviderCapabilities;
244
+ /**
245
+ * Register a single tool definition. Chainable.
246
+ *
247
+ * @description Appends a tool to the agent's tool list so the LLM can invoke it during the agentic loop.
248
+ *
249
+ * @param tool - The tool definition to add.
250
+ * @returns `this` for fluent chaining.
251
+ *
252
+ * @example
253
+ * ```ts
254
+ * agent.addTool({ name: "search", description: "Web search", parameters: { query: { type: "string" } } });
255
+ * ```
256
+ *
257
+ * @since 1.0.0
258
+ */
259
+ addTool(tool: ToolDef): this;
260
+ /**
261
+ * Register multiple tool definitions at once. Chainable.
262
+ *
263
+ * @description Appends all provided tools to the agent's tool list.
264
+ *
265
+ * @param tools - Array of tool definitions to add.
266
+ * @returns `this` for fluent chaining.
267
+ *
268
+ * @example
269
+ * ```ts
270
+ * agent.addTools([
271
+ * { name: "search", description: "Web search", parameters: { query: { type: "string" } } },
272
+ * { name: "calculate", description: "Math calculator", parameters: { expr: { type: "string" } } },
273
+ * ]);
274
+ * ```
275
+ *
276
+ * @since 1.0.0
277
+ */
278
+ addTools(tools: ToolDef[]): this;
279
+ /**
280
+ * Merge additional agent options into the current configuration. Chainable.
281
+ *
282
+ * @description Shallow-merges the provided options with the existing ones. Later calls override earlier values.
283
+ *
284
+ * @param options - Partial agent options to merge.
285
+ * @returns `this` for fluent chaining.
286
+ *
287
+ * @example
288
+ * ```ts
289
+ * agent.setOptions({ temperature: 0.5, maxTokens: 1024 });
290
+ * ```
291
+ *
292
+ * @since 1.0.0
293
+ */
294
+ setOptions(options: Partial<AgentOptions>): this;
295
+ /**
296
+ * Run the agentic loop to completion.
297
+ *
298
+ * @description Sends the input through the full agentic loop (tool calls, multi-step reasoning)
299
+ * and returns the final result. Accepts either a plain string prompt or a pre-built message array.
300
+ *
301
+ * @param input - A string prompt or an array of {@link Message} objects.
302
+ * @returns The completed {@link AgentResult} containing the response text, token counts, and optional structured output.
303
+ * @throws {Error} If the agent has been destroyed.
304
+ *
305
+ * @example
306
+ * ```ts
307
+ * const result = await agent.run("Explain quantum computing");
308
+ * console.log(result.text);
309
+ * console.log(`Tokens: ${result.inputTokens} in / ${result.outputTokens} out`);
310
+ * ```
311
+ *
312
+ * @since 1.0.0
313
+ */
314
+ run(input: string | Message[]): Promise<AgentResult>;
315
+ /**
316
+ * Run the agentic loop with a JavaScript-side tool executor.
317
+ *
318
+ * @description Like {@link Agent.run}, but delegates tool invocations to the provided
319
+ * `toolExecutor` callback. Use this when tools need access to the Node.js runtime
320
+ * (file system, network, databases, etc.).
321
+ *
322
+ * @param input - A string prompt or an array of {@link Message} objects.
323
+ * @param toolExecutor - Async callback that receives a JSON-encoded tool call and returns a JSON-encoded result.
324
+ * @returns The completed {@link AgentResult}.
325
+ * @throws {Error} If the agent has been destroyed.
326
+ *
327
+ * @example
328
+ * ```ts
329
+ * const result = await agent.runWithTools("Search for cats", async (callJson) => {
330
+ * const call = JSON.parse(callJson);
331
+ * return JSON.stringify({ results: ["cat1", "cat2"] });
332
+ * });
333
+ * ```
334
+ *
335
+ * @since 1.0.0
336
+ */
337
+ runWithTools(input: string | Message[], toolExecutor: ToolExecutor): Promise<AgentResult>;
338
+ /**
339
+ * Stream agent responses with real-time events via a callback.
340
+ *
341
+ * @description Runs the agentic loop while invoking `onEvent` for each streaming event
342
+ * (text deltas, tool calls, etc.). Returns the final aggregated result after the stream ends.
343
+ *
344
+ * @param input - A string prompt or an array of {@link Message} objects.
345
+ * @param onEvent - Callback invoked with each JSON-encoded stream event.
346
+ * @param toolExecutor - Optional async callback for handling tool invocations.
347
+ * @returns The completed {@link AgentResult}.
348
+ * @throws {Error} If the agent has been destroyed.
349
+ *
350
+ * @example
351
+ * ```ts
352
+ * const result = await agent.stream("Tell me a joke", (eventJson) => {
353
+ * const event = JSON.parse(eventJson);
354
+ * if (event.type === "text_delta") process.stdout.write(event.text ?? "");
355
+ * });
356
+ * ```
357
+ *
358
+ * @since 1.0.0
359
+ */
360
+ stream(input: string | Message[], onEvent: StreamCallback, toolExecutor?: ToolExecutor): Promise<AgentResult>;
361
+ /**
362
+ * Stream as an async iterable — use with `for await`.
363
+ *
364
+ * @description Returns an {@link AgentStream} that yields {@link StreamEvent} objects.
365
+ * After iteration completes, the final {@link AgentResult} is available via
366
+ * `stream.result`.
367
+ *
368
+ * @param input - A string prompt or an array of {@link Message} objects.
369
+ * @param toolExecutor - Optional async callback for handling tool invocations.
370
+ * @returns An {@link AgentStream} async iterable of {@link StreamEvent} objects.
371
+ * @throws {Error} If the agent has been destroyed.
372
+ *
373
+ * @example
374
+ * ```ts
375
+ * const stream = agent.streamIter("Tell me a story");
376
+ * for await (const event of stream) {
377
+ * if (event.type === "text_delta") process.stdout.write(event.text ?? "");
378
+ * }
379
+ * console.log(stream.result?.text);
380
+ * ```
381
+ *
382
+ * @since 1.0.0
383
+ */
384
+ streamIter(input: string | Message[], toolExecutor?: ToolExecutor): AgentStream;
385
+ /**
386
+ * Perform a single raw LLM call without the agentic loop.
387
+ *
388
+ * @description Bypasses the multi-step agent loop and sends the input directly to the model
389
+ * for a one-shot completion. Useful when you need a simple generation without tool use.
390
+ *
391
+ * @param input - A string prompt or an array of {@link Message} objects.
392
+ * @param options - Optional generation parameters.
393
+ * @param options.temperature - Sampling temperature override.
394
+ * @param options.maxTokens - Maximum output tokens override.
395
+ * @returns The raw provider response.
396
+ *
397
+ * @example
398
+ * ```ts
399
+ * const response = await agent.generate("Translate 'hello' to French", { temperature: 0 });
400
+ * ```
401
+ *
402
+ * @since 1.0.0
403
+ */
404
+ generate(input: string | Message[], options?: {
405
+ temperature?: number;
406
+ maxTokens?: number;
407
+ }): Promise<unknown>;
408
+ /**
409
+ * Perform a single raw LLM call with tool definitions (no agentic loop).
410
+ *
411
+ * @description Like {@link Agent.generate}, but also passes tool definitions to the model.
412
+ * The model may return tool-call requests in its response, but the caller is responsible
413
+ * for executing them — no automatic loop is performed.
414
+ *
415
+ * @param input - A string prompt or an array of {@link Message} objects.
416
+ * @param tools - Tool definitions to make available to the model.
417
+ * @param options - Optional generation parameters.
418
+ * @param options.temperature - Sampling temperature override.
419
+ * @param options.maxTokens - Maximum output tokens override.
420
+ * @returns The raw provider response, potentially containing tool call requests.
421
+ *
422
+ * @example
423
+ * ```ts
424
+ * const response = await agent.generateWithTools(
425
+ * "What's the weather?",
426
+ * [{ name: "get_weather", description: "Get weather", parameters: { city: { type: "string" } } }],
427
+ * );
428
+ * ```
429
+ *
430
+ * @since 1.0.0
431
+ */
432
+ generateWithTools(input: string | Message[], tools: ToolDef[], options?: {
433
+ temperature?: number;
434
+ maxTokens?: number;
435
+ }): Promise<unknown>;
436
+ /**
437
+ * Release all native resources held by this agent.
438
+ *
439
+ * @description Destroys the underlying native provider handle. Safe to call multiple times;
440
+ * subsequent calls are no-ops. After calling `destroy()`, any further method calls on this
441
+ * agent will throw.
442
+ *
443
+ * @since 1.0.0
444
+ */
445
+ destroy(): void;
446
+ /**
447
+ * Alias for {@link Agent.destroy} — enables the TC39 `using` pattern.
448
+ *
449
+ * @example
450
+ * ```ts
451
+ * {
452
+ * using agent = new Agent({ instructions: "Be helpful." });
453
+ * const result = await agent.run("Hi!");
454
+ * } // agent is automatically destroyed here
455
+ * ```
456
+ *
457
+ * @since 1.0.0
458
+ */
459
+ [Symbol.dispose](): void;
460
+ private assertNotDisposed;
461
+ }
462
+ /**
463
+ * One-liner convenience function — create an agent, run a prompt, and return the text.
464
+ *
465
+ * @description Creates a temporary {@link Agent}, sends the prompt through the agentic loop,
466
+ * and returns just the response text. The agent is automatically destroyed after the call.
467
+ * Ideal for quick, single-turn interactions.
468
+ *
469
+ * @param prompt - The user prompt to send to the agent.
470
+ * @param config - Optional agent configuration (everything except `name`).
471
+ * @returns The agent's response text.
472
+ * @throws {Error} If the provider cannot be initialised or the call fails.
473
+ *
474
+ * @example
475
+ * ```ts
476
+ * import { gauss } from "gauss-ts";
477
+ * const answer = await gauss("What is the meaning of life?");
478
+ * console.log(answer);
479
+ * ```
480
+ *
481
+ * @since 1.0.0
482
+ */
483
+ declare function gauss(prompt: string, config?: Omit<AgentConfig, "name">): Promise<string>;
484
+
485
+ export { type AgentConfig as A, type StreamEvent as S, Agent as a, AgentStream as b, gauss as g };