@agentium/harness. Types such as ChatMessage, RunContext, and ExecutionServices come from @agentium/core. A ? marks an optional field.
requestInputTool
/** Grant this tool explicitly to let the model ask a voluntary, live question. */
export declare function requestInputTool(options?: {
name?: string;
description?: string;
timeoutMs?: number;
}): import("@agentium/core").ToolDef;
HarnessBudgetSnapshot
export interface HarnessBudgetSnapshot {
tokens: HarnessResourceSnapshot;
/** Logical calls, not HTTP attempts or SDK retries. */
modelCalls: HarnessResourceSnapshot;
toolCalls: HarnessResourceSnapshot;
/** Calls charged at their projection because complete provider usage was unavailable. */
unknownUsageCalls: number;
}
HarnessBudgetState
export type HarnessBudgetState = z.infer<typeof budgetStateSchema>;
HarnessResourceSnapshot
export interface HarnessResourceSnapshot {
/** null means unlimited. All other quantities use this resource's units. */
limit: number | null;
used: number;
reserved: number;
remaining: number | null;
finishingReserved: number;
ordinaryRemaining: number | null;
}
InputTokenEstimator
export type InputTokenEstimator = (input: {
provider: ModelProvider;
messages: readonly ChatMessage[];
tools: readonly ToolDefinition[];
}) => number;
parseHarnessBudgetState
export declare function parseHarnessBudgetState(value: unknown): HarnessBudgetState;
ExecutionDriver
export interface ExecutionDriver {
id: string;
version: number;
capabilities: {
controls: readonly HarnessSendMode[];
durable: boolean;
policyCoverage: "local" | "remote" | "none";
/** True only when each model/tool operation uses provided execution services. */
controlledExecution: boolean;
};
start: (request: HarnessRunRequest, services: HarnessExecutionServices) => Promise<HarnessDriverOutput>;
}
HarnessBudgets
export interface HarnessBudgets {
maxModelCalls?: number;
maxToolCalls?: number;
/** Aggregate prompt + completion tokens for this run, including independent control/finishing calls. */
maxTokens?: number;
maxRevisions?: number;
/** Protected portion of maxTokens, not an additional allowance. */
finishingTokens?: number;
/** Protected portion of maxModelCalls. Finishing operations are tool-free. */
finishingModelCalls?: number;
}
HarnessDriverOutput
export interface HarnessDriverOutput {
status?: HarnessStatus;
text: string;
structured?: unknown;
reason?: HarnessReason;
partial?: boolean;
providerFinishReason?: string;
usage?: TokenUsage;
history?: readonly ChatMessage[];
artifacts?: readonly {
id: string;
mimeType?: string;
}[];
}
HarnessExecutionServices
export interface HarnessExecutionServices extends ExecutionServices {
/** Observe every settled effect before cancellation-sensitive result processing. */
observeToolSettlements(results: readonly ToolCallResult[], context?: RunContext): Promise<void>;
readonly budget: HarnessBudgetSnapshot;
readonly archivedHistory: readonly HistoryArchiveReference[];
retrieveHistory(referenceId: string): Promise<ChatMessage[]>;
/** Explicit tool-free finishing work; grants and terminal completion policy still apply. */
finishModel(role: string, messages: readonly ChatMessage[], options?: Pick<ModelConfig, "maxTokens" | "temperature">): Promise<ModelResponse>;
readonly definitionId?: string;
/** Agent-specific declarative options interpreted only by the configured Agent driver. */
readonly agentConfiguration?: {
defaults: HarnessDefaults;
limits: NonNullable<HarnessManifest["limits"]>;
projectRoot: string;
};
/** Independent, tool-free policy call using an explicitly granted host role and shared budgets.
* Skips task controllers, context projection and middleware to avoid policy recursion.
*/
controlModel(role: string, messages: readonly ChatMessage[], options?: Pick<ModelConfig, "maxTokens" | "temperature">): Promise<ModelResponse>;
append(messages: readonly ChatMessage[]): void;
emit(payload: Exclude<HarnessEventPayload, {
type: "run.terminal" | "run.started";
}>): void;
requestInput(request: InputRequestOptions): Promise<InputReply>;
takeInput(context?: RunContext): {
id: string;
input: MessageContent;
mode: HarnessSendMode;
} | undefined;
resource<T>(id: string, scope: "host" | "session" | "run", initialize: () => Promise<ScopedResource<T>>): Promise<T>;
putArtifact(value: unknown): string;
getArtifact(id: string): unknown;
}
HarnessGrants
export interface HarnessGrants {
toolIds: readonly string[];
requiredToolIds?: readonly string[];
modelRoles: readonly string[];
}
HarnessNativeJournal
/** Host implementation must atomically verify input identity and retain complete
* output under the existing task lease/fence. Rejected work is not completion.
* `snapshot-chunk` operations contain immutable content-addressed text, have no
* application effects, and may safely retry an interrupted write. Keep their
* outputs for the same lifetime as the operations that reference them. */
export interface HarnessNativeJournal {
operation(id: string, input: DurableJSON, execute: () => Promise<DurableJSON>): Promise<DurableJSON>;
}
HarnessNativeRecoveryOptions
export interface HarnessNativeRecoveryOptions {
/** Stable logical task identity, shared across replacement workers. */
taskId: string;
/** Pinned executable, tool/skill and policy identities; never credentials. */
configuration: DurableJSON;
journal: HarnessNativeJournal;
application?: {
capture(): DurableJSON | Promise<DurableJSON>;
restore(state: DurableJSON): void | Promise<void>;
};
/** Return a durably accepted answer, or throw HarnessNativeInputPending after
* durably recording the question. Never hold an open worker for a human wait. */
requestInput?(request: InputRequest): Promise<InputReply>;
/** Bound each journal envelope, including immutable snapshot fragments. */
maxRecordBytes?: number;
}
HarnessRecoveryBoundary
/** Complete portable observations, in native conversation order. Tool results are
* one complete settled batch in declaration order, never completion order. */
export type HarnessRecoveryBoundary = z.infer<typeof boundarySchema>;
HarnessRecoveryLifecycleOptions
/** Application-state lifecycle only. This does not replay providers, checkpoint
* the Agent cursor, recover questions/streams or make a native driver durable.
* Persistence must use the caller's existing task fence and atomic transaction. */
export interface HarnessRecoveryLifecycleOptions {
adapter: HarnessRecoveryStateAdapter;
state?: HarnessRecoveryState;
persist(state: HarnessRecoveryState): Promise<void>;
/** Reject rather than truncate. Paging/retention needs a separate contract. */
maxBytes?: number;
maxRecords?: number;
}
HarnessRecoveryState
export type HarnessRecoveryState = z.infer<typeof stateSchema>;
HarnessRecoveryStateAdapter
export interface HarnessRecoveryStateAdapter {
id: string;
version: string;
/** Host commitment to executable/configuration versions, including tools,
* skills, context, reducers and middleware. Never include credentials. */
configuration: DurableJSON;
captureInitialState(): DurableJSON | Promise<DurableJSON>;
restoreState(state: DurableJSON): void | Promise<void>;
/** Pure transition: do not mutate closures, persist, call tools or emit events.
* Inputs are frozen. Move application mutations into this ordered reducer. */
reduce(state: DurableJSON, boundary: HarnessRecoveryBoundary): DurableJSON | Promise<DurableJSON>;
}
HarnessRunRequest
export interface HarnessRunRequest {
input: MessageContent;
identity: HarnessIdentity;
sessionId: string;
runId: string;
attemptId: string;
parentRunId?: string;
rootRunId: string;
signal: AbortSignal;
deadline?: number;
grants: HarnessGrants;
runMode: RunMode;
}
HarnessRunState
export type HarnessRunState = "running" | "awaiting_input" | "cancelling" | "finished";
HarnessRuntimeConfig
export interface HarnessRuntimeConfig {
/** Optional observer bus for the runtime and its direct model/controller calls.
* Keep Agent instrumentation on its own bus to avoid counting the same call twice. */
telemetry?: EventBus;
driver?: ExecutionDriver;
definition?: HarnessDefinition;
projectRoot?: string;
requirements?: readonly string[];
tools?: readonly ToolDef[];
models?: Readonly<Record<string, ModelRoleBinding>>;
grants: HarnessGrants;
budgets?: HarnessBudgets;
/** Estimate projected input including tools and opaque replay; hard bounds require a conservative host estimator. */
estimateInputTokens?: InputTokenEstimator;
executionPolicy?: ExecutionPolicy;
approvalManager?: ApprovalManager;
controller?: StepController;
contextPolicy?: ContextPolicy;
completionPolicy?: CompletionPolicy;
/** Explicit opt-in to new tool effects in completion revisions. */
allowRevisionEffects?: boolean;
sessionStore?: HarnessSessionStore;
residentHistory?: ResidentHistoryPolicy;
/** Host-owned bounded source evidence, off by default. */
recall?: {
store: RecallStore;
budget: RecallBudget;
policy: RecallPolicy;
maxClarifications?: number;
};
/** Incremental archival summaries, off by default; requires recall and residentHistory. */
taskSummary?: TaskSummaryConfig;
resources?: HarnessResourcePool;
eventCapacity?: number;
/** Active wall time, excluding a pending user question. */
activeTimeoutMs?: number;
/** Maximum wait per question. Omit to wait until reply, cancellation or deadline. */
inputTimeoutMs?: number;
}
HarnessSendMode
export type HarnessSendMode = "follow_up" | "steer" | "replace";
HarnessStartOptions
export interface HarnessStartOptions {
/** Borrowed root admission boundary, shared by nested controlled work. */
rootExecution?: RootExecutionController;
/** Trusted recovery adapter only. Restored limits must exactly match host budgets. */
recovery?: {
budgetState?: HarnessBudgetState;
persistBudget(state: HarnessBudgetState): Promise<void>;
invokeTool?: ExecutionServices["invokeTool"];
/** Opt-in application-state causal boundaries only. Does not make this
* driver durable or replay model calls, context, input or streaming. */
lifecycle?: HarnessRecoveryLifecycleOptions;
/** SDK-owned recorded native decisions; the host supplies the authoritative
* fenced task journal and recoverable effect connectors. */
native?: HarnessNativeRecoveryOptions;
};
identity: HarnessIdentity;
sessionId: string;
parentRunId?: string;
rootRunId?: string;
signal?: AbortSignal;
deadline?: number;
grants?: HarnessGrants;
runMode?: RunMode;
recallScope?: {
projectId?: string;
repositoryId?: string;
};
/** Host attests that a meaningful untagged legacy snapshot belongs to the requested exact scope. */
attestLegacyMemoryScope?: boolean;
}
RunHandle
export interface RunHandle {
readonly budget: HarnessBudgetSnapshot;
readonly runId: string;
/** Live state; waiting never resolves result(). */
readonly state: HarnessRunState;
readonly pendingInput: InputRequest | undefined;
reply(requestId: string, input: MessageContent): Promise<void>;
events(options?: {
after?: number;
}): AsyncGenerator<HarnessEvent>;
result(): Promise<HarnessResult>;
cancel(reason?: string): void;
send(input: MessageContent, options: {
mode: HarnessSendMode;
}): Promise<void>;
}
createHarnessRecoveryLifecycle
/** Creates one causal cursor for one native execution attempt. On restoration,
* only the initial state is exposed; retained later states become visible after
* the corresponding exact boundary is encountered. */
export declare function createHarnessRecoveryLifecycle(options: HarnessRecoveryLifecycleOptions, scope: unknown): {
initialize: () => Promise<void>;
settle: (input: HarnessRecoveryBoundary) => Promise<void>;
idle: () => Promise<void>;
finish: () => Promise<void>;
};
HarnessBudgetError
export declare class HarnessBudgetError extends Error {
readonly code = "budget_exhausted";
constructor(message: string);
}
HarnessNativeInputPending
export declare class HarnessNativeInputPending extends Error {
readonly request: InputRequest;
readonly code = "native_input_pending";
constructor(request: InputRequest);
}
HarnessRecoveryLifecycleError
export declare class HarnessRecoveryLifecycleError extends Error {
readonly code = "recovery_lifecycle";
constructor(message: string, options?: ErrorOptions);
}
HarnessRuntime
/** Local lifecycle owner. Custom driver code is trusted; services enforce all intercepted effects. */
export declare class HarnessRuntime {
readonly sessions: HarnessSessionStore;
readonly resources: HarnessResourcePool;
getArtifact(identity: HarnessIdentity, sessionId: string, id: string): unknown;
constructor(config: HarnessRuntimeConfig);
/** Read archived canonical records by a scoped reference; never injects them into model context. */
retrieveHistory(identity: HarnessIdentity, sessionId: string, referenceId: string): Promise<ChatMessage[]>;
run(input: MessageContent, options: HarnessStartOptions): Promise<HarnessResult>;
stream(input: MessageContent, options: HarnessStartOptions): AsyncGenerator<HarnessEvent>;
start(input: MessageContent, options: HarnessStartOptions): RunHandle;
}
HarnessUnsupportedError
export declare class HarnessUnsupportedError extends Error {
readonly operation: string;
readonly code = "unsupported";
constructor(operation: string);
}
isHarnessNativeInputPending
/** Also recognizes the equivalent class from the package's other module format. */
export declare function isHarnessNativeInputPending(error: unknown): error is HarnessNativeInputPending;
HarnessInputErrorCode
export type HarnessInputErrorCode = "invalid_input" | "input_pending" | "input_not_pending" | "input_mismatch" | "input_already_resolved" | "run_finished";
HarnessInputError
export declare class HarnessInputError extends Error {
readonly code: HarnessInputErrorCode;
constructor(code: HarnessInputErrorCode, message: string);
}
parseRunInput
/** Prevalidate encoded message content before claiming a reply. State is checked again by reply/send/start. */
export declare function parseRunInput(encoded: string): MessageContent;
RUN_INPUT_LIMITS
export declare const RUN_INPUT_LIMITS: Readonly<{
maxEncodedBytes: 65536;
maxNormalizedBytes: 65536;
maxQuestionBytes: 32768;
maxChoices: 100;
}>;
validateRunInput
export declare function validateRunInput(input: unknown): MessageContent;
Supporting types
These shapes appear in the signatures above but are not named exports of the package entrypoint.ExecutionServices
/** Host-supplied execution boundary. Core consumes these operations; it does not
* construct or own the host's orchestration, configuration, or resource lifecycle.
*/
export interface ExecutionServices {
/** Durable native execution serializes tools to commit causal state safely. */
readonly toolConcurrency?: number;
/** Propagate host control flow (for example durable input suspension). */
isControlFlowError?(error: unknown): boolean;
/** Retain one complete tool outcome, including authorization and output transforms. */
executeTool?(call: ToolCall, context: RunContext, execute: () => Promise<ToolCallResult>): Promise<ToolCallResult>;
readonly rootExecution?: RootExecutionController;
/** Journal a validated/authorized invocation. Call execute only for fresh dispatch;
* recorded results can return without a new root work attempt. */
invokeTool?(tool: ToolDef, call: ToolCall, args: Record<string, unknown>, context: RunContext, execute: () => Promise<string | ToolResult>): Promise<string | ToolResult>;
/** Suspend a live tool or driver until a correlated user reply arrives. */
requestInput?(request: InputRequestOptions): Promise<InputReply>;
/** Consume steering only at a complete conversation boundary. */
takeInput?(context?: RunContext): RunInput | undefined;
publishMessage?(event: PublicMessageEvent): void;
/** Close steering atomically when the root conversation loop finishes. */
finishInput?(context: RunContext): void;
readonly ctx: RunContext;
readonly signal: AbortSignal;
readonly tools: readonly ToolDef[];
readonly history: readonly ChatMessage[];
/** Archive closed records before returning a bounded resident replay window. */
retainHistory?(provider: ModelProvider, messages: readonly ChatMessage[], context?: RunContext): Promise<ChatMessage[]>;
readonly executionPolicy: ExecutionPolicy;
readonly approvalManager?: ApprovalManager;
readonly state: Record<string, unknown>;
readonly sessionKey: string;
model(provider: ModelProvider, messages: ChatMessage[], options?: ModelConfig & {
tools?: ToolDefinition[];
}, context?: RunContext): Promise<ModelResponse>;
streamModel(provider: ModelProvider, messages: ChatMessage[], options?: ModelConfig & {
tools?: ToolDefinition[];
}, context?: RunContext): AsyncGenerator<StreamChunk>;
runOwned<T>(operation: () => Promise<T>): Promise<T>;
/** Observe every already-settled result before cancellation or control hooks stop
* batch processing. This callback records evidence only and must tolerate abort.
*/
observeToolSettlements?(results: readonly ToolCallResult[], context?: RunContext): Promise<void>;
observeTool(result: ToolCallResult, context?: RunContext): Promise<void>;
dispatchEffect<T>(name: string, args: Record<string, unknown>, execute: (args: Record<string, unknown>, ctx: RunContext) => Promise<T>): Promise<T>;
dispatch(call: ToolCall): Promise<ToolCallResult>;
recordConversation(executionId: string, messages: readonly ChatMessage[]): void;
}