import { type ImageContent, type Message, type SimpleStreamOptions, type ThinkingBudgets, type Transport } from "@leanandmean/ai"; import type { AfterToolCallContext, AfterToolCallResult, AgentEvent, AgentLoopConfig, AgentLoopTurnUpdate, AgentMessage, AgentState, AgentTool, BeforeToolBatchContext, BeforeToolCallContext, BeforeToolCallResult, PrepareNextTurnContext, QueueMode, StreamFn, ToolExecutionMode } from "./types.js"; export type { QueueMode } from "./types.js"; export declare function generateHarnessToolCallId(): string; /** Options for constructing an {@link Agent}. */ export interface AgentOptions { initialState?: Partial>; convertToLlm?: (messages: AgentMessage[]) => Message[] | Promise; transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise; beforeProviderCall?: AgentLoopConfig["beforeProviderCall"]; streamFn?: StreamFn; getApiKey?: (provider: string) => Promise | string | undefined; onPayload?: SimpleStreamOptions["onPayload"]; onResponse?: SimpleStreamOptions["onResponse"]; beforeToolBatch?: (context: BeforeToolBatchContext, signal?: AbortSignal) => Promise; beforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise; afterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise; prepareNextTurn?: (ctx: PrepareNextTurnContext, signal?: AbortSignal) => Promise | AgentLoopTurnUpdate | undefined; steeringMode?: QueueMode; followUpMode?: QueueMode; sessionId?: string; thinkingBudgets?: ThinkingBudgets; transport?: Transport; maxRetryDelayMs?: number; toolExecution?: ToolExecutionMode; } /** * Stateful wrapper around the low-level agent loop. * * `Agent` owns the current transcript, emits lifecycle events, executes tools, * and exposes queueing APIs for steering and follow-up messages. */ export declare class Agent { private _state; private readonly listeners; private readonly steeringQueue; private readonly followUpQueue; convertToLlm: (messages: AgentMessage[]) => Message[] | Promise; transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise; beforeProviderCall?: AgentLoopConfig["beforeProviderCall"]; streamFn: StreamFn; getApiKey?: (provider: string) => Promise | string | undefined; onPayload?: SimpleStreamOptions["onPayload"]; onResponse?: SimpleStreamOptions["onResponse"]; beforeToolBatch?: (context: BeforeToolBatchContext, signal?: AbortSignal) => Promise; beforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise; afterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise; prepareNextTurn?: (ctx: PrepareNextTurnContext, signal?: AbortSignal) => Promise | AgentLoopTurnUpdate | undefined; private activeRun?; /** Harness tool invocations queued while a run is active, drained at the next turn boundary. */ private readonly harnessToolQueue; /** * Every harness-tool invocation whose public promise has not yet settled — queued, shifted and * draining, or transient. Reset/teardown rejects this set; each invocation is removed as it * settles. Queue length is not a proxy for this: a draining call has left the queue but is still * unsettled (#341). */ private readonly unsettledHarnessTools; /** * Markers for in-flight transient (idle) harness-tool runs; each resolves when its run settles. * A set (not a single field) keeps nested and overlapping transient runs valid, and lets a new * real run wait for transient work to finish before emitting its own events. */ private readonly transientRuns; /** Shared, never-aborted signal delivered to listeners during transient harness-tool runs. */ private readonly transientRunAbort; /** Session identifier forwarded to providers for cache-aware backends. */ sessionId?: string; /** Optional per-level thinking token budgets forwarded to the stream function. */ thinkingBudgets?: ThinkingBudgets; /** Preferred transport forwarded to the stream function. */ transport: Transport; /** Optional cap for provider-requested retry delays. */ maxRetryDelayMs?: number; /** Tool execution strategy for assistant messages that contain multiple tool calls. */ toolExecution: ToolExecutionMode; constructor(options?: AgentOptions); /** * Subscribe to agent lifecycle events. * * Listener promises are awaited in subscription order and are included in * the current run's settlement. Listeners also receive the active abort * signal for the current run. * * `agent_end` is the final emitted event for a run, but the agent does not * become idle until all awaited listeners for that event have settled. */ subscribe(listener: (event: AgentEvent, signal: AbortSignal) => Promise | void): () => void; /** * Current agent state. * * Assigning `state.tools` or `state.messages` copies the provided top-level array. */ get state(): AgentState; /** Controls how queued steering messages are drained. */ set steeringMode(mode: QueueMode); get steeringMode(): QueueMode; /** Controls how queued follow-up messages are drained. */ set followUpMode(mode: QueueMode); get followUpMode(): QueueMode; /** Queue a message to be injected after the current assistant turn finishes. */ steer(message: AgentMessage): void; /** Queue a message to run only after the agent would otherwise stop. */ followUp(message: AgentMessage): void; /** Remove all queued steering messages. */ clearSteeringQueue(): void; /** Remove all queued follow-up messages. */ clearFollowUpQueue(): void; /** Remove all queued steering and follow-up messages. */ clearAllQueues(): void; /** Returns true when either queue still contains pending messages. */ hasQueuedMessages(): boolean; /** Active abort signal for the current run, if any. */ get signal(): AbortSignal | undefined; /** Abort the current run, if one is active. */ abort(): void; /** * Resolve when the current run and all awaited event listeners have finished. * * This resolves after `agent_end` listeners settle. */ waitForIdle(): Promise; /** Capture the active execution; rejects on escaping failure and is undefined outside a run. */ getRunExecution(): Promise | undefined; get hasActiveTransientHarnessTools(): boolean; /** Clear transcript state, runtime state, and queued messages. */ reset(): void; /** Start a new prompt from text, a single message, or a batch of messages. */ prompt(message: AgentMessage | AgentMessage[]): Promise; prompt(input: string, images?: ImageContent[]): Promise; /** Continue from the current transcript. The last message must be a user or tool-result message. */ continue(): Promise; private normalizePromptInput; private runPromptMessages; private runContinuation; private createContextSnapshot; private createLoopConfig; private runWithLifecycle; private handleRunFailure; private finishRun; private processEvents; /** * Execute a harness-originated tool call through the real execution pipeline. * * The tool object is supplied directly, so it need not appear in `state.tools` — this is what * lets LLM-invisible harness tools execute. The call produces the same `tool_execution_*` and * message events, persisted messages, and `beforeToolCall`/`afterToolCall` invocations as a * normal tool execution, but emits **no** run/turn framing events (`agent_start`, `turn_start`, * `turn_end`, `agent_end`). It is therefore intentionally invisible to every `agent_end`-keyed * consumer (probe scheduling, compaction bookkeeping). * * When idle, the call executes immediately in a transient run scope. When a run is active, it is * queued and drained at the next turn boundary — before the next intra-run LLM call — with an * end-of-run flush for calls queued during the run's final turn, so a queued call is never stranded. * * **Settlement (#341).** The returned promise resolves only after the call's full Agent-core * pipeline finishes: the synthetic assistant tool-call message, tool prepare/execute/finalize, the * tool-result message, Agent state reduction, and every awaited listener for those events. A queued * call therefore does not resolve at enqueue time — it resolves when the drain executes it. The * promise rejects when reset or session teardown revokes an unsettled invocation, when an * infrastructure/listener/hook failure escapes the pipeline, or when a failed final drain leaves a * later queued call unable to execute. A tool's own `execute()` throwing is **not** a rejection: it * becomes a normal `isError: true` tool result, so the promise resolves after that error-result * pipeline completes. Rejection means the promised pipeline did not complete — it does not prove * artifact absence (state and persistence may have partially completed), so callers must not blindly * retry. * * This settles Agent-core execution only. It does **not** prove AgentSession persistence; * `AgentSession.invokeHarnessTool` layers the persisted-settlement boundary on top of it. * * **Reentrancy.** Do not `await` this from work whose return is required for the Agent to reach the * drain point (a model-callable `execute`, `beforeToolBatch`/`beforeToolCall`/`afterToolCall`/ * `prepareNextTurn`, or an awaited listener), or the queued call can never execute and the await * deadlocks. Start/capture the promise, return from the gating callback, and await it from an * independent continuation. */ runHarnessTool(tool: AgentTool, args: unknown, options?: { toolCallId?: string; }): Promise; private createHarnessInvocation; private settleHarnessInvocation; private executeHarnessInvocation; rejectUnsettledHarnessTools(reason: Error): void; private drainHarnessToolQueue; private emitHarnessToolCall; private createHarnessAssistantMessage; } //# sourceMappingURL=agent.d.ts.map