Yolk SDK
API reference

Agent APIs

Public agent subpaths and commonly used exports.

Import feature APIs from explicit subpaths. The root package is intentionally tiny.

Protocol

@yolk-sdk/agent/protocol

ToolDef.parameters uses ToolJsonSchema (boolean or plain JSON object). ToolJsonSchemaObject is its object arm; decodeToolJsonSchema and decodeToolJsonSchemaObject return Option. Admission preserves identity, rejects accessors unread, exotic prototypes, hidden/symbol keys, nonfinite values and cycles, and permits dense arrays, null-prototype objects and DAG aliases. This is representation admission, not meta-schema validation; provider compatibility and tool execution validation are separate. Params/results/HITL remain opaque.

ExportPurpose
UserMessage, AssistantAgentMessage, ToolResultMessagetranscript messages
AgentEventstream event union
UserMessageEvent, AssistantMessageEventreplay-safe transcript events
AssistantReasoningReplay, SignedReasoningReplay, RedactedReasoningReplay, LLMReasoningReplayopaque provider state on AssistantReasoningPart.replay for replaying a reasoning block, and the event that closes a block with it (never edit a part that has it)
ToolDef, ToolCall, ToolResulttool protocol
BackgroundToolAccepted, BackgroundToolInput, decodeBackgroundToolInput, makeBackgroundToolAcceptedResultbackground tool acceptance
ToolCallableBy, ToolDiscovery, ToolExposure, toolDiscovery, isCodeModeCallable, isCodeModeFailClosedcode mode tool exposure (code mode)
isToolStageableapproval-gated tools a code mode script may stage into a reviewed plan (ToolDef.staging; staged plans)
providerToolDefs, isProviderToolDeffilter out codemode-only defs (realtime sessions; send declaredToolDefs in text requests)
ToolLoading, isDeferredTool, declaredToolDefs, activatedToolNames, ToolSearchActivation, toolSearchToolNamedeferred tool loading: the defs a request declares (codemode-only filtered, deferred ones once a tool_search result activated them; defer rarely used tools)
MessageInstruction, isInstructionMessage, latestInstructionState, latestInstructionMessageshost instruction messages (UserMessage.instruction); keep latestInstructionMessages through custom compaction (host instructions)
NestedToolCalls, NestedToolCallRecord, NestedToolCallStatus, NestedToolCallAccess, NestedToolCallCounts, recordNestedToolCall, nestedToolCallResultFields, makeNestedToolCallRecorder, emptyNestedToolCallRecorderbounded, non-model-visible nested call record for ToolResult.nestedCalls, with per-status counts
nestedToolCallMaxCalls, nestedToolCallMaxArgsBytes, nestedToolCallMaxTotalArgsBytes, nestedToolCallMaxErrorCharsnested call record bounds (nestedToolCallMaxCalls is the default maxCalls)
nestedToolCallMaxRecordedCalls, nestedToolCallRecordLimit, boundNestedToolCallArgs, BoundedNestedToolCallArgsrecord size ceiling (4096), maxCalls clamping, and the shared per-call/total argument budgets
truncateCodePointscut text to a code point budget with a trailing … (nested-call errors, code mode)
ToolExecutionAcceptedbackground admission event
ToolApprovalRequest, ToolApprovalResponseapproval HITL; requests carry an optional preview (ToolChangePreview) or previewError
makeInputRequiredToolResult, toolInputRequired, toolInputRequiredCode, ToolInputRequired, ToolInputRequiredRef, mergeInputRequiredRefs, inputRequiredNotice, inputReviewCallText, maxInputReviewPauseserror result marking a call paused for input: { code: 'input_required', inputRequired } (paused calls)
ToolChangePreview, ToolFieldChange and its variants, ToolChangeTarget, ToolChangeItem, ToolChangeScalar, ToolChangeCut, ToolChangeSideCuts, ToolChangeSetCuts, ToolChangePreviewError, ToolChangePreviewErrorCause, ToolChangePreviewFailure, ToolApprovalPreviewertool change preview Schemas and the ToolApprovalPreviewer loop seam (preview the change)
QuestionRequest, QuestionResponsequestion HITL
plainHitlResponse, hitlResponseEvent, questionResponseStructuredContentdurable/client HITL helpers
isTerminalAgentEventterminal event guard
AgentStatus and its variants, AgentActivity, AgentBlockedKind, AgentStatusTree, SubagentStatusEntry, nextAgentStatus, agentStatusFromEvents, nextAgentStatusTree, agentStatusTreeFromEvents, reconcileAgentStatus, withSubagentStatus, startAgentStatusTree, settleAgentStatusTree, hitlRequestBlockedKind, agentBlockedKind, agentStatusRetry, isAgentStatusLive, idleAgentStatus, initialAgentStatusTree, isSubagentAcceptedToolResult, isSubagentObservationToolResultrun status in OSC 7501 vocabulary (agent status)
assistantContent, contentText, contentPartscontent helpers
ImagePart, DocumentPart, AudioPart, FilePart, TextPartmultimodal content parts
urlAttachmentSource, inlineBase64AttachmentSource, refAttachmentSource, attachmentSourceText, AttachmentTextDecodeErrorattachment source helpers; attachmentSourceText decodes inline base64 to UTF-8 (Option.none() for URL/ref) and fails with AttachmentTextDecodeError
filePartFromBytes, bytesToBase64, base64ToBytes, filePartText, FileDescriptor, FileId, fileIdPattern, isFileId, fileLabel, fileNotCapturedLabel, formatFileSize, normalizeFileMimeTypefile parts and descriptors (move files between tools); ToolResult.files lists captured files and never reaches providers
FileBytes, ToolFile, FileRef, FileUnavailable, ToolFileValue, isFileRef, fileUnavailable, noFileStoreReason, containsToolFiletyped file fields (ADR 0013): tools return FileBytes in ToolFile output fields; the encoding holds a FileRef or FileUnavailable
FileStored, ToolFileOutput, ToolFileCapture, captureToolFileValue, capturedFilePartsa file the host already stored (FileStored; a ToolFile field takes ToolFileOutput) and the ambient file capture resolveTools provides to every registration (makeToolFileCapture in tools builds one)
typedToolResult, encodeToolOutput, toolOutputText, toolOutputFiles, ToolOutputEncodingError, ToolOutputSchema, ToolOutputRender, ToolOutputRenderFiles, EncodedToolOutput, CapturedToolFiletyped tool results for raw registrations and adapters (encoding fails closed on non-JSON values)
toolOutputDecoder, ToolOutputDecoderToolRegistration.decodeOutput of an output schema: the result check resolveTools runs (excess properties rejected, plain JSON only)
toolFileJsonSchemaDefinitions, toolFileJsonSchema, toolFileLabelcanonical $defs of file fields for hand-built output schemas (MCP), and their labels
FileSource, OmittedFileSource, omittedFilePartFilePart sources: an Omitted { reason } marks an unstored file (lowered as the "not captured" label)
AgentModelCapabilities, textOnlyModelCapabilities, textImageModelCapabilities, textImageDocumentModelCapabilitiesmodel input capability helpers
ProviderErrorInfo, ProviderFailureKind, ProviderStreamDiagnostics, ProviderStreamInvalidField, ProviderStreamFieldType, ProviderStreamProtocol, ProviderStreamResponseFormatsafe provider error metadata, incl. optional stream diagnostics (invalidField on invalid_stream_chunk) and quotaResetsAtMs (subscription quota reset, rate_limit only)
AgentUsage, addAgentUsage, zeroAgentUsageusage accounting helpers
CompactionStart, CompactionEndcompaction lifecycle events
validateNoDanglingHostToolCalls, repairDanglingHostToolCalls, danglingHostToolCallstranscript invariant helpers

