import { A as ToolResultMessage, C as TextContent, M as Usage, O as Tool, b as StreamFn$1, c as Context, d as Message, f as Model, i as AssistantMessageEvent, j as Transport, l as ImageContent, r as AssistantMessage, s as CompleteSimpleFn, v as SimpleStreamOptions, w as ThinkingBudgets, y as StopReason } from "./types-CZAevFX5.js"; import { i as EventStream } from "./index-D3HJMhgl.js"; import { Static, TSchema } from "typebox"; //#region packages/agent-core/src/runtime-deps.d.ts /** Runtime functions injected by host packages so agent-core stays provider-agnostic. */ interface AgentCoreRuntimeDeps { /** Streaming completion implementation used for normal agent turns. */ streamSimple: StreamFn$1; /** Non-streaming completion implementation used by summarization helpers. */ completeSimple: CompleteSimpleFn; } /** Runtime dependency subset required by streaming agent loops. */ type AgentCoreStreamRuntimeDeps = Pick; /** Runtime dependency subset required by summarization helpers. */ type AgentCoreCompletionRuntimeDeps = Pick; /** Resolve the stream function, preferring an explicit override over injected runtime deps. */ declare function resolveAgentCoreStreamFn(runtime: AgentCoreStreamRuntimeDeps | undefined, streamFn?: StreamFn$1): StreamFn$1; /** Resolve the completion function used by non-streaming helper flows. */ declare function resolveAgentCoreCompleteFn(runtime: AgentCoreCompletionRuntimeDeps | undefined): CompleteSimpleFn; //#endregion //#region packages/agent-core/src/types.d.ts /** * Stream function used by the agent loop. * * Contract: * - Must not throw or return a rejected promise for request/model/runtime failures. * - Must return an AssistantMessageEventStream. * - Failures must be encoded in the returned stream via protocol events and a * final AssistantMessage with stopReason "error" or "aborted" and errorMessage. */ type StreamFn = StreamFn$1; /** * Configuration for how tool calls from a single assistant message are executed. * * - "sequential": each tool call is prepared, executed, and finalized before the next one starts. * - "parallel": tool calls are prepared sequentially, then allowed tools execute concurrently. * `tool_execution_end` is emitted in tool completion order after each tool is finalized, * while tool-result message artifacts are emitted later in assistant source order. */ type ToolExecutionMode = "sequential" | "parallel"; /** * Controls how many queued user messages are injected when the agent loop reaches a queue drain point. * * - "all": drain and inject every queued message at that point. * - "one-at-a-time": drain and inject only the oldest queued message, leaving the rest queued for later drain points. */ type QueueMode = "all" | "one-at-a-time"; /** A single tool call content block emitted by an assistant message. */ type AgentToolCall = Extract; /** * Result returned from `beforeToolCall`. * * Returning `{ block: true }` prevents the tool from executing. The loop emits an error tool result instead. * `reason` becomes the text shown in that error result. If omitted, a default blocked message is used. */ interface BeforeToolCallResult { block?: boolean; reason?: string; } /** * Partial override returned from `afterToolCall`. * * Merge semantics are field-by-field: * - `content`: if provided, replaces the tool result content array in full * - `details`: if provided, replaces the tool result details value in full * - `isError`: if provided, replaces the tool result error flag * - `terminate`: if provided, replaces the early-termination hint * * Omitted fields keep the original executed tool result values. * There is no deep merge for `content` or `details`. */ interface AfterToolCallResult { content?: (TextContent | ImageContent)[]; details?: unknown; isError?: boolean; /** * Hint that the agent should stop after the current tool batch. * Early termination only happens when every finalized tool result in the batch sets this to true. */ terminate?: boolean; } /** Context passed to `beforeToolCall`. */ interface BeforeToolCallContext { /** The assistant message that requested the tool call. */ assistantMessage: AssistantMessage; /** The raw tool call block from `assistantMessage.content`. */ toolCall: AgentToolCall; /** Validated tool arguments for the target tool schema. */ args: unknown; /** Current agent context at the time the tool call is prepared. */ context: AgentContext; } /** Context passed to `afterToolCall`. */ interface AfterToolCallContext { /** The assistant message that requested the tool call. */ assistantMessage: AssistantMessage; /** The raw tool call block from `assistantMessage.content`. */ toolCall: AgentToolCall; /** Validated tool arguments for the target tool schema. */ args: unknown; /** The executed tool result before unknown `afterToolCall` overrides are applied. */ result: AgentToolResult; /** Whether the executed tool result is currently treated as an error. */ isError: boolean; /** Current agent context at the time the tool call is finalized. */ context: AgentContext; } /** Context passed to `shouldStopAfterTurn`. */ interface ShouldStopAfterTurnContext { /** The assistant message that completed the turn. */ message: AssistantMessage; /** Tool result messages passed to the preceding `turn_end` event. */ toolResults: ToolResultMessage[]; /** Current agent context after the turn's assistant message and tool results have been appended. */ context: AgentContext; /** Messages that this loop invocation will return if it exits at this point. Prompt runs include the initial prompt messages; continuation runs do not include pre-existing context messages. */ newMessages: AgentMessage[]; } /** Replacement runtime state used by the agent loop before starting another provider request. */ interface AgentLoopTurnUpdate { /** Context for the next provider request. */ context?: AgentContext; /** Model for the next provider request. */ model?: Model; /** Thinking level for the next provider request. */ thinkingLevel?: ThinkingLevel; } interface PrepareNextTurnContext extends ShouldStopAfterTurnContext {} interface AgentLoopConfig extends SimpleStreamOptions { model: Model; /** * Converts AgentMessage[] to LLM-compatible Message[] before each LLM call. * * Each AgentMessage must be converted to a UserMessage, AssistantMessage, or ToolResultMessage * that the LLM can understand. AgentMessages that cannot be converted (e.g., UI-only notifications, * status messages) should be filtered out. * * Contract: must not throw or reject. Return a safe fallback value instead. * Throwing interrupts the low-level agent loop without producing a normal event sequence. * * @example * ```typescript * convertToLlm: (messages) => messages.flatMap(m => { * if (m.role === "custom") { * // Convert custom message to user message * return [{ role: "user", content: m.content, timestamp: m.timestamp }]; * } * if (m.role === "notification") { * // Filter out UI-only messages * return []; * } * // Pass through standard LLM messages * return [m]; * }) * ``` */ convertToLlm: (messages: AgentMessage[]) => Message[] | Promise; /** * Optional transform applied to the context before `convertToLlm`. * * Use this for operations that work at the AgentMessage level: * - Context window management (pruning old messages) * - Injecting context from external sources * * Contract: must not throw or reject. Return the original messages or another * safe fallback value instead. * * @example * ```typescript * transformContext: async (messages) => { * if (estimateTokens(messages) > MAX_TOKENS) { * return pruneOldMessages(messages); * } * return messages; * } * ``` */ transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise; /** * Resolves an API key dynamically for each LLM call. * * Useful for short-lived OAuth tokens (e.g., GitHub Copilot) that may expire * during long-running tool execution phases. * * Contract: must not throw or reject. Return undefined when no key is available. */ getApiKey?: (provider: string) => Promise | string | undefined; /** * Called after each turn fully completes and `turn_end` has been emitted. * * If it returns true, the loop emits `agent_end` and exits before polling steering or follow-up queues, * without starting another LLM call. The current assistant response and any tool executions finish normally. * * Use this to request a graceful stop after the current turn, e.g. before context gets too full. * * Contract: must not throw or reject. Throwing interrupts the low-level agent loop without producing a normal event sequence. */ shouldStopAfterTurn?: (context: ShouldStopAfterTurnContext) => boolean | Promise; /** * Called after `turn_end` and before the loop decides whether another provider request should start. * Return replacement context/model/thinking state to affect the next turn in this run. * Return undefined to keep using the current context/config. */ prepareNextTurn?: (context: PrepareNextTurnContext) => AgentLoopTurnUpdate | undefined | Promise; /** * Returns steering messages to inject into the conversation mid-run. * * Called after the current assistant turn finishes executing its tool calls, unless `shouldStopAfterTurn` exits first. * If messages are returned, they are added to the context before the next LLM call. * Tool calls from the current assistant message are not skipped. * * Use this for "steering" the agent while it's working. * * Contract: must not throw or reject. Return [] when no steering messages are available. */ getSteeringMessages?: () => Promise; /** * Returns follow-up messages to process after the agent would otherwise stop. * * Called when the agent has no more tool calls and no steering messages. * If messages are returned, they're added to the context and the agent * continues with another turn. * * Use this for follow-up messages that should wait until the agent finishes. * * Contract: must not throw or reject. Return [] when no follow-up messages are available. */ getFollowUpMessages?: () => Promise; /** * Tool execution mode. * - "sequential": execute tool calls one by one * - "parallel": preflight tool calls sequentially, then execute allowed tools concurrently; * emit `tool_execution_end` in tool completion order after each tool is finalized, * then emit tool-result message artifacts later in assistant source order * * Default: "parallel" */ toolExecution?: ToolExecutionMode; /** * Called before a tool is executed, after arguments have been validated. * * Return `{ block: true }` to prevent execution. The loop emits an error tool result instead. * The hook receives the agent abort signal and is responsible for honoring it. */ beforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise; /** * Called after a tool finishes executing, before `tool_execution_end` and tool-result message events are emitted. * * Return an `AfterToolCallResult` to override parts of the executed tool result: * - `content` replaces the full content array * - `details` replaces the full details payload * - `isError` replaces the error flag * - `terminate` replaces the early-termination hint * * Any omitted fields keep their original values. No deep merge is performed. * The hook receives the agent abort signal and is responsible for honoring it. */ afterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise; } /** * Thinking/reasoning level for models that support it. * Note: "xhigh" is only supported by selected model families. Use model thinking-level metadata * from openclaw/plugin-sdk/llm to detect support for a concrete model. */ type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max"; interface BashExecutionMessage { /** Harness role for shell command transcripts. */ role: "bashExecution"; /** Command line that was executed. */ command: string; /** Captured command output, usually already truncated for context. */ output: string; /** Process exit code when the command reached process exit. */ exitCode: number | undefined; /** True when the command was interrupted before normal completion. */ cancelled: boolean; /** True when output was shortened for transcript/context storage. */ truncated: boolean; /** Optional path containing the complete output when truncation occurred. */ fullOutputPath?: string; /** Millisecond timestamp for transcript ordering. */ timestamp: number; /** Exclude this command transcript from model context while keeping it in session history. */ excludeFromContext?: boolean; } interface CustomMessage { /** Harness role for application-defined transcript content. */ role: "custom"; /** Application-defined discriminator for rendering or handling this message. */ customType: string; /** Content replayed into model context when this message is included. */ content: string | (TextContent | ImageContent)[]; /** Whether UI surfaces should display this message. */ display: boolean; /** Optional application-specific metadata. */ details?: T; /** Millisecond timestamp for transcript ordering. */ timestamp: number; } interface BranchSummaryMessage { /** Harness role for summaries produced when returning from another branch. */ role: "branchSummary"; /** Summary text inserted back into model context. */ summary: string; /** Entry id of the branch root or source leaf being summarized. */ fromId: string; /** Millisecond timestamp for transcript ordering. */ timestamp: number; } interface CompactionSummaryMessage { /** Harness role for summaries that replace compacted transcript history. */ role: "compactionSummary"; /** Summary text inserted back into model context. */ summary: string; /** Estimated context tokens before compaction. */ tokensBefore: number; /** Timestamp may be numeric in memory or string when loaded from older persisted rows. */ timestamp: number | string; /** Optional estimated context tokens after compaction. */ tokensAfter?: number; /** Optional first retained entry id from the compaction range. */ firstKeptEntryId?: string; /** Optional implementation-specific compaction metadata. */ details?: unknown; } /** * Extensible interface for custom app and harness messages. * Apps can extend via declaration merging. */ interface CustomAgentMessages { bashExecution: BashExecutionMessage; custom: CustomMessage; branchSummary: BranchSummaryMessage; compactionSummary: CompactionSummaryMessage; } /** * AgentMessage: Union of LLM messages + custom messages. * This abstraction allows apps to add custom message types while maintaining * type safety and compatibility with the base LLM messages. */ type AgentMessage = Message | CustomAgentMessages[keyof CustomAgentMessages]; /** * Public agent state. * * `tools` and `messages` use accessor properties so implementations can copy * assigned arrays before storing them. */ interface AgentState { /** System prompt sent with each model request. */ systemPrompt: string; /** Active model used for future turns. */ model: Model; /** Requested reasoning level for future turns. */ thinkingLevel: ThinkingLevel; /** Available tools. Assigning a new array copies the top-level array. */ set tools(tools: AgentTool[]); get tools(): AgentTool[]; /** Conversation transcript. Assigning a new array copies the top-level array. */ set messages(messages: AgentMessage[]); get messages(): AgentMessage[]; /** * True while the agent is processing a prompt or continuation. * * This remains true until awaited `agent_end` listeners settle. */ readonly isStreaming: boolean; /** Partial assistant message for the current streamed response, if any. */ readonly streamingMessage?: AgentMessage; /** Tool call ids currently executing. */ readonly pendingToolCalls: ReadonlySet; /** Error message from the most recent failed or aborted assistant turn, if any. */ readonly errorMessage?: string; } /** Channel-safe progress text emitted by a running tool. */ interface AgentToolProgress { /** Public text suitable for user-facing progress surfaces. */ text: string; /** Tool progress is rendered by channel progress UIs. */ visibility: "channel"; /** Progress text must not contain secrets, private args, or fetched content. */ privacy: "public"; /** Optional stable id for progress line replacement. */ id?: string; } /** Final or partial result produced by a tool. */ interface AgentToolResult { /** Text or image content returned to the model. */ content: (TextContent | ImageContent)[]; /** Arbitrary structured details for logs or UI rendering. */ details: T; /** Optional public progress hint for partial tool updates; never model content. */ progress?: AgentToolProgress; /** * Hint that the agent should stop after the current tool batch. * Early termination only happens when every finalized tool result in the batch sets this to true. */ terminate?: boolean; } /** Callback used by tools to stream partial execution updates. */ type AgentToolUpdateCallback = (partialResult: AgentToolResult) => void; /** Tool definition used by the agent runtime. */ interface AgentTool extends Tool { /** Human-readable label for UI display. */ label: string; /** * Optional compatibility shim for raw tool-call arguments before schema validation. * Must return an object that matches `TParameters`. */ prepareArguments?: (args: unknown) => Static; /** Execute the tool call. Throw on failure instead of encoding errors in `content`. */ execute: (toolCallId: string, params: Static, signal?: AbortSignal, onUpdate?: AgentToolUpdateCallback) => Promise>; /** * Per-tool execution mode override. * - "sequential": this tool must execute one at a time with other tool calls. * - "parallel": this tool can execute concurrently with other tool calls. * * If omitted, the default execution mode applies. */ executionMode?: ToolExecutionMode; } /** Context snapshot passed into the low-level agent loop. */ interface AgentContext { /** System prompt included with the request. */ systemPrompt: string; /** Transcript visible to the model. */ messages: AgentMessage[]; /** Tools available for this run. */ tools?: AgentTool[]; } /** * Events emitted by the Agent for UI updates. * * `agent_end` is the last event emitted for a run, but awaited `Agent.subscribe()` * listeners for that event are still part of run settlement. The agent becomes * idle only after those listeners finish. */ type AgentEvent = { type: "agent_start"; } | { type: "agent_end"; messages: AgentMessage[]; } | { type: "turn_start"; } | { type: "turn_end"; message: AgentMessage; toolResults: ToolResultMessage[]; } | { type: "message_start"; message: AgentMessage; } | { type: "message_update"; message: AgentMessage; assistantMessageEvent: AssistantMessageEvent; } | { type: "message_end"; message: AgentMessage; } | { type: "tool_execution_start"; toolCallId: string; toolName: string; args: unknown; } | { type: "tool_execution_update"; toolCallId: string; toolName: string; args: unknown; partialResult: unknown; } | { type: "tool_execution_end"; toolCallId: string; toolName: string; result: unknown; isError: boolean; }; //#endregion //#region packages/agent-core/src/agent.d.ts /** Options for constructing an {@link Agent}. */ interface AgentOptions { /** Initial transcript, tools, model, and prompt state. */ initialState?: Partial>; /** Convert agent-owned transcript messages into provider-facing messages. */ convertToLlm?: (messages: AgentMessage[]) => Message[] | Promise; /** Optionally rewrite context before each provider request. */ transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise; /** Injected stream runtime used when streamFn is not supplied. */ runtime?: AgentCoreStreamRuntimeDeps; /** Explicit stream implementation, preferred over runtime.streamSimple. */ streamFn?: StreamFn; /** Resolve provider API keys at request time. */ getApiKey?: (provider: string) => Promise | string | undefined; /** Inspect the provider payload before it is sent. */ onPayload?: SimpleStreamOptions["onPayload"]; /** Inspect the provider response after it returns. */ onResponse?: SimpleStreamOptions["onResponse"]; /** Hook that may short-circuit or alter a tool call before execution. */ beforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise; /** Hook that may alter a tool result after execution. */ afterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise; /** Hook that may update model, reasoning, or context after a turn. */ prepareNextTurn?: (signal?: AbortSignal) => Promise | AgentLoopTurnUpdate | undefined; /** Queue drain mode for steering messages injected before the next assistant response. */ steeringMode?: QueueMode; /** Queue drain mode for follow-up messages injected after the agent would otherwise stop. */ followUpMode?: QueueMode; /** Session identifier forwarded to cache-aware providers. */ sessionId?: string; /** Optional per-thinking-level token budgets forwarded to providers. */ thinkingBudgets?: ThinkingBudgets; /** Preferred provider transport. */ transport?: Transport; /** Optional cap for provider-requested retry delays. */ maxRetryDelayMs?: number; /** Default strategy for executing multiple tool calls in one assistant message. */ 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. */ declare class Agent { private mutableState; private readonly listeners; private readonly steeringQueue; private readonly followUpQueue; convertToLlm: (messages: AgentMessage[]) => Message[] | Promise; transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise; runtime?: AgentCoreStreamRuntimeDeps; streamFn: StreamFn; getApiKey?: (provider: string) => Promise | string | undefined; onPayload?: SimpleStreamOptions["onPayload"]; onResponse?: SimpleStreamOptions["onResponse"]; beforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise; afterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise; prepareNextTurn?: (signal?: AbortSignal) => Promise | AgentLoopTurnUpdate | undefined; private activeRun?; /** 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; /** 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; /** * Reduce internal state for a loop event, then await listeners. * * `agent_end` only means no further loop events will be emitted. The run is * considered idle later, after all awaited listeners for `agent_end` finish * and `finishRun()` clears runtime-owned state. */ private processEvents; } //#endregion //#region packages/agent-core/src/agent-loop.d.ts /** Callback used by synchronous loop runners to publish agent lifecycle events. */ type AgentEventSink = (event: AgentEvent) => Promise | void; /** * Start an agent loop with a new prompt message. * The prompt is added to the context and events are emitted for it. */ declare function agentLoop(prompts: AgentMessage[], context: AgentContext, config: AgentLoopConfig, signal?: AbortSignal, streamFn?: StreamFn, runtime?: AgentCoreStreamRuntimeDeps): EventStream; /** * Continue an agent loop from the current context without adding a new message. * Used for retries - context already has user message or tool results. * * **Important:** The last message in context must convert to a `user` or `toolResult` message * via `convertToLlm`. If it doesn't, the LLM provider will reject the request. * This cannot be validated here since `convertToLlm` is only called once per turn. */ declare function agentLoopContinue(context: AgentContext, config: AgentLoopConfig, signal?: AbortSignal, streamFn?: StreamFn, runtime?: AgentCoreStreamRuntimeDeps): EventStream; /** Run a prompt-started loop and emit events through a caller-owned sink. */ declare function runAgentLoop(prompts: AgentMessage[], context: AgentContext, config: AgentLoopConfig, emit: AgentEventSink, signal?: AbortSignal, streamFn?: StreamFn, runtime?: AgentCoreStreamRuntimeDeps): Promise; /** Continue an existing loop context and emit only newly produced messages. */ declare function runAgentLoopContinue(context: AgentContext, config: AgentLoopConfig, emit: AgentEventSink, signal?: AbortSignal, streamFn?: StreamFn, runtime?: AgentCoreStreamRuntimeDeps): Promise; //#endregion //#region packages/agent-core/src/harness/session/session.d.ts /** Build model context from the active session branch and its latest state markers. */ declare function buildSessionContext(pathEntries: SessionTreeEntry[]): SessionContext; /** High-level session API backed by pluggable tree storage. */ declare class Session { private storage; constructor(storage: SessionStorage); getMetadata(): Promise; getStorage(): SessionStorage; getLeafId(): Promise; getEntry(id: string): Promise; getEntries(): Promise; getBranch(fromId?: string): Promise; buildContext(): Promise; getLabel(id: string): Promise; getSessionName(): Promise; private appendTypedEntry; appendMessage(message: AgentMessage): Promise; appendThinkingLevelChange(thinkingLevel: string): Promise; appendModelChange(provider: string, modelId: string): Promise; appendCompaction(summary: string, firstKeptEntryId: string, tokensBefore: number, details?: unknown, fromHook?: boolean): Promise; /** Append a non-LLM transcript marker for harness-specific state. */ appendCustomEntry(customType: string, data?: unknown): Promise; /** Append harness-specific content that can also be replayed into model context. */ appendCustomMessageEntry(customType: string, content: string | (TextContent | ImageContent)[], display: boolean, details?: unknown): Promise; /** Record or clear the display label for an existing session entry. */ appendLabel(targetId: string, label: string | undefined): Promise; appendSessionName(name: string): Promise; /** Move the visible branch leaf and optionally attach a summary of the abandoned branch. */ moveTo(entryId: string | null, summary?: { summary: string; details?: unknown; fromHook?: boolean; }): Promise; } //#endregion //#region packages/agent-core/src/harness/agent-harness.d.ts /** Stateful harness for running, steering, compacting, and navigating sessions. */ declare class CoreAgentHarness { readonly env: ExecutionEnv; private session; private phase; private runAbortController?; private runPromise?; private pendingSessionWrites; private model; private thinkingLevel; private systemPrompt; private streamOptions; private getApiKeyAndHeaders?; private runtime?; private resources; private tools; private activeToolNames; private steerQueue; private steeringQueueMode; private followUpQueue; private followUpQueueMode; private nextTurnQueue; private handlers; constructor(options: AgentHarnessOptions); private getHandlers; private emitOwn; private emitAny; private emitHook; private emitBeforeProviderRequest; private emitBeforeProviderPayload; private emitQueueUpdate; private startRunPromise; private createTurnState; private createContext; private createStreamFn; private drainQueuedMessages; private createLoopConfig; private validateToolNames; private flushPendingSessionWrites; private handleAgentEvent; private emitRunFailure; private executeTurn; prompt(text: string, options?: { images?: ImageContent[]; }): Promise; skill(name: string, additionalInstructions?: string): Promise; promptFromTemplate(name: string, args?: string[]): Promise; steer(text: string, options?: { images?: ImageContent[]; }): Promise; followUp(text: string, options?: { images?: ImageContent[]; }): Promise; nextTurn(text: string, options?: { images?: ImageContent[]; }): Promise; appendMessage(message: AgentMessage): Promise; compact(customInstructions?: string): Promise<{ summary: string; firstKeptEntryId: string; tokensBefore: number; details?: unknown; }>; navigateTree(targetId: string, options?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string; }): Promise; getModel(): Model; getThinkingLevel(): ThinkingLevel; setModel(model: Model): Promise; setThinkingLevel(level: ThinkingLevel): Promise; setActiveTools(toolNames: string[]): Promise; getSteeringMode(): QueueMode; setSteeringMode(mode: QueueMode): Promise; getFollowUpMode(): QueueMode; setFollowUpMode(mode: QueueMode): Promise; getResources(): AgentHarnessResources; setResources(resources: AgentHarnessResources): Promise; getStreamOptions(): AgentHarnessStreamOptions; setStreamOptions(streamOptions: AgentHarnessStreamOptions): Promise; setTools(tools: TTool[], activeToolNames?: string[]): Promise; abort(): Promise; waitForIdle(): Promise; subscribe(listener: (event: AgentHarnessEvent, signal?: AbortSignal) => Promise | void): () => void; on(type: TType, handler: (event: Extract) => Promise | AgentHarnessEventResultMap[TType]): () => void; } //#endregion //#region packages/agent-core/src/harness/types.d.ts /** Result of a fallible operation. Expected failures are returned as `ok: false` instead of thrown. */ type Result = { ok: true; value: TValue; } | { ok: false; error: TError; }; /** Create a successful {@link Result}. */ declare function ok(value: TValue): Result; /** Create a failed {@link Result}. */ declare function err(error: TError): Result; /** Return the success value or throw the failure error. Intended for tests and explicit adapter boundaries. */ declare function getOrThrow(result: Result): TValue; /** Return the success value or `undefined`. Only object values are allowed to avoid truthiness bugs with primitives. */ declare function getOrUndefined(result: Result): TValue | undefined; /** Normalize unknown thrown values into Error instances before using them as typed error causes. */ declare function toError(error: unknown): Error; /** * Skill loaded from a `SKILL.md` file or provided by an application. * * `name`, `description`, and `filePath` are inserted into the system prompt in an XML-formatted block as suggested by agentskills.io. * Use {@link formatSkillsForSystemPrompt} to generate the spec-compatible system prompt block. */ interface Skill { /** Stable skill name used for lookup and model-visible listings. */ name: string; /** Short model-visible description of when to use the skill. */ description: string; /** Full skill instructions. */ content: string; /** Absolute path to the skill file. Used for model-visible location and resolving relative references. */ filePath: string; /** Exclude this skill from model-visible skill lists while still allowing explicit application invocation. */ disableModelInvocation?: boolean; } /** Prompt template that can be formatted into a prompt for explicit invocation. */ interface PromptTemplate { /** Stable template name used for lookup or application command routing. */ name: string; /** Optional description for command lists or autocomplete. */ description?: string; /** Template content. Argument placeholders are formatted by `formatPromptTemplateInvocation`. */ content: string; } /** Resources made available to explicit invocation methods and system-prompt callbacks. */ interface AgentHarnessResources { /** Prompt templates available for explicit invocation. */ promptTemplates?: TPromptTemplate[]; /** Skills available to the model and explicit skill invocation. */ skills?: TSkill[]; } /** Curated provider request options owned by the harness and snapshotted per turn. */ interface AgentHarnessStreamOptions { /** Preferred transport forwarded to the stream function. */ transport?: Transport; /** Provider request timeout in milliseconds. */ timeoutMs?: number; /** Maximum provider retry attempts. */ maxRetries?: number; /** Optional cap for provider-requested retry delays. */ maxRetryDelayMs?: number; /** Additional request headers merged with auth and lifecycle headers. */ headers?: Record; /** Provider metadata forwarded with requests. */ metadata?: SimpleStreamOptions["metadata"]; /** Provider cache retention hint. */ cacheRetention?: SimpleStreamOptions["cacheRetention"]; } /** Per-request stream option patch returned by provider hooks. */ interface AgentHarnessStreamOptionsPatch extends Omit, "headers" | "metadata"> { /** Header patch. `undefined` values delete keys; explicit `headers: undefined` clears all headers. */ headers?: Record; /** Metadata patch. `undefined` values delete keys; explicit `metadata: undefined` clears all metadata. */ metadata?: Record; } /** Kind of filesystem object as addressed by a {@link FileSystem}. Symlinks are not followed automatically. */ type FileKind = "file" | "directory" | "symlink"; /** Stable, backend-independent file error codes returned by {@link FileSystem} file operations. */ type FileErrorCode = "aborted" | "not_found" | "permission_denied" | "not_directory" | "is_directory" | "invalid" | "not_supported" | "unknown"; /** Error returned by {@link FileSystem} file operations. */ declare class FileError extends Error { /** Backend-independent error code. */ code: FileErrorCode; /** Absolute addressed path associated with the failure, when available. */ path?: string; constructor(code: FileErrorCode, message: string, path?: string, cause?: Error); } /** Stable, backend-independent execution error codes returned by {@link ExecutionEnv.exec}. */ type ExecutionErrorCode = "aborted" | "timeout" | "shell_unavailable" | "spawn_error" | "callback_error" | "unknown"; /** Error returned by {@link ExecutionEnv.exec}. */ declare class ExecutionError extends Error { /** Backend-independent error code. */ code: ExecutionErrorCode; constructor(code: ExecutionErrorCode, message: string, cause?: Error); } /** Stable compaction error codes returned by compaction helpers. */ type CompactionErrorCode = "aborted" | "summarization_failed" | "invalid_session" | "unknown"; /** Error returned by compaction helpers. */ declare class CompactionError extends Error { /** Backend-independent error code. */ code: CompactionErrorCode; constructor(code: CompactionErrorCode, message: string, cause?: Error); } /** Stable branch-summary error codes returned by branch summarization helpers. */ type BranchSummaryErrorCode = "aborted" | "summarization_failed" | "invalid_session"; /** Error returned by branch summarization helpers. */ declare class BranchSummaryError extends Error { /** Backend-independent error code. */ code: BranchSummaryErrorCode; constructor(code: BranchSummaryErrorCode, message: string, cause?: Error); } type SessionErrorCode = "not_found" | "invalid_session" | "invalid_entry" | "invalid_fork_target" | "storage" | "unknown"; /** Error thrown by session storage, repositories, and session tree operations. */ declare class SessionError extends Error { /** Session subsystem error code. */ code: SessionErrorCode; constructor(code: SessionErrorCode, message: string, cause?: Error); } type AgentHarnessErrorCode = "busy" | "invalid_state" | "invalid_argument" | "session" | "hook" | "auth" | "compaction" | "branch_summary" | "unknown"; /** Public AgentHarness failure with a stable top-level classification. */ declare class AgentHarnessError extends Error { code: AgentHarnessErrorCode; constructor(code: AgentHarnessErrorCode, message: string, cause?: Error); } /** Metadata for one filesystem object in a {@link FileSystem}. */ interface FileInfo { /** Basename of {@link path}. */ name: string; /** Absolute, syntactically normalized addressed path in the execution environment. Symlinks are not followed. */ path: string; /** Object kind. Symlink targets are not followed; use {@link FileSystem.canonicalPath} explicitly. */ kind: FileKind; /** Size in bytes for the addressed filesystem object. */ size: number; /** Modification time as milliseconds since Unix epoch. */ mtimeMs: number; } /** Options for {@link Shell.exec}. */ interface ExecutionEnvExecOptions { /** Working directory for the command. Relative paths are resolved against {@link ExecutionEnv.cwd}. Defaults to {@link ExecutionEnv.cwd}. */ cwd?: string; /** Additional environment variables for the command. Values override the environment defaults. Defaults to no overrides. */ env?: Record; /** Timeout in seconds. Implementations should return a timeout error when the command exceeds this duration. Defaults to no timeout. */ timeout?: number; /** Abort signal used to terminate the command. Defaults to no abort signal. */ abortSignal?: AbortSignal; /** Called with stdout chunks as they are produced. */ onStdout?: (chunk: string) => void; /** Called with stderr chunks as they are produced. */ onStderr?: (chunk: string) => void; } /** * Filesystem capability used by the harness. * * Paths passed to methods may be absolute or relative to {@link cwd}. Paths returned by file operations are addressed paths * in the filesystem namespace, but are not canonicalized through symlinks unless returned by {@link canonicalPath}. * * Operation methods must never throw or reject. All filesystem failures, including unexpected backend failures, must be * encoded in the returned {@link Result}. Implementations must preserve this invariant. */ interface FileSystem { /** Current working directory for relative paths. */ cwd: string; /** Return an absolute addressed path without requiring it to exist and without resolving symlinks. */ absolutePath(path: string, abortSignal?: AbortSignal): Promise>; /** Join path segments in the filesystem namespace without requiring the result to exist. */ joinPath(parts: string[], abortSignal?: AbortSignal): Promise>; /** Read a UTF-8 text file. */ readTextFile(path: string, abortSignal?: AbortSignal): Promise>; /** Read UTF-8 text lines. Implementations should stop once `maxLines` lines have been read. */ readTextLines(path: string, options?: { maxLines?: number; abortSignal?: AbortSignal; }): Promise>; /** Read a binary file. */ readBinaryFile(path: string, abortSignal?: AbortSignal): Promise>; /** Create or overwrite a file, creating parent directories when supported. */ writeFile(path: string, content: string | Uint8Array, abortSignal?: AbortSignal): Promise>; /** Create or append to a file, creating parent directories when supported. */ appendFile(path: string, content: string | Uint8Array, abortSignal?: AbortSignal): Promise>; /** Return metadata for the addressed path without following symlinks. */ fileInfo(path: string, abortSignal?: AbortSignal): Promise>; /** List direct children of a directory without following symlinks. */ listDir(path: string, abortSignal?: AbortSignal): Promise>; /** Return the canonical path for an existing path, resolving symlinks where supported. */ canonicalPath(path: string, abortSignal?: AbortSignal): Promise>; /** Return false for missing paths. Other errors, such as permission failures, return a {@link FileError}. */ exists(path: string, abortSignal?: AbortSignal): Promise>; /** Create a directory. Defaults: `recursive: true`, no abort signal. */ createDir(path: string, options?: { recursive?: boolean; abortSignal?: AbortSignal; }): Promise>; /** Remove a file or directory. Defaults: `recursive: false`, `force: false`, no abort signal. */ remove(path: string, options?: { recursive?: boolean; force?: boolean; abortSignal?: AbortSignal; }): Promise>; /** Create a temporary directory and return its absolute path. Defaults: `prefix: "tmp-"`, no abort signal. */ createTempDir(prefix?: string, abortSignal?: AbortSignal): Promise>; /** Create a temporary file and return its absolute path. Defaults: `prefix: ""`, `suffix: ""`, no abort signal. */ createTempFile(options?: { prefix?: string; suffix?: string; abortSignal?: AbortSignal; }): Promise>; /** Release filesystem resources. Must be best-effort and must not throw or reject. */ cleanup(): Promise; } /** Shell execution capability used by the harness. */ interface Shell { /** Execute a shell command in {@link FileSystem.cwd} unless `options.cwd` is provided. */ exec(command: string, options?: ExecutionEnvExecOptions): Promise>; /** Release shell resources. Must be best-effort and must not throw or reject. */ cleanup(): Promise; } /** Filesystem and process execution environment used by the harness. */ interface ExecutionEnv extends FileSystem, Shell {} /** Base fields shared by append-only session tree entries. */ interface SessionTreeEntryBase { /** Entry discriminator used for JSONL persistence and typed narrowing. */ type: string; /** Stable entry id unique within a session file. */ id: string; /** Parent entry id, or null for a root entry. */ parentId: string | null; /** ISO timestamp string used for persistence and sorting. */ timestamp: string; } /** Persisted transcript message entry. */ interface MessageEntry extends SessionTreeEntryBase { type: "message"; message: AgentMessage; } /** Persisted thinking-level selection marker. */ interface ThinkingLevelChangeEntry extends SessionTreeEntryBase { type: "thinking_level_change"; thinkingLevel: string; } /** Persisted model selection marker. */ interface ModelChangeEntry extends SessionTreeEntryBase { type: "model_change"; provider: string; modelId: string; } /** Persisted summary that replaces older transcript history in context. */ interface CompactionEntry extends SessionTreeEntryBase { type: "compaction"; summary: string; firstKeptEntryId: string; tokensBefore: number; details?: T; fromHook?: boolean; } /** Persisted summary of an abandoned branch when navigating the session tree. */ interface BranchSummaryEntry extends SessionTreeEntryBase { type: "branch_summary"; fromId: string; summary: string; details?: T; fromHook?: boolean; } /** Persisted harness/application marker that is not replayed into model context. */ interface CustomEntry extends SessionTreeEntryBase { type: "custom"; customType: string; data?: T; } /** Persisted harness/application message that can be replayed into model context. */ interface CustomMessageEntry extends SessionTreeEntryBase { type: "custom_message"; customType: string; content: string | (TextContent | ImageContent)[]; details?: T; display: boolean; } /** Append-only label update for another session entry. */ interface LabelEntry extends SessionTreeEntryBase { type: "label"; targetId: string; label: string | undefined; } /** Persisted session metadata marker. */ interface SessionInfoEntry extends SessionTreeEntryBase { type: "session_info"; name?: string; } /** Append-only marker that changes the active visible leaf. */ interface LeafEntry extends SessionTreeEntryBase { type: "leaf"; targetId: string | null; } /** All persisted session tree entry variants. */ type SessionTreeEntry = MessageEntry | ThinkingLevelChangeEntry | ModelChangeEntry | CompactionEntry | BranchSummaryEntry | CustomEntry | CustomMessageEntry | LabelEntry | SessionInfoEntry | LeafEntry; interface SessionContext { messages: AgentMessage[]; thinkingLevel: string; model: { provider: string; modelId: string; } | null; } interface SessionMetadata { id: string; createdAt: string; } interface JsonlSessionMetadata extends SessionMetadata { cwd: string; path: string; parentSessionPath?: string; } interface SessionStorage { getMetadata(): Promise; getLeafId(): Promise; /** Persist a leaf entry that records the active session-tree leaf. */ setLeafId(leafId: string | null): Promise; createEntryId(): Promise; appendEntry(entry: SessionTreeEntry): Promise; getEntry(id: string): Promise; findEntries(type: TType): Promise>>; getLabel(id: string): Promise; getPathToRoot(leafId: string | null): Promise; getEntries(): Promise; } interface SessionCreateOptions { id?: string; } interface SessionForkOptions { entryId?: string; position?: "before" | "at"; id?: string; } interface SessionRepo { create(options: TCreateOptions): Promise>; open(metadata: TMetadata): Promise>; list(options?: TListOptions): Promise; delete(metadata: TMetadata): Promise; fork(source: TMetadata, options: SessionForkOptions & TCreateOptions): Promise>; } interface JsonlSessionCreateOptions extends SessionCreateOptions { cwd: string; parentSessionPath?: string; } interface JsonlSessionListOptions { cwd?: string; } interface JsonlSessionRepoApi extends SessionRepo {} type AgentHarnessPhase = "idle" | "turn" | "compaction" | "branch_summary" | "retry"; type PendingSessionWrite = SessionTreeEntry extends infer TEntry ? TEntry extends SessionTreeEntry ? Omit : never : never; interface QueueUpdateEvent { type: "queue_update"; steer: AgentMessage[]; followUp: AgentMessage[]; nextTurn: AgentMessage[]; } interface SavePointEvent { type: "save_point"; hadPendingMutations: boolean; } interface AbortEvent { type: "abort"; clearedSteer: AgentMessage[]; clearedFollowUp: AgentMessage[]; } interface SettledEvent { type: "settled"; nextTurnCount: number; } interface BeforeAgentStartEvent { type: "before_agent_start"; prompt: string; images?: ImageContent[]; systemPrompt: string; resources: AgentHarnessResources; } interface ContextEvent { type: "context"; messages: AgentMessage[]; } interface BeforeProviderRequestEvent { type: "before_provider_request"; model: Model; sessionId: string; streamOptions: AgentHarnessStreamOptions; } interface BeforeProviderPayloadEvent { type: "before_provider_payload"; model: Model; payload: unknown; } interface AfterProviderResponseEvent { type: "after_provider_response"; status: number; headers: Record; } interface ToolCallEvent { type: "tool_call"; toolCallId: string; toolName: string; input: Record; } interface ToolResultEvent { type: "tool_result"; toolCallId: string; toolName: string; input: Record; content: Array; details: unknown; isError: boolean; } interface SessionBeforeCompactEvent { type: "session_before_compact"; preparation: CompactionPreparation$1; branchEntries: SessionTreeEntry[]; customInstructions?: string; signal: AbortSignal; } interface SessionCompactEvent { type: "session_compact"; compactionEntry: CompactionEntry; fromHook: boolean; } interface SessionBeforeTreeEvent { type: "session_before_tree"; preparation: TreePreparation; signal: AbortSignal; } interface SessionTreeEvent { type: "session_tree"; newLeafId: string | null; oldLeafId: string | null; summaryEntry?: BranchSummaryEntry; fromHook?: boolean; } interface ModelSelectEvent { type: "model_select"; model: Model; previousModel: Model | undefined; source: "set" | "restore"; } interface ThinkingLevelSelectEvent { type: "thinking_level_select"; level: ThinkingLevel; previousLevel: ThinkingLevel; } interface ResourcesUpdateEvent { type: "resources_update"; resources: AgentHarnessResources; previousResources: AgentHarnessResources; } type AgentHarnessOwnEvent = QueueUpdateEvent | SavePointEvent | AbortEvent | SettledEvent | BeforeAgentStartEvent | ContextEvent | BeforeProviderRequestEvent | BeforeProviderPayloadEvent | AfterProviderResponseEvent | ToolCallEvent | ToolResultEvent | SessionBeforeCompactEvent | SessionCompactEvent | SessionBeforeTreeEvent | SessionTreeEvent | ModelSelectEvent | ThinkingLevelSelectEvent | ResourcesUpdateEvent; type AgentHarnessEvent = AgentEvent | AgentHarnessOwnEvent; /** Hook result for mutating the initial prompt run before the agent starts. */ interface BeforeAgentStartResult { /** Replacement messages for the prompt run. */ messages?: AgentMessage[]; /** Replacement system prompt for the prompt run. */ systemPrompt?: string; } /** Hook result for replacing the full context message list before provider conversion. */ interface ContextResult { messages: AgentMessage[]; } /** Hook result for patching provider request options before payload construction. */ interface BeforeProviderRequestResult { streamOptions?: AgentHarnessStreamOptionsPatch; } /** Hook result for replacing the provider payload after construction. */ interface BeforeProviderPayloadResult { payload: unknown; } /** Hook result for blocking a tool call before execution. */ interface ToolCallResult { block?: boolean; reason?: string; } /** Hook patch for a completed tool result before it is persisted/emitted. */ interface ToolResultPatch { content?: Array; details?: unknown; isError?: boolean; terminate?: boolean; } /** Hook result for cancelling or replacing a planned compaction. */ interface SessionBeforeCompactResult { cancel?: boolean; compaction?: CompactResult; } /** Hook result for cancelling, labeling, or supplying branch-summary behavior before tree navigation. */ interface SessionBeforeTreeResult { cancel?: boolean; summary?: { summary: string; details?: unknown; }; customInstructions?: string; replaceInstructions?: boolean; label?: string; } /** Typed return values expected from AgentHarness hook handlers by event type. */ type AgentHarnessEventResultMap = { before_agent_start: BeforeAgentStartResult | undefined; context: ContextResult | undefined; before_provider_request: BeforeProviderRequestResult | undefined; before_provider_payload: BeforeProviderPayloadResult | undefined; after_provider_response: undefined; tool_call: ToolCallResult | undefined; tool_result: ToolResultPatch | undefined; session_before_compact: SessionBeforeCompactResult | undefined; session_compact: undefined; session_before_tree: SessionBeforeTreeResult | undefined; session_tree: undefined; model_select: undefined; thinking_level_select: undefined; resources_update: undefined; queue_update: undefined; save_point: undefined; abort: undefined; settled: undefined; }; /** Options for a prompt submitted through AgentHarness. */ interface AgentHarnessPromptOptions { images?: ImageContent[]; } /** Queued messages removed by an abort operation. */ interface AbortResult { clearedSteer: AgentMessage[]; clearedFollowUp: AgentMessage[]; } /** Compaction data supplied by hooks or returned from compaction preparation. */ interface CompactResult { summary: string; firstKeptEntryId: string; tokensBefore: number; details?: unknown; } /** Result of moving the active session-tree leaf. */ interface NavigateTreeResult { cancelled: boolean; editorText?: string; summaryEntry?: BranchSummaryEntry; } /** Settings that control automatic context compaction. */ interface CompactionSettings$1 { enabled: boolean; reserveTokens: number; keepRecentTokens: number; } /** Prepared compaction inputs exposed to hooks before a summary is generated. */ interface CompactionPreparation$1 { firstKeptEntryId: string; messagesToSummarize: AgentMessage[]; turnPrefixMessages: AgentMessage[]; isSplitTurn: boolean; tokensBefore: number; previousSummary?: string; fileOps: FileOperations$1; settings: CompactionSettings$1; } /** File operations accumulated from summarized transcript ranges. */ interface FileOperations$1 { read: Set; written: Set; edited: Set; } /** Prepared branch navigation inputs exposed to hooks before a summary is generated. */ interface TreePreparation { targetId: string; oldLeafId: string | null; commonAncestorId: string | null; entriesToSummarize: SessionTreeEntry[]; userWantsSummary: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string; } /** Options for generating a branch summary. */ interface GenerateBranchSummaryOptions$1 { model: Model; apiKey: string; headers?: Record; signal: AbortSignal; runtime?: AgentCoreCompletionRuntimeDeps; streamFn?: StreamFn$1; customInstructions?: string; replaceInstructions?: boolean; reserveTokens?: number; } /** Generated branch summary text and file-operation metadata. */ interface BranchSummaryResult { summary: string; readFiles: string[]; modifiedFiles: string[]; } /** Construction options for AgentHarness. */ interface AgentHarnessOptions { env: ExecutionEnv; session: Session; tools?: TTool[]; /** * Concrete resources available to explicit invocation methods and system-prompt callbacks. * Applications own loading/reloading resources and should call `setResources()` with new values. */ resources?: AgentHarnessResources; systemPrompt?: string | ((context: { env: ExecutionEnv; session: Session; model: Model; thinkingLevel: ThinkingLevel; activeTools: TTool[]; resources: AgentHarnessResources; }) => string | Promise); getApiKeyAndHeaders?: (model: Model) => Promise<{ apiKey: string; headers?: Record; } | undefined>; runtime?: AgentCoreRuntimeDeps; /** Curated stream/provider request options. Snapshotted at turn start. */ streamOptions?: AgentHarnessStreamOptions; model: Model; thinkingLevel?: ThinkingLevel; activeToolNames?: string[]; steeringMode?: QueueMode; followUpMode?: QueueMode; } //#endregion //#region packages/agent-core/src/harness/env/nodejs.d.ts /** Node-backed execution environment for agent harness filesystem and shell operations. */ declare class NodeExecutionEnv implements ExecutionEnv { cwd: string; private shellPath?; private shellEnv?; constructor(options: { cwd: string; shellPath?: string; shellEnv?: NodeJS.ProcessEnv; }); absolutePath(path: string): Promise>; joinPath(parts: string[]): Promise>; exec(command: string, options?: { cwd?: string; env?: Record; timeout?: number; abortSignal?: AbortSignal; onStdout?: (chunk: string) => void; onStderr?: (chunk: string) => void; }): Promise>; readTextFile(path: string, abortSignal?: AbortSignal): Promise>; readTextLines(path: string, options?: { maxLines?: number; abortSignal?: AbortSignal; }): Promise>; readBinaryFile(path: string, abortSignal?: AbortSignal): Promise>; writeFile(path: string, content: string | Uint8Array, abortSignal?: AbortSignal): Promise>; appendFile(path: string, content: string | Uint8Array): Promise>; fileInfo(path: string): Promise>; listDir(path: string, abortSignal?: AbortSignal): Promise>; canonicalPath(path: string): Promise>; exists(path: string): Promise>; createDir(path: string, options?: { recursive?: boolean; }): Promise>; remove(path: string, options?: { recursive?: boolean; force?: boolean; }): Promise>; createTempDir(prefix?: string): Promise>; createTempFile(options?: { prefix?: string; suffix?: string; }): Promise>; cleanup(): Promise; } //#endregion //#region packages/agent-core/src/harness/env/kill-tree.d.ts type KillProcessTreeOptions = { graceMs?: number; detached?: boolean; force?: boolean; }; /** * Best-effort process-tree termination with graceful shutdown. * - Windows: use taskkill /T to include descendants. Sends SIGTERM-equivalent * first (without /F), then force-kills if process survives. * - Unix: send SIGTERM to process group first, wait grace period, then SIGKILL. * * When the child was spawned with `detached: false`, pass `detached: false` to * skip the Unix `process.kill(-pid, ...)` group-kill. That avoids signaling the * gateway's own process group. */ declare function killProcessTree(pid: number, opts?: KillProcessTreeOptions): void; declare function signalProcessTree(pid: number, signal: "SIGTERM" | "SIGKILL", opts?: { detached?: boolean; }): void; //#endregion //#region packages/agent-core/src/harness/messages.d.ts /** Harness-only transcript entries that can be normalized into LLM messages. */ type HarnessMessage = AgentMessage | BashExecutionMessage | CustomMessage | BranchSummaryMessage | CompactionSummaryMessage; declare function asAgentMessage(message: HarnessMessage): AgentMessage; declare const COMPACTION_SUMMARY_PREFIX = "The conversation history before this point was compacted into the following summary:\n\n\n"; declare const COMPACTION_SUMMARY_SUFFIX = "\n"; declare const BRANCH_SUMMARY_PREFIX = "The following is a summary of a branch that this conversation came back from:\n\n\n"; declare const BRANCH_SUMMARY_SUFFIX = ""; /** Render a shell execution record as user-visible context text for the model. */ declare function bashExecutionToText(msg: BashExecutionMessage): string; /** Build a persisted branch summary message from the repository timestamp string. */ declare function createBranchSummaryMessage(summary: string, fromId: string, timestamp: string): BranchSummaryMessage; /** Build a persisted compaction summary message from the repository timestamp string. */ declare function createCompactionSummaryMessage(summary: string, tokensBefore: number, timestamp: string): CompactionSummaryMessage; /** Build a custom transcript message that can be shown and replayed into context. */ declare function createCustomMessage(customType: string, content: string | (TextContent | ImageContent)[], display: boolean, details: unknown, timestamp: string): CustomMessage; /** Convert harness transcript messages into the LLM-facing message sequence. */ declare function convertToLlm(messages: AgentMessage[]): Message[]; //#endregion //#region packages/agent-core/src/harness/prompt-template-arguments.d.ts /** Parse an argument string using simple shell-style single and double quotes. */ declare function parseCommandArgs(argsString: string): string[]; /** * Substitute prompt template placeholders (`$1`, `$@`, `$ARGUMENTS`, `${@:N}`, `${@:N:L}`) with command arguments. * * Unsafe integer placeholders resolve to empty text instead of throwing, so malformed templates cannot abort prompt * loading or invocation. */ declare function substituteArgs(content: string, args: string[]): string; //#endregion //#region packages/agent-core/src/harness/prompt-templates.d.ts type PromptTemplateDiagnosticCode = "file_info_failed" | "list_failed" | "read_failed" | "parse_failed"; /** Warning produced while loading prompt templates. */ interface PromptTemplateDiagnostic { /** Diagnostic severity. Currently only warnings are emitted. */ type: "warning"; /** Stable diagnostic code. */ code: PromptTemplateDiagnosticCode; /** Human-readable diagnostic message. */ message: string; /** Path associated with the diagnostic. */ path: string; } /** * Load prompt templates from one or more paths. * * Directory inputs load direct `.md` children non-recursively. File inputs load explicit `.md` files. Missing paths and * non-markdown files are skipped. Read and parse failures are returned as diagnostics. */ declare function loadPromptTemplates(env: ExecutionEnv, paths: string | string[]): Promise<{ promptTemplates: PromptTemplate[]; diagnostics: PromptTemplateDiagnostic[]; }>; /** * Load prompt templates from source-tagged paths. * * Source values are preserved exactly and attached to every loaded prompt template and diagnostic. The agent package does * not interpret source values; applications define their own provenance shape. */ declare function loadSourcedPromptTemplates(env: ExecutionEnv, inputs: Array<{ path: string; source: TSource; }>, mapPromptTemplate?: (promptTemplate: PromptTemplate, source: TSource) => TPromptTemplate): Promise<{ promptTemplates: Array<{ promptTemplate: TPromptTemplate; source: TSource; }>; diagnostics: Array; }>; /** Format a prompt template invocation with positional arguments. */ declare function formatPromptTemplateInvocation(template: PromptTemplate, args?: string[]): string; //#endregion //#region packages/agent-core/src/harness/skills.d.ts type SkillDiagnosticCode = "file_info_failed" | "list_failed" | "read_failed" | "parse_failed" | "invalid_metadata"; /** Warning produced while loading skills. */ interface SkillDiagnostic { /** Diagnostic severity. Currently only warnings are emitted. */ type: "warning"; /** Stable diagnostic code. */ code: SkillDiagnosticCode; /** Human-readable diagnostic message. */ message: string; /** Path associated with the diagnostic. */ path: string; } /** Format a skill invocation prompt, optionally appending additional user instructions. */ declare function formatSkillInvocation(skill: Skill, additionalInstructions?: string): string; /** * Load skills from one or more directories. * * Traverses directories recursively, loads `SKILL.md` files, loads direct root `.md` files as skills, honors ignore files, * and returns diagnostics for invalid skill files. Missing input directories are skipped. */ declare function loadSkills(env: ExecutionEnv, dirs: string | string[]): Promise<{ skills: Skill[]; diagnostics: SkillDiagnostic[]; }>; /** * Load skills from source-tagged directories. * * Source values are preserved exactly and attached to every loaded skill and diagnostic. The agent package does not * interpret source values; applications define their own provenance shape. */ declare function loadSourcedSkills(env: ExecutionEnv, inputs: Array<{ path: string; source: TSource; }>, mapSkill?: (skill: Skill, source: TSource) => TSkill): Promise<{ skills: Array<{ skill: TSkill; source: TSource; }>; diagnostics: Array; }>; //#endregion //#region packages/agent-core/src/harness/system-prompt.d.ts /** Format model-visible skill metadata for inclusion in the harness system prompt. */ declare function formatSkillsForSystemPrompt(skills: Skill[]): string; //#endregion //#region packages/agent-core/src/harness/session/jsonl-repo.d.ts type JsonlSessionRepoFileSystem = Pick; /** Repository for JSONL sessions grouped by working directory. */ declare class JsonlSessionRepo implements JsonlSessionRepoApi { private readonly fs; private readonly sessionsRootInput; private sessionsRoot; constructor(options: { fs: JsonlSessionRepoFileSystem; sessionsRoot: string; }); private getSessionsRoot; private getSessionDir; private createSessionFilePath; create(options: JsonlSessionCreateOptions): Promise>; open(metadata: JsonlSessionMetadata): Promise>; list(options?: JsonlSessionListOptions): Promise; delete(metadata: JsonlSessionMetadata): Promise; fork(sourceMetadata: JsonlSessionMetadata, options: JsonlSessionCreateOptions & { entryId?: string; position?: "before" | "at"; id?: string; }): Promise>; private listSessionDirs; } //#endregion //#region packages/agent-core/src/harness/session/storage-base.d.ts declare abstract class BaseSessionStorage implements SessionStorage { private readonly metadata; private readonly entries; private readonly byId; private readonly labelsById; private leafId; protected constructor(metadata: TMetadata, entries: SessionTreeEntry[], leafId?: string | null); getMetadata(): Promise; getLeafId(): Promise; protected createLeafEntry(leafId: string | null): LeafEntry; createEntryId(): Promise; protected recordEntry(entry: SessionTreeEntry): void; getEntry(id: string): Promise; findEntries(type: TType): Promise>>; getLabel(id: string): Promise; getPathToRoot(leafId: string | null): Promise; getEntries(): Promise; abstract setLeafId(leafId: string | null): Promise; abstract appendEntry(entry: SessionTreeEntry): Promise; } //#endregion //#region packages/agent-core/src/harness/session/jsonl-storage.d.ts type JsonlSessionStorageFileSystem = Pick; /** Read only the JSONL session header and convert it to session metadata. */ declare function loadJsonlSessionMetadata(fs: JsonlSessionStorageFileSystem, filePath: string): Promise; /** Append-only JSONL-backed storage for one session tree. */ declare class JsonlSessionStorage extends BaseSessionStorage { private readonly fs; private readonly filePath; private constructor(); static open(fs: JsonlSessionStorageFileSystem, filePath: string): Promise; /** Create a new JSONL file with a session header and no entries. */ static create(fs: JsonlSessionStorageFileSystem, filePath: string, options: { cwd: string; sessionId: string; parentSessionPath?: string; }): Promise; setLeafId(leafId: string | null): Promise; appendEntry(entry: SessionTreeEntry): Promise; } //#endregion //#region packages/agent-core/src/harness/session/memory-repo.d.ts /** In-memory session repository for tests and ephemeral harness usage. */ declare class InMemorySessionRepo implements SessionRepo { private sessions; create(options?: { id?: string; }): Promise; open(metadata: SessionMetadata): Promise; list(): Promise; delete(metadata: SessionMetadata): Promise; fork(sourceMetadata: SessionMetadata, options: { entryId?: string; position?: "before" | "at"; id?: string; }): Promise; } //#endregion //#region packages/agent-core/src/harness/session/memory-storage.d.ts /** Volatile session storage used by tests and in-process harness callers. */ declare class InMemorySessionStorage extends BaseSessionStorage { constructor(options?: { entries?: SessionTreeEntry[]; metadata?: TMetadata; }); setLeafId(leafId: string | null): Promise; appendEntry(entry: SessionTreeEntry): Promise; } //#endregion //#region packages/agent-core/src/harness/session/repo-utils.d.ts /** Create a time-sortable session id. */ declare function createSessionId(): string; /** Create a canonical session timestamp string. */ declare function createTimestamp(): string; /** Wrap a storage implementation in the Session facade. */ declare function toSession(storage: SessionStorage): Session; /** Unwrap filesystem results into session errors with caller context. */ declare function getFileSystemResultOrThrow(result: Result, message: string): TValue; /** Select the entries copied into a forked session. */ declare function getEntriesToFork(storage: SessionStorage, options: { entryId?: string; position?: "before" | "at"; }): Promise; //#endregion //#region packages/agent-core/src/harness/session/uuid.d.ts /** Generate a monotonic UUIDv7 string. */ declare function uuidv7(): string; //#endregion //#region packages/agent-core/src/harness/compaction/utils.d.ts /** File paths touched by a session branch or compaction range. */ interface FileOperations { /** Files read but not necessarily modified. */ read: Set; /** Files written by full-file write operations. */ written: Set; /** Files modified by edit operations. */ edited: Set; } /** Serialize LLM messages to plain text for summarization prompts. */ declare function serializeConversation(messages: Message[]): string; //#endregion //#region packages/agent-core/src/harness/compaction/branch-summarization.d.ts /** File-operation details stored on generated branch summary entries. */ interface BranchSummaryDetails { /** Files read while exploring the summarized branch. */ readFiles: string[]; /** Files modified while exploring the summarized branch. */ modifiedFiles: string[]; } /** Prepared branch content for summarization. */ interface BranchPreparation { /** Messages selected for the branch summary. */ messages: AgentMessage[]; /** File operations extracted from the branch. */ fileOps: FileOperations; /** Estimated token count for selected messages. */ totalTokens: number; } /** Entries selected for branch summarization. */ interface CollectEntriesResult { /** Entries to summarize in chronological order. */ entries: SessionTreeEntry[]; /** Deepest common ancestor between the previous leaf and target entry. */ commonAncestorId: string | null; } /** Minimal tree entry shape needed to compare two session branches. */ interface BranchPathEntry { /** Stable entry id. */ id: string; /** Parent entry id, or null for the session root. */ parentId: string | null; } /** Branch entries selected after comparing old and target paths. */ interface CollectBranchPathEntriesResult { /** Entries to summarize in chronological order. */ entries: TEntry[]; /** Deepest common ancestor between the previous leaf and target entry. */ commonAncestorId: string | null; } /** Options for generating a branch summary. */ interface GenerateBranchSummaryOptions { /** Model used for summarization. */ model: Model; /** API key forwarded to the provider. */ apiKey: string; /** Optional request headers forwarded to the provider. */ headers?: Record; /** Abort signal for the summarization request. */ signal: AbortSignal; /** Runtime used to complete the summarization request. */ runtime?: AgentCoreCompletionRuntimeDeps; /** Optional stream implementation used instead of the runtime complete function. */ streamFn?: StreamFn$1; /** Optional instructions appended to or replacing the default prompt. */ customInstructions?: string; /** Replace the default prompt with custom instructions instead of appending them. */ replaceInstructions?: boolean; /** Tokens reserved for prompt and model output. Defaults to 16384. */ reserveTokens?: number; } /** Collect entries that should be summarized before navigating to a different session tree entry. */ declare function collectEntriesForBranchSummaryFromBranches(oldBranch: readonly TEntry[], targetBranch: readonly TEntry[]): CollectBranchPathEntriesResult; /** Collect concrete session entries to summarize before moving from one leaf to another. */ declare function collectEntriesForBranchSummary(session: Session, oldLeafId: string | null, targetId: string): Promise; /** Prepare branch entries for summarization within an optional token budget. */ declare function prepareBranchEntries(entries: SessionTreeEntry[], tokenBudget?: number): BranchPreparation; /** Generate a summary for abandoned branch entries. */ declare function generateBranchSummary(entries: SessionTreeEntry[], options: GenerateBranchSummaryOptions): Promise>; //#endregion //#region packages/agent-core/src/harness/compaction/compaction.d.ts /** File-operation details stored on generated compaction entries. */ interface CompactionDetails { /** Files read in the compacted history. */ readFiles: string[]; /** Files modified in the compacted history. */ modifiedFiles: string[]; } /** Generated compaction data ready to be persisted as a compaction entry. */ interface CompactionResult { /** Summary text that replaces compacted history in future context. */ summary: string; /** Entry id where retained history starts. */ firstKeptEntryId: string; /** Estimated context tokens before compaction. */ tokensBefore: number; /** Optional implementation-specific details stored with the compaction entry. */ details?: T; } /** Compaction thresholds and retention settings. */ interface CompactionSettings { /** Enable automatic compaction decisions. */ enabled: boolean; /** Tokens reserved for summary prompt and output. */ reserveTokens: number; /** Approximate recent-context tokens to keep after compaction. */ keepRecentTokens: number; } /** Default compaction settings used by the harness. */ declare const DEFAULT_COMPACTION_SETTINGS: CompactionSettings; /** Calculate total context tokens from provider usage. */ declare function calculateContextTokens(usage: Usage): number; /** Return usage from the last successful assistant message in session entries. */ declare function getLastAssistantUsage(entries: SessionTreeEntry[]): Usage | undefined; /** Estimated context-token usage for a message list. */ interface ContextUsageEstimate { /** Estimated total context tokens. */ tokens: number; /** Tokens reported by the most recent assistant usage block. */ usageTokens: number; /** Estimated tokens after the most recent assistant usage block. */ trailingTokens: number; /** Index of the message that provided usage, or null when none exists. */ lastUsageIndex: number | null; } /** Estimate context tokens for messages using provider usage when available. */ declare function estimateContextTokens(messages: AgentMessage[]): ContextUsageEstimate; /** Return whether context usage exceeds the configured compaction threshold. */ declare function shouldCompact(contextTokens: number, contextWindow: number, settings: CompactionSettings): boolean; /** Estimate token count for one message using a conservative character heuristic. */ declare function estimateTokens(message: AgentMessage): number; /** Find the user-visible message that starts the turn containing an entry. */ declare function findTurnStartIndex(entries: SessionTreeEntry[], entryIndex: number, startIndex: number): number; /** Cut point selected for compaction. */ interface CutPointResult { /** Index of the first entry retained after compaction. */ firstKeptEntryIndex: number; /** Index of the turn-start entry when the cut splits a turn, otherwise -1. */ turnStartIndex: number; /** Whether the selected cut point splits an in-progress turn. */ isSplitTurn: boolean; } /** Find the compaction cut point that keeps approximately the requested recent-token budget. */ declare function findCutPoint(entries: SessionTreeEntry[], startIndex: number, endIndex: number, keepRecentTokens: number): CutPointResult; /** Generate or update a conversation summary for compaction. */ declare function generateSummary(currentMessages: AgentMessage[], model: Model, reserveTokens: number, apiKey: string | undefined, headers?: Record, signal?: AbortSignal, customInstructions?: string, previousSummary?: string, thinkingLevel?: ThinkingLevel, streamFn?: StreamFn$1, runtime?: AgentCoreCompletionRuntimeDeps): Promise>; /** Prepared inputs for a compaction run. */ interface CompactionPreparation { /** Entry id where retained history starts. */ firstKeptEntryId: string; /** Messages summarized into the history summary. */ messagesToSummarize: AgentMessage[]; /** Prefix messages summarized separately when compaction splits a turn. */ turnPrefixMessages: AgentMessage[]; /** Whether compaction splits a turn. */ isSplitTurn: boolean; /** Estimated context tokens before compaction. */ tokensBefore: number; /** Previous compaction summary used for iterative updates. */ previousSummary?: string; /** File operations extracted from summarized history. */ fileOps: FileOperations; /** Settings used to prepare compaction. */ settings: CompactionSettings; } /** Prepare session entries for compaction, or return undefined when compaction is not applicable. */ declare function prepareCompaction(pathEntries: SessionTreeEntry[], settings: CompactionSettings): Result; /** Generate compaction summary data from prepared session history. */ declare function compact(preparation: CompactionPreparation, model: Model, apiKey: string | undefined, headers?: Record, customInstructions?: string, signal?: AbortSignal, thinkingLevel?: ThinkingLevel, streamFn?: StreamFn$1, runtime?: AgentCoreCompletionRuntimeDeps): Promise>; //#endregion //#region packages/agent-core/src/harness/utils/shell-output.d.ts /** Options for shell execution with combined stdout/stderr capture. */ interface ShellCaptureOptions extends Omit { onChunk?: (chunk: string) => void; } /** Captured shell result, with large output optionally spilled to a file. */ interface ShellCaptureResult { output: string; exitCode: number | undefined; cancelled: boolean; truncated: boolean; fullOutputPath?: string; } /** Remove control characters that make terminal/model output unsafe to replay. */ declare function sanitizeBinaryOutput(str: string): string; /** Execute a command while keeping a bounded tail and optional full-output log. */ declare function executeShellWithCapture(env: ExecutionEnv, command: string, options?: ShellCaptureOptions): Promise>; //#endregion //#region packages/agent-core/src/harness/utils/truncate.d.ts declare const DEFAULT_MAX_LINES = 2000; declare const DEFAULT_MAX_BYTES: number; declare const GREP_MAX_LINE_LENGTH = 500; /** Result metadata for content truncated by line count, byte count, or both. */ interface TruncationResult { /** The truncated content */ content: string; /** Whether truncation occurred */ truncated: boolean; /** Which limit was hit: "lines", "bytes", or null if not truncated */ truncatedBy: "lines" | "bytes" | null; /** Total number of lines in the original content */ totalLines: number; /** Total number of bytes in the original content */ totalBytes: number; /** Number of complete lines in the truncated output */ outputLines: number; /** Number of bytes in the truncated output */ outputBytes: number; /** Whether the last line was partially truncated (only for tail truncation edge case) */ lastLinePartial: boolean; /** Whether the first line exceeded the byte limit (for head truncation) */ firstLineExceedsLimit: boolean; /** The max lines limit that was applied */ maxLines: number; /** The max bytes limit that was applied */ maxBytes: number; } /** Byte and line ceilings used by the truncation helpers. */ interface TruncationOptions { /** Maximum number of lines (default: 2000) */ maxLines?: number; /** Maximum number of bytes (default: 50KB) */ maxBytes?: number; } /** * Format byte counts for compact tool-output diagnostics. */ declare function formatSize(bytes: number): string; /** * Keep the beginning of content while respecting independent line and byte ceilings. * * Head truncation preserves complete lines; a first line that exceeds the byte * ceiling produces empty output and sets firstLineExceedsLimit. */ declare function truncateHead(content: string, options?: TruncationOptions): TruncationResult; /** * Keep the end of content while respecting independent line and byte ceilings. * * Tail truncation preserves recent output for command errors and may keep a * partial first line when one final line alone exceeds the byte ceiling. */ declare function truncateTail(content: string, options?: TruncationOptions): TruncationResult; /** * Trim a single display line and mark it with the grep-style truncation suffix. */ declare function truncateLine(line: string, maxChars?: number): { text: string; wasTruncated: boolean; }; //#endregion //#region src/agents/runtime/proxy.d.ts declare class ProxyMessageEventStream extends EventStream { constructor(); } /** * Proxy event types - server sends these with partial field stripped to reduce bandwidth. */ type ProxyAssistantMessageEvent = { type: "start"; } | { type: "text_start"; contentIndex: number; } | { type: "text_delta"; contentIndex: number; delta: string; } | { type: "text_end"; contentIndex: number; contentSignature?: string; } | { type: "thinking_start"; contentIndex: number; } | { type: "thinking_delta"; contentIndex: number; delta: string; } | { type: "thinking_end"; contentIndex: number; contentSignature?: string; } | { type: "toolcall_start"; contentIndex: number; id: string; toolName: string; } | { type: "toolcall_delta"; contentIndex: number; delta: string; } | { type: "toolcall_end"; contentIndex: number; } | { type: "done"; reason: Extract; usage: AssistantMessage["usage"]; } | { type: "error"; reason: Extract; errorMessage?: string; usage: AssistantMessage["usage"]; }; type ProxySerializableStreamOptions = Pick; interface ProxyStreamOptions extends ProxySerializableStreamOptions { /** Local abort signal for the proxy request */ signal?: AbortSignal; /** Auth token for the proxy server */ authToken: string; /** Proxy server URL (e.g., "https://genai.example.com") */ proxyUrl: string; } declare function streamProxy(model: Model, context: Context, options: ProxyStreamOptions): ProxyMessageEventStream; //#endregion export { JsonlSessionRepo as $, ThinkingLevelChangeEntry as $n, CompactionEntry as $t, getLastAssistantUsage as A, ResourcesUpdateEvent as An, AgentToolCall as Ar, AfterProviderResponseEvent as At, generateBranchSummary as B, SessionError as Bn, CustomMessage as Br, AgentHarnessStreamOptions as Bt, calculateContextTokens as C, MessageEntry as Cn, AgentContext as Cr, createCustomMessage as Ct, findCutPoint as D, PendingSessionWrite as Dn, AgentMessage as Dr, NodeExecutionEnv as Dt, estimateTokens as E, NavigateTreeResult as En, AgentLoopTurnUpdate as Er, signalProcessTree as Et, BranchSummaryDetails as F, SessionBeforeTreeEvent as Fn, BeforeToolCallContext as Fr, AgentHarnessOptions as Ft, createTimestamp as G, SessionRepo as Gn, ThinkingLevel as Gr, BeforeProviderPayloadResult as Gt, serializeConversation as H, SessionForkOptions as Hn, QueueMode as Hr, BeforeAgentStartEvent as Ht, CollectBranchPathEntriesResult as I, SessionBeforeTreeResult as In, BeforeToolCallResult as Ir, AgentHarnessOwnEvent as It, toSession as J, SessionTreeEntryBase as Jn, AgentCoreRuntimeDeps as Jr, BranchSummaryEntry as Jt, getEntriesToFork as K, SessionStorage as Kn, ToolExecutionMode as Kr, BeforeProviderRequestEvent as Kt, CollectEntriesResult as L, SessionCompactEvent as Ln, BranchSummaryMessage as Lr, AgentHarnessPhase as Lt, shouldCompact as M, SavePointEvent as Mn, AgentToolResult as Mr, AgentHarnessErrorCode as Mt, BranchPathEntry as N, SessionBeforeCompactEvent as Nn, AgentToolUpdateCallback as Nr, AgentHarnessEvent as Nt, findTurnStartIndex as O, PromptTemplate as On, AgentState as Or, AbortEvent as Ot, BranchPreparation as P, SessionBeforeCompactResult as Pn, BashExecutionMessage as Pr, AgentHarnessEventResultMap as Pt, loadJsonlSessionMetadata as Q, Skill as Qn, CompactResult as Qt, collectEntriesForBranchSummary as R, SessionContext as Rn, CompactionSummaryMessage as Rr, AgentHarnessPromptOptions as Rt, DEFAULT_COMPACTION_SETTINGS as S, LeafEntry as Sn, AfterToolCallResult as Sr, createCompactionSummaryMessage as St, estimateContextTokens as T, ModelSelectEvent as Tn, AgentLoopConfig as Tr, killProcessTree as Tt, uuidv7 as U, SessionInfoEntry as Un, ShouldStopAfterTurnContext as Ur, BeforeAgentStartResult as Ut, prepareBranchEntries as V, SessionErrorCode as Vn, PrepareNextTurnContext as Vr, AgentHarnessStreamOptionsPatch as Vt, createSessionId as W, SessionMetadata as Wn, StreamFn as Wr, BeforeProviderPayloadEvent as Wt, InMemorySessionRepo as X, SettledEvent as Xn, resolveAgentCoreCompleteFn as Xr, BranchSummaryErrorCode as Xt, InMemorySessionStorage as Y, SessionTreeEvent as Yn, AgentCoreStreamRuntimeDeps as Yr, BranchSummaryError as Yt, JsonlSessionStorage as Z, Shell as Zn, resolveAgentCoreStreamFn as Zr, BranchSummaryResult as Zt, CompactionDetails as _, JsonlSessionCreateOptions as _n, runAgentLoop as _r, HarnessMessage as _t, DEFAULT_MAX_LINES as a, CustomMessageEntry as an, TreePreparation as ar, loadSourcedSkills as at, CompactionSettings as b, JsonlSessionRepoApi as bn, AgentOptions as br, convertToLlm as bt, TruncationResult as c, ExecutionError as cn, getOrUndefined as cr, formatPromptTemplateInvocation as ct, truncateLine as d, FileErrorCode as dn, CoreAgentHarness as dr, parseCommandArgs as dt, CompactionError as en, ThinkingLevelSelectEvent as er, formatSkillsForSystemPrompt as et, truncateTail as f, FileInfo as fn, Session as fr, substituteArgs as ft, sanitizeBinaryOutput as g, GenerateBranchSummaryOptions$1 as gn, agentLoopContinue as gr, COMPACTION_SUMMARY_SUFFIX as gt, executeShellWithCapture as h, FileSystem as hn, agentLoop as hr, COMPACTION_SUMMARY_PREFIX as ht, DEFAULT_MAX_BYTES as i, CustomEntry as in, ToolResultPatch as ir, loadSkills as it, prepareCompaction as j, Result as jn, AgentToolProgress as jr, AgentHarnessError as jt, generateSummary as k, QueueUpdateEvent as kn, AgentTool as kr, AbortResult as kt, formatSize as l, ExecutionErrorCode as ln, ok as lr, loadPromptTemplates as lt, ShellCaptureResult as m, FileOperations$1 as mn, AgentEventSink as mr, BRANCH_SUMMARY_SUFFIX as mt, ProxyStreamOptions as n, ContextEvent as nn, ToolCallResult as nr, SkillDiagnosticCode as nt, GREP_MAX_LINE_LENGTH as o, ExecutionEnv as on, err as or, PromptTemplateDiagnostic as ot, ShellCaptureOptions as p, FileKind as pn, buildSessionContext as pr, BRANCH_SUMMARY_PREFIX as pt, getFileSystemResultOrThrow as q, SessionTreeEntry as qn, AgentCoreCompletionRuntimeDeps as qr, BeforeProviderRequestResult as qt, streamProxy as r, ContextResult as rn, ToolResultEvent as rr, formatSkillInvocation as rt, TruncationOptions as s, ExecutionEnvExecOptions as sn, getOrThrow as sr, PromptTemplateDiagnosticCode as st, ProxyAssistantMessageEvent as t, CompactionErrorCode as tn, ToolCallEvent as tr, SkillDiagnostic as tt, truncateHead as u, FileError as un, toError as ur, loadSourcedPromptTemplates as ut, CompactionPreparation as v, JsonlSessionListOptions as vn, runAgentLoopContinue as vr, asAgentMessage as vt, compact as w, ModelChangeEntry as wn, AgentEvent as wr, KillProcessTreeOptions as wt, ContextUsageEstimate as x, LabelEntry as xn, AfterToolCallContext as xr, createBranchSummaryMessage as xt, CompactionResult as y, JsonlSessionMetadata as yn, Agent as yr, bashExecutionToText as yt, collectEntriesForBranchSummaryFromBranches as z, SessionCreateOptions as zn, CustomAgentMessages as zr, AgentHarnessResources as zt };