gauss-ts 2.0.6 → 2.0.7

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/agent.ts","../src/sdk/agent.ts","../src/sdk/errors.ts","../src/sdk/models.ts","../src/sdk/types.ts","../src/sdk/routing-policy.ts","../src/sdk/stream-iter.ts","../src/sdk/tool.ts","../src/sdk/batch.ts","../src/sdk/code-execution.ts"],"sourcesContent":["export { Agent, gauss } from \"./sdk/agent.js\";\nexport type { AgentConfig } from \"./sdk/agent.js\";\nexport { AgentStream } from \"./sdk/stream-iter.js\";\nexport type { StreamEvent } from \"./sdk/stream-iter.js\";\nexport { batch } from \"./sdk/batch.js\";\nexport type { BatchItem } from \"./sdk/batch.js\";\nexport { executeCode, availableRuntimes, generateImage, version } from \"./sdk/code-execution.js\";\n","/**\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 MemoryEntry,\n GroundingMetadata,\n} from \"./types.js\";\n\nimport { DisposedError } from \"./errors.js\";\n\nimport { resolveApiKey, detectProvider } from \"./types.js\";\nimport { OPENAI_DEFAULT } from \"./models.js\";\nimport type { ResolveRoutingTargetOptions, RoutingPolicy } from \"./routing-policy.js\";\nimport { resolveRoutingTarget } from \"./routing-policy.js\";\nimport { AgentStream } from \"./stream-iter.js\";\nimport { tool as toolFn, isTypedTool, createToolExecutor, type TypedToolDef } from \"./tool.js\";\nimport type { MiddlewareChain } from \"./middleware.js\";\nimport type { GuardrailChain } from \"./guardrail.js\";\nimport type { Memory } from \"./memory.js\";\nimport type { McpClient } from \"./mcp-client.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 */\ninterface RawNapiResult {\n text: string;\n steps: number;\n inputTokens: number;\n outputTokens: number;\n messages?: Message[];\n tool_calls?: Array<{ name: string; arguments: Record<string, unknown> }>;\n thinking?: string;\n structuredOutput?: Record<string, unknown>;\n groundingMetadata?: GroundingMetadata[];\n citations?: Array<{\n citationType?: string;\n type?: string;\n citedText?: string;\n documentTitle?: string;\n start?: number;\n end?: number;\n }>;\n}\n\nfunction toSdkResult(raw: RawNapiResult): AgentResult {\n return {\n ...raw,\n citations: raw.citations?.map((c) => ({\n type: c.citationType ?? c.type ?? \"unknown\",\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 /** Optional alias/fallback routing policy for model selection. */\n routingPolicy?: RoutingPolicy;\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. Accepts both raw ToolDef and typed tools with execute callbacks. */\n tools?: (ToolDef | TypedToolDef)[];\n\n /** Middleware chain to apply (logging, caching, rate limiting). */\n middleware?: MiddlewareChain;\n\n /** Guardrail chain to apply (PII, content moderation, schema validation). */\n guardrails?: GuardrailChain;\n\n /** Memory instance for automatic conversation history. */\n memory?: Memory;\n\n /** Session ID for memory scoping (default: auto-generated). */\n sessionId?: string;\n\n /** MCP clients to consume tools from external MCP servers. */\n mcpClients?: McpClient[];\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 _requestedProvider: ProviderType;\n private readonly _requestedModel: string;\n private readonly _provider: ProviderType;\n private readonly _model: string;\n private readonly _routingPolicy: RoutingPolicy | undefined;\n private readonly _providerOptions: ProviderOptions & { apiKey: string };\n private readonly _instructions: string;\n private _tools: (ToolDef | TypedToolDef)[] = [];\n private _options: AgentOptions = {};\n private disposed = false;\n\n // ─── Integration Glue (M35) ──────────────────────────────────────\n private _middleware: MiddlewareChain | null = null;\n private _guardrails: GuardrailChain | null = null;\n private _memory: Memory | null = null;\n private _sessionId: string = \"\";\n private _mcpClients: McpClient[] = [];\n private _mcpToolsLoaded = 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 const requestedProvider = config.provider ?? detected?.provider ?? \"openai\";\n const requestedModel = config.model ?? detected?.model ?? OPENAI_DEFAULT;\n this._requestedProvider = requestedProvider;\n this._requestedModel = requestedModel;\n this._routingPolicy = config.routingPolicy;\n const resolved = resolveRoutingTarget(this._routingPolicy, requestedProvider, requestedModel);\n this._provider = resolved.provider;\n this._model = resolved.model;\n this._name = config.name ?? \"agent\";\n this._instructions = config.instructions ?? \"\";\n\n const apiKey =\n config.providerOptions?.apiKey ?? resolveApiKey(this._provider);\n this._providerOptions = {\n apiKey,\n ...config.providerOptions,\n } as ProviderOptions & { apiKey: string };\n this.providerHandle = create_provider(this._provider, this._model, this._providerOptions);\n\n if (config.tools) this._tools = [...config.tools];\n\n // Integration glue (M35)\n if (config.middleware) this._middleware = config.middleware;\n if (config.guardrails) this._guardrails = config.guardrails;\n if (config.memory) this._memory = config.memory;\n if (config.sessionId) this._sessionId = config.sessionId;\n if (config.mcpClients) this._mcpClients = [...config.mcpClients];\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 /**\n * Create an agent using provider/model auto-detection from environment variables.\n *\n * @description Equivalent to `new Agent(config)`, but clearer in intent for env-driven setup.\n *\n * @param config - Optional partial configuration overrides.\n * @returns A new {@link Agent} instance.\n *\n * @example\n * ```ts\n * const agent = Agent.fromEnv({ instructions: \"Be concise.\" });\n * ```\n */\n static fromEnv(config: AgentConfig = {}): Agent {\n return new Agent(config);\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 | TypedToolDef): 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 | TypedToolDef)[]): this {\n this._tools.push(...tools);\n return this;\n }\n\n /**\n * Inline tool shortcut — define and attach a tool in one step.\n *\n * @example\n * ```ts\n * const result = await agent\n * .withTool(\"get_weather\", \"Get weather for a city\", async ({ city }) => ({ temp: 72 }))\n * .run(\"Weather in Paris?\");\n * ```\n */\n withTool<TParams = Record<string, unknown>, TResult = unknown>(\n name: string,\n description: string,\n execute: (params: TParams) => TResult | Promise<TResult>,\n parameters?: Record<string, unknown>\n ): this {\n this._tools.push(toolFn({ name, description, parameters: parameters ?? {}, execute }));\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 /**\n * Clone this agent with a different model.\n *\n * @description Returns a **new** agent instance preserving tools and integrations,\n * but using the provided model identifier.\n *\n * @param model - Target model identifier.\n * @returns A new {@link Agent} configured with the selected model.\n */\n withModel(model: string): Agent {\n this.assertNotDisposed();\n return new Agent({\n ...this.toConfig(),\n model,\n });\n }\n\n /**\n * Clone this agent and resolve a routing decision using runtime context.\n *\n * @param context - Runtime routing context (availability, budget, rate).\n * @returns A new {@link Agent} routed according to current policy + context.\n */\n withRoutingContext(context: ResolveRoutingTargetOptions): Agent {\n this.assertNotDisposed();\n const resolved = resolveRoutingTarget(\n this._routingPolicy,\n this._requestedProvider,\n this._requestedModel,\n context,\n );\n return new Agent({\n ...this.toConfig(),\n provider: resolved.provider,\n model: resolved.model,\n });\n }\n\n // ─── Integration Glue (M35) ────────────────────────────────────\n\n /**\n * Attach a middleware chain (logging, caching, rate limiting). Chainable.\n *\n * @param chain - A configured {@link MiddlewareChain} instance.\n * @returns `this` for fluent chaining.\n *\n * @example\n * ```ts\n * agent.withMiddleware(\n * new MiddlewareChain().useLogging().useCaching(60000).useRateLimit(100)\n * );\n * ```\n *\n * @since 1.2.0\n */\n withMiddleware(chain: MiddlewareChain): this {\n this._middleware = chain;\n return this;\n }\n\n /**\n * Attach a guardrail chain (content moderation, PII, schema validation). Chainable.\n *\n * @param chain - A configured {@link GuardrailChain} instance.\n * @returns `this` for fluent chaining.\n *\n * @example\n * ```ts\n * agent.withGuardrails(\n * new GuardrailChain().addPiiDetection(\"redact\").addContentModeration([\"violence\"], [])\n * );\n * ```\n *\n * @since 1.2.0\n */\n withGuardrails(chain: GuardrailChain): this {\n this._guardrails = chain;\n return this;\n }\n\n /**\n * Attach memory for automatic conversation history. Chainable.\n *\n * @description When memory is attached, the agent automatically:\n * - Recalls recent entries before each run (prepended as context)\n * - Stores the conversation (input + output) after each run\n *\n * @param memory - A {@link Memory} instance.\n * @param sessionId - Optional session ID for scoping memory entries.\n * @returns `this` for fluent chaining.\n *\n * @example\n * ```ts\n * const memory = new Memory();\n * agent.withMemory(memory, \"session-123\");\n * await agent.run(\"Hello!\"); // stored in memory\n * await agent.run(\"What did I just say?\"); // recalls previous context\n * ```\n *\n * @since 1.2.0\n */\n withMemory(memory: Memory, sessionId?: string): this {\n this._memory = memory;\n if (sessionId) this._sessionId = sessionId;\n return this;\n }\n\n /**\n * Consume tools from an external MCP server. Chainable.\n *\n * @description Registers an MCP client whose tools will be loaded\n * and made available to the agent on the first run.\n *\n * @param client - A connected {@link McpClient} instance.\n * @returns `this` for fluent chaining.\n *\n * @example\n * ```ts\n * const mcp = new McpClient({ command: \"npx\", args: [\"-y\", \"@mcp/server-fs\"] });\n * await mcp.connect();\n * agent.useMcpServer(mcp);\n * ```\n *\n * @since 1.2.0\n */\n useMcpServer(client: McpClient): this {\n this._mcpClients.push(client);\n this._mcpToolsLoaded = false;\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\n // Load MCP tools if needed\n await this.ensureMcpTools();\n\n let messages = typeof input === \"string\"\n ? [{ role: \"user\" as const, content: input }]\n : [...input];\n\n // Memory recall: inject context\n if (this._memory) {\n const recalled = await this._memory.recall(\n this._sessionId ? { sessionId: this._sessionId } : undefined\n );\n if (recalled.length > 0) {\n const contextText = recalled.map(e => e.content).join(\"\\n\");\n messages = [\n { role: \"system\" as const, content: `Previous context:\\n${contextText}` },\n ...messages,\n ];\n }\n }\n\n // Extract tool definitions (strip execute callbacks for NAPI)\n const { toolDefs, executor } = this.resolveToolsAndExecutor();\n\n let result: AgentResult;\n if (executor) {\n result = toSdkResult(await agent_run_with_tool_executor(\n this._name,\n this.providerHandle,\n toolDefs,\n messages,\n this._options,\n executor\n ));\n } else {\n result = toSdkResult(await agent_run(\n this._name,\n this.providerHandle,\n toolDefs,\n messages,\n this._options\n ));\n }\n\n // Memory store: save conversation\n if (this._memory) {\n const userText = typeof input === \"string\" ? input : input.map(m => m.content).join(\"\\n\");\n await this._memory.store({\n id: `${Date.now()}-user`,\n content: userText,\n entryType: \"conversation\",\n timestamp: new Date().toISOString(),\n sessionId: this._sessionId || undefined,\n });\n await this._memory.store({\n id: `${Date.now()}-assistant`,\n content: result.text,\n entryType: \"conversation\",\n timestamp: new Date().toISOString(),\n sessionId: this._sessionId || undefined,\n });\n }\n\n return result;\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\n await this.ensureMcpTools();\n\n const messages = typeof input === \"string\"\n ? [{ role: \"user\" as const, content: input }]\n : input;\n\n const { toolDefs, executor: typedExecutor } = this.resolveToolsAndExecutor();\n\n // Compose typed tool executor with user-provided executor\n const composedExecutor: ToolExecutor = async (callJson: string) => {\n // Try typed tools first, then fall back to user executor\n if (typedExecutor) {\n const result = await typedExecutor(callJson);\n const parsed = JSON.parse(result);\n if (!parsed.error?.startsWith(\"Unknown tool:\")) return result;\n }\n return toolExecutor(callJson);\n };\n\n return toSdkResult(await agent_run_with_tool_executor(\n this._name,\n this.providerHandle,\n toolDefs,\n messages,\n this._options,\n composedExecutor\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\n await this.ensureMcpTools();\n\n const messages = typeof input === \"string\"\n ? [{ role: \"user\" as const, content: input }]\n : input;\n\n const { toolDefs, executor: typedExecutor } = this.resolveToolsAndExecutor();\n const finalExecutor = toolExecutor ?? typedExecutor ?? NOOP_TOOL_EXECUTOR;\n\n return toSdkResult(await agent_stream_with_tool_executor(\n this._name,\n this.providerHandle,\n toolDefs,\n messages,\n this._options,\n onEvent,\n finalExecutor\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\n const { toolDefs, executor: typedExecutor } = this.resolveToolsAndExecutor();\n const finalExecutor = toolExecutor ?? typedExecutor ?? NOOP_TOOL_EXECUTOR;\n\n return new AgentStream(\n this._name,\n this.providerHandle,\n toolDefs,\n messages,\n this._options,\n finalExecutor\n );\n }\n\n /**\n * Stream only text deltas with a tiny DX helper.\n *\n * @description Aggregates all streamed text deltas into a final string and optionally\n * invokes `onDelta` for each chunk as it arrives.\n *\n * @param input - A string prompt or an array of {@link Message} objects.\n * @param onDelta - Optional callback invoked for each text delta.\n * @param toolExecutor - Optional async callback for handling tool invocations.\n * @returns The final response text.\n */\n async streamText(\n input: string | Message[],\n onDelta?: (delta: string) => void,\n toolExecutor?: ToolExecutor\n ): Promise<string> {\n this.assertNotDisposed();\n const stream = this.streamIter(input, toolExecutor);\n let aggregated = \"\";\n\n for await (const event of stream) {\n if (event.type !== \"text_delta\") continue;\n const delta = typeof event.text === \"string\"\n ? event.text\n : (typeof event.delta === \"string\" ? event.delta : \"\");\n if (!delta) continue;\n aggregated += delta;\n onDelta?.(delta);\n }\n\n return stream.result?.text ?? aggregated;\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 // Close MCP clients\n for (const client of this._mcpClients) {\n try { client.close(); } catch { /* ignore */ }\n }\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 DisposedError(\"Agent\", this._name);\n }\n }\n\n /**\n * Resolve typed tools into plain ToolDefs + a ToolExecutor.\n * @internal\n */\n private resolveToolsAndExecutor(): { toolDefs: ToolDef[]; executor: ToolExecutor | null } {\n const typedTools = this._tools.filter(isTypedTool);\n\n // Strip execute callbacks for the NAPI layer\n const toolDefs: ToolDef[] = this._tools.map(t => ({\n name: t.name,\n description: t.description,\n parameters: t.parameters,\n }));\n\n const executor = typedTools.length > 0\n ? createToolExecutor(typedTools)\n : null;\n\n return { toolDefs, executor };\n }\n\n /**\n * Load tools from all connected MCP clients (lazy, once).\n * @internal\n */\n private async ensureMcpTools(): Promise<void> {\n if (this._mcpToolsLoaded || this._mcpClients.length === 0) return;\n\n for (const client of this._mcpClients) {\n const { tools, executor } = await client.getToolsWithExecutor();\n // Add MCP tools as typed tools with the MCP executor as their execute callback\n for (const t of tools) {\n const mcpTool: TypedToolDef = {\n ...t,\n execute: async (params: Record<string, unknown>) => {\n const callJson = JSON.stringify({ tool: t.name, args: params });\n const resultJson = await executor(callJson);\n return JSON.parse(resultJson);\n },\n };\n this._tools.push(mcpTool);\n }\n }\n\n this._mcpToolsLoaded = true;\n }\n\n /** Snapshot current agent configuration for cloning helpers. */\n private toConfig(): AgentConfig {\n return {\n name: this._name,\n provider: this._requestedProvider,\n model: this._requestedModel,\n routingPolicy: this._routingPolicy,\n providerOptions: { ...this._providerOptions },\n instructions: this._instructions || undefined,\n tools: [...this._tools],\n middleware: this._middleware ?? undefined,\n guardrails: this._guardrails ?? undefined,\n memory: this._memory ?? undefined,\n sessionId: this._sessionId || undefined,\n mcpClients: [...this._mcpClients],\n temperature: this._options.temperature,\n maxSteps: this._options.maxSteps,\n topP: this._options.topP,\n maxTokens: this._options.maxTokens,\n seed: this._options.seed,\n stopOnTool: this._options.stopOnTool,\n outputSchema: this._options.outputSchema,\n thinkingBudget: this._options.thinkingBudget,\n reasoningEffort: this._options.reasoningEffort,\n cacheControl: this._options.cacheControl,\n codeExecution: this._options.codeExecution,\n grounding: this._options.grounding,\n nativeCodeExecution: this._options.nativeCodeExecution,\n responseModalities: this._options.responseModalities,\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 * Structured error hierarchy for Gauss SDK.\n *\n * All Gauss errors extend {@link GaussError} to enable type-safe catch blocks:\n *\n * ```ts\n * try {\n * await agent.run(\"hello\");\n * } catch (e) {\n * if (e instanceof AgentDisposedError) { ... }\n * if (e instanceof ProviderError) { ... }\n * }\n * ```\n *\n * @module errors\n * @since 2.1.0\n */\n\n/** Base error for all Gauss SDK errors. Includes an error code for programmatic matching. */\nexport class GaussError extends Error {\n readonly code: string;\n constructor(code: string, message: string) {\n super(message);\n this.name = \"GaussError\";\n this.code = code;\n }\n}\n\n/** Thrown when an operation is attempted on a destroyed Agent/Team/Graph. */\nexport class DisposedError extends GaussError {\n readonly resourceType: string;\n readonly resourceName: string;\n constructor(resourceType: string, resourceName: string) {\n super(\"RESOURCE_DISPOSED\", `${resourceType} \"${resourceName}\" has been destroyed. Create a new instance.`);\n this.name = \"DisposedError\";\n this.resourceType = resourceType;\n this.resourceName = resourceName;\n }\n}\n\n/** Thrown when provider initialization or communication fails. */\nexport class ProviderError extends GaussError {\n readonly provider: string;\n constructor(provider: string, message: string) {\n super(\"PROVIDER_ERROR\", `[${provider}] ${message}`);\n this.name = \"ProviderError\";\n this.provider = provider;\n }\n}\n\n/** Thrown when tool execution fails. */\nexport class ToolExecutionError extends GaussError {\n readonly toolName: string;\n readonly cause?: Error;\n constructor(toolName: string, message: string, cause?: Error) {\n super(\"TOOL_EXECUTION_ERROR\", `Tool \"${toolName}\" failed: ${message}`);\n this.name = \"ToolExecutionError\";\n this.toolName = toolName;\n this.cause = cause;\n }\n}\n\n/** Thrown when configuration validation fails. */\nexport class ValidationError extends GaussError {\n readonly field?: string;\n constructor(message: string, field?: string) {\n super(\"VALIDATION_ERROR\", field ? `Invalid \"${field}\": ${message}` : message);\n this.name = \"ValidationError\";\n this.field = field;\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","import type { ProviderType } from \"./types.js\";\n\nexport interface RoutingCandidate {\n provider: ProviderType;\n model: string;\n priority?: number;\n maxCostUsd?: number;\n}\n\nexport type GovernanceRule =\n | { type: \"require_tag\"; tag: string }\n | { type: \"deny_provider\"; provider: ProviderType }\n | { type: \"allow_provider\"; provider: ProviderType };\n\nexport interface GovernancePolicyPack {\n rules: GovernanceRule[];\n}\n\nexport interface RoutingPolicy {\n aliases?: Record<string, RoutingCandidate[]>;\n fallbackOrder?: ProviderType[];\n maxTotalCostUsd?: number;\n maxRequestsPerMinute?: number;\n governance?: GovernancePolicyPack;\n}\n\nexport interface ResolvedRoutingTarget {\n provider: ProviderType;\n model: string;\n selectedBy: \"direct\" | `alias:${string}` | `fallback:${ProviderType}`;\n}\n\nexport interface ResolveRoutingTargetOptions {\n availableProviders?: ProviderType[];\n estimatedCostUsd?: number;\n currentRequestsPerMinute?: number;\n governanceTags?: string[];\n}\n\nexport function enforceRoutingCostLimit(\n policy: RoutingPolicy | undefined,\n costUsd: number,\n): void {\n if (policy?.maxTotalCostUsd !== undefined && costUsd > policy.maxTotalCostUsd) {\n throw new Error(`routing policy rejected cost ${costUsd}`);\n }\n}\n\nexport function enforceRoutingRateLimit(\n policy: RoutingPolicy | undefined,\n requestsPerMinute: number,\n): void {\n if (\n policy?.maxRequestsPerMinute !== undefined &&\n requestsPerMinute > policy.maxRequestsPerMinute\n ) {\n throw new Error(`routing policy rejected rate ${requestsPerMinute}`);\n }\n}\n\nexport function enforceRoutingGovernance(\n policy: RoutingPolicy | undefined,\n provider: ProviderType,\n tags?: string[],\n): void {\n const rules = policy?.governance?.rules ?? [];\n if (rules.length === 0) return;\n const allow = rules\n .filter((rule): rule is Extract<GovernanceRule, { type: \"allow_provider\" }> => rule.type === \"allow_provider\")\n .map((rule) => rule.provider);\n if (allow.length > 0 && !allow.includes(provider)) {\n throw new Error(`routing policy governance rejected provider ${provider}`);\n }\n for (const rule of rules) {\n if (rule.type === \"deny_provider\" && rule.provider === provider) {\n throw new Error(`routing policy governance rejected provider ${provider}`);\n }\n if (rule.type === \"require_tag\" && tags !== undefined && !tags.includes(rule.tag)) {\n throw new Error(`routing policy governance missing tag ${rule.tag}`);\n }\n }\n}\n\nexport function resolveFallbackProvider(\n policy: RoutingPolicy | undefined,\n availableProviders: ProviderType[],\n): ProviderType | null {\n const order = policy?.fallbackOrder;\n if (!order || order.length === 0 || availableProviders.length === 0) {\n return null;\n }\n const available = new Set(availableProviders);\n for (const candidate of order) {\n if (available.has(candidate)) {\n return candidate;\n }\n }\n return null;\n}\n\nexport function resolveRoutingTarget(\n policy: RoutingPolicy | undefined,\n provider: ProviderType,\n model: string,\n options: ResolveRoutingTargetOptions = {},\n): ResolvedRoutingTarget {\n const governanceTags = options.governanceTags;\n if (options.estimatedCostUsd !== undefined) {\n enforceRoutingCostLimit(policy, options.estimatedCostUsd);\n }\n if (options.currentRequestsPerMinute !== undefined) {\n enforceRoutingRateLimit(policy, options.currentRequestsPerMinute);\n }\n\n const candidates = policy?.aliases?.[model];\n if (candidates && candidates.length > 0) {\n const sorted = [...candidates].sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));\n const availableProviders = options.availableProviders;\n if (!availableProviders || availableProviders.length === 0) {\n enforceRoutingGovernance(policy, sorted[0].provider, governanceTags);\n return {\n provider: sorted[0].provider,\n model: sorted[0].model,\n selectedBy: `alias:${model}`,\n };\n }\n const available = new Set(availableProviders);\n const availableCandidate = sorted.find((candidate) => available.has(candidate.provider));\n if (availableCandidate) {\n enforceRoutingGovernance(policy, availableCandidate.provider, governanceTags);\n return {\n provider: availableCandidate.provider,\n model: availableCandidate.model,\n selectedBy: `alias:${model}`,\n };\n }\n }\n\n const fallback = resolveFallbackProvider(policy, options.availableProviders ?? []);\n if (fallback && fallback !== provider) {\n enforceRoutingGovernance(policy, fallback, governanceTags);\n return { provider: fallback, model, selectedBy: `fallback:${fallback}` };\n }\n\n enforceRoutingGovernance(policy, provider, governanceTags);\n return { provider, model, selectedBy: \"direct\" };\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 * Typed Tool System — define tools with inline execute callbacks.\n *\n * Quick start:\n * const weather = tool({\n * name: \"get_weather\",\n * description: \"Get current weather for a city\",\n * parameters: { city: { type: \"string\", description: \"City name\" } },\n * execute: async ({ city }) => ({ temp: 72, unit: \"F\", city }),\n * });\n * agent.addTools([weather]);\n *\n * The tool() helper creates a TypedToolDef that the agent auto-wires\n * into a ToolExecutor when it detects typed tools with execute callbacks.\n *\n * @since 1.2.0\n */\n\nimport type { ToolDef, ToolExecutor } from \"./types.js\";\n\n// ─── Typed Tool Interface ────────────────────────────────────────────\n\n/**\n * A tool definition with a typed execute callback.\n *\n * @typeParam TParams - The shape of the tool's input parameters.\n * @typeParam TResult - The shape of the tool's return value.\n */\nexport interface TypedToolDef<TParams = Record<string, unknown>, TResult = unknown> extends ToolDef {\n /** The function to execute when the LLM invokes this tool. */\n execute: (params: TParams) => Promise<TResult> | TResult;\n}\n\n// ─── tool() Helper ──────────────────────────────────────────────────\n\n/**\n * Create a typed tool with an inline execute callback.\n *\n * @description Defines a tool that the agent can invoke during the agentic loop.\n * When the LLM calls this tool, the `execute` callback is automatically invoked\n * with the parsed parameters and the return value is sent back to the model.\n *\n * @param config - Tool configuration with name, description, parameters schema, and execute callback.\n * @returns A {@link TypedToolDef} that can be passed to `agent.addTool()` or `agent.addTools()`.\n *\n * @example\n * ```ts\n * const calculator = tool({\n * name: \"calculate\",\n * description: \"Evaluate a math expression\",\n * parameters: {\n * expression: { type: \"string\", description: \"Math expression to evaluate\" },\n * },\n * execute: async ({ expression }) => {\n * return { result: eval(expression) };\n * },\n * });\n *\n * const agent = new Agent({ instructions: \"You can do math.\" });\n * agent.addTools([calculator]);\n * const result = await agent.run(\"What is 2+2?\");\n * ```\n *\n * @since 1.2.0\n */\nexport function tool<TParams = Record<string, unknown>, TResult = unknown>(config: {\n name: string;\n description: string;\n parameters?: Record<string, unknown>;\n execute: (params: TParams) => Promise<TResult> | TResult;\n}): TypedToolDef<TParams, TResult> {\n return {\n name: config.name,\n description: config.description,\n parameters: config.parameters,\n execute: config.execute,\n };\n}\n\n// ─── Tool Executor Builder ──────────────────────────────────────────\n\n/**\n * Check if a tool definition has an execute callback (is a TypedToolDef).\n */\nexport function isTypedTool(t: ToolDef): t is TypedToolDef {\n return typeof (t as TypedToolDef).execute === \"function\";\n}\n\n/**\n * Build a {@link ToolExecutor} from an array of typed tools.\n *\n * @description Creates a single async function that dispatches tool calls\n * to the correct typed tool's execute callback based on the tool name.\n *\n * @param tools - Array of typed tool definitions with execute callbacks.\n * @param fallback - Optional fallback executor for tools without execute callbacks.\n * @returns A {@link ToolExecutor} that can be passed to `agent.runWithTools()`.\n *\n * @since 1.2.0\n */\nexport function createToolExecutor(\n tools: TypedToolDef<any, any>[],\n fallback?: ToolExecutor\n): ToolExecutor {\n const toolMap = new Map(tools.map(t => [t.name, t]));\n\n return async (callJson: string): Promise<string> => {\n let call: { tool?: string; name?: string; args?: unknown; arguments?: unknown };\n try {\n call = JSON.parse(callJson);\n } catch {\n return JSON.stringify({ error: \"Invalid tool call JSON\" });\n }\n\n const toolName = call.tool ?? call.name ?? \"\";\n const toolDef = toolMap.get(toolName);\n\n if (!toolDef) {\n if (fallback) return fallback(callJson);\n return JSON.stringify({ error: `Unknown tool: ${toolName}` });\n }\n\n try {\n const params = (call.args ?? call.arguments ?? {}) as Record<string, unknown>;\n const result = await toolDef.execute(params);\n return typeof result === \"string\" ? result : JSON.stringify(result);\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : String(err);\n return JSON.stringify({ error: `Tool \"${toolName}\" failed: ${message}` });\n }\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-nap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M,CACzB,CACF","names":["agent_exports","__export","Agent","AgentStream","availableRuntimes","batch","executeCode","gauss","generateImage","__toCommonJS","import_gauss_napi","GaussError","code","message","DisposedError","resourceType","resourceName","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","enforceRoutingCostLimit","policy","costUsd","enforceRoutingRateLimit","requestsPerMinute","enforceRoutingGovernance","provider","tags","rules","allow","rule","resolveFallbackProvider","availableProviders","order","available","candidate","resolveRoutingTarget","model","options","governanceTags","candidates","sorted","a","b","availableCandidate","fallback","import_gauss_napi","toSdkResult","raw","c","AgentStream","agentName","providerHandle","tools","messages","options","toolExecutor","buffer","resolve","done","onEvent","json","runPromise","r","tool","config","isTypedTool","t","createToolExecutor","tools","fallback","toolMap","callJson","call","toolName","toolDef","params","result","err","message","toSdkResult","raw","c","Agent","_Agent","config","detected","detectProvider","requestedProvider","requestedModel","OPENAI_DEFAULT","resolved","resolveRoutingTarget","apiKey","resolveApiKey","ceOpt","codeExecution","tool","tools","name","description","execute","parameters","options","model","context","chain","memory","sessionId","client","input","messages","recalled","e","toolDefs","executor","result","userText","m","toolExecutor","typedExecutor","composedExecutor","callJson","onEvent","finalExecutor","NOOP_TOOL_EXECUTOR","AgentStream","onDelta","stream","aggregated","event","delta","DisposedError","typedTools","isTypedTool","t","createToolExecutor","mcpTool","params","resultJson","gauss","prompt","agent","batch","prompts","config","concurrency","agentConfig","items","input","agent","Agent","queue","workers","entry","idx","item","err","import_gauss_napi","import_gauss_napi","executeCode","language","code","options","availableRuntimes","generateImage","prompt","detected","detectProvider","providerType","model","apiKey","resolveApiKey","handle"]}
1
+ {"version":3,"sources":["../src/agent.ts","../src/sdk/agent.ts","../src/sdk/errors.ts","../src/sdk/models.ts","../src/sdk/types.ts","../src/sdk/routing-policy.ts","../src/sdk/stream-iter.ts","../src/sdk/tool.ts","../src/sdk/batch.ts","../src/sdk/code-execution.ts"],"sourcesContent":["export { Agent, gauss } from \"./sdk/agent.js\";\nexport type { AgentConfig } from \"./sdk/agent.js\";\nexport { AgentStream } from \"./sdk/stream-iter.js\";\nexport type { StreamEvent } from \"./sdk/stream-iter.js\";\nexport { batch } from \"./sdk/batch.js\";\nexport type { BatchItem } from \"./sdk/batch.js\";\nexport { executeCode, availableRuntimes, generateImage, version } from \"./sdk/code-execution.js\";\n","/**\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 MemoryEntry,\n GroundingMetadata,\n} from \"./types.js\";\n\nimport { DisposedError } from \"./errors.js\";\n\nimport { resolveApiKey, detectProvider } from \"./types.js\";\nimport { OPENAI_DEFAULT } from \"./models.js\";\nimport type { ResolveRoutingTargetOptions, RoutingPolicy } from \"./routing-policy.js\";\nimport { resolveRoutingTarget } from \"./routing-policy.js\";\nimport { AgentStream } from \"./stream-iter.js\";\nimport { tool as toolFn, isTypedTool, createToolExecutor, type TypedToolDef } from \"./tool.js\";\nimport type { MiddlewareChain } from \"./middleware.js\";\nimport type { GuardrailChain } from \"./guardrail.js\";\nimport type { Memory } from \"./memory.js\";\nimport type { McpClient } from \"./mcp-client.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 */\ninterface RawNapiResult {\n text: string;\n steps: number;\n inputTokens: number;\n outputTokens: number;\n messages?: Message[];\n tool_calls?: Array<{ name: string; arguments: Record<string, unknown> }>;\n thinking?: string;\n structuredOutput?: Record<string, unknown>;\n groundingMetadata?: GroundingMetadata[];\n citations?: Array<{\n citationType?: string;\n type?: string;\n citedText?: string;\n documentTitle?: string;\n start?: number;\n end?: number;\n }>;\n}\n\nfunction toSdkResult(raw: RawNapiResult): AgentResult {\n return {\n ...raw,\n citations: raw.citations?.map((c) => ({\n type: c.citationType ?? c.type ?? \"unknown\",\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 /** Optional alias/fallback routing policy for model selection. */\n routingPolicy?: RoutingPolicy;\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. Accepts both raw ToolDef and typed tools with execute callbacks. */\n tools?: (ToolDef | TypedToolDef)[];\n\n /** Middleware chain to apply (logging, caching, rate limiting). */\n middleware?: MiddlewareChain;\n\n /** Guardrail chain to apply (PII, content moderation, schema validation). */\n guardrails?: GuardrailChain;\n\n /** Memory instance for automatic conversation history. */\n memory?: Memory;\n\n /** Session ID for memory scoping (default: auto-generated). */\n sessionId?: string;\n\n /** MCP clients to consume tools from external MCP servers. */\n mcpClients?: McpClient[];\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 _requestedProvider: ProviderType;\n private readonly _requestedModel: string;\n private readonly _provider: ProviderType;\n private readonly _model: string;\n private readonly _routingPolicy: RoutingPolicy | undefined;\n private readonly _providerOptions: ProviderOptions & { apiKey: string };\n private readonly _instructions: string;\n private _tools: (ToolDef | TypedToolDef)[] = [];\n private _options: AgentOptions = {};\n private disposed = false;\n\n // ─── Integration Glue (M35) ──────────────────────────────────────\n private _middleware: MiddlewareChain | null = null;\n private _guardrails: GuardrailChain | null = null;\n private _memory: Memory | null = null;\n private _sessionId: string = \"\";\n private _mcpClients: McpClient[] = [];\n private _mcpToolsLoaded = 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 const requestedProvider = config.provider ?? detected?.provider ?? \"openai\";\n const requestedModel = config.model ?? detected?.model ?? OPENAI_DEFAULT;\n this._requestedProvider = requestedProvider;\n this._requestedModel = requestedModel;\n this._routingPolicy = config.routingPolicy;\n const resolved = resolveRoutingTarget(this._routingPolicy, requestedProvider, requestedModel);\n this._provider = resolved.provider;\n this._model = resolved.model;\n this._name = config.name ?? \"agent\";\n this._instructions = config.instructions ?? \"\";\n\n const apiKey =\n config.providerOptions?.apiKey ?? resolveApiKey(this._provider);\n this._providerOptions = {\n apiKey,\n ...config.providerOptions,\n } as ProviderOptions & { apiKey: string };\n this.providerHandle = create_provider(this._provider, this._model, this._providerOptions);\n\n if (config.tools) this._tools = [...config.tools];\n\n // Integration glue (M35)\n if (config.middleware) this._middleware = config.middleware;\n if (config.guardrails) this._guardrails = config.guardrails;\n if (config.memory) this._memory = config.memory;\n if (config.sessionId) this._sessionId = config.sessionId;\n if (config.mcpClients) this._mcpClients = [...config.mcpClients];\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 /**\n * Create an agent using provider/model auto-detection from environment variables.\n *\n * @description Equivalent to `new Agent(config)`, but clearer in intent for env-driven setup.\n *\n * @param config - Optional partial configuration overrides.\n * @returns A new {@link Agent} instance.\n *\n * @example\n * ```ts\n * const agent = Agent.fromEnv({ instructions: \"Be concise.\" });\n * ```\n */\n static fromEnv(config: AgentConfig = {}): Agent {\n return new Agent(config);\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 | TypedToolDef): 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 | TypedToolDef)[]): this {\n this._tools.push(...tools);\n return this;\n }\n\n /**\n * Inline tool shortcut — define and attach a tool in one step.\n *\n * @example\n * ```ts\n * const result = await agent\n * .withTool(\"get_weather\", \"Get weather for a city\", async ({ city }) => ({ temp: 72 }))\n * .run(\"Weather in Paris?\");\n * ```\n */\n withTool<TParams = Record<string, unknown>, TResult = unknown>(\n name: string,\n description: string,\n execute: (params: TParams) => TResult | Promise<TResult>,\n parameters?: Record<string, unknown>\n ): this {\n this._tools.push(toolFn({ name, description, parameters: parameters ?? {}, execute }));\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 /**\n * Clone this agent with a different model.\n *\n * @description Returns a **new** agent instance preserving tools and integrations,\n * but using the provided model identifier.\n *\n * @param model - Target model identifier.\n * @returns A new {@link Agent} configured with the selected model.\n */\n withModel(model: string): Agent {\n this.assertNotDisposed();\n return new Agent({\n ...this.toConfig(),\n model,\n });\n }\n\n /**\n * Clone this agent and resolve a routing decision using runtime context.\n *\n * @param context - Runtime routing context (availability, budget, rate).\n * @returns A new {@link Agent} routed according to current policy + context.\n */\n withRoutingContext(context: ResolveRoutingTargetOptions): Agent {\n this.assertNotDisposed();\n const resolved = resolveRoutingTarget(\n this._routingPolicy,\n this._requestedProvider,\n this._requestedModel,\n context,\n );\n return new Agent({\n ...this.toConfig(),\n provider: resolved.provider,\n model: resolved.model,\n });\n }\n\n // ─── Integration Glue (M35) ────────────────────────────────────\n\n /**\n * Attach a middleware chain (logging, caching, rate limiting). Chainable.\n *\n * @param chain - A configured {@link MiddlewareChain} instance.\n * @returns `this` for fluent chaining.\n *\n * @example\n * ```ts\n * agent.withMiddleware(\n * new MiddlewareChain().useLogging().useCaching(60000).useRateLimit(100)\n * );\n * ```\n *\n * @since 1.2.0\n */\n withMiddleware(chain: MiddlewareChain): this {\n this._middleware = chain;\n return this;\n }\n\n /**\n * Attach a guardrail chain (content moderation, PII, schema validation). Chainable.\n *\n * @param chain - A configured {@link GuardrailChain} instance.\n * @returns `this` for fluent chaining.\n *\n * @example\n * ```ts\n * agent.withGuardrails(\n * new GuardrailChain().addPiiDetection(\"redact\").addContentModeration([\"violence\"], [])\n * );\n * ```\n *\n * @since 1.2.0\n */\n withGuardrails(chain: GuardrailChain): this {\n this._guardrails = chain;\n return this;\n }\n\n /**\n * Attach memory for automatic conversation history. Chainable.\n *\n * @description When memory is attached, the agent automatically:\n * - Recalls recent entries before each run (prepended as context)\n * - Stores the conversation (input + output) after each run\n *\n * @param memory - A {@link Memory} instance.\n * @param sessionId - Optional session ID for scoping memory entries.\n * @returns `this` for fluent chaining.\n *\n * @example\n * ```ts\n * const memory = new Memory();\n * agent.withMemory(memory, \"session-123\");\n * await agent.run(\"Hello!\"); // stored in memory\n * await agent.run(\"What did I just say?\"); // recalls previous context\n * ```\n *\n * @since 1.2.0\n */\n withMemory(memory: Memory, sessionId?: string): this {\n this._memory = memory;\n if (sessionId) this._sessionId = sessionId;\n return this;\n }\n\n /**\n * Consume tools from an external MCP server. Chainable.\n *\n * @description Registers an MCP client whose tools will be loaded\n * and made available to the agent on the first run.\n *\n * @param client - A connected {@link McpClient} instance.\n * @returns `this` for fluent chaining.\n *\n * @example\n * ```ts\n * const mcp = new McpClient({ command: \"npx\", args: [\"-y\", \"@mcp/server-fs\"] });\n * await mcp.connect();\n * agent.useMcpServer(mcp);\n * ```\n *\n * @since 1.2.0\n */\n useMcpServer(client: McpClient): this {\n this._mcpClients.push(client);\n this._mcpToolsLoaded = false;\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\n // Load MCP tools if needed\n await this.ensureMcpTools();\n\n let messages = typeof input === \"string\"\n ? [{ role: \"user\" as const, content: input }]\n : [...input];\n\n // Memory recall: inject context\n if (this._memory) {\n const recalled = await this._memory.recall(\n this._sessionId ? { sessionId: this._sessionId } : undefined\n );\n if (recalled.length > 0) {\n const contextText = recalled.map(e => e.content).join(\"\\n\");\n messages = [\n { role: \"system\" as const, content: `Previous context:\\n${contextText}` },\n ...messages,\n ];\n }\n }\n\n // Extract tool definitions (strip execute callbacks for NAPI)\n const { toolDefs, executor } = this.resolveToolsAndExecutor();\n\n let result: AgentResult;\n if (executor) {\n result = toSdkResult(await agent_run_with_tool_executor(\n this._name,\n this.providerHandle,\n toolDefs,\n messages,\n this._options,\n executor\n ));\n } else {\n result = toSdkResult(await agent_run(\n this._name,\n this.providerHandle,\n toolDefs,\n messages,\n this._options\n ));\n }\n\n // Memory store: save conversation\n if (this._memory) {\n const userText = typeof input === \"string\" ? input : input.map(m => m.content).join(\"\\n\");\n await this._memory.store({\n id: `${Date.now()}-user`,\n content: userText,\n entryType: \"conversation\",\n timestamp: new Date().toISOString(),\n sessionId: this._sessionId || undefined,\n });\n await this._memory.store({\n id: `${Date.now()}-assistant`,\n content: result.text,\n entryType: \"conversation\",\n timestamp: new Date().toISOString(),\n sessionId: this._sessionId || undefined,\n });\n }\n\n return result;\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\n await this.ensureMcpTools();\n\n const messages = typeof input === \"string\"\n ? [{ role: \"user\" as const, content: input }]\n : input;\n\n const { toolDefs, executor: typedExecutor } = this.resolveToolsAndExecutor();\n\n // Compose typed tool executor with user-provided executor\n const composedExecutor: ToolExecutor = async (callJson: string) => {\n // Try typed tools first, then fall back to user executor\n if (typedExecutor) {\n const result = await typedExecutor(callJson);\n const parsed = JSON.parse(result);\n if (!parsed.error?.startsWith(\"Unknown tool:\")) return result;\n }\n return toolExecutor(callJson);\n };\n\n return toSdkResult(await agent_run_with_tool_executor(\n this._name,\n this.providerHandle,\n toolDefs,\n messages,\n this._options,\n composedExecutor\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\n await this.ensureMcpTools();\n\n const messages = typeof input === \"string\"\n ? [{ role: \"user\" as const, content: input }]\n : input;\n\n const { toolDefs, executor: typedExecutor } = this.resolveToolsAndExecutor();\n const finalExecutor = toolExecutor ?? typedExecutor ?? NOOP_TOOL_EXECUTOR;\n\n return toSdkResult(await agent_stream_with_tool_executor(\n this._name,\n this.providerHandle,\n toolDefs,\n messages,\n this._options,\n onEvent,\n finalExecutor\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\n const { toolDefs, executor: typedExecutor } = this.resolveToolsAndExecutor();\n const finalExecutor = toolExecutor ?? typedExecutor ?? NOOP_TOOL_EXECUTOR;\n\n return new AgentStream(\n this._name,\n this.providerHandle,\n toolDefs,\n messages,\n this._options,\n finalExecutor\n );\n }\n\n /**\n * Stream only text deltas with a tiny DX helper.\n *\n * @description Aggregates all streamed text deltas into a final string and optionally\n * invokes `onDelta` for each chunk as it arrives.\n *\n * @param input - A string prompt or an array of {@link Message} objects.\n * @param onDelta - Optional callback invoked for each text delta.\n * @param toolExecutor - Optional async callback for handling tool invocations.\n * @returns The final response text.\n */\n async streamText(\n input: string | Message[],\n onDelta?: (delta: string) => void,\n toolExecutor?: ToolExecutor\n ): Promise<string> {\n this.assertNotDisposed();\n const stream = this.streamIter(input, toolExecutor);\n let aggregated = \"\";\n\n for await (const event of stream) {\n if (event.type !== \"text_delta\") continue;\n const delta = typeof event.text === \"string\"\n ? event.text\n : (typeof event.delta === \"string\" ? event.delta : \"\");\n if (!delta) continue;\n aggregated += delta;\n onDelta?.(delta);\n }\n\n return stream.result?.text ?? aggregated;\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 // Close MCP clients\n for (const client of this._mcpClients) {\n try { client.close(); } catch { /* ignore */ }\n }\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 DisposedError(\"Agent\", this._name);\n }\n }\n\n /**\n * Resolve typed tools into plain ToolDefs + a ToolExecutor.\n * @internal\n */\n private resolveToolsAndExecutor(): { toolDefs: ToolDef[]; executor: ToolExecutor | null } {\n const typedTools = this._tools.filter(isTypedTool);\n\n // Strip execute callbacks for the NAPI layer\n const toolDefs: ToolDef[] = this._tools.map(t => ({\n name: t.name,\n description: t.description,\n parameters: t.parameters,\n }));\n\n const executor = typedTools.length > 0\n ? createToolExecutor(typedTools)\n : null;\n\n return { toolDefs, executor };\n }\n\n /**\n * Load tools from all connected MCP clients (lazy, once).\n * @internal\n */\n private async ensureMcpTools(): Promise<void> {\n if (this._mcpToolsLoaded || this._mcpClients.length === 0) return;\n\n for (const client of this._mcpClients) {\n const { tools, executor } = await client.getToolsWithExecutor();\n // Add MCP tools as typed tools with the MCP executor as their execute callback\n for (const t of tools) {\n const mcpTool: TypedToolDef = {\n ...t,\n execute: async (params: Record<string, unknown>) => {\n const callJson = JSON.stringify({ tool: t.name, args: params });\n const resultJson = await executor(callJson);\n return JSON.parse(resultJson);\n },\n };\n this._tools.push(mcpTool);\n }\n }\n\n this._mcpToolsLoaded = true;\n }\n\n /** Snapshot current agent configuration for cloning helpers. */\n private toConfig(): AgentConfig {\n return {\n name: this._name,\n provider: this._requestedProvider,\n model: this._requestedModel,\n routingPolicy: this._routingPolicy,\n providerOptions: { ...this._providerOptions },\n instructions: this._instructions || undefined,\n tools: [...this._tools],\n middleware: this._middleware ?? undefined,\n guardrails: this._guardrails ?? undefined,\n memory: this._memory ?? undefined,\n sessionId: this._sessionId || undefined,\n mcpClients: [...this._mcpClients],\n temperature: this._options.temperature,\n maxSteps: this._options.maxSteps,\n topP: this._options.topP,\n maxTokens: this._options.maxTokens,\n seed: this._options.seed,\n stopOnTool: this._options.stopOnTool,\n outputSchema: this._options.outputSchema,\n thinkingBudget: this._options.thinkingBudget,\n reasoningEffort: this._options.reasoningEffort,\n cacheControl: this._options.cacheControl,\n codeExecution: this._options.codeExecution,\n grounding: this._options.grounding,\n nativeCodeExecution: this._options.nativeCodeExecution,\n responseModalities: this._options.responseModalities,\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 * Structured error hierarchy for Gauss SDK.\n *\n * All Gauss errors extend {@link GaussError} to enable type-safe catch blocks:\n *\n * ```ts\n * try {\n * await agent.run(\"hello\");\n * } catch (e) {\n * if (e instanceof AgentDisposedError) { ... }\n * if (e instanceof ProviderError) { ... }\n * }\n * ```\n *\n * @module errors\n * @since 2.1.0\n */\n\n/** Base error for all Gauss SDK errors. Includes an error code for programmatic matching. */\nexport class GaussError extends Error {\n readonly code: string;\n constructor(code: string, message: string) {\n super(message);\n this.name = \"GaussError\";\n this.code = code;\n }\n}\n\n/** Thrown when an operation is attempted on a destroyed Agent/Team/Graph. */\nexport class DisposedError extends GaussError {\n readonly resourceType: string;\n readonly resourceName: string;\n constructor(resourceType: string, resourceName: string) {\n super(\"RESOURCE_DISPOSED\", `${resourceType} \"${resourceName}\" has been destroyed. Create a new instance.`);\n this.name = \"DisposedError\";\n this.resourceType = resourceType;\n this.resourceName = resourceName;\n }\n}\n\n/** Thrown when provider initialization or communication fails. */\nexport class ProviderError extends GaussError {\n readonly provider: string;\n constructor(provider: string, message: string) {\n super(\"PROVIDER_ERROR\", `[${provider}] ${message}`);\n this.name = \"ProviderError\";\n this.provider = provider;\n }\n}\n\n/** Thrown when tool execution fails. */\nexport class ToolExecutionError extends GaussError {\n readonly toolName: string;\n readonly cause?: Error;\n constructor(toolName: string, message: string, cause?: Error) {\n super(\"TOOL_EXECUTION_ERROR\", `Tool \"${toolName}\" failed: ${message}`);\n this.name = \"ToolExecutionError\";\n this.toolName = toolName;\n this.cause = cause;\n }\n}\n\n/** Thrown when configuration validation fails. */\nexport class ValidationError extends GaussError {\n readonly field?: string;\n constructor(message: string, field?: string) {\n super(\"VALIDATION_ERROR\", field ? `Invalid \"${field}\": ${message}` : message);\n this.name = \"ValidationError\";\n this.field = field;\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","import type { ProviderType } from \"./types.js\";\n\nexport interface RoutingCandidate {\n provider: ProviderType;\n model: string;\n priority?: number;\n maxCostUsd?: number;\n}\n\nexport type GovernanceRule =\n | { type: \"require_tag\"; tag: string }\n | { type: \"deny_provider\"; provider: ProviderType }\n | { type: \"allow_provider\"; provider: ProviderType };\n\nexport interface GovernancePolicyPack {\n rules: GovernanceRule[];\n}\n\nexport interface RoutingPolicy {\n aliases?: Record<string, RoutingCandidate[]>;\n fallbackOrder?: ProviderType[];\n maxTotalCostUsd?: number;\n maxRequestsPerMinute?: number;\n governance?: GovernancePolicyPack;\n}\n\nexport interface ResolvedRoutingTarget {\n provider: ProviderType;\n model: string;\n selectedBy: \"direct\" | `alias:${string}` | `fallback:${ProviderType}`;\n}\n\nexport interface ResolveRoutingTargetOptions {\n availableProviders?: ProviderType[];\n estimatedCostUsd?: number;\n currentRequestsPerMinute?: number;\n governanceTags?: string[];\n}\n\nexport function enforceRoutingCostLimit(\n policy: RoutingPolicy | undefined,\n costUsd: number,\n): void {\n if (policy?.maxTotalCostUsd !== undefined && costUsd > policy.maxTotalCostUsd) {\n throw new Error(`routing policy rejected cost ${costUsd}`);\n }\n}\n\nexport function enforceRoutingRateLimit(\n policy: RoutingPolicy | undefined,\n requestsPerMinute: number,\n): void {\n if (\n policy?.maxRequestsPerMinute !== undefined &&\n requestsPerMinute > policy.maxRequestsPerMinute\n ) {\n throw new Error(`routing policy rejected rate ${requestsPerMinute}`);\n }\n}\n\nexport function enforceRoutingGovernance(\n policy: RoutingPolicy | undefined,\n provider: ProviderType,\n tags?: string[],\n): void {\n const rules = policy?.governance?.rules ?? [];\n if (rules.length === 0) return;\n const allow = rules\n .filter((rule): rule is Extract<GovernanceRule, { type: \"allow_provider\" }> => rule.type === \"allow_provider\")\n .map((rule) => rule.provider);\n if (allow.length > 0 && !allow.includes(provider)) {\n throw new Error(`routing policy governance rejected provider ${provider}`);\n }\n for (const rule of rules) {\n if (rule.type === \"deny_provider\" && rule.provider === provider) {\n throw new Error(`routing policy governance rejected provider ${provider}`);\n }\n if (rule.type === \"require_tag\" && tags !== undefined && !tags.includes(rule.tag)) {\n throw new Error(`routing policy governance missing tag ${rule.tag}`);\n }\n }\n}\n\nexport function resolveFallbackProvider(\n policy: RoutingPolicy | undefined,\n availableProviders: ProviderType[],\n): ProviderType | null {\n const order = policy?.fallbackOrder;\n if (!order || order.length === 0 || availableProviders.length === 0) {\n return null;\n }\n const available = new Set(availableProviders);\n for (const candidate of order) {\n if (available.has(candidate)) {\n return candidate;\n }\n }\n return null;\n}\n\nexport function resolveRoutingTarget(\n policy: RoutingPolicy | undefined,\n provider: ProviderType,\n model: string,\n options: ResolveRoutingTargetOptions = {},\n): ResolvedRoutingTarget {\n const governanceTags = options.governanceTags;\n if (options.estimatedCostUsd !== undefined) {\n enforceRoutingCostLimit(policy, options.estimatedCostUsd);\n }\n if (options.currentRequestsPerMinute !== undefined) {\n enforceRoutingRateLimit(policy, options.currentRequestsPerMinute);\n }\n\n const candidates = policy?.aliases?.[model];\n if (candidates && candidates.length > 0) {\n const sorted = [...candidates].sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));\n const availableProviders = options.availableProviders;\n if (!availableProviders || availableProviders.length === 0) {\n enforceRoutingGovernance(policy, sorted[0].provider, governanceTags);\n return {\n provider: sorted[0].provider,\n model: sorted[0].model,\n selectedBy: `alias:${model}`,\n };\n }\n const available = new Set(availableProviders);\n const availableCandidate = sorted.find((candidate) => available.has(candidate.provider));\n if (availableCandidate) {\n enforceRoutingGovernance(policy, availableCandidate.provider, governanceTags);\n return {\n provider: availableCandidate.provider,\n model: availableCandidate.model,\n selectedBy: `alias:${model}`,\n };\n }\n }\n\n const fallback = resolveFallbackProvider(policy, options.availableProviders ?? []);\n if (fallback && fallback !== provider) {\n enforceRoutingGovernance(policy, fallback, governanceTags);\n return { provider: fallback, model, selectedBy: `fallback:${fallback}` };\n }\n\n enforceRoutingGovernance(policy, provider, governanceTags);\n return { provider, model, selectedBy: \"direct\" };\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: any) => {\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 * Typed Tool System — define tools with inline execute callbacks.\n *\n * Quick start:\n * const weather = tool({\n * name: \"get_weather\",\n * description: \"Get current weather for a city\",\n * parameters: { city: { type: \"string\", description: \"City name\" } },\n * execute: async ({ city }) => ({ temp: 72, unit: \"F\", city }),\n * });\n * agent.addTools([weather]);\n *\n * The tool() helper creates a TypedToolDef that the agent auto-wires\n * into a ToolExecutor when it detects typed tools with execute callbacks.\n *\n * @since 1.2.0\n */\n\nimport type { ToolDef, ToolExecutor } from \"./types.js\";\n\n// ─── Typed Tool Interface ────────────────────────────────────────────\n\n/**\n * A tool definition with a typed execute callback.\n *\n * @typeParam TParams - The shape of the tool's input parameters.\n * @typeParam TResult - The shape of the tool's return value.\n */\nexport interface TypedToolDef<TParams = Record<string, unknown>, TResult = unknown> extends ToolDef {\n /** The function to execute when the LLM invokes this tool. */\n execute: (params: TParams) => Promise<TResult> | TResult;\n}\n\n// ─── tool() Helper ──────────────────────────────────────────────────\n\n/**\n * Create a typed tool with an inline execute callback.\n *\n * @description Defines a tool that the agent can invoke during the agentic loop.\n * When the LLM calls this tool, the `execute` callback is automatically invoked\n * with the parsed parameters and the return value is sent back to the model.\n *\n * @param config - Tool configuration with name, description, parameters schema, and execute callback.\n * @returns A {@link TypedToolDef} that can be passed to `agent.addTool()` or `agent.addTools()`.\n *\n * @example\n * ```ts\n * const calculator = tool({\n * name: \"calculate\",\n * description: \"Evaluate a math expression\",\n * parameters: {\n * expression: { type: \"string\", description: \"Math expression to evaluate\" },\n * },\n * execute: async ({ expression }) => {\n * return { result: eval(expression) };\n * },\n * });\n *\n * const agent = new Agent({ instructions: \"You can do math.\" });\n * agent.addTools([calculator]);\n * const result = await agent.run(\"What is 2+2?\");\n * ```\n *\n * @since 1.2.0\n */\nexport function tool<TParams = Record<string, unknown>, TResult = unknown>(config: {\n name: string;\n description: string;\n parameters?: Record<string, unknown>;\n execute: (params: TParams) => Promise<TResult> | TResult;\n}): TypedToolDef<TParams, TResult> {\n return {\n name: config.name,\n description: config.description,\n parameters: config.parameters,\n execute: config.execute,\n };\n}\n\n// ─── Tool Executor Builder ──────────────────────────────────────────\n\n/**\n * Check if a tool definition has an execute callback (is a TypedToolDef).\n */\nexport function isTypedTool(t: ToolDef): t is TypedToolDef {\n return typeof (t as TypedToolDef).execute === \"function\";\n}\n\n/**\n * Build a {@link ToolExecutor} from an array of typed tools.\n *\n * @description Creates a single async function that dispatches tool calls\n * to the correct typed tool's execute callback based on the tool name.\n *\n * @param tools - Array of typed tool definitions with execute callbacks.\n * @param fallback - Optional fallback executor for tools without execute callbacks.\n * @returns A {@link ToolExecutor} that can be passed to `agent.runWithTools()`.\n *\n * @since 1.2.0\n */\nexport function createToolExecutor(\n tools: TypedToolDef<any, any>[],\n fallback?: ToolExecutor\n): ToolExecutor {\n const toolMap = new Map(tools.map(t => [t.name, t]));\n\n return async (callJson: string): Promise<string> => {\n let call: { tool?: string; name?: string; args?: unknown; arguments?: unknown };\n try {\n call = JSON.parse(callJson);\n } catch {\n return JSON.stringify({ error: \"Invalid tool call JSON\" });\n }\n\n const toolName = call.tool ?? call.name ?? \"\";\n const toolDef = toolMap.get(toolName);\n\n if (!toolDef) {\n if (fallback) return fallback(callJson);\n return JSON.stringify({ error: `Unknown tool: ${toolName}` });\n }\n\n try {\n const params = (call.args ?? call.arguments ?? {}) as Record<string, unknown>;\n const result = await toolDef.execute(params);\n return typeof result === \"string\" ? result : JSON.stringify(result);\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : String(err);\n return JSON.stringify({ error: `Tool \"${toolName}\" failed: ${message}` });\n }\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":"yaAAA,IAAAA,GAAA,GAAAC,EAAAD,GAAA,WAAA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ss","generateImage","__toCommonJS","import_gauss_napi","GaussError","code","message","DisposedError","resourceType","resourceName","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","enforceRoutingCostLimit","policy","costUsd","enforceRoutingRateLimit","requestsPerMinute","enforceRoutingGovernance","provider","tags","rules","allow","rule","resolveFallbackProvider","availableProviders","order","available","candidate","resolveRoutingTarget","model","options","governanceTags","candidates","sorted","a","b","availableCandidate","fallback","import_gauss_napi","toSdkResult","raw","c","AgentStream","agentName","providerHandle","tools","messages","options","toolExecutor","buffer","resolve","done","onEvent","json","runPromise","r","tool","config","isTypedTool","t","createToolExecutor","tools","fallback","toolMap","callJson","call","toolName","toolDef","params","result","err","message","toSdkResult","raw","c","Agent","_Agent","config","detected","detectProvider","requestedProvider","requestedModel","OPENAI_DEFAULT","resolved","resolveRoutingTarget","apiKey","resolveApiKey","ceOpt","codeExecution","tool","tools","name","description","execute","parameters","options","model","context","chain","memory","sessionId","client","input","messages","recalled","e","toolDefs","executor","result","userText","m","toolExecutor","typedExecutor","composedExecutor","callJson","onEvent","finalExecutor","NOOP_TOOL_EXECUTOR","AgentStream","onDelta","stream","aggregated","event","delta","DisposedError","typedTools","isTypedTool","t","createToolExecutor","mcpTool","params","resultJson","gauss","prompt","agent","batch","prompts","config","concurrency","agentConfig","items","input","agent","Agent","queue","workers","entry","idx","item","err","import_gauss_napi","import_gauss_napi","executeCode","language","code","options","availableRuntimes","generateImage","prompt","detected","detectProvider","providerType","model","apiKey","resolveApiKey","handle"]}