Attachment resolution helpers from @yolk-sdk/agent/protocol:

ExportPurpose
AttachmentSourceResolver<E, R>Host Effect callback from a media part to an attachment source
resolveContentAttachmentSourcesResolve media sources in one Content
resolveMessageAttachmentSourcesResolve one message, including assistant text and nested provider tool results
resolveMessagesAttachmentSourcesResolve a message list in order, without mutation or caching

The helpers preserve typed resolver errors/services and protocol metadata, but do not traverse opaque payloads or enforce provider capabilities. See private attachment integration for fresh signing inside retries.

PlainHitlResponse is also a constructor value on @yolk-sdk/agent/protocol: PlainHitlResponse.QuestionResponse, .ToolApprovalResponse, .InputResponse, and .InteractionResponse construct plain encoded payloads. Use plainHitlResponse to project existing protocol class instances while omitting absent optionals.

Typed-input protocol exports:

ExportPurpose
InputDescriptor, InputRequest, InputResponse, InputResponseOutcomeDisplay metadata, correlated request, and submitted/cancelled response
InputRequested, InputSubmitted, InputCancelledInput lifecycle events
InputResponseInputTyped client control input
plainInputResponse, inputResponseStructuredContent, formatInputResponseContentSerialization and result-content helpers
InputToolHandler, InputResponseValidator, InputContentFormatterServer-side validation and formatting contracts

Input descriptors carry display hints only; original server schemas own validation. Input collection never authorizes an action. See Collect typed input.

Action-backed interaction protocol exports:

ExportPurpose
InteractionDescriptor, InteractionActionDescriptorApp-renderer metadata and server-defined action labels
InteractionRequest, InteractionResponse, InteractionResponseOutcomeDistinct action-backed request and submitted/cancelled response
InteractionRequested, InteractionSubmitted, InteractionCancelled, InteractionResponseInputLifecycle events and typed client control input
InteractionHost, InteractionRef, InteractionReceipt, InteractionReceiptStatus, InteractionClaimScoped host-owned accepted records and fenced execution
InteractionPreflight, InteractionResponseValidator, InteractionCallValidator, InteractionCandidateOriginal-schema admission contracts; candidates are not authority. Call validators and validateAction may fail with InteractionHostError when host storage is unavailable
InteractionAdmissionError, InteractionValidationError, InteractionHostErrorTyped admission, business-validation, and host failures; admission cause unavailable is a retryable storage outage, not invalid input
validateInteractionSubmission, interactionRequestIdValidate a candidate against the authoritative pending request
InteractionOutcome, InteractionBusinessOutcome, makeInteractionToolResult, interactionUnknownOutcomeNoticeExplicit completed, failed, or unknown observations
validInteractionReceipt, sameInteractionBinding, sameInteractionCall, interactionJsonEqualsPure receipt/binding checks; never authentication
plainInteractionResponse, interactionResponseStructuredContent, formatInteractionResponseContentSerialization and cancellation-content helpers

See Authorize one action for authenticated acceptance, immutable receipt storage and host-owned rendering. InteractionSubmitted is not completion.

Loop

@yolk-sdk/agent/loop

ExportPurpose
runstateless agent loop, returns Stream<AgentEvent>
runModelTurn, runToolBatchlower-level model/tool-turn primitives
RunInstruction, instructionMessageshost instructions (RunConfig.instructions); durable runModelTurn hosts append instructionMessages themselves
makeAgentLoopLayermerge provider plus optional tools/transformer/config layers
decorateLLMProviderwrap an existing LLMProvider service
collectModelTurnsuccess-only fold of a model-turn stream to ModelTurnResult
collectModelTurnAttemptCollected / StreamFailed / SinkFailed with ModelTurnCollection
ModelTurnResultfinalized { assistantMessage, toolCalls, usage, stopReason, usageUnavailable? }
ModelTurnCollectionresult plus outputStarted and partialAssistantMessage
CollectModelTurnAttemptResultcollector tagged union
LLMProviderprovider service contract
ToolExecutorhost tool execution service; ToolExecutor.unavailable is the omitted-tools default
ContextTransformerhost context compaction/injection service
LoopConfigloop limits/retry config service
LLMError, ToolErrorsafe loop/provider/tool failures
LLMResponseIssue'missing_done' literal: a stream that ended without Done
accumulateAssistantMessage, collectText, collectReasoning, collectToolCallsstream accumulator helpers
LLMReasoningReplayprovider event closing a reasoning block with its replay state (tag ReasoningReplay)
LoopConfigSettingssettings object for LoopConfig.layer (renamed from LoopConfigShape)

Breaking type import (runtime/wire unchanged, no Shape alias):

import type { LoopConfigSettings } from '@yolk-sdk/agent/loop'

LoopConfigShape is removed. Update import type { LoopConfigShape } to LoopConfigSettings.

loadInteractionReceipts(calls, interactionHost) loads authoritative snapshots before preflight. Pass interactions: toolSet.interactions and interactionHost: toolSet.interactionHost into run, runToolBatch, or RuntimeConfig. ToolExecutionOptions.interaction carries only an InteractionRef; executor decorators must forward it or fail closed.

Whole-batch preflight

prepareToolBatch({ tools, inputs, responses, calls }) returns Effect.Effect<PreparedToolBatch, ToolError> without executing tools. It fails, with ToolError unavailable, only when host storage read by an interaction call validator (for example the plan store of a plan review) is unavailable: nothing runs, so fail the step and retry it. tools, responses, and calls are readonly arrays of ToolDef, HitlResponse, and ToolCall. Pass inputs: toolSet.inputs from resolveTools when using typed input tools; definitions alone fail closed as unavailable. Forward the same handlers into LoopConfig and RuntimeConfig when using run, runToolBatch, or runRuntime. Pass approvalPreviews: toolSet.approvalPreviews (also on run, runToolBatch, and RuntimeConfig) so pending approval requests carry preview or previewError.

PreparedToolBatch fieldPurpose
callsToExecute{ index, call } entries eligible after preflight
resultMessagessynthetic { index, message } results, including denied calls and answered questions
resultEventssynthetic tool-completion events
eventsnon-pending preflight events
pendingRequests, pendingEventsunresolved HITL requests and their events

Any pendingRequests fence all dispatch, even when callsToExecute is nonempty. Hosts carry HITL state through pause/resume, preserve synthetic results, and merge executed results by original index before the next model turn. The helper computes the preflight; the host enforces the fence.

