Skip to main content

@flow-state-dev/orchestration/tasks

Classes​

IllegalTaskTransitionError​

A lifecycle method refused a status change the state machine does not permit. Thrown by assertTransitionAllowed from inside the collection's CAS write, so nothing is committed.

Carries the three facts a caller needs to react without re-parsing the message. The taskTools boundary catches this by type and returns a recoverable { ok: false, error } result naming what the model can do instead; every other caller still gets the throw — driving a collection directly (a drain's rescue path, user code) is expected to handle or propagate it, which is why this class is exported rather than module-private.

The message text is deliberately unchanged from the plain Error this replaced: only the type is new.

Extends​

  • Error

Constructors​

Constructor​
new IllegalTaskTransitionError(options): IllegalTaskTransitionError;
Parameters​
options​
from​

| "completed" | "errored" | "cancelled" | "pending" | "in_progress" | "held"

taskId​

string

to​

| "completed" | "errored" | "cancelled" | "pending" | "in_progress" | "held"

Returns​

IllegalTaskTransitionError

Overrides​

Error.constructor

Properties​

cause?​
cause?: unknown;
Inherited from​

Error.cause

from​
readonly from:
| "completed"
| "errored"
| "cancelled"
| "pending"
| "in_progress"
| "held";

The status the task was in when the guard ran.

message​
message: string;
Inherited from​

Error.message

name​
name: string;
Inherited from​

Error.name

stack?​
stack?: string;
Inherited from​

Error.stack

taskId​
readonly taskId: string;

The task whose transition was refused.

to​
readonly to:
| "completed"
| "errored"
| "cancelled"
| "pending"
| "in_progress"
| "held";

The status the caller tried to move it to.


TaskCapExceededError​

A task creation was refused because it would cross one of the collection's caps. Thrown from createTask/createTasks after the CAS write no-ops, so nothing is inserted. The createTask task tool catches this and returns a soft error; internal batch callers (seed, replan) let it propagate.

Extends​

  • Error

Constructors​

Constructor​
new TaskCapExceededError(options): TaskCapExceededError;
Parameters​
options​
attempted​

number

cap​

TaskCapKind

collectionId​

string

limit​

number

Returns​

TaskCapExceededError

Overrides​

Error.constructor

Properties​

attempted​
readonly attempted: number;

The count the insertion would have produced.

cap​
readonly cap: TaskCapKind;

Which bound was crossed.

cause?​
cause?: unknown;
Inherited from​

Error.cause

limit​
readonly limit: number;

The configured limit for that bound.

message​
message: string;
Inherited from​

Error.message

name​
name: string;
Inherited from​

Error.name

stack?​
stack?: string;
Inherited from​

Error.stack


TaskFilingRefusedError​

A filing, or an edit of one, refused at the board. Nothing was written. Thrown, not declined: a filing that can never run as asked is a caller's mistake to correct, and the task tools turn it into a recoverable { ok: false, error } naming the rule.

Extends​

  • Error

Constructors​

Constructor​
new TaskFilingRefusedError(options): TaskFilingRefusedError;
Parameters​
options​
detail​

string

rule​

TaskFilingRule

taskId?​

string

Returns​

TaskFilingRefusedError

Overrides​

Error.constructor

Properties​

cause?​
cause?: unknown;
Inherited from​

Error.cause

message​
message: string;
Inherited from​

Error.message

name​
name: string;
Inherited from​

Error.name

rule​
readonly rule: TaskFilingRule;

The rule the filing broke.

stack?​
stack?: string;
Inherited from​

Error.stack

taskId​
readonly taskId: string | undefined;

The task the refused filing names, when it names one.


TaskWriteRefusedError​

A write a collection refuses for a reason only it can name.

A ref that wraps a ledger with rules of its own (a session board that files a worker's step for itself apart from its tasks for delegates) throws this from the write it refuses. The task tools answer it as a soft error the model can act on, { ok: false, error: "<code>: <message>" }, the same way they answer a creation cap. Nothing is written.

Extends​

  • Error

Constructors​

Constructor​
new TaskWriteRefusedError(
code,
message,
taskId?
): TaskWriteRefusedError;
Parameters​
code​

string

The snake_case code, e.g. "step_cannot_wait".

message​

string

What was refused and what to do instead, said to the model.

taskId?​

string

The task the write named, when it named one.

Returns​

TaskWriteRefusedError

Overrides​

Error.constructor

Properties​

cause?​
cause?: unknown;
Inherited from​

Error.cause

code​
readonly code: string;

A snake_case code the tool result leads with.

message​
message: string;
Inherited from​

Error.message

name​
name: string;
Inherited from​

Error.name

stack?​
stack?: string;
Inherited from​

Error.stack

taskId?​
readonly taskId?: string;

The task the refused write named, when it named one.

Interfaces​

ClaimOptions​

Options for claim — let the claim order narrow eligibility and tweak ordering.

Properties​

eligibility?​
eligibility?: (task, rows) => boolean;

Per-task predicate that narrows the substrate's candidates. It does not replace them: the substrate admits a task first, then CAS-claims the first admitted task that also passes this. Default: no narrowing.

The candidate set is no longer pending only. It is every task the substrate considers claimable, which since lease-based recovery includes an in_progress row whose lease has run out — a task whose worker died. So the predicate sees both, and the obvious-looking assertion is the one thing not to write here:

// WRONG — silently opts out of abandoned-job recovery.
eligibility: (t) => t.status === "pending" && t.assignee === "researcher"

// Right: narrow on what you care about, and leave claimability alone.
eligibility: (t) => t.assignee === "researcher"

A status assertion compiles, reads correctly, and quietly makes stranded jobs unrecoverable for that claim order, because the row it must match is in_progress. Claimability is the substrate's call — isClaimable — and composing rather than replacing is what stops the newest invariant being the one most easily switched off by accident.

rows is the board as the claim write reads it, so a predicate that depends on other rows (one open task per session) is decided against the same state as the claim.

Parameters​
task​

Task

rows​

readonly Task[]

Returns​

boolean

leaseDurationMs?​
leaseDurationMs?: number;

How long the claimant may be gone before its work is handed to someone else. Stamped onto the claimed task's leaseUntil; defaults to two minutes.

This is the recovery-latency knob. A worker the substrate drives renews this while it works, so a lease that lapses means no live worker is holding the row and the next claim takes it back. Pass less and a dead job comes back sooner, at the cost of taking work from a worker that merely stalled; size it to the whole job and nobody takes it back until then. A row you claim by hand gets no renewal — you hold it, so you renew it.

Validated rather than normalized: a value below one second, above ~74 days, or non-finite throws, because each would turn the renewal cadence derived from it into a write storm or an overflowed timer.

order?​
order?: (a, b) => number;

Sort comparator over candidates. Default: ascending createdAt.

Parameters​
a​

Task

b​

Task

Returns​

number


ClaimOrder​

Methods​

claim()​
claim(
collection,
workerId,
ctx
): Promise<Task | null>;

Atomically pick and claim the next eligible task. Returns null when nothing is ready to dispatch right now (loop should exit or back off).

Parameters​
collection​

TaskCollectionRef

workerId​

string

ctx​

BlockContext

Returns​

Promise<Task | null>


DeclaredDelivery​

How a board that hands rows out delivers its endings, declared on its ledger (defineTaskCollection({ delivery })). A board built with a task dispatcher marks its ledger with the defaults (markDelegating).

Properties​

address?​
readonly address?: (ctx, filerSessionId) => NoticeAddress | undefined;

How the running request reaches the filer's session, or undefined when it can't (the wake delivers instead). Default: the filer's session by id, on the running flow.

Parameters​
ctx​

BlockContext

filerSessionId​

string

Returns​

NoticeAddress | undefined

legacyFiler?​
readonly legacyFiler?: (row, partition) => string | undefined;

The filer of a row filed before Task.filer, from its partition.

Parameters​
row​

Task

partition​

string | undefined

Returns​

string | undefined

noticeEntry?​
readonly noticeEntry?: (row) => string;

The entry a row's notice arrives on. Default TASK_SETTLED_ENTRY.

Parameters​
row​

Task

Returns​

string

notices?​
readonly notices?: false;

false: an ending owes its filer no notice, only the resume of a request parked on it. A plan board's ledger: its drain waits on every row, so nobody else is told how one ended. Default: every ending owes one.

onMidwayQuestion?​
readonly onMidwayQuestion?: (ctx, row, questions) => Promise<void>;

A task on this ledger asked its filer's questions midway: told with the row's open midway questions, read from the committed row, from the asking request. Not the notice pipeline: no marker, no wake, no noticeEntry. The same declaration, a different moment. Called again when a replayed turn asks again, so it must be idempotent per hold (a Workforce board sends one message per hold, its id derived from the hold). Called only for a row whose filer is known. Runs inline in the asking turn, after its lease is dropped, so a slow telling only delays that turn's end. A throw is logged, never fails the question.

Parameters​
ctx​

BlockContext

row​

Task

questions​

readonly object[]

Returns​

Promise<void>

onUndeliverable?​
readonly onUndeliverable?: (ctx, row, notice, detail) => Promise<void>;

A notice settled undeliverable: its filer's session is gone.

Parameters​
ctx​

BlockContext

row​

Task

notice​

TaskNotice

detail​

string

Returns​

Promise<void>

passEntry?​
readonly passEntry?: string;

The internal entry a wake runs in the filer's session: the board's pass, which pays what is owed and clears the wake. Default TASK_SETTLED_ENTRY, which pays on an empty input.


DeclaredFiledCascade​

A ledger's payer for the tasks its tasks filed, as declared: pay takes the running context, bound when the ledger is resolved.

Properties​

owes​
readonly owes: (row, ending) => boolean;

Whether this ending owes the filed half: a pure function of the row as the ending writes it, run inside that write and possibly more than once.

Parameters​
row​

Task

ending​

TaskEnding

Returns​

boolean

pay​
readonly pay: (ctx, row) => Promise<boolean>;

Cancel the open tasks row filed, in the running context. true once paid; false leaves the cascade owed, for the next touch past its due time.

Parameters​
ctx​

BlockContext

row​

Task

Returns​

Promise<boolean>


DefineTaskCollectionOptions​

Type Parameters​

TInputSchema​

TInputSchema extends ZodTypeAny = ZodTypeAny

TScope​

TScope extends ResourceScope = ResourceScope

Properties​

cascadeFiled?​
cascadeFiled?: DeclaredFiledCascade;

The ledger's payer for the tasks a task on it filed elsewhere. A task that fails, retries or is cancelled owes a cascade, recorded in its ending's write when owes says so, and paid by pay: at once by the ending's own pass, and by a touch of the ledger once past due.

delivery?​
delivery?: DeclaredDelivery;

How the ledger's endings reach the sessions that filed them: the pass a wake runs, the entry a notice arrives on, how a filer is reached, and what a notice nobody can take does. A board with a task dispatcher gives its ledger the defaults when it declares none.

id​
id: string;

Literal collection id. Forms the resource pattern (<id>/**), the ctx.resources lookup key, and the board's collectionId. Must be a single plain segment — no */[param] pattern tokens, no /, no prototype-poisoning names.

maxInstances?​
maxInstances?: number;

Maximum number of tasks retained in the collection. Optional.

partitionBy?​
partitionBy?: TaskPartitionFn;

Keep one set of rows per partition, at the owner's user scope: a ref resolved in a running context reads and writes only the partition this function names for it. Use it for a board kept per conversation whose rows a task entry on another flow works: the user scope crosses the flow, and the partition keeps each conversation's board its own. A board's dispatch carries the partition it claimed in, so the receiving entry reads the row there and never calls this function itself. The rows sit in the user's own cell, shared with every flow of theirs, even on a flow that isolates its user state (isolateUserState).

Return a non-empty string from data only the server writes. The function gets the running session's server-set identity (sessionId, userId, orgId, tenantId) and nothing a caller supplies. user scope only, and not with maxInstances, whose cap would count every partition's rows. A partitioned ledger's task ids are one path segment (no /). Its rows load a partition at a time, on that partition's first read in a request, never the whole ledger when the request starts.

A partitioned ledger also declares a byTaskId index on its rows, so a bare task id finds the partitions that hold it (findTaskPartitions) without reading any partition's rows.

recordEnding?​
recordEnding?: TaskEndingRecorder;

Hand every write that records how a task ended to this function, inside that same atomic write, and keep the metadata it returns on the row: a completion, a failure (for good, or with attempts left), a park, a cancel, and the claim path settling a row whose worker died too often. Whatever it adds lands with the ending or not at all, so a debt the ending creates (someone to tell) can't be lost between the two. See TaskEnding for what each ending carries.

It must be a pure function of the row and the ending: a write that loses a version race runs it again against the fresher row. Only metadata is taken from what it returns; the transition decides every other field.

scope​
scope: TScope;

Intrinsic scope the collection lives in — "session", "user", or "org".

settings?​
settings?: TaskSettingsSupport;

The filing settings this ledger honours beyond the defaults: session: ["new", "ongoing"] when its hand-over can run a task in the delegate's ongoing session, resultTo: ["filer", "conversation"] when it can send a result to the conversation. A filing with a value it doesn't list is refused, naming the setting.

sharedToLineage?​
sharedToLineage?: boolean;

Give a session-scoped board ONE ledger across the session lineage, so the child session a dispatched row runs in settles against the same rows the dispatching session holds. Without it a session-scoped board hydrates empty inside a child session and the task cannot be settled.

Session-scope only — defineResourceCollection rejects it at user/org scope, where the ledger already spans every session the principal touches.

stateSchema?​
stateSchema?: TInputSchema;

Schema for each task's input payload. Optional; defaults to z.unknown(). This is the typed payload a worker receives, not the whole task — the rest of the Task envelope is validated automatically.


ExternalWait​

What the turn holding a task's claim waits on outside the board: a line a screen can show (prompt), and the events that end the wait.

Properties​

events​
readonly events: readonly ExternalWaitEvent[];
prompt​
readonly prompt: string;
title?​
readonly title?: string;

ExternalWaitEvent​

One thing an external wait waits on: what kind of event ("pull-request"), and which one (key).

Properties​

event​
readonly event: string;
key​
readonly key: string;

FailOptions​

fail's options: the ordinary transition guards, plus whether this failure may be retried at all.

Extends​

Properties​

adoptLapsedLease?​
adoptLapsedLease?: boolean;

Let a renewal take back a row whose lease lapsed while the claim it names stayed intact.

The lease fence declines a ticketed write on a lapsed row because a lapsed lease means the row is the queue's again. That is right for a result — a worker that ran past its lease may have been superseded, and the successor owns the outcome — and it is too strong for a claimant that has not started yet. A task handed to a child session is the case: nothing renews the row between the parent's release and the child's first breath, so a child that waits in the host's queue longer than the lease arrives to a lapsed row that no one has taken — same attempts, same createdAt, same incarnation, still in_progress.

With this set, that renewal is decided by the race instead of by the clock: every other guard still runs inside the same atomic write, so it is recorded only while the identity the ticket names is still the row's, and declines lost-claim the moment a reclaim has moved attempts or the status. Winning the write is the takeover — the caller holds the row for another lease span, on the same attempt.

Opt-in, because the substrate cannot tell the two lapsed claimants apart. A stalled worker whose renewal timer finally fired presents the same evidence as the queued child above, and only the second should take the row back: the first has been running against a row the queue may have re-dispatched. So the caller asserts "I have not started yet", which is something only it knows.

Honoured only on a renewal — the one write that targets in_progress. Passing it to a settlement changes nothing: complete and fail on a lapsed row still decline lost-claim.

Inherited from​

TaskTransitionOptions.adoptLapsedLease

claim?​
claim?: TaskClaimTicket;

Record the outcome only if the caller still owns the task it is writing to.

The ticket is minted by the substrate at claim time (ticketForClaim) and names the board, the task, the attempt, and the task's createdAt. It answers two questions the write cannot answer for itself:

  • Is this the task I claimed? Declines not-my-task when the ticket names another board, another task, or a task since recreated under the same id. This is the question a bare attempt number could not ask, which is why it replaced one.
  • Do I still hold it? Declines lost-claim unless task.attempts equals the ticket's attempt and the task is still in_progress. The status half is not belt-and-braces: reclaim() returns a task to pending without advancing attempts, so between a reclaim and the next claim a displaced worker matches the counter by construction — and since held is reachable only from pending, a counter-only guard would let a stale worker silently settle work a coordinator held.

Omit it and no ownership question is asked, which is the correct posture for a coordinator writing to a board it never claimed from.

Inherited from​

TaskTransitionOptions.claim

ifAllowed?​
ifAllowed?: boolean;

Record the outcome only if the task's state machine will accept it.

Declines when the task is already terminal, or when the transition is rejected. Both arms are load-bearing: the state machine treats same-status as allowed, so cancelled → cancelled is legal and terminal, and without the terminal arm an incidental repeat write would clobber the reason and timestamp an explicit settlement recorded.

Inherited from​

TaskTransitionOptions.ifAllowed

noRetry?​
noRetry?: boolean;

Settle the task errored even though it has attempts left: the failure is one no retry can change, such as a run refused before it started because it names nothing it may work on. Without it, a task with attempts left is re-queued and refused the same way on every one. Every guard still runs inside the same write, so a stale holder's noRetry failure is declined like any other.

refuseUntakenSteers?​
refuseUntakenSteers?: boolean;

Decline a complete while the task holds a steer no request of its attempt took, reason untaken-steers. Decided inside the write, so a steer that lands after the caller's own read still holds the task open. Pass it only where something then owes the steer a turn.

Inherited from​

TaskTransitionOptions.refuseUntakenSteers

viaTool?​
viaTool?: boolean;

A cancel made through a model's updateTask tool. Set by the task tools only, from how the block was built, never from input: the tools are blocks for a model's turn, and an app's or a person's cancel goes through taskToolActions, which never sets it. When the running session is the row's filer, the call's result is how it hears the cancel, so the cancel owes it no notice.

Inherited from​

TaskTransitionOptions.viaTool

write?​
write?: TaskWriteToken;

Record this write on the task, so the caller can find out afterwards whether it committed — even if this call throws.

Mint one with beginTaskWrite(tasks.get(id)) before the write and read the answer with didWriteLand(tasks.get(id), write) after. The returned TaskWriteOutcome already says what a call that returned did; this covers the path it cannot reach, where the durable write commits and the change announcement then rejects.

Three answers come back, and the third is the point: landed, did not land, or cannot tell. See didWriteLand for the rule and for what a false precisely means.

Correlation is available on the seven methods that take this options object. createTask, createTasks, claim, reclaim and the five field mutators still bump the task's revision but mint no receipt, so a caller of those cannot correlate its own write. Widening means adding an options argument to nine more methods on an already-large interface; it waits for a consumer that needs it.

A TaskCollectionRef written by hand maintains no provenance, and needs no migration to stay correct: absence of a record reads as "cannot tell", not as "your write did not land".

Inherited from​

TaskTransitionOptions.write


LeaseRenewalDriver​

A running renewal driver. Run the work under signal and stop it when the work returns, on every path.

Properties​

signal​
readonly signal: AbortSignal;

Aborted when the claim is lost — the substrate refused a renewal because the row is no longer this worker's (taken back, cancelled, recreated, or its lease already gone).

It aborts at the refusal, not at the loss, and the gap between them is a whole renewal interval. Nothing notifies a worker that its claim was taken; the only way this driver can find out is to attempt a write and be told no. So a claim lost just after a successful renewal leaves this signal clear until the next tick — up to span / RENEWAL_DIVISOR, about a third of the lease. Treat it as a bounded stop, not a prompt one: work started before it fires can still be running, and it is not a substitute for the write fence, which is what actually refuses a stale worker's result.

Compose it with the request's signal rather than substituting it; a step dispatched with .step(block, { abortSignal }) gets that composition for free. (withLeaseRenewal hands its callback the composition already made — this is the bare lease-loss signal.)

Methods​

stop()​
stop(): void;

Stop renewing. Idempotent, and safe to call before the first tick.

Returns​

void


LeaseRenewalOptions​

Properties​

claimedTask​
claimedTask: Task;

The task as claim() committed it. The renewal span is read off this row rather than passed in, which is what makes the driver correct by construction: a claim order that claimed with a five-second lease and a driver that assumed two minutes cannot disagree, because there is nothing to agree about.

collection​
collection: TaskCollectionRef;

The board holding the claimed row.

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

The clock renewal reasons against. Defaults to the collection's own, never to Date.now — the deadlines this driver writes are compared against leaseUntil, which the claim write stamped on that clock, so a driver reading a different one writes on a different timeline than the row it is extending. Override only to drive the driver itself in a test.

Returns​

number

signal?​
signal?: AbortSignal;

The ambient signal renewal rides — normally ctx.signal. When it aborts, renewal stops: a cancelled request is not a live worker.

ticket​
ticket: TaskClaimTicket;

The ticket minted from this claim — renewal's ownership assertion.

timer?​
timer?: RenewalTimer;

Timer injection for tests. Default: an unref'd setTimeout.


NoticeAddress​

Where a notice goes from the running request: a session target, and its flow when not the sender's own.

Properties​

flowKind?​
readonly flowKind?: string;
session​
readonly session: SessionTarget;

NoticeLine​

A notice as its line's item carries it: which task, how it ended, and what came back, for a client to read instead of the line's words.

Properties​

attempt?​
readonly attempt?: number;

The attempt that ended. Absent on a line read off its text alone.

boardId?​
readonly boardId?: string;

The ledger the task is on, by id. Absent on a line read off its text alone.

cancelled?​
readonly cancelled?: readonly string[];

On a failure or a cancel: the dependents it cancelled that share its filer, by id.

detail?​
readonly detail?: string;

What came back: a completion's output summary, a failure's error. Absent on a cancel.

ending​
readonly ending: NoticeEnding;
taskId​
readonly taskId: string;
title​
readonly title: string;

The row's title, or its goal when it has none.


NoticeRecording​

What the ending's write knows that its row can't say.

Properties​

causeSharesFiler?​
readonly causeSharesFiler?: boolean;

For a cascaded cancel: whether the row whose ending caused it shares this row's filer.

ownCancel?​
readonly ownCancel?: boolean;

The filer made this cancel itself, through its model's task tool in its own turn.


Observation​

One recorded tool-call observation. Cheap to copy; values are not cloned.

Properties​

args​
args: unknown;
cached​
cached: boolean;

True when the call was served from the per-tool memoization cache.

collectionId​
collectionId: string;

The Task Board collection id that owns this ledger.

error?​
error?: string;

Set when the call threw. Errors do NOT populate result.

result?​
result?: unknown;

Set when the call succeeded (or returned a cached hit).

seq​
seq: number;

Monotonic sequence within the ledger; assigned on append.

taskId?​
taskId?: string;

Id of the task whose worker made the call. May be absent for non-board generators.

toolName​
toolName: string;
ts​
ts: number;

Date.now() at observation time.

workerId?​
workerId?: string;

Stable id of the worker block / iteration that made the call.


ObservationLedgerView​

Read-only projection helpers over a ledger. Policies use this to select.

Methods​

all()​
all(): readonly Observation[];

All observations, oldest first. Read-only snapshot.

Returns​

readonly Observation[]

bounded()​
bounded(observations, maxTokens): Observation[];

Token-bounded slice of the supplied observations. Uses a simple character-count heuristic (~4 chars/token) — the spec calls for a pluggable token counter in a future revision.

Parameters​
observations​

Observation[]

maxTokens​

number

Returns​

Observation[]

fromAncestors()​
fromAncestors(
task,
collection,
opts?
): Observation[];

Observations from the supplied task's declared deps (and, when transitive: true, the deps' deps). Resolved against the live collection so a replan-introduced dep is honored.

Parameters​
task​

Task

collection​

TaskCollectionRef

opts?​
transitive?​

boolean

Returns​

Observation[]

fromCompleted()​
fromCompleted(collection): Observation[];

Observations from tasks the collection currently marks "completed".

Parameters​
collection​

TaskCollectionRef

Returns​

Observation[]

fromTasks()​
fromTasks(taskIds): Observation[];

Observations whose taskId is in the supplied set.

Parameters​
taskIds​

readonly string[]

Returns​

Observation[]

recent()​
recent(n): Observation[];

The most recent N observations (chronological, newest last).

Parameters​
n​

number

Returns​

Observation[]


QuestionAnswer​

An answer to one own hold: the user's words, the filer's for a midway question, or a service's for an external wait.

Properties​

by?​
readonly by?: string;

The user who answered, server-set; for a "service" answer, the sender's handle.

from​
readonly from: "user" | "filer" | "service";

Who sent it: a person ("user"), the filer for a midway question ("filer"), or words from outside the app, a delivered message ("service"), whose sender is by.

key?​
readonly key?: string;

A key naming this answer, so the same request run again adds nothing (a line typed in the task's session is keyed by its request). Its steer's id; a fresh one when absent.

message​
readonly message: string;
questionId​
readonly questionId: string;

The own hold it answers.


ResourceBackingSpec​

Resource-collection backing options.

Extends​

  • CommonOptions

Properties​

backing​
backing: "resource";
changeVisibility?​
changeVisibility?: ItemVisibility;

Visibility stamped on the task-change data items emitted on every lifecycle transition. Omit for the default, { client: true, history: false }: the change stream drives the live <Plan /> UI and never enters a model's history.

Inherited from​

CommonOptions.changeVisibility

collection​
collection: ResourceCollectionRef<JsonObject>;

The parameterized resource collection ref. Pattern: someTopic/{id}.

collectionId​
collectionId: string;
Inherited from​

CommonOptions.collectionId

immutableAssignee?​
immutableAssignee?: boolean;

Refuse setAssignee on an in_progress task in this collection. Set by a task board with dispatcher assignees, whose child's routing key is derived from the assignee. Only this backing carries it — a dispatched board is refused at construction on any other.

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

Clock injection for tests. Default: Date.now.

Returns​

number

Inherited from​

CommonOptions.now

partition?​
partition?: string;

The partition to read and write, required when collection was declared with partitionBy and refused otherwise. A board passes the value its partitionBy returns, or the one a dispatch names; a task entry's taskLedgers resolver passes the one it is handed.

readFor?​
readFor?: string;

The conversation a view reads this board for, in the running session's place: a user view runs in no session, so the board's notices are heard on this one's topic (the filer of a row with none, and of a board with no rows yet). The caller passes an id its owner check admitted, never input it didn't check. Absent, the running session.


StateBackingSpec​

Atomic-state backing options.

Tasks live as a Record<id, Task> on one atomic state, written through its CAS-guarded atomicState. Which state, and the default slot, follow from whether you pass state:

  • state passed (e.g. ctx.sequencer, or a generator's own state via ctx.parent) — tasks live at [stateKey], default "tasks", on that ref. Durability follows the ref: a sequencer's state is checkpointed and restored on resume; a generator's own state is not.
  • state omitted — tasks live on the request (ctx.request), at [stateKey], default the collectionId, so several boards in one request stay apart. The collection survives every block boundary within the request and ends with it; for cross-request boards use backing: "resource".

The caps are accepted here and not on ResourceBackingSpec: this arm builds createStateBackedTaskCollection, where enforcement lives, and asking for a cap on a backing that enforces nothing is a type error rather than a silently ignored ceiling. (That backing still counts retries; see task-caps.ts on why counting and enforcing are separate there.)

Extends​

Properties​

backing​
backing: "state";
changeVisibility?​
changeVisibility?: ItemVisibility;

Visibility stamped on the task-change data items emitted on every lifecycle transition. Omit for the default, { client: true, history: false }: the change stream drives the live <Plan /> UI and never enters a model's history.

Inherited from​

CommonOptions.changeVisibility

collectionId​
collectionId: string;
Inherited from​

CommonOptions.collectionId

maxEnqueuedTasks?​
maxEnqueuedTasks?: number | null;

Enqueued-at-creation pending count. null = unbounded.

Inherited from​

TaskCapOptions.maxEnqueuedTasks

maxTotalRetries?​
maxTotalRetries?: number | null;

Cumulative failure retries this collection may authorize, across every task. null = unbounded.

What omission does depends on where you are constructing. Only the DEFAULTING SURFACES turn an omitted axis into DEFAULT_MAX_TOTAL_RETRIES: taskBoard's declarative branch, the task-board capability, and eventActors — everything that routes through resolveTaskCapDefaults. Constructing a collection DIRECTLY (createStateBackedTaskCollection, getOrCreateTaskCollection({ backing: "state" })) applies no default: an omitted axis is passed through as undefined, and routeFailure reads undefined as unbounded. So a direct caller who omits this option gets NO cumulative retry bound, not 50. Pass the value you want, or resolveTaskCapDefaults first.

Three things about it are surprising and all three are deliberate:

  • 0 is legal and means "run every task once, never retry". Unlike the two creation caps — where 0 would mean "this board can do nothing" and is rightly refused — a zero retry budget is a coherent configuration, and without accepting it there would be no way to express one: on a defaulting surface omission gives the default, and null gives unbounded. A first attempt is never refused at any budget value, by construction.
  • The budget is spent at AUTHORIZATION, not at execution. If a re-pended task is never re-claimed (the worker died, the lease expired) the grant stays spent. That errs conservative — the bound can only under-spend relative to real model calls, never over-spend — and refunding it would mean inferring abandonment from lease expiry, which the task substrate does not treat as evidence.
  • Only failure retries count. unblock and reclaim also return a task to pending and do NOT consume the budget.

Enforced only on the backings that can check atomically against the whole ledger (backing: "state"). The resource backing still COUNTS retries but does not enforce, and reports maxTotalRetries: null so a caller can never read a non-zero count as evidence a budget applied.

Inherited from​

TaskCapOptions.maxTotalRetries

maxTotalTasks?​
maxTotalTasks?: number | null;

Lifetime task count, terminal tasks included. null = unbounded.

Inherited from​

TaskCapOptions.maxTotalTasks

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

Clock injection for tests. Default: Date.now.

Returns​

number

Inherited from​

CommonOptions.now

state?​
state?: StateRef<Record<string, unknown>>;

The atomic state that holds the tasks. Omit it to keep them on the request. A passed ref's state schema must include a record at [stateKey] shaped as Record<string, Task>.

stateKey?​
stateKey?: string;

Top-level field holding the Record<id, Task>. Default: "tasks" on a passed state; the collectionId on the request.


SteerInput​

What a sender hands the steer verb.

Properties​

by?​
readonly by?: string;

The user, when a person sent it.

from​
readonly from: "user" | "filer" | "board" | "service";
key?​
readonly key?: string;

A key naming this steer, so the same steer sent twice (a replay, an upgrade step run again) adds one. A fresh id when absent.

message​
readonly message: string;

TaskCapOptions​

The collection's caps, as accepted by every construction point. A finite integer sets the bound; null means explicitly unbounded on that axis; omitting the option leaves it to whatever default the construction point applies (which is why null exists — omission is not an off switch).

Extended by​

Properties​

maxEnqueuedTasks?​
maxEnqueuedTasks?: number | null;

Enqueued-at-creation pending count. null = unbounded.

maxTotalRetries?​
maxTotalRetries?: number | null;

Cumulative failure retries this collection may authorize, across every task. null = unbounded.

What omission does depends on where you are constructing. Only the DEFAULTING SURFACES turn an omitted axis into DEFAULT_MAX_TOTAL_RETRIES: taskBoard's declarative branch, the task-board capability, and eventActors — everything that routes through resolveTaskCapDefaults. Constructing a collection DIRECTLY (createStateBackedTaskCollection, getOrCreateTaskCollection({ backing: "state" })) applies no default: an omitted axis is passed through as undefined, and routeFailure reads undefined as unbounded. So a direct caller who omits this option gets NO cumulative retry bound, not 50. Pass the value you want, or resolveTaskCapDefaults first.

Three things about it are surprising and all three are deliberate:

  • 0 is legal and means "run every task once, never retry". Unlike the two creation caps — where 0 would mean "this board can do nothing" and is rightly refused — a zero retry budget is a coherent configuration, and without accepting it there would be no way to express one: on a defaulting surface omission gives the default, and null gives unbounded. A first attempt is never refused at any budget value, by construction.
  • The budget is spent at AUTHORIZATION, not at execution. If a re-pended task is never re-claimed (the worker died, the lease expired) the grant stays spent. That errs conservative — the bound can only under-spend relative to real model calls, never over-spend — and refunding it would mean inferring abandonment from lease expiry, which the task substrate does not treat as evidence.
  • Only failure retries count. unblock and reclaim also return a task to pending and do NOT consume the budget.

Enforced only on the backings that can check atomically against the whole ledger (backing: "state"). The resource backing still COUNTS retries but does not enforce, and reports maxTotalRetries: null so a caller can never read a non-zero count as evidence a budget applied.

maxTotalTasks?​
maxTotalTasks?: number | null;

Lifetime task count, terminal tasks included. null = unbounded.


TaskClaimTicket​

Proof that the holder claimed a specific task on a specific board.

Minted by ticketForClaim from a committed claim; presented on TaskTransitionOptions.claim. Callers do not construct one by hand — a hand-assembled ticket is an ownership assertion nobody checked.

Properties​

assignee?​
readonly assignee?: string;

task.assignee as of the claim. Server-derived like the rest: a board whose fallback dispatches rows addresses the hand-over by it, and the receiving gate checks the row still names it. Not part of the write fence.

attempt​
readonly attempt: number;

task.attempts as of the claim — i.e. post-increment, this attempt.

collectionId​
readonly collectionId: string;

The board the claim was taken on.

createdAt​
readonly createdAt: number;

task.createdAt as of the claim — task identity across delete/recreate.

createdBy?​
readonly createdBy?: string;

task.createdBy as of the claim: the user whose request filed the task, as the substrate stamped it. A hand-over that looks its target up per task resolves "the filer's own" against it. Not part of the write fence.

followUpOf?​
readonly followUpOf?: string;

task.followUpOf as of the claim: the finished task the claimed row follows up. A hand-over keys the follow-up's session by it, so the follow-up runs in that task's session. Not part of the write fence.

incarnationId?​
readonly incarnationId?: string;

task.incarnationId as of the claim — the row's identity nonce, and the only one of these fields that survives a same-millisecond recreate.

createdAt above is a millisecond clock, and a delete-then-recreate under the same id lands in the same millisecond often enough (measured 198/200, see schema/task.ts) that the two rows share it. Carried so a holder that has to re-verify its claim across a process boundary — the child's task gate is the one that does — can ask the question createdAt cannot answer.

Absent on a row persisted before incarnationId shipped, and on any hand-written TaskCollectionRef that maintains no provenance. A reader compares it only when both sides carry one, exactly as didWriteLand's incarnation arm does; absent is "cannot tell", never "does not match".

partition?​
readonly partition?: string;

The partition the claim was taken in, on a ledger declared with partitionBy: the claiming ref's own. A board's dispatch puts it on the dispatch so the receiving gate reads the row where it was claimed. Not part of the write fence: the ref a write goes through is already narrowed to it.

taskId​
readonly taskId: string;

The task the claim was taken on.

turn​
readonly turn: number;

task.turn as of the claim: the row's turn generation. Every claim of a row advances it, a same-attempt re-entry's included, so two turns of one attempt hold different tickets and a turn's late write never lands after its successor's claim. Checked by every claim-ticket write, at transitionDeclineReason.


TaskCollectionRef​

Runtime ref onto a TaskCollection. All mutations are CAS-safe and emit a task-change data item via the configured onChange callback (the getOrCreateTaskCollection factory wires this to ctx.emit.data).

Queries (get, list, count) are synchronous reads of the latest committed view. For the resource backing — whose underlying ResourceCollectionRef reads are async — this synchronous view is a mirror of resource refs hydrated once at construction time over the collection. Because resource refs are live getters, reads through the mirror still reflect the latest committed state for every task the mirror knows about.

Implementing this interface yourself​

taskBoard({ collection: (ctx) => ... }) accepts a caller-supplied ref, so this is a real extension point for an external or custom store — not just the shape the two built-in backings happen to return.

If you write one, every worker-callable transition — complete, fail, cancel — should accept and honour the optional TaskTransitionOptions argument. The type system cannot hold you to this: an implementation taking only (id, output) structurally satisfies the interface, and JavaScript discards the extra argument in silence. See TaskTransitionOptions for the guards, and evaluate them inside your atomic write so the check cannot race the write it guards.

What the substrate guarantees, and what you still owe​

Guaranteed — for one class of throw, not for every failure. The substrate's advisory write-backs contain a throw they can attribute to a decline a conforming store would have made before committing anything: the late result is dropped and the drain finishes its other tasks. So a ref that ignores the options no longer abandons every sibling task the first time a worker's result arrives late — the write-back conflict is contained.

That is the whole of it. A store that is unreachable, or that commits and then fails on the way out, still throws through to the caller and can still fail the drain, because neither is a task-state conflict and silencing them would lose real failures. Don't read this as fault isolation from your store.

Still yours: the write's correctness. Containment fires on a throw, and plenty of wrong writes don't throw. A worker reporting success on a task another worker has since taken over is an ordinary in_progress → completed, so an unguarded ref commits it and overwrites the holder's result; nothing outside your atomic section can see that, let alone stop it. Ownership goes unchecked the same way — a worker's write lands on whichever task the caller named.

So the options are no longer what keeps a board alive. They are what keeps its tasks' outcomes true.

Type Parameters​

TInput​

TInput = unknown

TOutput​

TOutput = unknown

Properties​

collectionId​
collectionId: string;

Stable identifier — matches data.collectionId on emitted task-change items.

maxTotalRetries​
readonly maxTotalRetries: number | null;

The cumulative retry budget this ref actually enforces, or null when none is in force.

Read by the board's completion item so the retry count it reports is never mistaken for evidence that a budget applied. It is exposed here, where enforcement lives, rather than derived from the board's own config, because a board handed a collection it did not construct knows nothing about that collection's caps — and a caller who builds one deliberately (getOrCreateTaskCollection({ backing: "state", maxTotalRetries: 5 })) would otherwise be told "no limit" about a limit they set themselves.

null means exactly one thing everywhere: no limit is in force. That covers both an explicit opt-out and a backing that counts retries without enforcing them (the resource backing), so there is no third "unknown" state. If you implement this interface yourself and enforce no budget, report null.

now​
readonly now: () => number;

The clock this collection stamps and judges leases against.

Exposed because a lease is a comparison, and a comparison needs one clock. leaseUntil is written by the claim write against this clock, so anything asking "has this lease run out" — the board's wake probe, the ready-task preview, a claim order's candidate scan, the renewal driver deciding when to write next — has to ask the same one. Reading Date.now() instead works right up until a collection is built on an injected clock, at which point the two sides silently answer different questions: a live task can read as abandoned and an abandoned one as live.

That divergence is invisible in production, where every clock is the wall clock. It is only visible under an injected clock — which is what tests use. So the failure mode is a lease test that passes without exercising a coherent timeline at all, which is the last test you want to be wrong.

Implementing this interface yourself? now: () => Date.now() is the right answer unless you have a reason for another.

Returns​

number

partition?​
readonly partition?: string;

The partition this ref reads and writes, on a ledger declared with partitionBy; absent on every other ledger.

A ref over a partitioned ledger reaches only its partition's rows, for every operation. Exposed so a claim made through the ref can name the partition it was made in: a board's dispatch puts it on the dispatch, and the receiving gate reads the row there.

Methods​

addLabel()​
addLabel(id, label): Promise<TaskWriteOutcome>;
Parameters​
id​

string

label​

string

Returns​

Promise<TaskWriteOutcome>

answer()?​
answer?(id, answer): Promise<TaskWriteOutcome>;

Answer one of the row's questions or confirms: the answer is kept as a steer carrying the hold's id, from answer.from, and joins the brief. The last open own hold's answer lets the work go on in the same write: a task that hasn't started becomes claimable, its first attempt a start; a running one owes one more turn on its same attempt (turnOwed).

The same words from the same sender again are unchanged, even after the task has finished. Declines answered for other words or another sender, terminal on a finished row, and no-such-question for an id that isn't a question or a confirm on it. Who may answer which hold is the caller's rule (the board's updateTask); this write never checks a caller. Publishes answered.

Optional, so a ref written before it keeps compiling.

Parameters​
id​

string

answer​

QuestionAnswer

Returns​

Promise<TaskWriteOutcome>

ask()?​
ask?(
id,
asks,
options
): Promise<TaskWriteOutcome & object>;

Ask questions midway: the turn holding the task's claim opens own holds (Task.holds), drops the lease and ends its turn unsettled, in one write. The row stays in_progress on its attempt with no lease until every question is answered (or a deadline the host set passes), then owes one more turn on that attempt (turnOwed), which the claim takes.

Fenced like linkRun: options.claim is required, and the write declines terminal, not-my-task or lost-claim (a later turn's claim included) otherwise. Declines held while a stop for a person holds the row (one wait per turn), and steer-limit when the questions' answers would take the row past MAX_STEERS places. A recorded ask names the new holds' ids (holds). Publishes asked.

Optional, so a ref written before it keeps compiling; a board without it can't hold a task midway.

Parameters​
id​

string

asks​

readonly QuestionInit[]

options​
claim​

TaskClaimTicket

Returns​

Promise<TaskWriteOutcome & object>

awaitExternal()?​
awaitExternal?(
id,
wait,
options
): Promise<TaskWriteOutcome & object>;

Wait on something outside the board: the turn holding the task's claim opens one external wait (actor: "system", kind external) through the same write a question makes, so the row stays in_progress on its attempt with no lease, the claim skips it, and the turn ends unsettled. Any steer that answers it (a person's line, a delivered message) releases it and owes the same attempt one more turn (turnOwed). It is never midway: the filer is not told of it, and the Inbox does not list it.

Fenced and refused as ask is. A recorded wait names its hold's id (questions). Publishes asked.

Optional, so a ref written before it keeps compiling.

Parameters​
id​

string

wait​

ExternalWait

options​
claim​

TaskClaimTicket

Returns​

Promise<TaskWriteOutcome & object>

cancel()​
cancel(
id,
reason?,
options?
): Promise<TaskWriteOutcome>;

Cancel the task (terminal).

Advisory by construction: cancelling an already-settled task writes nothing. It also says so — the returned TaskWriteOutcome is declined with reason terminal, instead of returning silently and leaving the caller to infer success. Discard the verdict and behaviour is exactly as before.

options.ifAllowed is forced on regardless of what you pass, which is what "advisory by construction" means here. options.claim is honoured, so a worker cancelling through this method is held to the same ownership check as one completing through complete.

Parameters​
id​

string

reason?​

string

options?​

CancelOptions

Returns​

Promise<TaskWriteOutcome>

claim()​
claim(workerId, options?): Promise<Task<TInput, TOutput> | null>;
Parameters​
workerId​

string

options?​

ClaimOptions

Returns​

Promise<Task<TInput, TOutput> | null>

clearResumeOwed()?​
clearResumeOwed?(id): Promise<TaskWriteOutcome>;

Clear the row's resume-owed marker (Task.resumeOwed) once its waiting turn has its answer, and with it the mirror of the stop a cancelled row kept to pay it (its suspension hold). unchanged when no marker is set.

Optional: both built-in backings implement it, together with writing the marker when a waited-on row ends. A hand-written ref that does neither cannot host a wait, and the wait path refuses on it.

Parameters​
id​

string

Returns​

Promise<TaskWriteOutcome>

complete()​
complete(
id,
output,
options?
): Promise<TaskWriteOutcome>;

Mark the task completed with output.

Throws on an illegal transition. Pass options to make the write advisory instead — see TaskTransitionOptions. An advisory decline is reported on the returned TaskWriteOutcome; discarding it is supported and behaves exactly as before.

Parameters​
id​

string

output​

TOutput

options?​

TaskTransitionOptions

Returns​

Promise<TaskWriteOutcome>

count()​
count(filter?): number;
Parameters​
filter?​

TaskFilter

Returns​

number

createTask()​
createTask(task): Promise<Task<TInput, TOutput>>;
Parameters​
task​

TaskInit<TInput>

Returns​

Promise<Task<TInput, TOutput>>

createTasks()​
createTasks(tasks): Promise<Task<TInput, TOutput>[]>;
Parameters​
tasks​

TaskInit<TInput>[]

Returns​

Promise<Task<TInput, TOutput>[]>

dropNoticeReadByWait()?​
dropNoticeReadByWait?(id): Promise<TaskWriteOutcome>;

The filer's wait found the row already ended and returned it: drop the notice the ending owes the filer, which that answer delivered. unchanged when the row owes none for its ending, or its notice is taken (takeNotice): that notice is the delivery. Server-owned, as the other wait writes are: a caller's patchMetadata can't clear a notice.

Optional: both built-in backings implement it. On a ref without it the filer hears the ending again, as onTaskSettled.

Parameters​
id​

string

Returns​

Promise<TaskWriteOutcome>

fail()​
fail(
id,
error,
options?
): Promise<TaskWriteOutcome>;

Mark the task failed.

Throws on an illegal transition. Pass options to make the write advisory instead — see TaskTransitionOptions. Both branches below honour the guards, so a settled task with retry budget left declines rather than throwing on its way to pending.

  • When the task carries a maxAttempts budget that has not yet been exhausted, this is a soft fail: status flips back to pending, the error is captured on feedback, and the next claim increments attempts for a fresh attempt. Emits a task-change item with kind: "retried".
  • Otherwise this is a hard fail: status transitions to terminal errored with the error captured on task.error. options.noRetry makes it a hard fail whatever budget is left.

An advisory decline is reported on the returned TaskWriteOutcome, from whichever branch ran; discarding it is supported and behaves exactly as before.

Parameters​
id​

string

error​

string

options?​

FailOptions

Returns​

Promise<TaskWriteOutcome>

filerOf()?​
filerOf?(row): string | undefined;

The session that filed row, by the ledger's delivery rule: Task.filer, or, for a row filed before it, the ledger's legacy filer. Present on a ledger a board hands rows out from; absent elsewhere, where Task.filer is the whole answer.

Parameters​
row​

Task

Returns​

string | undefined

get()​
get(id): TaskHandle<TInput, TOutput> | undefined;
Parameters​
id​

string

Returns​

TaskHandle<TInput, TOutput> | undefined

getCommitted()?​
getCommitted?(id): Promise<TaskHandle<TInput, TOutput> | undefined>;

The row as stored now, where get reads it as this request first did: another request's write (a steer sent while this one runs) is read here. Optional, so a ref written before it keeps compiling; a caller falls back to get.

Parameters​
id​

string

Returns​

Promise<TaskHandle<TInput, TOutput> | undefined>

hold()​
hold(id): Promise<TaskWriteOutcome>;

Hold a task that hasn't started: pending → held, so it doesn't start until release. The guarded settings write (patchSettings) with held: true, under a named entry point.

Declines started on a row that has ever started (a retry's return to pending included), and terminal on an ended one. unchanged on a row already held. Publishes held.

Parameters​
id​

string

Returns​

Promise<TaskWriteOutcome>

lapseWait()?​
lapseWait?(
id,
gateId,
requestId
): Promise<TaskWriteOutcome>;

At a wait's deadline: lapse the slot gateId holds for requestId, the waiting request, in one conditional write that loses to an ending already written. Declines terminal on a row that has ended (the ending reached the waiting request, and it reads that instead); unchanged when the slot is another gate's or already lapsed. An ending written after this is held for that request, until releaseWait.

Parameters​
id​

string

gateId​

string

requestId​

string

Returns​

Promise<TaskWriteOutcome>

linkRun()​
linkRun(
id,
run,
options
): Promise<TaskWriteOutcome>;
Parameters​
id​

string

run​
attempt​

number

requestId​

string

sessionId​

string

startedAt?​

number

options​

TaskTransitionOptions & object

Returns​

Promise<TaskWriteOutcome>

list()​
list(filter?): TaskHandle<TInput, TOutput>[];
Parameters​
filter?​

TaskFilter

Returns​

TaskHandle<TInput, TOutput>[]

markCancelOwed()?​
markCancelOwed?(id): Promise<TaskWriteOutcome>;

Mark an open waited-on row as owing its cancel (Task.cancelOwed): its wait is over and the cancel the waiting call wrote failed. The row's next ending, the touch's cancel among them, clears it. unchanged on a row that has ended, isn't waited on, or is already marked.

Optional, like clearResumeOwed: both built-in backings implement it. On a ref without it, a failed cancel leaves the row open, as before.

Parameters​
id​

string

Returns​

Promise<TaskWriteOutcome>

markWait()?​
markWait?(id, slot): Promise<TaskWriteOutcome>;

Take the row's wait slot for a request about to wait on it: one conditional write, so of two requests that read the slot free, one takes it and the other is refused. A lapsed slot, or a live one this same request holds (a drain waiting again at its deadline), is taken over; the same gate replayed is unchanged. Publishes wait_changed.

Declines terminal on a row that has ended (the waiting call reads its ending at once instead), and disallowed while another request's wait holds the slot.

Optional, like the other wait writes: both built-in backings implement them, and a ref without them can't host a wait, which refuses there.

Parameters​
id​

string

slot​

TaskWaitSlot

Returns​

Promise<TaskWriteOutcome>

patchMetadata()​
patchMetadata(id, patch): Promise<TaskWriteOutcome>;
Parameters​
id​

string

patch​

Record<string, unknown>

Returns​

Promise<TaskWriteOutcome>

patchSettings()​
patchSettings(id, patch): Promise<TaskWriteOutcome>;

Change a filing's start or attempts settings while the task has never started: held, deps (replaced whole), maxAttempts. The one guard every edit of a filing goes through, inside the write.

Declines started on a row that has ever started and terminal on an ended one; unchanged when nothing changes. Dependencies are checked as a filing's are, and a refusal throws TaskFilingRefusedError naming the rule. Publishes held or released when the status moves, else settings_changed.

Parameters​
id​

string

patch​

TaskSettingsPatch

Returns​

Promise<TaskWriteOutcome>

payHoldDeadlines()?​
payHoldDeadlines?(): Promise<string[]>;

A touch of the board: close every open question past the due time a host set, with the board's "no answer came" steer, which lets the work go on as an answer would. A question with no due time is never closed here. Returns the ids of the rows it wrote, so a board wakes only those.

Optional: both built-in backings implement it.

Returns​

Promise<string[]>

payOwedCascades()?​
payOwedCascades?(): Promise<number>;

A touch of the board: pay every cascade owed past its due time (Task.cascadeOwed), so one a crash left owed is paid. Returns how many were paid. Whatever touches a board calls it: a board's drain, an action on it.

Optional: both built-in backings implement it, and pay each ending's cascade in that ending's own pass besides.

Returns​

Promise<number>

reclaim()​
reclaim(now?): Promise<number>;

Reset stale leases. Tasks whose leaseUntil has passed are returned to pending. Returns the number of tasks reclaimed; emits one task-change(kind: 'resumed', prevStatus: 'in_progress') per reset — the lifecycle UI cares only that the task is back to pending.

Not the recovery path. An abandoned row is recovered inside claim, so nothing has to call this for you; the verb is unchanged and stays available for a caller that wants to reset leases by hand.

It is the UNBOUNDED way back to pending, and deliberately so. The automatic recovery claim performs is bounded — DEFAULT_MAX_ABANDONMENTS re-dispatches, after which the row settles errored rather than being handed out again. This verb does not count against that budget, so a caller that keeps calling it on a row whose worker keeps dying will keep re-dispatching it past the bound, and the failure will present as a spent maxAttempts instead of an abandonment cap.

That is the same stance release already takes, and for the same reason: a bound exists to make a judgment nobody is present to make, and a caller invoking this verb by hand is present. Counting it would settle a task an operator explicitly asked to requeue.

So the promise is precise: recovery the substrate performs on its own is bounded. A sweeper built on this verb opts out of that bound — which was once the only way to recover anything, and is now a manual override rather than the mechanism. If bounded recovery is what you want, delete the sweeper and let claim do it.

Parameters​
now?​

number

Returns​

Promise<number>

recordSpend()?​
recordSpend?(
id,
write,
options
): Promise<TaskWriteOutcome>;

Record what a request admitted for the task has spent: its live part while it runs, or what an ending handed on, settled into the request's settled part with its live part cleared, in one write. Only the task's run calls it (task-board/task-request.ts); read it folded with taskSpendView.

Fenced by the row's identity only: options.claim is required and a recreated row declines not-my-task, but a terminal row and a lapsed or moved-on claim still take it. A spend is history: a failed attempt's tokens land after its row may have settled, and they count. unchanged when the write changes nothing. Publishes no task-change.

Optional, so a ref written before it keeps compiling; a task on a board without it shows no spend.

Parameters​
id​

string

write​

TaskSpendWrite

options​
claim​

TaskClaimTicket

Returns​

Promise<TaskWriteOutcome>

refresh()?​
refresh?(id): Promise<void>;

Bring one row up to its committed state. A request reads a durable board as the snapshot it first took, so an ending another request wrote since is invisible to get until this runs. Reading a task whole (getTask) calls it first. Writes nothing.

Optional: the resource-backed board implements it. A board kept in the request's own state is never behind.

Parameters​
id​

string

Returns​

Promise<void>

release()​
release(id): Promise<TaskWriteOutcome>;

Release a held task: held → pending, so it starts once its deps have finished. patchSettings with held: false. Every release of a held row publishes released, whoever releases it. unchanged on a row that isn't held.

Parameters​
id​

string

Returns​

Promise<TaskWriteOutcome>

releaseWait()?​
releaseWait?(id, release): Promise<TaskWriteOutcome>;

Release a lapsed slot for the request it was lapsed for: that request read the row (read), so an ending it held is delivered; or it ended without reading it, so the held ending is owed to the filer's notice, its wake owed first. The slot clears either way. unchanged when the slot is not a lapsed one that request holds.

Parameters​
id​

string

release​
read​

boolean

requestId​

string

Returns​

Promise<TaskWriteOutcome>

removeLabel()​
removeLabel(id, label): Promise<TaskWriteOutcome>;
Parameters​
id​

string

label​

string

Returns​

Promise<TaskWriteOutcome>

renewLease()​
renewLease(
id,
leaseUntil,
options
): Promise<TaskWriteOutcome>;

Push this task's lease out to leaseUntil — the worker saying "still here" about a row it already proved it owns.

This is what makes an expired lease mean something. Nothing used to renew a lease, so an expired one was the normal condition of a perfectly healthy worker and could not be acted on. Once the holder keeps it alive, silence means the holder is gone, and claim can simply hand the row out again.

Writes exactly one field. Not attempts, not status, and nothing a consumer reads as progress. It publishes no task-change item, because a renewal is not a lifecycle change — the task did not move.

options.claim is required: renewal is an ownership assertion, so an unfenced one would let anything keep anyone's lease open. The write runs the same guards every other worker-callable write runs, so it declines terminal on a cancelled task, not-my-task on a recreated row, and lost-claim when the caller no longer holds it — including the case that motivated the verb: a renewal that commits after the lease it was extending. Without that arm a late renewal would install a fresh deadline on a row somebody else now holds.

TaskTransitionOptions.adoptLapsedLease is the one opt-out of that last arm, for a claimant that has not started yet — see it for why the choice cannot be made down here.

Throws — never declines — on a non-finite leaseUntil or a missing ticket. Both are programming errors rather than lost races, matching this repo's posture for a numeric argument outside its domain.

If you implement this interface yourself, the obligation is three-sided and the last two are easy to miss. You implement this write; your own claim() must consider expired rows, fence the takeover on the attempt, and settle a row whose abandonment allowance is spent instead of running it; and every ticket-fenced write you accept must refuse a claimant whose lease has already lapsed. A ref that implements only this verb compiles, renews correctly, and silently never recovers anything.

Parameters​
id​

string

leaseUntil​

number

options​

TaskTransitionOptions & object

Returns​

Promise<TaskWriteOutcome>

reportProgress()?​
reportProgress?(
id,
progress,
options
): Promise<TaskWriteOutcome>;

Report a running task's progress: statusNote, a one-line note for task views, and output, a checkpoint of the result so far. The worker's reportProgress tool calls it, for the row its request holds.

Fenced like linkRun: options.claim is required, the row must be in_progress, and the write declines terminal on a finished row, not-my-task on a recreated one, and lost-claim once a reclaim moved the attempt or the lease lapsed. Neither field changes the status.

A checkpoint is the task's output from then on (Task.checkpointed): complete keeps it rather than writing the final result, and a failed attempt keeps it for the next. Publishes progress_reported.

Optional, so a ref written before it keeps compiling; the tool refuses on a board without it.

Parameters​
id​

string

progress​

TaskProgress

options​
claim​

TaskClaimTicket

Returns​

Promise<TaskWriteOutcome>

retry()?​
retry?(id): Promise<TaskWriteOutcome>;

Retry a failed or cancelled task: errored or cancelled back to pending, keeping its id, its steers, its output and items window, and its spend. A failure's error becomes the next attempt's feedback. The grant is counted in the row's retryLedger, the board's one retry count, and the next claim takes a new attempt, whatever maxAttempts had left. Not an ending: no cascade, notice or recorder runs. Publishes retry_requested.

Declines disallowed on a row that hasn't ended or that completed (a completed task's output never changes: file a follow-up), settling on one whose last ending is still owed, dependency-ended on one whose dependency failed or was cancelled, and retry-budget where the board's maxTotalRetries is enforced and spent.

A person's or an app's move: the task tools offer it as an action only. Optional, so a ref written before it keeps compiling; a retry is refused on a board without it.

Parameters​
id​

string

Returns​

Promise<TaskWriteOutcome>

setAssignee()​
setAssignee(id, assignee): Promise<TaskWriteOutcome>;

Set the task's assignee.

Declines on a terminal task (completed / errored / cancelled) — reassigning work that will never run again is a write no caller can act on. Returns unchanged when the assignee already matches, recorded when it is written.

Declines on a running task on a board that dispatches (immutable-assignee). The assignee is what a dispatched task's routing key is derived from, and the child session that key addresses is keyed the moment the work is dispatched. Changing it while the attempt runs does not redirect anything: the work in flight keeps running under the old coordinate, and the new one addresses a session nothing will ever wake. So an in_progress task is refused. A pending or held task has no attempt; its next claim reads the new assignee, so it can change hands.

Parameters​
id​

string

assignee​

string

Returns​

Promise<TaskWriteOutcome>

setKeptOpenBy()?​
setKeptOpenBy?(
id,
keptOpenBy,
options
): Promise<TaskWriteOutcome>;

Record what a running task waits on, or that it waits on nothing again. The claim gate calls it for the request it admitted: at the request's end when the task is not done, and at the next request's admission.

  • keptOpenBy set: the row keeps its claim and drops its lease (leaseUntil), so no reclaim takes it back, unless options.leaseUntil is given. options.answer is that request's result, kept as the output (unless this attempt reported a checkpoint, which stays the output), for the settle that follows.
  • null: the field clears and the task holds a lease again, to options.leaseUntil (required then). The committed span (leaseDurationMs) is the claim's, unchanged.

Fenced like linkRun: options.claim is required, the row must be in_progress, and the write declines terminal, not-my-task or lost-claim otherwise. A clear does not require the row to be waiting: the gate clears only a row it read as waiting, and that two requests never clear one row at once rests on the task session running its notices and messages one at a time, not on this write. Publishes no task-change, as a renewal doesn't, so a screen showing a running row's kept output reads it stale until the row's next change.

Optional, so a ref written before it keeps compiling; the gate then keeps the lease as before.

Parameters​
id​

string

keptOpenBy​

TaskKeptOpenBy | null

options​
answer?​

{ output: unknown; }

answer.output​

unknown

claim​

TaskClaimTicket

hold?​

{ actor: "user" | "system"; ask: { kind: "input" | "approval" | "review"; prompt: string; title?: string; }; due?: number; id: string; openedAt: number; source: { kind: "suspension"; requestId: string; suspensionId: string; }; }

With a wait: the task run's stop for a person, mirrored on the row as a suspension hold in the same write. Refused held while a own hold is open: the stop arm then cancels the stop.

hold.actor​

"user" | "system"

hold.ask​

{ kind: "input" | "approval" | "review"; prompt: string; title?: string; }

hold.ask.kind​

"input" | "approval" | "review"

hold.ask.prompt​

string

hold.ask.title?​

string

hold.due?​

number

hold.id​

string

hold.openedAt​

number

hold.source​

{ kind: "suspension"; requestId: string; suspensionId: string; }

hold.source.kind​

"suspension"

hold.source.requestId​

string

hold.source.suspensionId​

string

leaseUntil?​

number

owesTurn?​

boolean

With "steer": the turn a steer no request took is owed, marked on the row (turnOwed) so the claim can take it when no wake starts it. With null and no leaseUntil: a stopped request gives back the owed turn its admission took; the row drops its lease and owes the turn again.

resume?​

boolean

With null: the run's own resume, which closes the mirror. A later request admitted while the run stays parked passes none and keeps it.

untakeSteersOf?​

string

A stopped request: the steers it took on this attempt are untaken again in the same write, for the turn after it. With a wait set, or a turn given back.

Returns​

Promise<TaskWriteOutcome>

setPriority()​
setPriority(id, priority): Promise<TaskWriteOutcome>;
Parameters​
id​

string

priority​

number

Returns​

Promise<TaskWriteOutcome>

steer()?​
steer?(id, steer): Promise<TaskWriteOutcome>;

Steer an open task: keep steer on the row (Task.steers), for every later attempt to read. Changes nothing else: no status, no claim, no lease, no attempt count, and no ending. A row running nothing while it waits on work it filed (keptOpenBy: "filed") waits on the steer instead, in the same write: a turn is owed for it, which its caller starts.

Declines terminal on a finished row, so a finished task's output never changes, and steer-limit past MAX_STEERS. unchanged for a key already kept. Publishes steered.

Optional, so a ref written before it keeps compiling; a steer is refused on a board without it.

Parameters​
id​

string

steer​

SteerInput

Returns​

Promise<TaskWriteOutcome>

takeNotice()?​
takeNotice?(
id,
notice,
take
): Promise<TaskWriteOutcome>;

Take a notice the row owes, for the onTaskSettled request take.by that is about to deliver it, in one conditional write: a wait's drop (dropNoticeReadByWait) and a take never both go through. unchanged when the row no longer owes it, or another request holds it, other than take.replacing (a taker the caller found has ended). The request that took it clears the marker once its block has run.

Optional: both built-in backings implement it. On a ref without it a notice is admitted with no take, as before.

Parameters​
id​

string

notice​
attempt​

number

ending​

NoticeEnding

take​
by​

string

replacing?​

string

Returns​

Promise<TaskWriteOutcome>

takeSteers()?​
takeSteers?(id, options): Promise<TaskWriteOutcome & object>;

Take the steers that arrived since the claim: mark each steer no request of the claim's attempt has taken as taken by it, in the read named takenIn, by request requestId: the request a stop of it names (untakeSteersOf) to give them back, whatever takenIn says. Read them back with steersTakenIn. A steer this attempt took already, in any read, stays as it is.

Fenced like linkRun: options.claim is required, the row must be in_progress, and the write declines terminal, not-my-task or lost-claim otherwise. unchanged when nothing was untaken. A recorded take names the steers this write took (taken, by id): a concurrent read under the same name, or a re-run of it, took none and names none. Publishes no task-change.

Optional, so a ref written before it keeps compiling.

Parameters​
id​

string

options​
claim​

TaskClaimTicket

requestId​

string

takenIn​

string

Returns​

Promise<TaskWriteOutcome & object>

tellMidwayQuestions()?​
tellMidwayQuestions?(row): Promise<void>;

Tell the filer of row its open midway questions, through the ledger's declared onMidwayQuestion. Present only on a ledger that declares one; askMidway calls it each time a turn asks, a replayed turn included.

Parameters​
row​

Task

Returns​

Promise<void>


TaskFlowPolicy​

A flow policy decides which observations a soon-to-dispatch worker sees on its priorWork slot. The board calls select once per task dispatch with the live ledger view and the task about to run.

Properties​

name​
readonly name: string;

Human-readable label stamped on priorWork.meta.policy.

Methods​

select()​
select(args):
| TaskPriorWork
| Promise<TaskPriorWork>;
Parameters​
args​
collection​

TaskCollectionRef

ctx​

BlockContext

ledger​

ObservationLedgerView

task​

Task

Returns​

| TaskPriorWork | Promise<TaskPriorWork>


TaskNotice​

One notice: plain data, the same whether the ending's writer sends it or the filer's pass sends it again. output rides a completion, error a failure.

Properties​

attempt​
readonly attempt: number;

The attempt that ended.

boardId​
readonly boardId: string;

The ledger the task is on, by id.

cancelled?​
readonly cancelled?: readonly string[];

On a failure or a cancel: the dependents this ending cancelled that share its filer, by id. They owe no notice of their own.

ending​
readonly ending: NoticeEnding;
error?​
readonly error?: string;
output?​
readonly output?: unknown;
taskId​
readonly taskId: string;
waitedOn?​
readonly waitedOn?: true;

The row is waited on: a turn is parked on its ending (read off a marker stored by an older version).


TaskPartitionContext​

What a partition function sees: the running session's server-set identity, and nothing else.

Purpose-built rather than a trimmed block context, because a block context carries request input through more than one handle (the parent's input, and the .input on the sequencer's, the block's own and every target's state ref). A partition read off any of them would let a caller name another conversation's partition. The function may be async, for a value the server keeps elsewhere that it looks up from these ids.

Properties​

lineageId?​
readonly lineageId?: string;

The lineage id the server minted when the running session's record was created, when the host sets one. A session deleted and created again under the same id gets a new one, so sessionId plus this names one incarnation of the session: a partition built from both starts empty for a recreated session instead of inheriting its predecessor's rows. Never written by a caller.

orgId?​
readonly orgId?: string;

The organization the request runs in, when it has one.

sessionId​
readonly sessionId: string;

The running session's id.

tenantId?​
readonly tenantId?: string;

The tenant the request runs under, when the app is multi-tenant.

userId​
readonly userId: string;

The user the session belongs to, whose scope holds the rows.


TaskPriorWork​

Structured value the board stamps on TaskWorkerInput.priorWork. Workers can either consume observations directly or use the pre-rendered narrative (when a policy produced one) as a context blob.

Properties​

meta?​
meta?: object;

Selection metadata for observability / DevTool.

available​
available: number;
policy​
policy: string;
selected​
selected: number;
tokensApprox?​
tokensApprox?: number;
narrative?​
narrative?: string;

Optional pre-rendered prompt-ready summary.

observations​
observations: readonly object[];

TaskProgress​

What a running task's worker reports (reportProgress).

Properties​

output?​
readonly output?: unknown;

A checkpoint of the result so far: the task's output from then on.

statusNote?​
readonly statusNote?: string;

A one-line note for task views. Never the task's status.


TaskSettingsPatch​

The fields a filing may change until the task first starts (ER-4; the brief's fields and the assignee). Each field's rule is the field table's (./field-rules), read inside the write.

Properties​

assignee?​
assignee?: string;

Who works it. A follow-up keeps its root's worker.

context?​
context?: string;

What its worker is told beside the goal.

deps?​
deps?: string[];

Its dependencies, replaced whole. Checked as a filing's are.

goal?​
goal?: string;

What it is for.

held?​
held?: boolean;

Hold the task (true) or release it (false).

ifRevision?​
ifRevision?: number;

Write only while the row is still at this revision (a row stored with none reads as 0): decided inside the write, so an edit decided on an earlier read of the row is declined revision-moved, never written over the newer one. Omitted, the edit lands on whatever the row is now.

input?​
input?: unknown;

Its structured input.

labels?​
labels?: string[];

Its labels, replaced whole.

maxAttempts?​
maxAttempts?: number;

Its attempts.

metadata?​
metadata?: Record<string, unknown>;

Metadata keys merged over its own.

priority?​
priority?: number;

Its priority.

title?​
title?: string;

Its short label.


TaskSettingsSupport​

The setting values a board honours. A plain board honours only the defaults; a board declares more (defineTaskCollection({ settings })) when its hand-over can run them.

Properties​

resultTo?​
readonly resultTo?: readonly TaskResultSetting[];

The resultTo values the board honours. Default: ["filer"].

session?​
readonly session?: readonly TaskSessionSetting[];

The session values the board honours. Default: ["new"].


TaskSpendWrite​

One spend write: a request's live part, or what its ending handed on.

Properties​

admittedAt?​
readonly admittedAt?: number;

When that admission was made: a later one of the same request supersedes an earlier one that never settled.

part​
readonly part: "live" | "settle";

live: what it has spent since its last ending. settle: what an ending handed on.

recovered?​
readonly recovered?: RequestSpend;

What that admission's ledger recovered from the request's log when it was admitted: its pending spend then.

requestId​
readonly requestId: string;

The request admitted for the task.

spend​
readonly spend: RequestSpend;
writer?​
readonly writer?: string;

The admission writing: a request continued after its process died is admitted again, under a new one.


TaskTransitionOptions​

Opt-in guards for every worker-callable lifecycle write-back.

Both guards are evaluated inside the same atomic write that performs the transition, so there is no window between checking and writing. Both are advisory in the sense that matters for containment: a rejected write is skipped and never throws, so a late worker cannot abandon its siblings by losing a race.

It is not silent, and that is the change. The call returns a TaskWriteOutcome; a rejected write yields outcome: "declined" carrying reason — which guard fired — so a caller that wants to know can read it without re-reading the task. A caller that doesn't care may keep ignoring the return value, which is why this stayed source-compatible.

The enumerated failure set is exactly that — a rejected transition and a lost claim. Everything else still throws: a missing task, a store failure, CAS exhaustion, an ordinary bug. This is a containment guard for task-state conflicts, not a blanket error suppressor.

Omit the options entirely (the default for every direct caller) and both methods behave exactly as before, throwing on an illegal transition.

Intended for the substrate's own write-backs — a task board's result recorders, a claim order's claim/execute cycle — where the task may have been settled by someone with better information (a coordinator cancelled it, the worker settled it through its own task tools, a lease reclaim re-queued it for another attempt) while the worker was still running.

Extended by​

Properties​

adoptLapsedLease?​
adoptLapsedLease?: boolean;

Let a renewal take back a row whose lease lapsed while the claim it names stayed intact.

The lease fence declines a ticketed write on a lapsed row because a lapsed lease means the row is the queue's again. That is right for a result — a worker that ran past its lease may have been superseded, and the successor owns the outcome — and it is too strong for a claimant that has not started yet. A task handed to a child session is the case: nothing renews the row between the parent's release and the child's first breath, so a child that waits in the host's queue longer than the lease arrives to a lapsed row that no one has taken — same attempts, same createdAt, same incarnation, still in_progress.

With this set, that renewal is decided by the race instead of by the clock: every other guard still runs inside the same atomic write, so it is recorded only while the identity the ticket names is still the row's, and declines lost-claim the moment a reclaim has moved attempts or the status. Winning the write is the takeover — the caller holds the row for another lease span, on the same attempt.

Opt-in, because the substrate cannot tell the two lapsed claimants apart. A stalled worker whose renewal timer finally fired presents the same evidence as the queued child above, and only the second should take the row back: the first has been running against a row the queue may have re-dispatched. So the caller asserts "I have not started yet", which is something only it knows.

Honoured only on a renewal — the one write that targets in_progress. Passing it to a settlement changes nothing: complete and fail on a lapsed row still decline lost-claim.

claim?​
claim?: TaskClaimTicket;

Record the outcome only if the caller still owns the task it is writing to.

The ticket is minted by the substrate at claim time (ticketForClaim) and names the board, the task, the attempt, and the task's createdAt. It answers two questions the write cannot answer for itself:

  • Is this the task I claimed? Declines not-my-task when the ticket names another board, another task, or a task since recreated under the same id. This is the question a bare attempt number could not ask, which is why it replaced one.
  • Do I still hold it? Declines lost-claim unless task.attempts equals the ticket's attempt and the task is still in_progress. The status half is not belt-and-braces: reclaim() returns a task to pending without advancing attempts, so between a reclaim and the next claim a displaced worker matches the counter by construction — and since held is reachable only from pending, a counter-only guard would let a stale worker silently settle work a coordinator held.

Omit it and no ownership question is asked, which is the correct posture for a coordinator writing to a board it never claimed from.

ifAllowed?​
ifAllowed?: boolean;

Record the outcome only if the task's state machine will accept it.

Declines when the task is already terminal, or when the transition is rejected. Both arms are load-bearing: the state machine treats same-status as allowed, so cancelled → cancelled is legal and terminal, and without the terminal arm an incidental repeat write would clobber the reason and timestamp an explicit settlement recorded.

refuseUntakenSteers?​
refuseUntakenSteers?: boolean;

Decline a complete while the task holds a steer no request of its attempt took, reason untaken-steers. Decided inside the write, so a steer that lands after the caller's own read still holds the task open. Pass it only where something then owes the steer a turn.

viaTool?​
viaTool?: boolean;

A cancel made through a model's updateTask tool. Set by the task tools only, from how the block was built, never from input: the tools are blocks for a model's turn, and an app's or a person's cancel goes through taskToolActions, which never sets it. When the running session is the row's filer, the call's result is how it hears the cancel, so the cancel owes it no notice.

write?​
write?: TaskWriteToken;

Record this write on the task, so the caller can find out afterwards whether it committed — even if this call throws.

Mint one with beginTaskWrite(tasks.get(id)) before the write and read the answer with didWriteLand(tasks.get(id), write) after. The returned TaskWriteOutcome already says what a call that returned did; this covers the path it cannot reach, where the durable write commits and the change announcement then rejects.

Three answers come back, and the third is the point: landed, did not land, or cannot tell. See didWriteLand for the rule and for what a false precisely means.

Correlation is available on the seven methods that take this options object. createTask, createTasks, claim, reclaim and the five field mutators still bump the task's revision but mint no receipt, so a caller of those cannot correlate its own write. Widening means adding an options argument to nine more methods on an already-large interface; it waits for a consumer that needs it.

A TaskCollectionRef written by hand maintains no provenance, and needs no migration to stay correct: absence of a record reads as "cannot tell", not as "your write did not land".


TaskWaitSlot​

What TaskCollectionRef.markWait takes the row's wait slot with (see Task.wait).

Properties​

deadline​
readonly deadline: number;

When the wait resumes with the row still running (epoch ms).

drain?​
readonly drain?: true;

The waiting request is a plan's drain, on a row it handed over (see Task.wait.drain).

gateId​
readonly gateId: string;

The gate the waiting request parks on: unique within its session.

requestId​
readonly requestId: string;

The waiting request, server-derived (ctx.request.identity.id).


TaskWriteToken​

A caller's claim on one write it is about to make.

Minted by beginTaskWrite before the write, from the task the caller holds; presented on TaskTransitionOptions.write. It cannot be minted after the fact — sinceRevision has to be the revision observed before the write for didWriteLand's coverage proofs to mean anything.

Tokens are minted by first-party callers from a task they already hold, and are never accepted from model or tool input: a model naming a write id would be asserting authorship of a write nobody checked.

Properties​

id​
readonly id: string;

Fresh id, recorded on the task if — and only if — the write commits a change.

incarnationId​
readonly incarnationId: string | undefined;

task.incarnationId as observed before the write, or undefined for a task that was not there at mint time, or one that carries no nonce (persisted before this shipped, or written by a ref that maintains no provenance) — task identity across delete/recreate.

A task removed (explicit delete(), or capacity eviction on the resource-backed collection) and recreated under the same id resets revision, so a stale token could otherwise satisfy the coverage arms against a row it never wrote to (the ABA case; ticketNamesTask in claim-ticket.ts guards the identical case on the claim side, keyed on createdAt there rather than a nonce — a pre-existing weakness of its own, out of scope here).

A millisecond clock (createdAt) was tried here first and rejected: a delete-then-recreate under the same id lands in the same millisecond often enough (measured 198/200 pairs) that two different rows share it, which reopens exactly the gap this field exists to close. incarnationId is a fresh id minted per row, not a timestamp, so it does not collide on a fast clock. It remains number | undefined-shaped in spirit — required key, optional value — because a legitimate mint against no task, or against a task that predates this field, has no nonce to record; forcing the value non-optional would mean fabricating one, which would make every correlated write against an already-live legacy task compare a synthetic value against undefined forever and read as a permanent incarnation mismatch, never firming up into a real answer. See didWriteLand's incarnation arm for how a mismatched presence (one side has a nonce, the other does not) is handled: it withholds rather than skipping the check the way a merely-absent value used to.

sinceRevision​
readonly sinceRevision: number | undefined;

task.revision as observed before the write, or undefined for a task that carries none (persisted before this shipped, or written by a ref that maintains no provenance). Absent means the read can only answer from receipt membership.

Type Aliases​

CancelOptions​

type CancelOptions = TaskTransitionOptions & object;

TaskCollectionRef.cancel's options: the guards, and how the cancel was made.

Type Declaration​

via?​
readonly via?: TaskCancelSource;

Written on the row as cancelledVia. Set by the updateTask block from how it was built (a tool, or an action), never from input.

whileHoldOpen?​
readonly whileHoldOpen?: string;

The cancel is a confirm's No (owner 2026-10-25): it lands only while this own hold is open, decided on the committed row in the cancel's own write, as an answer is. Declines answered once the hold has an answer (a yes first, say), and no-such-question for an id that isn't a question or a confirm on the row.


ConfirmOnNo​

type ConfirmOnNo = "cancel" | "continue";

What a confirm's No does: cancel the task (the default), or let the work go on.


DefinedTaskCollection​

type DefinedTaskCollection<TScope> = DefinedResourceCollection & object;

A durable task collection: a DefinedResourceCollection (brand preserved) plus an additive marker identifying it as a task collection and carrying its literal id.

Type Parameters​

TScope​

TScope extends ResourceScope = ResourceScope

Type Declaration​

__taskCollection​
readonly __taskCollection: object;
__taskCollection.cascadeFiled?​
readonly cascadeFiled?: DeclaredFiledCascade;

Present when the ledger's tasks file work elsewhere that a cascade cancels.

__taskCollection.delivery?​
delivery?: DeclaredDelivery;

Present when a board hands the ledger's rows out: each ending owes its filer a notice. Declared, or set by a board with a task dispatcher (markDelegating).

__taskCollection.id​
readonly id: string;
__taskCollection.partitionBy?​
readonly partitionBy?: TaskPartitionFn;

Present when the ledger keeps one set of rows per partition.

__taskCollection.recordEnding?​
readonly recordEnding?: TaskEndingRecorder;

Present when every ending written to the ledger goes through a recorder.

__taskCollection.settings?​
readonly settings?: TaskSettingsSupport;

Present when the ledger honours filing settings beyond the defaults.

scope​
readonly scope: TScope;

The scope the ledger lives in, as declared: a board kept per session ("session") can be reached in another session.


GetOrCreateTaskCollectionOptions​

type GetOrCreateTaskCollectionOptions =
| StateBackingSpec & object
| ResourceBackingSpec & object;

NoticeEnding​

type NoticeEnding = "completed" | "errored" | "retried" | "cancelled";

The endings a filer hears about. retried is read only off a marker an older version stored, which recorded one.


OwnHold​

type OwnHold = z.infer<typeof ownHoldSchema>;

QuestionInit​

type QuestionInit = object;

What a filer or a worker asks: a question's words, or a confirm with what its No does.

Properties​

kind​
readonly kind: "question" | "confirm";
onNo?​
readonly onNo?: ConfirmOnNo;
prompt​
readonly prompt: string;
title?​
readonly title?: string;
untimed?​
readonly untimed?: true;

No deadline, whatever the host's userDeadlineMs: the hold waits until the user answers it or the task is cancelled, so a deadline never releases the task without them. Set by server code only; the task tools never pass it.


RenewalTimer​

type RenewalTimer = (fn, ms) => () => void;

Schedule fn after ms; returns a cancel. Injected in tests.

Parameters​

fn​

() => void

ms​

number

Returns​

() => void


SuspensionHold​

type SuspensionHold = z.infer<typeof suspensionHoldSchema>;

Task​

type Task<TInput, TOutput> = Omit<z.infer<typeof taskSchema>, "input" | "output"> & object;

Generic Task type. Pattern code typically narrows TInput / TOutput via Task<MyInput, MyOutput> to surface payload types at the worker boundary.

Type Parameters​

TInput​

TInput = unknown

TOutput​

TOutput = unknown

Type Declaration​

input?​
input?: TInput;
output?​
output?: TOutput;

TaskBoardCounts​

type TaskBoardCounts = object;

A board's rows by status, as the end of a pass counts them, and the failure retries it granted.

Properties​

cancelled​
cancelled: number;
completed​
completed: number;
errored​
errored: number;
held​
held: number;
in_progress​
in_progress: number;
pending​
pending: number;
retries?​
retries?: number;
total​
total: number;

TaskBoardMeta​

type TaskBoardMeta = object;

One task-board-meta item's value. status is "active" while a pass runs and "completed" once it ends; a pattern over the board may write its own words ("planning"). counts, terminationReason and maxTotalRetries come with the end of a pass.

Properties​

collectionId​
collectionId: string;
counts?​
counts?: TaskBoardCounts;
maxTotalRetries?​
maxTotalRetries?: number | null;
status​
status: string;
terminationReason?​
terminationReason?: string;

TaskCancelSource​

type TaskCancelSource = "tool" | "action";

How a cancel was made, as Task.cancelledVia records it: "tool", a model's updateTask inside its filer's turn; "action", a public updateTask_<board> action, a screen's or an app's.


TaskCapKind​

type TaskCapKind = "total" | "enqueued";

Which bound a TaskCapExceededError reports.


TaskChangeKind​

type TaskChangeKind =
| "added"
| "claimed"
| "completed"
| "errored"
| "retried"
| "retry_requested"
| "held"
| "released"
| "settings_changed"
| "resumed"
| "cancelled"
| "label_changed"
| "metadata_changed"
| "priority_changed"
| "assignee_changed"
| "run_linked"
| "progress_reported"
| "resume_settled"
| "steered"
| "cancel_owed"
| "wait_changed"
| "asked"
| "answered";

Lifecycle transitions a TaskCollection can publish to a UI.


TaskEditField​

type TaskEditField = keyof typeof TASK_FIELD_RULES;

A field the table holds a rule for.


TaskEnding​

type TaskEnding =
| {
kind: "completed";
output: unknown;
}
| {
error: string;
kind: "errored";
}
| {
error: string;
kind: "retried";
}
| {
kind: "cancelled";
reason?: string;
};

How a task ended, as the write that records it describes it.

  • completed: settled with output.
  • errored: failed for good, with error. Also the claim path settling a row whose worker died more times than its allowance.
  • retried: failed with attempts left, so the row is pending again; the error is the attempt's.
  • cancelled: cancelled, with the reason when one was given.

TaskEndingRecorder​

type TaskEndingRecorder = (row, ending) => Task;

A ledger's ending recorder: handed the row as the ending write is about to commit it (status, output and error already the ending's) and the ending, returns the row to write. Only the returned row's metadata is kept; every other field is the transition's, so a recorder cannot move a status or rewrite a result.

Parameters​

row​

Task

ending​

TaskEnding

Returns​

Task


TaskFilingRule​

type TaskFilingRule =
| "questions_not_kept"
| "dependency_not_on_board"
| "dependency_ended"
| "dependency_loop"
| "setting_not_supported"
| "follow_up_takes_no_session"
| "follow_up_takes_no_target"
| "follow_up_takes_no_result_to"
| "conversation_result_one_attempt"
| "setting_not_from_task_session"
| "duplicate_task_id"
| "follow_up_of_unrun"
| "parent_cancelled";

Why a filing (or an edit of one) was refused. The code leads the error's message.


TaskFilter​

type TaskFilter = object;

Filter predicate used by list / count. All conditions are AND'd. Pass { status: ['pending', 'in_progress'] } to match either status.

Properties​

assignee?​
assignee?: string;
cancelOwed?​
cancelOwed?: true;

Match only tasks whose wait is over and still owes its cancel (Task.cancelOwed).

cascadeOwed?​
cascadeOwed?: true;

Match only tasks whose ending still owes its cascade (Task.cascadeOwed).

filedByTask?​
filedByTask?: string;

Match only tasks a given task's request filed (Task.filedByTask).

hasAllLabels?​
hasAllLabels?: string[];

Match tasks that carry every label in this list.

hasLabel?​
hasLabel?: string;
resumeOwed?​
resumeOwed?: true;

Match only tasks whose waiting turn is owed its answer (Task.resumeOwed).

sealed?​
sealed?: Record<string, string | number | boolean>;

Match only tasks whose sealed payload holds each of these keys at this plain value (compared with ===).

status?​
status?: TaskStatus | TaskStatus[];

TaskHandle​

type TaskHandle<TInput, TOutput> = Task<TInput, TOutput> & object;

Task plus a runtime accessor for the items the worker emitted while it held the claim window. Returned from list / get so pattern aggregators (synthesizers, reviewers, replanners) can pick from a worker's natural emissions — messages, sources, tool calls, reasoning — instead of relying solely on task.output.

Mixed staleness contract:

  • Data fields (status, output, goal, ...) are snapshot at the moment list / get returned, matching the older Task read contract. Holding a handle past a mutation reads stale data fields — re-call get(id) to refresh.
  • items() is live — re-reads the response item log on every call. This is intentional so synthesizers running after worker completion pick up emissions that landed during their own pre-execution.

Sync, throw-free. Returns [] when the task has not been claimed yet.

Window: [first claimed event ts, terminal event ts] for this taskId under this collection. Retries do NOT reset the start; all attempts append to the same window. Items the substrate emitted about itself are excluded — task-change, task-board-meta and task-board-recorder-failure — because they are the board's events, not the worker's.

Mutators (claim, createTask, ...) still return raw Task. The just-claimed task has no items in its window yet, so a handle would be empty by construction; re-fetch via get(id) post-completion if a handle is needed.

Type Parameters​

TInput​

TInput = unknown

TOutput​

TOutput = unknown

Type Declaration​

items()​
items(): readonly OutputItem[];
Returns​

readonly OutputItem[]


TaskHold​

type TaskHold = z.infer<typeof taskHoldSchema>;

TaskInit​

type TaskInit<TInput> = object;

Caller-supplied fields when creating a task. id is auto-generated when omitted.

Type Parameters​

TInput​

TInput = unknown

Properties​

assignee?​
assignee?: string;
attachments?​
attachments?: FileContent[];

The brief's files, in reference form. See Task.attachments. Set by the filing path from files it kept for the task (createTask keeps the turn's), never from model input; a caller filing directly through a ref is trusted with it.

causedBy?​
causedBy?: string;
context?​
context?: string;

Readable per-task support text handed to the worker. See Task.context.

deps?​
deps?: string[];
error?​
error?: string;

For a row filed already cancelled because a dependency ended: why, and that dependency (see Task.error, Task.causedBy), as a cascade's cancel writes them, kept only when the row is stored "cancelled" (held: true stores it held, so it keeps neither). Set by a replan filing a task skipped. Never from model input: the task tools build a row's init field by field and leave both out.

filedByTask?​
filedByTask?: string;

The task whose request filed this one (see Task.filedByTask). Set by the filing path from the filer's claim or session, never from model input.

followUpOf?​
followUpOf?: string;

The finished task this one follows up, already resolved to its root (see Task.followUpOf). Set by the createTask tool after it checked the named task; a caller filing directly through a ref is trusted with it.

goal​
goal: string;
held?​
held?: boolean;

File the row held (the start setting): status held, so it doesn't start until something releases it (release, or dispatch on a board that dispatches). Omitted, it starts once its deps have finished.

id?​
id?: string;
input?​
input?: TInput;
labels?​
labels?: string[];
maxAttempts?​
maxAttempts?: number;

Optional retry budget. When set and attempts < maxAttempts, collection.fail(id, ...) re-pends the task (with the error captured as feedback) instead of transitioning to terminal errored. Unset is single-attempt — fail goes terminal.

metadata?​
metadata?: Record<string, unknown>;
priority?​
priority?: number;
questions?​
questions?: QuestionInit[];

Questions the task waits on before it starts: each an own hold (Task.holds) the user answers, a plain question or a confirm (a yes or a no). The task stays pending and starts no attempt until every one is answered, or a deadline the host set passes; every answer joins its brief. Composes with held: both must clear. Refused by name past MAX_STEERS questions or MAX_QUESTION_PROMPT characters.

resultTo?​
resultTo?: TaskResultSetting;

Who hears the result (see Task.resultTo). Omitted is "filer". A "conversation" task has one attempt: maxAttempts unset reads as 1, and any other value is refused at filing.

sealed?​
sealed?: Record<string, unknown>;

The row's server-written payload (see Task.sealed). Never from model input: the task tools build a row's init field by field and leave it out.

session?​
session?: TaskSessionSetting;

Where the task runs (see Task.session). Omitted is "new". A board that can't honour a value refuses the filing, naming the setting (TaskFilingRefusedError): a plain board takes only the default.

status?​
status?: TaskStatus;
target?​
target?: string;

The workstream record the task goes to, by its target (see Task.target): a filing setting, for an assignee that is a workstream's lead. A board whose filer has no such record refuses it.

targetSessionId?​
targetSessionId?: string;

The session target resolved to when the task was filed (see Task.targetSessionId). Written by the board's filing path, never from model input: the task tools build a row's init field by field and leave it out.

title?​
title?: string;

Concise label, distinct from goal. Surfaced as the plan-UI row label.


TaskKeptOpenBy​

type TaskKeptOpenBy = NonNullable<Task["keptOpenBy"]>;

What a running task waits on (Task.keptOpenBy).


TaskPartitionFn​

type TaskPartitionFn = (ctx) => string | Promise<string>;

Names the partition the running context reads and writes. Must return a non-empty string derived from data only the server writes, and the same value for every run of one owner (a session's id alone is reused when a session is deleted and created again, which would hand the new one the old one's rows).

Parameters​

ctx​

TaskPartitionContext

Returns​

string | Promise<string>


TaskResultSetting​

type TaskResultSetting = "filer" | "conversation";

Who hears a task's result: whoever filed it, or the conversation it was filed from (Task.resultTo).


type TaskRunLink = NonNullable<z.infer<typeof taskSchema>["run"]>;

The run link a dispatched attempt writes onto its task — see taskSchema's run.


TaskSessionSetting​

type TaskSessionSetting = "new" | "ongoing";

Where a task runs: a session of its own, or the delegate's ongoing one for the conversation (Task.session).


TaskSpend​

type TaskSpend = z.infer<typeof taskSpendSchema>;

TaskSpendView​

type TaskSpendView = z.infer<typeof taskSpendViewSchema>;

TaskStatus​

type TaskStatus = z.infer<typeof taskStatusSchema>;

@flow-state-dev/orchestration — substrate package for task-shaped work primitives.

Exports the Task schema, the uniform TaskCollectionRef API across both backings (atomic state, resource collection), the standard claim order catalog, the worker contract, and the canonical helpers for composing task loops inside sequencer patterns.

Layering: core → tasks → patterns. Patterns consume this package; this package never imports from patterns.


TaskSteer​

type TaskSteer = z.infer<typeof taskSteerSchema>;

One steer on a task.


TaskWorker​

type TaskWorker<TIn, TOut> = BlockDefinition<any, any, TaskWorkerInput<TIn>, TOut>;

Worker block alias. Any BlockDefinition whose input matches TaskWorkerInput<TIn> is a valid worker. Forward-compat: agents and skills register under the same alias once those systems land.

Type Parameters​

TIn​

TIn = unknown

TOut​

TOut = unknown


TaskWorkerInput​

type TaskWorkerInput<TIn> = Omit<z.infer<typeof taskWorkerInputSchema>, "input"> & object;

Input contract handed to every worker, inferred from taskWorkerInputSchema. input is re-genericized here (the schema types it unknown) so a worker can name its typed payload without a second field list to keep in sync.

Type Parameters​

TIn​

TIn = unknown

Type Declaration​

input?​
input?: TIn;

TaskWriteDeclineReason​

type TaskWriteDeclineReason =
| "immutable-assignee"
| "terminal"
| "not-my-task"
| "disallowed"
| "lost-claim"
| "follow-up"
| "started"
| "unknown-status"
| "untaken-steers"
| "steer-limit"
| "open-question"
| "answered"
| "no-such-question"
| "settling"
| "dependency-ended"
| "retry-budget"
| "revision-moved";

Why a write was refused. Resolved in a fixed precedence order — immutable-assignee → terminal → not-my-task → disallowed → lost-claim — so a decline where two conditions hold always reports the same one, and two callers cannot render two different messages for the same refusal.

  • immutable-assignee — the board dispatches work, and an attempt holds the task (in_progress): its dispatch is keyed by the assignee it was claimed with. A pending or held task can change hands.
  • terminal — the task had already reached completed / errored / cancelled. The majority of the exposure, but not all of it.
  • not-my-task — the presented claim names a different board, a different task, or a task since recreated under the same id. The write targets a row the caller never held.
  • disallowed — the state machine rejects the move from a non-terminal status (pending → errored, held → errored).
  • lost-claim — the presented claim names this task but no longer owns it: it was reclaimed or re-queued while the caller was working, or its lease ran out while it was still in_progress.

Why not-my-task sits above disallowed, and below terminal. The guard runs inside the atomic write, but a decline aborts that write before it is attempted, so the conditional write never conflicts, never refreshes, and never re-runs the guard. Whatever basis the caller resolved the collection on is therefore the basis the arms read. Two of the four arms are safe under that: not-my-task reads no mutable task state at all, and terminality is absorbing, so a task observed terminal on any basis is terminal. disallowed is not — it compares two statuses, and a stale pending makes an ordinary settlement look illegal. Left last, the ownership arm would report disallowed on one interleaving and not-my-task on another for the same cross-task write: accidental protection, not a guarantee, and a reason no caller can act on.

Where immutable-assignee sits. It holds only for in_progress, and terminal only for a settled task, so the two never compete and either order reports the same reason. It reads the status inside the atomic write, like terminal, so a claim that lands first is what the decline reports.


TaskWriteOutcome​

type TaskWriteOutcome =
| {
note?: string;
outcome: "recorded";
}
| {
outcome: "unchanged";
}
| {
outcome: "declined";
reason: TaskWriteDeclineReason;
status: TaskStatus;
};

What a write actually did.

Produced inside the same atomic write that made the decision, so the verdict cannot race the write it describes and no caller has to re-read task state to find out what happened. Re-deriving it from a post-write read would be a check-after-write race — the thing the guards were moved inside the CAS to avoid.

Three variants, and all three are load-bearing:

  • recorded — a task field changed. Every verb that moves a task through its lifecycle also emits a task-change item; renewLease is the one exception and emits none, because a renewal is not a lifecycle change — the task did not move, the holder only said "still here". Do not wait on a task-change to observe a renewal; read leaseUntil.
  • unchanged — the desired state already held, so nothing was written and no task-change item was emitted. This is a task-level outcome: on the resource backing the underlying updateState still runs, so a resource_change may still fire (as it always has).
  • declined — the write was refused, carrying why and the status observed inside the write. A decline is a value, not an error: it never throws.

unchanged is not a nicety. Without it an idempotent setAssignee (the assignee already matches) would have to report recorded, claiming a write that did not happen — the same dishonesty write outcomes exist to remove.

Discarding the return value is a supported way to call these methods. The substrate's own containment write-backs do exactly that, which is what keeps the behaviour intact: reporting a decline and acting on one are deliberately separate.

Union Members​

Type Literal​
{
note?: string;
outcome: "recorded";
}
note?​
note?: string;

What a wrapping ref adds for the caller about what followed the write, when the write held but its follow-on didn't (a steer kept, but no turn could start for it). A tool that reports the write says it.

outcome​
outcome: "recorded";

Type Literal​
{
outcome: "unchanged";
}

Type Literal​
{
outcome: "declined";
reason: TaskWriteDeclineReason;
status: TaskStatus;
}
outcome​
outcome: "declined";
reason​
reason: TaskWriteDeclineReason;
status​
status: TaskStatus;

The status the task was in when the write was refused.

Variables​

DEFAULT_MAX_ABANDONMENTS​

const DEFAULT_MAX_ABANDONMENTS: 3 = 3;

How many times a task's work may be handed back out after its worker died before the substrate stops recovering it and settles the row errored.

Three, because a bad deploy or a cycling node strands a job once or twice. That covers the class while still bounding duplicate side effects at a small constant — and because this is its OWN budget, a job with no maxAttempts gets these three rather than the zero a shared budget would leave it.


fifoClaimOrder​

const fifoClaimOrder: ClaimOrder;

flowPolicy​

const flowPolicy: object;

Built-in flow policies. Import as flowPolicy and call as flowPolicy.recentTrajectory({ n: 8 }). The naming follows the [domain]Verb capability-helper convention.

Type Declaration​

allCompleted​
allCompleted: typeof allCompleted;
ancestors​
ancestors: typeof ancestors;
compact​
compact: typeof compact;
custom​
custom: typeof custom;
declaredDepsOnly​
declaredDepsOnly: typeof declaredDepsOnly;
none​
none: typeof none;
recentTrajectory​
recentTrajectory: typeof recentTrajectory;

ownHoldSchema​

const ownHoldSchema: z.ZodObject<{
actor: z.ZodEnum<["user", "system"]>;
ask: z.ZodObject<{
kind: z.ZodEnum<["question", "confirm", "external"]>;
onNo: z.ZodOptional<z.ZodEnum<["cancel", "continue"]>>;
prompt: z.ZodString;
title: z.ZodOptional<z.ZodString>;
}, "strip", z.ZodTypeAny, {
kind: "confirm" | "external" | "question";
onNo?: "cancel" | "continue";
prompt: string;
title?: string;
}, {
kind: "confirm" | "external" | "question";
onNo?: "cancel" | "continue";
prompt: string;
title?: string;
}>;
due: z.ZodOptional<z.ZodNumber>;
id: z.ZodString;
midway: z.ZodOptional<z.ZodLiteral<true>>;
openedAt: z.ZodNumber;
source: z.ZodObject<{
closedBy: z.ZodArray<z.ZodUnion<[z.ZodObject<{
by: z.ZodLiteral<"answer">;
}, "strip", z.ZodTypeAny, {
by: "answer";
}, {
by: "answer";
}>, z.ZodObject<{
by: z.ZodLiteral<"event">;
event: z.ZodString;
key: z.ZodString;
}, "strip", z.ZodTypeAny, {
by: "event";
event: string;
key: string;
}, {
by: "event";
event: string;
key: string;
}>]>, "many">;
kind: z.ZodLiteral<"task">;
}, "strip", z.ZodTypeAny, {
closedBy: (
| {
by: "answer";
}
| {
by: "event";
event: string;
key: string;
})[];
kind: "task";
}, {
closedBy: (
| {
by: "answer";
}
| {
by: "event";
event: string;
key: string;
})[];
kind: "task";
}>;
}, "strip", z.ZodTypeAny, {
actor: "system" | "user";
ask: {
kind: "confirm" | "external" | "question";
onNo?: "cancel" | "continue";
prompt: string;
title?: string;
};
due?: number;
id: string;
midway?: true;
openedAt: number;
source: {
closedBy: (
| {
by: "answer";
}
| {
by: "event";
event: string;
key: string;
})[];
kind: "task";
};
}, {
actor: "system" | "user";
ask: {
kind: "confirm" | "external" | "question";
onNo?: "cancel" | "continue";
prompt: string;
title?: string;
};
due?: number;
id: string;
midway?: true;
openedAt: number;
source: {
closedBy: (
| {
by: "answer";
}
| {
by: "event";
event: string;
key: string;
})[];
kind: "task";
};
}>;

A question, a confirm or an external wait: the task's own hold, with no run parked behind it.


priorityClaimOrder​

const priorityClaimOrder: ClaimOrder;

suspensionHoldSchema​

const suspensionHoldSchema: z.ZodObject<{
actor: z.ZodEnum<["user", "system"]>;
ask: z.ZodObject<{
kind: z.ZodEnum<["approval", "review", "input"]>;
prompt: z.ZodString;
title: z.ZodOptional<z.ZodString>;
}, "strip", z.ZodTypeAny, {
kind: "approval" | "input" | "review";
prompt: string;
title?: string;
}, {
kind: "approval" | "input" | "review";
prompt: string;
title?: string;
}>;
due: z.ZodOptional<z.ZodNumber>;
id: z.ZodString;
openedAt: z.ZodNumber;
source: z.ZodObject<{
kind: z.ZodLiteral<"suspension">;
requestId: z.ZodString;
suspensionId: z.ZodString;
}, "strip", z.ZodTypeAny, {
kind: "suspension";
requestId: string;
suspensionId: string;
}, {
kind: "suspension";
requestId: string;
suspensionId: string;
}>;
}, "strip", z.ZodTypeAny, {
actor: "system" | "user";
ask: {
kind: "approval" | "input" | "review";
prompt: string;
title?: string;
};
due?: number;
id: string;
openedAt: number;
source: {
kind: "suspension";
requestId: string;
suspensionId: string;
};
}, {
actor: "system" | "user";
ask: {
kind: "approval" | "input" | "review";
prompt: string;
title?: string;
};
due?: number;
id: string;
openedAt: number;
source: {
kind: "suspension";
requestId: string;
suspensionId: string;
};
}>;

A task run's parked stop for a person, mirrored on its task.


TASK_FIELD_RULES​

const TASK_FIELD_RULES: object;

Every field updateTask may change, with its one rule.

Type Declaration​

assignee​
readonly assignee: "until-start";
attachments​
readonly attachments: "until-start";
cancel​
readonly cancel: "until-finish";
context​
readonly context: "until-start";
deps​
readonly deps: "until-start";
goal​
readonly goal: "until-start";
held​
readonly held: "until-start";
input​
readonly input: "until-start";
labels​
readonly labels: "until-start";
maxAttempts​
readonly maxAttempts: "until-start";
message​
readonly message: "until-finish";
metadata​
readonly metadata: "until-start";
priority​
readonly priority: "until-start";
title​
readonly title: "until-start";

taskHoldSchema​

const taskHoldSchema: z.ZodUnion<[z.ZodObject<{
actor: z.ZodEnum<["user", "system"]>;
ask: z.ZodObject<{
kind: z.ZodEnum<["approval", "review", "input"]>;
prompt: z.ZodString;
title: z.ZodOptional<z.ZodString>;
}, "strip", z.ZodTypeAny, {
kind: "approval" | "input" | "review";
prompt: string;
title?: string;
}, {
kind: "approval" | "input" | "review";
prompt: string;
title?: string;
}>;
due: z.ZodOptional<z.ZodNumber>;
id: z.ZodString;
openedAt: z.ZodNumber;
source: z.ZodObject<{
kind: z.ZodLiteral<"suspension">;
requestId: z.ZodString;
suspensionId: z.ZodString;
}, "strip", z.ZodTypeAny, {
kind: "suspension";
requestId: string;
suspensionId: string;
}, {
kind: "suspension";
requestId: string;
suspensionId: string;
}>;
}, "strip", z.ZodTypeAny, {
actor: "system" | "user";
ask: {
kind: "approval" | "input" | "review";
prompt: string;
title?: string;
};
due?: number;
id: string;
openedAt: number;
source: {
kind: "suspension";
requestId: string;
suspensionId: string;
};
}, {
actor: "system" | "user";
ask: {
kind: "approval" | "input" | "review";
prompt: string;
title?: string;
};
due?: number;
id: string;
openedAt: number;
source: {
kind: "suspension";
requestId: string;
suspensionId: string;
};
}>, z.ZodObject<{
actor: z.ZodEnum<["user", "system"]>;
ask: z.ZodObject<{
kind: z.ZodEnum<["question", "confirm", "external"]>;
onNo: z.ZodOptional<z.ZodEnum<["cancel", "continue"]>>;
prompt: z.ZodString;
title: z.ZodOptional<z.ZodString>;
}, "strip", z.ZodTypeAny, {
kind: "confirm" | "external" | "question";
onNo?: "cancel" | "continue";
prompt: string;
title?: string;
}, {
kind: "confirm" | "external" | "question";
onNo?: "cancel" | "continue";
prompt: string;
title?: string;
}>;
due: z.ZodOptional<z.ZodNumber>;
id: z.ZodString;
midway: z.ZodOptional<z.ZodLiteral<true>>;
openedAt: z.ZodNumber;
source: z.ZodObject<{
closedBy: z.ZodArray<z.ZodUnion<[z.ZodObject<{
by: ...;
}, "strip", z.ZodTypeAny, {
by: ...;
}, {
by: ...;
}>, z.ZodObject<{
by: ...;
event: ...;
key: ...;
}, "strip", z.ZodTypeAny, {
by: ...;
event: ...;
key: ...;
}, {
by: ...;
event: ...;
key: ...;
}>]>, "many">;
kind: z.ZodLiteral<"task">;
}, "strip", z.ZodTypeAny, {
closedBy: (
| {
by: "answer";
}
| {
by: "event";
event: string;
key: string;
})[];
kind: "task";
}, {
closedBy: (
| {
by: "answer";
}
| {
by: "event";
event: string;
key: string;
})[];
kind: "task";
}>;
}, "strip", z.ZodTypeAny, {
actor: "system" | "user";
ask: {
kind: "confirm" | "external" | "question";
onNo?: "cancel" | "continue";
prompt: string;
title?: string;
};
due?: number;
id: string;
midway?: true;
openedAt: number;
source: {
closedBy: (
| {
by: "answer";
}
| {
by: "event";
event: string;
key: string;
})[];
kind: "task";
};
}, {
actor: "system" | "user";
ask: {
kind: "confirm" | "external" | "question";
onNo?: "cancel" | "continue";
prompt: string;
title?: string;
};
due?: number;
id: string;
midway?: true;
openedAt: number;
source: {
closedBy: (
| {
by: "answer";
}
| {
by: "event";
event: string;
key: string;
})[];
kind: "task";
};
}>]>;

One hold on a task.


taskSchema​

const taskSchema: z.ZodObject<{
abandonments: z.ZodOptional<z.ZodNumber>;
askedInTurn: z.ZodOptional<z.ZodNumber>;
assignee: z.ZodOptional<z.ZodString>;
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">>;
attempts: z.ZodDefault<z.ZodNumber>;
cancelledVia: z.ZodOptional<z.ZodEnum<["tool", "action"]>>;
cancelOwed: z.ZodOptional<z.ZodBoolean>;
cascadeOwed: z.ZodOptional<z.ZodObject<{
due: z.ZodNumber;
endedAt: z.ZodOptional<z.ZodNumber>;
}, "strip", z.ZodTypeAny, {
due: number;
endedAt?: number;
}, {
due: number;
endedAt?: number;
}>>;
causedBy: z.ZodOptional<z.ZodString>;
checkpointed: z.ZodOptional<z.ZodLiteral<true>>;
claimedBy: z.ZodOptional<z.ZodObject<{
requestId: z.ZodString;
sessionId: z.ZodString;
tenantId: z.ZodOptional<z.ZodString>;
}, "strip", z.ZodTypeAny, {
requestId: string;
sessionId: string;
tenantId?: string;
}, {
requestId: string;
sessionId: string;
tenantId?: string;
}>>;
completedAt: z.ZodOptional<z.ZodNumber>;
context: z.ZodOptional<z.ZodString>;
createdAt: z.ZodNumber;
createdBy: z.ZodOptional<z.ZodString>;
deps: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
error: z.ZodOptional<z.ZodString>;
feedback: z.ZodOptional<z.ZodString>;
filedByTask: z.ZodOptional<z.ZodString>;
filedUnder: z.ZodOptional<z.ZodObject<{
orgId: z.ZodOptional<z.ZodString>;
tenantId: z.ZodOptional<z.ZodString>;
}, "strip", z.ZodTypeAny, {
orgId?: string;
tenantId?: string;
}, {
orgId?: string;
tenantId?: string;
}>>;
filer: z.ZodOptional<z.ZodObject<{
requestId: z.ZodOptional<z.ZodString>;
sessionId: z.ZodString;
}, "strip", z.ZodTypeAny, {
requestId?: string;
sessionId: string;
}, {
requestId?: string;
sessionId: string;
}>>;
followUpOf: z.ZodOptional<z.ZodString>;
goal: z.ZodString;
holds: z.ZodOptional<z.ZodArray<z.ZodUnion<[z.ZodObject<{
actor: z.ZodEnum<["user", "system"]>;
ask: z.ZodObject<{
kind: z.ZodEnum<...>;
prompt: z.ZodString;
title: z.ZodOptional<...>;
}, "strip", z.ZodTypeAny, {
kind: ... | ... | ...;
prompt: string;
title?: ... | ...;
}, {
kind: ... | ... | ...;
prompt: string;
title?: ... | ...;
}>;
due: z.ZodOptional<z.ZodNumber>;
id: z.ZodString;
openedAt: z.ZodNumber;
source: z.ZodObject<{
kind: z.ZodLiteral<...>;
requestId: z.ZodString;
suspensionId: z.ZodString;
}, "strip", z.ZodTypeAny, {
kind: "suspension";
requestId: string;
suspensionId: string;
}, {
kind: "suspension";
requestId: string;
suspensionId: string;
}>;
}, "strip", z.ZodTypeAny, {
actor: "system" | "user";
ask: {
kind: "approval" | "input" | "review";
prompt: string;
title?: string;
};
due?: number;
id: string;
openedAt: number;
source: {
kind: "suspension";
requestId: string;
suspensionId: string;
};
}, {
actor: "system" | "user";
ask: {
kind: "approval" | "input" | "review";
prompt: string;
title?: string;
};
due?: number;
id: string;
openedAt: number;
source: {
kind: "suspension";
requestId: string;
suspensionId: string;
};
}>, z.ZodObject<{
actor: z.ZodEnum<["user", "system"]>;
ask: z.ZodObject<{
kind: z.ZodEnum<...>;
onNo: z.ZodOptional<...>;
prompt: z.ZodString;
title: z.ZodOptional<...>;
}, "strip", z.ZodTypeAny, {
kind: ... | ... | ...;
onNo?: ... | ... | ...;
prompt: string;
title?: ... | ...;
}, {
kind: ... | ... | ...;
onNo?: ... | ... | ...;
prompt: string;
title?: ... | ...;
}>;
due: z.ZodOptional<z.ZodNumber>;
id: z.ZodString;
midway: z.ZodOptional<z.ZodLiteral<true>>;
openedAt: z.ZodNumber;
source: z.ZodObject<{
closedBy: z.ZodArray<..., ...>;
kind: z.ZodLiteral<...>;
}, "strip", z.ZodTypeAny, {
closedBy: ...[];
kind: "task";
}, {
closedBy: ...[];
kind: "task";
}>;
}, "strip", z.ZodTypeAny, {
actor: "system" | "user";
ask: {
kind: "confirm" | "external" | "question";
onNo?: "cancel" | "continue";
prompt: string;
title?: string;
};
due?: number;
id: string;
midway?: true;
openedAt: number;
source: {
closedBy: ...[];
kind: "task";
};
}, {
actor: "system" | "user";
ask: {
kind: "confirm" | "external" | "question";
onNo?: "cancel" | "continue";
prompt: string;
title?: string;
};
due?: number;
id: string;
midway?: true;
openedAt: number;
source: {
closedBy: ...[];
kind: "task";
};
}>]>, "many">>;
id: z.ZodString;
incarnationId: z.ZodOptional<z.ZodString>;
input: z.ZodOptional<z.ZodUnknown>;
keptOpenBy: z.ZodOptional<z.ZodNullable<z.ZodEnum<["suspended", "filed", "steer"]>>>;
labels: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
leaseDurationMs: z.ZodOptional<z.ZodNumber>;
leaseUntil: z.ZodOptional<z.ZodNumber>;
maxAttempts: z.ZodOptional<z.ZodNumber>;
metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
output: z.ZodOptional<z.ZodUnknown>;
priority: z.ZodOptional<z.ZodNumber>;
resultTo: z.ZodOptional<z.ZodEnum<["filer", "conversation"]>>;
resumeOwed: z.ZodOptional<z.ZodBoolean>;
retryLedger: z.ZodOptional<z.ZodObject<{
deniedByBudget: z.ZodBoolean;
granted: z.ZodNumber;
}, "strip", z.ZodTypeAny, {
deniedByBudget: boolean;
granted: number;
}, {
deniedByBudget: boolean;
granted: number;
}>>;
retryPending: z.ZodOptional<z.ZodLiteral<true>>;
revision: z.ZodOptional<z.ZodNumber>;
run: z.ZodOptional<z.ZodObject<{
attempt: z.ZodNumber;
requestId: z.ZodString;
sessionId: z.ZodString;
startedAt: z.ZodOptional<z.ZodNumber>;
}, "strip", z.ZodTypeAny, {
attempt: number;
requestId: string;
sessionId: string;
startedAt?: number;
}, {
attempt: number;
requestId: string;
sessionId: string;
startedAt?: number;
}>>;
sealed: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
session: z.ZodOptional<z.ZodEnum<["new", "ongoing"]>>;
spend: z.ZodOptional<z.ZodNullable<z.ZodObject<{
requests: z.ZodDefault<z.ZodArray<z.ZodObject<{
admittedAt: z.ZodDefault<...>;
harness: z.ZodDefault<...>;
harnessModel: z.ZodDefault<...>;
live: z.ZodDefault<...>;
model: z.ZodDefault<...>;
recovered: z.ZodDefault<...>;
requestId: z.ZodString;
settled: z.ZodDefault<...>;
writer: z.ZodDefault<...>;
}, "strip", z.ZodTypeAny, {
admittedAt: ... | ...;
harness: ... | ...;
harnessModel: ... | ...;
live: ... | ...;
model: ... | ...;
recovered: ... | ...;
requestId: string;
settled: ...[];
writer: ... | ...;
}, {
admittedAt?: ... | ... | ...;
harness?: ... | ... | ...;
harnessModel?: ... | ... | ...;
live?: ... | ... | ...;
model?: ... | ... | ...;
recovered?: ... | ... | ...;
requestId: string;
settled?: ... | ...;
writer?: ... | ... | ...;
}>, "many">>;
}, "strip", z.ZodTypeAny, {
requests: object[];
}, {
requests?: object[];
}>>>;
startedAt: z.ZodOptional<z.ZodNumber>;
status: z.ZodEnum<["pending", "in_progress", "held", "completed", "errored", "cancelled"]>;
statusNote: z.ZodOptional<z.ZodString>;
steers: z.ZodOptional<z.ZodArray<z.ZodObject<{
answers: z.ZodOptional<z.ZodString>;
at: z.ZodNumber;
by: z.ZodOptional<z.ZodString>;
from: z.ZodEnum<["filer", "user", "board", "service"]>;
id: z.ZodString;
message: z.ZodString;
takenBy: z.ZodOptional<z.ZodNumber>;
takenFor: z.ZodOptional<z.ZodString>;
takenIn: z.ZodOptional<z.ZodString>;
}, "strip", z.ZodTypeAny, {
answers?: string;
at: number;
by?: string;
from: "board" | "filer" | "service" | "user";
id: string;
message: string;
takenBy?: number;
takenFor?: string;
takenIn?: string;
}, {
answers?: string;
at: number;
by?: string;
from: "board" | "filer" | "service" | "user";
id: string;
message: string;
takenBy?: number;
takenFor?: string;
takenIn?: string;
}>, "many">>;
target: z.ZodOptional<z.ZodString>;
targetSessionId: z.ZodOptional<z.ZodString>;
title: z.ZodOptional<z.ZodString>;
turn: z.ZodOptional<z.ZodNumber>;
turnOwed: z.ZodOptional<z.ZodLiteral<true>>;
updatedAt: z.ZodNumber;
wait: z.ZodOptional<z.ZodObject<{
deadline: z.ZodNumber;
drain: z.ZodOptional<z.ZodLiteral<true>>;
gateId: z.ZodString;
lapsed: z.ZodOptional<z.ZodLiteral<true>>;
requestId: z.ZodOptional<z.ZodString>;
}, "strip", z.ZodTypeAny, {
deadline: number;
drain?: true;
gateId: string;
lapsed?: true;
requestId?: string;
}, {
deadline: number;
drain?: true;
gateId: string;
lapsed?: true;
requestId?: string;
}>>;
writeLog: z.ZodOptional<z.ZodArray<z.ZodObject<{
id: z.ZodString;
revision: z.ZodNumber;
}, "strip", z.ZodTypeAny, {
id: string;
revision: number;
}, {
id: string;
revision: number;
}>, "many">>;
writeLogTruncated: z.ZodOptional<z.ZodBoolean>;
}, "strip", z.ZodTypeAny, {
abandonments?: number;
askedInTurn?: number;
assignee?: string;
attachments?: object[];
attempts: number;
cancelledVia?: "action" | "tool";
cancelOwed?: boolean;
cascadeOwed?: {
due: number;
endedAt?: number;
};
causedBy?: string;
checkpointed?: true;
claimedBy?: {
requestId: string;
sessionId: string;
tenantId?: string;
};
completedAt?: number;
context?: string;
createdAt: number;
createdBy?: string;
deps?: string[];
error?: string;
feedback?: string;
filedByTask?: string;
filedUnder?: {
orgId?: string;
tenantId?: string;
};
filer?: {
requestId?: string;
sessionId: string;
};
followUpOf?: string;
goal: string;
holds?: (
| {
actor: "system" | "user";
ask: {
kind: "approval" | "input" | "review";
prompt: string;
title?: string;
};
due?: number;
id: string;
openedAt: number;
source: {
kind: "suspension";
requestId: string;
suspensionId: string;
};
}
| {
actor: "system" | "user";
ask: {
kind: "confirm" | "external" | "question";
onNo?: "cancel" | "continue";
prompt: string;
title?: string;
};
due?: number;
id: string;
midway?: true;
openedAt: number;
source: {
closedBy: (... | ...)[];
kind: "task";
};
})[];
id: string;
incarnationId?: string;
input?: unknown;
keptOpenBy?: "filed" | "steer" | "suspended" | null;
labels?: string[];
leaseDurationMs?: number;
leaseUntil?: number;
maxAttempts?: number;
metadata?: Record<string, unknown>;
output?: unknown;
priority?: number;
resultTo?: "conversation" | "filer";
resumeOwed?: boolean;
retryLedger?: {
deniedByBudget: boolean;
granted: number;
};
retryPending?: true;
revision?: number;
run?: {
attempt: number;
requestId: string;
sessionId: string;
startedAt?: number;
};
sealed?: Record<string, unknown>;
session?: "new" | "ongoing";
spend?: | {
requests: object[];
}
| null;
startedAt?: number;
status: | "cancelled"
| "completed"
| "errored"
| "held"
| "in_progress"
| "pending";
statusNote?: string;
steers?: object[];
target?: string;
targetSessionId?: string;
title?: string;
turn?: number;
turnOwed?: true;
updatedAt: number;
wait?: {
deadline: number;
drain?: true;
gateId: string;
lapsed?: true;
requestId?: string;
};
writeLog?: object[];
writeLogTruncated?: boolean;
}, {
abandonments?: number;
askedInTurn?: number;
assignee?: string;
attachments?: object[];
attempts?: number;
cancelledVia?: "action" | "tool";
cancelOwed?: boolean;
cascadeOwed?: {
due: number;
endedAt?: number;
};
causedBy?: string;
checkpointed?: true;
claimedBy?: {
requestId: string;
sessionId: string;
tenantId?: string;
};
completedAt?: number;
context?: string;
createdAt: number;
createdBy?: string;
deps?: string[];
error?: string;
feedback?: string;
filedByTask?: string;
filedUnder?: {
orgId?: string;
tenantId?: string;
};
filer?: {
requestId?: string;
sessionId: string;
};
followUpOf?: string;
goal: string;
holds?: (
| {
actor: "system" | "user";
ask: {
kind: "approval" | "input" | "review";
prompt: string;
title?: string;
};
due?: number;
id: string;
openedAt: number;
source: {
kind: "suspension";
requestId: string;
suspensionId: string;
};
}
| {
actor: "system" | "user";
ask: {
kind: "confirm" | "external" | "question";
onNo?: "cancel" | "continue";
prompt: string;
title?: string;
};
due?: number;
id: string;
midway?: true;
openedAt: number;
source: {
closedBy: (... | ...)[];
kind: "task";
};
})[];
id: string;
incarnationId?: string;
input?: unknown;
keptOpenBy?: "filed" | "steer" | "suspended" | null;
labels?: string[];
leaseDurationMs?: number;
leaseUntil?: number;
maxAttempts?: number;
metadata?: Record<string, unknown>;
output?: unknown;
priority?: number;
resultTo?: "conversation" | "filer";
resumeOwed?: boolean;
retryLedger?: {
deniedByBudget: boolean;
granted: number;
};
retryPending?: true;
revision?: number;
run?: {
attempt: number;
requestId: string;
sessionId: string;
startedAt?: number;
};
sealed?: Record<string, unknown>;
session?: "new" | "ongoing";
spend?: | {
requests?: object[];
}
| null;
startedAt?: number;
status: | "cancelled"
| "completed"
| "errored"
| "held"
| "in_progress"
| "pending";
statusNote?: string;
steers?: object[];
target?: string;
targetSessionId?: string;
title?: string;
turn?: number;
turnOwed?: true;
updatedAt: number;
wait?: {
deadline: number;
drain?: true;
gateId: string;
lapsed?: true;
requestId?: string;
};
writeLog?: object[];
writeLogTruncated?: boolean;
}>;

The base Task schema.


taskSpendSchema​

const taskSpendSchema: z.ZodObject<{
requests: z.ZodDefault<z.ZodArray<z.ZodObject<{
admittedAt: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
harness: z.ZodDefault<z.ZodNullable<z.ZodString>>;
harnessModel: z.ZodDefault<z.ZodNullable<z.ZodString>>;
live: z.ZodDefault<z.ZodNullable<z.ZodArray<z.ZodObject<{
billing: ...;
costUsd: ...;
inputTokens: ...;
kind: ...;
outputTokens: ...;
runs: ...;
source: ...;
unreported: ...;
}, "strip", z.ZodTypeAny, {
billing: ...;
costUsd: ...;
inputTokens: ...;
kind: ...;
outputTokens: ...;
runs: ...;
source: ...;
unreported: ...;
}, {
billing?: ...;
costUsd?: ...;
inputTokens?: ...;
kind: ...;
outputTokens?: ...;
runs?: ...;
source: ...;
unreported?: ...;
}>, "many">>>;
model: z.ZodDefault<z.ZodNullable<z.ZodString>>;
recovered: z.ZodDefault<z.ZodNullable<z.ZodArray<z.ZodObject<{
billing: ...;
costUsd: ...;
inputTokens: ...;
kind: ...;
outputTokens: ...;
runs: ...;
source: ...;
unreported: ...;
}, "strip", z.ZodTypeAny, {
billing: ...;
costUsd: ...;
inputTokens: ...;
kind: ...;
outputTokens: ...;
runs: ...;
source: ...;
unreported: ...;
}, {
billing?: ...;
costUsd?: ...;
inputTokens?: ...;
kind: ...;
outputTokens?: ...;
runs?: ...;
source: ...;
unreported?: ...;
}>, "many">>>;
requestId: z.ZodString;
settled: z.ZodDefault<z.ZodArray<z.ZodObject<{
billing: z.ZodDefault<...>;
costUsd: z.ZodDefault<...>;
inputTokens: z.ZodDefault<...>;
kind: z.ZodEnum<...>;
outputTokens: z.ZodDefault<...>;
runs: z.ZodDefault<...>;
source: z.ZodString;
unreported: z.ZodDefault<...>;
}, "strip", z.ZodTypeAny, {
billing: ... | ... | ...;
costUsd: ... | ...;
inputTokens: number;
kind: ... | ...;
outputTokens: number;
runs: number;
source: string;
unreported: number;
}, {
billing?: ... | ... | ... | ...;
costUsd?: ... | ... | ...;
inputTokens?: ... | ...;
kind: ... | ...;
outputTokens?: ... | ...;
runs?: ... | ...;
source: string;
unreported?: ... | ...;
}>, "many">>;
writer: z.ZodDefault<z.ZodNullable<z.ZodString>>;
}, "strip", z.ZodTypeAny, {
admittedAt: number | null;
harness: string | null;
harnessModel: string | null;
live: object[] | null;
model: string | null;
recovered: object[] | null;
requestId: string;
settled: object[];
writer: string | null;
}, {
admittedAt?: number | null;
harness?: string | null;
harnessModel?: string | null;
live?: object[] | null;
model?: string | null;
recovered?: object[] | null;
requestId: string;
settled?: object[];
writer?: string | null;
}>, "many">>;
}, "strip", z.ZodTypeAny, {
requests: object[];
}, {
requests?: object[];
}>;

Task.spend: the task's requests, the one that last reported its harness or model last.


taskSpendViewSchema​

const taskSpendViewSchema: z.ZodObject<{
costUsd: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
harness: z.ZodNullable<z.ZodString>;
inputTokens: z.ZodNullable<z.ZodNumber>;
live: z.ZodBoolean;
model: z.ZodNullable<z.ZodString>;
outputTokens: z.ZodNullable<z.ZodNumber>;
unreported: z.ZodBoolean;
}, "strip", z.ZodTypeAny, {
costUsd?: number | null;
harness: string | null;
inputTokens: number | null;
live: boolean;
model: string | null;
outputTokens: number | null;
unreported: boolean;
}, {
costUsd?: number | null;
harness: string | null;
inputTokens: number | null;
live: boolean;
model: string | null;
outputTokens: number | null;
unreported: boolean;
}>;

What a reader shows of a task's spend (taskSpendView): listTasks action rows carry it.


taskStatusSchema​

const taskStatusSchema: z.ZodEnum<["pending", "in_progress", "held", "completed", "errored", "cancelled"]>;

taskSteerSchema​

const taskSteerSchema: z.ZodObject<{
answers: z.ZodOptional<z.ZodString>;
at: z.ZodNumber;
by: z.ZodOptional<z.ZodString>;
from: z.ZodEnum<["filer", "user", "board", "service"]>;
id: z.ZodString;
message: z.ZodString;
takenBy: z.ZodOptional<z.ZodNumber>;
takenFor: z.ZodOptional<z.ZodString>;
takenIn: z.ZodOptional<z.ZodString>;
}, "strip", z.ZodTypeAny, {
answers?: string;
at: number;
by?: string;
from: "board" | "filer" | "service" | "user";
id: string;
message: string;
takenBy?: number;
takenFor?: string;
takenIn?: string;
}, {
answers?: string;
at: number;
by?: string;
from: "board" | "filer" | "service" | "user";
id: string;
message: string;
takenBy?: number;
takenFor?: string;
takenIn?: string;
}>;

One steer on a task. Server-written by the steer verb, never by a patch; each field but the take marks is written once.

Functions​

allowedTransitionsFrom()​

function allowedTransitionsFrom(from): readonly (
| "completed"
| "errored"
| "cancelled"
| "pending"
| "in_progress"
| "held")[];

Returns the set of statuses reachable from from in a single transition. Terminal statuses return an empty array.

Parameters​

from​

| "completed" | "errored" | "cancelled" | "pending" | "in_progress" | "held"

Returns​

readonly ( | "completed" | "errored" | "cancelled" | "pending" | "in_progress" | "held")[]


beginTaskWrite()​

function beginTaskWrite(task): TaskWriteToken;

Open a correlated write against task.

Call it before the write, pass the result on the write's options, and hand the same token to didWriteLand afterwards:

const write = beginTaskWrite(tasks.get(taskId));
try {
await tasks.complete(taskId, output, { ifAllowed: true, claim, write });
} catch (err) {
// The write may already have committed — the throw came from the change
// announcement, which runs after the durable write resolves.
switch (didWriteLand(tasks.get(taskId), write)) {
case true: throw new PostCommitFailure(err); // real: report it
case false: return; // never landed: routine
case undefined: throw new UndeterminedWrite(err); // say so; never guess
}
}

task is allowed to be undefined — a caller reading a task that is not there still gets a usable token, which then answers "cannot tell" rather than forcing a null check at every call site.

Parameters​

task​

Task | undefined

Returns​

TaskWriteToken


claimDisposition()​

function claimDisposition(
task,
now,
maxAbandonments
): "claim" | "settle-abandoned";

What the claim write should do with a row isClaimable admitted — evaluated inside the atomic write, against committed state.

  • claim — hand it out. The ordinary case, and every pending row.
  • settle-abandoned — its worker died more times than the allowance permits, so the write settles it errored right here rather than handing out another duplicate execution. Settling in the claim write is what keeps the deadlock closed: a row left in_progress with nobody on it still counts as in-flight, and the board would then never report drained or blocked.

Parameters​

task​

Task

now​

number

maxAbandonments​

number

Returns​

"claim" | "settle-abandoned"


committedLeaseSpan()​

function committedLeaseSpan(task): number | undefined;

The lease duration the claim committed to — how long the claimant may be gone, as the claim wrote it, not how much of it is left.

The one number two mechanisms both rest on, which is why it is a function rather than a line in each of them: the renewal driver derives its cadence from it (startLeaseRenewal), and a claimant taking a lapsed row back renews for it, so the two would disagree the moment either copy was edited. Not the lease that is left — that is leaseUntil - now, a different number, and conflating them shrinks a late-starting driver's cadence to a write storm.

Read from leaseDurationMs, with leaseUntil - updatedAt as the fallback for a row claimed before that field existed. The subtraction is exact only at the instant of the claim, which is what made storing the number necessary: setPriority, addLabel, removeLabel and patchMetadata are supported on an in_progress row and all move updatedAt while leaving leaseUntil alone, so on a legacy row a coordinator's relabel shortens what this reports — and past the deadline drives it non-positive. Both consumers treat that as "cannot reason about this row" rather than as a short lease, which is the same conservative answer those rows got before this field existed.

undefined when the task holds no lease deadline — nothing is claiming to be alive on it, so there is no committed span to report even if the duration a past claim wrote is still on the row. A non-positive result is returned as-is; what to do about it is the caller's: the driver goes inert, the takeover refuses.

Parameters​

task​

Task

Returns​

number | undefined


defineTaskCollection()​

function defineTaskCollection<TInputSchema, TScope>(options): DefinedTaskCollection<TScope>;

Define a durable, resource-backed task collection. See module doc.

Type Parameters​

TInputSchema​

TInputSchema extends ZodTypeAny = ZodTypeAny

TScope​

TScope extends ResourceScope = ResourceScope

Parameters​

options​

DefineTaskCollectionOptions<TInputSchema, TScope>

Returns​

DefinedTaskCollection<TScope>


didWriteLand()​

function didWriteLand(task, token): boolean | undefined;

Did the write this token was minted for commit a change to task?

  • true — it committed. The receipt is in the record.
  • false — it committed nothing. Either it never landed, or it was a no-op (provenance is stamped only on a write that changed a field, so those two are deliberately one answer — see the note below).
  • undefined — cannot tell. No provenance on this record, no baseline on the token, the token was minted for a different incarnation of this id, or the receipt may have been evicted.

undefined is a first-class result, not a shrug, and a consumer must surface it as its own condition rather than collapsing it into either boolean. Collapsing it back into false reintroduces exactly the confident wrong answer this primitive exists to remove.

The rule, and why the order is load-bearing​

A bounded log evicts, so a receipt that was never written and one that was written and later dropped both present as "a log without my id". Answering false to both would be a confident lie to a delayed caller. Two independent proofs rescue it, and neither subsumes the other:

  • A retained receipt at or below my baseline proves the window still reaches back past the moment I started, because eviction is oldest-first and revisions only ever increase. Covers a busy task.
  • The log has never dropped anything proves the window covers everything by construction. Covers a fresh task, whose log is usually empty — on a first attempt nothing has minted a receipt yet, so the first proof cannot fire and this is the only one that can.

Membership is tested first, ahead of the baseline guard: a present receipt proves the write landed whatever the token knows, and a legacy task's first upgraded write has a receipt but no baseline.

The incarnation check runs second, ahead of every arm below it that reasons about revision. A task removed (explicit delete(), or capacity eviction on the resource-backed collection) and recreated under the same id resets revision — a replacement can restart at the token's own baseline, which would otherwise satisfy "nothing committed since the baseline" for a write that landed on the row that no longer exists (the ABA case; ticketNamesTask in claim-ticket.ts guards the identical case on the claim side). It cannot run ahead of membership: a receipt actually present in the current row's log proves that row committed this exact write, whatever the token's stale incarnationId says.

The check withholds whenever either side lacks a nonce, and only compares for inequality once both are present — deliberately not the plain token.incarnationId !== task.incarnationId this arm used to read for createdAt. createdAt could compare directly because it is a required field on Task — the token's copy of it was undefined only when the task itself was undefined at mint time, a case the baseline guard below already catches on its own. incarnationId has no such guarantee: a task can be undefined on either side independently (not there yet at mint time, or there but predating this field) — and a plain inequality on undefined values is false when both sides are absent, which would let a both-legacy pair (a task that predates this field, correlated by a token that read it before the write) fall straight through to the revision arms. That reopens the exact ABA gap this field exists to close: a legacy task deleted and recreated under the same id resets revision without minting a nonce on the replacement unless the replacement went through buildInitialTask, and during a rolling deploy the old code that deletes and recreates it may not. Requiring presence on both sides before comparing treats "one side has a nonce and the other doesn't" — and "neither does" — as its own mismatch and withholds — never a confident false — which also closes a token assembled by hand rather than minted by beginTaskWrite: leaving incarnationId off (or undefined) no longer buys a free pass through this arm the way an omitted createdAt once did.

Sound, deliberately not complete​

It never returns a wrong answer, but it can withhold one: a write that never landed, on a task whose later receipts then evicted everything at or below the baseline, answers undefined where an unbounded log would have said false. Closing that would mean retaining evicted ids, which defeats bounding. Withholding an answer is the only direction this can afford to err in.

What false means, precisely​

"My write changed nothing on this task" — which subsumes both "it never landed" and "the task was already in the state I asked for". That is the question this answers. It is not on its own enough to decide whether to contain or rethrow an error; a caller that needs to know why a write changed nothing reads the declined verdict on TaskWriteOutcome.

Parameters​

task​

Task | undefined

token​

TaskWriteToken

Returns​

boolean | undefined


externalHoldOf()​

function externalHoldOf(row):
| {
actor: "user" | "system";
ask: {
kind: "question" | "confirm" | "external";
onNo?: "cancel" | "continue";
prompt: string;
title?: string;
};
due?: number;
id: string;
midway?: true;
openedAt: number;
source: {
closedBy: (
| {
by: "answer";
}
| {
by: "event";
event: string;
key: string;
})[];
kind: "task";
};
}
| undefined;

The row's open external wait, if it has one: a turn opens at most one.

Parameters​

row​

Pick<Task, "status" | "holds" | "steers">

Returns​

| { actor: "user" | "system"; ask: { kind: "question" | "confirm" | "external"; onNo?: "cancel" | "continue"; prompt: string; title?: string; }; due?: number; id: string; midway?: true; openedAt: number; source: { closedBy: ( | { by: "answer"; } | { by: "event"; event: string; key: string; })[]; kind: "task"; }; } | undefined


extractTaskItems()​

function extractTaskItems(
items,
collectionId,
taskId
): readonly OutputItem[];

Items emitted under (collectionId, taskId), in stream order. Returns [] when the task was never claimed. Unions all attempts of a re-claimed task.

Parameters​

items​

readonly OutputItem[]

collectionId​

string

taskId​

string

Returns​

readonly OutputItem[]


filedWorkKeepsOpen()​

function filedWorkKeepsOpen(ledger, taskId): boolean;

Whether any row on ledger that taskId filed still holds it. Filters at the source (filedByTask) and stops at the first that holds.

Parameters​

ledger​

TaskCollectionRef

taskId​

string

Returns​

boolean


formatPriorWork()​

function formatPriorWork(priorWork): string;

Pretty-print prior-work observations for a worker prompt. Workers that don't want to interpret the structured shape can call this directly to get a Markdown-ish list. The default rendering is [#seq] toolName(args) → result | error plus a header noting which task the observation came from.

Parameters​

priorWork​

TaskPriorWork

Returns​

string


getOrCreateTaskCollection()​

function getOrCreateTaskCollection<TInput, TOutput>(options): Promise<TaskCollectionRef<TInput, TOutput>>;

Build a TaskCollectionRef against the chosen backing. The factory does not allocate the underlying storage — the caller is expected to have declared it (sequencer state schema, resource collection definition).

Example (on a sequencer's state):

const tasks = await getOrCreateTaskCollection({
ctx,
backing: "state",
state: ctx.sequencer!,
collectionId: "my-plan",
});

Throws, before touching any storage, when backing is not "state" or "resource", or when state is present but empty.

Async: the resource backing hydrates a sync read-mirror at construction (see createResourceBackedTaskCollection). The state backing builds synchronously, but the factory is uniformly async so callers await it regardless of backing.

Type Parameters​

TInput​

TInput = unknown

TOutput​

TOutput = unknown

Parameters​

options​

GetOrCreateTaskCollectionOptions

Returns​

Promise<TaskCollectionRef<TInput, TOutput>>


holdActorOf()​

function holdActorOf(row): "user" | "system" | undefined;

Who row waits on now, the one reading of a hold's actor: "user" while any open hold is a person's (a question, a confirm, a run's stop for a person), else "system" while an external wait is open, else undefined. A reader that says "waiting on a user" asks for "user"; one that only needs "nothing in a drain moves it" asks for any.

Parameters​

row​

Pick<Task, "status" | "holds" | "steers">

Returns​

"user" | "system" | undefined


isClaimable()​

function isClaimable(
task,
lookup,
now
): boolean;

The one admission predicate — "should the claim path look at this row?".

Shared by all three producers that used to answer it independently: the claim path, the board's wake probe (task-board/shared.ts), and the ready-task preview (blocks/select-next-ready-task.ts). Move a subset and a board recovers rows it never wakes for, or wakes for work it will not take.

It answers admission only. What to do with an admitted row — re-dispatch it, or settle it because its abandonment allowance is spent — is claimDisposition's question, decided inside the atomic write against committed state. Folding disposition in here is what produced an earlier contradiction: both backings filter candidates through eligibility before the write, so a row the predicate excluded could never reach the branch that was supposed to settle it.

There is deliberately no attempts arm. maxAttempts is optional and shouldRetryOnFail returns false without one, so an "attempts remain" arm would make an ordinary task unrecoverable after its first attempt — the feature off by default unless every caller opted into retries.

A held row is never admitted, whichever board or claim order drains the collection: held is not pending, so it starts only once something releases it. Nor is a row with an open hold: a question, a confirm, or a task run's stop for a person. A running row that owes a turn on its same attempt (owesTurn: its last question answered, or a steer no request took) is: the claim is that turn's start.

now is a parameter rather than a captured clock because the wake probe has none of its own.

Parameters​

task​

Task

lookup​

(id) => Task | undefined

now​

number

Returns​

boolean


isExternalHold()​

function isExternalHold(hold): hold is { actor: "user" | "system"; ask: { kind: "question" | "confirm" | "external"; onNo?: "cancel" | "continue"; prompt: string; title?: string }; due?: number; id: string; midway?: true; openedAt: number; source: { closedBy: ({ by: "answer" } | { by: "event"; event: string; key: string })[]; kind: "task" } };

Whether hold is an external wait: the running turn waits on something outside the board. Reads an unparsed hold as isOwnHold does.

Parameters​

hold​
ask​

{ kind: string; }

ask.kind​

string

source​

{ kind: string; }

source.kind​

string

Returns​

hold is { actor: "user" | "system"; ask: { kind: "question" | "confirm" | "external"; onNo?: "cancel" | "continue"; prompt: string; title?: string }; due?: number; id: string; midway?: true; openedAt: number; source: { closedBy: ({ by: "answer" } | { by: "event"; event: string; key: string })[]; kind: "task" } }


isTerminalStatus()​

function isTerminalStatus(status): boolean;

True when the status is terminal (no further transitions allowed).

Parameters​

status​

| "completed" | "errored" | "cancelled" | "pending" | "in_progress" | "held"

Returns​

boolean


isTransitionAllowed()​

function isTransitionAllowed(from, to): boolean;

True when from → to is permitted by the state machine. Same-status is allowed (idempotent updates).

Parameters​

from​

| "completed" | "errored" | "cancelled" | "pending" | "in_progress" | "held"

to​

| "completed" | "errored" | "cancelled" | "pending" | "in_progress" | "held"

Returns​

boolean


leaseLapsed()​

function leaseLapsed(task, now): boolean;

The one subtraction this whole mechanism rests on: an in_progress row whose lease deadline has already passed.

One fact, two readings. The queue reads it as "this row is available" (isClaimable); the holder reads it as "this row is no longer mine" (transitionDeclineReason's fence). They are the same comparison on the same committed row, so nothing has to be scheduled and nothing has to agree with anything — there is no window between them to get wrong.

Scoped to in_progress on purpose: the lease governs a running row and nothing else.

!= null rather than truthiness: a row persisted without a lease is not a lapsed one.

Parameters​

task​

Task

now​

number

Returns​

boolean


lockedFields()​

function lockedFields(task, fields): (
| "input"
| "goal"
| "title"
| "context"
| "attachments"
| "deps"
| "metadata"
| "priority"
| "message"
| "held"
| "cancel"
| "maxAttempts"
| "assignee"
| "labels")[];

The fields of fields the row's state no longer allows, by the table: every field on a finished row, and every until-start field on a row that has started. Empty when each may change now.

Parameters​

task​

Task

fields​

readonly ( | "input" | "goal" | "title" | "context" | "attachments" | "deps" | "metadata" | "priority" | "message" | "held" | "cancel" | "maxAttempts" | "assignee" | "labels")[]

Returns​

( | "input" | "goal" | "title" | "context" | "attachments" | "deps" | "metadata" | "priority" | "message" | "held" | "cancel" | "maxAttempts" | "assignee" | "labels")[]


noticeMetadata()​

function noticeMetadata(notice, task): object;

The metadata a notice's line is emitted with, so its item says which task ended and how without its words being parsed: ctx.emit.message(noticeText(notice, task), { metadata: noticeMetadata(notice, task) }).

Parameters​

notice​

TaskNotice

task​

The row's goal (or title), as noticeText takes it.

goal​

string

title?​

string

Returns​

object

taskNotice​
taskNotice: NoticeLine;

noticeText()​

function noticeText(notice, task): string;

A notice in words, for the turn it wakes or the line it lands as: the task, how it ended, and what came back.

Parameters​

notice​

TaskNotice

task​

The row's goal (or title) and its assignee.

assignee?​

string

goal​

string

title?​

string

Returns​

string


onTaskChangeFor()​

function onTaskChangeFor(collectionId): (item) => boolean;

Wake filter matching task-change data items for a specific collection. Returns false for every other item type and for task-change items targeting a different collection. Cheap: two equality checks plus a single field read.

A RuntimeItem predicate is a valid wakeOn (that slot is OutputItem).

Parameters​

collectionId​

string

Returns​

(item) => boolean

Example​

.waitForCondition(
whenBoardClaimable(collection),
{
timeoutMs: Math.max(idlePollMs * 100, 50),
wakeOn: onTaskChangeFor(collection.collectionId),
}
)

openHolds()​

function openHolds(row): (
| {
actor: "user" | "system";
ask: {
kind: "input" | "approval" | "review";
prompt: string;
title?: string;
};
due?: number;
id: string;
openedAt: number;
source: {
kind: "suspension";
requestId: string;
suspensionId: string;
};
}
| {
actor: "user" | "system";
ask: {
kind: "question" | "confirm" | "external";
onNo?: "cancel" | "continue";
prompt: string;
title?: string;
};
due?: number;
id: string;
midway?: true;
openedAt: number;
source: {
closedBy: (
| {
by: "answer";
}
| {
by: "event";
event: string;
key: string;
})[];
kind: "task";
};
})[];

Open questions, the one predicate (ER-8): what row waits on now, oldest first. None on an ended row: a cancel closes every question. A task's own question is open while no steer carries its id; a suspension question, while it is on the row.

Parameters​

row​

Pick<Task, "status" | "holds" | "steers">

Returns​

( | { actor: "user" | "system"; ask: { kind: "input" | "approval" | "review"; prompt: string; title?: string; }; due?: number; id: string; openedAt: number; source: { kind: "suspension"; requestId: string; suspensionId: string; }; } | { actor: "user" | "system"; ask: { kind: "question" | "confirm" | "external"; onNo?: "cancel" | "continue"; prompt: string; title?: string; }; due?: number; id: string; midway?: true; openedAt: number; source: { closedBy: ( | { by: "answer"; } | { by: "event"; event: string; key: string; })[]; kind: "task"; }; })[]


parseNotice()​

function parseNotice(item): NoticeLine | undefined;

The notice a message item is the line of, or undefined for any other item: read off the metadata noticeMetadata put on it, or, for a line stored before that, off its words. A client reads which task ended and how from this, never by matching noticeText's wording itself.

Parameters​

item​

A stored or streamed item: a message's metadata and content.

content?​

readonly object[]

metadata?​

Readonly<Record<string, unknown>>

role?​

string

type?​

string

Returns​

NoticeLine | undefined


recordEnding()​

function recordEnding(
row,
ending,
recording?
): Task;

Record an ending: the row to write in the one write that records it, with the notice it owes marked. An ending that owes none comes back unchanged.

Orchestration's own recorder on a board that hands rows out: every write that records an ending there runs it inside that write.

Parameters​

row​

Task

The row as the ending's write builds it.

ending​

TaskEnding

What the ending was.

recording?​

NoticeRecording

What the write knows about a cancel.

Returns​

Task


resolveResourceCollection()​

function resolveResourceCollection(ctx, key): ResourceCollectionRef<JsonObject, ScopeType> | undefined;

Resolve a resource collection ref from the unified resource registry: the running context's, or another session's ({ resources: ctx.resources.at({ session }) }).

Parameters​

ctx​

Pick<BlockContext, "resources">

key​

string

Returns​

ResourceCollectionRef<JsonObject, ScopeType> | undefined


spendAfterWrite()​

function spendAfterWrite(task, write):
| {
requests: object[];
}
| undefined;

The row's spend after write, or undefined when it changes nothing (a live part equal to the one stored). Pure: both backings run it inside their write, against the committed row.

Parameters​

task​

Pick<Task, "spend">

write​

TaskSpendWrite

Returns​

| { requests: object[]; } | undefined


startLeaseRenewal()​

function startLeaseRenewal(options): LeaseRenewalDriver;

Start renewing claimedTask's lease until LeaseRenewalDriver.stop.

The span is the one the claim committed, not the one that is left. committedLeaseSpan, shared with the claim gate's takeover so the two cannot read one lease differently. Deriving it from leaseUntil - now instead would let a driver that starts late shrink its own cadence: a valid one-second claim reached 990 ms late would read a 10 ms span and derive a 3.33 ms cadence from it, which is the write storm the lease minimum exists to prevent, rebuilt out of a perfectly valid claim.

The span sets the cadence; the lease that is left sets the phase. Those are two different numbers and conflating them breaks a healthy worker. A driver that starts late and then waits a full span / RENEWAL_DIVISOR schedules its first renewal after the lease it is extending — the same 1,000 ms claim reached 990 ms late would first write at ~1,323 ms against a lease that died at 1,000 — so the fence would decline it and a healthy worker would lose its row. So the first tick is phased against the remaining lease and every tick after it uses the committed span: one early write, then the normal cadence.

And the promise it makes carries its condition. Renewal keeps a healthy worker's claim when the driver starts with more lease left than one store write takes to commit. Below that it does not, and nothing can — no timer and no inline call beats a deadline that arrives sooner than the store answers, and the substrate cannot know a custom store's latency to name the constant that would. Under that window the worker loses the row and its work is re-run, which is inside the mechanism's stated bound rather than beside it.

Parameters​

options​

LeaseRenewalOptions

Returns​

LeaseRenewalDriver


taskSpendView()​

function taskSpendView(task):
| {
costUsd?: number | null;
harness: string | null;
inputTokens: number | null;
live: boolean;
model: string | null;
outputTokens: number | null;
unreported: boolean;
}
| null;

A task's spend, folded for a reader, or null when the task never ran in a request of its own. Every request counts, every attempt's included; a request's live part counts until its ending settles it.

An admission whose process died never settles: its live part stays. Once a later admission of the same request has written, that part is superseded: it counts less what the next admission recovered from the log (that one reports those itself; a block that never finished logged nothing, so what it spent is only here), and it no longer reads as running. An older next admission that recorded nothing recovered drops its model calls and keeps its harness runs whole. A predecessor's ending that is only late replaces its live part with what it settles, so nothing counts twice. live is never true on a terminal row either. costUsd sums the charges vendors reported, over the same parts, and is null when none did.

Parameters​

task​

Pick<Task, "spend"> & Partial<Pick<Task, "status">>

Returns​

| { costUsd?: number | null; harness: string | null; inputTokens: number | null; live: boolean; model: string | null; outputTokens: number | null; unreported: boolean; } | null


ticketForClaim()​

function ticketForClaim(
collectionId,
claimed,
partition?
): TaskClaimTicket;

Mint a ticket for a task the caller has just claimed.

Pass the task returned by claim(), never the pre-claim task: attempts is incremented by the claim, so a ticket built from a createTask() result names an attempt nobody holds and every write presenting it is refused.

partition is the claiming ref's own (TaskCollectionRef.partition), on a partitioned ledger.

Parameters​

collectionId​

string

claimed​

Task

partition?​

string

Returns​

TaskClaimTicket


toEmittedTask()​

function toEmittedTask<TInput, TOutput>(task): Task<TInput, TOutput>;

Project a task for client emission — the whole row minus SERVER_ONLY_TASK_FIELDS.

Applied where the data-item payload is built, because schema membership is itself a publication: the collection factory spreads the post-mutation row into a task-change data item and a board can mark that stream client-visible, so a field on Task reaches a browser with no consumer required.

Unconditional by design — redaction must not depend on a caller's visibility flag, since the board that matters already sets client: true.

Type Parameters​

TInput​

TInput

TOutput​

TOutput

Parameters​

task​

Task<TInput, TOutput>

Returns​

Task<TInput, TOutput>


withLeaseRenewal()​

function withLeaseRenewal<T>(options): Promise<T>;

Run run while renewing the claim's lease, stopping on every path out.

The convenience form of startLeaseRenewal, for a caller driving claim by hand whose whole use of the claim fits in one callback.

Do not settle the task outside run. Renewal stops the moment run returns, so a complete() or fail() issued after it is a ticket-fenced write on a lease nobody is holding open — one slow store round trip and the fence refuses a healthy worker's result, the task is recovered, and its side effects run twice. Either settle inside run, or use startLeaseRenewal directly and stop() in a finally that closes after the settlement, which is what every first-party seam does.

run receives the signal already composed — options.signal (when you passed one) or lease loss, whichever fires first. Hand it straight to the work; there is nothing left to combine.

It hands over the composition rather than the bare lease signal because the narrower one is a trap in this exact shape. options.signal stops the driver, not the work, so a caller given only the lease signal writes a worker that keeps running and keeps spending after its request is cancelled, against a claim it is no longer renewing. That is not a mistake a reader makes by ignoring the contract — it is the one they make by following the shape of the arguments. The helper holds both signals already, so it is the right place for the composition to happen once instead of at every call site.

Type Parameters​

T​

T

Parameters​

options​

LeaseRenewalOptions & object

Returns​

Promise<T>