Skip to main content

@flow-state-dev/core/harness

Classes​

HarnessAttachmentRefusedError​

Thrown before a harness run starts: the turn carries a file the harness can't take. Nothing ran.

Extends​

  • Error

Constructors​

Constructor​
new HarnessAttachmentRefusedError(harness, attachment): HarnessAttachmentRefusedError;
Parameters​
harness​

string

The harness that refused, as a person names it (Codex).

attachment​

FileContent

Returns​

HarnessAttachmentRefusedError

Overrides​

Error.constructor

Properties​

attachment​
readonly attachment: FileContent;
cause?​
cause?: unknown;
Inherited from​

Error.cause

harness​
readonly harness: string;

The harness that refused, as a person names it (Codex).

message​
message: string;
Inherited from​

Error.message

name​
name: string;
Inherited from​

Error.name

stack?​
stack?: string;
Inherited from​

Error.stack


HarnessAttachmentUnavailableError​

Thrown when a turn's file can't be read for the harness. The run does not start without it.

Extends​

  • Error

Constructors​

Constructor​
new HarnessAttachmentUnavailableError(attachment, options?): HarnessAttachmentUnavailableError;
Parameters​
attachment​

FileContent

options?​
cause?​

unknown

Returns​

HarnessAttachmentUnavailableError

Overrides​

Error.constructor

Properties​

attachment​
readonly attachment: FileContent;
cause?​
cause?: unknown;
Inherited from​

Error.cause

message​
message: string;
Inherited from​

Error.message

name​
name: string;
Inherited from​

Error.name

stack?​
stack?: string;
Inherited from​

Error.stack

Interfaces​

ClassifiedHarnessError​

An error a harness block fails with, carrying its HarnessFailureKind.

Extends​

  • Error

Properties​

cause?​
cause?: unknown;
Inherited from​

Error.cause

harnessFailure​
readonly harnessFailure: "unknown-conversation" | null;
message​
message: string;
Inherited from​

Error.message

name​
name: string;
Inherited from​

Error.name

stack?​
stack?: string;
Inherited from​

Error.stack


FollowingRun​

What the host knows of the run that recorded a pull request, handed to its PullRequestFollower.

Properties​

taskId?​
readonly taskId?: string;

The task the run works, when it works one: its failure or cancel ends what the follower made.


Harness​

One coding harness, as a plain value: what a harness package (Claude Code, Codex, Cursor, one of your own) exports and the harness kit's harnesses slot holds. A scripted stand-in under the same id is a harness value too.

Properties​

agent​
readonly agent: (feeds) => HarnessBlock;

The block one run runs, built from the feeds its runner hands it.

Parameters​
feeds​

HarnessFeeds

Returns​

HarnessBlock

id​
readonly id: string;

The harness's key: what a worker's harness: line names, and what readiness rows are keyed by.

label?​
readonly label?: string;

The name a person sees (Codex). Defaults to id.

models?​
readonly models?: (options?) => Promise<HarnessModelList<HarnessModelInfo>>;

The models it offers, when it can list them.

Parameters​
options?​
signal?​

AbortSignal

Returns​

Promise<HarnessModelList<HarnessModelInfo>>

pass​
readonly pass: readonly string[];

The environment variable names a run of it is given, beside the base ones.

readiness​
readonly readiness: HarnessReadinessCheck;

Whether this machine can run it, over the environment its runs get.

usage?​
readonly usage?: HarnessUsageReader;

How much of its subscription the machine has used, when the harness reports it.


HarnessAttachmentBytes​

One file's bytes, as a harness adapter hands them to its SDK.

Properties​

bytes​
bytes: Uint8Array;
filename?​
filename?: string;

The name it was attached under, when it had one.

mediaType​
mediaType: string;

The type the file was stored as, which is the one a harness is told.

Methods​

base64()​
base64(): string;

The bytes as base64, for an SDK that takes a string.

Returns​

string

text()?​
text?(): Promise<string>;

A document's text as a target that gets text receives it, headed by its name: a text-like file's own text, a PDF's extracted text. The engine's reader fills it. Rejects with AttachmentTextTooLargeError for a PDF whose text is over ATTACHMENT_LIMITS.maxTextBytes, never cutting it.

Returns​

Promise<string>


HarnessEnvOptions​

Options for harnessEnv.

Properties​

env?​
env?: Record<string, string | undefined>;

Where the values are read from. Default: process.env where there is a process, and an empty source where there is none (a browser or edge runtime), so calling this there returns {} instead of throwing.

pass​
pass: readonly string[];

The variables the child may see, by exact name. Nothing else is passed: not PATH, not HOME, not the harness's own credential, unless it is named here. A name that is unset in the source is left out rather than passed empty.


HarnessFeeds​

The feeds a runner hands a harness when it builds the block one run or turn runs: where it works, which conversation it continues, and the hooks it reports through.

One type for every runner: a task run (the harness manager) and a session turn (the session flow) both build it. A field only one of them fills is optional and says so. A harness ignores a hook it cannot call.

Why onSession and not only cwd and resume: a harness stopped on a deadline returns no handle at all, so unless it hands the session id to runner-owned durable state the moment its vendor names it, the next attempt has nothing to resume.

Properties​

cwd​
readonly cwd: HarnessResolver<string>;

Where this run works. Provisioned by the runner, then handed back.

model?​
readonly model?: HarnessResolver<string | undefined>;

The model this run uses, or undefined for the harness's own default. Filled by the session runner (the session's pick); a task run leaves it unset.

onActivity?​
readonly onActivity?: HarnessActivityHook;

Called with each assistant message and tool call of the run. Filled by the task runner, which keeps the task's status note from it.

onEvent?​
readonly onEvent?: HarnessEventHook;

Called on every event the run sends: each one starts the run's silence window again (and, on a task run, marks its checkout lock live). A harness that never calls it is stopped once that window has passed.

onSession​
readonly onSession: HarnessSessionHook;

Called the moment the vendor names the session. The runner's only writer of that id.

onSteerable?​
readonly onSteerable?: HarnessSteerHook;

Called by a harness whose run can take a line into its turn in flight, with the steer that does it, and with null once it can't. Both runners fill it; optional so a host wrapping the feeds in a slot of its own keeps compiling.

onToolApproval?​
readonly onToolApproval?: HarnessToolApprovalHook;

Called by a harness that asks about each tool call before it runs. Handed only when the runner is built with approveTools; absent otherwise. A held call stops the run, waits for a person, and the conversation resumes with the answer.

onUsage​
readonly onUsage: HarnessUsageHook;

Called with each subscription usage window the vendor reports during the run, writing it into the run owner's usage record. A harness that reports no usage ignores it.

resume​
readonly resume: HarnessResolver<string | null>;

Which conversation this run continues, or null to start fresh: the first attempt or turn, and any after one whose harness never confirmed a session, so a dead id is asked for once rather than forever.

worktree​
readonly worktree: HarnessResolver<string>;

Where the run's working directory is, for a fence that names it (a sandbox's writable paths). Its real path once cwd has provisioned it.


HarnessModelInfo​

One model a harness offers, as its package's model-list function reports it.

Properties​

description?​
description?: string;

The harness's description of it, when it gave one.

id​
id: string;

The id a run takes. Pass it as the block's model.

isDefault​
isDefault: boolean;

Whether this is the model the harness runs when none is named. A list may mark none: a vendor whose catalog names no default.

label​
label: string;

The harness's name for it, for a person.


HarnessRunCost​

What a run cost, and where the number came from.

Properties​

basis​
basis: HarnessCostBasis;
usd​
usd: number;

HarnessRunEnvelope​

The identity and status of a run — what every dispatch can report, whether or not it ever observes a result.

A one-way door (dispatch into a cloud queue and return) stops here; a harness that runs to completion returns the fuller HarnessRunHandle.

Extended by​

Properties​

dispatchedAt​
dispatchedAt: number;

Epoch millis when the handle was created.

sessionId​
sessionId: string | null;

The harness's own session/run id, when one could be determined.

source​
source: string;

Which harness and door produced this — see HarnessSource.

status​
status: HarnessRunStatus;
url​
url: string | null;

Human-openable URL for the run, when the harness exposes one.


HarnessRunHandle​

What a harness hands back after a run it observed to completion.

Every field is one any harness can fill honestly — that is the bar for belonging here. The four beyond the envelope are null when the harness reported nothing; values are never invented.

Extends​

Properties​

cost​
cost: HarnessRunCost | null;

What the run cost and how that was arrived at, or null when neither is known.

dispatchedAt​
dispatchedAt: number;

Epoch millis when the handle was created.

Inherited from​

HarnessRunEnvelope.dispatchedAt

finalMessage​
finalMessage: string | null;

The run's last assistant text, or null if it produced none.

outcome​
outcome: HarnessRunOutcome | null;