For action-backed tools, also pass interactions and the freshly loaded interactionReceipts map. Preparation never reads receipts, claims or executes; interaction call validators may read host storage (a plan review reads its plan store). The returned interactionBindings map is keyed by tool-call ID; forward its ref to ToolExecutor.execute(call, { interaction: ref }) only after every pending sibling is resolved.

Testing: @yolk-sdk/agent/loop/testing

ExportPurpose
FauxProviderdeterministic test provider layer
Replyfake model replies: text, reasoning, tool calls, usage
TestToolExecutorcanned tool results

Runtime

@yolk-sdk/agent/runtime

ExportPurpose
runRuntimetranscript or append-backed runtime stream
RuntimeConfig, RuntimeRequest, TranscriptRuntimeRequest, AppendInputRuntimeRequest, AppendHitlResponseRuntimeRequesttyped runtime inputs/config
SessionEventStoreappend-log service contract
makeInMemorySessionEventStoreLayertest/local store layer
InputAppended, HitlResponseAppended, RunStarted, RunCompleted, RunAwaitingInput, RunFailed, RunInterruptedruntime log events
appendRuntimeSessionEventsToLogappend helper for adapters
replayRuntimeSessionEvents, replayRuntimeHitlResponsesrebuild transcript/responses from log
latestIncompleteRuntimeRundetect interrupted active run
runtimeErrorToAgentErrormap runtime errors to protocol AgentError
SessionConflictError, SessionLoadError, SessionNotFoundError, SessionSaveErrorruntime/session error types

Runtime request tags:

  • Transcript
  • AppendInput
  • AppendHitlResponse

RuntimeRequest is both a type and a constructor value on @yolk-sdk/agent/runtime. Its variants are Transcript, AppendInput, and AppendHitlResponse.

Tools

@yolk-sdk/agent/tools

ExportPurpose
makeToolschema-backed tool registration
MakeTypedToolOptions, MakeContentToolOptions, MakeToolResultToolOptions, ToolOutput, ToolContentthe makeTool forms: typed ({ output }), content-only ({ content }), deprecated (ToolResult)
makeToolWithJsonSchemas, precomputeToolJsonSchemas, PrecomputedToolJsonSchemas, ToolJsonSchemaSourcea makeTool taking a host's build-time JSON Schema texts by tool name, and the one form a host generates and checks them in
resolveToolsfilter/merge modules into model-visible defs and executor
BackgroundToolHosthost seam that admits model-chosen background calls
makeToolExecutorLayerprovide resolved executor as ToolExecutor
EmptyToolParamsno-arg tool schema
ToolAccess, toolCallAccessread, write, destructive; a call's effective access (isReadCall)
makeQuestionToolModulebuilt-in question HITL tool
makeNonRecursiveSubagentToolModulesubagent tool without recursive delegation
SubagentRuntimeSelectionOptionshost-advertised subagent model and reasoning choices
SubagentModelDefinitionmodel id and model-visible selection guidance
SubagentReasoningEffortDefinitionreasoning effort and model-visible selection guidance
modelVisibleToolErrorrecoverable error visible to model
withToolArgumentsErrorHintappend unknown-argument hints, and wrong-type hints for Yolk's own argument decode errors
omitNullOptionalToolArgumentsdrop strict-mode nulls for hosts dispatching directly
makePlanReviewTool, MakePlanReviewToolOptions, toolPlanReviewToolName, toolPlanReviewRenderer, toolPlanReviewActionIdplan review interaction (review_plan) that applies a person's selection of a staged plan once (staged plans)
ToolPlanStore, StoredToolPlan, ToolPlanClaimResult, ToolPlanStoreError, ToolPlanOptions, makeInMemoryToolPlanStore, InMemoryToolPlanStorehost-implemented plan storage (resolveTools plans option) and a non-durable reference
ToolPlan, StagedCall, ToolPlanReviewParams, ToolPlanReviewResponse, toolPlanDigest, stagedCallDigest, toolPlanIntegrityProblempersisted plan Schemas and digests
ToolPlanOutcome, ToolPlanCallOutcome, ToolPlanCallStatus, ToolPlanCallCountsresult Schemas (structuredContent.result; statuses include input_required); ToolPlanApplyResult is the apply action's result type
previewToolPlan, previewStoredToolPlan, toolPlanKeyPages, ToolPlanPreview, ToolPlanPreviewPage, ToolPlanPreviewError, maxToolPlanPreviewKeysbounded, paged previews for review screens
makeInputReviewTool, MakeInputReviewToolOptions, inputReviewToolName, inputReviewRenderer, inputReviewActionId, maxInputReviewPausesinput review interaction (review_input) resuming stored pauses once (paused calls)
InputReviewHost, InputPause, InputPauseEntry, InputPauseResolutionhost port over stored pauses and the resolution of one resumed pause
InputReviewParams, InputReviewResponse, InputReviewOutcome, InputReviewPauseOutcome, InputReviewPauseStatus, inputReviewResultreview params, answers, and result Schemas (structuredContent.result of the interaction outcome)
ToolChangePreview, ToolFieldChange (ToolValueChange, ToolTextChange, ToolSetChange, ToolListChange, ToolStructuredChange), ToolChangeTarget, ToolChangeItem, ToolChangeScalar, ToolChangeCut, ToolChangeSideCuts, ToolChangeSetCuts, ToolChangePreviewError, ToolChangePreviewErrorCause, ToolChangePreviewFailure, ToolApprovalPreviewertool-agnostic before → after change preview Schemas and the ToolApprovalPreviewer loop seam (also in ./protocol; preview the change)
ToolChangePreviewHandler, ToolChangePreviewOptions, boundToolChangePreview, toolChangeSignature, groupToolChangePreviews, ToolChangeGroup, isToolChangePreviewTruncated, defaultToolChangePreviewMaxBytes, minToolChangePreviewMaxBytes, defaultToolChangePreviewTimeoutMschange preview hook, truncation, grouping, and defaults (16 KiB, at least 1 KiB, 5 s)
ToolStaging, ToolStagingHandlers, ToolPlanBeforeCall, ToolPlanFailurePolicy, ToolPlanRuntime, ToolPlanStaging, ToolPlanBuilder, StagedCallReceipt, ToolPlanStageError, ToolPlanStageErrorReason, NestedToolStagingDescription, ResolvedToolPlansstaging hooks, the per-call beforeCall authority hook, and staging contracts for nested-access tools
stagedToolPlanNotice, StagedToolPlanRefsaved-plan notice code mode writes; the tool ledger keeps a cut replay's plan only with it
defaultToolPlanMaxCalls, defaultToolPlanMaxArgsBytes, toolPlanPrecheckConcurrencyplan defaults: 500 calls, 1 MiB of staged arguments, 8 concurrent prechecks
NestedTool, NestedToolExecutor, NestedToolDescribernested tool access for code mode registrations
NestedToolInstructorinstruct hook: a nested-access registration's host instruction (ResolvedToolSet.instructions)
makeToolSearchTool, rankToolSearchDocuments, toolSearchTokens, ToolSearchDocument, defaultToolSearchLimit, maxToolSearchLimitthe package tool_search tool and its BM25 ranking (shared with code mode search)
ToolLedgerStore, ToolLedgerOptions, ToolLedgerClaim, ToolLedgerClaimRequest, ToolLedgerHeartbeatRequest, ToolLedgerErrorhost-implemented durable tool-call ledger (resolveTools ledger option)
ToolLedgerDecision, ToolLedgerDecisionEventonLedgerDecision observability events
ToolLedgerEntry, ToolLedgerOutcome, ToolLedgerSucceeded, ToolLedgerFailed, ToolLedgerFailurepersisted ledger entry Schemas
makeInMemoryToolLedgerStore, InMemoryToolLedgerStore, classifyToolLedgerEntry, toolLedgerResult, toolLedgerArgs, ToolLedgerArgs, sortToolLedgerEntriesreference store and helpers for host stores
defaultToolLedgerLeaseMs, defaultToolLedgerPollIntervalMs, defaultToolLedgerMaxWaitMs, defaultToolLedgerMaxResultBytes, toolLedgerMaxArgsBytesledger defaults: 30 s lease, 1 s poll, 150 s wait, 1 MiB stored result, 8 KiB argument preview
toolLedgerCompleteTimeoutMstimeout of each complete attempt (5 s; three attempts) and heartbeat (or a sixth of leaseMs)
toolIdempotencyKey, defaultToolLedgerPolicy, abandonedToolCallResult, ToolLedgerPolicyInput, ToolLedgerAbandonedInput, ToolLedgerErrorDetailsidempotency keys, default policy, and ledger results
FileStoreApi, FileStoreError, ToolFileCaptureOptions, captureToolResultFiles, defaultMaxCapturedFileBytes, makeToolFileCapturefile capture (resolveTools files option, 100 MiB default bound; move files between tools)

