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.
| Export | Purpose |
|---|---|
UserMessage, AssistantAgentMessage, ToolResultMessage | transcript messages |
AgentEvent | stream event union |
UserMessageEvent, AssistantMessageEvent | replay-safe transcript events |
AssistantReasoningReplay, SignedReasoningReplay, RedactedReasoningReplay, LLMReasoningReplay | opaque 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, ToolResult | tool protocol |
BackgroundToolAccepted, BackgroundToolInput, decodeBackgroundToolInput, makeBackgroundToolAcceptedResult | background tool acceptance |
ToolCallableBy, ToolDiscovery, ToolExposure, toolDiscovery, isCodeModeCallable, isCodeModeFailClosed | code mode tool exposure (code mode) |
isToolStageable | approval-gated tools a code mode script may stage into a reviewed plan (ToolDef.staging; staged plans) |
providerToolDefs, isProviderToolDef | filter out codemode-only defs (realtime sessions; send declaredToolDefs in text requests) |
ToolLoading, isDeferredTool, declaredToolDefs, activatedToolNames, ToolSearchActivation, toolSearchToolName | deferred 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, latestInstructionMessages | host instruction messages (UserMessage.instruction); keep latestInstructionMessages through custom compaction (host instructions) |
NestedToolCalls, NestedToolCallRecord, NestedToolCallStatus, NestedToolCallAccess, NestedToolCallCounts, recordNestedToolCall, nestedToolCallResultFields, makeNestedToolCallRecorder, emptyNestedToolCallRecorder | bounded, non-model-visible nested call record for ToolResult.nestedCalls, with per-status counts |
nestedToolCallMaxCalls, nestedToolCallMaxArgsBytes, nestedToolCallMaxTotalArgsBytes, nestedToolCallMaxErrorChars | nested call record bounds (nestedToolCallMaxCalls is the default maxCalls) |
nestedToolCallMaxRecordedCalls, nestedToolCallRecordLimit, boundNestedToolCallArgs, BoundedNestedToolCallArgs | record size ceiling (4096), maxCalls clamping, and the shared per-call/total argument budgets |
truncateCodePoints | cut text to a code point budget with a trailing … (nested-call errors, code mode) |
ToolExecutionAccepted | background admission event |
ToolApprovalRequest, ToolApprovalResponse | approval HITL; requests carry an optional preview (ToolChangePreview) or previewError |
makeInputRequiredToolResult, toolInputRequired, toolInputRequiredCode, ToolInputRequired, ToolInputRequiredRef, mergeInputRequiredRefs, inputRequiredNotice, inputReviewCallText, maxInputReviewPauses | error 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, ToolApprovalPreviewer | tool change preview Schemas and the ToolApprovalPreviewer loop seam (preview the change) |
QuestionRequest, QuestionResponse | question HITL |
plainHitlResponse, hitlResponseEvent, questionResponseStructuredContent | durable/client HITL helpers |
isTerminalAgentEvent | terminal 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, isSubagentObservationToolResult | run status in OSC 7501 vocabulary (agent status) |
assistantContent, contentText, contentParts | content helpers |
ImagePart, DocumentPart, AudioPart, FilePart, TextPart | multimodal content parts |
urlAttachmentSource, inlineBase64AttachmentSource, refAttachmentSource, attachmentSourceText, AttachmentTextDecodeError | attachment 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, normalizeFileMimeType | file parts and descriptors (move files between tools); ToolResult.files lists captured files and never reaches providers |
FileBytes, ToolFile, FileRef, FileUnavailable, ToolFileValue, isFileRef, fileUnavailable, noFileStoreReason, containsToolFile | typed file fields (ADR 0013): tools return FileBytes in ToolFile output fields; the encoding holds a FileRef or FileUnavailable |
FileStored, ToolFileOutput, ToolFileCapture, captureToolFileValue, capturedFileParts | a 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, CapturedToolFile | typed tool results for raw registrations and adapters (encoding fails closed on non-JSON values) |
toolOutputDecoder, ToolOutputDecoder | ToolRegistration.decodeOutput of an output schema: the result check resolveTools runs (excess properties rejected, plain JSON only) |
toolFileJsonSchemaDefinitions, toolFileJsonSchema, toolFileLabel | canonical $defs of file fields for hand-built output schemas (MCP), and their labels |
FileSource, OmittedFileSource, omittedFilePart | FilePart sources: an Omitted { reason } marks an unstored file (lowered as the "not captured" label) |
AgentModelCapabilities, textOnlyModelCapabilities, textImageModelCapabilities, textImageDocumentModelCapabilities | model input capability helpers |
ProviderErrorInfo, ProviderFailureKind, ProviderStreamDiagnostics, ProviderStreamInvalidField, ProviderStreamFieldType, ProviderStreamProtocol, ProviderStreamResponseFormat | safe provider error metadata, incl. optional stream diagnostics (invalidField on invalid_stream_chunk) and quotaResetsAtMs (subscription quota reset, rate_limit only) |
AgentUsage, addAgentUsage, zeroAgentUsage | usage accounting helpers |
CompactionStart, CompactionEnd | compaction lifecycle events |
validateNoDanglingHostToolCalls, repairDanglingHostToolCalls, danglingHostToolCalls | transcript invariant helpers |
Attachment resolution helpers from @yolk-sdk/agent/protocol:
| Export | Purpose |
|---|---|
AttachmentSourceResolver<E, R> | Host Effect callback from a media part to an attachment source |
resolveContentAttachmentSources | Resolve media sources in one Content |
resolveMessageAttachmentSources | Resolve one message, including assistant text and nested provider tool results |
resolveMessagesAttachmentSources | Resolve 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:
| Export | Purpose |
|---|---|
InputDescriptor, InputRequest, InputResponse, InputResponseOutcome | Display metadata, correlated request, and submitted/cancelled response |
InputRequested, InputSubmitted, InputCancelled | Input lifecycle events |
InputResponseInput | Typed client control input |
plainInputResponse, inputResponseStructuredContent, formatInputResponseContent | Serialization and result-content helpers |
InputToolHandler, InputResponseValidator, InputContentFormatter | Server-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:
| Export | Purpose |
|---|---|
InteractionDescriptor, InteractionActionDescriptor | App-renderer metadata and server-defined action labels |
InteractionRequest, InteractionResponse, InteractionResponseOutcome | Distinct action-backed request and submitted/cancelled response |
InteractionRequested, InteractionSubmitted, InteractionCancelled, InteractionResponseInput | Lifecycle events and typed client control input |
InteractionHost, InteractionRef, InteractionReceipt, InteractionReceiptStatus, InteractionClaim | Scoped host-owned accepted records and fenced execution |
InteractionPreflight, InteractionResponseValidator, InteractionCallValidator, InteractionCandidate | Original-schema admission contracts; candidates are not authority. Call validators and validateAction may fail with InteractionHostError when host storage is unavailable |
InteractionAdmissionError, InteractionValidationError, InteractionHostError | Typed admission, business-validation, and host failures; admission cause unavailable is a retryable storage outage, not invalid input |
validateInteractionSubmission, interactionRequestId | Validate a candidate against the authoritative pending request |
InteractionOutcome, InteractionBusinessOutcome, makeInteractionToolResult, interactionUnknownOutcomeNotice | Explicit completed, failed, or unknown observations |
validInteractionReceipt, sameInteractionBinding, sameInteractionCall, interactionJsonEquals | Pure receipt/binding checks; never authentication |
plainInteractionResponse, interactionResponseStructuredContent, formatInteractionResponseContent | Serialization 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
| Export | Purpose |
|---|---|
run | stateless agent loop, returns Stream<AgentEvent> |
runModelTurn, runToolBatch | lower-level model/tool-turn primitives |
RunInstruction, instructionMessages | host instructions (RunConfig.instructions); durable runModelTurn hosts append instructionMessages themselves |
makeAgentLoopLayer | merge provider plus optional tools/transformer/config layers |
decorateLLMProvider | wrap an existing LLMProvider service |
collectModelTurn | success-only fold of a model-turn stream to ModelTurnResult |
collectModelTurnAttempt | Collected / StreamFailed / SinkFailed with ModelTurnCollection |
ModelTurnResult | finalized { assistantMessage, toolCalls, usage, stopReason, usageUnavailable? } |
ModelTurnCollection | result plus outputStarted and partialAssistantMessage |
CollectModelTurnAttemptResult | collector tagged union |
LLMProvider | provider service contract |
ToolExecutor | host tool execution service; ToolExecutor.unavailable is the omitted-tools default |
ContextTransformer | host context compaction/injection service |
LoopConfig | loop limits/retry config service |
LLMError, ToolError | safe loop/provider/tool failures |
LLMResponseIssue | 'missing_done' literal: a stream that ended without Done |
accumulateAssistantMessage, collectText, collectReasoning, collectToolCalls | stream accumulator helpers |
LLMReasoningReplay | provider event closing a reasoning block with its replay state (tag ReasoningReplay) |
LoopConfigSettings | settings 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 field | Purpose |
|---|---|
callsToExecute | { index, call } entries eligible after preflight |
resultMessages | synthetic { index, message } results, including denied calls and answered questions |
resultEvents | synthetic tool-completion events |
events | non-pending preflight events |
pendingRequests, pendingEvents | unresolved 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
| Export | Purpose |
|---|---|
FauxProvider | deterministic test provider layer |
Reply | fake model replies: text, reasoning, tool calls, usage |
TestToolExecutor | canned tool results |
Runtime
@yolk-sdk/agent/runtime
| Export | Purpose |
|---|---|
runRuntime | transcript or append-backed runtime stream |
RuntimeConfig, RuntimeRequest, TranscriptRuntimeRequest, AppendInputRuntimeRequest, AppendHitlResponseRuntimeRequest | typed runtime inputs/config |
SessionEventStore | append-log service contract |
makeInMemorySessionEventStoreLayer | test/local store layer |
InputAppended, HitlResponseAppended, RunStarted, RunCompleted, RunAwaitingInput, RunFailed, RunInterrupted | runtime log events |
appendRuntimeSessionEventsToLog | append helper for adapters |
replayRuntimeSessionEvents, replayRuntimeHitlResponses | rebuild transcript/responses from log |
latestIncompleteRuntimeRun | detect interrupted active run |
runtimeErrorToAgentError | map runtime errors to protocol AgentError |
SessionConflictError, SessionLoadError, SessionNotFoundError, SessionSaveError | runtime/session error types |
Runtime request tags:
TranscriptAppendInputAppendHitlResponse
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
| Export | Purpose |
|---|---|
makeTool | schema-backed tool registration |
MakeTypedToolOptions, MakeContentToolOptions, MakeToolResultToolOptions, ToolOutput, ToolContent | the makeTool forms: typed ({ output }), content-only ({ content }), deprecated (ToolResult) |
makeToolWithJsonSchemas, precomputeToolJsonSchemas, PrecomputedToolJsonSchemas, ToolJsonSchemaSource | a makeTool taking a host's build-time JSON Schema texts by tool name, and the one form a host generates and checks them in |
resolveTools | filter/merge modules into model-visible defs and executor |
BackgroundToolHost | host seam that admits model-chosen background calls |
makeToolExecutorLayer | provide resolved executor as ToolExecutor |
EmptyToolParams | no-arg tool schema |
ToolAccess, toolCallAccess | read, write, destructive; a call's effective access (isReadCall) |
makeQuestionToolModule | built-in question HITL tool |
makeNonRecursiveSubagentToolModule | subagent tool without recursive delegation |
SubagentRuntimeSelectionOptions | host-advertised subagent model and reasoning choices |
SubagentModelDefinition | model id and model-visible selection guidance |
SubagentReasoningEffortDefinition | reasoning effort and model-visible selection guidance |
modelVisibleToolError | recoverable error visible to model |
withToolArgumentsErrorHint | append unknown-argument hints, and wrong-type hints for Yolk's own argument decode errors |
omitNullOptionalToolArguments | drop strict-mode nulls for hosts dispatching directly |
makePlanReviewTool, MakePlanReviewToolOptions, toolPlanReviewToolName, toolPlanReviewRenderer, toolPlanReviewActionId | plan review interaction (review_plan) that applies a person's selection of a staged plan once (staged plans) |
ToolPlanStore, StoredToolPlan, ToolPlanClaimResult, ToolPlanStoreError, ToolPlanOptions, makeInMemoryToolPlanStore, InMemoryToolPlanStore | host-implemented plan storage (resolveTools plans option) and a non-durable reference |
ToolPlan, StagedCall, ToolPlanReviewParams, ToolPlanReviewResponse, toolPlanDigest, stagedCallDigest, toolPlanIntegrityProblem | persisted plan Schemas and digests |
ToolPlanOutcome, ToolPlanCallOutcome, ToolPlanCallStatus, ToolPlanCallCounts | result Schemas (structuredContent.result; statuses include input_required); ToolPlanApplyResult is the apply action's result type |
previewToolPlan, previewStoredToolPlan, toolPlanKeyPages, ToolPlanPreview, ToolPlanPreviewPage, ToolPlanPreviewError, maxToolPlanPreviewKeys | bounded, paged previews for review screens |
makeInputReviewTool, MakeInputReviewToolOptions, inputReviewToolName, inputReviewRenderer, inputReviewActionId, maxInputReviewPauses | input review interaction (review_input) resuming stored pauses once (paused calls) |
InputReviewHost, InputPause, InputPauseEntry, InputPauseResolution | host port over stored pauses and the resolution of one resumed pause |
InputReviewParams, InputReviewResponse, InputReviewOutcome, InputReviewPauseOutcome, InputReviewPauseStatus, inputReviewResult | review 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, ToolApprovalPreviewer | tool-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, defaultToolChangePreviewTimeoutMs | change 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, ResolvedToolPlans | staging hooks, the per-call beforeCall authority hook, and staging contracts for nested-access tools |
stagedToolPlanNotice, StagedToolPlanRef | saved-plan notice code mode writes; the tool ledger keeps a cut replay's plan only with it |
defaultToolPlanMaxCalls, defaultToolPlanMaxArgsBytes, toolPlanPrecheckConcurrency | plan defaults: 500 calls, 1 MiB of staged arguments, 8 concurrent prechecks |
NestedTool, NestedToolExecutor, NestedToolDescriber | nested tool access for code mode registrations |
NestedToolInstructor | instruct hook: a nested-access registration's host instruction (ResolvedToolSet.instructions) |
makeToolSearchTool, rankToolSearchDocuments, toolSearchTokens, ToolSearchDocument, defaultToolSearchLimit, maxToolSearchLimit | the package tool_search tool and its BM25 ranking (shared with code mode search) |
ToolLedgerStore, ToolLedgerOptions, ToolLedgerClaim, ToolLedgerClaimRequest, ToolLedgerHeartbeatRequest, ToolLedgerError | host-implemented durable tool-call ledger (resolveTools ledger option) |
ToolLedgerDecision, ToolLedgerDecisionEvent | onLedgerDecision observability events |
ToolLedgerEntry, ToolLedgerOutcome, ToolLedgerSucceeded, ToolLedgerFailed, ToolLedgerFailure | persisted ledger entry Schemas |
makeInMemoryToolLedgerStore, InMemoryToolLedgerStore, classifyToolLedgerEntry, toolLedgerResult, toolLedgerArgs, ToolLedgerArgs, sortToolLedgerEntries | reference store and helpers for host stores |
defaultToolLedgerLeaseMs, defaultToolLedgerPollIntervalMs, defaultToolLedgerMaxWaitMs, defaultToolLedgerMaxResultBytes, toolLedgerMaxArgsBytes | ledger defaults: 30 s lease, 1 s poll, 150 s wait, 1 MiB stored result, 8 KiB argument preview |
toolLedgerCompleteTimeoutMs | timeout of each complete attempt (5 s; three attempts) and heartbeat (or a sixth of leaseMs) |
toolIdempotencyKey, defaultToolLedgerPolicy, abandonedToolCallResult, ToolLedgerPolicyInput, ToolLedgerAbandonedInput, ToolLedgerErrorDetails | idempotency keys, default policy, and ledger results |
FileStoreApi, FileStoreError, ToolFileCaptureOptions, captureToolResultFiles, defaultMaxCapturedFileBytes, makeToolFileCapture | file 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:
| Helper | Signature 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
| Export | Purpose |
|---|---|
streamAgentEventStreamUntilTerminal | start/consume HTTP stream until terminal event |
streamAgentRunEventStreamUntilTerminal | consume durable run tail |
streamAgentRunHitlResponseEventStreamUntilTerminal | resume HITL and consume stream |
streamAgentEventStream | one-shot NDJSON stream helper |
streamAgentRunEventStream | durable tail stream helper |
streamAgentRunHitlResponseEventStream | durable HITL stream helper |
streamCloudflareAgentEventStream | Cloudflare WebSocket stream helper |
collectAgentEvents | collect a stream into an array |
streamToolApprovalResponseEventStream, streamQuestionResponseEventStream | client resume stream helpers |
cancelAgentRun | call host cancel endpoint |
agentRunIdFromHeaders, agentRunStreamTailIndexFromHeaders, agentRunStreamStartIndexFromHeaders, agentRunEndpointWithStartIndex | durable route header helpers |
initialAgentClientState, applyAgentEvent, reduceAgentEvents | client reducer helpers |
toolRunsFromHitlRequests | paused UI hydration |
markAgentRunStart | run start after a snapshot rebuild |
documentPartFromTextFile, textFromBlob | browser file/blob helpers returning Effect |
BlobTextReadError | file/blob read failure |
AgentTransportError | transport 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.
| Export | Purpose |
|---|---|
useAgentChat | headless chat hook |
buildAgentChatItems | render-friendly item model |
applyAgentEventToChatProjection | replay-safe durable projection |
stepAgentChatProjection, AgentChatProjectionStep | projection plus the event status follows |
stepAgentChatProjectionAll, AgentChatProjectionBatch | a batch: projection, status events, whether message ids changed |
AgentChatEventProjectionStateSchema, AgentChatStateSchema, the other …Schema exports, HitlPauses | chat state Schemas (JSON via Schema.toCodecJson) |
makeAgentChatEventProjectionState | projection initial state |
markChatRunStart | run start after a snapshot rebuild |
applyAgentEventToChatMessages | ephemeral stream reducer |
buildAgentChatMessages, toAgentMessages | convert chat UI messages to protocol messages |
getActiveChatToolParts, getCompletedChatToolParts, getAgentChatLiveActivityCount | chat projection selectors |
deleteChatTurn, editChatUserMessage, regenerateChatMessagesFrom | chat editing helpers |
AgentChatSessionEvent, UserMessageSubmitted, ProtocolMessageAppended, MessagesRegenerated, TurnDeleted, UserMessageEdited | chat 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 family | Constructor values |
|---|---|
| Messages and tools | AgentChatPart, ChatToolState |
| Rendered items | AgentChatItem, AgentChatItemEnvelope, ToolRunState |
| Reducer actions | AgentChatAction |
| Message edit results | DeleteChatTurnResult, EditChatUserMessageResult, RegenerateChatMessagesResult |
| Hook results | AgentChatSubmitResult, AgentChatDeleteTurnResult, AgentChatRegenerateResult, AgentChatEditUserMessageResult, AgentChatHitlResponseResult |
| Duration descriptors | ToolDurationKnown, 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)
| Export | Purpose |
|---|---|
ClassifierModel | provider-neutral classifier service (classify(request)) |
classify, ClassificationRequestFor, ClassificationResultFor, ClassifierAnswerFor, ClassifierAnswersFor | typed entry point; answers inferred from questions |
ClassificationRequest, ClassificationResult, ClassificationUsage, ClassifierState | request, result, and usage schemas |
ClassifierQuestion, BooleanClassifierQuestion, ChoiceClassifierQuestion, ScoreClassifierQuestion | question schemas |
ClassifierAnswer, BooleanClassifierAnswer, ChoiceClassifierAnswer, ScoreClassifierAnswer | answer schemas |
ClassificationRequestInvalid, ClassificationProviderError, ClassificationResponseInvalid, ClassificationError | typed errors; ClassificationResponseInvalid keeps billed usage |
decodeClassificationRequest, decodeClassifierAnswer, decodeClassifierAnswers, isClassificationResultFor | validation 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.
| Export | Purpose |
|---|---|
makeContextBudget, contextBudgetStatus, contextBudgetUsageRatio | budget helpers |
estimateAgentMessageTokens, estimateAgentMessagesTokens, estimateContentTokens, estimateTextTokens | token estimation helpers |
TokenEstimateOptions, MessageTokenEstimator, TranscriptTokenEstimator | host tokenizer and estimator contracts |
planWindowCompaction, applyCompactionPlan, compactWindowMessages | window compaction helpers |
makeWindowCompactionTransformer | ContextTransformer layer helper |
makeCompactionCheckpointText, makeCompactionCheckpointMessage | synthetic checkpoint helpers |
isCompactionCheckpointText, isCompactionCheckpointMessage | host-controlled marker predicates |
formatAgentMessageForCompaction, formatAgentMessagesForCompaction | rich transcript summary-source formatter |
CompactionMessageFormatOptions | reasoning/tool formatting controls |
compactionSummarySourceMessages, dropLeadingCompactionCheckpointMessage | repeated-summary helper |
makeContextOverflowRetryProvider | one-shot provider overflow retry wrapper |
applyOverflowCompaction | shared compact-or-skip decision |
overflowCompactionMayRun | compact only before published output |
overflowCompactionAttemptAllowed, overflowCompactionMaxAttempts, isOverflowCompactionAttemptCount | durable compact-once budget helpers |
OverflowCompactionDecision | Compacted / Skipped |
ContextOverflowRetryCompactionResult, ContextOverflowRetryCompactor, ContextOverflowRetryProviderInput | retry 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
| Export | Purpose |
|---|---|
OAuthAccessToken, TokenBrokerRequest, TokenBrokerResponse | provider-neutral token contracts |
credentialSourceFromBroker | turn a host token broker into a credential source |
isTokenFresh, shouldRefreshToken, tokenRemainingTtlMs | token freshness helpers |
OAuthError | safe OAuth error |
Skillset
@yolk-sdk/agent/skillset
| Export | Purpose |
|---|---|
SkillInfo, parseSkillMarkdown, formatAvailableSkills | portable skill parsing/rendering |
CommandInfo, parseCommandMarkdown, parseCommandArguments, renderCommand | slash-command parsing/rendering |
SkillsetManifest, emptySkillsetManifest, mergeSkillsets | skillset catalog helpers |
validateSkillsetName, validateDirectoryName | safe 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
| Export | Purpose |
|---|---|
VoiceEvent, VoiceCommand, VoiceSessionConfig, VoiceSessionError | provider-neutral voice protocol |
makeVoiceController | client controller: tool forwarding, approval pause/resume, batching |
handleVoiceToolCall, decideVoiceToolCall, voiceApprovalRequestId, voiceToolDenialOutput | server-side tool policy/execution |
VoiceSessionToolCallRequest, VoiceToolCallOutcome | server tool endpoint wire contracts |
executeVoiceToolCall, VoiceToolCallRequest, VoiceToolExecutionResult, VoiceToolBridgeError | tool bridge over ToolExecutor |
projectVoiceEvent, emptyVoiceProjectionState, voiceSeedTextsFromMessages | transcript projection and reconnect seeds |
StoredVoiceEvent, sequenceVoiceEvent, dedupeStoredVoiceEvents, makeVoiceEventId | replay-safe durable voice events |
makeWebSocketVoiceTransport | Effect Socket voice transport; requires a host Socket.WebSocketConstructor layer |
VoiceSpeechSynthesizer, VoiceSpeechRequest, VoiceSpeechResult, VoiceTranscriber, VoiceTranscriptionRequest, VoiceTranscriptionResult, VoiceTranscriptionSegment, VoiceSpeechError, VoiceSpeechErrorCode, speechResultToAudioPart | one-shot TTS/STT contracts, results, and safe failures |
VoiceTransport | transport service contract |
@yolk-sdk/agent/voice/browser
| Export | Purpose |
|---|---|
makeWebRtcVoiceTransport, defaultWebRtcVoiceRuntime | browser WebRTC transport with fake-able runtime seam |
@yolk-sdk/agent/voice/react
| Export | Purpose |
|---|---|
useYolkVoice | headless 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.
| Subpath | Main exports |
|---|---|
@yolk-sdk/agent/providers/openai/provider | makeOpenAiProviderLayer, OpenAiProviderLayer, OpenAiProviderConfig, toOpenAiRequestBody, openAiChatResponseIssues, OpenAiChatResponseIssue |
@yolk-sdk/agent/providers/openai/conformance | openAiConformanceFixtures, 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/codex | Codex request, auth, OAuth token, and broker helpers |
@yolk-sdk/agent/providers/openai/codex-usage | fetchOpenAiCodexSubscriptionUsage, parser, URL, and options |
@yolk-sdk/agent/providers/openai/codex-provider | makeOpenAiCodexProviderLayer, OpenAiCodexProviderConfig, toOpenAiCodexRequestBody |
@yolk-sdk/agent/providers/openai | Codex OAuth/broker helpers |
@yolk-sdk/agent/providers/openai/realtime | Realtime session config, server-event decoder, VoiceEvent mapper, client codec |
@yolk-sdk/agent/providers/openai/speech | OpenAiSpeechConfig, makeOpenAiSpeechSynthesizerLayer, makeOpenAiTranscriberLayer |
@yolk-sdk/agent/providers/vercel/ai-gateway-provider | makeVercelAiGatewayProviderLayer, VercelAiGatewayProviderLayer, config/routing types, URL/id |
@yolk-sdk/agent/providers/vercel/ai-gateway-classifier | makeVercelAiGatewayClassifierLayer, VercelAiGatewayClassifierLayer, VercelAiGatewayClassifierConfig, vercelAiGatewayClassifierDefaultModel, vercelAiGatewayEvaluateUrl, vercelAiGatewayBaseUrl, vercelAiGatewayEvaluatePath, vercelAiGatewayEvaluationFallbackHeaderPrefix |
@yolk-sdk/agent/providers/vercel/conformance | vercelAiGatewayConformanceFixtures and four verified Gateway WireFixture recordings for replay tests; vercelAiGatewayClassifierConformanceFixtures, vercelAiGatewayClassifierConformanceCases, VercelAiGatewayClassifierConformanceConfig, and four synthetic classifier WireFixtures |
@yolk-sdk/agent/providers/opencode/go-provider | makeOpenCodeGoProviderLayer, OpenCodeGoProviderConfig, OpenCodeGoProtocol, OpenCodeGoReasoningSummary, openCodeGoBaseUrl, openCodeGoProviderId |
@yolk-sdk/agent/providers/opencode/usage | fetchOpenCodeGoSubscriptionUsage, parseOpenCodeGoSubscriptionUsage, OpenCodeGoSubscriptionUsageOptions, openCodeGoSubscriptionUsageUrl |
@yolk-sdk/agent/providers/opencode/conformance | openCodeGoConformanceFixtures, openCodeGoConformanceCases, OpenCodeGoConformanceConfig, and five synthetic OpenCode Go WireFixtures (plain text per protocol, commentary replay, usage) |
@yolk-sdk/agent/providers/anthropic/claude | Claude request, auth, OAuth token, authorization URL, and broker helpers |
@yolk-sdk/agent/providers/anthropic/usage | fetchAnthropicClaudeSubscriptionUsage, parser, URL, and options |
@yolk-sdk/agent/providers/anthropic/claude-provider | makeAnthropicClaudeProviderLayer, AnthropicClaudeProviderConfig, AnthropicClaudeThinkingConfig, toAnthropicClaudeRequestBody, streamAnthropicClaudeResponse, anthropicClaudeReasoningReplayProvider |
@yolk-sdk/agent/providers/anthropic/conformance | anthropicConformanceFixtures, anthropicConformanceCases, AnthropicConformanceConfig, five synthetic Anthropic Messages WireFixtures, and the Claude usage case (anthropicClaudeUsageSnapshotCase, AnthropicClaudeUsageConformanceConfig) and fixture |
@yolk-sdk/agent/providers/anthropic | Claude OAuth/broker helpers |
@yolk-sdk/agent/providers/xai/grok | Grok OAuth constants, authorization URL/parser, auth headers, token, and broker helpers |
@yolk-sdk/agent/providers/xai/grok-provider | makeXAiGrokProviderLayer, toXAiGrokRequestBody, streamXAiGrokResponse, config/reasoning types |
@yolk-sdk/agent/providers/xai/usage | fetchXAiGrokSubscriptionUsage, parser, URL, and options |
@yolk-sdk/agent/providers/xai/conformance | xAiGrokConformanceFixtures, xAiGrokConformanceCases, XAiGrokConformanceConfig, four synthetic Grok Responses WireFixtures, and the Grok usage case (xAiGrokUsageSnapshotCase, XAiGrokUsageConformanceConfig) and fixture |
@yolk-sdk/agent/providers/xai | Grok OAuth/broker helpers |
@yolk-sdk/agent/providers/subscription-usage | Snapshot/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.maxCompletionTokensbecomes vendormax_completion_tokens.VercelAiGatewayProviderConfig.maxCompletionTokensbecomes Gatewaymax_tokens; optionalfallbackModelsandroutingbecome Gateway request extensions.- ChatGPT subscription Codex rejects vendor
max_output_tokens; its optional deprecatedmaxOutputTokenscompatibility field is ignored. AnthropicClaudeProviderConfig.maxTokensbecomes vendormax_tokens.XAiGrokProviderConfig.maxOutputTokensbecomes vendormax_output_tokenson the xAI CLI proxy.XAiGrokProviderConfig.clientVersionis required and sent asx-grok-client-version; the xAI CLI proxy version-gates requests and rejects missing or outdated client versions with HTTP 426.OpenAiProviderLayerreadsOPENAI_API_KEYand integerOPENAI_MAX_COMPLETION_TOKENSthrough Effect Config.VercelAiGatewayProviderLayerreadsAI_GATEWAY_API_KEY, falls back toVERCEL_OIDC_TOKEN, and requires integerAI_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
| Subpath | Export | Contract |
|---|---|---|
@yolk-sdk/agent/protocol | toolResultMessageFromResult(result, envelope?) | Preserve all result payload fields and acceptance; optional explicit message envelope |
@yolk-sdk/agent/providers/openai/realtime | toOpenAiRealtimeToolEffect(tool) | Effect<OpenAiRealtimeFunctionTool, VoiceToolBridgeError> |
@yolk-sdk/agent/providers/openai/realtime | makeOpenAiRealtimeSessionConfigEffect(input) | Effect<OpenAiRealtimeSessionConfig, VoiceToolBridgeError> |
@yolk-sdk/agent/providers/openai/realtime | openAiRealtimeSessionConfigFromVoiceEffect(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.