How the run ended, or null while it is unknown.

sessionId​
sessionId: string | null;

The harness's own session/run id, when one could be determined.

Inherited from​

HarnessRunEnvelope.sessionId

source​
source: string;

Which harness and door produced this — see HarnessSource.

Inherited from​

HarnessRunEnvelope.source

status​
status: HarnessRunStatus;
Inherited from​

HarnessRunEnvelope.status

url​
url: string | null;

Human-openable URL for the run, when the harness exposes one.

Inherited from​

HarnessRunEnvelope.url

usage​
usage: HarnessRunUsage | null;

Token usage, or null when the harness reported none.


HarnessRunInput​

What a caller hands a harness for one run.

Properties​

attachments?​
attachments?: FileContent[];

The turn's files, in reference form (FileContent whose data is fsd-blob:<id>), in the order attached. The adapter reads their bytes (readHarnessAttachments) and hands them on in its SDK's form; a type the harness doesn't take refuses the run. Absent or empty: a text turn.

prompt​
prompt: string;

The instruction to run.


HarnessRunSpend​

What one harness run has spent, as its harness reports it: at the run's start, on each usage event its vendor sends, and when the run ends, however it ends. Only what the vendor reported: a token count or a cost the vendor never sent is null, never 0 and never an estimate.

Properties​

billing​
billing: HarnessBilling | null;

How the run was paid for, or null when the harness can't tell.

costUsd​
costUsd: number | null;

The cost the vendor reported, in US dollars, or null when it reported none. Never a price-table estimate.

harness​
harness: string;

The harness, by the name a usage record is kept under (claude-code, codex, cursor).

inputTokens​
inputTokens: number | null;

Input tokens the vendor reported, or null when it reported none (a run killed before its usage arrived).

model?​
model?: string | null;

The model the run uses, as the harness knows it: the one its vendor named, else the one the run was started with. null when neither is known (the vendor picked its default and never said which). Absent on a report made before it existed.

outputTokens​
outputTokens: number | null;

Output tokens the vendor reported, or null when it reported none.

runId?​
runId?: string;

The harness's own id for this run. A later report with the same id replaces the earlier one, so a harness reports its running total, never an increment. Absent: the report is one settled run of its own, and the engine names it (a fresh settled_… id) as it counts it, so what a reader reads back, and what a continuation recovers from the log, carries that id.


HarnessRunUsage​

Token usage a harness reported, or null when it reported none.

Properties​

inputTokens​
inputTokens: number;
outputTokens​
outputTokens: number;

HarnessSteerActionOptions​

Options for HarnessSteering.action.

Properties​

onTaken?​
onTaken?: (ctx, turnRequestId, text) => void | Promise<void>;

Called once the running turn took a line, with that turn's request id, so the flow can record it on the turn. Not called for a line the turn refused.

Parameters​
ctx​

HarnessCallbackContext

turnRequestId​

string

text​

string

Returns​

void | Promise<void>


HarnessSteerAnswer​

What became of a line handed to the running turn.

Properties​

live​
readonly live: boolean;

The running turn offered to take a line.

taken​
readonly taken: boolean;

The turn took it. false means nothing was sent: send it as the next turn.


HarnessSteering​

One flow's steering: the hook its harness is handed, and the action that hands a line in.

Properties​

onSteerable​
readonly onSteerable: HarnessSteerHook;

Hand this to the harness block's onSteerable.

Methods​

action()​
action(options?): ActionCore;

The action to declare beside the turn action: input { prompt }, output HarnessSteerAnswer. Allowed beside a running turn, and never the session's auto-resume target, so a client that reloads still reattaches to the turn.

Parameters​
options?​

HarnessSteerActionOptions

Returns​

ActionCore

steer()​
steer(ctx, text): Promise<HarnessSteerAnswer & object>;

Hand text to the turn running in the calling session.

Parameters​
ctx​

HarnessCallbackContext

text​

string

Returns​

Promise<HarnessSteerAnswer & object>

The answer, and the running turn's request id when it offered one.


HarnessToolApprovalRequest​

One tool call a harness asks about, before it runs.

Properties​

input​
input: unknown;

The call's arguments, as the model issued them.

signal?​
signal?: AbortSignal;

The harness's abort signal for this one call, when it has one.

toolName​
toolName: string;

The tool's name as the harness calls it (Bash, Edit, mcp__<server>__<tool>).


HarnessTurnFiles​

A turn's files as a harness hands them on: the ones it reads as files, and the text of the rest.

Properties​

files​
files: HarnessAttachmentBytes[];

The files the harness reads as files, in the order attached.

text​
text: string;

Each other file's text, headed by its name, in the order attached, a blank line apart. "" for none.


HarnessUsageReport​

One window a harness heard about during a run: what a HarnessUsageHook is handed.

A run reports the pool it draws from, not its own share, and only the window its vendor named. The account and the run's start let a host keep one account's windows apart from another's: a run that started before a look found no subscription belongs to the old sign-in.

Properties​

accountId​
accountId: string | null;

The vendor's id for the account the run is signed in as, or null when it named none. Never shown.

harness​
harness: string;

The harness that heard it, by the name a usage record is kept under (claude-code).

observedAt​
observedAt: number;

When the vendor said it, in epoch ms.

runStartedAt​
runStartedAt: number;

When the run started, in epoch ms.

window​
window: HarnessUsageWindow;

HarnessUsageWindow​

One window of a harness's subscription limit, as its vendor reported it: how much of it is used, how close to its limit it is, and when it resets.

A vendor names a window by its length (Codex: 300 minutes, 10 080 minutes), by its own word for it (Claude Code: five_hour), or both. minutes and id carry what was said. usedPercent is 0 to 100; a vendor that sends a fraction has it scaled by 100, and nothing else is derived. A vendor that sends no percent leaves it null, never 0, and says how close the window is through level instead.

Properties​

id​
id: string;

The vendor's id for this window, unique within one reading.

label​
label: string | null;

The vendor's name for the limit this window belongs to, or null when it gave none.

level​
level: HarnessUsageLevel | null;

How close the window is to its limit, as the vendor said: ok (under its warning line), warning (near the limit) or reached. null when the vendor sends a percent and no level (Codex).

minutes​
minutes: number | null;

The window's length in minutes, or null when the vendor didn't say.

resetsAt​
resetsAt: number | null;

When the window resets, in epoch ms, or null when the vendor didn't say.

usedPercent​
usedPercent: number | null;

How much of the window is used, 0 to 100, or null when the vendor sent no percent.


PlanListCollection​

The slice of a collection ref replacePlanList uses. Structural, and deliberately without list/count, which load a lazy collection's whole prefix.

Methods​

delete()​
delete(key): Promise<void>;
Parameters​
key​

string

Returns​

Promise<void>

getOptional()​
getOptional(key): Promise<
| {
state: Record<string, unknown>;
}
| undefined>;
Parameters​
key​

string

Returns​

Promise< | { state: Record<string, unknown>; } | undefined>

upsert()​
upsert(key, update): Promise<unknown>;
Parameters​
key​

string

update​

Record<string, unknown>

Returns​

Promise<unknown>


PlanListItem​

One item of a whole-list plan, as the harness reported it.

Properties​

status​
status: string | null;

The harness's own status word for it.

title​
title: string | null;

The item's wording.


PlanMarkerRead​

A plan list marker as a collection read lists it, topic under its collection.

Properties​

conversation?​
readonly conversation?: string | null;
topic​
readonly topic: string;

PullRequestCollection​

The slice of a collection ref writePullRequests uses. No list: it loads the whole prefix.

Methods​

getOptional()​
getOptional(key): Promise<
| {
state: Record<string, unknown>;
}
| undefined>;
Parameters​
key​

string

Returns​

Promise< | { state: Record<string, unknown>; } | undefined>

upsert()​
upsert(key, update): Promise<unknown>;
Parameters​
key​

string

update​

Record<string, unknown>

Returns​

Promise<unknown>


PullRequestFollower()​