makeTool also accepts output (typed results: execute returns { output }, encoded into structuredContent and declared as ToolDef.outputSchema; file fields are ToolFile, ADR 0013), render, callableBy, discovery, loading, invokesModel (the tool calls a model when it runs; copied to ToolMetadata.invokesModel and NestedTool.invokesModel), nestedToolAccess, describe, instruct, abandonedResult (the result of a ledgered call found abandoned), changePreview (approval-gated tools: the change preview of approvals and plan reviews; ResolvedToolSet.approvalPreviews carries the resolved previewers for loop configs, and resolveTools(..., { changePreview: { maxBytes, timeoutMs } }) bounds them), and staging (stageable approval-gated tools, with an optional precheck hook), and precomputedJsonSchemas ({ parameters, output? }: the JSON texts precomputeToolJsonSchemas gives for the tool's schemas, parsed for ToolDef.parameters and outputSchema instead of lowering the schemas when the tool is made; the host keeps them equal to the lowering, since a stale text is advertised as given, and calls still decode with parameters; an invalid text, or an output text without output, throws). makeToolWithJsonSchemas(lookup) returns a makeTool with the same overloads that passes each tool the texts lookup answers for (it gets the tool's ToolJsonSchemaSource: name and schemas). resolveTools(modules, context, { interactionHost, plans }) enables staged tool plans with one makePlanReviewTool registration; applied plan calls bypass beforeNestedCall and ToolExecutor decorators, so pass per-call checks as makePlanReviewTool({ beforeCall }). resolveTools(modules, context, { ledger }) runs ledgered calls (default every non-read tool plus the built-in subagent tool, top-level and nested) at most once per key, detects conflicts by argsDigest (SHA-256 of the full arguments), and passes executors, subagent executors included, a stable idempotencyKey; see Durable tool ledger. resolveTools(modules, context, { files: { store, maxFileBytes? } }) stores the inline bytes of every executed result (direct, nested, staged and interaction calls) before the ledger and replaces FilePart bytes with fileId labels; without it inline FilePart bytes become "file not captured" labels (move files between tools). ToolResult.nestedCalls, ToolResult.usage and ToolResult.usageIncomplete (the usage under-counts a nested model call that completed without its usage report) never reach the model: toolResultMessageFromResult drops them and the loop does not add ToolResult.usage to run usage. ToolRegistryError causes include codemode_unsupported_tool, invalid_tool_exposure, deferred_unsupported_tool, duplicate_instruction, staging_unsupported_policy, staging_validation_required, plan_review_duplicate, and change_preview_unsupported_policy. See Add code mode. resolveTools adds the package tool_search tool when any tool is deferred ({ toolSearch: false } opts out) and collects instruct hooks in ResolvedToolSet.instructions. ResolvedToolSet.nestedExecutor({ parentCallId }) returns the NestedToolExecutor a nested-access registration gets, bound to a host id instead of a tool call (no staging), for scripts the host runs itself (Run a script outside a model turn).

Typed-input helpers: makeInputTool keeps original call/response validators server-side; makeInputToolModule packages the registration as a module. makeInputToolDef creates only a serializable advertisement, not a handler or executor. ResolvedToolSet.inputs carries the resolved handlers alongside tools and execute; pass it explicitly to loop/runtime configs. Input tools reject approval/background policy and direct execution.

Action-backed helpers: makeInteractionTool and makeInteractionToolModule register inferred call/response schemas and server-defined actions. Resolve with { interactionHost }; pass both ResolvedToolSet.interactions and ResolvedToolSet.interactionHost to the loop/runtime. Host acceptance precedes SDK claim/execute; ordinary makeInputTool remains data-only.

Subagent/question helpers: makeSubagentToolModule, makeSubagentToolDef, makeSubagentToolResult, subagentToolName, makeQuestionToolDef, questionToolName.

Background tool calls: makeTool({ background: true }) (or ToolRegistration.background with a side-effect-free validate) opts a tool in; resolveTools(modules, context, { backgroundHost }) activates opted-in tools with a required { execution: 'foreground' | 'background', arguments } envelope. BackgroundToolHost.accept({ call, request, context }) returns a versioned BackgroundToolAccepted receipt; the registry returns one acknowledgement ToolResult with acceptance metadata and the loop emits ToolExecutionAccepted. Without a host, definitions and behavior are unchanged. Activation supports only document-root #/$defs/... pointers, with unsupported references/resource keywords rejected as ToolRegistryError.cause: 'background_unsupported_schema'. Activated definitions are unsupported in voice/realtime: synchronous realtime tool/config mappers throw VoiceToolBridgeError; their Effect counterparts return it in the typed error channel. Voice dispatch fails closed even with replayed approvals. See Tools and HITL.

Configure models and reasoningEfforts on a subagent tool module to expose validated optional model and reasoning_effort parameters to the parent agent. Omission means the host should inherit its current runtime setting. Hosts remain responsible for provider credentials, capability checks, constructing the selected child runtime, and context/tool-result budgeting. Pass effective runtime metadata to makeSubagentToolResult; optional reasoningEffort, usage, turns, and typed error fields are added to structured result metadata.

The public subagent types are:

// TypeScript fragments

type SubagentDefinition = {
  readonly name: string
  readonly description: string
}

type SubagentModelDefinition = {
  readonly id: string
  readonly description: string
}

type SubagentReasoningEffortDefinition = {
  readonly value: AgentReasoningEffort
  readonly description: string
}

