import type { ImageContent, Model, SimpleStreamOptions, TextContent, Transport } from "@leanandmean/ai"; import type { AgentEvent, AgentMessage, AgentTool, QueueMode, ThinkingLevel } from "../index.js"; import type { Session } from "./session/session.js"; /** Result of a fallible operation. Expected failures are returned as `ok: false` instead of thrown. */ export type Result = { ok: true; value: TValue; } | { ok: false; error: TError; }; /** Create a successful {@link Result}. */ export declare function ok(value: TValue): Result; /** Create a failed {@link Result}. */ export declare function err(error: TError): Result; /** Return the success value or throw the failure error. Intended for tests and explicit adapter boundaries. */ export declare function getOrThrow(result: Result): TValue; /** Return the success value or `undefined`. Only object values are allowed to avoid truthiness bugs with primitives. */ export declare function getOrUndefined(result: Result): TValue | undefined; /** Normalize unknown thrown values into Error instances before using them as typed error causes. */ export 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. */ export 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. */ export 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. */ export 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. */ export 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. */ export 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. */ export type FileKind = "file" | "directory" | "symlink"; /** Stable, backend-independent file error codes returned by {@link FileSystem} file operations. */ export type FileErrorCode = "aborted" | "not_found" | "permission_denied" | "not_directory" | "is_directory" | "invalid" | "not_supported" | "unknown"; /** Error returned by {@link FileSystem} file operations. */ export declare class FileError extends Error { /** Backend-independent error code. */ code: FileErrorCode; /** Absolute addressed path associated with the failure, when available. */ path?: string | undefined; constructor( /** Backend-independent error code. */ code: FileErrorCode, message: string, /** Absolute addressed path associated with the failure, when available. */ path?: string | undefined, cause?: Error); } /** Stable, backend-independent execution error codes returned by {@link ExecutionEnv.exec}. */ export type ExecutionErrorCode = "aborted" | "timeout" | "shell_unavailable" | "spawn_error" | "callback_error" | "unknown"; /** Error returned by {@link ExecutionEnv.exec}. */ export declare class ExecutionError extends Error { /** Backend-independent error code. */ code: ExecutionErrorCode; constructor( /** Backend-independent error code. */ code: ExecutionErrorCode, message: string, cause?: Error); } /** Stable compaction error codes returned by compaction helpers. */ export type CompactionErrorCode = "aborted" | "summarization_failed" | "invalid_session" | "unknown"; /** Error returned by compaction helpers. */ export declare class CompactionError extends Error { /** Backend-independent error code. */ code: CompactionErrorCode; constructor( /** Backend-independent error code. */ code: CompactionErrorCode, message: string, cause?: Error); } /** Stable branch-summary error codes returned by branch summarization helpers. */ export type BranchSummaryErrorCode = "aborted" | "summarization_failed" | "invalid_session"; /** Error returned by branch summarization helpers. */ export declare class BranchSummaryError extends Error { /** Backend-independent error code. */ code: BranchSummaryErrorCode; constructor( /** Backend-independent error code. */ code: BranchSummaryErrorCode, message: string, cause?: Error); } export type SessionErrorCode = "not_found" | "invalid_session" | "invalid_entry" | "invalid_fork_target" | "storage" | "unknown"; /** Error thrown by session storage, repositories, and session tree operations. */ export declare class SessionError extends Error { /** Session subsystem error code. */ code: SessionErrorCode; constructor( /** Session subsystem error code. */ code: SessionErrorCode, message: string, cause?: Error); } export type AgentHarnessErrorCode = "busy" | "invalid_state" | "invalid_argument" | "session" | "hook" | "auth" | "compaction" | "branch_summary" | "unknown"; /** Public AgentHarness failure with a stable top-level classification. */ export declare class AgentHarnessError extends Error { code: AgentHarnessErrorCode; constructor(code: AgentHarnessErrorCode, message: string, cause?: Error); } /** Metadata for one filesystem object in a {@link FileSystem}. */ export 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}. */ export 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. */ export 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. */ export 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. */ export interface ExecutionEnv extends FileSystem, Shell { } export interface SessionTreeEntryBase { type: string; id: string; parentId: string | null; timestamp: string; } export interface MessageEntry extends SessionTreeEntryBase { type: "message"; message: AgentMessage; } export interface ThinkingLevelChangeEntry extends SessionTreeEntryBase { type: "thinking_level_change"; thinkingLevel: string; } export interface ModelChangeEntry extends SessionTreeEntryBase { type: "model_change"; provider: string; modelId: string; } export interface CompactionEntry extends SessionTreeEntryBase { type: "compaction"; summary: string; firstKeptEntryId: string; tokensBefore: number; details?: T; fromHook?: boolean; } export interface BranchSummaryEntry extends SessionTreeEntryBase { type: "branch_summary"; fromId: string; summary: string; details?: T; fromHook?: boolean; } export interface CustomEntry extends SessionTreeEntryBase { type: "custom"; customType: string; data?: T; } export interface CustomMessageEntry extends SessionTreeEntryBase { type: "custom_message"; customType: string; content: string | (TextContent | ImageContent)[]; details?: T; display: boolean; } export interface LabelEntry extends SessionTreeEntryBase { type: "label"; targetId: string; label: string | undefined; } export interface SessionInfoEntry extends SessionTreeEntryBase { type: "session_info"; name?: string; } export interface LeafEntry extends SessionTreeEntryBase { type: "leaf"; targetId: string | null; } export type SessionTreeEntry = MessageEntry | ThinkingLevelChangeEntry | ModelChangeEntry | CompactionEntry | BranchSummaryEntry | CustomEntry | CustomMessageEntry | LabelEntry | SessionInfoEntry | LeafEntry; export interface SessionContext { messages: AgentMessage[]; thinkingLevel: string; model: { provider: string; modelId: string; } | null; } export interface SessionMetadata { id: string; createdAt: string; } export interface JsonlSessionMetadata extends SessionMetadata { cwd: string; path: string; parentSessionPath?: string; } export 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; } export type { Session } from "./session/session.js"; export interface SessionCreateOptions { id?: string; } export interface SessionForkOptions { entryId?: string; position?: "before" | "at"; id?: string; } export 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>; } export interface JsonlSessionCreateOptions extends SessionCreateOptions { cwd: string; parentSessionPath?: string; } export interface JsonlSessionListOptions { cwd?: string; } export interface JsonlSessionRepoApi extends SessionRepo { } export type AgentHarnessPhase = "idle" | "turn" | "compaction" | "branch_summary" | "retry"; export type PendingSessionWrite = SessionTreeEntry extends infer TEntry ? TEntry extends SessionTreeEntry ? Omit : never : never; export interface QueueUpdateEvent { type: "queue_update"; steer: AgentMessage[]; followUp: AgentMessage[]; nextTurn: AgentMessage[]; } export interface SavePointEvent { type: "save_point"; hadPendingMutations: boolean; } export interface AbortEvent { type: "abort"; clearedSteer: AgentMessage[]; clearedFollowUp: AgentMessage[]; } export interface SettledEvent { type: "settled"; nextTurnCount: number; } export interface BeforeAgentStartEvent { type: "before_agent_start"; prompt: string; images?: ImageContent[]; systemPrompt: string; resources: AgentHarnessResources; } export interface ContextEvent { type: "context"; messages: AgentMessage[]; } export interface BeforeProviderRequestEvent { type: "before_provider_request"; model: Model; sessionId: string; streamOptions: AgentHarnessStreamOptions; } export interface BeforeProviderPayloadEvent { type: "before_provider_payload"; model: Model; payload: unknown; } export interface AfterProviderResponseEvent { type: "after_provider_response"; status: number; headers: Record; } export interface ToolCallEvent { type: "tool_call"; toolCallId: string; toolName: string; input: Record; } export interface ToolResultEvent { type: "tool_result"; toolCallId: string; toolName: string; input: Record; content: Array; details: unknown; isError: boolean; } export interface SessionBeforeCompactEvent { type: "session_before_compact"; preparation: CompactionPreparation; branchEntries: SessionTreeEntry[]; customInstructions?: string; signal: AbortSignal; } export interface SessionCompactEvent { type: "session_compact"; compactionEntry: CompactionEntry; fromHook: boolean; } export interface SessionBeforeTreeEvent { type: "session_before_tree"; preparation: TreePreparation; signal: AbortSignal; } export interface SessionTreeEvent { type: "session_tree"; newLeafId: string | null; oldLeafId: string | null; summaryEntry?: BranchSummaryEntry; fromHook?: boolean; } export interface ModelSelectEvent { type: "model_select"; model: Model; previousModel: Model | undefined; source: "set" | "restore"; } export interface ThinkingLevelSelectEvent { type: "thinking_level_select"; level: ThinkingLevel; previousLevel: ThinkingLevel; } export interface ResourcesUpdateEvent { type: "resources_update"; resources: AgentHarnessResources; previousResources: AgentHarnessResources; } export type AgentHarnessOwnEvent = QueueUpdateEvent | SavePointEvent | AbortEvent | SettledEvent | BeforeAgentStartEvent | ContextEvent | BeforeProviderRequestEvent | BeforeProviderPayloadEvent | AfterProviderResponseEvent | ToolCallEvent | ToolResultEvent | SessionBeforeCompactEvent | SessionCompactEvent | SessionBeforeTreeEvent | SessionTreeEvent | ModelSelectEvent | ThinkingLevelSelectEvent | ResourcesUpdateEvent; export type AgentHarnessEvent = AgentEvent | AgentHarnessOwnEvent; export interface BeforeAgentStartResult { messages?: AgentMessage[]; systemPrompt?: string; } export interface ContextResult { messages: AgentMessage[]; } export interface BeforeProviderRequestResult { streamOptions?: AgentHarnessStreamOptionsPatch; } export interface BeforeProviderPayloadResult { payload: unknown; } export interface ToolCallResult { block?: boolean; reason?: string; } export interface ToolResultPatch { content?: Array; details?: unknown; isError?: boolean; terminate?: boolean; } export interface SessionBeforeCompactResult { cancel?: boolean; compaction?: CompactResult; } export interface SessionBeforeTreeResult { cancel?: boolean; summary?: { summary: string; details?: unknown; }; customInstructions?: string; replaceInstructions?: boolean; label?: string; } export 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; }; export interface AgentHarnessPromptOptions { images?: ImageContent[]; } export interface AbortResult { clearedSteer: AgentMessage[]; clearedFollowUp: AgentMessage[]; } export interface CompactResult { summary: string; firstKeptEntryId: string; tokensBefore: number; details?: unknown; } export interface NavigateTreeResult { cancelled: boolean; editorText?: string; summaryEntry?: BranchSummaryEntry; } export interface CompactionSettings { enabled: boolean; reserveTokens: number; keepRecentTokens: number; } export interface CompactionPreparation { firstKeptEntryId: string; messagesToSummarize: AgentMessage[]; turnPrefixMessages: AgentMessage[]; isSplitTurn: boolean; tokensBefore: number; previousSummary?: string; fileOps: FileOperations; settings: CompactionSettings; } export interface FileOperations { read: Set; written: Set; edited: Set; } export interface TreePreparation { targetId: string; oldLeafId: string | null; commonAncestorId: string | null; entriesToSummarize: SessionTreeEntry[]; userWantsSummary: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string; } export interface GenerateBranchSummaryOptions { model: Model; apiKey: string; headers?: Record; signal: AbortSignal; customInstructions?: string; replaceInstructions?: boolean; reserveTokens?: number; } export interface BranchSummaryResult { summary: string; readFiles: string[]; modifiedFiles: string[]; } export 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>; /** Curated stream/provider request options. Snapshotted at turn start. */ streamOptions?: AgentHarnessStreamOptions; model: Model; thinkingLevel?: ThinkingLevel; activeToolNames?: string[]; steeringMode?: QueueMode; followUpMode?: QueueMode; } export type { AgentHarness } from "./agent-harness.js"; //# sourceMappingURL=types.d.ts.map