What a host hands a coding session to act on each pull request it records for the first time, in the request that records it (workforce's followPullRequest, which subscribes the session to the pull request). Run as the session's own user, in the writer's request; what it throws is a status note, never a failed run. resources are the collections it writes, declared beside the session's own so the request carries them.

PullRequestFollower(
ctx,
pr,
run?
): void | Promise<void>;

What a host hands a coding session to act on each pull request it records for the first time, in the request that records it (workforce's followPullRequest, which subscribes the session to the pull request). Run as the session's own user, in the writer's request; what it throws is a status note, never a failed run. resources are the collections it writes, declared beside the session's own so the request carries them.

Parameters​

ctx​

BlockContext

pr​

RecordedPullRequest

run?​

FollowingRun

Returns​

void | Promise<void>

Properties​

resources?​
readonly resources?: Readonly<Record<string, DeclaredResourceEntry>>;

PullRequestRecorderContext​

What the recorder reads off a block's context: the request's id and item stream, the flow's resources, and the status emitter. Any block's context is one.

Properties​

emit?​
readonly emit?: object;
status()?​
status?(message, options?): unknown;
Parameters​
message​

string

options?​
transient?​

boolean

Returns​

unknown

request​
readonly request: object;
identity​
readonly identity: object;
identity.id​
readonly id: string;
resources?​
readonly resources?: unknown;
response​
readonly response: ResponseEmitterHandle;

PullRequestRef​

A pull request a rule or a check found.

Extended by​

Properties​

branch?​
readonly branch?: string | null;
host​
readonly host: string;

The forge's host (github.com).

name​
readonly name: string;

The repository's name.

number​
readonly number: number;
owner​
readonly owner: string;

The repository's owner.

state?​
readonly state?: string | null;
title?​
readonly title?: string | null;
url​
readonly url: string;

The pull request's web link.


PullRequestRule​

A forge's rule: the pull requests one settled tool call opened, or [].

Properties​

name​
readonly name: string;

For status notes.

Methods​

match()​
match(call): PullRequestRef[];
Parameters​
call​

PullRequestToolCall

Returns​

PullRequestRef[]


PullRequestToolCall​

The parts of a tool call a rule reads: the tool's name, its arguments (a JSON string or a value), and its output (any shape).

Properties​

arguments​
readonly arguments: unknown;
name​
readonly name: string;
output​
readonly output: unknown;

RecordedPullRequest​

A pull request a writer recorded for the first time: the ref, and its entry's key.

Extends​

Properties​

branch?​
readonly branch?: string | null;
Inherited from​

PullRequestRef.branch

host​
readonly host: string;

The forge's host (github.com).

Inherited from​

PullRequestRef.host

key​
readonly key: string;

The entry's key: pullRequestKey.

name​
readonly name: string;

The repository's name.

Inherited from​

PullRequestRef.name

number​
readonly number: number;
Inherited from​

PullRequestRef.number

owner​
readonly owner: string;

The repository's owner.

Inherited from​

PullRequestRef.owner

state?​
readonly state?: string | null;
Inherited from​

PullRequestRef.state

title?​
readonly title?: string | null;
Inherited from​

PullRequestRef.title

url​
readonly url: string;

The pull request's web link.

Inherited from​

PullRequestRef.url


RecordPullRequestsOptions​

Options for recordPullRequests and pullRequestRecorder.

Properties​

rules?​
readonly rules?: readonly PullRequestRule[];

The rules that read a create call. GitHub's by default. Only the request's first recorder's rules apply.


WritePullRequestsOptions​

What a writer says about the refs it writes.

Properties​

now?​
readonly now?: () => number;
Returns​

number

onRecorded?​
readonly onRecorded?: PullRequestRecordedCallback;

Called once for each key this write records for the first time, after its entry is written, and never for an entry that was already there. Awaited, in order; what it throws, the write throws (after the entry landed).

requestId?​
readonly requestId?: string | null;

The request that opened them, when the writer knows it.

source​
readonly source: PullRequestSource;

How they were found.

Type Aliases​

HarnessActivity​

type HarnessActivity =
| {
kind: "message";
text: string;
}
| {
arguments: string;
kind: "tool";
name: string;
}
| {
kind: "thinking";
};

One thing a run did, as a HarnessActivityHook is handed it: a completed assistant message, a tool call it started, or a whole block of reasoning (thinking), in the shapes a harness's translator already produces. Thinking carries no text: a host says only that the run is thinking, never what the model reasoned.


HarnessActivityHook​

type HarnessActivityHook = (activity, ctx) => void;

Called by a harness with each HarnessActivity of its run, so the host can say how the run is doing (harness-manager keeps the task's status note from it). Not awaited, and a throw or a rejection never fails the run: like usage, it is a reading, not part of the work. A harness that reports none never calls it.

Parameters​

activity​

HarnessActivity

ctx​

HarnessCallbackContext

Returns​

void


HarnessBilling​

type HarnessBilling = "api-key" | "subscription";

How a harness run was paid for, as the harness knows it from its own sign-in: api-key, billed per token; subscription, drawn from a plan's windows. null when the harness can't tell.


HarnessBlock​

type HarnessBlock = BlockDefinition<any, any, HarnessRunInput, HarnessRunHandle> & object;

A block that conforms to the harness contract.

Deliberately typed over the input and output types, not their schemas: a real harness returns the neutral handle plus its own extension, and the schema-typed spelling rejects every one of them. This is the same shape TaskWorker uses, and for the same reason.

An alias over any, any proves less than it looks like it does. The real conformance proof is a runtime one — the handle a harness returns parsing against harnessRunHandleSchema; asserting assignability here is the cheap half. This is a type, not an installation point: nothing in the framework asks for a HarnessBlock slot.

Type Declaration​

accepts?​
readonly accepts?: AttachmentAccepts;

The file types the harness takes on HarnessRunInput's attachments. A host checks a turn's files against it before the turn starts (refuseUnacceptedAttachments), and the adapter again before its run. Absent means it takes no files. Stamped on the block the factory returns, as stopsOnAbort is.

stopsOnAbort?​
readonly stopsOnAbort?: boolean;

The harness's own word that when its abort signal fires, the block returns only after its process has exited, so a host may stop a run and start the next one in the same working directory. A host that drives harnesses, such as harness-manager, reads it unless it was told otherwise. Absent means no. Stamped on the block the harness factory returns, so a block rebuilt from it (connectInput, a wrapping sequencer) doesn't carry it.


HarnessCallbackContext​

type HarnessCallbackContext = BlockContext<Record<string, unknown>, any, Record<string, unknown>, Record<string, unknown>, Record<string, AnyResourceRef>, Record<string, unknown>, unknown, any, any>;

The block context a harness feed is handed — loose in three slots and checked in every other one.

A feed's body is ordinary code a host writes against a context, so the context is the only thing keeping it honest. Declaring the whole thing any makes every read off it any too: ctx.user.state.typo.deeper type-checks as whatever the reader asked for, and so does a scope-state field nobody ever declared. That is not a small loss, because the one caller these exist for — a manager resolving a checkout path and a session id per attempt — reads exactly those slots.

The three that stay open are the three a HARNESS's own configuration decides, so pinning them would break a feed because of an option set beside it:

  • session state, present or absent depending on whether the harness runs detached;
  • targets and capability namespaces, both derived from the harness block's uses.

Everything else takes its default, so scope state reads unknown and has to be narrowed deliberately. Contravariance is what makes the rest safe to pin: a harness calls a feed with its OWN, narrower context, and the three open slots are precisely the ones a harness narrows.

This is the same reasoning @flow-state-dev/claude-code already reached for its own option callbacks; the two are one alias now rather than two copies that have to stay identical for a harness to be able to call a feed at all.


HarnessCostBasis​

type HarnessCostBasis = "reported" | "estimated";

Whether a cost came from the harness or from us.

"reported" — the harness gave the number. "estimated" — we derived it, because the harness reports no cost at all. Carried so a report can never show a precision the harness never gave.


HarnessEventHook​

type HarnessEventHook = (ctx) => void;

Called by a harness on every event its run sends, of any kind: output, a message delta, a tool call starting or its result. It carries nothing but the fact that the run is still sending, so a host can tell a run that is working from one that has gone silent (harness-manager stops a run that has sent nothing for its idle window). Not awaited, and a throw never fails the run. A harness that never calls it looks silent to such a host.

Parameters​

ctx​

HarnessCallbackContext

Returns​

void


HarnessFailureKind​

type HarnessFailureKind = "unknown-conversation";

Why a harness run failed, in framework vocabulary, for the failures a host has to tell apart. One kind today:

  • "unknown-conversation": the harness was asked to continue a conversation (resume) and reported that it does not know it.

Carried on the error a harness block fails with, as its harnessFailure field, never on the handle: a refused continuation ends the run before there is a handle to return. Each harness package sets it for its own vendor's failure, so a host reads the classification and never a vendor's message. A failure a harness has not classified reads as null, which a host treats as an ordinary error.


HarnessModelList​

type HarnessModelList<M> =
| {
models: M[];
status: "models";
}
| {
reason: string;
status: "failed";
};

What a harness's model-list function found (listClaudeCodeModels, listCodexModels, listCursorModels). The function asks with no run and never throws: a list it can't read is failed with the reason. M is the harness's own extension of a model, where it has one (Cursor's variants).

Type Parameters​

M​

M extends HarnessModelInfo = HarnessModelInfo

Union Members​

Type Literal​
{
models: M[];
status: "models";
}

The harness's models, its default first when it marks one.


Type Literal​
{
reason: string;
status: "failed";
}

No list: the SDK or program missing, an error, no answer in time, or an empty list. reason is for a person.


HarnessReadiness​

type HarnessReadiness =
| {
ready: true;
}
| {
ready: false;
reason: string;
remedy?: string;
unanswered?: true;
};

Whether a harness can run on this machine, as one check found it.

ready: false carries reason, what is wrong, and remedy, what the user does about it, as two sentences so a chip can show the remedy alone. unanswered is set when the check got no answer (it timed out, was stopped, or could not start), so nothing is known either way; such a row usually has no remedy, since there is nothing to fix yet.


HarnessReadinessCheck​

type HarnessReadinessCheck = (options?) => Promise<HarnessReadiness>;

Check, with no run, whether a harness can run on this machine: its SDK, its sign-in or key. A host hands one per harness to whatever keeps the answer. A check never throws for an expected state; it returns it with its reason. signal aborts a check the caller stopped waiting for: a check that starts a process ends it then, or the process outlives the caller's timeout.

Parameters​

options?​
signal?​

AbortSignal

Returns​

Promise<HarnessReadiness>


HarnessResolver​

type HarnessResolver<T> = (ctx) => T | Promise<T>;

How a host feeds a harness one piece of per-run configuration.

The working directory a run writes in, and the session it resumes, arrive this way rather than on HarnessRunInput — the input schema is model-facing through a block's capability tool preset, so a field there is a field a model could set. A resolver's answer is trusted.

It is handed the context and NOTHING ELSE, and that is the guarantee rather than a convenience. An earlier shape passed the run's input alongside the context, which quietly undid the whole argument above: the prompt is the one value a caller — or a tool-using model holding the block — controls, and a resolver that can see it can be written, in ordinary-looking code, to pick the directory a run writes in or the conversation it continues from what the caller sent. That is the trust defect the resolver exists to prevent, reintroduced through the resolver.

Documentation could not close it. A guarantee a caller violates by writing plain code is not a guarantee, so the parameter is gone: a host cannot derive a session id from the prompt because it does not have the prompt. Everything a resolver legitimately needs — who this run belongs to, which attempt it is, where its state lives — is a fact about the RUN and reaches it through ctx.

Declared here, with the contract, because a harness package and a manager package both name this signature and land independently.

A manager's own state is not reachable from the type, deliberately: the harness block carries the framework's default sequencer state, so a resolver that reads the manager's shape casts to it. The manager owns that shape and the harness never learns it, which is the whole point of the channel — the cast is the honest spelling of that split rather than a hole in it.

Type Parameters​

T​

T

Parameters​

ctx​

HarnessCallbackContext

Returns​

T | Promise<T>


HarnessRunOutcome​

type HarnessRunOutcome = "finished" | "stopped-at-limit" | "failed";

How a run ended, in framework vocabulary — null until known.

Three ways and no more: it finished, it was stopped by a limit (turns, budget, time), or it failed. A vendor's own richer reason stays on the vendor's extension, so no framework code ever branches on a vendor string.


HarnessRunStatus​

type HarnessRunStatus = "dispatched" | "running" | "completed" | "errored";

Lifecycle status of a run.

A fire-and-forget door only ever reports "dispatched"; a harness that observes its run reaches "completed" or "errored".


HarnessSessionHook​

type HarnessSessionHook = (sessionId, ctx) => void | Promise<void>;

Called by a harness the moment its vendor names a session, so the host can persist the id it will later resume through a HarnessResolver.

Fires during the run, not after it: a run that dies mid-flight has still named its session, and a host that only learned the id from the returned handle would have nothing to resume.

Parameters​

sessionId​

string

ctx​

HarnessCallbackContext

Returns​

void | Promise<void>


HarnessSource​

type HarnessSource = string;

Which harness, and which of its doors, produced a handle.

A plain string so a harness we do not ship can name itself — but every writer of the field owes the <package>/<door> convention (claude-code/sdk, codex/sdk). The rule, not the type, is what keeps the values comparable when something later checks that a run came from the harness it dispatched. Nothing branches on the value today.


HarnessSteer​

type HarnessSteer = (text) => Promise<"delivered" | "refused">;

Hands one line to a run's turn in flight. Resolves "delivered" only when the turn has the words; anything less (the run refused, the turn ended, the call threw) is "refused", and the caller sends the line some other way.

It never rejects. It waits for the vendor's own answer rather than a timer: a timeout cannot tell a refusal from a delivery, and guessing would send the line twice.

Parameters​

text​

string

Returns​

Promise<"delivered" | "refused">


HarnessSteerHook​

type HarnessSteerHook = (steer, ctx) => void;

Called by a harness while its run can take a line in flight, with the HarnessSteer that does it, and again with null once it no longer can, before the block returns, on every exit.

A fact about one run, not about the harness: a harness that can steer still has runs that can't (a cloud run, a turn not yet started). A harness that never steers simply never calls it. The twin of HarnessSessionHook.

Parameters​

steer​

HarnessSteer | null

ctx​

HarnessCallbackContext

Returns​

void


HarnessToolApprovalDecision​

type HarnessToolApprovalDecision =
| {
decision: "allow";
updatedInput?: unknown;
}
| {
decision: "deny";
message?: string;
}
| {
decision: "held";
message?: string;
};

What the onToolApproval feed answers for one call.

  • allow: the call runs (with updatedInput, when given).
  • deny: it doesn't, the model is told with message, and the turn goes on.
  • held: it doesn't run now, and the turn stops: a person decides it outside this run, and the session resumes with the answer.

HarnessToolApprovalHook​

type HarnessToolApprovalHook = (request, ctx) =>
| HarnessToolApprovalDecision
| Promise<HarnessToolApprovalDecision>;

The onToolApproval feed: called by a harness that can ask about each tool call before it runs (Claude Code). A harness that can't ignores it.

Parameters​

request​

HarnessToolApprovalRequest

ctx​

HarnessCallbackContext

Returns​

| HarnessToolApprovalDecision | Promise<HarnessToolApprovalDecision>


HarnessUsageHook​

type HarnessUsageHook = (report, ctx) => void | Promise<void>;

Called by a harness when its vendor reports a usage window during a run, so the host can record it. The twin of HarnessSessionHook.

A harness awaits it, so a write can't land after the run ends, but a throw never fails the run: usage is a reading, not part of the work.

Parameters​

report​

HarnessUsageReport

ctx​

HarnessCallbackContext

Returns​

void | Promise<void>


HarnessUsageLevel​

type HarnessUsageLevel = "ok" | "warning" | "reached";

How close a HarnessUsageWindow is to its limit.


HarnessUsageReader​

type HarnessUsageReader = (options?) => Promise<HarnessUsageReading>;

Read one harness's subscription usage on demand, with no run.

A host hands one per harness to whatever holds the usage record, which calls it when someone asks for a fresh number. A reader never throws for an expected no-number state; it returns that state with its reason. signal aborts a read the caller stopped waiting for.

Parameters​

options?​
signal?​

AbortSignal

Returns​

Promise<HarnessUsageReading>


HarnessUsageReading​

type HarnessUsageReading =
| {
accountId: string | null;
plan: string | null;
status: "windows";
windows: HarnessUsageWindow[];
}
| {
reason: string;
status: "api-key";
}
| {
reason: string;
status: "signed-out";
}
| {
reason: string;
status: "unavailable";
};

What one read of a harness's subscription usage found.

Only windows carries a number. The other three say why there is none, in words a person can be shown: the harness runs on an API key (no subscription limit), nobody is signed in, or the read could not be made. None of them is ever read as zero.

Union Members​

Type Literal​
{
accountId: string | null;
plan: string | null;
status: "windows";
windows: HarnessUsageWindow[];
}
accountId​
accountId: string | null;

The vendor's account id, when it named one. Never shown; a store keeps a hash of it.

plan​
plan: string | null;

The subscription plan, as the vendor names it, or null.

status​
status: "windows";
windows​
windows: HarnessUsageWindow[];

Type Literal​
{
reason: string;
status: "api-key";
}

Type Literal​
{
reason: string;
status: "signed-out";
}

Type Literal​
{
reason: string;
status: "unavailable";
}

ObservedOutcome​

type ObservedOutcome = "pending" | "applied" | "failed";

How a recorded mutation settled.

Three-valued, not a boolean: a mutation is recorded when its call is seen and settled when its result arrives, so pending is a real state; and an update the harness rejects is recorded as failed with the statuses left where the harness has them.


ObservedPlanListStatus​

type ObservedPlanListStatus = "writing" | "complete" | "incomplete";

Where a run's plan write stands.

  • writing — a write has started and not finished. Read once the run has ended, it means the write never finished, the same as incomplete.
  • complete — the rows are the plan. With count: 0, the agent reported an empty list.
  • incomplete — a write failed partway. The rows are what landed, not the plan, and reason says why.

ObservedPullRequestState​

type ObservedPullRequestState = z.infer<typeof observedPullRequestStateSchema>;

One row of observedPullRequestsCollection.


PlanListMarkerCollection​

type PlanListMarkerCollection = Pick<PlanListCollection, "getOptional" | "upsert">;

The slice of the marker collection ref replacePlanList uses.


type PullRequestLink = Omit<PullRequestRef, "title" | "state" | "branch">;

A link found in text, as a ref with no title, state or branch.


PullRequestRecordedCallback​

type PullRequestRecordedCallback = (pr) => void | Promise<void>;

Called once per pull request a write records for the first time.

Parameters​

pr​

RecordedPullRequest

Returns​

void | Promise<void>


PullRequestSource​

type PullRequestSource = "tool" | "branch";

How a row was found.

  • tool — a create call in the session's tool calls named it.
  • branch — a host's turn-end check found it on the session's branch.

A tool sighting upgrades a branch row, so a branch check that wins the race does not hide the turn that opened it.


ReplacePlanListResult​

type ReplacePlanListResult =
| {
status: "complete";
}
| {
reason: string;
status: "incomplete";
};

How a replacePlanList call ended.

Variables​

DEFAULT_PULL_REQUEST_RULES​

const DEFAULT_PULL_REQUEST_RULES: readonly PullRequestRule[];

The default rules: GitHub's.


githubPullRequestRule​

const githubPullRequestRule: PullRequestRule;

GitHub's rule, for github.com and GitHub Enterprise hosts.

A call is a create call when its command runs gh pr create (or gh pr new), or when the tool is a create-pull-request tool (GitHub's MCP create_pull_request, under any harness's prefix). The pull requests are read from the call's OUTPUT, never from the arguments, so a link the agent only typed is not a pull request it opened. A gh pr view, gh pr list or search names links and is not a create call.

  • create_pull_request opens one pull request: the result's own html_url (else url). Its result also holds the new pull request's body, and a link the body names is not opened. A result with no such field (plain text, an error) gives its first link.
  • gh pr create prints only the link it opened, so a command whose only link-printing gh verb is a create records every link in its output (a loop of creates opens several). A command that also runs gh pr view, gh api or another verb that prints links records none: the output can't be split by command, and a wrong row is never corrected. The turn-end check of the session's branch finds a pull request missed this way.

A create that fails because the branch already has a pull request still names it ("already exists: <link>"), and it counts: the session's branch has it. The title and branch come from the create call's own flags or fields when it set them.


HARNESS_BASE_PASS​

const HARNESS_BASE_PASS: readonly ["PATH", "HOME", "USER", "SHELL", "TMPDIR", "HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy", "NO_PROXY", "no_proxy"];

The variables every harness's child process needs, whatever the vendor: the shell's own (PATH, HOME, USER, SHELL, TMPDIR) and the proxy settings a proxied network needs, in upper and lower case, since the tools a run shells out to disagree on which they read. No credential: each harness package's pass-list is this base plus its own keys and certificates, and a host adds its own after it:

env: harnessEnv({ pass: [...HARNESS_BASE_PASS, "MY_KEY"] }),

harnessRunEnvelopeSchema​

const harnessRunEnvelopeSchema: z.ZodObject<{
dispatchedAt: z.ZodNumber;
sessionId: z.ZodNullable<z.ZodString>;
source: z.ZodString;
status: z.ZodEnum<["dispatched", "running", "completed", "errored"]>;
url: z.ZodNullable<z.ZodString>;
}, "strip", z.ZodTypeAny, {
dispatchedAt: number;
sessionId: string | null;
source: string;
status: "completed" | "dispatched" | "errored" | "running";
url: string | null;
}, {
dispatchedAt: number;
sessionId: string | null;
source: string;
status: "completed" | "dispatched" | "errored" | "running";
url: string | null;
}>;

Runtime validator for HarnessRunEnvelope.


harnessRunHandleSchema​

const harnessRunHandleSchema: z.ZodObject<object & object, "strip", z.ZodTypeAny, {
cost: | {
basis: "estimated" | "reported";
usd: number;
}
| null;
dispatchedAt: number;
finalMessage: string | null;
outcome: "failed" | "finished" | "stopped-at-limit" | null;
sessionId: string | null;
source: string;
status: "completed" | "dispatched" | "errored" | "running";
url: string | null;
usage: | {
inputTokens: number;
outputTokens: number;
}
| null;
}, {
cost?: | {
basis: "estimated" | "reported";
usd: number;
}
| null;
dispatchedAt: number;
finalMessage?: string | null;
outcome?: "failed" | "finished" | "stopped-at-limit" | null;
sessionId: string | null;
source: string;
status: "completed" | "dispatched" | "errored" | "running";
url: string | null;
usage?: | {
inputTokens: number;
outputTokens: number;
}
| null;
}>;

Runtime validator for HarnessRunHandle.

The four post-envelope fields default to null so a handle persisted before a harness reported them still parses. The declared shape carries no vendor field; a harness's extended handle still parses against it, because the contract's job is to say what any reader may rely on — not to reject what a vendor added beside it.


harnessRunInputSchema​

const harnessRunInputSchema: z.ZodObject<{
attachments: z.ZodOptional<z.ZodArray<z.ZodObject<{
data: z.ZodEffects<z.ZodString, string, string>;
filename: z.ZodOptional<z.ZodString>;
mediaType: z.ZodString;
type: z.ZodLiteral<"file">;
}, "strip", z.ZodTypeAny, {
data: string;
filename?: string;
mediaType: string;
type: "file";
}, {
data: string;
filename?: string;
mediaType: string;
type: "file";
}>, "many">>;
prompt: z.ZodString;
}, "strip", z.ZodTypeAny, {
attachments?: object[];
prompt: string;
}, {
attachments?: object[];
prompt: string;
}>;

Runtime validator for HarnessRunInput.

Strips unknown keys rather than rejecting them, deliberately: a smuggled field (resumeSessionId, a cwd) is dropped instead of honoured, which is all a trusted source needs here — resume and working directory reach a harness through the caller-fed HarnessResolver, never through block input. .strict() would fail louder, at the cost of breaking callers that pass framework metadata through the same object.


harnessSchema​

const harnessSchema: z.ZodType<Harness, z.ZodTypeDef, unknown>;

What a harnesses slot checks each entry against.


harnessUsageWindowSchema​

const harnessUsageWindowSchema: z.ZodObject<{
id: z.ZodString;
label: z.ZodDefault<z.ZodNullable<z.ZodString>>;
level: z.ZodDefault<z.ZodNullable<z.ZodEnum<["ok", "warning", "reached"]>>>;
minutes: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
resetsAt: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
usedPercent: z.ZodNullable<z.ZodNumber>;
}, "strip", z.ZodTypeAny, {
id: string;
label: string | null;
level: "ok" | "reached" | "warning" | null;
minutes: number | null;
resetsAt: number | null;
usedPercent: number | null;
}, {
id: string;
label?: string | null;
level?: "ok" | "reached" | "warning" | null;
minutes?: number | null;
resetsAt?: number | null;
usedPercent: number | null;
}>;

Runtime validator for HarnessUsageWindow. level defaults to null, so a window stored before it existed still parses.


OBSERVED_PLAN​

const OBSERVED_PLAN: "observed-plan";

Accessor key AND storage prefix for the run's plan rows.


OBSERVED_PLAN_LIST​

const OBSERVED_PLAN_LIST: "observed-plan-list";

Accessor key AND storage prefix for the per-run plan list markers.


OBSERVED_PULL_REQUESTS​

const OBSERVED_PULL_REQUESTS: "observed-pull-requests";

Accessor key AND storage prefix for the pull-request rows.


observedOutcomeSchema​

const observedOutcomeSchema: z.ZodEnum<["pending", "applied", "failed"]>;

Runtime validator for ObservedOutcome.


observedPlanCollection​

const observedPlanCollection: object & ResourceCollectionConfig & object;

The run's plan rows.

**, not *: a key carries a multi-segment run namespace and then the item. prefetchMode: "lazy" because rows are namespaced per run and a session is reused across runs, so an eager collection would load every earlier run's rows before this one wrote a key. A writer only upserts and deletes by exact key; list()/count() would load the whole prefix, so writers never call them. live streams each change to an open page as it happens, rather than at the end of the request.

Type Declaration​

client​
readonly client: object;
client.expose​
readonly expose: readonly ["title", "status", "previousStatus", "lastOutcome", "lastTouchedAt", "requestId"];
client.live​
readonly live: true;
client.state​
readonly state: object;
client.state.read​
readonly read: true;
pattern​
readonly pattern: "observed-plan/**";
prefetchMode​
readonly prefetchMode: "lazy";
scope​
readonly scope: "session";
stateSchema​
readonly stateSchema: z.ZodObject<{
lastOutcome: z.ZodDefault<z.ZodNullable<z.ZodEnum<["pending", "applied", "failed"]>>>;
lastTouchedAt: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
previousStatus: z.ZodDefault<z.ZodNullable<z.ZodString>>;
requestId: z.ZodDefault<z.ZodNullable<z.ZodString>>;
status: z.ZodDefault<z.ZodNullable<z.ZodString>>;
title: z.ZodDefault<z.ZodNullable<z.ZodString>>;
}, "strip", z.ZodTypeAny, {
lastOutcome: "applied" | "failed" | "pending" | null;
lastTouchedAt: number | null;
previousStatus: string | null;
requestId: string | null;
status: string | null;
title: string | null;
}, {
lastOutcome?: "applied" | "failed" | "pending" | null;
lastTouchedAt?: number | null;
previousStatus?: string | null;
requestId?: string | null;
status?: string | null;
title?: string | null;
}>;
__brand​
readonly __brand: "ResourceCollection";
ClientType​
ClientType: Pick<{
lastOutcome: "applied" | "failed" | "pending" | null;
lastTouchedAt: number | null;
previousStatus: string | null;
requestId: string | null;
status: string | null;
title: string | null;
},
| "lastOutcome"
| "lastTouchedAt"
| "previousStatus"
| "requestId"
| "status"
| "title">;
StateType​
StateType: object;
StateType.lastOutcome​
lastOutcome: "applied" | "failed" | "pending" | null;
StateType.lastTouchedAt​
lastTouchedAt: number | null;
StateType.previousStatus​
previousStatus: string | null;
StateType.requestId​
requestId: string | null;
StateType.status​
status: string | null;
StateType.title​
title: string | null;

observedPlanItemStateSchema​

const observedPlanItemStateSchema: z.ZodObject<{
lastOutcome: z.ZodDefault<z.ZodNullable<z.ZodEnum<["pending", "applied", "failed"]>>>;
lastTouchedAt: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
previousStatus: z.ZodDefault<z.ZodNullable<z.ZodString>>;
requestId: z.ZodDefault<z.ZodNullable<z.ZodString>>;
status: z.ZodDefault<z.ZodNullable<z.ZodString>>;
title: z.ZodDefault<z.ZodNullable<z.ZodString>>;
}, "strip", z.ZodTypeAny, {
lastOutcome: "applied" | "failed" | "pending" | null;
lastTouchedAt: number | null;
previousStatus: string | null;
requestId: string | null;
status: string | null;
title: string | null;
}, {
lastOutcome?: "applied" | "failed" | "pending" | null;
lastTouchedAt?: number | null;
previousStatus?: string | null;
requestId?: string | null;
status?: string | null;
title?: string | null;
}>;

One plan row, keyed <run namespace>/<item>: the harness's own item id, or the item's place in the list when the harness reports none (see replacePlanList).

status and previousStatus are free strings, not an enum: the vocabulary belongs to the harness, and a value we have never seen records as itself rather than throwing. status stays null until the harness reports one. Every field is nullable with a null default so a row written by an older or newer shape still parses.


observedPlanListCollection​

const observedPlanListCollection: object & ResourceCollectionConfig & object;

The per-run plan list markers. Same storage notes as observedPlanCollection.

Type Declaration​

client​
readonly client: object;
client.expose​
readonly expose: readonly ["status", "count", "reason", "conversation"];
client.live​
readonly live: true;
client.state​
readonly state: object;
client.state.read​
readonly read: true;
pattern​
readonly pattern: "observed-plan-list/**";
prefetchMode​
readonly prefetchMode: "lazy";
scope​
readonly scope: "session";
stateSchema​
readonly stateSchema: z.ZodObject<{
conversation: z.ZodDefault<z.ZodNullable<z.ZodString>>;
count: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
reason: z.ZodDefault<z.ZodNullable<z.ZodString>>;
status: z.ZodDefault<z.ZodNullable<z.ZodEnum<["writing", "complete", "incomplete"]>>>;
}, "strip", z.ZodTypeAny, {
conversation: string | null;
count: number | null;
reason: string | null;
status: "complete" | "incomplete" | "writing" | null;
}, {
conversation?: string | null;
count?: number | null;
reason?: string | null;
status?: "complete" | "incomplete" | "writing" | null;
}>;
__brand​
readonly __brand: "ResourceCollection";
ClientType​
ClientType: Pick<{
conversation: string | null;
count: number | null;
reason: string | null;
status: "complete" | "incomplete" | "writing" | null;
}, "conversation" | "count" | "reason" | "status">;
StateType​
StateType: object;
StateType.conversation​
conversation: string | null;
StateType.count​
count: number | null;
StateType.reason​
reason: string | null;
StateType.status​
status: "complete" | "incomplete" | "writing" | null;

observedPlanListStateSchema​

const observedPlanListStateSchema: z.ZodObject<{
conversation: z.ZodDefault<z.ZodNullable<z.ZodString>>;
count: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
reason: z.ZodDefault<z.ZodNullable<z.ZodString>>;
status: z.ZodDefault<z.ZodNullable<z.ZodEnum<["writing", "complete", "incomplete"]>>>;
}, "strip", z.ZodTypeAny, {
conversation: string | null;
count: number | null;
reason: string | null;
status: "complete" | "incomplete" | "writing" | null;
}, {
conversation?: string | null;
count?: number | null;
reason?: string | null;
status?: "complete" | "incomplete" | "writing" | null;
}>;

One marker per namespace, keyed by the namespace itself. Every field is nullable: a harness that writes rows by id (Claude Code) writes only incomplete markers, with no count.

A marker plays one of two parts. Under a conversation namespace it says where that conversation's plan write stands (status, count, reason). Under a run namespace it carries conversation, the pointer from one run to the conversation it worked in, which is how a reader that knows only the run finds the plan.


observedPullRequestsCollection​

const observedPullRequestsCollection: object & ResourceCollectionConfig & object;

The session's pull-request rows.

Lazy for the reason the plan record is: a session is reused across runs, and an eager collection loads every row before a writer touches one key. A writer reads and upserts by exact key and never lists. live streams each row to an open page as it is written, mid-turn. The client reads; nothing the client sends writes.

Type Declaration​

client​
readonly client: object;
client.expose​
readonly expose: readonly ["host", "repository", "number", "url", "title", "state", "branch", "requestId", "source", "firstSeenAt"];
client.live​
readonly live: true;
client.state​
readonly state: object;
client.state.read​
readonly read: true;
indexes​
readonly indexes: object;
indexes.requestId​
requestId: (_key, state) => string | undefined;
Parameters​
_key​

string

state​
requestId?​

unknown

Returns​

string | undefined

pattern​
readonly pattern: "observed-pull-requests/**";
prefetchMode​
readonly prefetchMode: "lazy";
scope​
readonly scope: "session";
stateSchema​
readonly stateSchema: z.ZodObject<{
branch: z.ZodDefault<z.ZodNullable<z.ZodString>>;
firstSeenAt: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
host: z.ZodDefault<z.ZodNullable<z.ZodString>>;
number: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
repository: z.ZodDefault<z.ZodNullable<z.ZodString>>;
requestId: z.ZodDefault<z.ZodNullable<z.ZodString>>;
source: z.ZodDefault<z.ZodNullable<z.ZodEnum<["tool", "branch"]>>>;
state: z.ZodDefault<z.ZodNullable<z.ZodString>>;
title: z.ZodDefault<z.ZodNullable<z.ZodString>>;
url: z.ZodDefault<z.ZodNullable<z.ZodString>>;
}, "strip", z.ZodTypeAny, {
branch: string | null;
firstSeenAt: number | null;
host: string | null;
number: number | null;
repository: string | null;
requestId: string | null;
source: "branch" | "tool" | null;
state: string | null;
title: string | null;
url: string | null;
}, {
branch?: string | null;
firstSeenAt?: number | null;
host?: string | null;
number?: number | null;
repository?: string | null;
requestId?: string | null;
source?: "branch" | "tool" | null;
state?: string | null;
title?: string | null;
url?: string | null;
}>;
__brand​
readonly __brand: "ResourceCollection";
ClientType​
ClientType: Pick<{
branch: string | null;
firstSeenAt: number | null;
host: string | null;
number: number | null;
repository: string | null;
requestId: string | null;
source: "branch" | "tool" | null;
state: string | null;
title: string | null;
url: string | null;
},
| "branch"
| "firstSeenAt"
| "host"
| "number"
| "repository"
| "requestId"
| "source"
| "state"
| "title"
| "url">;
StateType​
StateType: object;
StateType.branch​
branch: string | null;
StateType.firstSeenAt​
firstSeenAt: number | null;
StateType.host​
host: string | null;
StateType.number​
number: number | null;
StateType.repository​
repository: string | null;
StateType.requestId​
requestId: string | null;
StateType.source​
source: "branch" | "tool" | null;
StateType.state​
state: string | null;
StateType.title​
title: string | null;
StateType.url​
url: string | null;

observedPullRequestStateSchema​

const observedPullRequestStateSchema: z.ZodObject<{
branch: z.ZodDefault<z.ZodNullable<z.ZodString>>;
firstSeenAt: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
host: z.ZodDefault<z.ZodNullable<z.ZodString>>;
number: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
repository: z.ZodDefault<z.ZodNullable<z.ZodString>>;
requestId: z.ZodDefault<z.ZodNullable<z.ZodString>>;
source: z.ZodDefault<z.ZodNullable<z.ZodEnum<["tool", "branch"]>>>;
state: z.ZodDefault<z.ZodNullable<z.ZodString>>;
title: z.ZodDefault<z.ZodNullable<z.ZodString>>;
url: z.ZodDefault<z.ZodNullable<z.ZodString>>;
}, "strip", z.ZodTypeAny, {
branch: string | null;
firstSeenAt: number | null;
host: string | null;
number: number | null;
repository: string | null;
requestId: string | null;
source: "branch" | "tool" | null;
state: string | null;
title: string | null;
url: string | null;
}, {
branch?: string | null;
firstSeenAt?: number | null;
host?: string | null;
number?: number | null;
repository?: string | null;
requestId?: string | null;
source?: "branch" | "tool" | null;
state?: string | null;
title?: string | null;
url?: string | null;
}>;

One pull request, keyed by pullRequestKey.

requestId is a read key: a reader narrows a shared session's rows to the request that opened them by it (a task's run, a turn). It is set once and never moved. state is the last state a writer saw (at opening, at the branch check, or at a read of the pull request): each sighting that names one replaces it, so a row reads merged once a read saw the merge. Every field is nullable with a null default, so a row written by an older or newer shape still parses.

Functions​

followRecordedPullRequests()​

function followRecordedPullRequests(
ctx,
follower,
run?
): void;

Hand each pull request this request records for the first time to follower, as ctx's request: once per request, however often it is called. A host calls it before the harness runs (a coding task's step) and before its own writes, so a pull request any writer in the request records reaches it, mid-turn. What the follower throws is a status note, never a failed write. run is handed to the follower with each pull request.