type SubagentRuntimeSelectionOptions = {
  readonly background?: boolean
  readonly models?: ReadonlyArray<SubagentModelDefinition>
  readonly reasoningEfforts?: ReadonlyArray<SubagentReasoningEffortDefinition>
}

type SubagentContext = {
  readonly subagent?: boolean
}

type SubagentToolParams = {
  readonly description: string
  readonly prompt: string
  readonly subagent_type: string
  readonly model?: string
  readonly reasoning_effort?: AgentReasoningEffort
  readonly background?: boolean
}

type SubagentExecutionInput<Context> = {
  readonly call: ToolCall
  readonly context: Context
  readonly params: SubagentToolParams
  readonly idempotencyKey?: string // with a tool ledger: `<scope>:<ledger key>`
}

type SubagentToolOptions<Context> = SubagentRuntimeSelectionOptions & {
  readonly subagents: ReadonlyArray<SubagentDefinition>
  readonly isEnabled?: (context: Context) => Effect.Effect<boolean, ToolRegistryError>
  readonly execute: (input: SubagentExecutionInput<Context>) => Effect.Effect<ToolResult, ToolError>
}

type SubagentRunError = {
  readonly code: AgentErrorCode
  readonly message: string
  readonly retryable: boolean
  readonly provider?: ProviderErrorInfo
}

type SubagentRunStatus = 'completed' | 'awaiting_input' | 'error'

type SubagentRunResult = {
  readonly status: SubagentRunStatus
  readonly text: string
  readonly usage?: AgentUsage
  readonly turns?: number
  readonly requests?: ReadonlyArray<HitlRequest>
  readonly error?: SubagentRunError
}

type SubagentToolResultInput = {
  readonly callId: string
  readonly output: string
  readonly subagentType: string
  readonly description: string
  readonly subagentRunId: string
  readonly startedAtMs: number
  readonly endedAtMs: number
  readonly model: string
  readonly reasoningEffort?: AgentReasoningEffort
  readonly usage?: AgentUsage
  readonly turns?: number
  readonly status?: SubagentRunStatus
  readonly requests?: ReadonlyArray<HitlRequest>
  readonly error?: SubagentRunError
  readonly isError?: boolean
}

AgentReasoningEffort accepts none, minimal, low, medium, high, xhigh, or max (support is model dependent; Anthropic Messages rejects none). Model IDs are host-owned opaque strings and are not normalized by the subagent tool.

Subagent helper signatures:

HelperSignature and return
makeSubagentToolDef(subagents: ReadonlyArray<SubagentDefinition>, runtimeSelections?: SubagentRuntimeSelectionOptions) => ToolDef
makeSubagentToolRegistration<Context>(options: SubagentToolOptions<Context>) => ToolRegistration<Context>
makeSubagentToolModule<Context>(options: SubagentToolOptions<Context>) => ToolModule<Context>
makeNonRecursiveSubagentToolModule<Context extends SubagentContext>(options: SubagentToolOptions<Context>) => ToolModule<Context>
makeSubagentToolResult(input: SubagentToolResultInput) => ToolResult
makeSubagentAcceptedToolResult({ callId, workflowRunId, parentRunId? }) => ToolResult
formatSubagentResult(output: string) => string
subagentResultFromEvents(events: ReadonlyArray<AgentEvent>) => SubagentRunResult
subagentResultText(events: ReadonlyArray<AgentEvent>) => string
subagentUsageFromToolResult(result: ToolResult) => AgentUsage | undefined
subagentToolRunId(parentToolCallId: string) => string
subagentToolName"subagent"

Selections outside the configured enums, empty required strings, and unknown subagent types return model-visible validation results before host execution. Their structured error reason is validation. The host execute callback may fail with ToolError. makeSubagentToolResult includes optional fields only when provided. subagentResultFromEvents extracts terminal text and usage/turns from AgentEnd or AgentAwaitingInput, preserves awaiting HITL requests/status, or returns typed AgentError metadata. subagentResultText remains the compatibility text-only helper. Use subagentUsageFromToolResult to recover child usage from a structured result for cumulative host accounting.

Background acceptance

makeSubagentAcceptedToolResult({ callId, workflowRunId, parentRunId? }) returns a ToolResult; all input fields are strings. Enable background: true in registration options to advertise the optional model parameter. The host handles params.background and starts the actual child.

The acknowledgement carries type: 'subagent_accepted', status: 'accepted', logical subagent_run_id (subagent:<callId>), physical workflow_run_id, and optional parent_run_id. It completes the launch tool call, not the child: the loop emits no SubagentCompleted or child usage for this result. Later status/wait calls use their own tool-call ids; usage extraction requires the logical child id to match the result's call id, preventing observation calls from charging the original child again.

The SDK registers no status or wait tools and does not promise automatic completion delivery. Hosts choose whether to deliver findings automatically or expose authenticated observation tools, and own lookup, authorization, persistence, and Stop policy. Existing inline registrations remain unchanged. See Background subagents.

Client

@yolk-sdk/agent/client

ExportPurpose
streamAgentEventStreamUntilTerminalstart/consume HTTP stream until terminal event
streamAgentRunEventStreamUntilTerminalconsume durable run tail
streamAgentRunHitlResponseEventStreamUntilTerminalresume HITL and consume stream
streamAgentEventStreamone-shot NDJSON stream helper
streamAgentRunEventStreamdurable tail stream helper
streamAgentRunHitlResponseEventStreamdurable HITL stream helper
streamCloudflareAgentEventStreamCloudflare WebSocket stream helper
collectAgentEventscollect a stream into an array
streamToolApprovalResponseEventStream, streamQuestionResponseEventStreamclient resume stream helpers
cancelAgentRuncall host cancel endpoint
agentRunIdFromHeaders, agentRunStreamTailIndexFromHeaders, agentRunStreamStartIndexFromHeaders, agentRunEndpointWithStartIndexdurable route header helpers
initialAgentClientState, applyAgentEvent, reduceAgentEventsclient reducer helpers
toolRunsFromHitlRequestspaused UI hydration
markAgentRunStartrun start after a snapshot rebuild
documentPartFromTextFile, textFromBlobbrowser file/blob helpers returning Effect
BlobTextReadErrorfile/blob read failure
AgentTransportErrortransport and decoding failure

streamInputResponseEventStream submits a SubmitInputResponseRequest over HTTP. Clients build it via SubmitInputResponseRequest from @yolk-sdk/agent/client. InputResponseInput also travels through the Cloudflare WebSocket transport and durable HITL helpers. Hosts own auth, pending-request matching, and server validation.

streamInteractionResponseEventStream takes a SubmitInteractionResponseRequest for HTTP. InteractionResponseInput is its WebSocket control variant; durable HITL helpers also carry InteractionResponse. Transports submit candidates, not authenticated execution authority.

React

@yolk-sdk/agent/react exports useAgentChat and re-exports @yolk-sdk/agent/chat, the chat projection without React.

