import type { JsonRepresentation } from "@earendil-works/chord"; import type { Api, AssistantMessage, AssistantMessageEvent, AssistantMessageFrame, DeferredHandle, ImageContent, Message, Model, Models, RetryPolicy, ToolResultMessage, Usage } from "@earendil-works/pi-ai"; import type { AgentMessage, AgentToolResult, QueueMode, ThinkingLevel } from "../types.ts"; import type { BranchPreparation, BranchSummaryResult } from "./compaction/branch-summarization.ts"; import type { CompactionPreparation, CompactionSettings, CompactResult } from "./compaction/compaction.ts"; import type { Context } from "./context.ts"; import type { Closed, InvalidMessage, InvalidNavigation, LaneBusy, NoActiveOperation, NothingToCompact, NothingToResume, OperationMismatch, Result, UnknownSkill, UnknownTarget, UnknownTemplate } from "./result.ts"; export { Closed, HarnessClosed, HarnessFault, InvalidLane, InvalidMessage, InvalidNavigation, LaneBusy, NoActiveOperation, NoActiveRun, NothingToCompact, NothingToResume, OperationMismatch, UnknownSkill, UnknownTarget, UnknownTemplate, } from "./result.ts"; export { SliceNotImplemented } from "./runtime/types.ts"; import { createAgentHarness } from "./runtime/harness.ts"; import type { BranchScan, Entry, EntryProjector, JsonValue, LaneConfiguration, OperationError, OperationResultRecord, Session, SessionStats, SettledAssistantMessage, UsageRow } from "./session/types.ts"; import type { AgentHarnessResources, AgentHarnessStreamOptions, AgentHarnessStreamOptionsPatch, AgentHarnessTool, PromptTemplate, Skill } from "./types.ts"; /** Convenience-only suspended run observation, constructed when M8 exposes public drive. */ export interface SuspendedRun { operationId: string; status: "suspended"; deferred: DeferredHandle; } export type RunResult = Result; export type CompactionResult = Result<{ compaction: OperationResultRecord; run?: OperationResultRecord | SuspendedRun; }, LaneBusy | NothingToCompact | Closed>; export type NavigationResult = Result<{ navigation: OperationResultRecord; run?: OperationResultRecord | SuspendedRun; }, LaneBusy | InvalidNavigation | UnknownTarget | Closed>; export type ResumeResult = Result; export type QueueResult = Result<{ entryId: string; }, InvalidMessage | Closed>; export type CancelQueuedResult = Result<{ kind: "cancelled" | "already_consumed" | "not_found"; }, Closed>; export type AbortResult = Result<{ operationId: string; steer: AgentMessage[]; followUp: AgentMessage[]; }, NoActiveOperation | Closed>; export type RecordUsageResult = Result<{ usageId: string; }, Closed>; export interface NavigateOptions { summarize?: boolean; label?: string; customInstructions?: string; } export type OperationRequest = { kind: "prompt"; operationId?: string; prompt: string; images?: ImageContent[]; } | { kind: "prompt"; operationId?: string; prompt: AgentMessage | AgentMessage[]; images?: never; } | { kind: "skill"; operationId?: string; name: string; additionalInstructions?: string; } | { kind: "prompt_template"; operationId?: string; name: string; args?: string[]; } | { kind: "compaction"; operationId?: string; customInstructions?: string; } | { kind: "navigation"; operationId?: string; targetId: string | null; options?: NavigateOptions; }; export interface OperationAdmission { operationId: string; kind: "run" | "compaction" | "navigation"; startedAt: number; } export type OperationAdmissionError = LaneBusy | InvalidMessage | UnknownSkill | UnknownTemplate | NothingToCompact | InvalidNavigation | UnknownTarget | Closed; export type OperationAdmissionResult = Result; export interface DriveOptions { operationId: string; waitForRetry?: boolean; pollDeferred?: boolean; } export interface ModelIdentity { provider: string; modelId: string; } export type OperationStatus = "running" | "open" | "aborting"; export interface CurrentOperationInfo { id: string; kind: "run" | "compaction" | "navigation"; startedAt: number; status: OperationStatus; capturedModel?: ModelIdentity; } export interface LaneExecutionInfo { lane: string; tipId: string | null; configuredModel: ModelIdentity; current: CurrentOperationInfo | null; lastOperationId: string | null; } export type DriveOutcome = { kind: "settled"; outcome: OperationResultRecord; } | { kind: "waiting"; operationId: string; reason: "retry"; notBefore: number; } | { kind: "waiting"; operationId: string; reason: "deferred"; deferred: DeferredHandle; }; export type DriveResult = Result; export type AbortRequestResult = Result<{ operationId: string; newlyRequested: boolean; steer: AgentMessage[]; followUp: AgentMessage[]; }, OperationMismatch | Closed>; export interface WatchHandle { snapshot: T; start(listener: EventListener): void; resnapshot(context: Context): Promise; unsubscribe(): void; } export interface LaneInfo { name: string; tipId: string | null; operation: CurrentOperationInfo | null; } export type LaneSnapshotTool = { status: "running"; toolCallId: string; toolName: string; args: unknown; result?: AgentToolResult; } | { status: "settled"; toolCallId: string; toolName: string; args: unknown; result: AgentToolResult; isError: boolean; }; export interface OpenOperation { lane: string; operationId: string; kind: "run" | "compaction" | "navigation"; startedAt: number; aborting?: true; } export type LaneQueuedItem = { entryId: string; kind: "steer" | "followUp" | "nextRun" | "write"; type: "message"; message: AgentMessage; } | { entryId: string; kind: "write"; type: "custom"; customType: string; data?: JsonValue; }; export interface LaneSnapshot { lane: string; transcript: Entry[]; tipId: string | null; lastResult?: OperationResultRecord; configuration: LaneConfiguration; stats: SessionStats; operation: null | { id: string; kind: "run" | "compaction" | "navigation"; startedAt: number; fromTipId: string | null; status: OperationStatus; retry?: { attempt: number; maxAttempts: number; nextAttemptAt: number; }; deferred?: { handle: DeferredHandle; poll: number; }; streamingMessage?: AssistantMessage; runningTools: LaneSnapshotTool[]; }; queues: LaneQueuedItem[]; faulted: boolean; } export interface SessionSnapshot { lanes: LaneInfo[]; faulted: boolean; } export type HarnessEventPayload = { type: "run_start"; runId: string; startedAt: number; } | { type: "run_resume"; runId: string; } | { type: "run_suspend"; runId: string; reason: "deferred"; deferred: DeferredHandle; poll: number; } | { type: "operation_abort"; operationId: string; steer: AgentMessage[]; followUp: AgentMessage[]; } | ({ type: "run_end"; runId: string; fromTipId: string | null; tipId: string | null; endedAt: number; } & ({ status: "completed" | "aborted"; error?: never; } | { status: "failed"; error: OperationError; })) | { type: "fault"; code: string; message: string; } | ({ type: "handler_error"; error: string; stack?: string; } & ({ kind: "hook"; hook: string; } | { kind: "event"; event: string; })) | { type: "turn_start"; runId: string; turnId: string; } | { type: "turn_end"; runId: string; turnId: string; message: AssistantMessage; toolResults: ToolResultMessage[]; } | { type: "retry_scheduled"; runId: string; step: string; attempt: number; maxAttempts: number; delayMs: number; notBefore: number; errorMessage: string; } | { type: "retry_start"; runId: string; step: string; attempt: number; } | { type: "retry_end"; runId: string; step: string; attempt: number; success: boolean; finalError?: string; } | { type: "message_start"; runId?: string; message: AgentMessage; } | { type: "message_update"; runId: string; message: AgentMessage; event: AssistantMessageEvent; frame?: AssistantMessageFrame; } | { type: "message_end"; runId?: string; message: AgentMessage; entryId?: string; } | { type: "tool_start"; runId: string; turnId: string; toolCallId: string; toolName: string; args: unknown; } | { type: "tool_update"; runId: string; turnId: string; toolCallId: string; toolName: string; partialResult: AgentToolResult; } | { type: "tool_end"; runId: string; turnId: string; toolCallId: string; toolName: string; result: AgentToolResult; isError: boolean; terminate: boolean; } | { type: "entry_added"; entry: Entry; } | { type: "queue_update"; queues: LaneQueuedItem[]; } | ({ type: "value_update"; } & ({ value: "session_name"; name: string | undefined; } | { value: "entry_label"; targetId: string; label: string | undefined; })) | ({ type: "config_update"; } & ({ property: "model"; value: { provider: string; modelId: string; }; previous: unknown; } | { property: "thinkingLevel"; value: ThinkingLevel; previous: ThinkingLevel; } | { property: "activeTools"; value: string[]; previous: string[]; } | { property: "tools" | "resources"; } | { property: "streamOptions"; value: AgentHarnessStreamOptions; previous: AgentHarnessStreamOptions; } | { property: "retryPolicy"; value: RetryPolicy; previous: RetryPolicy; } | { property: "compactionSettings"; value: CompactionSettings; previous: CompactionSettings; } | { property: "steeringMode"; value: QueueMode; previous: QueueMode; } | { property: "followUpMode"; value: QueueMode; previous: QueueMode; })) | { type: "compaction_start"; runId: string; reason: "manual" | "threshold" | "overflow"; startedAt: number; } | ({ type: "compaction_end"; runId: string; reason: "manual" | "threshold" | "overflow"; endedAt: number; } & ({ status: "completed"; entryId: string; error?: never; } | { status: "declined" | "aborted"; entryId?: never; error?: never; } | { status: "failed"; entryId?: never; error: OperationError; })) | { type: "navigation_start"; runId: string; targetId: string | null; startedAt: number; } | ({ type: "navigation_end"; runId: string; fromTipId: string | null; tipId: string | null; endedAt: number; } & ({ status: "completed" | "declined" | "aborted"; error?: never; } | { status: "failed"; error: OperationError; })) | { type: "lane_created"; at: string | null; } | { type: "usage"; lane: string; row: UsageRow; totals: Usage; }; export type SpecialEventPayload = Extract; export type LaneEventPayload = Exclude; export type ConfigEventPayload = Extract; export type LaneConfigEventPayload = Extract; export type GlobalConfigEventPayload = Exclude; export type HandlerErrorPayload = Extract; export type HarnessEvent = (LaneEventPayload & { lane: string; recovery?: true; }) | (LaneConfigEventPayload & { lane: string; recovery?: true; }) | (Extract & { lane?: never; recovery?: never; }) | (Extract & { recovery?: never; }) | (GlobalConfigEventPayload & { lane?: never; recovery?: never; }) | (HandlerErrorPayload & ({ lane: string; recovery?: true; } | { lane?: never; recovery?: never; })); type LaneWatchSourceEvent = Exclude | Extract | Omit, "event">; /** Strict-JSON snapshot representation published to remote transcript consumers. */ export type LaneTranscriptSnapshot = JsonRepresentation; /** Reducer-relevant strict-JSON Harness events published to remote transcript consumers. */ export type LaneWatchEvent = JsonRepresentation; export type HarnessEventType = HarnessEvent["type"]; export type EventListener = (event: TEvent, context: Context) => void | Promise; export interface Events { on(type: TType, listener: EventListener>): () => void; } export type Resources = AgentHarnessResources; type VoidHookResult = ReturnType<() => void>; export interface HookMap { before_run: { event: { prompt: AgentMessage[]; resources: Resources; }; result: { messages?: AgentMessage[]; } | undefined; }; before_drive: { event: { operation: "run" | "compaction" | "navigation"; }; result: VoidHookResult; }; before_run_end: { event: { runId: string; messages: AgentMessage[]; }; result: { followUp?: string; } | undefined; }; transform_context: { event: { messages: AgentMessage[]; systemPrompt: string; }; result: { messages?: AgentMessage[]; systemPrompt?: string; } | undefined; }; before_request: { event: { model: Model; step: "assistant" | "deferred" | "compaction" | "branch_summary"; attempt: number; streamOptions: AgentHarnessStreamOptions; }; result: { streamOptions?: AgentHarnessStreamOptionsPatch; } | undefined; }; before_payload: { event: { model: Model; payload: unknown; }; result: { payload: unknown; } | undefined; }; after_response: { event: { status?: number; headers?: Record; message: SettledAssistantMessage; }; result: { message?: SettledAssistantMessage; } | undefined; }; before_tool: { event: { toolCallId: string; toolName: string; args: Record; }; result: { args?: Record; block?: { reason: string; terminate?: boolean; }; } | undefined; }; after_tool: { event: { toolCallId: string; toolName: string; args: Record; content: AgentToolResult["content"]; details?: JsonValue; isError: boolean; usage?: Usage; }; result: { content?: AgentToolResult["content"]; details?: JsonValue; isError?: boolean; usage?: Usage; terminate?: boolean; } | undefined; }; before_compaction: { event: { reason: "manual" | "threshold" | "overflow"; preparation: CompactionPreparation; customInstructions?: string; }; result: { decline?: boolean; compaction?: CompactResult; } | undefined; }; before_navigation: { event: { targetId: string; preparation: BranchPreparation; customInstructions?: string; }; result: { decline?: boolean; summary?: BranchSummaryResult; } | undefined; }; } export type HookName = keyof HookMap; export type HookInvocation = HookMap[TName]["event"] & { lane: string; runId: string; }; export type HookHandler = (event: HookInvocation, context: Context) => Promise | HookMap[TName]["result"]; export interface Hooks { on(name: TName, handler: HookHandler, options?: { id?: string; }): () => void; } export type { EntryProjector } from "./session/types.ts"; export interface AgentHarnessOptions { session: Session; models: Models; model: Model; thinkingLevel?: ThinkingLevel; activeToolNames?: string[]; tools?: AgentHarnessTool[]; toolContext?: TContext | ((context: Context) => TContext | Promise); systemPrompt?: string | ((toolContext: TContext, context: Context) => string | Promise); resources?: Resources; streamOptions?: AgentHarnessStreamOptions; retry?: RetryPolicy; compaction?: CompactionSettings; steeringMode?: QueueMode; followUpMode?: QueueMode; toolExecution?: "sequential" | "parallel"; toProviderMessages?: (messages: AgentMessage[], context: Context) => Message[] | Promise; entryProjectors?: Record; } export interface AgentLane { readonly name: string; getTipId(context: Context): Promise; findEntries(query: BranchScan | undefined, context: Context): Promise; findEntry(query: BranchScan | undefined, context: Context): Promise; appendMessage(message: AgentMessage, context: Context): Promise; appendCustomEntry(customType: string, data: JsonValue | undefined, context: Context): Promise; getResult(operationId: string, context: Context): Promise; accept(request: OperationRequest, context: Context): Promise; drive(options: DriveOptions, context: Context): Promise; requestAbort(operationId: string, context: Context): Promise; inspectExecution(context: Context): Promise; prompt(text: string, images: ImageContent[] | undefined, context: Context): Promise; prompt(message: AgentMessage | AgentMessage[], context: Context): Promise; skill(name: string, additionalInstructions: string | undefined, context: Context): Promise; promptFromTemplate(name: string, args: string[] | undefined, context: Context): Promise; compact(options: { customInstructions?: string; } | undefined, context: Context): Promise; navigateTree(targetId: string | null, options: NavigateOptions | undefined, context: Context): Promise; resume(context: Context): Promise; abort(context: Context): Promise; steer(message: string | AgentMessage, images: ImageContent[] | undefined, context: Context): Promise; followUp(message: string | AgentMessage, images: ImageContent[] | undefined, context: Context): Promise; nextRun(message: string | AgentMessage, images: ImageContent[] | undefined, context: Context): Promise; cancelQueued(entryId: string, context: Context): Promise; recordUsage(usage: Usage, options: { entryId?: string; details?: JsonValue; } | undefined, context: Context): Promise; waitForIdle(context: Context): Promise; runWhenIdle(callback: (context: Context) => void | Promise, context: Context): Promise; getModel(context: Context): Promise | undefined>; setModel(model: ModelIdentity, context: Context): Promise; getThinkingLevel(context: Context): Promise; setThinkingLevel(level: ThinkingLevel, context: Context): Promise; getActiveTools(context: Context): Promise; setActiveTools(names: string[], context: Context): Promise; watch(context: Context): Promise>; } export interface AcquireLaneOptions { createAt?: string | null; } export interface AgentHarness { lane(name: string, context: Context): Promise; lane(name: string, options: AcquireLaneOptions, context: Context): Promise; lanes(context: Context): Promise; getName(context: Context): Promise; setName(name: string | undefined, context: Context): Promise; getLabel(targetId: string, context: Context): Promise; setLabel(targetId: string, label: string | undefined, context: Context): Promise; getTools(context: Context): Promise[]>; setTools(tools: AgentHarnessTool[], context: Context): Promise; getResources(context: Context): Promise; setResources(resources: Resources, context: Context): Promise; getStreamOptions(context: Context): Promise; setStreamOptions(options: AgentHarnessStreamOptions, context: Context): Promise; getRetryPolicy(context: Context): Promise; setRetryPolicy(policy: RetryPolicy, context: Context): Promise; getCompactionSettings(context: Context): Promise; setCompactionSettings(settings: CompactionSettings, context: Context): Promise; getSteeringMode(context: Context): Promise; setSteeringMode(mode: QueueMode, context: Context): Promise; getFollowUpMode(context: Context): Promise; setFollowUpMode(mode: QueueMode, context: Context): Promise; watchSession(context: Context): Promise>; readonly hooks: Hooks; readonly events: Events; close(context: Context): Promise; } export interface AgentHarnessConstructor { create(options: AgentHarnessOptions, context: Context): Promise<{ harness: AgentHarness; open: OpenOperation[]; }>; } /** Runtime constructor for attaching the durable harness to one open session. */ export declare const AgentHarness: { create: typeof createAgentHarness; }; //# sourceMappingURL=agent-harness.d.ts.map