Parameters​

ctx​

BlockContext

follower​

PullRequestFollower | undefined

run?​

FollowingRun

Returns​

void


formatRunDuration()​

function formatRunDuration(ms): string;

Words for a duration in milliseconds, rounded to the nearest second. A duration under half a second, or one that is negative or not a number (a clock that ran backwards), is "less than a second".

Parameters​

ms​

number

The duration in milliseconds.

Returns​

string


harnessActivityOf()​

function harnessActivityOf(event): HarnessActivity | null;

The activity an event is, or null for one that isn't (deltas, results, statuses).

Parameters​

event​

ActivityEvent

Returns​

HarnessActivity | null


harnessConversationNamespace()​

function harnessConversationNamespace(conversationId): string;

The key namespace for ONE harness conversation's plan: conversation/<conversation id>. Every turn of the conversation writes its plan here, so a later turn updates the plan an earlier one recorded instead of starting a new one, and a new conversation starts with none.

The id is the one the harness confirmed (Claude Code's session id, Cursor's agent id): the conversation's identity, where harnessRunNamespace is one invocation's. The plan record is session-scoped and a session binds one harness, so the vendor's id alone keeps two conversations apart.

It can't be read as a run namespace: a run namespace's second segment always ends in #<attempt>, and a conversation id is the harness's own, escaped with planKeySegment into one segment.

