@agtlantis/core 0.4.1

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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors/utils.ts","../src/errors/types.ts","../src/execution/constants.ts","../src/execution/utils.ts","../src/execution/shared.ts","../src/execution/streaming-host.ts","../src/execution/simple-host.ts","../src/execution/mapping.ts","../src/observability/logger.ts","../src/patterns/progressive/progressive-pattern.ts","../src/pricing/validator.ts","../src/pricing/defaults.ts","../src/pricing/config.ts","../src/pricing/calculator.ts","../src/prompt/errors.ts","../src/prompt/template.ts","../src/prompt/prompt-template.ts","../src/prompt/file-prompt-repository.ts","../src/provider/types.ts","../src/provider/hash.ts","../src/provider/file-cache.ts","../src/provider/base-provider.ts","../src/provider/noop-file-manager.ts","../src/provider/file-source.ts","../src/provider/google/file-manager.ts","../src/session/usage-extractors.ts","../src/session/types.ts","../src/session/simple-session.ts","../src/session/streaming-session.ts","../src/provider/google/factory.ts","../src/provider/openai/factory.ts","../src/validation/validation-history.ts","../src/validation/errors.ts","../src/validation/with-validation.ts"],"names":["ExecutionErrorCode","ConfigurationErrorCode","FileErrorCode","resolve","hasToolCall","tool","z","globalConfig","PromptErrorCode","path","Handlebars","fs","yaml","createHash","readFile","path3","stat","GoogleGenAI","merge","aiGenerateText","aiStreamText","createGoogleGenerativeAI","createOpenAI","ValidationErrorCode"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAaO,SAAS,WAAA,CAId,KAAA,EACA,UAAA,EACA,OAAA,EACG;AACH,EAAA,MAAM,KAAA,GAAQ,iBAAiB,KAAA,GAAQ,KAAA,GAAQ,IAAI,KAAA,CAAM,MAAA,CAAO,KAAK,CAAC,CAAA;AACtE,EAAA,OAAO,IAAI,WAAW,KAAA,CAAM,OAAA,EAAS,EAAE,GAAG,OAAA,EAAS,OAAO,CAAA;AAC5D;;;ACrBO,IAAK,kBAAA,qBAAA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ACzE,EAAA,MAAM,WAAA,GAAc,IAAA,CAAK,GAAA,CAAI,CAAA,EAAG,UAAU,CAAC,CAAA;AAC3C,EAAA,MAAM,OAAA,GAAU,IAAI,iBAAA,EAA2B;AAE/C,EAAA,OAAO,OAAA,CAAQ,eAAe,WAAA,EAAa;AACzC,IAAA,MAAA,EAAQ,cAAA,EAAe;AAEvB,IAAA,MAAM,MAAA,GAAS,MAAM,OAAA,CAAQ,OAAO,CAAA;AACpC,IAAA,MAAM,UAAA,GAAa,MAAM,QAAA,CAAS,MAAA,EAAQ,OAAO,CAAA;AACjD,IAAA,OAAA,CAAQ,GAAA,CAAI,QAAQ,UAAU,CAAA;AAE9B,IAAA,SAAA,GAAY,QAAQ,IAAK,CAAA;AAEzB,IAAA,IAAI,WAAW,KAAA,EAAO;AACpB,MAAA,OAAO,MAAA;AAAA,IACT;AAEA,IAAA,MAAM,eAAA,GAAkB,QAAQ,WAAA,IAAe,WAAA;AAC/C,IAAA,IAAI,cAAc,eAAA,EAAiB;AACjC,MAAA,MAAM,IAAI,OAAA,CAAQ,CAACpB,aAAY,UAAA,CAAWA,QAAAA,EAAS,UAAU,CAAC,CAAA;AAAA,IAChE;AAAA,EACF;AAEA,EAAA,MAAM,IAAI,wBAAA;AAAA,IACR,CAAA,wBAAA,EAA2B,OAAA,CAAQ,GAAA,CAAI,MAAM,CAAA,SAAA,CAAA;AAAA,IAC7C;AAAA,GACF;AACF","file":"index.cjs","sourcesContent":["import type { AgtlantisError, AgtlantisErrorCode, AgtlantisErrorOptions } from './types';\n\n/**\n * Wraps an unknown error as a specific AgtlantisError subclass.\n * Internal utility - not part of public API.\n *\n * @param error - The unknown error to wrap\n * @param ErrorClass - The error class constructor to use\n * @param options - Error options including code and optional context\n * @returns A new instance of the specified error class\n *\n * @internal\n */\nexport function wrapAsError<\n T extends AgtlantisError<TCode>,\n TCode extends AgtlantisErrorCode\n>(\n error: unknown,\n ErrorClass: new (message: string, options: AgtlantisErrorOptions<TCode>) => T,\n options: { code: TCode; context?: Record<string, unknown> }\n): T {\n const cause = error instanceof Error ? error : new Error(String(error));\n return new ErrorClass(cause.message, { ...options, cause });\n}\n","import { wrapAsError } from './utils';\n\nexport enum ExecutionErrorCode {\n EXECUTION_ERROR = 'EXECUTION_ERROR',\n STREAM_ERROR = 'STREAM_ERROR',\n RESULT_EXTRACTION_ERROR = 'RESULT_EXTRACTION_ERROR',\n CANCELLED = 'CANCELLED',\n VALIDATION_ERROR = 'VALIDATION_ERROR',\n}\n\nexport enum ConfigurationErrorCode {\n CONFIG_ERROR = 'CONFIG_ERROR',\n MISSING_API_KEY = 'MISSING_API_KEY',\n INVALID_CONFIG = 'INVALID_CONFIG',\n MISSING_REQUIRED = 'MISSING_REQUIRED',\n}\n\nexport enum FileErrorCode {\n FILE_ERROR = 'FILE_ERROR',\n UPLOAD_ERROR = 'UPLOAD_ERROR',\n DELETE_ERROR = 'DELETE_ERROR',\n NOT_FOUND = 'NOT_FOUND',\n TOO_LARGE = 'TOO_LARGE',\n UNSUPPORTED_TYPE = 'UNSUPPORTED_TYPE',\n}\n\nexport type AgtlantisErrorCode = ExecutionErrorCode | ConfigurationErrorCode | FileErrorCode;\n\nexport interface AgtlantisErrorOptions<TCode extends AgtlantisErrorCode = AgtlantisErrorCode> {\n code: TCode;\n cause?: Error;\n context?: Record<string, unknown>;\n}\n\nexport interface ErrorOptions<TCode extends AgtlantisErrorCode> {\n code?: TCode;\n cause?: Error;\n context?: Record<string, unknown>;\n}\n\nexport type ExecutionErrorOptions = ErrorOptions<ExecutionErrorCode>;\nexport type ConfigurationErrorOptions = ErrorOptions<ConfigurationErrorCode>;\nexport type FileErrorOptions = ErrorOptions<FileErrorCode>;\n\n/**\n * Base error class for all Agtlantis errors.\n * Provides structured error information including error code and optional context.\n */\nexport class AgtlantisError<TCode extends AgtlantisErrorCode = AgtlantisErrorCode> extends Error {\n readonly code: TCode;\n override readonly cause?: Error;\n readonly context?: Record<string, unknown>;\n\n constructor(message: string, options: AgtlantisErrorOptions<TCode>) {\n super(message);\n this.name = 'AgtlantisError';\n this.code = options.code;\n this.cause = options.cause;\n this.context = options.context;\n\n // V8-specific stack trace capture\n const ErrorWithCapture = Error as typeof Error & {\n captureStackTrace?: (targetObject: object, constructorOpt?: Function) => void;\n };\n ErrorWithCapture.captureStackTrace?.(this, this.constructor);\n }\n\n get isRetryable(): boolean {\n return false;\n }\n\n toJSON(): Record<string, unknown> {\n return {\n name: this.name,\n message: this.message,\n code: this.code,\n isRetryable: this.isRetryable,\n context: this.context,\n cause: this.cause?.message,\n stack: this.stack,\n };\n }\n}\n\n/**\n * Error thrown during agent execution (streaming failures, result extraction, cancellation).\n */\nexport class ExecutionError extends AgtlantisError<ExecutionErrorCode> {\n constructor(message: string, options: ExecutionErrorOptions = {}) {\n super(message, {\n code: options.code ?? ExecutionErrorCode.EXECUTION_ERROR,\n cause: options.cause,\n context: options.context,\n });\n this.name = 'ExecutionError';\n }\n\n static from(\n error: unknown,\n code: ExecutionErrorCode = ExecutionErrorCode.EXECUTION_ERROR,\n context?: Record<string, unknown>\n ): ExecutionError {\n if (error instanceof ExecutionError) {\n return error;\n }\n return wrapAsError(error, ExecutionError, { code, context });\n }\n}\n\n/**\n * Error thrown when configuration is invalid or missing (API keys, model names).\n */\nexport class ConfigurationError extends AgtlantisError<ConfigurationErrorCode> {\n constructor(message: string, options: ConfigurationErrorOptions = {}) {\n super(message, {\n code: options.code ?? ConfigurationErrorCode.CONFIG_ERROR,\n cause: options.cause,\n context: options.context,\n });\n this.name = 'ConfigurationError';\n }\n\n static from(\n error: unknown,\n code: ConfigurationErrorCode = ConfigurationErrorCode.CONFIG_ERROR,\n context?: Record<string, unknown>\n ): ConfigurationError {\n if (error instanceof ConfigurationError) {\n return error;\n }\n return wrapAsError(error, ConfigurationError, { code, context });\n }\n}\n\n/**\n * Error thrown during file operations (upload, delete, not found, size limits).\n */\nexport class FileError extends AgtlantisError<FileErrorCode> {\n constructor(message: string, options: FileErrorOptions = {}) {\n super(message, {\n code: options.code ?? FileErrorCode.FILE_ERROR,\n cause: options.cause,\n context: options.context,\n });\n this.name = 'FileError';\n }\n\n static from(\n error: unknown,\n code: FileErrorCode = FileErrorCode.FILE_ERROR,\n context?: Record<string, unknown>\n ): FileError {\n if (error instanceof FileError) {\n return error;\n }\n return wrapAsError(error, FileError, { code, context });\n }\n}\n","export const ERRORS = {\n ALREADY_CONSUMED: 'Execution already consumed',\n METADATA_NOT_AVAILABLE:\n 'Metadata not available yet. Consume the execution first.',\n NO_RESULT: 'No result available',\n UNKNOWN_ERROR: 'Execution failed with unknown error',\n} as const;\n","/**\n * Calculate duration from start time in milliseconds.\n *\n * @param startTime - The start timestamp from Date.now()\n * @returns Duration in milliseconds\n */\nexport function getDuration(startTime: number): number {\n return Date.now() - startTime;\n}\n\n/**\n * Combine multiple AbortSignals into a single signal.\n * The combined signal aborts when ANY of the source signals abort.\n *\n * Node 18 compatible - doesn't use AbortSignal.any() which is Node 20+.\n *\n * @param signals - AbortSignals to combine\n * @returns A new AbortSignal that aborts when any input signal aborts\n *\n * @example\n * ```typescript\n * const userController = new AbortController();\n * const timeoutController = new AbortController();\n *\n * const combined = combineSignals(userController.signal, timeoutController.signal);\n *\n * // Either abort triggers the combined signal\n * userController.abort(); // combined.aborted === true\n * ```\n */\nexport function combineSignals(...signals: AbortSignal[]): AbortSignal {\n const controller = new AbortController();\n\n for (const signal of signals) {\n // If any signal is already aborted, immediately abort and return\n if (signal.aborted) {\n controller.abort(signal.reason);\n return controller.signal;\n }\n\n // Listen for future aborts\n signal.addEventListener('abort', () => controller.abort(signal.reason), {\n once: true,\n });\n }\n\n return controller.signal;\n}\n\n/**\n * A Promise that can be resolved or rejected externally.\n *\n * Useful for bridging callback-based APIs to async/await patterns.\n * The resolve/reject functions are exposed as instance properties,\n * allowing external code to control when the promise settles.\n *\n * @typeParam T - The type of the resolved value (defaults to void)\n *\n * @example\n * ```typescript\n * const deferred = new Deferred<string>();\n *\n * // Later, in a callback:\n * someApi.onData((data) => deferred.resolve(data));\n * someApi.onError((err) => deferred.reject(err));\n *\n * // Await the result:\n * const result = await deferred.promise;\n * ```\n *\n * @example\n * ```typescript\n * // In async generator for event notification:\n * let pending = new Deferred<void>();\n * const subscriber = () => pending.resolve();\n *\n * while (!done) {\n * await pending.promise;\n * pending = new Deferred<void>(); // Reset for next wait\n * }\n * ```\n */\nexport class Deferred<T = void> {\n readonly promise: Promise<T>;\n readonly resolve: (value: T) => void;\n readonly reject: (error: Error) => void;\n\n constructor() {\n let res!: (value: T) => void;\n let rej!: (error: Error) => void;\n this.promise = new Promise<T>((resolve, reject) => {\n res = resolve;\n rej = reject;\n });\n this.resolve = res;\n this.reject = rej;\n }\n}\n","import type { ExecutionStatus } from './types';\n\n/**\n * Shared utilities for execution hosts.\n *\n * These functions extract common patterns from SimpleExecutionHost and\n * StreamingExecutionHost to reduce code duplication and ensure consistent\n * behavior across both implementations.\n */\n\n/**\n * Checks if an error is an abort-related error.\n *\n * An error is considered abort-related if either:\n * - The error has the name 'AbortError' (standard for AbortController)\n * - The signal has been aborted (covers edge cases where error name differs)\n *\n * @param error - The error to check\n * @param signal - The AbortSignal associated with the execution\n * @returns true if this is an abort-related error\n */\nexport function isAbortError(error: unknown, signal: AbortSignal): boolean {\n if (error instanceof Error && error.name === 'AbortError') {\n return true;\n }\n return signal.aborted;\n}\n\n/**\n * Normalizes an unknown error to an Error instance.\n *\n * If the error is already an Error instance, it's returned as-is.\n * Otherwise, it's converted to a string and wrapped in a new Error.\n *\n * @param error - The unknown error to normalize\n * @returns A proper Error instance\n */\nexport function normalizeError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error));\n}\n\n/**\n * Determines the execution status based on the execution state.\n *\n * Status determination priority:\n * 1. If user called cancel() OR the operation was aborted → 'canceled'\n * 2. If there's an error → 'failed'\n * 3. Otherwise → 'succeeded'\n *\n * Note: The 'aborted' flag takes precedence over 'hasError' because\n * AbortError is treated as a normal cancellation, not a failure.\n *\n * @param cancelRequested - Whether cancel() was explicitly called\n * @param aborted - Whether the signal was aborted (includes external abort)\n * @param hasError - Whether the execution ended with an error\n * @returns The appropriate execution status\n */\nexport function determineResultStatus(\n cancelRequested: boolean,\n aborted: boolean,\n hasError: boolean\n): ExecutionStatus {\n // Cancellation takes priority (abort errors are treated as cancellation)\n if (cancelRequested || aborted) {\n return 'canceled';\n }\n\n // Error state\n if (hasError) {\n return 'failed';\n }\n\n // Success\n return 'succeeded';\n}\n\n/**\n * Return type for createHookRunner utility.\n */\nexport type HookRunner = {\n /**\n * Ensures hooks run exactly once.\n * Safe to call multiple times - only executes on first call.\n */\n ensureRun: () => Promise<void>;\n /**\n * Check if hooks have already been run.\n */\n hasRun: () => boolean;\n};\n\n/**\n * Creates a hook runner that ensures hooks run exactly once.\n *\n * This utility encapsulates the common pattern of running cleanup hooks\n * with a guard flag to prevent double execution. Both SimpleExecutionHost\n * and StreamingExecutionHost use this pattern for onDone hooks.\n *\n * @param runHooks - The async function to run hooks\n * @returns Object with ensureRun() and hasRun() methods\n *\n * @example\n * ```typescript\n * const hookRunner = createHookRunner(async () => {\n * await session.runOnDoneHooks();\n * });\n *\n * // In finally block or cleanup:\n * await hookRunner.ensureRun();\n *\n * // Safe to call multiple times - only executes once\n * await hookRunner.ensureRun(); // no-op\n * ```\n */\nexport function createHookRunner(runHooks: () => Promise<void>): HookRunner {\n let ran = false;\n\n return {\n ensureRun: async () => {\n if (!ran) {\n ran = true;\n await runHooks();\n }\n },\n hasRun: () => ran,\n };\n}\n","import { SessionSummary } from '../session/types';\nimport type { StreamingSession } from '../session/streaming-session';\nimport type { ErrorEvent, ExtractResult, SessionEvent, SessionStreamGeneratorFn, StreamingExecution, StreamingResult } from './types';\nimport { ERRORS } from './constants';\nimport { combineSignals, Deferred } from './utils';\nimport { isAbortError, normalizeError, createHookRunner, type HookRunner } from './shared';\n\n/**\n * Internal result structure for tracking streaming execution outcome.\n */\ntype InternalStreamingResult<T> =\n | { success: true; result: T; summary: SessionSummary }\n | { success: false; error: Error; aborted: boolean; summary: SessionSummary };\n\n/**\n * Streaming execution host that uses StreamingSession.\n * Starts execution eagerly on construction - events are buffered automatically.\n *\n * @typeParam TEvent - User's pure domain event type with required `type` field (metrics added automatically)\n *\n * @example\n * ```typescript\n * const execution = new StreamingExecutionHost(\n * () => new StreamingSession({\n * defaultLanguageModel: provider.model,\n * fileManager: new GoogleFileManager(apiKey),\n * }),\n * async function* (session) {\n * session.onDone(() => session.fileManager.clear());\n * const result = await session.generateText({ prompt: 'Hello' });\n * yield session.emit({ type: 'progress', message: 'Working...' });\n * return session.done(result.text);\n * }\n * );\n * // ↑ Execution already started, events being buffered\n *\n * // Option 1: Stream events (buffered + real-time)\n * for await (const event of execution.stream()) {\n * console.log(event.type, event.metrics.elapsedMs);\n * }\n * const result = await execution.result();\n *\n * // Option 2: Skip streaming, events available in result\n * const result = await execution.result();\n * console.log(`Received ${result.events.length} events`);\n *\n * if (result.status === 'succeeded') {\n * console.log(result.value);\n * }\n * ```\n */\nexport class StreamingExecutionHost<\n TEvent extends { type: string },\n> implements StreamingExecution<TEvent> {\n private readonly abortController = new AbortController();\n private readonly effectiveSignal: AbortSignal;\n private readonly consumerPromise: Promise<InternalStreamingResult<ExtractResult<TEvent>>>;\n private readonly eventBuffer: SessionEvent<TEvent>[] = [];\n private readonly subscribers = new Set<(event: SessionEvent<TEvent>) => void>();\n private completed = false;\n private cleaned = false;\n private hookRunner: HookRunner | null = null;\n private cancelRequested = false;\n\n private extractedOutcome:\n | { type: 'result'; value: ExtractResult<TEvent> }\n | { type: 'error'; error: Error }\n | null = null;\n private extractedSummary: SessionSummary | null = null;\n\n constructor(\n private readonly createSession: (signal?: AbortSignal) => StreamingSession<TEvent>,\n private readonly generator: SessionStreamGeneratorFn<TEvent>,\n userSignal?: AbortSignal\n ) {\n // Combine user signal with internal controller for dual cancellation support\n this.effectiveSignal = userSignal\n ? combineSignals(userSignal, this.abortController.signal)\n : this.abortController.signal;\n\n // Eager start! Begin consuming immediately\n this.consumerPromise = this.startConsuming();\n }\n\n private hasDataField(event: SessionEvent<TEvent>): event is SessionEvent<TEvent> & { data: ExtractResult<TEvent> } {\n return 'data' in event && (event as { data?: unknown }).data !== undefined;\n }\n\n private hasSummaryField(event: SessionEvent<TEvent>): event is SessionEvent<TEvent> & { summary: SessionSummary } {\n return 'summary' in event && (event as { summary?: unknown }).summary !== undefined;\n }\n\n private hasErrorField(event: SessionEvent<TEvent>): event is SessionEvent<TEvent> & { error: Error } {\n return 'error' in event && (event as { error?: unknown }).error instanceof Error;\n }\n\n private extractResultAndMetadata(event: SessionEvent<TEvent>): void {\n const isCompleteOrError = event.type === 'complete' || event.type === 'error';\n\n if (!isCompleteOrError) {\n return;\n }\n\n // Extract outcome (error takes precedence if both present)\n if (this.hasErrorField(event)) {\n this.extractedOutcome = { type: 'error', error: event.error };\n } else if (this.hasDataField(event)) {\n this.extractedOutcome = { type: 'result', value: event.data };\n }\n\n if (this.hasSummaryField(event)) {\n this.extractedSummary = event.summary;\n }\n }\n\n private notifySubscribers(event: SessionEvent<TEvent>): void {\n this.subscribers.forEach(fn => fn(event));\n }\n\n private async startConsuming(): Promise<InternalStreamingResult<ExtractResult<TEvent>>> {\n // Pass the effective signal to session for AI SDK cancellation\n const session = this.createSession(this.effectiveSignal);\n this.hookRunner = createHookRunner(() => session.runOnDoneHooks());\n const gen = this.generator(session);\n\n try {\n let next = await gen.next();\n\n while (!next.done) {\n // Buffer and notify\n this.eventBuffer.push(next.value);\n this.notifySubscribers(next.value);\n\n // Auto-abort after terminal events to prevent further AI calls\n const isTerminal = next.value.type === 'complete' || next.value.type === 'error';\n if (isTerminal) {\n this.extractResultAndMetadata(next.value);\n this.abortController.abort();\n break;\n }\n\n if (this.abortController.signal.aborted) {\n break;\n }\n\n next = await gen.next();\n }\n\n // Handle return value from generator\n if (next.done && next.value !== undefined) {\n const finalEvent = await Promise.resolve(next.value);\n this.eventBuffer.push(finalEvent);\n this.notifySubscribers(finalEvent);\n this.extractResultAndMetadata(finalEvent);\n\n // Auto-abort after terminal event from return statement\n const isTerminal = finalEvent.type === 'complete' || finalEvent.type === 'error';\n if (isTerminal) {\n this.abortController.abort();\n }\n }\n\n return this.buildResult(session);\n } catch (error) {\n const errorObj = normalizeError(error);\n\n // AbortError is treated as normal cancellation\n if (isAbortError(error, this.abortController.signal)) {\n return {\n success: false,\n aborted: true,\n error: errorObj,\n summary: await session.getSummary(),\n };\n }\n\n // Generate error event via session.fail()\n const errorEvent = await session.fail(errorObj);\n this.eventBuffer.push(errorEvent);\n this.notifySubscribers(errorEvent);\n this.extractResultAndMetadata(errorEvent);\n\n // Auto-abort after error event\n this.abortController.abort();\n\n return this.buildResult(session);\n } finally {\n this.completed = true;\n // Note: Don't clear subscribers here - each stream() consumer\n // cleans up its own subscriber in its finally block to avoid orphaning\n\n await this.hookRunner?.ensureRun();\n\n await gen.return(undefined);\n }\n }\n\n private async buildResult(session: StreamingSession<TEvent>): Promise<InternalStreamingResult<ExtractResult<TEvent>>> {\n const summary = this.extractedSummary ?? await session.getSummary();\n\n // Use discriminated union for clean pattern matching\n if (this.extractedOutcome?.type === 'error') {\n return {\n success: false,\n aborted: false,\n error: this.extractedOutcome.error,\n summary,\n };\n }\n\n if (this.extractedOutcome?.type === 'result') {\n return {\n success: true,\n result: this.extractedOutcome.value,\n summary,\n };\n }\n\n // No result extracted - likely canceled or abnormal termination\n return {\n success: false,\n aborted: true,\n error: new Error(ERRORS.NO_RESULT),\n summary,\n };\n }\n\n /**\n * Get the event stream.\n * Returns buffered events first, then real-time events.\n * Can be called multiple times - replays buffer each time.\n */\n async *stream(): AsyncIterable<SessionEvent<TEvent | ErrorEvent>> {\n // 1. Yield buffered events first\n let index = 0;\n while (index < this.eventBuffer.length) {\n yield this.eventBuffer[index++];\n }\n\n // 2. If completed, we're done\n if (this.completed) {\n return;\n }\n\n // 3. Subscribe for real-time events using Deferred for clean async coordination\n const queue: SessionEvent<TEvent>[] = [];\n let pending = new Deferred<void>();\n\n const subscriber = (event: SessionEvent<TEvent>) => {\n queue.push(event);\n pending.resolve();\n };\n this.subscribers.add(subscriber);\n\n try {\n while (!this.completed || queue.length > 0) {\n if (queue.length > 0) {\n yield queue.shift()!;\n } else if (!this.completed) {\n await pending.promise;\n pending = new Deferred<void>(); // Reset for next wait\n }\n }\n } finally {\n this.subscribers.delete(subscriber);\n }\n }\n\n cancel(): void {\n this.cancelRequested = true;\n this.abortController.abort();\n }\n\n async cleanup(): Promise<void> {\n if (this.cleaned) {\n return;\n }\n this.cleaned = true;\n\n // Cancel if still running\n if (!this.completed) {\n this.cancel();\n await this.consumerPromise.catch(() => {});\n }\n\n // Clean up resources\n this.subscribers.clear();\n\n await this.hookRunner?.ensureRun();\n }\n\n async [Symbol.asyncDispose](): Promise<void> {\n await this.cleanup();\n }\n\n /**\n * Get the execution result with status, summary, and all events.\n * Never throws - returns a discriminated union with status.\n */\n async result(): Promise<StreamingResult<SessionEvent<TEvent | ErrorEvent>, ExtractResult<TEvent>>> {\n const internal = await this.consumerPromise;\n const events = Object.freeze([...this.eventBuffer]) as readonly SessionEvent<TEvent>[];\n\n // Success state\n if (internal.success) {\n return {\n status: 'succeeded',\n value: internal.result,\n summary: internal.summary,\n events,\n };\n }\n\n // Canceled state\n if (this.cancelRequested || internal.aborted) {\n return {\n status: 'canceled',\n summary: internal.summary,\n events,\n };\n }\n\n // Failed state\n return {\n status: 'failed',\n error: internal.error,\n summary: internal.summary,\n events,\n };\n }\n}\n","import { SessionSummary } from '../session/types';\nimport type { SimpleSession } from '../session/simple-session';\nimport type { SimpleExecution, SimpleResult } from './types';\nimport { combineSignals } from './utils';\nimport { isAbortError, normalizeError, createHookRunner } from './shared';\n\n/**\n * Internal result structure for tracking execution outcome.\n * Used to avoid throwing errors in the execution flow.\n */\ntype InternalResult<T> =\n | { success: true; result: T; summary: SessionSummary }\n | { success: false; error: Error; aborted: boolean; summary: SessionSummary };\n\n/**\n * SimpleExecutionHost implements the SimpleExecution interface for eager execution.\n *\n * Execution starts immediately on construction (eager evaluation).\n * Use result() to get the execution outcome with status and summary.\n *\n * Signal combination:\n * - If userSignal is provided, it's combined with internal AbortController\n * - Both cancel() and userSignal abort will trigger cancellation\n * - The combined signal is passed to SimpleSession for AI SDK calls\n *\n * @example\n * ```typescript\n * const execution = new SimpleExecutionHost(createSession, async (session) => {\n * return await session.generateText({ prompt: 'Hello' });\n * });\n *\n * const result = await execution.result();\n *\n * if (result.status === 'succeeded') {\n * console.log(result.value);\n * }\n * console.log(`Cost: $${result.summary.totalCost}`);\n * ```\n */\nexport class SimpleExecutionHost<TResult> implements SimpleExecution<TResult> {\n private readonly abortController = new AbortController();\n private readonly effectiveSignal: AbortSignal;\n private readonly consumerPromise: Promise<InternalResult<TResult>>;\n private cachedSession?: SimpleSession;\n private readonly startTime = Date.now();\n private cancelRequested = false;\n\n constructor(\n createSession: (signal?: AbortSignal) => SimpleSession,\n fn: (session: SimpleSession) => Promise<TResult>,\n userSignal?: AbortSignal\n ) {\n // Combine user signal with internal controller for dual cancellation support\n this.effectiveSignal = userSignal\n ? combineSignals(userSignal, this.abortController.signal)\n : this.abortController.signal;\n\n // Start execution immediately (eager evaluation)\n this.consumerPromise = this.execute(createSession, fn);\n }\n\n private async execute(\n createSession: (signal?: AbortSignal) => SimpleSession,\n fn: (session: SimpleSession) => Promise<TResult>\n ): Promise<InternalResult<TResult>> {\n const session = createSession(this.effectiveSignal);\n this.cachedSession = session;\n const hookRunner = createHookRunner(() => session.runOnDoneHooks());\n\n // Notify execution start\n session.notifyExecutionStart();\n\n try {\n const result = await fn(session);\n\n // Notify execution done\n await session.notifyExecutionDone(result, this.startTime);\n\n return {\n success: true,\n result,\n summary: await session.getSummary(),\n };\n } catch (error) {\n const errorObj = normalizeError(error);\n const isCancellation = isAbortError(error, this.abortController.signal);\n\n // Notify execution error (AbortError excluded - treated as normal cancellation)\n if (!isCancellation) {\n await session.notifyExecutionError(errorObj, this.startTime);\n }\n\n return {\n success: false,\n error: errorObj,\n aborted: isCancellation,\n summary: await session.getSummary(),\n };\n } finally {\n await hookRunner.ensureRun();\n }\n }\n\n /**\n * Request cancellation of the execution.\n * Aborts the current LLM call if in progress.\n * No-op if execution already completed.\n */\n cancel(): void {\n this.cancelRequested = true;\n this.abortController.abort();\n }\n\n /**\n * Get the execution result with status and summary.\n * Never throws - returns a discriminated union with status.\n */\n async result(): Promise<SimpleResult<TResult>> {\n const internal = await this.consumerPromise;\n\n // Success state\n if (internal.success) {\n return {\n status: 'succeeded',\n value: internal.result,\n summary: internal.summary,\n };\n }\n\n // Canceled state (user called cancel() or external signal aborted)\n if (this.cancelRequested || internal.aborted) {\n return {\n status: 'canceled',\n summary: internal.summary,\n };\n }\n\n // Failed state\n return {\n status: 'failed',\n error: internal.error,\n summary: internal.summary,\n };\n }\n\n /**\n * Cleanup resources.\n * For SimpleExecution, hooks are already run during execution,\n * so this is intentionally a no-op.\n */\n async cleanup(): Promise<void> {\n // SimpleExecution runs hooks in execute(), nothing to clean up\n }\n\n async [Symbol.asyncDispose](): Promise<void> {\n await this.cleanup();\n }\n}\n","import type {\n StreamingExecution,\n SimpleExecution,\n SessionEvent,\n StreamingResult,\n SimpleResult,\n CompletionEvent,\n ErrorEvent,\n ExtractResult,\n} from './types';\nimport { normalizeError } from './shared';\n\nexport type ReplaceResult<TEvent extends { type: string }, U> =\n | Exclude<TEvent, { type: 'complete' }>\n | CompletionEvent<U>;\n\n// ============================================================================\n// mapExecution\n// ============================================================================\n\nexport function mapExecution<TEvent extends { type: string }, UEvent extends { type: string }>(\n execution: StreamingExecution<TEvent>,\n fn: (event: TEvent) => UEvent | Promise<UEvent>,\n): StreamingExecution<UEvent>;\n\nexport function mapExecution<A, B>(\n execution: SimpleExecution<A>,\n fn: (result: A) => B | Promise<B>,\n): SimpleExecution<B>;\n\nexport function mapExecution(\n execution: StreamingExecution<any> | SimpleExecution<any>,\n fn: (input: any) => any,\n): any {\n if ('stream' in execution) {\n return mapStreamingExecution(execution, fn);\n }\n return mapSimpleExecution(execution, fn);\n}\n\n// ============================================================================\n// mapExecutionResult\n// ============================================================================\n\nexport function mapExecutionResult<TEvent extends { type: string }, U>(\n execution: StreamingExecution<TEvent>,\n fn: (result: ExtractResult<TEvent>) => U | Promise<U>,\n): StreamingExecution<ReplaceResult<TEvent, U>>;\n\nexport function mapExecutionResult<A, B>(\n execution: SimpleExecution<A>,\n fn: (result: A) => B | Promise<B>,\n): SimpleExecution<B>;\n\nexport function mapExecutionResult(\n execution: StreamingExecution<any> | SimpleExecution<any>,\n fn: (input: any) => any,\n): any {\n if ('stream' in execution) {\n return mapStreamingExecutionResult(execution, fn);\n }\n return mapSimpleExecution(execution, fn);\n}\n\n// ============================================================================\n// Internal: Streaming — full event mapping\n// ============================================================================\n\nfunction mapStreamingExecution<TEvent extends { type: string }, UEvent extends { type: string }>(\n execution: StreamingExecution<TEvent>,\n fn: (event: TEvent) => UEvent | Promise<UEvent>,\n): StreamingExecution<UEvent> {\n return {\n stream(): AsyncIterable<SessionEvent<UEvent | ErrorEvent>> {\n const original = execution.stream();\n return {\n [Symbol.asyncIterator](): AsyncIterator<SessionEvent<UEvent | ErrorEvent>> {\n const iter = original[Symbol.asyncIterator]();\n return {\n async next() {\n const { value, done } = await iter.next();\n if (done) return { value: undefined, done: true };\n\n const event = value as SessionEvent<TEvent | ErrorEvent>;\n if (event.type === 'error') {\n return { value: event as SessionEvent<UEvent | ErrorEvent>, done: false };\n }\n\n const { metrics, ...pureEvent } = event;\n try {\n const mapped = await fn(pureEvent as unknown as TEvent);\n return {\n value: { ...mapped, metrics } as SessionEvent<UEvent | ErrorEvent>,\n done: false,\n };\n } catch (err) {\n const errorEvent: SessionEvent<ErrorEvent> = {\n type: 'error',\n error: normalizeError(err),\n metrics,\n };\n return { value: errorEvent as SessionEvent<UEvent | ErrorEvent>, done: false };\n }\n },\n };\n },\n };\n },\n\n async result(): Promise<StreamingResult<SessionEvent<UEvent | ErrorEvent>, ExtractResult<UEvent>>> {\n const original = await execution.result();\n if (original.status !== 'succeeded') {\n return original as unknown as StreamingResult<SessionEvent<UEvent | ErrorEvent>, ExtractResult<UEvent>>;\n }\n\n try {\n const mappedEvents: SessionEvent<UEvent | ErrorEvent>[] = [];\n for (const event of original.events) {\n if ((event as any).type === 'error') {\n mappedEvents.push(event as unknown as SessionEvent<UEvent | ErrorEvent>);\n continue;\n }\n const { metrics, ...pureEvent } = event as any;\n const mapped = await fn(pureEvent as TEvent);\n mappedEvents.push({ ...mapped, metrics } as SessionEvent<UEvent | ErrorEvent>);\n }\n\n const completionEvent = mappedEvents.find(e => (e as any).type === 'complete') as\n | SessionEvent<CompletionEvent<ExtractResult<UEvent>>>\n | undefined;\n\n return {\n status: 'succeeded',\n value: completionEvent!.data as ExtractResult<UEvent>,\n events: mappedEvents,\n summary: original.summary,\n };\n } catch (err) {\n return {\n status: 'failed',\n error: normalizeError(err),\n events: original.events as unknown as SessionEvent<UEvent | ErrorEvent>[],\n summary: original.summary,\n };\n }\n },\n\n cancel: () => execution.cancel(),\n cleanup: () => execution.cleanup(),\n [Symbol.asyncDispose]: () => execution[Symbol.asyncDispose](),\n };\n}\n\n// ============================================================================\n// Internal: Streaming — result-only mapping\n// ============================================================================\n\nfunction mapStreamingExecutionResult<TEvent extends { type: string }, U>(\n execution: StreamingExecution<TEvent>,\n fn: (result: ExtractResult<TEvent>) => U | Promise<U>,\n): StreamingExecution<ReplaceResult<TEvent, U>> {\n type OutEvent = ReplaceResult<TEvent, U>;\n\n return {\n stream(): AsyncIterable<SessionEvent<OutEvent | ErrorEvent>> {\n const original = execution.stream();\n return {\n [Symbol.asyncIterator](): AsyncIterator<SessionEvent<OutEvent | ErrorEvent>> {\n const iter = original[Symbol.asyncIterator]();\n return {\n async next() {\n const { value, done } = await iter.next();\n if (done) return { value: undefined, done: true };\n\n const event = value as SessionEvent<TEvent | ErrorEvent>;\n if (event.type === 'complete') {\n const { metrics, ...rest } = event as any;\n try {\n const mapped = await fn(rest.data);\n return {\n value: { type: 'complete', data: mapped, summary: rest.summary, metrics } as SessionEvent<OutEvent | ErrorEvent>,\n done: false,\n };\n } catch (err) {\n const errorEvent: SessionEvent<ErrorEvent> = {\n type: 'error',\n error: normalizeError(err),\n metrics,\n };\n return { value: errorEvent as SessionEvent<OutEvent | ErrorEvent>, done: false };\n }\n }\n\n return { value: event as SessionEvent<OutEvent | ErrorEvent>, done: false };\n },\n };\n },\n };\n },\n\n async result(): Promise<StreamingResult<SessionEvent<OutEvent | ErrorEvent>, ExtractResult<OutEvent>>> {\n type Result = StreamingResult<SessionEvent<OutEvent | ErrorEvent>, ExtractResult<OutEvent>>;\n const original = await execution.result();\n if (original.status !== 'succeeded') {\n return original as unknown as Result;\n }\n\n try {\n const mapped = await fn(original.value);\n const mappedEvents = original.events.map(event => {\n if ((event as any).type === 'complete') {\n return { ...event, data: mapped } as unknown as SessionEvent<OutEvent | ErrorEvent>;\n }\n return event as SessionEvent<OutEvent | ErrorEvent>;\n });\n\n return {\n status: 'succeeded',\n value: mapped as ExtractResult<OutEvent>,\n events: mappedEvents,\n summary: original.summary,\n };\n } catch (err) {\n return {\n status: 'failed',\n error: normalizeError(err),\n events: original.events as unknown as SessionEvent<OutEvent | ErrorEvent>[],\n summary: original.summary,\n } as Result;\n }\n },\n\n cancel: () => execution.cancel(),\n cleanup: () => execution.cleanup(),\n [Symbol.asyncDispose]: () => execution[Symbol.asyncDispose](),\n };\n}\n\n// ============================================================================\n// Internal: Simple execution mapping (shared by both mapExecution and mapExecutionResult)\n// ============================================================================\n\nfunction mapSimpleExecution<A, B>(\n execution: SimpleExecution<A>,\n fn: (result: A) => B | Promise<B>,\n): SimpleExecution<B> {\n return {\n async result(): Promise<SimpleResult<B>> {\n const original = await execution.result();\n if (original.status !== 'succeeded') {\n return original as SimpleResult<B>;\n }\n\n try {\n const mapped = await fn(original.value);\n return {\n status: 'succeeded',\n value: mapped,\n summary: original.summary,\n };\n } catch (err) {\n return {\n status: 'failed',\n error: normalizeError(err),\n summary: original.summary,\n };\n }\n },\n\n cancel: () => execution.cancel(),\n cleanup: () => execution.cleanup(),\n [Symbol.asyncDispose]: () => execution[Symbol.asyncDispose](),\n };\n}\n","import type { LanguageModelUsage } from 'ai';\nimport type { SessionSummary } from '../session/types';\n\n/**\n * Logger interface for observability.\n * All methods are optional - implement only the events you care about.\n *\n * @example\n * ```typescript\n * const myLogger: Logger = {\n * onLLMCallEnd(event) {\n * console.log(`${event.modelId}: ${event.response.duration}ms`);\n * },\n * onExecutionDone(event) {\n * console.log('Total duration:', event.duration);\n * },\n * };\n * ```\n */\nexport interface Logger {\n onLLMCallStart?(event: LLMCallStartEvent): void;\n onLLMCallEnd?(event: LLMCallEndEvent): void;\n onExecutionStart?(event: ExecutionStartEvent): void;\n onExecutionEmit?<TEvent>(event: ExecutionEmitEvent<TEvent>): void;\n onExecutionDone?<TResult>(event: ExecutionDoneEvent<TResult>): void;\n onExecutionError?<TResult>(event: ExecutionErrorEvent<TResult>): void;\n log?(level: LogLevel, message: string, data?: Record<string, unknown>): void;\n}\n\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\nexport type LLMCallLogType = 'generateText' | 'streamText';\n\n/**\n * Event emitted when an LLM call starts.\n *\n * @example\n * ```typescript\n * logger.onLLMCallStart?.({\n * type: 'llm_call_start',\n * callType: 'generateText',\n * modelId: 'gemini-2.5-flash',\n * timestamp: Date.now(),\n * request: { params: { prompt: 'Hello' } },\n * });\n * ```\n */\nexport interface LLMCallStartEvent {\n type: 'llm_call_start';\n callType: LLMCallLogType;\n modelId: string;\n timestamp: number;\n request: {\n params: Record<string, unknown>;\n };\n}\n\n/**\n * Event emitted when an LLM call ends (success or error).\n *\n * @example Success case:\n * ```typescript\n * logger.onLLMCallEnd?.({\n * type: 'llm_call_end',\n * callType: 'generateText',\n * modelId: 'gemini-2.5-flash',\n * timestamp: Date.now(),\n * response: {\n * duration: 1500,\n * usage: { inputTokens: 100, outputTokens: 50, totalTokens: 150 },\n * raw: result,\n * },\n * });\n * ```\n *\n * @example Error case:\n * ```typescript\n * logger.onLLMCallEnd?.({\n * type: 'llm_call_end',\n * callType: 'streamText',\n * modelId: 'gpt-4o',\n * timestamp: Date.now(),\n * response: {\n * duration: 500,\n * error: new Error('Rate limit exceeded'),\n * raw: null,\n * },\n * });\n * ```\n */\nexport interface LLMCallEndEvent {\n type: 'llm_call_end';\n callType: LLMCallLogType;\n modelId: string;\n timestamp: number;\n response: {\n duration: number;\n usage?: LanguageModelUsage;\n raw: unknown;\n error?: Error;\n };\n}\n\nexport interface ExecutionStartEvent {\n type: 'execution_start';\n timestamp: number;\n}\n\n/**\n * Event emitted for each intermediate event during execution.\n * @typeParam TEvent - The type of the emitted event (includes metrics)\n */\nexport interface ExecutionEmitEvent<TEvent = unknown> {\n type: 'execution_emit';\n event: TEvent;\n}\n\n/**\n * Event emitted when execution completes successfully.\n * @typeParam TResult - The type of the execution result\n */\nexport interface ExecutionDoneEvent<TResult = unknown> {\n type: 'execution_done';\n timestamp: number;\n duration: number;\n data: TResult;\n summary: SessionSummary;\n}\n\n/**\n * Event emitted when execution fails with an error.\n * @typeParam TResult - The type of partial result data (if available)\n */\nexport interface ExecutionErrorEvent<TResult = unknown> {\n type: 'execution_error';\n timestamp: number;\n duration: number;\n error: Error;\n data?: TResult;\n summary?: SessionSummary;\n}\n\n/**\n * No-op logger (default when no logger provided).\n *\n * @example\n * ```typescript\n * const provider = createGoogleProvider({\n * apiKey: 'xxx',\n * logger: noopLogger,\n * });\n * ```\n */\nexport const noopLogger: Logger = {};\n\n/**\n * Helper to create a logger with only the handlers you need.\n *\n * @example\n * ```typescript\n * const metricsLogger = createLogger({\n * onLLMCallEnd(event) {\n * metrics.recordLatency(event.response.duration);\n * },\n * onExecutionDone(event) {\n * metrics.recordTokens(event.summary.totalLLMUsage.totalTokens);\n * },\n * });\n * ```\n */\nexport function createLogger(handlers: Partial<Logger>): Logger {\n return handlers;\n}\n","import { type StopCondition, type ToolSet, hasToolCall, tool } from 'ai';\nimport { z } from 'zod';\n\nimport type {\n EmittableEventInput,\n ErrorEvent,\n ExtractResult,\n SessionEvent,\n} from '@/execution/types';\nimport type { BaseProvider } from '@/provider/base-provider';\nimport type { StreamingSession } from '@/session/streaming-session';\nimport type { StreamTextParams } from '@/session/types';\n\nexport type ProgressiveStreamOptions<TUserTools extends ToolSet = {}> = Omit<\n StreamTextParams<TUserTools>,\n 'tools' | 'toolChoice' | 'stopWhen'\n> & {\n tools?: TUserTools;\n /**\n * Additional stop conditions. Will be combined with the default\n * `hasToolCall('submitResult')`.\n */\n stopWhen?: StopCondition<ToolSet> | StopCondition<ToolSet>[];\n /**\n * Custom protocol instructions appended to the system prompt.\n * If not provided, uses the default TOOL_CALLING_PROTOCOL.\n */\n protocol?: string;\n};\n\n/**\n * Progress event - pure domain event without metrics.\n * Framework automatically wraps with SessionEvent at runtime.\n */\nexport interface ProgressEvent<TProgress> {\n type: 'progress';\n data: TProgress;\n}\n\n/**\n * Complete event - pure domain event without metrics.\n * Framework automatically wraps with SessionEvent at runtime.\n */\nexport interface CompleteEvent<TResult> {\n type: 'complete';\n data: TResult;\n summary: unknown;\n}\n\nconst TOOL_DESCRIPTIONS = {\n reportProgress:\n '[OPTIONAL] Report progress during task execution. Use this to show intermediate work. You may call this multiple times, then you MUST call tools::submitResult.',\n submitResult:\n '[REQUIRED] Submit the final result. You MUST call this exactly once to complete the task. Without this call, the task FAILS.',\n} as const;\n\nexport const TOOL_CALLING_PROTOCOL = `## CRITICAL INSTRUCTION - READ CAREFULLY\n\nYou have 2 tools available:\n1. reportProgress - [OPTIONAL] Show intermediate work (multiple times)\n2. submitResult - [REQUIRED] Submit your final answer\n\n⚠️ IMPORTANT RULES:\n- You may call reportProgress 0-3 times to show progress\n- You MUST call submitResult exactly once to complete the task\n- After calling reportProgress, you MUST call submitResult in your NEXT response\n- If you call reportProgress more than 3 times without submitResult, the task FAILS\n- The task is NOT complete until submitResult is called\n\nCORRECT SEQUENCE:\n1. [Optional] reportProgress\n2. [Required] submitResult (exactly once)\n\n❌ WRONG: reportProgress → reportProgress → reportProgress → reportProgress (no submitResult = FAIL)\n✅ CORRECT: reportProgress → submitResult (SUCCESS)`;\n\n/**\n * Creates a progressive pattern for streaming LLM responses with intermediate progress updates.\n *\n * The pattern automatically:\n * - Injects `reportProgress` and `submitResult` tools\n * - Stops when `submitResult` is called (via `hasToolCall('submitResult')`)\n * - Appends protocol instructions to the system prompt\n *\n * @example Basic usage\n * ```typescript\n * const pattern = defineProgressivePattern({\n * progressSchema: z.object({ stage: z.string(), message: z.string() }),\n * resultSchema: z.object({ summary: z.string(), score: z.number() }),\n * });\n *\n * for await (const event of pattern.run(provider, {\n * system: 'You are an analyzer.',\n * prompt: 'Analyze this...',\n * })) {\n * console.log(event.type, event.data);\n * }\n * ```\n *\n * @example With custom stopWhen (add step limit)\n * ```typescript\n * import { stepCountIs } from 'ai';\n *\n * for await (const event of pattern.run(provider, {\n * prompt: 'Analyze...',\n * stopWhen: stepCountIs(10), // Stop at submitResult OR after 10 steps\n * })) { ... }\n * ```\n *\n * @example With custom protocol\n * ```typescript\n * for await (const event of pattern.run(provider, {\n * prompt: 'Analyze...',\n * protocol: 'Call reportProgress for each step, then submitResult.',\n * })) { ... }\n * ```\n *\n * @example Composable (within a session)\n * ```typescript\n * provider.streamingExecution(async function*(session) {\n * yield* pattern.runInSession(session, {\n * system: 'You are an analyzer.',\n * messages: [...],\n * });\n * });\n * ```\n */\nexport function defineProgressivePattern<\n TProgressSchema extends z.ZodType,\n TResultSchema extends z.ZodType,\n>(config: { progressSchema: TProgressSchema; resultSchema: TResultSchema }) {\n return new ProgressivePattern(config.progressSchema, config.resultSchema);\n}\n\nexport class ProgressivePattern<\n TProgressSchema extends z.ZodType,\n TResultSchema extends z.ZodType,\n TProgress = z.infer<TProgressSchema>,\n TResult = z.infer<TResultSchema>,\n TEvent extends { type: string } = { type: string },\n> {\n constructor(\n readonly progressSchema: TProgressSchema,\n readonly resultSchema: TResultSchema\n ) {}\n\n private lastParseError: Error | null = null;\n\n /**\n * Runs the pattern within an existing session. Use this for composing\n * multiple patterns or when you need fine-grained control over the session.\n *\n * @param session - The streaming session to run within\n * @param options - Stream options including:\n * - `stopWhen` - Additional stop conditions (combined with default `hasToolCall('submitResult')`)\n * - `protocol` - Custom protocol instructions (replaces default `TOOL_CALLING_PROTOCOL`)\n * - All other `streamText` options except `tools`, `toolChoice`, `stopWhen`\n *\n * @example Basic usage\n * ```typescript\n * provider.streamingExecution(async function*(session) {\n * yield* pattern.runInSession(session, {\n * system: 'You are an analyzer.',\n * messages: [{ role: 'user', content: 'Analyze...' }],\n * });\n * });\n * ```\n *\n * @example With custom stopWhen\n * ```typescript\n * yield* pattern.runInSession(session, {\n * prompt: 'Analyze...',\n * stopWhen: stepCountIs(5), // Combined: submitResult OR 5 steps\n * });\n * ```\n */\n async *runInSession<TUserTools extends ToolSet = {}>(\n session: StreamingSession<TEvent>,\n options: ProgressiveStreamOptions<TUserTools>\n ): AsyncGenerator<SessionEvent<TEvent>, SessionEvent<TEvent>, undefined> {\n const {\n tools: userTools,\n system,\n stopWhen: userStopWhen,\n protocol,\n ...restOptions\n } = options;\n\n const internalTools = this.createTools();\n const allTools = { ...userTools, ...internalTools } as ToolSet;\n const systemString = typeof system === 'string' ? system : undefined;\n const fullSystem = this.renderSystemPrompt(systemString, protocol);\n\n const defaultStopCondition = hasToolCall('submitResult');\n const stopConditions = this.combineStopConditions(defaultStopCondition, userStopWhen);\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const stream = session.streamText({\n ...restOptions,\n system: fullSystem,\n tools: allTools as any,\n toolChoice: 'required',\n stopWhen: stopConditions as any,\n });\n\n let result: TResult | null = null;\n\n for await (const part of stream.fullStream) {\n if (part.type === 'tool-call') {\n if (part.toolName === 'reportProgress') {\n const input = 'input' in part ? part.input : undefined;\n const progressData = this.parseProgressInput(input);\n if (progressData !== null) {\n // Cast required: TypeScript can't know that TEvent includes a 'progress' variant\n yield session.emit({\n type: 'progress',\n data: progressData,\n } as unknown as EmittableEventInput<TEvent>);\n }\n } else if (part.toolName === 'submitResult') {\n const input = 'input' in part ? part.input : undefined;\n result = this.parseResultInput(input);\n }\n }\n }\n\n if (result === null) {\n const baseMsg = 'ProgressivePattern: No result received.';\n const detail = this.lastParseError\n ? ` Last parse error: ${this.lastParseError.message}`\n : ' The LLM did not call submitResult tool.';\n throw new Error(baseMsg + detail);\n }\n\n const completeEvent = await session.done(result as ExtractResult<TEvent>);\n yield completeEvent;\n return completeEvent;\n }\n\n /**\n * Standalone execution that creates a new session internally.\n * Use this for simple, single-pattern executions.\n *\n * @param provider - The AI provider to use\n * @param options - Stream options including:\n * - `stopWhen` - Additional stop conditions (combined with default `hasToolCall('submitResult')`)\n * - `protocol` - Custom protocol instructions (replaces default `TOOL_CALLING_PROTOCOL`)\n *\n * @example Basic usage\n * ```typescript\n * for await (const event of pattern.run(provider, {\n * system: 'You are an analyzer.',\n * prompt: 'Analyze this document...',\n * })) {\n * if (event.type === 'progress') {\n * console.log('Progress:', event.data);\n * } else if (event.type === 'complete') {\n * console.log('Result:', event.data);\n * }\n * }\n * ```\n *\n * @example With step limit\n * ```typescript\n * import { stepCountIs } from 'ai';\n *\n * for await (const event of pattern.run(provider, {\n * prompt: 'Analyze...',\n * stopWhen: stepCountIs(10),\n * })) { ... }\n * ```\n */\n run<TUserTools extends ToolSet = {}>(\n provider: BaseProvider,\n options: ProgressiveStreamOptions<TUserTools>\n ): AsyncIterable<SessionEvent<TEvent | ErrorEvent>> {\n const self = this;\n const execution = provider.streamingExecution<TEvent>(async function* (session) {\n return yield* self.runInSession(session, options);\n });\n return execution.stream();\n }\n\n private createTools() {\n return {\n reportProgress: tool({\n description: TOOL_DESCRIPTIONS.reportProgress,\n inputSchema: z.object({\n data: this.progressSchema,\n }),\n execute: async () => ({\n status: 'progress_recorded',\n instruction:\n 'After all progress reports, you MUST call tools::submitResult to complete the task.',\n }),\n }),\n submitResult: tool({\n description: TOOL_DESCRIPTIONS.submitResult,\n inputSchema: z.object({\n data: this.resultSchema,\n }),\n execute: async () => ({\n status: 'result_submitted',\n message: 'Task completed successfully.',\n }),\n }),\n };\n }\n\n private parseJsonWrapper<T>(input: unknown, schema: z.ZodType<T>): T | null {\n try {\n if (!input || typeof input !== 'object') return null;\n const wrapper = input as { data?: unknown };\n if (wrapper.data === undefined) return null;\n\n const parsed =\n typeof wrapper.data === 'string' ? JSON.parse(wrapper.data) : wrapper.data;\n\n return schema.parse(parsed) as T;\n } catch (error) {\n this.lastParseError = error instanceof Error ? error : new Error(String(error));\n return null;\n }\n }\n\n private parseProgressInput(input: unknown): TProgress | null {\n return this.parseJsonWrapper(input, this.progressSchema) as TProgress | null;\n }\n\n private parseResultInput(input: unknown): TResult | null {\n return this.parseJsonWrapper(input, this.resultSchema) as TResult | null;\n }\n\n private combineStopConditions(\n defaultCondition: StopCondition<ToolSet>,\n userConditions?: StopCondition<ToolSet> | StopCondition<ToolSet>[]\n ): StopCondition<ToolSet>[] {\n if (!userConditions) {\n return [defaultCondition];\n }\n const userArray = Array.isArray(userConditions) ? userConditions : [userConditions];\n return [defaultCondition, ...userArray];\n }\n\n private renderSystemPrompt(userSystem?: string, protocol?: string): string {\n const protocolText = protocol ?? TOOL_CALLING_PROTOCOL;\n return userSystem ? `${userSystem}\\n\\n${protocolText}` : protocolText;\n }\n}\n","/**\n * Pricing validation utilities.\n *\n * Provides fail-fast validation for pricing configuration to catch\n * invalid values (negative, NaN, Infinity) at configuration time.\n *\n * @module pricing/validator\n */\n\nimport type { ModelPricing, PricingConfig, ProviderPricing } from './types';\n\nfunction validatePriceValue(\n value: number,\n fieldName: string,\n context: string\n): void {\n if (!Number.isFinite(value)) {\n throw new Error(`${context}: ${fieldName} must be a finite number`);\n }\n if (value < 0) {\n throw new Error(`${context}: ${fieldName} cannot be negative`);\n }\n}\n\n/**\n * Validates a ModelPricing object.\n * Ensures all price values are non-negative and finite.\n *\n * @throws {Error} If any price value is invalid\n *\n * @example\n * ```typescript\n * validateModelPricing(\n * { inputPricePerMillion: 2.5, outputPricePerMillion: 10.0 },\n * 'openai/gpt-4o'\n * );\n * ```\n */\nexport function validateModelPricing(\n pricing: ModelPricing,\n context: string\n): void {\n validatePriceValue(\n pricing.inputPricePerMillion,\n 'inputPricePerMillion',\n context\n );\n validatePriceValue(\n pricing.outputPricePerMillion,\n 'outputPricePerMillion',\n context\n );\n\n if (pricing.cachedInputPricePerMillion !== undefined) {\n validatePriceValue(\n pricing.cachedInputPricePerMillion,\n 'cachedInputPricePerMillion',\n context\n );\n }\n}\n\n/**\n * Validates a ProviderPricing object.\n *\n * @throws {Error} If any model pricing is invalid\n *\n * @example\n * ```typescript\n * validateProviderPricing({\n * 'gemini-2.5-flash': { inputPricePerMillion: 0.3, outputPricePerMillion: 2.5 },\n * 'gemini-2.5-pro': { inputPricePerMillion: 1.25, outputPricePerMillion: 10.0 },\n * }, 'google');\n * ```\n */\nexport function validateProviderPricing(\n pricing: ProviderPricing,\n providerContext?: string\n): void {\n for (const [model, modelPricing] of Object.entries(pricing)) {\n const context = providerContext ? `${providerContext}/${model}` : model;\n validateModelPricing(modelPricing, context);\n }\n}\n\n/**\n * Validates a PricingConfig object.\n *\n * @throws {Error} If any pricing configuration is invalid\n *\n * @example\n * ```typescript\n * validatePricingConfig({\n * providers: {\n * google: { 'gemini-2.5-flash': { inputPricePerMillion: 0.3, outputPricePerMillion: 2.5 } },\n * },\n * fallback: { inputPricePerMillion: 1.0, outputPricePerMillion: 5.0 },\n * });\n * ```\n */\nexport function validatePricingConfig(config: PricingConfig): void {\n if (config.providers) {\n for (const [providerKey, pricing] of Object.entries(config.providers)) {\n if (pricing) {\n validateProviderPricing(pricing, providerKey);\n }\n }\n }\n\n if (config.fallback) {\n validateModelPricing(config.fallback, 'fallback');\n }\n}\n","/**\n * Built-in pricing tables (USD per million tokens).\n *\n * These are the default prices for common models. They can be overridden\n * using `configurePricing()` (global) or `Provider.withPricing()` (per-provider).\n *\n * Last updated: January 2025\n *\n * @module pricing/defaults\n */\n\nimport type { ModelPricing, PricingConfig, ProviderPricing } from './types';\n\n/**\n * OpenAI model pricing.\n * @see https://openai.com/pricing\n */\nexport const OPENAI_PRICING: ProviderPricing = {\n 'gpt-4o': { inputPricePerMillion: 2.5, outputPricePerMillion: 10.0 },\n 'gpt-4o-mini': { inputPricePerMillion: 0.15, outputPricePerMillion: 0.6 },\n 'gpt-4-turbo': { inputPricePerMillion: 10.0, outputPricePerMillion: 30.0 },\n 'gpt-4-turbo-preview': {\n inputPricePerMillion: 10.0,\n outputPricePerMillion: 30.0,\n },\n 'gpt-4': { inputPricePerMillion: 30.0, outputPricePerMillion: 60.0 },\n 'gpt-4-32k': { inputPricePerMillion: 60.0, outputPricePerMillion: 120.0 },\n 'gpt-3.5-turbo': { inputPricePerMillion: 0.5, outputPricePerMillion: 1.5 },\n 'gpt-3.5-turbo-16k': {\n inputPricePerMillion: 3.0,\n outputPricePerMillion: 4.0,\n },\n 'o1': { inputPricePerMillion: 15.0, outputPricePerMillion: 60.0 },\n 'o1-mini': { inputPricePerMillion: 3.0, outputPricePerMillion: 12.0 },\n 'o1-preview': { inputPricePerMillion: 15.0, outputPricePerMillion: 60.0 },\n 'o3': { inputPricePerMillion: 20.0, outputPricePerMillion: 80.0 },\n 'o3-mini': { inputPricePerMillion: 4.0, outputPricePerMillion: 16.0 },\n};\n\n/**\n * Google Gemini model pricing.\n * @see https://ai.google.dev/gemini-api/docs/pricing\n */\nexport const GOOGLE_PRICING: ProviderPricing = {\n 'gemini-2.5-flash': {\n inputPricePerMillion: 0.15,\n outputPricePerMillion: 0.6,\n cachedInputPricePerMillion: 0.0375,\n },\n 'gemini-2.5-flash-lite': {\n inputPricePerMillion: 0.075,\n outputPricePerMillion: 0.3,\n cachedInputPricePerMillion: 0.01875,\n },\n 'gemini-2.5-pro': {\n inputPricePerMillion: 1.25,\n outputPricePerMillion: 10.0,\n cachedInputPricePerMillion: 0.3125,\n },\n 'gemini-2.0-flash': {\n inputPricePerMillion: 0.1,\n outputPricePerMillion: 0.4,\n cachedInputPricePerMillion: 0.025,\n },\n 'gemini-2.0-flash-lite': {\n inputPricePerMillion: 0.075,\n outputPricePerMillion: 0.3,\n cachedInputPricePerMillion: 0.01875,\n },\n 'gemini-1.5-pro': {\n inputPricePerMillion: 1.25,\n outputPricePerMillion: 5.0,\n cachedInputPricePerMillion: 0.3125,\n },\n 'gemini-1.5-flash': {\n inputPricePerMillion: 0.075,\n outputPricePerMillion: 0.3,\n cachedInputPricePerMillion: 0.01875,\n },\n 'gemini-1.5-flash-8b': {\n inputPricePerMillion: 0.0375,\n outputPricePerMillion: 0.15,\n cachedInputPricePerMillion: 0.01,\n },\n 'gemini-pro': { inputPricePerMillion: 0.5, outputPricePerMillion: 1.5 },\n};\n\n/**\n * Anthropic Claude model pricing.\n * @see https://www.anthropic.com/pricing\n */\nexport const ANTHROPIC_PRICING: ProviderPricing = {\n 'claude-opus-4-5-20250514': {\n inputPricePerMillion: 15.0,\n outputPricePerMillion: 75.0,\n cachedInputPricePerMillion: 1.875,\n },\n 'claude-sonnet-4-20250514': {\n inputPricePerMillion: 3.0,\n outputPricePerMillion: 15.0,\n cachedInputPricePerMillion: 0.375,\n },\n 'claude-3-5-sonnet-20241022': {\n inputPricePerMillion: 3.0,\n outputPricePerMillion: 15.0,\n cachedInputPricePerMillion: 0.375,\n },\n 'claude-3-5-haiku-20241022': {\n inputPricePerMillion: 0.8,\n outputPricePerMillion: 4.0,\n cachedInputPricePerMillion: 0.1,\n },\n 'claude-3-opus-20240229': {\n inputPricePerMillion: 15.0,\n outputPricePerMillion: 75.0,\n cachedInputPricePerMillion: 1.875,\n },\n 'claude-3-sonnet-20240229': {\n inputPricePerMillion: 3.0,\n outputPricePerMillion: 15.0,\n cachedInputPricePerMillion: 0.375,\n },\n 'claude-3-haiku-20240307': {\n inputPricePerMillion: 0.25,\n outputPricePerMillion: 1.25,\n cachedInputPricePerMillion: 0.03,\n },\n};\n\nexport const DEFAULT_PRICING_CONFIG: Required<PricingConfig> = {\n providers: {\n openai: OPENAI_PRICING,\n google: GOOGLE_PRICING,\n anthropic: ANTHROPIC_PRICING,\n },\n fallback: {\n inputPricePerMillion: 1.0,\n outputPricePerMillion: 5.0,\n },\n};\n\nexport const DEFAULT_FALLBACK_PRICING: ModelPricing = {\n inputPricePerMillion: 1.0,\n outputPricePerMillion: 5.0,\n};\n","/**\n * Global pricing configuration.\n *\n * Priority order (highest to lowest):\n * 1. Provider.withPricing() - per-provider override\n * 2. configurePricing() - global override\n * 3. Built-in defaults (defaults.ts)\n * 4. Fallback pricing\n *\n * @module pricing/config\n */\n\nimport type { ModelPricing, PricingConfig, ProviderType } from './types';\nimport { validatePricingConfig } from './validator';\nimport { DEFAULT_PRICING_CONFIG, DEFAULT_FALLBACK_PRICING } from './defaults';\n\nlet globalConfig: PricingConfig | undefined;\n\n/**\n * Configure global pricing overrides.\n *\n * WARNING: This uses global mutable state and is not thread-safe.\n * For multi-tenant scenarios or concurrent requests with different pricing,\n * use `Provider.withPricing()` instead for proper isolation.\n *\n * @example\n * ```typescript\n * configurePricing({\n * providers: {\n * google: {\n * 'gemini-2.5-flash': { inputPricePerMillion: 0.5, outputPricePerMillion: 3.0 },\n * },\n * },\n * });\n *\n * // Reset to built-in defaults\n * configurePricing(undefined);\n * ```\n */\nexport function configurePricing(config: PricingConfig | undefined): void {\n if (config) {\n validatePricingConfig(config);\n }\n globalConfig = config;\n}\n\nexport function getPricingConfig(): PricingConfig | undefined {\n return globalConfig;\n}\n\n/**\n * Reset global pricing configuration.\n * Useful for testing to ensure clean state between tests.\n */\nexport function resetPricingConfig(): void {\n globalConfig = undefined;\n}\n\nexport type PricingSource = 'global' | 'default' | 'fallback';\n\nexport interface EffectivePricingResult {\n pricing: ModelPricing;\n source: PricingSource;\n}\n\n/**\n * Get effective pricing for a model with source information.\n * Useful for debugging to understand which pricing layer is applied.\n *\n * @example\n * ```typescript\n * const result = getEffectivePricing('gemini-2.5-flash', 'google');\n * console.log(result.source); // 'default' (using built-in pricing)\n *\n * configurePricing({ providers: { google: { 'gemini-2.5-flash': {...} } } });\n * const result2 = getEffectivePricing('gemini-2.5-flash', 'google');\n * console.log(result2.source); // 'global' (using configured override)\n * ```\n */\nexport function getEffectivePricing(\n model: string,\n provider: ProviderType\n): EffectivePricingResult {\n if (globalConfig?.providers?.[provider]?.[model]) {\n return {\n pricing: globalConfig.providers[provider]![model],\n source: 'global',\n };\n }\n\n const defaultPricing = DEFAULT_PRICING_CONFIG.providers[provider];\n if (defaultPricing?.[model]) {\n return {\n pricing: defaultPricing[model],\n source: 'default',\n };\n }\n\n return {\n pricing:\n globalConfig?.fallback ??\n DEFAULT_PRICING_CONFIG.fallback ??\n DEFAULT_FALLBACK_PRICING,\n source: 'fallback',\n };\n}\n","/**\n * Cost calculation functions.\n *\n * @module pricing/calculator\n *\n * NOTE: Cost calculations use standard JavaScript floating-point arithmetic.\n * For high-volume usage tracking, accumulated totals may have minor precision drift.\n * For financial reporting, consider rounding results to appropriate decimal places\n * (e.g., `Math.round(cost * 100) / 100` for cents).\n */\n\nimport type { LanguageModelUsage } from 'ai';\nimport type {\n CalculateCostParams,\n CostResult,\n ModelPricing,\n ProviderPricing,\n ProviderType,\n} from './types';\nimport { DEFAULT_PRICING_CONFIG, DEFAULT_FALLBACK_PRICING } from './defaults';\nimport { getPricingConfig } from './config';\n\nconst TOKENS_PER_MILLION = 1_000_000;\n\n/**\n * Get pricing for a specific model.\n *\n * Resolution order:\n * 1. Provider-level config (providerPricing param)\n * 2. Global config (configurePricing)\n * 3. Built-in defaults\n * 4. Fallback pricing\n */\nexport function getModelPricing(\n model: string,\n provider: ProviderType,\n providerPricing?: ProviderPricing\n): ModelPricing {\n if (providerPricing?.[model]) {\n return providerPricing[model];\n }\n\n const globalConfig = getPricingConfig();\n if (globalConfig?.providers?.[provider]?.[model]) {\n return globalConfig.providers[provider][model];\n }\n\n const defaultProviderPricing = DEFAULT_PRICING_CONFIG.providers[provider];\n if (defaultProviderPricing?.[model]) {\n return defaultProviderPricing[model];\n }\n\n return (\n globalConfig?.fallback ??\n DEFAULT_PRICING_CONFIG.fallback ??\n DEFAULT_FALLBACK_PRICING\n );\n}\n\nfunction validateCostParams(params: CalculateCostParams): void {\n const { inputTokens, outputTokens, cachedInputTokens = 0 } = params;\n\n if (inputTokens < 0 || outputTokens < 0 || cachedInputTokens < 0) {\n throw new Error('Token counts must be non-negative');\n }\n\n if (cachedInputTokens > inputTokens) {\n throw new Error('cachedInputTokens cannot exceed inputTokens');\n }\n\n if (\n !Number.isFinite(inputTokens) ||\n !Number.isFinite(outputTokens) ||\n !Number.isFinite(cachedInputTokens)\n ) {\n throw new Error('Token counts must be finite numbers');\n }\n}\n\n/**\n * Calculate cost from token counts.\n *\n * @throws Error if token counts are negative, non-finite, or if cachedInputTokens > inputTokens\n *\n * @example\n * ```typescript\n * const cost = calculateCost({\n * inputTokens: 1000,\n * outputTokens: 500,\n * cachedInputTokens: 200,\n * model: 'gemini-2.5-flash',\n * provider: 'google',\n * });\n * console.log(cost.total); // 0.000315\n * ```\n */\nexport function calculateCost(\n params: CalculateCostParams,\n providerPricing?: ProviderPricing\n): CostResult {\n validateCostParams(params);\n\n const {\n inputTokens,\n outputTokens,\n cachedInputTokens = 0,\n model,\n provider,\n } = params;\n\n const pricing = getModelPricing(model, provider, providerPricing);\n\n const nonCachedInputTokens = inputTokens - cachedInputTokens;\n const inputCost =\n (nonCachedInputTokens / TOKENS_PER_MILLION) * pricing.inputPricePerMillion;\n const outputCost =\n (outputTokens / TOKENS_PER_MILLION) * pricing.outputPricePerMillion;\n\n const cachedInputPricePerMillion =\n pricing.cachedInputPricePerMillion ?? pricing.inputPricePerMillion;\n const cachedInputCost =\n (cachedInputTokens / TOKENS_PER_MILLION) * cachedInputPricePerMillion;\n\n return {\n total: inputCost + outputCost + cachedInputCost,\n inputCost,\n outputCost,\n cachedInputCost,\n };\n}\n\n/**\n * Calculate cost from AI SDK LanguageModelUsage.\n *\n * Convenience function that extracts token counts from the\n * AI SDK's LanguageModelUsage type and calculates the cost.\n *\n * @example\n * ```typescript\n * const usage = await result.usage;\n * const cost = calculateCostFromUsage(usage, 'gemini-2.5-flash', 'google');\n * ```\n */\nexport function calculateCostFromUsage(\n usage: LanguageModelUsage,\n model: string,\n provider: ProviderType,\n providerPricing?: ProviderPricing\n): CostResult {\n return calculateCost(\n {\n inputTokens: usage.inputTokens ?? 0,\n outputTokens: usage.outputTokens ?? 0,\n cachedInputTokens: usage.inputTokenDetails?.cacheReadTokens ?? 0,\n model,\n provider,\n },\n providerPricing\n );\n}\n\n/**\n * Calculate total cost for multiple LLM calls.\n *\n * Aggregates costs from multiple calls, grouping by model.\n *\n * @returns Object with:\n * - `totalCost`: Sum of all call costs in USD\n * - `costByModel`: Map where key format is `${provider}/${model}`\n */\nexport function calculateTotalCost(\n calls: Array<{\n usage: LanguageModelUsage;\n model: string;\n provider: ProviderType;\n }>,\n providerPricing?: ProviderPricing\n): { totalCost: number; costByModel: Record<string, number> } {\n const costByModel: Record<string, number> = {};\n let totalCost = 0;\n\n for (const call of calls) {\n const cost = calculateCostFromUsage(\n call.usage,\n call.model,\n call.provider,\n providerPricing\n );\n totalCost += cost.total;\n\n const key = `${call.provider}/${call.model}`;\n costByModel[key] = (costByModel[key] ?? 0) + cost.total;\n }\n\n return { totalCost, costByModel };\n}\n","/**\n * Prompt module error classes for @agtlantis/core.\n *\n * Each error type has a specific code and context for precise error handling.\n */\n\nimport { AgtlantisError, type AgtlantisErrorCode } from '../errors';\n\n// =============================================================================\n// Prompt Error Codes\n// =============================================================================\n\nexport enum PromptErrorCode {\n /** Generic prompt error */\n PROMPT_ERROR = 'PROMPT_ERROR',\n /** Prompt not found in repository */\n NOT_FOUND = 'PROMPT_NOT_FOUND',\n /** Invalid prompt file format (e.g., malformed YAML) */\n INVALID_FORMAT = 'PROMPT_INVALID_FORMAT',\n /** Template compilation failed */\n TEMPLATE_ERROR = 'PROMPT_TEMPLATE_ERROR',\n /** File I/O operation failed */\n IO_ERROR = 'PROMPT_IO_ERROR',\n}\n\n// Extend AgtlantisErrorCode to include PromptErrorCode\ndeclare module '../errors' {\n interface AgtlantisErrorCodeMap {\n prompt: PromptErrorCode;\n }\n}\n\n// =============================================================================\n// Prompt Error Options\n// =============================================================================\n\nexport interface PromptErrorOptions {\n code?: PromptErrorCode;\n cause?: Error;\n context?: Record<string, unknown>;\n}\n\n// =============================================================================\n// Base Prompt Error\n// =============================================================================\n\n/**\n * Base error class for prompt operations.\n * Use specific error subclasses for more precise error handling.\n *\n * @example\n * ```typescript\n * throw new PromptError('Something went wrong', {\n * code: PromptErrorCode.PROMPT_ERROR,\n * context: { promptId: 'greeting' }\n * });\n * ```\n */\nexport class PromptError extends AgtlantisError<PromptErrorCode & AgtlantisErrorCode> {\n constructor(message: string, options: PromptErrorOptions = {}) {\n super(message, {\n code: (options.code ?? PromptErrorCode.PROMPT_ERROR) as PromptErrorCode & AgtlantisErrorCode,\n cause: options.cause,\n context: options.context,\n });\n this.name = 'PromptError';\n }\n\n /**\n * Creates a PromptError from an unknown error.\n */\n static from(\n error: unknown,\n code: PromptErrorCode = PromptErrorCode.PROMPT_ERROR,\n context?: Record<string, unknown>\n ): PromptError {\n if (error instanceof PromptError) {\n return error;\n }\n\n const cause = error instanceof Error ? error : new Error(String(error));\n return new PromptError(cause.message, { code, cause, context });\n }\n}\n\n// =============================================================================\n// Prompt Not Found Error\n// =============================================================================\n\n/**\n * Error thrown when a prompt is not found in the repository.\n *\n * @example\n * ```typescript\n * throw new PromptNotFoundError('greeting', '1.0.0');\n * // Error: Prompt 'greeting' version '1.0.0' not found\n *\n * throw new PromptNotFoundError('greeting');\n * // Error: Prompt 'greeting' not found\n * ```\n */\nexport class PromptNotFoundError extends PromptError {\n readonly promptId: string;\n readonly version?: string;\n\n constructor(promptId: string, version?: string, options: Omit<PromptErrorOptions, 'code'> = {}) {\n const message = version\n ? `Prompt '${promptId}' version '${version}' not found`\n : `Prompt '${promptId}' not found`;\n\n super(message, {\n code: PromptErrorCode.NOT_FOUND,\n cause: options.cause,\n context: { promptId, version, ...options.context },\n });\n this.name = 'PromptNotFoundError';\n this.promptId = promptId;\n this.version = version;\n }\n}\n\n// =============================================================================\n// Prompt Invalid Format Error\n// =============================================================================\n\n/**\n * Error thrown when a prompt file has invalid format.\n * Examples: malformed YAML, missing required fields, invalid schema.\n *\n * @example\n * ```typescript\n * throw new PromptInvalidFormatError('greeting', 'Missing required field: system');\n * // Error: Invalid format for prompt 'greeting': Missing required field: system\n * ```\n */\nexport class PromptInvalidFormatError extends PromptError {\n readonly promptId: string;\n readonly details: string;\n\n constructor(promptId: string, details: string, options: Omit<PromptErrorOptions, 'code'> = {}) {\n super(`Invalid format for prompt '${promptId}': ${details}`, {\n code: PromptErrorCode.INVALID_FORMAT,\n cause: options.cause,\n context: { promptId, details, ...options.context },\n });\n this.name = 'PromptInvalidFormatError';\n this.promptId = promptId;\n this.details = details;\n }\n}\n\n// =============================================================================\n// Prompt Template Error\n// =============================================================================\n\n/**\n * Error thrown when template compilation fails.\n * Examples: invalid Handlebars syntax, missing helper.\n *\n * @example\n * ```typescript\n * throw new PromptTemplateError('greeting', 'Unexpected token {{/if}}');\n * // Error: Template compilation failed for prompt 'greeting': Unexpected token {{/if}}\n * ```\n */\nexport class PromptTemplateError extends PromptError {\n readonly promptId: string;\n readonly details: string;\n\n constructor(promptId: string, details: string, options: Omit<PromptErrorOptions, 'code'> = {}) {\n super(`Template compilation failed for prompt '${promptId}': ${details}`, {\n code: PromptErrorCode.TEMPLATE_ERROR,\n cause: options.cause,\n context: { promptId, details, ...options.context },\n });\n this.name = 'PromptTemplateError';\n this.promptId = promptId;\n this.details = details;\n }\n}\n\n// =============================================================================\n// Prompt IO Error\n// =============================================================================\n\n/**\n * Error thrown when file I/O operations fail.\n * Examples: read failure, write failure, directory access denied.\n *\n * @example\n * ```typescript\n * throw new PromptIOError('read', '/path/to/prompt.yaml', {\n * cause: originalError\n * });\n * // Error: Failed to read prompt file: /path/to/prompt.yaml\n * ```\n */\nexport class PromptIOError extends PromptError {\n readonly operation: 'read' | 'write' | 'list';\n readonly path: string;\n\n constructor(\n operation: 'read' | 'write' | 'list',\n path: string,\n options: Omit<PromptErrorOptions, 'code'> = {}\n ) {\n const opText = operation === 'list' ? 'list prompts in' : `${operation} prompt file`;\n super(`Failed to ${opText}: ${path}`, {\n code: PromptErrorCode.IO_ERROR,\n cause: options.cause,\n context: { operation, path, ...options.context },\n });\n this.name = 'PromptIOError';\n this.operation = operation;\n this.path = path;\n }\n}\n","/**\n * Template engine for prompt compilation.\n *\n * Uses Handlebars for template rendering with custom helpers.\n */\n\nimport Handlebars from 'handlebars';\n\n// Note: PromptTemplate class uses compileTemplate, not the other way around\n// This avoids circular dependencies\nimport { PromptTemplateError } from './errors';\n\n// =============================================================================\n// Handlebars Instance Setup\n// =============================================================================\n\n/**\n * Create a sandboxed Handlebars instance with custom helpers.\n * Using a separate instance prevents pollution of the global Handlebars.\n */\nconst handlebars = Handlebars.create();\n\n// Register custom helpers\nhandlebars.registerHelper('add', (a: unknown, b: unknown) => {\n const numA = Number(a);\n const numB = Number(b);\n if (Number.isNaN(numA) || Number.isNaN(numB)) {\n return NaN;\n }\n return numA + numB;\n});\n\n// =============================================================================\n// Template Compilation\n// =============================================================================\n\nfunction wrapTemplateError(promptId: string, error: unknown): PromptTemplateError {\n const message = error instanceof Error ? error.message : String(error);\n const cause = error instanceof Error ? error : undefined;\n return new PromptTemplateError(promptId, message, { cause });\n}\n\n/**\n * Compiles a Handlebars template string into a render function.\n *\n * @typeParam TInput - Type of the input object for template rendering\n * @param template - Handlebars template string\n * @param promptId - Prompt ID for error context\n * @returns Compiled template function\n * @throws {PromptTemplateError} If template compilation fails\n *\n * @example\n * ```typescript\n * const render = compileTemplate<{ name: string }>('Hello, {{name}}!', 'greeting');\n * const result = render({ name: 'World' });\n * // => 'Hello, World!'\n * ```\n */\nexport function compileTemplate<TInput>(\n template: string,\n promptId: string\n): (input: TInput) => string {\n try {\n const compiled = handlebars.compile(template, {\n strict: true,\n noEscape: true,\n });\n\n return (input: TInput): string => {\n try {\n return compiled(input);\n } catch (error) {\n throw wrapTemplateError(promptId, error);\n }\n };\n } catch (error) {\n throw wrapTemplateError(promptId, error);\n }\n}\n\n","/**\n * PromptTemplate class for prompt management.\n *\n * Provides a rich object for prompt templates with compilation capabilities.\n */\nimport { compileTemplate } from './template';\nimport type { PromptRenderer, PromptTemplateData } from './types';\n\n/**\n * Prompt template with compilation capabilities.\n *\n * Use `PromptTemplate.from()` to create from raw data, then call `compile()`\n * to get compiled template functions.\n *\n * @example\n * ```typescript\n * // From raw data\n * const template = PromptTemplate.from({\n * id: 'greeting',\n * version: '1.0.0',\n * system: 'You are helping {{studentName}}.',\n * userTemplate: 'Previous answers: {{answers}}',\n * });\n *\n * // Compile to renderer\n * interface SessionCtx { studentName: string }\n * interface TurnCtx { answers: string[] }\n *\n * const renderer = template.compile<SessionCtx, TurnCtx>();\n * const systemPrompt = renderer.renderSystemPrompt({ studentName: 'Kim' });\n * const userPrompt = renderer.renderUserPrompt({ answers: ['A', 'B'] });\n * ```\n */\nexport class PromptTemplate implements PromptTemplateData {\n private constructor(\n readonly id: string,\n readonly version: string,\n readonly system: string,\n readonly userTemplate: string\n ) {}\n\n /**\n * Creates a PromptTemplate instance from raw data.\n *\n * @param data - Raw prompt template data\n * @returns PromptTemplate instance\n */\n static from(data: PromptTemplateData): PromptTemplate {\n return new PromptTemplate(data.id, data.version, data.system, data.userTemplate);\n }\n\n /**\n * Compiles templates and returns a PromptRenderer.\n *\n * @typeParam TSystemInput - Type of input for system prompt template\n * @typeParam TUserInput - Type of input for user prompt template (defaults to TSystemInput)\n * @returns Compiled prompt renderer with renderSystemPrompt and renderUserPrompt functions\n * @throws {PromptTemplateError} If template compilation fails\n *\n * @example\n * ```typescript\n * // Different input types for system and user prompts\n * const renderer = template.compile<SessionCtx, TurnCtx>();\n *\n * // Same input type for both\n * const simpleRenderer = template.compile<CommonCtx>();\n * ```\n */\n compile<TSystemInput = unknown, TUserInput = TSystemInput>(): PromptRenderer<\n TSystemInput,\n TUserInput\n > {\n return {\n id: this.id,\n version: this.version,\n renderSystemPrompt: compileTemplate<TSystemInput>(this.system, this.id),\n renderUserPrompt: compileTemplate<TUserInput>(this.userTemplate, this.id),\n };\n }\n\n /**\n * Returns raw data representation.\n * Useful for serialization or passing to repository.write().\n */\n toData(): PromptTemplateData {\n return {\n id: this.id,\n version: this.version,\n system: this.system,\n userTemplate: this.userTemplate,\n };\n }\n}\n","/**\n * File-based prompt repository implementation.\n *\n * Stores prompts as YAML files with naming convention: {id}-{version}.yaml\n */\n\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\n\nimport * as yaml from 'yaml';\n\nimport type { FileSystem, PromptTemplateData, PromptRepository } from './types';\nimport { PromptInvalidFormatError, PromptIOError, PromptNotFoundError } from './errors';\nimport { compileTemplate } from './template';\n\n// =============================================================================\n// Types\n// =============================================================================\n\nexport interface FilePromptRepositoryOptions {\n /** Directory path where prompt files are stored */\n directory: string;\n /** Optional custom file system implementation (defaults to Node.js fs) */\n fs?: FileSystem;\n /** Enable in-memory caching for read operations (defaults to true) */\n cache?: boolean;\n}\n\n// =============================================================================\n// Error Utilities\n// =============================================================================\n\nfunction toErrorCause(error: unknown): Error | undefined {\n return error instanceof Error ? error : undefined;\n}\n\nfunction toErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n// =============================================================================\n// Default File System Implementation\n// =============================================================================\n\nconst defaultFileSystem: FileSystem = {\n readFile: (filePath: string) => fs.readFile(filePath, 'utf-8'),\n writeFile: (filePath: string, content: string) => fs.writeFile(filePath, content, 'utf-8'),\n readdir: (dirPath: string) => fs.readdir(dirPath),\n};\n\n// =============================================================================\n// Version Utilities\n// =============================================================================\n\n/**\n * Parses a semver version string into numeric components.\n * @param version - Version string (e.g., '1.2.3')\n * @returns Tuple of [major, minor, patch] or null if invalid\n */\nfunction parseVersion(version: string): [number, number, number] | null {\n const match = version.match(/^(\\d+)\\.(\\d+)\\.(\\d+)$/);\n if (!match) return null;\n return [parseInt(match[1], 10), parseInt(match[2], 10), parseInt(match[3], 10)];\n}\n\n/**\n * Compares two semver versions.\n * @returns Negative if a < b, positive if a > b, zero if equal\n */\nfunction compareVersions(a: string, b: string): number {\n const parsedA = parseVersion(a);\n const parsedB = parseVersion(b);\n\n // Invalid versions sort last\n if (!parsedA && !parsedB) return 0;\n if (!parsedA) return 1;\n if (!parsedB) return -1;\n\n for (let i = 0; i < 3; i++) {\n if (parsedA[i] !== parsedB[i]) {\n return parsedA[i] - parsedB[i];\n }\n }\n return 0;\n}\n\n// =============================================================================\n// File Name Utilities\n// =============================================================================\n\nconst FILE_EXTENSION = '.yaml';\n\n/**\n * Generates file name from prompt id and version.\n * @example getFileName('greeting', '1.0.0') => 'greeting-1.0.0.yaml'\n */\nfunction getFileName(id: string, version: string): string {\n return `${id}-${version}${FILE_EXTENSION}`;\n}\n\n/**\n * Parses file name into id and version.\n * @example parseFileName('greeting-1.0.0.yaml') => { id: 'greeting', version: '1.0.0' }\n */\nfunction parseFileName(fileName: string): { id: string; version: string } | null {\n if (!fileName.endsWith(FILE_EXTENSION)) return null;\n\n const baseName = fileName.slice(0, -FILE_EXTENSION.length);\n const lastDash = baseName.lastIndexOf('-');\n if (lastDash === -1) return null;\n\n const id = baseName.slice(0, lastDash);\n const version = baseName.slice(lastDash + 1);\n\n if (!id || !parseVersion(version)) return null;\n\n return { id, version };\n}\n\n// =============================================================================\n// YAML Parsing & Validation\n// =============================================================================\n\n/**\n * Parses and validates YAML content as PromptTemplateData.\n */\nfunction parsePromptYaml(content: string, promptId: string): PromptTemplateData {\n let parsed: unknown;\n try {\n parsed = yaml.parse(content);\n } catch (error) {\n throw new PromptInvalidFormatError(\n promptId,\n `Invalid YAML: ${toErrorMessage(error)}`,\n { cause: toErrorCause(error) }\n );\n }\n\n if (!parsed || typeof parsed !== 'object') {\n throw new PromptInvalidFormatError(promptId, 'Expected YAML object');\n }\n\n const obj = parsed as Record<string, unknown>;\n\n // Validate required fields\n const requiredFields = ['id', 'version', 'system', 'userTemplate'] as const;\n for (const field of requiredFields) {\n if (typeof obj[field] !== 'string') {\n throw new PromptInvalidFormatError(\n promptId,\n `Missing or invalid required field: ${field} (expected string)`\n );\n }\n }\n\n return {\n id: obj.id as string,\n version: obj.version as string,\n system: obj.system as string,\n userTemplate: obj.userTemplate as string,\n };\n}\n\n/**\n * Serializes PromptTemplateData to YAML string.\n */\nfunction serializePromptYaml(content: PromptTemplateData): string {\n return yaml.stringify(content);\n}\n\n// =============================================================================\n// Repository Implementation\n// =============================================================================\n\n/**\n * File-based prompt repository.\n *\n * Prompts are stored as YAML files with naming convention: {id}-{version}.yaml\n *\n * Can be subclassed to customize parsing/serialization (e.g., JSON instead of YAML).\n *\n * @example\n * ```typescript\n * const repo = new FilePromptRepository({ directory: './prompts' });\n *\n * // Read latest version\n * const prompt = await repo.read<GreetingInput>('greeting');\n *\n * // Subclass to use JSON format\n * class JsonPromptRepository extends FilePromptRepository {\n * protected parseContent(content: string, promptId: string): PromptTemplateData {\n * return JSON.parse(content);\n * }\n * protected serializeContent(content: PromptTemplateData): string {\n * return JSON.stringify(content, null, 2);\n * }\n * }\n * ```\n */\nexport class FilePromptRepository implements PromptRepository {\n protected readonly directory: string;\n protected readonly fileSystem: FileSystem;\n protected readonly cacheEnabled: boolean;\n\n private readonly contentCache = new Map<string, PromptTemplateData>();\n\n constructor(options: FilePromptRepositoryOptions) {\n this.directory = options.directory;\n this.fileSystem = options.fs ?? defaultFileSystem;\n this.cacheEnabled = options.cache ?? true;\n }\n\n /**\n * Generates file name from prompt id and version.\n * Override this along with `parseFileName` to change file naming convention.\n */\n protected getFileName(id: string, version: string): string {\n return getFileName(id, version);\n }\n\n /**\n * Parses file name into id and version.\n * Override this along with `getFileName` to change file naming convention.\n */\n protected parseFileName(fileName: string): { id: string; version: string } | null {\n return parseFileName(fileName);\n }\n\n /**\n * Parses raw file content into PromptTemplateData.\n * Override this to support different file formats (e.g., JSON, TOML).\n */\n protected parseContent(content: string, promptId: string): PromptTemplateData {\n return parsePromptYaml(content, promptId);\n }\n\n /**\n * Serializes PromptTemplateData to file content string.\n * Override this to support different file formats (e.g., JSON, TOML).\n */\n protected serializeContent(content: PromptTemplateData): string {\n return serializePromptYaml(content);\n }\n\n private getCacheKey(id: string, version: string): string {\n return `${id}:${version}`;\n }\n\n async read(id: string, version?: string): Promise<PromptTemplateData> {\n if (version) {\n const cacheKey = this.getCacheKey(id, version);\n\n if (this.cacheEnabled) {\n const cached = this.contentCache.get(cacheKey);\n if (cached) {\n return cached;\n }\n }\n\n const fileName = this.getFileName(id, version);\n const filePath = path.join(this.directory, fileName);\n\n let content: string;\n try {\n content = await this.fileSystem.readFile(filePath);\n } catch (error) {\n if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {\n throw new PromptNotFoundError(id, version);\n }\n throw new PromptIOError('read', filePath, { cause: toErrorCause(error) });\n }\n\n const promptContent = this.parseContent(content, id);\n\n if (promptContent.id !== id || promptContent.version !== version) {\n throw new PromptInvalidFormatError(\n id,\n `File content mismatch: expected id='${id}' version='${version}', got id='${promptContent.id}' version='${promptContent.version}'`\n );\n }\n\n if (this.cacheEnabled) {\n this.contentCache.set(cacheKey, promptContent);\n }\n\n return promptContent;\n }\n\n let files: string[];\n try {\n files = await this.fileSystem.readdir(this.directory);\n } catch (error) {\n throw new PromptIOError('list', this.directory, { cause: toErrorCause(error) });\n }\n\n const versions: string[] = [];\n for (const file of files) {\n const parsed = this.parseFileName(file);\n if (parsed && parsed.id === id) {\n versions.push(parsed.version);\n }\n }\n\n if (versions.length === 0) {\n throw new PromptNotFoundError(id);\n }\n\n versions.sort((a, b) => compareVersions(b, a));\n const latestVersion = versions[0];\n\n return this.read(id, latestVersion);\n }\n\n async write(content: PromptTemplateData): Promise<void> {\n // Invalidate cache for this id:version (before any validation)\n if (this.cacheEnabled) {\n this.contentCache.delete(this.getCacheKey(content.id, content.version));\n }\n\n const fileName = this.getFileName(content.id, content.version);\n const filePath = path.join(this.directory, fileName);\n\n if (!parseVersion(content.version)) {\n throw new PromptInvalidFormatError(\n content.id,\n `Invalid version format: '${content.version}' (expected semver like '1.0.0')`\n );\n }\n\n // Validate templates can be compiled (fails fast on syntax errors)\n compileTemplate(content.system, content.id);\n compileTemplate(content.userTemplate, content.id);\n\n const yamlContent = this.serializeContent(content);\n\n try {\n await this.fileSystem.writeFile(filePath, yamlContent);\n } catch (error) {\n throw new PromptIOError('write', filePath, { cause: toErrorCause(error) });\n }\n }\n}\n\n/**\n * Creates a file-based prompt repository.\n *\n * This is a convenience factory function. For subclassing, use `FilePromptRepository` class directly.\n *\n * @example\n * ```typescript\n * const repo = createFilePromptRepository({ directory: './prompts' });\n * const prompt = await repo.read<GreetingInput>('greeting');\n * ```\n */\nexport function createFilePromptRepository(options: FilePromptRepositoryOptions): PromptRepository {\n return new FilePromptRepository(options);\n}\n","import type { FilePart, ImagePart, ToolSet } from 'ai';\n\nimport type {\n ExecutionOptions,\n SessionEvent,\n SimpleExecution,\n StreamingExecution,\n} from '@/execution';\nimport type { Logger } from '@/observability/logger';\nimport type { ProviderPricing } from '@/pricing';\nimport { SimpleSession, StreamingSession } from '@/session';\nimport type {\n GenerateTextParams,\n GenerateTextResultTyped,\n OutputSpec,\n StreamTextParams,\n StreamTextResultTyped,\n ToolCallSummary,\n} from '@/session';\n\ntype DefaultOutput = OutputSpec<string, string>;\n\n/** Result of uploading a file to a provider's file storage */\nexport interface UploadedFile {\n /** Unique identifier from the provider (used for deletion, null for external URLs) */\n id: string | null;\n /** AI SDK part ready for use in prompts */\n part: FilePart | ImagePart;\n}\n\n/** Provider-agnostic file manager interface for upload/delete operations */\nexport interface FileManager {\n upload(files: FileSource[]): Promise<UploadedFile[]>;\n delete(fileId: string): Promise<void>;\n clear(): Promise<void>;\n getUploadedFiles(): UploadedFile[];\n}\n\n/** Cache for uploaded files to prevent duplicate uploads */\nexport interface FileCache {\n get(hash: string): UploadedFile | null;\n set(hash: string, file: UploadedFile, ttl?: number): void;\n delete(hash: string): void;\n clear(): void;\n}\n\nexport interface FileManagerOptions {\n cache?: FileCache;\n}\n\nexport interface FileSourcePath {\n source: 'path';\n path: string;\n mediaType?: string;\n filename?: string;\n hash?: string;\n}\n\nexport interface FileSourceData {\n source: 'data';\n data: Buffer | Uint8Array;\n mediaType: string;\n filename?: string;\n hash?: string;\n}\n\nexport interface FileSourceBase64 {\n source: 'base64';\n data: string;\n mediaType: string;\n filename?: string;\n hash?: string;\n}\n\nexport interface FileSourceUrl {\n source: 'url';\n url: string;\n mediaType?: string;\n filename?: string;\n hash?: string;\n}\n\n/** Union of all file part types. Use `source` to discriminate. */\nexport type FileSource = FileSourcePath | FileSourceData | FileSourceBase64 | FileSourceUrl;\n\nconst FILE_SOURCE_TYPES = new Set(['path', 'data', 'base64', 'url']);\n\nexport function isFileSource(v: unknown): v is FileSource {\n return (\n typeof v === 'object' &&\n v !== null &&\n FILE_SOURCE_TYPES.has((v as Record<string, unknown>).source as string)\n );\n}\n\nexport function isFileSourcePath(v: FileSource): v is FileSourcePath {\n return v.source === 'path';\n}\n\nexport function isFileSourceData(v: FileSource): v is FileSourceData {\n return v.source === 'data';\n}\n\nexport function isFileSourceBase64(v: FileSource): v is FileSourceBase64 {\n return v.source === 'base64';\n}\n\nexport function isFileSourceUrl(v: FileSource): v is FileSourceUrl {\n return v.source === 'url';\n}\n\n/** Provider interface with fluent configuration for AI model operations */\nexport interface Provider {\n withDefaultModel(modelId: string): Provider;\n withLogger(logger: Logger): Provider;\n withPricing(pricing: ProviderPricing): Provider;\n /**\n * Set default provider-specific options for all LLM calls.\n * These options will be deep-merged with per-call providerOptions.\n * The actual options type depends on the provider (Google, OpenAI, etc.).\n */\n withDefaultOptions(options: Record<string, unknown>): Provider;\n\n streamingExecution<TEvent extends { type: string }>(\n generator: (\n session: StreamingSession<TEvent>\n ) => AsyncGenerator<SessionEvent<TEvent>, SessionEvent<TEvent> | Promise<SessionEvent<TEvent>>>,\n options?: ExecutionOptions\n ): StreamingExecution<TEvent>;\n\n /**\n * Execute a non-streaming function with the provider.\n * Returns immediately (sync) - execution starts in the background.\n *\n * Breaking change: Previously returned Promise<Execution<TResult>>.\n * Now returns SimpleExecution<TResult> directly (no await needed).\n *\n * @example\n * ```typescript\n * // Before (v1.x):\n * const execution = provider.simpleExecution(fn);\n *\n * // After (v2.x):\n * const execution = provider.simpleExecution(fn);\n * execution.cancel(); // Can cancel in-progress LLM calls\n * const result = await execution.result();\n * ```\n */\n simpleExecution<TResult>(\n fn: (session: SimpleSession) => Promise<TResult>,\n options?: ExecutionOptions\n ): SimpleExecution<TResult>;\n}\n","import { createHash } from 'node:crypto';\nimport { readFile } from 'node:fs/promises';\nimport path from 'node:path';\n\nimport type { FileSource } from './types';\n\nexport async function computeFileSourceHash(source: FileSource): Promise<string> {\n if (source.hash) {\n return source.hash;\n }\n\n const hash = createHash('sha256');\n\n switch (source.source) {\n case 'path': {\n const fullPath = path.isAbsolute(source.path)\n ? source.path\n : path.resolve(process.cwd(), source.path);\n const content = await readFile(fullPath);\n hash.update(content);\n break;\n }\n case 'data': {\n hash.update(source.data);\n break;\n }\n case 'base64': {\n const buffer = Buffer.from(source.data, 'base64');\n hash.update(buffer);\n break;\n }\n case 'url': {\n hash.update(source.url);\n break;\n }\n }\n\n return hash.digest('hex');\n}\n","import type { FileCache, UploadedFile } from './types';\n\nexport interface InMemoryFileCacheOptions {\n defaultTTL?: number;\n}\n\ninterface CacheEntry {\n file: UploadedFile;\n expiresAt?: number;\n}\n\nexport class InMemoryFileCache implements FileCache {\n private readonly cache = new Map<string, CacheEntry>();\n private readonly defaultTTL: number | undefined;\n\n constructor(options?: InMemoryFileCacheOptions) {\n this.defaultTTL = options?.defaultTTL;\n }\n\n get(hash: string): UploadedFile | null {\n const entry = this.cache.get(hash);\n if (!entry) return null;\n if (entry.expiresAt !== undefined && Date.now() > entry.expiresAt) {\n this.cache.delete(hash);\n return null;\n }\n return entry.file;\n }\n\n set(hash: string, file: UploadedFile, ttl?: number): void {\n const effectiveTTL = ttl ?? this.defaultTTL;\n const expiresAt = effectiveTTL !== undefined ? Date.now() + effectiveTTL : undefined;\n this.cache.set(hash, { file, expiresAt });\n }\n\n delete(hash: string): void {\n this.cache.delete(hash);\n }\n\n clear(): void {\n this.cache.clear();\n }\n}\n","import type { Logger } from '@/observability/logger';\nimport type { ProviderPricing } from '@/pricing';\nimport type { SessionEvent, StreamingExecution, SimpleExecution, ExecutionOptions } from '../execution/types';\nimport { StreamingExecutionHost } from '../execution/streaming-host';\nimport { SimpleExecutionHost } from '../execution/simple-host';\nimport type { SimpleSession } from '../session/simple-session';\nimport type { StreamingSession } from '../session/streaming-session';\nimport type { Provider } from './types';\n\n/**\n * Abstract base class for AI providers.\n *\n * Provides common streamingExecution and simpleExecution implementation.\n * Subclasses implement session creation and fluent configuration methods.\n */\nexport abstract class BaseProvider implements Provider {\n /**\n * Create a SimpleSession for non-streaming execution.\n * @param signal - AbortSignal for cancellation support\n */\n protected abstract createSimpleSession(signal?: AbortSignal): SimpleSession;\n\n /**\n * Create a StreamingSession for streaming execution.\n * @param signal - AbortSignal for cancellation support\n */\n protected abstract createStreamingSession<\n TEvent extends { type: string },\n >(signal?: AbortSignal): StreamingSession<TEvent>;\n\n abstract withDefaultModel(modelId: string): Provider;\n\n abstract withLogger(logger: Logger): Provider;\n\n abstract withPricing(pricing: ProviderPricing): Provider;\n\n abstract withDefaultOptions(options: Record<string, unknown>): Provider;\n\n streamingExecution<TEvent extends { type: string }>(\n generator: (\n session: StreamingSession<TEvent>\n ) => AsyncGenerator<SessionEvent<TEvent>, SessionEvent<TEvent> | Promise<SessionEvent<TEvent>>>,\n options?: ExecutionOptions\n ): StreamingExecution<TEvent> {\n return new StreamingExecutionHost(\n (signal) => this.createStreamingSession<TEvent>(signal),\n generator,\n options?.signal\n );\n }\n\n /**\n * Execute a non-streaming function with cancellation support.\n * Returns immediately - execution starts in the background.\n */\n simpleExecution<TResult>(\n fn: (session: SimpleSession) => Promise<TResult>,\n options?: ExecutionOptions\n ): SimpleExecution<TResult> {\n return new SimpleExecutionHost(\n (signal) => this.createSimpleSession(signal),\n fn,\n options?.signal\n );\n }\n}\n","import { FileError, FileErrorCode } from '../errors';\nimport type { FileManager, FileSource, UploadedFile } from './types';\n\n/** FileManager for providers without file upload support (throws on upload/delete) */\nexport class NoOpFileManager implements FileManager {\n upload(_files: FileSource[]): Promise<UploadedFile[]> {\n throw new FileError('File upload not supported by this provider', {\n code: FileErrorCode.UNSUPPORTED_TYPE,\n context: {\n provider: 'noop',\n suggestion: 'Use a provider with file support (e.g., Google) or pass files inline',\n },\n });\n }\n\n delete(_fileId: string): Promise<void> {\n throw new FileError('File delete not supported by this provider', {\n code: FileErrorCode.UNSUPPORTED_TYPE,\n context: {\n provider: 'noop',\n },\n });\n }\n\n clear(): Promise<void> {\n return Promise.resolve();\n }\n\n getUploadedFiles(): UploadedFile[] {\n return [];\n }\n}\n","import { readFile, stat } from 'node:fs/promises';\nimport * as path from 'node:path';\n\nimport { FileError, FileErrorCode } from '../errors';\nimport { FileSource, FileSourceData, isFileSource, isFileSourcePath } from './types';\n\nexport const EXTENSION_TO_MIME: Record<string, string> = {\n '.pdf': 'application/pdf',\n '.html': 'text/html',\n '.htm': 'text/html',\n '.txt': 'text/plain',\n '.json': 'application/json',\n '.xml': 'application/xml',\n '.csv': 'text/csv',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.webp': 'image/webp',\n '.svg': 'image/svg+xml',\n '.bmp': 'image/bmp',\n '.zip': 'application/zip',\n};\n\n/** Infers MIME type from file extension (case-insensitive) */\nexport function inferMediaType(filePath: string): string | undefined {\n const ext = path.extname(filePath).toLowerCase();\n return EXTENSION_TO_MIME[ext];\n}\n\nexport interface FoundFileSource {\n part: FileSource;\n path: (string | number)[];\n}\n\n/** Recursively scans an input for FileSources and returns them with their JSON paths */\nexport function scanForFileSources(\n input: unknown,\n currentPath: (string | number)[] = []\n): FoundFileSource[] {\n if (isFileSource(input)) {\n return [{ part: input, path: currentPath }];\n }\n\n if (input === null || typeof input !== 'object') {\n return [];\n }\n\n if (Buffer.isBuffer(input) || input instanceof Uint8Array || input instanceof URL) {\n return [];\n }\n\n const results: FoundFileSource[] = [];\n\n if (Array.isArray(input)) {\n for (let i = 0; i < input.length; i++) {\n results.push(...scanForFileSources(input[i], [...currentPath, i]));\n }\n } else {\n for (const key of Object.keys(input)) {\n results.push(\n ...scanForFileSources((input as Record<string, unknown>)[key], [\n ...currentPath,\n key,\n ])\n );\n }\n }\n\n return results;\n}\n\nexport interface ResolveOptions {\n basePath?: string;\n maxSize?: number;\n}\n\nexport const DEFAULT_MAX_SIZE = 50 * 1024 * 1024;\n\n/**\n * Resolves a FileSource to AI SDK compatible format.\n * Path-based parts are read into Buffer; others returned unchanged.\n */\nexport async function resolveFileSource(\n part: FileSource,\n options: ResolveOptions = {}\n): Promise<FileSource> {\n const { basePath = process.cwd(), maxSize = DEFAULT_MAX_SIZE } = options;\n\n if (!isFileSourcePath(part)) {\n // data, base64, url - return as-is\n return part;\n }\n\n // path source - read file and convert to data\n const fullPath = path.isAbsolute(part.path) ? part.path : path.resolve(basePath, part.path);\n\n const stats = await stat(fullPath).catch((err) => {\n throw new FileError(`File not found: ${part.path}`, {\n code: FileErrorCode.NOT_FOUND,\n context: { path: part.path, fullPath },\n cause: err,\n });\n });\n\n if (stats.size > maxSize) {\n throw new FileError(`File too large: ${stats.size} bytes > ${maxSize} bytes`, {\n code: FileErrorCode.TOO_LARGE,\n context: { path: part.path, size: stats.size, maxSize },\n });\n }\n\n const buffer = await readFile(fullPath);\n const mediaType = part.mediaType ?? inferMediaType(part.path) ?? 'application/octet-stream';\n const filename = part.filename ?? path.basename(part.path);\n\n const result: FileSourceData = {\n source: 'data',\n data: buffer,\n mediaType,\n filename,\n };\n return result;\n}\n\nfunction deepClone<T>(value: T): T {\n if (value === null || typeof value !== 'object') return value;\n if (Buffer.isBuffer(value)) return Buffer.from(value) as T;\n if (value instanceof URL) return new URL(value.href) as T;\n if (value instanceof Uint8Array) return new Uint8Array(value) as T;\n if (Array.isArray(value)) return value.map(deepClone) as T;\n\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(value)) {\n result[key] = deepClone((value as Record<string, unknown>)[key]);\n }\n return result as T;\n}\n\nfunction setAtPath(obj: unknown, targetPath: (string | number)[], value: unknown): unknown {\n if (targetPath.length === 0) {\n return value;\n }\n let current = obj as Record<string | number, unknown>;\n for (let i = 0; i < targetPath.length - 1; i++) {\n current = current[targetPath[i]] as Record<string | number, unknown>;\n }\n current[targetPath[targetPath.length - 1]] = value;\n return obj;\n}\n\n/** Resolves all FileSources in an input (returns new object, original unchanged) */\nexport async function resolveFileSourcesInInput<T>(\n input: T,\n options: ResolveOptions = {}\n): Promise<T> {\n const found = scanForFileSources(input);\n\n if (found.length === 0) {\n return input;\n }\n\n // Resolve all parts in parallel\n const resolved = await Promise.all(found.map(({ part }) => resolveFileSource(part, options)));\n\n // Special case: if input itself is a FileSource (path = [])\n if (found.length === 1 && found[0].path.length === 0) {\n return resolved[0] as T;\n }\n\n // Clone and replace in-place\n const result = deepClone(input);\n for (let i = 0; i < found.length; i++) {\n setAtPath(result, found[i].path, resolved[i]);\n }\n\n return result;\n}\n\nexport interface FileSourceDisplayInfo {\n source: FileSource['source'];\n description: string;\n mediaType: string;\n filename?: string;\n}\n\n/** Extracts display info from a FileSource for reporting (excludes raw data) */\nexport function getFileSourceDisplayInfo(part: FileSource): FileSourceDisplayInfo {\n switch (part.source) {\n case 'path':\n return {\n source: 'path',\n description: part.path,\n mediaType: part.mediaType ?? inferMediaType(part.path) ?? 'unknown',\n filename: part.filename ?? path.basename(part.path),\n };\n\n case 'url':\n return {\n source: 'url',\n description: part.url,\n mediaType: part.mediaType ?? 'unknown',\n filename: part.filename,\n };\n\n case 'base64': {\n const sizeKB = ((part.data.length * 3) / 4 / 1024).toFixed(1);\n return {\n source: 'base64',\n description: `[base64 data, ~${sizeKB}KB]`,\n mediaType: part.mediaType,\n filename: part.filename,\n };\n }\n\n case 'data': {\n const size = Buffer.isBuffer(part.data) ? part.data.length : part.data.length;\n const sizeKB = (size / 1024).toFixed(1);\n return {\n source: 'data',\n description: `[Buffer, ${sizeKB}KB]`,\n mediaType: part.mediaType,\n filename: part.filename,\n };\n }\n }\n}\n\nexport function getFileSourcesDisplayInfo(input: unknown): FileSourceDisplayInfo[] {\n const found = scanForFileSources(input);\n return found.map(({ part }) => getFileSourceDisplayInfo(part));\n}\n","import path from 'node:path';\n\nimport { GoogleGenAI } from '@google/genai';\nimport type { FilePart, ImagePart } from 'ai';\n\nimport { FileError, FileErrorCode } from '../../errors';\nimport { computeFileSourceHash } from '../hash';\nimport type { FileCache, FileManager, FileManagerOptions, FileSource, UploadedFile } from '../types';\n\ninterface GoogleFileUploadResponse {\n name?: string;\n uri?: string;\n mimeType?: string;\n}\n\nfunction assertValidUploadResponse(\n response: GoogleFileUploadResponse,\n context: Record<string, unknown>\n): asserts response is Required<GoogleFileUploadResponse> {\n if (!response.name || !response.uri || !response.mimeType) {\n throw new FileError('Invalid upload response from Google API: missing required fields', {\n code: FileErrorCode.UPLOAD_ERROR,\n context: {\n ...context,\n hasName: !!response.name,\n hasUri: !!response.uri,\n hasMediaType: !!response.mimeType,\n },\n });\n }\n}\n\nfunction isImageMediaType(mediaType: string): boolean {\n return mediaType.startsWith('image/');\n}\n\nfunction createPart(uri: string, mediaType: string): FilePart | ImagePart {\n const url = new URL(uri);\n if (isImageMediaType(mediaType)) {\n return { type: 'image', image: url, mediaType: mediaType };\n }\n return { type: 'file', data: url, mediaType: mediaType };\n}\n\n/** Google GenAI File API implementation with automatic session cleanup */\nexport class GoogleFileManager implements FileManager {\n private uploadedFiles: UploadedFile[] = [];\n private client: GoogleGenAI;\n private cache: FileCache | null;\n\n constructor(apiKey: string, options?: FileManagerOptions) {\n this.client = new GoogleGenAI({ apiKey });\n this.cache = options?.cache ?? null;\n }\n\n private async uploadOne(fileSource: FileSource, index: number, hash: string): Promise<UploadedFile> {\n if (this.cache) {\n const cached = this.cache.get(hash);\n if (cached) return cached;\n }\n\n if (fileSource.source === 'url') {\n const mediaType = fileSource.mediaType ?? 'application/octet-stream';\n const result: UploadedFile = {\n id: null,\n part: createPart(fileSource.url, mediaType),\n };\n if (this.cache) {\n this.cache.set(hash, result);\n }\n return result;\n }\n\n if (fileSource.source === 'path') {\n const fullPath = path.isAbsolute(fileSource.path)\n ? fileSource.path\n : path.resolve(process.cwd(), fileSource.path);\n\n try {\n const uploaded = await this.client.files.upload({\n file: fullPath,\n config: {\n mimeType: fileSource.mediaType,\n displayName: fileSource.filename ?? path.basename(fileSource.path),\n },\n });\n\n assertValidUploadResponse(uploaded, {\n source: 'path',\n path: fileSource.path,\n });\n\n const result: UploadedFile = {\n id: uploaded.name,\n part: createPart(uploaded.uri, uploaded.mimeType),\n };\n if (this.cache) {\n this.cache.set(hash, result);\n }\n return result;\n } catch (error) {\n if (error instanceof FileError) throw error;\n throw FileError.from(error, FileErrorCode.UPLOAD_ERROR, {\n source: 'path',\n path: fileSource.path,\n mediaType: fileSource.mediaType,\n });\n }\n }\n\n const buffer =\n fileSource.source === 'base64'\n ? Buffer.from(fileSource.data, 'base64')\n : fileSource.data;\n\n const arrayBuffer = buffer.buffer.slice(\n buffer.byteOffset,\n buffer.byteOffset + buffer.byteLength\n ) as ArrayBuffer;\n const blob = new Blob([arrayBuffer], { type: fileSource.mediaType });\n\n try {\n const uploaded = await this.client.files.upload({\n file: blob,\n config: {\n mimeType: fileSource.mediaType,\n displayName: fileSource.filename ?? `upload-${Date.now()}-${index}`,\n },\n });\n\n assertValidUploadResponse(uploaded, {\n source: fileSource.source,\n mediaType: fileSource.mediaType,\n });\n\n const result: UploadedFile = {\n id: uploaded.name,\n part: createPart(uploaded.uri, uploaded.mimeType),\n };\n if (this.cache) {\n this.cache.set(hash, result);\n }\n return result;\n } catch (error) {\n if (error instanceof FileError) throw error;\n throw FileError.from(error, FileErrorCode.UPLOAD_ERROR, {\n source: fileSource.source,\n mediaType: fileSource.mediaType,\n filename: fileSource.filename,\n });\n }\n }\n\n async upload(files: FileSource[]): Promise<UploadedFile[]> {\n const hashes = await Promise.all(files.map((file) => computeFileSourceHash(file)));\n\n const results = await Promise.allSettled(\n files.map((file, i) => this.uploadOne(file, i, hashes[i]))\n );\n\n const successful: Array<{ file: UploadedFile; hash: string }> = [];\n const failed: PromiseRejectedResult[] = [];\n\n for (let i = 0; i < results.length; i++) {\n const result = results[i];\n if (result.status === 'fulfilled') {\n successful.push({ file: result.value, hash: hashes[i] });\n } else {\n failed.push(result);\n }\n }\n\n if (failed.length > 0) {\n await Promise.all(\n successful\n .filter(({ file }) => file.id !== null)\n .map(async ({ file, hash }) => {\n await this.client.files.delete({ name: file.id! }).catch(() => {});\n if (this.cache) {\n this.cache.delete(hash);\n }\n })\n );\n\n const firstError = failed[0].reason;\n throw new FileError(\n `Failed to upload ${failed.length} file(s): ${firstError instanceof Error ? firstError.message : String(firstError)}`,\n {\n code: FileErrorCode.UPLOAD_ERROR,\n cause: firstError instanceof Error ? firstError : undefined,\n context: {\n totalFiles: files.length,\n failedCount: failed.length,\n successCount: successful.length,\n },\n }\n );\n }\n\n this.uploadedFiles.push(...successful.filter(({ file }) => file.id !== null).map(({ file }) => file));\n return successful.map(({ file }) => file);\n }\n\n async delete(fileId: string): Promise<void> {\n try {\n await this.client.files.delete({ name: fileId });\n this.uploadedFiles = this.uploadedFiles.filter((f) => f.id !== fileId);\n } catch (error) {\n throw FileError.from(error, FileErrorCode.DELETE_ERROR, {\n fileId,\n });\n }\n }\n\n async clear(): Promise<void> {\n await Promise.all(\n this.uploadedFiles\n .filter((f) => f.id !== null)\n .map((f) => this.delete(f.id!).catch(() => {}))\n );\n this.uploadedFiles = [];\n }\n\n getUploadedFiles(): UploadedFile[] {\n return [...this.uploadedFiles];\n }\n}\n","import type { LanguageModelUsage } from 'ai';\nimport type { ProviderType } from '@/pricing/types';\n\nexport type { ProviderType } from '@/pricing/types';\n\nexport function mergeUsages(usages: LanguageModelUsage[]): LanguageModelUsage {\n if (usages.length === 0) {\n return createZeroUsage();\n }\n\n let inputTokens = 0;\n let outputTokens = 0;\n let totalTokens = 0;\n let noCacheTokens = 0;\n let cacheReadTokens = 0;\n let cacheWriteTokens = 0;\n let textTokens = 0;\n let reasoningTokens = 0;\n\n for (const usage of usages) {\n inputTokens += usage.inputTokens ?? 0;\n outputTokens += usage.outputTokens ?? 0;\n totalTokens += usage.totalTokens ?? 0;\n\n noCacheTokens += usage.inputTokenDetails?.noCacheTokens ?? 0;\n cacheReadTokens += usage.inputTokenDetails?.cacheReadTokens ?? 0;\n cacheWriteTokens += usage.inputTokenDetails?.cacheWriteTokens ?? 0;\n\n textTokens += usage.outputTokenDetails?.textTokens ?? 0;\n reasoningTokens += usage.outputTokenDetails?.reasoningTokens ?? 0;\n }\n\n return {\n inputTokens,\n outputTokens,\n totalTokens,\n inputTokenDetails: {\n noCacheTokens,\n cacheReadTokens,\n cacheWriteTokens,\n },\n outputTokenDetails: {\n textTokens,\n reasoningTokens,\n },\n };\n}\n\nexport function createZeroUsage(): LanguageModelUsage {\n return {\n inputTokens: 0,\n outputTokens: 0,\n totalTokens: 0,\n inputTokenDetails: {\n noCacheTokens: 0,\n cacheReadTokens: 0,\n cacheWriteTokens: 0,\n },\n outputTokenDetails: {\n textTokens: 0,\n reasoningTokens: 0,\n },\n };\n}\n\nexport function detectProviderType(modelId: string): ProviderType | undefined {\n const lowerModel = modelId.toLowerCase();\n\n if (\n lowerModel.startsWith('gpt-') ||\n lowerModel === 'o1' ||\n lowerModel.startsWith('o1-') ||\n lowerModel === 'o3' ||\n lowerModel.startsWith('o3-')\n ) {\n return 'openai';\n }\n\n if (lowerModel.startsWith('gemini')) {\n return 'google';\n }\n\n if (lowerModel.startsWith('claude')) {\n return 'anthropic';\n }\n\n return undefined;\n}\n","/**\n * Session module types for @agtlantis/core.\n * Provides interfaces for tracking LLM calls, tool calls, and session summaries.\n */\n\nimport type {\n LanguageModelUsage,\n generateText as aiGenerateText,\n streamText as aiStreamText,\n generateObject as aiGenerateObject,\n GenerateTextResult,\n StreamTextResult,\n ToolSet,\n} from 'ai';\nimport type { ExecutionMetadata } from '@/observability/types';\nimport type { ProviderType } from '@/pricing/types';\nimport { createZeroUsage } from './usage-extractors';\n\n/**\n * Structural interface matching AI SDK's internal Output<OUTPUT, PARTIAL>.\n *\n * AI SDK exports `output as Output` (runtime value), not the interface directly.\n * We define this compatible interface to enable structural typing.\n *\n * CRITICAL: Method signatures MUST exactly match AI SDK's internal interface\n * for generic type inference to work.\n *\n * @see AI SDK source: node_modules/ai/dist/index.d.ts lines 572-596\n */\nexport interface OutputSpec<OUTPUT = unknown, PARTIAL = unknown> {\n responseFormat: PromiseLike<unknown>;\n\n parseCompleteOutput(\n options: { text: string },\n context: { response: unknown; usage: unknown; finishReason: unknown }\n ): Promise<OUTPUT>;\n\n parsePartialOutput(options: { text: string }): Promise<{ partial: PARTIAL } | undefined>;\n}\n\nexport type DefaultOutput = OutputSpec<string, string>;\n\nexport type InferOutputComplete<T> = T extends OutputSpec<infer O, unknown> ? O : string;\n\nexport type GenerateTextResultTyped<\n TOOLS extends ToolSet,\n OUTPUT extends OutputSpec,\n> = Awaited<ReturnType<typeof aiGenerateText<TOOLS>>> & {\n output: InferOutputComplete<OUTPUT> | undefined;\n};\n\nexport type StreamTextResultTyped<\n TOOLS extends ToolSet,\n OUTPUT extends OutputSpec,\n> = ReturnType<typeof aiStreamText<TOOLS>> & {\n output: Promise<InferOutputComplete<OUTPUT> | undefined>;\n};\n\n/**\n * Parameters for session.generateText().\n * Mirrors AI SDK's generateText() with 'model' excluded (injected by session).\n */\nexport type GenerateTextParams<\n TOOLS extends ToolSet = {},\n OUTPUT extends OutputSpec = DefaultOutput,\n> = Omit<Parameters<typeof aiGenerateText<TOOLS>>[0], 'model' | 'output'> & {\n model?: string;\n output?: OUTPUT;\n};\n\nexport type { GenerateTextResult };\n\n/**\n * Parameters for session.streamText().\n * Mirrors AI SDK's streamText() with 'model' excluded (injected by session).\n */\nexport type StreamTextParams<\n TOOLS extends ToolSet = {},\n OUTPUT extends OutputSpec = DefaultOutput,\n> = Omit<Parameters<typeof aiStreamText<TOOLS>>[0], 'model' | 'output'> & {\n model?: string;\n output?: OUTPUT;\n};\n\nexport type { StreamTextResult };\n\n/**\n * @deprecated Use generateText with Output.object instead\n */\nexport type GenerateObjectParams = Omit<Parameters<typeof aiGenerateObject>[0], 'model'>;\n\nexport type { ToolSet };\n\nexport interface ToolCallSummary {\n name: string;\n duration?: number;\n success: boolean;\n error?: string;\n}\n\nexport type LLMCallType = 'generateText' | 'streamText' | 'generateObject' | 'manual';\n\nexport interface LLMCallRecord {\n startTime: number;\n endTime: number;\n duration: number;\n usage: LanguageModelUsage;\n type: LLMCallType;\n model: string;\n provider: ProviderType;\n}\n\n/**\n * Aggregated summary of all activity within an execution session.\n * Used for cost tracking, performance analysis, and metadata reporting.\n */\nexport interface AdditionalCost {\n type: string;\n cost: number;\n label?: string;\n metadata?: Record<string, unknown>;\n timestamp: number;\n}\n\n/**\n * Internal data structure for SessionSummary constructor.\n */\ninterface SessionSummaryData {\n totalLLMUsage: LanguageModelUsage;\n llmCalls: LLMCallRecord[];\n toolCalls: ToolCallSummary[];\n customRecords: Record<string, unknown>[];\n llmCost: number;\n additionalCosts: AdditionalCost[];\n metadata: Record<string, unknown>;\n costByModel: Record<string, number>;\n}\n\n/**\n * Aggregated summary of all activity within an execution session.\n * Used for cost tracking, performance analysis, and metadata reporting.\n *\n * This is an immutable Value Object. All mutation methods return new instances.\n */\nexport class SessionSummary {\n readonly totalLLMUsage: LanguageModelUsage;\n readonly llmCallCount: number;\n readonly llmCalls: readonly LLMCallRecord[];\n readonly toolCalls: readonly ToolCallSummary[];\n readonly customRecords: readonly Record<string, unknown>[];\n readonly llmCost: number;\n readonly additionalCosts: readonly AdditionalCost[];\n readonly metadata: Readonly<Record<string, unknown>>;\n /** Cost breakdown by model. Key format: `${provider}/${model}` */\n readonly costByModel: Readonly<Record<string, number>>;\n\n private readonly startTime: number;\n\n private constructor(data: SessionSummaryData, startTime: number) {\n this.startTime = startTime;\n this.totalLLMUsage = data.totalLLMUsage;\n this.llmCallCount = data.llmCalls.length;\n this.llmCalls = Object.freeze([...data.llmCalls]);\n this.toolCalls = Object.freeze([...data.toolCalls]);\n this.customRecords = Object.freeze([...data.customRecords]);\n this.llmCost = data.llmCost;\n this.additionalCosts = Object.freeze([...data.additionalCosts]);\n this.metadata = Object.freeze({ ...data.metadata });\n this.costByModel = Object.freeze({ ...data.costByModel });\n }\n\n /**\n * Total duration from session start to now (computed dynamically).\n */\n get totalDuration(): number {\n return Date.now() - this.startTime;\n }\n\n /**\n * Creates an empty SessionSummary.\n */\n static empty(startTime: number): SessionSummary {\n return new SessionSummary(\n {\n totalLLMUsage: createZeroUsage(),\n llmCalls: [],\n toolCalls: [],\n customRecords: [],\n llmCost: 0,\n additionalCosts: [],\n metadata: {},\n costByModel: {},\n },\n startTime\n );\n }\n\n /**\n * Creates a SessionSummary with custom data for testing purposes.\n * @internal For testing only - do not use in production code.\n */\n static forTest(data: Partial<SessionSummaryData> & { startTime?: number }): SessionSummary {\n const startTime = data.startTime ?? Date.now() - 1000;\n return new SessionSummary(\n {\n totalLLMUsage: data.totalLLMUsage ?? createZeroUsage(),\n llmCalls: data.llmCalls ?? [],\n toolCalls: data.toolCalls ?? [],\n customRecords: data.customRecords ?? [],\n llmCost: data.llmCost ?? 0,\n additionalCosts: data.additionalCosts ?? [],\n metadata: data.metadata ?? {},\n costByModel: data.costByModel ?? {},\n },\n startTime\n );\n }\n\n /**\n * Total cost of all additional (non-LLM) operations.\n */\n get totalAdditionalCost(): number {\n return this.additionalCosts.reduce((sum, c) => sum + c.cost, 0);\n }\n\n /**\n * Total cost including LLM and additional costs.\n */\n get totalCost(): number {\n return this.llmCost + this.totalAdditionalCost;\n }\n\n /**\n * Returns a new SessionSummary with an LLM call added.\n */\n withLLMCall(\n call: LLMCallRecord,\n newLlmCost: number,\n newCostByModel: Record<string, number>,\n newTotalUsage: LanguageModelUsage\n ): SessionSummary {\n return new SessionSummary(\n {\n totalLLMUsage: newTotalUsage,\n llmCalls: [...this.llmCalls, call],\n toolCalls: [...this.toolCalls],\n customRecords: [...this.customRecords],\n llmCost: newLlmCost,\n additionalCosts: [...this.additionalCosts],\n metadata: { ...this.metadata },\n costByModel: newCostByModel,\n },\n this.startTime\n );\n }\n\n /**\n * Returns a new SessionSummary with an additional cost recorded.\n */\n withAdditionalCost(cost: AdditionalCost): SessionSummary {\n return new SessionSummary(\n {\n totalLLMUsage: this.totalLLMUsage,\n llmCalls: [...this.llmCalls],\n toolCalls: [...this.toolCalls],\n customRecords: [...this.customRecords],\n llmCost: this.llmCost,\n additionalCosts: [...this.additionalCosts, cost],\n metadata: { ...this.metadata },\n costByModel: { ...this.costByModel },\n },\n this.startTime\n );\n }\n\n /**\n * Returns a new SessionSummary with metadata updated.\n */\n withMetadata(key: string, value: unknown): SessionSummary {\n return new SessionSummary(\n {\n totalLLMUsage: this.totalLLMUsage,\n llmCalls: [...this.llmCalls],\n toolCalls: [...this.toolCalls],\n customRecords: [...this.customRecords],\n llmCost: this.llmCost,\n additionalCosts: [...this.additionalCosts],\n metadata: { ...this.metadata, [key]: value },\n costByModel: { ...this.costByModel },\n },\n this.startTime\n );\n }\n\n /**\n * Returns a new SessionSummary with a tool call added.\n */\n withToolCall(call: ToolCallSummary): SessionSummary {\n return new SessionSummary(\n {\n totalLLMUsage: this.totalLLMUsage,\n llmCalls: [...this.llmCalls],\n toolCalls: [...this.toolCalls, call],\n customRecords: [...this.customRecords],\n llmCost: this.llmCost,\n additionalCosts: [...this.additionalCosts],\n metadata: { ...this.metadata },\n costByModel: { ...this.costByModel },\n },\n this.startTime\n );\n }\n\n /**\n * Returns a new SessionSummary with a custom record added.\n */\n withCustomRecord(record: Record<string, unknown>): SessionSummary {\n return new SessionSummary(\n {\n totalLLMUsage: this.totalLLMUsage,\n llmCalls: [...this.llmCalls],\n toolCalls: [...this.toolCalls],\n customRecords: [...this.customRecords, record],\n llmCost: this.llmCost,\n additionalCosts: [...this.additionalCosts],\n metadata: { ...this.metadata },\n costByModel: { ...this.costByModel },\n },\n this.startTime\n );\n }\n\n /**\n * Serializes to plain JSON object for database storage.\n */\n toJSON(): SessionSummaryJSON {\n return {\n totalDuration: this.totalDuration,\n totalLLMUsage: this.totalLLMUsage,\n llmCallCount: this.llmCallCount,\n llmCalls: [...this.llmCalls],\n toolCalls: [...this.toolCalls],\n customRecords: [...this.customRecords],\n llmCost: this.llmCost,\n additionalCosts: [...this.additionalCosts],\n metadata: { ...this.metadata },\n costByModel: { ...this.costByModel },\n totalCost: this.totalCost,\n totalAdditionalCost: this.totalAdditionalCost,\n };\n }\n}\n\n/**\n * JSON representation of SessionSummary for database storage.\n */\nexport interface SessionSummaryJSON {\n totalDuration: number;\n totalLLMUsage: LanguageModelUsage;\n llmCallCount: number;\n llmCalls: LLMCallRecord[];\n toolCalls: ToolCallSummary[];\n customRecords: Record<string, unknown>[];\n llmCost: number;\n additionalCosts: AdditionalCost[];\n metadata: Record<string, unknown>;\n costByModel: Record<string, number>;\n totalCost: number;\n totalAdditionalCost: number;\n}\n\n/**\n * Session for tracking LLM calls, tool calls, and custom records.\n * Provides AI SDK wrappers with auto-tracking and manual recording methods.\n */\nexport interface ExecutionSession {\n generateText(params: GenerateTextParams): Promise<Awaited<ReturnType<typeof aiGenerateText>>>;\n streamText(params: StreamTextParams): ReturnType<typeof aiStreamText>;\n generateObject<T>(\n params: GenerateObjectParams & { schema: import('zod').ZodType<T> }\n ): Promise<Awaited<ReturnType<typeof aiGenerateObject>>>;\n\n recordToolCall(summary: ToolCallSummary): void;\n recordLLMCall(record: Omit<LLMCallRecord, 'type'> & { type?: LLMCallType }): void;\n record(data: Record<string, unknown>): void;\n\n recordAdditionalCost(cost: Omit<AdditionalCost, 'timestamp'>): void;\n setMetadata(key: string, value: unknown): void;\n setMetadata(data: Record<string, unknown>): void;\n\n summary(): Promise<SessionSummary>;\n}\n\n/**\n * Metadata passed to done() and fail() in StreamGeneratorControl.\n * Union of SessionSummary and ExecutionMetadata for flexible usage.\n */\nexport type DoneMetadata = SessionSummary | ExecutionMetadata;\n","import {\n generateText as aiGenerateText,\n streamText as aiStreamText,\n} from 'ai';\nimport type {\n LanguageModel,\n LanguageModelUsage,\n ToolSet,\n} from 'ai';\nimport merge from 'lodash/merge';\nimport type { Logger } from '@/observability/logger';\nimport { noopLogger } from '@/observability/logger';\nimport type { FileManager } from '@/provider/types';\nimport type { ProviderType, ProviderPricing } from '@/pricing/types';\nimport { calculateTotalCost } from '@/pricing/calculator';\nimport {\n SessionSummary,\n type DefaultOutput,\n type GenerateTextParams,\n type GenerateTextResultTyped,\n type StreamTextParams,\n type StreamTextResultTyped,\n type LLMCallRecord,\n type LLMCallType,\n type ToolCallSummary,\n type OutputSpec,\n type AdditionalCost,\n} from './types';\nimport { mergeUsages, createZeroUsage } from './usage-extractors';\n\n/**\n * Provider-specific options type.\n * Maps provider names (e.g., 'google', 'openai') to their option objects.\n */\ntype ProviderOptions = Record<string, Record<string, unknown>>;\n\nexport interface SimpleSessionOptions {\n defaultLanguageModel?: LanguageModel | null;\n modelFactory?: (modelId: string) => LanguageModel;\n providerType: ProviderType;\n providerPricing?: ProviderPricing;\n fileManager: FileManager;\n logger?: Logger;\n startTime?: number;\n /**\n * AbortSignal for cancelling AI SDK calls.\n * When aborted, ongoing generateText/streamText calls will be cancelled.\n */\n signal?: AbortSignal;\n /**\n * Default provider-specific options to apply to all LLM calls.\n * These will be deep-merged with per-call providerOptions (per-call takes precedence).\n */\n defaultProviderOptions?: ProviderOptions;\n /**\n * Default tools to apply to all LLM calls (e.g., google_search, url_context).\n * These will be merged with per-call tools (per-call takes precedence).\n */\n defaultTools?: ToolSet;\n}\n\nexport class SimpleSession {\n private readonly defaultLanguageModel: LanguageModel | null;\n private readonly modelFactory: ((modelId: string) => LanguageModel) | null;\n private readonly providerType: ProviderType;\n private readonly providerPricing: ProviderPricing | undefined;\n private readonly defaultProviderOptions: ProviderOptions | undefined;\n private readonly defaultTools: ToolSet | undefined;\n private readonly _fileManager: FileManager;\n private readonly logger: Logger;\n private readonly sessionStartTime: number;\n private readonly signal?: AbortSignal;\n\n private summary!: SessionSummary;\n private readonly pendingUsagePromises: Promise<LanguageModelUsage | undefined>[] = [];\n\n private readonly onDoneFns: Array<() => Promise<void> | void> = [];\n\n constructor(options: SimpleSessionOptions) {\n this.defaultLanguageModel = options.defaultLanguageModel ?? null;\n this.modelFactory = options.modelFactory ?? null;\n this.providerType = options.providerType;\n this.providerPricing = options.providerPricing;\n this.defaultProviderOptions = options.defaultProviderOptions;\n this.defaultTools = options.defaultTools;\n this._fileManager = options.fileManager;\n this.logger = options.logger ?? noopLogger;\n this.sessionStartTime = options.startTime ?? Date.now();\n this.signal = options.signal;\n this.summary = SessionSummary.empty(this.sessionStartTime);\n }\n\n private getModel(requestedModelId?: string): LanguageModel {\n if (requestedModelId) {\n if (!this.modelFactory) {\n throw new Error(\n `Model '${requestedModelId}' requested but no modelFactory provided. ` +\n `Either use the default model or configure the provider with modelFactory.`\n );\n }\n return this.modelFactory(requestedModelId);\n }\n\n if (!this.defaultLanguageModel) {\n throw new Error(\n 'No model specified and no default model set. ' +\n 'Either specify a model in the call or configure the provider with withDefaultModel().'\n );\n }\n return this.defaultLanguageModel;\n }\n\n private extractModelId(model: LanguageModel): string {\n const modelWithId = model as unknown as { modelId?: string };\n if (!modelWithId.modelId) {\n console.warn(\n '[SimpleSession] Model does not have modelId property, using \"unknown\". ' +\n 'This may affect cost tracking accuracy.'\n );\n }\n return modelWithId.modelId ?? 'unknown';\n }\n\n async generateText<\n TOOLS extends ToolSet = {},\n OUTPUT extends OutputSpec = DefaultOutput,\n >(\n params: GenerateTextParams<TOOLS, OUTPUT>\n ): Promise<GenerateTextResultTyped<TOOLS, OUTPUT>> {\n const callStartTime = Date.now();\n const { model: requestedModel, providerOptions, tools, ...restParams } = params;\n const languageModel = this.getModel(requestedModel);\n const modelId = this.extractModelId(languageModel);\n\n // Deep merge default + per-call options (per-call takes precedence)\n const mergedProviderOptions = (this.defaultProviderOptions || providerOptions)\n ? merge({}, this.defaultProviderOptions ?? {}, providerOptions ?? {})\n : undefined;\n\n // Merge default tools with per-call tools (per-call takes precedence)\n const mergedTools = (this.defaultTools || tools)\n ? { ...this.defaultTools, ...tools }\n : undefined;\n\n this.logger.onLLMCallStart?.({\n type: 'llm_call_start',\n callType: 'generateText',\n modelId,\n timestamp: callStartTime,\n request: { params: restParams as Record<string, unknown> },\n });\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result = await aiGenerateText({\n ...restParams,\n tools: mergedTools,\n providerOptions: mergedProviderOptions,\n model: languageModel,\n abortSignal: this.signal,\n } as any);\n const callEndTime = Date.now();\n\n const call: LLMCallRecord = {\n startTime: callStartTime,\n endTime: callEndTime,\n duration: callEndTime - callStartTime,\n usage: result.usage ?? createZeroUsage(),\n type: 'generateText',\n model: modelId,\n provider: this.providerType,\n };\n this.updateSummaryWithLLMCall(call);\n\n this.logger.onLLMCallEnd?.({\n type: 'llm_call_end',\n callType: 'generateText',\n modelId,\n timestamp: callEndTime,\n response: {\n duration: callEndTime - callStartTime,\n usage: result.usage,\n raw: result,\n },\n });\n\n return result as unknown as GenerateTextResultTyped<TOOLS, OUTPUT>;\n } catch (error) {\n const callEndTime = Date.now();\n\n this.logger.onLLMCallEnd?.({\n type: 'llm_call_end',\n callType: 'generateText',\n modelId,\n timestamp: callEndTime,\n response: {\n duration: callEndTime - callStartTime,\n raw: null,\n error: error instanceof Error ? error : new Error(String(error)),\n },\n });\n\n throw error;\n }\n }\n\n streamText<\n TOOLS extends ToolSet = {},\n OUTPUT extends OutputSpec = DefaultOutput,\n >(params: StreamTextParams<TOOLS, OUTPUT>): StreamTextResultTyped<TOOLS, OUTPUT> {\n const callStartTime = Date.now();\n const { model: requestedModel, providerOptions, tools, ...restParams } = params;\n const languageModel = this.getModel(requestedModel);\n const modelId = this.extractModelId(languageModel);\n\n // Deep merge default + per-call options (per-call takes precedence)\n const mergedProviderOptions = (this.defaultProviderOptions || providerOptions)\n ? merge({}, this.defaultProviderOptions ?? {}, providerOptions ?? {})\n : undefined;\n\n // Merge default tools with per-call tools (per-call takes precedence)\n const mergedTools = (this.defaultTools || tools)\n ? { ...this.defaultTools, ...tools }\n : undefined;\n\n this.logger.onLLMCallStart?.({\n type: 'llm_call_start',\n callType: 'streamText',\n modelId,\n timestamp: callStartTime,\n request: { params: restParams as Record<string, unknown> },\n });\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result = aiStreamText({\n ...restParams,\n tools: mergedTools,\n providerOptions: mergedProviderOptions,\n model: languageModel,\n abortSignal: this.signal,\n } as any);\n\n const usagePromise = Promise.resolve(result.usage).then((usage) => {\n const callEndTime = Date.now();\n\n const call: LLMCallRecord = {\n startTime: callStartTime,\n endTime: callEndTime,\n duration: callEndTime - callStartTime,\n usage: usage ?? createZeroUsage(),\n type: 'streamText',\n model: modelId,\n provider: this.providerType,\n };\n this.updateSummaryWithLLMCall(call);\n\n this.logger.onLLMCallEnd?.({\n type: 'llm_call_end',\n callType: 'streamText',\n modelId,\n timestamp: callEndTime,\n response: {\n duration: callEndTime - callStartTime,\n usage,\n raw: result,\n },\n });\n\n return usage;\n });\n\n this.pendingUsagePromises.push(usagePromise);\n\n return result as unknown as StreamTextResultTyped<TOOLS, OUTPUT>;\n }\n\n get fileManager(): FileManager {\n return this._fileManager;\n }\n\n record(data: Record<string, unknown>): void {\n this.summary = this.summary.withCustomRecord(data);\n }\n\n recordToolCall(toolCallSummary: ToolCallSummary): void {\n this.summary = this.summary.withToolCall(toolCallSummary);\n }\n\n recordLLMCall(record: Omit<LLMCallRecord, 'type'> & { type?: LLMCallType }): void {\n const call: LLMCallRecord = {\n ...record,\n type: record.type ?? 'manual',\n };\n this.updateSummaryWithLLMCall(call);\n }\n\n recordAdditionalCost(cost: Omit<AdditionalCost, 'timestamp'>): void {\n this.summary = this.summary.withAdditionalCost({\n ...cost,\n timestamp: Date.now(),\n });\n }\n\n setMetadata(key: string, value: unknown): void;\n setMetadata(data: Record<string, unknown>): void;\n setMetadata(keyOrData: string | Record<string, unknown>, value?: unknown): void {\n if (typeof keyOrData === 'string') {\n this.summary = this.summary.withMetadata(keyOrData, value);\n } else {\n for (const [k, v] of Object.entries(keyOrData)) {\n this.summary = this.summary.withMetadata(k, v);\n }\n }\n }\n\n private updateSummaryWithLLMCall(call: LLMCallRecord): void {\n const newCalls = [...this.summary.llmCalls, call];\n const { totalCost: llmCost, costByModel } = calculateTotalCost(\n newCalls.map((c) => ({ usage: c.usage, model: c.model, provider: c.provider })),\n this.providerPricing\n );\n const newTotalUsage = mergeUsages(newCalls.map((c) => c.usage));\n\n this.summary = this.summary.withLLMCall(call, llmCost, costByModel, newTotalUsage);\n }\n\n onDone(fn: () => Promise<void> | void): void {\n this.onDoneFns.push(fn);\n }\n\n async runOnDoneHooks(): Promise<void> {\n const reversedHooks = [...this.onDoneFns].reverse();\n\n for (const fn of reversedHooks) {\n try {\n await fn();\n } catch (error) {\n console.error('[SimpleSession] onDone hook error:', error);\n }\n }\n }\n\n async getSummary(): Promise<SessionSummary> {\n await Promise.all(this.pendingUsagePromises);\n return this.summary;\n }\n\n /**\n * Notifies Logger of execution start.\n * @internal Called by SimpleExecutionHost - not intended for direct use.\n */\n notifyExecutionStart(): void {\n this._logger.onExecutionStart?.({\n type: 'execution_start',\n timestamp: Date.now(),\n });\n }\n\n /**\n * Notifies Logger of execution completion with result data and summary.\n * @param data - The execution result data\n * @param startTime - Execution start timestamp for duration calculation\n * @internal Called by SimpleExecutionHost - not intended for direct use.\n */\n async notifyExecutionDone<T>(data: T, startTime: number): Promise<void> {\n const summary = await this.getSummary();\n this._logger.onExecutionDone?.({\n type: 'execution_done',\n timestamp: Date.now(),\n duration: Date.now() - startTime,\n data,\n summary,\n });\n }\n\n /**\n * Notifies Logger of execution error with error details and summary (if available).\n * Gracefully handles getSummary() failures - summary will be undefined if it fails.\n * @param error - The error that occurred\n * @param startTime - Execution start timestamp for duration calculation\n * @internal Called by SimpleExecutionHost - not intended for direct use.\n */\n async notifyExecutionError(error: Error, startTime: number): Promise<void> {\n let summary: SessionSummary | undefined;\n try {\n summary = await this.getSummary();\n } catch {\n // Ignore summary errors on failure path\n }\n this._logger.onExecutionError?.({\n type: 'execution_error',\n timestamp: Date.now(),\n duration: Date.now() - startTime,\n error,\n summary,\n });\n }\n\n protected get _logger(): Logger {\n return this.logger;\n }\n\n protected get _startTime(): number {\n return this.sessionStartTime;\n }\n\n protected get _modelId(): string {\n if (!this.defaultLanguageModel) {\n return 'unknown';\n }\n return this.extractModelId(this.defaultLanguageModel);\n }\n}\n","import type { LanguageModel, ToolSet } from 'ai';\nimport type { EventMetrics } from '@/observability';\nimport type { Logger } from '@/observability/logger';\nimport { noopLogger } from '@/observability/logger';\nimport type { FileManager } from '@/provider/types';\nimport type { ProviderType, ProviderPricing } from '@/pricing/types';\nimport type { SessionSummary } from './types';\nimport { SimpleSession } from './simple-session';\nimport type { SessionEvent, EmittableEventInput, ExtractResult } from '@/execution/types';\n\ntype ProviderOptions = Record<string, Record<string, unknown>>;\n\nexport interface StreamingSessionOptions {\n defaultLanguageModel?: LanguageModel | null;\n modelFactory?: (modelId: string) => LanguageModel;\n providerType: ProviderType;\n providerPricing?: ProviderPricing;\n fileManager: FileManager;\n logger?: Logger;\n startTime?: number;\n signal?: AbortSignal;\n defaultProviderOptions?: ProviderOptions;\n defaultTools?: ToolSet;\n}\n\nexport class StreamingSession<TEvent extends { type: string }> extends SimpleSession {\n private lastEventTime: number;\n private _terminated = false;\n\n constructor(options: StreamingSessionOptions) {\n super({\n defaultLanguageModel: options.defaultLanguageModel,\n modelFactory: options.modelFactory,\n providerType: options.providerType,\n providerPricing: options.providerPricing,\n fileManager: options.fileManager,\n logger: options.logger,\n startTime: options.startTime,\n signal: options.signal,\n defaultProviderOptions: options.defaultProviderOptions,\n defaultTools: options.defaultTools,\n });\n\n this.lastEventTime = this._startTime;\n\n this._logger.onExecutionStart?.({\n type: 'execution_start',\n timestamp: Date.now(),\n });\n }\n\n /**\n * Emits a streaming event with automatically attached metrics.\n *\n * Reserved types ('complete', 'error') throw at runtime - use session.done()\n * or session.fail() instead.\n *\n * @param event - The event to emit (metrics will be added automatically)\n * @returns The complete event with metrics attached\n * @throws Error when attempting to emit reserved types ('complete', 'error')\n */\n emit(event: EmittableEventInput<TEvent>): SessionEvent<TEvent> {\n if (this._terminated) {\n throw new Error('Session already terminated. Cannot call emit() after a terminal operation.');\n }\n\n // Runtime check: prevent reserved types even when TypeScript is bypassed\n const eventType = (event as { type: string }).type;\n if (eventType === 'complete' || eventType === 'error') {\n throw new Error(\n `Cannot emit reserved type \"${eventType}\". ` +\n 'Use session.done() for completion or session.fail() for errors.'\n );\n }\n\n return this.emitInternal(event as TEvent);\n }\n\n /**\n * Internal emit method - bypasses reserved type check.\n * Used by done() and fail() to emit terminal events.\n */\n private emitInternal(event: TEvent): SessionEvent<TEvent> {\n const metrics = this.createMetrics();\n const fullEvent = { ...event, metrics } as SessionEvent<TEvent>;\n\n this._logger.onExecutionEmit?.({\n type: 'execution_emit',\n event: fullEvent,\n });\n\n return fullEvent;\n }\n\n /**\n * Signals successful completion of the streaming execution.\n * Emits a 'complete' event with the result data and session summary.\n * Also triggers Logger.onExecutionDone for observability.\n * @param data - The final result data\n * @returns The complete event with data and summary\n */\n async done(data: ExtractResult<TEvent>): Promise<SessionEvent<TEvent>> {\n if (this._terminated) {\n throw new Error('Session already terminated. Cannot call done() after a terminal operation.');\n }\n this._terminated = true;\n\n const summary = await this.getSummary();\n\n this._logger.onExecutionDone?.({\n type: 'execution_done',\n timestamp: Date.now(),\n duration: summary.totalDuration,\n data,\n summary,\n });\n\n // Use emitInternal to bypass reserved type check (internal only)\n return this.emitInternal({\n type: 'complete',\n data,\n summary,\n } as unknown as Extract<TEvent, { type: 'complete' }>);\n }\n\n /**\n * Signals that the streaming execution failed with an error.\n * Emits an 'error' event and triggers Logger.onExecutionError for observability.\n * Gracefully handles getSummary() failures - summary will be undefined if it fails.\n * @param error - The error that caused the failure\n * @param data - Optional partial result data (if any was produced before failure)\n * @returns The error event\n */\n async fail(error: Error, data?: ExtractResult<TEvent>): Promise<SessionEvent<TEvent>> {\n if (this._terminated) {\n throw new Error('Session already terminated. Cannot call fail() after a terminal operation.');\n }\n this._terminated = true;\n\n let summary: SessionSummary | undefined;\n try {\n summary = await this.getSummary();\n } catch {\n // Ignore summary errors on failure path\n }\n\n this._logger.onExecutionError?.({\n type: 'execution_error',\n timestamp: Date.now(),\n duration: summary?.totalDuration ?? (Date.now() - this._startTime),\n error,\n data,\n summary,\n });\n\n const errorEvent: Record<string, unknown> = {\n type: 'error',\n error,\n };\n\n if (summary) {\n errorEvent.summary = summary;\n }\n\n if (data !== undefined) {\n errorEvent.data = data;\n }\n\n // Use emitInternal to bypass reserved type check (internal only)\n return this.emitInternal(errorEvent as unknown as Extract<TEvent, { type: 'error' }>);\n }\n\n private createMetrics(): EventMetrics {\n const now = Date.now();\n const metrics: EventMetrics = {\n timestamp: now,\n elapsedMs: now - this._startTime,\n deltaMs: now - this.lastEventTime,\n };\n this.lastEventTime = now;\n return metrics;\n }\n}\n\nexport interface StreamingSessionInternal<TEvent extends { type: string }> {\n generateText: SimpleSession['generateText'];\n streamText: SimpleSession['streamText'];\n fileManager: FileManager;\n onDone: SimpleSession['onDone'];\n record: SimpleSession['record'];\n recordToolCall: SimpleSession['recordToolCall'];\n\n emit(event: EmittableEventInput<TEvent>): SessionEvent<TEvent>;\n done(data: ExtractResult<TEvent>): Promise<SessionEvent<TEvent>>;\n fail(error: Error, data?: ExtractResult<TEvent>): Promise<SessionEvent<TEvent>>;\n\n runOnDoneHooks(): Promise<void>;\n getSummary(): Promise<SessionSummary>;\n}\n\nexport interface CreateStreamingSessionOptions {\n defaultLanguageModel: LanguageModel;\n providerType: ProviderType;\n fileManager: FileManager;\n logger?: Logger;\n startTime?: number;\n signal?: AbortSignal;\n}\n\nexport function createStreamingSession<TEvent extends { type: string }>(\n options: CreateStreamingSessionOptions\n): StreamingSessionInternal<TEvent> {\n const session = new StreamingSession<TEvent>({\n defaultLanguageModel: options.defaultLanguageModel,\n providerType: options.providerType,\n fileManager: options.fileManager,\n logger: options.logger ?? noopLogger,\n startTime: options.startTime,\n signal: options.signal,\n });\n\n return session as unknown as StreamingSessionInternal<TEvent>;\n}\n","import type { LanguageModel } from 'ai';\nimport { createGoogleGenerativeAI, type GoogleGenerativeAIProviderOptions } from '@ai-sdk/google';\nimport type { Logger } from '@/observability/logger';\nimport { noopLogger } from '@/observability/logger';\nimport type { ProviderPricing } from '@/pricing';\nimport { validateProviderPricing } from '@/pricing';\nimport { GoogleFileManager } from './file-manager';\nimport { SimpleSession } from '@/session/simple-session';\nimport { StreamingSession } from '@/session/streaming-session';\nimport { BaseProvider } from '../base-provider';\nimport type { FileCache } from '../types';\nimport { InMemoryFileCache } from '../file-cache';\n\nexport type HarmCategory =\n | 'HARM_CATEGORY_HATE_SPEECH'\n | 'HARM_CATEGORY_SEXUALLY_EXPLICIT'\n | 'HARM_CATEGORY_DANGEROUS_CONTENT'\n | 'HARM_CATEGORY_HARASSMENT'\n | 'HARM_CATEGORY_CIVIC_INTEGRITY';\n\nexport type HarmBlockThreshold =\n | 'BLOCK_NONE'\n | 'BLOCK_ONLY_HIGH'\n | 'BLOCK_MEDIUM_AND_ABOVE'\n | 'BLOCK_LOW_AND_ABOVE'\n | 'OFF';\n\nexport interface SafetySetting {\n category: HarmCategory;\n threshold: HarmBlockThreshold;\n}\n\nexport interface GoogleProviderConfig {\n apiKey: string;\n safetySettings?: SafetySetting[];\n}\n\nexport class GoogleProvider extends BaseProvider {\n private readonly google: ReturnType<typeof createGoogleGenerativeAI>;\n\n constructor(\n private readonly apiKey: string,\n private readonly defaultModelId: string | null,\n private readonly logger: Logger,\n private readonly safetySettings?: SafetySetting[],\n private readonly pricingConfig?: ProviderPricing,\n private readonly defaultOptions?: GoogleGenerativeAIProviderOptions,\n private readonly searchEnabled: boolean = false,\n private readonly urlContextEnabled: boolean = false,\n private readonly fileCache?: FileCache,\n ) {\n super();\n this.google = createGoogleGenerativeAI({ apiKey });\n }\n\n withDefaultModel(modelId: string): GoogleProvider {\n return new GoogleProvider(\n this.apiKey,\n modelId,\n this.logger,\n this.safetySettings,\n this.pricingConfig,\n this.defaultOptions,\n this.searchEnabled,\n this.urlContextEnabled,\n this.fileCache,\n );\n }\n\n withLogger(newLogger: Logger): GoogleProvider {\n return new GoogleProvider(\n this.apiKey,\n this.defaultModelId,\n newLogger,\n this.safetySettings,\n this.pricingConfig,\n this.defaultOptions,\n this.searchEnabled,\n this.urlContextEnabled,\n this.fileCache,\n );\n }\n\n withPricing(pricing: ProviderPricing): GoogleProvider {\n validateProviderPricing(pricing, 'google');\n return new GoogleProvider(\n this.apiKey,\n this.defaultModelId,\n this.logger,\n this.safetySettings,\n pricing,\n this.defaultOptions,\n this.searchEnabled,\n this.urlContextEnabled,\n this.fileCache,\n );\n }\n\n /**\n * Set default provider-specific options for all LLM calls.\n * These options will be deep-merged with per-call providerOptions.\n *\n * @example\n * ```typescript\n * createGoogleProvider({ apiKey: 'xxx' })\n * .withDefaultModel('gemini-2.0-flash-thinking-exp')\n * .withDefaultOptions({\n * thinkingConfig: { includeThoughts: true, thinkingLevel: 'low' }\n * })\n * ```\n */\n withDefaultOptions(options: GoogleGenerativeAIProviderOptions): GoogleProvider {\n return new GoogleProvider(\n this.apiKey,\n this.defaultModelId,\n this.logger,\n this.safetySettings,\n this.pricingConfig,\n options,\n this.searchEnabled,\n this.urlContextEnabled,\n this.fileCache,\n );\n }\n\n /**\n * Enable Google Search grounding for all LLM calls.\n * Allows the model to access real-time web information.\n *\n * @example\n * ```typescript\n * createGoogleProvider({ apiKey: 'xxx' })\n * .withDefaultModel('gemini-2.5-flash')\n * .withSearchEnabled()\n * ```\n */\n withSearchEnabled(): GoogleProvider {\n return new GoogleProvider(\n this.apiKey,\n this.defaultModelId,\n this.logger,\n this.safetySettings,\n this.pricingConfig,\n this.defaultOptions,\n true,\n this.urlContextEnabled,\n this.fileCache,\n );\n }\n\n /**\n * Enable URL Context grounding for all LLM calls.\n * Allows the model to retrieve and use content from URLs in the prompt.\n *\n * @example\n * ```typescript\n * createGoogleProvider({ apiKey: 'xxx' })\n * .withDefaultModel('gemini-2.5-flash')\n * .withUrlContextEnabled()\n * ```\n */\n withUrlContextEnabled(): GoogleProvider {\n return new GoogleProvider(\n this.apiKey,\n this.defaultModelId,\n this.logger,\n this.safetySettings,\n this.pricingConfig,\n this.defaultOptions,\n this.searchEnabled,\n true,\n this.fileCache,\n );\n }\n\n /**\n * Set a file cache for reusing uploaded files across sessions.\n * If no cache is provided, creates a new InMemoryFileCache.\n *\n * @example\n * ```typescript\n * // Use default InMemoryFileCache\n * createGoogleProvider({ apiKey: 'xxx' })\n * .withFileCache()\n *\n * // Use custom cache with TTL\n * const cache = new InMemoryFileCache({ defaultTTL: 3600000 });\n * createGoogleProvider({ apiKey: 'xxx' })\n * .withFileCache(cache)\n * ```\n */\n withFileCache(cache?: FileCache): GoogleProvider {\n return new GoogleProvider(\n this.apiKey,\n this.defaultModelId,\n this.logger,\n this.safetySettings,\n this.pricingConfig,\n this.defaultOptions,\n this.searchEnabled,\n this.urlContextEnabled,\n cache ?? new InMemoryFileCache(),\n );\n }\n\n private getSessionConfig() {\n // Build default tools based on enabled grounding features\n const defaultTools = {\n ...(this.searchEnabled && { google_search: this.google.tools.googleSearch({}) }),\n ...(this.urlContextEnabled && { url_context: this.google.tools.urlContext({}) }),\n };\n const hasDefaultTools = this.searchEnabled || this.urlContextEnabled;\n\n return {\n defaultLanguageModel: this.defaultModelId\n ? this.createModel(this.defaultModelId)\n : null,\n modelFactory: (modelId: string) => this.createModel(modelId),\n providerType: 'google' as const,\n providerPricing: this.pricingConfig,\n fileManager: new GoogleFileManager(this.apiKey, { cache: this.fileCache }),\n logger: this.logger,\n defaultProviderOptions: this.defaultOptions\n ? { google: this.defaultOptions }\n : undefined,\n defaultTools: hasDefaultTools ? defaultTools : undefined,\n };\n }\n\n protected createStreamingSession<\n TEvent extends { type: string },\n >(signal?: AbortSignal): StreamingSession<TEvent> {\n return new StreamingSession<TEvent>({ ...this.getSessionConfig(), signal });\n }\n\n protected createSimpleSession(signal?: AbortSignal): SimpleSession {\n return new SimpleSession({ ...this.getSessionConfig(), signal });\n }\n\n /**\n * Type assertion needed because @ai-sdk/google's type signature doesn't\n * include the second parameter, but it's supported at runtime.\n */\n private createModel(modelId: string): LanguageModel {\n if (this.safetySettings) {\n return (\n this.google as (\n id: string,\n opts?: { safetySettings?: SafetySetting[] }\n ) => LanguageModel\n )(modelId, { safetySettings: this.safetySettings });\n }\n return this.google(modelId);\n }\n}\n\nexport function createGoogleProvider(config: GoogleProviderConfig): GoogleProvider {\n return new GoogleProvider(\n config.apiKey,\n null, // No default model - must be set with withDefaultModel()\n noopLogger,\n config.safetySettings\n );\n}\n\n// Re-export provider options type for consumers\nexport type { GoogleGenerativeAIProviderOptions } from '@ai-sdk/google';\n","import { createOpenAI, type OpenAIChatLanguageModelOptions } from '@ai-sdk/openai';\nimport type { FileCache } from '../types';\nimport type { Logger } from '@/observability/logger';\nimport { noopLogger } from '@/observability/logger';\nimport type { ProviderPricing } from '@/pricing';\nimport { validateProviderPricing } from '@/pricing';\nimport { NoOpFileManager } from '../noop-file-manager';\nimport { SimpleSession } from '@/session/simple-session';\nimport { StreamingSession } from '@/session/streaming-session';\nimport { BaseProvider } from '../base-provider';\n\nexport interface OpenAIProviderConfig {\n apiKey: string;\n baseURL?: string;\n organization?: string;\n}\n\nclass OpenAIProvider extends BaseProvider {\n private readonly openai: ReturnType<typeof createOpenAI>;\n\n constructor(\n private readonly apiKey: string,\n private readonly defaultModelId: string | null,\n private readonly logger: Logger,\n private readonly baseURL?: string,\n private readonly organization?: string,\n private readonly pricingConfig?: ProviderPricing,\n private readonly defaultOptions?: OpenAIChatLanguageModelOptions,\n private readonly fileCache?: FileCache,\n ) {\n super();\n this.openai = createOpenAI({\n apiKey,\n baseURL,\n organization,\n });\n }\n\n withDefaultModel(modelId: string): OpenAIProvider {\n return new OpenAIProvider(\n this.apiKey,\n modelId,\n this.logger,\n this.baseURL,\n this.organization,\n this.pricingConfig,\n this.defaultOptions,\n this.fileCache,\n );\n }\n\n withLogger(newLogger: Logger): OpenAIProvider {\n return new OpenAIProvider(\n this.apiKey,\n this.defaultModelId,\n newLogger,\n this.baseURL,\n this.organization,\n this.pricingConfig,\n this.defaultOptions,\n this.fileCache,\n );\n }\n\n withPricing(pricing: ProviderPricing): OpenAIProvider {\n validateProviderPricing(pricing, 'openai');\n return new OpenAIProvider(\n this.apiKey,\n this.defaultModelId,\n this.logger,\n this.baseURL,\n this.organization,\n pricing,\n this.defaultOptions,\n this.fileCache,\n );\n }\n\n /**\n * Set default provider-specific options for all LLM calls.\n * These options will be deep-merged with per-call providerOptions.\n *\n * @example\n * ```typescript\n * createOpenAIProvider({ apiKey: 'xxx' })\n * .withDefaultModel('gpt-4o')\n * .withDefaultOptions({\n * reasoningEffort: 'high',\n * parallelToolCalls: true,\n * })\n * ```\n */\n withDefaultOptions(options: OpenAIChatLanguageModelOptions): OpenAIProvider {\n return new OpenAIProvider(\n this.apiKey,\n this.defaultModelId,\n this.logger,\n this.baseURL,\n this.organization,\n this.pricingConfig,\n options,\n this.fileCache,\n );\n }\n\n /**\n * Set a file cache for API consistency with GoogleProvider.\n * Note: OpenAI does not support file caching, so this is a no-op.\n *\n * @example\n * ```typescript\n * createOpenAIProvider({ apiKey: 'xxx' })\n * .withFileCache()\n * ```\n */\n withFileCache(cache?: FileCache): OpenAIProvider {\n return new OpenAIProvider(\n this.apiKey,\n this.defaultModelId,\n this.logger,\n this.baseURL,\n this.organization,\n this.pricingConfig,\n this.defaultOptions,\n cache,\n );\n }\n\n private getSessionConfig() {\n return {\n defaultLanguageModel: this.defaultModelId ? this.openai(this.defaultModelId) : null,\n modelFactory: (modelId: string) => this.openai(modelId),\n providerType: 'openai' as const,\n providerPricing: this.pricingConfig,\n fileManager: new NoOpFileManager(),\n logger: this.logger,\n defaultProviderOptions: this.defaultOptions\n ? { openai: this.defaultOptions }\n : undefined,\n };\n }\n\n protected createStreamingSession<\n TEvent extends { type: string },\n >(signal?: AbortSignal): StreamingSession<TEvent> {\n return new StreamingSession<TEvent>({ ...this.getSessionConfig(), signal });\n }\n\n protected createSimpleSession(signal?: AbortSignal): SimpleSession {\n return new SimpleSession({ ...this.getSessionConfig(), signal });\n }\n}\n\nexport function createOpenAIProvider(config: OpenAIProviderConfig): OpenAIProvider {\n return new OpenAIProvider(\n config.apiKey,\n null, // No default model - must be set with withDefaultModel()\n noopLogger,\n config.baseURL,\n config.organization\n );\n}\n\n// Re-export provider options type for consumers\nexport type { OpenAIChatLanguageModelOptions } from '@ai-sdk/openai';\n","import type {\n ValidationResult,\n ValidationAttempt,\n ReadonlyValidationHistory,\n} from './types';\n\nexport class ValidationHistory<TResult>\n implements ReadonlyValidationHistory<TResult>\n{\n private attempts: ValidationAttempt<TResult>[] = [];\n\n get nextAttempt(): number {\n return this.attempts.length + 1;\n }\n\n get last(): ValidationAttempt<TResult> | undefined {\n return this.attempts.at(-1);\n }\n\n get all(): readonly ValidationAttempt<TResult>[] {\n return this.attempts;\n }\n\n get failureReasons(): string[] {\n return this.attempts\n .filter((a) => !a.valid && a.reason)\n .map((a) => a.reason!);\n }\n\n get isRetry(): boolean {\n return this.attempts.length > 0;\n }\n\n /** Internal use only - not exposed via ReadonlyValidationHistory. */\n add(result: TResult, validation: ValidationResult): void {\n this.attempts.push({\n result,\n ...validation,\n attempt: this.attempts.length + 1,\n });\n }\n}\n","import { AgtlantisError, type AgtlantisErrorCode } from '../errors';\nimport type { ReadonlyValidationHistory } from './types';\n\nexport enum ValidationErrorCode {\n VALIDATION_EXHAUSTED = 'VALIDATION_EXHAUSTED',\n}\n\n/**\n * Error thrown when validation fails after all attempts are exhausted.\n * Contains the full validation history for debugging and partial result recovery.\n *\n * @example\n * ```typescript\n * try {\n * const result = await withValidation(execute, options);\n * } catch (e) {\n * if (e instanceof ValidationExhaustedError) {\n * console.log(`Failed after ${e.history.all.length} attempts`);\n * console.log('Last result:', e.history.last?.result);\n * console.log('All failures:', e.history.failureReasons);\n * console.log('Error code:', e.code); // 'VALIDATION_EXHAUSTED'\n * }\n * }\n * ```\n */\nexport class ValidationExhaustedError<TResult> extends AgtlantisError<\n ValidationErrorCode & AgtlantisErrorCode\n> {\n constructor(\n message: string,\n public readonly history: ReadonlyValidationHistory<TResult>\n ) {\n super(message, {\n code: ValidationErrorCode.VALIDATION_EXHAUSTED as ValidationErrorCode & AgtlantisErrorCode,\n context: {\n attempts: history.all.length,\n failureReasons: history.failureReasons,\n },\n });\n this.name = 'ValidationExhaustedError';\n }\n}\n","import type { ReadonlyValidationHistory, ValidationOptions } from './types';\nimport { ValidationHistory } from './validation-history';\nimport { ValidationExhaustedError } from './errors';\n\n/**\n * Wraps an async operation with validation and retry logic.\n *\n * Executes the function and validates the result. If validation fails,\n * retries up to maxAttempts times, passing the history to the execute\n * function so it can adjust its approach based on previous failures.\n *\n * @param execute - Function to execute. Receives history for retry context.\n * @param options - Validation options including the validate function.\n * @returns The first result that passes validation.\n * @throws {ValidationExhaustedError} If all attempts fail validation.\n *\n * @example\n * ```typescript\n * const result = await withValidation(\n * (history) => session.generateText({\n * messages: [\n * { role: 'user', content: prompt },\n * ...(history.isRetry ? [{\n * role: 'user' as const,\n * content: `Fix: ${history.last!.reason}`,\n * }] : []),\n * ],\n * schema,\n * }),\n * {\n * validate: (result) => ({\n * valid: result.confidence > 0.8,\n * reason: `Confidence ${result.confidence} below 0.8`,\n * }),\n * maxAttempts: 3,\n * }\n * );\n * ```\n */\nexport async function withValidation<TResult>(\n execute: (history: ReadonlyValidationHistory<NoInfer<TResult>>) => Promise<TResult>,\n options: ValidationOptions<NoInfer<TResult>>\n): Promise<TResult> {\n const { validate, maxAttempts: rawMax, signal, retryDelay, onAttempt } = options;\n const maxAttempts = Math.max(1, rawMax ?? 3);\n const history = new ValidationHistory<TResult>();\n\n while (history.nextAttempt <= maxAttempts) {\n signal?.throwIfAborted();\n\n const result = await execute(history);\n const validation = await validate(result, history);\n history.add(result, validation);\n\n onAttempt?.(history.last!);\n\n if (validation.valid) {\n return result;\n }\n\n const hasMoreAttempts = history.nextAttempt <= maxAttempts;\n if (retryDelay && hasMoreAttempts) {\n await new Promise((resolve) => setTimeout(resolve, retryDelay));\n }\n }\n\n throw new ValidationExhaustedError(\n `Validation failed after ${history.all.length} attempts`,\n history\n );\n}\n"]}