ExportPurpose
useAgentChatheadless chat hook
buildAgentChatItemsrender-friendly item model
applyAgentEventToChatProjectionreplay-safe durable projection
stepAgentChatProjection, AgentChatProjectionStepprojection plus the event status follows
stepAgentChatProjectionAll, AgentChatProjectionBatcha batch: projection, status events, whether message ids changed
AgentChatEventProjectionStateSchema, AgentChatStateSchema, the other …Schema exports, HitlPauseschat state Schemas (JSON via Schema.toCodecJson)
makeAgentChatEventProjectionStateprojection initial state
markChatRunStartrun start after a snapshot rebuild
applyAgentEventToChatMessagesephemeral stream reducer
buildAgentChatMessages, toAgentMessagesconvert chat UI messages to protocol messages
getActiveChatToolParts, getCompletedChatToolParts, getAgentChatLiveActivityCountchat projection selectors
deleteChatTurn, editChatUserMessage, regenerateChatMessagesFromchat editing helpers
AgentChatSessionEvent, UserMessageSubmitted, ProtocolMessageAppended, MessagesRegenerated, TurnDeleted, UserMessageEditedchat session event helpers

useAgentChat().submitInputResponse(response) submits typed input. ChatToolState and ToolRunState include InputRequested, InputSubmitted, and InputCancelled; render pending requests using host-owned forms keyed by InputRequest.input.kind. Keep it pending until server acceptance. Invalid submissions re-pend the same request and may be corrected; never synthesize replayable input results optimistically.

useAgentChat().submitInteractionResponse(response) submits an interaction candidate. ChatToolState and ToolRunState include InteractionRequested, InteractionSubmitted, and InteractionCancelled. Render by InteractionRequest.interaction.kind. Local submission does not accept or complete the action; server acceptance stays active until a real result, and stored interaction_outcome metadata distinguishes completed, failed, unknown and cancelled observations.

Tagged model constructors are also exported from @yolk-sdk/agent/react:

Model familyConstructor values
Messages and toolsAgentChatPart, ChatToolState
Rendered itemsAgentChatItem, AgentChatItemEnvelope, ToolRunState
Reducer actionsAgentChatAction
Message edit resultsDeleteChatTurnResult, EditChatUserMessageResult, RegenerateChatMessagesResult
Hook resultsAgentChatSubmitResult, AgentChatDeleteTurnResult, AgentChatRegenerateResult, AgentChatEditUserMessageResult, AgentChatHitlResponseResult
Duration descriptorsToolDurationKnown, ToolDurationUnknown

Duration descriptors use Schema.TaggedStruct.make (validated plains). The other companions are Data.taggedEnum values: plain objects with _tag last, not Equal/Hash classes. Omit absent optionals. Discriminate with $is (for example AgentChatAction.$is('Submit')(action)). useAgentChat dispatches AgentChatAction constructors and returns the hook-result constructors. The existing model types remain available under the same names.

Classification

@yolk-sdk/agent/classification (see Classifier models)

ExportPurpose
ClassifierModelprovider-neutral classifier service (classify(request))
classify, ClassificationRequestFor, ClassificationResultFor, ClassifierAnswerFor, ClassifierAnswersFortyped entry point; answers inferred from questions
ClassificationRequest, ClassificationResult, ClassificationUsage, ClassifierStaterequest, result, and usage schemas
ClassifierQuestion, BooleanClassifierQuestion, ChoiceClassifierQuestion, ScoreClassifierQuestionquestion schemas
ClassifierAnswer, BooleanClassifierAnswer, ChoiceClassifierAnswer, ScoreClassifierAnsweranswer schemas
ClassificationRequestInvalid, ClassificationProviderError, ClassificationResponseInvalid, ClassificationErrortyped errors; ClassificationResponseInvalid keeps billed usage
decodeClassificationRequest, decodeClassifierAnswer, decodeClassifierAnswers, isClassificationResultForvalidation helpers for provider implementations

Compaction

@yolk-sdk/agent/compaction

makeContextBudget accepts an optional maxInputTokens cap for provider- or endpoint-specific input ceilings below a model's total context window. usableInputTokens is the smaller of this cap and contextWindowTokens - reservedOutputTokens; omit it when the endpoint has no separate input ceiling.

ExportPurpose
makeContextBudget, contextBudgetStatus, contextBudgetUsageRatiobudget helpers
estimateAgentMessageTokens, estimateAgentMessagesTokens, estimateContentTokens, estimateTextTokenstoken estimation helpers
TokenEstimateOptions, MessageTokenEstimator, TranscriptTokenEstimatorhost tokenizer and estimator contracts
planWindowCompaction, applyCompactionPlan, compactWindowMessageswindow compaction helpers
makeWindowCompactionTransformerContextTransformer layer helper
makeCompactionCheckpointText, makeCompactionCheckpointMessagesynthetic checkpoint helpers
isCompactionCheckpointText, isCompactionCheckpointMessagehost-controlled marker predicates
formatAgentMessageForCompaction, formatAgentMessagesForCompactionrich transcript summary-source formatter
CompactionMessageFormatOptionsreasoning/tool formatting controls
compactionSummarySourceMessages, dropLeadingCompactionCheckpointMessagerepeated-summary helper
makeContextOverflowRetryProviderone-shot provider overflow retry wrapper
applyOverflowCompactionshared compact-or-skip decision
overflowCompactionMayRuncompact only before published output
overflowCompactionAttemptAllowed, overflowCompactionMaxAttempts, isOverflowCompactionAttemptCountdurable compact-once budget helpers
OverflowCompactionDecisionCompacted / Skipped
ContextOverflowRetryCompactionResult, ContextOverflowRetryCompactor, ContextOverflowRetryProviderInputretry wrapper contracts

TokenEstimateOptions.countTextTokens accepts a synchronous host tokenizer for message text, reasoning, and host tool-call ids/names. Media, message overhead, non-message request input, and vendor framing remain outside that callback. Window planners and transformers also accept a whole-transcript estimateTokens; use one estimator consistently and keep a safety margin.

Checkpoint predicates detect the package's open/close marker strings; they are not structural parsers. Use them only on host-produced projected context, not arbitrary user-authored messages.

OAuth

@yolk-sdk/agent/oauth

ExportPurpose
OAuthAccessToken, TokenBrokerRequest, TokenBrokerResponseprovider-neutral token contracts
credentialSourceFromBrokerturn a host token broker into a credential source
isTokenFresh, shouldRefreshToken, tokenRemainingTtlMstoken freshness helpers
OAuthErrorsafe OAuth error

Skillset

@yolk-sdk/agent/skillset

ExportPurpose
SkillInfo, parseSkillMarkdown, formatAvailableSkillsportable skill parsing/rendering
CommandInfo, parseCommandMarkdown, parseCommandArguments, renderCommandslash-command parsing/rendering
SkillsetManifest, emptySkillsetManifest, mergeSkillsetsskillset catalog helpers
validateSkillsetName, validateDirectoryNamesafe skillset names

Voice

VoiceSession, VoiceController and VoiceEventOutbox are exported from @yolk-sdk/agent/voice. VoiceSession.layer composes a supplied transport layer and optional eventLog; configured logging runs without an external event consumer, and omission never captures an ambient outbox. makeVoiceController now requires the VoiceTransport service instead of an option value. Transport layers are webSocketVoiceTransportLayer (voice) and webRtcVoiceTransportLayer (voice/browser). Keep a provided layer alive throughout use, or build with an explicit scope. Layer.succeed injects caller-owned resources; it does not allocate or finalize them.