Parameters​

conversationId​

string

Returns​

string


harnessEnv()​

function harnessEnv(options): Record<string, string>;

Build a harness child's environment from an allowlist of variable names.

Pass the result as the harness adapter's env option:

claudeCodeAgent({
env: harnessEnv({ pass: ["PATH", "HOME", "ANTHROPIC_API_KEY"] }),
});

The values are read when this is called — when the block is built — so a variable set after that is not seen. Only the source's own string-valued entries count: a name such as toString or constructor is not "set" because every object inherits one.

Parameters​

options​

HarnessEnvOptions

The names to pass, and optionally the source to read them from.

Returns​

Record<string, string>

A new null-prototype object holding exactly the named variables that are set.


harnessFailureKind()​

function harnessFailureKind(error): "unknown-conversation" | null;

The HarnessFailureKind a harness classified an error as, or null.

Follows cause, so the classification still reads after the framework or a host wraps the harness's error. A value that is not a known kind reads as null, so a host's branch on the result stays exhaustive.

catch (err) {
if (harnessFailureKind(err) === "unknown-conversation") showRefused();
else showError(err);
}

Parameters​

error​

unknown

Returns​

"unknown-conversation" | null


harnessRunNamespace()​

function harnessRunNamespace(ctx): string;

The key namespace for ONE harness run: <requestId>/<invocation>. Every harness that writes the plan record (and Claude Code's other work records) keys its rows under it, so one run is one namespace whichever harness ran.

The request id alone is not the run's identity, and using it as one is a silent data-merging bug. A generator holding a harness as a tool can call it several times inside a single request — the framework's own tool executor disambiguates each call by stepNumber:toolCallId precisely because that happens. Every such call is a separate coding run: its own files, its own to-do ids (the harness numbers those per agent session, so two runs both having a task 5 is ordinary), and its own gap ordinals, which restart at 1 per recorder and would therefore overwrite each other outright.

blockPath is the framework's per-invocation identity — derived from the block tree and the model step, so it is unique per call AND stable across a replay, which a minted id would not be. Slashes are flattened so one invocation stays one key segment.

Two segments rather than one, deliberately: the request id stays the leading segment, so topicPrefix=<collection>/<requestId>/ still selects everything one request did, while <collection>/<requestId>/<invocation>/ narrows to a single run. Replacing the request id outright would have made a row impossible to correlate back to the request that caused it.

Both parts are escaped into a single segment each — see planKeySegment for why that escaping must not be lossy.

Parameters​

ctx​

BlockContext

Returns​

string


harnessSteering()​

function harnessSteering(): HarnessSteering;

Create one flow's steering.

const steering = harnessSteering();
const agent = cursorAgent({ cwd, resume, onSession, onSteerable: steering.onSteerable });
defineFlow({
kind: "coder",
actions: {
turn: { block: turn(agent), concurrency: "defer" },
steer: steering.action(),
},
});

Returns​

HarnessSteering


planKeySegment()​

function planKeySegment(value): string;

Escape one value into ONE key segment of the plan record: /, \, control characters, and a segment of exactly .., the four the resource path normalizer rejects or splits on, are percent-escaped, and % first.

The escaping is injective, so two distinct values never share a key: a request id that holds a / keys under %2F rather than splitting into two segments or merging with another request's rows. Every other value is unchanged byte for byte, so a plain request id is its own segment. The one boundary: injectivity holds among values encoded here, not across rows written before ids were escaped, when an id that was literally a%2Fb keyed itself raw, which is what a/b encodes to now.

A writer builds a run's namespace from it (<planKeySegment(requestId)>/<run>); a reader finds a request's rows with planResourcesPrefix, which uses it.

Parameters​

value​

string

Returns​

string


planResourcesPrefix()​

function planResourcesPrefix(requestId, key?): string;

The storage-key prefix every run of one request keeps its rows under, in the plan record (observed-plan) or its list markers (observed-plan-list). Pass it as a collection read's topicPrefix to select what one request planned and nothing an earlier request in the same session did.

Built with planKeySegment, the escaping writers use, so a reader never hand-copies it.

Parameters​

requestId​

string

The request whose rows to select, as the framework names it.

key?​

"observed-plan" | "observed-plan-list"

Which collection: the plan rows (default) or the list markers.

Returns​

string


promptWithTurnText()​

function promptWithTurnText(prompt, turn): string;

The prompt a harness runs: the person's text, then the turn's documents' text after a blank line, when there is any.

Parameters​

prompt​

string

turn​

HarnessTurnFiles

Returns​

string


pullRequestKey()​

function pullRequestKey(ref): string;

A row's key: host, owner, repository and number, one segment each, escaped with planKeySegment. Host, owner and repository are lower-cased, because GitHub reads them case-insensitively, so two spellings of one link land on one row.

Parameters​

ref​

Pick<PullRequestRef, "host" | "owner" | "name" | "number">

Returns​

string


pullRequestRecordedOf()​

function pullRequestRecordedOf(response):
| PullRequestRecordedCallback
| undefined;

The onRecorded a writer in this request passes to writePullRequests: every callback registered with whenPullRequestRecorded, in order. undefined when none is.

Parameters​

response​

unknown

The request's response (ctx.response).

Returns​

| PullRequestRecordedCallback | undefined


pullRequestRecorder()​

function pullRequestRecorder(options?): BlockDefinition<ZodTypeAny, ZodTypeAny, unknown, void>;

A handler block that records this request's pull requests: add it to a flow with no harness as a .tap step. It declares the collection, reads the request's items so far and starts the recorder for the rest. Tapped before the generator, rows appear as each call settles; tapped after, when the step runs.

sequencer({ name: "turn" })
.tap(pullRequestRecorder())
.step(assistant)

Parameters​

options?​

RecordPullRequestsOptions & object

Returns​

BlockDefinition<ZodTypeAny, ZodTypeAny, unknown, void>


pullRequestRefFromUrl()​

function pullRequestRefFromUrl(url): PullRequestLink | null;

A pull request's web link read as a ref (host, owner, name, number and the normalized url), or null when url does not start with one. The one reading of a link every writer keys by, so a link found in a tool's output and the same pull request listed by a host check are one row.

Parameters​

url​

string

Returns​

PullRequestLink | null


pullRequestWritesSettled()​

function pullRequestWritesSettled(response): Promise<void>;

Resolves once every write this request's recorder has started has finished; at once when the request has no recorder. A host writer that runs at the end of a request (the branch check, in a request onFinished hook, which runs before the recorder stops) awaits it first, so it reads the recorder's rows rather than racing them.

Parameters​

response​

unknown

Returns​

Promise<void>


readHarnessAttachments()​

function readHarnessAttachments(ctx, attachments): Promise<HarnessAttachmentBytes[]>;

Each file's bytes, in the order given, read through the engine's one resolver for the conversation ctx runs in. Empty for no files.

Parameters​

ctx​

object

attachments​

readonly FileContent[] | undefined

Returns​

Promise<HarnessAttachmentBytes[]>

Throws​

When a file can't be read: gone, another conversation's, or the context carries no reader (a hand-built test context, a server with no blob store). A store that fails rejects with its own error.


readHarnessTurnFiles()​

function readHarnessTurnFiles(
harness,
ctx,
accepts,
attachments
): Promise<HarnessTurnFiles>;

A turn's files as harness hands them on: refused first, by refuseUnacceptedAttachments, before anything is read; then each read through the engine's one resolver, and split into the files the harness reads (accepts) and the text of every other document.

Parameters​

harness​

string

ctx​

object

accepts​

AttachmentAccepts

attachments​

readonly FileContent[] | undefined

Returns​

Promise<HarnessTurnFiles>

Throws​

Before anything is read.

Throws​

When a file can't be read, or a document's text can't (a reader with no text).


readPlanTarget()​

function readPlanTarget(requestId, markers):
| {
kind: "conversation";
namespace: string;
resourcesPrefix: string;
}
| {
kind: "run";
resourcesPrefix: string;
};

Where to read one request's plan, from that request's run markers (the markers listed under planResourcesPrefix(requestId, OBSERVED_PLAN_LIST)).

  • conversation — a run of the request left a pointer: the plan is the conversation's, its rows under resourcesPrefix and its marker keyed namespace.
  • run — no run left one: the request was recorded before plans were kept per conversation, or it never confirmed a conversation. Its own rows are under resourcesPrefix and its markers are the ones passed in, as before.

With several pointers (a retried block), the last run's wins, by key order. The one reader rule both apps share, so the fallback never forks.

Parameters​

requestId​

string

markers​

readonly PlanMarkerRead[]

Returns​

| { kind: "conversation"; namespace: string; resourcesPrefix: string; } | { kind: "run"; resourcesPrefix: string; }


recordPullRequests()​

function recordPullRequests(ctx, options?): void;

Start this request's pull-request recorder, once. Later calls in the same request are no-ops. It stops when the request ends.

Records nothing, and says so in a status note, when the flow has not declared the OBSERVED_PULL_REQUESTS collection, or when the context has no item subscription or no request-end seam (a hand-built context).

Parameters​

ctx​

PullRequestRecorderContext

options?​

RecordPullRequestsOptions

Returns​

void


refuseUnacceptedAttachments()​

function refuseUnacceptedAttachments(
harness,
accepts,
attachments
): void;

Refuse the turn when a file's type is not one harness takes. A harness that declares no accepts takes no files. Called by each adapter before its run starts, and by a host before it starts the turn (a harness session's flow), so a refusal never costs a checkout or a process.

