import { _ as Tool, b as Usage, c as CompleteSimpleFn, d as Message, f as Model, g as ThinkingBudgets, h as TextContent, l as EventStream, m as StreamFn$1, n as EventStream$1, o as AssistantMessage, p as SimpleStreamOptions, s as AssistantMessageEvent, u as ImageContent, v as ToolResultMessage, y as Transport } from "./event-stream-ATJ--twH.js"; import { _ as SimpleStreamOptions$1, d as Model$1, i as AssistantMessageEvent$1, r as AssistantMessage$1, s as Context, v as StopReason } from "./types-CBQ0-JNc.js"; import { Static, TSchema } from "typebox"; //#region packages/agent-core/src/runtime-deps.d.ts interface AgentCoreRuntimeDeps { streamSimple: StreamFn$1; completeSimple: CompleteSimpleFn; } type AgentCoreStreamRuntimeDeps = Pick; type AgentCoreCompletionRuntimeDeps = Pick; declare function resolveAgentCoreStreamFn(runtime: AgentCoreStreamRuntimeDeps | undefined, streamFn?: StreamFn$1): StreamFn$1; 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"; /** * Extensible interface for custom app messages. * Apps can extend via declaration merging: * * @example * ```typescript * declare module "@mariozechner/agent" { * interface CustomAgentMessages { * artifact: ArtifactMessage; * notification: NotificationMessage; * } * } * ``` */ interface CustomAgentMessages extends Record {} /** * 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 { initialState?: Partial>; 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; 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. */ 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 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; declare function runAgentLoop(prompts: AgentMessage[], context: AgentContext, config: AgentLoopConfig, emit: AgentEventSink, signal?: AbortSignal, streamFn?: StreamFn, runtime?: AgentCoreStreamRuntimeDeps): Promise; 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 declare function buildSessionContext(pathEntries: SessionTreeEntry[]): SessionContext; 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; appendCustomEntry(customType: string, data?: unknown): Promise; appendCustomMessageEntry(customType: string, content: string | (TextContent | ImageContent)[], display: boolean, details?: unknown): Promise; appendLabel(targetId: string, label: string | undefined): Promise; appendSessionName(name: string): Promise; moveTo(entryId: string | null, summary?: { summary: string; details?: unknown; fromHook?: boolean; }): Promise; } //#endregion //#region packages/agent-core/src/harness/agent-harness.d.ts declare class AgentHarness { 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 {} interface SessionTreeEntryBase { type: string; id: string; parentId: string | null; timestamp: string; } interface MessageEntry extends SessionTreeEntryBase { type: "message"; message: AgentMessage; } interface ThinkingLevelChangeEntry extends SessionTreeEntryBase { type: "thinking_level_change"; thinkingLevel: string; } interface ModelChangeEntry extends SessionTreeEntryBase { type: "model_change"; provider: string; modelId: string; } interface CompactionEntry extends SessionTreeEntryBase { type: "compaction"; summary: string; firstKeptEntryId: string; tokensBefore: number; details?: T; fromHook?: boolean; } interface BranchSummaryEntry extends SessionTreeEntryBase { type: "branch_summary"; fromId: string; summary: string; details?: T; fromHook?: boolean; } interface CustomEntry extends SessionTreeEntryBase { type: "custom"; customType: string; data?: T; } interface CustomMessageEntry extends SessionTreeEntryBase { type: "custom_message"; customType: string; content: string | (TextContent | ImageContent)[]; details?: T; display: boolean; } interface LabelEntry extends SessionTreeEntryBase { type: "label"; targetId: string; label: string | undefined; } interface SessionInfoEntry extends SessionTreeEntryBase { type: "session_info"; name?: string; } interface LeafEntry extends SessionTreeEntryBase { type: "leaf"; targetId: string | null; } 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; interface BeforeAgentStartResult { messages?: AgentMessage[]; systemPrompt?: string; } interface ContextResult { messages: AgentMessage[]; } interface BeforeProviderRequestResult { streamOptions?: AgentHarnessStreamOptionsPatch; } interface BeforeProviderPayloadResult { payload: unknown; } interface ToolCallResult { block?: boolean; reason?: string; } interface ToolResultPatch { content?: Array; details?: unknown; isError?: boolean; terminate?: boolean; } interface SessionBeforeCompactResult { cancel?: boolean; compaction?: CompactResult; } interface SessionBeforeTreeResult { cancel?: boolean; summary?: { summary: string; details?: unknown; }; customInstructions?: string; replaceInstructions?: boolean; label?: string; } 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; }; interface AgentHarnessPromptOptions { images?: ImageContent[]; } interface AbortResult { clearedSteer: AgentMessage[]; clearedFollowUp: AgentMessage[]; } interface CompactResult { summary: string; firstKeptEntryId: string; tokensBefore: number; details?: unknown; } interface NavigateTreeResult { cancelled: boolean; editorText?: string; summaryEntry?: BranchSummaryEntry; } interface CompactionSettings$1 { enabled: boolean; reserveTokens: number; keepRecentTokens: number; } interface CompactionPreparation$1 { firstKeptEntryId: string; messagesToSummarize: AgentMessage[]; turnPrefixMessages: AgentMessage[]; isSplitTurn: boolean; tokensBefore: number; previousSummary?: string; fileOps: FileOperations$1; settings: CompactionSettings$1; } interface FileOperations$1 { read: Set; written: Set; edited: Set; } interface TreePreparation { targetId: string; oldLeafId: string | null; commonAncestorId: string | null; entriesToSummarize: SessionTreeEntry[]; userWantsSummary: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string; } interface GenerateBranchSummaryOptions$1 { model: Model; apiKey: string; headers?: Record; signal: AbortSignal; runtime?: AgentCoreCompletionRuntimeDeps; streamFn?: StreamFn$1; customInstructions?: string; replaceInstructions?: boolean; reserveTokens?: number; } interface BranchSummaryResult { summary: string; readFiles: string[]; modifiedFiles: string[]; } 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 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 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 = ""; interface BashExecutionMessage { role: "bashExecution"; command: string; output: string; exitCode: number | undefined; cancelled: boolean; truncated: boolean; fullOutputPath?: string; timestamp: number; excludeFromContext?: boolean; } interface CustomMessage { role: "custom"; customType: string; content: string | (TextContent | ImageContent)[]; display: boolean; details?: T; timestamp: number; } interface BranchSummaryMessage { role: "branchSummary"; summary: string; fromId: string; timestamp: number; } interface CompactionSummaryMessage { role: "compactionSummary"; summary: string; tokensBefore: number; timestamp: number; } declare module "../types.js" { interface CustomAgentMessages { bashExecution: BashExecutionMessage; custom: CustomMessage; branchSummary: BranchSummaryMessage; compactionSummary: CompactionSummaryMessage; } } declare function bashExecutionToText(msg: BashExecutionMessage): string; declare function createBranchSummaryMessage(summary: string, fromId: string, timestamp: string): BranchSummaryMessage; declare function createCompactionSummaryMessage(summary: string, tokensBefore: number, timestamp: string): CompactionSummaryMessage; declare function createCustomMessage(customType: string, content: string | (TextContent | ImageContent)[], display: boolean, details: unknown, timestamp: string): CustomMessage; declare function convertToLlm(messages: AgentMessage[]): Message[]; //#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; }>; /** 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. */ declare function substituteArgs(content: string, args: string[]): string; /** 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 declare function formatSkillsForSystemPrompt(skills: Skill[]): string; //#endregion //#region packages/agent-core/src/harness/session/jsonl-repo.d.ts type JsonlSessionRepoFileSystem = Pick; 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; declare function loadJsonlSessionMetadata(fs: JsonlSessionStorageFileSystem, filePath: string): Promise; declare class JsonlSessionStorage extends BaseSessionStorage { private readonly fs; private readonly filePath; private constructor(); static open(fs: JsonlSessionStorageFileSystem, filePath: string): Promise; 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 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 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 declare function createSessionId(): string; declare function createTimestamp(): string; declare function toSession(storage: SessionStorage): Session; declare function getFileSystemResultOrThrow(result: Result, message: string): TValue; declare function getEntriesToFork(storage: SessionStorage, options: { entryId?: string; position?: "before" | "at"; }): Promise; //#endregion //#region packages/agent-core/src/harness/session/uuid.d.ts 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; } interface BranchPathEntry { id: string; parentId: string | null; } 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 entries that should be summarized before navigating to a different session tree entry. */ 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 interface ShellCaptureOptions extends Omit { onChunk?: (chunk: string) => void; } interface ShellCaptureResult { output: string; exitCode: number | undefined; cancelled: boolean; truncated: boolean; fullOutputPath?: string; } declare function sanitizeBinaryOutput(str: string): string; declare function executeShellWithCapture(env: ExecutionEnv, command: string, options?: ShellCaptureOptions): Promise>; //#endregion //#region packages/agent-core/src/harness/utils/truncate.d.ts /** * Shared truncation utilities for tool outputs. * * Truncation is based on two independent limits - whichever is hit first wins: * - Line limit (default: 2000 lines) * - Byte limit (default: 50KB) * * Never returns partial lines (except bash tail truncation edge case). */ declare const DEFAULT_MAX_LINES = 2000; declare const DEFAULT_MAX_BYTES: number; declare const GREP_MAX_LINE_LENGTH = 500; 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; } interface TruncationOptions { /** Maximum number of lines (default: 2000) */ maxLines?: number; /** Maximum number of bytes (default: 50KB) */ maxBytes?: number; } /** * Format bytes as human-readable size. */ declare function formatSize(bytes: number): string; /** * Truncate content from the head (keep first N lines/bytes). * Suitable for file reads where you want to see the beginning. * * Never returns partial lines. If first line exceeds byte limit, * returns empty content with firstLineExceedsLimit=true. */ declare function truncateHead(content: string, options?: TruncationOptions): TruncationResult; /** * Truncate content from the tail (keep last N lines/bytes). * Suitable for bash output where you want to see the end (errors, final results). * * May return partial first line if the last line of original content exceeds byte limit. */ declare function truncateTail(content: string, options?: TruncationOptions): TruncationResult; /** * Truncate a single line to max characters, adding [truncated] suffix. * Used for grep match lines. */ declare function truncateLine(line: string, maxChars?: number): { text: string; wasTruncated: boolean; }; //#endregion //#region src/agents/runtime/proxy.d.ts declare class ProxyMessageEventStream extends EventStream$1 { 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$1["usage"]; } | { type: "error"; reason: Extract; errorMessage?: string; usage: AssistantMessage$1["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$1, context: Context, options: ProxyStreamOptions): ProxyMessageEventStream; //#endregion export { JsonlSessionRepo as $, Shell as $n, BranchSummaryResult as $t, getLastAssistantUsage as A, PromptTemplate as An, AgentState as Ar, AbortEvent as At, generateBranchSummary as B, SessionContext as Bn, QueueMode as Br, AgentHarnessPromptOptions as Bt, calculateContextTokens as C, LabelEntry as Cn, AfterToolCallContext as Cr, createBranchSummaryMessage as Ct, findCutPoint as D, ModelSelectEvent as Dn, AgentLoopConfig as Dr, killProcessTree as Dt, estimateTokens as E, ModelChangeEntry as En, AgentEvent as Er, KillProcessTreeOptions as Et, BranchSummaryDetails as F, SessionBeforeCompactEvent as Fn, AgentToolUpdateCallback as Fr, AgentHarnessEvent as Ft, createTimestamp as G, SessionInfoEntry as Gn, AgentCoreCompletionRuntimeDeps as Gr, BeforeAgentStartResult as Gt, serializeConversation as H, SessionError as Hn, StreamFn as Hr, AgentHarnessStreamOptions as Ht, CollectBranchPathEntriesResult as I, SessionBeforeCompactResult as In, BeforeToolCallContext as Ir, AgentHarnessEventResultMap as It, toSession as J, SessionStorage as Jn, resolveAgentCoreCompleteFn as Jr, BeforeProviderRequestEvent as Jt, getEntriesToFork as K, SessionMetadata as Kn, AgentCoreRuntimeDeps as Kr, BeforeProviderPayloadEvent as Kt, CollectEntriesResult as L, SessionBeforeTreeEvent as Ln, BeforeToolCallResult as Lr, AgentHarnessOptions as Lt, shouldCompact as M, ResourcesUpdateEvent as Mn, AgentToolCall as Mr, AfterProviderResponseEvent as Mt, BranchPathEntry as N, Result as Nn, AgentToolProgress as Nr, AgentHarnessError as Nt, findTurnStartIndex as O, NavigateTreeResult as On, AgentLoopTurnUpdate as Or, signalProcessTree as Ot, BranchPreparation as P, SavePointEvent as Pn, AgentToolResult as Pr, AgentHarnessErrorCode as Pt, loadJsonlSessionMetadata as Q, SettledEvent as Qn, BranchSummaryErrorCode as Qt, collectEntriesForBranchSummary as R, SessionBeforeTreeResult as Rn, CustomAgentMessages as Rr, AgentHarnessOwnEvent as Rt, DEFAULT_COMPACTION_SETTINGS as S, JsonlSessionRepoApi as Sn, AgentOptions as Sr, convertToLlm as St, estimateContextTokens as T, MessageEntry as Tn, AgentContext as Tr, createCustomMessage as Tt, uuidv7 as U, SessionErrorCode as Un, ThinkingLevel as Ur, AgentHarnessStreamOptionsPatch as Ut, prepareBranchEntries as V, SessionCreateOptions as Vn, ShouldStopAfterTurnContext as Vr, AgentHarnessResources as Vt, createSessionId as W, SessionForkOptions as Wn, ToolExecutionMode as Wr, BeforeAgentStartEvent as Wt, InMemorySessionRepo as X, SessionTreeEntryBase as Xn, BranchSummaryEntry as Xt, InMemorySessionStorage as Y, SessionTreeEntry as Yn, resolveAgentCoreStreamFn as Yr, BeforeProviderRequestResult as Yt, JsonlSessionStorage as Z, SessionTreeEvent as Zn, BranchSummaryError as Zt, CompactionDetails as _, FileSystem as _n, agentLoop as _r, COMPACTION_SUMMARY_PREFIX as _t, DEFAULT_MAX_LINES as a, ContextResult as an, ToolResultEvent as ar, loadSourcedSkills as at, CompactionSettings as b, JsonlSessionListOptions as bn, runAgentLoopContinue as br, CustomMessage as bt, TruncationResult as c, ExecutionEnv as cn, err as cr, formatPromptTemplateInvocation as ct, truncateLine as d, ExecutionErrorCode as dn, ok as dr, parseCommandArgs as dt, CompactResult as en, Skill as er, formatSkillsForSystemPrompt as et, truncateTail as f, FileError as fn, toError as fr, substituteArgs as ft, sanitizeBinaryOutput as g, FileOperations$1 as gn, AgentEventSink as gr, BranchSummaryMessage as gt, executeShellWithCapture as h, FileKind as hn, buildSessionContext as hr, BashExecutionMessage as ht, DEFAULT_MAX_BYTES as i, ContextEvent as in, ToolCallResult as ir, loadSkills as it, prepareCompaction as j, QueueUpdateEvent as jn, AgentTool as jr, AbortResult as jt, generateSummary as k, PendingSessionWrite as kn, AgentMessage as kr, NodeExecutionEnv as kt, formatSize as l, ExecutionEnvExecOptions as ln, getOrThrow as lr, loadPromptTemplates as lt, ShellCaptureResult as m, FileInfo as mn, Session as mr, BRANCH_SUMMARY_SUFFIX as mt, ProxyStreamOptions as n, CompactionError as nn, ThinkingLevelSelectEvent as nr, SkillDiagnosticCode as nt, GREP_MAX_LINE_LENGTH as o, CustomEntry as on, ToolResultPatch as or, PromptTemplateDiagnostic as ot, ShellCaptureOptions as p, FileErrorCode as pn, AgentHarness as pr, BRANCH_SUMMARY_PREFIX as pt, getFileSystemResultOrThrow as q, SessionRepo as qn, AgentCoreStreamRuntimeDeps as qr, BeforeProviderPayloadResult as qt, streamProxy as r, CompactionErrorCode as rn, ToolCallEvent as rr, formatSkillInvocation as rt, TruncationOptions as s, CustomMessageEntry as sn, TreePreparation as sr, PromptTemplateDiagnosticCode as st, ProxyAssistantMessageEvent as t, CompactionEntry as tn, ThinkingLevelChangeEntry as tr, SkillDiagnostic as tt, truncateHead as u, ExecutionError as un, getOrUndefined as ur, loadSourcedPromptTemplates as ut, CompactionPreparation as v, GenerateBranchSummaryOptions$1 as vn, agentLoopContinue as vr, COMPACTION_SUMMARY_SUFFIX as vt, compact as w, LeafEntry as wn, AfterToolCallResult as wr, createCompactionSummaryMessage as wt, ContextUsageEstimate as x, JsonlSessionMetadata as xn, Agent as xr, bashExecutionToText as xt, CompactionResult as y, JsonlSessionCreateOptions as yn, runAgentLoop as yr, CompactionSummaryMessage as yt, collectEntriesForBranchSummaryFromBranches as z, SessionCompactEvent as zn, PrepareNextTurnContext as zr, AgentHarnessPhase as zt };