Tools and HITL
Define typed tools, expose them to the loop, and pause for human input.
Tools are how the model asks your app to do something. Yolk gives you schema-backed registration and protocol events; your app decides which tools are available and how risky calls are approved.
Define a tool
Use makeTool with Effect Schema so validation is the source of truth.
import { Effect, Schema } from 'effect'
import { makeTool } from '@yolk-sdk/agent/tools'
const EchoParams = Schema.Struct({ text: Schema.String })
export const echoTool = makeTool({
name: 'echo',
description: 'Echo text.',
parameters: EchoParams,
output: Schema.Struct({ text: Schema.String }),
access: 'read',
execute: ({ params }) => Effect.succeed({ output: { text: params.text } })
})Optional invalidParamsMessage: (error: Schema.SchemaError) => string customizes the
model-visible validation text. Only decoding parameters (through its JSON codec) invokes it, and
the decode error is passed through unwrapped. Default:
Invalid ${name} arguments: ${String(error)}, followed by one line per object that names its
unknown keys and lists the allowed keys, and one line per number or boolean argument sent as a JSON
string, naming the string and, when it is one, the literal to send. Custom callbacks can keep that
hint with withToolArgumentsErrorHint(message, error); the wrong-type lines need the error Yolk
passed in, not one from your own decode. In Effect 4, SchemaError extends native Error, but do
not default to .message: that drops the SchemaError(...) wrapper required by this tool-message
contract. Existing (error: unknown) => string callbacks remain assignable.
Typed outputs and file fields
A tool's typed output is its result contract (ADR 0013):
- With
output(an Effect Schema that encodes without services),executereturns{ output }. Yolk encodes it withSchema.toCodecJson(output)intostructuredContent, which code mode scripts receive as declared. A value that does not encode (or does not encode to plain JSON) fails the call without the value in the error. - The model sees
render(value, files)when you pass it (optional), else a string output as is, else the compact JSON of the encoding with file fields shown as file labels. - Without
output,executereturns{ content }(text, and file parts fromfilePartFromBytes); scripts get its text only. - File fields are
ToolFilein the output schema: returnnew FileBytes({ bytes, name, mimeType })(view: truealso shows the model an image, audio or document), ornew FileStored({ fileId, name, mimeType, size })for a file the host already wrote to the store (checked withstore.head, never read).resolveToolsstores the bytes through itsfilesoption, and the encoding holds aFileRef{ fileId, name, mimeType, size }or aFileUnavailable{ unavailable, name, mimeType }(Move files between tools).ToolFilebelongs only inoutput. resolveToolschecks every successful result of a tool with an output schema through its registration'sdecodeOutput(excess properties rejected, plain JSON only) and passes on the checked value; a mismatched value is dropped with a warning that names only the tool, so scripts reject the call while the model still sees the content.makeToolsetsdecodeOutputfromoutput; raw registrations that setdef.outputSchemapasstoolOutputDecoder(schema), or resolution fails withoutput_validation_required.- With explicit type arguments, the typed form takes three:
makeTool<Context, typeof Params, typeof Output>.
Migration note: returning a raw ToolResult from execute still works in this canary but is
deprecated; move to { output } or { content } (Migration).
Optional arguments, null, and unknown keys
The advertised ToolDef.parameters describe the schema's JSON codec, so Schema.optional(X)
reaches the model as X | null, and models often send null for fields they do not use. Tool
arguments decode through Schema.toCodecJson(parameters):
nullonSchema.optional(X)is treated as omitted, andSchema.withDecodingDefaultstill applies.Schema.optional(Schema.NullOr(X))keepsnull; use it only whennullmeans something different from omission, such as clearing a value.- The
nullmember advertised forSchema.optional(X)carries$comment: toolJsonSchemaOmittedNullComment('yolk:null-means-omitted', a stable value from@yolk-sdk/agent/protocol), a standard annotation validators ignore. It marks thisnullas "not sent", unlike the identical-lookingnullofSchema.optionalKey(Schema.NullOr(X))or a third-party MCP schema. The Claude provider uses it to show such fields to the model asX(named optional schemas included); othernulls keep their meaning. The other providers receive the schema without the marker. Tools served by the@yolk-sdk/mcpserver keep it in their listing. Input and interaction response schemas never carry it: user responses decode with the response schema itself, which rejectsnullonSchema.optional(X), although the descriptor still advertisesanyOf [X, null]there: UI clients omit an empty optional field rather than sendnull. - Required non-nullable fields still reject
nullwith a model-visible validation error. - Non-finite numbers (
"NaN","Infinity","-Infinity") are rejected. Declare number parameters asSchema.FiniteorSchema.Int: a bareSchema.Numberadvertises those strings. - Where the wire schema takes only a number or boolean, a value sent as a JSON string is rejected,
and the error names the string and, when the schema takes it, the unquoted literal to send. No
line is added for a string the schema could take. For example:
Argument "offset" must be a JSON number, but it was the string "120": send 120 without quotes. - Unknown keys are rejected at any depth with a model-visible validation error. Parameters are
advertised as closed objects, and silently dropping a key would let the model believe it set
something (a filter, a start time) that was ignored. The error names the key and lists the
allowed ones, for example
Unknown argument "start". Allowed arguments: id, note.One exception: Effect parsesSchema.Struct({})as any object, so only a root empty struct is checked. Nested, useEmptyToolParamsor a declared struct.
resolveTools also drops null on properties advertised as optional without null, such as
Schema.optionalKey(X) fields or raw MCP schemas, before any tool sees the call. It never touches
undeclared keys: a null on an unknown key, including another union member's field, is rejected
like a value, with a hint listing the allowed keys. If you dispatch
registrations without resolveTools, apply omitNullOptionalToolArguments(def.parameters, params)
from @yolk-sdk/agent/tools yourself.
Resolve tools for a request
Group tools into modules, resolve them for a request context, then pass definitions to the loop.
import { Effect } from 'effect'
import { makeToolExecutorLayer, resolveTools } from '@yolk-sdk/agent/tools'
const module = { id: 'local', tools: [echoTool] }
const toolSet = await Effect.runPromise(resolveTools([module], requestContext))
const ToolExecutorLayer = makeToolExecutorLayer(toolSet)Pass toolSet.tools into run/runRuntime. Provide ToolExecutorLayer alongside your provider, loop config, and context transformer layers. Build a custom ToolExecutor layer only when you need advanced dispatch.
Defer rarely used tools
With many tools (for example several MCP servers), declare the rarely used ones with
loading: 'deferred'. They stay out of provider requests until the model loads them, so they cost
no context (ADR 0007).
const listIssues = makeTool<HostContext, typeof ListIssuesParams>({
name: 'list_issues',
description: 'List issues of a repository.',
parameters: ListIssuesParams,
access: 'read',
loading: 'deferred',
execute: ({ params }) => listIssuePage(params) // host-owned
})- When any tool is deferred,
resolveToolsadds the packagetool_searchtool. The model searches by what it needs; the result loads the best matches, which are declared from the next request on. Opt out withresolveTools(modules, context, { toolSearch: false })or register your owntool_search. - Activation is read from
tool_searchresults in the transcript, never stored, so redelivered and resumed steps declare the same tools. Loading a tool changes the declared tools, which start the request, so that request misses the prompt cache once; later requests reuse the new prefix. Prefer code mode scripts for exploratory use. - Deferral saves context, not authority: approval-gated tools keep their approval, and an allowed deferred tool still runs when called by name.
loadingapplies to model-callable tools only (a type error oncallableBy: 'codemode').tool_search,question,subagent, input, interaction, plan review, background, and nested-access tools cannot be deferred (deferred_unsupported_tool).- Connector and MCP tools take
loadingthrough theirexposureoption, for exampleexposure: { callableBy: 'all', loading: 'deferred' }. - If you call providers yourself, declare
declaredToolDefs(toolSet.tools, messages)from@yolk-sdk/agent/protocol. Realtime voice sessions declare deferred tools eagerly.
Choose access level
Every tool declares one access level:
| Access | Use for |
|---|---|
read | search, fetch, inspect |
write | create/update external state |
destructive | delete, execute commands, send messages, mutate broadly |
The SDK records access metadata. Your host enforces approval policy.
Mark tools that call a model
Access says what a call changes, not what it costs. A tool that calls a model when it runs (a
language model, a classifier, a child agent run) sets invokesModel: true, on makeTool options
or a raw ToolRegistration:
makeTool({
name: 'summarize_thread',
parameters: SummarizeParams,
access: 'read',
invokesModel: true,
execute
})resolveTools copies it to ToolMetadata.invokesModel and, for code mode,
NestedTool.invokesModel; it is never sent to providers. It changes nothing by itself: host policy
reads it, for example code mode's
readOnlyNestedCallGate, which refuses such calls in
scripts that must run without a model unless its admitModelCall admits them. The package's subagent and classify tools set it.
Tools whose host handlers call a model are yours to mark, for example a makeKnowledgeLookupTool
whose search embeds the query: { ...makeKnowledgeLookupTool(handlers), invokesModel: true }.
Ledger writes for re-executed steps
Durable hosts re-execute steps: Vercel Workflow's queue is at-least-once, so a tool-batch step
runs again after a crash and sometimes concurrently with a first execution that is still running.
Pass a durable ledger when you resolve tools and every ledgered call runs at most once per key. By
default that is every non-read call, including the nested calls of a
code mode script, plus the built-in
subagent tool (a read tool whose child run could otherwise repeat its writes). Input and
interaction tools are never ledgered: their at-most-once guarantee is your InteractionHost
receipts.
A write tool that also reads (one tool with list and update operations, say) can mark its
read-only calls with isReadCall. Those calls are not ledgered: re-running a read is safe, while a
ledgered read that crashed before recording its outcome would be refused on every retry as possibly
applied. Code mode records their access as read. A call whose arguments do not decode counts as
a read too: it runs nothing and answers with its validation error, never a ledger refusal.
makeTool({
name: 'tasks',
parameters: TasksParams,
access: 'write',
isReadCall: params => params.operation === 'list' || params.operation === 'get',
execute
})Fragment: db, modules, requestContext, runId, and stepDeadlineMs are host-owned.
import { Effect } from 'effect'
import { classifyToolLedgerEntry, resolveTools, type ToolLedgerStore } from '@yolk-sdk/agent/tools'
// Your storage, scoped to one run. `db` is host code (for example Drizzle over Postgres) returning
// interruptible Effects (`Effect.tryPromise` passing the AbortSignal to the driver), and leases
// use the database clock: `now() + leaseMs`, classified against `now()`.
const makeRunToolLedger = (runId: string): ToolLedgerStore => ({
scope: runId,
// Atomic: insert a claimed entry if the key is absent, else classify the stored entry.
claim: request =>
db.claimToolCall(runId, request, (entry, dbNowMs) => classifyToolLedgerEntry(entry, dbNowMs)),
// Extend the lease to now() + leaseMs only while the entry has no outcome.
heartbeat: ({ key, leaseMs }) => db.extendLeaseIfClaimed(runId, key, leaseMs),
// Record the outcome once; ignore later completions.
complete: ({ key, outcome, completedAtMs }) =>
db.completeOnce(runId, key, outcome, completedAtMs),
// Entries whose parentKey is the given key (a script's nested calls).
list: parentKey => db.listChildren(runId, parentKey)
})
const resolveStepTools = Effect.gen(function* () {
return yield* resolveTools(modules, requestContext, {
ledger: { store: makeRunToolLedger(runId), deadline: () => stepDeadlineMs }
})
})| Claim | When | Result |
|---|---|---|
Fresh | first execution of the key | runs, heartbeats its lease, stores the outcome |
Completed | an outcome is stored | returns the stored result (or the stored ToolError), no run |
InFlight | another execution holds a live lease | waits for it up to maxWaitMs/deadline; never runs |
Abandoned | the lease expired without an outcome (a crash) | never runs; tells the model it may already have been applied and to verify it |
- Keys are
call.id, and<parentCallId>/<seq>for nested calls. Call ids must be unique within a ledger scope: a reused id with the same arguments replays the earlier result. Scope the store to one run (add the turn or step if your provider can reuse call ids across turns). - Persist
ToolLedgerEntrywithSchema.toCodecJson(ToolLedgerEntry), or store every claim field:argsis an 8 KiB audit preview (argsTruncatedsays it was cut) andargsDigestis the SHA-256 of the full arguments' canonical JSON. A different tool name orargsDigestunder the same key is a model-visible conflict; never compare the preview.argsDigestis a stable format (store it as text, for examplechar(64)): lower-case hex SHA-256 of the UTF-8 canonical JSON of the rawcall.params, with object keys sorted by UTF-16 code units andJSON.stringifynumber and string rules. It is a conflict fingerprint, not a security boundary: unserializable arguments share one digest, and integers beyond 2^53 lose precision before hashing. Stored results are bounded (maxResultBytes, default 1 MiB, measured on the serialized JSON) and wire-safe; the live call still returns the full result. - Tool executors receive
idempotencyKey(<scope>:<key>), stable across re-executions. Pass it to external APIs that deduplicate, which covers a crash between their commit andcomplete. Custom executor or registration wrappers must forwardidempotencyKey(likenested). - Pick one clock per store.
claimandheartbeatreceive bothleaseMs(for stores that use their own clock, such as a databasenow()) andnowMs/leaseExpiresAtMsfrom the caller'sClock(for clock-agnostic stores, such as the in-memory one). Database time avoids clock skew between step instances. - Change which calls are ledgered with
isLedgered. Include your own delegation tools, for exampleinput => defaultToolLedgerPolicy(input) || input.call.name === 'delegate'. Withoutledger, execution is unchanged. - Waits, store polls included, end at
maxWaitMsordeadline(one final poll runs halfway through the last interval); a failed poll fails closed. Each of up to threecompleteattempts is bounded to 5 s; an outcome that cannot be recorded reads as abandoned. Eachheartbeatis bounded to 5 s or a sixth ofleaseMs, whichever is shorter, andheartbeatIntervalMsis clamped to half the lease minus that bound. A heartbeat that failed or timed out is retried one heartbeat timeout later (one interval, when that is shorter), so one failed or hung heartbeat does not let the lease of a running call lapse, provided the claim and the heartbeat before it are fast andleaseMsis at least 4 ms: the retry lands about a sixth of the lease or more before it ends (5 s at the defaults, 10 s + 3 × 5 s = 25 s of 30 s). While heartbeats land, they run one interval apart. That is a margin for one late heartbeat at a time, not a guarantee: a stalled process, two late heartbeats in a row, or a slow success followed by a hang (still zero margin at the defaults) can still let the lease lapse. - Store latency: each
heartbeat, and theclaim, must answer in less thanmin(5 s, leaseMs / 6). On a short lease a slower store has every heartbeat cut at that bound (a 6 s lease with 1.2 s heartbeats is cut at 1 s each time) and the lease lapses; give a slow store a longer lease. deadlinebounds only waiting for a duplicate. A call that runs is not cut at it, and recording its outcome can take up to about 15 s (three 5 s attempts) after the call returns, so reserve that finalization time before the platform stops the step.- Store operations (
claim,heartbeat,complete,list) must be interruptible, for exampleEffect.tryPromisepassing theAbortSignalto the driver. The ledger's timeouts interrupt the operation and wait for it to stop, so uninterruptible store work holds the wait, heartbeat, or completion until it ends. onLedgerDecision({ key, parentKey?, toolName, decision, waitedMs? })reports each ledgered call's decision (fresh,completed,in_flight_wait,in_flight_timeout,abandoned,conflict) for logs and metrics, for example to count replays. It never affects execution: errors are logged and ignored.makeInMemoryToolLedgerStore()is for tests and single-process hosts only.
ledger option | Default | Meaning |
|---|---|---|
store | required | host-implemented ToolLedgerStore |
isLedgered | defaultToolLedgerPolicy | which calls are ledgered (readCall input) |
leaseMs | defaultToolLedgerLeaseMs (30 s) | lease of a running call |
heartbeatIntervalMs | a third of leaseMs (clamped, see above) | how often a running call renews its lease |
pollIntervalMs | defaultToolLedgerPollIntervalMs (1 s) | how often a duplicate polls an in-flight call |
maxWaitMs | defaultToolLedgerMaxWaitMs (150 s) | longest wait for an in-flight call |
deadline | none | epoch ms after which a duplicate stops waiting |
maxResultBytes | defaultToolLedgerMaxResultBytes (1 MiB) | bound on a stored result's serialized JSON |
onLedgerDecision | none | one ToolLedgerDecisionEvent per ledgered call |
Argument previews are cut at toolLedgerMaxArgsBytes (8 KiB).
Pass files: { store, maxFileBytes? } to resolveTools as well to capture file bytes before the
ledger stores a result: results then hold fileId labels and ToolResult.files, and a reduced
stored result keeps its file labels. See Move files between tools.
Ask a human
Human-in-the-loop is protocol-level:
- approval requests pause with
AgentAwaitingInput - question tools pause with structured options
- clients resume through typed HITL responses
The SDK owns generic event and response shape. Hosts own UI, auth, request matching, audit, and policy.
Use the built-in question tool when the model needs a user choice. Use approval policy when a normal tool call needs permission before execution.
Preview the change
An approval-gated tool can describe what one call would change, so a person reviews a before → after diff instead of raw arguments. The same hook previews direct approvals, sibling approvals in one turn, and staged plan reviews, and every host renders it with one tool-agnostic component.
Fragment: UpdateRecordParams, HostContext, context.records, and applyUpdate are host-owned.
import { Effect } from 'effect'
import { ToolApprovalPolicy } from '@yolk-sdk/agent/protocol'
import {
makeTool,
resolveTools,
ToolChangePreview,
ToolTextChange,
ToolValueChange
} from '@yolk-sdk/agent/tools'
const updateRecord = makeTool<HostContext, typeof UpdateRecordParams>({
name: 'update_record',
description: 'Update a record.',
parameters: UpdateRecordParams,
access: 'write',
approval: ToolApprovalPolicy.make({ mode: 'manual' }),
// Side-effect free: read the current state and describe the change.
changePreview: ({ params, context }) =>
context.records.get(params.id).pipe(
Effect.map(record =>
ToolChangePreview.make({
target: { label: record.title, kind: 'record', id: record.id, href: record.url },
changes: [
ToolValueChange.make({
field: 'status',
label: 'Status',
before: record.status,
after: params.status
}),
ToolTextChange.make({
field: 'body',
label: 'Body',
before: record.body,
after: params.body
})
],
// Shown with a selectable call. Use `blocked` for what `staging.precheck` rejects.
warnings: record.archived ? ['The record is archived.'] : []
})
)
),
execute: input => applyUpdate(input)
})
const toolSet =
yield *
resolveTools(modules, context, {
changePreview: { maxBytes: 32 * 1024 } // optional; default 16 KiB per preview, 5 s timeout
})Pass approvalPreviews: toolSet.approvalPreviews to run, runToolBatch, prepareToolBatch, or
the runtime config, next to inputs and interactions. A pending ToolApprovalRequest then
carries preview (a ToolChangePreview) or previewError ({ cause, message }; cause is
failed, invalid, too_large, or timeout). Render request.preview when present, else the
raw request.call.params. Once the call settles, render its result instead of the pending diff:
an approved call that ran shows the after state, and a denied call shows "not applied".
A ToolChangePreview is { target, summary?, changes, warnings?, blocked? }. Each change has a
field, a display label, and one of five shapes:
_tag | Shape | Render as |
|---|---|---|
Value | before?, after: short scalar or null | old → new |
Text | before?, after: string | a text diff |
Set | added, removed, unchanged? items | + / − chips |
List | before?, after: ordered items | an ordered list diff |
Structured | before?, after: JSON, summary? | your structural renderer, or the summary |
Items are { id, label }. An absent before means unknown or new; null means known empty. An
empty changes means the call changes nothing.
- Display only. The approval binds to the call (
approval:<callId>), never to the preview. The arguments stay the source of truth for what runs, and the tool's own write stays authoritative.warningsare shown with a selectable call;blockedmarks a call that cannot apply as requested (recommend denying it). For staged plans,staging.precheckis the authority: express the same condition inblocked. - Failures never block approval. A failing, slow (
timeoutMs), invalid, or oversized preview becomespreviewError; invalid arguments report an error without calling the hook. - Bounded. Previews larger than
maxBytes(compact JSON) are truncated deterministically and never silently:Set.unchangedgoes first, then values are capped at an equal share. Cut strings and item arrays keep one window, which for abefore/afterpair starts shortly before their first difference; a cutStructuredvalue becomesnull. Each cut value has atruncatedmarker withunit(chars,items,bytes),originalSize, and an optionaloffset(absent: 0). Checktruncatedbefore rendering aStructurednull. Labels, the target,summary,warnings, andblockedare never cut: a preview they alone push past the bound reportspreviewError(too_large). - When it is computed. Previews run server-side when the approval request is raised, at most
8 at a time per batch, against the state before any call of the batch runs. Two siblings that
touch the same record are both previewed against its current state. Durable hosts that resume
one response per round re-raise the remaining siblings, recomputing their previews: render the
latest
ToolApprovalRequestedfor a call. Each preview is up tomaxBytesand appears inToolApprovalRequestedandAgentAwaitingInput.requests; size durable event storage for it. - Group repeated changes.
toolChangeSignature(preview)is a stable digest ofchanges(ignoring the target,Set.unchanged, andSetorder).groupToolChangePreviewsgroups{ toolName, preview }entries so you can show "add X on 120 records" once. Truncated previews are never grouped. - Voice approvals do not compute previews.
Collect typed input
Use makeInputTool when the model needs structured user data (such as a draft or form). Questions remain the built-in option/free-text UI; custom inputs use app-owned renderers. Input tools share the HITL lifecycle: the loop pauses with AgentAwaitingInput, your UI renders by kind, and you resume with a typed InputResponse.
import { Schema } from 'effect'
import { makeInputTool } from '@yolk-sdk/agent/tools'
const DraftResponse = Schema.Struct({
to: Schema.String,
subject: Schema.String,
body: Schema.String
})
export const draftTool = makeInputTool({
name: 'compose_draft',
description: 'Collect an email draft from the user.',
response: DraftResponse,
renderer: 'draft-composer',
title: 'Compose draft'
})Rules:
responseis the server Effect Schema that validates user payloads; theToolDefcarries only display metadata (kind,title?,description?, display-only JSON Schema hint). Never validate against the lowered hint.- Input tools never take approval/background options and never execute through direct dispatch; they complete only through HITL resume with JSON-only (
Schema.Json) payloads. - Resolve with
resolveTools, then passtoolSet.inputsexplicitly intorun/runToolBatch/prepareToolBatch/runRuntimeconfigs. Without them, input tools fail closed as model-visibleunavailableerrors. - Render pending input from
InputRequestedbyinput.kindthrough host-owned components; submit viastreamInputResponseEventStream, theInputResponseInputWebSocket message,AppendHitlResponse, or ReactsubmitInputResponse. EchorequestId/toolCallIdopaquely. callParametersvalidates model-supplied context before opening the request (defaults to no arguments). Invalid user payloads re-pend the same request for correction. The first valid submission or cancellation settles it; stale/duplicate responses cannot replace it. React keeps the form pending until server acceptance, including after transport failures.- Voice sessions deny input tools; omit them from subagents and other hosts without nested HITL resume.
Authorize one action
makeInteractionTool lets a person review proposed values, edit them, and authorize one
server-defined action, such as Publish or Archive. It is distinct from data-only makeInputTool.
Opt in only on surfaces with an authenticated, durable host adapter and an app-owned renderer.
Registration fragment (the host supplies the document service and renderer):
import { Effect, Schema } from 'effect'
import type { ToolError } from '@yolk-sdk/agent/loop'
import {
makeInteractionTool,
type InteractionActionResult,
type ToolModule
} from '@yolk-sdk/agent/tools'
const DocumentDraft = Schema.Struct({ title: Schema.String, body: Schema.String })
type DocumentContext = {
readonly publish: (
data: typeof DocumentDraft.Type,
submissionId: string
) => Effect.Effect<InteractionActionResult, ToolError>
readonly archive: (
data: typeof DocumentDraft.Type,
submissionId: string
) => Effect.Effect<InteractionActionResult, ToolError>
}
export const documents: ToolModule<DocumentContext> = {
id: 'documents',
tools: [
makeInteractionTool({
name: 'document',
description: 'Review and file a document.',
access: 'write',
callParameters: Schema.Struct({ folder: Schema.String }),
response: DocumentDraft,
renderer: 'document-editor',
title: 'Review document',
actions: {
publish: {
label: 'Publish',
execute: ({ data, context, submissionId }) => context.publish(data, submissionId)
},
archive: {
label: 'Archive',
execute: ({ data, context, submissionId }) => context.archive(data, submissionId)
}
}
})
]
}Callbacks infer data from response and call.params from callParameters. Original Effect
schemas validate both; provider JSON Schema is display/model guidance only. V1 supports
JSON-preserving schemas: excess, missing and invalid values are rejected, as are nested
normalization/defaults/transforms that change the exact consented JSON. null, false and 0
are valid when the schema admits them; absence is not.
Accept on the host before execution
The host owns authentication, pending ownership, session/run/generation, current account policy,
renderers and storage. A click, source: 'user', raw InteractionResponse, transcript entry or
opaque ID does not authorize execution.
Integration fragment; host and scopedReceipts below are explicitly host-owned services,
not Yolk exports:
import { Effect } from 'effect'
import { validateInteractionSubmission, type InteractionResponse } from '@yolk-sdk/agent/protocol'
import { resolveTools } from '@yolk-sdk/agent/tools'
const acceptResponse = (response: InteractionResponse) =>
Effect.gen(function* () {
const actor = yield* host.authenticate()
const pending = yield* host.pendingOwnedBy(actor, response.requestId)
const context = yield* host.freshDocumentContext(actor)
// Bind the receipt port to THIS active session/run/pending generation, never a
// global model-supplied call-ID lookup.
const scopedReceipts = host.receiptsFor(pending.scope)
const toolSet = yield* resolveTools([documents], context, { interactionHost: scopedReceipts })
const interaction = toolSet.interactions[pending.call.name]
if (interaction === undefined) return yield* host.unavailable()
const candidate = yield* validateInteractionSubmission({
request: pending.request,
response,
...interaction
})
// Host transaction: recheck scope/ownership and atomically choose the first valid
// submission across ALL actions and cancellation. Persist an immutable full binding
// beside a unique host-allocated submission ID. Invalid attempts consume nothing.
yield* host.acceptTransaction({ actor, pending, candidate, response })
// Only now append/resume; transport submission alone is not acceptance.
return toolSet
})Optional action validate is called by the resolved validateAction during admission,
with fresh bound context and no business effects. Use InteractionValidationError from
@yolk-sdk/agent/protocol for an expected business rejection; the person can edit or cancel.
Validation is not authentication and is rechecked before new execution.
InteractionHost is a port over host storage, not an SDK storage engine:
read(slot)returns an independent immutable accepted/started/settled receipt, including the original call, selected action and exact final data. Scope is already bound in the adapter.claim(ref)only advances existing accepted → started atomically and returns the same binding with a fencing token. It must never manufacture acceptance. Concurrent losers and abandoned started records cannot take over or resend.settle(token, outcome)is token-fenced and idempotent. It validates receipt identity and never overwrites a settled result. A lost acknowledgement may replay completed on retry, but never licenses another dispatch.
The protocol subpath exports validInteractionReceipt, sameInteractionBinding,
sameInteractionCall, and interactionJsonEquals for adapter binding and settlement checks.
These pure checks do not authenticate storage records or replace host ownership checks.
Submission IDs are unique host-owned identities, not authentication or globally safe
payload-derived provider idempotency keys. All actions and cancellation compete for one slot;
identical retries reuse acceptance, changed action/data/call conflict. Built-in cancellation
rejects action/data, requires no valid form (even after schema changes), and executes no business
handler. The host records cancellation as a settled receipt with an error tool result whose
structuredContent is { type: 'interaction_outcome', requestId, slot, submissionId, outcome: 'cancelled' }.
Resume and replay
Pass both toolSet.interactions and toolSet.interactionHost into run, runToolBatch or
runtime config. The executor layer still comes from makeToolExecutorLayer(toolSet). Without a
host adapter, forms are unavailable rather than executing through an in-memory fallback.
If a form keeps reappearing after acceptance, check that the same scoped interactionHost
is passed to the loop/runtime, not only to resolveTools: without it the loop cannot load
accepted receipts. Durable preflight must load and pass fresh receipt snapshots.
Durable preflight fragment:
import { loadInteractionReceipts, prepareToolBatch } from '@yolk-sdk/agent/loop'
const interactionReceipts = yield * loadInteractionReceipts(calls, toolSet.interactionHost)
const prepared =
yield *
prepareToolBatch({
calls,
tools: toolSet.tools,
inputs: toolSet.inputs,
interactions: toolSet.interactions,
interactionReceipts,
responses: hitlResponses
})
// Do not dispatch ANY sibling while prepared.pendingRequests is nonempty.
// Forward prepared.interactionBindings.get(call.id) as { interaction: ref } to
// ToolExecutor.execute. Dropping the ref fails closed.Preparation only validates and plans: no receipt reads, claims, settlements or actions. Load
fresh snapshots before every preparation boundary. A call validator may read host storage (the
plan review reads the plan store); when that storage is unavailable it fails with
InteractionHostError and prepareToolBatch fails with a ToolError unavailable, like
loadInteractionReceipts: retry the step. An accepted receipt whose call no longer validates is
still dispatched, so the executor can re-read the receipt and report a delivery that already
started or settled it. Historical receipts replay before current
schemas/actions, even if a tool is removed or disabled; a missing handler can never start new
work. The executor re-reads and validates the full receipt binding, then runs only its chosen
action/data, before the next model turn. No extra approval or ambient permission is introduced.
Observe truthful outcomes
InteractionSubmitted is authoritative acceptance, not completion. It stays active until
a real server result. Local submit remains pending; neither acceptance nor transcripts synthesize
completed tool results. Submit transport options are streamInteractionResponseEventStream,
InteractionResponseInput, AppendHitlResponse or React submitInteractionResponse; these do
not replace the authenticated host acceptance step.
Action results distinguish completed, explicit failed (known no effect), and unknown.
Escaped post-dispatch failures, including ModelVisibleToolError timeouts, are unknown, not
proof of failure. Defects and interruption retain their original Cause while a bounded finalizer
attempts uncertainty settlement. Host callbacks must cooperate with interruption. Unknown
results carry receipt identity, isError: true, and explicit text that the action may have happened
and must not be retried automatically, including rich content. Headless result metadata preserves
outcome: 'unknown' separately from failed.
Hosts own reconciliation, external-provider idempotency and warnings against separately consented duplicates. Voice/realtime, background activation and hosts without authenticated receipt storage remain unsupported. This API does not promise exactly-once external effects.
Review a staged plan
A code mode script can stage calls of
approval-gated tools marked staging instead of running them. makePlanReviewTool is the
interaction a person uses to review that plan once and select the calls to apply. It reuses the
authorization flow above: host acceptance, receipts, claim and settle.
import { makePlanReviewTool, resolveTools } from '@yolk-sdk/agent/tools'
const reviewPlan = makePlanReviewTool<HostContext>({
// The only per-call authority hook for applied calls (see below).
beforeCall: ({ call, context }) => authorizeWrite(context, call), // host-owned
onFailure: 'stop' // default; 'continue' runs the remaining selected calls
})
const resolveHostTools = (context: HostContext) =>
resolveTools([{ id: 'host', tools: [codemode, reviewPlan] }, ...hostModules], context, {
interactionHost: scopedReceipts, // host-owned
plans: {
store: planStore, // host-owned ToolPlanStore, scoped to the conversation
// Provider call ids can repeat across turns: make plan ids unique and stable.
planId: ({ call }) => `${context.runId}:${context.turn}:${call.id}` // host-owned values
}
})- The model calls
review_plan({ planId, planDigest })with the values the script reported. Call validation loads the plan from the store: present, in scope, digests matching, not yet applied. - Render the
tool_plan_reviewkind withpreviewStoredToolPlan({ toolSet, planId, planDigest, offset }): one page of at most 50 calls, each with its stagedparamsand the tool's change preview (preview, orpreviewErrorwhen it failed), plusnextOffsetand whether a review already claimed the plan. The results are plain JSON; decode them with the exportedToolPlanPreviewPageSchema on the client. Group identical changes across all pages withgroupToolChangePreviews. - The person submits action
applywith{ selectedKeys }, a non-empty subset of the staged keys; they can untick calls but never change arguments. Cancel applies nothing. - Admission (
validateInteractionSubmission) checks the selection with your fresh context: no duplicates, keys of the plan, tools still stageable, and each tool'sstaging.precheck(at most 8 at a time). Keep prechecks cheap; make the tool's own write a compare-and-set for correctness. - On execution Yolk re-reads the receipt, claims the plan once (
ToolPlanStore.claim), and runs the selected calls in staged order through the resolved execute path and ledger, with ids<reviewCallId>/<n>. The result lists each call asapplied,failed,skipped,not_run,unknown, orinput_requiredinstructuredContent.result(stateisapplied,refused, orinterrupted); decode it with theToolPlanOutcomeSchema. - An
input_requiredcall ran and paused for a person's input: it has not completed, carries itsinputRequiredref ({ reviewToolName, pauseIds }), and never stops the apply underonFailure: 'stop'. The result text names the review call that finishes it.ToolPlanCallCounts.input_requiredis optional, so outcomes recorded before it still decode. - Per-call authority: applied calls run inside the review action, so code mode's
beforeNestedCalland decorators around yourToolExecutornever see them.beforeCallis the only per-call hook: wire the same run-authority or write authorizer you use for nested calls.beforeCalland any customplanReviewhandler are trusted host code. - Steps can be redelivered while the first execution is still applying (Vercel queues are
at-least-once). With a tool ledger, each apply runs behind a ledger entry for the review call: a
redelivery waits for the running apply (up to the ledger's
maxWaitMsordeadline) and returns its real outcome. If the wait ends first, or the apply crashed, it returns anunknownoutcome listing each staged call (orfailedwhen Yolk proves nothing ran); a call isnot_runonly when Yolk can prove it never ran and never will, otherwiseunknown. The apply is never run twice. Give the ledger wait room for your largest plan. - A plan store outage is never a verdict: loop preflight fails the batch with an
unavailableToolError(retry the step; the review stays accepted), admission answersInteractionAdmissionErrorunavailable, and an outage that starts mid-step fails the call closed. Once the receipt is claimed, an outage ends that review attempt withfailedand nothing applied: when reading the receipt or plan or claiming the apply's ledger entry failed, the model is told the plan is unchanged and can open a new review; when claiming the plan itself failed, the plan may now be locked against further reviews. A delivery that finds the receipt already started or settled by another delivery reports that outcome instead of an invalid-arguments error. - The apply's ledger entry must be visible to every redelivery of the review step: resolve the review step with the same ledger scope each time and keep ledger entries at least as long as the review receipts.
- Calls apply one after another in one tool step: keep plans small enough to fit your step budget
(lower
staging.maxCallson the code mode tool). - After the review settles, show each call from
ToolPlanOutcome.calls, not the pending diff:appliedshows theafterstate,skipped,not_run, andfailedshow "not applied" with no pending diff,unknownsays the call may have been applied, andinput_requiredsays it waits for a person's input.
ToolPlanStore is a port over host storage:
putis atomic insert-or-compare by plan id (for exampleINSERT ... ON CONFLICT DO NOTHING, then compare digests): the same digest is a no-op, another digest aconflict.getreturns the plan and its claim.claim({ planId, submissionId })is one conditional update (... WHERE claimed_by IS NULL) returningclaimed,same, ortaken; a plan is applied at most once. Submission ids must be unique within the store scope.- JSON(B) columns are safe: digests use canonical JSON (sorted keys). Decode stored plans with
Schema.toCodecJson(ToolPlan). - Retention is yours: unreviewed plans are inert, so expire them after the review window; keep claimed plans as long as the ledger entries they explain.
makeInMemoryToolPlanStore is a non-durable reference. There is no atomic batch: a partial apply
reports exactly which calls ran.
Finish calls that paused for input
A remote system can pause a call after it was made: an MCP server answers a tools/call with a
form (for example a confirmation before a delete) and finishes only when the form is answered.
A tool's execute never pauses. It stores the pause in host storage and returns an
input-required result; a person later answers through the input review interaction, whose action
resumes each stored pause once
(ADR 0014).
For MCP tools, see Finish calls that ask for input.
Fragment: pauseStore is host-owned.
import { makeInputRequiredToolResult } from '@yolk-sdk/agent/protocol'
import { inputReviewToolName } from '@yolk-sdk/agent/tools'
// In the tool's execute, after the remote system paused the call:
const pauseId = yield * pauseStore.save({ call, pause: remotePause }) // host-owned
return makeInputRequiredToolResult({
toolCallId: call.id,
content: 'The server asks to confirm deleting invoice 42.',
reviewToolName: inputReviewToolName, // 'review_input'
pauseIds: [pauseId]
})The result is an error result whose structuredContent is
{ code: 'input_required', inputRequired: { reviewToolName, pauseIds } }, and its content tells the
model to call review_input({ pauseIds }) and not to call the tool again. Being an error result,
the call is over: output checks skip it, the tool ledger
records it (it never runs again), code mode rejects
the nested call with error.code === 'input_required', and a staged plan reports it
input_required. toolInputRequired(result) reads the ref back (Option<ToolInputRequiredRef>);
mergeInputRequiredRefs merges refs per review tool and splits them into reviews of at most
maxInputReviewPauses (50); inputRequiredNotice renders the model-visible notice, listing every
review to call in turn. A remote MCP error result never carries the marker: Yolk's MCP
client keeps such content under remoteStructuredContent.
Register one input review tool next to your other interactions. Fragment: the pauseStore methods
are host-owned.
import {
makeInputReviewTool,
resolveTools,
type InputPause,
type InputReviewHost
} from '@yolk-sdk/agent/tools'
// Your stored pause: `id`, a person-readable `label`, and whatever resuming needs.
type HostPause = InputPause & { readonly form: RemoteForm }
const pauses: InputReviewHost<HostPause> = {
// The listed pauses, in order: in this session's scope and still waiting.
load: pauseIds => pauseStore.loadWaiting(pauseIds),
// Side-effect free: does the answer fit the pause's form?
validateAnswer: ({ pause, answer }) => pauseStore.check(pause, answer),
// Claim the pause for `submissionId`, send once, record and return an InputPauseResolution.
resume: ({ pause, answer, submissionId }) => pauseStore.resumeOnce(pause, answer, submissionId),
// Optional: the recorded resolutions of a review that crashed after its claim.
recorded: ({ pauseIds, submissionId }) => pauseStore.recorded(pauseIds, submissionId)
}
const toolSet =
yield *
resolveTools(
[{ id: 'host', tools: [makeInputReviewTool<HostContext, HostPause>({ host: pauses })] }],
context,
{ interactionHost: scopedReceipts } // host-owned
)- The model calls
review_input({ pauseIds })(InputReviewParams: at mostmaxInputReviewPauses, 50, no repeats). Call validation loads them throughload: a missing, foreign, or answered id is anInteractionValidationError, and a storage outage anInteractionHostError, never a verdict. The model passes only ids, so forms are rendered only from stored pauses. - Render the
input_reviewkind (inputReviewRenderer) from the stored pauses. The person submits actionsubmit(inputReviewActionId, labelSend answers) with{ answers }(InputReviewResponse): exactly one JSON answer per listed pause, keyed by pause id. Admission checks each withvalidateAnswer; an invalid answer is never accepted and consumes nothing. Cancel sends nothing, and the pauses stay reviewable. - The action resumes the pauses in review order through
resume. The host claims each pause before sending and never sends after a claim.resumeanswers anInputPauseResolution:Completed({ result })(the remote result, even an error result),InputRequired({ pauseIds })(asked again: the new pauses are stored),NotSent({ message })(refused before sending), orUnknown({ message })(it may have run; a claim found without a recorded resolution is this). - The result lists every pause with its outcome, each completed call's own result content (files
included), then the review call for any new pauses.
structuredContent.resultis anInputReviewOutcome:{ type: 'input_review_outcome', pauses, interrupted? }, each pause{ pauseId, label, status, isError?, inputRequired?, error? }withstatuscompleted,input_required,not_sent, orunknown. The interaction outcome isunknownwhen any pause is unknown,failedwhen none was sent, elsecompleted. - A review that started without a recorded outcome (a crash after the claim, or a redelivered step
finding the receipt started) lists what
recordedreturns, withinterrupted: true, and sends nothing again. Only a replay where every pause has a recorded resolution reports a proven outcome; withoutrecorded, the result is a generic unknown notice. - The original call stays input-required in the transcript; the review result is its completion. A script that needed the value continues in a new script from the review result, never by calling the tool again.
- Options:
name(defaultreview_input),description,renderer,title,interactionDescription,actionLabel, andaccess(defaultwrite: answers are sent to the system that paused the calls). Wire the interaction like any other:interactionHostinresolveTools, andtoolSet.interactionsplustoolSet.interactionHostin loop/runtime config.
Let the model choose background execution
Any makeTool registration may opt into background execution with background: true. The flag is
inert on its own: definitions, schemas, approval ids, and inline execution stay byte-for-byte the
same until resolveTools receives a backgroundHost. Supply a host only when a real lifecycle
owner (for example a durable Workflow) will run, track, and eventually deliver the work.
import { Effect, Schema } from 'effect'
import { BackgroundToolAccepted } from '@yolk-sdk/agent/protocol'
import { makeTool, resolveTools, type BackgroundToolHost } from '@yolk-sdk/agent/tools'
export const reportTool = makeTool({
name: 'build_report',
description: 'Build a report. Choose background execution for long inputs.',
parameters: Schema.Struct({ topic: Schema.String }),
access: 'write',
background: true,
execute: () => Effect.succeed({ content: 'inline report' })
})
// Host-owned: durably admit the exact call and return a receipt, never a closure.
const backgroundHost: BackgroundToolHost<RequestContext> = {
accept: ({ call, context }) =>
hostReserveExecution({ callId: call.id, name: call.name, params: call.params, context }).pipe(
Effect.map(execution =>
BackgroundToolAccepted.make({ version: 1, executionId: execution.id })
)
)
}
const toolSet = await Effect.runPromise(
resolveTools([{ id: 'local', tools: [reportTool] }], requestContext, { backgroundHost })
)With a host, activated tools advertise a required envelope instead of their raw parameters:
{ "execution": "foreground", "arguments": { "topic": "Q3" } }The original schema nests under arguments unchanged (including tools whose own parameters are
named execution, arguments, or background), and $defs stay at the document root so nested
#/$defs/... references keep resolving through OpenAI and Anthropic lowering. Activation supports
only these document-root definition pointers (without percent-encoded fragments). Other $ref
forms (root #, anchors, #/properties/..., #/definitions/..., relative or external references)
and resource/anchor keywords ($id, legacy id, $anchor, $dynamicAnchor, $dynamicRef,
$recursiveAnchor, $recursiveRef) fail with ToolRegistryError.cause: 'background_unsupported_schema'.
This check visits schema positions, not literal defaults, examples, const, or enum data.
Without activation, schemas remain unchanged. The registry validates the envelope
and the original parameters without running business effects, strips the control fields, and then
either executes inline (foreground) or calls host.accept. Raw ToolRegistration objects must
provide a side-effect-free validate callback before they can activate; resolveTools fails
closed otherwise, as it does for the loop-owned question and subagent tools.
Acceptance returns one acknowledgement ToolResult for the original call with typed
acceptance: { version: 1, executionId } metadata. The loop emits ToolExecutionAccepted instead
of ToolExecutionCompleted, records no usage, and continues the model turn. Client state, chat
projection, and tool cards treat Accepted as settled, non-error, and not completed. Stale client
Started/input events for an accepted call cannot reopen it.
Activated background-v1 definitions are unsupported in voice/realtime, even when a call chooses
foreground. Resolve voice toolsets without a background host. toOpenAiRealtimeTool and both
realtime session config builders throw VoiceToolBridgeError rather than advertise activated tools.
decideVoiceToolCall denies them and handleVoiceToolCall returns Denied before approval matching,
including replayed approvals. The low-level executeVoiceToolCall bridge also rejects activated
registry dispatch before validation, inline execution, or host admission. Ordinary voice tools,
including inert background: true definitions without a host, retain their existing behavior.
Host responsibilities:
acceptmust be idempotent per call id so step retries recover the same receipt.- Own authorization, cancellation, status/wait tools, terminal storage, usage accounting, and delivery.
- Never append a second result for the original call; deliver terminal output through distinct status/wait tool-call ids or a later host continuation.
- Fail
acceptwith aToolErrorto decline; the registry never falls back to inline execution.
Manual approval still fences the whole batch before any launch. For activated calls the approval
requestId binds the tool name, execution mode, and canonical arguments, so an approval cannot be
reused for a different payload or mode; a malformed envelope is rejected before anyone is asked.
Non-activated tools keep the legacy approval:<callId> identity.
Spawn a subagent
The subagent tool contract is domain-free. Hosts provide child execution, prompts, models, tools,
and recursion policy. Current v1 subagents should not receive the subagent tool recursively unless
explicitly enabled in a future capability.
Use subagentResultFromEvents to extract final or awaiting-input text, status, HITL requests,
usage, turns, and typed AgentError details from child events. Pass that metadata to
makeSubagentToolResult. Durable hosts
can call subagentUsageFromToolResult on completed tool results and add the returned child usage to
their cumulative workflow usage. If a host does not implement nested HITL resume, omit approval- and
question-gated tools from child toolsets rather than returning an unresumable awaiting_input result.
Background subagents
Background execution is opt-in. Set background: true in makeSubagentToolModule or
makeNonRecursiveSubagentToolModule registration options to advertise the optional background
model parameter. This does not launch work by itself: your executor must handle params.background
and durably start the child. Omitted registration opt-in preserves the inline contract.
After a successful background launch, return makeSubagentAcceptedToolResult instead of a final
child result. Host executor fragment; hostStartChild and hostRunInlineChild are host-owned
implementations:
import { Effect } from 'effect'
import { makeSubagentAcceptedToolResult } from '@yolk-sdk/agent/tools'
const execute = input =>
Effect.gen(function* () {
if (input.params.background !== true) return yield* hostRunInlineChild(input)
const child = yield* hostStartChild(input)
return makeSubagentAcceptedToolResult({
callId: input.call.id,
workflowRunId: child.runId
})
})Acceptance completes the launch tool call, not the child. It emits no SubagentCompleted or child
usage. Keep logical subagent:<callId> identity separate from the physical Workflow run id.
Hosts may deliver later findings automatically or expose their own authenticated observation tools;
when observations are separate calls, use distinct tool-call ids rather than a second result for the
original launch call. Do not charge the same child usage again.
The SDK registers no status or wait tools and does not promise automatic completion delivery. Your host owns its completion policy, authenticated child lookup/routes, durable admission/reservations/results, child HITL handling, and explicit Stop/cancellation policy. Do not infer that parent completion or failure cancels an independent child. Preserve any lookup identity the model needs in model-visible content when customizing the acknowledgement.
For durable hosts, see Independent child orchestration.
Nonterminal child observations
If a host finishes observing a subagent call while the child's outcome is still running or
unknown, return a nonterminal observation rather than inventing a final child result. Host
executor fragment; hostChildRunId is the authorized physical recovery handle:
import { ToolResult } from '@yolk-sdk/agent/protocol'
const observation = ToolResult.make({
toolCallId: input.call.id,
content: 'Child is still running; use the recovery handle to observe it later.',
structuredContent: {
type: 'subagent_observation',
subagent_run_id: `subagent:${input.call.id}`,
workflow_run_id: hostChildRunId,
status: 'running',
done: false
}
})Use running only when known; report uncertainty truthfully otherwise. The loop suppresses
SubagentCompleted only when the marker is subagent_observation and subagent_run_id matches
subagent:<originalCallId> for that subagent call. A mismatched ID does not suppress completion.
The observation still emits ToolExecutionCompleted for the call, not child completion, and adds
no nested usage. Return a recovery handle only after host ownership checks.
This differs from launch acceptance (makeSubagentAcceptedToolResult) and from generic background
ToolResult.acceptance, which produces ToolExecutionAccepted. Do not append another result to
the original call later; observe through distinct status/wait calls. See
Bounded child observations.
Effect-native realtime validation
Use toOpenAiRealtimeToolEffect, makeOpenAiRealtimeSessionConfigEffect, or
openAiRealtimeSessionConfigFromVoiceEffect from @yolk-sdk/agent/providers/openai/realtime
in Effect programs. They fail with typed VoiceToolBridgeError for activated definitions, so
Effect.catchTag('VoiceToolBridgeError', ...) can recover before SDP exchange or other host effects.
The synchronous counterparts remain compatible and throw that error; unexpected defects are not
converted into host-correctable failures.
makeTool returns the same structured model_visible_tool_error for invalid business arguments
with or without activation, in either execution mode, before business execution or admission.
Malformed envelopes and raw-registration/host ToolErrors retain their typed failure semantics.
Activated approval IDs intentionally contain the full canonical payload for lossless exact binding. Hosts must accommodate opaque, potentially long IDs or enforce input bounds before admission. Never truncate, hash, or rebuild these IDs when storing or returning approvals.