Parameters​

harness​

string

accepts​

AttachmentAccepts | undefined

attachments​

readonly FileContent[] | undefined

Returns​

void

Throws​

Naming the first file refused.


replacePlanList()​

function replacePlanList(
plan,
marker,
namespace,
items,
options?
): Promise<ReplacePlanListResult>;

Write a plan that arrived as the whole list into the plan record, replacing the run's previous list.

Row n holds the list's nth item (keyed <namespace>/<n, zero-padded>), with lastOutcome: "applied": the helper writes only lists the harness confirmed. Where a place's wording is unchanged and its status changed, the earlier status becomes previousStatus; a repeated status leaves it as it was; a reworded place clears it. Places past the new end are deleted.

Around the rows, the run's marker in observedPlanListCollection goes writing (with the new count) first and complete last. If any write throws, the marker ends incomplete with the error, and the function returns rather than throws: a plan that cannot be stored in full never fails the run.

options.requestId is stamped on every row it writes, so a reader can say which turn last changed the plan.

One writer per namespace at a time. The previous count is read from the marker and each place's previous row by its own key; the prefix is never listed. A row past the end left behind by a failed write doesn't show, because a reader shows only places below the marker's count.

await replacePlanList(
ctx.resources[OBSERVED_PLAN],
ctx.resources[OBSERVED_PLAN_LIST],
runNamespace,
todos.map((t) => ({ title: t.text, status: t.state })),
);