@yolk-sdk/agent/voice

ExportPurpose
VoiceEvent, VoiceCommand, VoiceSessionConfig, VoiceSessionErrorprovider-neutral voice protocol
makeVoiceControllerclient controller: tool forwarding, approval pause/resume, batching
handleVoiceToolCall, decideVoiceToolCall, voiceApprovalRequestId, voiceToolDenialOutputserver-side tool policy/execution
VoiceSessionToolCallRequest, VoiceToolCallOutcomeserver tool endpoint wire contracts
executeVoiceToolCall, VoiceToolCallRequest, VoiceToolExecutionResult, VoiceToolBridgeErrortool bridge over ToolExecutor
projectVoiceEvent, emptyVoiceProjectionState, voiceSeedTextsFromMessagestranscript projection and reconnect seeds
StoredVoiceEvent, sequenceVoiceEvent, dedupeStoredVoiceEvents, makeVoiceEventIdreplay-safe durable voice events
makeWebSocketVoiceTransportEffect Socket voice transport; requires a host Socket.WebSocketConstructor layer
VoiceSpeechSynthesizer, VoiceSpeechRequest, VoiceSpeechResult, VoiceTranscriber, VoiceTranscriptionRequest, VoiceTranscriptionResult, VoiceTranscriptionSegment, VoiceSpeechError, VoiceSpeechErrorCode, speechResultToAudioPartone-shot TTS/STT contracts, results, and safe failures
VoiceTransporttransport service contract

@yolk-sdk/agent/voice/browser

ExportPurpose
makeWebRtcVoiceTransport, defaultWebRtcVoiceRuntimebrowser WebRTC transport with fake-able runtime seam

@yolk-sdk/agent/voice/react

ExportPurpose
useYolkVoiceheadless browser voice hook: lifecycle, drafts, approvals, audio attach

Providers

OpenAiProviderConfig.extraBody is JSON-object input (OpenAiRequestExtras on the existing providers/openai/provider subpath). Lowering drops canonical fields unread and snapshots surviving portable data; invalid/accessor input fails before HTTP. Chat transport defaults to one JSON body; streaming: true opts into SSE deltas, and OpenCode Go chat always streams. See the migration guide and Go configuration.

VercelAiGatewayProviderConfig also accepts factory options streaming and reasoningContent, both false by default. Enable streaming for SSE deltas; enable reasoningContent independently to preserve compatible models' reasoning output and assistant replay, which spends input tokens. It also accepts reasoningEffortFormat ('reasoning-object' by default; 'reasoning-effort' sends the literal field instead for DeepSeek-style hosts; 'omit' never sends the effort and never fails) and an optional thinking: { type: 'enabled' | 'disabled' } toggle merged into the request body. supportsPdfAttachments defaults to true for Gateway and can be set to false; generic OpenAiProviderConfig defaults it to false. When enabled, URL-backed PDF user-message parts are fetched and buffered through the host-provided HttpClient before provider submission. Hosts own URL authorization, redirect and credential policy, streamed limits, timeouts, and safe logging; see provider setup.

SubpathMain exports
@yolk-sdk/agent/providers/openai/providermakeOpenAiProviderLayer, OpenAiProviderLayer, OpenAiProviderConfig, toOpenAiRequestBody, openAiChatResponseIssues, OpenAiChatResponseIssue
@yolk-sdk/agent/providers/openai/conformanceopenAiConformanceFixtures, openAiConformanceCases, OpenAiConformanceConfig, and seven synthetic OpenAI chat WireFixtures; openAiCodexConformanceFixtures, openAiCodexConformanceCases, OpenAiCodexConformanceConfig, four synthetic Codex Responses WireFixtures and the Codex usage case (openAiCodexUsageSnapshotCase, OpenAiCodexUsageConformanceConfig) and fixture
@yolk-sdk/agent/providers/openai/codexCodex request, auth, OAuth token, and broker helpers
@yolk-sdk/agent/providers/openai/codex-usagefetchOpenAiCodexSubscriptionUsage, parser, URL, and options
@yolk-sdk/agent/providers/openai/codex-providermakeOpenAiCodexProviderLayer, OpenAiCodexProviderConfig, toOpenAiCodexRequestBody
@yolk-sdk/agent/providers/openaiCodex OAuth/broker helpers
@yolk-sdk/agent/providers/openai/realtimeRealtime session config, server-event decoder, VoiceEvent mapper, client codec
@yolk-sdk/agent/providers/openai/speechOpenAiSpeechConfig, makeOpenAiSpeechSynthesizerLayer, makeOpenAiTranscriberLayer
@yolk-sdk/agent/providers/vercel/ai-gateway-providermakeVercelAiGatewayProviderLayer, VercelAiGatewayProviderLayer, config/routing types, URL/id
@yolk-sdk/agent/providers/vercel/ai-gateway-classifiermakeVercelAiGatewayClassifierLayer, VercelAiGatewayClassifierLayer, VercelAiGatewayClassifierConfig, vercelAiGatewayClassifierDefaultModel, vercelAiGatewayEvaluateUrl, vercelAiGatewayBaseUrl, vercelAiGatewayEvaluatePath, vercelAiGatewayEvaluationFallbackHeaderPrefix
@yolk-sdk/agent/providers/vercel/conformancevercelAiGatewayConformanceFixtures and four verified Gateway WireFixture recordings for replay tests; vercelAiGatewayClassifierConformanceFixtures, vercelAiGatewayClassifierConformanceCases, VercelAiGatewayClassifierConformanceConfig, and four synthetic classifier WireFixtures
@yolk-sdk/agent/providers/opencode/go-providermakeOpenCodeGoProviderLayer, OpenCodeGoProviderConfig, OpenCodeGoProtocol, OpenCodeGoReasoningSummary, openCodeGoBaseUrl, openCodeGoProviderId
@yolk-sdk/agent/providers/opencode/usagefetchOpenCodeGoSubscriptionUsage, parseOpenCodeGoSubscriptionUsage, OpenCodeGoSubscriptionUsageOptions, openCodeGoSubscriptionUsageUrl
@yolk-sdk/agent/providers/opencode/conformanceopenCodeGoConformanceFixtures, openCodeGoConformanceCases, OpenCodeGoConformanceConfig, and five synthetic OpenCode Go WireFixtures (plain text per protocol, commentary replay, usage)
@yolk-sdk/agent/providers/anthropic/claudeClaude request, auth, OAuth token, authorization URL, and broker helpers
@yolk-sdk/agent/providers/anthropic/usagefetchAnthropicClaudeSubscriptionUsage, parser, URL, and options
@yolk-sdk/agent/providers/anthropic/claude-providermakeAnthropicClaudeProviderLayer, AnthropicClaudeProviderConfig, AnthropicClaudeThinkingConfig, toAnthropicClaudeRequestBody, streamAnthropicClaudeResponse, anthropicClaudeReasoningReplayProvider
@yolk-sdk/agent/providers/anthropic/conformanceanthropicConformanceFixtures, anthropicConformanceCases, AnthropicConformanceConfig, five synthetic Anthropic Messages WireFixtures, and the Claude usage case (anthropicClaudeUsageSnapshotCase, AnthropicClaudeUsageConformanceConfig) and fixture
@yolk-sdk/agent/providers/anthropicClaude OAuth/broker helpers
@yolk-sdk/agent/providers/xai/grokGrok OAuth constants, authorization URL/parser, auth headers, token, and broker helpers
@yolk-sdk/agent/providers/xai/grok-providermakeXAiGrokProviderLayer, toXAiGrokRequestBody, streamXAiGrokResponse, config/reasoning types
@yolk-sdk/agent/providers/xai/usagefetchXAiGrokSubscriptionUsage, parser, URL, and options
@yolk-sdk/agent/providers/xai/conformancexAiGrokConformanceFixtures, xAiGrokConformanceCases, XAiGrokConformanceConfig, four synthetic Grok Responses WireFixtures, and the Grok usage case (xAiGrokUsageSnapshotCase, XAiGrokUsageConformanceConfig) and fixture
@yolk-sdk/agent/providers/xaiGrok OAuth/broker helpers
@yolk-sdk/agent/providers/subscription-usageSnapshot/window schemas and sanitized request/response/auth/rate-limit/configuration errors