Parameters​

plan​

PlanListCollection

marker​

PlanListMarkerCollection

namespace​

string

items​

readonly PlanListItem[]

options?​
now?​

() => number

requestId?​

string

Returns​

Promise<ReplacePlanListResult>


reportHarnessActivity()​

function reportHarnessActivity(
onActivity,
event,
ctx
): void;

Hand an event to onActivity when it is activity, without awaiting it. Never throws: a host's failure to record how the run is doing, thrown or rejected, never fails the run.

Parameters​

onActivity​

HarnessActivityHook | undefined

event​

ActivityEvent

ctx​

HarnessCallbackContext

Returns​

void


reportHarnessEvent()​

function reportHarnessEvent(onEvent, ctx): void;

Tell onEvent the run sent something. Call it on every event, of every kind, before anything else reads the event, without awaiting it. Never throws: a host's failure to note it, thrown or rejected, never fails the run.

Parameters​

onEvent​

HarnessEventHook | undefined

ctx​

HarnessCallbackContext

Returns​

void


reportHarnessSpend()​

function reportHarnessSpend(ctx, spend): boolean;

Report a harness run's spend to the running request. It is counted in the request's spend, which request-end hooks are handed and readRequestSpend reads; it is not a model call, so ctx.request.tokenUsage and an action's token budget never see it.

A later report for the same run replaces the earlier one. With a runId, a harness reports as its run goes: at its start (its model, tokens null), on each usage event its vendor sends (the run's total so far), and from its finally when the run ends however it ends (the final total). Each report carries the whole run so far, never an increment, and the run counts once. Without a runId, each call is one settled run, which the engine gives an id of its own.

Parameters​

ctx​

object

spend​

HarnessRunSpend

Returns​

boolean

false when the context carries no spend ledger: a hand-built test context, or a block run outside a request. Nothing is counted then.


whenPullRequestRecorded()​

function whenPullRequestRecorded(response, callback): void;

Call callback for each pull request any writer in this request records for the first time: the recorder as a create call settles, and a host's branch check. Register before the harness runs (a step ahead of it); a pull request recorded before it registered is not handed to it.

Parameters​

response​

unknown

The request's response (ctx.response).

callback​

PullRequestRecordedCallback

Returns​

void


writePullRequests()​

function writePullRequests(
collection,
refs,
options
): Promise<void>;

The one write path. Upserts each ref by pullRequestKey:

  • A new key is written whole, with firstSeenAt.
  • An existing row keeps requestId and firstSeenAt once set; a later sighting only fills a null title, branch, requestId or url. That is what lands a repeated link, a second recorder and the branch check on one row.
  • state is kept current: a sighting that names one replaces the stored one, so a read that saw the pull request merged or closed lands on the row.
  • A tool sighting upgrades a branch row's source.
  • A new key, once written, is handed to onRecorded.

Writes run one after another, so two refs to one key in a call never race. Throws what the store throws; a caller that must not fail on bookkeeping catches it.

Parameters​

collection​

PullRequestCollection

refs​

readonly PullRequestRef[]

options​

WritePullRequestsOptions

Returns​

Promise<void>