Subscription-usage fetchers require HttpClient.HttpClient. Claude, Codex, and Grok require a matching fresh OAuthAccessToken; OpenCode Go requires a redacted API key (Redacted<string>). All accept an optional positive requestTimeoutMs and an optional url endpoint override that defaults to the exported URL constant. Override url only with a trusted proxy or local emulator: the credential is sent to it. Grok additionally requires explicit xAiUserId and truthful host clientVersion options and does not derive the xAI identity from generic token accountId. With FetchHttpClient.layer, redirects are manual and rejected. A custom HttpClient must not follow redirects for these credential-bearing requests. Returned windows is an immutable Effect Chunk whose entries have semantic id, usedPercent, and optional resetsAt, resetsAfterSeconds, windowDurationMinutes, and models (lowercase model id substrings a model-scoped window limits; absent means every model of the account) fields. HTTP, decoding, and recognized malformed-field failures use sanitized ProviderSubscriptionUsageError variants; unrecognized or absent buckets may produce an empty snapshot. Raw response bodies are not retained.

Provider output limits are host-owned where supported:

  • OpenAiProviderConfig.maxCompletionTokens becomes vendor max_completion_tokens.
  • VercelAiGatewayProviderConfig.maxCompletionTokens becomes Gateway max_tokens; optional fallbackModels and routing become Gateway request extensions.
  • ChatGPT subscription Codex rejects vendor max_output_tokens; its optional deprecated maxOutputTokens compatibility field is ignored.
  • AnthropicClaudeProviderConfig.maxTokens becomes vendor max_tokens.
  • XAiGrokProviderConfig.maxOutputTokens becomes vendor max_output_tokens on the xAI CLI proxy.
  • XAiGrokProviderConfig.clientVersion is required and sent as x-grok-client-version; the xAI CLI proxy version-gates requests and rejects missing or outdated client versions with HTTP 426.
  • OpenAiProviderLayer reads OPENAI_API_KEY and integer OPENAI_MAX_COMPLETION_TOKENS through Effect Config.
  • VercelAiGatewayProviderLayer reads AI_GATEWAY_API_KEY, falls back to VERCEL_OIDC_TOKEN, and requires integer AI_GATEWAY_MAX_COMPLETION_TOKENS.

Provider prompt caching is always on. LLMRequest.cacheKey (set it once as cacheKey on RunConfig or RuntimeConfig) routes a conversation to its cached prefix, LLMRequest.turnContext carries per-request text after the conversation, and LLMRequest.toolChoice: 'none' forbids tool calls while keeping the definitions. AnthropicClaudeProviderConfig.promptCacheTtl ('5m' default or '1h') sets the Claude cache lifetime; OpenAiProviderConfig.cacheKeyHeaders opts a generic OpenAI-compatible endpoint into session headers. See Prompt caching.

AnthropicClaudeProviderConfig.thinking (display, optional prefixMismatchBehavior) requests adaptive thinking summaries. The Claude provider keeps each thinking block's signature on AssistantReasoningPart.replay (streamed as the LLMReasoningReplay agent event) and sends the block back unchanged, in produced order. Never edit a reasoning part that has replay.

toOpenAiRequestBody, toAnthropicClaudeRequestBody, and toXAiGrokRequestBody require matching limit configuration. toOpenAiCodexRequestBody accepts the optional ignored compatibility field but sends no output limit. Yolk does not infer limits from model ids. Generic OpenAI-compatible hosts may select OpenAiProviderConfig.completionTokenField, add endpoint extensions through extraBody, and set providerIdentity for accurate safe error metadata; canonical request fields and required HTTP headers take precedence.

Chat Completions responses the parser rejects fail non-retryable invalid_response with provider.kind: 'invalid_response' and a providerCode from openAiChatResponseIssues naming the failed check (invalid_stream_json, invalid_stream_chunk, invalid_reasoning, invalid_tool_call, invalid_tool_arguments, invalid_usage, invalid_response_json, invalid_response_body, missing_choices). Streamed failures also carry provider.stream diagnostics. The codes are fixed literals, never upstream values, so hosts can log and persist them.

Every provider turns a returned tool call into an LLMToolCall by decoding protocol ToolCall, whose id and name are non-empty trimmed strings. A malformed call (for example an empty name) fails as the provider's own typed non-retryable LLMError (invalid_response; Chat Completions adds providerCode: 'invalid_tool_call'), never a defect, so it reaches the loop's error handling (the loop does not retry it), host fallback models and host failure handling.

Claude lowering (toAnthropicClaudeRequestBody / makeAnthropicClaudeProviderLayer) requires ToolDef.parameters and ToolCall.params to decode as Schema.Json. Non-JSON fails non-retryable LLMError provider_error. Protocol ToolDef.parameters admits a ToolJsonSchema representation at construction; tool-call params and results stay opaque. Lone-surrogate rewrite is re-decoded as JSON (failure, not skip). HTTP non-JSON errors still classify from status.

Result conversion and typed realtime builders

SubpathExportContract
@yolk-sdk/agent/protocoltoolResultMessageFromResult(result, envelope?)Preserve all result payload fields and acceptance; optional explicit message envelope
@yolk-sdk/agent/providers/openai/realtimetoOpenAiRealtimeToolEffect(tool)Effect<OpenAiRealtimeFunctionTool, VoiceToolBridgeError>
@yolk-sdk/agent/providers/openai/realtimemakeOpenAiRealtimeSessionConfigEffect(input)Effect<OpenAiRealtimeSessionConfig, VoiceToolBridgeError>
@yolk-sdk/agent/providers/openai/realtimeopenAiRealtimeSessionConfigFromVoiceEffect(config, tools)Effect<OpenAiRealtimeSessionConfig, VoiceToolBridgeError>

The synchronous realtime exports remain available; use the Effect variants inside Effect programs so unsupported background activation is catchable before host transport effects.

On this page