# Yolk SDK

URL: /docs

Build host-owned agent products with typed streams, tools, memory, integrations, sandbox execution, and durable runtimes.



Yolk SDK gives you the reusable parts of an agent product without taking over your app:

* a typed agent transcript protocol
* a streaming model/tool loop
* schema-backed tools and HITL
* browser/client state helpers
* MCP adapters
* knowledge ingestion/search contracts
* bounded file-to-text extraction
* connector actions
* sandbox execution
* Vercel Workflow orchestration helpers
* a run-lifecycle harness for ownership, wakes, and recovery

You bring your app: auth, routes, DB, storage, provider credentials, UI, and product policy.

## Build your first agent in one file [#build-your-first-agent-in-one-file]

```ts
import { Effect, Layer, Stream } from 'effect'
import { ContextTransformer, LoopConfig, run } from '@yolk-sdk/agent/loop'
import { FauxProvider, Reply, TestToolExecutor } from '@yolk-sdk/agent/loop/testing'
import { UserMessage } from '@yolk-sdk/agent/protocol'

const TestLayer = Layer.mergeAll(
  FauxProvider.layer(Reply.text('Hello from Yolk.')),
  TestToolExecutor.layer({}),
  LoopConfig.defaultLayer,
  ContextTransformer.identity
)

const events = await Effect.runPromise(
  run({
    messages: [UserMessage.make({ content: 'Say hello' })],
    systemPrompt: 'Be concise.',
    tools: [],
    model: 'test-model'
  }).pipe(Stream.runCollect, Effect.provide(TestLayer))
)
```

This uses the test provider so you can learn the loop without a provider account. Swap in a real provider layer when your host app is ready.

## What should I read? [#what-should-i-read]

| I want to...                | Read                                                                    |
| --------------------------- | ----------------------------------------------------------------------- |
| run a first agent           | [Quickstart](./quickstart)                                              |
| create a Next route         | [Build a chat route](./guides/build-chat-route)                         |
| add a typed tool            | [Add a tool](./guides/add-tool)                                         |
| stream to React             | [Stream to React](./guides/stream-react)                                |
| persist sessions            | [Persist a session](./guides/persist-session)                           |
| choose model providers      | [Model providers](./integrations/model-providers)                       |
| see available integrations  | [Available integrations](./integrations)                                |
| add MCP tools               | [Add MCP tools](./integrations/mcp-tools)                               |
| add knowledge search        | [Add knowledge search](./integrations/knowledge-search)                 |
| run commands safely         | [Add sandbox execution](./integrations/sandbox)                         |
| script many tool calls      | [Add code mode](./integrations/code-mode)                               |
| run tool writes once        | [Ledger writes](./agent/tools-hitl#ledger-writes-for-re-executed-steps) |
| extract text from files     | [Extract file text](./integrations/file-extraction)                     |
| move files between tools    | [Move files between tools](./integrations/files)                        |
| share subscription accounts | [Share subscription accounts](./integrations/subscription-pools)        |
| own run lifecycle           | [Harness package](./harness)                                            |

## Public packages [#public-packages]

| Package                      | Role                                                 |
| ---------------------------- | ---------------------------------------------------- |
| `@yolk-sdk/agent`            | build and stream agent turns                         |
| `@yolk-sdk/mcp`              | use MCP tools or expose Yolk tools as MCP            |
| `@yolk-sdk/knowledge`        | model, ingest, search, and pack agent knowledge      |
| `@yolk-sdk/connectors`       | define reusable external API actions                 |
| `@yolk-sdk/sandbox`          | run commands in sandbox sessions                     |
| `@yolk-sdk/codemode`         | let one script call many tools (code mode)           |
| `@yolk-sdk/extractors`       | turn uploaded files into bounded, sanitized text     |
| `@yolk-sdk/files`            | move files between tools by `fileId`                 |
| `@yolk-sdk/pool`             | serve several subscription accounts as one provider  |
| `@yolk-sdk/vercel-workflows` | orchestrate durable agent loops on Vercel Workflows  |
| `@yolk-sdk/harness`          | own run lifecycle, claims, inbox, and recovery       |
| `@yolk-sdk/conformance`      | experimental wire-fixture record, replay, and faults |
| `@yolk-sdk/emulators`        | experimental service emulators for tests             |

## How docs are organized [#how-docs-are-organized]

* **Quickstart** gets one agent loop running.
* **Build guides** show the app surfaces most hosts need.
* **Integrations** show how packages combine into tools and runtime capabilities.
* **Reference** is for package maps, protocol terminology, and boundaries.

## AI-readable docs [#ai-readable-docs]

* [`/llms.txt`](/llms.txt) lists the curated docs index for agents and coding assistants.
* [`/llms-full.txt`](/llms-full.txt) includes processed Markdown for all docs pages.


---

# Installation

URL: /docs/installation

Install canary Yolk packages with matching lockstep versions.



Yolk packages currently publish on the `canary` channel and release in lockstep. Keep every `@yolk-sdk/*` dependency on the same version.

```bash
pnpm add @yolk-sdk/agent@canary effect@4.2.0
```

`effect` is a peer dependency of every package (`~4.2.0`, tested on `4.2.0`), so the host installs
it and every package shares that one copy. Effect patch releases satisfy the range; a new Effect
minor needs a new Yolk canary, because Yolk calls Effect's unstable `http`, `process`, and `socket`
modules. Install `@effect/platform-node` at the same version as `effect` when you use
`@yolk-sdk/mcp/client/node`. Check both when upgrading canaries.

Add sibling packages as needed:

```bash
pnpm add @yolk-sdk/mcp@canary @yolk-sdk/knowledge@canary @yolk-sdk/connectors@canary
pnpm add @yolk-sdk/sandbox@canary @yolk-sdk/vercel-workflows@canary workflow@^5.0.0-beta.42
pnpm add @yolk-sdk/harness@canary @yolk-sdk/codemode@canary @yolk-sdk/extractors@canary
pnpm add @yolk-sdk/files@canary @yolk-sdk/pool@canary
# Only for XLSX extraction with @yolk-sdk/extractors: SheetJS from its CDN, not the npm `xlsx`.
pnpm add https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz
```

For tests, add the experimental conformance and emulator packages as dev dependencies:

```bash
pnpm add -D @yolk-sdk/conformance@canary @yolk-sdk/emulators@canary
```

`@yolk-sdk/harness` is available from `0.1.0-canary.77`. `@yolk-sdk/codemode`,
`@yolk-sdk/conformance`, and `@yolk-sdk/emulators` are available from `0.1.0-canary.96`; they are
unavailable in `0.1.0-canary.95` and earlier. `@yolk-sdk/extractors` is available from
`0.1.0-canary.98`, `@yolk-sdk/files` from `0.1.0-canary.114`, and `@yolk-sdk/pool` from
`0.1.0-canary.116`. `@yolk-sdk/conformance` and
`@yolk-sdk/emulators` are experimental and meant for tests only; see [Test with emulators](./guides/testing-with-emulators).
Keep every package on the same lockstep version as the other public packages.

## Runtime expectations [#runtime-expectations]

| Requirement   | Notes                                                                                                                                                       |
| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Node          | Packages declare `>=22`; `@yolk-sdk/codemode` requires `>=22.19.0`                                                                                          |
| Module format | ESM only                                                                                                                                                    |
| Effect        | Peer (`effect ~4.2.0`) of every package; `@yolk-sdk/mcp` also has an optional `@effect/platform-node` peer for `./client/node`                              |
| React         | Optional peer only for `@yolk-sdk/agent/react`                                                                                                              |
| SheetJS       | Optional peer (`xlsx >=0.20.3`) only for XLSX extraction in `@yolk-sdk/extractors/node`; install the tarball from `cdn.sheetjs.com`                         |
| Workflow      | Required only by `@yolk-sdk/vercel-workflows` hosts; `workflow@^5.0.0-beta.42` (5.x region-pins runs — 4.x streams were `iad1`-only and burst cross-region) |

## Canary policy [#canary-policy]

Canary means APIs are useful but unstable. Expect breaking changes before `1.0.0`. Prefer explicit imports and small host adapters so package movement is easy to absorb.


---

# Migration and versioning

URL: /docs/migration

Canary stability, lockstep package versions, upgrade checks, and migration workflow.



Yolk packages are canary-stage. APIs can change between canary releases.

## Version rule [#version-rule]

Keep every public package on the same canary version:

```bash
pnpm add @yolk-sdk/agent@canary @yolk-sdk/mcp@canary @yolk-sdk/knowledge@canary @yolk-sdk/connectors@canary @yolk-sdk/sandbox@canary @yolk-sdk/vercel-workflows@canary @yolk-sdk/harness@canary @yolk-sdk/codemode@canary @yolk-sdk/extractors@canary @yolk-sdk/files@canary @yolk-sdk/pool@canary
pnpm add -D @yolk-sdk/conformance@canary @yolk-sdk/emulators@canary
```

Add only the packages you use. `@yolk-sdk/harness` is available from `0.1.0-canary.77`.
`@yolk-sdk/codemode`, `@yolk-sdk/conformance`, and `@yolk-sdk/emulators` are available from
`0.1.0-canary.96`. `@yolk-sdk/extractors` is available from `0.1.0-canary.98`,
`@yolk-sdk/files` from `0.1.0-canary.114`, and `@yolk-sdk/pool` from `0.1.0-canary.116`. Keep each
of them on the same lockstep version as the other public packages.

Check installed versions:

```bash
pnpm list '@yolk-sdk/*'
```

Do not mix versions unless a release note explicitly says it is safe.

## Recent canary migrations [#recent-canary-migrations]

### Canary.178: Effect 4.2.0, effect as a peer [#canary178-effect-420-effect-as-a-peer]

Canary.178 targets `effect@4.2.0`, and `effect` becomes a peer dependency. Upgrade the Yolk packages
and Effect together, and move `effect` and the coordinated Effect runtime packages
(`@effect/platform-*`, `@effect/sql-*`, `@effect/opentelemetry`, `@effect/vitest`) to `4.2.0`
together. Yolk APIs are unchanged.

* Every package declares `effect` as a peer with the range `~4.2.0` (tested on 4.2.0) instead of an
  exact dependency, so the host installs `effect` and every package shares that one copy. Effect
  patch releases satisfy the range; a new Effect minor needs a new Yolk canary, because Yolk calls
  Effect's unstable `http`, `process`, and `socket` modules. A host still on `effect@4.1.7` gets an
  unmet peer: npm fails the install with `ERESOLVE`, and pnpm only warns (then runs Yolk against
  4.1.7, which it does not support), so check `pnpm install`'s peer warnings.
* `@yolk-sdk/mcp` declares `@effect/platform-node` as an optional peer (`~4.2.0`). Only
  `@yolk-sdk/mcp/client/node` imports it: Node hosts that use it install `@effect/platform-node` at
  the same version as `effect`; other hosts need nothing.
* `@effect/platform-node` 4.2.0 requires `ws` ^8.23.1. If another dependency keeps an older `ws`,
  the package manager can install `@workflow/core` twice, and a Workflow build fails with duplicate
  step ids. Dedupe `ws`, for example with a pnpm override `ws: ^8.23.1`.
* Effect 4.2 has breaking changes of its own: a custom `ChildProcessSpawner.makeHandle` must provide
  `exitStatus`; `Cookies.cookies` is an array (read cookies with `Cookies.get`);
  `HttpClient.withRateLimiter` adds `HttpClientError` to the error type unless `failsWith` is set;
  `FileSystem.glob` takes one `PathFilter.Input`; `Yaml.parse` returns a `Result` and follows YAML
  1.2; `RpcServer.layerProtocolStdio` is a function; a hand-built `Pool.Stats` needs `acquiring`, a
  hand-built `Toolkit.HandlerContext` needs `modelOutput`; and exhaustive `SystemErrorTag` handlers
  need `DirectoryNotEmpty`. Check the
  [Effect 4.2.0 changelog](https://github.com/Effect-TS/effect/releases/tag/effect%404.2.0) for the
  APIs your code uses.
* `@effect/opentelemetry` 4.2 is built on the OpenTelemetry SDK v3: install
  `@opentelemetry/sdk-trace` (its `NodeSdk` imports it), `@opentelemetry/sdk-logs` 3.x, and
  `@opentelemetry/api` 1.10 or later, and pass the exporter as an option:
  `new BatchLogRecordProcessor({ exporter })`.

### Canary.163: model step execution ids under Workflow 5.8 [#canary163-model-step-execution-ids-under-workflow-58]

Workflow 5.8's speculative execution can discard a step body's outcome and run the body again under
the same `getStepMetadata()` `stepId` and `attempt`, possibly beside the first, for steps with
`maxRetries > 0`. An `executionId` of `${stepId}:${attempt}`, the example earlier docs gave, then
repeats: both executions write the same event ids and clients splice their answers. Generate the
id once at the start of the step body instead, for example
`${stepId}:${attempt}:${crypto.randomUUID()}`. `TestWorkflowWorld`'s new `discardStepExecution`
option reproduces this in tests
([Speculative execution](./vercel-workflows/testing#speculative-execution)).

### Canary.158: Fortnox bookkeeping actions [#canary158-fortnox-bookkeeping-actions]

`FortnoxConnector` grows from 91 to 102 actions: financial years, accounts, voucher series,
vouchers, voucher file connections, and SIE files. Hosts that expose every Fortnox action as agent
tools gain these eleven tools, including the `destructive` `fortnox.create_voucher` (Fortnox books
the voucher at once and its API documents no voucher delete or update): keep approval on
`destructive` tools, or filter the actions you expose. The new `bookkeeping` scope
(`FortnoxBookkeepingOAuthCredentialSlot`) stays outside `FortnoxCombinedOAuthCredentialSlot`;
Fortnox grants a scope added to an app only after the user authorizes again, so existing
connections must reconnect before these actions work. `fortnox.get_sie_file` also needs the host
`ConnectorBinaryHttpClient` in the connector layer. See [Bookkeeping](./connectors/fortnox#bookkeeping).

### Canary.152: lazy knowledge tokenizer [#canary152-lazy-knowledge-tokenizer]

`@yolk-sdk/knowledge/chunking` no longer evaluates `gpt-tokenizer` (about 2 MB) on import: the
default chunker loads it the first time text is chunked or counted. Imports of `KnowledgeChunker`,
`DefaultKnowledgeChunkerLive`, `makeDefaultKnowledgeChunker`, and `chunkKnowledgeText` are
unchanged and need no migration.

`countKnowledgeChunkTokens(text)` now returns `Effect<number, KnowledgeChunkingError>` instead of a
`number`. Run it in your Effect (`const tokens = yield* countKnowledgeChunkTokens(text)`), or call
`gpt-tokenizer` yourself where you need a synchronous count. `chunkKnowledgeText` and the default
chunker can also fail with `KnowledgeChunkingError` (`Failed to load the default tokenizer`) when
the tokenizer module cannot load.

`makeDynamicWorkerCodeModeExecutor` (`@yolk-sdk/codemode/cloudflare`) now loads Sucrase when the
first script runs instead of on import; if Sucrase cannot load, the execution fails like a sandbox
that cannot load (`Could not load the script sandbox.`, `onInternalError` stage `load`).

### Canary.150: pi code mode executor failure messages [#canary150-pi-code-mode-executor-failure-messages]

`makePiCodeModeExecutor` (`@yolk-sdk/codemode/node`) now answers its own failures with fixed
messages, as the Dynamic Worker executor does: a sandbox that cannot be created fails with `Could
not create the sandbox.` (before: `Could not create the sandbox: <error>`), and a `sandbox` failure
of pi's worker or QuickJS VM (`Failed to load QuickJS: …`, `Failed to start worker: …`, a worker
crash or exit) with `The script sandbox failed.`. Script errors, timeouts, and aborts are unchanged.
Code matching the old text needs the new messages; to log the original error, pass the new
`onInternalError` option (both executors).

### Canary.149: reasoning effort levels and OpenAI chat effort [#canary149-reasoning-effort-levels-and-openai-chat-effort]

`AgentReasoningEffort` adds `none` and `max` (`none`, `minimal`, `low`, `medium`, `high`, `xhigh`,
`max`). Stored efforts keep decoding. Exhaustive matches or `Record`s keyed by the type need the
two new cases, and code passing an `AgentReasoningEffort` where a narrower host type is expected
needs a guard. Data written with the new values does not decode on an earlier canary, so roll every
reader forward first. Anthropic Messages (Claude, OpenCode Go `messages`) sends `max` and rejects
`none` with a `validation_error` `LLMError`; the other providers pass both through.

`makeOpenAiProviderLayer` and `OpenAiProviderLayer` now send `reasoningEffort` as
`reasoning_effort` on the native OpenAI endpoint (no `chatCompletionsUrl`, or
`https://api.openai.com/v1/chat/completions`). Before, it was dropped unless
`reasoningEffortFormat` was set. Models without reasoning reject the field: stop sending them an
effort, or set `reasoningEffortFormat: 'omit'` (new), which never sends it and never fails. Move an
`extraBody.reasoning_effort` workaround to the request's `reasoningEffort` (`reasoning_effort` is
now a canonical key there and is dropped from `extraBody`). On any other `chatCompletionsUrl`, and
in `toOpenAiRequestBody` without a format, a request with an effort now fails with a
`validation_error` instead of being sent without it: set `reasoningEffortFormat` (`'omit'`
included), or stop sending the effort. Vercel AI Gateway and OpenCode Go set their format already;
the Gateway's `reasoningEffortFormat` also accepts `'omit'`.

### Canary.149: Dynamic Worker code mode CPU limit [#canary149-dynamic-worker-code-mode-cpu-limit]

`makeDynamicWorkerCodeModeExecutor` (`@yolk-sdk/codemode/cloudflare`) now loads every script with
`limits.cpuMs` (new option `cpuMs`, default 500). A script that used more CPU time before now fails
with a `timeout` (`Execution exceeded its CPU limit of <cpuMs> ms`): raise `cpuMs` if your scripts
compute more. A tool or global call the script left pending is rejected when the execution ends,
and calls arriving afterwards are rejected without running. Loader and isolate failures now carry
fixed messages (`Could not load the script sandbox.`, `The script sandbox failed.`) instead of the
runtime's error text after `The script sandbox failed: `; code matching that prefix needs the new
messages. A custom `WorkerLoader` now receives `limits` in `WorkerLoaderCode`.

### Canary.145: Cloudflare runtime hook token conflicts [#canary145-cloudflare-runtime-hook-token-conflicts]

The Cloudflare runtime (`@yolk-sdk/vercel-workflows/cloudflare*`) now refuses a hook whose token
another live hook holds, in another run or the same one, as Vercel does. Before, the newest hook
took the token and `resumeHook` reached it instead of the live holder. Now creating it succeeds,
but awaiting it rejects with `HookConflictError` (`token`, `conflictingRunId`, exported from
`./cloudflare`), and the holder keeps the token. Disposing a hook (`using` or `dispose()`) now frees
its token, and so does its run's end; an answered hook keeps its token until then. Give each pause
its own token, or dispose the previous hook before the run waits again (a loop with
`using hook = createHook({ token })` per round keeps working). A second `resumeHook` to a live,
answered hook now succeeds (the payload is dropped) instead of failing with `HookNotFoundError`.
Hosts that drive `WorkflowExecution` themselves pass `claimHook` (returning a `HookClaim`) instead
of `registerHook`; custom `WorkflowRunStub` namespaces implement `hookClaim` and `hookHeld` instead
of `hookRegister` ([Cloudflare runtime](./vercel-workflows/cloudflare)).

Runs in flight at the upgrade keep what the earlier build left. A run waiting on a token that the
earlier build let a newer run take stays unreachable: the index names the newer run, and its
`resumeHook` calls reach the newer run. Before upgrading, drain or cancel runs waiting on tokens
that several runs share. Earlier builds also kept the token entry of a hook that was disposed but
never answered. A run that replays after the upgrade (after an eviction, or on its next `resumeHook`)
repairs both: disposing that hook again deletes its entry, and a hook that still has an entry asks
the index for its token again (it is refused if another live hook holds it). A run that does not
replay keeps that entry until it ends, and the token stays taken until then.

### Canary.144: Cloudflare sandbox state [#canary144-cloudflare-sandbox-state]

`@yolk-sdk/sandbox` adds a Cloudflare Containers adapter
([Cloudflare Containers](./sandbox/cloudflare)), and with it a second sandbox state:

* `SandboxState` gains `CloudflareSandboxState` (`_tag: 'Cloudflare'`, with `bootId`). Exhaustive
  matches over `SandboxState` need a `Cloudflare` case; a host state store that decodes stored
  state with the `SandboxState` schema accepts both.
* `SandboxProviderError.provider` is `'vercel' | 'cloudflare'`.
* The `sandbox` tool's `SandboxToolOutput.state` is a union of the Vercel and Cloudflare shapes.
* `sandboxStateDecision` takes an optional `provider`; the Vercel layer passes `'Vercel'`, so a
  stored Cloudflare state for the same session recreates (`reason: 'provider_mismatch'`).

### Canary.143: non-empty harness pause [#canary143-non-empty-harness-pause]

`Driver.pause` and `Inbox.park` from `@yolk-sdk/harness` take a non-empty request id list
(`Array.NonEmptyReadonlyArray<string>` from `effect`). An empty pause was Ready at once, so the
drain kept its claim and nothing woke the run. `StepOutcome.AwaitingInput` `requests` and
`ParkedState.requestIds` are non-empty too. Map a tool batch's requests with Effect's `Array.map`,
which keeps the list non-empty (the native `.map` returns `string[]`). Fragment, inside a drain:

```ts
import { Array as Arr } from 'effect'

const requestIds = Arr.map(outcome.requests, request => request.requestId)
const decision = yield * inbox.park(runId, requestIds, context.drainToken)
```

Check a host-built list with `Arr.isReadonlyArrayNonEmpty` and do not pause when it is empty.
Custom `InboxApi` / `DriverApi` implementations take the narrower parameter
([Harness API](./api-reference/harness#inbox)).

### Canary.143: test world hook token conflicts [#canary143-test-world-hook-token-conflicts]

`TestWorkflowWorld` now refuses a hook whose token another live hook holds, in another run or the
same one, as Vercel does. Creating it succeeds, but awaiting it rejects with
`TestWorkflowHookConflictError` (named `HookConflictError`, with `token` and `conflictingRunId`),
and the holder keeps the token. Vercel decides the conflict at the run's next suspension and the
world once the code that created the hook yields, so a disposal made before then frees the token
for the new hook. Before, the world registered both. Update host tests in which two live runs, or
two live hooks of one run, share a token: give each pause its own token, or let the holder dispose
its hook or end its run first. `TestWorkflowHookConflictError` is no longer deprecated
([Hooks](./vercel-workflows/testing#hooks)).

### Canary.141: idempotent stream close [#canary141-idempotent-stream-close]

`TestWorkflowWorld` now treats closing an already closed stream as Vercel does: the close succeeds
(still counted in `inspect(runId).streamCloseCount`) instead of throwing the 409
`TestWorkflowStreamConflictError`. Writes after close still throw that conflict. Update host tests
that expected a second close to throw.

`runVercelAgentWorkflow` now retries the close step by default: `closeStreamRetry` defaults to
`defaultCloseStreamRetry` (`{ maxAttempts: 3 }`, any rejection, a `FatalError` too), so a close
applied by an attempt that then failed completes the run when a later attempt succeeds. Keep
`closeStream` close-only and safe to repeat, or opt out with
`closeStreamRetry: noWorkflowStepRetry`. Tests that counted one `closeStream` call for a failing
close now see up to three
([Retry policy](./vercel-workflows/step-contracts#retry-policy)).

### Canary.131: test world step errors [#canary131-test-world-step-errors]

`TestWorkflowWorld.runStep` now treats step errors as the platform does: it stores each thrown value
with the installed workflow runtime's serializer and throws only the value read back, never retries a
`FatalError`, and wraps an exhausted step's error in the platform's `FatalError`
(`Step "<name>" failed after N retries: ...`, with the error as `cause`). Update tests that compared
a step error by identity or class: compare `message`, `name` and plain-data `cause` instead. Tests
that execute steps must run in Vitest's Node environment. A step error the platform cannot store is
listed in `inspect(runId).unstorableStepErrors`; assert it is empty
([Step errors](./vercel-workflows/testing#step-errors)).

Providers also fail a malformed returned tool call (empty or padded id or name) as a typed
`invalid_response` `LLMError` instead of a defect; hosts that caught that defect can drop the
workaround.

### Canary.126: typed tool results [#canary126-typed-tool-results]

A tool's typed output is now the single contract for code mode scripts, files are typed fields of
that output, and script values never contain file labels
([ADR 0013](https://github.com/magoz/yolk-sdk/blob/main/docs/adr/0013-typed-tool-results.md)).
`makeTool` tools that return a `ToolResult` keep working in this canary (deprecated), except for
files: see the first bullet below before upgrading.

Convert a tool that returns `[TextPart(JSON), FilePart]`. Fragment: `Params` and `exportInvoice` are
host-owned; `ToolFile` and `FileBytes` come from `@yolk-sdk/agent/protocol`.

```ts
// Before (deprecated)
makeTool({
  name: 'export_invoice',
  description: 'Export an invoice as JSON and its PDF.',
  parameters: Params,
  access: 'read',
  execute: ({ call, params }) =>
    exportInvoice(params.id).pipe(
      Effect.map(invoice =>
        ToolResult.make({
          toolCallId: call.id,
          content: [
            TextPart.make({ text: JSON.stringify({ number: invoice.number }) }),
            filePartFromBytes({
              bytes: invoice.pdf,
              mimeType: 'application/pdf',
              filename: 'invoice.pdf'
            })
          ]
        })
      )
    )
})

// After
makeTool({
  name: 'export_invoice',
  description: 'Export an invoice as JSON and its PDF.',
  parameters: Params,
  output: Schema.Struct({ number: Schema.String, pdf: ToolFile }),
  access: 'read',
  execute: ({ params }) =>
    exportInvoice(params.id).pipe(
      Effect.map(invoice => ({
        output: {
          number: invoice.number,
          pdf: new FileBytes({
            bytes: invoice.pdf,
            name: 'invoice.pdf',
            mimeType: 'application/pdf'
          })
        }
      }))
    )
})
```

* Files returned as `FilePart` by tools without `output` (deprecated `ToolResult` tools included)
  are no longer reachable from scripts: the model still sees their labels, the script only the
  text. Before upgrading, give every byte-producing tool whose files scripts move an `output` with
  a `ToolFile` field (as above).
* With `output`, return `{ output }`: Yolk encodes it (`Schema.toCodecJson`), captures file fields
  into `FileRef` (`{ fileId, name, mimeType, size }`) or `FileUnavailable`
  (`{ unavailable, name, mimeType }`), and shows the model compact JSON with file labels, or
  `render(value, files)`. `output` schemas must encode without services and to plain JSON (a
  `FileBytes` in a `Schema.Any` field fails the call); `Schema.Void` encodes as `null`. `ToolFile`
  belongs only in `output`: `makeTool` throws when `parameters` holds one.
* `resolveTools` checks every successful result of a tool with an output schema against it
  (excess properties rejected) and passes on the checked value; a value that does not match is
  dropped (logged without the value), so scripts reject the call while the model still sees the
  content. This covers deprecated `ToolResult` tools and raw registrations.
* Raw registrations (not `makeTool`) whose `def.outputSchema` is set need
  `decodeOutput: toolOutputDecoder(schema)` (`@yolk-sdk/agent/protocol`); MCP registrations built
  from `mcpToolToToolDef` defs need `decodeOutput: mcpToolOutputDecoder` (`@yolk-sdk/mcp/client`).
  Without it `resolveTools` fails with `output_validation_required`. For raw interaction
  registrations, `def.outputSchema` and `decodeOutput` describe the action's own value
  (`structuredContent.result` of a completed outcome), checked before the receipt is settled
  ([ADR 0013, Result boundary](https://github.com/magoz/yolk-sdk/blob/main/docs/adr/0013-typed-tool-results.md#result-boundary)).
* `makeTool` with explicit type arguments and `output` takes three:
  `makeTool<Context, typeof Params, typeof Output>`. Two explicit type arguments no longer accept a
  typed `{ output }` (it used to escape its schema); drop them to infer, or add the third.
* Without `output`, return `{ content }`; a structured value needs `output`.
* `modelVisibleToolError({ code })` gives scripts `error.code`.
* Scripts: typed tools resolve to their declared value with no merged `files`; a typed result
  without a value rejects (`returned an invalid result`); untyped tools resolve to their text
  without file labels; failures reject with the message and `error.code`. Remove `JSON.parse` of
  typed results and `typeof r === 'string'` guards.
* MCP tools declare and resolve to `{ value, files }` (`value` is `structuredContent`, else the text
  of the text blocks and embedded text resources, parsed once when it is one JSON object or array,
  else the text; `resource_link` blocks never enter it). Read `value` where scripts read the result
  itself (`upload.value.url`, not `upload.url`). Local stdio calls now list the tools in the same
  session and validate `structuredContent` against the listed `outputSchema`, like remote calls.
* MCP blobs, images and audio are stored when the call runs: inside `resolveTools` through the
  resolution's `files`; elsewhere (a HITL route calling `resumeRemoteMcpServerToolCall`, a direct
  `callLocalMcpServerTool`) pass `fileCapture: makeToolFileCapture({ store })`
  (`@yolk-sdk/agent/tools`) on the call input, or every file is `FileUnavailable`
  (`no file store`). Results without file blocks keep their previous model content.
* Connector `gmail.get_attachment`, `outlook.get_attachment` and `email.get_attachment` resolve to
  `{ value, files }` instead of `{ ...metadata, files }`.
* Labels are `File` parts now: a captured image, document or audio part is followed by a `File` part
  with a `Ref` source instead of a text label, and an unstored file is a `File` part with the new
  `Omitted { reason }` source. Providers render the same text. Readers older than this canary cannot
  decode transcripts holding an `Omitted` source.
* The tool ledger keeps typed values whole: an oversized value replays as an error result. Stored
  copies keep `File` parts as parts through every reduction (labels are never flattened into the
  text).

New, opt-in: `@yolk-sdk/connectors/kie` adds the Kie connector (GPT Image 2 and Wan 2.7 tasks and
their status) with the `KieApiKeySlot` credential slot. See [Kie](./integrations/connectors#kie).

### Canary.125: Fortnox invoice Remarks and row inputs [#canary125-fortnox-invoice-remarks-and-row-inputs]

`fortnox.create_invoice` and `fortnox.update_invoice` accept `Remarks`, the invoice text
(Fakturatext) printed on the invoice, and `FortnoxInvoice` returns it. `Comments` stays the
internal note; both are limited to 1024 characters. Invoice write rows change shape, a breaking
change for hosts that build them:

* Write rows are `FortnoxInvoiceRowInput`, not the read schema `FortnoxInvoiceRow`. It is a closed
  schema with a matching type, not a class: replace `FortnoxInvoiceRow.make(row)` with a plain
  object typed `FortnoxInvoiceRowInput`. Read-only `PriceExcludingVAT`, `Total`, and
  `TotalExcludingVAT` are no longer inputs (Fortnox rejected a written `PriceExcludingVAT` with
  code 2000321); send `Price`.
* Rows are closed: an unknown row key fails instead of being dropped. Connector `execute`/`invoke`
  fail with `validation_failed`, generated agent tools reject the call, and
  `FortnoxCreateInvoiceInput.make` / `FortnoxUpdateInvoiceInput.make` throw. `executeTyped` does
  not re-check an existing instance, so an instance changed after `make` is not re-validated.
  Invoice-level unknown keys are still dropped on `execute`.
* Row fields reject `null` (generated agent tools still treat a model's `null` as omitted), `VAT`
  is an integer, `DiscountType` is `AMOUNT` or `PERCENT`, and `Description` and `Unit` follow
  Fortnox's 255 and 20 character limits.

Hosts that list these tools over MCP serve changed tool schemas once, so grants keyed on a tool
snapshot digest return to their default for both invoice write tools.

### Canary.124: Effect 4.1.2 [#canary124-effect-412]

Canary.124 targets `effect@4.1.2`. Upgrade the Yolk packages and Effect together, and move `effect`
and the coordinated Effect runtime packages (`@effect/platform-*`, `@effect/sql-*`,
`@effect/opentelemetry`, `@effect/vitest`) to `4.1.2` together. Three Yolk boundary failures are
now typed (below).

* Effect 4.1 has breaking changes of its own: `effect/Crypto` is replaced by `effect/crypto/*`
  services that runtimes no longer provide implicitly; `HttpClientRequest.method` is a `string`
  (so `HttpClientRequest.make(request.method)` no longer type-checks); and `KeyValueStore`,
  `FileSystem.make`, `ChildProcess` templates and `McpServer` registrations change. Check the
  [Effect 4.1.0 changelog](https://github.com/Effect-TS/effect/releases/tag/effect%404.1.0) for
  the APIs your code uses.
* Tool JSON Schemas generated from Effect schemas are flatter: a nested `anyOf` is merged into its
  parent, and a named definition reached from a required and an optional property is emitted once.
  What each schema admits is unchanged. Hosts that list tools over MCP serve changed tool schemas
  once, so grants keyed on a tool snapshot digest return to their default for the affected tools.
* `@effect/platform-node` 4.1 requires `ws` ^8.22.1. If another dependency keeps an older `ws`, the
  package manager can install `@workflow/core` twice, and a Workflow build fails with duplicate step
  ids. Dedupe `ws`, for example with a pnpm override `ws: ^8.22.1`.
* Typed boundary failures, each keeping the original failure as `cause` when one exists:
  `textFromBlob` and `documentPartFromTextFile` fail with `BlobTextReadError` (was `Error`);
  `attachmentSourceText` fails with `AttachmentTextDecodeError` (was the raw decoding error); and
  `writeDurableAgentEvent` fails with `DurableAgentEventWriteError` (was the writer's raw rejection).
  Code that inspected the raw value reads `cause`.

### Canary.122: connector input numbers [#canary122-connector-input-numbers]

Connector action inputs advertise only finite numbers (bare `Schema.Number` offered models
`"NaN"`/`"Infinity"`, which argument decoding then rejected). Validation is stricter, for tool calls
and in-process `invoke` alike: an input outside the following constraints now fails validation
instead of reaching the provider.

* Gmail and Google Calendar `maxResults`, LinkedIn search `numResults`: integers of at least 1.
* Notion `pageSize`: an integer from 1 to 100. Todoist `limit`, `priority` and `duration`: integers
  from 1 to 200, from 1 to 4, and of at least 1.
* GitHub issue field `number` inputs and Fortnox nullable amounts: finite numbers.

Hosts that list these tools over MCP serve changed tool schemas once (these inputs, and the declared
outputs of Fortnox tools whose results carry nullable amounts), so grants keyed on a tool snapshot
digest return to their default for the affected tools.

### Canary.116: subscription pools and quota signals [#canary116-subscription-pools-and-quota-signals]

New, opt-in ([ADR 0011](https://github.com/magoz/yolk-sdk/blob/main/docs/adr/0011-subscription-pools.md)):
`@yolk-sdk/pool` serves several accounts of one provider as one `LLMProvider`. See
[Share subscription accounts](./integrations/subscription-pools).

* `ProviderErrorInfo` gains optional `quotaResetsAtMs`: on a `rate_limit` failure for a spent
  account-wide subscription quota, Claude and Responses providers (ChatGPT Codex) attach the reset
  when they can read a trusted one. Hosts that persist provider errors in a
  closed schema should allow it.
* `ProviderSubscriptionUsageWindow` gains optional `models` (model-scoped limits), and Claude and
  OpenCode Go usage now set `windowDurationMinutes`. Claude snapshots also report model-scoped
  weekly windows (`seven-day-<model>`): hosts that show every window will show them too. The
  emulators' `/anthropic` usage route reports one, so tests that count its windows see one more.
* `outlook.get_message` now returns `internetMessageHeaders: []` for Sent Items and drafts, where
  Microsoft Graph omits the headers; it used to fail with `validation_failed`.

### Canary.116: Effect 4.0.5 [#canary116-effect-405]

Canary.116 targets `effect@4.0.5`. Upgrade the Yolk packages and Effect together, and move `effect` and the coordinated Effect runtime packages (`@effect/platform-*`,
`@effect/sql-*`, `@effect/opentelemetry`, `@effect/vitest`) to `4.0.5` together. Yolk APIs are
unchanged.

* Effect 4.0.5 drops a typed failure when an interruption skipped its recovery handler. If you run
  connector conformance cases with `runConformance` and interrupt a run while a case's cleanup
  fails, a write's outcome is unknown, or a cleanup is refused, the run now ends interrupt-only
  instead of with the case's error (`RestoreFailed`, `ActionFailed`, or `CleanupRefused`). Read cleanup problems from `ConformanceCleanupReporter`, which receives them
  either way. The repository's conformance runners now exit 130 in that case, not 1.

### Canary.115: agent status [#canary115-agent-status]

Breaking for `@yolk-sdk/agent/client` and `@yolk-sdk/agent/react`. The string `AgentRunStatus`
is removed; `status` is now an [`AgentStatus`](./agent/status) from `@yolk-sdk/agent/protocol`,
and `AgentClientState`/`AgentChatState` gain `subagents`.

| Before                              | After                                                         |
| ----------------------------------- | ------------------------------------------------------------- |
| `status === 'idle'` or `'aborted'`  | `Predicate.isTagged(status, 'Idle')`                          |
| `status === 'running'`              | `Predicate.isTagged(status, 'Working')` (or `chat.isRunning`) |
| `status === 'waiting'`              | `Predicate.isTagged(status, 'Blocked')` (or `chat.isWaiting`) |
| `status === 'done'`                 | `Predicate.isTagged(status, 'Done')`                          |
| `status === 'error'`, `state.error` | `Failed` status: `status.message`                             |
| `state.errorInfo`                   | `Failed` status: `status.error` (absent for transport errors) |
| `state.retryInfo`                   | `agentStatusRetry(status)`                                    |
| `useAgentChat().error`              | `Failed` status from `useAgentChat().status`                  |

`markAgentError(state, message, error?)` takes an optional `AgentError` instead of
`AgentError | null`. A stopped run is `Idle`, as in OSC 7501; there is no separate aborted
status. `AgentError` gains an optional `abortReason` (`user`, `system`, `max_turns`) on `aborted`
errors: `user` (or absent) maps to `Idle`, the others to `Failed`.

New in `@yolk-sdk/agent/protocol`: `AgentStatus` and its variants, `AgentActivity`,
`AgentBlockedKind`, `nextAgentStatus`, `agentStatusFromEvents`, `reconcileAgentStatus`,
`AgentStatusTree` with `nextAgentStatusTree`, `withSubagentStatus`, `startAgentStatusTree`, and
`settleAgentStatusTree`, plus `hitlRequestBlockedKind`, `agentBlockedKind`, `agentStatusRetry`,
`isAgentStatusLive`, `AgentAbortReason`, and the subagent result predicates
`isSubagentAcceptedToolResult` and `isSubagentObservationToolResult`.

### Canary.114: file claim check [#canary114-file-claim-check]

New, opt-in ([ADR 0009](https://github.com/magoz/yolk-sdk/blob/main/docs/adr/0009-file-claim-check.md)):
agents move files between tools by `fileId`. See [Move files between tools](./integrations/files).

* `ContentPart` has a new `File` member (`FilePart`): exhaustive `Match`es over content parts need
  a case; render it with `filePartText`.
* `resolveTools` captures file bytes even without the new `files` option: an inline `FilePart`
  becomes a "file not captured" label. Pass `files: { store }` to store them.
* MCP embedded resource blobs reach the model as a file label instead of base64 text.
* As agent tools, `gmail.get_attachment`, `outlook.get_attachment` and `email.get_attachment`
  return a file instead of base64 (`connector.invoke` is unchanged), and connector sinks such as
  Gmail draft attachments do not take `fileId`s yet: hosts that forwarded attachment base64
  through the model need their own file-aware tool.
* Custom `VercelSandboxHandle` implementations and fakes need `readFile`, and
  `SandboxInputErrorCause` gains `invalid_path`, `file_not_found` and `file_too_large`: exhaustive
  matches on it need cases.
* The code mode description gains one line about `files`, which changes the cached prompt prefix
  once.

### Canary.113: Claude thinking summaries and signed thinking replay [#canary113-claude-thinking-summaries-and-signed-thinking-replay]

* Opus 5 and later think by default but return thinking blocks without text. Set
  `thinking: { display: 'summarized' }` on `makeAnthropicClaudeProviderLayer` to stream readable
  summaries. See [Thinking](./integrations/model-providers#thinking).
* The Claude provider now keeps each thinking block's signature (or redacted data) on
  `AssistantReasoningPart.replay` and sends it back unchanged on later requests, with or without
  `thinking`. Never edit, truncate or reorder a reasoning part that has `replay`; hosts that rewrite
  history per request can skip parts whose `replay.provider` is
  `anthropicClaudeReasoningReplayProvider`.
* `LLMReasoningReplay` is a new `AgentEvent` (and loop `LLMEvent`, tag `ReasoningReplay`) member:
  exhaustive matches need a case. Live chat projections can ignore it.
* Claude turns emit it on almost every thinking block, and older SDKs reject unknown event tags:
  deploy servers and clients together, reload open tabs, and do not roll back to an older SDK over
  durable logs that contain it.
* A Claude thinking block that ends without a signature now fails the turn as non-retryable
  `invalid_response`.
* Persist `AssistantReasoningPart.replay` with the message. React `toAgentMessages` rebuilds reasoning without `replay`: hosts that resend chat-derived history
  should resend the protocol messages instead to keep the reasoning.

### Canary.108: tool exposure, catalog instructions, Claude Code 2.1.299 [#canary108-tool-exposure-catalog-instructions-claude-code-21299]

New, opt-in ([ADR 0007](https://github.com/magoz/yolk-sdk/blob/main/docs/adr/0007-tool-exposure-and-catalog.md)):

* `loading: 'deferred'` keeps a tool out of provider requests until the package `tool_search`
  tool loads it. See [Defer rarely used tools](./agent/tools-hitl#defer-rarely-used-tools).
* A stageable approval tool may be `callableBy: 'codemode'` (stage-only); resolution used to reject
  this. See [Stage-only tools](./integrations/code-mode#stage-only-tools).
* `makeCodeModeTool({ catalog: 'instructions' })` delivers the code mode catalog as a host
  instruction (`RunConfig.instructions`); `catalog: 'description'` stays the default. Hosts with
  custom compaction must keep `latestInstructionMessages(...)`, and durable `runModelTurn` hosts
  append `instructionMessages(...)` themselves. See
  [Deliver the catalog as instructions](./integrations/code-mode#deliver-the-catalog-as-instructions).
* `ToolDiscovery` gains `pinned`, and `ToolRegistryError` gains `deferred_unsupported_tool` and
  `duplicate_instruction`: exhaustive `switch`es over them need a new case.

The Claude subscription transport identifies as Claude Code 2.1.299 (was 2.1.112), so Anthropic
accepts newer models such as Claude Opus 5.5; no code change is required. Proxies or tests that
assert the `user-agent` or billing header need updating. Claude errors now report
`error.details.error_code` (for example `claude_code_version_too_old`) as `providerCode` when
present, so hosts that match `providerCode: 'invalid_request_error'` for those failures should match
the specific code.

### Canary.107: provider prompt caching and Fortnox scopes [#canary107-provider-prompt-caching-and-fortnox-scopes]

Prompt caching is always on and changes outbound provider requests; no code change is required.
Anthropic requests carry `cache_control` markers, Codex and Grok send `prompt_cache_key` plus their
session headers, Vercel AI Gateway sends `providerOptions.gateway.caching: 'auto'` and
`x-session-affinity`, and OpenCode Go sends `x-opencode-session`. To benefit:

* Set `cacheKey` (for example the session id) on `run` or `runRuntime`. It travels in HTTP headers, so
  keep it printable ASCII.
* Keep the system prompt and tool list stable within a conversation and move per-request facts
  (fresh signed URLs, the current time) out of earlier messages into `LLMRequest.turnContext`.
* Optionally set `promptCacheTtl: '1h'` on `makeAnthropicClaudeProviderLayer` for sessions that
  idle between turns.
* Proxies or tests that assert exact request bodies or headers need updating.

See [Prompt caching](./integrations/model-providers#prompt-caching) and ADR 0008.

New, opt-in: `@yolk-sdk/connectors/fortnox` grows from 14 to 91 actions behind nine new opt-in
OAuth slots that stay outside `FortnoxCombinedOAuthCredentialSlot`, so existing consent is
unchanged. New host-only helpers: `downloadFortnoxOfferPreview`, `downloadFortnoxInboxFile`, and
`uploadFortnoxInboxFile`. The Fortnox emulator serves their reads with unverified synthetic shapes.
See [Read and write Fortnox records](./connectors/fortnox).

### Canary.105: Gmail draft attachments [#canary105-gmail-draft-attachments]

New, opt-in: `gmail.draft_compose`, `gmail.draft_update`, and `gmail.draft_reply` take an optional
`attachments` array of `{ filename, mimeType, contentBase64 }`. It is available from
`0.1.0-canary.105`. New exports from `@yolk-sdk/connectors/google`: `GmailDraftAttachment`,
`GmailDraftAttachments`, `GmailDraftAttachmentFilename`, `GmailDraftAttachmentMimeType`,
`GmailDraftAttachmentBase64`, and the limits `gmailDraftAttachmentsMaxItems` (10 files),
`gmailDraftAttachmentsMaxBytes` (25 MiB decoded in total), and `gmailDraftMessageMaxBytes` (35 MiB
of decoded MIME). See [Gmail draft attachments](./integrations/connectors#gmail-draft-attachments).

* A draft with attachments is written with one never-retried `multipart/related` upload to
  `https://gmail.googleapis.com/upload/gmail/v1/users/me/drafts?uploadType=multipart` (an update:
  `PUT .../drafts/{id}?uploadType=multipart`). Host HTTP adapters must forward that body exactly as
  UTF-8 and accept outgoing bodies up to about 35 MiB.
* A draft whose decoded MIME exceeds 35 MiB fails with `validation_failed` and
  `underlying: { outcome: 'rejected', retryable: false, reason: 'too_large' }` before anything is
  written.
* `gmail.draft_update` replaces the whole message: attachments not sent again are removed.
* Drafts without attachments (absent or empty) are written exactly as before, through the JSON
  endpoint.
* The Google emulator does not emulate the draft media upload: a draft with attachments answers its
  unrecognised 400. See [Google emulator](./api-reference/emulators#google-emulator).

### Canary.104: tool change previews [#canary104-tool-change-previews]

New, opt-in: approval-gated tools can describe what a call would change with
`makeTool({ approval, changePreview })`. It is available from `0.1.0-canary.104`. Pass
`toolSet.approvalPreviews` as `approvalPreviews` to your loop or runtime config and pending
`ToolApprovalRequest`s carry `preview` (a `ToolChangePreview`) or `previewError`; staged plan
reviews use the same hook. See [Preview the change](./agent/tools-hitl#preview-the-change).

Breaking changes for staged plan hosts:

* `staging.preview` is removed. Move it to the tool's `changePreview` and return a
  `ToolChangePreview` (`{ target, changes, ... }`) instead of arbitrary JSON.
* `ToolPlanPreview` `ok` entries carry `params` and either `preview: ToolChangePreview`,
  `previewError` (`{ cause, message }`), or neither (no hook), never both; narrow with
  `entry.status === 'ok' && entry.preview !== undefined`. A failing preview no longer turns the
  entry into `status: 'error'`, and oversized previews are truncated with markers instead of
  becoming error entries.
* `maxToolPlanPreviewBytes` is removed. Use `defaultToolChangePreviewMaxBytes` (16 KiB) and set
  the bound with `resolveTools(..., { changePreview: { maxBytes } })`.

Type changes that may need code updates even if you don't use staged plans:

* `ToolRegistryError` has a new cause, `change_preview_unsupported_policy` (a `changePreview` on a
  tool without `approval`). Update exhaustive matches.
* `ResolvedToolSet` has a new required field, `approvalPreviews`: update hand-built tool sets.

### Canary.103: staged tool plans [#canary103-staged-tool-plans]

New, opt-in: code mode scripts can stage approval-gated tool calls with `stage(name, args)`, and a
person reviews the plan once through `makePlanReviewTool` before Yolk applies the selected calls.
It is available from `0.1.0-canary.103` and needs `makeTool({ approval, staging })` on the tools,
`resolveTools(..., { interactionHost, plans: { store } })`, and one plan review tool. Without them,
tool execution and code mode are unchanged. See
[Stage approval-gated writes](./integrations/code-mode#stage-approval-gated-writes) and
[Review a staged plan](./agent/tools-hitl#review-a-staged-plan).

Type changes that may need code updates even if you don't use staged plans:

* `prepareToolBatch` now returns `Effect<PreparedToolBatch, ToolError>`. It fails with `ToolError`
  `unavailable` only when host storage read by an interaction call validator is unavailable;
  nothing runs, so fail the step and retry it.
* Interaction call validators (`InteractionCallValidator`) and `validateAction` may fail with
  `InteractionHostError` for a storage outage, and `validateInteractionSubmission` then answers the
  new `InteractionAdmissionError` cause `unavailable`: treat it as retryable, not as invalid input.
* `ToolRegistryError` has three new causes: `staging_unsupported_policy`,
  `staging_validation_required`, and `plan_review_duplicate`. Update exhaustive matches.
* Raw interaction registrations' action `validate` (`InteractionActionHandler.validate`) now also
  receives the interaction `call` (`makeInteractionTool` action `validate` is unchanged), and interaction
  registrations accept an optional `unknownOutcome` hook. Existing handlers keep working.

If you adopt staged plans with a tool ledger, resolve the review step with the same ledger scope on
every redelivery, keep ledger entries as long as review receipts, and wire your per-call write
authorizer as `makePlanReviewTool({ beforeCall })`: applied calls bypass `beforeNestedCall` and
`ToolExecutor` decorators.

### Canary.102: Gmail draft bodies and thread body decoding [#canary102-gmail-draft-bodies-and-thread-body-decoding]

`gmail.draft_compose`, `gmail.draft_update`, and `gmail.draft_reply` keep their inputs and outputs,
plus a new optional `contentType: 'text' | 'html'` (`GmailDraftContentType`, `text` when omitted).
The draft MIME they write changes:

* A `text` body is now 7-bit `multipart/alternative` (a quoted-printable text/plain part and a
  derived text/html part) instead of one unencoded text/plain part, so Gmail web no longer
  hard-wraps it when a person sends the draft. An `html` body is one quoted-printable text/html
  part. Write each paragraph as one line. See
  [Gmail draft bodies](./integrations/connectors#gmail-draft-bodies).
* Tests, fakes, or recorded fixtures that compare a draft's exact `message.raw` need updating.
* `gmail.get_thread` no longer applies a part's `Content-Transfer-Encoding` to Gmail's already
  decoded `body.data`: quoted-printable text holding `=XX` (such as `?date=2026`) and base64-encoded
  parts now read back correctly. Remove any host workaround for those bodies.

`gmail.send_message` is unchanged.

### Canary.99: durable tool-call ledger [#canary99-durable-tool-call-ledger]

New, opt-in: `resolveTools(modules, context, { ledger: { store } })` runs ledgered tool calls at
most once per ledger key when a step re-executes. It is available from `0.1.0-canary.99`; without
`ledger`, tool execution is unchanged.

* Vercel Workflow tool-batch steps are at-least-once: the queue redelivers them after crashes and
  sometimes while a first execution is still running, even with `noWorkflowStepRetry`. Hosts that
  resolve tools inside a step should pass a durable store. See
  [Tool steps run at least once](./integrations/vercel-workflow#tool-steps-run-at-least-once) and
  [Ledger writes for re-executed steps](./agent/tools-hitl#ledger-writes-for-re-executed-steps).
* Custom executor or registration wrappers must forward `idempotencyKey` (like `nested`).
* A custom `isLedgered` should compose `defaultToolLedgerPolicy`, which also ledgers the built-in
  `subagent` tool.
* Code mode: `ToolResult.nestedCalls` is now sized from `limits.maxNestedCalls` (up to 4096)
  instead of a fixed 256, and `NestedToolCalls` gains optional per-status `counts`. Hosts with a
  higher limit store larger records in step output and audit storage.

### Canary.98: extractors package [#canary98-extractors-package]

New package: `@yolk-sdk/extractors`, bounded text extraction for PDF, DOCX, XLSX, PPTX, CSV, JSON,
Markdown, and plain-text files. Existing packages have no API changes, and `@yolk-sdk/knowledge`
does not depend on it.

* The root export is runtime-portable (`FileExtractor`, formats, limits, errors).
  `@yolk-sdk/extractors/node` is server-only and parses PDF and Office files in a worker thread
  per file; text formats are decoded in the calling thread.
  `@yolk-sdk/extractors/knowledge` exports `FileKnowledgeExtractorLayer`, which provides
  `KnowledgeExtractor` for [knowledge ingestion](./knowledge/ingestion-pipeline).
* SheetJS is an optional peer needed only for XLSX. Install it from
  `https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz`, not the npm `xlsx`.
* In Next.js, keep the package unbundled:
  `serverExternalPackages: ['@yolk-sdk/extractors', 'xlsx']`.

### Canary.97: Effect 4.0.0 [#canary97-effect-400]

Canary.97 targets the stable `effect@4.0.0` release; canary.96 and earlier use
`effect@4.0.0-rc.115`. Upgrade matching Yolk packages and Effect together, and keep `effect` and the coordinated Effect runtime packages
(`@effect/platform-*`, `@effect/sql-*`, `@effect/opentelemetry`, `@effect/vitest`) on the same
version. Tooling such as `@effect/language-service` is versioned independently.

* Effect 4.0.0 removes the `effect/unstable/*` entrypoints. Drop the `unstable` segment:
  `effect/unstable/http` becomes `effect/http`, likewise `effect/socket`, `effect/sql`,
  `effect/process` and the other areas; `effect/unstable/httpapi` becomes `effect/http-api`. Import
  `Arbitrary` from `effect`.
* Check Effect-integrated dependencies for removed paths, not just your own code. For example,
  `drizzle-orm` `1.0.0-rc.5` declarations still import `effect/unstable/sql/SqlError`; with
  `skipLibCheck` that type silently becomes `any` and `catchTag('SqlError')` stops being checked.
  The Next example pins a declaration-only `pnpm patch` until drizzle ships a fix.
* `effect/Encoding` is split into `effect/encoding/Base64`, `Base64Url`, `Hex` and
  `EncodingError`. For example, `Encoding.encodeBase64` / `decodeBase64` become `Base64.encode` /
  `Base64.decode`.
* Host Effect code must also adopt upstream renames, such as `Schema.isBetweenLength` /
  `Schema.isBetweenProperties` and `Scope.close` accepting only a `Scope.Closeable`. Follow
  Effect's release notes for semantic changes in your own code; for example, `Array`, `Chunk`,
  `Effect` and `Record` `partition` now return successes before failures.
* Tool JSON Schemas: Effect 4.0.0 exports `Schema.isPattern` only when the regex flags are `u`,
  optionally with `d`, `g` or `y`, and silently omits other patterns (including `v`-mode regexes and
  `u` combined with `i`, `m` or `s`). Yolk's connector schemas now use `u`, so connector tool
  parameters keep their `pattern` hints with unchanged runtime validation; the Fortnox identifier
  pattern is advertised as the equivalent BMP-only class
  `^(?!\.{1,2}$)[\u0020-\u007e\u0080-\ud7ff\ue000-\uffff]+$`. Add `u` to `Schema.isPattern` in
  your own tool parameter schemas to keep their hints, and check that `u` does not change what
  your regex accepts (surrogate ranges and bounded quantifiers over astral characters can).
* String `Schema.isMinLength(n)` and the minimum of `Schema.isBetweenLength` (`n >= 2`) are
  advertised as `minLength: ceil(n / 2)` code points. Tool execution still validates against the
  original Effect Schema (through its JSON codec).

### Canary.97: tool arguments accept `null` for optional fields and reject unknown keys [#canary97-tool-arguments-accept-null-for-optional-fields-and-reject-unknown-keys]

`makeTool`, `makeInputTool`/`makeInteractionTool` call params, and the `question` tool now decode
model arguments with `Schema.toCodecJson(parameters)`, the codec that `ToolDef.parameters` already
advertised. `null` on `Schema.optional(X)` now decodes as omitted instead of failing validation;
`Schema.optional(Schema.NullOr(X))` still keeps `null`, and required fields still reject it.
`resolveTools` also drops `null` on properties advertised as optional without `null`
(`Schema.optionalKey(X)`, the subagent `model`/`reasoning_effort`, raw MCP schemas) before any
registration sees the call. Advertised schemas are unchanged. Non-finite numbers stay rejected.
Unknown keys are now rejected (`onExcessProperty: 'error'`) instead of silently stripped, matching
the `additionalProperties: false` that tool schemas already advertised; one error reports every
issue, naming each unknown key with the allowed ones (root `Schema.Struct({})` tools included),
including a `null` on another union member's field. Callers or fixtures that sent extra keys to a tool now get a model-visible validation
error, and app wrappers that only existed to reject unknown keys can be removed.
If you worked around this with `Schema.optional(Schema.NullOr(X))` plus `null`-to-`undefined`
mapping, `Schema.optional(X)` is now enough; app wrappers that re-decoded with the JSON codec can
use `makeTool` directly. Custom `invalidParamsMessage` callbacks can keep the unknown-key hint with
the new `withToolArgumentsErrorHint`. `omitNullOptionalToolArguments` is new on `@yolk-sdk/agent/tools` for
hosts that dispatch registrations without `resolveTools`.

Package-generated agent tools follow the same policy: connector tools from
`makeConnectorToolModule`, `knowledge_lookup`/`knowledge_manage`, and the `sandbox` tool reject
unknown keys instead of stripping them. For example, `outlook.list_messages` rejects the search-only
`query`, and Fortnox invoice update tools reject provider-managed fields such as `Booked` or `Sent`.
Connector `execute`/`invoke` and `executeTyped` are unchanged.

### Canary.97: code mode JSON arguments and structured tool outputs [#canary97-code-mode-json-arguments-and-structured-tool-outputs]

* Code mode (`@yolk-sdk/codemode`, breaking): nested calls that end in an error result, a
  `beforeNestedCall` failure, or the `maxNestedCalls` limit now reject in the script with
  `<label>: <message>` instead of the bare message. The label is `tools.<identifier>`, or
  `tools["<name>"]` when an earlier tool already uses the identifier; cancelled and
  failed-unexpectedly rejections use the same label. `ToolResult.nestedCalls` keeps the raw
  message. Update scripts or checks that compare rejection messages.
* The pi executor now rejects, inside the script and before the call, arguments that JSON would
  silently change: `NaN`/`Infinity`, invalid `Date`s, `undefined`/function/symbol array items and
  holes, functions, symbols, bigints, cycles, `Map`/`Set`/`RegExp`/`Error`/class instances without
  `toJSON`, and arguments with more than 100000 values or 64 levels of nesting. A valid `Date` is
  sent as its ISO string. See [What scripts see](./integrations/code-mode#what-scripts-see).
* `CodeModeCatalogTool` gains a required `callLabel`; hosts that build catalog entries by hand must
  set it. Custom executors receive an optional `CodeModeExecutorTool.callLabel` (set by
  `makeCodeModeTool`) and should apply the same argument rules.
* Connector agent tools (`makeConnectorToolModule`) return the JSON encoding of the action
  `outputSchema` in both `structuredContent` and the text: `Chunk`s become arrays (instead of
  `{"_id":"Chunk","values":[...]}`), `DateTime`s ISO strings, class instances plain objects, and
  fields the output schema does not declare are dropped. A value that does not encode fails the call
  with an `execution` `ToolError`. Provider failures keep their text; their `structuredContent` is
  the JSON-encoded `ProviderFailure`, without a non-JSON `underlying`. Update UI or persistence that
  read the old shapes. Modules now carry the connector `description` (override it with the
  `description` option).
* `knowledge_lookup`/`knowledge_manage` declare `KnowledgeLookupOutput`/`KnowledgeManageOutput` and
  the `sandbox` tool declares `SandboxToolOutput` (with bounded `stdout`/`stderr`), returned as
  `structuredContent`; code mode scripts now receive these objects instead of the text. Text
  content is unchanged for the model.
* New: the experimental `@yolk-sdk/connectors/afloat/conformance` subpath and the `afloat` profile
  of `@yolk-sdk/emulators/mcp`; see [Afloat MCP conformance](./connectors/afloat).

### Canary.96: code mode, classifier models, conformance, and emulators [#canary96-code-mode-classifier-models-conformance-and-emulators]

New packages: `@yolk-sdk/codemode` ([Add code mode](./integrations/code-mode)) and the
experimental, test-only `@yolk-sdk/conformance` and `@yolk-sdk/emulators`
([Test with emulators](./guides/testing-with-emulators)). `@yolk-sdk/agent`, `@yolk-sdk/connectors`,
and `@yolk-sdk/mcp` now depend on `@yolk-sdk/conformance` for their conformance subpaths; add it
yourself only if you import its runner or replay client.

The agent tool contract gains optional fields. Existing tools keep working unchanged:

* `ToolDef.outputSchema` (`makeTool({ output })`), `callableBy` (default `all`), and `discovery`.
* `nestedToolAccess` and `describe` on registrations, and `ToolResult.nestedCalls` and
  `ToolResult.usage`. Neither reaches the model; `toolResultMessageFromResult` drops both and the
  loop does not add `ToolResult.usage` to run usage.
* `ToolRegistryError` gains the `codemode_unsupported_tool` and `invalid_tool_exposure` causes. If
  you match its `cause` exhaustively, add both.
* If you send `ToolDef`s to providers yourself (outside `run`/`runModelTurn`), filter them with
  protocol `providerToolDefs` so codemode-only tools never reach providers.

`@yolk-sdk/agent/classification` and `@yolk-sdk/agent/providers/vercel/ai-gateway-classifier` add
classifier models over AI Gateway `POST /v1/evaluate`; see
[Classifier models](./agent/classifier-models). Connector and MCP tool adapters accept an
`exposure` option for code mode.

`gmail.draft_delete` now succeeds on Gmail's empty `204` response instead of failing to decode it.

### Canary.95: Gmail multipart send and Outlook draft attachments [#canary95-gmail-multipart-send-and-outlook-draft-attachments]

`gmail.send_message` keeps its `{ raw, threadId? }` input and output and still sends exactly one
request. 7-bit MIME now goes to `upload/gmail/v1/users/me/messages/send?uploadType=multipart`
carrying the decoded MIME, so messages up to Gmail's 35 MiB cap are accepted; MIME with any byte
`>= 0x80` keeps the previous JSON `raw` request. Decoded MIME larger than 35 MiB now fails before
credentials or network with `validation_failed` and
`underlying: { outcome: 'rejected', retryable: false, reason: 'too_large' }`; nothing is sent.
Host HTTP adapters must preserve the `multipart/related` content type and the string body exactly.
Rejected/unknown HTTP classification is unchanged.

`addOutlookAttachment` is a new host-only helper (not an action) on `@yolk-sdk/connectors/microsoft`.
It requires `CredentialResolver` and `ConnectorHttpClient`: its Graph JSON POSTs
(`fileAttachment` under 3 MiB and `createUploadSession`) use your existing string HTTP adapter,
which must allow those POSTs and a success body of `maxMetadataBytes` plus the echoed base64 content,
and must not log, trace or persist those bodies (file content and the token-bearing `uploadUrl`).
Only files of 3 MiB or more need a `ConnectorBinaryWriteHttpClient` with the new optional
`uploadSession` method; hosts without that method, or without the port at all, fail those uploads
with `upload_session_required` before credentials or network. See
[Attach a file to an Outlook draft](./connectors/files#attach-a-file-to-an-outlook-draft).

### Canary.94: Fortnox customer write inputs [#canary94-fortnox-customer-write-inputs]

This is a breaking change to the Fortnox customer write actions that shipped in canary.90. When
upgrading `@yolk-sdk/connectors` from canary.93:

* `FortnoxCreateCustomerInput` and `FortnoxUpdateCustomerInput` no longer accept `Country` or
  `Phone`. Set `CountryCode` instead of `Country`, and `Phone1`/`Phone2` instead of `Phone`.
  `FortnoxCustomer` and `FortnoxSupplier` responses still include both fields.
* `fortnox.create_customer` and `fortnox.update_customer` reject unknown keys instead of dropping
  them, before any request is sent. Connector `execute`/`invoke` and `executeTyped` fail with
  `ConnectorError` cause `validation_failed`; generated agent tools reject the call arguments with a
  tool `validation` error. Remove `Country`, `Phone`, and any other unsupported keys from host-built
  inputs, and expect model tool calls that include them to fail validation.
* The `inputSchema` of both actions is now a closed wrapper, not the input class. Build typed
  inputs with `FortnoxCreateCustomerInput.make` / `FortnoxUpdateCustomerInput.make`. Decoding those
  classes directly still strips unknown keys.

Invoice write inputs were unchanged in canary.94: `execute` and generated agent tools still dropped
unknown keys (from canary.97, generated agent tools reject them), and
`executeTyped` trusts an existing invoice input class instance without rechecking its keys. See
[Fortnox write semantics](./connectors/fortnox#fortnox-write-semantics).

### Canary.91: OneDrive move/copy and email Sent copy [#canary91-onedrive-movecopy-and-email-sent-copy]

Upgrading `@yolk-sdk/connectors` adds three Microsoft tools when hosts pass the complete
`MicrosoftConnector` to `makeConnectorToolModule`: `onedrive.move_item` and `onedrive.copy_item`
(`write`), and `onedrive.get_copy_status` (`read`). Copy acceptance is not completion. Hosts that
allowlist actions or override access should review the new ids. Copy polling sends no credential to
the monitor URL and requires the host HTTP adapter to honor `redirect: 'manual'` and
`credentials: 'omit'`.

`email.send_message` now returns `sentCopy` even for legacy hosts: `unsupported` when saving was
requested but unavailable, or `skipped` when disabled. Saving is requested by default; set
`saveToSentItems: false` to skip it. A `failed` or unverified Sent copy after SMTP acceptance does
not mean the message was not sent; do not resend.

OpenAI-compatible Chat Completions lower tool-result images, readable text documents, and opted-in
PDFs to supplementary user content after the complete tool-result block. Other document formats and
audio still fail. Canonical history is unchanged.

### Canary.90: Fortnox customer and invoice writes [#canary90-fortnox-customer-and-invoice-writes]

Upgrading `@yolk-sdk/connectors` adds four generated write tools when hosts pass the complete
`FortnoxConnector` to `makeConnectorToolModule`: `fortnox.create_customer`,
`fortnox.update_customer`, `fortnox.create_invoice`, and `fortnox.update_invoice`. Existing Fortnox
resource scopes already grant read and write access, so this does not require new OAuth consent.

Read-only hosts should restrict enabled actions explicitly and review any host access override:
blanket `access: 'read'` overrides declared action metadata, including these new `write` declarations.
Keep authorization and approval policy host-owned. Sending, booking, cancellation, and payment remain
outside the connector. See [Fortnox](./connectors/fortnox).

### Unreleased: reviewed email connector primitives [#unreleased-reviewed-email-connector-primitives]

* `gmail.send_message` is a new **destructive** action for complete host-generated base64url MIME.
  It supports new messages and replies whose headers and `threadId` meet Google's threading
  requirements. Keep it out of model allowlists unless the host explicitly intends that exposure;
  a host-owned reviewed interaction is a separate opt-in. Success means submission, not delivery.
* Its `GoogleGmailSendOAuthCredentialSlot` uses the existing `google.oauth` binding and hints
  `gmail.send`. Existing `gmail.compose`, `gmail.modify`, or full-mail grants already permit sending;
  the action inspects OAuth scope metadata, then re-resolves through the selected operation slot
  so strict host resolvers enforce an existing sufficient grant without additional consent. Bearer
  credentials or missing scope metadata fall back to the send slot. Combined consent and existing
  draft APIs are unchanged.
* `outlook.update_draft` is a new **write** action for edited recipients, subject, and complete body.
  Omitted fields remain unchanged; empty arrays clear recipients. Unlike `create_reply_draft`, its
  body replaces the full content and does not prepend quoted history. Update followed by send is
  not atomic and does not provide compare-and-swap.
* `outlook.reply` is a new **destructive** action that sends the complete reviewed reply in one
  Graph `POST .../reply` with explicit `to`/`cc`/`bcc`, subject, and full body. Required recipient
  arrays (including empty ones) prevent provider recipient defaults; no `comment`, `from`, quoted
  history, or draft round-trip is involved. It reuses the existing send-slot mailbox permissions.
  Only HTTP 202 counts as accepted, meaning submission rather than delivery, with no message ID
  or exactly-once claim. Prefer it over update-then-send for reviewed replies.
* None of these three actions retries automatically. Gmail/Outlook unconfirmed-send metadata and
  Outlook's existing-draft recovery identity must be handled before another mutation. See
  [connector sending and editing](./integrations/connectors#submit-a-reviewed-gmail-message).

### Action-backed interaction opt-in [#action-backed-interaction-opt-in]

`makeInteractionTool` introduces distinct interaction request, response, event and client-input
variants. Update exhaustive HITL consumers before advertising these tools; never downgrade
`InteractionResponse` to data-only input or synthesize a result from `InteractionSubmitted`.
`makeInputTool`, questions and ordinary approvals retain their existing behavior.

Opt-in hosts must authenticate and atomically accept immutable submissions, provide the scoped
`InteractionHost`, load receipt snapshots before durable preflight, and forward the optional
`ToolExecutionOptions.interaction` reference through executor decorators. Raw HITL responses or
client transcript replay are not execution authority. No live example app opts in implicitly.
See [Authorize one action](./agent/tools-hitl#authorize-one-action).

### Canary.82: typed inputs and Gateway streaming [#canary82-typed-inputs-and-gateway-streaming]

When upgrading from canary.81:

* Prefer `resolveTools` over hand-built toolsets. `ResolvedToolSet` now requires `inputs`; custom
  toolsets without typed input tools must supply an empty record (`inputs: {}`). Pass the resolved handlers as
  `inputs: toolSet.inputs` to loop/runtime configuration and `prepareToolBatch`; serializable
  definitions alone return unavailable instead of prompting.
* Update exhaustive protocol/client/React consumers for input requests, submitted/cancelled
  responses, lifecycle events, `InputResponseInput`, and `InputRequested`/`InputSubmitted`/`InputCancelled` tool states. Extend any
  host-owned closed persistence/wire schemas before storing or transporting these variants.
* Keep typed input pending until server acceptance. Invalid response data re-pends the same request
  for correction; transport failure is not an accepted result. Existing question behavior remains
  compatible. Input collection is not approval, and voice still supports approvals only.
* Full `run` streams now emit synthetic `ToolExecutionCompleted` events for rejected calls and
  resolved HITL, including while siblings remain pending. These do not execute tools; custom event
  consumers should preserve server results without completing the same call twice.
* Gateway keeps JSON completions by default. Factory `streaming: true` enables SSE deltas;
  `reasoningContent: true` independently preserves compatible reasoning output and assistant replay
  (spending input tokens). Neither option is enabled automatically.

See [typed input wiring](./agent/tools-hitl#collect-typed-input) and
[Gateway setup](./integrations/provider-setup#vercel-ai-gateway).

### Next canary: generic-email labels, flags, moves, and required headers [#next-canary-generic-email-labels-flags-moves-and-required-headers]

New `@yolk-sdk/connectors` actions `email.modify_labels`, `email.set_flag`, and `email.move`
work through optional `EmailClient` host methods; missing methods fail with a typed validation
error, so existing adapters keep working. `email.get_message` now requires `headers` and
runtime-validates host output: hosts that omit `headers` fail with `validation_failed`, so update
`EmailClient.getMessage` adapters to return RFC 5322 headers. Outlook `outlook.get_message`
returns required `internetMessageHeaders`; list, draft, and mutation responses are unchanged.

### Next canary: chat-stream failure diagnostics [#next-canary-chat-stream-failure-diagnostics]

OpenAI-compatible chat streaming now rejects a 2xx response with an explicit non-SSE content type
before reading its body: `invalid_response` carries `providerCode: 'unexpected_content_type'`
instead of waiting for an `incomplete_stream` failure. Missing content-type headers retain lenient
SSE parsing. Update host error-code handling accordingly; both failures are non-retryable.

`ProviderErrorInfo` also adds optional `stream: ProviderStreamDiagnostics`, preserved through
`LLMError` and `AgentError`. Hosts persisting provider metadata through their own closed schemas
should allow this field; it contains counters/milestones only, not transcript or raw response data.
See [stream diagnostics](./troubleshooting#diagnose-chat-stream-failures-with-stream-diagnostics).

### Next canary: Outlook mailbox identity and reply-draft recovery [#next-canary-outlook-mailbox-identity-and-reply-draft-recovery]

These `@yolk-sdk/connectors` changes target the next matching canary; they are not in canary.80.

* Explicit delegated `mailbox` operations now resolve the scope-free `microsoft.oauth` identity slot,
  then the enforcing operation slot. Hosts must support both resolutions. Set `OAuthCredential.accountId`
  to the same Graph user ID or `userPrincipalName` form passed as `mailbox` to retain ordinary
  `Mail.*` scopes; comparison ignores case only and does not resolve aliases. Other mailboxes still
  require Shared scopes. Application-mode guards are unchanged.
* `outlook.create_reply_draft` now **prepends** its `body` to Graph-generated quoted history instead
  of replacing it. Pass only the new reply. This is a multi-step write; post-create HTTP failures
  use `outlook_create_reply_draft_partial` with the HTTP `status` and no `retryAfterMs`. Both these
  failures and post-create typed `ConnectorError`s expose
  `underlying: { draftId, retryable: false, recovery: 'read_edit_existing_draft' }` when the ID is
  known. Update retry handlers to read/edit the existing draft, never recreate it. Lost creation
  responses still require mailbox reconciliation. See [reply draft recovery](./integrations/connectors#reply-drafts-and-recovery).
* Attachment listing selects base properties only: fetch the individual file attachment for
  `contentId`/`cid:` mapping. `lastModifiedDateTime` can now be `null` as well as absent or a string;
  update consumers that assume a present value is always a string.

### Next canary: chat streaming, Anthropic tool results, union tool schemas [#next-canary-chat-streaming-anthropic-tool-results-union-tool-schemas]

These `@yolk-sdk/agent` behavior changes target the next matching canary. See [Go setup](./integrations/provider-setup#opencode-go) and [troubleshooting](./troubleshooting).

* OpenAI Chat Completions transport stays one JSON body by default. `OpenAiProviderConfig.streaming:
  true` requests incremental `chat.completion.chunk` SSE deltas with usage; unterminated streams
  fail `invalid_response` without `Done`. OpenCode Go chat always streams. Only enable streaming
  against endpoints that serve chat SSE.
* Anthropic tool-result blocks omit `is_error` when the result carries no error flag, keeping
  follow-up request bodies valid. Explicit boolean flags are still serialized.
* `makeTool` may add root `type: "object"` to typeless object-only `anyOf`/`oneOf` unions for strict
  OpenAI-compatible upstreams. Call validation still uses the original Effect Schema.
* Chat Completions and Responses HTTP failures copy the envelope string `code` (falling back to
  `type`) into `provider.providerCode`; raw upstream bodies stay out of typed failures.

### Next canary: selected branded identities and typed connector actions [#next-canary-selected-branded-identities-and-typed-connector-actions]

These source changes target a future matching canary. Identity wire representations stay strings,
but typed host implementations and fixtures must migrate; this is a breaking pre-1.0 minor change.

| Surface                         | Migration                                                                                                                          |
| ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `@yolk-sdk/knowledge/documents` | Use `KnowledgeScopeId` and `KnowledgeDocumentId` in models, store adapters, chunking, ingestion, and search scopes.                |
| `@yolk-sdk/harness/inbox`       | Forward live `DrainToken` and `ParkGeneration` values; custom Inbox/Driver adapters must return the corresponding brands.          |
| `@yolk-sdk/sandbox`             | `normalizeWorkspaceCwd` now returns `NormalizedWorkspaceCwd`; raw command `cwd` remains a string.                                  |
| `@yolk-sdk/connectors/fortnox`  | File discovery uses canonical `FortnoxGivenNumber`; preview downloads require `FortnoxDocumentNumber`. Archive IDs remain strings. |

Effect-decode external/persisted strings with the exported schema; `.make` is synchronous and is
appropriate for trusted constants or freshly minted values. Do not cast raw IDs or annotate ORM
columns to bypass decoding. For example, inside an Effect program:

```ts
import * as Schema from 'effect/Schema'
import { KnowledgeDocumentId } from '@yolk-sdk/knowledge/documents'

const documentId = yield * Schema.decodeUnknownEffect(KnowledgeDocumentId)(rawDocumentId)
```

This is a fragment; `rawDocumentId` is host-owned input. Brands do not establish authorization,
ownership, existence, or freshness. Harness token schemas remain nominal-only and accept arbitrary
strings; runtime stale/foreign-token decisions remain authoritative. Do not restore old in-memory
park generations by decoding them after restart.

Fortnox file metadata now rejects nonnumeric `givenNumber` values through the canonical schema.
Preview identifiers use the same validator as invoice reads and complete-segment URL encoding,
rather than unrelated archive-ID restrictions.

`defineAction` additionally returns `TypedConnectorAction` with `executeTyped`. It accepts decoded
`InputSchema.Type`, validates using `Schema.toType(inputSchema)`, and retains the output type. It
does not reapply wire transformations: a `NumberFromString` field is a number at this entrypoint.
Existing dynamic `execute`/`invoke` paths remain compatible and decode encoded input as before.
External output validation remains the implementation's responsibility.

### Next canary: Effect rc.115 [#next-canary-effect-rc115]

This source upgrade targets `effect@4.0.0-rc.115`; it is not a claim that an already-published canary uses that version. Upgrade matching Yolk packages and Effect together when the corresponding canary is available.

* Use `Schema.TaggedError`, `Schema.fromJsonString(Schema.Unknown)` and capitalized `Config.String` / `Config.Int` / `Config.Redacted` APIs.
* Schema construction now follows schema field order, including `_tag` first. JSON field values and optional presence are unchanged, but raw serialized bytes can differ. Do not depend on beta.80's property insertion order.
* `Schema.SchemaError` is now a native `Error`. Synchronous schema makers throw a native error with a `SchemaIssue.Issue` cause; Effectful makers fail with the issue. Keep typed owner errors and inspect retained causes rather than matching old diagnostic text.
* Tool schemas use Effect's canonical JSON representation. Prefer finite-number schemas for JSON inputs; definition references may acquire an `Encoded` suffix. Empty-struct tools still advertise a closed empty object. Custom JSON Schema output must still pass Yolk's portable-data boundary.

### Next canary: renamed public service types [#next-canary-renamed-public-service-types]

Update type imports from these existing subpaths. The former names have no compatibility aliases;
runtime behavior and wire formats are unchanged.

| Subpath                    | Before            | After                |
| -------------------------- | ----------------- | -------------------- |
| `@yolk-sdk/agent/loop`     | `LoopConfigShape` | `LoopConfigSettings` |
| `@yolk-sdk/harness/store`  | `RunStoreShape`   | `RunStoreApi`        |
| `@yolk-sdk/harness/inbox`  | `InboxShape`      | `InboxApi`           |
| `@yolk-sdk/harness/driver` | `DriverShape`     | `DriverApi`          |

### Next canary: optional harness and collector recovery [#next-canary-optional-harness-and-collector-recovery]

`@yolk-sdk/harness` is a new optional run-lifecycle package (coordinator, store, inbox, drivers, outcomes). It is not the agent loop and does not add a Workflow driver. It is introduced after `0.1.0-canary.76` and unavailable in `0.1.0-canary.76` and earlier. Choose a newer matching canary once available.

Loop composition now names `makeAgentLoopLayer`, `decorateLLMProvider`, `collectModelTurn`, and `collectModelTurnAttempt`. Omitted tools use `ToolExecutor.unavailable`.

Kernel streams that end with zero `Done` events fail as `LLMError` `invalid_response` / `retryable: false` with `responseIssue: 'missing_done'`. That is not automatic provider or tool replay. Codex additionally synthesizes `Done` only for the specific missing-final-`output` error; see [OpenAI Codex](./integrations/model-providers#openai-codex).

Overflow compact now refuses to run after published output (`overflowCompactionMayRun`). Durable persist-then-retry stays host-owned.

`attemptModelTurn` classifies one `runModelTurn` after that stream's inner retries. It does not add an outer retry loop. A finalized collector failure (`collectModelTurn` / `collectModelTurnAttempt`) is not host-chosen recovery; see [Troubleshooting](./troubleshooting#collector-failed-versus-host-chosen-recovery) and [Harness composition](./vercel-workflows/harness-composition).

### Next canary: owned JSON data and voice session resources [#next-canary-owned-json-data-and-voice-session-resources]

`ToolDef.parameters` now requires `ToolJsonSchema`: boolean or plain JSON-object representation.
Constructors/raw decode reject nonfinite values, cycles, exotics and accessor fields; accessors are
not executed. Dense ordinary arrays, null-prototype objects and DAG aliases are legal. Admitted
identity is retained, not frozen. Use `decodeToolJsonSchema` / `decodeToolJsonSchemaObject` for raw
inputs (`Option`); JSON Schema semantic/provider validation is separate. Tool arguments/results and
HITL stay opaque. Background envelopes preserve boolean argument schemas. MCP discovery requires
the object arm and retains typed validation errors and the omitted-schema default.

`OpenAiProviderConfig.extraBody` now takes JSON-object input (`OpenAiRequestExtras`). Build inert
JSON data, not getter-backed configuration. Lowering snapshots surviving enumerable own fields,
discarding canonical request keys unread. Surviving accessors/exotics/invalid JSON fail with fixed
`Invalid … extraBody JSON: expected a JSON object` before HTTP. The snapshot preserves JSON values,
own `__proto__`/`constructor` and DAG aliases; it does not retain input identity. Root symbols/hidden
fields are omitted; nested symbols/hidden fields and extra array properties fail. Final request
serialization remains independently checked. Proxy reflection traps are not guaranteed inert.

Connector integration/binding `metadata` now uses `PortableMetadata`. Convert Dates, Maps, custom
instances and other rich values to explicit JSON first. Decode/make return non-frozen snapshots with
null-prototype objects and dense arrays; aliases share copied nodes, cycles/accessors/exotics fail.
Absent metadata stays absent. Config, credential secrets, error `underlying` and host DB schemas are
unchanged; this is not a database migration.

`makeVoiceController` now requires `VoiceTransport` instead of `options.transport`. Wrap existing
transport values with `Effect.provideService`, or use `VoiceSession.layer` with a transport layer,
codec/tool endpoint and optional `eventLog`. Browser/WebSocket transport layer constructors are
exported from their existing subpaths. Configured logging runs without an external event consumer;
no `eventLog` means no ambient outbox capture. Keep provided layers alive through the full session
usage, or use `Layer.buildWithScope` for an explicit lifetime. `Layer.succeed` injects externally
owned values; it does not allocate/finalize resources. These are breaking 0.x changes (minor).

### Next canary: makeTool SchemaError and workflow CommitError callbacks [#next-canary-maketool-schemaerror-and-workflow-commiterror-callbacks]

`makeTool({ invalidParamsMessage })` on `@yolk-sdk/agent/tools` is now
`(error: Schema.SchemaError) => string` (was `(error: unknown) => string`). Only
`Schema.decodeUnknownEffect` on `parameters` invokes it (validate and execute). The decode error
is passed through unwrapped. Default remains `Invalid ${name} arguments: ${String(error)}`,
including the `SchemaError(...)` wrapper. In Effect rc.115, `SchemaError` extends native `Error`,
but the wrapper remains part of this tool-message contract; do not switch the default to `.message`. Existing `(error: unknown) => string` callbacks remain assignable. No new
export subpath; `MakeToolOptions` is still not barreled from `@yolk-sdk/agent/tools`.

`commitThenWriteTerminalEvent({ writeCommitError })` on `@yolk-sdk/vercel-workflows` is now
`(error: CommitError) => …`, where `CommitError` is the existing generic on `commit`. The producer
is `Effect.matchEffect` `onFailure` of `commit`; typed failures—not defects or interruptions—are
passed to the callback. Result tags still carry `commitError` and `error` as `unknown`; those fields are not
tightened. Existing `(error: unknown) => …` callbacks remain assignable. No generic expansion or
export-map change.

### Next canary: voice void addTrack, finite voice argument JSON, MCP protocol owners [#next-canary-voice-void-addtrack-finite-voice-argument-json-mcp-protocol-owners]

`WebRtcPeerConnectionLike.addTrack` on `@yolk-sdk/agent/voice/browser` is now a void command (was
unused `unknown`). Hosts and fakes must not read a sender. Real `RTCPeerConnection.addTrack`
remains assignable. No export-map change.

Voice raw-argument JSON on `@yolk-sdk/agent/voice`: `protocolToolCallFromVoice` and
`decideVoiceToolCall` admit finite JSON. Actual `null` / `false` / `0` still admit as those values.
Raw text `1e999` uses the existing malformed fallbacks instead of publishing `Infinity`:
projection params are the raw string `'1e999'`; approval display params are
`{ argumentsJson: '1e999' }`. Nested overflow such as `{"n":1e999}` takes the same fallbacks. Do
not demonstrate with `JSON.stringify(Infinity)` (that is `null`). `protocolToolCallFromVoice` still
returns `ToolCall`. Execution schema validation, approval identifiers, and gates are unchanged.

`@yolk-sdk/mcp/client` and `@yolk-sdk/mcp/protocol` add Schema owners `InitializeClientInfo`,
`InitializeParams`, `InitializedNotification`, and `ToolsCallParams` (same `protocol.ts`; no new
export subpath). Prefer Schema owners for new construction. Compatibility `makeJsonRpcRequest`,
`makeInitializeParams`, and `makeInitializedNotification` remain and build through those schemas.
`makeJsonRpcRequest` still omits `params` when `undefined`; when params are present, getter access
order stays `id`, `method`, `params`, `params`.

### Next canary: OpenAI JSON admission, Realtime parameters, and Gmail finite JSON [#next-canary-openai-json-admission-realtime-parameters-and-gmail-finite-json]

OpenAI Chat Completions and Responses lowering now requires `ToolDef.parameters` and tool-call
`params` to decode as `Schema.Json`. Non-JSON values fail as non-retryable `LLMError`
`provider_error` before transport. `ToolDef.parameters` now has the admission contract above;
`ToolCall.params` remains `Schema.Unknown`. Public
Codex wrapper `OpenAiCodexTool.parameters` is still `unknown`. Optional body fields are omitted
unless present. After lone-surrogate rewrite, request bodies are decoded as JSON again and fail
rather than skipping. Inbound HTTP JSON admits `Schema.Json` (`invalid_response` on failure).
Responses SSE JSON admits `Schema.Json`: non-object JSON events are ignored; malformed non-JSON
event text fails. First `response.completed` remains terminal. HTTP error bodies stay raw text.

The former extraBody spread/getter contract is superseded by the portable snapshot migration above.
Canonical fields are discarded unread and surviving accessors are rejected without execution.
Composed-body admission after lone-surrogate rewriting remains the final serialization defense.

Public Realtime `OpenAiRealtimeFunctionTool.parameters` and `openAiRealtimeToolParameters` now take
`Schema.Json`. Non-JSON advertisement fails `VoiceToolBridgeError`: sync helpers throw; Effect
helpers fail in the typed channel. Mapper defects stay defects. Union-root lowering uses a `Map` so
own `__proto__` / `constructor` merge instead of prototype assignment.

Gmail `get_thread` / `list_attachments` MIME `payload` admits `Schema.Json` after JSON parse.
Best-effort optional size omission (`-1`, `1.5`, `null`, `"12"`, missing) and sibling preservation
are unchanged. Finite JSON is a deliberate whole-payload reject: raw HTTP `1e999` → `Infinity` →
`ConnectorError` `validation_failed` (`Invalid response shape`). Public action classes,
`GmailUnknownOutput`, and `gmail.get_attachment` are unchanged. Independent raw wire/key goldens were
not migrated.

### Next canary: Claude JSON tool payloads and React constructor usage [#next-canary-claude-json-tool-payloads-and-react-constructor-usage]

Claude lowering now requires `ToolDef.parameters` and `ToolCall.params` to decode as `Schema.Json`.
Non-JSON values fail as non-retryable `LLMError` with `cause: 'provider_error'`. `ToolDef.parameters`
now has the admission contract above; `ToolCall.params` remains opaque. After lone-surrogate
rewrite, the Claude request body is decoded as JSON again and fails rather than skipping.
HTTP error bodies that are not JSON still classify from status.

`useAgentChat` now dispatches the existing `AgentChatAction` constructors and returns the existing
hook-result constructors (`AgentChatSubmitResult`, `AgentChatDeleteTurnResult`, and siblings).
Those values are `Data.taggedEnum` plain objects with `_tag` last, not Equal/Hash classes. Prefer
constructors and `$is`; omit absent optionals. Duration descriptors still use
`Schema.TaggedStruct.make`. No new React export paths.

MCP production client/protocol/index are unchanged in this batch. App-owned knowledge-search File
identity, Cloudflare occupancy, and example UI wiring are not `@yolk-sdk/*` APIs.

### Next canary: canonical tagged constructors [#next-canary-canonical-tagged-constructors]

Several public ADTs that were type-only, or that callers built as handwritten `{ _tag }` objects,
now have constructors on existing subpaths. No new export paths.

`Data.taggedEnum` builds **plain objects** `{ ...fields, _tag }` (`_tag` last). They are not
`Equal`/`Hash` Data classes. `Schema.Class` / `Data.TaggedClass` remain class instances.
`Schema.TaggedStruct.make` constructs validated plain values. Prefer constructors; omit absent optionals.
Existing `_tag` reads still work.

| Package / subpath               | Before                                                              | After                                                                                                                                                                    |
| ------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `@yolk-sdk/agent/protocol`      | `PlainHitlResponse` type-only; helpers wrote `_tag` (often first)   | Value `PlainHitlResponse.QuestionResponse` / `.ToolApprovalResponse`; helpers omit absent optionals                                                                      |
| `@yolk-sdk/agent/runtime`       | `export type { RuntimeRequest }` only                               | `export { runRuntime, RuntimeRequest }` (value carries the type)                                                                                                         |
| `@yolk-sdk/agent/react`         | Chat ADTs type-only                                                 | Values `AgentChatPart`, `ChatToolState`, `AgentChatItem`, `ToolRunState`, message mutators, `AgentChatAction`, hook results; `ToolDurationKnown` / `ToolDurationUnknown` |
| `@yolk-sdk/harness/outcome`     | `StepOutcome` / `HitlMatch` / overflow result type-only or internal | Public `StepOutcome`, `HitlMatch`, `OverflowCompactionResult`                                                                                                            |
| `@yolk-sdk/harness/inbox`       | Private decision constructors                                       | Public `HitlDecision`, `PauseDecision`, `RecoveryAttempt`, `RecoveryAdmission`, `DrainBegin`                                                                             |
| `@yolk-sdk/harness/driver`      | `export type StopDecision` only                                     | Type + `export const StopDecision`; recovery uses Inbox `RecoveryAttempt`                                                                                                |
| `@yolk-sdk/knowledge/documents` | Inline `{ _tag: 'File' }` / `{ _tag: 'KnowledgeScope' }` objects    | `KnowledgeFileSource` / `Url` / `Text` and `KnowledgeSearchScope` / `KnowledgeSearchScopes` `.make`                                                                      |
| `@yolk-sdk/vercel-workflows`    | Type-only `WorkflowStepResult` / `VercelAgentWorkflowRunResult`     | Matching value companions; `settleWorkflowStep` returns `Success` / `Failure` constructors                                                                               |

JSON key order for `Data.taggedEnum` values puts `_tag` last. Do not treat that as `Equal`/`Hash`.
The knowledge **value** `KnowledgeSearchScope` is the single-id constructor; the **type** remains the union.
A missing source URL is not a storage object id; do not invent locators to satisfy `.make`.

### Next canary: host-only connector file retrieval and writes [#next-canary-host-only-connector-file-retrieval-and-writes]

New byte helpers on existing connector subpaths are host-only. They are not connector actions and
`makeConnectorToolModule` does not serialize them. Provide `ConnectorBinaryHttpClient` and/or
`ConnectorBinaryWriteHttpClient`, keep streamed limits and connection-time network policy in the
host, and keep raw bytes out of generic tool JSON. Dropbox create is strict add; Dropbox update
requires a stable `id:` and expected revision; OneDrive update requires `acknowledgeOverwrite: true`
and is unconditional, not compare-and-swap; R2 puts stay ETag-conditional. Fortnox `connectfile` and
`archive` slots are opt-in and are **not** on `FortnoxCombinedOAuthCredentialSlot`. Drive content
defaults to `drive.file`; `contentAccess: 'readonly'` is host-only `drive.readonly`.

Passing whole `FortnoxConnector` or `TodoistConnector` into `makeConnectorToolModule` now also
exposes `fortnox.list_supplier_invoice_files` and `todoist.list_comments`. See
[Transfer connector files](./connectors/files).

### Next canary: host-only Dropbox original-byte download [#next-canary-host-only-dropbox-original-byte-download]

`downloadDropboxFile` from `@yolk-sdk/connectors/dropbox` is an optional host helper that reuses
the root `ConnectorBinaryHttpClient` port. Default Dropbox actions and `makeConnectorToolModule`
serialization are unchanged. `DropboxCombinedOAuthCredentialSlot` now also hints
`files.content.read`; hosts that consent with the combined slot will request that scope on the
next authorization, and hosts that want original bytes should use the new
`DropboxContentReadOAuthCredentialSlot`. See
[Host-only Dropbox original-byte download](./integrations/connectors#host-only-dropbox-original-byte-download).

### Next canary: host-only OneDrive original-byte download [#next-canary-host-only-onedrive-original-byte-download]

`downloadOneDriveItem` from `@yolk-sdk/connectors/microsoft` is an optional host helper plus the
root `ConnectorBinaryHttpClient` port. Default Microsoft actions and `makeConnectorToolModule`
serialization are unchanged. Hosts that want original bytes provide the binary port, keep
connection-time network policy, and own file materialization. See
[Host-only OneDrive original-byte download](./integrations/connectors#host-only-onedrive-original-byte-download).

### Next canary: background tool admission and bounded child observations [#next-canary-background-tool-admission-and-bounded-child-observations]

Tools with `background: true` remain unchanged without a `BackgroundToolHost`. When a host is
supplied to `resolveTools`, activated tools require `{ execution, arguments }` rather than raw
business parameters. Update exhaustive event/state consumers for `ToolExecutionAccepted` and
`Accepted`: admission settles the call but does not complete the work. Preserve the full call and
`acceptance` receipt through persistence, replay, hydration, and next-turn cleanup.

Store and return activated approval request IDs unchanged as opaque, potentially long values;
they bind the exact tool, execution mode, and arguments. Resolve voice/realtime toolsets without a
background host, even for foreground calls. Custom voice decision consumers must handle `Deny`;
Effect hosts can use the typed realtime config builders to recover from `VoiceToolBridgeError`.
See [Model-chosen background execution](./agent/tools-hitl#let-the-model-choose-background-execution).

Explicitly include the `question` definition in the loop's enabled tools to allow question HITL.
Omitting it now returns an unavailable-tool result without pausing, even with a replayed answer.

`awaitWorkflowChild` read/sleep callbacks now receive zero-based attempt indices; existing
zero-argument callbacks remain valid. Hosts can stop observation at their own ceiling without
claiming the child terminated. For a nonterminal `subagent` result, use the matching
`subagent_observation` marker and logical child ID to avoid a false `SubagentCompleted` event.
See [Nonterminal child observations](./agent/tools-hitl#nonterminal-child-observations) and
[Bounded child observations](./vercel-workflows/step-contracts#bounded-child-observations).

### Next canary: private attachment resolution [#next-canary-private-attachment-resolution]

Use `resolveMessageAttachmentSources` or `resolveMessagesAttachmentSources` from
`@yolk-sdk/agent/protocol` to resolve media in a request-local transcript copy. These helpers do not
automatically sign refs or add provider media support. Keep authorization/signing inside each
provider attempt, including overflow retry, while persisted messages retain refs. See
[Resolve private attachments](./guides/private-attachments).

Gmail discovery now omits malformed optional attachment sizes; zero remains valid. Public
`GmailThreadAttachment` schema decoding requires any present `size` to be a nonnegative integer.
Update stored-metadata decoders and fixtures that previously supplied negative or fractional sizes;
provider sizes still do not prove actual decoded byte length.

### Next canary: opt-in durable subagents [#next-canary-opt-in-durable-subagents]

Inline subagent registrations remain compatible. Hosts opting into `background: true` must
implement durable child launch and choose a completion policy. They may deliver findings
automatically or expose authenticated status/wait observations through host-owned tools. Return
`makeSubagentAcceptedToolResult` for launch acceptance; it is not final child output and adds no
child usage or `SubagentCompleted`. Storage, ownership, and Stop policy remain host-owned. See
[Background subagents](./agent/tools-hitl#background-subagents).

Custom Workflow tool-batch hosts can use `prepareToolBatch` inside a preflight step and
`orchestrateWorkflowToolBatch` / `awaitWorkflowChild` in orchestration. Pending HITL fences all
launches. Do not wrap an independent child loop in a parent step, and handle partial results plus
failures before returning the batch result. See
[Independent child orchestration](./vercel-workflows/step-contracts#independent-child-orchestration).

### `0.1.0-canary.72`: Outlook optional read inputs [#010-canary72-outlook-optional-read-inputs]

`outlook.list_messages` and `outlook.search_messages` now normalize null/blank optional strings
and null page sizes to `undefined` for direct calls and generated agent tools. Existing non-blank
values are unchanged; search still requires `query`, and application access still requires a
non-blank `mailbox`. See [Optional Outlook read inputs](./integrations/connectors#optional-outlook-read-inputs)
for the accepted fields and validation rules.

### `0.1.0-canary.57`: remove Codex output-token configuration [#010-canary57-remove-codex-output-token-configuration]

ChatGPT subscription Codex rejects `max_output_tokens`. Stop passing `maxOutputTokens` to
`makeOpenAiCodexProviderLayer` and `toOpenAiCodexRequestBody`; the optional deprecated field remains
accepted but is ignored for compatibility. Keep host-owned input/context budgeting separate from
provider output configuration.

### `0.1.0-canary.55`: rename task delegation to subagent [#010-canary55-rename-task-delegation-to-subagent]

The model-facing `task` delegation tool is now named `subagent` to distinguish isolated child-agent
runs from durable application tasks. Update tool-name checks and replace the public tools helpers:

| Previous                         | Replacement                            |
| -------------------------------- | -------------------------------------- |
| `makeTaskToolModule`             | `makeSubagentToolModule`               |
| `makeNonRecursiveTaskToolModule` | `makeNonRecursiveSubagentToolModule`   |
| `makeTaskToolDef`                | `makeSubagentToolDef`                  |
| `makeTaskToolRegistration`       | `makeSubagentToolRegistration`         |
| `makeTaskToolResult`             | `makeSubagentToolResult`               |
| `formatTaskResult`               | `formatSubagentResult`                 |
| `taskToolName`                   | `subagentToolName`                     |
| `taskSubagentRunId`              | `subagentToolRunId`                    |
| `Task*` public types             | corresponding `Subagent*` public types |

The old names are removed rather than aliased. Hosts must expose `subagent`, omit it from child
agent toolsets, and update UI/tool-call matching from `task` to `subagent`.

### `0.1.0-canary.52`: Codex omits the unsupported output limit [#010-canary52-codex-omits-the-unsupported-output-limit]

ChatGPT subscription Codex requests no longer send `max_output_tokens` because the endpoint rejects
that field. In that historical canary, `OpenAiCodexProviderConfig.maxOutputTokens` remained required
host configuration but was not serialized. Since `0.1.0-canary.57`, it is optional, deprecated,
and ignored; remove it from Codex provider construction.

### `0.1.0-canary.48`: required provider output limits [#010-canary48-required-provider-output-limits]

Provider constructors no longer infer output-token limits or apply hidden fallbacks. Supply the
required field for the selected adapter:

| Provider config                 | Required output-limit field | Previous behavior                               |
| ------------------------------- | --------------------------- | ----------------------------------------------- |
| `OpenAiProviderConfig`          | `maxCompletionTokens`       | defaulted to `4096`                             |
| `OpenAiCodexProviderConfig`     | `maxOutputTokens`           | historically required but omitted from requests |
| `AnthropicClaudeProviderConfig` | `maxTokens`                 | defaulted to `8192`                             |

In that canary, the public `toOpenAiRequestBody`, `toOpenAiCodexRequestBody`, and
`toAnthropicClaudeRequestBody` lowerers also required their limit configuration. Since
`0.1.0-canary.57`, the Codex compatibility config is optional; OpenAI API and Anthropic lowerers still require their
host-owned output limits. The env-backed
`OpenAiProviderLayer` now requires integer `OPENAI_MAX_COMPLETION_TOKENS` alongside
`OPENAI_API_KEY`. Keep these values in host-owned model configuration.

### `0.1.0-canary.47`: Claude output limits [#010-canary47-claude-output-limits]

Anthropic Claude turns that stop at `max_tokens` now fail as non-retryable `invalid_response`
instead of reporting normal completion. Stream consumers may observe partial text, but no normal
`Done` follows. Increase `maxTokens`, request shorter output, or adjust host output policy.

### `0.1.0-canary.46`: Anthropic context overflow [#010-canary46-anthropic-context-overflow]

Anthropic prompt-too-long responses now classify as non-retryable `context_overflow`. Generic loop
retry does not retry them. Hosts with compaction can use `makeContextOverflowRetryProvider` to
compact and retry once.

### `0.1.0-canary.46`: normalized Gmail threads [#010-canary46-normalized-gmail-threads]

`gmail.get_thread` no longer accepts only `{ threadId }` or returns Gmail's raw thread wire payload.
Use this fragment to pass an explicit format:

```ts
import { GmailGetThreadInput } from '@yolk-sdk/connectors/google'

const input = GmailGetThreadInput.make({
  threadId: hostGmailThreadId,
  format: 'full'
})
```

Allowed formats are `full`, `metadata`, and `minimal`; use `full` when decoded bodies are required.
Read normalized `messages[].body`, `bodyMimeType`, `headers`, and `attachments` instead of Gmail
`payload`, MIME parts, or `body.data`. Thread output contains attachment metadata only. When
`attachmentId` exists, fetch content through `gmail.get_attachment` with the parent message `id` as
`messageId`. Gmail inline attachments may omit `attachmentId`; their content is intentionally absent
from normalized thread output and cannot be fetched through that action.

## Upgrade checklist [#upgrade-checklist]

1. Update all `@yolk-sdk/*` dependencies together.
2. Run typecheck and tests in your host app.
3. Search for changed subpath imports.
4. Re-run one agent loop with the fake provider.
5. Re-run one real provider smoke test.
6. Re-run one tool call, one HITL pause/resume, and one stream reconnect path if your app uses them.
7. Re-check connector credentials and OAuth scopes if connector packages changed.
8. Re-check sandbox lifecycle and Workflow terminal-event ordering if platform packages changed.

## What can break during canary [#what-can-break-during-canary]

| Area         | Watch for                                                            |
| ------------ | -------------------------------------------------------------------- |
| Protocol     | event names, message fields, terminal state, tool/HITL payloads      |
| Loop/runtime | required Effect services, runtime request shapes, stream semantics   |
| Client/React | projection state, transport headers, resume helpers                  |
| Providers    | auth config, model capabilities, output limits, usage/error metadata |
| Tools        | registration metadata, access levels, approval semantics             |
| MCP          | remote/local config, result adaptation, HTTPS policy                 |
| Knowledge    | store contracts, search request shape, agent tool options            |
| Connectors   | action ids, input/output schemas, credential slots, config keys      |
| Sandbox      | lifecycle defaults, command result shape, provider adapter options   |
| Workflows    | callback contracts, terminal status, retry/default behavior          |
| Harness      | drain/token contracts, claim vs Inbox persistence, recovery budgets  |

## Safe migration pattern [#safe-migration-pattern]

Create one compatibility boundary in your app for each package area:

| Boundary              | Owns                                                      |
| --------------------- | --------------------------------------------------------- |
| Agent runtime adapter | provider layer, loop config, enabled tools, stream format |
| Tool catalog          | app-owned tools, connector tools, MCP tools, approvals    |
| Persistence adapter   | transcript/session event store and replay repair          |
| Credential adapter    | OAuth/API token resolution and refresh                    |
| UI adapter            | event projection, retry display, HITL controls            |

Then most package changes affect one adapter instead of the entire app.

## Stable import habit [#stable-import-habit]

Use public subpaths only:

```ts
import { runRuntime } from '@yolk-sdk/agent/runtime'
import { listRemoteMcpServerTools } from '@yolk-sdk/mcp/client'
import { GoogleConnector } from '@yolk-sdk/connectors/google'
```

Avoid root imports for feature APIs and never import from package `src/*` internals.

## Before filing an issue [#before-filing-an-issue]

Include:

* exact package versions
* Node version
* runtime environment
* relevant public subpath imports
* minimal reproduction using `FauxProvider` when possible
* terminal `AgentError` or typed provider/tool error metadata


---

# Quickstart

URL: /docs/quickstart

Run a complete Yolk agent loop with a typed tool and fake provider.



This guide runs one complete agent turn locally: user message → model tool call → host tool execution → final assistant message.

It uses the fake provider, so you do not need provider credentials yet.

## Install [#install]

```bash
pnpm add @yolk-sdk/agent@canary effect@4.2.0
```

## Create `index.ts` [#create-indexts]

```ts
import { Effect, Layer, Stream } from 'effect'
import * as Schema from 'effect/Schema'
import { ContextTransformer, LoopConfig, run } from '@yolk-sdk/agent/loop'
import { FauxProvider, Reply } from '@yolk-sdk/agent/loop/testing'
import { assistantContent, UserMessage } from '@yolk-sdk/agent/protocol'
import { makeTool, makeToolExecutorLayer, resolveTools } from '@yolk-sdk/agent/tools'

const WeatherParams = Schema.Struct({
  city: Schema.String
})

const Weather = Schema.Struct({
  city: Schema.String,
  condition: Schema.String
})

const weatherTool = makeTool({
  name: 'get_weather',
  description: 'Get the current weather for a city.',
  parameters: WeatherParams,
  output: Weather,
  access: 'read',
  // Optional: what the model reads. Without it, the compact JSON of the output.
  render: weather => `Weather in ${weather.city}: ${weather.condition}`,
  execute: ({ params }) => Effect.succeed({ output: { city: params.city, condition: 'sunny' } })
})

const toolSet = await Effect.runPromise(resolveTools([{ id: 'weather', tools: [weatherTool] }], {}))

const AppAgentLayer = Layer.mergeAll(
  FauxProvider.layer(
    Reply.toolCall({
      id: 'call_weather_1',
      name: 'get_weather',
      params: { city: 'Barcelona' }
    }),
    Reply.text('It is sunny in Barcelona.')
  ),
  makeToolExecutorLayer(toolSet),
  LoopConfig.defaultLayer,
  ContextTransformer.identity
)

const events = Array.from(
  await Effect.runPromise(
    run({
      messages: [UserMessage.make({ content: 'What is the weather in Barcelona?' })],
      systemPrompt: 'Use tools when useful. Be concise.',
      tools: toolSet.tools,
      model: 'test-model'
    }).pipe(Stream.runCollect, Effect.provide(AppAgentLayer))
  )
)

console.log(events.map(event => event._tag).join(' -> '))

const assistant = events.find(event => event._tag === 'AssistantMessage')

if (assistant !== undefined) {
  console.log(assistantContent(assistant.message))
}
```

## Run it [#run-it]

```bash
pnpm dlx tsx index.ts
```

You should see an event sequence ending in `AgentEnd`, plus the assistant answer:

```txt
AgentStart -> TurnStart -> ... -> ToolExecutionCompleted -> ... -> AgentEnd
It is sunny in Barcelona.
```

## What happened [#what-happened]

1. `makeTool` built a schema-backed tool definition and executor; its typed `output` is encoded
   into the result (`render` turns it into the text the model reads).
2. `resolveTools` produced the model-visible `ToolDef` list and host executor.
3. `FauxProvider` simulated a model calling `get_weather`, then answering.
4. `run` streamed protocol events for model output, tool execution, assistant messages, and terminal state.

## Move to your host app [#move-to-your-host-app]

In a real app you replace only the boundaries:

| Boundary      | Replace fake quickstart part with                                                                                                                                |
| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Provider      | `makeOpenAiProviderLayer`, `makeVercelAiGatewayProviderLayer`, `makeOpenAiCodexProviderLayer`, `makeAnthropicClaudeProviderLayer`, or `makeXAiGrokProviderLayer` |
| Tool executor | app-owned tools, connector tools, MCP tools, knowledge search, sandbox tool                                                                                      |
| Transport     | Next route, Worker, Durable Object, CLI, or Workflow stream                                                                                                      |
| Storage       | database/session event log owned by your app                                                                                                                     |
| UI            | React client helpers or app-owned chat state                                                                                                                     |

## Runtime choices [#runtime-choices]

| API                             | Use for                                                          |
| ------------------------------- | ---------------------------------------------------------------- |
| `run`                           | unit tests, direct loop control, custom runtimes                 |
| `runRuntime` with `Transcript`  | stateless HTTP route where client sends the transcript           |
| `runRuntime` with `AppendInput` | durable session log, Worker/Durable Object, database-backed chat |
| `@yolk-sdk/vercel-workflows`    | long-lived Vercel Workflow runs                                  |

Next steps:

* [Build a chat route](./guides/build-chat-route)
* [Add a tool](./guides/add-tool)
* [Choose a model provider](./integrations/model-providers)


---

# Troubleshooting

URL: /docs/troubleshooting

Common setup, runtime, streaming, provider, MCP, sandbox, and workflow failures.



Use this page when a guide compiles but the app does not behave as expected.

## Package and module errors [#package-and-module-errors]

### Cannot find an export [#cannot-find-an-export]

Check that all `@yolk-sdk/*` packages use the same canary version:

```bash
pnpm list '@yolk-sdk/*'
```

Yolk packages release in lockstep. Do not mix canary versions.

Also check that `effect` and the coordinated `@effect/*` runtime packages match the version the
canary expects (`pnpm list effect`): canary.97 to canary.115 use `effect@4.0.0`, which removed the
`effect/unstable/*` entrypoints, canary.116 to canary.123 use `effect@4.0.5`, canary.124 to canary.138 use `effect@4.1.2`, canary.139 to canary.154 use `effect@4.1.4`, canary.155 to canary.166 use `effect@4.1.5`, canary.167 to canary.177 use `effect@4.1.7`, and canary.178 and later require `effect` \~4.2.0 (tested on 4.2.0) as a peer dependency. Import from
`effect/http`, `effect/process`, and the other `effect/<area>` paths; see
[Migration](./migration#canary97-effect-400).

### Node or ESM errors [#node-or-esm-errors]

Yolk packages are ESM-first and require Node 22 or newer. `@yolk-sdk/codemode` requires Node
22.19 or newer.

Use explicit public subpaths:

```ts
import { run } from '@yolk-sdk/agent/loop'
import { makeTool } from '@yolk-sdk/agent/tools'
```

Do not import package-internal `src/*` files from an app.

## Effect layer errors [#effect-layer-errors]

### Missing service [#missing-service]

Most runtime failures that mention a missing service mean an Effect layer was not provided.

| Missing service      | Provide                                                 |
| -------------------- | ------------------------------------------------------- |
| `LLMProvider`        | model provider layer or `FauxProvider.layer(...)`       |
| `ToolExecutor`       | `makeToolExecutorLayer(toolSet)` or host executor layer |
| `LoopConfig`         | `LoopConfig.defaultLayer` or custom loop config         |
| `ContextTransformer` | `ContextTransformer.identity` or compaction layer       |
| `HttpClient`         | `FetchHttpClient.layer` or host HTTP layer              |
| `ClassifierModel`    | `VercelAiGatewayClassifierLayer` or a host classifier   |

Build one app-level layer and provide it at the route/runtime boundary.

## Provider errors [#provider-errors]

### Missing OpenAI provider environment configuration [#missing-openai-provider-environment-configuration]

`OpenAiProviderLayer` reads `OPENAI_API_KEY` and `OPENAI_MAX_COMPLETION_TOKENS` through Effect Config.
The output limit must parse as an integer. If you do not want env config, use
`makeOpenAiProviderLayer({ apiKey, maxCompletionTokens })` and provide an HTTP layer.

### Missing Vercel AI Gateway environment configuration [#missing-vercel-ai-gateway-environment-configuration]

`VercelAiGatewayProviderLayer` reads `AI_GATEWAY_API_KEY`, falling back to `VERCEL_OIDC_TOKEN`, and
requires integer `AI_GATEWAY_MAX_COMPLETION_TOKENS`. If you configure the layer explicitly, pass the
selected credential as `apiKey` to `makeVercelAiGatewayProviderLayer`; model ids must use Gateway's
opaque `provider/model` form.

`VercelAiGatewayClassifierLayer` reads only the credential (`AI_GATEWAY_API_KEY`, falling back to
`VERCEL_OIDC_TOKEN`); it does not need `AI_GATEWAY_MAX_COMPLETION_TOKENS`. A missing credential
fails with `ClassificationProviderError` (kind `auth`).

### Diagnose provider failures with providerCode [#diagnose-provider-failures-with-providercode]

Chat Completions and Responses HTTP failures copy the envelope string `code` (falling back to
`type`) into `LLMError.provider.providerCode`, alongside status and kind. Codes may be absent, and
raw upstream bodies stay out of typed failures: diagnose from `providerCode`, status, and kind
rather than logging raw response bodies.

Claude subscription (`anthropic_claude`) HTTP and stream errors report the more specific
`error.details.error_code` when present, then `error.type`, then `error.code`. Native Messages HTTP
errors (OpenCode Go `protocol: 'messages'`) follow the same rule, so an unknown model reports
`providerCode: 'not_found_error'`.

Retryability follows the structured fields: a provider code that names a failure (for example
`rate_limit_error` or `overloaded_error`), then the HTTP status (429, 408, 5xx, and 529
retry; other 4xx do not). Upstream message text only refines that, and request values the upstream echoes back,
such as the model id, are ignored, so a model id containing "overload" never makes a 404 retryable.
Stream error events (Chat Completions error envelopes, Responses `error` / `response.failed`,
Claude and Messages `error`) carry no status, so their text decides when their code names no failure; the requested model id is removed
from that text too, so it never makes an in-stream error retryable.

### Claude rejects a model with claude\_code\_version\_too\_old [#claude-rejects-a-model-with-claude_code_version_too_old]

Anthropic gates newer models by the Claude Code version the Claude subscription transport reports.
An HTTP 400 with `providerCode: 'claude_code_version_too_old'` means the installed
`@yolk-sdk/agent` reports a version that model does not accept yet: upgrade to the latest canary, or
pick an older model until a release supports it.

### Diagnose chat stream failures with stream diagnostics [#diagnose-chat-stream-failures-with-stream-diagnostics]

OpenAI-compatible chat streaming expects server-sent events. When a 2xx response declares an
explicit non-SSE `Content-Type` (JSON or HTML), the provider fails before consuming the body with
`invalid_response` and `providerCode: 'unexpected_content_type'` (non-retryable, safe numeric status
attached). A missing `Content-Type` keeps the existing lenient SSE parsing.

Chat stream failures (`unexpected_content_type`, `incomplete_stream`, and streamed
`openAiChatResponseIssues` parser rejections) carry optional `provider.stream` diagnostics
(`ProviderStreamDiagnostics`) that survive provider sanitization and wire serialization:

| Field            | Meaning                                                                        |
| ---------------- | ------------------------------------------------------------------------------ |
| `protocol`       | Provider wire protocol; these chat diagnostics report `chat-completions`       |
| `responseFormat` | Coarse declared content type (`sse`, `json`, `other`, `unknown` for no header) |
| `receivedBytes`  | Bytes received from HTTP body chunks before text decoding                      |
| `bufferedChars`  | Undelivered SSE tail characters, counted in UTF-16 code units                  |
| `outputStarted`  | Whether text or reasoning output was actually emitted to the consumer          |
| `terminalSeen`   | Whether a terminal frame (`[DONE]` or a processed finish reason) was observed  |
| `invalidField`   | On `invalid_stream_chunk`: first rejected field `path` and its JSON `received` |

`invalidField.path` uses the provider schema's own field names with `[]` for any array item (for
example `$.choices[].delta.tool_calls[].id`), and `received` is the JSON type found there
(`missing`, `null`, `boolean`, `number`, `string`, `array`, or `object`), never the value. The chat
parser already reads `null` in every optional chunk field as absent (OpenAI-compatible hosts send
`"tool_calls": null` or `"id": null` on continuation deltas), so an `invalidField` names a real shape
mismatch. An omitted `choices` is accepted (usage-only chunks), but `choices: null` stays a
rejection: it is not a chat chunk (often an error in another shape) and must not read as an empty one.

Diagnostics carry counters and milestones only: no transcript bytes, raw header values, or body
fragments are retained. Streams that end without a terminal frame fail `incomplete_stream`
(non-retryable) even when output already started, and the SDK never synthesizes success or a
retry for a missing terminal.

### Provider returned a tool call with an empty name [#provider-returned-a-tool-call-with-an-empty-name]

A model or endpoint sometimes returns a tool call whose `id` or `name` is empty or padded. Providers
fail the request with a typed non-retryable `LLMError` (`invalid_response`); on Chat Completions it
carries `providerCode: 'invalid_tool_call'`. The call never reaches your tools. Surface it like other
provider failures: a host fallback model can retry the turn, and repeated failures point at the
model or endpoint. See [provider errors](./api-reference/agent#providers).

### OAuth provider returns unauthorized [#oauth-provider-returns-unauthorized]

Codex, Claude, and Grok provider layers need a fresh `OAuthAccessToken`. Your host owns token storage,
refresh, broker routes, account linking, and audit.

For Grok subscriptions, send the token to the default xAI CLI proxy, not `api.x.ai`. A custom
`responsesUrl` must be a trusted proxy because it receives the bearer. Browser PKCE requires xAI's
fixed loopback callback. The SDK exports device-flow constants but the host must implement initiation
and polling when it cannot listen there. Coalesce concurrent refreshes and persist a rotated refresh
token atomically. The provider rejects mismatched or expired access-token envelopes before HTTP.
The CLI proxy is a private, unsupported surface that may change; use it only when permitted by xAI's
terms.

### Grok allowance returns HTTP 412 [#grok-allowance-returns-http-412]

The private Grok billing endpoint may return `412` for team or organization principals without a
personal team even while model requests still work. Treat the sanitized usage error as allowance
unavailable; do not classify it as token expiry or expose the raw response body. The host owns any
principal-specific fallback or UI message.

### Media input rejected [#media-input-rejected]

Set model capabilities to match the provider/model. The loop rejects unsupported image, document, or audio parts before provider execution.

Capabilities do not resolve private sources or convert unsupported media. Codex/Claude reject
unresolved image/document refs and audio tool results; their assistant text lowering still rejects
media even after resolution. Resolve refs in a request-local copy inside each provider attempt,
including overflow retry. See [Resolve private attachments](./guides/private-attachments) for
retry composition and provider limitations.

For generic OpenAI chat, native PDF user-message parts require `supportsPdfAttachments: true`;
Gateway enables them by default and accepts `false` to disable them. URL-backed PDFs are fetched and
buffered by the host's `HttpClient`, not by Gateway. If fetch or read fails, verify the source URL is
authorized and reachable through a bounded transport that controls redirects, credentials, byte
limits, timeouts, and logs, or provide validated inline bytes instead. The SDK does not add those
network guarantees.

### Anthropic context is too long [#anthropic-context-is-too-long]

Anthropic prompt-too-long responses become non-retryable `context_overflow` failures. Generic loop
retry does not retry them. Compact before provider execution, or use
`makeContextOverflowRetryProvider` to run your host compactor and retry once.

### Claude reaches `max_tokens` [#claude-reaches-max_tokens]

Claude output-limit stops fail as non-retryable `invalid_response` instead of normal completion. A
stream may already have emitted partial text, but it will not emit normal `Done`. Increase
`maxTokens`, request shorter output, or adjust host output policy before retrying.

### Claude thinking ended without a signature [#claude-thinking-ended-without-a-signature]

The Claude provider fails a turn as non-retryable `invalid_response` when a thinking block ends
without the signature its replay needs (a `max_tokens` or `content_filter` stop is reported first).
Anthropic always signs thinking, so look for a proxy that rewrites the stream.

## Tool errors [#tool-errors]

### Tool is not configured [#tool-is-not-configured]

The model called a tool name not present in the resolved tool set. Resolve tools server-side and pass the same `toolSet.tools` and `toolSet.execute` into the run.

### Tool input validation failed [#tool-input-validation-failed]

`makeTool` validates model input with Effect Schema. Return model-visible validation errors for recoverable cases. Keep thrown `ToolError`s safe and non-secret.

Unknown keys are rejected at any depth, for example
`Unknown argument "x". Allowed arguments: a, b.` Remove extra keys from callers, fixtures, and code
mode scripts. A number or boolean the model sent as a JSON string is rejected with the string and
the literal to send (`Argument "offset" must be a JSON number, but it was the string "120": send 120
without quotes.`); some models quote numbers inside union-shaped parameters. `null` on a
`Schema.optional(X)` field is accepted as omitted, but required fields still reject it. Custom `invalidParamsMessage` callbacks can keep the hint with
`withToolArgumentsErrorHint(message, error)` from `@yolk-sdk/agent/tools`.

In code mode, a call whose arguments JSON would change (`NaN`, invalid `Date`s, `Map`, class
instances) rejects before it runs, for example
`tools.search: argument at limit is NaN; pass a finite number or omit the key`.

### Typed input is unavailable or stays pending [#typed-input-is-unavailable-or-stays-pending]

Pass `toolSet.inputs` from `resolveTools` alongside `toolSet.tools` into loop/runtime configuration
and `prepareToolBatch`. Display-only `ToolDef.input` metadata cannot validate a response; omitted
handlers produce unavailable results without prompting or executing.

Use `makeInputTool` to retain original call/response validators. `input_validation_required` means
an input registration lacks required validation; `input_unsupported_policy` means it combines input
with unsupported approval/background policy. Inputs collect data, not action authorization.

Invalid response data re-pends the same request without validation details in events. Keep the
form open, correct the payload, and resubmit with the same opaque request/call ids. Do not project
an optimistic accepted result; only the first valid submission or cancellation settles the request.
See [Collect typed input](./agent/tools-hitl#collect-typed-input).

### Action-backed interaction is unavailable or reappears [#action-backed-interaction-is-unavailable-or-reappears]

Pass `interactionHost` to `resolveTools`, then both `toolSet.interactions` and
`toolSet.interactionHost` to loop/runtime configuration. Configuring only the executor does not let
the loop load accepted receipts. Durable preflight must call `loadInteractionReceipts` and pass
fresh `interactionReceipts` to `prepareToolBatch`; missing host wiring never grants execution.

The host must authenticate and atomically accept the response before SDK resume. Keep invalid
submissions editable; local submission and `InteractionSubmitted` are not completion. Voice/realtime
and background activation do not support these tools.

An `unknown` outcome means the action may have happened. Reconcile using the authoritative receipt
and provider state; never automatically retry the action or overwrite its settled receipt.
See [Authorize one action](./agent/tools-hitl#authorize-one-action).

### Code mode tool resolution fails [#code-mode-tool-resolution-fails]

`resolveTools` fails with `ToolRegistryError` before any tool runs when the exposure is invalid:

* `invalid_tool_exposure`: a tool sets `discovery` without `callableBy: 'codemode'`.
* `codemode_unsupported_tool`: a tool marked `callableBy: 'codemode'` needs approval, input, an
  interaction, or background activation, is `question` or `subagent`, or has `nestedToolAccess`.
  These tools never run from code mode; use `callableBy: 'all'` or `'model'`.

A logged warning, `Code-mode-only tools are unreachable from model turns without a nested tool
access registration`, means you marked tools `callableBy: 'codemode'` but did not register the code
mode tool (or another `nestedToolAccess` registration) in the same resolution. Scripts you run
yourself through `ResolvedToolSet.nestedExecutor` still reach them; ignore the warning for
resolutions used only for those. See
[Choose what scripts can call](./integrations/code-mode#choose-what-scripts-can-call).

Staged tool plans add three causes:

* `staging_unsupported_policy`: a tool sets `staging` without `approval`, or combines it with
  input, an interaction, background execution, nested tool access, or `callableBy: 'model'`.
* `staging_validation_required`: a raw stageable registration has no side-effect-free `validate`.
* `plan_review_duplicate`: more than one `makePlanReviewTool` registration resolves.

Tool change previews add one cause:

* `change_preview_unsupported_policy`: a tool sets `changePreview` without `approval`.

Typed tool results add one cause:

* `output_validation_required`: a registration sets `def.outputSchema` without `decodeOutput`.
  `makeTool` with `output` sets it; raw registrations pass `toolOutputDecoder(schema)`, MCP
  registrations `mcpToolOutputDecoder`, and wrappers that rebuild a registration field by field
  must forward it. See [Typed outputs and file fields](./agent/tools-hitl#typed-outputs-and-file-fields).

### `stage` is not defined, or `review_plan` is unavailable [#stage-is-not-defined-or-review_plan-is-unavailable]

Scripts get `stage(name, args)`, and the review tool becomes available, only when the resolution
has `plans`, an `interactionHost`, and exactly one plan review tool, and the code mode tool does
not set `staging: false`. Voice and subagent resolutions without them never get it.

A plan store outage is never reported as invalid input: `prepareToolBatch` fails with `ToolError`
`unavailable` (retry the step) and admission answers `InteractionAdmissionError` `unavailable`. See
[Review a staged plan](./agent/tools-hitl#review-a-staged-plan).

### Code mode worker or `quickjs.wasm` not found [#code-mode-worker-or-quickjswasm-not-found]

The Node executor loads a worker file and `quickjs.wasm` from disk. When a bundler inlines the
engine, those files are missing at runtime. In Next.js, add `@yolk-sdk/codemode`,
`@earendil-works/pi-codemode`, and `quickjs-wasi` to `serverExternalPackages`, or pass `wasm` and
`workerUrl` to `makePiCodeModeExecutor`. See [Add code mode](./integrations/code-mode).

### Approval requests have no preview [#approval-requests-have-no-preview]

Pending `ToolApprovalRequest`s carry `preview` only when you pass
`approvalPreviews: toolSet.approvalPreviews` to `run`, `runToolBatch`, `prepareToolBatch`, or the
runtime config, and the tool has a `changePreview` hook. Voice approvals never compute previews.
When `previewError` is set instead, its `cause` says why: `failed` (the hook failed or the
arguments are invalid), `invalid` (not a `ToolChangePreview`), `too_large` (labels, target,
summary, warnings, or `blocked` alone exceed `maxBytes`), or `timeout`. Show the raw arguments in
that case. See [Preview the change](./agent/tools-hitl#preview-the-change).

### A file shows as "file not captured" or `FileUnavailable` [#a-file-shows-as-file-not-captured-or-fileunavailable]

A tool returned a file that was not stored or could not be verified: a `FileBytes` or `FileStored`
in a typed tool's `ToolFile` field (the script value holds
`FileUnavailable { unavailable, name, mimeType }`) or an untyped tool's `FilePart`. The model sees
`[file not captured (reason): name, mime]` instead of a `fileId`. The reason says why:

* `no file store`: pass `files: { store }` to `resolveTools` on that surface (MCP calls outside
  `resolveTools`: pass `fileCapture: makeToolFileCapture({ store })`).
* `too large`: the file is over `maxFileBytes` (default 100 MiB).
* `storage unavailable`: the store failed; check its logs.
* `storage timed out`: an interaction result's files were not stored within the bound before its
  receipt was settled.
* `invalid base64`: an MCP server or an untyped tool returned malformed bytes.
* `not found`: a `FileStored` names a file the store's scope does not hold (not written yet, a
  malformed `fileId`, or another scope's).
* `size mismatch`: a `FileStored`'s `size` differs from the stored file's; the write was cut or
  named the wrong file.

Typed file fields take `FileBytes` or `FileStored` only, never base64 strings or plain objects:
decode the bytes yourself (`base64ToBytes`) before returning them. File tools report a missing or
foreign `fileId` as not found. A `file_upload` that got no complete response has an unknown outcome:
check the destination before retrying. See [Move files between tools](./integrations/files).

### A script call rejects with `returned an invalid result` [#a-script-call-rejects-with-returned-an-invalid-result]

A code mode call of a typed tool rejects with `<label>: returned an invalid result` when the result
reaching the script has no value: the tool returned no `structuredContent`, or `resolveTools`
dropped a value that did not match the output schema (an excess property, a wrong type, or a value
that is not plain JSON). The model still saw the content. A warning naming only the tool (never
the value) is logged: fix the tool so its value matches its `output`, or return `{ output }` from
`makeTool` so Yolk encodes it. Scripts never fall back to text.

### Attachment tools return `{ value, files }` instead of base64 [#attachment-tools-return--value-files--instead-of-base64]

`gmail.get_attachment`, `outlook.get_attachment` and `email.get_attachment` used as agent tools
resolve to `{ value, files }`: `value` is the metadata output, `files` the attachment as a
`FileRef` (or `FileUnavailable`). Move it with the `@yolk-sdk/files` tools, or call
`connector.invoke` for the base64 output.

### Approval pauses forever [#approval-pauses-forever]

If a tool has manual approval, the loop emits `AgentAwaitingInput`. Your host must persist pending request ids and resume with matching HITL responses (Workflow hosts: match the named pause; see [HITL resume](./vercel-workflows/hitl-resume#name-the-pause-an-answer-is-for)).

## Streaming errors [#streaming-errors]

### Browser receives one big chunk [#browser-receives-one-big-chunk]

Disable buffering at your platform/proxy and use streaming-friendly headers.

Also confirm provider streaming configuration: generic OpenAI chat and Vercel AI Gateway default to one JSON body, so a
host expecting incremental events must set `streaming: true` against an endpoint that serves chat
SSE. Unterminated chat streams fail `invalid_response` (`incomplete_stream`) without `Done`; treat
them as failures, not quiet completion. Gateway's independent `reasoningContent: true` option
preserves compatible reasoning output and assistant replay; enabling streaming alone does not
retain reasoning. Replayed reasoning spends input tokens.

For NDJSON routes, use `content-type: application/x-ndjson` and avoid middleware that buffers responses.

### Client never completes [#client-never-completes]

Streams reach a logical client boundary after `AgentEnd`, `AgentError`, or `AgentAwaitingInput`. Use
`isTerminalAgentEvent` when writing custom consumers, but do not treat resumable
`AgentAwaitingInput` as a final Workflow close.

### Collector failed versus host-chosen recovery [#collector-failed-versus-host-chosen-recovery]

`collectModelTurn` returns a finalized `ModelTurnResult` or re-fails. `collectModelTurnAttempt`
keeps a partial `ModelTurnCollection` on typed `StreamFailed` or `SinkFailed`. An `onEvent` sink
error is not a model-recovery outcome. Defects, interrupts, and mixed Causes stay Causes rather than
those tags.

Kernel `responseIssue: 'missing_done'` is an incomplete stream, not automatic provider/tool replay.
Providers whose wire requires a terminal event set it too when the stream ends before any `Done`:
Claude and native Messages without `message_stop`, Grok and OpenCode Go `responses` without
`response.completed` (still `providerCode: 'incomplete_stream'`). Harness hosts then get `Continue`
(output started) or `RecoverFull` (none) instead of a failed run. Codex completes a stream cut
before `response.completed` (EOF compatibility) and recovers a final response with missing
`output`; see [OpenAI Codex](./integrations/model-providers#openai-codex).

`@yolk-sdk/harness/outcome` classifies one invocation after inner loop/provider retries. It does not
add an outer retry loop. Hosts that opt in choose whether to schedule another physical attempt. See
[Loop and runtime](./agent/loop-runtime#compose-the-loop-layer) and
[Harness composition](./vercel-workflows/harness-composition).

## MCP errors [#mcp-errors]

### Remote MCP URL rejected [#remote-mcp-url-rejected]

Remote MCP requires HTTPS by default. `http://localhost` is only for development policy.

### Local MCP fails in browser or edge runtime [#local-mcp-fails-in-browser-or-edge-runtime]

Stdio MCP is Node-only. Keep it behind `@yolk-sdk/mcp/client/node` and run it from a Node host.

### Tool result shape differs from agent results [#tool-result-shape-differs-from-agent-results]

Use the MCP client/server adapters so `isError` and supported content blocks are preserved. A successful call's `structuredContent` is `{ value, files }` (the server's `structuredContent` is `value`); blobs, images and audio are `files`, stored as `FileRef`s or `FileUnavailable`. See [Add MCP tools](./integrations/mcp-tools).

## Knowledge errors [#knowledge-errors]

### Search returns nothing [#search-returns-nothing]

Check search scope, document ids, chunk ingestion, embedding dimensions, and host permission filters.

### Ingestion compiles but fails at runtime [#ingestion-compiles-but-fails-at-runtime]

The package defines contracts. Your host must provide extraction, chunking, embedding, summarization, and `SearchIndexStore` layers. For file bytes, `FileKnowledgeExtractorLayer` from `@yolk-sdk/extractors/knowledge` provides extraction when given `FileExtractorLayer` from `@yolk-sdk/extractors/node`; see [Ingestion pipeline](./knowledge/ingestion-pipeline).

## Connector errors [#connector-errors]

### Credential binding missing [#credential-binding-missing]

Connector provider modules declare credential slots needed by their actions. Bind the slots required by your selected connector/actions to host credential refs with `makeCredentialBinding`.

### Provider request fails [#provider-request-fails]

Provide a `ConnectorHttpClient` layer. Preserve method, URL, headers, body, and content type exactly when adapting to your HTTP client.

### Generic email action fails before transport [#generic-email-action-fails-before-transport]

Provide `EmailClient` and `CredentialResolver` layers. Incoming actions require `incomingHost` plus
an `EmailIncomingCredentialSlot` binding; SMTP send requires `smtpHost` plus an
`EmailSmtpCredentialSlot` binding. The slots may point to the same credential ref, but one binding
does not silently satisfy the other. Both slots require `UsernamePasswordCredential`; use the
Google or Microsoft connector for their provider-specific OAuth flows.

Use only `none`, `starttls`, or `tls` for security and ports from `1` through `65535`. POP3 has no
folder or draft model, so omit `folder` for reads and configure IMAP for `email.create_draft`. When a
draft omits `folder`, the host adapter must discover a mailbox advertised with `\Drafts` by the IMAP
SPECIAL-USE extension and may fall back to `Drafts`; servers without UIDPLUS may save successfully
without returning `draftId`. SMTP `{ accepted: true }` means
the server accepted the submission; it does not prove delivery. Transport failures should remain
typed `ConnectorError`
effects, while expected server rejection should be returned by the host port as
`ActionResult.failure`.

### Generic email filters, batches, labels, flags, and moves fail [#generic-email-filters-batches-labels-flags-and-moves-fail]

`email.list_messages` with `isRead` or `isFlagged` requires IMAP and optional
`EmailClient.listMessagesFiltered`; it never falls back to legacy `listMessages`. POP3 filters fail
before credentials. A missing method is a typed validation error, and malformed successful list
output is rejected at the connector boundary.

Batch/delete actions require 1-100 unique nonempty `messageIds`; duplicate, empty, or oversized
inputs fail before credentials or host calls. Each action also needs its matching optional
`EmailClient.batch*` or `deletePermanently` method. Successful output must cover every requested ID
in `messageIds` order, use only `succeeded | failed | unknown | not_attempted`, include consistent
summary counts, and keep
error codes sanitized. Successful move-shaped results require destination `folder`; only
`movedMessageId` is optional. For permanent deletion, use UID-scoped deletion of exactly the
requested IDs; never blanket `EXPUNGE`. SDK success does not prove backup or retention erasure.

Gmail batch failures expose sanitized codes only (`invalid_request`, `unauthorized`, `forbidden`,
`not_found`, `conflict`, `precondition_failed`, `payload_too_large`, `locked`, `rate_limited`,
`provider_rejected`, `outcome_ambiguous`, `invalid_response`, `batch_stopped`): never provider
bodies or credentials. `unknown` means the mutation may have executed, so reconcile before
retrying; `not_attempted` means no request was sent. Outlook batch results use the same codes plus
`invalid_batch_response` (broken envelope correlation) and `prerequisite_failed` (a category read
failed, so no PATCH was sent). Later chunks stop after auth/permission rejection, throttling,
transport ambiguity, server failure, or broken correlation; already-established results are
preserved. Combining fresh `isRead`/`isFlagged` filters with an Outlook `nextLink` fails before
credentials: reuse the returned `nextLink` unchanged instead.

Label, flag, and move inputs are validated before any host call: `EmailImapKeyword` rejects
system flags such as `\Seen`, whitespace, control characters, and IMAP atom specials;
`email.modify_labels` requires at least one of `addLabels`/`removeLabels`;
`email.move` requires a `destinationFolder` that differs from the source folder. Hosts return
`ActionResult.failure` for keywords the server rejects (check `PERMANENTFLAGS` first) and for
missing destinations. A moved message gets a new destination UID, so omitted `messageId` means
re-list the destination rather than reusing the source UID. Hosts own partial-move
reconciliation. See [the generic-email catalog](./integrations/connectors#mark-readunread-and-move-tofrom-trash).

### Google Drive action is unauthorized or search is incomplete [#google-drive-action-is-unauthorized-or-search-is-incomplete]

All Google workloads share the `google.oauth` credential binding, but the resolved token still needs
the selected action's consent. Drive list/search/get request `drive.metadata.readonly`; folder
create, trash, and permanent delete request `drive.file`. The latter only covers files the app
created or that the user explicitly opened/shared with the app. Use Google Picker or equivalent
host-owned UX to grant per-file access. If the product must mutate arbitrary existing files, the
host owns broader restricted-scope consent, Google verification, storage/security requirements, and
authorization policy.

For shared-drive list/search, pass that shared drive's `driveId`. If output reports
`incompleteSearch: true`, narrow the search to one drive rather than assuming the page is complete.
Pass `nextPageToken` back unchanged as `pageToken`. Google still checks returned file
`capabilities`, ownership, shared-drive role, and administrator policy for destructive calls.

For a protected link-shared item, pass its returned `resourceKey` with get/trash/delete or
`parentResourceKey` with parent-scoped list/search/create. The connector sends
`X-Goog-Drive-Resource-Keys`; omitting the key can look like a permission failure even when the user
opened the item through Picker. Drive quota-related `403` reasons map to `google_rate_limited`
rather than re-consent errors; honor `retryAfterMs` when present.

The connector excludes trashed files unless `includeTrashed` is true. Prefer `drive.trash_file` for
reversible removal; `drive.delete_file` permanently bypasses trash. Upload/download is not in the
string/JSON HTTP port, so the host must transfer binary content separately.

### Dropbox download fails [#dropbox-download-fails]

Binary download is not a `dropbox.*` action and is never serialized by `makeConnectorToolModule`;
a missing download tool is expected. Use host-only `downloadDropboxFile` with a compliant
`ConnectorBinaryHttpClient` — do not reuse string `ConnectorHttpClient`. `credential_failed` means
the `dropbox.oauth` binding or its `files.content.read` slot could not be resolved; `unauthorized`
usually means the token lacks that scope (Dropbox reports `missing_scope`). `invalid_input` covers
share links, relative paths, control characters, and Dropbox `malformed_path`. `not_a_file` is a
folder; `not_downloadable` is a Paper or other export-only entry; `unexpected_redirect` means the
adapter returned a 3xx that the helper refuses to follow. `partial_content` covers incomplete or
ranged 200 responses and a body whose length differs from the served metadata `size`. Host-only writes use a separate port; see [Transfer connector files](./connectors/files).

### Gmail draft lines are hard-wrapped after sending [#gmail-draft-lines-are-hard-wrapped-after-sending]

Drafts from `gmail.draft_compose`, `gmail.draft_update`, and `gmail.draft_reply` before
`0.1.0-canary.102` were plain text only, which Gmail web opens in its plain-text composer and wraps
at about 70 columns when a person sends them. Upgrade, and write each paragraph of a `text` body as
one line (never wrap by hand). Recipients then see the HTML part unwrapped; the text/plain
alternative Gmail web regenerates on send is still wrapped at about 76 columns, as for any message
composed there. See [Gmail draft bodies](./integrations/connectors#gmail-draft-bodies).

### Gmail draft with attachments fails [#gmail-draft-with-attachments-fails]

A `validation_failed` error from `gmail.draft_compose`, `gmail.draft_update`, or
`gmail.draft_reply` with `underlying.reason: 'too_large'` means the decoded MIME exceeds 35 MiB and
nothing was written. More than 10 attachments or over 25 MiB decoded in total also fails
`validation_failed`, from input validation. A draft with attachments is one
`multipart/related` upload: a host HTTP adapter that re-encodes the string body or caps outgoing
bodies below about 35 MiB breaks it, so forward the body exactly as UTF-8. Against the Google
emulator, the draft media upload is not emulated and answers its unrecognised 400. See
[Gmail draft attachments](./integrations/connectors#gmail-draft-attachments).

### Gmail submission is unconfirmed or its send scope is rejected [#gmail-submission-is-unconfirmed-or-its-send-scope-is-rejected]

`gmail.send_message` forwards host-generated base64url MIME unchanged. Its input validation checks
encoding, not MIME structure, recipient correctness, or sender aliases. A `validation_failed` error
with `underlying.outcome: 'rejected'` and `reason: 'too_large'` means nothing was sent: keep decoded
MIME at or below 35 MiB. 7-bit MIME uses Gmail's multipart upload; 8-bit MIME keeps the JSON `raw`
request, so prefer quoted-printable/base64 parts for large messages. The host must construct and
review the message before dispatch. A valid success returns an accepted message ID, not delivery
confirmation. HTTP ambiguity, transport errors, or malformed success acknowledgements can follow
an actual send; do not automatically resend. Reconcile mailbox state first. Failure metadata uses
`underlying: { outcome: 'rejected' | 'unknown', retryable: false }` after a response, or the unknown
variant on after-dispatch typed errors; neither includes provider bodies or retry-delay hints.

The action's slot hints `gmail.send`, but Google also accepts `gmail.compose`, `gmail.modify`, or
`https://mail.google.com/`. The action inspects OAuth scope metadata, then re-resolves through a
slot for the existing sufficient grant; the host must still authorize that operation slot. Return
accurate scopes on `OAuthCredential` so compose-only credentials do not fall back to a literal send
hint. Bearer credentials or missing scope metadata use the send slot. Do not weaken unrelated
scope checks or add unnecessary consent. See [Gmail submission](./integrations/connectors#submit-a-reviewed-gmail-message).

### Microsoft action is unauthorized [#microsoft-action-is-unauthorized]

Microsoft Outlook and OneDrive actions call Microsoft Graph, so the token audience and consent must be for
Graph rather than the retired `outlook.office.com/api` endpoint. This applies to tokens only:
`addOutlookAttachment` session ranges go to Graph-issued, pre-authenticated
`outlook.office.com/api/.../AttachmentSessions(...)` URLs through `uploadSession`, without Authorization. Read actions need `Mail.Read`,
draft actions need `Mail.ReadWrite`, and send actions need the separate `Mail.Send` permission.
All action-scoped credential slots share the `microsoft.oauth` binding id.

An explicit `mailbox` equal to `OAuthCredential.accountId` (case-insensitive, no whitespace trimming)
keeps ordinary `Mail.*` scopes. If your own mailbox unexpectedly asks for Shared scopes, verify the
host populated `accountId` with the same Graph user ID or `userPrincipalName` form as `mailbox`;
missing identity, aliases, and ID-versus-principal-name mismatches do not qualify. Delegated
explicit-mailbox actions resolve the scope-free identity slot before the enforcing operation slot.

When `mailbox` targets another Exchange Online mailbox, delegated tokens need the corresponding
`Mail.Read.Shared`, `Mail.ReadWrite.Shared`, or `Mail.Send.Shared` permission. Reads and writes need
the relevant shared-folder or Full Access grant. Sending requires **Send As** or **Send on Behalf**;
the connector's `/users/{mailbox}` send path also requires Full Access. Microsoft Graph cannot list
which mailboxes the signed-in user may access, so the host must obtain and authorize the mailbox
identifier.

Application-token hosts set integration config `mailboxAccessMode` to `application` and must provide
`mailbox`. Grant the non-Shared application permission and apply mailbox scoping through host/admin
policy.

A successful send returns `{ accepted: true }` when Graph responds `202 Accepted`. This means Graph
accepted the submission; it does not prove processing or delivery. Honor `retryAfterMs` when a
provider failure maps a Graph `429` response only after establishing that retrying the operation is
safe. A retry delay is not a guarantee that the operation had no side effects.

For `outlook.create_reply_draft`, a post-create HTTP failure uses
`outlook_create_reply_draft_partial` and omits `retryAfterMs`, even for 429. Both these failures and
post-create typed `ConnectorError`s include
`underlying: { draftId, retryable: false, recovery: 'read_edit_existing_draft' }` once the draft ID
is known. Read and edit that draft using the original `mailbox` instead of invoking creation again:
a failed save response may follow a successful save. If the creation response was lost or no usable
ID was returned, reconcile mailbox state before another creation. See [reply draft recovery](./integrations/connectors#reply-drafts-and-recovery).

For `outlook.update_draft`, the body is a complete replacement, not a reply to prepend. Omitted
fields are unchanged and empty arrays clear recipient fields. After-dispatch HTTP failures use
`outlook_update_draft_failed`; typed failures also preserve the existing draft ID with
`retryable: false` and `recovery: 'read_edit_existing_draft'`. Read the original draft/mailbox
before any further edit or send. Update then send is not atomic, and the interaction host cannot
prevent another mailbox client from changing the provider draft between calls.

For `outlook.reply`, the reviewed recipients, subject, and complete body travel in a single send
request, so there is no intermediate mutable draft. Only HTTP 202 Accepted returns
`{ accepted: true }`; recognized rejections use `outlook_reply_rejected` and anything else
(including other 2xx statuses, redirects, 408, and 5xx) uses `outlook_reply_unknown`, both with
`underlying: { outcome: 'rejected' | 'unknown', retryable: false }` and no retry hints or provider
bodies. Typed after-dispatch failures carry the unknown variant. Acceptance means submission,
not delivery: reconcile mailbox state before considering another send.

For OneDrive, delegated reads and writes use `Files.Read` or `Files.ReadWrite` by default, including
an explicit `driveId` when those permissions cover the target. Set `oneDriveAccessMode` to
`delegated_all` when broader delegated access requires `Files.Read.All` or `Files.ReadWrite.All`.
Application-token hosts set it to `application` and must provide `driveId`; apply tenant/admin policy
to limit the app's accessible drives. Reusing an Outlook credential works only when its consent also
includes the required `Files.*` permission.

If OneDrive pagination is rejected, pass the full Graph `nextLink` unchanged and repeat `driveId`.
For `onedrive.list_items`, also repeat the original `parentItemId`. Binary download is not a
connector action and is never serialized by `makeConnectorToolModule`; a missing download tool is
expected. Use host-only `downloadOneDriveItem` with a compliant `ConnectorBinaryHttpClient` — do not
reuse string `ConnectorHttpClient`. `invalid_input` covers bad or dot-only IDs and application mode
without `driveId`. `credential_failed` means missing `microsoft.oauth` or the `Files.Read` /
`Files.Read.All` slot. Size and partial failures include `response_too_large` and `partial_content`;
do not trust metadata `size`. The adapter must disable auto-redirects; the helper strips headers
after the first content request. Host-only create/update are supported; see [Transfer connector files](./connectors/files).

### New file helper fails or a write outcome is uncertain [#new-file-helper-fails-or-a-write-outcome-is-uncertain]

New helpers use `ConnectorFileTransferError`, with code-only failures. `invalid_input` fails before
credentials/network; `response_too_large` means a host/provider byte bound was exceeded;
`upload_session_required` from other upload helpers means the file exceeds that provider's
single-request cap and no session flow is implemented. From `addOutlookAttachment` it means a file of 3 MiB or more
needs `ConnectorBinaryWriteHttpClient` with the optional `uploadSession` method; files under 3 MiB
do not. See [Attach a file to an Outlook draft](./connectors/files#attach-a-file-to-an-outlook-draft).
Never increase limits using model input. `not_downloadable` includes unsupported native exports,
folders, and item/reference mail attachments. Drive content needs drive.file or explicitly authorized
drive.readonly, not metadata-only consent. Notion external files require host URL policy.

`conflict` is not permission to retry without a revision/ETag. OneDrive simple replacement is
unconditional and requires explicit overwrite acknowledgement; decline when atomic CAS is required.
A transport timeout, cancellation or invalid success can follow a committed write: inspect provider
state and reconcile before another attempt. No helper retries writes automatically. Hosts must still
enforce streamed bounds, cancellation, DNS/socket policy, TLS and secret-safe telemetry.

## Sandbox errors [#sandbox-errors]

### Workspace resets unexpectedly [#workspace-resets-unexpectedly]

Disposable sandbox lifecycle can recreate stale or max-expired sessions. Treat `workspaceReset: true` as a signal to refresh app UI/state.

### Command cannot access a path [#command-cannot-access-a-path]

Sandbox `cwd` is workspace-relative. Absolute paths and `..` escapes are rejected.

### Command times out [#command-times-out]

Timeout is owned by Yolk. Long-running commands may be killed and returned as command-result data, not stream failure.

## Vercel Workflow errors [#vercel-workflow-errors]

### Background launch completes but child output is missing [#background-launch-completes-but-child-output-is-missing]

`makeSubagentAcceptedToolResult` acknowledges launch only. It intentionally adds no child usage or
`SubagentCompleted`. Choose a host-owned completion policy: deliver findings automatically or expose
authenticated observation tools and durable lookup. If observations use new tool-call ids, do not
complete the original launch twice. The SDK registers no status or wait tools.
See [Background subagents](./agent/tools-hitl#background-subagents).

### Child steps run inline or waiting never finishes [#child-steps-run-inline-or-waiting-never-finishes]

Do not put an entire child loop inside one parent `'use step'`: nested step calls execute inline.
Orchestrate an independent Workflow start outside that step. Use `awaitWorkflowChild` with short
read steps and Workflow `sleep`; treat failed/cancelled children as terminal values. The helper has
no built-in timeout, and independent children need explicit host Stop policy. Use the zero-based
read/sleep `attempt` indices for host observation budgets and capped backoff. At the ceiling,
return a truthful still-running or unknown value with a recovery handle; ending observation does
not terminate the child. Map nonterminal `subagent` results with the matching
[observation marker](./agent/tools-hitl#nonterminal-child-observations) to avoid false completion.
Also check `orchestrateWorkflowToolBatch` failures even when `ready: true`; it may return partial
progress. See [Bounded child observations](./vercel-workflows/step-contracts#bounded-child-observations).

### `Missing intrinsic getter: href` at import [#missing-intrinsic-getter-href-at-import]

`workflow` 5.x hardens serialization by capturing Node `URL` intrinsics when the module loads and
rejects jsdom's URL shape. Run any test whose import graph reaches the `workflow` package (any
entrypoint, including through `@yolk-sdk/vercel-workflows`) in a node vitest environment — add
`// @vitest-environment node` or exclude those suites from jsdom projects. `TestWorkflowWorld` loads
the same runtime when it executes a step, so under jsdom `runStep` fails with an error starting
"TestWorkflowWorld cannot load the workflow step-error serializer"; see
[Step errors](./vercel-workflows/testing#step-errors).

### A custom error class or field is lost across a step boundary [#a-custom-error-class-or-field-is-lost-across-a-step-boundary]

The platform stores a step's thrown value and the workflow body reads it back: error tags,
prototypes and custom fields are gone, and only `message`, `name`, `stack` and a serializable `cause`
survive. Carry what the workflow body must read as plain data in `cause`. A class instance anywhere in
the `cause` chain makes the error unstorable, and the step is redelivered until it exceeds its
retries; in tests, assert `world.inspect(runId).unstorableStepErrors` is empty. See
[Step errors](./vercel-workflows/testing#step-errors).

### Workflow build reports duplicate step ids [#workflow-build-reports-duplicate-step-ids]

Two `ws` versions can make the package manager install `@workflow/core` twice, once per peer
variant, and the Workflow build then sees each step twice. `@effect/platform-node` 4.2.0 requires
`ws` ^8.23.1; dedupe it, for example with a pnpm override `ws: ^8.23.1`.

### Deployed streams arrive in multi-second bursts [#deployed-streams-arrive-in-multi-second-bursts]

On `workflow` 4.x the hosted backend served durable streams only from `iad1`; deployments in other
regions paid a cross-region round trip per 10 ms write batch, with writer backpressure compounding
the delay. Upgrade to `workflow@^5.0.0-beta.42`: 5.x region-pins each run so storage, queuing, and
streams are served from the run's own region.

### Tool ran twice after a crash or redelivery [#tool-ran-twice-after-a-crash-or-redelivery]

The Workflow queue is at-least-once: a tool-batch step runs again after a crash, and sometimes
while its first execution is still running, even with `noWorkflowStepRetry`. Without a ledger,
every tool call in that step runs again. Pass a durable store with
`resolveTools(modules, context, { ledger: { store } })` inside the step, scoped to the run (plus the
turn or step if call ids can repeat). Input and interaction tools are never ledgered; they rely on
your `InteractionHost` receipts. See
[Ledger writes for re-executed steps](./agent/tools-hitl#ledger-writes-for-re-executed-steps).

### Ledgered call returns unavailable, conflict, or may already have been applied [#ledgered-call-returns-unavailable-conflict-or-may-already-have-been-applied]

* `ToolError` with reason `unavailable`: the store failed to claim or poll. The call fails closed
  and nothing runs. Check store connectivity, and keep store operations interruptible.
* Conflict: the same ledger key holds a different tool name or `argsDigest`, usually because a
  provider reused a call id within the scope. Add the turn or step to the scope.
* "May already have been applied": an earlier execution's lease expired without an outcome (a
  crash or a step stopped mid-call). The call never re-runs; verify the side effect before retrying.
* Timeout while waiting for an in-flight call: `maxWaitMs` (default 150 s) or `deadline` passed.
* A step overruns its budget after a call: recording the outcome can take about 15 s after
  `deadline`. Pass a `deadline` that leaves that finalization time before the platform stops the
  step.

Log `onLedgerDecision` to see which decision each call got.

### Duplicate or replayed events [#duplicate-or-replayed-events]

Durable clients should de-dupe by `eventId` when available and resume from the last known stream index.

### Stream fails on `LLMReasoningReplay` [#stream-fails-on-llmreasoningreplay]

An older SDK cannot decode the `LLMReasoningReplay` event that newer servers emit for Claude
thinking. Upgrade clients with servers, reload open tabs, and do not read newer durable logs with an
older SDK.

### HITL resume fails [#hitl-resume-fails]

Your host owns hook tokens, route auth, run ownership, and pending request matching. The package only carries serializable awaiting-input state.

An answer that `resumeHook` accepted but the run never used went to a hook that had already taken
another answer (a live hook accepts every payload and the workflow reads the first), or to the next
pause through a token several pauses share. Use one token per pause and record answers durably before
resuming ([HITL resume](./vercel-workflows/hitl-resume)).

An answer taken for the wrong pause (a late retry filling a later pause, or a new answer taken for a
retry of an old one) was matched by request id alone. Requests re-pend under the same id after an
invalid answer, and providers reuse call ids across turns. Have the client name the pause it
answers, the `eventId` of its `AgentAwaitingInput`, and match strictly by it
([Name the pause](./vercel-workflows/hitl-resume#name-the-pause-an-answer-is-for)).

`HookNotFoundError` means no hook is resumable under that token right now: the workflow has not
created it yet (a client faster than the replay after `AgentAwaitingInput`), the token is wrong, the
hook was disposed (its answer already used, possibly by an earlier attempt of the same resume), or
the run ended. While the stored pause is still pending, retry resuming the recorded answer a bounded
number of times; once the pause has moved on, report the recorded answer as delivered.

### Terminal event missing [#terminal-event-missing]

For `AgentEnd`, commit durable state, write the event, then let `closeStream` close. For
`AgentError`, `writeError` must write the safe event and close. Do not final-close after resumable
`AgentAwaitingInput`; release the writer lock and continue the same Workflow run after the hook
resolves.


---

# Classifier models

URL: /docs/agent/classifier-models

Ask typed questions about data and get calibrated probabilities instead of text.



Classifier models such as TypeSafe's Jev answer typed questions about one value with
probabilities. They do not chat or generate text. Use them for fast, typed decisions: route a
ticket, score urgency, or check whether a reply approves a result.

AI Gateway calls this capability **evaluation** (`POST /v1/evaluate`). Yolk calls it
**classification** everywhere (`classify`, `ClassifierModel`, `ClassificationResult`); the Gateway
provider maps the wire name.

Install:

```bash
pnpm add @yolk-sdk/agent@canary effect@4.2.0
```

## Subpaths [#subpaths]

| Subpath                                                  | Use for                                                                   |
| -------------------------------------------------------- | ------------------------------------------------------------------------- |
| `@yolk-sdk/agent/classification`                         | provider-neutral questions, answers, usage, errors, and `classify`        |
| `@yolk-sdk/agent/providers/vercel/ai-gateway-classifier` | `ClassifierModel` layer over AI Gateway `POST /v1/evaluate`               |
| `@yolk-sdk/agent/providers/vercel/conformance`           | classifier conformance cases and synthetic fixtures for replay tests      |
| `@yolk-sdk/emulators/gateway`                            | fixture-only `/v1/evaluate` route next to the Gateway chat emulator route |

## Classify [#classify]

A classification is one `state` (a string, JSON object, or JSON array; an array is one state, not a
batch) and named questions answered together. This fragment routes a ticket; `gatewayKey` is your
host-owned AI Gateway API key or Vercel OIDC token.

```ts
import { Effect, Redacted } from 'effect'
import { FetchHttpClient } from 'effect/http'
import { classify } from '@yolk-sdk/agent/classification'
import { makeVercelAiGatewayClassifierLayer } from '@yolk-sdk/agent/providers/vercel/ai-gateway-classifier'

const program = classify({
  state: { subject: 'Invoice question', body: 'I was charged twice.' },
  questions: {
    route: {
      type: 'choice',
      instructions: 'Which team should handle this ticket?',
      criteria: {
        billing: 'Payments and refunds.',
        bug: 'Product defects.',
        other: 'Anything else.'
      }
    },
    urgent: { type: 'boolean', instructions: 'Does the customer need an answer today?' }
  }
}).pipe(
  Effect.map(result => ({
    team: result.answers.route.choice, // 'billing' | 'bug' | 'other'
    urgent: result.answers.urgent.probability > 0.7,
    costUsd: result.usage?.costUsd
  })),
  Effect.provide(makeVercelAiGatewayClassifierLayer({ apiKey: Redacted.make(gatewayKey) })),
  Effect.provide(FetchHttpClient.layer)
)
```

`classify` types each answer from its question: a `choice` answer's `choice` is the union of that
question's option keys. `VercelAiGatewayClassifierLayer` reads the same credential as the Gateway
chat provider from the environment (`AI_GATEWAY_API_KEY`, falling back to `VERCEL_OIDC_TOKEN`) and
provides the Fetch `HttpClient`.

## Questions and answers [#questions-and-answers]

| Question  | `criteria`                                                          | Answer                                                     |
| --------- | ------------------------------------------------------------------- | ---------------------------------------------------------- |
| `boolean` | optional `{ true, false }` descriptions                             | `{ type: 'boolean', probability }` (probability of `true`) |
| `choice`  | option key to a description or JSON value (2 to 255 options)        | `{ type: 'choice', choice, probabilities, confidence? }`   |
| `score`   | ordinal levels, lowest first, as descriptions or JSON (2–10 levels) | `{ type: 'score', score, probabilities, confidence? }`     |

Probabilities are kept exactly as the provider returns them (Jev rounds to two decimals) and are
never renormalized. Every answer is checked against its question: a missing answer, an answer for
a question that was not asked, a type mismatch, a choice that names no option, or a probability or
confidence that is not a finite number in `[0, 1]` fails the classification.

`ClassificationResult` carries `model`, `answers` (keyed by question id), `usage`
(`inputTokens`, `outputTokens`, and `costUsd` when the provider reports a cost), and
`providerMetadata`.

## Errors [#errors]

Failures are typed errors in the Effect error channel, never result flags:

| Error                           | When                                                                                                |
| ------------------------------- | --------------------------------------------------------------------------------------------------- |
| `ClassificationRequestInvalid`  | the request breaks the contract (for example 256 options); nothing is sent                          |
| `ClassificationProviderError`   | the provider is unreachable or rejects the request; `provider` has the kind, status, and error code |
| `ClassificationResponseInvalid` | the response or an answer does not fit the request; `usage` is kept because the request was billed  |

Provider error messages are status-only (`Vercel AI Gateway returned 404`); they never carry the
provider's body or your credential.

## AI Gateway [#ai-gateway]

* Calls `POST https://ai-gateway.vercel.sh/v1/evaluate` with `typesafe-ai/jev` by default. Set
  `model` to choose another classifier model, and `baseUrl` only for a trusted proxy or a local
  emulator: the bearer credential is sent there.
* `providerOptions` passes through unchanged, so Gateway options such as
  `{ gateway: { zeroDataRetention: true, only: [...], models: [...] } }` reach the Gateway as you
  write them.
* `providerMetadata.gateway.cost` (US dollars) becomes `usage.costUsd`.
* Evaluation fallback response headers (`x-ai-gateway-evaluation-fallback-*`) are kept in
  `providerMetadata.evaluationFallbackHeaders`.
* `choice` and `score` confidence is read from the answer, or else from
  `providerMetadata.typesafe.confidence[questionId]`. The live Gateway sends both.
* Score levels are indexed from 0: `probabilities` keys run from `"0"` to `"n-1"` and `score` is
  the probability-weighted level index.
* 408, 429, 5xx, and transport failures are retried up to `maxRetries` times (default 2; `0`
  disables) with exponential backoff and full jitter (base 250 ms, cap 4 s), or after the
  response's `Retry-After` (seconds or an HTTP date, capped at 10 s). Other 4xx statuses and
  responses that fail to decode are never retried. Delays use the Effect `Clock`, so `TestClock`
  drives them in tests; interrupting the classification stops the retries. After the last attempt
  you get the same typed error a single attempt would give.

## Classify from code mode scripts [#classify-from-code-mode-scripts]

`makeClassifierTool` from `@yolk-sdk/codemode` exposes a `ClassifierModel` as a code-mode-only
`classify` tool, so one script can classify many items with per-script and per-process
concurrency caps. See
[Add code mode](../integrations/code-mode#classify-items-from-scripts).

## Policy stays in your host [#policy-stays-in-your-host]

Classification is a read with no side effects. A classifier can say a command looks destructive,
but your host policy decides whether it runs. Thresholds, model choice, credentials, and what to do
with each answer are host-owned.

## Testing [#testing]

The four classifier conformance cases (`vercelAiGatewayClassifierConformanceCases`: boolean,
choice, score, and the error envelope) need only an `HttpClient` and
`VercelAiGatewayClassifierConformanceConfig`. Replay them from
`vercelAiGatewayClassifierConformanceFixtures` with `ReplayHttpClient`, or run them against the
`@yolk-sdk/emulators/gateway` emulator, whose `emulator.evaluate` part answers the same synthetic
recordings. The fixtures are synthetic placeholders (`evidence: 'unverified'`) until an
owner-approved live probe records them.


---

# Client and React

URL: /docs/agent/client-react

Connect browser UI to an agent stream and render replay-safe chat state.



Use `@yolk-sdk/agent/client` for transport helpers and `@yolk-sdk/agent/react` for headless chat state.

## Stream events from an endpoint [#stream-events-from-an-endpoint]

```ts
import { Stream } from 'effect'
import { streamAgentEventStreamUntilTerminal } from '@yolk-sdk/agent/client'

const events = streamAgentEventStreamUntilTerminal({
  endpoint: '/api/agent',
  sessionId: 'browser-session',
  messages
})

for await (const event of Stream.toAsyncIterable(events)) {
  // update state, persist event, or project into UI
}
```

Use client helpers for:

* NDJSON event streams
* terminal-event detection
* durable run continuation headers
* HITL response submission
* abort/cancel flows
* typed error/retry state

Durable transports may replay events. Prefer event ids and projection helpers for reconnect-safe UI.

## Use React state [#use-react-state]

`@yolk-sdk/agent/react` exports `useAgentChat` and everything in `@yolk-sdk/agent/chat`, the same
chat projection without React (for another UI framework, or a fold on a server):

* `buildAgentChatItems`
* `applyAgentEventToChatProjection`, and `stepAgentChatProjection` for a host that folds status
  beside it; `stepAgentChatProjectionAll` folds a batch of events (the projection, the events status
  follows, and whether the message ids changed)
* the state's Effect Schemas, the types derived from them (each `…Schema` export, for example
  `AgentChatEventProjectionStateSchema`, plus `HitlPauses`); `Schema.toCodecJson` of one is its JSON
  form (`seenEventIds`, a persistent `HashSet`, as an array of ids)
* chat reducer and selectors
* tagged constructors: `AgentChatPart`, `ChatToolState`, `AgentChatItem`, `ToolRunState`,
  `DeleteChatTurnResult`, `EditChatUserMessageResult`, `RegenerateChatMessagesResult`,
  `AgentChatAction`, and hook results (`AgentChatSubmitResult`, `AgentChatDeleteTurnResult`,
  `AgentChatRegenerateResult`, `AgentChatEditUserMessageResult`, `AgentChatHitlResponseResult`)
* `ToolDurationKnown` / `ToolDurationUnknown` (`Schema.TaggedStruct`)

The tagged chat ADTs are `Data.taggedEnum` values (plain objects, `_tag` last, not Equal/Hash
classes). Build parts with `AgentChatPart.Text({ id, content, state })` rather than handwritten
`{ _tag: 'Text', ... }`. Omit absent optionals. Discriminate with `$is`, for example
`AgentChatSubmitResult.$is('Submitted')(result)`. `useAgentChat` dispatches `AgentChatAction`
constructors and returns the hook-result constructors. Duration descriptors use
`Schema.TaggedStruct.make`.

Client and chat state carry the run's `status` as an [`AgentStatus`](./status) plus `subagents`;
failures and pending retries are statuses (`Failed`, `Working(Retrying)`), not separate fields.

## Name the pause an answer is for [#name-the-pause-an-answer-is-for]

A durable host matches an answer to the pause that asked, not to its request id alone (requests
pend again after an invalid answer, and providers reuse call ids;
[HITL resume](../vercel-workflows/hitl-resume#name-the-pause-an-answer-is-for)). `useAgentChat`
remembers, per request id, the `eventId` of the latest `AgentAwaitingInput` that holds the request
(`state.hitlPauses`, from your transport's streams and from `applyEvent` replays; every pause counts,
seen or not, so a replay from an earlier index ends at the latest; stream order decides, so a
replay that stops partway or a late duplicate of an earlier pause leaves the earlier one, the
route refuses that answer, and a full replay recovers), and gives
an answer's transport request that pause as `request.pause` (absent when no such pause had an
`eventId`). A durable transport passes it on (fragment; the full transport is in
[HITL resume](../vercel-workflows/hitl-resume#name-the-pause-an-answer-is-for)):

```ts
const hitlResponse = request.hitlResponses?.[0]

if (hitlResponse !== undefined) {
  return Stream.toAsyncIterable(
    streamAgentRunHitlResponseEventStreamUntilTerminal({
      endpoint: runEndpoint,
      hitlResponses: [hitlResponse],
      pause: request.pause, // sent as `?pause=<eventId>` on the POST, never on tail reads
      signal: request.signal
    })
  )
}
```

The map belongs to one stream, like `seenEventIds`: a new message, an answer, a regeneration or an
edit starts afresh. Without React, keep a `HitlPauses` yourself with `rememberHitlPause` and
`hitlPauseFor` from `@yolk-sdk/agent/client`. The default transport (`streamAgentEventStream`)
ignores `pause`.

The package is headless. It does not ship Yolk UI components, styling, auth, uploads, or route handlers. Your UI owns the input box, message bubbles, attachments, voice controls, pending states, and errors.

## Replay-safe projection [#replay-safe-projection]

```ts
import {
  applyAgentEventToChatProjection,
  makeAgentChatEventProjectionState
} from '@yolk-sdk/agent/react'

const projection = events.reduce(
  (state, event) => applyAgentEventToChatProjection(state, event),
  makeAgentChatEventProjectionState()
)
```

Use append-only projection for durable logs. Use simpler message reducers only for ephemeral local streams.

A retried or redelivered model step streams a second answer for the same turn. Events from a
model call can carry `executionId` and `streamId` (its run); the chat projection, the `useAgentChat`
reducer and `reduceAgentEvents` route by them, per run and turn. When a newer execution of a turn
starts, the older one's output (streaming text, its assistant message, tool calls nothing acted on)
is removed and its later events are dropped; a start for an older turn, or after its run's
terminal event, is dropped.
At `AgentEnd` and `AgentAwaitingInput`, each turn in which a newer execution superseded an older one
shows the committed answer from the event's messages, with its tool calls' state; before that
event, a non-final turn whose older execution committed shows the newer one. A turn retried after a
user message and a client that connected mid-turn have
[limits](../vercel-workflows#emit-replay-safe-stream-events). A model event whose execution this
client never saw start but that names its turn (`executionTurn`) starts that turn first, as its
`LLMStreamStart` would have, keeping the draft. Hosts folding status beside the projection fold
`stepAgentChatProjection`'s `missedStart` before its `statusEvent`. Keep the projection's
`executions` and `turnStart` with its `seenEventIds`, and reset `executions` to `[]` per run if
events carry no `streamId`. Events without `executionId` only discard output still streaming at the
next `LLMStreamStart`.

Providers can reuse tool call ids across turns. The chat projection and the `useAgentChat` reducer
record where the latest model turn starts (`turnStart`), and a turn's tool events only match a
call after it, so a later turn's call never changes an earlier turn's call with the same id. A
replayed or late request or tool-batch event updates the earlier part holding the same call (send
the call as the model emitted it), and a replayed answer the part holding its request, also when
the latest turn holds another call reusing the id: a replay of an earlier turn's pause leaves a
later turn's pending card, and the status blocked on it, alone. An answer whose request no part
holds changes nothing when the call it reaches holds another request or already has its result (a
stale answer), and a denial answers only a pending approval (or a call holding no request);
`reduceAgentEvents` reads its runs the same way. A replayed request (or `AgentAwaitingInput`)
never reopens a call already answered, cancelled, denied or finished, and the `useAgentChat` reducer keeps its status when a replayed `AgentAwaitingInput`
names only such calls (a pause naming some blocks only on its pending requests); a host folding
status beside the projection gets the same answer from `stepAgentChatProjection`
([status](./status#from-live-events)). An invalid input answer re-pends a request that is still pending, and a
running call stopped by an abort is asked again when the next run resumes it. A replayed start of
the same call leaves a completed, accepted or errored call, and the status, alone. `AgentStart` and
a local submit (or answer, regenerate, edit) mark a run start, so a resumed run's tool batch,
which runs before the run's first model turn, acts on the paused call, or adds its own, never on an
earlier turn's call reusing its id. Before any start is seen, and in `applyAgentEventToChatMessages`, a tool event matches the last message
holding the call (answers and added results update only that one). `reduceAgentEvents` scopes its
tool runs the same way (`turnStart` on its state): a later turn's call reusing an id gets its own
run, also when the id was an accepted background call's, so `toolRuns` can hold one run per turn
for an id (the last is the latest). It follows the same request rule and status fence: a replayed
request leaves a run already answered, cancelled, denied or finished alone (a running call is asked
again), and a replayed pause blocks only on its pending requests.

## Rebuild from a snapshot [#rebuild-from-a-snapshot]

A host that keeps its own snapshot (stored messages, pending requests, accepted interaction
receipts) rebuilds chat state with `buildAgentChatMessages`. Its `toolRuns` can hold runs of
several turns for one call id (one per turn from `reduceAgentEvents`, or pending requests from
`toolRunsFromHitlRequests` beside an earlier turn's receipt), so each run goes to one card, later
runs first, each card taking at most one. A run holding a call (its own or its request's) takes the
last card holding the same call (id, name and arguments equal). A run holding no call (an input
still streaming, an answer or denial without its request) that answers an earlier run's request
takes that run's card (a later denial wins over the pending approval it denies), else the last card
with its id that no run took (one without a result message first while the run still waits on
its result: an input streaming, a submitted interaction). A card no run reaches shows its
own result message: the result after it, never another turn's reusing the id (a result with no
card before it shows on its own).

Give each run the call as the transcript holds it (`toolRunsFromHitlRequests` does, from the loop's
requests). A run whose call equals no card's (arguments you normalized or re-serialized) falls back
to the last card with its id and name that no run took and that has no result message, and shows
nowhere when there is none; a different name is another turn's call.

When the snapshot's run may resume (a HITL answer, a stopped run going on), mark a run start on the
rebuilt state:

```ts
import { initialAgentClientState, markAgentRunStart } from '@yolk-sdk/agent/client'
import {
  buildAgentChatMessages,
  makeAgentChatEventProjectionState,
  markChatRunStart
} from '@yolk-sdk/agent/react'

const projection = markChatRunStart(
  makeAgentChatEventProjectionState(
    buildAgentChatMessages({
      messages,
      toolRuns,
      userDraft: '',
      assistantDraft: '',
      reasoningDraft: '',
      error: null
    })
  )
)

const client = markAgentRunStart({ ...initialAgentClientState, messages, toolRuns })
```

The resumed run's `AgentStart` can lie before your stream cursor, and its tool batch runs before
its first model turn. Without a start, the batch acts on the last card or run holding its call id,
which can be an earlier turn's (client runs kept from earlier turns, or stored messages that lag the
run). With the run start, it reaches the snapshot's cards and runs only as the same call or, for
answers, the one holding their request, and adds its own otherwise. A snapshot taken mid-turn keeps
working: that turn's later host events name calls in the snapshot's last message and find them as
the same call. Its model events carrying `executionTurn` with their `executionId` (the
vercel-workflows sequencer sets both) start the turn they name, as its missed `LLMStreamStart`
would, so a reused id among them stays off earlier turns' calls. Model events without
`executionTurn` before the next `LLMStreamStart` count as replays of an earlier run's, so a reused
id among them can still reach an earlier turn's call, as without a start. A client that missed a
run's `LLMStreamStart` otherwise (it connected mid-turn after a local submit, or an `AgentStart`
replayed without `eventId` after the turn's start, whose replay its event id then dedupes) has the
same limit for such events. The next `AgentStart` or `LLMStreamStart` replaces the run start.


---

# Agent package

URL: /docs/agent

Build streaming agents with messages, model providers, tools, clients, and React state.



Use `@yolk-sdk/agent` when you want to run model turns, execute tools, stream protocol events, and project those events into a UI.

Install:

```bash
pnpm add @yolk-sdk/agent@canary effect@4.2.0
```

Import by subpath:

```ts
import { run } from '@yolk-sdk/agent/loop'
import { UserMessage } from '@yolk-sdk/agent/protocol'
import { runRuntime } from '@yolk-sdk/agent/runtime'
import { planWindowCompaction } from '@yolk-sdk/agent/compaction'
import { makeTool } from '@yolk-sdk/agent/tools'
```

## Most common jobs [#most-common-jobs]

| Job                                 | API                                        |
| ----------------------------------- | ------------------------------------------ |
| Make a user message                 | `UserMessage.make({ content })`            |
| Run a model/tool loop               | `run(...)`                                 |
| Run behind an HTTP/session boundary | `runRuntime(...)`                          |
| Define schema-backed tools          | `makeTool(...)`                            |
| Stream from browser/client          | `streamAgentEventStreamUntilTerminal(...)` |
| Render headless React chat          | `useAgentChat(...)`                        |
| Track run and subagent status       | `AgentStatus`, `nextAgentStatusTree(...)`  |
| Build provider layers               | provider subpaths                          |
| Plan bounded model context          | `planWindowCompaction(...)`                |
| Test without provider accounts      | `FauxProvider`, `TestToolExecutor`         |

## Local test loop [#local-test-loop]

```ts
import { Effect, Layer, Stream } from 'effect'
import { ContextTransformer, LoopConfig, run } from '@yolk-sdk/agent/loop'
import { FauxProvider, Reply, TestToolExecutor } from '@yolk-sdk/agent/loop/testing'
import { UserMessage } from '@yolk-sdk/agent/protocol'

const TestLayer = Layer.mergeAll(
  FauxProvider.layer(Reply.text('Done.')),
  TestToolExecutor.layer({}),
  LoopConfig.defaultLayer,
  ContextTransformer.identity
)

const events = await Effect.runPromise(
  run({
    messages: [UserMessage.make({ content: 'Hello' })],
    systemPrompt: 'Be helpful.',
    tools: [],
    model: 'test-model'
  }).pipe(Stream.runCollect, Effect.provide(TestLayer))
)
```

Next: [add tools](./tools-hitl), [serve it with `runRuntime`](./loop-runtime), or [render it in React](./client-react).


---

# Loop and runtime

URL: /docs/agent/loop-runtime

Choose `run` or `runRuntime` and stream agent events from your app.



Use the loop when you want direct control. Use runtime when you want a reusable HTTP/session boundary.

| API                                 | Use when                                                          |
| ----------------------------------- | ----------------------------------------------------------------- |
| `run`                               | you already have messages/tools/provider layers and want a stream |
| `runRuntime` + `Transcript`         | the client sends the full transcript each turn                    |
| `runRuntime` + `AppendInput`        | your server stores an append log                                  |
| `runRuntime` + `AppendHitlResponse` | resuming a paused approval/question                               |

## Direct loop [#direct-loop]

```ts
import { Effect, Stream } from 'effect'
import { run } from '@yolk-sdk/agent/loop'
import { UserMessage } from '@yolk-sdk/agent/protocol'

const stream = run({
  messages: [UserMessage.make({ content: 'Draft a reply.' })],
  systemPrompt: 'Be helpful.',
  tools,
  model: 'gpt-5.5'
})

const events = await Effect.runPromise(
  stream.pipe(Stream.runCollect, Effect.provide(AppAgentLayer))
)
```

Provide these Effect services from your host:

* `LLMProvider`
* `ToolExecutor`
* `ContextTransformer`
* `LoopConfig` (`LoopConfigSettings` for `LoopConfig.layer`; formerly `LoopConfigShape`)

## Compose the loop layer [#compose-the-loop-layer]

`makeAgentLoopLayer` merges those four Layers. The provider layer is required. Omitted tools use `ToolExecutor.unavailable` (calls fail with `ToolError` `cause: 'execution'`). Omitted transformer/config use `ContextTransformer.identity` and `LoopConfig.defaultLayer`.

Fragment. This constructs a layer and does not run a provider call:

```ts
import { makeAgentLoopLayer } from '@yolk-sdk/agent/loop'
import { FauxProvider, Reply } from '@yolk-sdk/agent/loop/testing'

const LoopLayer = makeAgentLoopLayer({
  provider: FauxProvider.layer(Reply.text('ok'))
})
```

Intercept by decorating a service (`decorateLLMProvider`), not with hooks. Pass the decorator layer as `provider` after providing the inner provider.

`collectModelTurn(stream, { initialUsage, onEvent })` is the success-only wrapper: it returns a finalized `ModelTurnResult` or re-fails. `initialUsage` is the starting cumulative usage; `UsageUpdate` events add to it. `usageUnavailable: true` says the stream's `LLMStreamEnd` was marked `usageUnavailable`, so `usage` under-counts the turn; a tool that runs model turns reports it as `ToolResult.usageIncomplete`.

`collectModelTurnAttempt` keeps a `ModelTurnCollection` on typed stream or sink failure:

| Tag            | Meaning                                             |
| -------------- | --------------------------------------------------- |
| `Collected`    | stream completed; collection is finalized           |
| `StreamFailed` | typed provider/loop error; partial collection kept  |
| `SinkFailed`   | typed `onEvent` error; not a model-recovery outcome |

`onEvent` sink errors are not model-recovery outcomes. Defects, interrupts, and mixed typed+defect/interrupt Causes are re-failed as Causes rather than `StreamFailed` / `SinkFailed`.

For durable Workflow hosts, use the existing [Harness composition](../vercel-workflows/harness-composition) cookbook rather than duplicating collector/recovery policy here.

## Stateless transcript runtime [#stateless-transcript-runtime]

Use this when your route receives the whole transcript from a client:

```ts
import { runRuntime } from '@yolk-sdk/agent/runtime'
import { UserMessage } from '@yolk-sdk/agent/protocol'

const stream = runRuntime(
  {
    _tag: 'Transcript',
    sessionId: 'browser-session',
    messages: [UserMessage.make({ content: 'Hello' })]
  },
  {
    systemPrompt: 'Be helpful.',
    tools,
    model: 'gpt-5.5'
  }
)
```

Your route converts the stream to NDJSON/SSE and provides provider/tool layers.

## Append-backed runtime [#append-backed-runtime]

Use this when your server stores every input/run/result in `SessionEventStore`. This fits Durable Objects, databases, or other append logs:

```ts
const stream = runRuntime(
  {
    _tag: 'AppendInput',
    sessionId: 'session_123',
    input: UserMessage.make({ content: 'Continue' }),
    runId: 'run_123'
  },
  runtimeConfig
)
```

Production apps implement `SessionEventStore`; tests can use the in-memory layer.

## Host instructions [#host-instructions]

A `RunInstruction` (`{ key, state, render }`) is host context kept current in the conversation,
for example the code mode catalog (`toolSet.instructions` from `resolveTools`). Pass it as
`RunConfig.instructions` or `RuntimeConfig.instructions`.

* Before each model request the loop compares `state` with the latest instruction message of the
  same `key`. Only when it changed does it append a user-role message with `render(state)` and a
  non-model-visible `instruction: { key, state }` envelope (`state: undefined` appends a removal
  notice once). Earlier messages never change, so the cached request prefix survives.
* `render` gets only the current state: compaction keeps the latest message of each key, so every
  message must stand alone.
* Appended messages are part of the run's created messages (persist them with the turn) but emit no
  `UserMessage` event. Chat projections hide them and `toAgentMessages` round-trips them.
* Durable hosts driving `runModelTurn` append and persist
  `instructionMessages(transcript, instructions)` before each model step; `runModelTurn` does not
  accept `instructions`.
* Two instructions with one key fail resolution (`duplicate_instruction`).

## Add compaction [#add-compaction]

`@yolk-sdk/agent/compaction` provides helpers for budgets, token estimation, preview summaries,
checkpoint messages, transcript formatting, overflow retry, and window transforms.

For long-lived server-owned sessions, see [Implement durable compaction](/docs/guides/durable-compaction).


---

# Protocol

URL: /docs/agent/protocol

Create transcript messages, pass files, and consume stream events.



Use `@yolk-sdk/agent/protocol` any time your app needs to build messages, inspect stream events, or persist a transcript.

## Create messages [#create-messages]

Concrete transcript message variants:

* `UserMessage`
* `AssistantAgentMessage`
* `ToolResultMessage`

`AgentMessage` is the union of those variants, not a fourth message kind:

```ts
type AgentMessage = UserMessage | AssistantAgentMessage | ToolResultMessage
```

`AssistantAgentMessage` is the assistant/model-authored variant. It can contain text, reasoning, host tool calls, provider tool calls, and provider tool results.

Create a normal user message:

```ts
import { UserMessage } from '@yolk-sdk/agent/protocol'

const message = UserMessage.make({ content: 'Summarize this file.' })
```

Add optional model-visible envelope facts:

```ts
const message = UserMessage.make({
  content: 'Summarize this.',
  createdAtMs: Date.now(),
  author: { displayName: 'Magoz' },
  annotations: { timezone: 'Europe/Madrid' }
})
```

Do not put secrets, auth state, private ids, or hidden policy in envelope fields. Providers may send them to models.

## Send files and media [#send-files-and-media]

`Content` is either plain text or ordered content parts:

* `TextPart`
* `ImagePart`
* `DocumentPart`
* `AudioPart`
* `FilePart`: bytes a tool yields for other tools to move, not for the model to view. Tool
  resolution stores them and the model only sees a `fileId` label (the file claim check,
  `docs/adr/0009-file-claim-check.md` in the repository; tools in `@yolk-sdk/files`).

Media sources can be inline base64, durable URLs, or host-owned refs:

```ts
import { ImagePart, UserMessage, urlAttachmentSource } from '@yolk-sdk/agent/protocol'

const message = UserMessage.make({
  content: [
    ImagePart.make({
      source: urlAttachmentSource('https://cdn.example.com/image.webp'),
      mimeType: 'image/webp'
    })
  ]
})
```

Hosts own upload, auth, URL durability, retention, and ref hydration policy. Use
`resolveMessageAttachmentSources` or `resolveMessagesAttachmentSources` to resolve sources throughout
user, assistant, and tool-result content without changing durable history. These Effect-native helpers
also traverse nested assistant provider tool results and preserve envelope/part metadata and ordering.
They do not interpret opaque tool/provider payloads or add provider media capabilities.

For private files, resolve fresh URLs inside each provider attempt, after context projection and
compaction. See [Resolve private attachments](../guides/private-attachments) for authorization,
overflow-retry composition, native tool-result content, and bounded connector downloads.

## Consume events [#consume-events]

Streams emit `AgentEvent` values such as:

* `AgentStart`, `AgentEnd`, `AgentError`, `AgentRetry`
* `TurnStart`, `TurnEnd`
* `LLMStreamStart`, `LLMTextDelta`, `LLMReasoningDelta`, `LLMStreamEnd`
* `LLMReasoningReplay` (closes a reasoning block with opaque provider state for replay; UIs ignore it)
* `ToolExecutionStarted`, `ToolExecutionCompleted`, `ToolExecutionError`
* `ToolExecutionAccepted` (a host admitted a background tool call; not completion, no usage)
* `UserMessageEvent`, `AssistantMessageEvent`
* `AgentAwaitingInput`, `QuestionRequested`, approval events

Use `UserMessageEvent` when a host promotes queued user input into a durable stream. The host owns
queue/promotion policy and assigns a stable `eventId` so replay does not project the message twice:

```ts
import { UserMessage, UserMessageEvent } from '@yolk-sdk/agent/protocol'

const event = UserMessageEvent.make({
  eventId: 'session_1:user-message_42',
  message: UserMessage.make({ content: 'Please compare the alternatives too.' })
})
```

Durable HITL payloads that must be plain JSON use `plainHitlResponse` /
`plainQuestionResponse` / `plainToolApprovalResponse`. Those helpers omit absent optionals and
call `PlainHitlResponse.QuestionResponse` / `PlainHitlResponse.ToolApprovalResponse`
(`Data.taggedEnum` plain objects, `_tag` last, not Schema classes). `QuestionResponse` and
`ToolApprovalResponse` remain Schema classes for protocol values.

Use `isTerminalAgentEvent` to detect logical stream termination.

```ts
import { isTerminalAgentEvent } from '@yolk-sdk/agent/protocol'

for (const event of events) {
  if (event._tag === 'LLMTextDelta') {
    process.stdout.write(event.text)
  }

  if (isTerminalAgentEvent(event)) {
    break
  }
}
```

### Missing usage [#missing-usage]

`UsageUpdate` carries each model call's token usage as an additive delta, and `AgentEnd` /
`AgentAwaitingInput` carry the run's total. When a model stream completes without the usage report
its request asked for (a streamed chat completion cut after its finish chunk, before the
`stream_options.include_usage` chunk; a streamed Responses `response.completed` without `usage`; a
Codex stream without `response.completed`, or whose recovered `response.completed` has no `usage`
that decodes; a Claude or native Messages stream whose
`message_stop` came without a `message_delta` carrying an output count), the turn still completes,
and that stream's `LLMStreamEnd` carries
`usageUnavailable: true`. Its usage is then missing from the totals, or partial when the stream
sent some `UsageUpdate`s first. Hosts decide how to account for it, for example:

```ts
import type { AgentEvent } from '@yolk-sdk/agent/protocol'

const unreportedModelCalls = (events: ReadonlyArray<AgentEvent>) =>
  events.filter(event => event._tag === 'LLMStreamEnd' && event.usageUnavailable === true).length
```

The field is optional: it is absent when the report arrived and on events recorded before it
existed, so persisted streams decode either way. Non-streamed (JSON) responses are never marked.

## Validate transcripts before provider calls [#validate-transcripts-before-provider-calls]

Every assistant host tool call must have a matching `ToolResultMessage` before the next provider request. Use `validateNoDanglingHostToolCalls` before lowering transcripts to providers.

### Choose model-visible tool content intentionally [#choose-model-visible-tool-content-intentionally]

`ToolResult.content` is the provider-facing result. Provider adapters preserve its supported text and
media plus error semantics, but they do not automatically serialize `structuredContent` into model
requests. `structuredContent` remains available in tool events, transcript messages, durable wire
round-trips, host UI, and replay.

If the model must use an event, continuation cursor, or other structured value, render a bounded,
intentional projection into `content` as well. Do not rely on `structuredContent` alone, and do not
put secrets or private host metadata into model-visible `content`.

### Preserving tool acknowledgements [#preserving-tool-acknowledgements]

Use `toolResultMessageFromResult(result, envelope?)` to copy `toolCallId`, `content`, `isError`,
`structuredContent`, and background `acceptance` into a `ToolResultMessage`. It invents no timestamp,
author, or annotations; pass those optional message-envelope fields explicitly.

It intentionally drops `ToolResult.nestedCalls`, `ToolResult.usage` and
`ToolResult.usageIncomplete`, which are never model-visible. Capture them from the `ToolResult` or
tool events if you keep audit or billing records. The loop does not add `ToolResult.usage` to run
usage. `usageIncomplete: true` means `usage` under-counts the nested work: a nested model call
completed without (all of) its usage report (its stream's `LLMStreamEnd.usageUnavailable`, a
provider's `LLMDone.usageUnavailable`, a classification without usage). It can be set without
`usage`. A tool that runs its own model calls sets it; `recordNestedToolCall` ORs it from the
nested calls it records, dropped ones included.

An accepted call is settled, not completed. Client and React projections preserve its original call
and receipt across active-event replays (even without event IDs), turn cleanup, and transcript
hydration. Persisted acceptance takes precedence over stale active client runs.


---

# Providers and OAuth

URL: /docs/agent/providers-oauth

Provide model layers and keep token storage in your host app.



Provider subpaths translate Yolk messages/tools into vendor requests and normalize stream events back into Yolk protocol.

For the current provider catalog and setup snippets, see [Model providers](../integrations/model-providers).

## Pick a provider subpath [#pick-a-provider-subpath]

| Subpath                                                  | Purpose                                                                                 |
| -------------------------------------------------------- | --------------------------------------------------------------------------------------- |
| `@yolk-sdk/agent/providers/openai`                       | Codex OAuth and token broker helpers                                                    |
| `@yolk-sdk/agent/providers/openai/provider`              | OpenAI-compatible chat provider factory                                                 |
| `@yolk-sdk/agent/providers/openai/conformance`           | OpenAI chat, Codex Responses, and Codex usage fixtures and conformance cases            |
| `@yolk-sdk/agent/providers/vercel/ai-gateway-provider`   | Vercel AI Gateway provider factory and configuration                                    |
| `@yolk-sdk/agent/providers/vercel/ai-gateway-classifier` | Vercel AI Gateway [classifier model](./classifier-models) layer (`/v1/evaluate`)        |
| `@yolk-sdk/agent/providers/vercel/conformance`           | Gateway chat and classifier wire fixtures for replay tests with `@yolk-sdk/conformance` |
| `@yolk-sdk/agent/providers/opencode/go-provider`         | OpenCode Go API-key provider for three host-selected protocols                          |
| `@yolk-sdk/agent/providers/opencode/usage`               | Best-effort Go allowance snapshots using an API key                                     |
| `@yolk-sdk/agent/providers/opencode/conformance`         | OpenCode Go wire fixtures and conformance cases (protocols and usage) for replay        |
| `@yolk-sdk/agent/providers/openai/codex`                 | Codex request, authorization header, and token broker helpers                           |
| `@yolk-sdk/agent/providers/openai/codex-usage`           | Best-effort Codex subscription-allowance snapshots                                      |
| `@yolk-sdk/agent/providers/openai/codex-provider`        | OpenAI Codex provider factory                                                           |
| `@yolk-sdk/agent/providers/anthropic`                    | Claude OAuth and token broker helpers                                                   |
| `@yolk-sdk/agent/providers/anthropic/claude`             | Claude authorization URL, callback parsing, and token broker helpers                    |
| `@yolk-sdk/agent/providers/anthropic/usage`              | Best-effort Claude subscription-allowance snapshots                                     |
| `@yolk-sdk/agent/providers/anthropic/claude-provider`    | Claude provider factory                                                                 |
| `@yolk-sdk/agent/providers/anthropic/conformance`        | Anthropic Messages and Claude usage fixtures and conformance cases for replay tests     |
| `@yolk-sdk/agent/providers/xai`                          | Grok subscription OAuth and token broker helpers                                        |
| `@yolk-sdk/agent/providers/xai/grok`                     | Grok PKCE/device constants, callback parsing, auth, and broker helpers                  |
| `@yolk-sdk/agent/providers/xai/grok-provider`            | Grok subscription Responses provider factory                                            |
| `@yolk-sdk/agent/providers/xai/usage`                    | Best-effort Grok subscription-allowance snapshots                                       |
| `@yolk-sdk/agent/providers/xai/conformance`              | Grok Responses and Grok usage fixtures and conformance cases for replay tests           |
| `@yolk-sdk/agent/providers/subscription-usage`           | Shared allowance snapshot and safe error schemas                                        |
| `@yolk-sdk/agent/oauth`                                  | Provider-neutral access-token and broker contracts                                      |

## Provide fresh credentials at runtime [#provide-fresh-credentials-at-runtime]

Provider packages may model vendor auth mechanics, but hosts own:

* refresh token storage
* encryption and rotation
* broker routes
* OAuth callbacks
* account linking
* model-specific output-token limits
* policy and audit

Give provider layers fresh access tokens at execution time. Do not store raw secrets in protocol messages, annotations, tool results, or docs examples.

Vercel AI Gateway accepts either an AI Gateway API key or a Vercel OIDC token as Bearer auth. The
host chooses which credential source to use, owns model routing/fallback policy, and treats custom
Gateway endpoint URLs as credential-bearing trusted proxies.

OpenCode Go accepts a redacted API key, not `OAuthAccessToken`. Hosts select the model's protocol
and output limit. Messages uses `x-api-key`; Chat Completions and Responses use Bearer auth. No
Claude/Codex subscription fingerprints are added. Only configure a trusted credential-bearing
`baseUrl` override. See [Go setup](../integrations/provider-setup#opencode-go).

Grok subscription tokens default to the fixed xAI CLI proxy, not the developer API-key origin.
Browser PKCE uses xAI's fixed loopback callback. The package exports device-flow constants only; a
host that cannot listen on the callback must implement device-code initiation, polling, cancellation,
and exchange itself. Validate token provider/freshness before construction, serialize refreshes, and
atomically persist any replacement refresh token. Only configure a custom Grok response URL when it
is a trusted credential-bearing proxy. The default CLI proxy is a private, unsupported surface that
may change; use it only when permitted by xAI's terms.

Claude/Codex/Grok subscription-usage adapters accept the same `OAuthAccessToken` values but do not
refresh or persist them. Go's `fetchOpenCodeGoSubscriptionUsage` accepts a redacted API key instead. Grok usage also requires the authenticated xAI `user_id` and a truthful host integration
version as explicit options; it does not reinterpret generic token `accountId` or impersonate an
official client version. Their private provider endpoints are best-effort. Hosts own polling,
labels, stale-data rules, alerts, and UI; the adapters only fetch and normalize allowance windows
with sanitized errors.

## What the provider gives the loop [#what-the-provider-gives-the-loop]

Provider layers implement `LLMProvider`. The loop calls that service with messages, tool definitions, system prompt, model id, and optional capabilities. The provider emits text deltas, tool calls, usage, and done/error events. Tool calls are decoded as protocol `ToolCall`; a malformed one (empty or padded id or name) fails the request with a typed `LLMError`, never a thrown defect.

A stream that completes without the usage report its request asked for still ends with `LLMDone`, marked `usageUnavailable: true`:

| Provider                                                               | Marked when                                                                                                                                                          |
| ---------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Streamed chat (OpenAI-compatible, Vercel AI Gateway, OpenCode Go chat) | the stream ends after the finish chunk, without the `stream_options.include_usage` usage chunk                                                                       |
| Streamed Responses (OpenAI Codex, xAI Grok, OpenCode Go `responses`)   | `response.completed` carries no `usage`                                                                                                                              |
| OpenAI Codex                                                           | the stream ends without `response.completed`, or the `response.completed` `output` is missing or misses a required key and its `usage` is missing or does not decode |
| Anthropic Claude, native Messages (OpenCode Go `messages`)             | `message_stop` arrives without a `message_delta` carrying an output count (only `message_start` usage, if any)                                                       |

Non-streamed (JSON) responses are never marked. Grok and OpenCode Go Responses fail without `response.completed`, and Messages streams fail without `message_stop`, so neither completes without its terminal event: such a stream emits no `LLMDone` and fails as non-retryable `invalid_response` with `responseIssue: 'missing_done'`, the loop's incomplete stream. The loop forwards the mark on the protocol `LLMStreamEnd` ([Protocol](./protocol#missing-usage)).

Codex's recovery of a final response with missing `output` (streamed or JSON) keeps its valid output items, so a function call the stream never emitted still runs, and reports its `usage` when that decodes (Done unmarked). A function call that does not decode must replay one the stream already emitted, and a message that does not decode and carries text must be one whose text already streamed; otherwise the response fails as `invalid_response` instead of ending the turn without it ([OpenAI Codex](../integrations/model-providers#openai-codex)).

## OpenAI JSON admission [#openai-json-admission]

OpenAI Chat Completions and Responses lowering admits `ToolDef.parameters` and tool-call `params` as
`Schema.Json` before transport. Non-JSON values fail as non-retryable `LLMError` `provider_error`.
`ToolDef.parameters` now admits `ToolJsonSchema` at construction; call params/results remain opaque.
Public Codex `OpenAiCodexTool.parameters` remains
`unknown`. Inbound HTTP JSON and Responses SSE event JSON admit `Schema.Json` before helpers;
non-object SSE JSON is ignored, malformed non-JSON event text fails `invalid_response`, and HTTP
error bodies stay raw text for classification.

`OpenAiProviderConfig.reasoningEffortFormat` picks the request field for `reasoningEffort`:
`reasoning-object` sends `{ reasoning: { effort } }`, and `reasoning-effort` sends `reasoning_effort`.
The native OpenAI endpoint (no `chatCompletionsUrl`) defaults to `reasoning-effort`; compatible
endpoints have no default, and a request with an effort fails with a `validation_error` until one is
set. `omit` never sends the effort and never fails.
`reasoningContent: true` validates/emits `reasoning_content` (or the normalized `reasoning` thinking field, preferring `reasoning_content` when both are present) and preserves it in assistant replay;
by default this vendor extension is ignored. OpenCode Go enables the latter two options.

Chat stays one JSON body by default; `streaming: true` requests SSE deltas (OpenCode Go chat always
sets it). Only stream against endpoints that serve chat SSE. See the [API reference](../api-reference/agent#providers)
and [Go setup](../integrations/provider-setup#opencode-go).

`OpenAiProviderConfig.extraBody` takes JSON-object input. Lowering discards canonical request fields
without reading their values and snapshots surviving enumerable own data. Accessors are rejected
unread, not evaluated; nonfinite values, cycles and exotic objects fail with a fixed
`Invalid … extraBody JSON: expected a JSON object` and no HTTP request. Root symbols/hidden fields
are omitted; nested hidden/symbol keys and extra array properties fail. DAG aliases are supported;
mutating the input after lowering does not mutate the snapshot. Proxy traps are not guaranteed
side-effect-free. Final composed-body `Schema.Json` admission after lone-surrogate rewriting remains.
Gateway routing projects its declared JSON fields. See [the migration guide](../migration).

## Errors and retries [#errors-and-retries]

Provider adapters classify safe metadata into `ProviderErrorInfo`. Raw provider response bodies stay out of protocol/UI. The loop owns bounded retry behavior and usage aggregation.

Subscription-usage requests use separate `ProviderSubscriptionUsageError` variants because they run
outside the LLM loop. They suppress credential-bearing HTTP traces and never preserve raw response
bodies in typed failures.


---

# Agent status

URL: /docs/agent/status

One typed status for a run (idle, working, blocked on a person, done, failed), from live events or stored state.



`AgentStatus` in `@yolk-sdk/agent/protocol` says what a run is doing. It uses the vocabulary of
the [OSC 7501 Program Status Protocol](https://www.superlogical.com/rex/docs/build/program-status):
the SDK reports state, and your app decides how to show it (badges, inbox rows, notifications).

| `_tag`    | Meaning                                                                                         |
| --------- | ----------------------------------------------------------------------------------------------- |
| `Idle`    | At rest, waiting for the next instruction. Also the status after a person stops a run.          |
| `Working` | Running. `activity` says what: `Busy`, `Generating`, `Tools`, `Compacting`, `Retrying`.         |
| `Blocked` | Paused until a person settles every request. `kind` says what is needed, `requests` holds them. |
| `Done`    | Finished. The result is in the transcript.                                                      |
| `Failed`  | Failed and stopped. `message`, plus the `AgentError` when the stream sent one.                  |

Every variant is an Effect Schema class, so a status encodes to JSON with
`Schema.toCodecJson(AgentStatus)` and can be stored next to the run.

## Blocked kinds [#blocked-kinds]

| Request                                     | `kind`       |
| ------------------------------------------- | ------------ |
| `ToolApprovalRequest`, `InteractionRequest` | `permission` |
| `QuestionRequest`, `InputRequest`           | `question`   |
| (reserved for logins and credentials)       | `auth`       |

One pause can hold several requests (same-turn sibling calls). `agentBlockedKind` reports one kind
for the batch, `auth` over `permission` over `question`; `hitlRequestBlockedKind` gives each
request's own kind.

## From live events [#from-live-events]

```ts
import { agentStatusFromEvents, nextAgentStatus } from '@yolk-sdk/agent/protocol'

let status = agentStatusFromEvents(replayedEvents)
status = nextAgentStatus(status, event)
```

| Event                                                               | Status                                    |
| ------------------------------------------------------------------- | ----------------------------------------- |
| `AgentStart`, `TurnStart`                                           | `Working(Busy)`                           |
| `LLMStreamStart`                                                    | `Working(Generating)`                     |
| `ToolExecutionStarted` / `Completed`, `Accepted`, `Error`           | adds / removes a running tool             |
| `CompactionStart` / `CompactionEnd`                                 | `Working(Compacting)` / `Busy`            |
| `AgentRetry`                                                        | `Working(Retrying)`, until output resumes |
| `AgentAwaitingInput`                                                | `Blocked`                                 |
| `AgentEnd`                                                          | `Done`                                    |
| `AgentError` with code `aborted` and `abortReason` `user` (or none) | `Idle`                                    |
| any other `AgentError`, including `system` and `max_turns` aborts   | `Failed`                                  |

Other events leave the status unchanged. Work events mean the run is working whatever came
before, so a resumed durable stream leaves `Blocked` even when it does not replay `AgentStart`.
Dedupe replayed events by `eventId` before folding them. `agentStatusRetry(status)` returns the
pending `AgentRetry` while retrying.

The `useAgentChat` reducer and `reduceAgentEvents` also fence replays without `eventId`: a replayed
`AgentAwaitingInput` blocks only on the requests their chat or tool runs still show pending, and
leaves the status as it was when every request names a call (same id, name and arguments) already
answered, cancelled, denied or finished. A replayed start of a finished call leaves it too.

A host that keeps a chat projection and folds status itself gets the same fence from
`stepAgentChatProjection` in `@yolk-sdk/agent/react`. It applies the event as
`applyAgentEventToChatProjection` does and returns `statusEvent`: the event to fold, or
`undefined` when the status must not move (an event seen before, one from a superseded or stale
model step, a replayed start of a finished call, a pause whose every call is past its request).
A pause naming some such calls comes back with only its pending requests. Folding every event
instead would show `Blocked` with no card to answer. When the event's model step started before
the projection's first event (a mid-turn snapshot rebuild) and names its turn (`executionTurn`),
the step also returns `missedStart`, the `LLMStreamStart` the projection applied first: fold it
before `statusEvent`.

```ts
import { idleAgentStatus, nextAgentStatus } from '@yolk-sdk/agent/protocol'
import { makeAgentChatEventProjectionState, stepAgentChatProjection } from '@yolk-sdk/agent/react'

let projection = makeAgentChatEventProjectionState()
let status = idleAgentStatus

for (const event of events) {
  const step = stepAgentChatProjection(projection, event)
  projection = step.projection
  if (step.missedStart !== undefined) status = nextAgentStatus(status, step.missedStart)
  if (step.statusEvent !== undefined) status = nextAgentStatus(status, step.statusEvent)
}
```

To use `agentStatusFromEvents` (or `agentStatusTreeFromEvents`), collect each step's `missedStart`
and then its `statusEvent`, leaving out `undefined`, and pass those instead of the raw events.

## From stored state [#from-stored-state]

Store the encoded status in the same commit as the rest of the run, and reconcile it when you read
it back:

```ts
import { reconcileAgentStatus } from '@yolk-sdk/agent/protocol'

const status = reconcileAgentStatus(stored, { runActive: run.workflowRunId !== null })
```

`Working` and `Blocked` only hold while the run is alive, so they become `Idle` when you tell it
the run is not active (lease cleared, platform run terminal). `Done` and `Failed` stay until you
replace them. Base `runActive` on your authoritative run record, never on the last event seen.

## Subagents [#subagents]

`AgentStatusTree` is the run's `root` status plus one `SubagentStatusEntry` per subagent, in start
order. `nextAgentStatusTree` and `agentStatusTreeFromEvents` fold events into it:

* `SubagentStarted` adds a `Working` entry; `SubagentCompleted` sets `Done` or `Failed`.
* A subagent call that the host accepts as background work (its result passes
  `isSubagentAcceptedToolResult`, as one built by `makeSubagentAcceptedToolResult` does, or a
  `ToolExecutionAccepted` event) is marked `background: true`. Its status comes from you after
  that: write it with `withSubagentStatus`.
* When the run stops (`AgentEnd`, `AgentError`, a local stop, or a transport failure), live inline
  subagents become `Idle`.
* `AgentStart` drops entries settled in earlier runs.

## In client and React state [#in-client-and-react-state]

`AgentClientState` and `AgentChatState` carry `status: AgentStatus` and `subagents`. Failures and
retries live in the status (`Failed`, `Working(Retrying)`), not in separate fields. `useAgentChat`
returns `status` and `subagents`, and keeps `isRunning` (`Working`) and `isWaiting` (`Blocked`).

```tsx
import { Match } from 'effect'

const label = Match.value(chat.status).pipe(
  Match.tag('Idle', () => 'Idle'),
  Match.tag('Working', () => 'Working'),
  Match.tag('Blocked', current =>
    Match.value(current.kind).pipe(
      Match.when('permission', () => 'Needs approval'),
      Match.when('question', () => 'Needs answer'),
      Match.when('auth', () => 'Needs sign-in'),
      Match.exhaustive
    )
  ),
  Match.tag('Done', () => 'Done'),
  Match.tag('Failed', current => current.message),
  Match.exhaustive
)
```

## Host-owned [#host-owned]

* Whether a person has seen a `Done` or `Failed` run (unread state).
* Labels, wording, and which statuses notify, plus rate limits for notifications.
* Proof that a run is alive (`runActive`).
* Emitting OSC 7501 sequences, if you ship a terminal app.


---

# Tools and HITL

URL: /docs/agent/tools-hitl

Define typed tools, expose them to the loop, and pause for human input.



Tools are how the model asks your app to do something. Yolk gives you schema-backed registration and protocol events; your app decides which tools are available and how risky calls are approved.

## Define a tool [#define-a-tool]

Use `makeTool` with Effect Schema so validation is the source of truth.

```ts
import { Effect, Schema } from 'effect'
import { makeTool } from '@yolk-sdk/agent/tools'

const EchoParams = Schema.Struct({ text: Schema.String })

export const echoTool = makeTool({
  name: 'echo',
  description: 'Echo text.',
  parameters: EchoParams,
  output: Schema.Struct({ text: Schema.String }),
  access: 'read',
  execute: ({ params }) => Effect.succeed({ output: { text: params.text } })
})
```

Optional `invalidParamsMessage: (error: Schema.SchemaError) => string` customizes the
model-visible validation text. Only decoding `parameters` (through its JSON codec) invokes it, and
the decode error is passed through unwrapped. Default:
`Invalid ${name} arguments: ${String(error)}`, followed by one line per object that names its
unknown keys and lists the allowed keys, and one line per number or boolean argument sent as a JSON
string, naming the string and, when it is one, the literal to send. Custom callbacks can keep that
hint with `withToolArgumentsErrorHint(message, error)`; the wrong-type lines need the error Yolk
passed in, not one from your own decode. In Effect 4, `SchemaError` extends native `Error`, but do
not default to `.message`: that drops the `SchemaError(...)` wrapper required by this tool-message
contract. Existing `(error: unknown) => string` callbacks remain assignable.

### Typed outputs and file fields [#typed-outputs-and-file-fields]

A tool's typed output is its result contract
([ADR 0013](https://github.com/magoz/yolk-sdk/blob/main/docs/adr/0013-typed-tool-results.md)):

* With `output` (an Effect Schema that encodes without services), `execute` returns
  `{ output }`. Yolk encodes it with `Schema.toCodecJson(output)` into `structuredContent`, which
  [code mode](../integrations/code-mode) scripts receive as declared. A value that does not encode
  (or does not encode to plain JSON) fails the call without the value in the error.
* The model sees `render(value, files)` when you pass it (optional), else a string output as is,
  else the compact JSON of the encoding with file fields shown as file labels.
* Without `output`, `execute` returns `{ content }` (text, and file parts from
  `filePartFromBytes`); scripts get its text only.
* File fields are `ToolFile` in the output schema: return `new FileBytes({ bytes, name, mimeType })`
  (`view: true` also shows the model an image, audio or document), or
  `new FileStored({ fileId, name, mimeType, size })` for a file the host already wrote to the store
  (checked with `store.head`, never read). `resolveTools` stores the bytes
  through its `files` option, and the encoding holds a `FileRef` `{ fileId, name, mimeType, size }`
  or a `FileUnavailable` `{ unavailable, name, mimeType }`
  ([Move files between tools](../integrations/files)). `ToolFile` belongs only in `output`.
* `resolveTools` checks every successful result of a tool with an output schema through its
  registration's `decodeOutput` (excess properties rejected, plain JSON only) and passes on the
  checked value; a mismatched value is dropped with a warning that names only the tool, so scripts
  reject the call while the model still sees the content. `makeTool` sets `decodeOutput` from
  `output`; raw registrations that set `def.outputSchema` pass `toolOutputDecoder(schema)`, or
  resolution fails with `output_validation_required`.
* With explicit type arguments, the typed form takes three:
  `makeTool<Context, typeof Params, typeof Output>`.

Migration note: returning a raw `ToolResult` from `execute` still works in this canary but is
deprecated; move to `{ output }` or `{ content }` ([Migration](../migration)).

### Optional arguments, `null`, and unknown keys [#optional-arguments-null-and-unknown-keys]

The advertised `ToolDef.parameters` describe the schema's JSON codec, so `Schema.optional(X)`
reaches the model as `X | null`, and models often send `null` for fields they do not use. Tool
arguments decode through `Schema.toCodecJson(parameters)`:

* `null` on `Schema.optional(X)` is treated as omitted, and `Schema.withDecodingDefault` still
  applies.
* `Schema.optional(Schema.NullOr(X))` keeps `null`; use it only when `null` means something
  different from omission, such as clearing a value.
* The `null` member advertised for `Schema.optional(X)` carries
  `$comment: toolJsonSchemaOmittedNullComment` (`'yolk:null-means-omitted'`, a stable value from
  `@yolk-sdk/agent/protocol`), a standard annotation validators ignore. It marks this `null` as
  "not sent", unlike the identical-looking `null` of `Schema.optionalKey(Schema.NullOr(X))` or a
  third-party MCP schema. The Claude provider uses it to show such fields to the model as `X`
  (named optional schemas included); other `null`s keep their meaning. The other providers
  receive the schema without the marker. Tools served by the `@yolk-sdk/mcp` server keep it in
  their listing. Input and interaction response schemas never carry it: user responses decode
  with the response schema itself, which rejects `null` on `Schema.optional(X)`, although the
  descriptor still advertises `anyOf [X, null]` there: UI clients omit an empty optional field
  rather than send `null`.
* Required non-nullable fields still reject `null` with a model-visible validation error.
* Non-finite numbers (`"NaN"`, `"Infinity"`, `"-Infinity"`) are rejected. Declare number
  parameters as `Schema.Finite` or `Schema.Int`: a bare `Schema.Number` advertises those strings.
* Where the wire schema takes only a number or boolean, a value sent as a JSON string is rejected,
  and the error names the string and, when the schema takes it, the unquoted literal to send. No
  line is added for a string the schema could take. For example:
  `Argument "offset" must be a JSON number, but it was the string "120": send 120 without quotes.`
* Unknown keys are rejected at any depth with a model-visible validation error. Parameters are
  advertised as closed objects, and silently dropping a key would let the model believe it set
  something (a filter, a start time) that was ignored. The error names the key and lists the
  allowed ones, for example `Unknown argument "start". Allowed arguments: id, note.` One
  exception: Effect parses `Schema.Struct({})` as any object, so only a root empty struct is
  checked. Nested, use `EmptyToolParams` or a declared struct.

`resolveTools` also drops `null` on properties advertised as optional without `null`, such as
`Schema.optionalKey(X)` fields or raw MCP schemas, before any tool sees the call. It never touches
undeclared keys: a `null` on an unknown key, including another union member's field, is rejected
like a value, with a hint listing the allowed keys. If you dispatch
registrations without `resolveTools`, apply `omitNullOptionalToolArguments(def.parameters, params)`
from `@yolk-sdk/agent/tools` yourself.

## Resolve tools for a request [#resolve-tools-for-a-request]

Group tools into modules, resolve them for a request context, then pass definitions to the loop.

```ts
import { Effect } from 'effect'
import { makeToolExecutorLayer, resolveTools } from '@yolk-sdk/agent/tools'

const module = { id: 'local', tools: [echoTool] }

const toolSet = await Effect.runPromise(resolveTools([module], requestContext))
const ToolExecutorLayer = makeToolExecutorLayer(toolSet)
```

Pass `toolSet.tools` into `run`/`runRuntime`. Provide `ToolExecutorLayer` alongside your provider, loop config, and context transformer layers. Build a custom `ToolExecutor` layer only when you need advanced dispatch.

## Defer rarely used tools [#defer-rarely-used-tools]

With many tools (for example several MCP servers), declare the rarely used ones with
`loading: 'deferred'`. They stay out of provider requests until the model loads them, so they cost
no context ([ADR 0007](https://github.com/magoz/yolk-sdk/blob/main/docs/adr/0007-tool-exposure-and-catalog.md)).

```ts
const listIssues = makeTool<HostContext, typeof ListIssuesParams>({
  name: 'list_issues',
  description: 'List issues of a repository.',
  parameters: ListIssuesParams,
  access: 'read',
  loading: 'deferred',
  execute: ({ params }) => listIssuePage(params) // host-owned
})
```

* When any tool is deferred, `resolveTools` adds the package `tool_search` tool. The model searches
  by what it needs; the result loads the best matches, which are declared from the next request on.
  Opt out with `resolveTools(modules, context, { toolSearch: false })` or register your own
  `tool_search`.
* Activation is read from `tool_search` results in the transcript, never stored, so redelivered
  and resumed steps declare the same tools. Loading a tool changes the declared tools, which start
  the request, so that request misses the prompt cache once; later requests reuse the new prefix.
  Prefer code mode scripts for exploratory use.
* Deferral saves context, not authority: approval-gated tools keep their approval, and an allowed
  deferred tool still runs when called by name.
* `loading` applies to model-callable tools only (a type error on `callableBy: 'codemode'`).
  `tool_search`, `question`, `subagent`, input, interaction, plan review, background, and
  nested-access tools cannot be deferred (`deferred_unsupported_tool`).
* Connector and MCP tools take `loading` through their `exposure` option, for example
  `exposure: { callableBy: 'all', loading: 'deferred' }`.
* If you call providers yourself, declare `declaredToolDefs(toolSet.tools, messages)` from
  `@yolk-sdk/agent/protocol`. Realtime voice sessions declare deferred tools eagerly.

## Choose access level [#choose-access-level]

Every tool declares one access level:

| Access        | Use for                                                 |
| ------------- | ------------------------------------------------------- |
| `read`        | search, fetch, inspect                                  |
| `write`       | create/update external state                            |
| `destructive` | delete, execute commands, send messages, mutate broadly |

The SDK records access metadata. Your host enforces approval policy.

### Mark tools that call a model [#mark-tools-that-call-a-model]

Access says what a call changes, not what it costs. A tool that calls a model when it runs (a
language model, a classifier, a child agent run) sets `invokesModel: true`, on `makeTool` options
or a raw `ToolRegistration`:

```ts
makeTool({
  name: 'summarize_thread',
  parameters: SummarizeParams,
  access: 'read',
  invokesModel: true,
  execute
})
```

`resolveTools` copies it to `ToolMetadata.invokesModel` and, for code mode,
`NestedTool.invokesModel`; it is never sent to providers. It changes nothing by itself: host policy
reads it, for example code mode's
[`readOnlyNestedCallGate`](../integrations/code-mode#allow-only-reads), which refuses such calls in
scripts that must run without a model unless its `admitModelCall` admits them. The package's `subagent` and `classify` tools set it.
Tools whose host handlers call a model are yours to mark, for example a `makeKnowledgeLookupTool`
whose search embeds the query: `{ ...makeKnowledgeLookupTool(handlers), invokesModel: true }`.

## Ledger writes for re-executed steps [#ledger-writes-for-re-executed-steps]

Durable hosts re-execute steps: Vercel Workflow's queue is at-least-once, so a tool-batch step
runs again after a crash and sometimes concurrently with a first execution that is still running.
Pass a durable ledger when you resolve tools and every ledgered call runs at most once per key. By
default that is every non-`read` call, including the nested calls of a
[code mode](../integrations/code-mode#survive-step-re-execution) script, plus the built-in
`subagent` tool (a `read` tool whose child run could otherwise repeat its writes). Input and
interaction tools are never ledgered: their at-most-once guarantee is your `InteractionHost`
receipts.

A `write` tool that also reads (one tool with `list` and `update` operations, say) can mark its
read-only calls with `isReadCall`. Those calls are not ledgered: re-running a read is safe, while a
ledgered read that crashed before recording its outcome would be refused on every retry as possibly
applied. Code mode records their access as `read`. A call whose arguments do not decode counts as
a read too: it runs nothing and answers with its validation error, never a ledger refusal.

```ts
makeTool({
  name: 'tasks',
  parameters: TasksParams,
  access: 'write',
  isReadCall: params => params.operation === 'list' || params.operation === 'get',
  execute
})
```

Fragment: `db`, `modules`, `requestContext`, `runId`, and `stepDeadlineMs` are host-owned.

```ts
import { Effect } from 'effect'
import { classifyToolLedgerEntry, resolveTools, type ToolLedgerStore } from '@yolk-sdk/agent/tools'

// Your storage, scoped to one run. `db` is host code (for example Drizzle over Postgres) returning
// interruptible Effects (`Effect.tryPromise` passing the AbortSignal to the driver), and leases
// use the database clock: `now() + leaseMs`, classified against `now()`.
const makeRunToolLedger = (runId: string): ToolLedgerStore => ({
  scope: runId,
  // Atomic: insert a claimed entry if the key is absent, else classify the stored entry.
  claim: request =>
    db.claimToolCall(runId, request, (entry, dbNowMs) => classifyToolLedgerEntry(entry, dbNowMs)),
  // Extend the lease to now() + leaseMs only while the entry has no outcome.
  heartbeat: ({ key, leaseMs }) => db.extendLeaseIfClaimed(runId, key, leaseMs),
  // Record the outcome once; ignore later completions.
  complete: ({ key, outcome, completedAtMs }) =>
    db.completeOnce(runId, key, outcome, completedAtMs),
  // Entries whose parentKey is the given key (a script's nested calls).
  list: parentKey => db.listChildren(runId, parentKey)
})

const resolveStepTools = Effect.gen(function* () {
  return yield* resolveTools(modules, requestContext, {
    ledger: { store: makeRunToolLedger(runId), deadline: () => stepDeadlineMs }
  })
})
```

| Claim       | When                                           | Result                                                                        |
| ----------- | ---------------------------------------------- | ----------------------------------------------------------------------------- |
| `Fresh`     | first execution of the key                     | runs, heartbeats its lease, stores the outcome                                |
| `Completed` | an outcome is stored                           | returns the stored result (or the stored `ToolError`), no run                 |
| `InFlight`  | another execution holds a live lease           | waits for it up to `maxWaitMs`/`deadline`; never runs                         |
| `Abandoned` | the lease expired without an outcome (a crash) | never runs; tells the model it may already have been applied and to verify it |

* Keys are `call.id`, and `<parentCallId>/<seq>` for nested calls. Call ids must be unique within
  a ledger scope: a reused id with the same arguments replays the earlier result. Scope the store
  to one run (add the turn or step if your provider can reuse call ids across turns).
* Persist `ToolLedgerEntry` with `Schema.toCodecJson(ToolLedgerEntry)`, or store every claim field:
  `args` is an 8 KiB audit preview (`argsTruncated` says it was cut) and `argsDigest` is the SHA-256
  of the full arguments' canonical JSON. A different tool name or `argsDigest` under the same key is
  a model-visible conflict; never compare the preview. `argsDigest` is a stable format (store it as
  text, for example `char(64)`): lower-case hex SHA-256 of the UTF-8 canonical JSON of the raw
  `call.params`, with object keys sorted by UTF-16 code units and `JSON.stringify` number and string
  rules. It is a conflict fingerprint, not a security boundary: unserializable arguments share one
  digest, and integers beyond 2^53 lose precision before hashing. Stored results are bounded
  (`maxResultBytes`, default 1 MiB, measured on the serialized JSON) and wire-safe; the live call
  still returns the full result.
* Tool executors receive `idempotencyKey` (`<scope>:<key>`), stable across re-executions. Pass it
  to external APIs that deduplicate, which covers a crash between their commit and `complete`.
  Custom executor or registration wrappers must forward `idempotencyKey` (like `nested`).
* Pick one clock per store. `claim` and `heartbeat` receive both `leaseMs` (for stores that use
  their own clock, such as a database `now()`) and `nowMs`/`leaseExpiresAtMs` from the caller's
  `Clock` (for clock-agnostic stores, such as the in-memory one). Database time avoids clock skew
  between step instances.
* Change which calls are ledgered with `isLedgered`. Include your own delegation tools, for
  example `input => defaultToolLedgerPolicy(input) || input.call.name === 'delegate'`. Without
  `ledger`, execution is unchanged.
* Waits, store polls included, end at `maxWaitMs` or `deadline` (one final poll runs halfway through
  the last interval); a failed poll fails closed. Each of up to three `complete` attempts is
  bounded to 5 s; an outcome that cannot be recorded reads as abandoned. Each `heartbeat` is
  bounded to 5 s or a sixth of `leaseMs`, whichever is shorter, and `heartbeatIntervalMs` is
  clamped to half the lease minus that bound. A heartbeat that failed or timed out is retried one
  heartbeat timeout later (one interval, when that is shorter), so one failed or hung heartbeat
  does not let the lease of a running call lapse, provided the claim and the heartbeat before it
  are fast and `leaseMs` is at least 4 ms: the retry lands about a sixth of the lease or more before
  it ends (5 s at the defaults, 10 s + 3 × 5 s = 25 s of 30 s). While heartbeats land, they run one
  interval apart. That is a margin for one late heartbeat at a time, not a guarantee: a stalled
  process, two late heartbeats in a row, or a slow success followed by a hang (still zero margin
  at the defaults) can still let the lease lapse.
* Store latency: each `heartbeat`, and the `claim`, must answer in less than
  `min(5 s, leaseMs / 6)`. On a short lease a slower store has every heartbeat cut at that bound
  (a 6 s lease with 1.2 s heartbeats is cut at 1 s each time) and the lease lapses; give a slow
  store a longer lease.
* `deadline` bounds only waiting for a duplicate. A call that runs is not cut at it, and recording
  its outcome can take up to about 15 s (three 5 s attempts) after the call returns, so reserve
  that finalization time before the platform stops the step.
* Store operations (`claim`, `heartbeat`, `complete`, `list`) must be interruptible, for example
  `Effect.tryPromise` passing the `AbortSignal` to the driver. The ledger's timeouts interrupt the
  operation and wait for it to stop, so uninterruptible store work holds the wait, heartbeat, or
  completion until it ends.
* `onLedgerDecision({ key, parentKey?, toolName, decision, waitedMs? })` reports each ledgered
  call's decision (`fresh`, `completed`, `in_flight_wait`, `in_flight_timeout`, `abandoned`,
  `conflict`) for logs and metrics, for example to count replays. It never affects execution:
  errors are logged and ignored.
* `makeInMemoryToolLedgerStore()` is for tests and single-process hosts only.

| `ledger` option       | Default                                   | Meaning                                         |
| --------------------- | ----------------------------------------- | ----------------------------------------------- |
| `store`               | required                                  | host-implemented `ToolLedgerStore`              |
| `isLedgered`          | `defaultToolLedgerPolicy`                 | which calls are ledgered (`readCall` input)     |
| `leaseMs`             | `defaultToolLedgerLeaseMs` (30 s)         | lease of a running call                         |
| `heartbeatIntervalMs` | a third of `leaseMs` (clamped, see above) | how often a running call renews its lease       |
| `pollIntervalMs`      | `defaultToolLedgerPollIntervalMs` (1 s)   | how often a duplicate polls an in-flight call   |
| `maxWaitMs`           | `defaultToolLedgerMaxWaitMs` (150 s)      | longest wait for an in-flight call              |
| `deadline`            | none                                      | epoch ms after which a duplicate stops waiting  |
| `maxResultBytes`      | `defaultToolLedgerMaxResultBytes` (1 MiB) | bound on a stored result's serialized JSON      |
| `onLedgerDecision`    | none                                      | one `ToolLedgerDecisionEvent` per ledgered call |

Argument previews are cut at `toolLedgerMaxArgsBytes` (8 KiB).

Pass `files: { store, maxFileBytes? }` to `resolveTools` as well to capture file bytes before the
ledger stores a result: results then hold `fileId` labels and `ToolResult.files`, and a reduced
stored result keeps its file labels. See [Move files between tools](../integrations/files).

## Ask a human [#ask-a-human]

Human-in-the-loop is protocol-level:

* approval requests pause with `AgentAwaitingInput`
* question tools pause with structured options
* clients resume through typed HITL responses

The SDK owns generic event and response shape. Hosts own UI, auth, request matching, audit, and policy.

Use the built-in question tool when the model needs a user choice. Use approval policy when a normal tool call needs permission before execution.

## Preview the change [#preview-the-change]

An approval-gated tool can describe what one call would change, so a person reviews a
before → after diff instead of raw arguments. The same hook previews direct approvals, sibling
approvals in one turn, and [staged plan reviews](#review-a-staged-plan), and every host renders it
with one tool-agnostic component.

Fragment: `UpdateRecordParams`, `HostContext`, `context.records`, and `applyUpdate` are host-owned.

```ts
import { Effect } from 'effect'
import { ToolApprovalPolicy } from '@yolk-sdk/agent/protocol'
import {
  makeTool,
  resolveTools,
  ToolChangePreview,
  ToolTextChange,
  ToolValueChange
} from '@yolk-sdk/agent/tools'

const updateRecord = makeTool<HostContext, typeof UpdateRecordParams>({
  name: 'update_record',
  description: 'Update a record.',
  parameters: UpdateRecordParams,
  access: 'write',
  approval: ToolApprovalPolicy.make({ mode: 'manual' }),
  // Side-effect free: read the current state and describe the change.
  changePreview: ({ params, context }) =>
    context.records.get(params.id).pipe(
      Effect.map(record =>
        ToolChangePreview.make({
          target: { label: record.title, kind: 'record', id: record.id, href: record.url },
          changes: [
            ToolValueChange.make({
              field: 'status',
              label: 'Status',
              before: record.status,
              after: params.status
            }),
            ToolTextChange.make({
              field: 'body',
              label: 'Body',
              before: record.body,
              after: params.body
            })
          ],
          // Shown with a selectable call. Use `blocked` for what `staging.precheck` rejects.
          warnings: record.archived ? ['The record is archived.'] : []
        })
      )
    ),
  execute: input => applyUpdate(input)
})

const toolSet =
  yield *
  resolveTools(modules, context, {
    changePreview: { maxBytes: 32 * 1024 } // optional; default 16 KiB per preview, 5 s timeout
  })
```

Pass `approvalPreviews: toolSet.approvalPreviews` to `run`, `runToolBatch`, `prepareToolBatch`, or
the runtime config, next to `inputs` and `interactions`. A pending `ToolApprovalRequest` then
carries `preview` (a `ToolChangePreview`) or `previewError` (`{ cause, message }`; `cause` is
`failed`, `invalid`, `too_large`, or `timeout`). Render `request.preview` when present, else the
raw `request.call.params`. Once the call settles, render its result instead of the pending diff:
an approved call that ran shows the `after` state, and a denied call shows "not applied".

A `ToolChangePreview` is `{ target, summary?, changes, warnings?, blocked? }`. Each change has a
`field`, a display `label`, and one of five shapes:

| `_tag`       | Shape                                      | Render as                                |
| ------------ | ------------------------------------------ | ---------------------------------------- |
| `Value`      | `before?`, `after`: short scalar or `null` | old → new                                |
| `Text`       | `before?`, `after`: string                 | a text diff                              |
| `Set`        | `added`, `removed`, `unchanged?` items     | + / − chips                              |
| `List`       | `before?`, `after`: ordered items          | an ordered list diff                     |
| `Structured` | `before?`, `after`: JSON, `summary?`       | your structural renderer, or the summary |

Items are `{ id, label }`. An absent `before` means unknown or new; `null` means known empty. An
empty `changes` means the call changes nothing.

* **Display only.** The approval binds to the call (`approval:<callId>`), never to the preview. The
  arguments stay the source of truth for what runs, and the tool's own write stays authoritative.
  `warnings` are shown with a selectable call; `blocked` marks a call that cannot apply as
  requested (recommend denying it). For staged plans, `staging.precheck` is the authority:
  express the same condition in `blocked`.
* **Failures never block approval.** A failing, slow (`timeoutMs`), invalid, or oversized preview
  becomes `previewError`; invalid arguments report an error without calling the hook.
* **Bounded.** Previews larger than `maxBytes` (compact JSON) are truncated deterministically and
  never silently: `Set.unchanged` goes first, then values are capped at an equal share. Cut
  strings and item arrays keep one window, which for a `before`/`after` pair starts shortly before
  their first difference; a cut `Structured` value becomes `null`. Each cut value has a
  `truncated` marker with `unit` (`chars`, `items`, `bytes`), `originalSize`, and an optional
  `offset` (absent: 0). Check `truncated` before rendering a `Structured` `null`. Labels, the
  target, `summary`, `warnings`, and `blocked` are never cut: a preview they alone push past the
  bound reports `previewError` (`too_large`).
* **When it is computed.** Previews run server-side when the approval request is raised, at most
  8 at a time per batch, against the state before any call of the batch runs. Two siblings that
  touch the same record are both previewed against its current state. Durable hosts that resume
  one response per round re-raise the remaining siblings, recomputing their previews: render the
  latest `ToolApprovalRequested` for a call. Each preview is up to `maxBytes` and appears in
  `ToolApprovalRequested` and `AgentAwaitingInput.requests`; size durable event storage for it.
* **Group repeated changes.** `toolChangeSignature(preview)` is a stable digest of `changes`
  (ignoring the target, `Set.unchanged`, and `Set` order). `groupToolChangePreviews` groups
  `{ toolName, preview }` entries so you can show "add X on 120 records" once. Truncated
  previews are never grouped.
* Voice approvals do not compute previews.

## Collect typed input [#collect-typed-input]

Use `makeInputTool` when the model needs structured user data (such as a draft or form). Questions remain the built-in option/free-text UI; custom inputs use app-owned renderers. Input tools share the HITL lifecycle: the loop pauses with `AgentAwaitingInput`, your UI renders by kind, and you resume with a typed `InputResponse`.

```ts
import { Schema } from 'effect'
import { makeInputTool } from '@yolk-sdk/agent/tools'

const DraftResponse = Schema.Struct({
  to: Schema.String,
  subject: Schema.String,
  body: Schema.String
})

export const draftTool = makeInputTool({
  name: 'compose_draft',
  description: 'Collect an email draft from the user.',
  response: DraftResponse,
  renderer: 'draft-composer',
  title: 'Compose draft'
})
```

Rules:

* `response` is the server Effect Schema that validates user payloads; the `ToolDef` carries only display metadata (`kind`, `title?`, `description?`, display-only JSON Schema hint). Never validate against the lowered hint.
* Input tools never take approval/background options and never execute through direct dispatch; they complete only through HITL resume with JSON-only (`Schema.Json`) payloads.
* Resolve with `resolveTools`, then pass `toolSet.inputs` explicitly into `run`/`runToolBatch`/`prepareToolBatch`/`runRuntime` configs. Without them, input tools fail closed as model-visible `unavailable` errors.
* Render pending input from `InputRequested` by `input.kind` through host-owned components; submit via `streamInputResponseEventStream`, the `InputResponseInput` WebSocket message, `AppendHitlResponse`, or React `submitInputResponse`. Echo `requestId`/`toolCallId` opaquely.
* `callParameters` validates model-supplied context before opening the request (defaults to no arguments). Invalid user payloads re-pend the same request for correction. The first valid submission or cancellation settles it; stale/duplicate responses cannot replace it. React keeps the form pending until server acceptance, including after transport failures.
* Voice sessions deny input tools; omit them from subagents and other hosts without nested HITL resume.

## Authorize one action [#authorize-one-action]

`makeInteractionTool` lets a person review proposed values, edit them, and authorize one
server-defined action, such as Publish or Archive. It is distinct from data-only `makeInputTool`.
Opt in only on surfaces with an authenticated, durable host adapter and an app-owned renderer.

Registration fragment (the host supplies the document service and renderer):

```ts
import { Effect, Schema } from 'effect'
import type { ToolError } from '@yolk-sdk/agent/loop'
import {
  makeInteractionTool,
  type InteractionActionResult,
  type ToolModule
} from '@yolk-sdk/agent/tools'

const DocumentDraft = Schema.Struct({ title: Schema.String, body: Schema.String })

type DocumentContext = {
  readonly publish: (
    data: typeof DocumentDraft.Type,
    submissionId: string
  ) => Effect.Effect<InteractionActionResult, ToolError>
  readonly archive: (
    data: typeof DocumentDraft.Type,
    submissionId: string
  ) => Effect.Effect<InteractionActionResult, ToolError>
}

export const documents: ToolModule<DocumentContext> = {
  id: 'documents',
  tools: [
    makeInteractionTool({
      name: 'document',
      description: 'Review and file a document.',
      access: 'write',
      callParameters: Schema.Struct({ folder: Schema.String }),
      response: DocumentDraft,
      renderer: 'document-editor',
      title: 'Review document',
      actions: {
        publish: {
          label: 'Publish',
          execute: ({ data, context, submissionId }) => context.publish(data, submissionId)
        },
        archive: {
          label: 'Archive',
          execute: ({ data, context, submissionId }) => context.archive(data, submissionId)
        }
      }
    })
  ]
}
```

Callbacks infer `data` from `response` and `call.params` from `callParameters`. Original Effect
schemas validate both; provider JSON Schema is display/model guidance only. V1 supports
JSON-preserving schemas: excess, missing and invalid values are rejected, as are nested
normalization/defaults/transforms that change the exact consented JSON. `null`, `false` and `0`
are valid when the schema admits them; absence is not.

### Accept on the host before execution [#accept-on-the-host-before-execution]

The host owns authentication, pending ownership, session/run/generation, current account policy,
renderers and storage. A click, `source: 'user'`, raw `InteractionResponse`, transcript entry or
opaque ID does **not** authorize execution.

Integration fragment; `host` and `scopedReceipts` below are explicitly **host-owned** services,
not Yolk exports:

```ts
import { Effect } from 'effect'
import { validateInteractionSubmission, type InteractionResponse } from '@yolk-sdk/agent/protocol'
import { resolveTools } from '@yolk-sdk/agent/tools'

const acceptResponse = (response: InteractionResponse) =>
  Effect.gen(function* () {
    const actor = yield* host.authenticate()
    const pending = yield* host.pendingOwnedBy(actor, response.requestId)
    const context = yield* host.freshDocumentContext(actor)
    // Bind the receipt port to THIS active session/run/pending generation, never a
    // global model-supplied call-ID lookup.
    const scopedReceipts = host.receiptsFor(pending.scope)
    const toolSet = yield* resolveTools([documents], context, { interactionHost: scopedReceipts })
    const interaction = toolSet.interactions[pending.call.name]
    if (interaction === undefined) return yield* host.unavailable()
    const candidate = yield* validateInteractionSubmission({
      request: pending.request,
      response,
      ...interaction
    })
    // Host transaction: recheck scope/ownership and atomically choose the first valid
    // submission across ALL actions and cancellation. Persist an immutable full binding
    // beside a unique host-allocated submission ID. Invalid attempts consume nothing.
    yield* host.acceptTransaction({ actor, pending, candidate, response })
    // Only now append/resume; transport submission alone is not acceptance.
    return toolSet
  })
```

Optional action `validate` is called by the resolved `validateAction` during admission,
with fresh bound context and no business effects. Use `InteractionValidationError` from
`@yolk-sdk/agent/protocol` for an expected business rejection; the person can edit or cancel.
Validation is not authentication and is rechecked before new execution.

`InteractionHost` is a port over host storage, not an SDK storage engine:

* `read(slot)` returns an independent immutable accepted/started/settled receipt, including the
  original call, selected action and exact final data. Scope is already bound in the adapter.
* `claim(ref)` only advances **existing accepted → started** atomically and returns the same
  binding with a fencing token. It must never manufacture acceptance. Concurrent losers and
  abandoned started records cannot take over or resend.
* `settle(token, outcome)` is token-fenced and idempotent. It validates receipt identity and
  never overwrites a settled result. A lost acknowledgement may replay completed on retry,
  but never licenses another dispatch.

The protocol subpath exports `validInteractionReceipt`, `sameInteractionBinding`,
`sameInteractionCall`, and `interactionJsonEquals` for adapter binding and settlement checks.
These pure checks do not authenticate storage records or replace host ownership checks.

Submission IDs are unique host-owned identities, not authentication or globally safe
payload-derived provider idempotency keys. All actions and cancellation compete for one slot;
identical retries reuse acceptance, changed action/data/call conflict. Built-in cancellation
rejects action/data, requires no valid form (even after schema changes), and executes no business
handler. The host records cancellation as a settled receipt with an error tool result whose
`structuredContent` is `{ type: 'interaction_outcome', requestId, slot, submissionId, outcome: 'cancelled' }`.

### Resume and replay [#resume-and-replay]

Pass **both** `toolSet.interactions` and `toolSet.interactionHost` into `run`, `runToolBatch` or
runtime config. The executor layer still comes from `makeToolExecutorLayer(toolSet)`. Without a
host adapter, forms are unavailable rather than executing through an in-memory fallback.
If a form keeps reappearing after acceptance, check that the same scoped `interactionHost`
is passed to the loop/runtime, not only to `resolveTools`: without it the loop cannot load
accepted receipts. Durable preflight must load and pass fresh receipt snapshots.

Durable preflight fragment:

```ts
import { loadInteractionReceipts, prepareToolBatch } from '@yolk-sdk/agent/loop'

const interactionReceipts = yield * loadInteractionReceipts(calls, toolSet.interactionHost)
const prepared =
  yield *
  prepareToolBatch({
    calls,
    tools: toolSet.tools,
    inputs: toolSet.inputs,
    interactions: toolSet.interactions,
    interactionReceipts,
    responses: hitlResponses
  })
// Do not dispatch ANY sibling while prepared.pendingRequests is nonempty.
// Forward prepared.interactionBindings.get(call.id) as { interaction: ref } to
// ToolExecutor.execute. Dropping the ref fails closed.
```

Preparation only validates and plans: no receipt reads, claims, settlements or actions. Load
fresh snapshots before every preparation boundary. A call validator may read host storage (the
plan review reads the plan store); when that storage is unavailable it fails with
`InteractionHostError` and `prepareToolBatch` fails with a `ToolError` `unavailable`, like
`loadInteractionReceipts`: retry the step. An accepted receipt whose call no longer validates is
still dispatched, so the executor can re-read the receipt and report a delivery that already
started or settled it. Historical receipts replay before current
schemas/actions, even if a tool is removed or disabled; a missing handler can never start new
work. The executor re-reads and validates the full receipt binding, then runs only its chosen
action/data, before the next model turn. No extra approval or ambient permission is introduced.

### Observe truthful outcomes [#observe-truthful-outcomes]

`InteractionSubmitted` is authoritative acceptance, **not completion**. It stays active until
a real server result. Local submit remains pending; neither acceptance nor transcripts synthesize
completed tool results. Submit transport options are `streamInteractionResponseEventStream`,
`InteractionResponseInput`, `AppendHitlResponse` or React `submitInteractionResponse`; these do
not replace the authenticated host acceptance step.

Action results distinguish `completed`, explicit `failed` (known no effect), and `unknown`.
Escaped post-dispatch failures, including `ModelVisibleToolError` timeouts, are **unknown**, not
proof of failure. Defects and interruption retain their original Cause while a bounded finalizer
attempts uncertainty settlement. Host callbacks must cooperate with interruption. Unknown
results carry receipt identity, `isError: true`, and explicit text that the action may have happened
and must not be retried automatically, including rich content. Headless result metadata preserves
`outcome: 'unknown'` separately from `failed`.

Hosts own reconciliation, external-provider idempotency and warnings against separately consented
duplicates. Voice/realtime, background activation and hosts without authenticated receipt storage
remain unsupported. This API does not promise exactly-once external effects.

## Review a staged plan [#review-a-staged-plan]

A [code mode](../integrations/code-mode#stage-approval-gated-writes) script can stage calls of
approval-gated tools marked `staging` instead of running them. `makePlanReviewTool` is the
interaction a person uses to review that plan once and select the calls to apply. It reuses the
authorization flow above: host acceptance, receipts, claim and settle.

```ts
import { makePlanReviewTool, resolveTools } from '@yolk-sdk/agent/tools'

const reviewPlan = makePlanReviewTool<HostContext>({
  // The only per-call authority hook for applied calls (see below).
  beforeCall: ({ call, context }) => authorizeWrite(context, call), // host-owned
  onFailure: 'stop' // default; 'continue' runs the remaining selected calls
})

const resolveHostTools = (context: HostContext) =>
  resolveTools([{ id: 'host', tools: [codemode, reviewPlan] }, ...hostModules], context, {
    interactionHost: scopedReceipts, // host-owned
    plans: {
      store: planStore, // host-owned ToolPlanStore, scoped to the conversation
      // Provider call ids can repeat across turns: make plan ids unique and stable.
      planId: ({ call }) => `${context.runId}:${context.turn}:${call.id}` // host-owned values
    }
  })
```

* The model calls `review_plan({ planId, planDigest })` with the values the script reported. Call
  validation loads the plan from the store: present, in scope, digests matching, not yet applied.
* Render the `tool_plan_review` kind with
  `previewStoredToolPlan({ toolSet, planId, planDigest, offset })`: one page of at most 50 calls,
  each with its staged `params` and the tool's [change preview](#preview-the-change) (`preview`,
  or `previewError` when it failed), plus `nextOffset` and whether a review already claimed the
  plan. The results are plain JSON; decode them with the exported `ToolPlanPreviewPage` Schema on
  the client. Group identical changes across all pages with `groupToolChangePreviews`.
* The person submits action `apply` with `{ selectedKeys }`, a non-empty subset of the staged
  keys; they can untick calls but never change arguments. Cancel applies nothing.
* Admission (`validateInteractionSubmission`) checks the selection with your fresh context: no
  duplicates, keys of the plan, tools still stageable, and each tool's `staging.precheck` (at most
  8 at a time). Keep prechecks cheap; make the tool's own write a compare-and-set for
  correctness.
* On execution Yolk re-reads the receipt, claims the plan once (`ToolPlanStore.claim`), and runs
  the selected calls in staged order through the resolved execute path and ledger, with ids
  `<reviewCallId>/<n>`. The result lists each call as `applied`, `failed`, `skipped`, `not_run`,
  `unknown`, or `input_required` in `structuredContent.result` (`state` is `applied`, `refused`, or
  `interrupted`); decode it with the `ToolPlanOutcome` Schema.
* An `input_required` call ran and [paused for a person's input](#finish-calls-that-paused-for-input):
  it has not completed, carries its `inputRequired` ref (`{ reviewToolName, pauseIds }`), and never
  stops the apply under `onFailure: 'stop'`. The result text names the review call that finishes
  it. `ToolPlanCallCounts.input_required` is optional, so outcomes recorded before it still decode.
* **Per-call authority:** applied calls run inside the review action, so code mode's
  `beforeNestedCall` and decorators around your `ToolExecutor` never see them. `beforeCall` is the
  only per-call hook: wire the same run-authority or write authorizer you use for nested calls.
  `beforeCall` and any custom `planReview` handler are trusted host code.
* Steps can be redelivered while the first execution is still applying (Vercel queues are
  at-least-once). With a tool ledger, each apply runs behind a ledger entry for the review call: a
  redelivery waits for the running apply (up to the ledger's `maxWaitMs` or `deadline`) and returns
  its real outcome. If the wait ends first, or the apply crashed, it returns an `unknown` outcome
  listing each staged call (or `failed` when Yolk proves nothing ran); a call is `not_run` only when Yolk can prove it never ran and never
  will, otherwise `unknown`. The apply is never run twice. Give the ledger wait room for your
  largest plan.
* A plan store outage is never a verdict: loop preflight fails the batch with an `unavailable`
  `ToolError` (retry the step; the review stays accepted), admission answers
  `InteractionAdmissionError` `unavailable`, and an outage that starts mid-step fails the call
  closed. Once the receipt is claimed, an outage ends that review attempt with `failed` and nothing
  applied: when reading the receipt or plan or claiming the apply's ledger entry failed, the model
  is told the plan is unchanged and can open a new review; when claiming the plan itself failed,
  the plan may now be locked against further reviews. A delivery that finds
  the receipt already started or settled by another delivery reports that outcome instead of an
  invalid-arguments error.
* The apply's ledger entry must be visible to every redelivery of the review step: resolve the
  review step with the same ledger scope each time and keep ledger entries at least as long as the
  review receipts.
* Calls apply one after another in one tool step: keep plans small enough to fit your step budget
  (lower `staging.maxCalls` on the code mode tool).
* After the review settles, show each call from `ToolPlanOutcome.calls`, not the pending diff:
  `applied` shows the `after` state, `skipped`, `not_run`, and `failed` show "not applied" with no
  pending diff, `unknown` says the call may have been applied, and `input_required` says it waits
  for a person's input.

`ToolPlanStore` is a port over host storage:

* `put` is atomic insert-or-compare by plan id (for example `INSERT ... ON CONFLICT DO NOTHING`,
  then compare digests): the same digest is a no-op, another digest a `conflict`.
* `get` returns the plan and its claim.
* `claim({ planId, submissionId })` is one conditional update (`... WHERE claimed_by IS NULL`)
  returning `claimed`, `same`, or `taken`; a plan is applied at most once. Submission ids must be
  unique within the store scope.
* JSON(B) columns are safe: digests use canonical JSON (sorted keys). Decode stored plans with
  `Schema.toCodecJson(ToolPlan)`.
* Retention is yours: unreviewed plans are inert, so expire them after the review window; keep
  claimed plans as long as the ledger entries they explain.

`makeInMemoryToolPlanStore` is a non-durable reference. There is no atomic batch: a partial apply
reports exactly which calls ran.

## Finish calls that paused for input [#finish-calls-that-paused-for-input]

A remote system can pause a call after it was made: an MCP server answers a `tools/call` with a
form (for example a confirmation before a delete) and finishes only when the form is answered.
A tool's `execute` never pauses. It stores the pause in host storage and returns an
input-required result; a person later answers through the input review interaction, whose action
resumes each stored pause once
([ADR 0014](https://github.com/magoz/yolk-sdk/blob/main/docs/adr/0014-input-required-tool-calls.md)).
For MCP tools, see [Finish calls that ask for input](../integrations/mcp-tools#finish-calls-that-ask-for-input).

Fragment: `pauseStore` is host-owned.

```ts
import { makeInputRequiredToolResult } from '@yolk-sdk/agent/protocol'
import { inputReviewToolName } from '@yolk-sdk/agent/tools'

// In the tool's execute, after the remote system paused the call:
const pauseId = yield * pauseStore.save({ call, pause: remotePause }) // host-owned

return makeInputRequiredToolResult({
  toolCallId: call.id,
  content: 'The server asks to confirm deleting invoice 42.',
  reviewToolName: inputReviewToolName, // 'review_input'
  pauseIds: [pauseId]
})
```

The result is an error result whose `structuredContent` is
`{ code: 'input_required', inputRequired: { reviewToolName, pauseIds } }`, and its content tells the
model to call `review_input({ pauseIds })` and not to call the tool again. Being an error result,
the call is over: output checks skip it, the [tool ledger](#ledger-writes-for-re-executed-steps)
records it (it never runs again), [code mode](../integrations/code-mode#what-scripts-see) rejects
the nested call with `error.code === 'input_required'`, and a staged plan reports it
`input_required`. `toolInputRequired(result)` reads the ref back (`Option<ToolInputRequiredRef>`);
`mergeInputRequiredRefs` merges refs per review tool and splits them into reviews of at most
`maxInputReviewPauses` (50); `inputRequiredNotice` renders the model-visible notice, listing every
review to call in turn. A remote MCP error result never carries the marker: Yolk's MCP
client keeps such content under `remoteStructuredContent`.

Register one input review tool next to your other interactions. Fragment: the `pauseStore` methods
are host-owned.

```ts
import {
  makeInputReviewTool,
  resolveTools,
  type InputPause,
  type InputReviewHost
} from '@yolk-sdk/agent/tools'

// Your stored pause: `id`, a person-readable `label`, and whatever resuming needs.
type HostPause = InputPause & { readonly form: RemoteForm }

const pauses: InputReviewHost<HostPause> = {
  // The listed pauses, in order: in this session's scope and still waiting.
  load: pauseIds => pauseStore.loadWaiting(pauseIds),
  // Side-effect free: does the answer fit the pause's form?
  validateAnswer: ({ pause, answer }) => pauseStore.check(pause, answer),
  // Claim the pause for `submissionId`, send once, record and return an InputPauseResolution.
  resume: ({ pause, answer, submissionId }) => pauseStore.resumeOnce(pause, answer, submissionId),
  // Optional: the recorded resolutions of a review that crashed after its claim.
  recorded: ({ pauseIds, submissionId }) => pauseStore.recorded(pauseIds, submissionId)
}

const toolSet =
  yield *
  resolveTools(
    [{ id: 'host', tools: [makeInputReviewTool<HostContext, HostPause>({ host: pauses })] }],
    context,
    { interactionHost: scopedReceipts } // host-owned
  )
```

* The model calls `review_input({ pauseIds })` (`InputReviewParams`: at most
  `maxInputReviewPauses`, 50, no repeats). Call validation loads them through `load`: a missing,
  foreign, or answered id is an `InteractionValidationError`, and a storage outage an
  `InteractionHostError`, never a verdict. The model passes only ids, so forms are rendered only
  from stored pauses.
* Render the `input_review` kind (`inputReviewRenderer`) from the stored pauses. The person submits
  action `submit` (`inputReviewActionId`, label `Send answers`) with `{ answers }`
  (`InputReviewResponse`): exactly one JSON answer per listed pause, keyed by pause id. Admission
  checks each with `validateAnswer`; an invalid answer is never accepted and consumes nothing.
  Cancel sends nothing, and the pauses stay reviewable.
* The action resumes the pauses in review order through `resume`. The host claims each pause before
  sending and never sends after a claim. `resume` answers an `InputPauseResolution`:
  `Completed({ result })` (the remote result, even an error result), `InputRequired({ pauseIds })`
  (asked again: the new pauses are stored), `NotSent({ message })` (refused before sending), or
  `Unknown({ message })` (it may have run; a claim found without a recorded resolution is this).
* The result lists every pause with its outcome, each completed call's own result content (files
  included), then the review call for any new pauses. `structuredContent.result` is an
  `InputReviewOutcome`: `{ type: 'input_review_outcome', pauses, interrupted? }`, each pause
  `{ pauseId, label, status, isError?, inputRequired?, error? }` with `status` `completed`,
  `input_required`, `not_sent`, or `unknown`. The interaction outcome is `unknown` when any pause is
  unknown, `failed` when none was sent, else `completed`.
* A review that started without a recorded outcome (a crash after the claim, or a redelivered step
  finding the receipt started) lists what `recorded` returns, with `interrupted: true`, and sends
  nothing again. Only a replay where every pause has a recorded resolution reports a proven outcome;
  without `recorded`, the result is a generic unknown notice.
* The original call stays input-required in the transcript; the review result is its completion. A
  script that needed the value continues in a new script from the review result, never by calling
  the tool again.
* Options: `name` (default `review_input`), `description`, `renderer`, `title`,
  `interactionDescription`, `actionLabel`, and `access` (default `write`: answers are sent to the
  system that paused the calls). Wire the interaction like any other: `interactionHost` in
  `resolveTools`, and `toolSet.interactions` plus `toolSet.interactionHost` in loop/runtime config.

## Let the model choose background execution [#let-the-model-choose-background-execution]

Any `makeTool` registration may opt into background execution with `background: true`. The flag is
inert on its own: definitions, schemas, approval ids, and inline execution stay byte-for-byte the
same until `resolveTools` receives a `backgroundHost`. Supply a host only when a real lifecycle
owner (for example a durable Workflow) will run, track, and eventually deliver the work.

```ts
import { Effect, Schema } from 'effect'
import { BackgroundToolAccepted } from '@yolk-sdk/agent/protocol'
import { makeTool, resolveTools, type BackgroundToolHost } from '@yolk-sdk/agent/tools'

export const reportTool = makeTool({
  name: 'build_report',
  description: 'Build a report. Choose background execution for long inputs.',
  parameters: Schema.Struct({ topic: Schema.String }),
  access: 'write',
  background: true,
  execute: () => Effect.succeed({ content: 'inline report' })
})

// Host-owned: durably admit the exact call and return a receipt, never a closure.
const backgroundHost: BackgroundToolHost<RequestContext> = {
  accept: ({ call, context }) =>
    hostReserveExecution({ callId: call.id, name: call.name, params: call.params, context }).pipe(
      Effect.map(execution =>
        BackgroundToolAccepted.make({ version: 1, executionId: execution.id })
      )
    )
}

const toolSet = await Effect.runPromise(
  resolveTools([{ id: 'local', tools: [reportTool] }], requestContext, { backgroundHost })
)
```

With a host, activated tools advertise a required envelope instead of their raw parameters:

```json
{ "execution": "foreground", "arguments": { "topic": "Q3" } }
```

The original schema nests under `arguments` unchanged (including tools whose own parameters are
named `execution`, `arguments`, or `background`), and `$defs` stay at the document root so nested
`#/$defs/...` references keep resolving through OpenAI and Anthropic lowering. Activation supports
only these document-root definition pointers (without percent-encoded fragments). Other `$ref`
forms (root `#`, anchors, `#/properties/...`, `#/definitions/...`, relative or external references)
and resource/anchor keywords (`$id`, legacy `id`, `$anchor`, `$dynamicAnchor`, `$dynamicRef`,
`$recursiveAnchor`, `$recursiveRef`) fail with `ToolRegistryError.cause: 'background_unsupported_schema'`.
This check visits schema positions, not literal defaults, examples, `const`, or `enum` data.
Without activation, schemas remain unchanged. The registry validates the envelope
and the original parameters without running business effects, strips the control fields, and then
either executes inline (`foreground`) or calls `host.accept`. Raw `ToolRegistration` objects must
provide a side-effect-free `validate` callback before they can activate; `resolveTools` fails
closed otherwise, as it does for the loop-owned `question` and `subagent` tools.

Acceptance returns one acknowledgement `ToolResult` for the original call with typed
`acceptance: { version: 1, executionId }` metadata. The loop emits `ToolExecutionAccepted` instead
of `ToolExecutionCompleted`, records no usage, and continues the model turn. Client state, chat
projection, and tool cards treat `Accepted` as settled, non-error, and not completed. Stale client
Started/input events for an accepted call cannot reopen it.

Activated `background-v1` definitions are **unsupported in voice/realtime**, even when a call chooses
`foreground`. Resolve voice toolsets without a background host. `toOpenAiRealtimeTool` and both
realtime session config builders throw `VoiceToolBridgeError` rather than advertise activated tools.
`decideVoiceToolCall` denies them and `handleVoiceToolCall` returns `Denied` before approval matching,
including replayed approvals. The low-level `executeVoiceToolCall` bridge also rejects activated
registry dispatch before validation, inline execution, or host admission. Ordinary voice tools,
including inert `background: true` definitions without a host, retain their existing behavior.

Host responsibilities:

* `accept` must be idempotent per call id so step retries recover the same receipt.
* Own authorization, cancellation, status/wait tools, terminal storage, usage accounting, and delivery.
* Never append a second result for the original call; deliver terminal output through distinct
  status/wait tool-call ids or a later host continuation.
* Fail `accept` with a `ToolError` to decline; the registry never falls back to inline execution.

Manual approval still fences the whole batch before any launch. For activated calls the approval
`requestId` binds the tool name, execution mode, and canonical arguments, so an approval cannot be
reused for a different payload or mode; a malformed envelope is rejected before anyone is asked.
Non-activated tools keep the legacy `approval:<callId>` identity.

## Spawn a subagent [#spawn-a-subagent]

The `subagent` tool contract is domain-free. Hosts provide child execution, prompts, models, tools,
and recursion policy. Current v1 subagents should not receive the `subagent` tool recursively unless
explicitly enabled in a future capability.

Use `subagentResultFromEvents` to extract final or awaiting-input text, status, HITL requests,
usage, turns, and typed `AgentError` details from child events. Pass that metadata to
`makeSubagentToolResult`. Durable hosts
can call `subagentUsageFromToolResult` on completed tool results and add the returned child usage to
their cumulative workflow usage. If a host does not implement nested HITL resume, omit approval- and
question-gated tools from child toolsets rather than returning an unresumable `awaiting_input` result.

### Background subagents [#background-subagents]

Background execution is opt-in. Set `background: true` in `makeSubagentToolModule` or
`makeNonRecursiveSubagentToolModule` registration options to advertise the optional `background`
model parameter. This does not launch work by itself: your executor must handle `params.background`
and durably start the child. Omitted registration opt-in preserves the inline contract.

After a successful background launch, return `makeSubagentAcceptedToolResult` instead of a final
child result. Host executor fragment; `hostStartChild` and `hostRunInlineChild` are host-owned
implementations:

```ts
import { Effect } from 'effect'
import { makeSubagentAcceptedToolResult } from '@yolk-sdk/agent/tools'

const execute = input =>
  Effect.gen(function* () {
    if (input.params.background !== true) return yield* hostRunInlineChild(input)
    const child = yield* hostStartChild(input)
    return makeSubagentAcceptedToolResult({
      callId: input.call.id,
      workflowRunId: child.runId
    })
  })
```

Acceptance completes the launch tool call, not the child. It emits no `SubagentCompleted` or child
usage. Keep logical `subagent:<callId>` identity separate from the physical Workflow run id.
Hosts may deliver later findings automatically or expose their own authenticated observation tools;
when observations are separate calls, use distinct tool-call ids rather than a second result for the
original launch call. Do not charge the same child usage again.

The SDK registers no status or wait tools and does not promise automatic completion delivery. Your
host owns its completion policy, authenticated child lookup/routes, durable
admission/reservations/results, child HITL handling, and explicit Stop/cancellation policy. Do not
infer that parent completion or failure cancels an independent child. Preserve any lookup identity
the model needs in model-visible content when customizing the acknowledgement.

For durable hosts, see [Independent child orchestration](../vercel-workflows/step-contracts#independent-child-orchestration).

### Nonterminal child observations [#nonterminal-child-observations]

If a host finishes observing a `subagent` call while the child's outcome is still running or
unknown, return a nonterminal observation rather than inventing a final child result. Host
executor fragment; `hostChildRunId` is the authorized physical recovery handle:

```ts
import { ToolResult } from '@yolk-sdk/agent/protocol'

const observation = ToolResult.make({
  toolCallId: input.call.id,
  content: 'Child is still running; use the recovery handle to observe it later.',
  structuredContent: {
    type: 'subagent_observation',
    subagent_run_id: `subagent:${input.call.id}`,
    workflow_run_id: hostChildRunId,
    status: 'running',
    done: false
  }
})
```

Use `running` only when known; report uncertainty truthfully otherwise. The loop suppresses
`SubagentCompleted` only when the marker is `subagent_observation` and `subagent_run_id` matches
`subagent:<originalCallId>` for that `subagent` call. A mismatched ID does not suppress completion.
The observation still emits `ToolExecutionCompleted` for the call, not child completion, and adds
no nested usage. Return a recovery handle only after host ownership checks.

This differs from launch acceptance (`makeSubagentAcceptedToolResult`) and from generic background
`ToolResult.acceptance`, which produces `ToolExecutionAccepted`. Do not append another result to
the original call later; observe through distinct status/wait calls. See
[Bounded child observations](../vercel-workflows/step-contracts#bounded-child-observations).

### Effect-native realtime validation [#effect-native-realtime-validation]

Use `toOpenAiRealtimeToolEffect`, `makeOpenAiRealtimeSessionConfigEffect`, or
`openAiRealtimeSessionConfigFromVoiceEffect` from `@yolk-sdk/agent/providers/openai/realtime`
in Effect programs. They fail with typed `VoiceToolBridgeError` for activated definitions, so
`Effect.catchTag('VoiceToolBridgeError', ...)` can recover before SDP exchange or other host effects.
The synchronous counterparts remain compatible and throw that error; unexpected defects are not
converted into host-correctable failures.

`makeTool` returns the same structured `model_visible_tool_error` for invalid business arguments
with or without activation, in either execution mode, before business execution or admission.
Malformed envelopes and raw-registration/host `ToolError`s retain their typed failure semantics.

Activated approval IDs intentionally contain the full canonical payload for lossless exact binding.
Hosts must accommodate opaque, potentially long IDs or enforce input bounds before admission.
Never truncate, hash, or rebuild these IDs when storing or returning approvals.


---

# Voice

URL: /docs/agent/voice

Build live browser voice agents with Yolk tools, approvals, and durable transcripts.



Use the voice subpaths when you want a speech-to-speech agent session that runs your normal Yolk tools with server-side policy, HITL approvals, and transcript projection into protocol messages.

Install:

```bash
pnpm add @yolk-sdk/agent@canary effect@4.2.0
```

Add `react` for `@yolk-sdk/agent/voice/react`.

## Subpaths [#subpaths]

| Subpath                                     | Use for                                                                                         |
| ------------------------------------------- | ----------------------------------------------------------------------------------------------- |
| `@yolk-sdk/agent/voice`                     | voice events/commands, controller, server tool handler, transcript projection, speech contracts |
| `@yolk-sdk/agent/voice/browser`             | browser WebRTC transport                                                                        |
| `@yolk-sdk/agent/voice/react`               | headless `useYolkVoice` hook                                                                    |
| `@yolk-sdk/agent/providers/openai/realtime` | OpenAI Realtime session config + event codecs                                                   |
| `@yolk-sdk/agent/providers/openai/speech`   | OpenAI one-shot TTS/STT service layers                                                          |

## Architecture [#architecture]

Browser owns media and transport. Your server owns tools, policy, HITL state, and durability.

```txt
useYolkVoice
  -> WebRTC transport (mic, audio, provider data channel)
  -> voice controller (events, tool forwarding, approval pause/resume)
  -> your server tool endpoint -> ToolExecutor
```

Tools never execute in the browser. The controller forwards each provider tool call to your authenticated endpoint as a `VoiceSessionToolCallRequest` and submits the returned output back to the provider.

`WebRtcPeerConnectionLike.addTrack(track, stream)` on `@yolk-sdk/agent/voice/browser` is a void command. The transport discards the DOM `RTCRtpSender`. Hosts and fakes must not read a sender from this capability (`addTrack: () => {}` is sufficient). Real `RTCPeerConnection.addTrack` remains assignable.

## Browser hook [#browser-hook]

This fragment shows the host-owned wiring; `negotiate` posts SDP to your session route and `executeToolCall` posts to your tool route.

```tsx
'use client'

import { useYolkVoice } from '@yolk-sdk/agent/voice/react'
import {
  decodeOpenAiRealtimeServerEvent,
  openAiRealtimeServerEventToVoiceEvents,
  openAiRealtimeVoiceClientCodec
} from '@yolk-sdk/agent/providers/openai/realtime'

const voice = useYolkVoice({
  negotiate: offerSdp => postSdpToYourSessionRoute(offerSdp),
  executeToolCall: (call, approval) => postToYourToolRoute(call, approval),
  codec: openAiRealtimeVoiceClientCodec,
  decodeMessage: raw =>
    openAiRealtimeServerEventToVoiceEvents(decodeOpenAiRealtimeServerEvent(raw)),
  dataChannelLabel: 'oai-events',
  onEvent: projectIntoYourChatState
})

// voice.start() / voice.stop() / voice.userDraft / voice.pendingApprovals
// voice.approveTool(requestId, toolCallId) / voice.denyTool(...)
// <audio ref={voice.attachAudioElement} autoPlay />
```

When projecting into chat state built on `@yolk-sdk/agent/react`, emit each projected assistant message as an `AssistantMessage` event — it deterministically replaces the streamed bubble — before any `AgentEnd` status event. Realtime ordering (late user transcript finals, duplicate final event families, back-to-back responses) breaks the text-runtime assumptions behind `AgentEnd`'s fallback append and can duplicate messages.

## Server tool endpoint [#server-tool-endpoint]

Resolve your voice toolset per session, then apply approval policy and execute:

```ts
import {
  handleVoiceToolCall,
  VoiceSessionToolCallRequest,
  VoiceToolCall
} from '@yolk-sdk/agent/voice'
import { makeToolExecutorLayer } from '@yolk-sdk/agent/tools'

const outcome =
  yield *
  handleVoiceToolCall({
    call: VoiceToolCall.make({ callId, name, argumentsJson }),
    tools: toolSet.tools,
    approval
  }).pipe(Effect.provide(makeToolExecutorLayer(toolSet)))
```

`handleVoiceToolCall` never executes a tool whose `ToolDef.approval` is `manual` without a matching approved response. Denials return model-visible denial output.

`protocolToolCallFromVoice` still maps `VoiceToolCall` to protocol `ToolCall`. Raw `argumentsJson` admits finite JSON (`Schema.Json`). Actual JSON `null`, `false`, and `0` (and objects containing them) still admit as those values.

Raw text `1e999` is valid JSON syntax but is not finite JSON, so admission fails and each mapper uses its existing malformed fallback:

| Public mapper                          | Previous params | New params                    |
| -------------------------------------- | --------------- | ----------------------------- |
| `protocolToolCallFromVoice`            | `Infinity`      | raw argument string `'1e999'` |
| `decideVoiceToolCall` approval display | `Infinity`      | `{ argumentsJson: '1e999' }`  |

Do not demonstrate this with `JSON.stringify(Infinity)` (that is `null`). Nested overflow such as `{"n":1e999}` fails whole-value admission and takes the same mapper-specific fallbacks. Approval identifiers, gates, deny, and execution schema validation are unchanged.

## Approvals in voice [#approvals-in-voice]

Approval-gated calls pause: the controller emits `AwaitingInput`, the hook exposes `pendingApprovals`, and `approveTool`/`denyTool` resume through your tool endpoint. If the session ends while waiting, the approval stays pending host-side; reconnect replays context and applies the stored response. Voice HITL supports approval only in v1. Question HITL is unsupported; exclude question tools from voice toolsets. Typed-input and action-backed interaction tools are denied before execution; exclude them rather than retrying them here. Use the normal text-agent HITL flow for these tools, optionally with [one-shot speech and transcription](#one-shot-speech-and-transcription) around that flow.

## Durable transcripts [#durable-transcripts]

Project voice events into protocol messages with `projectVoiceEvent`; final user/assistant transcripts and settled tool call/result pairs become normal `AgentMessage`s with no dangling host tool calls. Assistant drafts are keyed per provider output item (falling back to response id): back-to-back responses, multi-item responses, and duplicate final transcript event families never concatenate, wipe, or duplicate messages, and finals for already-flushed items project nothing. Use `sequenceVoiceEvent`/`dedupeStoredVoiceEvents` for replay-safe durable event ids and `voiceSeedTextsFromMessages` to seed a new provider session after reconnect. Reconnect never resumes a provider session.

## Server WebSocket transport [#server-websocket-transport]

`makeWebSocketVoiceTransport` supports provider realtime sessions from Node/server runtimes. It
requires an Effect `Socket.WebSocketConstructor` layer from the host, for example
`Socket.layerWebSocketConstructorGlobal`; it does not construct a platform socket implicitly.

## One-shot speech and transcription [#one-shot-speech-and-transcription]

```ts
import {
  speechResultToAudioPart,
  VoiceSpeechRequest,
  VoiceSpeechSynthesizer,
  VoiceTranscriber
} from '@yolk-sdk/agent/voice'
import { Effect } from 'effect'

const program = Effect.gen(function* () {
  const synthesizer = yield* VoiceSpeechSynthesizer
  const transcriber = yield* VoiceTranscriber
  const speech = yield* synthesizer.synthesize(VoiceSpeechRequest.make({ text: 'Hello!' }))
  const transcript = yield* transcriber.transcribe({
    audio: speech.audio,
    mimeType: speech.mimeType
  })

  return {
    transcript,
    audioPart: speechResultToAudioPart(speech, { filename: 'hello.mp3' })
  }
})
```

This is a server-side fragment. Provide `makeOpenAiSpeechSynthesizerLayer` and
`makeOpenAiTranscriberLayer` from `@yolk-sdk/agent/providers/openai/speech`, each with an Effect
`HttpClient` layer and host-owned `OpenAiSpeechConfig`. Never expose the OpenAI API key to browser
code. `VoiceSpeechRequest.instructions` (or `defaultInstructions` in the OpenAI layer config)
steers delivery style — tone, pacing, emotion — per synthesis request; OpenAI's
`tts-1`/`tts-1-hd` reject instructions, so leave it unset for those models.

### Hold-to-speak pattern [#hold-to-speak-pattern]

The one-shot services compose into a second voice mode alongside realtime: record while a button is held, transcribe on release into the chat input, send through your normal text agent runtime, and optionally speak assistant replies with TTS. This trades realtime's low latency for the full text stack — any model provider, the complete toolset including subagents, and `question` HITL. The Next example implements this (host integration, not SDK API): STT/TTS routes wrap the OpenAI layers, a hold-to-speak hook drives MediaRecorder capture and streamed sentence playback, and the composer offers hold-to-speak, realtime, and speak-replies controls side by side.

## Realtime tool JSON [#realtime-tool-json]

`OpenAiRealtimeFunctionTool.parameters` and `openAiRealtimeToolParameters` require admitted
`Schema.Json`. Non-JSON tool advertisement fails `VoiceToolBridgeError` before transport.
Synchronous `toOpenAiRealtimeTool`, `makeOpenAiRealtimeSessionConfig`, and
`openAiRealtimeSessionConfigFromVoice` throw that error. Use `toOpenAiRealtimeToolEffect`,
`makeOpenAiRealtimeSessionConfigEffect`, and `openAiRealtimeSessionConfigFromVoiceEffect` inside
Effect programs so advertisement failures stay in the typed error channel. Unexpected mapper defects
(for example throwing getters) remain defects, not `VoiceToolBridgeError`.

Union-root lowering merges own `__proto__` / `constructor` fields with a `Map` plus
`Object.fromEntries` (first-seen / string-enum union). Required intersection, empty-required
omission, and object-root identity are unchanged. `events.ts` uses `Schema.fromJsonString(Schema.Unknown)`.

## Host responsibilities [#host-responsibilities]

* Own the SDP/session route, auth, and provider API keys.
* Resolve voice toolsets per session with `{ surface: 'voice' }` context.
* Persist projected messages and pending approvals in your session log.
* Own audio element rendering, mic permission UX, and reconnect policy.

## Limitations [#limitations]

* OpenAI Realtime is the only packaged realtime provider in v1.
* Provider sessions do not resume; reconnect is a new session plus context seeding.
* Voice `question` HITL is deferred; approvals only.
* Browsers require user-gesture mic permission and may block autoplay; keep the audio element mounted and user-initiated start.


---

# Agent APIs

URL: /docs/api-reference/agent

Public agent subpaths and commonly used exports.



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

## Protocol [#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](../integrations/code-mode#choose-what-scripts-can-call))                                                                                                                              |
| `isToolStageable`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   | approval-gated tools a code mode script may stage into a reviewed plan (`ToolDef.staging`; [staged plans](../agent/tools-hitl#review-a-staged-plan))                                                                       |
| `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](../agent/tools-hitl#defer-rarely-used-tools))              |
| `MessageInstruction`, `isInstructionMessage`, `latestInstructionState`, `latestInstructionMessages`                                                                                                                                                                                                                                                                                                                                                                                                                 | host instruction messages (`UserMessage.instruction`); keep `latestInstructionMessages` through custom compaction ([host instructions](../agent/loop-runtime#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](../agent/tools-hitl#finish-calls-that-paused-for-input))                                                         |
| `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](../agent/tools-hitl#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](../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](../integrations/files)); `ToolResult.files` lists captured files and never reaches providers                                                                        |
| `FileBytes`, `ToolFile`, `FileRef`, `FileUnavailable`, `ToolFileValue`, `isFileRef`, `fileUnavailable`, `noFileStoreReason`, `containsToolFile`                                                                                                                                                                                                                                                                                                                                                                     | typed file fields ([ADR 0013](https://github.com/magoz/yolk-sdk/blob/main/docs/adr/0013-typed-tool-results.md)): 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](../guides/private-attachments)
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](../agent/tools-hitl#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](../agent/tools-hitl#authorize-one-action) for authenticated acceptance,
immutable receipt storage and host-owned rendering. `InteractionSubmitted` is not completion.

## Loop [#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):

```ts
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 [#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 [#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:

* `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 [#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 `null`s 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](../agent/tools-hitl#review-a-staged-plan))                         |
| `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](../agent/tools-hitl#finish-calls-that-paused-for-input))                                     |
| `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](../agent/tools-hitl#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](../integrations/files))                                                             |

`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](../agent/tools-hitl#ledger-writes-for-re-executed-steps).
`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](../integrations/files)).
`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](../integrations/code-mode#choose-what-scripts-can-call). `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](../integrations/code-mode#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](../agent/tools-hitl#let-the-model-choose-background-execution).

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:

```ts
// 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 [#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](../agent/tools-hitl#background-subagents).

## Client [#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 [#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 [#classification]

`@yolk-sdk/agent/classification` (see [Classifier models](../agent/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 [#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 [#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 [#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 [#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 [#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](../migration)
and [Go configuration](../integrations/provider-setup#opencode-go).

`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](../integrations/provider-setup#bound-pdf-attachment-fetches).

| 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 `WireFixture`s; `openAiCodexConformanceFixtures`, `openAiCodexConformanceCases`, `OpenAiCodexConformanceConfig`, four synthetic Codex Responses `WireFixture`s 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 `WireFixture`s                                                                                           |
| `@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 `WireFixture`s (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 `WireFixture`s, 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 `WireFixture`s, 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.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](../integrations/model-providers#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 [#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.


---

# Conformance APIs

URL: /docs/api-reference/conformance

Experimental wire-fixture record, replay, fault-injection, conformance case, and runner subpaths.



> **Experimental.** `@yolk-sdk/conformance` may change in any canary release. It is new after
> `0.1.0-canary.95`; keep it on the same lockstep version as the other public packages.

`@yolk-sdk/conformance` records real HTTP exchanges with outside services, replays them in tests
offline (fail closed), and injects wire faults. It also defines conformance cases, each proving one
claim about how a service really behaves on the wire, and a runner that gates cases by safety and
reports. It depends only on `effect` and never performs
network I/O itself: for live recording, your host supplies the real `HttpClient`.

There is no root export. Import an explicit subpath.

## Fixture [#fixture]

`@yolk-sdk/conformance/fixture`

| Export                                                                                                   | Purpose                                                                                                                                                                                                                                                                                                                                   |
| -------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `WireFixture`                                                                                            | Schema and type: `id`, `caseId`, `evidence`, `recordedAt` (`YYYY-MM-DD`), `account`, `endpoint`, `model?`, `note?`, `exchanges`                                                                                                                                                                                                           |
| `WireExchange`, `WireRequest`, `WireResponse`                                                            | One request (method, absolute URL, allowlisted headers, JSON or text body) and its response                                                                                                                                                                                                                                               |
| `WireBodyResponse`, `WireTextBodyResponse`, `WireBase64BodyResponse`                                     | Whole body: exactly one of `body` (valid UTF-8 string) or `bodyBase64` (exact bytes, for example a PDF)                                                                                                                                                                                                                                   |
| `WireStreamResponse`, `WireChunk`                                                                        | Streamed `chunks` with original boundaries; each entry is a string (valid UTF-8 on its own, empty chunks `""`) or `{ base64 }` with the exact bytes                                                                                                                                                                                       |
| `WireFixtureEvidence`, `WireHeaders`                                                                     | `verified` / `unverified`; lowercase header record                                                                                                                                                                                                                                                                                        |
| `decodeWireFixture`                                                                                      | Decode unknown input (for example a JSON file) into a fixture                                                                                                                                                                                                                                                                             |
| `isWireStreamResponse`, `isWireBase64BodyResponse`                                                       | Narrow a response to the streamed or base64 body shape                                                                                                                                                                                                                                                                                    |
| `fixtureAgeDays`, `isFixtureStale`                                                                       | Whole UTC days since `recordedAt`; stale after `maxAgeDays` (default 30)                                                                                                                                                                                                                                                                  |
| `PortFixture`, `PortFailure`, `decodePortFixture`                                                        | One non-HTTP port call: `id`, `port`, `method`, credential-free JSON `request`, exactly one of `response` or `failure` (`expected` / `error`), `observed?`, `note?`                                                                                                                                                                       |
| `redactPortPayload`, `scanPortFixtureForSecrets`                                                         | Drop credential fields (AWS-style `accessKeyId` / `secretAccessKey` / `sessionToken` included) from a port payload; scan a port fixture (token patterns, credential fields, any non-null `credential(s)`, credential query parameters inside JSON strings, `note`, and `failure.message`)                                                 |
| `PortValueFixture`, `PortFailureFixture`, `isPortFixture`, `isPortFailureFixture`, `isPortCredentialKey` | The two port fixture branches, their narrowing helpers, and the credential-key predicate `redactPortPayload` uses                                                                                                                                                                                                                         |
| `ConformanceFixture`, `conformanceFixtureEvidence`                                                       | `WireFixture \| PortFixture`; evidence and date (a port fixture is `verified` only with `observed`)                                                                                                                                                                                                                                       |
| `scanFixtureForSecrets`, `FixtureSecretIssue`                                                            | Pure scan for credential headers, bearer tokens, API-key prefixes, JWTs, credential query/form params and JSON fields                                                                                                                                                                                                                     |
| `syntheticPortCredentialParams`                                                                          | Frozen exact synthetic placeholders, keyed by parameter name (SigV4 `x-amz-signature`, `x-amz-credential`): the only values `scanPortFixtureForSecrets` accepts, compared with the whole raw value (up to `&`, `#`, whitespace, `"`, `<`, `>`, or the end; never `?` or `'`) after percent-decoding; `scanFixtureForSecrets` accepts none |

Fixtures must contain synthetic or scrubbed data only. The scan covers metadata strings, URLs,
headers, request and response bodies (including decodable `bodyBase64` text), each chunk, and the
reassembled stream, so a secret split across chunks is still found. JSON bodies and SSE `data:`
payloads get the credential-field scan (`access_token`, `client_secret`, `password`, `token`, ...);
numeric usage counters such as `max_tokens` are not flagged. SSE framing with CRLF, LF, or bare CR
line endings is recognized. The scan errs toward flagging: a field named exactly `token` (for
example an OpenAI `logprobs` entry) is flagged, so avoid recording logprobs. It reports locations,
never secret values, and is a safety net rather than a guarantee.

A `PortFixture` records one call through a host port that is not HTTP, such as the generic
`EmailClient`. Without `observed` it is a synthetic placeholder (`unverified`, no date); with
`observed: { account, date }` it is `verified` as of that date. Record requests through
`redactPortPayload` and scan them with `scanPortFixtureForSecrets`, which also flags credential
query parameters inside any JSON string, the note, or the failure message (a signed URL a port
answered, such as an S3 presigned URL's `X-Amz-Signature`). Every `name=` is found and judged on its
own. The only exemption: the raw value, up to a structural boundary (`&`, `#`, whitespace, `"`,
`<`, `>`, or the end; a raw `?` or `'` and encoded delimiters such as `%3F` or `%26` stay inside it),
percent-decoded, exactly equals that parameter's entry in `syntheticPortCredentialParams`. It does
not see parameters with escaped names (`&amp;` before them, percent-encoded names), which port
owners check themselves (the R2 port cases ship `findR2PortFixtureSecrets`). Replaying port fixtures
belongs to the port owner (for example `makeEmailReplayBackend`); the runner accepts both fixture
kinds for its fixture warnings.

## Replay [#replay]

`@yolk-sdk/conformance/replay`

| Export                                       | Purpose                                                                                                                                                 |
| -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ReplayHttpClient.layer(fixtures, options?)` | `Layer<HttpClient.HttpClient \| ReplayLedger>` with fresh state per build                                                                               |
| `makeReplayHttpClient`                       | Effect returning `{ client, ledger }` for manual wiring                                                                                                 |
| `ReplayLedger.entries`, `ReplayLedgerEntry`  | Every request: method, URL, redacted headers, body text/JSON, attempt, match outcome (`matched`, `injected`, `unmatched`, `invalid`), applied fault tag |
| `ReplayLedger.remaining`                     | Recorded exchanges (`fixtureId`, `exchangeIndex`) not consumed yet, in fixture order                                                                    |
| `WireFault`                                  | `StatusOnAttempt`, `FailAfterChunks`, `TruncateAfterChunks`, `HoldAfterChunks` constructors                                                             |
| `WireTransportFault`                         | Cause attached to a body stream failed by `FailAfterChunks`                                                                                             |
| `WireReplayInvalid`                          | Cause of the `HttpClientError` for a matched exchange that cannot be replayed as requested                                                              |

Requests match by method and normalized absolute URL (hash removed, query parameters sorted). Each
exchange is consumed once, in recorded order per method and URL. Unknown requests fail with an
`HttpClientError` whose message names the method and URL only, and are still recorded in the
ledger as `unmatched`; faults never answer them, so `StatusOnAttempt` fires only when an
unconsumed recorded exchange exists for the method and URL. Replay emits the exact recorded bytes:
one `Uint8Array` per recorded chunk (including empty ones), each produced only when pulled, and
`bodyBase64` as the original bytes. A fault `match.url` matches exactly, or as a prefix when it
ends with `*`.

A chunk fault that cannot take effect fails the request with an `HttpClientError` whose cause is
`WireReplayInvalid`, recorded in the ledger as `invalid` without a fault tag: any chunk fault
matched against a whole-body response, `TruncateAfterChunks` or `HoldAfterChunks` with `chunks` at
or beyond the recorded chunk count, or `FailAfterChunks` with `chunks` beyond it. The error reason
is a `TransportError`, which generic transient-retry policies retry; when a test runs through a
retrying client, also assert the ledger has no `invalid` outcome.

```ts
import { Effect } from 'effect'
import { ReplayHttpClient, ReplayLedger, WireFault } from '@yolk-sdk/conformance/replay'

const replayLayer = ReplayHttpClient.layer([hostFixture], {
  faults: [WireFault.StatusOnAttempt({ attempt: 1, status: 429, headers: { 'retry-after': '2' } })]
})

const ledgerEntries = Effect.gen(function* () {
  const ledger = yield* ReplayLedger
  return yield* ledger.entries
})
```

`hostFixture` is a placeholder for your own `WireFixture`. Provide `replayLayer` below the code
under test, for example a provider layer.

## Record [#record]

`@yolk-sdk/conformance/record`

| Export                                                                                       | Purpose                                                                                                             |
| -------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| `WireRecorder.layer(options?)`                                                               | Wraps the `HttpClient` already in context; provides the recording client and `WireRecorder`                         |
| `makeRecordingHttpClient`                                                                    | Effect returning `{ client, recorder }` around a given client                                                       |
| `WireRecorderApi.drain`                                                                      | Take recorded exchanges; fails with `WireRecordingIncomplete` if a request failed or was unread                     |
| `makeWireFixture`                                                                            | Validate a fixture; fails with `WireFixtureInvalid` on schema errors or `WireFixtureSecretsFound` on any scan issue |
| `WireFixtureInvalid`, `WireFixtureSecretsFound`, `WireRecordingIncomplete`                   | Typed errors from `makeWireFixture` and `drain`                                                                     |
| `defaultRecordedRequestHeaders`, `defaultRecordedResponseHeaders`, `defaultStreamMediaTypes` | Allowlist defaults                                                                                                  |

The recorder keeps `content-type` and `accept` request headers and `content-type`, `retry-after`,
`retry-after-ms`, and rate-limit response headers by default. Credential headers such as
`authorization`, `cookie`, `set-cookie`, and token/key-bearing names such as `x-auth-token`,
`private-token`, or `x-*-key` are always dropped. `text/event-stream` responses are teed chunk by
chunk without changing what the caller receives; each chunk is recorded standalone as text when
valid UTF-8, otherwise as `{ base64 }`. Other bodies are recorded as `body` or `bodyBase64`. A
request still pending when `drain` runs is reported by that drain and then dropped; it never lands
in a later drain.

## Case [#case]

`@yolk-sdk/conformance/case`

| Export                                            | Purpose                                                                                                                                               |
| ------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ConformanceCase<E, R>`                           | `id`, `title?`, `safety`, `docs` (what the docs claim), `wire` (what the wire does), `observed?`, `fixtures` (fixture ids), `run: Effect<void, E, R>` |
| `defineConformanceCase`                           | Validates case metadata; throws `ConformanceCaseInvalid` for an invalid definition                                                                    |
| `ConformanceSafety`                               | Schema and type: `read`, `write-reversible` (leaves the account as it found it), `write-irreversible` (never automated)                               |
| `ConformanceObservation`                          | Schema and type: `{ account, date }`, a synthetic account label and `YYYY-MM-DD`; absent on a case means unverified                                   |
| `ConformanceCaseId`                               | Schema: dotted lower-case id, two or more segments                                                                                                    |
| `expectConformance(condition, message, details?)` | Fails with `ConformanceMismatch` when `condition` is false                                                                                            |
| `expectEqual(actual, expected, message)`          | Structural JSON equality (`Equal.equals`); fails with `ConformanceMismatch` carrying both values                                                      |
| `ConformanceMismatch`, `ConformanceCaseInvalid`   | Typed mismatch (`message`, optional JSON `expected` / `actual`); invalid-definition error                                                             |

## Runner [#runner]

`@yolk-sdk/conformance/runner`

| Export                                               | Purpose                                                                                                                                                 |
| ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `runConformance(cases, options)`                     | `Effect<ConformanceReport, never, LR>`; runs allowed cases one at a time by default, each with a freshly built `options.layer(case)`                    |
| `ConformanceRunOptions`                              | `target`, `layer`, `fixtures?` (wire or port), `now?` (default `Clock`), `maxFixtureAgeDays?` (default 30), `concurrency?` (default 1)                  |
| `ConformanceTarget`                                  | `replay`, `in-process`, `emulated`, or `live` with `account`, `allowWrites?` (`none` default / `reversible`), and `allowIrreversible?` (exact ids)      |
| `conformanceSkipReason`                              | The safety policy: `undefined` (runs), `writes-not-allowed`, or `manual-only`                                                                           |
| `conformanceCaseWarnings`, `ConformanceWarning`      | `unverified-case`, `stale-observation`, `unverified-fixture`, `stale-fixture`, `missing-fixture`                                                        |
| `ConformanceReport`, `ConformanceCaseResult`         | Target, `startedAt`, per-case `status` / `skipReason` / sanitized `failure` / `durationMs` / `warnings`, and a summary                                  |
| `formatConformanceReport`, `conformanceReportFailed` | Plain-text report (one line per case plus a summary, no colors); true when any case failed                                                              |
| `sanitizeConformanceMessage`                         | Best-effort message sanitizer the runner applies to non-mismatch failures (credentials and credential header lines redacted, JSON spans elided, capped) |
| `ConformanceCaseRequirements`                        | Requirements of a case type (or union); what `layer` must provide                                                                                       |

| Target                             | `read` | `write-reversible`                                                    | `write-irreversible`                                                    |
| ---------------------------------- | ------ | --------------------------------------------------------------------- | ----------------------------------------------------------------------- |
| `replay`, `in-process`, `emulated` | runs   | runs                                                                  | runs                                                                    |
| `live`                             | runs   | runs only with `allowWrites: 'reversible'`, else `writes-not-allowed` | runs only if its exact id is in `allowIrreversible`, else `manual-only` |

Skipped cases never build their layer. Each running case calls `options.layer(case)` and builds
the result fresh (fresh memo map and scope), so state a layer allocates when it is built (replay
consumption, ledgers, emulator state) never leaks between cases. Layers must allocate their
mutable state when built: a service captured in a shared value (one `Layer.succeed(service,
instance)` reused across cases) or provided by the caller's environment is not rebuilt and stays
shared. Failures, layer build failures, a throwing `layer` factory, and defects become `failed`
results; interruption still interrupts the run.

Failure reports carry an identifier-like, non-credential-shaped error tag (other tags are omitted)
and a message, never request bodies, headers, or mismatch `expected` / `actual` details. A
`ConformanceMismatch` keeps its case-authored message with credential patterns redacted. Every
other message is sanitized best-effort by `sanitizeConformanceMessage`: credential patterns shared
with the fixture secret scan and credential header lines (`Cookie:`, `X-Api-Key:`,
`Proxy-Authorization:`, ...) are redacted, JSON-looking spans become `[json]`, whitespace is
collapsed, and the length is capped at 300 characters. Hosts should still keep secrets out of error
messages.

Live targets omit all fixture-level warnings (`unverified-fixture`, `stale-fixture`,
`missing-fixture`) because fixtures are not used live; case-level warnings always apply. On other
targets fixture warnings need `fixtures`.

```ts
import { Effect } from 'effect'
import { ReplayHttpClient } from '@yolk-sdk/conformance/replay'
import { formatConformanceReport, runConformance } from '@yolk-sdk/conformance/runner'

const report = runConformance(hostCases, {
  target: { kind: 'replay' },
  fixtures: hostFixtures,
  layer: testCase =>
    ReplayHttpClient.layer(hostFixtures.filter(fixture => testCase.fixtures.includes(fixture.id)))
}).pipe(Effect.map(formatConformanceReport))
```

`hostCases` and `hostFixtures` are placeholders for your own cases and fixtures.

## Provider fixtures [#provider-fixtures]

`@yolk-sdk/agent/providers/vercel/conformance` exports Vercel AI Gateway fixtures for replay tests:
`vercelAiGatewayPlainTextFixture`, `vercelAiGatewayDeepSeekReasoningFixture`,
`vercelAiGatewayToolCallDeltasFixture`, `vercelAiGatewayErrorEnvelopeFixture`, and
`vercelAiGatewayConformanceFixtures`. They are verified live recordings (`evidence: 'verified'`,
recorded 2026-09-30 with the synthetic account label `synthetic` and synthetic prompts) written by
`pnpm conformance:gateway --live --owner-approved --account <label>`.

The same subpath exports four `read` conformance cases backed by those fixtures
(`vercelAiGatewayPlainTextCase`, `vercelAiGatewayDeepSeekReasoningCase`,
`vercelAiGatewayToolCallDeltasCase`, `vercelAiGatewayErrorEnvelopeCase`, and
`vercelAiGatewayConformanceCases`). They require only an `HttpClient` and the
`VercelAiGatewayConformanceConfig` service (API key, output limits, reasoning effort, and model ids;
`vercelAiGatewayConformanceDefaultModels` holds the live probe's default model ids, which are the
models every fixture was recorded with, including the reasoning model
`deepseek/deepseek-v4.1-flash`), so they run against replay, the Gateway emulator in
`@yolk-sdk/emulators/gateway` (whose route is verified against these recordings), or a host's live
client. Each case records the live observation that produced its fixture
(`observed: { account: 'synthetic', date: '2026-09-30' }`), so reports do not warn
`unverified-case`.

The same subpath exports four classifier (`POST /v1/evaluate`) `read` cases, apart from the chat
arrays: `vercelAiGatewayClassifierBooleanCase`, `vercelAiGatewayClassifierChoiceCase`,
`vercelAiGatewayClassifierScoreCase`, `vercelAiGatewayClassifierErrorEnvelopeCase`, and
`vercelAiGatewayClassifierConformanceCases`, backed by four synthetic placeholder fixtures
(`evidence: 'unverified'`) in `vercelAiGatewayClassifierConformanceFixtures`. They require an
`HttpClient` and the `VercelAiGatewayClassifierConformanceConfig` service (API key and model ids;
`vercelAiGatewayClassifierConformanceDefaultModels`). None is observed live yet, so reports warn
`unverified-case` and `unverified-fixture`.

`@yolk-sdk/agent/providers/openai/conformance` does the same for the generic OpenAI-compatible chat
provider against OpenAI Chat Completions (`https://api.openai.com/v1/chat/completions`,
`max_completion_tokens`): seven synthetic fixtures (`openAiChatPlainTextFixture`,
`openAiChatToolCallDeltasFixture`, `openAiChatErrorEnvelopeFixture`,
`openAiChatJsonPlainTextFixture`, `openAiChatReasoningEffortFixture`,
`openAiChatJsonReasoningUsageFixture`, `openAiChatUnsupportedParameterFixture`, and
`openAiConformanceFixtures`) and seven `read` cases (`openAiChatPlainTextCase`,
`openAiChatToolCallDeltasCase`, `openAiChatErrorEnvelopeCase`, `openAiChatJsonPlainTextCase`,
`openAiChatReasoningEffortCase`, `openAiChatJsonReasoningUsageCase`,
`openAiChatUnsupportedParameterCase`, and `openAiConformanceCases`). They require an `HttpClient`
and the `OpenAiConformanceConfig` service (API key, `maxCompletionTokens`, the reasoning cases'
`reasoningMaxCompletionTokens` and `reasoningEffort`, and model ids;
`openAiConformanceDefaultModels` holds the fixture model ids). The tool-call case forces its one
tool with `tool_choice`. The error-envelope case requires provider code `model_not_found` with
status 404 (or 400, which OpenAI has also used) and fails any other code, a 401/403, or an `auth`
failure; the JSON case covers `stream: false`. The reasoning cases send `reasoning_effort` to the
reasoning model (streamed and JSON) and require no reasoning text and a usage report counting
reasoning tokens (`completion_tokens_details.reasoning_tokens`); the unsupported-parameter case
sends `max_tokens` to the reasoning model and requires a non-retryable 400 with provider code
`unsupported_parameter`.

`@yolk-sdk/agent/providers/anthropic/conformance` covers Anthropic Messages
(`https://api.anthropic.com/v1/messages`) through the native Messages provider path OpenCode Go uses
(`x-api-key`, `anthropic-version: 2023-06-01`, native `system` and tool names, `message_stop`
required), not the Claude subscription provider, which only accepts a Claude OAuth token. It exports
five synthetic fixtures (`anthropicMessagesPlainTextFixture`,
`anthropicMessagesToolUseInputDeltasFixture`, `anthropicMessagesThinkingBeforeTextFixture`,
`anthropicMessagesErrorEnvelopeFixture`, `anthropicMessagesMaxTokensFixture`, and
`anthropicConformanceFixtures`) and five `read` cases (`anthropicMessagesPlainTextCase`,
`anthropicMessagesToolUseInputDeltasCase`, `anthropicMessagesThinkingBeforeTextCase`,
`anthropicMessagesErrorEnvelopeCase`, `anthropicMessagesMaxTokensCase`, and
`anthropicConformanceCases`). They require an `HttpClient` and the `AnthropicConformanceConfig`
service (API key, `maxTokens`, `thinkingBudgetTokens`, and model ids;
`anthropicConformanceDefaultModels` holds the fixture model ids). The tool-use case forces its tool
with `tool_choice: { type: 'tool', name, disable_parallel_tool_use: true }`; the thinking case
enables `thinking` and sends `max_tokens` = `maxTokens + thinkingBudgetTokens`; the error-envelope
case requires a 404 that is not an `auth` failure and whose body, read at the case's `HttpClient`
boundary, is `{ type: 'error', error: { type: 'not_found_error', message } }`; the max-tokens case
requires `stop_reason: max_tokens` to fail as a non-retryable `invalid_response` without `Done`.

The Responses-based subscription providers share one case shape. `@yolk-sdk/agent/providers/openai/conformance`
also covers the ChatGPT Codex endpoint (`https://chatgpt.com/backend-api/codex/responses`) through
the public Codex provider, and `@yolk-sdk/agent/providers/xai/conformance` covers the Grok CLI proxy
(`https://cli-chat-proxy.grok.com/v1/responses`) through the public Grok provider. Each exports four
synthetic fixtures and four `read` cases: streamed plain text (non-empty text, one `Done(stop)`, and
usage from `response.completed`), `function_call` argument assembly (at least one call, every call
named `lookup_weather` with distinct call ids and a non-empty string `city`, then one
`Done(tool_use)`; the providers send no `tool_choice`; the body, teed at the case's `HttpClient`
boundary, must assemble its `response.function_call_arguments.delta` fragments per item into the
completed item's `arguments`, since the providers read only the completed items), the unknown-model error envelope (a
non-retryable 400 or 404 that is not an `auth` failure, a status-only message, and a JSON error body
with a message read at the case's `HttpClient` boundary), and the terminal event (the body, teed
chunk for chunk at the case's `HttpClient` boundary, ends with exactly one `response.completed` whose
`response.status` is `completed`). Codex exports `openAiCodexPlainTextCase`,
`openAiCodexFunctionCallArgumentsCase`, `openAiCodexErrorEnvelopeCase`,
`openAiCodexTerminalEventCase`, `openAiCodexConformanceCases`, the matching `openAiCodex*Fixture`s,
`openAiCodexConformanceFixtures`, and `OpenAiCodexConformanceConfig` (OAuth token and model ids).
Grok exports the same with the `xAiGrok` prefix and `XAiGrokConformanceConfig` (OAuth token,
host-owned `clientVersion`, `maxOutputTokens`, and model ids). The terminal-event case pins each
provider's behaviour: Grok fails a stream without `response.completed` as a non-retryable
`invalid_response`, while Codex keeps EOF-completion compatibility, so only the body check catches
it. `pnpm conformance:codex` and `pnpm conformance:grok` are dry-run probes; live runs use
subscription OAuth tokens (`OPENAI_CODEX_ACCESS_TOKEN`, `XAI_GROK_ACCESS_TOKEN`) and need the
repository owner's approval (`--owner-approved`); `--live` is refused whenever `CI` is set to any
non-empty value, `0` and `false` included.

`@yolk-sdk/agent/providers/opencode/conformance` covers OpenCode Go through the public Go provider
and usage fetcher (`https://opencode.ai/inference/go/v1`): five synthetic fixtures
(`openCodeGoConformanceFixtures`) and five `read` cases (`openCodeGoConformanceCases`), requiring an
`HttpClient` and `OpenCodeGoConformanceConfig` (redacted API key, `maxOutputTokens`, and one model
id per protocol). `openCodeGoChatPlainTextCase`, `openCodeGoMessagesPlainTextCase`, and
`openCodeGoResponsesPlainTextCase` claim non-empty text, one `Done(stop)`, and usage on each
protocol; `openCodeGoResponsesCommentaryReplayCase` reads its own request at the case's
`HttpClient` boundary and requires a replayed tool turn in order with the assistant text tagged
`phase: "commentary"`, then an accepted stream with one `Done`; `openCodeGoUsageSnapshotCase` is the
Go usage case. `pnpm conformance:opencode` is a dry-run probe; live runs need `OPENCODE_API_KEY`,
owner approval, and real Go model ids for every protocol.

Subscription-usage cases share one shape across vendors: `anthropicClaudeUsageSnapshotCase`
(`@yolk-sdk/agent/providers/anthropic/conformance`, `AnthropicClaudeUsageConformanceConfig`),
`openAiCodexUsageSnapshotCase` (`@yolk-sdk/agent/providers/openai/conformance`,
`OpenAiCodexUsageConformanceConfig`), `xAiGrokUsageSnapshotCase`
(`@yolk-sdk/agent/providers/xai/conformance`, `XAiGrokUsageConformanceConfig`), and
`openCodeGoUsageSnapshotCase`. Each calls the public fetcher at its default URL and asserts the
normalized `ProviderSubscriptionUsageSnapshot`: the vendor provider id, at least one window with
distinct known ids in vendor order, and, against the raw body read at the case's `HttpClient`
boundary, exactly one window per reported wire window with the same id, used percentage, and reset
instant, so no window is fabricated or dropped. The Claude case also accepts model-scoped weekly
windows (`scopedWindowIdPrefix`, ids such as `seven-day-<model>` with `models`), and its synthetic
fixture reports one. The usage cases and fixtures are exported apart
from the model-route suites (`anthropicClaudeUsageConformanceCases`,
`openAiCodexUsageConformanceCases`, `xAiGrokUsageConformanceCases`, and the matching
`*UsageConformanceFixtures`). `pnpm conformance:usage --family claude|codex|grok` is a dry-run
probe with the same owner-approval and CI rules.

## MCP conformance [#mcp-conformance]

> **Experimental.** Conformance/testing only.

`@yolk-sdk/mcp/conformance` exports nine `read` cases (`mcpConformanceCases`) that check the wire
claims `@yolk-sdk/mcp/client` relies on. Each case runs the real client operations
(`listRemoteMcpServerTools`, `callRemoteMcpServerTool`) and wraps the host's `HttpClient` with the
observing client (`makeMcpObservingHttpClient`). The observer never sends a request of its own. It
keeps the method, the URL, allowlisted MCP headers, the JSON request body, the status, allowlisted
answer headers, the media type and the answer body. Its guarantees are exactly these:

* it never keeps `authorization` or any other credential-named header;
* it never keeps the URL query (origin and path only);
* it never keeps a raw `mcp-session-id` value, only evidence (`McpObservedSession`: an equality
  class such as `session#1`, and whether it is visible ASCII);
* request and response bodies are kept exactly as received. They may reflect anything a server
  echoes, credentials and session ids included, so they are sensitive: in memory only, never
  logged or persisted. Persisted or printed output is the live runner's job.

A case that calls a tool (`mcp.modern.stateless`, `mcp.errors.unknown-tool`,
`mcp.tools.call-read`, `mcp.tools.call-tool-error`) is protected by the observer's fail-closed call
gate. The `tools/call` is forwarded only when every exchange of the call operation is fully
understood, that operation's own listing (made right before the call) is complete, and that
listing proves the call safe: the absent tool is not listed, or the read tool is marked
`readOnlyHint: true`. Anything else, including any uncertainty (a 202 answer to a request, a
message delivered on a GET, an unparseable body, an unterminated stream, two responses for one id,
an unknown shape, any server request but the one below), refuses to forward. The one server request
the gate understands is a plain server ping in a POST's answer (`jsonrpc: "2.0"`, a string or
number id, `method: "ping"`, no other member, params absent or empty) that the client answered
exactly once, after it, with only the empty result (`{"jsonrpc":"2.0","id":<ping id>,"result":{}}`),
and that the server accepted with 202 and no body. A ping is side-effect free (MCP `2025-11-25`
basic/utilities/ping: its only answer is an empty result, and the SDK's handler returns `{}` and
touches no state); it is a request, so it resolves none of the client's requests and carries no
listing, and the accepted answer delivers nothing back. Any other server request, a ping with
params, a ping not answered exactly once, or an answer with no status yet, rejected, or with a body
still refuses, as does an answer in another session than the exchange that carried the ping
(#382). The gate decides from what it has recorded when the call is about to be sent. Pings during
`initialize` and in the answers of earlier `tools/list` pages are normally settled by then, since
more round trips follow them (if not, the gate refuses). A ping in the
last `tools/list` page's answer almost always refuses against a live server: the client buffers the
whole page, sends the ping's answer and finishes the listing at almost the same moment, and does no
network I/O before the call, so the call is gated before the answer's 202 returns (fail closed). A refusal before any forwarded call fails the precondition
with zero forwarded calls; a refused client retry after a forwarded call is reported as a retry.
Earlier preflight listings stay as friendly early failures. Answers are read as the SDK reads them:
JSON with `JSON.parse` semantics, and event streams with the SDK's own parser
(the same `eventsource-parser` the client resolves, verified in-repo by a parity test; a consumer
install whose package manager does not dedupe could still resolve two copies), fed the decoder
chunks the client's `TextDecoderStream` emits.

Mismatch messages carry only structural facts (methods, statuses, counts, positions, codes), never
body text or the target URL. A client failure a case re-raises is reported as the client words it
(it can quote a server body) and is sanitized by the runner (`sanitizeConformanceMessage`). A
response or listing page delivered on a `last-event-id` GET (SEP-1699 resumption) is not accepted
(unverified), although the SDK accepts it. Cases name no product: they read the
`McpConformanceTarget` service (`name`, `url`, `headers`, `era`, `protocolVersion`, `timeoutMs`, and
optional `invalidCredentialHeaders`) and the `McpConformanceConfig` seeds (`readTool`,
`invalidArguments`, `expectedTools`, `notReadOnly`, and `absentToolName`, default
`yolk_conformance_absent`). A case whose seed is missing fails with a `precondition:` mismatch before
any request.

| Case                              | Claim                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `mcp.negotiation.era`             | The first request is POST `server/discover` with the `_meta` envelope, `mcp-protocol-version: 2026-07-28` and `mcp-method`. Classified as the SDK classifies it, the answer selects `target.era`: modern when the discover result is valid for the 2026 schema and `supportedVersions` lists `2026-07-28`; legacy for any other discover result (invalid, or without that version), any JSON-RPC error but a modern -32022, or a 4xx other than 401/403. Never 5xx, 401 or 403, and at most one corrective -32022 retry. |
| `mcp.modern.stateless`            | No answer carries `mcp-session-id`. Every request carries the envelope, `mcp-protocol-version` and `mcp-method` equal to the body method (tools/call: also `mcp-name`, the encoded tool name). Every `result` is an object carrying `resultType: "complete"`. The absent-tool call is forwarded only when no raw wire listing names the tool.                                                                                                                                                                            |
| `mcp.legacy.session`              | `initialize` answers a supported `protocolVersion` (equal to `target.protocolVersion`) and `capabilities.tools`. Any session id is visible ASCII, echoed and accepted. `notifications/initialized` gets 202 with no body. The standing GET gets 405 or an event stream (unverified). With a session, the client ends it with exactly one `DELETE` after its last POST, answered 2xx, 404 or 405; without one it sends none.                                                                                              |
| `mcp.transport.response-encoding` | Every 2xx answer to a request is JSON or an SSE stream that ends. Among the events the client reads (completed, non-empty data, no `event:` or `event: message`), every one is JSON and the response appears exactly once. Priming events, other event types and notifications after the response are allowed. A 202 answering a POST has no body (a client-sent response, such as an answer to a server ping, is no request; the session-ending `DELETE` is not constrained).                                           |
| `mcp.tools.list`                  | The server advertises `capabilities.tools`. Every page lists tools with a `name` and an object `inputSchema` (`type: "object"`); cursors are followed, never repeat, and the last page has none. Listed tools and `McpResolvedTool`s correspond one to one, with `title`, `outputSchema` and the five modeled annotation keys unchanged; adapted names stay unique.                                                                                                                                                      |
| `mcp.tools.call-read`             | Precondition: the listing, and the call operation's own complete listing (the call gate), mark `readTool` `readOnlyHint: true`. The call answers a `result` object with `isError` absent or false; with an `outputSchema`, `structuredContent` passes SDK validation.                                                                                                                                                                                                                                                    |
| `mcp.tools.call-tool-error`       | Same precondition. `invalidArguments` answer a `result` object with `isError: true` and text content, not a JSON-RPC error (unverified: some servers answer -32602).                                                                                                                                                                                                                                                                                                                                                     |
| `mcp.errors.unknown-tool`         | Precondition: no raw wire listing names `absentToolName`, and the call gate forwards the call only when the call operation's own complete listing proves it absent. Its tools/call gets a JSON-RPC error with the request id (HTTP 200, or 400 for modern targets), never a 5xx or a `result`, and fails as `McpError` with `cause: "protocol"`.                                                                                                                                                                         |
| `mcp.auth.rejected`               | The first request, with the invalid credential merged over the non-credential target headers, gets 401 with a `Bearer` challenge anywhere in `WWW-Authenticate`; no listing follows, and the error is `McpError` with `cause: "transport"`.                                                                                                                                                                                                                                                                              |

`mcp.modern.*` and `mcp.legacy.*` cases apply to one era only. `selectMcpConformanceCases(cases,
era)` returns the `applicable` cases for `runConformance` and the `notApplicable` ones (with a
reason) for a dry run to list. The synthetic fixtures (`mcpConformanceFixtures`, sixteen,
`evidence: 'unverified'`) use two synthetic servers on one reserved origin.
`https://mcp.example.test/modern/mcp` answers JSON statelessly. `https://mcp.example.test/legacy/mcp`
answers SSE in session `yolk-synthetic-session-0001`. The exchanges are in the order the pinned SDK
sends them, the request bodies carry its exact ids and `_meta` envelope, and `authorization` is never
recorded. `mcpConformanceSyntheticTarget(era)` and `mcpConformanceFixtureSeeds` replay them.

`mcpElicitationDeclarationCase` (`mcp.elicitation.declaration`, read, both eras) is opt-in: it is
not in `mcpConformanceCases`, and its two fixtures are `mcpConformanceElicitationFixtures`, not part
of `mcpConformanceFixtures`. Run it for a host that sets `McpClientOptions.elicitation`. It only
lists: modern tools/list requests carry `elicitation.form` in their `_meta` client capabilities and
get an object result; legacy `initialize` declares no elicitation and no request after the era probe
carries `_meta` client capabilities. It never calls a tool, so it never triggers a confirmation.

`mcpServerPingCase` (`mcp.legacy.server-ping`, read, legacy only) is opt-in too: it is not in
`mcpConformanceCases`, and its one fixture is `mcpConformanceServerPingFixtures`. Run it for a
legacy target that pings its clients. MCP `2025-11-25` lets a server ping (basic/utilities/ping:
"The receiver MUST respond promptly with an empty response") but never requires it, and
`2026-07-28` removed `ping` and every server-to-client request. The case lists tools and needs at
least one `ping` request in an answer (else its precondition fails). For each ping, the client sends
exactly one POST to the target URL holding `{"jsonrpc":"2.0","id":<ping id>,"result":{}}`, with an
`accept` listing both media types and the issued session id, and the server accepts it with 202 and
no body (basic/transports, "Sending Messages to the Server"). The client never surfaces a rejected
answer (its send error only reaches `onerror`), so only the wire shows it, and an answer with no
observed status (a transport failure, or the client closing first) fails the case. The Effect fetch
bridge buffers each whole answer, so the client reads, and answers, a ping only after the SSE stream
carrying it ends: a server that waits for the answer before ending that stream stalls the operation
until the client's timeout (unverified: whether live servers do), and a ping on the standing GET is
unverified. The synthetic fixture
pings inside the `initialize` answer, before its response; the pinned SDK answers before
`notifications/initialized`, without `mcp-protocol-version`. The calling cases run against a pinging
server: the call gate understands a plain ping whose empty-result answer the server accepted with
202 and no body, and still refuses when that answer is missing, rejected, or bodied, when the ping
carries params, or for any other server request (#382).

Every operation is its own connection, so a closing legacy client that holds a session ends it:
it sends `DELETE` with the session id (MCP `2025-11-25` basic/transports, "Session Management" item
5: a client SHOULD; the server MAY answer 405, and a 404 means the session is already gone). It is awaited (one more round trip, at most 2 s)
but best effort: it never fails or changes the operation's result, and an interrupted operation
sends none. `mcp.legacy.session` checks it, and every legacy fixture with a session ends with it.

Not covered, because `@yolk-sdk/mcp/client` never sends them (it lists and calls tools only): the
client's own `ping`, `resources/*`, `prompts/*`, `completion/*`, `logging/setLevel` (removed in
`2026-07-28`), `tasks/*` (no task capability is declared; an extension in `2026-07-28`), and
JSON-RPC batches (removed in `2025-06-18`). Servers' `notifications/message` are ignored (every
legacy fixture answer carries one).

The cases also run in-process against `makeMcpToolServer().handleHttpRequest`. Five cases apply
there: era, stateless, response encoding, listing and unknown tool. The legacy session never happens
because the client negotiates the modern era. The two call cases stop at their precondition, because
the tool server publishes no `readOnlyHint`. The auth case does not apply, because the tool server
has no authentication. The MCP emulator (`@yolk-sdk/emulators/mcp`) answers both synthetic servers
from these fixtures and passes every applicable case offline (give the target a synthetic
`Authorization: Bearer` header). No case is observed live yet.

Provider targets live with the provider, never in `@yolk-sdk/mcp`.
`@yolk-sdk/connectors/afloat/conformance` builds the Afloat target by running the real
`afloat.mcp_auth` action (`makeAfloatMcpConformanceTarget`: `https://useafloat.com/mcp`, modern
`2026-07-28`, `Authorization: Bearer <afloat_ key>`, the reserved invalid key
`afloat_yolkconformanceinvalid0000` for the auth case), names the published nine-tool subset as
seeds (`afloatMcpConformanceLiveSeeds`; no `readTool`, so a live run calls a tool only when a person
names one), and ships eight fixtures derived from the provider's source (owner-supplied; not a live
recording; every case but `mcp.legacy.session` applies). `pnpm conformance:mcp --target afloat`
previews the run (a dry run: no network, no credential read); adding `--live --owner-approved --account <label>` runs the cases by hand with the owner's approval (`AFLOAT_API_KEY` from the
environment only; refused in CI; tool calls only with the `--read-tool` flag, never from the
environment); the MCP emulator serves them as profile `afloat`. See [Afloat MCP
conformance](../connectors/afloat#conformance-cases). `@yolk-sdk/connectors/figma/conformance`
builds the Figma target the same way, by running the real `figma.mcp_auth`
(`makeFigmaMcpConformanceTarget`: `https://mcp.figma.com/mcp`, the legacy era with protocol
`2025-11-25`, unverified, and the access token as `Authorization: Bearer`), names six known Figma
tool names with synthetic schemas as seeds, and ships eight synthetic placeholder fixtures (every
case but `mcp.modern.stateless` applies); `pnpm conformance:mcp --target figma` stays refused until
an owner-approved practice seat exists, and the MCP emulator serves the fixtures as profile `figma`.
See [Figma MCP conformance](../connectors/figma#conformance-cases).

## Connector conformance [#connector-conformance]

> **Experimental.** Conformance/testing only.

`@yolk-sdk/connectors/conformance` provides the connector ports from an Effect `HttpClient`, so
connector cases run the real connector actions over replay, an emulator, or a host's live client:

| Export                                                    | Purpose                                                                                                                                                                                                                              |
| --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `connectorHttpClientFromEffectHttpClientLayer`            | `ConnectorHttpClient` over the `HttpClient` in context; keeps method, URL, headers, string body, content type, status, and body text                                                                                                 |
| `connectorBinaryHttpClientFromEffectHttpClientLayer`      | GET-only `ConnectorBinaryHttpClient`; `request` buffers, then fails oversize 200s (`response_too_large`) and truncates error bodies; `stream` streams 200 bodies (failing past `maxBytes` while streaming) and aborts on scope close |
| `connectorBinaryWriteHttpClientFromEffectHttpClientLayer` | `ConnectorBinaryWriteHttpClient` with `uploadSession`: POST/PUT bytes, and PUT ranges / empty DELETE cancellation to pre-authenticated session URLs; refuses bad requests and credential headers on sessions before sending          |
| `connectorHttpClientsFromEffectHttpClientLayer`           | All three bridges                                                                                                                                                                                                                    |
| `ConformanceCleanupReporter`                              | `Context.Reference` receiving cleanup problems a write case raises while being interrupted; default `Effect.logWarning`; the Dropbox, Notion, Todoist, and Telegram live runners print WARN lines                                    |
| `staticCredentialResolverLayer(credentials)`              | `CredentialResolver` returning one `RuntimeCredential` for every slot, or credentials keyed by slot id (missing: `credential_missing`)                                                                                               |

These bridges are **not production adapters**. They enforce no redirect, DNS/IP, timeout, or TLS
policy; binary limits are checked only after buffering, except that the binary bridge's `stream`
counts an HTTP 200 body against `maxBytes` while it streams. `redirect: 'manual'`
and `credentials: 'omit'` are forwarded as `FetchHttpClient.RequestInit` options, and transport
failures become code-only errors without URLs, headers, or bodies. The static resolver ignores
scopes and never refreshes; hosts own real credential storage.

`@yolk-sdk/connectors/fortnox/conformance` exports twenty-five Fortnox cases
(`fortnoxConformanceCases`: seven invoice and customer cases, and eighteen seedless `read` cases of
company information, the customer list, the read-only resources, and bookkeeping), their synthetic fixtures
(`fortnoxConformanceFixtures`, `evidence: 'unverified'`), and the seeds they replay with
(`fortnoxConformanceFixtureSeeds`). Cases need the connector ports plus
`FortnoxConformanceConfig`, which holds seed identities in a Fortnox developer test company. A
missing seed fails the case with a `precondition:` mismatch before any request. None of the cases is
observed live yet, so reports warn `unverified-case`.

The row and customer mutation cases restore what they change, verify the restore by reading back,
and fail with `FortnoxConformanceRestoreFailed` instead of hiding a failed restore. The rejection
case restores nothing: it only confirms that the customer is absent before its write, and reports
any invoice Fortnox unexpectedly creates for manual cancellation. See
[Fortnox conformance cases](../connectors/fortnox#conformance-cases) for the case table, seeds, and
claims.

`@yolk-sdk/connectors/microsoft/conformance` exports nineteen Microsoft Graph cases
(`microsoftConformanceCases`), their synthetic fixtures (`microsoftConformanceFixtures`), and the
seeds they replay with (`microsoftConformanceFixtureSeeds`). Cases need `ConnectorHttpClient`,
`CredentialResolver`, and `MicrosoftConformanceConfig` (seed identities in a Microsoft 365 practice
tenant). Outlook, OneDrive, SharePoint site, and Teams cases run the real connector actions. The
connector has no calendar actions yet, so the four calendar cases send raw Graph requests through
the same ports and pin expected Graph behaviour (unverified until a live run) for hosts and the
Microsoft Graph emulator (`@yolk-sdk/emulators/microsoft`). Write cases create their own event,
draft, or folder and remove it again automatically when its id is recoverable, failing with
`MicrosoftConformanceRestoreFailed` when the removal fails or a create returns no id. An ambiguous
create (transport or decoding failure, no status, HTTP 408, or HTTP 5xx) fails with
`MicrosoftConformanceActionFailed` (`createOutcome: 'unknown'`); both messages carry manual-recovery
advice. The create is not interruptible and the runner has no request timeout. The one
write-irreversible case, `microsoft.teams.send-chat-message`, posts a real Teams chat message naming
the seeded `runId` and runs live only by its exact id; an ambiguous send fails with
`MicrosoftConformanceActionFailed` (`sendOutcome: 'unknown'`). See [Microsoft conformance
cases](../connectors/microsoft#conformance-cases).

`@yolk-sdk/connectors/email/conformance` exports ten port-level email cases
(`emailConformanceCases`), their synthetic `PortFixture`s (`emailConformanceFixtures`), and the seeds
they replay with (`emailConformanceFixtureSeeds`). Yolk never speaks IMAP, POP3, or SMTP: the cases
run the real email actions over the host `EmailClient`, `CredentialResolver`, and
`EmailConformanceConfig`. `emailClientLayerFromBackend` turns any plain-JSON backend
`{ call(method, request) }` into the `EmailClient` layer (requests arrive without credential fields;
responses are decoded with each method's output schema; `notEmulated` fails closed), and
`makeEmailReplayBackend` replays the fixtures: each fixture answers at most once, and a call takes
the first unused matching fixture. Testing only, never a production
adapter. See [Email conformance cases](../connectors/email#conformance-cases).

`@yolk-sdk/connectors/dropbox/conformance` exports eight Dropbox cases (`dropboxConformanceCases`),
their synthetic fixtures (`dropboxConformanceFixtures`), and the seeds they replay with
(`dropboxConformanceFixtureSeeds`). Cases need `ConnectorHttpClient`,
`ConnectorBinaryWriteHttpClient` (the upload case runs `createDropboxFile` / `updateDropboxFile`),
`CredentialResolver`, and `DropboxConformanceConfig` (seed paths in a practice Dropbox account).
Every case runs the real connector actions or host-only helpers. Write cases work only inside an
invocation-unique `yolk-conformance-<runId>-*` folder (the `runId` seed; the live runner generates a
fresh one each time, so concurrent runs are supported only through distinct run ids). A definitive
create rejection deletes nothing; an ambiguous create fails with `DropboxConformanceActionFailed`
(`createOutcome: 'unknown'`) naming the exact path; successful creates are deleted by id and
verified, failing with `DropboxConformanceRestoreFailed` when that fails; and a path outside the
case folder is never deleted (`DropboxConformanceCleanupRefused`). Every write inside the case
folder (the create, copy, move, upload, and delete) is not interruptible, and the runner has no
request timeout. `findDropboxConformanceLeftovers` lists, read-only, the folders under
`workFolderPath` whose names start with `dropboxConformanceRunFolderPrefix`
(`yolk-conformance-run-`; every valid `runId` starts with `run-`). The Dropbox emulator
(`@yolk-sdk/emulators/dropbox`) passes every case offline. See
[Dropbox conformance cases](../connectors/dropbox#conformance-cases).

`@yolk-sdk/connectors/notion/conformance` exports eight Notion cases (`notionConformanceCases`),
their synthetic fixtures (`notionConformanceFixtures`), and the seeds they replay with
(`notionConformanceFixtureSeeds`). Cases need `ConnectorHttpClient`, `CredentialResolver`, and
`NotionConformanceConfig` (seed ids in a practice Notion workspace). Every case runs the real
connector actions; the pinned-version case observes the outgoing `Notion-Version` at the
`ConnectorHttpClient` port. The write case creates its own page and moves it to the trash again,
failing with `NotionConformanceRestoreFailed` when that fails; an ambiguous create fails with
`NotionConformanceActionFailed` (`createOutcome: 'unknown'`) and manual-recovery advice. The create
is not interruptible and the runner has no request timeout. `findNotionConformanceLeftovers`
searches, read-only, bounded (at most 10 search pages), and best effort, for untrashed
`yolk-conformance page` pages; `findDropboxConformanceLeftovers` likewise reads at most 50
listing pages. The Notion emulator (`@yolk-sdk/emulators/notion`) passes every case offline. See
[Notion conformance cases](../connectors/notion#conformance-cases).

`@yolk-sdk/connectors/todoist/conformance` exports eight Todoist cases (`todoistConformanceCases`),
their synthetic fixtures (`todoistConformanceFixtures`), and the seeds they replay with
(`todoistConformanceFixtureSeeds`). Cases need `ConnectorHttpClient`, `CredentialResolver`, and
`TodoistConformanceConfig` (seed ids in a practice Todoist account). Every case runs the real
connector actions. Write cases each create their own invocation-unique
`yolk-conformance-<runId>-<case>` project under `workProjectId` and delete it again by id, failing
with `TodoistConformanceRestoreFailed` when that fails. A definitive create rejection deletes
nothing; an ambiguous create fails with `TodoistConformanceActionFailed` (`createOutcome: 'unknown'`)
naming the exact project or task; and a created project without the requested name or with a
seeded project's id, or a task outside the case project, is never deleted
(`TodoistConformanceCleanupRefused`). No write is interruptible, and the runner has no request
timeout. The cleanup verifies that the project is gone; that its tasks go with it is checked only
by the delete case. `findTodoistConformanceLeftovers` lists,
read-only and bounded (at most 20 listing pages), the active projects whose names start with
`todoistConformanceRunProjectPrefix` (`yolk-conformance-run-`); the project paging case
(`todoist.projects.list-cursor-paging`) sends its listing request, so a fixture records it. See
[Todoist conformance cases](../connectors/todoist#conformance-cases).

`@yolk-sdk/connectors/telegram/conformance` exports four Telegram cases
(`telegramConformanceCases`), their synthetic fixtures (`telegramConformanceFixtures`, whose URLs
carry the synthetic `telegramConformanceReplayBotToken`), and the seeds they replay with
(`telegramConformanceFixtureSeeds`). Cases need `ConnectorHttpClient`, `ConnectorBinaryHttpClient`
(the file case runs `downloadTelegramFile`), `CredentialResolver`, and `TelegramConformanceConfig`
(a practice chat id, a file id, and the run id). The Telegram actions read only HTTP statuses, so
claims about the Bot API `ok` field are observed at the ports; the host-only `downloadTelegramFile`
decodes the `getFile` result. The send case is **write-irreversible**: a sent
message cannot be deleted through the connector, so it runs only when a person names its exact id
(`allowIrreversible`); an ambiguous send (including a 2xx whose body lacks `ok: true`) fails with
`TelegramConformanceActionFailed` (`sendOutcome: 'unknown'`) naming the text to look for in the
chat. There is no leftover lookup.
See [Telegram conformance cases](../connectors/telegram#conformance-cases).

`@yolk-sdk/connectors/github/conformance` exports eight GitHub cases (`githubConformanceCases`),
their synthetic fixtures (`githubConformanceFixtures`), and the seeds they replay with
(`githubConformanceFixtureSeeds`). Cases need `ConnectorHttpClient`, `CredentialResolver`, and
`GithubConformanceConfig` (the practice repository's `owner` and `repo`, a work issue, a label, a
text file, and the run id). Every case runs the real connector actions; claims about response bodies
the actions only partly read are observed at the `ConnectorHttpClient` port. The comment and label
cases are write-reversible: each write names the invocation-unique `runId` or works only on the
seeded work issue and label, is not interruptible, and is undone by id and verified, failing with
`GithubConformanceRestoreFailed` when that fails; they cannot undo the notification to the work
issue's subscribers or the label timeline events, so the work issue must be a practice issue nobody
else watches. A definitive rejection undoes nothing; an ambiguous write fails with
`GithubConformanceActionFailed` (`writeOutcome: 'unknown'`) naming the exact item; an answer outside
the run namespace is never adopted (`GithubConformanceCleanupRefused`). The issue lifecycle case is
**write-irreversible**: GitHub issues cannot be deleted through the REST API, so the issue it opens
stays in the repository, closed, and it runs only when a person names its exact id.
`findGithubConformanceLeftovers` lists, read-only and bounded, open `yolk-conformance run-*` issues,
run comments on the work issue, and the seeded label on it; the open-listing case
(`github.issues.open-listing`) sends its listing requests, so a fixture records them. See [GitHub conformance
cases](../connectors/github#conformance-cases).

`@yolk-sdk/connectors/google/conformance` exports nineteen Gmail, Calendar, and Drive cases
(`googleConformanceCases`), their synthetic fixtures (`googleConformanceFixtures`), and the seeds
they replay with (`googleConformanceFixtureSeeds`). Cases need `ConnectorHttpClient`,
`CredentialResolver`, and `GoogleConformanceConfig` (a practice mailbox address, practice messages
and a label, a practice calendar and time range, a practice Drive folder and file, and the run id).
Every case runs the real connector actions; answers an action returns undecoded are decoded in the
case, and error bodies are observed at the `ConnectorHttpClient` port. The label, draft, trash,
event, and folder cases are write-reversible: each write names the invocation-unique `runId` or
works only on the seeded work message, is not interruptible, and is undone by id and verified,
failing with `GoogleConformanceRestoreFailed` when that fails. Events never have attendees, so no
invitation is ever sent; the folder case trashes its folder and then deletes it permanently. A
definitive rejection undoes nothing; an ambiguous write fails with `GoogleConformanceActionFailed`
(`writeOutcome: 'unknown'`) naming the exact item; an answer outside the run namespace is never
adopted (`GoogleConformanceCleanupRefused`). The send case is **write-irreversible**: Gmail cannot
unsend, so it runs only when a person names its exact id, and it sends one message whose only
recipient is the seeded practice address. `findGoogleConformanceLeftovers` lists, read-only and
bounded, run labels and drafts, the work message in Trash, run events, and run Drive items; the
label-listing, draft-search, free-text-query, and trashed-listing cases send its requests, so
fixtures record them. See [Google conformance cases](../connectors/google#conformance-cases).

`@yolk-sdk/connectors/linkedin-search/conformance` exports seven LinkedIn search cases
(`linkedInSearchConformanceCases`), their synthetic fixtures (`linkedInSearchConformanceFixtures`,
whose people, companies, and profile URLs are all obviously synthetic), and the seeds they replay
with (`linkedInSearchConformanceFixtureSeeds`). Cases need `ConnectorHttpClient`,
`CredentialResolver` (two API keys, one per slot: `linkedInSearchConformanceCredentials` keys them
for `staticCredentialResolverLayer`), and `LinkedInSearchConformanceConfig` (an Exa people query, a
profile URL, and a profile URL that names no profile). Every case runs the real connector actions
and is a read: Exa people search results and its `numResults` limit, the Enrich Layer profile and
email lookup answers, an unknown key at each provider, and a missing profile. Answers the actions
decode only partly are observed at the `ConnectorHttpClient` port. There is nothing to clean up and
no leftover lookup. Live recordings hold real third parties' personal data: promoting one replaces
each recorded 2xx body wholesale with a minimal synthetic body that keeps only the keys and types
the case reads. See [LinkedIn search conformance
cases](../connectors/linkedin-search#conformance-cases).

`@yolk-sdk/connectors/kie/conformance` exports six Kie cases (`kieConformanceCases`), their
synthetic fixtures (`kieConformanceFixtures`), and the seeds they replay with
(`kieConformanceFixtureSeeds`). Cases need `ConnectorHttpClient`, `CredentialResolver`, and
`KieConformanceConfig` (a finished `success` task id, a finished `fail` task id, a public
first-frame URL, and the run id). Four reads (a finished task with result URLs, a failed task read
as a success, an unknown task id answering Kie code 404 or 422, an invalid key answering
`kie_unauthorized`) and two **write-irreversible** creates (every task spends credits and the
connector cannot cancel one), which run only when a person names their exact ids. Envelope `code`
and HTTP status claims are observed at the `ConnectorHttpClient` port. A create whose outcome is
unknown fails with `KieConformanceActionFailed` (`taskOutcome: 'unknown'`) naming the run id to look
for. There is nothing to clean up and no leftover lookup. See [Kie conformance
cases](../connectors/kie#conformance-cases).

`@yolk-sdk/connectors/r2-storage/conformance` exports six port-level R2 cases
(`r2ConformanceCases`), their synthetic `PortFixture`s (`r2ConformanceFixtures`), and the seeds they
replay with (`r2ConformanceFixtureSeeds`). The connector never talks to R2 itself: the cases run
`r2_storage.upload_url` over the host `R2Presigner` and the host-only `getR2Object` /
`createR2Object` / `updateR2Object` over the host `R2ObjectClient`, plus `CredentialResolver` and
`R2ConformanceConfig`. `r2PortsLayerFromBackend` turns any plain-JSON backend `{ call(port, method,
request) }` into both port layers (requests never carry the credentials or the integration;
`notEmulated` fails closed), and `makeR2ReplayBackend` replays the fixtures. The two write cases are
**write-irreversible**: the connector cannot delete R2 objects, so they run only when named by exact
id, write only under `yolk-conformance/<runId>/`, and report an ambiguous put (any port failure but
`conflict`) with the exact bucket and key. Presigned URLs in fixtures carry only synthetic
credential placeholders: next to the shared `scanPortFixtureForSecrets`, the fail-closed
`findR2PortFixtureSecrets` refuses any `X-Amz-Signature`, `X-Amz-Credential`, or
`X-Amz-Security-Token` name outside an exact canonical placeholder occurrence, in any letter case,
raw or in any variant reachable with up to three rounds of percent-decoding and three of
escape-decoding (JSON `\uXXXX`, `\xXX`, `\\`, numeric HTML character references), in any order,
prose included (deliberate obfuscation is out of scope: a person reviews every recording), and
`scrubR2PortFixture` rewrites a recorded fixture to the placeholders (not escaped URLs: rerun both
scans). Live verification needs a host implementation of both ports; no live R2 runner ships. See
[R2 conformance cases](../connectors/r2-storage#conformance-cases).

When a case is interrupted, the run no longer produces a report, and no further case starts. So
Dropbox, Notion, Todoist, GitHub, Google, and Microsoft write cases, the Fortnox row and customer
mutation cases, the Telegram and Gmail sends, and the R2 puts also hand a cleanup problem raised during the interruption
(a failed cleanup, or a create, send, or put whose outcome is unknown) to `ConformanceCleanupReporter`
from `@yolk-sdk/connectors/conformance`, a `Context.Reference` whose default logs it with
`Effect.logWarning`. The Fortnox rejection case and the Fortnox email send do not report. With the
Effect version this repository pins (4.2.0), such a run ends as a plain interruption, just like a
run whose cleanup succeeded: Effect drops a typed failure whose recovery handler the interruption
skipped, so the reporter is the only record of the cleanup problem. Drills in the connector tests
pin this, so an Effect upgrade that changes it fails visibly. The Dropbox, Notion, Todoist,
Telegram, GitHub, and Google live runners print reported problems to stderr as WARN lines. Their first
SIGINT/SIGTERM interrupts the run fiber so the cleanup is attempted; duplicates within a second (one
Ctrl-C reaches every process of the foreground group, and the wrappers relay it) are ignored, and a
later signal exits at once. An interrupted run exits with code 130, whether or not its cleanup
succeeded; the WARN lines tell which. After that exit the read-only leftover lookup runs again and
lists what is still present. Run live runs as `pnpm conformance:<provider>` or with `tsx` directly:
`pnpm exec tsx` returns to the prompt at once on Ctrl-C (observed), so later output prints after the
prompt, `$?` is pnpm's own code, and the runner is then stopped with `kill -TERM <pid>` (the
first-signal message prints the pid).


---

# Emulator APIs

URL: /docs/api-reference/emulators

Experimental service emulators, HttpClient routing to them, and a loopback server.



> **Experimental.** `@yolk-sdk/emulators` may change in any canary release. It is new after
> `0.1.0-canary.95`; keep it on the same lockstep version as the other public packages.

`@yolk-sdk/emulators` runs stand-ins for outside services in tests and local development, and routes
an Effect `HttpClient` to them instead of the real service. The email and R2 emulators are
port-level fakes instead: plain-JSON backends for `EmailClient` and for `R2Presigner` and
`R2ObjectClient`. Emulators never import other `@yolk-sdk/*` code: their wire shapes follow the
conformance fixtures (verified recordings for the Gateway, synthetic placeholders elsewhere), and
each emulated route names the conformance cases it follows. The package depends on `effect`; the
Node-only `fortnox`, `microsoft`, `dropbox`, `notion`, `todoist`, `telegram`, `github`, `google`,
`linkedin-search`, `mcp`, and `kie` subpaths also depend on the upstream `@emulators/core` runtime
(Apache-2.0, pinned to exactly `0.12.0`).

There is no root export. Import an explicit subpath.

## Router [#router]

`@yolk-sdk/emulators/router`

| Export                              | Purpose                                                                                                           |
| ----------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| `EmulatorRoute`                     | `{ origin, target }`; `EmulatorRoute.url(origin, baseUrl)` and `EmulatorRoute.handler(origin, fetch)` build one   |
| `EmulatedHttpClient.layer(routes)`  | Rewrites each routed origin to a loopback base URL (path and query kept) over the `HttpClient` already in context |
| `InProcessHttpClient.layer(routes)` | Calls the route's fetch handler directly with a web `Request`; returns `HttpClientResponse.fromWeb`               |
| `EmulatorRouteInvalid`              | Build error: malformed or duplicate origin, wrong target kind, or a base URL that is not http(s) on loopback      |
| `EmulatorEnvironmentRefused`        | Build error: `NODE_ENV` is `production` or cannot be read (a missing `NODE_ENV` is allowed)                       |

Pick the transport by swapping layers; the code under test keeps calling the real origin:

| Transport | Layer                                                        |
| --------- | ------------------------------------------------------------ |
| Replay    | `ReplayHttpClient.layer` from `@yolk-sdk/conformance/replay` |
| InProcess | `InProcessHttpClient.layer`                                  |
| Emulated  | `EmulatedHttpClient.layer` over your `HttpClient`            |
| Live      | your own `HttpClient`                                        |

Both layers fail closed: a request to an origin without a route fails with an `HttpClientError`
whose message names only the origin (never the path, query, headers, or body). Emulated base URLs
must be `http(s)` on `127.0.0.0/8`, `::1`, or `localhost` (IPv4-mapped forms such as
`[::ffff:127.0.0.1]` are rejected). The in-process client sends `Empty`, `Uint8Array`, and string
`Raw` bodies; other body kinds fail with an `EncodeError`.

`EmulatedHttpClient` routes at the send step, so redirect follow-ups (`HttpClient.followRedirects`
on top) and URLs changed by your `HttpClient.mapRequest` are routed or fail closed too. Over
`FetchHttpClient`, routed requests use `redirect: 'manual'`, so a 3xx reaches the caller as a 3xx;
other `RequestInit` defaults are kept when provided around the whole client stack. Put
`HttpClient.followRedirects` on top of `EmulatedHttpClient`, never underneath it. Any other
underlying client must not follow redirects by itself.

```ts
import { Layer } from 'effect'
import { makeGatewayEmulator } from '@yolk-sdk/emulators/gateway'
import { EmulatorRoute, InProcessHttpClient } from '@yolk-sdk/emulators/router'

const gateway = makeGatewayEmulator()

const httpLayer = InProcessHttpClient.layer([
  EmulatorRoute.handler('https://ai-gateway.vercel.sh', gateway.fetch)
])
```

Provide `httpLayer` below the code under test, for example a Gateway provider layer.

## Gateway emulator [#gateway-emulator]

`@yolk-sdk/emulators/gateway`

| Export                                            | Purpose                                                                                          |
| ------------------------------------------------- | ------------------------------------------------------------------------------------------------ |
| `makeGatewayEmulator(options?)`                   | `{ fetch, ledger, reset, faults, script, coverage }` for `POST /v1/chat/completions`             |
| `gatewayEmulatorRoutes`                           | Route evidence manifest: `method`, `path`, `kind`, `write`, `caseIds`, `evidence`, `observedAt`  |
| `gatewayEvaluateEmulatorRoutes`                   | Manifest of the fixture-only classifier route `POST /v1/evaluate` (`unverified`)                 |
| `GatewayEvaluateFault`, `GatewayEvaluateEmulator` | Classifier-route fault schema and its emulator API (`emulator.evaluate`)                         |
| `GatewayFault`, `GatewayScriptedTurn`             | Schemas and types for wire faults and scripted turns                                             |
| `GatewayLedgerEntry`, `GatewayCoverage`           | Ledger entry and coverage report types                                                           |
| `gatewayEmulatorDefaultModels`                    | Synthetic-safe default model ids (includes `openai/gpt-4.1-nano` and the DeepSeek ids)           |
| `gatewayEmulatorDefaultReasoningModels`           | `deepseek/deepseek-v3.2` and `deepseek/deepseek-v4.1-flash`                                      |
| `gatewayEmulatorDefaultEventsPerChunk`            | `2`: SSE events per network chunk by default                                                     |
| `emulatorEvidenceHeader`                          | `x-emulator-evidence`, set to `unverified` on every response from an unverified route            |
| `GatewayEmulatorInputInvalid`                     | Thrown by `faults.add` / `script.enqueue` for invalid input, and for an invalid `eventsPerChunk` |

The Gateway route is `verified`: its wire shapes follow the verified live recordings of
2026-09-30 in `@yolk-sdk/agent/providers/vercel/conformance`, with synthetic ids, costs, and
routing metadata. Without a script, a known model gets synthetic output. `stream: true` streams
`chat.completion.chunk` events as recorded: a `{ role: 'assistant' }` opening delta, several text
deltas, then one finish event whose `delta` carries `provider_metadata` and which carries `usage`
(when `stream_options.include_usage` is set), `system_fingerprint`, `service_tier` (`openai/*`
models only), and `generationId`, followed only by `data: [DONE]`. Events are packed
`eventsPerChunk` per network chunk (option, default 2; counted from the end, so the finish event
and `data: [DONE]` share the last chunk). `stream: false` returns one JSON completion (not covered
by a recording). Reasoning models asked for reasoning (`reasoning_effort`, or `thinking` enabled)
stream `delta.reasoning` with `delta.reasoning_details` first. A request with `tools` gets one tool
call whose arguments are synthesized from the tool's JSON Schema and streamed in several
fragments, finishing with `tool_calls`; a `tool_choice` naming an offered function picks that tool
(otherwise the first), and `tool_choice: 'none'` answers with text. Unknown models get the
recorded 404 envelope `{ error: { message, type: 'model_not_found', param: { modelId } } }` (no
`code`), a missing bearer credential gets 401, and unknown routes get a 404 JSON error. The
credential is never checked or stored.

`script.enqueue(turn)` queues a completion (`text`, `reasoning`, `reasoningField`, `order`,
`toolCalls`, `usage`, `finishReason`; `usage: null` drops usage, `reasoningField` defaults to
`reasoning`) or an error (`{ error: { status, body, headers? } }`) for the next request.
`faults.add` injects `status` (for example 429 with `retry-after`), `error-after-chunks`, or
`truncate-after-chunks`, each with an optional `match: { path?, model? }` and `count`; chunk faults
count network chunks, each packing up to `eventsPerChunk` events. Emulators never redirect and always send a body: fault and scripted-error statuses
exclude 1xx, 204, 205, and every 3xx (including 304), header names and values must be valid, and a
`location` header is rejected.

The same fetch handler answers the classifier route `POST /v1/evaluate` (AI Gateway calls
classification "evaluation"), fixture-only: a request matching one of the four synthetic
classifier recordings in `@yolk-sdk/agent/providers/vercel/conformance` (the `model` and question
`type` exact, any other string, the recorded question ids, option keys, and level count) gets the
recorded answer; anything else answers 400 not-emulated. It has its own unverified manifest
(`gatewayEvaluateEmulatorRoutes`), ledger, faults (statuses 400-599), scripted errors, and coverage
(`emulator.evaluate`, control plane `/_emulate/evaluate/*`); `reset()` resets both routes.

The ledger records every emulated API request (control-plane requests are not recorded): method,
path, parsed body, model, `stream`, the `max_tokens` limit (`maxCompletionTokens`, never
validated), `reasoning_effort`, `thinking`, tool names, the applied fault,
the evidence tag, the status actually sent, and body chunks sent; never credential headers. When a
planned response cannot be built, the emulator answers an evidence-tagged 500, records it with
`responseError`, and does not use up the fault. The same fetch handler serves the control plane:

| Route                | Methods                 |
| -------------------- | ----------------------- |
| `/_emulate/ledger`   | `GET`, `DELETE`         |
| `/_emulate/faults`   | `GET`, `POST`, `DELETE` |
| `/_emulate/script`   | `POST`                  |
| `/_emulate/reset`    | `POST`                  |
| `/_emulate/state`    | `GET`                   |
| `/_emulate/coverage` | `GET`                   |

## OpenAI emulator [#openai-emulator]

`@yolk-sdk/emulators/openai`

| Export                                 | Purpose                                                                              |
| -------------------------------------- | ------------------------------------------------------------------------------------ |
| `makeOpenAiEmulator(options?)`         | `{ fetch, ledger, reset, faults, script, coverage }` for `POST /v1/chat/completions` |
| `openAiEmulatorRoutes`                 | Route evidence manifest linked to the OpenAI chat conformance cases                  |
| `OpenAiFault`, `OpenAiScriptedTurn`    | Schemas and types for wire faults and scripted turns (no reasoning text fields)      |
| `OpenAiLedgerEntry`, `OpenAiCoverage`  | Ledger entry and coverage report types                                               |
| `openAiEmulatorDefaultModels`          | Synthetic-safe default model ids (`gpt-4.1-nano`, `gpt-4.1-mini`, `gpt-6-luna`)      |
| `openAiEmulatorDefaultReasoningModels` | Default reasoning model ids (`gpt-6-luna`)                                           |
| `OpenAiEmulatorInputInvalid`           | Thrown by `faults.add` / `script.enqueue` for invalid input                          |

It stands in for OpenAI Chat Completions at `https://api.openai.com` and shares the Gateway
emulator's Chat Completions core, so JSON mode, tool-call fragments, scripted turns, faults, the
ledger, and the control plane behave the same. Streaming uses the plain OpenAI framing (one event
per network chunk, usage in a trailing chunk, none of the Gateway's metadata fields). Errors use the OpenAI envelope
`{ error: { message, type, param, code } }`: an unknown model gets 404 `model_not_found`, and a
missing bearer credential gets 401 `invalid_api_key` (the credential is never checked or stored).
The ledger records `max_completion_tokens` as `maxCompletionTokens`.

Reasoning models (`reasoningModels`, default `openAiEmulatorDefaultReasoningModels`) follow the
three synthetic OpenAI reasoning conformance fixtures: they take `reasoning_effort` and
`max_completion_tokens`, send no reasoning text, and report it only as
`usage.completion_tokens_details.reasoning_tokens`, counted in `completion_tokens`. A non-null
`max_tokens` gets the fixture's 400 `{ error: { message, type: 'invalid_request_error', param:
'max_tokens', code: 'unsupported_parameter' } }` (after model validation, never for a scripted
turn; the ledger's `unsupportedParameter`). Scripted turns reject reasoning text fields; script
reasoning as `usage.reasoningTokens`. Not emulated until a fixture backs them: sampling parameter
rules, `reasoning_effort` on a model that does not reason (recorded and ignored), and per-model
effort values. `reasoning_effort: 'none'` reporting 0 reasoning tokens is synthetic.

## Anthropic emulator [#anthropic-emulator]

`@yolk-sdk/emulators/anthropic`

| Export                                      | Purpose                                                                            |
| ------------------------------------------- | ---------------------------------------------------------------------------------- |
| `makeAnthropicEmulator(options?)`           | `{ fetch, ledger, reset, faults, script, coverage }` for `POST /v1/messages`       |
| `anthropicEmulatorRoutes`                   | Route evidence manifest linked to the Anthropic Messages conformance cases         |
| `AnthropicFault`, `AnthropicScriptedTurn`   | Schemas and types for wire faults (including a mid-stream `error` event) and turns |
| `AnthropicLedgerEntry`, `AnthropicCoverage` | Ledger entry and coverage report types                                             |
| `anthropicEmulatorDefaultModels`            | Synthetic-safe default model ids (`claude-haiku-4-5`, `claude-sonnet-4-5`)         |
| `AnthropicEmulatorInputInvalid`             | Thrown by `faults.add` / `script.enqueue` for invalid input                        |

It stands in for Anthropic Messages at `https://api.anthropic.com`. `stream: true` streams the
events in the order the API sends them: `message_start` (input usage), then per content block
`content_block_start`, its deltas, and `content_block_stop` (a `ping` follows the first block
start), then `message_delta` (`stop_reason`, and usage with input and cache counts next to
`output_tokens`, as the unverified fixtures record it) and `message_stop`; `stream: false`
returns one `message` JSON body. A request with `thinking` enabled (`enabled` or `adaptive`) gets a
`thinking` block (`thinking_delta` events, then a `signature_delta`) before the text. A request
with `tools` gets one `tool_use` block whose input is synthesized from the tool's `input_schema`
and streamed as `input_json_delta` fragments, stopping with `tool_use`; `tool_choice: { type:
'tool', name }` picks that tool and `tool_choice: { type: 'none' }` answers with text. An answer
that would not fit `max_tokens` is cut and stops with `max_tokens`.

Errors use the Anthropic envelope `{ type: 'error', error: { type, message } }`: an unknown model
gets 404 `not_found_error`; a missing or unsupported `anthropic-version` (only `2023-06-01`, the
value the SDK providers send), a missing or non-positive `max_tokens`, or `thinking` with a forced
`tool_choice` (`tool` or `any`) gets 400 `invalid_request_error`; and a request with neither a non-empty `x-api-key` (native API keys) nor
an `Authorization: Bearer` credential (Claude OAuth) gets 401 `authentication_error`. Neither
credential is checked or stored; the ledger records which header carried it
(`credentialHeader`), `anthropic-version`, `anthropic-beta`, `max_tokens` (`maxTokens`),
`thinking`, `tool_choice`, and tool names. The OAuth `anthropic-beta` header and `budget_tokens`
limits are not enforced.

Scripted turns are messages (`thinking`, `text`, `toolUses` with `inputFragments`, `order`,
`usage`, `stopReason`; `usage: null` drops usage, `order: 'text-first'` sends thinking after the
text) or errors. Faults are `status` (the default body is the envelope for the status, for
example `rate_limit_error` for 429 and `overloaded_error` for 529), `error-after-chunks`,
`truncate-after-chunks` (for example before `message_stop`), and `error-event-after-chunks`
(N events, then an `event: error` with `overloaded_error` by default; streamed responses only,
and only before `message_stop`). Faults, the ledger, and the control plane are shared with the
Chat Completions emulators.

## Responses emulators [#responses-emulators]

`@yolk-sdk/emulators/codex` and `@yolk-sdk/emulators/xai`

| Export                                                       | Purpose                                                                                      |
| ------------------------------------------------------------ | -------------------------------------------------------------------------------------------- |
| `makeCodexEmulator(options?)`                                | `{ fetch, ledger, reset, faults, script, coverage }` for `POST /backend-api/codex/responses` |
| `makeXAiGrokEmulator(options?)`                              | The same for `POST /v1/responses` on the Grok CLI proxy                                      |
| `codexEmulatorRoutes`, `xAiGrokEmulatorRoutes`               | Route evidence manifests linked to the Codex and Grok Responses conformance cases            |
| `CodexFault`, `CodexScriptedTurn`, `XAiGrok*`                | Schemas and types for wire faults (including mid-stream error events) and turns              |
| `CodexLedgerEntry`, `XAiGrokLedgerEntry`                     | Ledger entry types                                                                           |
| `codexEmulatorDefaultModels`, `xAiGrokEmulatorDefaultModels` | Synthetic-safe default model ids                                                             |
| `CodexEmulatorInputInvalid`, `XAiGrokEmulatorInputInvalid`   | Thrown by `faults.add` / `script.enqueue` for invalid input                                  |

They stand in for the ChatGPT Codex endpoint at `https://chatgpt.com` and the xAI Grok CLI proxy
at `https://cli-chat-proxy.grok.com`, on one shared OpenAI Responses core. `stream: true` streams
server-sent events with typed `event:` names and a `sequence_number`, in the API's order:
`response.created`, `response.in_progress`, then per output item `response.output_item.added`, its
parts and deltas, and `response.output_item.done`, then `response.completed` with the full
`response` and `usage`; `stream: false` returns one completed `response` JSON body. A request whose
`reasoning` asks for a `summary` gets a `reasoning` item (summary part and
`response.reasoning_summary_text.delta` events) first; answers are a `message` item
(`response.output_text.delta`); a request with function `tools` gets one `function_call` item whose
arguments are synthesized from the tool's JSON Schema and streamed as
`response.function_call_arguments.delta` fragments.

Errors use `{ error: { message, type, param, code } }`: an unknown model gets 400
`model_not_found`, and a request without a non-empty `Authorization: Bearer` credential gets 401
`invalid_api_key` (never checked or stored). `/codex` answers `max_output_tokens` with 400
`unsupported_parameter` (the endpoint takes no output limit) and records `originator`. `/xai`
requires, in order, `X-XAI-Token-Auth` (401), `x-grok-client-version` (426), and
`x-grok-model-override` (400); it records the client version and model override (never the
token-auth value) and records `max_output_tokens` as `maxOutputTokens`.

Scripted turns are responses (`reasoning`, `text`, `functionCalls` with `argumentFragments`,
`order`, `usage`, and `format: 'json'` for a JSON body even on `stream: true`) or errors. Faults are
`status` (for example 429 with `retry-after`), `error-after-chunks`, `truncate-after-chunks` (for
example before `response.completed`), and `error-event-after-chunks` (N events, then an `error`
event, or a `response.failed` event with `event: 'response.failed'`; streamed responses only, and
only before `response.completed`).

## Fixture-only routes [#fixture-only-routes]

The OpenCode Go routes and the Claude, Codex, and Grok subscription-usage routes are fixture-only;
the earlier model routes above keep their behaviour. A request matching a recorded request's shape
gets that fixture's recorded response (same status, headers, and bytes). Everything else answers
one 400 not-emulated, written to the ledger and using up no fault or turn:
`{ error: { type: 'not_emulated', message } }`. That covers unknown routes and methods, missing or
invalid credentials, missing or other headers and query parameters, unknown models, non-streamed
modes, tools, reasoning, and extra fields. No provider status or error envelope is guessed.

Accepted request-shape latitude: any credential value; extra headers; key order; any string value
except `model`, `role`, `type`, and `phase`; any positive integer where the recording has a number
(the output-token limit); an `anthropic-beta` list that includes `oauth-2025-04-20`; any
non-empty Grok `x-userid` and `x-grok-client-version`; and `content-type` parameters. The query
string must match byte for byte (a bare `?` counts as no query), and Grok's `X-XAI-Token-Auth` (`xai-grok-cli`) and
`x-grok-client-mode` (`headless`) must be the SDK's fixed values. Test controls are the shared faults, scripted error turns, and, on usage
routes, a scripted `{ usage }` body or `subscriptionUsage` option with the recorded JSON shape;
fault and scripted-error statuses are 400-599 only. All
of these routes are `unverified` (synthetic fixtures).

## OpenCode Go emulator [#opencode-go-emulator]

`@yolk-sdk/emulators/opencode`

| Export                             | Purpose                                                                                                  |
| ---------------------------------- | -------------------------------------------------------------------------------------------------------- |
| `makeOpenCodeGoEmulator(options?)` | `{ fetch, reset, coverage, chat, messages, responses, usage }` for `https://opencode.ai/inference/go/v1` |
| `openCodeGoEmulatorRoutes`         | Route evidence manifest (four routes) linked to the OpenCode Go conformance cases                        |
| `openCodeGoUsageDefault`           | The recorded usage body (`usage.rolling`, `.weekly`, `.monthly` as `{ percent, resetsAt }`)              |
| `openCodeGoEmulatorDefaultModels`  | The recorded model ids (one per protocol); no other model is emulated                                    |
| `OpenCodeGoEmulatorInputInvalid`   | Thrown by a part's `faults.add` / `script.enqueue`, or for a differently shaped `subscriptionUsage`      |

One fetch handler serves the four routes the OpenCode Go provider and usage fetcher call, each
answering its Go fixture: `POST /inference/go/v1/chat/completions` (Bearer; streamed plain text with
usage), `POST /inference/go/v1/messages` (`x-api-key`, `anthropic-version: 2023-06-01`; streamed plain
text), `POST /inference/go/v1/responses` (Bearer; streamed plain text, or a text answer to a replayed tool
turn with commentary-tagged text), and `GET /inference/go/v1/usage` (Bearer). Each part (`emulator.chat`,
`.messages`, `.responses`, `.usage`) is a full emulator API with its own ledger, faults, and turns,
and its control plane over HTTP is `/_emulate/<part>/*`; `coverage()` / `GET /_emulate/coverage`
combine every route, and `reset()` / `POST /_emulate/reset` reset every part. Requests on no route
answer 400 not-emulated, ledgered by the chat part.

## Subscription-usage routes [#subscription-usage-routes]

The Anthropic, Codex, and Grok emulators also answer their provider's subscription-usage endpoint
on the same origin, with their own manifest, ledger, faults, turns, and coverage (`emulator.usage`,
control plane `/_emulate/usage/*`). The model route's manifest and coverage are unchanged; the
emulator types gain `usage` and a `subscriptionUsage` option.

| Emulator     | Route                            | Headers the fetcher sends (all required)                                              | Manifest                                   |
| ------------ | -------------------------------- | ------------------------------------------------------------------------------------- | ------------------------------------------ |
| `/anthropic` | `GET /api/oauth/usage`           | Bearer, `anthropic-beta` listing `oauth-2025-04-20`                                   | `anthropicSubscriptionUsageEmulatorRoutes` |
| `/codex`     | `GET /backend-api/wham/usage`    | Bearer, `ChatGPT-Account-Id`                                                          | `codexSubscriptionUsageEmulatorRoutes`     |
| `/xai`       | `GET /v1/billing?format=credits` | Bearer, `X-XAI-Token-Auth`, `x-userid`, `x-grok-client-version`, `x-grok-client-mode` | `xAiGrokSubscriptionUsageEmulatorRoutes`   |

Each answers its recorded synthetic snapshot body (`*SubscriptionUsageDefault`) for a request with
those headers, `accept: application/json`, and exactly the recorded query; anything else is 400
not-emulated. Credential and account values are never recorded, and are not checked except Grok's
fixed `X-XAI-Token-Auth: xai-grok-cli`.

## Email emulator [#email-emulator]

`@yolk-sdk/emulators/email`

| Export                                                                                          | Purpose                                                                                                   |
| ----------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
| `makeEmailEmulator({ seed? })`                                                                  | `{ call, state, seed, ledger, reset, faults, coverage }`: a fixture-driven fake `EmailClient` backend     |
| `emailEmulatorRoutes`                                                                           | Route evidence manifest: one `PORT EmailClient.<method>` route per emulated method, linked to email cases |
| `emailEmulatorPort`, `emailEmulatorRouteMethod`                                                 | Helpers: `EmailClient` and `PORT`, the port name and pseudo method of the manifest routes                 |
| `EmailEmulatorSpecialUse`, `EmailEmulatorFolder`, `EmailEmulatorMessage`                        | Seed schemas: SPECIAL-USE attributes, folders, and messages                                               |
| `emailEmulatorDefaultSeed`, `EmailEmulatorSeed`                                                 | The synthetic practice mailbox the fixtures describe (folders, SPECIAL-USE attributes, messages)          |
| `EmailEmulatorFault`, `EmailEmulatorLedgerEntry`, `EmailEmulatorReply`, `EmailEmulatorCoverage` | Fault schema, ledger entry, reply, and coverage types                                                     |
| `emailEmulatorFixtures`                                                                         | The email conformance `PortFixture`s, copied as data                                                      |
| `EmailEmulatorInputInvalid`                                                                     | Thrown for an invalid seed or fault                                                                       |

Yolk never speaks IMAP, POP3, or SMTP, and neither does this emulator: no socket, TLS, MIME, or
mail library, no Node builtin, and no SDK import. `call(method, request)` takes one `EmailClient`
call as plain JSON (without credential fields) and answers `{ response }`, `{ failure }`, or
`{ notEmulated: { reason } }`. `emailClientLayerFromBackend(emulator)` from
`@yolk-sdk/connectors/email/conformance` turns it into the `EmailClient` layer.

Responses come only from the email conformance fixtures. The in-memory mailbox only selects the
first matching fixture consistent with it (preferring fixtures unused since the last reset) and
records what that fixture says happened (flags set, a draft appended, a message moved to the
destination id the fixture names, a message deleted, a Sent copy saved); it never invents an id,
flag, or response.

* Request-shape latitude: credential fields are never compared or recorded, and `connection.host`
  is not compared. Every other connection field (`protocol`, `port`, `security`) and everything
  else must equal a fixture request.

Anything else fails closed with a ledgered `notEmulated` answer, the port analogue of HTTP 400:
`unknown-method`, `invalid-request`, `no-matching-fixture`, or `state-conflict`. Faults
(`{ kind: 'failure', method, match?, count?, failure }`, `match` a deep subset of the request)
change no state. `reset()` restores the seed and clears the ledger, faults, and fixture use.

## R2 emulator [#r2-emulator]

`@yolk-sdk/emulators/r2`

| Export                                                                              | Purpose                                                                                                    |
| ----------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| `makeR2Emulator({ seed? })`                                                         | `{ call, state, seed, ledger, reset, faults, coverage }`: a fixture-driven fake R2 port backend            |
| `r2EmulatorRoutes`                                                                  | Route evidence manifest: one `PORT <Port>.<method>` route per emulated method, linked to R2 cases          |
| `r2EmulatorPresignerPort`, `r2EmulatorObjectClientPort`, `r2EmulatorRouteMethod`    | Helpers: `R2Presigner`, `R2ObjectClient`, and `PORT`, the port names and pseudo method of the routes       |
| `R2EmulatorObject`, `R2EmulatorBucket`, `r2EmulatorDefaultSeed`, `R2EmulatorSeed`   | Seed schemas and the synthetic practice bucket the fixtures describe (the object the get fixtures read)    |
| `R2EmulatorFault`, `R2EmulatorLedgerEntry`, `R2EmulatorReply`, `R2EmulatorCoverage` | Fault schema, ledger entry, reply, and coverage types                                                      |
| `r2EmulatorFixtures`                                                                | The R2 conformance `PortFixture`s, copied as data                                                          |
| `r2EmulatorRedacted`, `r2EmulatorUnrecognised`                                      | The constant request (`<redacted>`) and port and method (`<unrecognised>`) of refusals that record nothing |
| `R2EmulatorInputInvalid`                                                            | Thrown for an invalid seed or fault                                                                        |

The R2 connector never talks to R2 itself, and neither does this emulator: no SigV4 signer, S3
client, socket, Node builtin, or SDK import. `call(port, method, request)` takes one `R2Presigner`
or `R2ObjectClient` call as plain JSON (without credential fields; bytes as base64) and answers
`{ response }`, `{ failure }`, or `{ notEmulated: { reason } }`. `r2PortsLayerFromBackend(emulator)`
from `@yolk-sdk/connectors/r2-storage/conformance` turns it into both port layers.

Responses come only from the R2 conformance fixtures. The in-memory bucket only selects the first
matching fixture consistent with it (preferring fixtures unused since the last reset) and records
what that fixture says happened (an object created absent-only or replaced under its current etag,
with the etag the fixture names); it never invents an etag, a byte, or a failure, and presigning
writes nothing. The connector cannot delete R2 objects, so objects the write cases create stay, and
running the write cases again on the same emulator fails them without writing.

Credentials never reach the ledger or any other output. Every credential field (`credential(s)`,
`accessKeyId`, `secretAccessKey`, `sessionToken`, `token`, and the other names the shared port scan
classifies as credentials) is dropped at any depth before anything is compared or recorded. Every
refusal is ledgered with constant text only (request `<redacted>`), uses no fault, and changes no
state; only a request equal to a fixture request is recorded, with every `bodyBase64` as
`<redacted>` plus its decoded length (`bodyBytes`). Every `bodyBase64` (put bytes) must be canonical
standard base64 of UTF-8 text (else `uncheckable-body`), and its decoded text is checked like the
rest of the request. A request is refused as `credential-in-request` when any key, string value,
number (as printed or as its digit string), or decoded body repeats a value found under a credential
field (any non-empty key, string, or number, with no minimum length), or holds, outside the exact
canonical synthetic placeholders, `X-Amz-Credential`, `X-Amz-Signature`, `X-Amz-Security-Token`, a
credential query parameter, or a token the shared scan flags (a bearer token, a common API-key
prefix, a JSON Web Token, a PEM private key). Each text is checked raw, within three rounds of
percent-decoding and three of escape-decoding (`\uXXXX`, `\xXX`, and numeric HTML references, as the
R2 conformance guard decodes), and through any depth of percent-encoding and JSON escaping, failing
closed past a work cap. A request with an own `__proto__` key at any depth is refused as
`invalid-request`, and one the checks cannot walk (cyclic, or nested too deeply) as
`uncheckable-request`: `call` never throws. The copied key, parameter, and token lists have one test
sample each, counted against the list and checked against the shared scan.

* Request-shape latitude: credential fields are never compared or recorded, and JSON key order is
  not compared. Everything else (the endpoint, bucket, key, content type, `maxBytes`,
  `expectedEtag`, the put `condition`, `bodyBase64`, and `maxUploadBytes`) must equal a fixture
  request exactly, so only the fixtures' `run-synthetic` run id is emulated. A `bodyBase64` must be
  canonical standard base64 of UTF-8 text (else `uncheckable-body`); it is compared as sent but
  recorded only as its decoded length. No object may have an own `__proto__` key (else
  `invalid-request`), and no key or value, the decoded body included, may carry a credential or
  repeat a dropped credential value of any length (else `credential-in-request`). Every refusal is
  ledgered with constant text only (request `<redacted>`).

Anything else fails closed with a ledgered `notEmulated` answer, the port analogue of HTTP 400, with
constant text only (request `<redacted>`): `unknown-method` and `uncheckable-request` (ledgered as
`<unrecognised>`), `invalid-request`, `uncheckable-body`, `credential-in-request`,
`no-matching-fixture`, or `state-conflict`; none uses a fault or changes the bucket. Faults
(`{ kind: 'failure', port, method, match?, count?, failure }`, `match` a deep subset of the request)
apply only to a call a fixture would answer and change no state. `reset()` restores the seed and
clears the ledger, faults, and fixture use.

## Fortnox emulator [#fortnox-emulator]

`@yolk-sdk/emulators/fortnox`

> **Experimental, Node only.** A stateful stand-in for the Fortnox `/3` API, built on the
> `@emulators/core` custom runtime (loaded lazily when you create an emulator).

| Export                                          | Purpose                                                                                          |
| ----------------------------------------------- | ------------------------------------------------------------------------------------------------ |
| `makeFortnoxEmulator(options?)`                 | `Promise` of `{ fetch, baseUrl, ledger, faults, reset, seed, snapshot, coverage, close }`        |
| `fortnoxEmulatorRoutes`                         | Route evidence manifest (54 routes, every one `unverified`; four are connector write routes)     |
| `fortnoxEmulatorQuirks`                         | The observed quirks it implements, each with its conformance case id and drill knob              |
| `FortnoxEmulatorSeed`, `FortnoxEmulatorProfile` | Typed seed schema (`profile`, entities, read-only resources) and account-variance profiles       |
| `FortnoxFault`                                  | `{ kind: 'status', status, headers?, body?, match?: { method?, path? }, count? }`                |
| `fortnoxEmulatorErrorCodes`                     | `ErrorInformation` codes (customer-not-found codes from the fixtures; `2999xxx` codes synthetic) |
| `FortnoxEmulatorInputInvalid`                   | Invalid seed, fault, or option passed to the JS API                                              |

It serves `GET /3/companyinformation`, `GET /3/customers`, `GET`/`PUT /3/customers/{CustomerNumber}`,
`GET`/`POST /3/invoices`, `GET`/`PUT /3/invoices/{DocumentNumber}`,
`GET /3/invoices/{DocumentNumber}/preview` (a small synthetic PDF), and
`GET /3/invoices/{DocumentNumber}/email` (marks the invoice sent and records an outbox entry in
state; nothing is ever delivered). Requests need `Authorization: Bearer <non-empty>`; the token is
never stored or ledgered. Anything else fails closed with a 404 `ErrorInformation`, and unsupported
query parameters or fields get a 400 instead of being ignored.

It also serves the reads of the connector's newer Fortnox actions, `GET` only: articles, price
lists, prices (`/3/prices/sublist/{PriceList}/{ArticleNumber}` and
`/3/prices/{PriceList}/{ArticleNumber}/{FromQuantity}`), cost centers, customer and supplier invoice
payments, offers and their preview PDF, print templates, the inbox (folder JSON; a file id answers
the file bytes), company settings, the locked period, predefined accounts, labels, the modes and
terms of payment, terms and ways of delivery, and units registers, and `/3/me`, plus the
bookkeeping reads: financial years, accounts per financial year, voucher series, vouchers (and the
series sublist), voucher file connections, and SIE file bytes (`/3/sie/{Type}`). These 44 routes,
`GET /3/companyinformation`, and `GET /3/customers` cite the Fortnox read conformance cases, whose
synthetic fixtures are the source of these answers (bodies shaped from the Fortnox OpenAPI spec and
its archived examples; a test requires every read fixture request to get the fixture's body byte
for byte, so the emulator cannot drift from them). They are `unverified`, use minimal synthetic shapes named after the fields the connector
reads, and answer requests no fixture records (other pages, filters, searches, ids) from the state.
Their writes (and side-effecting reads such as
`/3/offers/{DocumentNumber}/email`, voucher and voucher file connection creates) are not emulated
and fail closed with the 404; a key the state
does not hold answers 404 code `2999011`; `lastmodified` gets a 400 on every list.

The default seed holds the synthetic fixture entities with the same numbers as
`fortnoxConformanceFixtureSeeds`, so the Fortnox conformance cases run unmodified against it, plus
small synthetic read-only data (Example AB, `example.test`) consistent with them. Each read-only
resource has its own seed key (`articles`, `priceLists`, `prices`, `costCenters`,
`invoicePayments`, `supplierInvoicePayments`, `offers`, `printTemplates`, `inboxFolders`,
`inboxFiles`, `companySettings`, `lockedPeriod`, `predefinedAccounts`, `labels`, `modesOfPayment`,
`termsOfPayment`, `termsOfDelivery`, `waysOfDelivery`, `units`, `me`, `financialYears`,
`accounts`, `voucherSeries`, `vouchers`, `voucherFileConnections`, `sieFiles`) that replaces the profile's
part; a seed with a duplicate key or a dangling reference (an offer naming a missing customer, a
payment naming a missing invoice, ...) is rejected. Replacing `customers` or `invoices` without
seeding `offers` or `invoicePayments` starts those empty. Profiles: `default`, `empty-company` (no
business data; settings, registers, and inbox folders stay), `no-booked-invoices` (no invoice
payments either). `reset()` restores the seed; `seed()` replaces it.

It implements the quirks the Fortnox cases claim: an omitted row `Discount` stays on positional row
updates (`Discount: 0` clears; RowIds regenerate; totals are recomputed); an empty customer string
keeps the stored value; `unpaid`/`unpaidoverdue`/`fullypaid` skip unbooked invoices
(`unpaidoverdue` uses the injectable `now` clock); rejected writes answer 400 `ErrorInformation`;
customer `Country` is read-only.

The `quirks` option (`stickyRowDiscount: false`, `emptyStringClears: true`,
`paymentFiltersIncludeUnbooked: true`) is a test-only drill knob: it flips one quirk to prove that
the matching conformance case fails.

Fortnox faults are `status` faults only
(`{ kind: 'status', status, headers?, body?, match?: { method?, path? }, count? }`). A fault
answers only a request the route would answer successfully, and nothing is written: the route
checks the request against the state first, so a request it refuses (a 404 for an unknown id, or
a 400 for an invalid state or a query key, field, or value it does not emulate) uses up no fault.
They follow the Gateway emulator's rules: statuses without a body (1xx, 204, 205) and redirects
(3xx) are rejected, as are invalid header names or values, a `location` header, and framing
headers, both in `faults.add` and in `POST /_emulate/faults`. A fault is used up only after its
response is built; a response that cannot be built answers an evidence-tagged 500
`ErrorInformation` recorded in the ledger with `responseError`. The control plane serves
`/_emulate/ledger`, `faults`, `reset`, `state`, `seed`, and `coverage`; unlike the Gateway, it has
no scripted turns and no chunk faults, and `reset`/`seed` also restore or replace the Fortnox
state.

```ts
import { makeFortnoxEmulator } from '@yolk-sdk/emulators/fortnox'
import { EmulatorRoute, InProcessHttpClient } from '@yolk-sdk/emulators/router'

const fortnox = await makeFortnoxEmulator({ seed: { profile: 'default' } })

const httpLayer = InProcessHttpClient.layer([
  EmulatorRoute.handler('https://api.fortnox.se', fortnox.fetch)
])
```

## Microsoft Graph emulator [#microsoft-graph-emulator]

`@yolk-sdk/emulators/microsoft`

> **Experimental, Node only.** A stateful stand-in for the Microsoft Graph v1.0 routes the Microsoft
> conformance cases use (calendar, Outlook mail, OneDrive, SharePoint sites, Teams) plus the
> OneDrive copy monitor URL, built on the same `@emulators/core` runtime (loaded lazily when you
> create an emulator).

| Export                                                                       | Purpose                                                                                                                       |
| ---------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| `makeMicrosoftEmulator(options?)`                                            | `Promise` of `{ fetch, baseUrl, sharePointOrigin, ledger, faults, monitors, reset, seed, snapshot, coverage, close }`         |
| `microsoftEmulatorRoutes`                                                    | Route evidence manifest (35 routes, all `unverified`; twelve are connector write routes)                                      |
| `MicrosoftEmulatorSeed`, `MicrosoftEmulatorProfile`                          | Typed seed schema (`profile`, `user`, `mailFolders`, `messages`, `attachments`, `calendars`, `events`, `drive`, `driveItems`) |
| `MicrosoftFault`                                                             | `{ kind: 'status', status, headers?, body?, match?: { method?, path? }, count? }`                                             |
| `microsoftEmulatorErrorCodes`                                                | Graph error codes, in three groups (below)                                                                                    |
| `MicrosoftEmulatorInputInvalid`                                              | Invalid seed, fault, or option passed to the JS API                                                                           |
| `microsoftEmulatorDefaultOrigin`, `microsoftEmulatorDefaultSharePointOrigin` | `https://graph.microsoft.com` and `https://synthetic-my.sharepoint.com` (the copy monitor host)                               |

Route both origins to the same fetch handler (the paths never overlap, so one loopback server serves
both):

```ts
import { makeMicrosoftEmulator } from '@yolk-sdk/emulators/microsoft'
import { EmulatorRoute, InProcessHttpClient } from '@yolk-sdk/emulators/router'

const microsoft = await makeMicrosoftEmulator()

const httpLayer = InProcessHttpClient.layer([
  EmulatorRoute.handler('https://graph.microsoft.com', microsoft.fetch),
  EmulatorRoute.handler(microsoft.sharePointOrigin, microsoft.fetch)
])
```

It serves, under `/v1.0`: `calendarView` (events overlapping `[startDateTime, endDateTime)`), event
create, get, update, delete, and `cancel` (202; the event is removed, so later reads and deletes are
404\); folder message listing (by folder id) with `$top`/`$skip` and an opaque `@odata.nextLink`;
draft create, update, and move to Deleted Items; attachment listing (inline included, never
`contentId`) and retrieval (with `contentId`); `$batch` with draft `permanentDelete` subrequests
only; and OneDrive item read, children listing, folder create, delete, and file copy (202 with one
monitor `Location`). Folder message listings, calendar views, and children listings need `$top`, at
most the largest value a fixture sends (2, 50, and 200); calendar views and children listings
answer one page. The monitor URL needs no credential; its first poll answers `completed` with a
`resourceId`, as the copy fixture records (`copyInProgressPolls`, default 0, adds `inProgress`
answers first). Graph routes need `Authorization: Bearer <non-empty>`; the token is never stored or
ledgered, and credential-named keys in ledgered bodies and queries are redacted. Responses carry
the fixtures' `@odata.context` envelopes.

Behaviour comes only from the conformance fixtures. Everything they do not show fails closed with
the Graph error envelope `{ error: { code, message, innerError } }`: `/me` paths other than the
Teams ones below and other unknown routes get 404; query keys, `$select` fields, body properties
(including unknown nested keys), and values the emulator does not emulate get a 400 before anything
is written. That includes Outlook requests without `Prefer: IdType="ImmutableId"` and calendar
requests without `Prefer: outlook.timezone="UTC"` (every fixture of theirs sends it), writes to
messages that are not drafts, moves to any destination but `deleteditems`, folder listings by
well-known name, `If-Match`, conflict behaviors other than `fail`, name conflicts, folder or renamed
copies, and failed copies. A route handler that throws answers a 500 envelope recorded in the
ledger. The few behaviours the cases need without a fixture (the concurrency window, advancing id
counters, removal on delete, synthesized seed values), the request-shape latitude it accepts (for
example optional `$select`, smaller `$top`, user aliases, subsets of the fixture body keys), and the
opt-in in-progress copy polls are listed in the package README under "Emulator extrapolations (no
fixture)".

`microsoftEmulatorErrorCodes` groups:

* **From the fixtures:** `ErrorItemNotFound`, `itemNotFound`, `ErrorIrresolvableConflict`.
* **Documented Graph codes (no fixture):** `InvalidAuthenticationToken` (missing bearer),
  `ErrorInvalidUser` (a user other than the seeded mailbox), `TooManyRequests` (the default 429
  fault body).
* **Synthetic emulator codes:** `SyntheticRouteNotEmulated`, `SyntheticQueryNotEmulated`,
  `SyntheticValueNotEmulated`, `SyntheticInvalidRequest`, `SyntheticInvalidBody`,
  `SyntheticUpstreamError`.

Messages keep their immutable id across moves. Event times are UTC with seven fractional digits. For
concurrent writes, the first committed write holds the message for `conflictWindowMs` (default 25; a
refused or faulted write holds nothing); an overlapping write gets 409 `ErrorIrresolvableConflict`;
non-overlapping writes both apply (an emulator extrapolation). The default seed is the synthetic
fixture entities with the same ids as `microsoftConformanceFixtureSeeds`; profiles `default` and
`empty`. Faults, the ledger (which also records the `Prefer` header), and the `/_emulate/*` control
plane behave as in the Fortnox emulator: a refusal (a 404 for an unknown id, a 400 not emulated, or
a 409 conflict) uses up no fault, and a faulted request writes nothing, creates no copy monitor, and
holds no message. `reset` and `seed` also clear copy monitors. The `drills` option
(`calendarRangeEmpty`, `createOmitsId`, `timestampPrecisionDigits`, `omitNextLink`, and one per
SharePoint site and Teams case: `siteSearchEmpty`, `siteDrivesNoLibrary`, `chatsOmitMembers`,
`chatMessagesOmitNextLink`, `joinedTeamsEmpty`, `repliesOmitReplyToId`, `transcriptsOtherMeeting`,
`chatSendUnescaped`) is a test-only drill knob that makes the matching conformance case fail.

The SharePoint site and Teams routes are fixture-only, without exceptions: site search
(`GET /sites?search=`) and site drives; chats (`GET /me/chats`, `GET /chats/{chatId}`), chat
messages (two recorded pages, the second through an `@odata.nextLink` naming the chat id
unencoded) and one message; joined teams, a team, its channels, and one channel; a channel's
top-level posts, one post, and its replies; the meeting found by its join link
(`GET /me/onlineMeetings?$filter=`) and its transcripts; and the chat send
(`POST /chats/{chatId}/messages`). They answer only the recorded exchanges of the eight
`microsoft.sharepoint.*` and `microsoft.teams.*` fixtures (synthetic, shaped from the Microsoft
Graph v1.0 docs examples), byte for byte, for a request whose raw path and query parameters
(decoded, in any order) equal a recorded one, and only under the `default` profile: under `empty`
every one of them answers the 400 not emulated, since no fixture records an empty listing. Anything
else answers 400 before anything is written or a fault is used. The send answers only the recorded
send chat (a dedicated chat, never the paging chat) and the recorded text with any run id: the recorded 201 under a minted message id from a counter that only
advances. A send cannot be undone on Graph, so the emulator keeps it in the state
(`chatMessagesSent`, never seeded): a read of the sent message answers the recorded readback, and a
listing of a chat holding a sent message is not emulated.

## Dropbox emulator [#dropbox-emulator]

`@yolk-sdk/emulators/dropbox`

> **Experimental, Node only.** A stateful stand-in for the Dropbox `/2` RPC and upload routes the
> Dropbox conformance cases use, built on the same `@emulators/core` runtime (loaded lazily when you
> create an emulator). It is fixture-only, without exceptions: it answers only what the
> conformance fixtures show.

| Export                                                     | Purpose                                                                                                     |
| ---------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| `makeDropboxEmulator(options?)`                            | `Promise` of `{ fetch, fetchOn, ledger, faults, cursors, reset, seed, snapshot, coverage, close }`          |
| `dropboxEmulatorRoutes`                                    | Route evidence manifest (10 routes, all `unverified`; five are connector write routes)                      |
| `DropboxEmulatorSeed`, `DropboxEmulatorProfile`            | Typed seed schema (`profile`, `entries` by display path, `deleted`)                                         |
| `DropboxFault`                                             | `{ kind: 'status', status (400-599), headers?, body?, match?: { method?, path?, route? }, count? }`         |
| `dropboxEmulatorErrorBodies`                               | The fixtures' 409 `error_summary` envelopes, byte for byte (`notFound`, `folderConflict`, `uploadConflict`) |
| `DropboxEmulatorInputInvalid`                              | Invalid seed, fault, or option passed to the JS API                                                         |
| `dropboxEmulatorApiOrigin`, `dropboxEmulatorContentOrigin` | `https://api.dropboxapi.com` (RPC) and `https://content.dropboxapi.com` (upload)                            |

In a fault's `match`, `method` is the HTTP method, `path` the raw request path (a trailing `*`
makes it a prefix), and `route` a route template of the manifest; a `route` that names no manifest
row is rejected when the fault is added. The Notion, GitHub, Google, LinkedIn search, and MCP
faults take the same `match`.

Each route answers only on the origin its fixtures record. `fetch` reads the origin from the
request URL (in-process routing keeps it); behind a loopback rewrite, serve `fetchOn(origin)` for
each origin on its own server:

```ts
import { makeDropboxEmulator } from '@yolk-sdk/emulators/dropbox'
import { EmulatorRoute, InProcessHttpClient } from '@yolk-sdk/emulators/router'

const dropbox = await makeDropboxEmulator()

const httpLayer = InProcessHttpClient.layer([
  EmulatorRoute.handler('https://api.dropboxapi.com', dropbox.fetch),
  EmulatorRoute.handler('https://content.dropboxapi.com', dropbox.fetch)
])
```

It serves, as `POST` under `/2/files`: `list_folder` and `list_folder/continue` (cursor paging; every
page carries a cursor), `get_metadata` (case-insensitive lookups; `path_display` keeps the stored
casing of the last component only; `include_deleted: true` answers `deleted` metadata after an empty
folder's delete), `search_v2` and `search/continue_v2` (file name matches in the nested `metadata`
envelope; a cursor only with `has_more`), `create_folder_v2` (metadata without `.tag`; an existing
folder in any casing is a 409 `path/conflict/folder`), `delete_v2` (by path or `id:`; folders and
their content), `copy_v2` (a new file with the source's size and content hash) and `move_v2` (the
same id), and `upload` on the content host (`add` never overwrites; `update` by `id:` needs the
current rev; both conflicts are 409 `path/conflict/file`). Route errors are the fixtures' HTTP 409
`error_summary` envelopes. Every route needs `Authorization: Bearer <non-empty>`; the token is never
stored or ledgered.

Every answer value comes from a fixture, or is a value the emulator mints (created ids and revs from
counters that start above the seeded ones, content hashes derived from revs, upload timestamps from
the injectable `now` clock, and cursors). Folders a fixture never shows (the parents of the seeded
paths) are implied: never rendered. A cursor is accepted only when this emulator issued it since the
last reset and its listing or search renders exactly as when it was issued. Anything else answers
one ledgered 400 not-emulated (`{ error: { type: 'not_emulated', message } }`), writes nothing, and
uses up no fault: each route's pure, state-reading eligibility check runs before a fault is
decided. That includes a listing of an empty folder and a search without matches (no fixture
records either), so `findDropboxConformanceLeftovers` fails against the default seed's empty work
folder with `DropboxConformanceActionFailed` (HTTP 400), which the live runner reports as its
lookup-failed `WARN`.

* Request-shape latitude (`/dropbox`, the only accepted deviations): any bearer value (never
  checked or stored); extra request headers; JSON key order; `content-type` media-type parameters;
  any path and search query (looked up in the state); any `list_folder` `limit` from 1 to 2000 and
  any `search_v2` `options.max_results` from 1 to 1000; and any upload body bytes. Everything else
  (other keys, booleans, modes, query parameters, another origin, ids or revs where the fixtures
  send paths, the root folder, and cursors not issued since the last reset or whose listing
  changed) is not emulated.

The default seed is the synthetic fixture entries at the paths of `dropboxConformanceFixtureSeeds`;
profiles `default` and `empty`. Faults (statuses 400-599, default body
`{ error: { type: 'emulator_fault', message } }`), the ledger (which records the `Dropbox-API-Arg`
header and any JSON-looking query value with credential-named keys redacted, and an upload's length,
never its bytes), and the `/_emulate/*` control plane behave as in the Microsoft Graph emulator;
`reset` and `seed` also clear cursors. The `drills` option (eight booleans, one per Dropbox case) is
a test-only drill knob that makes exactly the matching conformance case fail. The package README
lists the routes, wire behaviour, minted values, and refusals in full.

## Notion emulator [#notion-emulator]

`@yolk-sdk/emulators/notion`

> **Experimental, Node only.** A stateful stand-in for the Notion `/v1` routes the Notion conformance
> cases use at API version `2025-09-03`, built on the same `@emulators/core` runtime (loaded lazily
> when you create an emulator). It is fixture-only, without exceptions: it answers only what the
> conformance fixtures show.

| Export                                          | Purpose                                                                                                                  |
| ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| `makeNotionEmulator(options?)`                  | `Promise` of `{ fetch, fetchOn, ledger, faults, reset, seed, snapshot, coverage, close }`                                |
| `notionEmulatorRoutes`                          | Route evidence manifest (10 routes, all `unverified`; two are connector write routes)                                    |
| `NotionEmulatorSeed`, `NotionEmulatorProfile`   | Typed seed schema (`profile`, `botUser`, `pages`, `impliedPages`, `blocks`, `propertyItems`, `databases`, `dataSources`) |
| `NotionFault`                                   | `{ kind: 'status', status (400-599), headers?, body?, match?: { method?, path?, route? }, count? }`                      |
| `NotionEmulatorInputInvalid`                    | Invalid seed, fault, or option passed to the JS API                                                                      |
| `notionEmulatorOrigin`, `notionEmulatorVersion` | `https://api.notion.com` and `2025-09-03`                                                                                |

```ts
import { makeNotionEmulator } from '@yolk-sdk/emulators/notion'
import { EmulatorRoute, InProcessHttpClient } from '@yolk-sdk/emulators/router'

const notion = await makeNotionEmulator()

const httpLayer = InProcessHttpClient.layer([
  EmulatorRoute.handler('https://api.notion.com', notion.fetch)
])
```

It serves, under `/v1`: `POST /search` (pages by title, `filter` `object: page` only), `GET
/users/me` (the bot user), `GET /pages/{id}` (trashed pages too; 404 `object_not_found` and 400
`validation_error` envelopes as the fixtures record them), `POST /pages` (the recorded create: a
child of a page titled `yolk-conformance page: safe to delete`), `PATCH /pages/{id}` with
`{ archived: true }` (the page with `archived` and `in_trash` true; it still reads back), `GET
/blocks/{id}/children`, `GET /pages/{id}/properties/{propertyId}` (the property id decoded once, so
the connector's second percent-encoding names it), and the database / data source split: `GET
/databases/{id}` lists its `data_sources`, `GET /data_sources/{id}` holds the schema and names its
database, and `POST /data_sources/{id}/query` with `page_size: 1` answers the recorded first row,
whose parent is the data source, and the next row's id as its cursor. Lists page with `has_more`
and `next_cursor`, and the last page carries `next_cursor: null`. Every route needs
`Authorization: Bearer <non-empty>` (never stored or ledgered) and `Notion-Version: 2025-09-03`,
and answers only on the recorded origin `https://api.notion.com` (`notionEmulatorOrigin`): `fetch`
reads the origin from the request URL; behind a loopback rewrite, serve
`fetchOn(notionEmulatorOrigin)`.

Every answer value comes from a fixture, or is a value the emulator mints (created page ids from a
counter that starts above the seeded ones, their timestamps from the injectable `now` clock,
request ids, and cursors). Pages a fixture only names by id (the blocks page, the parent
pages, the next query row) are implied: their ids resolve where a fixture names them, but they are
never rendered, and search considers only the pages whose content the state holds, so an implied
page never matches. A cursor is accepted only when this emulator issued it for the same list since
the last reset or seed and the list renders exactly as when it was issued. No cursor value crosses
a reset or seed: property cursors come from a counter that never resets, and search and block
cursors are the next result's id (the fixture's value) only in the generation that first issued
that id for that list, `<id>.g<generation>` afterwards, so a pre-reset cursor stays refused even
after the same first-page request. Anything else answers one ledgered
400 not-emulated, writes nothing, and uses up no fault: unknown routes and methods, another
origin, other `Notion-Version` values, query parameters a route does not take, a missing `page_size`, other
search filters, a search without matches or whose matches include a trashed page or a page shown
only as a query row, children of a page without recorded child blocks, `sorts` and query filters, a
query page that would show an unrecorded row, creates with `children`, under a database, or with another
title, page updates other than `{ archived: true }`, and archiving a missing or already trashed
page. So `findNotionConformanceLeftovers` fails against a clean workspace or after the write case
(no match, or a trashed match) with `NotionConformanceActionFailed` (HTTP 400), which the live
runner reports as its lookup-failed `WARN`.

* Request-shape latitude (`/notion`, the only accepted deviations): any bearer value (never checked
  or stored); extra request headers; JSON key order; `content-type` media-type parameters; the
  order of query parameters; Notion ids with or without dashes, in any case; any search `query`
  (looked up in the state); and any `page_size` from 1 to 100 whose page shows only recorded results
  (the data source query: 1). `Notion-Version` must be `2025-09-03`. Everything else (other keys,
  filters, booleans, sorts, query parameters, another origin, titles, repeated or missing `page_size`, and cursors
  not issued for the same list since the last reset or whose list changed) is not emulated.

The default seed is the synthetic fixture entities with the same ids as
`notionConformanceFixtureSeeds`; profiles `default` and `empty`; an archived page stays in the
state, in the trash. Faults, the ledger (which records the `Notion-Version` header), and the control
plane behave as in the Dropbox emulator. The `drills` option (eight booleans, one per Notion case)
is a test-only drill knob that makes exactly the matching conformance case fail.

## Todoist emulator [#todoist-emulator]

`@yolk-sdk/emulators/todoist`

> **Experimental, Node only.** A stateful, fixture-only stand-in for the Todoist API v1 routes the
> Todoist conformance cases use, built on the same `@emulators/core` runtime (loaded lazily when you
> create an emulator).

| Export                                          | Purpose                                                                                                |
| ----------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
| `makeTodoistEmulator(options?)`                 | `Promise` of `{ fetch, ledger, faults, cursors, reset, seed, snapshot, coverage, close }`              |
| `todoistEmulatorRoutes`                         | Route evidence manifest (ten routes, all `unverified`; five are connector write routes)                |
| `TodoistEmulatorSeed`, `TodoistEmulatorProfile` | Typed seed schema (`profile`, `userId`, `projects`, `tasks`, `labels`); profiles `default` and `empty` |
| `TodoistFault`                                  | `{ kind: 'status', status (400-599), headers?, body?, match?: { method?, path?, route? }, count? }`    |
| `TodoistEmulatorInputInvalid`                   | Invalid seed or fault passed to the JS API                                                             |
| `todoistEmulatorDefaultOrigin`                  | `https://api.todoist.com`                                                                              |

```ts
import { makeTodoistEmulator } from '@yolk-sdk/emulators/todoist'
import { EmulatorRoute, InProcessHttpClient } from '@yolk-sdk/emulators/router'

const todoist = await makeTodoistEmulator()

const httpLayer = InProcessHttpClient.layer([
  EmulatorRoute.handler('https://api.todoist.com', todoist.fetch)
])
```

It serves, under `/api/v1` with `Authorization: Bearer <token>` (at least 8 characters; never stored
or ledgered, and refused when the path, query, or body repeats it): `GET /tasks` (active tasks of a
project, REST v1 cursor paging with `next_cursor`), task create, read, update, and close, `GET
/labels`, `GET /projects` (every project, REST v1 cursor paging), and project create, read, and
delete (which removes the project's task). Case projects are
named `yolk-conformance-<runId>-<case>` with any `run-` run id, so a live runner's `run-<hex>` ids
work. Bodies, 404 envelopes (`{ error, error_code, error_extra, error_tag, http_code }`), cursors,
and due objects follow the synthetic fixtures; created ids (reserved prefix `6XEmu`, which seeds may
not use) and `event_id`s come from counters that only advance, timestamps from the injectable `now`
clock, and cursors are valid only as issued since the last reset or seed (a project cursor also only
while the project listing is unchanged); the cursor counters never reset, so no cursor value crosses
a reset or seed.

It is **fixture-only**, with no synthesised answers: anything the fixtures do not record answers one
ledgered 400 `{ error: { type: 'not_emulated', message } }` before anything is written and before
any fault is chosen, for example other routes, body fields such as `labels` or `due_string`, other
due values, task listings other than the paging project with `limit=2` or a case project created
here without `limit`, unpaged label listings larger than `limit`, a project listing without `limit`
or without projects, a closed task, reading a seeded project alone (only the project listing
fixture records its object), writes to seeded items (only items created through the recorded
create flow are updated, closed, or deleted), and a second task in a case project or a second
sub-project (the fixtures record `child_order: 1` only). The project listing (`GET /projects`) of
the read-only leftover lookup `findTodoistConformanceLeftovers` is the one the project paging case
(`todoist.projects.list-cursor-paging`) records, so the lookup runs against the emulator: it finds
nothing on the default seed and lists every `yolk-conformance-run-*` project the state holds.

Unrecognised requests (no emulated route under that HTTP method, or raw id segments that are not
Todoist ids) are ledgered and answered with constant text only: the path `/<unrecognised>`, a
standard method or `<other>`, no query or body, and a constant reason. So is a request whose
`Authorization` header is present but is not one recognisable bearer, whatever its route: its
credential cannot be extracted and scrubbed.

Run write cases sequentially on one emulator, or `reset()` between cases: a seeded parent takes one
case project at a time (the fixtures record `child_order: 1` only), so concurrent write cases, or a
case that failed before its cleanup, make later project creates answer not-emulated (a definitive
rejection: nothing is created).

Accepted request-shape latitude: any credential value of at least 8 characters that occurs nowhere
else in the request (its path, query, or body; never checked against anything, stored, or ledgered);
extra request headers; `content-type` parameters; query parameters in any order; any Todoist id
(1-64 of `[A-Za-z0-9_-]`) of an existing item where a fixture has an id (reads: seeded or created
tasks and created projects; task listings: the paging project with `limit=2` and case projects
created here without `limit`; writes: only items created through the recorded create flow; a new
project's `parent_id`: a seeded project); any `run-` run id (at most 40 characters) in a case
project name; any non-empty task `content`; a task update sending `content`, `due_datetime`, or
both; a label listing `limit` of 1 to 200 that covers every label; a project listing `limit` of 1
to 200, its pages chained through cursors this emulator issued for the same `limit` and unchanged
listing. The `drills` option (`cursorRestarts`, `notFoundWithoutError`, `taskLabelsAsIds`,
`projectCursorRestarts`, `listIncludesClosed`, `ignoreDue`, `createOmitsParent`, `deleteKeepsTasks`)
is a test-only knob that makes exactly one Todoist case fail.

## Telegram emulator [#telegram-emulator]

`@yolk-sdk/emulators/telegram`

> **Experimental, Node only.** A stateful, fixture-only stand-in for the Telegram Bot API routes the
> Telegram conformance cases use, built on the same `@emulators/core` runtime (loaded lazily when
> you create an emulator).

| Export                                            | Purpose                                                                                              |
| ------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| `makeTelegramEmulator(options?)`                  | `Promise` of `{ fetch, ledger, faults, reset, seed, snapshot, coverage, close }`                     |
| `telegramEmulatorRoutes`                          | Route evidence manifest (four routes, all `unverified`; `sendMessage` is a connector write route)    |
| `TelegramEmulatorSeed`, `TelegramEmulatorProfile` | Typed seed schema (`profile`, `bot`, `chats`, `files`, `nextMessageId`); profiles `default`, `empty` |
| `TelegramFault`                                   | `{ kind: 'status', status (400-599), headers?, body?, match?: { method?, path?, route? }, count? }`  |
| `TelegramEmulatorInputInvalid`                    | Invalid seed or fault passed to the JS API                                                           |
| `telegramEmulatorDefaultOrigin`                   | `https://api.telegram.org`                                                                           |

It serves `POST /bot<token>/getChat` (a member chat, or the recorded 400 `chat not found`), `GET
/bot<token>/getFile?file_id=...`, the hosted file download `GET /file/bot<token>/<file_path>`, and
`POST /bot<token>/sendMessage`. &#x2A;*The bot token is required but never stored, forwarded, ledgered,
or echoed.** The emulator fails closed: only a request whose raw path is exactly one of these route
shapes (the strict token on the raw segment, an emulated method, no other path text) is recognised,
and its token is taken from that exact segment. Every other request is ledgered and answered with
constant text only (the path `/<unrecognised>`, a standard method or `<other>`, no query or body, a
constant reason), so an encoded separator, a malformed token, or extra segments carry nothing into
the ledger. For a recognised request, the token and its secret part are scrubbed from the ledgered
method, path (`/bot<redacted>/...`), query keys and values, and every not-emulated message, and a
query, remaining path, or body that repeats them (raw, percent-decoded, or in any parsed JSON key,
string value, or number) is refused with constant text. A token whose bot id is `0` names no bot
(`getChat` answers the recorded 401). A send is irreversible on the real service; the emulator
records it in its state (`sentMessages`) and never delivers anything.

It is **fixture-only**, like the Todoist emulator: anything else answers the ledgered 400
not-emulated. Accepted request-shape latitude: any credential value of at least 8 characters that
occurs nowhere else in the request (its path, query, or body; never checked against anything,
stored, or ledgered); extra request headers; `content-type` parameters; a well-formed
`<digits>:<secret>` bot token with a secret of at least 8 characters (the bot id `0` names no bot);
any well-formed `chat_id` string (an integer or a public `@username`; one the bot is not in answers
the recorded 400 on `getChat`); any non-empty message `text`. The `drills` option (`getChatOkFalse`,
`errorsAs200`, `fileSizeOffByOne`, `sendOkFalse`) makes exactly one Telegram case fail.

Both emulators share faults (status only, 400-599, chosen only after the request passed every check,
including the route's eligibility check against the state, and answered before the commit, so a
refused request never uses one and nothing is written; the check, the fault decision, and the commit
run together, so concurrent requests never interleave; a `match.route` naming no manifest route is
rejected when the fault is added; a 429 reaches the connector as
`todoist_rate_limited` / `telegram_rate_limited`), the ledger (credential-named query and body keys
redacted, guarded credential values scrubbed), clock-free recovery (a handler that throws answers an
evidence-tagged 500 `emulator_error` recorded with `responseError`; a closed emulator answers 503),
and the `/_emulate/*` control plane (`ledger`, `faults`, `reset`, `state`, `seed`, `coverage`).

## GitHub emulator [#github-emulator]

`@yolk-sdk/emulators/github`

> **Experimental, Node only.** A stateful, fixture-only stand-in for exactly the GitHub REST routes
> the GitHub conformance cases use, built on the same `@emulators/core` runtime (loaded lazily when
> you create an emulator).

| Export                                             | Purpose                                                                                                                                    |
| -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `makeGithubEmulator(options?)`                     | `Promise` of `{ fetch, fetchOn, ledger, faults, reset, seed, snapshot, coverage, close }`                                                  |
| `githubEmulatorRoutes`                             | Route evidence manifest (12 routes, all `unverified`; six are connector write routes)                                                      |
| `GithubEmulatorSeed`, `GithubEmulatorProfile`      | Typed seed schema (`profile`, `viewer`, `repository`, `labels`, `issues`, `files`, `impliedIssues`, counters); profiles `default`, `empty` |
| `GithubFault`                                      | `{ kind: 'status', status (400-599), headers?, body?, match?: { method?, path?, route? }, count? }`                                        |
| `GithubEmulatorInputInvalid`                       | Invalid seed, fault, or option passed to the JS API                                                                                        |
| `githubEmulatorOrigin`                             | `https://api.github.com`                                                                                                                   |
| `githubEmulatorErrorBodies`                        | The fixtures' not-found, label, and validation error bodies, byte for byte                                                                 |
| `githubEmulatorAccept`, `githubEmulatorApiVersion` | `application/vnd.github+json` and `2026-03-10`, the header values every request needs                                                      |

```ts
import { makeGithubEmulator } from '@yolk-sdk/emulators/github'
import { EmulatorRoute, InProcessHttpClient } from '@yolk-sdk/emulators/router'

const github = await makeGithubEmulator()

const httpLayer = InProcessHttpClient.layer([
  EmulatorRoute.handler('https://api.github.com', github.fetch)
])
```

It serves, on the seeded repository: `GET /repos/{owner}/{repo}/labels` (`per_page`, `page`, with
the paging fixture's `Link` header minted in its exact form; a listing that fits one page carries
none), `GET /repos/{owner}/{repo}/issues` (`state=open`, `per_page`, `page=1`: the open issues,
newest first, on one page), `GET .../issues/{number}` (the recorded 404 for a number the repository
has not reached),
`GET /search/issues` (the recorded 422 for a repository-scoped query longer than 256 characters),
`GET .../contents/{path}` (base64 folded every 60 characters), comment create, listing
(`per_page=100` with `since`, or `page=1`), and delete (204, then the recorded 404), issue label add and remove (the recorded
404 for a repository label not on the issue; removing an issue's last label is not emulated), and
issue create, rename, and close as completed. Every route needs exactly
`Authorization: Bearer <token>` (a recognisable bearer, as below; never compared against anything,
stored, or ledgered), `Accept: application/vnd.github+json` (`githubEmulatorAccept`), and
`X-GitHub-Api-Version: 2026-03-10` (`githubEmulatorApiVersion`), and answers only on the recorded
origin `https://api.github.com` (`githubEmulatorOrigin`): `fetch` reads the origin from the request
URL; behind a loopback rewrite, serve `fetchOn(githubEmulatorOrigin)`.

Every answer value comes from a fixture, or is a value the emulator mints: created issue numbers and
comment ids from counters that only advance (the default seed starts at the fixtures' issue `42` and
comment `9000000001`, a seed's counters lie above its seeded numbers, no seeded node id may use a
minted form at or above its counter, and a create past the last addressable number or id is
refused), the issue and comment ids derived from them in the fixtures' form, and timestamps from the
injectable `now` clock. Issue numbers below the counter that the state does not hold are implied,
never rendered; the open-issue listing answers only while the seed's `impliedIssues` is `closed`
(the default seed's, as the open-listing fixture records) or no number is implied; a seed that
replaces `repository` or `issues` or sets `nextIssueNumber` gets `unknown` unless it names `impliedIssues: 'closed'`. Label pages are page numbers, not cursors, and the label list never changes within a
seed (no route writes labels). A deleted comment's id and a closed issue stay in the state (GitHub
keeps both), so a write case ends at the seed except those and the counters.

It fails closed: only a request whose raw path is exactly an emulated route shape under that route's
method, with no `Authorization` header or exactly `Bearer <token>`, is recognised. Every other
request is ledgered and answered with constant text only (the path `/<unrecognised>`, a standard
method or `<other>`, no query or body, a constant reason). A recognised bearer must match the RFC
6750 `b64token` syntax exactly (`^[A-Za-z0-9\-._~+/]+=*$`, at least 8 characters), start with a
character in `[G-Zg-z\-._~+/]` other than `n`, `r`, `t`, `u`, and hold at least one character
outside the JSON-number alphabet `[0-9.eE+-]` (every GitHub and Google token form does: `ghp_…`,
`github_pat_…`, `gho_…`, `ya29.…`). So no number's text can contain it; it holds no escape
introducer (`%`, `\`, `"`), so no escape starts inside it; and its first character is no hex digit
and no JSON escape letter, so no stray `%`, `\`, or partial escape to its left can complete with it,
and its characters always decode in place. An `Authorization` header with any other value is
unrecognisable. A recognised request that repeats the bearer value in its raw path, any path
segment, the raw query or any query key or value, any recorded header, or its body is refused and
ledgered with constant text only: a standard method, the path `/<unrecognised>`, its route template,
an empty query, no headers or body, and a constant reason (`the query repeats the credential`, for
example). Each part is checked through the closure of two total, lexical transforms that cannot
fail: a tolerant percent-decode (every `%XX` below `%80` becomes its ASCII character; any other `%`
sequence is left as it is) and a tolerant JSON-unescape (in any text, whether or not it parses as
JSON, `\uXXXX` below `\u0080` and `\"`, `\\`, `\/`, `\b`, `\f`, `\n`, `\r`, `\t` become their
characters). Starting from each part's raw text, either transform is applied to every text of the
previous step, deduplicated, until no new text appears (a fixpoint), and every text is checked for
the bearer as a substring; both transforms never lengthen a text and shorten it whenever they change
it. So any depth of percent-encoding or JSON escaping, in any order, is seen through in every part:
the raw path and each raw path segment, the raw query and each query key and value (already decoded
once by `URLSearchParams`), each recorded header, and the raw body. The work is capped at 64 rounds,
1024 distinct texts, or 8 Mi characters read by the transforms, whichever comes first; a part whose
closure hits a cap before its fixpoint counts as repeating the credential and is refused with the
same constant entry (uncertainty refuses, it never admits; so any part over 4 Mi characters is
always refused). Any other recognised request has the bearer value scrubbed from its ledgered fields
and every not-emulated reason (plan-time reasons included); its recorded query is keyed by recorded
key; a key recorded more than once lists its values in order (as a JSON array); and recorded headers
and query keys and values that start like JSON (`{`, `[`, `"`) are recorded parsed with
credential-named keys redacted at any depth, or as `<redacted>` when they do not parse, whatever the
header's declared format. Also, refusals never echo a request's own query or body keys; empty query
components are refused. It is **fixture-only**: anything else answers the ledgered 400 not-emulated
before anything is written and before any fault is chosen, for example other routes, issue creates
with labels or assignees, updates other than the two recorded ones (so the lifecycle case's
failure-path restore, which closes as `not_planned`, is not emulated), adding a label the repository
lacks (it would create it), a comment listing of more than one comment, rendering an issue that
holds comments (every fixture answers `comments: 0`), issue paging, and writes to closed or implied
issues. The reads of the read-only leftover lookup `findGithubConformanceLeftovers` (the open-issue
listing, the work issue's first comment page, and the work issue) are the ones the open-listing
case (`github.issues.open-listing`) records, so the lookup runs against the emulator: it finds
nothing on the default seed and lists an open `yolk-conformance run-*` issue the state holds.

* Request-shape latitude (`/github`, the only accepted deviations): any bearer value in the RFC 6750
  `b64token` syntax (`[A-Za-z0-9\-._~+/]+=*`) of at least 8 characters, starting with a character in
  `[G-Zg-z\-._~+/]` other than `n`, `r`, `t`, `u` (so a legacy all-hex token is refused), with at
  least one outside `[0-9.eE+-]`, that occurs nowhere else in the request (never compared against
  anything, stored, or ledgered); extra request headers; JSON key order; `content-type` media-type
  parameters; the order of query parameters; any non-empty issue title and comment body, and any
  issue body text; any comment listing `since` of the form `YYYY-MM-DDTHH:MM:SSZ` (or, instead of
  `since`, `page=1`); any label listing `per_page` from 1 to 100, with no `page` or a `page` from 2
  to one past the last page; any open-issue listing (`state=open`, `page=1`) `per_page` from 1 to
  100; any issue search `q` that starts with the seeded `repo:<owner>/<repo>` qualifier and whose
  query after it is longer than 256 characters (answered the recorded 422); any issue number the repository has not
  reached (answered the recorded 404); and any issue, comment, repository label, or file the state
  holds where a fixture has one, under the per-route state rules. `Authorization` must be exactly
  `Bearer <token>` (that spelling, one space), `Accept` `application/vnd.github+json`, and
  `X-GitHub-Api-Version` `2026-03-10`. Everything else (other keys and values, query parameters,
  empty query components such as a bare `?` or a stray `&`, another origin or repository, a repeated
  query key, an explicit `page=1` on the label listing, and a comment listing `per_page` other than 100) is not emulated.

Faults, the ledger (which records the `Accept` and `X-GitHub-Api-Version` headers), clock-free
recovery, and the control plane behave as in the Dropbox emulator; a 429 fault reaches the
connector as `github_rate_limited`. The `drills` option (eight booleans, one per GitHub case) is a
test-only knob that makes exactly the matching conformance case fail.

## Google emulator [#google-emulator]

`@yolk-sdk/emulators/google`

> **Experimental, Node only.** A stateful, fixture-only stand-in for the Gmail, Calendar, and Drive
> routes the Google conformance cases use, built on the same `@emulators/core` runtime (loaded
> lazily when you create an emulator).

| Export                                                  | Purpose                                                                                             |
| ------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
| `makeGoogleEmulator(options?)`                          | `Promise` of `{ fetch, fetchOn, ledger, faults, reset, seed, snapshot, coverage, close }`           |
| `googleEmulatorRoutes`                                  | Route evidence manifest (27 routes, all `unverified`; 15 are connector write routes)                |
| `GoogleEmulatorSeed`, `GoogleEmulatorProfile`           | Typed seed schema (messages, implied entities, attachments, calendars, events, Drive files)         |
| `GoogleFault`                                           | `{ kind: 'status', status (400-599), headers?, body?, match?: { method?, path?, route? }, count? }` |
| `GoogleEmulatorInputInvalid`                            | Invalid seed, fault, or option passed to the JS API                                                 |
| `googleEmulatorGmailOrigin`, `googleEmulatorApisOrigin` | `https://gmail.googleapis.com` and `https://www.googleapis.com`                                     |

```ts
import {
  googleEmulatorApisOrigin,
  googleEmulatorGmailOrigin,
  makeGoogleEmulator
} from '@yolk-sdk/emulators/google'
import { EmulatorRoute, InProcessHttpClient } from '@yolk-sdk/emulators/router'

const google = await makeGoogleEmulator()

const httpLayer = InProcessHttpClient.layer([
  EmulatorRoute.handler(googleEmulatorGmailOrigin, google.fetch),
  EmulatorRoute.handler(googleEmulatorApisOrigin, google.fetch)
])
```

It serves the Gmail routes the cases use (label listings of messages and of threads with page
tokens, message reads in the `format` renderings a fixture records, with an optional
`metadataHeaders` selection, attachments, the label listing and lifecycle, adding a created label,
trash and untrash, the draft search, the draft lifecycle and its thread, and the multipart practice
send), the Calendar event routes (time-range listings with page tokens, the free-text query, and a
run event created, read, renamed by `PATCH`, deleted to `cancelled`, and answered the recorded 410
when deleted again), and the Drive file routes (folder listings with page tokens, with or without
trashed items, reads with the connector `fields` selection, and a run folder created, trashed, and
deleted, then the recorded 404). Every route needs
`Authorization: Bearer <token>` (a recognisable bearer) and answers only on its recorded origin:
`fetch` reads the origin from the request URL; behind a loopback rewrite, serve `fetchOn(origin)`
for each origin on its own server.

**The leftover lookup's reads.** `findGoogleConformanceLeftovers` reads what four read cases
record: the label listing (`google.gmail.label-listing`: the seeded system and paging labels as
recorded, then the labels created here), the draft search (`google.gmail.draft-search`), the
free-text event query (`google.calendar.free-text-query`), and the folder listing with trashed
items (`google.drive.list-includes-trashed`). So the lookup runs against the default seed and lists
a run label or a run folder (in Trash too) the state holds. The draft search and the event query
are recorded only empty, and stay fixture-only: the draft search answers only while the state holds
no draft and no message labelled `DRAFT` (Gmail's search syntax is not emulated), and the event
query only while no event of the calendar, cancelled or not, holds `yolk` or `conformance` in any
case in its summary or description, nor, while the calendar holds events, its id or summary (the
organizer) or the practice address (the creator): Google's free-text matching cannot be emulated honestly. Otherwise
they answer the ledgered 400 not-emulated, so after the event cases, whose cancelled run events stay
in the state, the lookup fails closed and a runner prints its lookup-failed `WARN`.

**Draft attachments are not emulated.** `gmail.draft_compose`, `gmail.draft_update`, and
`gmail.draft_reply` with `attachments` write through the draft media upload
(`POST /upload/gmail/v1/users/me/drafts?uploadType=multipart`, or
`PUT .../drafts/{id}?uploadType=multipart`), which no fixture records, so it answers the constant
unrecognised 400 until a draft-attachment conformance case is recorded live. Drafts without
attachments are unaffected.

**The practice send is recorded, never delivered.** It is irreversible on Gmail; the emulator
accepts only the recorded 7-bit message whose sole recipient header is `To: <the seeded
practiceAddress>`, records it in its state (it reads back with the recorded headers, its `Date`
from the injectable `now` clock), and delivers nothing anywhere. A seed may set another
`practiceAddress`, but then every send is refused: the recorded `sizeEstimate` of the sent message
covers its address, as it covers the draft and send subjects (which therefore take only a run id of
the fixtures' length, 13 characters).

**Fail closed: the shared rule.** Google follows the same fail-closed rule as the GitHub emulator
above: every route parameter has a raw pattern matched in full, so a request is recognised only when
its raw path is exactly an emulated route shape and any `Authorization` header is exactly
`Bearer <token>` with a recognisable bearer (Google's `ya29.…` tokens qualify); every other request
is ledgered and answered with constant text only (the path `/<unrecognised>`, a standard method or
`<other>`, no query or body, a constant reason). The bearer value is never stored or ledgered: a
recognised request that repeats it in its path, query, recorded `content-type` header, or raw body
(the multipart send body included) or, on the draft routes, in the base64url-decoded MIME of
`message.raw`, through any depth of percent-encoding or JSON escaping, is ledgered as the constant
credential-repeat entry, and any other recognised request has it scrubbed from everything the ledger
keeps and every not-emulated message. A `message.raw` the route would refuse (anything but canonical
unpadded base64url of exactly the recorded draft MIME, the run id aside) makes the view throw a
`DecodedViewRefusal` with one of the route's declared constant reasons (`viewRefusalReasons`: the
canonical-base64url reason, the other-than-the-recorded-run-draft reason, the 13-character run-id
reason, the extra-key reason), which the wrapper ledgers in the constant entry before anything is
recorded (or `the request body repeats the credential` when the raw decodes cleanly to text holding
the bearer), so a refused `message.raw` never reaches the ledger. Refusals never echo a request's
own query or body keys.

Every answer value comes from a fixture, or is a value the emulator mints: created label ids above
every seeded label number, draft, message, event, and folder ids in forms seeds may not use, page
tokens (the fixtures' values on first issuance, `<token>.g<generation>` after a reset or seed, and a
distinct `<token>.v<k>` for another list or page size or a changed list: token values are globally
unique and never rebound), and timestamps from the `now` clock. Entities a fixture only names (the
paging label, the messages its listing names, their threads (named by the thread listing), the
practice Drive folder) are implied: references resolve through them, but no answer renders them. A
page token is accepted only when this emulator issued it for the same list since the last reset or
seed and the list renders exactly as when it was issued. Anything else answers one ledgered 400
not-emulated, writes nothing, and uses up no fault, including an empty listing and every read of
`findGoogleConformanceLeftovers` (its label listing, draft search, free-text event query, and
trashed-included Drive listing have no fixture): the lookup fails with
`GoogleConformanceActionFailed` (`gmail_list_labels_failed`, HTTP 400), which the live runner
reports as its lookup-failed `WARN`.

* Request-shape latitude (`/google`, the only accepted deviations): any bearer value in the RFC 6750
  `b64token` syntax (`[A-Za-z0-9\-._~+/]+=*`) of at least 8 characters, starting with a character in
  `[G-Zg-z\-._~+/]` other than `n`, `r`, `t`, `u`, with at least one outside `[0-9.eE+-]` (Google's
  `ya29.…` access tokens qualify), that occurs nowhere else in the request (never compared against
  anything, stored, or ledgered); extra request headers (except `X-Goog-Drive-Resource-Keys`, which
  no fixture sends); JSON key order; `content-type` media-type parameters on JSON requests; query
  parameters in any order; any `run-` run id (at most 40 characters) in a run-scoped label name,
  event summary, or folder name; in a draft subject (compose and update) and the sent subject, only
  a run id of exactly 13 characters, the length of the fixtures' `run-synthetic`, because the
  recorded `sizeEstimate` of the draft and sent messages (answered by their message reads and the
  draft thread) covers the subject; on the practice send, a `content-type` of exactly
  `multipart/related; boundary=<b>` with any one unquoted boundary of 1 to 70 `[A-Za-z0-9_]`
  characters and no other parameter; a `gmail.list`, `gmail.list_threads`, or `gmail.list_drafts`
  (the recorded `q` only) `maxResults` from 1 to 500, a `calendar.list_events` `maxResults` from 1
  to 2500 (a range, or the recorded `q`), and a `drive.list_files` `pageSize` from 1 to 1000 (with
  or without `and trashed = false`); any `timeMin` before `timeMax` (RFC 3339 instants with a real
  calendar date, hour
  0 to 23, minute and second 0 to 59, and a `Z` or in-range numeric offset); any id of an item the
  state holds where a fixture has an id (writes: only items created here, plus label changes, trash,
  and untrash of a stored non-draft message); and, for an id the state does not hold, only the
  recorded not-found answers (a `format=minimal` read of a 16-hex-digit message id, a read of a
  `Label_<1 to 999999999>` label, a delete of an `r-<digits>` draft, and a Drive file read); on a
  `format=metadata` message read, and on a `format=metadata` read of a thread of stored non-draft
  messages (a thread read in that format takes a selection), a `metadataHeaders` selection, repeated
  in any order, of 1 to 50 distinct header names each spelled exactly as a header of the recorded
  metadata rendering, answered as that rendering with only the selected headers, in recorded order.
  A seed may set another `practiceAddress`, but then every send is refused, since the recorded
  `sizeEstimate` of the sent message also covers the address: the send answers only while the seeded
  address is the recorded `practice@example.test`. On the draft compose and update routes,
  `message.raw` must be canonical unpadded base64url of exactly the recorded draft MIME of that
  route, the run id aside; any other `message.raw` (line-wrapped, the standard alphabet, padded,
  with a stray character, or with MIME-level encodings such as RFC 2047 encoded-words,
  quoted-printable other than the recorded parts, or UTF-16) is refused before anything is
  recorded or a fault is decided, as a constant entry with the route's own declared reason
  (`message.raw must be canonical base64url UTF-8 MIME`,
  `a draft compose other than the recorded run draft is not emulated` or its `update` form, the
  13-character run-id reason, or `message has a key this route does not take`), or
  `the request body repeats the credential` when that raw decodes cleanly to text holding the
  bearer, so a refused `message.raw` never reaches the ledger and an admitted one is the recorded
  text. `Authorization` must be exactly `Bearer <token>` (that spelling, one space). Everything else
  (other keys, values, formats, query parameters, empty query components such as a bare `?` or a
  stray `&`, recorded headers such as Drive's `accept: application/json` missing, another origin,
  repeated query parameters, any recipient but the seeded practice address, a draft or send run id
  of another length, a bearer repeated anywhere in the request, including base64url-encoded inside a
  draft's `message.raw`, and page tokens not issued for the same list since the last reset or seed,
  or whose list changed) is not emulated.

The default seed is the synthetic fixture entities with the ids of `googleConformanceFixtureSeeds`;
profiles `default` and `empty`. A reversible case ends at the seed except the counters and, for the
event cases, its own event, which stays readable as `cancelled`; the send leaves its sent message.
Faults, the ledger, clock-free recovery, and the control plane behave as in the Dropbox emulator; a
429 fault with `retry-after` reaches the connector as `google_rate_limited`. The `drills` option
(nineteen booleans, one per Google case) is a test-only knob that makes exactly the matching
conformance case fail.

## LinkedIn search emulator [#linkedin-search-emulator]

`@yolk-sdk/emulators/linkedin-search`

> **Experimental, Node only.** A stateful, fixture-only stand-in for the Exa and Enrich Layer
> routes the LinkedIn search conformance cases use, built on the same `@emulators/core` runtime
> (loaded lazily when you create an emulator).

| Export                                                                       | Purpose                                                                                             |
| ---------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
| `makeLinkedInSearchEmulator(options?)`                                       | `Promise` of `{ fetch, fetchOn, ledger, faults, reset, seed, snapshot, coverage, close }`           |
| `linkedInSearchEmulatorRoutes`                                               | Route evidence manifest (3 routes, all `unverified` reads)                                          |
| `LinkedInSearchEmulatorSeed`                                                 | Typed seed schema (searches, profiles, absent profile URLs, rejected keys per origin)               |
| `LinkedInSearchFault`                                                        | `{ kind: 'status', status (400-599), headers?, body?, match?: { method?, path?, route? }, count? }` |
| `LinkedInSearchEmulatorInputInvalid`                                         | Invalid seed, fault, or option passed to the JS API                                                 |
| `linkedInSearchEmulatorExaOrigin`, `linkedInSearchEmulatorEnrichLayerOrigin` | `https://api.exa.ai` and `https://enrichlayer.com`                                                  |
| `linkedInSearchEmulatorErrorBodies`                                          | The fixtures' 401 and 404 bodies, byte for byte                                                     |

```ts
import {
  linkedInSearchEmulatorEnrichLayerOrigin,
  linkedInSearchEmulatorExaOrigin,
  makeLinkedInSearchEmulator
} from '@yolk-sdk/emulators/linkedin-search'
import { EmulatorRoute, InProcessHttpClient } from '@yolk-sdk/emulators/router'

const linkedIn = await makeLinkedInSearchEmulator()

const httpLayer = InProcessHttpClient.layer([
  EmulatorRoute.handler(linkedInSearchEmulatorExaOrigin, linkedIn.fetch),
  EmulatorRoute.handler(linkedInSearchEmulatorEnrichLayerOrigin, linkedIn.fetch)
])
```

It serves three reads: the Exa people search (`POST /search` on `https://api.exa.ai`) and the
Enrich Layer profile and email lookups (`GET /api/v2/profile` and `GET /api/v2/profile/email` on
`https://enrichlayer.com`, with `linkedin_profile_url`). Every route needs
`Authorization: Bearer <key>` (a recognisable bearer; each provider takes its own key) and answers
only on its recorded origin: `fetch` reads the origin from the request URL; behind a loopback
rewrite, serve `fetchOn(origin)` for each origin on its own server.

Every answer comes from a fixture, byte for byte, through the seed, and nothing is written or
minted: a search answers only the results the state holds for exactly its query and `numResults`
(the default seed holds the fixtures' three answers for the seeded query, `numResults` 10, 3, and
2\); a profile lookup answers a held profile or, for a seeded absent profile, the recorded 404; an
email lookup answers a held profile's recorded email. A key the seed marks as rejected on an origin
answers that origin's recorded 401 (the default seed rejects the synthetic invalid keys the two
unauthorized cases send; a key rejected on one origin is accepted on the other). Anything else
answers one ledgered 400 not-emulated and uses up no fault, and every case ends exactly at its
seed.

**Fail closed: the shared rule, and keys kept only as digests.** LinkedIn search follows the same
fail-closed rule as the GitHub emulator above: a request is recognised only when its raw path is
exactly an emulated route path and any `Authorization` header is exactly `Bearer <key>` with a
recognisable bearer (a UUID-form key starts with a hex digit and is unrecognisable, so use a
synthetic key); every other request is ledgered with constant text only. A recognised request that
repeats its bearer in its path, query, recorded `content-type` header, or body, through any depth of
percent-encoding or JSON escaping, is ledgered as the constant credential-repeat entry, and any
other has it scrubbed from everything the ledger keeps. The bearer is never stored or ledgered:
through the shared wrapper's opt-in per-origin bearer digest, routes see only SHA-256 of the origin,
a space, and the key, which they compare with the digests of the seed's rejected keys for that
origin. The state holds only those digests, so a key a request carries as its bearer, a rejected one
included, never reaches the state, a snapshot, or `/_emulate/*` (a key sent as data elsewhere in a
request is ledgered like any other text), and no seed error quotes one: seed errors are constant
text, a category and a field path. This guarding covers the emulated provider API calls only:
`/_emulate/*` is the host's trusted control plane, and the seed and fault data a host gives it is
stored and returned as given.

* Request-shape latitude (`/linkedin-search`, the only accepted deviations): any bearer value in the
  RFC 6750 `b64token` syntax (`[A-Za-z0-9\-._~+/]+=*`) of at least 8 characters, starting with a
  character in `[G-Zg-z\-._~+/]` other than `n`, `r`, `t`, `u`, with at least one outside
  `[0-9.eE+-]`, that occurs nowhere else in the request (never stored or ledgered; only its
  per-origin digest is compared, with the digests of the keys the seed marks as rejected on that
  origin); extra request headers; JSON key order; `content-type` media-type parameters on the
  search; any percent-encoding of the `linkedin_profile_url` value that decodes once to the same
  profile URL; and, with a key the seed marks as rejected on the request's origin, any search
  `query` (one trimmed line of at most 500 characters) with any integer `numResults` from 1 to 100,
  and any profile URL of the form `https://<host>/in/<slug>`, each answered the origin's
  recorded 401. `Authorization` must be exactly `Bearer <token>` (that spelling, one space).
  Everything else (other body keys or values, a `category` other than `people`, a `type` other than
  `auto`, `contents` other than `{ "text": true }`, a search the state holds no answer for (another
  query, or a `numResults` no seeded search of that query records), a profile URL the state holds
  neither as a profile nor as absent, an email lookup of an absent profile, any query parameter on
  the search, other, missing, or repeated query parameters on a lookup, a query parameter name in
  any but its plain form (such as `%6cinkedin_profile_url`), empty query components such as a bare
  `?` or a stray `&`, a body on a lookup, another origin, and a bearer repeated anywhere in the
  request) is not emulated.

Seed with `seed: { searches?, profiles?, absentProfileUrls?, exaRejectedKeys?,
enrichLayerRejectedKeys? }` (each list replaces the default's). Faults, the ledger, recovery, and
the control plane behave as in the Dropbox emulator; the connector maps every non-2xx answer to its
action's failure code, so a 429 fault reaches it as `linkedin_search_failed` with status 429. The
`drills` option (seven booleans, one per LinkedIn search case) is a test-only knob that makes
exactly the matching conformance case fail.

## MCP emulator [#mcp-emulator]

`@yolk-sdk/emulators/mcp`

> **Experimental, Node only.** A stateful, fixture-only stand-in for the two synthetic MCP servers
> of the `@yolk-sdk/mcp/conformance` fixtures, for the Afloat MCP endpoint of the
> `@yolk-sdk/connectors/afloat/conformance` fixtures, and for the Figma MCP endpoint of the
> `@yolk-sdk/connectors/figma/conformance` fixtures, built on the same `@emulators/core` runtime
> (loaded lazily when you create an emulator).

| Export                                       | Purpose                                                                                                  |
| -------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
| `makeMcpEmulator(options?)`                  | `Promise` of `{ fetch, fetchOn, ledger, faults, reset, seed, snapshot, coverage, close }`                |
| `mcpEmulatorRoutes`                          | Route evidence manifest (21 rows: one `RPC <origin><path>#<method>` per method, plus `GET` and `DELETE`) |
| `McpEmulatorSeed`                            | Typed seed schema (`modernListing`, `legacyInitialize`; sessions are never seeded)                       |
| `McpFault`                                   | A status fault (400-599) or `{ kind: 'truncate-after-chunks', chunks, match?, count? }`                  |
| `McpEmulatorInputInvalid`                    | Invalid seed, fault, or option passed to the JS API                                                      |
| `mcpEmulatorOrigin`                          | `https://mcp.example.test` (paths `/modern/mcp` and `/legacy/mcp`)                                       |
| `mcpEmulatorReservedInvalidCredential`       | `yolk-conformance-invalid-credential-0000`, answered the recorded 401 on the era probe                   |
| `mcpEmulatorFixtures`                        | The sixteen synthetic MCP fixtures, copied as data                                                       |
| `mcpEmulatorServerPingFixtures`              | The opt-in server ping's synthetic legacy fixture, copied as data                                        |
| `mcpEmulatorAfloatOrigin`                    | `https://useafloat.com`: the origin of the `afloat` profile                                              |
| `mcpEmulatorAfloatPath`                      | `/mcp`: the path of the `afloat` profile (`https://useafloat.com/mcp`)                                   |
| `mcpEmulatorAfloatKeyPrefix`                 | `afloat_`: the public key prefix; the remainder after it is the guarded secret                           |
| `mcpEmulatorAfloatReservedInvalidCredential` | `afloat_yolkconformanceinvalid0000`, answered the recorded 401 on the Afloat era probe                   |
| `mcpEmulatorAfloatFixtures`                  | The eight derived Afloat MCP fixtures, copied as data                                                    |
| `mcpEmulatorFigmaOrigin`                     | `https://mcp.figma.com`: the origin of the `figma` profile                                               |
| `mcpEmulatorFigmaPath`                       | `/mcp`: the path of the `figma` profile (`https://mcp.figma.com/mcp`)                                    |
| `mcpEmulatorFigmaFixtures`                   | The eight synthetic Figma MCP fixtures, copied as data                                                   |

Setup fragment (not a runnable example): it builds the emulator and the `HttpClient` layer to
provide to the code under test, which then targets `https://mcp.example.test/{modern,legacy}/mcp`
with a synthetic `Authorization: Bearer` header; `await mcp.close()` when done.

```ts
import { makeMcpEmulator, mcpEmulatorOrigin } from '@yolk-sdk/emulators/mcp'
import { EmulatorRoute, InProcessHttpClient } from '@yolk-sdk/emulators/router'

const mcp = await makeMcpEmulator()

const httpLayer = InProcessHttpClient.layer([EmulatorRoute.handler(mcpEmulatorOrigin, mcp.fetch)])
```

It serves profile `synthetic-modern` on `https://mcp.example.test/modern/mcp` (stateless
`2026-07-28`: `server/discover`, `tools/list`, and `tools/call`, JSON answers) and profile
`synthetic-legacy` on `https://mcp.example.test/legacy/mcp` (the era probe's recorded 400 fallback,
`initialize`, `notifications/initialized`, the standing `GET` answered 405, `tools/list`,
`tools/call`, SSE answers, and the `DELETE` that ends a session, answered 200), so
`@yolk-sdk/mcp/client` and the MCP conformance cases run unchanged against it. Every request needs
`Authorization: Bearer <token>` (a recognisable bearer); behind a loopback rewrite, serve
`fetchOn(mcpEmulatorOrigin)`.

It also serves profile `afloat` on the provider endpoint `https://useafloat.com/mcp` (stateless
`2026-07-28`, JSON answers, no session, one listing page): the published nine-tool subset, the
`list-invoices` read call, its `VALIDATION_ERROR` tool error, the absent tool's JSON-RPC error (HTTP
200\), and the 401, all from the derived Afloat fixtures (from the provider's source, not recorded
live; unverified). Answering the two derived `tools/call` fixtures, rather than only recorded calls,
is in scope by the owner's decision; they stay unverified until a live call is recorded. Its
credential rule: an Afloat key is `afloat_` and a remainder, and `a` is a hex digit, so on
`https://useafloat.com` a bearer is recognised only as `afloat_<remainder>` whose remainder is a
recognisable bearer, and the remainder is the guarded secret (repeat checks, output guard, digest),
never stored, ledgered, or echoed. Use a synthetic key such as `afloat_synthetic-key-0001`; a
real-format key whose remainder starts with a hex digit, a bearer without `afloat_` there, and an
`afloat_` key on the synthetic origin are not emulated. Behind a loopback rewrite, serve
`fetchOn(mcpEmulatorAfloatOrigin)`.

It also serves profile `figma` on the provider endpoint `https://mcp.figma.com/mcp`, in the legacy
era exactly as `synthetic-legacy` (the session-less era probe answered 400, `initialize` minting a
session over SSE, `notifications/initialized` 202, the standing `GET` 405, the closing `DELETE` 200,
one listing page of six known Figma tool names with synthetic schemas, the `get_metadata` read call,
its tool error, the absent tool's SSE JSON-RPC error, and the 401), all from the synthetic Figma
fixtures (placeholders, not recorded live; unverified). Every legacy session is bound to the profile
that minted it, and a legacy profile answers only its own sessions. Its bearer follows the plain
recognisable-bearer rule (use a synthetic token such as `synthetic-figma-token-0001`), and the
public reserved invalid credential answers the Figma 401 on its era probe. Behind a loopback
rewrite, serve `fetchOn(mcpEmulatorFigmaOrigin)`.

The opt-in `mcp.legacy.server-ping` case of `@yolk-sdk/mcp/conformance` runs against
`synthetic-legacy` seeded with `{ legacyInitialize: 'server-ping' }` (default `plain`): `initialize`
then answers that case's fixture, whose SSE answer sends a `ping` request before its response, and
the session awaits the client's answer to that ping, which the `response:ping` row
(`https://mcp.example.test/legacy/mcp#response:ping`) accepts once with the recorded 202, in either
phase. The Figma profile records no ping and ignores the seed. Under that seed every applicable
legacy case passes too: the call gate understands a plain ping whose answer the server accepted
with 202 and no body, so the calling cases forward their `tools/call`; with the
`pingAnswerRejected` drill the gate refuses them (#382).

Every answer is a fixture's, byte for byte, with only the request id substituted at the recorded
place (the top-level `id` of a JSON answer, or of the SSE response event's payload; notification
events and SSE `id:` lines stay byte for byte), the minted session id in the recorded
`mcp-session-id` header, and the cursor of the current generation. `initialize` mints
`yolk-emu-session-<n>` from a counter that never resets (a form no seed holds); at most 256 sessions
are held, and another `initialize` is refused before any fault; the `DELETE` the client sends as it
closes a legacy operation (MCP `2025-11-25` basic/transports, "Session Management" item 5) answers
the recorded 200 on a ready session and ends it, so later requests on it are refused; `reset` and
`seed` clear the sessions. With `seed: { modernListing: 'two-pages' }`, `tools/list` answers the
recorded paged listing, whose first page issues `synthetic-cursor-0001` in the generation that first
issues it and `<cursor>.g<generation>` after a reset or seed; the second page answers only the
cursor issued in the current generation. The bearer is never stored, ledgered, or echoed: routes see
only its digest, compared only with the digest of the public reserved invalid credential (on the
Afloat profile, of the remainder of `afloat_yolkconformanceinvalid0000`) to answer its recorded 401.
Scope: the bearer is never copied from the request into a response, the state, or `/_emulate/*`; the
output guard also refuses a prepared fixture answer, minted session id, or cursor that happens to
contain it, but the emulator's other constants (state values such as `initializing`, wrapper headers
such as `x-emulator-evidence`) and host-configured control-plane data (a fault body) may
coincidentally equal a bearer and are not checked. A request that repeats the bearer in any header
name or value (not only the recorded headers), its path, query, or body, and a request whose
prepared answer or minted session id or cursor would repeat it (a bearer such as
`yolk-emu-session-1`, or `synthetic-mcp`, inside the recorded `yolk-synthetic-mcp`), is refused
before any fault is decided or anything is written. Every refusal, by shape or by state, is one 400
not-emulated ledgered with constant text only (`/<unrecognised>`, no query, headers, or body), and
it writes nothing and uses up no fault.

* Request-shape latitude (`/mcp`, the only accepted deviations): any bearer value in the RFC 6750
  `b64token` syntax (`[A-Za-z0-9\-._~+/]+=*`) of at least 8 characters, starting with a character in
  `[G-Zg-z\-._~+/]` other than `n`, `r`, `t`, `u`, with at least one outside `[0-9.eE+-]` (on the
  Afloat profile, `afloat_` followed by such a value: an Afloat key starts with the hex digit `a`,
  so its remainder after `afloat_` is the value checked, guarded, and digested), that occurs nowhere
  else in the request (any header name or value included) and in no answer or value the request
  would store (never stored or ledgered; only its digest is compared, with the digest of the public
  reserved invalid credential `yolk-conformance-invalid-credential-0000`, or on the Afloat profile
  of the remainder of `afloat_yolkconformanceinvalid0000`, each answering the recorded 401 on its
  profile's era probe); extra request headers, except `mcp-*` headers other than `mcp-method`,
  `mcp-name`, `mcp-protocol-version`, and `mcp-session-id`; a recorded header value sent as several
  headers that the HTTP layer joins into the recorded value; JSON key order; any JSON-RPC request id
  that is an integer from 0 to 2^53 - 1 or 1 to 64 printable ASCII characters where the recording
  has an id; any non-empty `name` and `version` (and no other key) in the `_meta` client info
  (`io.modelcontextprotocol/clientInfo`) of a modern request; a session id this emulator minted on
  the same profile since the last reset or seed, and that no `DELETE` has ended, where the recording
  sends `mcp-session-id` (initializing for `notifications/initialized`, either phase for the answer
  to the server ping, ready otherwise); on the `DELETE` that ends a session, an `accept` of any
  media type (the Fetch default an HTTP layer adds where the recording sends none); and, with the
  seed's `two-pages` listing, the cursor this emulator issued in the current generation on the
  second page. `Authorization` must be exactly `Bearer <token>` (that spelling, one space).
  Everything else (another origin or path, any query, other HTTP methods, a `GET` or `DELETE` on the
  modern or Afloat profile, a bearer without `afloat_` on the Afloat profile or with it on the
  synthetic profiles, an Afloat key whose remainder fails the rule above (such as one starting with
  a hex digit), JSON-RPC methods no fixture of the profile records such as `ping`, `resources/*`, or
  `prompts/*`, batches, client-sent responses other than the answer to the recorded server ping
  (exactly as recorded, the server's ping id included, on a session awaiting it), other members, a
  JSON body repeating a key (compared after unescaping), a `null`, negative, or fractional id, other
  params (other tools, arguments, protocol versions, or capabilities, extra client-info keys, a
  cursor on the Afloat listing, and a legacy `initialize` client info other than the recorded one),
  the MCP headers `accept`, `content-type`, `mcp-method`, `mcp-protocol-version`, `mcp-name`, and
  `last-event-id` other than the recorded values or present where none is recorded, any other
  `mcp-*` header (such as `mcp-param-*`), `mcp-session-id` missing where recorded or present where
  not, an unknown session or one in the wrong phase, a cursor not issued in the current generation,
  a reserved invalid credential on anything but its profile's era probe, a bearer repeated anywhere
  in the request, and a bearer an answer or a minted session id or cursor would repeat)
  is not emulated.

Not emulated: the client's own `ping`, `resources/*`, `prompts/*`, `logging/*`,
`completion/*`, `tasks/*` (`@yolk-sdk/mcp/client` sends none of them), JSON-RPC batches, client-sent
responses other than the answer to the recorded server ping, a JSON body repeating a key, `mcp-*`
headers no recording carries (such as `mcp-param-*`), cursors the emulator did not issue, any other
tool or arguments, and a missing `Authorization`. Status and `truncate-after-chunks` faults apply
only after a request is admitted and planned, and a faulted request writes nothing: a truncation
sends the prepared answer cut short and never runs its commit (a truncated `initialize` mints no
session; a truncated first page issues no cursor; a faulted `DELETE` ends nothing). Truncating a
legacy SSE answer after its first chunk ends the stream before the response, so the client fails as
an `McpError` at its timeout instead of hanging. In `match`, `method` is the HTTP method and `route`
one manifest row; a `route` naming no row is rejected when the fault is added. `makeMcpEmulator`
throws when a copied recording is not canonical JSON. The ledger, recovery, and the control plane
behave as in the Dropbox emulator. The `drills` option (eleven booleans: one per MCP case, the
opt-in server ping included, and `sessionEndRejected`, a second `mcp.legacy.session` knob that
answers the `DELETE` 500) is a test-only knob that makes exactly the matching conformance case fail,
on every profile whose answers it changes (the Afloat profile included, except the legacy-only
session knob; `pingAnswerRejected` changes nothing without the `server-ping` seed).

## Kie emulator [#kie-emulator]

`@yolk-sdk/emulators/kie`

> **Experimental, Node only.** A stateful, fixture-only stand-in for the Kie Market API task read
> and create routes the Kie conformance cases use, built on the same `@emulators/core` runtime
> (loaded lazily when you create an emulator).

| Export                          | Purpose                                                                                             |
| ------------------------------- | --------------------------------------------------------------------------------------------------- |
| `makeKieEmulator(options?)`     | `Promise` of `{ fetch, fetchOn, ledger, faults, reset, seed, snapshot, coverage, close }`           |
| `kieEmulatorRoutes`             | Route evidence manifest (2 routes, `unverified`; `POST /api/v1/jobs/createTask` is a write)         |
| `KieEmulatorSeed`               | Typed seed schema (finished tasks, absent task ids, rejected keys)                                  |
| `KieFault`                      | `{ kind: 'status', status (400-599), headers?, body?, match?: { method?, path?, route? }, count? }` |
| `KieEmulatorInputInvalid`       | Invalid seed, fault, or option passed to the JS API                                                 |
| `kieEmulatorOrigin`             | `https://api.kie.ai`                                                                                |
| `kieEmulatorErrorBodies`        | The fixtures' not-found (`code` 422) and 401 bodies, byte for byte                                  |
| `kieEmulatorCreatedId(counter)` | The minted created-task id form (`yolk_synthetic_task_created_0001`)                                |

```ts
import { kieEmulatorOrigin, makeKieEmulator } from '@yolk-sdk/emulators/kie'
import { EmulatorRoute, InProcessHttpClient } from '@yolk-sdk/emulators/router'

const kie = await makeKieEmulator()

const httpLayer = InProcessHttpClient.layer([EmulatorRoute.handler(kieEmulatorOrigin, kie.fetch)])
```

It emulates only `GET /api/v1/jobs/recordInfo` and `POST /api/v1/jobs/createTask`, so the Kie
connector actions and the Kie conformance cases run unchanged against it. `recordInfo` answers a
held finished task's record (the default seed: the fixtures' `success` and `fail` tasks), the
recorded not-found envelope (`code` 422 at HTTP 200) for a seeded absent task id, and, for a key the
seed marks as rejected (kept only as its digest), the recorded 401 for any well-formed task id.
`createTask` accepts only the two recorded create flows (GPT Image 2 text-to-image, square at `1K`;
Wan 2.7 image-to-video, `720p` for 5 seconds) and answers envelope `code` 200 with a minted
`yolk_synthetic_task_created_<n>` task id (in suite order on a fresh emulator, the fixtures' ids). A
create is irreversible on Kie, so the emulator records each created task in the state, never
readable; a faulted create records nothing. The create route is a connector write: its evidence
stays pending until an owner-approved live run of the two create cases. Every request needs
`Authorization: Bearer <key>` (a recognisable bearer) and `Accept: application/json`; anything else
answers a ledgered 400 not-emulated.

* Request-shape latitude (`/kie`, the only accepted deviations): any bearer value in the RFC 6750
  `b64token` syntax (`[A-Za-z0-9\-._~+/]+=*`) of at least 8 characters, starting with a character in
  `[G-Zg-z\-._~+/]` other than `n`, `r`, `t`, `u`, with at least one outside `[0-9.eE+-]`, that
  occurs nowhere else in the request (never stored or ledgered; only its digest is compared, with
  the digests of the keys the seed marks as rejected); extra request headers; JSON key order;
  `content-type` media-type parameters on the create; with a key the seed marks as rejected, any
  `recordInfo` task id of 1 to 128 letters, digits, underscores, or hyphens, answered the recorded
  401; any non-empty `prompt` within the connector's limit (20000 characters for GPT Image 2, 5000
  for Wan 2.7); and any absolute https `first_frame_url` without credentials or whitespace of at
  most 2048 characters. `Authorization` must be exactly `Bearer <token>` (that spelling, one space),
  and `Accept` `application/json`. Everything else (a request without `Authorization`, other body
  keys or values, a `callBackUrl`, another model, aspect ratio, resolution, or duration,
  `input_urls`, a task id the state holds neither as a finished task nor as absent, a created task's
  `recordInfo`, a create with a rejected key, any query parameter on the create, other, missing, or
  repeated query parameters on `recordInfo`, a query parameter name in any but its plain form, empty
  query components such as a bare `?` or a stray `&`, another origin, and a bearer repeated anywhere
  in the request) is not emulated.

## Node server [#node-server]

`@yolk-sdk/emulators/node`

| Export                                    | Purpose                                                                           |
| ----------------------------------------- | --------------------------------------------------------------------------------- |
| `serveFetchHandler(handler, { port? })`   | Scoped Effect resource `{ url, close }` serving on `127.0.0.1` (port `0` default) |
| `startFetchHandlerServer(handler, opts?)` | The same server as a Promise `{ url, close }`, for non-Effect test runners        |
| `EmulatorServeError`                      | Refused host, invalid port, or listen failure                                     |

Only `127.0.0.1` is accepted as a host. Streamed bodies are written chunk by chunk, so progressive
delivery survives the socket; a body stream error drops the connection.

## Evidence [#evidence]

Emulated routes carry evidence: `verified` routes follow a live observation dated by `observedAt`;
`unverified` routes follow synthetic placeholders. Fetch-handler emulators tag every response from
an unverified route with `x-emulator-evidence: unverified`; the email and R2 emulators' plain-JSON
replies carry no header, so they record the evidence on each ledger entry instead. The Gateway route
is verified (`observedAt: '2026-09-30'`): the emulator follows the verified live Gateway recordings,
and the Yolk repository checks its response shapes against each recording. The OpenAI, Anthropic,
Codex, Grok, OpenCode Go, subscription-usage, email, R2, Fortnox, Microsoft, Dropbox, Notion,
Todoist, Telegram, GitHub, Google, LinkedIn search, and MCP routes are unverified, like the
synthetic fixtures they follow (the LinkedIn search routes and the MCP rows are reads, so none is
held in the pending list).
The email write routes are connector writes: until an owner-approved live run against a practice
mailbox, through a host `EmailClient` implementation, verifies them, the repository lists them in a
time-bounded allowlist (`scripts/emulator-evidence-pending.json`), and the evidence check reports
them as PENDING warnings until each entry's expiry date and fails again after it. The R2
`R2ObjectClient.put` route is held in the same list until a live run against a practice bucket,
through a host `R2ObjectClient` implementation, verifies it. The four Fortnox write routes, the
twelve Microsoft write routes, the five Dropbox write routes, the two Notion write routes, the five
Todoist write routes, the Telegram `sendMessage` route, the six GitHub write routes, and the fifteen
Google write routes are held in the same pending list until a live run against a Fortnox test
company, a Microsoft practice tenant, a Dropbox practice account, a Notion practice workspace, a
Todoist practice account, a practice bot, a GitHub practice repository, or a practice Google account
verifies them.


---

# Harness APIs

URL: /docs/api-reference/harness

Public harness subpaths and commonly used exports.



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

`@yolk-sdk/harness` is introduced after `0.1.0-canary.76`. See [Harness package](../harness) for installation and a runnable memory-host drain.

## Coordinator [#coordinator]

`@yolk-sdk/harness/coordinator`

| Export            | Purpose                                                                                                                                |
| ----------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `Promotable`      | `'input' \| 'steer'`; input subsumes steer when coalescing wakes                                                                       |
| `CapturedRun`     | `Started` / `Joined` / `Stopping` waiter                                                                                               |
| `StopReceipt`     | `Idle` / `Interrupted` / `LiveStopping` / `Settling`                                                                                   |
| `Coordinator`     | Process-local doorbell coordinator shape                                                                                               |
| `makeCoordinator` | Build a process-local coordinator                                                                                                      |
| `RunCoordinator`  | Owning service; `.layer({ drain, keepClaimOnSettle })` needs `RunStore`; `keepClaimOnSettle` true keeps an uninterrupted owner's claim |

The `drain` callback of `RunCoordinator.layer` and `makeCoordinator` gets a fourth argument,
`stopping`: an effect reading that execution's stopping flag. Forward it to `Inbox.beginDrain`.

## Store [#store]

`@yolk-sdk/harness/store`

| Export                      | Purpose                                              |
| --------------------------- | ---------------------------------------------------- |
| `RunStore`                  | Claim/release service                                |
| `RunStoreApi`               | Claim, release, claimed-id, and resume-count methods |
| `DurableRunStoreSnapshot`   | `{ claimed, resumes }` snapshot                      |
| `makeInMemoryRunStoreLayer` | Process-local claim store                            |
| `makeSnapshotRunStoreLayer` | Persist claims through host `load` / `save`          |

`RunStore.inMemoryLayer()` owns process-local claims; `RunStore.snapshotLayer({ load, save })`
owns snapshot-backed claims. Both build fresh layers without service dependencies. The existing
`makeInMemoryRunStoreLayer` / `makeSnapshotRunStoreLayer` factories delegate to these owners.

The snapshot stores claimed ids and resume counts. It is not transcript storage and does not persist Inbox items or HITL parks.

## Inbox [#inbox]

`@yolk-sdk/harness/inbox`

| Export                   | Purpose                                                               |
| ------------------------ | --------------------------------------------------------------------- |
| `Inbox`                  | Admission, park, and drain-token service                              |
| `InboxApi`               | Service methods for admission, queueing, HITL parks, and drain tokens |
| `InboxItem`              | Queued input/HITL item (`id`, `runId`, `delivery`, `kind`)            |
| `InboxKind`              | `'input' \| 'hitl'`                                                   |
| `ParkedResponse`         | `{ itemId, requestId }`                                               |
| `ParkedState`            | Generation, non-empty request ids, responses, ready                   |
| `HitlAdmission`          | `{ itemId, requestId, generation }`                                   |
| `HitlDecision`           | Accepted / Ready / Duplicate / Stale / UnknownRequest / NotParked     |
| `PauseDecision`          | `Parked` or `Stale`                                                   |
| `DrainBegin`             | `Skip` or `Run` with `drainToken` and ready responses                 |
| `makeInMemoryInboxLayer` | Process-lifetime Inbox                                                |

`DrainToken` and `ParkGeneration` are also schema/type exports from this subpath. `DrainContext`,
dequeue/pause/end-drain contracts use `DrainToken`; park state, admission, and `clearPark` use
`ParkGeneration`. Forward values returned by the live Inbox. Custom adapters must construct/decode
these types; they still serialize as strings. The schemas intentionally validate only string shape,
not token format, freshness, or authorization.

`Inbox.layer()` owns a fresh process-local queue, admission gate, and HITL generations with no
service dependencies. `makeInMemoryInboxLayer` delegates to it.

`park(runId, requestIds, drainToken)` (and `Driver.pause`) takes a non-empty
`Array.NonEmptyReadonlyArray<string>`: a park with no request ids would be Ready at once and keep
the claim with nothing to wake the run. Map `StepOutcome.AwaitingInput` `requests` (non-empty) with
Effect's `Array.map`; check a host-built list with `Array.isReadonlyArrayNonEmpty`. The type
enforces this; an empty list at runtime (an untyped caller) is a defect that dies before any park
state changes.

`takePromotable(runId, scope, drainToken)` requires the live `beginDrain` token. Missing, empty, inactive, stale, or wrong-run tokens return `undefined` and do not dequeue.

`beginDrain(runId, scope, stopping?)` returns `Skip` without consuming pending intent when `stopping` reads true under the admission gate. Driver passes the owner's stopping flag, so a message admitted right after an interrupt drains in the successor. An Inbox implementation must read `stopping` under the same lock that consumes intent and, when it is true, return `Skip` without touching pending intent; a wrapper must forward it. Driver now runs `beginDrain` uninterruptibly, so keep it short and non-blocking.

## Driver [#driver]

`@yolk-sdk/harness/driver`

| Export                     | Purpose                                                      |
| -------------------------- | ------------------------------------------------------------ |
| `Driver`                   | Run, wake, interrupt, admit, pause, resume, clear park, stop |
| `DriverApi`                | Driver service method contract                               |
| `Drain`                    | Host execution; see signature below                          |
| `DrainContext`             | `{ drainToken, readyResponses }`                             |
| `makeDriverLayer`          | Driver layer; default drain is `Effect.void`                 |
| `makeHarness`              | Merge driver + store + inbox layers                          |
| `admit`                    | Enqueue an inbox item and wake                               |
| `defaultMaxResumeAttempts` | `10`                                                         |
| `InvalidMaxResumeAttempts` | Layer-init failure for invalid budgets                       |
| `ResumeSuspendedResult`    | `{ resumed, exhausted }`                                     |
| `StopDecision`             | `Interrupted` / `ParkCleared` / `Idle`                       |
| `InterruptReason`          | `'user' \| 'shutdown'`                                       |

`Driver.layer({ maxResumeAttempts })` requires `RunStore`, `Inbox`, and `RunCoordinator`.
`Driver.coordinatedLayer({ drain, maxResumeAttempts })` wires the coordinator and requires only
`RunStore` and `Inbox`; `makeDriverLayer` delegates to it. Omitted budgets use the default; invalid
numeric budgets fail layer initialization with `InvalidMaxResumeAttempts`. Share the same store
and inbox instances across the composed layers, or use the memory/durable-object factories below.

Fragment. Exported `Drain` type:

```ts
type Drain = (
  runId: string,
  force: boolean,
  scope: Promotable,
  context: DrainContext
) => Effect.Effect<void, never, Inbox | RunStore>
```

The driver provides `Inbox` and `RunStore` to the drain. Provide any additional host dependencies before passing `drain`.

`interrupt` acknowledges request delivery, not owner settlement. User stop releases a leftover claim after that owner has settled. Shutdown interrupt keeps the claim. A drain defect releases it, except while the run has a Ready park: the claim stays (also through a successor that skips and succeeds), and a later `resumeSuspended` in the same process re-delivers those answers under `maxResumeAttempts`. Hosts that want in-process recovery after a crashed continuation run `resumeSuspended` during runtime, not only at boot; after a restart the host rebuilds the park from its checkpoint.

`clearPark(runId, generation)` drops a park without its answers and wakes the run for input admitted while it blocked. Raw `Inbox.clearPark` takes that wake effect as its third argument.

`@yolk-sdk/harness/driver/memory`

| Export                     | Purpose                           |
| -------------------------- | --------------------------------- |
| `makeInMemoryDriverLayer`  | In-memory driver over Store/Inbox |
| `makeInMemoryHarnessLayer` | In-memory driver + store + inbox  |

`@yolk-sdk/harness/driver/durable-object`

| Export                         | Purpose                                                |
| ------------------------------ | ------------------------------------------------------ |
| `makeDurableObjectDriverLayer` | Snapshot `RunStore` plus driver; Inbox stays in-memory |
| `DurableRunStoreSnapshot`      | Re-exported claim snapshot                             |

Fragment. Hosts supply `load` / `save`; this is not a Cloudflare runtime API:

```ts
import { Effect, Ref } from 'effect'
import { makeDurableObjectDriverLayer } from '@yolk-sdk/harness/driver/durable-object'
import type { DurableRunStoreSnapshot } from '@yolk-sdk/harness/store'

const snapshot = await Effect.runPromise(Ref.make<DurableRunStoreSnapshot | undefined>(undefined))

const DurableLayer = makeDurableObjectDriverLayer({
  load: Ref.get(snapshot),
  save: next => Ref.set(snapshot, next)
})
```

That adapter does not persist Inbox, closures, or automatically reconstruct work.

## Outcome [#outcome]

`@yolk-sdk/harness/outcome`

| Export                | Purpose                                                          |
| --------------------- | ---------------------------------------------------------------- |
| `attemptModelTurn`    | Classify one `runModelTurn` after that stream's inner retries    |
| `attemptToolBatch`    | Classify one `runToolBatch`; pending HITL fences the whole batch |
| `ModelTurnOutcome`    | `Completed` / `Retry` / `Continue` / `RecoverFull` / `Compacted` |
| `ToolBatchOutcome`    | `Completed` / `AwaitingInput` (non-empty `requests`)             |
| `StepOutcome`         | Model or tool-batch outcome                                      |
| `matchHitlResponse`   | Protocol identity match for a HITL response                      |
| `resumeHitlIfMatched` | Resume only when kind/request/tool-call identity matches         |

`attemptModelTurn` does not add an outer retry loop. Configured `LoopConfig.maxRetries` and provider retry decorators still apply inside that invocation. Hosts that own physical-attempt scheduling should pass `maxRetries: 0` and skip retry decorators.

`onEvent` sink errors, compact errors, Abort, and mixed defect/interrupt Causes are not classified as provider `Retry` / `Continue`. Incomplete streams use `responseIssue: 'missing_done'` only (set by the kernel, or by a provider whose stream ended without its terminal event).


---

# Integration APIs

URL: /docs/api-reference/integrations

Public MCP, knowledge, connector, sandbox, code mode, and file extraction APIs.



## Portable connector annotations [#portable-connector-annotations]

`PortableMetadata` is exported from `@yolk-sdk/connectors` and owns optional integration/binding
metadata. Decode/make produce mutable snapshot data (null-prototype objects, dense ordinary arrays,
finite JSON primitives); input identity is not preserved and DAG aliases share copied nodes.
Exotics, cycles, hidden/symbol keys and accessors fail, without invoking accessors. Omission stays
absent. This does not narrow integration config, credential secrets, error causes or host DB columns.

## MCP [#mcp]

Yolk tool discovery admits object-root plain JSON `inputSchema` documents. Boolean roots fail with
typed `McpError` validation; omitted schemas retain the permissive object default. This is not
JSON Schema meta-validation.

| Subpath                     | Main exports                                                                                                                                     |
| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| `@yolk-sdk/mcp/client`      | Official `Client`, Streamable HTTP, full-core client types/helpers, plus Effect/Yolk tool list/call adapters                                     |
| `@yolk-sdk/mcp/client/node` | Official `StdioClientTransport` plus NodeServices wrappers for Yolk local tool helpers                                                           |
| `@yolk-sdk/mcp/conformance` | Experimental MCP conformance cases, target, seeds, and synthetic fixtures; see [MCP conformance](./conformance#mcp-conformance)                  |
| `@yolk-sdk/mcp/core`        | Official MCP v2 Zod wire schemas                                                                                                                 |
| `@yolk-sdk/mcp/protocol`    | Yolk JSON-RPC/MCP adapter schemas and helpers                                                                                                    |
| `@yolk-sdk/mcp/server`      | Official `McpServer`, `createMcpHandler`, resources, prompts, completions, MRTR, subscriptions, plus `makeMcpToolServer` and `runStdioMcpServer` |
| `@yolk-sdk/mcp/server/node` | Official `serveStdio` and `StdioServerTransport`                                                                                                 |

`McpClientOptions.exposure` (`McpToolExposureResolver`) sets code mode exposure on listed tool
definitions. Adapted tools are typed
([ADR 0013](https://github.com/magoz/yolk-sdk/blob/main/docs/adr/0013-typed-tool-results.md)):
`mcpToolToToolDef` declares `ToolDef.outputSchema` `{ value, files }` (`mcpToolOutputSchema`, with
a plain-object MCP `outputSchema` as `value`), and calls return `mcpToolResult` (`value` the
server's `structuredContent` or text, `files` its blobs, images and audio). `@yolk-sdk/mcp/client`
also exports `McpToolOutput` (that envelope as a Schema), `mcpToolOutputDecoder` (the
`decodeOutput` registrations built from these defs must set), `mcpTextValue`, and the
`fileCapture` call option. See [Add MCP tools](../integrations/mcp-tools) and
[Connector and MCP tools](../integrations/code-mode#connector-and-mcp-tools).

Both `@yolk-sdk/mcp/client` and `@yolk-sdk/mcp/protocol` export these Effect Schema owners:

| Schema                    | Fields                                                  |
| ------------------------- | ------------------------------------------------------- |
| `InitializeClientInfo`    | `name`, `version`                                       |
| `InitializeParams`        | `protocolVersion`, `capabilities`, `clientInfo`         |
| `InitializedNotification` | `jsonrpc: '2.0'`, `method: 'notifications/initialized'` |
| `ToolsCallParams`         | `name`, optional opaque `arguments`                     |

Use their `.make` constructors for typed values and Effect Schema decoders for raw input.
Compatibility helpers `makeJsonRpcRequest`, `makeInitializeParams`, and
`makeInitializedNotification` remain available. Requests omit `params` when it is `undefined`.

## Knowledge [#knowledge]

| Subpath                             | Main exports                                                                                           |
| ----------------------------------- | ------------------------------------------------------------------------------------------------------ |
| `@yolk-sdk/knowledge`               | `buildKnowledgeContext`, `KnowledgeStore`, `SearchIndexStore`, `KnowledgeFileBlobStore`, shared errors |
| `@yolk-sdk/knowledge/documents`     | document, file, chunk, scope, status, availability schemas                                             |
| `@yolk-sdk/knowledge/files`         | `KnowledgeFileBlobStore`                                                                               |
| `@yolk-sdk/knowledge/context`       | pinned context assembly helpers                                                                        |
| `@yolk-sdk/knowledge/store`         | document store and search-index store contracts                                                        |
| `@yolk-sdk/knowledge/errors`        | shared knowledge error types                                                                           |
| `@yolk-sdk/knowledge/ingestion`     | `ingestKnowledgeDocument`, `makeIngestionPipeline`                                                     |
| `@yolk-sdk/knowledge/search`        | `searchKnowledge`, `packKnowledgeSearchContext`                                                        |
| `@yolk-sdk/knowledge/chunking`      | `KnowledgeChunker`, `DefaultKnowledgeChunkerLive`, `chunkKnowledgeText`, `countKnowledgeChunkTokens`   |
| `@yolk-sdk/knowledge/embeddings`    | `KnowledgeEmbedder`                                                                                    |
| `@yolk-sdk/knowledge/extraction`    | `KnowledgeExtractor` and source types                                                                  |
| `@yolk-sdk/knowledge/summarization` | `KnowledgeSummarizer`, `NoopKnowledgeSummarizerLive`                                                   |
| `@yolk-sdk/knowledge/agent`         | `makeKnowledgeLookupTool`, `makeKnowledgeManageTool`, `KnowledgeLookupOutput`, `KnowledgeManageOutput` |

`@yolk-sdk/knowledge/documents` exposes validated source/scope constructors:

| Constructor                  | Variant / fields                             |
| ---------------------------- | -------------------------------------------- |
| `KnowledgeFileSource.make`   | `File`: `ref`, optional `name` / `mediaType` |
| `KnowledgeUrlSource.make`    | `Url`: `url`                                 |
| `KnowledgeTextSource.make`   | `Text`: optional `label`                     |
| `KnowledgeSearchScope.make`  | `KnowledgeScope`: `id`                       |
| `KnowledgeSearchScopes.make` | `KnowledgeScopes`: non-empty `ids`           |

The type `KnowledgeSearchScope` remains the union of both scope variants; its value constructor
creates only the single-id variant. `KnowledgeScopeId` and `KnowledgeDocumentId` are exported
schema/type companions from `@yolk-sdk/knowledge/documents`; scope/document references throughout
stores, chunking, ingestion, and search use them. Decode external IDs, use `.make` for trusted
constants, and keep host access checks. Encoded identities remain strings.

## Connectors [#connectors]

`defineAction` accepts optional `access: 'read' | 'write' | 'destructive'` metadata, exported as
`ConnectorActionAccess`. `makeConnectorToolModule` uses it unless the host supplies an access
override.

`defineAction` returns `TypedConnectorAction<InputSchema, Output, Env, Error>` (type exported from
`@yolk-sdk/connectors`). Its additive `executeTyped` method accepts decoded `InputSchema.Type`
and retains `ActionResult<Output>`. It validates the type-side schema without replaying wire
transforms. Existing `execute` and connector `invoke` remain dynamic decoding boundaries;
implementations still validate external outputs themselves.

| Subpath                                            | Main exports                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| -------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `@yolk-sdk/connectors`                             | `defineConnector`, `defineAction`, `makeIntegration`, `makeCredentialBinding`, `CredentialResolver`, `ConnectorHttpClient`, `ConnectorBinaryHttpClient`, `ConnectorBinaryHttpStreamResponse`, `ConnectorBinaryWriteHttpClient`, `ConnectorBinaryHttpError`, `ConnectorFileTransferError`, `ConnectorFileTransferBudget`, `ConnectorFileStream`                                                                                                                                                                                                                                                            |
| `@yolk-sdk/connectors/agent`                       | `makeConnectorToolModule`, `makeConnectorToolRegistration`, `ConnectorToolExposureResolver`, `ConnectorToolActionInfo`; the `exposure` option sets code mode exposure per tool, action `outputSchema` passes through to `ToolDef.outputSchema`, results are its JSON encoding, and `description` overrides the module description (default: the connector's)                                                                                                                                                                                                                                              |
| `@yolk-sdk/connectors/conformance`                 | Experimental, conformance/testing only: `connectorHttpClientFromEffectHttpClientLayer`, `connectorBinaryHttpClientFromEffectHttpClientLayer`, `connectorBinaryWriteHttpClientFromEffectHttpClientLayer`, `connectorHttpClientsFromEffectHttpClientLayer`, `staticCredentialResolverLayer`, `ConformanceCleanupReporter`                                                                                                                                                                                                                                                                                   |
| `@yolk-sdk/connectors/afloat`                      | `AfloatConnector`, `AfloatApiKeyCredentialSlot`, MCP endpoint and protocol constants                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `@yolk-sdk/connectors/afloat/conformance`          | Experimental: `makeAfloatMcpConformanceTarget`, `afloatMcpConformanceLiveSeeds`, `afloatMcpConformanceFixtureSeeds`, `afloatMcpConformanceFixtures`, `afloatMcpConformanceTools` for the `@yolk-sdk/mcp/conformance` cases ([Afloat MCP conformance](../connectors/afloat#conformance-cases))                                                                                                                                                                                                                                                                                                             |
| `@yolk-sdk/connectors/dropbox`                     | `DropboxConnector`, Dropbox OAuth slots, metadata schemas, file actions, host-only `downloadDropboxFile`, `streamDropboxFile`, `getDropboxTemporaryLink`, `createDropboxFile`, `updateDropboxFile`                                                                                                                                                                                                                                                                                                                                                                                                        |
| `@yolk-sdk/connectors/dropbox/conformance`         | Experimental: `dropboxConformanceCases`, `DropboxConformanceConfig`, `dropboxConformanceFixtures`, `dropboxConformanceFixtureSeeds` ([Conformance APIs](./conformance#connector-conformance))                                                                                                                                                                                                                                                                                                                                                                                                             |
| `@yolk-sdk/connectors/email`                       | `EmailConnector`, `EmailClient`, connection/message schemas, incoming and SMTP credential slots                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `@yolk-sdk/connectors/email/conformance`           | Experimental: `emailConformanceCases`, `EmailConformanceConfig`, `emailConformanceFixtures` (`PortFixture`s), `emailConformanceFixtureSeeds`, `emailClientLayerFromBackend`, `emailClientFromBackend`, `makeEmailReplayBackend`, `emailMessageNotFoundCode`; helpers `emailPortRequestJson`, `emailBackendMethods`, `emailPortName` ([Conformance APIs](./conformance#connector-conformance))                                                                                                                                                                                                             |
| `@yolk-sdk/connectors/fortnox`                     | `FortnoxConnector`, shared/resource-scoped OAuth slots, read/write/destructive actions, resource/input/output schemas, host-only preview/archive/inbox byte helpers                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `@yolk-sdk/connectors/fortnox/conformance`         | Experimental: `fortnoxConformanceCases`, `fortnoxReadConformanceCases`, `FortnoxConformanceConfig`, `fortnoxConformanceFixtures`, `fortnoxConformanceFixtureSeeds` ([Conformance APIs](./conformance#connector-conformance))                                                                                                                                                                                                                                                                                                                                                                              |
| `@yolk-sdk/connectors/github`                      | `GithubConnector`, `githubActions`, `GithubTokenSlot`, `GithubUploadTokenSlot`, issue/PR/repository actions and schemas, host-only `createGithubAppInstallationToken` and `uploadGithubAttachment`                                                                                                                                                                                                                                                                                                                                                                                                        |
| `@yolk-sdk/connectors/github/conformance`          | Experimental: `githubConformanceCases`, `GithubConformanceConfig`, `githubConformanceFixtures`, `githubConformanceFixtureSeeds`, `findGithubConformanceLeftovers` ([Conformance APIs](./conformance#connector-conformance))                                                                                                                                                                                                                                                                                                                                                                               |
| `@yolk-sdk/connectors/google`                      | `GoogleConnector`, shared Google OAuth slots, Gmail/Calendar/Drive actions and schemas, host-only Drive/Gmail byte helpers                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `@yolk-sdk/connectors/google/conformance`          | Experimental: `googleConformanceCases`, `GoogleConformanceConfig`, `googleConformanceFixtures`, `googleConformanceFixtureSeeds`, `findGoogleConformanceLeftovers` ([Conformance APIs](./conformance#connector-conformance))                                                                                                                                                                                                                                                                                                                                                                               |
| `@yolk-sdk/connectors/notion`                      | `NotionConnector`, `NotionApiTokenSlot`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `@yolk-sdk/connectors/notion/conformance`          | Experimental: `notionConformanceCases`, `NotionConformanceConfig`, `notionConformanceFixtures`, `notionConformanceFixtureSeeds` ([Conformance APIs](./conformance#connector-conformance))                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `@yolk-sdk/connectors/todoist`                     | `TodoistConnector`, `TodoistApiTokenSlot`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `@yolk-sdk/connectors/todoist/conformance`         | Experimental: `todoistConformanceCases`, `TodoistConformanceConfig`, `todoistConformanceFixtures`, `todoistConformanceFixtureSeeds` ([Conformance APIs](./conformance#connector-conformance))                                                                                                                                                                                                                                                                                                                                                                                                             |
| `@yolk-sdk/connectors/telegram`                    | `TelegramConnector`, `TelegramBotTokenSlot`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `@yolk-sdk/connectors/telegram/conformance`        | Experimental: `telegramConformanceCases`, `TelegramConformanceConfig`, `telegramConformanceFixtures`, `telegramConformanceFixtureSeeds` ([Conformance APIs](./conformance#connector-conformance))                                                                                                                                                                                                                                                                                                                                                                                                         |
| `@yolk-sdk/connectors/figma`                       | `FigmaConnector`, `FigmaOAuthCredentialSlot`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `@yolk-sdk/connectors/figma/conformance`           | Experimental: `makeFigmaMcpConformanceTarget`, `figmaMcpConformanceFixtures`, `figmaMcpConformanceLiveSeeds`, `figmaMcpConformanceFixtureSeeds`, `figmaMcpConformanceTools` ([Figma MCP conformance](../connectors/figma#conformance-cases))                                                                                                                                                                                                                                                                                                                                                              |
| `@yolk-sdk/connectors/kie`                         | `KieConnector`, `kieActions` (`kieCreateImageTaskAction`, `kieCreateVideoTaskAction`, `kieGetTaskAction`), `KieApiKeySlot` (`kie.api_key`), schemas `KieCreateImageTaskInput`, `KieCreateVideoTaskInput`, `KieCreateTaskOutput`, `KieGetTaskInput`, `KieGetTaskOutput`, `KieHttpUrl`, `KieAspectRatio`, `KieImageResolution`, `KieVideoResolution`, `KieTaskState`, and the id, base URL and model constants                                                                                                                                                                                              |
| `@yolk-sdk/connectors/kie/conformance`             | Experimental: `kieConformanceCases`, `KieConformanceConfig`, `kieConformanceFixtures`, `kieConformanceFixtureSeeds` ([Conformance APIs](./conformance#connector-conformance))                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `@yolk-sdk/connectors/linkedin-search`             | LinkedIn search/profile/email connector and API key slots                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `@yolk-sdk/connectors/linkedin-search/conformance` | Experimental: `linkedInSearchConformanceCases`, `LinkedInSearchConformanceConfig`, `linkedInSearchConformanceFixtures`, `linkedInSearchConformanceFixtureSeeds`, `linkedInSearchConformanceCredentials` ([Conformance APIs](./conformance#connector-conformance))                                                                                                                                                                                                                                                                                                                                         |
| `@yolk-sdk/connectors/microsoft`                   | `MicrosoftConnector`, shared OAuth slots, Outlook mail and OneDrive actions/schemas, host-only OneDrive download/create/update, Outlook attachment bytes and draft uploads                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `@yolk-sdk/connectors/microsoft/conformance`       | Experimental: `microsoftConformanceCases`, `MicrosoftConformanceConfig`, `microsoftConformanceFixtures`, `microsoftConformanceFixtureSeeds` ([Conformance APIs](./conformance#connector-conformance))                                                                                                                                                                                                                                                                                                                                                                                                     |
| `@yolk-sdk/connectors/r2-storage`                  | `R2StorageConnector`, `R2Presigner`, R2 credential slots, host-only `R2ObjectClient` get/create/update                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `@yolk-sdk/connectors/r2-storage/conformance`      | Experimental: `r2ConformanceCases`, `R2ConformanceConfig`, `r2ConformanceFixtures`, `r2ConformanceFixtureSeeds`, `r2ConformanceIntegration`, `r2PortsFromBackend`, `r2PortsLayerFromBackend`, `makeR2ReplayBackend`, `r2PresignRequestJson` / `r2GetRequestJson` / `r2PutRequestJson`, `r2PresignerPortName` / `r2ObjectClientPortName`, `r2BytesToBase64`, `findR2PortFixtureSecrets`, `scrubR2PortFixture`, `scrubR2PresignedUrl`, `r2ConformanceSyntheticSignature`, `r2ConformanceSyntheticCredential`, `r2ConformanceSyntheticAccessKeyId` ([Conformance APIs](./conformance#connector-conformance)) |

Fortnox exports `FortnoxCompanyInformation`, `FortnoxCustomer`, `FortnoxInvoice`,
`FortnoxSupplier`, `FortnoxSupplierInvoice`, row schemas, `FortnoxPagination`, and matching
`FortnoxGet*Input` / `FortnoxList*Input` / `FortnoxList*Output` classes, plus
`FortnoxCreateCustomerInput`, `FortnoxUpdateCustomerInput`, `FortnoxCreateInvoiceInput`,
`FortnoxUpdateInvoiceInput`, and the invoice write row `FortnoxInvoiceRowInput`. Branded identifier schemas
are `FortnoxCustomerNumber`, `FortnoxDocumentNumber`, `FortnoxSupplierNumber`, and
`FortnoxGivenNumber`. Individual actions are exported as `fortnoxGetCompanyInformationAction`,
`fortnoxListCustomersAction`, `fortnoxGetCustomerAction`, `fortnoxListInvoicesAction`,
`fortnoxGetInvoiceAction`, `fortnoxListSuppliersAction`, `fortnoxGetSupplierAction`,
`fortnoxListSupplierInvoicesAction`, `fortnoxGetSupplierInvoiceAction`,
`fortnoxCreateCustomerAction`, `fortnoxUpdateCustomerAction`, `fortnoxCreateInvoiceAction`,
`fortnoxUpdateInvoiceAction`, and `fortnoxListSupplierInvoiceFilesAction`. Matching file schemas are
`FortnoxListSupplierInvoiceFilesInput`, `FortnoxListSupplierInvoiceFilesOutput`, and
`FortnoxSupplierInvoiceFile`; both discovery input/output use `FortnoxGivenNumber`.
`downloadFortnoxInvoicePreview` requires `FortnoxDocumentNumber`; archive file IDs stay strings.
Customer/invoice create and update actions declare `write` access; customer-invoice sending or
booking is not exposed and remains host approval policy. Opt-in file slots are
`FortnoxConnectFileOAuthCredentialSlot` and `FortnoxArchiveOAuthCredentialSlot`; they are not on the
combined slot.

Resource modules add, each with a `Fortnox*` read model and, where the resource supports them, a
branded identifier, list/get/create/update/delete input and output classes, `fortnox*Action` exports, and an action array:
articles (`FortnoxArticle`, `FortnoxArticleNumber`, `fortnoxArticleActions`), prices
(`FortnoxPriceList`, `FortnoxPrice`, `FortnoxPriceListCode`, `FortnoxPriceFromQuantity`,
`fortnoxPriceActions`), cost centers (`FortnoxCostCenter`, `FortnoxCostCenterCode`,
`fortnoxCostCenterActions`), payments (`FortnoxInvoicePayment`, `FortnoxSupplierInvoicePayment`,
`FortnoxInvoicePaymentNumber`, `FortnoxSupplierInvoicePaymentNumber`, `fortnoxPaymentActions`),
offers (`FortnoxOffer`, `FortnoxOfferRow`, `fortnoxOfferActions`, host-only
`downloadFortnoxOfferPreview`, `streamFortnoxOfferPreview`), print templates
(`FortnoxPrintTemplate`, `fortnoxPrintActions`), inbox (`FortnoxInboxFolder`, `FortnoxInboxFile`,
`FortnoxInboxId`, `fortnoxInboxActions`, host-only `downloadFortnoxInboxFile`,
`streamFortnoxInboxFile`, `FortnoxInboxFileStream`, `uploadFortnoxInboxFile`,
`fortnoxInboxUploadMaxBytes`),
settings (`FortnoxCompanySettings`, `FortnoxLockedPeriod`, `FortnoxPredefinedAccount`,
`FortnoxLabel`, `fortnoxSettingsActions`), settings registers (`FortnoxModeOfPayment`,
`FortnoxTermsOfPayment`, `FortnoxTermsOfDelivery`, `FortnoxWayOfDelivery`, `FortnoxUnit`,
`fortnoxSettingsRegisterActions`), profile (`FortnoxProfile`, `fortnoxProfileActions`), and
bookkeeping (`FortnoxFinancialYear`, `FortnoxFinancialYearId`, `FortnoxAccount`,
`FortnoxVoucherSeries`, `FortnoxVoucherSeriesCode`, `FortnoxVoucher`, `FortnoxVoucherRow`,
`FortnoxVoucherNumber`, `FortnoxCreateVoucherInput`, `FortnoxVoucherRowInput`,
`fortnoxBookkeepingActions`; voucher file connections `FortnoxVoucherFileConnection`,
`fortnoxVoucherFileActions`; SIE files `FortnoxGetSieFileOutput`, `FortnoxSieFile`,
`FortnoxSieType`, `fortnoxSieFileMaxBytes`, `fortnoxSieActions`; host-only archive upload
`uploadFortnoxArchiveFile`, `FortnoxArchiveFile`, `FortnoxArchiveFileId`,
`fortnoxArchiveUploadMaxBytes`).
Their opt-in slots (`FortnoxArticleOAuthCredentialSlot`, `FortnoxPriceOAuthCredentialSlot`,
`FortnoxCostCenterOAuthCredentialSlot`, `FortnoxPaymentOAuthCredentialSlot`,
`FortnoxOfferOAuthCredentialSlot`, `FortnoxPrintOAuthCredentialSlot`,
`FortnoxInboxOAuthCredentialSlot`, `FortnoxSettingsOAuthCredentialSlot`,
`FortnoxProfileOAuthCredentialSlot`, `FortnoxBookkeepingOAuthCredentialSlot`) are not on the
combined slot. Read actions declare `read`; create/update actions declare `write`; deletes,
bookkeeping, creating a voucher, and offer lifecycle actions declare `destructive`.
See [Read and write Fortnox records](../connectors/fortnox) for OAuth constants, consent limitations,
pagination, selected fields, and monetary wire types.

Gmail submission exports `gmailSendMessageAction` (`gmail.send_message`, `destructive`),
`GmailRawMessage`, `GmailSendMessageInput` (`{ raw, threadId? }`), `GmailSendMessageOutput`
(`{ accepted: true, id, threadId? }`), `gmailSendMessageMaxBytes` (35 MiB of decoded MIME),
`GoogleGmailSendOAuthCredentialSlot`, and `googleGmailSendScopes`. Sending uses exactly one
request: 7-bit MIME uses `upload/gmail/v1/users/me/messages/send?uploadType=multipart`; MIME with
bytes `>= 0x80` uses the JSON `raw` request to `/gmail/v1/users/me/messages/send`. The host constructs and reviews complete base64url MIME; no MIME parsing
or sender validation is performed by this action. Existing broader Gmail grants can authorize
sending without new consent. Submission is not delivery, and unconfirmed sends must not be
retried automatically. See [Submit a reviewed Gmail message](../integrations/connectors#submit-a-reviewed-gmail-message)
for threading, authorization, and recovery responsibilities.

Generic email's principal contracts are `EmailIncomingConnection`, `EmailImapConnection`,
`EmailSmtpConnection`, `EmailAddress`, `EmailBody`, `EmailAttachmentMetadata`,
`EmailAttachmentBase64`, `EmailAttachmentContent`, `EmailMessageSummary`, `EmailMessage` (both with
optional `isRead` / `isFlagged`), `EmailListMessagesInput`, `EmailListMessagesRequest` (both with
optional state filters), `EmailListMessagesOutput`, `EmailGetMessageInput`, `EmailGetMessageOutput`,
`EmailGetAttachmentInput`, `EmailGetAttachmentRequest`, `EmailGetAttachmentOutput`, `EmailMessageHeader`
(required `headers` on `EmailMessage` from `email.get_message`; hosts fetch via `BODY.PEEK[HEADER]`),
`EmailComposeMessage`, `EmailFolderName`, `EmailDraftId`, `EmailCreateDraftInput`,
`EmailCreateDraftOutput`, `EmailSendMessageInput`, `EmailSendMessageOutput`,
`EmailSentCopyStatus`, `EmailSentCopyRequest`, and `EmailSentCopyOutput`. `EmailSendMessageInput`
accepts optional `saveToSentItems` and `sentFolder`. `EmailSendMessageOutput` may include `sentCopy`
and a fixed unverified-receipt `warning`. `EmailClient` receives
typed list/get/get-attachment/IMAP-draft/SMTP-send requests plus a runtime
`UsernamePasswordCredential`; hosts opt into attachment retrieval through its optional
`getAttachment` method. Filtered list calls use optional `listMessagesFiltered`; unfiltered calls
retain `listMessages`. Successful list and attachment output is schema-validated before exposure. The
connector exports separate `EmailIncomingCredentialSlot` and `EmailSmtpCredentialSlot` bindings and
does not bundle transport or MIME libraries.

IMAP mailbox mutations export `emailSetReadAction`, `emailTrashAction`, and `emailUntrashAction`,
with `EmailSetReadInput`, `EmailTrashInput`, `EmailUntrashInput`, matching `*Request` classes,
`EmailSetReadOutput`, and `EmailMoveMessageOutput`. Optional `EmailClient.setRead`, `trash`, and
`untrash` methods receive IMAP connections and incoming credentials. Successful output is validated;
POP3 is rejected. Move output includes the destination folder and an optional new message ID.
See the [catalog](../integrations/connectors#mark-readunread-and-move-tofrom-trash) for adapter safety
and trash-discovery requirements. Flag mutations export `emailSetFlagAction` with `EmailSetFlagInput`, `EmailSetFlagRequest`,
`EmailSetFlagOutput`, and optional `EmailClient.setFlag` host support for the `\Flagged` system flag.
Label mutations export `emailModifyLabelsAction` with
`EmailModifyLabelsInput`, `EmailModifyLabelsRequest`, `EmailModifyLabelsOutput` (an Effect `Chunk`
of `EmailImapKeyword` atoms), and optional `EmailClient.modifyLabels` host support. Relocation
exports `emailMoveAction` with `EmailMoveInput`, `EmailMoveRequest`, and optional
`EmailClient.move` host support, returning `EmailMoveMessageOutput` with destination
UIDVALIDITY/UID mapping when known.

Batch exports are `emailBatchSetReadAction`, `emailBatchSetFlagAction`, `emailBatchMoveAction`,
`emailBatchTrashAction`, `emailBatchUntrashAction`, and `emailBatchModifyLabelsAction`, with matching
`EmailBatch*Input` / `EmailBatch*Request` contracts and optional `EmailClient.batch*` methods.
`EmailBatchMessageIds` enforces 1-100 unique nonempty IDs. `EmailBatchOperationOutput` and
`EmailBatchMoveOutput` contain one per-ID `EmailBatchOperationStatus` in `messageIds` order plus
`EmailBatchSummary`; every succeeded move-shaped result requires destination `folder`, while
`movedMessageId` is optional and only supplied when the destination UIDVALIDITY/UID mapping is known. `emailDeletePermanentlyAction`
uses `EmailDeletePermanentlyInput` / `EmailDeletePermanentlyRequest` and optional
`EmailClient.deletePermanently`. It is UID-scoped and destructive; hosts never blanket-expunge, and
backup/retention erasure is outside the contract. The shared batch outcome shapes
(`EmailBatchMessageIds`, `EmailBatchOperationStatus`, `EmailBatchResultCode`, `EmailBatchResultItem`,
`EmailBatchSummary`, `EmailBatchOperationOutput`) live in the internal `email-batch` module and are
re-exported from the `/email`, `/google`, and `/microsoft` entrypoints.

Gmail batch exports are `gmailSetReadAction` (`gmail.set_read`, `write`, returns the normalized
`GmailMessageOutput` with `isRead`/`isFlagged` derived from `labelIds`), `gmailBatchSetReadAction`,
`gmailBatchSetStarredAction`, `gmailBatchModifyLabelsAction` (with `GmailBatchModifyLabelsInput`;
removals win, each delta capped at 100), `gmailBatchTrashAction`, `gmailBatchUntrashAction`, and
`gmailDeletePermanentlyAction`, all returning shared `EmailBatchOperationOutput` with sanitized
codes only. `GoogleGmailFullMailOAuthCredentialSlot` requests only `https://mail.google.com/` for
permanent deletion and is never added to combined/default consent.

The package root also exports the pure `parseUnsubscribeMethods` helper (RFC 2369/8058
`List-Unsubscribe` parser returning `UnsubscribeMethods` with mailto/http methods; execution stays
host-owned). See [Unsubscribe from mailing lists and report spam](../integrations/connectors#unsubscribe-from-mailing-lists-and-report-spam).

Microsoft Outlook's principal contracts are `OutlookMessage`, `OutlookMessageWithHeaders`
(required `internetMessageHeaders` on `outlook.get_message` only; list/draft/mutation responses
stay on the base message), `OutlookInternetMessageHeader`, `OutlookMessageIdInput`,
`OutlookListMessagesInput`, `OutlookSearchMessagesInput`, `OutlookListMessagesOutput`,
`OutlookAttachmentKind`, `OutlookAttachmentMetadata`, `OutlookAttachment`,
`OutlookListAttachmentsInput`, `OutlookListAttachmentsOutput`, `OutlookGetAttachmentInput`,
`OutlookGetAttachmentOutput`, `OutlookComposeInput`, `OutlookCreateReplyDraftInput`,
`OutlookUpdateDraftInput` (used by `outlookUpdateDraftAction` / `outlook.update_draft`),
`OutlookSendMailInput`, `OutlookReplyInput` (used by `outlookReplyAction` / `outlook.reply`),
`OutlookSendOutput`, `OutlookSetReadInput`, `OutlookTrashInput`, and
`OutlookUntrashInput`. `outlookSetReadAction`, `outlookTrashAction`, and `outlookUntrashAction`
return the updated `OutlookMessage`, select mailbox-aware write permissions, and request immutable
IDs. Restore targets Deleted Items as its source and defaults the destination to inbox.
`outlookUpdateDraftAction` edits recipients, subject, or complete body on an existing draft;
empty arrays clear recipients and omitted fields remain unchanged. It is a write, not a send,
and preserves existing mailbox permission selection. See [Edit a draft](../integrations/connectors#edit-a-draft)
for replacement-body and non-atomic update/send semantics.
`outlookReplyAction` sends the complete reviewed reply in one Graph `POST .../reply` with
explicit recipients, subject, and full body; only HTTP 202 counts as accepted, which means
submission, not delivery. See [Send a reviewed reply](../integrations/connectors#send-a-reviewed-reply)
for single-request dispatch and recovery semantics.
File attachment retrieval requires Graph's file
discriminator and valid base64 content, then exposes it as required `contentBase64`; item and
reference attachments are available only as list metadata.
`OutlookListAttachmentsOutput.attachments` decodes to an Effect `Chunk`. `outlookMoveMessageAction`
with `OutlookMoveMessageInput` moves a message to a required `destinationFolderId` via Graph
`/move`; `outlookSetFlagAction` with `OutlookSetFlagInput` PATCHes follow-up `flagStatus`.
`OutlookMessage` carries optional `isFlagged` normalized from Graph `flag.flagStatus`, and
`OutlookListMessagesInput` accepts optional `isRead`/`isFlagged` filters composed into `$filter`.
Outlook batch exports are `outlookBatchSetReadAction`, `outlookBatchSetFlagAction`,
`outlookBatchMoveAction`, `outlookBatchTrashAction`, `outlookBatchUntrashAction` (returning
`OutlookBatchMoveOutput` with provider-returned `movedMessageId`/`destinationFolderId`),
`outlookBatchModifyCategoriesAction`, and `outlookDeletePermanentlyAction` (returning shared
`EmailBatchOperationOutput`), with matching `OutlookBatch*Input` contracts, Graph JSON batching
(at most 20 subrequests per envelope), and sanitized codes only. Category exports are
`OutlookCategory`, `OutlookCategoryColor`, `OutlookListCategoriesInput/Output`,
`OutlookCreateCategoryInput`, `OutlookDeleteCategoryInput/Output`, `OutlookSetCategoriesInput`,
`OutlookModifyCategoriesInput`, `OutlookGetCategoryInput`, `OutlookUpdateCategoryInput`, plus
`MicrosoftOutlookCategoryRead/WriteOAuthCredentialSlot` opt-in
slots (excluded from the combined slot). OAuth exports include generic,
signed-in-mailbox, shared-mailbox, and combined
slots that share `microsoft.oauth`. Action inputs use `/me` by default and accept optional `mailbox`
for `/users/{id|userPrincipalName}` Exchange Online targets. Set integration config key
`microsoftMailboxAccessModeConfigKey` (`mailboxAccessMode`) to `application` for application-token
mailbox targeting; delegated is the default.

`OutlookListMessagesInput` and `OutlookSearchMessagesInput` decode null/blank optional strings and
null page sizes to `undefined` without rewriting real cursors. See
[Optional Outlook read inputs](../integrations/connectors#optional-outlook-read-inputs) for the
accepted fields, page-size range, and application-mailbox requirement.

OneDrive's principal contracts are `OneDriveItem`, `OneDriveItemIdInput`,
`OneDriveListItemsInput`, `OneDriveSearchItemsInput`, `OneDriveListItemsOutput`,
`OneDriveCreateFolderInput`, `OneDriveDeleteItemInput`, `OneDriveDeleteItemOutput`,
`OneDriveMoveItemInput`, `OneDriveCopyItemInput`, `OneDriveCopyAcceptedOutput`,
`OneDriveCopyMonitorUrl`, `OneDriveCopyStatus`, `OneDriveCopyStatusInput`,
`OneDriveCopyStatusOutput`, and `OneDriveCopyStatusError`. Action exports include
`oneDriveMoveItemAction`, `oneDriveCopyItemAction`, and `oneDriveGetCopyStatusAction`. Inputs default
to `/me/drive`; explicit `driveId` targets `/drives/{driveId}`. Set
`microsoftOneDriveAccessModeConfigKey` (`oneDriveAccessMode`) to `delegated_all` for broad delegated
slots or `application` for application-token access; application mode requires `driveId`. Microsoft
actions use Graph v1.0 with `outlook.*` and `onedrive.*`
ids, and all scoped slots share `microsoft.oauth`.

Host-only original-byte download is `downloadOneDriveItem`, with `OneDriveDownloadError`,
`OneDriveDownloadErrorCode`, `OneDriveDownloadSource`, `OneDriveDownloadBudget`,
`OneDriveDownloadInput`, and `OneDriveDownloadResult`. It is not an action output. Bytes are
untouched `Uint8Array`. Errors expose only `code`. `source` metadata is observed before download and
is not a verified snapshot. Provide `ConnectorBinaryHttpClient` in addition to the existing
`CredentialResolver`; the optional GET-only port is independent of `ConnectorHttpClient` and must
not auto-follow redirects, attach cookies, or add ambient auth. Hosts enforce streamed limits and
connection-time public DNS/IP policy. Root types include `ConnectorBinaryHttpRequest`,
`ConnectorBinaryHttpResponse`, and `ConnectorBinaryHttpClientApi`, whose optional `stream` method
answers `ConnectorBinaryHttpStreamResponse` (`Stream` for HTTP 200, else bounded `Bytes`; types
`ConnectorBinaryHttpBodyStream` and `ConnectorBinaryHttpBufferedResponse`) inside a `Scope`.
`streamOneDriveItem` answers `OneDriveDownloadStream` (the same `source` plus `body` and
`contentLength`), and `getOneDriveDownloadUrl` answers `OneDriveDownloadUrl` (Graph's
`@microsoft.graph.downloadUrl` as a `Redacted` `url`, a conservative `expiresAt` from
`oneDriveDownloadUrlLifetimeMs` minus the root `connectorLinkExpiryMarginMs`, `source`,
`requested`). See [Stream, or skip the download](../connectors/files#stream-or-skip-the-download).

The Dropbox equivalent is `downloadDropboxFile`, with `DropboxDownloadError`,
`DropboxDownloadErrorCode`, `DropboxDownloadSource`, `DropboxDownloadBudget` (`maxBytes`,
`maxErrorBodyBytes`), `DropboxDownloadInput` (`path`), and `DropboxDownloadResult`. It uses the same
`ConnectorBinaryHttpClient` port and `CredentialResolver`, requests the
`DropboxContentReadOAuthCredentialSlot` (`files.content.read`), issues one `GET`, never follows
redirects, and returns `source` metadata taken from the `Dropbox-API-Result` header of the served
response. The content hash is not verified. `streamDropboxFile` answers `DropboxDownloadStream` (the
same `source` plus `body` and `contentLength`), and `getDropboxTemporaryLink(integration, { path })`
answers `DropboxTemporaryLink` (a `Redacted` `url`, a conservative `expiresAt` from
`dropboxTemporaryLinkLifetimeMs` minus `connectorLinkExpiryMarginMs`, `source`, `requested`) over
`ConnectorHttpClient`. Dropbox scope exports now include `dropboxFilesContentReadScope`,
`dropboxContentReadScopes`, and `dropboxContentApiBaseUrl`.

`GoogleCalendarEventDateTime` is the exclusive union `{ date, timeZone? } | { dateTime,
timeZone? }`. Create/update boundaries require exactly one non-empty `date` or `dateTime` and reject
null, missing, empty, and dual-field values before provider execution.

`GoogleCalendarSendUpdates` is the `'all' | 'externalOnly' | 'none'` literal union for the optional
`sendUpdates` field of `GoogleCalendarCreateEventInput`, `GoogleCalendarUpdateEventInput`, and
`GoogleCalendarDeleteEventInput`; it is sent only as Google's `sendUpdates` query parameter.
`googleCalendarDeleteEventAction` validates a struct over `GoogleCalendarDeleteEventInput`'s fields,
so `executeTyped` accepts both `GoogleCalendarDeleteEventInput` and existing
`GoogleCalendarEventIdInput` values. `googleCalendarGetEventAction` keeps
`GoogleCalendarEventIdInput`.

Google Drive's principal contracts are `GoogleDriveFile`, `GoogleDriveUser`,
`GoogleDriveCapabilities`, `GoogleDriveListFilesInput`, `GoogleDriveSearchFilesInput`,
`GoogleDriveListFilesOutput`, `GoogleDriveFileIdInput`, `GoogleDriveCreateFolderInput`, and
`GoogleDriveDeleteFileOutput`. Public actions are `googleDriveListFilesAction`,
`googleDriveSearchFilesAction`, `googleDriveGetFileAction`, `googleDriveCreateFolderAction`,
`googleDriveTrashFileAction`, and `googleDriveDeleteFileAction`; `googleDriveActions` composes them
into `GoogleConnector`.

`GoogleDriveListFilesOutput.files` and repeated `GoogleDriveFile` metadata fields decode to Effect
`Chunk` values for structural equality. `GoogleDriveFileIdInput` accepts optional `resourceKey`;
parent-scoped list, search, and create inputs accept optional `parentResourceKey`. These values
produce `X-Goog-Drive-Resource-Keys` for protected link-shared files.

`GoogleDriveMetadataReadonlyOAuthCredentialSlot` requests `googleDriveMetadataReadonlyScope` for
list/search/get. `GoogleDriveFileOAuthCredentialSlot` requests `googleDriveFileScope` for folder
create, trash, and permanent delete. Both use `googleOAuthSlotId` (`google.oauth`), and
`GoogleCombinedOAuthCredentialSlot` includes both Drive scopes alongside Gmail and Calendar scopes.
Constants also include `googleDriveApiBaseUrl`, `googleDriveFolderMimeType`, and
`googleDriveFileFields`.

Google's normalized attachment and thread contracts are `GmailListAttachmentsInput`,
`GmailListAttachmentsOutput`, `GmailGetAttachmentInput`, `GmailGetAttachmentOutput`,
`GmailAttachmentBase64Url`, `GmailAttachmentBase64`, `GmailGetThreadInput`, `GmailGetMessageInput`,
`GmailMetadataHeaders`, `GmailMetadataHeaderName`, `gmailMetadataHeadersMaxItems`,
`GmailListThreadsInput`, `GmailListThreadsOutput`, `GmailThreadRef`, `GmailThreadAttachment`,
`GmailThreadMessage`, and `GmailThreadOutput`.

* `GmailGetThreadInput`: required `threadId` and `format: 'full' | 'metadata' | 'minimal'`;
  optional `metadataHeaders` (`GmailMetadataHeaders`), only with `format: 'metadata'`.
* `GmailGetMessageInput`: required `id`; optional `format: 'minimal' | 'full' | 'raw' | 'metadata'`
  and `metadataHeaders`, only with `format: 'metadata'`. Another combination fails decoding, and
  `make` throws on it.
* `GmailMetadataHeaders`: 1 to `gmailMetadataHeadersMaxItems` (50) `GmailMetadataHeaderName` values
  (RFC 5322 field names: 1 to 128 printable ASCII characters without `:`), sent as repeated
  `metadataHeaders` query parameters. On `gmail.get_thread`, each message keeps exactly the selected
  headers (case-insensitive) instead of the default allowlist.
* `GmailListThreadsInput` (`gmail.list_threads`): the `GmailListInput` fields (`query`, `labelId`,
  `maxResults`, `pageToken`, `isRead`, `isFlagged`).
* `GmailListThreadsOutput`: optional `threads` (`GmailThreadRef`: required `id`; optional `snippet`
  and `historyId`), `nextPageToken`, and `resultSizeEstimate`.
* `GmailThreadOutput`: required `id` and `messages`; optional `historyId`.
* `GmailThreadMessage`: required `id`, `headers`, and `attachments`; optional `threadId`, `labelIds`,
  `snippet`, `internalDate`, `body`, and `bodyMimeType`.
* `GmailThreadAttachment`: optional `partId`, `filename`, `mimeType`, `size`, `attachmentId`,
  `inline`, and `contentId`.
* `GmailListAttachmentsInput` / `GmailListAttachmentsOutput`: one `messageId` to a metadata-only
  attachment `Chunk`.
* `GmailGetAttachmentInput`: required `messageId` and `attachmentId`.
* `GmailGetAttachmentOutput`: required input IDs, non-negative integer `size`, Gmail base64url `data`,
  and standard-base64 `contentBase64`.

Non-success provider responses return `ActionResult.failure`; authorization failures use
`google_unauthorized`, while action-specific failures use `gmail_get_thread_failed`,
`gmail_list_threads_failed`, `gmail_list_attachments_failed`, or `gmail_get_attachment_failed`.
Invalid JSON or response shape fails with `ConnectorError { cause: 'validation_failed' }`.

Gmail label contracts are `GmailLabel` (with `GmailLabelMessageListVisibility`,
`GmailLabelListVisibility`, and `GmailLabelType`), `GmailCreateLabelInput`, `GmailLabelIdInput`,
`GmailUpdateLabelInput` (PATCH rename, at least one updatable field), and `GmailDeleteLabelOutput`
(`{ id, deleted: true }` without decoding the empty 204 body). `gmailSetStarredAction` with
`GmailSetStarredInput` stars through the `STARRED` system label. Label mutations reuse the existing
`gmail.modify` slot; reads use the readonly slot.

Gmail draft contracts are `GmailDraftComposeInput` (`to`, `subject`, `body`, optional
`contentType`, `cc`, `bcc`, `from`, `attachments`), `GmailDraftUpdateInput` (the same fields plus
`draftId`), `GmailDraftReplyInput` (`messageId`, `body`, optional `contentType`, `from`,
`attachments`), `GmailDraftIdInput` (`draftId`), and `GmailDraftContentType` (`'text' | 'html'`;
`text` when omitted). A `text` body is sent as `multipart/alternative` with a derived HTML part; see
[Gmail draft bodies](../integrations/connectors#gmail-draft-bodies).

Gmail draft attachment contracts are `GmailDraftAttachment` (`{ filename, mimeType, contentBase64 }`),
`GmailDraftAttachments`, the field schemas `GmailDraftAttachmentFilename`,
`GmailDraftAttachmentMimeType`, and `GmailDraftAttachmentBase64`, and the limits
`gmailDraftAttachmentsMaxItems` (10), `gmailDraftAttachmentsMaxBytes` (25 MiB decoded in total), and
`gmailDraftMessageMaxBytes` (35 MiB of decoded MIME). A draft with attachments is written through
the draft media upload; see [Gmail draft attachments](../integrations/connectors#gmail-draft-attachments).

See [Connectors catalog](../integrations/connectors) for action ids.

## Sandbox [#sandbox]

| Subpath                        | Main exports                                                                                                                                                                                                                                                                                                                                                                                                 |
| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `@yolk-sdk/sandbox`            | `Sandbox`, `SandboxStateStore`, `makeSandboxName`, `CloudflareSandboxState`, `normalizeWorkspaceCwd`, `NormalizedWorkspaceCwd`, `normalizeWorkspacePath`, `NormalizedWorkspacePath`, `SandboxReadFileInput`, `SandboxWriteFileInput`, command/result/lifecycle/source schemas                                                                                                                                |
| `@yolk-sdk/sandbox/agent`      | `makeSandboxToolModule`, `makeSandboxToolModuleFromApi`, `sandboxToolName`, `SandboxToolOutput`                                                                                                                                                                                                                                                                                                              |
| `@yolk-sdk/sandbox/vercel`     | `makeVercelSandboxLayer`, `makeVercelSandboxLayerWithClient`, `VercelSandboxEnvironment`, `VercelSandboxFileTooLargeError`                                                                                                                                                                                                                                                                                   |
| `@yolk-sdk/sandbox/cloudflare` | `CloudflareSandbox` (Durable Object class), `makeCloudflareSandboxLayer`, `CloudflareSandboxLayerConfig`, `CloudflareSandboxInitialSource`, `CloudflareSandboxNamespace`, `CloudflareSandboxStub`, `CloudflareSandboxSourceSpec`, `CloudflareSandboxReadFileOutput`, RPC protocol types, `defaultCloudflareSandboxWorkspaceRoot`, `defaultCloudflareSandboxDiskMb`, `defaultCloudflareSandboxMaxOutputBytes` |
| `@yolk-sdk/sandbox/testing`    | `makeFakeSandboxLayer`, `makeFakeSandboxFiles`, `makeInMemorySandboxStateStoreLayer`                                                                                                                                                                                                                                                                                                                         |

## Code mode [#code-mode]

| Subpath                         | Main exports                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `@yolk-sdk/codemode`            | `makeCodeModeTool`, `runCodeModeScript`, `RunCodeModeScriptOptions`, `CodeModeScriptResult`, `CodeModeScriptCall`, `CodeModeScriptStaged`, `readOnlyNestedCallGate`, `ReadOnlyNestedCallGateOptions`, `ReadOnlyNestedCallRefusalCode`, `CodeModeNestedCallRefused`, `CodeModeNestedCallRefusal`, `CodeModeBeforeNestedCall`, `CodeModeBeforeNestedCallInput`, `CodeModeToolBeforeNestedCallInput`, `CodeModeNestedCallSettledInput`, `CodeModeExecutor`, `CodeModeInternalError`, `CodeModeInternalErrorStage`, `CodeModeInternalErrorObserver`, `CodeModeLimits`, `CodeModeAfterNestedCallInput`, `CodeModeNestedCallOutcome`, `CodeModeStructuredContent`, `CodeModeInterruptedCalls`, `CodeModeInterruptedCall`, `CodeModeInterruptedCallStatus`, `CodeModeStagedPlan`, `CodeModeStagingOptions`, `CodeModeStagingDescription`, `defaultCodeModeLimits`, `codeModeStoreFromToolResults`, `renderCodeModeDescription`, `renderCodeModeInstructedDescription`, `codeModeCatalogInstruction`, `codeModeCatalogInstructionKey`, `CodeModeCatalogSummary`, `summarizeCodeModeCatalog`, `renderCodeModeCatalog`, `codeModeStageOnlyCatalog`, `selectCodeModeListing`, `searchCodeModeTools`, `codeModeToolSignature`, `maxCodeModeSearchSignatureChars`, `boundCodeModeSegments`, `makeClassifierTool`, `ClassifierToolParams` |
| `@yolk-sdk/codemode/node`       | `makePiCodeModeExecutor`, `defaultMaxConcurrentExecutions`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `@yolk-sdk/codemode/cloudflare` | `makeDynamicWorkerCodeModeExecutor`, `WorkerLoader`, `WorkerLoaderCode`, `DynamicWorkerCodeModeExecutorOptions`, `defaultDynamicWorkerCompatibilityDate`, `defaultDynamicWorkerCpuMs`, `maxDynamicWorkerHostCallFailureReports`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |

See [Add code mode](../integrations/code-mode); `makeCodeModeTool({ catalog: 'instructions' })` delivers the catalog as a host instruction ([Deliver the catalog as instructions](../integrations/code-mode#deliver-the-catalog-as-instructions)).
`readOnlyNestedCallGate({ admit?, admitModelCall? })` takes two predicates over the
`CodeModeBeforeNestedCallInput` (`{ call, tool, access }`): `admit` relaxes the access check and
`admitModelCall` the `invokesModel` check ([Allow only reads](../integrations/code-mode#allow-only-reads)).

## File extraction [#file-extraction]

| Subpath                          | Main exports                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `@yolk-sdk/extractors`           | `FileExtractor`, `FileExtractorApi`, `FileInput`, `ExtractedFile`, `ExtractedFileMetadata`, `ExtractedFileFormat`, `OfficeFileFormat`, `extractedFileFormats`, `fileFormatFor`, `isOfficeFileFormat`, `FileExtractorLimits`, `defaultFileExtractorLimits`, `sanitizeExtractedText`, `FileExtractorError`, `FileExtractionError`, `FileExtractionFailureReason`, `UnsupportedFileFormatError`, `OfficeArchiveError`, `SheetJsUnavailableError`, `minimumSheetJsVersion`, `sheetJsInstallCommand` |
| `@yolk-sdk/extractors/node`      | `FileExtractorLayer`, `makeFileExtractorLayer`, `FileExtractorOptions`, `FileExtractorIsolation`, `WorkerIsolationOptions`, `defaultWorkerIsolation`, `normalizeOfficeArchive`, `OfficeArchiveLimits`, `SheetJsLoader`; re-exports `FileExtractor`, `FileExtractorApi`                                                                                                                                                                                                                          |
| `@yolk-sdk/extractors/knowledge` | `FileKnowledgeExtractorLayer`, `makeFileKnowledgeExtractor`                                                                                                                                                                                                                                                                                                                                                                                                                                     |

`@yolk-sdk/extractors/node/extraction-worker` is the worker entry the Node layer starts; do not
import it directly. See [Extract file text](../integrations/file-extraction).

## Files [#files]

| Subpath           | Main exports                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `@yolk-sdk/files` | `makeObjectStorageFileStore`, `ObjectStorageApi`, `ObjectStorageHead`, `ObjectStorageError`, `ObjectStorageFileStoreOptions`, `deleteScopeFiles`, `fileIdFor`, `isValidFileScope`, `makeFileToolModule`, `FileToolModuleOptions`, `FileUploadTransportApi`, `FileUploadTransportError`, `FileSandboxApi`, `FileSandboxError`, `fileUploadToolName`, `fileUrlToolName`, `fileToSandboxToolName`, `fileFromSandboxToolName`, `defaultMaxFileTransferBytes` |

Capture itself (`FilePart`, `FileStoreApi`, `resolveTools({ files })`) is in `@yolk-sdk/agent`. See
[Move files between tools](../integrations/files).

## Subscription pools [#subscription-pools]

| Subpath                | Main exports                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `@yolk-sdk/pool`       | `makePool`, `Pool`, `PoolOptions`, `PoolAccount`, `PoolAccountState`, `PoolState`, `poolFailureCooldown`, `defaultPoolMaxAgeMs`, `poolQuotaRetryAfterFloorMs`, `poolMaxCooldownMs`, `poolAuthCooldownMs`, `rankPool`, `staleQuotaCooldowns`, `isCooldownActive`, `poolReadingFromSnapshot`, `poolRoute`, `PoolDecision`, `PoolCandidate`, `PoolRankInput`, `PoolReading`, `PoolWindow`, `PoolAccountId`, `PoolPin`, `PoolCooldown`, `PoolQuotaCooldown`, `PoolAuthCooldown`, `PoolConfigError`, `PoolStoreError`, `PoolUnknownAccountError` |
| `@yolk-sdk/pool/store` | `PoolStoreApi`, `PoolStoreSnapshot`, `PoolStoreState`, `PoolStoredReading`, `PoolStoreError`, `makeMemoryPoolStore`, `poolStoreContract`, `PoolStoreContractCase`, `PoolStoreContractViolation`                                                                                                                                                                                                                                                                                                                                             |

See [Share subscription accounts](../integrations/subscription-pools).

## Connector file APIs [#connector-file-apis]

The root also exports `connectorActionFile`, `sniffBase64MimeType` and the action `fileOutput`
types (`ConnectorActionFile`, `ConnectorActionFileOutput`, `UnknownConnectorActionFileOutput`):
actions whose output carries bytes return them to agent tools as files. The root additionally exports `ConnectorBinaryWriteHttpClient`, `ConnectorBinaryWriteHttpClientApi`
(with optional `uploadSession`), `ConnectorBinaryWriteHttpRequest`, `ConnectorBinaryUploadSessionRequest`, `ConnectorFileTransferError`, `ConnectorFileTransferBudget` and
`ConnectorFileBytes`. Existing GET-only binary ports remain unchanged.

See [Transfer connector files](../connectors/files) for all helper signatures and the complete
provider matrix, including `R2ObjectClient`/`R2ObjectClientApi`, Drive's
`GoogleDriveReadonlyOAuthCredentialSlot` and `GoogleDriveDownloadBudget`, Notion's
`NotionFileDownloadPolicy`, and optional `EmailClient.getAttachmentBytes` returning
`EmailAttachmentBytesResult`. Provider input/result types are exported from their existing subpaths;
new helpers return host-only bytes or allowlisted write metadata and code-only transfer errors.
New metadata actions are `fortnoxListSupplierInvoiceFilesAction` and `todoistListCommentsAction`,
with their provider-named input/output schemas. No new package subpaths or generic agent file actions.


---

# Workflow APIs

URL: /docs/api-reference/workflows

Public Vercel Workflow orchestration exports.



Use `@yolk-sdk/vercel-workflows` or the equivalent `@yolk-sdk/vercel-workflows/workflow` subpath for orchestration. Use `@yolk-sdk/vercel-workflows/effect` for Effect-native host route wrappers around public `workflow/api` calls, and `@yolk-sdk/vercel-workflows/testing` for host tests. The `./cloudflare*` subpaths run the same Workflow code on Cloudflare Durable Objects ([Cloudflare runtime](../vercel-workflows/cloudflare)).

## Loop exports [#loop-exports]

| Export                    | Purpose                                                                                                                                                                                |
| ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `runVercelAgentWorkflow`  | orchestrate model/tool/HITL/close callbacks                                                                                                                                            |
| `defaultMaxWorkflowTurns` | default max turns, currently `500`                                                                                                                                                     |
| `noWorkflowStepRetry`     | default retry policy (except `closeStreamRetry`), `{ maxAttempts: 1 }`; queue redelivery still happens ([at-least-once](../integrations/vercel-workflow#tool-steps-run-at-least-once)) |
| `defaultCloseStreamRetry` | default `closeStreamRetry`, `{ maxAttempts: 3 }`; a Vercel stream close is idempotent                                                                                                  |
| `retryWorkflowStep`       | retry helper for Workflow callback promises                                                                                                                                            |
| `settleWorkflowStep`      | convert a promise into `Success` / `Failure` result                                                                                                                                    |

`WorkflowStepResult` and `VercelAgentWorkflowRunResult` are both types and constructor values
on the package root and `@yolk-sdk/vercel-workflows/workflow`. Use
`WorkflowStepResult.Success({ value })` / `.Failure({ error })` for settled steps and
`VercelAgentWorkflowRunResult.Completed({ turns, state })` or its failure variants for terminal results.
Their `$is(tag)` helpers narrow to a specific variant.

## Independent child helpers [#independent-child-helpers]

Both helpers are exported from root and `./workflow` and run in Workflow orchestration, not inside
a single parent tool step. They do not start children or implement storage/authorization themselves.

### `orchestrateWorkflowToolBatch<Call, Result, Pause>` [#orchestrateworkflowtoolbatchcall-result-pause]

Inputs:

* `calls: ReadonlyArray<Call>` and `concurrency: number`.
* `preflight: () => Promise<{ ready: true } | { ready: false; value: Pause }>`: runs once before
  dispatch; a pause fences every call.
* `execute: (call: Call, index: number) => Promise<Result>`: invokes host steps or child starts.

Returns a Promise of `{ ready: false, value }` or
`{ ready: true, results: ReadonlyArray<Result>, failures?: ReadonlyArray<{ index: number, error: unknown }> }`.
Concurrency is floored/clamped to at least one; non-finite values become one. On rejection, no new
calls are dispatched; active siblings settle and successful results retain original call order.
`ready: true` is **not** a success guarantee: inspect `failures`, retain partial progress, and map
errors to safe wire data before returning the loop callback result. Results omit failed and
undispatched calls; carry call identity in each result when mapping partial progress.

### `awaitWorkflowChild<A>` [#awaitworkflowchilda]

Accepts `read: (attempt: number) => Promise<{ done: false } | { done: true; value: A }>` and
`sleep: (attempt: number) => Promise<void>`, returning `Promise<A>`. Attempts start at zero. Each
read returning `done: false` is followed by a sleep with the same index, then the next read.
Existing zero-argument callbacks remain compatible.

It alternates short durable read steps with Workflow `sleep` until `done: true`. There is no
built-in timeout or observation ceiling. Hosts can use the index for budgets/backoff and return
`{ done: true, value }` at their ceiling with a truthful still-running or unknown value; this ends
observation, not the child. Represent completed, failed, and cancelled states explicitly and keep
Stop policy host-owned. Never place a long child `returnValue` poll inside one step.

See [Bounded child observations](../vercel-workflows/step-contracts#bounded-child-observations)
for host budgeting and [Nonterminal child observations](../agent/tools-hitl#nonterminal-child-observations)
for the subagent result marker.

## Durable event exports [#durable-event-exports]

| Export                                | Purpose                                                                       |
| ------------------------------------- | ----------------------------------------------------------------------------- |
| `makeDurableAgentEventSequencerState` | initialize event sequence state                                               |
| `durableAgentEventId`                 | build `${streamId}:${turn}:${eventSequence}`, plus `:${executionId}` when set |
| `sequenceDurableAgentEvent`           | add deterministic `eventId` without writing                                   |
| `writeDurableAgentEvent`              | write sequenced NDJSON to a writer                                            |
| `DurableAgentEventWriteError`         | writer rejection, kept as `cause`                                             |
| `commitThenWriteTerminalEvent`        | commit durable state before writing terminal event                            |

## Effect API exports [#effect-api-exports]

Import from `@yolk-sdk/vercel-workflows/effect`.

| Export                          | Purpose                                                       |
| ------------------------------- | ------------------------------------------------------------- |
| `VercelWorkflows`               | Effect service for start/read/replay/resume/cancel operations |
| `VercelWorkflowsClient`         | service shape for injected fakes/custom layers                |
| `VercelWorkflowsError`          | tagged error for public Workflow SDK failures                 |
| `VercelWorkflowsSdk`            | injectable low-level SDK dependency for tests/custom hosts    |
| `VercelWorkflowsSdkClient`      | low-level SDK dependency shape                                |
| `VercelWorkflowsSdkRun`         | low-level SDK run shape                                       |
| `VercelWorkflowFunction`        | Workflow function type accepted by `start`                    |
| `VercelWorkflowRun`             | Effect-native run handle returned by `start`/`getRun`         |
| `VercelWorkflowRunStatus`       | native Workflow run status type                               |
| `VercelWorkflowStartOptions`    | `start` options: plaintext run `attributes`                   |
| `VercelWorkflowReadableOptions` | readable stream options, including `startIndex`               |
| `VercelWorkflowReadableStream`  | native Workflow readable stream type                          |
| `VercelWorkflowsOperation`      | operation names carried by `VercelWorkflowsError`             |

Layers:

| Layer                          | Purpose                                                               |
| ------------------------------ | --------------------------------------------------------------------- |
| `VercelWorkflows.layer`        | live service backed by public `workflow/api`                          |
| `VercelWorkflows.layerFromSdk` | service requiring injected `VercelWorkflowsSdk` for tests/custom SDKs |

`VercelWorkflows` methods:

| Method                         | Purpose                                                 |
| ------------------------------ | ------------------------------------------------------- |
| `start(workflow, args, opts?)` | start a Workflow and return an Effect-native run handle |
| `getRun(runId)`                | create an Effect-native handle for an existing run      |
| `getReadable(runId, options?)` | read/replay a run stream                                |
| `tailIndex(runId)`             | read current stream tail index                          |
| `resumeHook(token, payload)`   | resume a pending Workflow hook                          |
| `cancel(runId)`                | cancel a run                                            |

`start`'s optional `attributes` seed the run's searchable metadata (Workflow run attributes) at
creation, without an extra event. They are plaintext and the platform validates them before the run
exists, so an invalid one fails the start: keys of 1-256 characters not starting with `$`, values of
at most 256 UTF-8 bytes, at most 64 per run. Use identifiers, never secrets or content. A run
started from inside a workflow or step also gets the reserved `$parentRunId` and `$rootRunId`.

`VercelWorkflowRun` members:

| Member                  | Purpose                                                       |
| ----------------------- | ------------------------------------------------------------- |
| `runId`                 | native Workflow run id                                        |
| `getReadable(options?)` | Effect-wrapped readable stream for this run                   |
| `cancel`                | Effect that cancels this run                                  |
| `status`                | Effect that resolves the native run status                    |
| `returnValue`           | Effect that resolves the typed Workflow function return value |

The API wrapper keeps Vercel's SDK underneath. It does not reimplement Vercel backend HTTP, queue, hook, or stream internals.

Every Effect operation on `VercelWorkflows` and `VercelWorkflowRun` fails with
`VercelWorkflowsError`, which carries `_tag`, `operation`, `message`, and the original `cause`.
`operation` is one of `start`, `getRun`, `getReadable`, `tailIndex`, `resumeHook`, `cancel`,
`status`, or `returnValue`. `runId` is plain data and cannot fail.

`VercelWorkflowsClient` is the Effect service shape. `VercelWorkflowsSdkClient` and
`VercelWorkflowsSdkRun` are the lower-level Promise SDK seam used by `VercelWorkflowsSdk`.

## Testing exports [#testing-exports]

Import from `@yolk-sdk/vercel-workflows/testing`.

| Export                                                                                                                               | Purpose                                                                                                                                                                 |
| ------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `TestWorkflowWorld`                                                                                                                  | behavioral emulator for lifecycle, streams, steps, hooks, and cancellation                                                                                              |
| `testWorkflowModule`                                                                                                                 | ambient `workflow` module surface for `vi.mock`                                                                                                                         |
| `defaultTestWorkflowStepMaxRetries`                                                                                                  | emulated platform default retry budget                                                                                                                                  |
| `TestWorkflowStreamConflictError`, `TestWorkflowRunConflictError`                                                                    | write-after-close and run-state conflict errors                                                                                                                         |
| `TestWorkflowHookNotFoundError`, `TestWorkflowHookConflictError`, `TestWorkflowRunNotFoundError`, `TestWorkflowRunCancelledError`    | hook/run lookup and cancellation errors; awaiting a hook whose token another live hook held fails with `TestWorkflowHookConflictError` (`token`, `conflictingRunId`)    |
| `TestWorkflowRunStatus`, `TestWorkflowRunInspection`, `TestWorkflowMetadata`, `TestWorkflowStepMetadata`, `TestWorkflowStepFunction` | test-world status, inspection, and step contracts                                                                                                                       |
| `TestWorkflowHook`                                                                                                                   | disposable promise returned by emulated `createHook`                                                                                                                    |
| `TestWorkflowUnstorableStepError`                                                                                                    | a step error the platform could not store (`inspect(runId).unstorableStepErrors`)                                                                                       |
| `TestWorkflowWorldOptions`, `TestWorkflowDiscardedStepExecution`                                                                     | `discardStepExecution` reproduces Workflow 5.8 speculative execution; a discarded execution with its Effect `Result` outcome (`inspect(runId).discardedStepExecutions`) |

Executing steps loads the installed workflow runtime's step-error serializer, so tests that run steps
need Vitest's Node environment ([Step errors](../vercel-workflows/testing#step-errors)).

## Cloudflare runtime exports [#cloudflare-runtime-exports]

See [Cloudflare runtime](../vercel-workflows/cloudflare) for wiring.

| Subpath                                            | Main exports                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `@yolk-sdk/vercel-workflows/cloudflare`            | `WorkflowRun` (Durable Object class), `registerWorkflowModules`, `registerRunPreloads`, `WorkflowExecution`, `ExecutionHost`, `HookClaim`, `makeMemoryRunStore`, `makeSqliteRunStore`, `makeHookIndex`, `RunStore`, `RunRecord`, `RunStatus`, `JournalEntry`, `workflowRunsBinding`, `runNamespace`, `WorkflowRunStub`, `WorkflowRunNamespace`, `StartRunInput`, `StartNewOutcome`, `RunOutcome`, `WorkflowFunction`, `serialize`, `deserialize`, `FatalError`, `RetryableError`, `HookConflictError`, `HookNotFoundError`, `WorkflowRunCancelledError`, `parseDuration`, `defaultStepMaxRetries`, `stepGuardIntervalMs` |
| `@yolk-sdk/vercel-workflows/cloudflare/workflow`   | drop-in `workflow`: `createHook`, `sleep`, `getWritable`, `getStepMetadata`, `getWorkflowMetadata`, `FatalError`, `RetryableError`; Cloudflare-only `getStepSignal`                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `@yolk-sdk/vercel-workflows/cloudflare/api`        | drop-in `workflow/api`: `start`, `getRun`, `resumeHook`, `WorkflowRun`, `WorkflowReadableStream`, `WorkflowReadableStreamOptions`, `HookNotFoundError`, `WorkflowRunCancelledError`; Cloudflare-only `startWithRunId`, `StartWithRunIdResult`, `prepareRun`, `createRunId`, `isRunId`                                                                                                                                                                                                                                                                                                                                    |
| `@yolk-sdk/vercel-workflows/cloudflare/directives` | `workflowStep`, `workflowEntry` (imported by compiled directives)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `@yolk-sdk/vercel-workflows/cloudflare/vite`       | `workflowDirectives`, `WorkflowDirectivesOptions`, `workflowDirectivesRuntime`, `compileWorkflowDirectives`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |

## Callback types [#callback-types]

| Type                                     | Meaning                                                                           |
| ---------------------------------------- | --------------------------------------------------------------------------------- |
| `VercelAgentWorkflowInput`               | `{ request, context }` passed to workflow                                         |
| `SerializableWorkflowState`              | persisted loop state between steps                                                |
| `VercelAgentWorkflowLoopConfig`          | full config for `runVercelAgentWorkflow`                                          |
| `VercelAgentWorkflowModelStepInput`      | model callback input                                                              |
| `VercelAgentWorkflowModelStepResult`     | model callback result                                                             |
| `VercelAgentWorkflowToolBatchStepInput`  | tool callback input                                                               |
| `VercelAgentWorkflowToolBatchStepResult` | tool callback result                                                              |
| `VercelAgentWorkflowAwaitingInput`       | HITL hook payload                                                                 |
| `VercelAgentWorkflowRunResult`           | terminal run result union                                                         |
| `VercelAgentWorkflowStepRetryPolicy`     | `{ maxAttempts }`; finite values floor/clamp to `1`, non-finite values become `1` |
| `WorkflowStepResult`                     | `Success` / `Failure` wrapper from `settleWorkflowStep`                           |

## Durable event types [#durable-event-types]

| Type                                 | Meaning                                  |
| ------------------------------------ | ---------------------------------------- |
| `DurableAgentEvent`                  | JSON event with deterministic `eventId`  |
| `DurableAgentEventIdInput`           | input for `durableAgentEventId`          |
| `DurableAgentEventSequencerState`    | current durable event sequence state     |
| `SequenceDurableAgentEventInput`     | input for `sequenceDurableAgentEvent`    |
| `SequencedDurableAgentEvent`         | event plus current/next sequence values  |
| `WriteDurableAgentEventInput`        | sequenced event input plus stream writer |
| `CommitThenWriteTerminalEventInput`  | terminal barrier input                   |
| `CommitThenWriteTerminalEventResult` | terminal barrier result union            |

## Run result tags [#run-result-tags]

| Tag                   | Meaning                             |
| --------------------- | ----------------------------------- |
| `Completed`           | closed normally                     |
| `ModelStepFailed`     | model callback failed after retries |
| `ToolBatchStepFailed` | tool callback failed after retries  |
| `AwaitInputFailed`    | HITL hook failed or missing handler |
| `CloseStreamFailed`   | close callback failed after retries |
| `MaxTurnsExceeded`    | exceeded `maxTurns`                 |

## Harness constructors [#harness-constructors]

The separate `@yolk-sdk/harness` package exposes lifecycle model companions:

| Subpath                     | Constructor values                                                                    |
| --------------------------- | ------------------------------------------------------------------------------------- |
| `@yolk-sdk/harness/inbox`   | `HitlDecision`, `PauseDecision`, `RecoveryAttempt`, `RecoveryAdmission`, `DrainBegin` |
| `@yolk-sdk/harness/driver`  | `StopDecision`                                                                        |
| `@yolk-sdk/harness/outcome` | `OverflowCompactionResult`, `StepOutcome`, `HitlMatch`                                |

These are `Data.taggedEnum` constructors for the corresponding public types. They construct
receipt values, not lifecycle operations: hosts still use Driver/Inbox services to perform work.

## Terminal helper results [#terminal-helper-results]

| Tag                      | Meaning                                                 |
| ------------------------ | ------------------------------------------------------- |
| `Committed`              | commit succeeded and terminal write succeeded           |
| `CommitFailed`           | commit failed and commit-error terminal write succeeded |
| `TerminalWriteFailed`    | commit succeeded but terminal write failed              |
| `CommitErrorWriteFailed` | commit failed and commit-error terminal write failed    |

The terminal helper does not close streams or infer finality from event tags. Successful
`AgentEnd` closes through `closeStream`; failure `AgentError` closes through `writeError`. Release
the writer lock without final-closing resumable `AgentAwaitingInput`.


---

# Afloat MCP conformance

URL: /docs/connectors/afloat

Experimental Afloat MCP target, seeds, and fixtures for the MCP conformance cases, and the Afloat emulator profile.



Afloat's connector action (`afloat.mcp_auth`) is documented in the
[connectors package guide](./index) and the
[integrations reference](../integrations/connectors#afloat). This page lists the experimental
conformance target and the emulator profile only.

## Conformance cases [#conformance-cases]

> **Experimental.** For tests and hand-run checks against a practice Afloat account.

`@yolk-sdk/connectors/afloat/conformance` holds no case code. The cases are the generic MCP cases of
[`@yolk-sdk/mcp/conformance`](../api-reference/conformance#mcp-conformance), run through the real
`@yolk-sdk/mcp/client`; this subpath supplies what Afloat claims, as target and seed data. It never
imports `@yolk-sdk/mcp`.

* **Target.** `makeAfloatMcpConformanceTarget()` runs the real `afloat.mcp_auth` action over the
  host's `CredentialResolver` (for example `staticCredentialResolverLayer` of
  `@yolk-sdk/connectors/conformance`) and builds the `McpConformanceTarget` value from its output:
  server `afloat`, `https://useafloat.com/mcp`, era `modern`, protocol version `2026-07-28`, and the
  key as `Authorization: Bearer <afloat_ key>`. The auth case sends the public reserved invalid key
  `afloat_yolkconformanceinvalid0000` in the same header instead.
* **Seeds.** `afloatMcpConformanceLiveSeeds` name the published tools (`expectedTools`) and the two
  that write (`notReadOnly`), and no `readTool`: a live run calls a tool only when a person names
  it. `afloatMcpConformanceFixtureSeeds` add the synthetic read call the fixtures replay with:
  `list-invoices` with `{ "size": 10 }`, and `{ "size": "ten" }` as the invalid arguments.
* **Published tools.** Nine of the tools Afloat lists, in Afloat's listing order, with the source's
  names, titles, input and output schemas, and annotations (`afloatMcpConformanceTools`):
  `list-invoices`, `get-invoice`, `get-tax-return-download`, `get-logo-download`,
  `create-receipt-upload`, `complete-receipt-upload`, `get-receipt-download`, `get-invoice-pdf`, and
  `get-quote-pdf`. The tool descriptions and the server instructions are rewritten generically. The
  five download tools mint a one-hour grant on every call but are marked `readOnlyHint: true`; the
  two receipt-upload tools are marked `readOnlyHint: false`. Annotation keys keep the source's order
  (`readOnlyHint`, `destructiveHint`, `idempotentHint`, `openWorldHint`); JSON key order inside the
  input and output schemas follows the source's sorted schema snapshot, so a live listing may order
  those keys differently.

| Case id                           | Applies | Afloat claim (as currently understood)                                                                         |
| --------------------------------- | ------- | -------------------------------------------------------------------------------------------------------------- |
| `mcp.negotiation.era`             | yes     | `server/discover` answers `supportedVersions: ["2026-07-28"]` with `capabilities.tools`: the modern era        |
| `mcp.modern.stateless`            | yes     | No answer carries `mcp-session-id`; every result carries `resultType: "complete"`                              |
| `mcp.legacy.session`              | no      | Afloat is modern; its `2025-11-25` fallback is stateless (no session), and the client never selects it         |
| `mcp.transport.response-encoding` | yes     | Every answer is one `application/json` body holding the response                                               |
| `mcp.tools.list`                  | yes     | One listing page holds every published tool; the receipt-upload tools are never marked read-only               |
| `mcp.tools.call-read`             | yes     | `list-invoices` answers a tool result whose `structuredContent` passes its output schema                       |
| `mcp.tools.call-tool-error`       | yes     | Invalid arguments answer `isError: true` with a `VALIDATION_ERROR` text, not a JSON-RPC error                  |
| `mcp.errors.unknown-tool`         | yes     | An absent tool answers JSON-RPC `-32602` with the request id, at HTTP 200                                      |
| `mcp.auth.rejected`               | yes     | The reserved invalid key answers 401 with `WWW-Authenticate: Bearer` and a JSON error body; no listing follows |

`afloatMcpConformanceNotApplicable` lists the case that does not apply and why;
`selectMcpConformanceCases(cases, 'modern')` gives the same split.

**Fixtures.** `afloatMcpConformanceFixtures` holds one fixture per applicable case, on the real
endpoint, `evidence: 'unverified'`, account `synthetic`. They are **derived from the provider's
source (owner-supplied), not a live recording**: no live Afloat service was contacted. The answers
are what the pinned official MCP server SDK (2.0.0, the version Afloat pins) produces when it runs
in-process with Afloat's handler options (the stateless legacy fallback and JSON responses), server
info, and tool capability, over the published tool subset; the tool results and the 401 follow
Afloat's output builders over synthetic data (cuid-shaped `yolksynthetic…` ids, a synthetic request
id). The requests are the ones the client sends, in its order; `authorization` is never recorded,
and Afloat's `x-request-id` response header is not kept. Every `tools/call` answer is a minimal
synthetic body, checked by an allowlist test. The shared credential scan flags Afloat-shaped keys
(`afloat_` followed by 16 or more letters and digits).

Claims no live run has settled yet: all of them (no case is observed live), in particular the real
listing's size (it holds more than the nine published tools), whether a live 401 carries more than
`Bearer`, and whether a call of an absent tool still answers HTTP 200.

### Live runs [#live-runs]

`pnpm conformance:mcp --target afloat` dry-runs by default (no network, no credential read) and
lists `mcp.legacy.session` as not applicable. `--live --owner-approved --account <label>` runs the
cases against a practice account, never in CI; `AFLOAT_API_KEY` is read from the environment only
and must be `afloat_` followed by 16 to 256 letters and digits; every printed line is redacted of
the key and of its secret remainder after `afloat_`, and argument errors never repeat a value. A
tool is called only when a person names it on the command line:
`--read-tool <name> --read-args <json>` adds `mcp.tools.call-read`, and
`--read-tool <name> --invalid-args <json>` adds `mcp.tools.call-tool-error` (flags only: no
environment variable switches a call on; the listing must mark the tool read-only, and a download
tool mints a grant, so prefer `list-invoices`). `--record` stages recordings under the gitignored
`.conformance-recordings/mcp/afloat/` (refusing any recording that carries the key or its remainder
alone, in any encoding) for wholesale synthetic replacement: every `tools/call` answer body is
replaced by a minimal synthetic one before promotion, never scrubbed field by field.
`--target figma` is refused until an owner-approved practice seat exists.

### Confirmation-gated tools [#confirmation-gated-tools]

Afloat confirms destructive tools (hard deletes, tax-return generation) with MCP form elicitation
over multi round-trip requests: a client that declares `elicitation.form` gets an
`InputRequiredResult` and resumes with `callRemoteMcpServerToolResumable` and
`resumeRemoteMcpServerToolCall`; a client that does not, including every legacy-era client, gets a
`CLIENT_CAPABILITY_REQUIRED` tool error. The conformance cases never call these tools (the call gate
forwards only read-only calls), and no Afloat fixture covers them. The opt-in
`mcpElicitationDeclarationCase` only lists; against Afloat it is a dry-run note for now: it has no
Afloat fixture and the runner does not schedule it, so a live check would need its own owner-approved
run.

## Emulator profile [#emulator-profile]

`@yolk-sdk/emulators/mcp` serves profile `afloat` on `https://useafloat.com/mcp` from a data copy of
these fixtures (`mcpEmulatorAfloatFixtures`; a drift test fails when they differ): stateless
`2026-07-28`, JSON answers, no session, one listing page, the `list-invoices` call and its tool
error, the absent tool, and the 401. The two `tools/call` answers are derived, not recorded calls:
answering them is in scope by the owner's decision, and they stay `unverified` until an
owner-approved live run records a call. The credential rule: on `https://useafloat.com` a bearer is
recognised only as `afloat_<remainder>` with a remainder that passes the emulators' recognisable
bearer rule (an Afloat key starts with the hex digit `a`, which fails it), and the remainder is the
guarded secret, never stored, ledgered, or echoed. Use a synthetic key such as
`afloat_synthetic-key-0001`.

Setup fragment (inside an async test; not a runnable example):

```ts
import { Effect, Layer } from 'effect'
import { ApiKeyCredential } from '@yolk-sdk/connectors'
import {
  afloatMcpConformanceFixtureSeeds,
  makeAfloatMcpConformanceTarget
} from '@yolk-sdk/connectors/afloat/conformance'
import { staticCredentialResolverLayer } from '@yolk-sdk/connectors/conformance'
import { makeMcpEmulator, mcpEmulatorAfloatOrigin } from '@yolk-sdk/emulators/mcp'
import { EmulatorRoute, InProcessHttpClient } from '@yolk-sdk/emulators/router'
import { McpConformanceConfig, McpConformanceTarget } from '@yolk-sdk/mcp/conformance'

const emulator = await makeMcpEmulator()

const layer = Layer.mergeAll(
  InProcessHttpClient.layer([EmulatorRoute.handler(mcpEmulatorAfloatOrigin, emulator.fetch)]),
  Layer.effect(
    McpConformanceTarget,
    makeAfloatMcpConformanceTarget().pipe(
      Effect.provide(
        staticCredentialResolverLayer(ApiKeyCredential.make({ key: 'afloat_synthetic-key-0001' }))
      )
    )
  ),
  Layer.succeed(McpConformanceConfig, afloatMcpConformanceFixtureSeeds)
)
// ...run the applicable cases with `layer`, then:
await emulator.close()
```

See the [MCP emulator reference](../api-reference/emulators#mcp-emulator) for faults, refusals, and
the request-shape latitude.


---

# Dropbox conformance

URL: /docs/connectors/dropbox

Experimental Dropbox conformance cases for tests and hand-run practice-account checks.



Dropbox actions are documented in the [connectors package guide](./index) and the
[integrations reference](../integrations/connectors#dropbox). This page lists the experimental
conformance cases only.

## Conformance cases [#conformance-cases]

> **Experimental.** For tests and hand-run checks against a practice Dropbox account.

`@yolk-sdk/connectors/dropbox/conformance` exports conformance cases for
`@yolk-sdk/conformance/runner`. Every case runs the real connector actions or the host-only upload
helpers (`createDropboxFile`, `updateDropboxFile`) over the connector ports, and checks one wire
claim the connector relies on. The claims are as currently understood; none is observed live yet.

| Case id                                   | Safety             | Seeds                                       | Claim (as currently understood)                                                                                                                                  |
| ----------------------------------------- | ------------------ | ------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `dropbox.files.list-folder-cursor-paging` | `read`             | `pagingFolderPath`                          | `limit: 2` on a larger folder answers `has_more` and a cursor; `list_folder/continue` returns the rest with no repeats and still carries a cursor at the end     |
| `dropbox.files.path-lower-lookup`         | `read`             | `mixedCasePath`                             | A lower-cased path finds the same entry id; `path_lower` is the lower-cased path and the last `path_display` component keeps its casing                          |
| `dropbox.files.search-continue`           | `read`             | `searchQuery`                               | `max_results: 1` answers the nested `{ ".tag": "metadata", metadata }` match, `has_more`, and a cursor; `search/continue_v2` returns new matches                 |
| `dropbox.errors.not-found-409-envelope`   | `read`             | `workFolderPath`                            | A missing path answers HTTP 409 (not 404) with `error_summary` `path/not_found/...`; the connector reports `dropbox_not_found`                                   |
| `dropbox.files.create-folder-conflict`    | `write-reversible` | `workFolderPath`, `runId`                   | Creating an existing folder again, or with its name upper-cased, fails with HTTP 409 `path/conflict/folder` (`dropbox_conflict`)                                 |
| `dropbox.files.delete-then-not-found`     | `write-reversible` | `workFolderPath`, `runId`                   | `delete_v2` answers the folder metadata; `get_metadata` then answers `not_found`, and with `include_deleted` answers `deleted` metadata (unverified for folders) |
| `dropbox.files.copy-move-metadata`        | `write-reversible` | `workFolderPath`, `copySourcePath`, `runId` | Single-item `copy_v2` answers `{ metadata }` for a new file; `move_v2` answers `{ metadata }` keeping the id; no async job                                       |
| `dropbox.files.upload-rev-precondition`   | `write-reversible` | `workFolderPath`, `runId`                   | `add` never overwrites and an `update` naming a stale rev fails with HTTP 409 (`conflict`); the file keeps its current rev                                       |

A wire claim no live run has settled yet, marked "(unverified: ...)" in its case's `wire`:

* `get_metadata` with `include_deleted` answers `deleted` metadata for a deleted **folder**, not
  only for files.

A cleanup assumption, which no case asserts: the cleanup's `delete_v2` accepts the created entry's
`id:` form. When it does not, the cleanup falls back to the owned path, so a passing run does not
show which delete removed the folder.

`DropboxConformanceConfig` holds the seed paths and the `runId`. Cases never hard-code account data, and a missing
seed fails the case with a `precondition:` mismatch before any request. Credentials bind through
`dropboxConformanceIntegration` (`dropbox.oauth`, credential ref `dropbox.conformance`); an OAuth or
bearer token for the practice account needs `files.metadata.read` and `files.content.write`.

Every write case works only inside its own `yolk-conformance-<runId>-<case>` folder under
`workFolderPath`. The `runId` seed makes that namespace unique per invocation: the fixtures replay
with `run-synthetic`, and the live runner generates a fresh random id every time (it is never a
flag). &#x2A;*Concurrent runs are supported only through distinct run ids.** The cleanup is attempted and
verified under these conditions:

* Before writing, a case proves its folder path absent; an existing entry is a precondition failure,
  and nothing is written.
* The create request, its decoding, and the registration of the created entry run together without
  interruption, and so does every later write inside the case folder (copy, move, upload, delete):
  an aborted request could otherwise land after the cleanup. Neither the runner nor the bridges set
  a request timeout, so a hanging request delays an interruption until it answers.
* A definitive create rejection (HTTP 4xx other than 408, such as `path/conflict` when something else created the
  folder first) proves the case created nothing: it fails and deletes **nothing**.
* An ambiguous create (a transport or decoding failure, no status, HTTP 408, or HTTP 5xx) may still create the
  folder later. The case makes one best-effort delete of its own path, but always fails with
  `DropboxConformanceActionFailed` (`createOutcome: 'unknown'`) naming the exact path: check it by
  hand. The same holds for the conflict case's two duplicate creates: the known original is cleaned
  up as usual, then the case reports the attempted path as an unknown create.
* After a successful create, the cleanup deletes the entry by id and checks that `get_metadata`
  then answers not-found. A not-found answer to the id delete proves the entry gone; any other
  failure of it (a rejected `id:` form, a transport failure) falls back to the owned path. The
  cleanup also runs after a failed assertion or a fiber interruption. A failed cleanup fails with
  `DropboxConformanceRestoreFailed` naming the path.
* A create that answers a path outside the case folder is never deleted: the case fails with
  `DropboxConformanceCleanupRefused` naming it.

Deleted folders stay restorable in the account's deleted files for the Dropbox retention period.

In the live runner, the first SIGINT or SIGTERM (Ctrl-C) interrupts the run fiber, and the running
case's cleanup is attempted before the process exits; no further case starts. The cleanup is not
confirmed:

* A cleanup that fails, or a create whose outcome is unknown, while the case is being interrupted
  prints its full message, with the exact path, as a WARN line (through the case's
  `ConformanceCleanupReporter`). The run still ends as a plain interruption (exit code 130): the
  WARN line is the record of the problem.
* After the interruption, the runner lists `workFolderPath` again (read-only, bounded as below) and print a WARN line for every
  `yolk-conformance-run-*` folder still present.

One Ctrl-C reaches every process of the foreground group, and the wrappers relay it, so further
signals within a second count as the same keypress. A signal a second or more later exits at once
and may skip the cleanup, as does killing the process. Run live runs as
`pnpm conformance:dropbox …` (pnpm waits for the runner and exits with its code; observed with
pnpm 11) or `./node_modules/.bin/tsx scripts/run-dropbox-conformance.ts …`. Avoid
`pnpm exec tsx …`: on Ctrl-C it returns to the prompt at once (observed), so the WARN and leftover
lines print after the prompt, `$?` is pnpm's own code rather than the runner's, and a second Ctrl-C
no longer reaches the runner; stop it with `kill -TERM <pid>`, using the pid the first-signal
message prints, at least a second after the first signal.

Before any write case, the runner lists `workFolderPath` read-only
(`findDropboxConformanceLeftovers`) and prints a WARN line for each `yolk-conformance-run-*`
folder an earlier run left behind; a work folder that does not exist yet holds none, and a failed
lookup prints its failure code. The lookup is bounded, not exhaustive: it reads at most 50 listing
pages of up to 2,000 entries each. It never deletes them. Check each one, and delete it by hand when
no run is using it. Every valid `runId` starts with `run-` (`dropboxConformanceRunFolderPrefix` is
`yolk-conformance-run-`), so the lookup covers every run, host-supplied run ids included.

The shipped fixtures are synthetic (`evidence: 'unverified'`). In this repository,
`pnpm conformance:dropbox` dry-runs by default; `--live --owner-approved --account <label>` (refused
whenever `CI` is non-empty) needs `DROPBOX_ACCESS_TOKEN` and the seeds, `--allow-writes reversible`
adds the write cases, and `--record` stages verified recordings only in the gitignored
`.conformance-recordings/dropbox/` for manual scrubbing and promotion. See
[Conformance APIs](../api-reference/conformance#connector-conformance) for the bridges.

For offline tests, the experimental
[Dropbox emulator](../api-reference/emulators#dropbox-emulator) (`@yolk-sdk/emulators/dropbox`) is a
stateful, fixture-only stand-in that passes these cases through the real connector actions and
upload helpers over the connector ports; route both `https://api.dropboxapi.com` and
`https://content.dropboxapi.com` to it (each route answers only on the origin its fixtures record).
The leftover lookup fails against its default seed: no fixture records a listing of the empty work
folder, so the emulator answers it not-emulated (HTTP 400) and the runner prints its lookup-failed
`WARN`.


---

# Email conformance

URL: /docs/connectors/email

Experimental port-level conformance cases for the generic EmailClient, for tests and hand-run practice-mailbox checks.



Generic email actions are documented in the [connectors package guide](./index) and the
[integrations reference](../api-reference/integrations). This page lists the experimental
conformance cases only.

## Conformance cases [#conformance-cases]

> **Experimental.** For tests and hand-run checks against a practice mailbox.

Yolk never speaks IMAP, POP3, or SMTP: generic email goes through the host-provided `EmailClient`
port. `@yolk-sdk/connectors/email/conformance` exports port-level cases for
`@yolk-sdk/conformance/runner` that run the real connector email actions over that port, plus
`CredentialResolver` and `EmailConformanceConfig` seeds. The claims are as currently understood;
none is observed live yet, and the fixtures are synthetic `PortFixture`s.

| Case id                                       | Safety               | Seeds                                               | Claim (as currently understood)                                                                                                                                                                                                               |
| --------------------------------------------- | -------------------- | --------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `email.imap.list-and-get-headers`             | `read`               | `imapHost`, `unreadMessageId`                       | `get_message` returns the id and `headers` including `Date` and `From` (and a matching `Message-ID`); listing again still shows the message unread (`BODY.PEEK`)                                                                              |
| `email.imap.filtered-list-no-fallback`        | `read`               | `imapHost`, `unreadMessageId`                       | An `isRead: false` list calls `listMessagesFiltered` once and `listMessages` never; against a legacy-host shim without it, the list fails `validation_failed` with no call                                                                    |
| `email.imap.draft-drafts-discovery`           | `write-reversible`   | `imapHost`, `draftsFolder`                          | A folder-less draft lands in the `\Drafts` SPECIAL-USE mailbox (not a fallback name) with a `draftId` that reads it back; `\Draft` itself is checked by hand                                                                                  |
| `email.imap.set-read-and-flag`                | `write-reversible`   | `imapHost`, `unreadMessageId`                       | `set_read` and `set_flag` each change exactly one flag, visible through `get_message`; the restore puts both back                                                                                                                             |
| `email.imap.trash-untrash-to-inbox`           | `write-reversible`   | `imapHost`, `draftsFolder`, `trashFolder`           | Trash moves the case's draft to the discovered `\Trash` mailbox with a new id; untrash restores it to INBOX (not the Drafts mailbox) with another new id                                                                                      |
| `email.imap.move-destination-ids`             | `write-reversible`   | `imapHost`, `draftsFolder`, `moveDestinationFolder` | A move returns the destination id, which resolves there; the stale source id answers `message_not_found` (any other failure fails the case)                                                                                                   |
| `email.pop3.rejects-folders-drafts-mutations` | `read`               | `pop3Host`                                          | POP3 folders, filters, drafts, and every mutation (single-message, labels, the six batch actions, and `delete_permanently`) fail `validation_failed` with no port call and no credential resolution; a plain list reaches `listMessages` once |
| `email.smtp.sent-copy-statuses`               | `write-irreversible` | `imapHost`, `smtpHost`, `recipient`, `sentFolder`   | Default saving sends an IMAP `sentCopy` and reports `saved` in the `\Sent` mailbox; `saveToSentItems: false` reports `skipped`; a missing Sent folder reports `failed`, still accepted                                                        |
| `email.smtp.legacy-host-sent-copy`            | `write-irreversible` | `imapHost`, `smtpHost`, `recipient`                 | Behind a legacy-host shim (no `sentCopy` in or out), the action synthesizes `unsupported` (saving requested) or `skipped` (disabled), never `saved`                                                                                           |
| `email.smtp.acceptance-not-delivery`          | `write-irreversible` | `imapHost`, `smtpHost`, `undeliverableRecipient`    | SMTP accepts a submission to an undeliverable address; the output claims submission only (`accepted`, `submissionId`, `sentCopy`, `warning`), never delivery                                                                                  |

The move case relies on one host-port convention, exported as `emailMessageNotFoundCode`:
`EmailClient.getMessage` for an id that addresses no message in the folder answers
`ActionResult.failure` with code `message_not_found`. Authentication, throttling, or server
failures prove nothing about absence, so they fail the case.

`EmailConformanceConfig` holds the seeds; a missing seed fails the case with a `precondition:`
mismatch before any port call. Use a practice mailbox whose `\Drafts` mailbox is not literally
named `Drafts`, so discovery differs from a hard-coded fallback. Credentials bind through
`emailConformanceIntegration` (credential refs `email.conformance.incoming` and
`email.conformance.smtp`).

Write cases never touch seeded messages except the flag case, which restores the seeded flags.
Draft, trash, and move cases create their own `yolk-conformance` draft, track its location across
moves, and permanently delete it again through `email.delete_permanently`, also after a failed
claim or an interruption. A failed removal fails the case with `EmailConformanceRestoreFailed`;
remove the draft by hand if it still exists. The three send cases send real mail (to the practice
mailbox itself, or to the seeded undeliverable address) and run live only when started by id.

For tests, `emailClientLayerFromBackend` turns any plain-JSON backend `{ call(method, request) }`
into the `EmailClient` layer. `makeEmailReplayBackend(fixtures)` returns `{ backend, ledger }`, so
pass its `backend` (and keep the `ledger` to check which fixtures answered):

```ts
import {
  emailClientLayerFromBackend,
  emailConformanceFixtures,
  makeEmailReplayBackend
} from '@yolk-sdk/connectors/email/conformance'

const replay = makeEmailReplayBackend(emailConformanceFixtures)
const emailLayer = emailClientLayerFromBackend(replay.backend)
```

The fixture-driven fake in [`@yolk-sdk/emulators/email`](../api-reference/emulators#email-emulator)
is itself a backend: pass it directly (`emailClientLayerFromBackend(makeEmailEmulator())`). Neither
is a production adapter. Live verification needs a host `EmailClient` implementation connected to a
practice mailbox; no live probe ships in the repository. See
[Conformance APIs](../api-reference/conformance#connector-conformance) for the fixture type.


---

# Figma MCP conformance

URL: /docs/connectors/figma

Experimental Figma MCP target, seeds, and synthetic fixtures for the MCP conformance cases, and the Figma emulator profile.



Figma's connector action (`figma.mcp_auth`) is documented in the
[connectors package guide](./index) and the
[integrations reference](../integrations/connectors#figma). This page lists the experimental
conformance target and the emulator profile only.

## Conformance cases [#conformance-cases]

> **Experimental.** For tests; no live run exists yet.

`@yolk-sdk/connectors/figma/conformance` holds no case code. The cases are the generic MCP cases of
[`@yolk-sdk/mcp/conformance`](../api-reference/conformance#mcp-conformance), run through the real
`@yolk-sdk/mcp/client`; this subpath supplies what Figma claims, as target and seed data. It never
imports `@yolk-sdk/mcp`.

* **Target.** `makeFigmaMcpConformanceTarget()` runs the real `figma.mcp_auth` action over the
  host's `CredentialResolver` (an `OAuthCredential` or `BearerTokenCredential`) and builds the
  `McpConformanceTarget` value from its output: server `figma`, `https://mcp.figma.com/mcp`, and the
  access token as `Authorization: Bearer <token>`. The refresh token and client credentials of the
  output are never sent. The auth case sends the public reserved invalid credential
  `yolk-conformance-invalid-credential-0000` in the same header instead.
* **Era.** The target is legacy-era with protocol `2025-11-25` (an `initialize` handshake with a
  session), unverified until a live run: `figma.mcp_auth` names no protocol version.
* **Seeds.** `figmaMcpConformanceLiveSeeds` name six known Figma tool names (`expectedTools`) and
  the two that write (`notReadOnly`), and no `readTool`. `figmaMcpConformanceFixtureSeeds` add the
  synthetic read call the fixtures replay with: `get_metadata` with `{ "nodeId": "0:1" }`, and
  `{ "nodeId": 1 }` as the invalid arguments.
* **Published tools.** `figmaMcpConformanceTools`: `get_design_context`, `get_metadata`,
  `get_screenshot`, `whoami`, `use_figma`, and `create_new_file`, with synthetic placeholder input
  schemas and descriptions, never Figma's (dynamic discovery owns the real contract). The four
  reads are marked `readOnlyHint: true`, `use_figma` and `create_new_file` `readOnlyHint: false`.

| Case id                           | Applies | Figma claim (as currently understood)                                                                                             |
| --------------------------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------- |
| `mcp.negotiation.era`             | yes     | `server/discover` answers 400 with a JSON-RPC error: the client falls back to the legacy era                                      |
| `mcp.modern.stateless`            | no      | The target is legacy-era                                                                                                          |
| `mcp.legacy.session`              | yes     | `initialize` issues a session id every later request echoes; initialized gets 202, the standing GET 405, the closing `DELETE` 200 |
| `mcp.transport.response-encoding` | yes     | Every answer to a request is an SSE stream holding the response, then the end; 202 has no body                                    |
| `mcp.tools.list`                  | yes     | One listing page holds every published tool; `use_figma` and `create_new_file` are never read-only                                |
| `mcp.tools.call-read`             | yes     | `get_metadata` answers a text tool result                                                                                         |
| `mcp.tools.call-tool-error`       | yes     | Invalid arguments answer `isError: true` with text content, not a JSON-RPC error                                                  |
| `mcp.errors.unknown-tool`         | yes     | An absent tool answers JSON-RPC `-32602` with the request id, inside an HTTP 200 SSE stream                                       |
| `mcp.auth.rejected`               | yes     | The reserved invalid credential answers 401 with a `WWW-Authenticate` Bearer challenge                                            |

`figmaMcpConformanceNotApplicable` lists the case that does not apply and why;
`selectMcpConformanceCases(cases, 'legacy')` gives the same split.

**Fixtures.** `figmaMcpConformanceFixtures` holds one fixture per applicable case, on the real
endpoint, `evidence: 'unverified'`, account `synthetic`. They are **synthetic placeholders**, neither
recorded from a live service nor derived from provider source: the envelopes are the ones a pre-2026
stateful server on the official MCP server SDK answers, the listing publishes known Figma tool names
with synthetic schemas, and every `tools/call` answer is a minimal synthetic body checked by an
allowlist test. Every claim is unverified, in particular the era and protocol version, whether the
server answers over SSE or JSON, the real listing (it holds more tools, with Figma's schemas and
annotations), and the 401 challenge.

### Live runs [#live-runs]

There is none yet: `pnpm conformance:mcp --target figma` stays refused until an owner-approved
practice seat exists.

## Emulator profile [#emulator-profile]

`@yolk-sdk/emulators/mcp` serves profile `figma` on `https://mcp.figma.com/mcp` from a data copy of
these fixtures (`mcpEmulatorFigmaFixtures`; a drift test fails when they differ), in the legacy era
exactly as its synthetic legacy profile: a session-less era probe answered 400, `initialize`
minting a session over SSE, `notifications/initialized` 202, the standing `GET` 405, one listing
page, the `get_metadata` call and its tool error, the absent tool, and the 401. Every legacy
session is bound to the profile that minted it. The bearer follows the plain recognisable-bearer
rule: use a synthetic token such as `synthetic-figma-token-0001`. Route `https://mcp.figma.com` to
it (`mcpEmulatorFigmaOrigin`), or serve `fetchOn(mcpEmulatorFigmaOrigin)` behind a loopback rewrite.
See the [MCP emulator](../api-reference/emulators#mcp-emulator).


---

# Transfer connector files

URL: /docs/connectors/files

Download bytes and create or update files through bounded host-only ports.



Use these helpers in trusted host code, not connector action arrays. They return `Uint8Array`
bytes or allowlisted write metadata. Your host authorizes the operation, supplies the transport,
materializes and scans files, and extracts content for an agent. A skill cannot perform downloads,
and `makeConnectorToolModule` does not expose these helpers. Existing base64 attachment actions
remain available for compatibility; do not route the new byte results through generic tool JSON.

## Start with a bounded download [#start-with-a-bounded-download]

Install matching package versions as described in [Connectors](./index). Host integration fragment:

```ts
import { downloadGoogleDriveFile } from '@yolk-sdk/connectors/google'

const budget = {
  maxBytes: 20_000_000,
  maxMetadataBytes: 1_000_000,
  maxErrorBodyBytes: 16_384
}

const program = downloadGoogleDriveFile(
  googleIntegration, // host-owned integration with a google.oauth binding
  { fileId: selectedFile.id, resourceKey: selectedFile.resourceKey },
  budget
)
// Provide CredentialResolver + ConnectorBinaryHttpClient, then run in the host runtime.
// Result: { bytes, byteLength, source }. Store/scan/extract; never serialize raw bytes to an agent.
```

Budgets are trusted host configuration, not model parameters. `maxBytes` bounds downloaded or
uploaded file bytes; `maxMetadataBytes` separately bounds JSON responses; `maxErrorBodyBytes`
bounds unsuccessful/redirect bodies. Zero-length files are supported. Gmail needs a metadata budget
large enough for JSON plus base64 expansion. Existing `downloadDropboxFile` retains its two-field
budget without `maxMetadataBytes`; existing OneDrive download keeps its original API.

## Capability matrix [#capability-matrix]

All names below are exported through the indicated `@yolk-sdk/connectors/*` subpath.

| Provider/subpath       | Host byte retrieval                                                                                                                                                                                                                        | Host byte writes                                     | Discovery and limits                                                                                                                 |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| Dropbox (`dropbox`)    | `downloadDropboxFile`, `streamDropboxFile`, `getDropboxTemporaryLink`                                                                                                                                                                      | `createDropboxFile`, `updateDropboxFile`             | Existing metadata actions; 150,000,000-byte single upload, upload sessions past it (at most 350 GB)                                  |
| OneDrive (`microsoft`) | `downloadOneDriveItem`, `streamOneDriveItem`, `getOneDriveDownloadUrl`                                                                                                                                                                     | `createOneDriveFile`, `updateOneDriveFile`           | Existing drive actions; 250,000,000-byte single upload, upload sessions past it (at most 250 GB)                                     |
| R2 (`r2-storage`)      | `getR2Object`                                                                                                                                                                                                                              | `createR2Object`, `updateR2Object`                   | Host supplies bucket/key and `R2ObjectClient`; 100,000,000-byte PUT cap                                                              |
| Drive (`google`)       | `downloadGoogleDriveFile`, `exportGoogleDriveFile`, `streamGoogleDriveFile`, `streamGoogleDriveExport`, `exportGoogleDriveText`                                                                                                            | Not added                                            | Blob versus explicit native export; 10,000,000-byte export cap                                                                       |
| Fortnox (`fortnox`)    | `downloadFortnoxInvoicePreview`, `streamFortnoxInvoicePreview`, `downloadFortnoxOfferPreview`, `streamFortnoxOfferPreview`, `downloadFortnoxArchiveFile`, `streamFortnoxArchiveFile`, `downloadFortnoxInboxFile`, `streamFortnoxInboxFile` | `uploadFortnoxInboxFile`, `uploadFortnoxArchiveFile` | `fortnox.list_supplier_invoice_files`, `fortnox.get_inbox_folder`; previews are generated PDFs; 50 MiB inbox and archive upload caps |
| Notion (`notion`)      | `downloadNotionFile`, `streamNotionFile`                                                                                                                                                                                                   | Not added                                            | Page/property/block file objects; required host URL policy                                                                           |
| Gmail (`google`)       | `downloadGmailAttachment`, `streamGmailAttachment`                                                                                                                                                                                         | Not added                                            | Existing attachment discovery; canonical base64url decoded inside host helper; streamed send and draft twins (below)                 |
| Outlook (`microsoft`)  | `downloadOutlookAttachment`, `streamOutlookAttachment`                                                                                                                                                                                     | `addOutlookAttachment` (drafts)                      | Existing discovery; file attachments only, raw `/$value`; uploads up to 150 MiB                                                      |
| IMAP/POP3 (`email`)    | `downloadEmailAttachment`, `streamEmailAttachment`                                                                                                                                                                                         | Not added                                            | Optional `EmailClient.getAttachmentBytes`; no MIME library bundled                                                                   |
| Telegram (`telegram`)  | `downloadTelegramFile`, `streamTelegramFile`                                                                                                                                                                                               | Not added                                            | File IDs from messages available to the bot; 20,000,000-byte hosted download cap                                                     |
| Todoist (`todoist`)    | `downloadTodoistAttachment`, `streamTodoistAttachment`                                                                                                                                                                                     | Not added                                            | `todoist.list_comments` with task/project selection; download by comment ID                                                          |
| GitHub (`github`)      | Not added                                                                                                                                                                                                                                  | `uploadGithubAttachment`                             | Undocumented user-attachments endpoint; user token only; 10 MB image / 100 MB video cap                                              |
| Afloat (`afloat`)      | Reuse remote MCP file grants                                                                                                                                                                                                               | Reuse remote MCP upload intents                      | Dynamic discovery owns exact contracts; no duplicate SDK file wrappers                                                               |
| Figma (`figma`)        | Reuse remote MCP asset exports                                                                                                                                                                                                             | Reuse remote MCP asset/design tools                  | No whole `.fig` download or arbitrary file-upload claim                                                                              |

## Stream, or skip the download [#stream-or-skip-the-download]

A buffered download holds the whole file in the host's memory until it returns. Where memory is
shared (several sessions in one isolate, for example), skip the download where the provider allows
it and stream where it does not.

### Pre-authorized links [#pre-authorized-links]

```ts
import { Redacted } from 'effect'
import { getDropboxTemporaryLink } from '@yolk-sdk/connectors/dropbox'
import { getOneDriveDownloadUrl } from '@yolk-sdk/connectors/microsoft'

const dropboxLink = getDropboxTemporaryLink(dropboxIntegration, { path: selectedFile.id })
const oneDriveLink = getOneDriveDownloadUrl(microsoftIntegration, { itemId, driveId }, budget)
// Result: { url: Redacted<string>, expiresAt, source, requested }.
// Hand Redacted.value(result.url) only to the component allowed to fetch the file.
```

Both answer the provider's own short-lived link to the file's content, which works without
credentials, so another component (a parser Worker, for example) can fetch the file and the host
never holds it. `getDropboxTemporaryLink` calls `POST /2/files/get_temporary_link` over
`ConnectorHttpClient` with the `files.content.read` slot and needs no budget (there is no body to
bound). `getOneDriveDownloadUrl` runs the `downloadOneDriveItem` metadata walk (same slots, guards,
remote items and size check) and selects `@microsoft.graph.downloadUrl`. Inputs, identity checks
and error codes match the downloads.

* **Links are secrets.** Anyone holding one reads the file until it expires. `url` is a
  `Redacted<string>`: logs, `String()` and `JSON.stringify` print `<redacted>`, and no error ever
  carries it. Your host decides who may use it and must not log it either.
* **Lifetime.** `expiresAt` (epoch ms) is conservative: the request time plus the provider's
  documented lifetime, minus `connectorLinkExpiryMarginMs` (5 minutes, so a link is not handed on
  just before it ends): `dropboxTemporaryLinkLifetimeMs` (4 hours; then Dropbox answers 410) and
  `oneDriveDownloadUrlLifetimeMs` (about 1 hour, treated as an upper bound; Graph documents it only
  as short-lived). A link may stop working sooner, and removing a permission may not invalidate a
  Graph link at once.
* **Network policy.** The SDK screens a link's syntax (public HTTPS) only. The component that
  fetches it must apply the binary port's policy: public DNS and socket IP on every hop, TLS, no
  cookies or ambient credentials.
* Drive blobs (`webContentLink` needs a Google session) and Todoist attachments (`files.todoist.com`
  needs the token) have no credential-free link: stream them.

### Google-native files as text [#google-native-files-as-text]

`exportGoogleDriveText(integration, { fileId, resourceKey? }, budget)` exports a Google Doc as
Markdown, a Sheet as CSV (the first sheet only) and Slides as plain text
(`googleDriveTextExportTypes`), through Drive's export and its 10,000,000-byte cap. It answers
`{ text, byteLength, source }`: UTF-8 text without a leading byte order mark, so no binary
download or document parser is needed. The format follows the file's type, read from its metadata
first; other types, blobs included, fail with `not_downloadable` before any content request, and
text that is not UTF-8 fails with `invalid_metadata`.

### Streamed downloads [#streamed-downloads]

```ts
import { Effect } from 'effect'
import { streamOneDriveItem } from '@yolk-sdk/connectors/microsoft'

const stored = Effect.scoped(
  Effect.gen(function* () {
    const file = yield* streamOneDriveItem(microsoftIntegration, { itemId, driveId }, budget)
    // file: { body: Stream<Uint8Array, OneDriveDownloadError>, contentLength, source, requested }
    return yield* hostStorage.put(key, file.body, file.contentLength) // app-owned sink
  })
)
```

`streamDropboxFile`, `streamOneDriveItem`, `streamGoogleDriveFile`, `streamGoogleDriveExport`,
`streamTodoistAttachment`, `streamOutlookAttachment`, `streamNotionFile`, `streamTelegramFile`,
`streamFortnoxInvoicePreview`, `streamFortnoxOfferPreview`, `streamFortnoxArchiveFile` and
`streamFortnoxInboxFile` take the same arguments as their buffered twins and send the same requests
(same slots, redirect rules and errors); a Fortnox preview's PDF magic bytes are checked as the body
streams. They answer the same `source` metadata plus `body` and `contentLength`
(`ConnectorFileStream`): the exact length a completed body has, when the provider reported a size
(Dropbox, Drive blobs, Telegram's `file_size`) or the response declared a decoded one. OneDrive's
metadata `size` is no byte snapshot, so, as in the buffered helper, it only bounds the download
against `maxBytes`. The body is only readable inside the scope that opened it; closing the scope
closes the connection, read or not.

`streamGmailAttachment` is the one exception to the same requests and checks: Gmail answers its
attachment as base64url inside JSON, so it decodes `data` as the response streams (the JSON, its
base64 and the file are never whole). It sends the buffered twin's URL and headers with a larger
bound, the base64 of `maxBytes` plus `maxMetadataBytes`: every byte but `data`'s base64 counts
against `maxMetadataBytes`, where the twin bounds the whole JSON by it. The body fails with
`response_too_large` past either limit or on a `size` over `maxBytes`, and with `invalid_metadata`,
never `partial_content`, on JSON or base64 that is not Gmail's or a length other than Gmail's
`size`. A `size` read before `data` is checked before any byte and binds the decoding at once. It
declares no `contentLength` (the decoded length is known only at the end).

Without a provider size or a declared length (OneDrive, Drive exports, Todoist, Outlook, Notion,
Fortnox, Telegram without `file_size`), nothing in the SDK can tell a body that ends early but
cleanly from a whole one, in the buffered helpers as here: your port must never answer a body cut
before the response's own end (short of its `Content-Length`, or chunked without its last chunk)
as complete, but fail it with `transport_failed`.

* Every check that does not need the body runs before it opens: metadata, identity,
  `canDownload`, and the provider's size against `maxBytes`.
* The SDK counts the body on top of the host: more than `maxBytes` fails it with
  `response_too_large`, a declared length over `maxBytes` fails before reading, and a body that does
  not end at exactly the provider's `size` (or the declared length) fails with `partial_content`. With
  either, a body that completes is never a truncated file.
* Each request opens in its own child of your scope: a redirect hop, an error answer, or a check
  that fails before the body closes its connection at once, so a redirect chain holds one
  connection at a time. Only the final body stays open until your scope closes.
* Non-200 answers stay bounded bytes and are classified exactly as the buffered helpers classify
  them.
* A host whose port has no `stream` still works: the helpers fall back to `request` and answer its
  bytes as one chunk. That is still bounded by `maxBytes`, but buffered.
* For reuse caches, key on the provider's file revision in `source` (streamed, buffered and link
  results alike): Dropbox `rev`, OneDrive `cTag` (content) or `eTag` (any change), Drive
  `headRevisionId` (blobs) or `version` (any change); Todoist reports none, so key on `commentId`.
  When you need a content hash, compute it while piping the body (for example with `Stream.tap`,
  or `crypto.DigestStream` on Workers); the SDK verifies none.

Not streamed: `fortnox.get_sie_file` (an agent action whose bytes become a file through
`fileOutput`; at most 50 MiB), Gmail and the other base64 attachment reads (base64 inside a JSON
body; Gmail caps a message at 25 MB), and the small, bounded Telegram, Teams transcript and Fortnox
preview, archive and inbox reads.

## Create and update explicitly [#create-and-update-explicitly]

Host integration fragment (credentials, approval, transport and execution omitted):

```ts
import { createDropboxFile, updateDropboxFile } from '@yolk-sdk/connectors/dropbox'
import { createOneDriveFile, updateOneDriveFile } from '@yolk-sdk/connectors/microsoft'

const create = createDropboxFile(dropboxIntegration, { path: '/reports/new.pdf', bytes }, budget)
const update = updateDropboxFile(
  dropboxIntegration,
  { fileId: selectedDropboxFile.id, expectedRev: selectedDropboxFile.rev, bytes },
  budget
)
const createDrive = createOneDriveFile(
  microsoftIntegration,
  { driveId, parentItemId, name: 'new.pdf', bytes },
  budget
)
const overwriteDrive = updateOneDriveFile(
  microsoftIntegration,
  { driveId, itemId, bytes, acknowledgeOverwrite: true },
  budget
)
```

Each also takes `body: { size, stream }` (`ConnectorUploadBody`) as an alternative to `bytes`
(callers passing `bytes` are unaffected; the input types are now generic type aliases, no longer
interfaces; `addOutlookAttachment` takes it too, below; R2, Fortnox and GitHub take `bytes` only): a
stored file goes to the provider as it is read: up to the single-upload caps in one request (through
the optional `ConnectorBinaryWriteHttpClient.requestStream`, `content-length: size`, never chunked;
without it the body is collected and sent through `request`), past them in an upload session, one
part held at a time (below). The limits are checked against `size` first, the body is held to
exactly `size` (`partial_content` otherwise), and a body that fails fails the write with its own
error.

* **Dropbox:** create uses `mode: 'add'`; update uses a stable `id:` and concrete expected `rev`.
  Both send `strict_conflict: true` and `autorename: false`. Missing/deleted targets and stale
  revisions cannot silently turn an update into a create. Permission hint: `files.content.write`.
  `content_hash` is not a revision. Returned revision metadata is validated, not a verified checksum.
  Up to 150,000,000 bytes (`dropboxSingleUploadMaxBytes`) one `files/upload`; past it, up to 350 GB
  (`dropboxUploadSessionMaxBytes`), an upload session through the write port's `request`:
  `upload_session/start` with the first 8 MiB part (`dropboxUploadSessionPartBytes`), `append_v2`
  with each next part at its offset, `finish` with the last part and the same commit. A 409 on
  `finish` is `conflict`; before it, the session's own error is `upstream_failed`. Dropbox has no
  session cancellation: a session that fails is never finished (no file exists) and expires; a
  session lasts at most 7 days, so a slower upload fails midway.
* **OneDrive:** creation sends `@microsoft.graph.conflictBehavior=fail`, never the provider default
  replace. Update replaces bytes by stable ID and requires explicit `acknowledgeOverwrite: true`.
  &#x2A;*This is unconditional overwrite, not compare-and-swap.** No `If-Match` guarantee is invented
  for Graph's simple `/content` upload. A concurrent edit can be overwritten. Hosts must obtain
  informed overwrite approval, or decline the operation when atomic concurrency is required.
  Write hints use `Files.ReadWrite`, or `Files.ReadWrite.All` for `delegated_all`/`application`;
  application mode requires `driveId` before credentials are resolved. Up to 250,000,000 bytes
  (`oneDriveSingleUploadMaxBytes`) one content `PUT`; past it, up to 250 GB
  (`oneDriveUploadSessionMaxBytes`), an upload session, which needs the write port's
  `uploadSession` and `ConnectorHttpClient` (`upload_session_required` before credentials or
  network without them): `createUploadSession` (conflict behavior `fail` on create, `replace` on
  update), then sequential 10 MiB ranges (`oneDriveUploadSessionRangeBytes`) to its `uploadUrl`,
  with no Authorization. The `uploadUrl` must be on a host of `oneDriveUploadSessionHosts`
  (`*.sharepoint.com`, `api.onedrive.com`, `*.1drv.com`, `*.microsoftpersonalcontent.com`), over
  https without userinfo or a port, else `network_policy_rejected` uncontacted; only the host is
  enforced. The paths sessions are seen with (`/up/…` on `*.1drv.com`,
  `…/_api/v2.0/…/uploadSession` on SharePoint and `*.microsoftpersonalcontent.com`, `/rup…` on
  `api.onedrive.com`) are informative only, not enforced. A range's error status maps as the
  single upload's; any failure after the session exists cancels it (one best-effort `DELETE`). A
  session expires at its `expirationDateTime` when no range arrives before then (a stalled upload
  fails `not_found`).
* **R2:** `createR2Object` and `updateR2Object` accept `{ bucket, key, bytes }`; update additionally
  requires `expectedEtag`. `getR2Object` accepts `{ bucket, key, expectedEtag? }`.
  The host's `R2ObjectClient.put` must atomically enforce `condition: { kind: 'absent' }` using
  `If-None-Match: *`, or `{ kind: 'etag', etag }` using a concrete `If-Match`. Never HEAD-then-PUT.
  Preserve HTTP ETag quotes; translate representation explicitly for binding adapters. Failed
  conditional PUT (`null` from R2 bindings) is `conflict`, not success. Missing GET is `not_found`;
  conditional GET metadata without a body is `conflict`, never an empty file. The host selects
  authorized integration/bucket/key access and resolves credentials or bindings. No AWS dependency
  is bundled. ETag conditions do not distinguish every identical-content rewrite. Existing
  `R2Presigner` and `r2_storage.upload_url` are unchanged and do not inherit these conditions.

R2 uploads are single-request, memory-bounded only: larger files fail `upload_session_required`
before transport. Dropbox and OneDrive files past their single upload, and Outlook draft attachments
of 3 MiB or more (below), use upload sessions; past the session limits, or a smaller host budget,
the helpers fail `response_too_large`. No session is resumed, and these helpers do not claim atomic
conditional R2 multipart completion. No write retries occur. Transport errors, timeouts,
cancellation or an invalid success response may follow a committed write: reconcile with provider
metadata before trying again; never remove a precondition or silently switch to another write
mode.

## Attach a file to an Outlook draft [#attach-a-file-to-an-outlook-draft]

Host integration fragment (approval, transport layers and execution omitted):

```ts
import { addOutlookAttachment } from '@yolk-sdk/connectors/microsoft'

const attach = addOutlookAttachment(
  microsoftIntegration,
  { messageId: draft.id, name: 'report.pdf', contentType: 'application/pdf', bytes, mailbox },
  budget
)
// Result: { attachmentId?, name, size }. Send later with outlook.send_draft after review.
```

It also takes the file as `body: { size, stream }`, as an alternative to `bytes` (callers passing
`bytes` are unaffected; `OutlookAddAttachmentInput<E>` is now a generic type alias, no
longer an interface). The session ranges are then read from the stream a range at a time, one range
held; a file under 3 MiB is collected for its one JSON request. The body is held to exactly `size`
(`partial_content` otherwise), and a body that fails fails the call with its own error; either way
the session is cancelled.

`addOutlookAttachment` adds one file to an **existing draft** and never sends it. It uses the Outlook
write slot (`Mail.ReadWrite`; `Mail.ReadWrite.Shared` for a delegated mailbox that is not the
connected account) and the application-mode `mailbox` guard. Files under 3 MiB
(`outlookAttachmentSingleRequestMaxBytes`) use one Graph `POST .../messages/{id}/attachments`
with a `#microsoft.graph.fileAttachment` body; Graph echoes the base64 content, so the success
budget is `maxMetadataBytes` plus that base64 length. Files from 3 MiB up to 150 MiB
(`outlookAttachmentUploadSessionMaxBytes`) use `POST .../attachments/createUploadSession`, then
sequential 3,932,160-byte ranges (`outlookAttachmentUploadChunkBytes`, 12 x 320 KiB) sent with
`PUT`, `Content-Range: bytes start-end/total`, `Content-Type: application/octet-stream` and **no
Authorization header** to the pre-authenticated `uploadUrl`. Each intermediate 200 must name exactly
the next expected range, and the final range must return 201; its `Location` header supplies
`attachmentId` when parseable. A 200/201 POST or final 201 without a readable ID still succeeds, without
`attachmentId`. See Microsoft's [large attachment guide](https://learn.microsoft.com/en-us/graph/outlook-large-attachments),
including its known issue for shared or delegated mailboxes.

The helper requires `CredentialResolver` and `ConnectorHttpClient`. Both authenticated Graph POSTs
(`fileAttachment` and `createUploadSession`) go through the regular `ConnectorHttpClient` as
ASCII-only JSON string bodies with Bearer, JSON `accept`/`content-type` and
`Prefer: IdType="ImmutableId"` headers, `redirect: 'manual'` and `credentials: 'omit'`. Your HTTP
adapter must allow those Graph POSTs and a success body of `maxMetadataBytes` plus the echoed base64
content (about 4 MiB for a file just under 3 MiB). The adapter must not log, trace or persist these
request or response bodies: they carry file content and the token-bearing `uploadUrl`. Status codes
map the same way as the binary port; success bodies are bounded after the adapter returns them, so
enforce your own streaming cap. The helper never reads error bodies from these Graph POSTs, so your adapter may truncate them for
these requests (other connectors, such as Fortnox, do read error bodies); cap them without failing so
the status still maps, because an adapter failure becomes `transport_failed` without a status.

Only session ranges need the optional `ConnectorBinaryWriteHttpClient.uploadSession` method; the
helper reads that port optionally, so hosts without any binary write port can still attach files
under 3 MiB. Hosts without it fail `upload_session_required` for files of 3 MiB or more, before
credentials or network.
The `uploadUrl` embeds an auth token: the SDK only contacts `https://outlook.office.com/api/{v1.0,v2.0,gv1.0,beta}/.../AttachmentSessions('...')`
URLs (others fail `network_policy_rejected` without being contacted), never returns the URL, and
sends one best-effort `DELETE` to cancel the session after any later failure or interruption.
Failures are code/status-only `ConnectorFileTransferError`s. The draft is never sent, but a failure
after dispatch (transport error, timeout, malformed response) may still have attached the file:
list the draft's attachments before retrying. No automatic retries occur.

## Send or draft Gmail with streamed attachments [#send-or-draft-gmail-with-streamed-attachments]

A host whose outgoing Gmail message carries its stored files never holds them: host-only twins send
the message as one multipart media upload through `ConnectorBinaryWriteHttpClient` (`requestStream`
when the host has it; otherwise the body is collected and sent through `request`), its size known
before its first byte.

* `sendGmailMimeStreamed(integration, { mime: { size, stream }, threadId? })` is
  `gmail.send_message`'s twin for a MIME the host streams: the same send authority, 35 MiB cap
  (checked on `size` first), `threadId` check and outcomes.
* `composeGmailDraftStreamed`, `updateGmailDraftStreamed` and `replyGmailDraftStreamed` are the
  draft actions' twins: the action's input without `attachments`, and `GmailDraftStreamedAttachment`s
  (`{ filename, mimeType, body: { size, stream } }`) checked as the action checks its attachments
  before any request; they write the bytes the held draft writes.
* `streamedMime` builds a MIME from `StreamedMimePiece.Text` and `StreamedMimePiece.Base64` pieces
  (`streamBase64MimeLines`: base64 in 76-character CRLF lines, a chunk at a time;
  `base64MimeLinesLength` their length).

A message that is not its declared size, or that holds the upload's random boundary, is refused
before Gmail has all of it (a rejected `ConnectorError`, nothing sent or written); a body that
fails fails the call with its own error; a transport failure leaves the outcome unknown (reconcile
before another send).

## Provider retrieval details [#provider-retrieval-details]

### Drive [#drive]

`downloadGoogleDriveFile` accepts `{ fileId, resourceKey? }`; `exportGoogleDriveFile` additionally
requires `mimeType`. Metadata is bounded and checked before content. Caller-specific
`capabilities.canDownload` must be true; role restriction flags alone do not identify the caller's
role. Google still enforces authorization when content is requested. Shared-drive downloads use
`supportsAllDrives=true`; resource keys are validated and forwarded in the resource-key header.
No abuse acknowledgement is sent. Folders, shortcuts, unsupported native files and incompatible
exports fail; there is no shortcut chasing or Vids long-running download implementation.

Content consent defaults to `GoogleDriveFileOAuthCredentialSlot` (`drive.file`, app-created or
explicitly selected/shared files). Only trusted hosts can select `contentAccess: 'readonly'` in
`GoogleDriveDownloadBudget`, requesting `GoogleDriveReadonlyOAuthCredentialSlot` (`drive.readonly`,
broad restricted scope). Metadata-only consent is insufficient. Hosts own Picker/per-file access,
consent UX, OAuth verification and restricted-scope compliance. Slot hints are not access control.

Supported exports: Docs PDF, DOCX, ODT, RTF, plain text, HTML, ZIP, EPUB and Markdown; Sheets XLSX,
ODS, PDF, CSV, TSV and ZIP; Slides PPTX, ODP, PDF and plain text; Drawings PDF, JPEG, PNG and SVG;
Apps Script JSON. CSV/TSV export the first sheet only. Exports are generated representations, not
original blob snapshots. See Google's [export formats](https://developers.google.com/workspace/drive/api/guides/ref-export-formats).

### Fortnox and Notion [#fortnox-and-notion]

Fortnox preview input is `{ documentNumber }`; archive input is `{ fileId }`.
`documentNumber` uses `FortnoxDocumentNumber` from `@yolk-sdk/connectors/fortnox`: decode external
strings with that schema, or use `.make` for trusted values. `fileId` remains a plain string.
Preview uses `/3/invoices/{DocumentNumber}/preview`, &#x2A;*not `/print`**, and does not set `Sent` true.
The preview request sends no `Accept` header and success is verified by `%PDF-` magic bytes,
not the response content type. Archive retrieval uses `/3/archive/{id}` with IDs from discovery, not supplier external-URL
connections. `fortnox.list_supplier_invoice_files` takes `{ givenNumber, page?, limit? }` and returns
`{ files, pagination }`; the filter is the internal GivenNumber, not the supplier InvoiceNumber.
`FortnoxConnectFileOAuthCredentialSlot` requests `connectfile`; archive uses
`FortnoxArchiveOAuthCredentialSlot` (`archive`); preview uses the invoice slot (`invoice`). All
Fortnox scopes grant **read and write at the provider**. File discovery/download helpers remain
separate from the customer/invoice action writes.
These two new scopes are opt-in, not automatically added to the existing five-scope combined slot.
Archive response modeling and generic list pagination in Fortnox OpenAPI are imperfect; validate
sanitized provider responses before production, never infer a final page from missing metadata.

`downloadFortnoxOfferPreview` takes `{ documentNumber }` and reads `/3/offers/{DocumentNumber}/preview`
with the offer slot (`offer`); like the invoice preview it verifies PDF magic bytes and does not mark
the offer Sent.

Inbox helpers use `FortnoxInboxOAuthCredentialSlot` (`inbox`). `downloadFortnoxInboxFile` takes
`{ fileId }` from `fortnox.get_inbox_folder` and reads `/3/inbox/{Id}`; it rejects `root` and the
static folder IDs (`fortnoxInboxStaticFolderIds`), since a folder ID answers with folder JSON.
`uploadFortnoxInboxFile` takes `{ folderId, fileName, contentType?, bytes }` and sends one
`multipart/form-data` POST (field `file`) to `/3/inbox?folderid=…` through
`ConnectorBinaryWriteHttpClient`. It validates the file name, picks a boundary absent from the bytes,
never retries, and returns the uploaded file metadata, failing with `invalid_metadata` when the
reported `Size` differs from the bytes sent. Fortnox documents no upload limit; the helper caps
uploads at `fortnoxInboxUploadMaxBytes` (50 MiB) and fails larger files with
`upload_session_required`. Upload query key and form field follow Fortnox's archived docs and
official SDK; they are not yet observed live.

`uploadFortnoxArchiveFile` takes `{ folderId?, fileName, contentType?, bytes }` and sends the same
single, never-retried multipart POST to `/3/archive` (`?folderid=…` when a folder is given; the
archive root otherwise) with `FortnoxArchiveOAuthCredentialSlot` (`archive`). It returns
`FortnoxArchiveFile` (`Id`, `Name`, `Path`, `Size`, `Comments`) and caps uploads at
`fortnoxArchiveUploadMaxBytes` (50 MiB). The returned `Id` is the `FileId` that
`fortnox.create_voucher_file_connection` attaches to a voucher; see
[Bookkeeping](./fortnox#bookkeeping). Neither the archive upload nor the voucher file connection is
observed live yet.

Notion input is a provider `{ type: 'file', file: { url, expiry_time? } }` or
`{ type: 'external', external: { url } }` object from existing page/property/block reads. Pass a fourth
argument `NotionFileDownloadPolicy` with `allowHostedUrl(url)`; external downloads additionally
require `allowExternalUrl(url)`. Supply policy from trusted host code, not model-controlled URL
approval. No Notion credentials are resolved or forwarded. URLs are temporary: reread the owning
page/block/property after expiry. `file_upload.id` is an upload reference, not downloadable content.

### Mail, Telegram and Todoist [#mail-telegram-and-todoist]

Gmail and Outlook inputs are `{ messageId, attachmentId }`; Outlook optionally accepts `mailbox`.
Gmail validates the base64url alphabet, padding, decoded byte count and `size`, including empty
files; unused pad bits are accepted.
Inline Gmail parts without `attachmentId` remain outside this focused helper. Outlook checks the
file discriminator before fetching `/$value`; item MIME/reference attachments are rejected.
Graph's attachment metadata size is not treated as exact raw-byte length. Existing shared-mailbox,
application-mailbox and immutable-ID guards remain in effect. In delegated mode, an explicit
`mailbox` also triggers a scope-free `microsoft.oauth` identity lookup before the enforcing read slot;
matching the connected identity keeps ordinary read scopes. Identity-resolution failures return
`credential_failed`, not `invalid_input`. See [Microsoft mailbox permissions](../integrations/connectors#microsoft).

`downloadEmailAttachment` takes `{ messageId, attachmentId, folder? }` and uses the incoming
connection and username/password slot. Adapters can add optional `EmailClient.getAttachmentBytes`
without changing old methods. Return actual raw bytes, matching IDs and byteLength, optionally
filename/contentType; never Buffer→base64→Buffer. Enforce MIME decoded-byte limits during streaming,
release streams and use IMAP reads that preserve flags. POP3 rejects folders and may require
fetching the whole message; hosts must also bound that larger fetch.

`streamEmailAttachment` is its stream twin over the optional `EmailClient.streamAttachmentBytes`
(not part of the HTTP-binary stream family: the email port, not `ConnectorBinaryHttpClient`). Same
input, slot and matching-ID checks; it answers `{ body, contentLength?, messageId, attachmentId,
filename?, contentType? }` (`ConnectorFileStream`). Without `streamAttachmentBytes` it fails
`not_downloadable`. The host reads the attachment's decoded bytes as the body (IMAP `BODY.PEEK`,
read flags preserved) inside the scope that opened it; closing the scope releases the message stream
and the connection. The SDK counts the body again against `maxBytes` (`response_too_large`, never a
short success), holds it to a declared `contentLength` (`partial_content`), and fails
`invalid_metadata` before the body on a mismatched message/attachment or a `contentLength` that is
not a byte count. Host errors carry codes only. POP3 still rejects folders and may fetch the whole
UIDL-addressed message, which the host bounds.

Telegram input is `{ fileId }`. Only `api.telegram.org` hosted Bot API is supported. `getFile`
resolves a validated relative path; local Bot API absolute filesystem paths are rejected. Download
URLs contain the bot token and must never enter logs. Returned source contains file IDs only:
`getFile` does not preserve original filename/MIME. Links last at least one hour; call `getFile`
again after expiry. No `getUpdates` calls or update acknowledgements are performed here.

Todoist discovery uses `todoist.list_comments` with exactly one `taskId` or `projectId`, optional
`cursor`/`limit`, returning `comments` (Chunk) and `nextCursor`; metadata omits attachment URLs.
`downloadTodoistAttachment` takes `{ commentId }`, rereads bounded metadata, authenticates only the
initial `files.todoist.com` download, and treats `todoist.b-cdn.net` and
`d1ysz50cxb9zwl.cloudfront.net` as unauthenticated CDNs. At most five validated HTTPS redirects are
followed; no authorization is reapplied, even on same-origin redirects. Unknown hosts fail closed.

## Reuse MCP file capabilities [#reuse-mcp-file-capabilities]

Afloat at `https://useafloat.com/mcp` exposes `get-invoice-pdf`, `get-quote-pdf`,
`get-receipt-download`, `get-logo-download` and `get-tax-return-download`. These return one-hour
same-origin opaque URL grants, as `structuredContent: { url, expiresAt }`. `create-receipt-upload`
returns an upload intent, URL, expiry and required headers; `complete-receipt-upload` attaches or
replaces the receipt atomically. Corresponding logo operations exist. Receipt upload inputs allow
JPEG/PNG/WebP/GIF/PDF, length 1–2,147,483,647 and an optional SHA-256 checksum. The published
schemas of these tools, and their provenance, are on the
[Afloat MCP conformance](./afloat#conformance-cases) page. Use discovered schemas and enforce
smaller host budgets; do not duplicate these operations as static SDK wrappers.

Figma discovery confirmed `download_assets` for node renders/source images/SVG temporary URLs,
`upload_assets` (including SVG, 10 MB per asset), `use_figma` for edits and `create_new_file` for
creation. Deployed node-selection parameters differ from published documentation; dynamic
discovery owns the exact contract. These are asset/design operations, not whole `.fig` downloads.
Authorize write-capable MCP tools as writes; do not assume `use_figma` is read-only. Hosts consume
structured/multipart results and download/upload grants through a bounded private file pipeline,
never expose credentials or signed grants in ordinary model text. No live provider writes were used
to validate these capabilities.

## Host transport contract and failures [#host-transport-contract-and-failures]

The root exports `ConnectorBinaryWriteHttpClient` separately from the GET-only
`ConnectorBinaryHttpClient`. Its optional `stream` method takes the same request as `request` and
keeps every guarantee: one hop, no redirects or ambient credentials, public DNS and socket IP policy
on every hop, and `maxBytes` enforced while streaming, so an oversize body fails with
`response_too_large` instead of ending early. It runs in a `Scope` and answers
`ConnectorBinaryHttpStreamResponse.Stream({ status: 200, headers, contentLength?, body })` for HTTP
200 (`contentLength` is the decoded length; omit it for a `Content-Encoding` other than `identity`,
whose `Content-Length` `fetch` keeps compressed) or
`ConnectorBinaryHttpStreamResponse.Bytes({ status, headers, bytes, bodyComplete })` for any other
status, bounded by `maxErrorBodyBytes`. Close the connection when the scope closes, whether or not the body was read. Existing adapters without
`stream` keep compiling. Write requests carry raw bytes, `maxUploadBytes`, successful metadata
`maxBytes`, `maxErrorBodyBytes`, `successStatuses: [200, 201]`, manual redirects and omitted ambient
credentials. Reads accept HTTP 200 only. The optional `uploadSession` method takes a
`ConnectorBinaryUploadSessionRequest` (`PUT` range or `DELETE` cancellation, success `[200, 201]` or
`[204]`) for a provider-issued pre-authenticated URL. Implement it only with an origin and path
allowlist (Outlook:
`https://outlook.office.com/api/{v1.0,v2.0,gv1.0,beta}/.../AttachmentSessions(...)`), the URL sent
unchanged, no Authorization or ambient credentials, no redirects or retries, no URL
logging/tracing/persistence, and response headers (including `Location`) returned intact. Existing
adapters without it keep compiling. The optional `requestStream` takes a
`ConnectorBinaryWriteStreamRequest` (the write request with `body: { size, stream }` for `bytes`):
declare `content-length: size`, send the body as it arrives, abort on a body of another length or
one that fails (failing with that body's error). `addOutlookAttachment` uses this port only for
`uploadSession`;
its authenticated Graph JSON POSTs use `ConnectorHttpClient`. Host adapters must enforce limits
while consuming streams, including decompression, cap headers independently, close/cancel I/O,
verify TLS, implement timeouts/cancellation, and enforce public DNS **and socket IP** policy on
every request/hop. Never use cookie jars, automatic redirects/retries, ambient auth or
URL/header/body logging. R2 and email adapters have equivalent streaming, authorization and
cancellation obligations.

SDK URL syntax screens and post-buffer checks are defense in depth, **not proof of network
isolation or pre-buffer limits**. New transfers reject redirects except the bounded Todoist flow;
existing OneDrive download retains its own unauthenticated redirect handling. Provider access,
licensing, host materialization/storage/retention, malware scanning and format readers are not
implemented here. No download metadata establishes a consistent provider snapshot.

New helpers fail with root `ConnectorFileTransferError` containing only `code` plus an optional HTTP `status` number: `invalid_input`,
`credential_failed`, `transport_failed`, `network_policy_rejected`, `response_too_large`,
`upload_session_required`, `unauthorized`, `forbidden`, `not_found`, `conflict`, `rate_limited`,
`upstream_failed`, `invalid_metadata`, `not_downloadable`, `unexpected_redirect`, or `partial_content`.
They never carry signed URLs, raw upstream errors or wrapped causes; only the link helpers return a
provider link, and only as `Redacted`. Hosts must avoid adding
those details in their own errors/telemetry. Existing Dropbox/OneDrive downloads keep their original
error types. Deterministic fake-port tests prove request orchestration only, not live provider or
host network enforcement.


---

# Read and write Fortnox records

URL: /docs/connectors/fortnox

Read and write Fortnox records, prices, payments, offers, inbox, settings, and bookkeeping with host-owned OAuth.



Use `@yolk-sdk/connectors/fortnox` to read Fortnox records directly or expose them as agent tools.
The connector exposes 102 actions: 51 `read`, 32 `write`, and 19 `destructive`. It sends GET, POST,
PUT, and DELETE requests to `https://api.fortnox.se/3`.

`destructive` actions cannot be undone through the Fortnox API: deletes, payment bookkeeping,
creating a voucher (Fortnox books it at once), offer conversion, cancellation, emailing, and marking
an offer sent. Gate them with host approval. Customer invoices still have no send, book, cancel, or
credit action; those remain host capabilities.

Host-only invoice and offer preview PDFs, archive and inbox downloads, archive and inbox uploads, and
supplier-file discovery are described in [Transfer connector files](./files#fortnox-and-notion).
Previews do not mark a document Sent. `fortnox.get_sie_file` is the one action that returns file
bytes; see [Bookkeeping](#bookkeeping).

## Connect a host credential [#connect-a-host-credential]

Install matching canary versions:

```bash
pnpm add @yolk-sdk/connectors@canary @yolk-sdk/agent@canary effect@4.2.0
```

Wiring fragment (host layers and Effect execution omitted):

```ts
import { makeCredentialBinding, makeIntegration } from '@yolk-sdk/connectors'
import { FortnoxConnector, FortnoxOAuthCredentialSlot } from '@yolk-sdk/connectors/fortnox'

const integration = makeIntegration({
  connectorId: 'fortnox',
  credentialBindings: [
    makeCredentialBinding({
      slotId: FortnoxOAuthCredentialSlot.id,
      credentialRef: 'host-fortnox-credential'
    })
  ]
})

const program = FortnoxConnector.invoke({
  integration,
  action: 'fortnox.list_invoices',
  input: { filter: 'unpaid', limit: 25 }
})
```

Provide `CredentialResolver` and `ConnectorHttpClient` Effect layers. The resolver must return an
`OAuthCredential` with `provider: 'fortnox'` and a current `accessToken`. Resolve or refresh the
credential before returning it; the connector does not refresh tokens or enforce their expiry.
Integration config needs no keys and must not contain tokens or client secrets.

The HTTP adapter must preserve `Authorization: Bearer …` and `Accept: application/json`.
When a request carries a JSON body it must also preserve `Content-Type: application/json` and the
body. Lifecycle PUTs (`bookkeep`, `createorder`, `createinvoice`, `cancel`, `externalprint`) and all
DELETEs are body-less. `fortnox.email_offer` is a side-effecting GET: never retry it or follow its
redirects. Never retry POSTs either: a retried `fortnox.create_voucher` books a second voucher.
Hosts own network policy, response-size limits, redirect safety, and avoiding credential/body logs.

## Choose consent scopes [#choose-consent-scopes]

**Fortnox has no read-only OAuth scopes.** Each resource scope grants read and write access at the
provider. Explain this distinction during consent and retain host authorization checks. Fortnox also
requires a company license for each resource. Action access metadata (`read`, `write`,
`destructive`) is what hosts gate on; it does not narrow the token.

All slots bind through `fortnox.oauth`:

| Slot                                           | Required scope       | Developer Portal name | Fortnox license               |
| ---------------------------------------------- | -------------------- | --------------------- | ----------------------------- |
| `FortnoxCompanyInformationOAuthCredentialSlot` | `companyinformation` | Företagsinformation   | Any                           |
| `FortnoxCustomerOAuthCredentialSlot`           | `customer`           | Kund                  | Kundfaktura or Order          |
| `FortnoxInvoiceOAuthCredentialSlot`            | `invoice`            | Faktura               | Order or Kundfaktura          |
| `FortnoxSupplierOAuthCredentialSlot`           | `supplier`           | Leverantör            | Bokföring                     |
| `FortnoxSupplierInvoiceOAuthCredentialSlot`    | `supplierinvoice`    | Leverantörsfaktura    | Bokföring                     |
| `FortnoxConnectFileOAuthCredentialSlot`        | `connectfile`        | Koppla filer          | Bokföring, Anläggning, Arkiv  |
| `FortnoxArchiveOAuthCredentialSlot`            | `archive`            | Arkivplats            | Any                           |
| `FortnoxArticleOAuthCredentialSlot`            | `article`            | Artikel               | Order or Kundfaktura          |
| `FortnoxPriceOAuthCredentialSlot`              | `price`              | Pris                  | Order or Kundfaktura          |
| `FortnoxCostCenterOAuthCredentialSlot`         | `costcenter`         | Kostnadsställe        | Bokföring, Order, Kundfaktura |
| `FortnoxPaymentOAuthCredentialSlot`            | `payment`            | Betalningar           | Bokföring, Order, Kundfaktura |
| `FortnoxOfferOAuthCredentialSlot`              | `offer`              | Offert                | Order                         |
| `FortnoxPrintOAuthCredentialSlot`              | `print`              | Utskrift              | Order or Kundfaktura          |
| `FortnoxInboxOAuthCredentialSlot`              | `inbox`              | Inbox                 | Any                           |
| `FortnoxSettingsOAuthCredentialSlot`           | `settings`           | Inställningar         | Any                           |
| `FortnoxProfileOAuthCredentialSlot`            | `profile`            | Profil                | Any                           |
| `FortnoxBookkeepingOAuthCredentialSlot`        | `bookkeeping`        | Bokföring             | Bokföring or Kundfaktura      |

`print` covers only print templates; printing, previewing, or emailing a document uses the
document's own scope (`invoice`, `offer`). Fortnox also lists Company Logo (Företagslogga) and a
sales API (Försäljnings-API) as Developer Portal scopes, but documents no endpoints for them, so the
connector has no actions for either.

`FortnoxOAuthCredentialSlot` is the generic binding without scope hints.
`FortnoxCombinedOAuthCredentialSlot` declares the original five record scopes only (not the file,
article, price, cost-center, payment, offer, print, inbox, settings, profile, or bookkeeping scopes); use it only
when the host needs exactly those resources. Action-scoped slots supply consent hints to the
resolver, not a token store or permission checker.

Host OAuth implementation:

* Use `fortnoxOAuthAuthorizeUrl` (`https://apps.fortnox.se/oauth-v1/auth`) with `response_type=code`,
  a CSRF-protected `state`, the registered redirect URI, and space-delimited scopes. Request
  `access_type=offline` when refresh is needed. Service-account selection is host policy.
* Exchange the code at `fortnoxOAuthTokenUrl` (`https://apps.fortnox.se/oauth-v1/token`) with HTTP
  Basic client authentication and a form-urlencoded body.
* Store and refresh tokens server-side. Fortnox rotates refresh tokens; serialize refreshes and
  persist the replacement safely. Hosts own revocation, reauthorization, and credential identity.

`fortnox.list_supplier_invoice_files` takes `{ givenNumber, page?, limit? }`, returns
`{ files, pagination }`, and uses `connectfile` consent. Its filter is internal GivenNumber, not
supplier InvoiceNumber. The new file scopes grant both reads and writes like other Fortnox scopes.

## Actions and outputs [#actions-and-outputs]

| Action                                | Access | Input                                  | Success value                      |
| ------------------------------------- | ------ | -------------------------------------- | ---------------------------------- |
| `fortnox.get_company_information`     | read   | `{}`                                   | `FortnoxCompanyInformation`        |
| `fortnox.list_customers`              | read   | `FortnoxListCustomersInput`            | `{ customers, pagination }`        |
| `fortnox.get_customer`                | read   | `{ customerNumber }`                   | `FortnoxCustomer`                  |
| `fortnox.create_customer`             | write  | `FortnoxCreateCustomerInput`           | `FortnoxCustomer`                  |
| `fortnox.update_customer`             | write  | `FortnoxUpdateCustomerInput`           | `FortnoxCustomer`                  |
| `fortnox.list_invoices`               | read   | `FortnoxListInvoicesInput`             | `{ invoices, pagination }`         |
| `fortnox.get_invoice`                 | read   | `{ documentNumber }`                   | `FortnoxInvoice`                   |
| `fortnox.create_invoice`              | write  | `FortnoxCreateInvoiceInput`            | `FortnoxInvoice`                   |
| `fortnox.update_invoice`              | write  | `FortnoxUpdateInvoiceInput`            | `FortnoxInvoice`                   |
| `fortnox.list_suppliers`              | read   | `FortnoxListSuppliersInput`            | `{ suppliers, pagination }`        |
| `fortnox.get_supplier`                | read   | `{ supplierNumber }`                   | `FortnoxSupplier`                  |
| `fortnox.list_supplier_invoices`      | read   | `FortnoxListSupplierInvoicesInput`     | `{ supplierInvoices, pagination }` |
| `fortnox.get_supplier_invoice`        | read   | `{ givenNumber }`                      | `FortnoxSupplierInvoice`           |
| `fortnox.list_supplier_invoice_files` | read   | `FortnoxListSupplierInvoiceFilesInput` | `{ files, pagination }`            |

### Master data, payments, offers, inbox, settings, and profile [#master-data-payments-offers-inbox-settings-and-profile]

Get and delete inputs use camelCase identifiers (`{ articleNumber }`, `{ code }`,
`{ paymentNumber }`, `{ documentNumber }`, `{ itemId }`, `{ labelId }`). Create and update inputs
use Fortnox field spelling, carry the identifier, and bind it into the URL instead of the body.
Deletes return `{ <identifier>, deleted: true }` without decoding Fortnox's empty answer.

| Resource (scope)                      | Actions                                                                                                                                                                                        |
| ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Articles (`article`)                  | read: `list_articles`, `get_article`; write: `create_article`, `update_article`; destructive: `delete_article`                                                                                 |
| Price lists (`price`)                 | read: `list_price_lists`, `get_price_list`; write: `create_price_list`, `update_price_list`                                                                                                    |
| Prices (`price`)                      | read: `list_prices`, `get_price`; write: `create_price`, `update_price`; destructive: `delete_price`                                                                                           |
| Cost centers (`costcenter`)           | read: `list_cost_centers`, `get_cost_center`; write: `create_cost_center`, `update_cost_center`; destructive: `delete_cost_center`                                                             |
| Invoice payments (`payment`)          | read: `list_invoice_payments`, `get_invoice_payment`; write: `create_invoice_payment`, `update_invoice_payment`; destructive: `delete_invoice_payment`, `bookkeep_invoice_payment`             |
| Supplier invoice payments (`payment`) | read: `list_supplier_invoice_payments`, `get_supplier_invoice_payment`; write: `create_…`, `update_…`; destructive: `delete_supplier_invoice_payment`, `bookkeep_supplier_invoice_payment`     |
| Offers (`offer`)                      | read: `list_offers`, `get_offer`; write: `create_offer`, `update_offer`; destructive: `create_order_from_offer`, `create_invoice_from_offer`, `cancel_offer`, `email_offer`, `mark_offer_sent` |
| Print templates (`print`)             | read: `list_print_templates` (`type`: `invoice`, `offer`, or `order`; not paginated)                                                                                                           |
| Inbox (`inbox`)                       | read: `get_inbox_folder` (`{ folderId? }`, root when omitted); destructive: `delete_inbox_item`                                                                                                |
| Company settings (`settings`)         | read: `get_company_settings`, `get_locked_period`                                                                                                                                              |
| Predefined accounts (`settings`)      | read: `list_predefined_accounts`, `get_predefined_account`; write: `update_predefined_account`                                                                                                 |
| Labels (`settings`)                   | read: `list_labels`; write: `create_label`, `update_label`; destructive: `delete_label`                                                                                                        |
| Modes of payment (`settings`)         | read: `list_modes_of_payment`, `get_mode_of_payment`; write: `create_…`, `update_…`; destructive: `delete_mode_of_payment`                                                                     |
| Terms of payment (`settings`)         | read: `list_terms_of_payment`, `get_terms_of_payment`; write: `create_…`, `update_…`; destructive: `delete_terms_of_payment`                                                                   |
| Terms of delivery (`settings`)        | read: `list_terms_of_delivery`, `get_terms_of_delivery`; write: `create_…`, `update_…` (Fortnox has no delete)                                                                                 |
| Ways of delivery (`settings`)         | read: `list_ways_of_delivery`, `get_way_of_delivery`; write: `create_…`, `update_…`; destructive: `delete_way_of_delivery`                                                                     |
| Units (`settings`)                    | read: `list_units`, `get_unit`; write: `create_unit`, `update_unit`; destructive: `delete_unit`                                                                                                |
| Profile (`profile`)                   | read: `get_profile` (`GET /3/me`: the user behind the token)                                                                                                                                   |

All action IDs carry the `fortnox.` prefix. Notes per resource:

* **Articles.** `ArticleNumber` is assigned by Fortnox when omitted and cannot change later.
  `SalesPrice` is read-only (it is the price in the default price list); set prices through the
  price actions. Update changes only the sent fields. Delete is permanent.
* **Prices.** A price is identified by price list, article number, and `FromQuantity` (0 for the
  base price); all three form its URL path. The default price list is usually `A`. Fortnox
  documents no price-list delete. `list_prices` lists one article's prices in one price list.
* **Cost centers.** `Code` is writable only on create. Prefer `Active: false` over deleting.
* **Payments.** Created payments are normally unbooked; check `Booked` in the response.
  `AmountCurrency` is required when the invoice currency is not SEK. A supplier invoice payment's
  `InvoiceNumber` is the supplier invoice **GivenNumber** (`FortnoxGivenNumber`), not the supplier's
  own invoice number. Bookkeeping posts a voucher and has no API undo.
* **Offers.** Row updates follow the invoice rules below (rows replace the list; `RowId` matches
  rows and is regenerated). `create_order_from_offer` needs the Order license;
  `create_invoice_from_offer` creates a customer invoice. Both return the offer number and the new
  order or invoice number (null if Fortnox does not report it), accepting either the documented
  `{ Offer }` answer or the new document's own `{ Order }`/`{ Invoice }` envelope; do not retry an ambiguous
  conversion, read the offer instead. `email_offer` sends to the offer's stored
  `EmailInformation` recipient through a GET (the only method Fortnox offers); host HTTP adapters
  must not retry it or follow redirects. `mark_offer_sent` sets `Sent` without producing a document. There
  is no print action: `/print` returns bytes and marks the offer Sent; use the host preview plus
  `mark_offer_sent`.
* **Inbox.** Fortnox has nine static root folders (`inbox_s` supplier invoices, `inbox_v`
  vouchers, `inbox_kf` customer invoices, and others). `get_inbox_folder` returns folder metadata;
  a file id returns bytes, so use the host download helper. Deleting a subfolder deletes everything
  in it; `delete_inbox_item` refuses `root` and the static folders.
* **Settings.** Company settings and the locked period are read-only through the API.
  `update_predefined_account` changes the account Fortnox books with by default. Deleting a label
  removes it from every document that uses it. Labels and predefined accounts are not paginated.
* **Not covered.** Article URL connections, price-list deletion, `?path=` inbox addressing,
  Email Senders, Predefined Voucher Series, Account Charts, voucher series writes, account writes,
  voucher external URL connections, Company Logo, and the sales API (scope or endpoint not
  confirmed, or not needed yet). Within the original scopes, customer-invoice send, book, cancel,
  and credit, customer deletion, supplier and supplier-invoice writes, and file-connection writes
  other than voucher file connections are also not connector actions yet.

These additions follow Fortnox's current API reference and archived resource pages; none has been
observed against a live company yet. The
[Fortnox emulator](../api-reference/emulators#fortnox-emulator) serves their read endpoints
(including the offer preview and inbox file bytes) with unverified, synthetic shapes named after the
fields these actions read, which the read [conformance cases](#conformance-cases) cover; their
writes, and side-effecting reads such as `email_offer`, are not emulated and fail closed with a 404.

### Bookkeeping [#bookkeeping]

Every bookkeeping action needs the `bookkeeping` scope, except the voucher file connections, which
need `connectfile`, and uploads to the archive, which need `archive` (Fortnox
[scopes guide](https://www.fortnox.se/developer/guides-and-good-to-know/scopes)).

| Action                                   | Access      | Input                                                                                                 | Success value                               |
| ---------------------------------------- | ----------- | ----------------------------------------------------------------------------------------------------- | ------------------------------------------- |
| `fortnox.list_financial_years`           | read        | `{ date?, page?, limit? }`                                                                            | `{ financialYears, pagination }`            |
| `fortnox.get_financial_year`             | read        | exactly one of `{ id }` or `{ date }`                                                                 | `FortnoxFinancialYear`                      |
| `fortnox.list_accounts`                  | read        | `{ financialYearId?, page?, limit?, lastModified? }`                                                  | `{ accounts, pagination }`                  |
| `fortnox.get_account`                    | read        | `{ accountNumber, financialYearId? }`                                                                 | `FortnoxAccount`                            |
| `fortnox.list_voucher_series`            | read        | `{ financialYearId?, page?, limit?, lastModified? }`                                                  | `{ voucherSeries, pagination }`             |
| `fortnox.list_vouchers`                  | read        | `{ financialYearId?, voucherSeries?, fromDate?, toDate?, costCenter?, page?, limit?, lastModified? }` | `{ vouchers, pagination }`                  |
| `fortnox.get_voucher`                    | read        | `{ voucherSeries, voucherNumber, financialYearId }`                                                   | `FortnoxVoucher` with `VoucherRows`         |
| `fortnox.create_voucher`                 | destructive | `FortnoxCreateVoucherInput`                                                                           | `FortnoxVoucher`                            |
| `fortnox.list_voucher_file_connections`  | read        | `{ voucherSeries, voucherNumber, financialYearId }`                                                   | `{ connections }`                           |
| `fortnox.create_voucher_file_connection` | write       | `{ FileId, VoucherSeries, VoucherNumber, VoucherYear }`                                               | `FortnoxVoucherFileConnection`              |
| `fortnox.get_sie_file`                   | read        | `{ sieType: 1 \| 2 \| 3 \| 4, financialYearId }`                                                      | `FortnoxGetSieFileOutput` (file for agents) |

* **Financial years.** `financialYearId` is a financial year's `Id`; it is the `financialyear`
  query Fortnox uses to select the year (accounts, voucher series, and vouchers are per year).
  Omitted, Fortnox uses the current financial year. `get_financial_year` by `date` lists
  `financialyears?date=…` and answers `fortnox_not_found` when no year contains the date.
* **Accounts.** `BalanceBroughtForward` is the opening balance (ingående balans) and
  `BalanceCarriedForward` the closing balance (utgående balans) in the selected year. The accounts
  endpoint has no per-period balances: SIE type 2 holds monthly balances, type 3 adds cost center
  and project balances.
* **Vouchers.** A voucher is unique by `VoucherSeries`, `VoucherNumber`, and `Year` (the financial
  year Id): numbers restart every year. `costCenter` is Fortnox's substring search. List rows
  usually leave out `VoucherRows`; `get_voucher` returns them. A row's `Description` is the
  account name Fortnox sets; `TransactionInformation` is the row text. `list_vouchers` with
  `voucherSeries` uses `/vouchers/sublist/{VoucherSeries}`.
* **Creating a voucher books it.** The Fortnox API documents no endpoint to delete or change a
  voucher (its licence table names a Delete Voucher right, with no documented endpoint), so
  `create_voucher` is `destructive`: a mistake needs a new correcting voucher. The input is closed
  (unknown keys fail at every depth) and is checked before any request: at least two rows, each
  with an `Account`, exactly one positive `Debit` or `Credit` that is exactly a two-decimal amount,
  optional `TransactionInformation` (at most 100 characters), `CostCenter`, and `Project`; total
  debit equals total credit, summed exactly in whole öre. An answer that names another series or
  financial year fails with `fortnox_voucher_mismatch`: that voucher is booked, so never create it
  again. The `TransactionDate` must lie in the financial year and after any locked period; Fortnox
  enforces that, and active accounts and existing cost centers and projects. The request is sent
  once and never retried: after a transport failure or an unreadable answer the voucher may exist,
  so list vouchers before trying again. Series codes compare case-insensitively.
* **Attaching files.** A voucher file connection links an archive file to a voucher. Upload the file
  with the host-only `uploadFortnoxArchiveFile` (or take an inbox file's `ArchiveFileId` from
  `get_inbox_folder`), then call `create_voucher_file_connection` with its id. Which id forms
  Fortnox accepts is not verified against a live company. The create sends `VoucherYear` in the
  body (OpenAPI) and as the `financialyear` query (the archived page marks it read-only and selects
  the year in the URL with `financialyeardate`), and fails with `fortnox_voucher_mismatch` unless
  the answer names the same file, series, number, and year. The parameters guide allows one
  resource-specific filter at a time and matches substrings, so `list_voucher_file_connections`
  sends `vouchernumber` with the global `financialyear`, reads every page (at most ten of 500,
  `MetaInformation` required), and returns only the requested voucher's connections; a matching
  connection without `VoucherYear` fails closed. Neither request shape is verified live.
* **SIE files.** `get_sie_file` downloads `GET /3/sie/{type}?financialyear={id}` through the host
  `ConnectorBinaryHttpClient` (the string HTTP port cannot carry the bytes) and fails with
  `validation_failed` when the host provides none. The file is IBM437 (code page 437) text, as the
  [SIE format](https://sie.se/format/) requires, and must start with `#FLAGGA`. As an agent tool it
  returns `{ value, files }`: `value` is `FortnoxSieFile` (`sieType`, `financialYearId`, `fileName`,
  `mimeType: 'text/plain'`, `encoding: 'IBM437'`, `byteLength`) and the bytes become a file
  ([file claim check](../integrations/files)); invoked directly it returns them as `contentBase64`.
  Files over `fortnoxSieFileMaxBytes` (50 MiB) fail with `fortnox_response_too_large`. The stored
  file is `text/plain` (file MIME types carry no charset): hosts and scripts that read it as text
  must decode IBM437, not UTF-8.
* **Wire forms.** The archived examples send voucher and account `Project` as the number `0`,
  financial year lists name the chart type `accountCharts`, and voucher file connections send
  `VoucherNumber` as a string. These decode to the public string and integer types.

None of the bookkeeping endpoints has been observed against a live company yet. The
[Fortnox emulator](../api-reference/emulators#fortnox-emulator) serves their reads with unverified,
synthetic shapes, which the bookkeeping [conformance cases](#conformance-cases) cover; the voucher
and voucher file connection creates and the archive upload are not emulated.

Create customer inputs require `Name`; Fortnox assigns `CustomerNumber`. Create invoice inputs
require `CustomerNumber`; Fortnox assigns `DocumentNumber`. Update inputs carry the provider
identifier (`CustomerNumber` or `DocumentNumber`) and omit it from the request body because it is
bound into the URL. Invoice write inputs use `InvoiceRows` as JSON arrays; returned invoice rows are
runtime `Chunk` values. Writes do not send or book invoices and are subject to host authorization.
The connector forwards accepted write fields unchanged; it does not inject defaults or rewrite
values. Invoice write inputs are not closed: when `execute` decodes input, unknown or
provider-managed invoice keys (such as `Booked` or `VoucherNumber`) are dropped before the request.
Agent tools from `makeConnectorToolModule` reject those keys instead, with a model-visible
validation error, so a model never believes it booked or sent an invoice.
`executeTyped` trusts an existing invoice input class instance and does not re-check its keys.
`InvoiceRows` are closed when decoded or made, because dropping a row key (such as
`PriceExcludingVAT`) would send a row without its price: `execute` and agent tools fail validation, and
`FortnoxCreateInvoiceInput.make` / `FortnoxUpdateInvoiceInput.make` throw on an unknown row key.
`FortnoxInvoiceRowInput` is a closed schema, not a class: build rows as plain objects.

### Fortnox write semantics [#fortnox-write-semantics]

These notes describe Fortnox behavior and connector validation. The action descriptions that agents
see repeat the Fortnox behavior:

* **Customer contact fields.** Customer write inputs omit `Country` and `Phone`. Fortnox derives the
  read-only `Country` from `CountryCode`, and the Customer resource has no `Phone` field; use
  `Phone1`/`Phone2`. `Phone` appears only in list rows. The `fortnox.create_customer` and
  `fortnox.update_customer` action inputs are closed: `Country`, `Phone`, or any other unknown key
  fails input validation before a request is sent, rather than being stripped. Decoding the
  exported input classes directly uses default Effect parsing, which strips unknown keys. `FortnoxCustomer` and `FortnoxSupplier` responses still include
  `Country` and `Phone`.
* **Customer updates.** Only provided fields change; omitted fields keep their stored value. An
  empty string does not clear a stored value.
* **Invoice row inputs.** Write rows are `FortnoxInvoiceRowInput`: the writable fields of
  Fortnox's row payload. `Price` is the unit price; Fortnox computes `PriceExcludingVAT`, `Total`,
  and `TotalExcludingVAT`, which are read-only (Fortnox rejects a written `PriceExcludingVAT` with
  code 2000321) and appear only on returned `FortnoxInvoiceRow` values.
* **Invoice rows on update.** Sending `InvoiceRows` replaces the row list: existing rows that are
  not sent are deleted. If no sent row has `RowId`, rows are matched to existing rows by position,
  and fields omitted on a matched row keep their previous value (for example
  `Discount`/`DiscountType`). Send every row that should remain with all pricing fields, including
  `Discount: 0` when no discount is intended. If any sent row has `RowId`, rows with a matching
  `RowId` are updated and rows without one are added. Fortnox
  regenerates RowIds on every update, so read the invoice again before reusing them.
* **Invoice text.** `Remarks` is the invoice text (Fakturatext) printed on the invoice; `Comments`
  is an internal note that is not printed. Both are writable on create and update, and
  `FortnoxInvoice` returns both.
* **Referenced records.** `CostCenter`, `Project`, `ArticleNumber`, `AccountNumber`, and a non-SEK
  `Currency` must already exist in the Fortnox company.

Pass identifier strings returned by the provider, preserving leading zeros. `givenNumber` is the
numeric-string **GivenNumber**, not the supplier's `InvoiceNumber`. Identifiers are validated and
encoded as path segments; returned provider URLs are never followed. Typed file-discovery inputs
and outputs use `FortnoxGivenNumber`; `downloadFortnoxInvoicePreview` takes
`FortnoxDocumentNumber`. Decode raw provider/request values with those exported schemas, or use
`.make` for trusted constants. Dynamic `FortnoxConnector.invoke` still accepts plain JSON and
decodes it at runtime.

Resource fields retain Fortnox spelling, including `CustomerNumber`, `DocumentNumber`,
`GivenNumber`, `CompanyName`, and `OrganisationNumber` (company information uses
`OrganizationNumber`). These are bounded read models: unknown provider fields are omitted, not a
lossless accounting export. The exported schemas define the selected contact, status, reference,
amount, and invoice-row fields. Supplier bank details and unmodeled provider fields are not exposed.
List responses can contain fewer fields than detail responses; optional omission does not mean zero
or false. Use a get action to retrieve available rows.

Collections are runtime Effect `Chunk` values, including `InvoiceRows` and `SupplierInvoiceRows`.
Customer-invoice `Total` and `Balance` remain numbers; supplier-invoice `Total` and `Balance` remain
strings, preserving their supplied decimal representation. Row amounts are numbers with nullable
`Total`/`CostCenter` values; supplier invoice row amounts also accept numeric strings. The connector
does not round or recompute response amounts; its only monetary arithmetic is the
`fortnox.create_voucher` balance check (whole öre) before the request.

Supplier invoice read actions also accept JSON forms Fortnox's OpenAPI types do not list: `GivenNumber`,
`SupplierNumber`, `InvoiceNumber`, `OCR`, `CostCenter`, `Project` and the row `ArticleNumber`,
`CostCenter` and `Project` as strings or integers; `VoucherNumber` and row `Account` as integers or
integer strings (`""` is unset); the `Booked`, `Cancelled`, `Credit` and `PaymentPending` flags as
booleans or `"true"`/`"false"` (`""` is unset); row amounts as numbers or numeric strings; and
invoice-level `Total`, `Balance` and `CurrencyRate` as strings or numbers (recorded as their string
form). The public schemas do not change and stay strict when a host decodes raw provider JSON with
them. A Fortnox amount sent as a JSON number past the double range (which parses to `Infinity`) fails
the read with `validation_failed`. An identifier sent as a JSON number past `Number.MAX_SAFE_INTEGER` (a
long OCR) still fails to decode: its digits are already lost.

### Pagination and search [#pagination-and-search]

Every list action fetches exactly one page, except `fortnox.list_voucher_file_connections` (see
[Bookkeeping](#bookkeeping)). Record-list inputs support `page` (integer, at least 1), `limit`
(integer, 1–500), and `lastModified` (provider timestamp string). Omitted values use Fortnox defaults
(page 1, limit 100). Output `pagination` contains `currentPage`, `totalPages`, `totalResources`, and
optional `nextPage`. Continue with `page: nextPage`, repeating the same limit and selection fields;
stop when `nextPage` is absent. Missing or malformed pagination metadata is an error, not an assumed
final page. The connector does not auto-paginate or promise snapshot consistency while records change.

Fortnox's OpenAPI invoice-list wrapper omits the generic `MetaInformation` field that this connector
expects. Invoice pagination needs confirmation with a sanitized response from your account before
production use; the connector does not infer completion when metadata is missing.

For resource-specific searches, supply one `search: { field, value }` pair:

| Resource                  | Supported `search.field` values                                                                                           |
| ------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
| Customers                 | `customernumber`, `name`, `organisationnumber`, `email`, `city`, `phone`                                                  |
| Suppliers                 | `suppliernumber`, `name`, `organisationnumber`, `email`, `city`, `phone`                                                  |
| Invoices                  | `customernumber`, `customername`, `documentnumber`, `ocr`                                                                 |
| Supplier invoices         | `suppliernumber`, `suppliername`, `invoicenumber`, `serialnumber`, `ocr`                                                  |
| Articles                  | `articlenumber`, `description`, `ean`, `suppliernumber`, `manufacturer`, `manufacturerarticlenumber`                      |
| Price lists               | `code`, `comments`                                                                                                        |
| Invoice payments          | `invoicenumber` (customer invoice DocumentNumber)                                                                         |
| Supplier invoice payments | `invoicenumber` (supplier invoice GivenNumber)                                                                            |
| Offers                    | `customername`, `customernumber`, `documentnumber`, `offerdate`, `ourreference`, `yourreference`, `costcenter`, `project` |

Fortnox supports only one resource-specific search field at a time; matching follows provider
semantics, not guaranteed exact equality. Combine it with global `lastModified`, and for invoice
lists, `fromDate`/`toDate` date strings. Dates are forwarded unchanged without timezone conversion.

Customers and articles additionally accept `filter: 'active' | 'inactive'`. Offers accept
`cancelled`, `expired`, `completed`, `notcompleted`, `ordercreated`, or `ordernotcreated`, plus
`fromDate`/`toDate`. Settings registers (modes of payment, terms, ways of delivery, units) take
`page` and `limit` only. Print templates, labels, and predefined accounts are not paginated. Both invoice lists accept `cancelled`,
`fullypaid`, `unpaid`, `unpaidoverdue`, or `unbooked`; supplier invoices also accept `pendingpayment`
and `authorizepending`. Supplier lists do not expose a status filter. Unsupported sort/offset or
arbitrary query parameters are not part of this connector.

Fortnox's API docs do not state how payment-status filters treat unbooked invoices. On a demo
tenant, `unpaid`, `unpaidoverdue`, and `fullypaid` did not return unbooked customer invoices; use
`filter: 'unbooked'` for those. An empty payment-status result does not prove nothing is outstanding.

## Handle failures and rate limits [#handle-failures-and-rate-limits]

Non-2xx responses return `ActionResult.failure`, including `fortnox_unauthorized` (401),
`fortnox_forbidden` (403), `fortnox_not_found` (404), `fortnox_rate_limited` (429), and
`fortnox_request_failed` for other statuses. Fortnox `ErrorInformation` fields accept both documented casings (`message`/`code` and
`Message`/`Code`). The message is retained; the code, when present, is available as
`error.underlying.providerCode`. Raw error bodies are not
returned. Missing/invalid credentials, input validation, malformed success bodies, and transport
errors stay in the typed Effect error channel.

Hosts can classify failures from `underlying.providerCode` using Fortnox's
[documented error codes](https://www.fortnox.se/developer/guides-and-good-to-know/errors). The
connector does not map these codes itself. Codes relevant to these actions include:

| Code(s)                         | Fortnox meaning                                           |
| ------------------------------- | --------------------------------------------------------- |
| `2000310`, `2000311`            | Access token (or client secret) missing or incorrect      |
| `2001101`, `2001103`, `2000663` | No license for the scope or API, or no access to scope    |
| `2001399`                       | Invalid field name                                        |
| `2000106`, `2000108`, `2000134` | Value must be alphanumeric, numeric, or boolean           |
| `2000359`, `2000588`            | Value contains invalid characters; invalid parameter      |
| `2001304`                       | Account not found                                         |
| `2001302`, `2000428`            | Article not found                                         |
| `2000204`, `2000433`            | Customer not found                                        |
| `2000637`                       | Customer number already used or reserved by a deleted one |

Fortnox documents 25 requests per 5 seconds per access token. Hosts own throttling and retry policy;
the connector never retries automatically. A valid delta-seconds `Retry-After` header is exposed as
`retryAfterMs`; HTTP-date headers are not interpreted. A 403 may mean missing consent, license, or
permissions rather than an expired token.

## Expose agent tools [#expose-agent-tools]

Wiring fragment; `HostConnectorLayer` is the host-provided layer described above:

```ts
import { makeConnectorToolModule } from '@yolk-sdk/connectors/agent'

const tools = makeConnectorToolModule(FortnoxConnector, {
  integration,
  layer: HostConnectorLayer
})
```

The adapter inherits each action's declared access metadata (`read`, `write`, or `destructive`);
explicit host access overrides still win. Require manual approval for `destructive` tools such as
`fortnox.email_offer`, `fortnox.bookkeep_invoice_payment`, and `fortnox.create_voucher`, or exclude
them from the module.
Customer-invoice sending and booking are still not connector actions, so any host-owned outbound
action must keep its own approval gate.
See [Add connector tools](../integrations/connector-tool) for tool execution and authorization.

## Conformance cases [#conformance-cases]

> **Experimental.** For tests and hand-run checks against a Fortnox developer test company.

`@yolk-sdk/connectors/fortnox/conformance` exports conformance cases for
`@yolk-sdk/conformance/runner`. Each checks one claimed Fortnox behavior through the real connector
actions. The claims are as currently understood; none is observed live yet. This table is the
canonical list of cases:

| Case id                                            | Safety               | Seeds                                          | Claim (as currently understood)                                                                                                                                                                                                                               |
| -------------------------------------------------- | -------------------- | ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `fortnox.invoice.list-populated`                   | `read`               | none                                           | Invoice lists carry `MetaInformation`; amounts decode to finite numbers or are unset, whether sent as numbers or as numeric strings (such as `CurrencyRate: "1"`)                                                                                             |
| `fortnox.invoice.preview-pdf`                      | `read`               | `previewInvoiceDocumentNumber`                 | `/preview` returns a complete PDF (`%PDF-` ... `%%EOF`) whatever content type it declares                                                                                                                                                                     |
| `fortnox.invoice.payment-filters-exclude-unbooked` | `read`               | none                                           | `unpaid` leaves out an unbooked invoice with a positive balance; `unpaidoverdue` leaves out one whose `DueDate` is before today (Effect `Clock`). Aborts without such an invoice                                                                              |
| `fortnox.invoice.row-discount-sticky`              | `write-reversible`   | `discountInvoiceDocumentNumber`                | A positional row update without `Discount` keeps the previous discount; only `Discount: 0` clears it. Every row needs an explicit `Discount` and `DiscountType: PERCENT` beforehand                                                                           |
| `fortnox.customer.empty-string-keeps-value`        | `write-reversible`   | `customerNumber`                               | Updating `Comments` to `""` keeps the stored value; how to clear a value is not established. The customer needs a non-empty `Comments`                                                                                                                        |
| `fortnox.write.rejection-error-information`        | `write-reversible`   | `missingCustomerNumber`                        | Rejected writes return `ErrorInformation` with a code and message, surfaced as `underlying.providerCode` and the provider message                                                                                                                             |
| `fortnox.invoice.send-email`                       | `write-irreversible` | `emailInvoiceDocumentNumber`, `emailRecipient` | `GET /3/invoices/{DocumentNumber}/email` answers 2xx with the invoice; whether a test company delivers the email is not established                                                                                                                           |
| `fortnox.company.information-decodes`              | `read`               | none                                           | `CompanyInformation` decodes with a non-empty `CompanyName`                                                                                                                                                                                                   |
| `fortnox.customer.list-matches-get`                | `read`               | none                                           | Customer lists carry `MetaInformation`; the first row reads back by `CustomerNumber` with the same `Name` (a mismatch never echoes either value)                                                                                                              |
| `fortnox.article.list-row-numeric-strings`         | `read`               | none                                           | Article list rows (numeric strings) and single reads (numbers) decode to the same `VAT`, `SalesPrice`, `PurchasePrice`, and `QuantityInStock`                                                                                                                 |
| `fortnox.price.tier-matches-sublist`               | `read`               | none                                           | The `PreSelected` price list and a price tier read back as listed; an article's `SalesPrice` is its base (`FromQuantity` 0) price in that list                                                                                                                |
| `fortnox.cost-center.list-matches-get`             | `read`               | none                                           | Cost center lists carry `MetaInformation`; the first row reads back by `Code` as listed                                                                                                                                                                       |
| `fortnox.payment.invoice-payment-wire-numbers`     | `read`               | none                                           | Invoice payment voucher fields and `ModeOfPaymentAccount` decode (from numeric strings in the docs examples); the first row reads back as listed                                                                                                              |
| `fortnox.payment.supplier-payment-wire-numbers`    | `read`               | none                                           | Supplier invoice payment voucher fields decode (from numeric strings in the docs examples); the first row reads back as listed                                                                                                                                |
| `fortnox.offer.rows-on-get-and-preview-pdf`        | `read`               | none                                           | Offer list rows carry no `OfferRows` (unverified: no live run confirms it); a single read has its rows; the offer preview is a complete PDF                                                                                                                   |
| `fortnox.print-templates.unpaginated`              | `read`               | none                                           | Invoice and offer print templates decode, and their raw answers carry no `MetaInformation`                                                                                                                                                                    |
| `fortnox.inbox.file-bytes-match-size`              | `read`               | none                                           | The inbox root lists its subfolders; a file found in the root or a direct subfolder downloads exactly its listed `Size`                                                                                                                                       |
| `fortnox.settings.company-and-locked-period`       | `read`               | none                                           | `CompanySettings` has a non-empty `Name`; the locked period `EndDate` is a `YYYY-MM-DD` date, empty, or unset (unverified); a 404 aborts with a precondition                                                                                                  |
| `fortnox.settings.predefined-accounts-and-labels`  | `read`               | none                                           | Predefined accounts and labels decode, and their raw answers carry no `MetaInformation`; the first account reads back by `Name`; label ids are distinct                                                                                                       |
| `fortnox.settings.registers-list-matches-get`      | `read`               | none                                           | Each of the five settings registers lists with `MetaInformation`, and its first row reads back by `Code` as listed (a mode of payment `AccountNumber` decodes to the same integer whatever its wire type)                                                     |
| `fortnox.profile.me`                               | `read`               | none                                           | `Me` decodes with a non-empty `Id`                                                                                                                                                                                                                            |
| `fortnox.bookkeeping.financial-year-id-and-date`   | `read`               | none                                           | Financial year lists carry `MetaInformation`; the first year reads back with the same `Id`, dates, and `AccountingMethod` by `id` and by its `FromDate` (the chart type, `accountCharts` in list rows, is not compared)                                       |
| `fortnox.bookkeeping.account-balances-list-get`    | `read`               | none                                           | A populated account page of the first year is sorted by number and in that year; the first account reads back with the same balances in whole öre (unverified: OpenAPI types the list closing balance as a float)                                             |
| `fortnox.bookkeeping.voucher-list-get-balanced`    | `read`               | none                                           | A populated voucher page of the first year; its series and series sublist hold the first voucher, which reads back as listed with at least two rows that balance (unverified: removed rows); every raw file connection row carries `VoucherYear` (unverified) |
| `fortnox.bookkeeping.sie-file-ibm437`              | `read`               | none                                           | The type 1 SIE file is exactly the bytes Fortnox answered and declares `#FORMAT PC8` and `#SIETYP 1` (unverified: whether Fortnox writes `#FORMAT PC8`)                                                                                                       |

The last eighteen cases cover company information, the customer list, the read-only resource
modules, and bookkeeping: each only reads, needs no seed (it reads back the first row a list answers), and aborts
with a `precondition:` mismatch when the practice company holds nothing to read. Their fixtures are
shaped from the [Fortnox API reference](https://api.fortnox.se/apidocs) and the JSON examples of
its archived resource pages.

The cases need `FortnoxConformanceConfig` seed identities (never hard-coded account data) and the
connector ports; `@yolk-sdk/connectors/conformance` bridges an Effect `HttpClient` to those ports for
tests only. A missing seed fails the case with a `precondition:` mismatch before any request.

What the write cases guarantee differs:

* **Row and customer cases** read the original state first, always restore it afterwards (also after
  a failed assertion or an interruption), and verify the restore by reading back. The row case
  compares every written row field plus `VATCode`, and the invoice `Total`, `TotalVAT`, `Net`, and
  `Gross`, exactly. A failed restore fails the case with `FortnoxConformanceRestoreFailed`, which
  summarizes the original failure when the claim failed; check the account and restore it by hand
  if it still differs. A failed restore raised while the case is being interrupted is also handed,
  with its full message, to `ConformanceCleanupReporter` from `@yolk-sdk/connectors/conformance`
  (default: `Effect.logWarning`), since the interruption may replace it. The repository runner
  (`pnpm conformance:fortnox`) turns a first Ctrl-C into an interruption and prints these reports
  on stderr as `WARN` lines. Like the shared runners, it prints every line of a live run (the
  report, `WARN` lines, the run's own failure, staging output) with the live access token redacted,
  since Fortnox can echo it into a field a case reports. The rejection case and the email send do
  not report.
* **The rejection case** does not restore anything. It first confirms that the customer is absent: a
  404, or another 4xx with a customer-not-found `ErrorInformation` code (`2000204`, `2000433`).
  401, 403, and every other failure abort before the write. If Fortnox unexpectedly accepted the
  create, the case fails and names the invoice to cancel by hand.
* **The email case** reads the invoice first and aborts unless `EmailInformation.EmailAddressTo`
  equals the `emailRecipient` seed exactly and no CC or BCC address is set. It sends with
  `redirect: 'manual'` and `credentials: 'omit'`, and fails on any 3xx rather than treating it as
  sent. It is never automated.

The shipped fixtures are synthetic (`evidence: 'unverified'`). See
[Conformance APIs](../api-reference/conformance#connector-conformance) for the bridges.

For offline tests, the experimental [Fortnox emulator](../api-reference/emulators#fortnox-emulator)
(`@yolk-sdk/emulators/fortnox`) is a stateful stand-in that passes these cases and reproduces their
quirks.

## Official Fortnox references [#official-fortnox-references]

* [API reference](https://apps.fortnox.se/apidocs)
* [Scopes and required licenses](https://www.fortnox.se/developer/guides-and-good-to-know/scopes)
* [Authorization code](https://www.fortnox.se/developer/authorization/get-authorization-code)
* [Access-token exchange](https://www.fortnox.se/developer/authorization/get-access-token)
* [Authorization and refresh lifecycle](https://www.fortnox.se/developer/authorization/)
* [API request authentication](https://www.fortnox.se/developer/authorization/make-request)
* [Parameters and pagination](https://www.fortnox.se/developer/guides-and-good-to-know/parameters/)
* [Response and error envelopes](https://www.fortnox.se/developer/guides-and-good-to-know/responses)
* [Error codes](https://www.fortnox.se/developer/guides-and-good-to-know/errors)
* [SIE file format](https://sie.se/format/)
* [Voucher resource (archived)](https://web.archive.org/web/2023/https://developer.fortnox.se/documentation/resources/vouchers/)
* [Customer resource (archived)](https://web.archive.org/web/20220812174224/https://developer.fortnox.se/documentation/resources/customers/)
* [Updating document rows with RowId (archived)](https://web.archive.org/web/20211203193604/https://developer.fortnox.se/blog/updating-document-rows-using-rowid/)


---

# GitHub conformance

URL: /docs/connectors/github

Experimental GitHub conformance cases for tests and hand-run practice-repository checks.



GitHub actions are documented in the [connectors package guide](./index) and the
[integrations reference](../integrations/connectors#github). This page lists the experimental
conformance cases only.

## Conformance cases [#conformance-cases]

> **Experimental.** For tests and hand-run checks against a practice GitHub repository.

`@yolk-sdk/connectors/github/conformance` exports conformance cases for
`@yolk-sdk/conformance/runner`. Every case runs the real connector actions over the connector ports
against the GitHub REST API (`https://api.github.com`, `X-GitHub-Api-Version: 2026-03-10`), and
checks one wire claim the connector relies on. Where an action reads only part of a response body
(error envelopes, the base64 file content), the case observes the body at the `ConnectorHttpClient`
port the host provides; it sends no request of its own. The claims are as currently understood;
none is observed live yet.

| Case id                             | Safety               | Seeds                                           | Claim (as currently understood)                                                                                                                                                                              |
| ----------------------------------- | -------------------- | ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `github.labels.list-link-paging`    | `read`               | `owner`, `repo`                                 | `per_page=2` label pages carry `Link` `rel="next"` while labels remain; `page` numbers continue the list with no repeat within or across pages; the page after the last is empty                             |
| `github.errors.not-found-envelope`  | `read`               | `owner`, `repo`                                 | An unused issue number maps to `github_not_found`; the JSON `message` follows the connector's message prefix and `documentation_url` reaches `underlying` (status unverified)                                |
| `github.errors.validation-envelope` | `read`               | `owner`, `repo`                                 | A search over 256 characters maps to `github_validation` with a `message` and `errors` entries the connector reads (the trigger is unverified)                                                               |
| `github.contents.base64-file`       | `read`               | `owner`, `repo`, `filePath`                     | A text file answers base64 broken into lines (unverified) that decodes to exactly `size` UTF-8 bytes                                                                                                         |
| `github.issues.open-listing`        | `read`               | `owner`, `repo`, `workIssueNumber`              | The leftover lookup's open-issue listing (`per_page=100`, `page=1`) answers only open items, the work issue among them, and no next page when it fits; the work issue's first comment page matches its count |
| `github.comments.create-delete`     | `write-reversible`   | `owner`, `repo`, `workIssueNumber`, `runId`     | A run-scoped comment is listed `since` its `created_at`, deleted by id, then no longer listed; a second delete answers not found (both unverified); residue: a notification to the work issue's subscribers  |
| `github.labels.add-remove`          | `write-reversible`   | `owner`, `repo`, `workIssueNumber`, `labelName` | Adding and removing the seeded label answer the issue's label names with and without it, and `get_issue` agrees; a second remove answers not found; residue: two timeline events                             |
| `github.issues.lifecycle-close`     | `write-irreversible` | `owner`, `repo`, `runId`                        | A run-scoped issue is created open, read, renamed, and closed as `completed`, and reads back closed; the closed issue stays                                                                                  |

Claims no live run has settled yet, marked "(unverified: ...)" in each case's `wire`:

* An issue number the repository has not reached answers 404 (the connector maps 404 and 410 alike,
  so the case accepts either).
* GitHub refuses a search longer than 256 characters with 422 and an `errors` array, rather than
  answering 200. The case reads no search results, so search index consistency (search is
  eventually consistent) does not matter to it.
* GitHub folds the base64 `content` of a file every 60 characters; the connector strips all
  whitespace before decoding, and the case requires at least one line break so that path is
  exercised.
* `list_issue_comments` with `since` set to a comment's `created_at` still lists that comment. The
  comment case checks this before the delete, so a `since` that excluded it would fail the case
  rather than make the later absence check pass vacuously.
* Deleting an already deleted comment answers 404, and removing a label that is not on the issue
  answers 404. Both cleanups rely on it: a not-found answer to the undo counts as undone.
* An issue listing's `comments` count matches the issue's comment listing (the open-listing case
  compares them for the work issue).

Claims are narrowed to what the connector reads. The error cases check the status class the
connector maps, that the connector message starts with the body `message`, that
`documentation_url` reaches `underlying`, and (validation case only) that the `errors` entries have
a shape the connector can turn into details (a string, or an object with a string `resource`,
`field`, `code`, or `message`); they do not pin GitHub's exact wording, the not-found `errors`, or
the body `status` field. The paging case checks `rel="next"` only (the connector never follows the
`Link` URL, it asks for the next `page` number) and requires each page to list every label once.

`GithubConformanceConfig` holds the seeds: `owner` and `repo` (the practice repository, as
integration config; it must have 3 to 20 labels, since the paging case pages by two and gives up
after ten pages), `workIssueNumber` (an open practice issue, not a pull request, that **nobody else
watches**, which the comment and label cases write to), `labelName` (an existing repository label
that is not on the work issue), `filePath` (a UTF-8 text file in the default branch, more than 45
bytes, with at least one non-ASCII character, and under 100,000 characters, beyond which the
connector truncates the content), and `runId`. Cases never hard-code
account data, and a missing seed fails the case with a `precondition:` mismatch before any request.
Credentials bind through `githubConformanceIntegration(owner, repo)` (`github.token`, credential ref
`github.conformance`).

### Write ownership and cleanup [#write-ownership-and-cleanup]

The `runId` seed is a per-invocation `run-<hex>` value: the fixtures replay with `run-synthetic`, and
the live runner generates a fresh one every time and never takes it as a flag. Every comment body
and issue title a case writes starts with `yolk-conformance <runId>`.

* The create request (comment create, label add, issue create), its decoding, its classification,
  and the registration of what it created run together without interruption, and so does every
  later write (deletes, removes, renames, closes). Neither the runner nor the bridges set a request
  timeout, so a hanging request delays an interruption until it answers.
* A definitive rejection (HTTP 4xx other than 408) changed nothing: the case fails and undoes
  **nothing**.
* An ambiguous outcome (a transport or decoding failure, no status, HTTP 408, or HTTP 5xx) may have
  written anyway, and the case never learned what: it fails with `GithubConformanceActionFailed`
  (`writeOutcome: 'unknown'`) naming the exact comment text, label, or issue title to check by hand,
  and undoes nothing.
* A create that answers an item outside the run namespace (a comment without the requested body, an
  issue without the requested title, a pull request, or the seeded work issue's number) is never
  adopted: the case fails with `GithubConformanceCleanupRefused` naming it.
* After a successful create, the cleanup undoes the item **by id** (the comment id, the issue
  number) or by the seeded issue and label, also after a failed claim or an interruption, and then
  verifies it: the comment is no longer listed, the label is no longer on the issue, the issue reads
  closed. A failed cleanup fails with `GithubConformanceRestoreFailed` naming the item and what to
  do by hand.
* The label case starts only when the label is **not** on the work issue (so it never removes a
  label it did not add) and when the label already exists in the repository (adding a missing label
  creates it, and the connector cannot delete repository labels). It adds and removes the same
  seeded label on the same seeded issue, so **concurrent runs of the label case are not supported**:
  a second run refuses to start while the first holds the label.

### What the reversible cases leave behind [#what-the-reversible-cases-leave-behind]

The comment and label cases undo the **state** they change: the comment is deleted, and the label
is off the issue again. They cannot undo what that state change triggered:

* **Notifications.** Creating the comment notifies the work issue's subscribers (web, email, and
  mobile); deleting it does not recall them.
* **Timeline events.** Adding and removing the label leave permanent `labeled` and `unlabeled`
  events on the issue timeline.

This residue is why the work issue must be a practice issue **nobody else watches**. The cases stay
`write-reversible` because nothing they create outlives the run; the lifecycle case is
`write-irreversible` because it leaves state behind (a closed issue), not only notifications or
timeline events.

### The issue lifecycle is irreversible [#the-issue-lifecycle-is-irreversible]

**GitHub issues cannot be deleted through the REST API**, and the connector has no delete action:
closing is the only undo, and the closed issue stays in the repository: state, not only a
notification or a timeline event. `github.issues.lifecycle-close` is therefore `write-irreversible`: it never runs under
`allowWrites: 'reversible'`, and a runner starts it only when a person names its exact id
(`allowIrreversible: ['github.issues.lifecycle-close']`; the live runner's
`--allow-irreversible github.issues.lifecycle-close`). Every run leaves one closed issue titled
`yolk-conformance <runId> lifecycle renamed: ...`. If a step fails after the create, the cleanup
closes the issue as `not_planned` and verifies that it reads closed; if that fails, the error names
the issue number to close by hand. When the lifecycle case will run, the live runner prints the run
id before any case.

### Leftovers and interruptions [#leftovers-and-interruptions]

Before any write case, and again after an interrupt-only exit, the live runner calls
`findGithubConformanceLeftovers` and prints a WARN line for each open issue titled
`yolk-conformance run-*` (at most 10 pages of 100 open issues), each `yolk-conformance run-*`
comment on the work issue (at most 10 pages of 100), and the seeded label when it is on the work
issue. The lookup is read-only and bounded; nothing is changed automatically. Closed
`yolk-conformance run-*` issues are the lifecycle case's documented leftover and are not listed.

In the live runner, the first SIGINT or SIGTERM (Ctrl-C) interrupts the run fiber; the running
case's cleanup is attempted before the process exits, and no further case starts. A cleanup that
fails, or a write whose outcome is unknown, while the case is being interrupted prints its full
message as a WARN line (through the case's `ConformanceCleanupReporter`), the record of the problem;
either way the run ends as a plain interruption with exit code 130 after the leftover lookup runs
again. Further signals within a second count as the same keypress; a later one exits at once and may
skip the cleanup. Run live runs as `pnpm conformance:github …` or
`./node_modules/.bin/tsx scripts/run-github-conformance.ts …`, not `pnpm exec tsx …`, which returns
to the prompt at once on Ctrl-C.

### Token safety and recording [#token-safety-and-recording]

The token travels only in the `Authorization: Bearer` header, which the conformance recorder never
records (credential headers are always dropped); the replay ledger redacts it. The live runner
refuses a `GITHUB_TOKEN` that is not 20 to 255 letters, digits, and underscores (every GitHub token
format) before any request, without printing it. `--record` still refuses to stage, or print a
review checklist for, any recording in which the live token survives anywhere (an echo in a body or
header; raw, percent-encoded, escaped, or base64-encoded) or that holds a body outside the guard's
inspectable allowlist (strict UTF-8 text without NUL characters), and the fixture secret scan refuses
credential query parameters. A private repository's contents answer carries a temporary `token` in
its `download_url`, so record the contents case against a **public** practice repository.

The shipped fixtures are synthetic (`evidence: 'unverified'`). In this repository,
`pnpm conformance:github` dry-runs by default; `--live --owner-approved --account <label>` (refused
whenever `CI` is non-empty) needs `GITHUB_TOKEN` (a token for the practice repository only; a
fine-grained token with Issues read/write and Contents read is enough) and the seeds (`--owner`,
`--repo`, `--work-issue`, `--label`, `--file-path`). `--allow-writes reversible` adds the comment
and label cases; `--allow-irreversible github.issues.lifecycle-close` adds the lifecycle case.
`--record` keeps the `link` response header and the `x-github-api-version` request header and stages
verified recordings only in the gitignored `.conformance-recordings/github/` for manual scrubbing
(owner, repository, numeric repository ids in `Link` URLs, logins, ids, titles, bodies, label names,
file contents) and promotion. See
[Conformance APIs](../api-reference/conformance#connector-conformance) for the bridges.

For offline tests, the experimental [GitHub emulator](../api-reference/emulators#github-emulator)
(`@yolk-sdk/emulators/github`) is a stateful, fixture-only stand-in that passes these cases through
the real connector actions over the connector ports, including the lifecycle case (its closed issue
stays in the emulator's state). The open-listing case records the leftover lookup's reads, so
against the emulator the lookup runs: it finds nothing on the default seed (the lifecycle case's
issues are closed) and reports an open `yolk-conformance run-*` issue the emulator holds.


---

# Google conformance

URL: /docs/connectors/google

Experimental Gmail, Calendar, and Drive conformance cases for tests and hand-run practice-account checks.



Google actions are documented in the [connectors package guide](./index) and the
[integrations reference](../integrations/connectors#google). This page lists the experimental
conformance cases only.

## Conformance cases [#conformance-cases]

> **Experimental.** For tests and hand-run checks against a practice Google account.

`@yolk-sdk/connectors/google/conformance` exports conformance cases for
`@yolk-sdk/conformance/runner`. Every case runs the real connector actions over the connector ports
against the Gmail (`https://gmail.googleapis.com/gmail/v1`), Calendar
(`https://www.googleapis.com/calendar/v3`), and Drive (`https://www.googleapis.com/drive/v3`) APIs,
and checks one wire claim the connector relies on. Where an action returns the answer undecoded
(`gmail.list`, drafts, `gmail.modify_labels`, trash), the case decodes the fields it needs with a
local schema; where the connector reads only part of an error body, the case observes the body at
the `ConnectorHttpClient` port the host provides. The cases send no request of their own. The claims
are as currently understood; none is observed live yet.

| Case id                                    | Safety               | Seeds                                            | Claim (as currently understood)                                                                                                                                                                                                                                                                                                                                      |
| ------------------------------------------ | -------------------- | ------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `google.gmail.list-page-token`             | `read`               | `pagingLabelId`                                  | `gmail.list` pages of two chain through `nextPageToken`, repeat no message, and list exactly the messages of one large page                                                                                                                                                                                                                                          |
| `google.gmail.attachment-base64url`        | `read`               | `attachmentMessageId`                            | An attachment `get_attachment` answers base64url `data` (no `+` or `/`) decoding to exactly `size` bytes                                                                                                                                                                                                                                                             |
| `google.gmail.not-found-envelope`          | `read`               | none                                             | An unused message id answers 404 (unverified), mapped to `google_not_found`, with a JSON `error.message` the connector appends to its message                                                                                                                                                                                                                        |
| `google.gmail.list-threads-page-token`     | `read`               | `pagingLabelId`                                  | `gmail.list_threads` names exactly the threads of the label's messages (unverified), and pages of two chain through `nextPageToken`, repeat no thread, and list exactly the threads of one large page                                                                                                                                                                |
| `google.gmail.metadata-headers`            | `read`               | `attachmentMessageId`                            | A `format: "metadata"` read with `metadataHeaders: ["Subject", "From"]` answers exactly those headers of the unfiltered read (unverified: case-insensitive matching), for the message and in `get_thread`                                                                                                                                                            |
| `google.gmail.label-listing`               | `read`               | `pagingLabelId`                                  | The leftover lookup's label listing names each label once, the seeded paging label as `type: "user"` and `INBOX` as `type: "system"`                                                                                                                                                                                                                                 |
| `google.gmail.draft-search`                | `read`               | none                                             | The leftover lookup's draft search (`subject:yolk-conformance`, `maxResults: 100`) answers 2xx with at most 100 drafts by id and message id, or none                                                                                                                                                                                                                 |
| `google.gmail.label-create-apply-delete`   | `write-reversible`   | `workMessageId`, `runId`                         | A run label is created, applied to the work message, listed on it, deleted by id (204, empty body), reads `google_not_found`, and is gone from the message                                                                                                                                                                                                           |
| `google.gmail.draft-compose-update-delete` | `write-reversible`   | `runId`                                          | A draft without recipients, proven the run's own before adoption, round-trips its ASCII subject and non-ASCII body through `get_thread`, before and after an update, then deletes (204, empty body); its message then answers not found, and stays gone after a second delete (2xx or not found); live only, the leftover lookup's search finds it before the delete |
| `google.gmail.trash-untrash`               | `write-reversible`   | `workMessageId`                                  | Trash adds `TRASH`, and untrash removes it; the cleanup restores and verifies every earlier label                                                                                                                                                                                                                                                                    |
| `google.gmail.send-practice-address`       | `write-irreversible` | `practiceAddress`, `runId`                       | One 7-bit message to the practice address only (decoded again in the case as exactly one plain address), sent as one multipart upload, answers an id whose `To` and `Subject` read back                                                                                                                                                                              |
| `google.calendar.list-range-paging`        | `read`               | `calendarId`, `eventRangeStart`, `eventRangeEnd` | A time-range listing returns only events overlapping the range, and pages of two chained through `nextPageToken` list exactly the events of one large page                                                                                                                                                                                                           |
| `google.calendar.free-text-query`          | `read`               | `calendarId`                                     | The leftover lookup's free-text query (`q=yolk-conformance`, `maxResults: 250`) repeats no event and answers only events that mention `yolk` or `conformance` in any text Google searches, organizer, creator, and working location included (observed at the port; unverified)                                                                                      |
| `google.calendar.event-lifecycle`          | `write-reversible`   | `calendarId`, `runId`                            | An event without attendees is created with the requested times, read, renamed by PATCH (start kept), deleted, and reads gone (404, 410, or `cancelled`; unverified which); live only, the leftover lookup's search finds it before the delete                                                                                                                        |
| `google.calendar.deleted-event-gone`       | `write-reversible`   | `calendarId`, `runId`                            | A deleted event reads gone, and stays gone after a second delete (2xx, 404, or 410; unverified which)                                                                                                                                                                                                                                                                |
| `google.drive.list-page-token`             | `read`               | `driveFolderId`                                  | A folder listing returns only untrashed children, and pages of two chained through `nextPageToken` list exactly the files of one large page                                                                                                                                                                                                                          |
| `google.drive.get-file-fields`             | `read`               | `driveFileId`, `driveFolderId`                   | `get_file` accepts the connector's full `fields` selection and answers the same id, name, mime type, and parents as the listing                                                                                                                                                                                                                                      |
| `google.drive.list-includes-trashed`       | `read`               | `driveFolderId`, `driveTrashedFileId`            | The leftover lookup's listing with trashed items answers the seeded trashed file (`trashed: true`, left out of the default listing), every file of the default listing, and only trashed extras (unverified)                                                                                                                                                         |
| `google.drive.folder-trash-delete`         | `write-reversible`   | `driveFolderId`, `runId`                         | A run folder is created, trashed (`trashed: true`, left out of listings), deleted permanently by id (204, empty body), and reads `google_not_found`                                                                                                                                                                                                                  |

No case covers draft attachments: `gmail.draft_compose`, `gmail.draft_update`, and
`gmail.draft_reply` with `attachments` write through the draft media upload
(`upload/gmail/v1/users/me/drafts[/{id}]?uploadType=multipart`), which no fixture records and the
Google emulator does not emulate (it answers the constant unrecognised 400). Unit tests pin the
request shape; a draft-attachment case needs an owner-approved live recording. The draft case above
sends no attachments, so its JSON requests are unchanged.

Claims no live run has settled yet, marked "(unverified: ...)" in each case's `wire`:

* An unused 16-hex-digit message id answers 404 rather than 400 `Invalid id value`.
* Gmail lists a thread under a label when any of its messages carries it, and never a thread none
  of them carries.
* A `metadataHeaders` selection matches header names case-insensitively (the connector filters
  `get_thread` headers that way; the case selects the usual spelling), and Gmail keeps the selected
  headers in the order of the unfiltered read.
* A metadata read of a fresh draft returns the `DRAFT` label and the subject exactly as sent (the
  draft ownership check relies on it; if not, the case refuses its own draft and the leftover
  lookup reports it).
* Gmail keeps the `multipart/alternative` draft as the connector wrote it and answers its
  text/plain part's `body.data` transfer-decoded (the part keeps its quoted-printable header), so
  `get_thread` decodes exactly the UTF-8 the case sent; deleting a draft deletes its message;
  whether deleting a deleted draft answers 2xx or 404 (the case and the cleanup accept either, then
  verify the message is gone).
* A deleted event reads back as 404, 410, or the event with `status: "cancelled"` (the case accepts
  any of them, never a live event); whether deleting a deleted event answers 2xx, 404, or 410 (the
  case and the cleanup accept any of them, then verify the event still reads gone).
* Google's free-text event query matches only where one of its tokens occurs: every event it
  answers, unless cancelled, mentions `yolk` or `conformance` in its summary, description, or
  location, in an attendee's, the organizer's, or the creator's address or name, or in a
  working-location label, building, or desk (observed at the port; the reference names the fields
  Google searches, not how it splits the hyphenated query).
* A Drive listing of `'<folder>' in parents` without `trashed = false` lists the folder's trashed
  children too (the files.list reference says so; the case requires the seeded trashed file).
* Gmail's draft search and Calendar's event query find a draft or event created moments earlier
  (live only: with `GoogleConformanceLookupRecall` on, which the repository's live runner sets, the
  draft and event lifecycle cases run the leftover lookup's search before deleting their item and
  require it there; the committed fixtures and the emulator answer those searches only empty, so
  replay and emulator runs skip the check). The search is retried up to three times over about 6
  seconds, since indexing can lag.

Claims are narrowed to what the connector reads. The error case checks the status the connector
maps and that its message carries the body `error.message`; it does not pin `error.errors` reasons
(the connector reads them only for 403) or the body `status`. The paging cases check
`nextPageToken` and page contents only; the tokens stay opaque. The Drive fields case checks that
the full `fields` selection is accepted (an unknown field name answers 400) and that the fields the
other actions rely on agree, not every optional field. Some checks protect the case's own cleanup
rather than claim connector behavior: whether untrash restores every earlier label is not claimed
(the cleanup re-adds and verifies them), and the listed attachment part `size` is not compared with
the `get_attachment` answer (the connector never relies on them matching).

`GoogleConformanceConfig` holds the seeds: `practiceAddress` (a practice mailbox **the owner
controls**: the only address the send case ever sends to; exactly one plain address `local@domain`,
typed as the branded `GooglePracticeAddress`), `pagingLabelId` (a Gmail user label on 3 to 20
practice messages in 3 to 20 distinct threads, none in Trash or Spam), `attachmentMessageId` (a
practice message with a file attachment Gmail stores apart), `workMessageId` (a practice message,
not in Trash, which the label and trash cases change and restore), `calendarId` (a practice calendar
the account owns), `eventRangeStart` and `eventRangeEnd` (RFC 3339 instants around 3 to 20 events in
it, away from the case events on 2030-01-07), `driveFolderId` (a practice Drive folder with 3 to 20
untrashed items the token may write into; trashed items are not counted), `driveFileId` (a practice
file directly inside it), `driveTrashedFileId` (a practice file directly inside it that is in Trash,
which the trashed-listing case expects; Drive empties Trash after 30 days, so re-trash it within
30 days of a run, or the case fails a `precondition:`), and `runId` (the branded `GoogleConformanceRunId`). Cases never hard-code
account data. `practiceAddress` and `runId` are branded schema types, so a host building the config
by hand constructs them (`GooglePracticeAddress.make(...)`, `GoogleConformanceRunId.make(...)`) or
decodes the whole config with `GoogleConformanceSeeds`; a plain string is a type error. Each case
also decodes every seed it reads again, so a host that bypasses the types (JSON, a cast) is still
refused: a missing or invalid seed fails the case with a `precondition:` mismatch before any
request. Credentials bind through `googleConformanceIntegration` (`google.oauth`, credential ref
`google.conformance`).

### Write ownership and cleanup [#write-ownership-and-cleanup]

The `runId` seed is a per-invocation `run-<hex>` value: the fixtures replay with `run-synthetic`, and
the live runner generates a fresh one every time and never takes it as a flag. Every label name,
draft subject, sent subject, event summary, and folder name a case writes starts with
`yolk-conformance <runId>`.

* The create request (label, draft, trash, event, folder), its decoding, its classification, and
  the registration of what it created run together without interruption, and so does every later
  write (modify, update, untrash, delete). Neither the runner nor the bridges set a request timeout,
  so a hanging request delays an interruption until it answers.
* A definitive rejection (HTTP 4xx other than 408) changed nothing: the case fails and undoes
  **nothing**.
* An ambiguous outcome (a transport or decoding failure, no status, HTTP 408, or HTTP 5xx) may have
  written anyway, and the case never learned what: it fails with `GoogleConformanceActionFailed`
  (`writeOutcome: 'unknown'`) naming the exact label name, draft subject, message, event summary, or
  folder name to check by hand, and undoes nothing.
* Before the case adopts what a create answered (inside the same uninterruptible step, before it
  is registered for cleanup), it proves the item is this run's own: a label with the requested
  name (not a system label), an event with the requested summary and no attendees, a Drive folder
  with the requested name, type, and parent (not a seeded item), the work message itself, and for
  a draft a `format: "metadata"` read of its message showing the `DRAFT` label, the run-scoped
  subject, and no recipient header (a draft answer carries no subject). An answer that is foreign,
  or cannot be verified (the read fails), is never adopted, updated, or deleted: the case fails with
  `GoogleConformanceCleanupRefused` naming it, to check by hand.
* After a successful create, the cleanup undoes the item **by id** (label id, draft id, event id,
  folder id) or by the seeded work message, also after a failed claim or an interruption, and then
  verifies it: the label, draft message, and folder read `google_not_found`, the event reads gone,
  the work message is out of Trash with its earlier labels. A not-found (or, for events, gone)
  answer to the undo counts as undone. A failed cleanup fails with
  `GoogleConformanceRestoreFailed` naming the item and what to do by hand.
* The trash case starts only when the work message is **not** in Trash (so it never untrashes a
  message it did not trash), and its cleanup always runs: it untrashes the message if needed,
  re-adds any earlier label the untrash lost, and verifies them all. It works
  on the same seeded message as the label case, so **concurrent runs are not supported**.

### What the reversible cases leave behind [#what-the-reversible-cases-leave-behind]

* **Gmail labels and drafts** are gone after the cleanup; the draft has no recipient, so nothing
  can be sent from it. The work message gets its earlier labels back; its history id changes.
* **Calendar events** never have attendees, so no invitation, update, or cancellation is ever sent
  to anyone. A deleted event may stay readable through the API as `status: "cancelled"`; it no
  longer shows in the calendar.
* **Drive trash versus delete.** `drive.trash_file` only moves the folder to Trash (recoverable for
  30 days); `drive.delete_file` deletes it permanently without going through Trash. The case does
  both, and its cleanup always deletes permanently, so nothing stays in Trash. Only a failed cleanup
  can leave the folder in Trash, and the leftover lookup reports it there.

### The send is irreversible [#the-send-is-irreversible]

**Gmail cannot unsend.** `google.gmail.send-practice-address` is `write-irreversible`: it never runs
under `allowWrites: 'reversible'`, and a runner starts it only when a person names its exact id
(`allowIrreversible: ['google.gmail.send-practice-address']`; the live runner's
`--allow-irreversible google.gmail.send-practice-address`). It sends exactly one 7-bit message whose
**only** recipient header is `To: <practiceAddress>` (no Cc or Bcc). The case itself decodes
`practiceAddress` again, before building the message or making any request, as exactly one plain
address `local@domain`: no display name, no list (comma or semicolon), no angle brackets or quotes,
no whitespace or control characters (a CR or LF could inject a header), a local part of at most 64
and an address of at most 254 characters. Anything else fails with a `precondition:` mismatch and
no request, whether the host went through the runner or built the config itself. The subject is
`yolk-conformance <runId> send: ...` (the run id is decoded the same way). The message stays in Sent and at the practice address. A
definitive rejection sends nothing. An ambiguous send (a transport failure, no status, HTTP 408,
5xx, or any answer the connector reports as `gmail_send_message_unknown`) fails with
`GoogleConformanceActionFailed` (`writeOutcome: 'unknown'`) naming the subject to look for; never
resend automatically. When the send will run, the live runner prints the run id before any case.

### Leftovers and interruptions [#leftovers-and-interruptions]

Before any write case, and again after an interrupt-only exit, the live runner calls
`findGoogleConformanceLeftovers` and prints a WARN line for each Gmail label named
`yolk-conformance run-*` and each draft a `subject:yolk-conformance` search finds (one page of 100,
search-based, so best effort; with any Gmail seed), the work message when it is in Trash, each
event titled `yolk-conformance run-*` in `calendarId` (at most 4 pages of 250), and each item named
`yolk-conformance run-*` in `driveFolderId`, trashed ones included (at most 4 pages of 100). The
lookup is read-only and bounded; nothing is changed automatically. Messages the send case sent are
its documented residue and are not listed.

In the live runner, the first SIGINT or SIGTERM (Ctrl-C) interrupts the run fiber; the running
case's cleanup is attempted before the process exits, and no further case starts. A cleanup that
fails, or a write whose outcome is unknown, while the case is being interrupted prints its full
message as a WARN line (through the case's `ConformanceCleanupReporter`), the record of the problem;
either way the run ends as a plain interruption with exit code 130 after the leftover lookup runs
again. Further signals within a second count as the same keypress; a later one exits at once and may
skip the cleanup. Run live runs as `pnpm conformance:google …` or
`./node_modules/.bin/tsx scripts/run-google-conformance.ts …`, not `pnpm exec tsx …`, which returns
to the prompt at once on Ctrl-C.

### Token safety and recording [#token-safety-and-recording]

The OAuth access token travels only in the `Authorization: Bearer` header, which the conformance
recorder never records (credential headers are always dropped); the replay ledger redacts it. The
live runner refuses a `GOOGLE_ACCESS_TOKEN` that is not `ya29.` followed by 20 or more letters,
digits, `.`, `_`, or `-` before any request, without printing it. `--record` still refuses to stage,
or print a review checklist for, any recording in which the live token survives anywhere (an echo in
a body, header, or URL; raw, percent-encoded, escaped, or base64-encoded) or that holds a body
outside the guard's inspectable allowlist (strict UTF-8 text without NUL characters), and the
fixture secret scan refuses credential query parameters. A provider can also echo the token into
a field a case reports (a refused label's name, a leftover's title, a failure message), so the
shared live runner prints every line (the report, cleanup WARN lines, leftover warnings, the run's
own failure, the staging checklist) with every raw, percent-encoded, or base64 form of the live
token replaced by `<redacted live token>`. It withholds a line that still holds an escaped form,
or 16 or more consecutive characters of the token raw or base64-encoded (so a report the runner
truncated in the middle of an echoed token is withheld too), and withholds the whole message when
the token only appears once its lines are joined with whitespace removed (a token folded across
lines).

The shipped fixtures are synthetic (`evidence: 'unverified'`, `example.test` addresses). In this
repository, `pnpm conformance:google` dry-runs by default;
`--live --owner-approved --account <label>` (refused whenever `CI` is non-empty) needs `GOOGLE_ACCESS_TOKEN` (a token for the practice
account only, with the scopes of the cases that will run: `gmail.readonly`, `gmail.modify`,
`gmail.compose`, `gmail.send`, `calendar.readonly`, `calendar.events`, `drive.metadata.readonly`,
`drive.file`) and the seeds (`--practice-address`, `--paging-label`, `--attachment-message`,
`--work-message`, `--calendar`, `--event-range-start`, `--event-range-end`, `--drive-folder`,
`--drive-file`). With `drive.file` only, the token may write into `--drive-folder` only when the app
created it or the user opened it with the app. `--allow-writes reversible` adds the write-reversible
cases; `--allow-irreversible google.gmail.send-practice-address` adds the send. `--record` stages
verified recordings only in the gitignored `.conformance-recordings/google/` for manual scrubbing
(addresses, message, thread, draft, label, event, and file ids, subjects, snippets, bodies, names,
page tokens, links) and promotion; staged recordings carry the Gmail API base URL as their
`endpoint`, so set each Calendar and Drive fixture's `endpoint` to its own API base URL when
promoting. See
[Conformance APIs](../api-reference/conformance#connector-conformance) for the bridges.

For offline tests, the experimental [Google emulator](../api-reference/emulators#google-emulator)
(`@yolk-sdk/emulators/google`) is a stateful, fixture-only stand-in that passes these cases through
the real connector actions over the connector ports, including the send (recorded in its state,
never delivered, and accepted only for the seeded practice address), without ever keeping or
echoing the access token. The label-listing, draft-search, free-text-query, and trashed-listing
cases record the leftover lookup's reads, so against the emulator the lookup runs: it finds nothing
on the default seed and reports a run label or run folder the emulator holds. The draft search and
the event query are recorded only empty, so the emulator answers them only while nothing could
match (no draft and no message labelled `DRAFT`; no event mentioning `yolk` or `conformance`,
cancelled ones included, nor such a word in the calendar or the practice address): after the
event cases, whose cancelled run events stay in its state, the lookup fails (HTTP 400
not-emulated) and a runner prints its lookup-failed WARN.


---

# Connectors package

URL: /docs/connectors

Define external API actions and turn them into agent tools.



Use `@yolk-sdk/connectors` when you want reusable, typed actions for external services such as Afloat, Dropbox, Fortnox, generic IMAP/POP3/SMTP email, GitHub, Google Gmail/Calendar/Drive, Kie image and video generation, LinkedIn search, Microsoft Outlook/OneDrive, Notion, Telegram, Todoist, R2, Figma, or custom APIs.

Install:

```bash
pnpm add @yolk-sdk/connectors@canary @yolk-sdk/agent@canary effect@4.2.0
```

## Invoke a connector action [#invoke-a-connector-action]

```ts
import { Effect } from 'effect'
import { makeCredentialBinding, makeIntegration } from '@yolk-sdk/connectors'
import { TelegramBotTokenSlot, TelegramConnector } from '@yolk-sdk/connectors/telegram'

const integration = makeIntegration({
  connectorId: 'telegram',
  config: { chatId: '123456' },
  credentialBindings: [
    makeCredentialBinding({
      slotId: TelegramBotTokenSlot.id,
      credentialRef: 'telegram-bot-token'
    })
  ]
})

const program = TelegramConnector.invoke({
  integration,
  action: 'telegram.send_message',
  input: { message: 'Hello from Yolk' }
})

const result = await Effect.runPromise(program.pipe(Effect.provide(HostConnectorLayer)))
```

`HostConnectorLayer` provides `CredentialResolver`, `ConnectorHttpClient`, and any provider-specific ports.

## Turn connector actions into agent tools [#turn-connector-actions-into-agent-tools]

Wiring fragment; provide host HTTP and credential layers for a separate Google integration:

```ts
import { makeCredentialBinding, makeIntegration } from '@yolk-sdk/connectors'
import { makeConnectorToolModule } from '@yolk-sdk/connectors/agent'
import { GoogleConnector, GoogleOAuthCredentialSlot } from '@yolk-sdk/connectors/google'

const googleIntegration = makeIntegration({
  connectorId: 'google',
  credentialBindings: [
    makeCredentialBinding({
      slotId: GoogleOAuthCredentialSlot.id,
      credentialRef: 'host-google-oauth-credential'
    })
  ]
})

const destructiveGoogleActions = new Set([
  'calendar.delete_event',
  'drive.trash_file',
  'drive.delete_file',
  'gmail.trash',
  'gmail.batch_trash',
  'gmail.delete_permanently',
  'gmail.draft_delete',
  'gmail.delete_label',
  'gmail.send_message'
])

const writingGoogleActions = new Set([
  'calendar.create_event',
  'calendar.update_event',
  'drive.create_folder',
  'gmail.modify_labels',
  'gmail.create_label',
  'gmail.update_label',
  'gmail.untrash',
  'gmail.set_read',
  'gmail.batch_set_read',
  'gmail.batch_set_starred',
  'gmail.batch_modify_labels',
  'gmail.batch_untrash',
  'gmail.draft_compose',
  'gmail.draft_update',
  'gmail.draft_reply'
])

const googleTools = makeConnectorToolModule(GoogleConnector, {
  integration: googleIntegration,
  layer: HostConnectorLayer,
  access: action =>
    destructiveGoogleActions.has(action)
      ? 'destructive'
      : writingGoogleActions.has(action)
        ? 'write'
        : 'read'
})
```

Resolve the module with `@yolk-sdk/agent/tools`, pass the tool definitions into the loop, and execute through the returned tool executor.

## Provider modules [#provider-modules]

| Subpath                                | Use for                                                                                                                                                                     |
| -------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `@yolk-sdk/connectors/afloat`          | Afloat remote MCP auth data                                                                                                                                                 |
| `@yolk-sdk/connectors/dropbox`         | Dropbox metadata, search, file management, and host-only file download                                                                                                      |
| `@yolk-sdk/connectors/email`           | Generic IMAP reads/drafts/message state, POP3 reads, and SMTP submission                                                                                                    |
| `@yolk-sdk/connectors/figma`           | Figma remote MCP auth data                                                                                                                                                  |
| `@yolk-sdk/connectors/fortnox`         | Company, customers, invoices, suppliers, articles, prices, cost centers, payments, offers, inbox, settings, profile, bookkeeping (vouchers, accounts, financial years, SIE) |
| `@yolk-sdk/connectors/github`          | GitHub issues, pull requests, reviews, and repository context for one configured repo                                                                                       |
| `@yolk-sdk/connectors/google`          | Gmail, Calendar, and Drive                                                                                                                                                  |
| `@yolk-sdk/connectors/kie`             | Kie image/video generation tasks (GPT Image 2, Wan 2.7) and task status                                                                                                     |
| `@yolk-sdk/connectors/linkedin-search` | Exa people search and Enrich Layer profile/email                                                                                                                            |
| `@yolk-sdk/connectors/microsoft`       | Microsoft Outlook and OneDrive through Microsoft Graph                                                                                                                      |
| `@yolk-sdk/connectors/notion`          | Notion pages, blocks, databases, data sources, comments, users                                                                                                              |
| `@yolk-sdk/connectors/r2-storage`      | R2 upload URL with host presigner                                                                                                                                           |
| `@yolk-sdk/connectors/telegram`        | Telegram bot send/validate                                                                                                                                                  |
| `@yolk-sdk/connectors/todoist`         | Todoist projects, tasks, labels                                                                                                                                             |

[Fortnox](./fortnox) exposes 51 `read`, 32 `write`, and 19 `destructive` actions through one
`fortnox.oauth` binding. Fortnox scopes themselves permit both read and write; action metadata
helps hosts authorize connector calls but does not narrow the underlying token. Destructive actions
(deletes, payment bookkeeping, creating a voucher, offer conversion, cancellation, emailing, marking sent) need host
approval. Customer-invoice sending and booking are not exposed. Hosts own consent and token
lifecycle.

Microsoft Outlook and OneDrive are exposed from the provider-level `microsoft` subpath because
Microsoft Graph is their shared API and OAuth resource boundary. Workload action ids remain
`outlook.*` and `onedrive.*`, while every scoped slot uses the same `microsoft.oauth` binding. One
credential can therefore cover both workloads when consent includes their `Mail.*` and `Files.*`
permissions.

Outlook inputs use `/me` by default; set `mailbox` for an explicit Exchange Online mailbox.
Delegated message calls use Shared scopes unless `mailbox` matches `OAuthCredential.accountId`
case-insensitively, in the same Graph ID/principal-name form; see [Microsoft mailbox permissions](../integrations/connectors#microsoft).
Application hosts use `mailboxAccessMode: 'application'`. OneDrive inputs use `/me/drive` by default;
set `driveId` for an explicit drive, `oneDriveAccessMode: 'delegated_all'` for broader delegated
permissions, or `oneDriveAccessMode: 'application'` for application tokens. Discovery, metadata,
same-drive move, asynchronous copy, and copy-status polling stay on `onedrive.*` actions. Original file bytes use host-only `downloadOneDriveItem` with
`ConnectorBinaryHttpClient`; create/update use the separate binary-write port. OneDrive resumable sessions remain unimplemented;
host-only `addOutlookAttachment` attaches files to Outlook drafts, with upload sessions for 3–150 MiB. Default Microsoft
tools still need `CredentialResolver` and `ConnectorHttpClient`. The host still owns
Entra tenant policy, OAuth callbacks, refresh, storage, consent,
application resource scoping, Exchange grants, network policy, and file materialization.

Dropbox follows the same split: `dropbox.*` actions cover discovery, metadata, and file management,
while original file bytes use host-only `downloadDropboxFile` with `ConnectorBinaryHttpClient` and
the `files.content.read` scope. Host-only create/update require `files.content.write`.

Google's `gmail.get_thread` action returns normalized messages with decoded message text and
attachment metadata, without raw MIME or attachment content. See the [Connectors
catalog](../integrations/connectors#fetch-a-normalized-gmail-thread) for its required format, its
optional `metadataHeaders` selection (also on `gmail.get_message`, only with `format: 'metadata'`),
and output contract.

Google Drive actions stay in the provider-level `google` subpath and share the existing
`google.oauth` credential binding with Gmail and Calendar. Metadata reads request
`drive.metadata.readonly`; folder creation, trash, and permanent deletion request `drive.file`,
which is limited to files created by or explicitly opened/shared with the app. The host owns OAuth
refresh, consent policy, Google Picker integration, restricted-scope compliance, and binary file
transfer.

Outlook and generic IMAP email support `set_read` (with boolean `isRead`), `set_flag` (with
boolean `isFlagged`), `trash`, and `untrash`
actions in their respective `outlook.*` and `email.*` namespaces, plus `outlook.move_message` for
Graph folder moves. Outlook calls Graph directly;
generic email requires optional host `EmailClient.setRead`, `trash`, and `untrash` methods.
Generic email additionally supports `email.move` to any folder through optional
`EmailClient.move` host support; the destination folder is required and the returned message ID
uses destination UIDVALIDITY/UID when the host can map it.
POP3/SMTP do not support these mailbox-state actions. Restore defaults to the inbox rather than
remembering the original folder. See the [Connectors catalog](../integrations/connectors) for
inputs, permissions, and safe IMAP adapter requirements.

Gmail reports read state from the `UNREAD` label and flag state from the `STARRED` label through
optional `isRead`/`isFlagged` fields (absent when labels are omitted), with matching typed filters
on `gmail.search`, `gmail.list`, and `gmail.list_threads` (one decoded page of thread ids, snippets,
and history ids). `gmail.set_read` flips `UNREAD` via `gmail.modify` consent and returns the
normalized message. Outlook reports `isRead` plus follow-up flag state as `isFlagged` (flagged is
true; not-flagged and completed are false; anything else asserts nothing), with matching typed
filters composed into `$filter` on `outlook.list_messages`. These are provider-native models: Gmail
labels, Outlook flags/folders/categories, and IMAP flags/keywords/folders are not identical, and the
connector never pretends they are.

Explicit batch actions cover 1-100 unique messages with complete per-ID outcomes in `messageIds`
order (`succeeded`, `failed`, `unknown`, `not_attempted`) plus exact summary counts, sanitized codes
only, and provider-safe chunking: Gmail issues individually addressed requests sequentially
(`gmail.batch_set_read`, `gmail.batch_set_starred`, `gmail.batch_modify_labels`,
`gmail.batch_trash`, `gmail.batch_untrash`); Outlook uses Graph JSON batching with at most 20
subrequests per envelope (`outlook.batch_set_read`, `outlook.batch_set_flag`,
`outlook.batch_move`, `outlook.batch_trash`, `outlook.batch_untrash`,
`outlook.batch_modify_categories`); generic email forwards to matching optional host
`EmailClient.batch*` methods. A batch report returns `ActionResult.success` even when every item
failed: success means a valid report exists, not that every mutation worked. `unknown` means the
mutation may or may not have executed, so hosts must reconcile before retrying; cancellation may
prevent a report entirely, and durable reconciliation stays host-owned.

Permanent deletion is a separate destructive batch-shaped action on each provider
(`gmail.delete_permanently`, `outlook.delete_permanently`, `email.delete_permanently`). Gmail
deletes immediately (not trash) and requires opt-in full-mail (`https://mail.google.com/`)
consent, which is never added to combined/default consent; `gmail.modify` is insufficient.
Outlook `permanentDelete` moves items into Recoverable Items/Purges, so retention or holds may
still preserve them: it is not compliance erasure. Generic email deletes exactly the identified
UID-scoped messages without blanket-expunge and claims no backup erasure. Approval, auditing,
retention policy, and reconciliation remain host-owned.

## Manage email labels [#manage-email-labels]

Gmail supports label create/get/update/delete through `gmail.create_label`, `gmail.get_label`,
`gmail.update_label`, and `gmail.delete_label`, alongside existing list and message assignment
via `gmail.modify_labels`. Mutations reuse `gmail.modify` consent.

Outlook exposes `outlook.list_categories`, `outlook.create_category`, and
`outlook.delete_category` with opt-in `MailboxSettings.Read` / `MailboxSettings.ReadWrite`
consent. Message assignment uses category **names**, not IDs: `outlook.set_categories` replaces
all names (`[]` clears), while `outlook.modify_categories` merges additions/removals through a
non-atomic read followed by PATCH. Both use ordinary/shared message write permissions.

Generic email exposes `email.modify_labels` through optional `EmailClient.modifyLabels` host
support. Labels are IMAP keywords, not system flags; hosts preserve unrelated flags and check
server keyword support. `email.set_flag` stars through optional `EmailClient.setFlag` host support,
and Gmail stars through `gmail.set_starred` with the `STARRED` system label. IMAP has no standalone
label catalog, and POP3/SMTP cannot persist labels.
See the [Connectors catalog](../integrations/connectors) for inputs and host contracts.

## Transfer files [#transfer-files]

See [Transfer connector files](./files) for the full capability matrix, raw-byte download/export and
create/update helpers, consent, provider limits, concurrency guarantees and host transport duties.
This also covers Outlook draft attachment uploads, R2, Drive, Fortnox, Notion, email, Telegram, Todoist
and reuse of Afloat/Figma MCP.
Bytes and write helpers are never added to generic connector action serialization.

## What the host provides [#what-the-host-provides]

Your app stores, encrypts, refreshes, revokes, and audits credentials. It also owns OAuth routes, callbacks, consent scopes, identity mapping, authorization, and HTTP execution policy.


---

# Kie conformance

URL: /docs/connectors/kie

Experimental Kie conformance cases for tests and hand-run practice-account checks, and the Kie emulator.



Kie actions are documented in the [connectors package guide](./index) and the
[integrations reference](../integrations/connectors#kie). This page lists the experimental
conformance cases only.

## Conformance cases [#conformance-cases]

> **Experimental.** For tests and hand-run checks against a practice Kie account.

`@yolk-sdk/connectors/kie/conformance` exports conformance cases for `@yolk-sdk/conformance/runner`.
Every case runs the real Kie actions (`kie.get_task`, `kie.create_image_task`,
`kie.create_video_task`) over the connector ports and checks one wire claim the connector relies on.
The actions return only their decoded output, so the envelope `code` and the HTTP status are
observed at the `ConnectorHttpClient` port the host provides; the cases send no request of their own.
The claims are as currently understood; none is observed live yet.

| Case id                       | Safety               | Seeds                    | Claim (as currently understood)                                                                                                   |
| ----------------------------- | -------------------- | ------------------------ | --------------------------------------------------------------------------------------------------------------------------------- |
| `kie.tasks.get-success`       | `read`               | `successTaskId`          | One GET `recordInfo?taskId=` answered HTTP 200, envelope `code` 200, `state: success`, and https result URLs in `resultJson`      |
| `kie.tasks.get-failed`        | `read`               | `failedTaskId`           | A failed task reads HTTP 200 with envelope `code` 200 and `state: fail`, no result URLs, and a non-empty `failMsg` or `failCode`  |
| `kie.errors.task-not-found`   | `read`               | none                     | An unknown task id answers Kie code 404 or 422 (any other code, such as 429 or 455, fails), never a success                       |
| `kie.errors.unauthorized`     | `read`               | none                     | A synthetic invalid key answers code 401 (`kie_unauthorized`), whether as HTTP 401 or as an envelope at HTTP 200                  |
| `kie.tasks.create-image-task` | `write-irreversible` | `runId`                  | One POST `createTask` (GPT Image 2 text-to-image, square at `1K`) answered HTTP 200, envelope `code` 200, a non-empty `taskId`    |
| `kie.tasks.create-video-task` | `write-irreversible` | `firstFrameUrl`, `runId` | One POST `createTask` (Wan 2.7 image-to-video, `720p` for 5 seconds) answered HTTP 200, envelope `code` 200, a non-empty `taskId` |

Claims no live run has settled yet, marked "(unverified: ...)" in each case's `wire`:

* GPT Image 2 results are listed under `resultJson.resultUrls`, not another key.
* Which of `failMsg` and `failCode` a failed task fills, and whether its `resultJson` is null or
  empty.
* An unknown task id answers envelope `code` 422 (`recordInfo is null`) at HTTP 200, or 404.
* An invalid key answers HTTP 401 with envelope `code` 401, or HTTP 200 with envelope `code` 401.
* Kie accepts a create before generating it (a later generation failure shows only in
  `kie.get_task`), and accepts a video task before fetching its first frame.

`KieConformanceConfig` holds the seeds: `successTaskId` (a finished GPT Image 2 task of the practice
account whose state is `success`), `failedTaskId` (a finished task whose state is `fail`),
`firstFrameUrl` (a public https URL of a small still image Kie fetches as the first video frame),
and `runId`. Cases never hard-code account data, and a missing seed fails the case with a
`precondition:` mismatch before any request. Credentials bind through `kieConformanceIntegration()`
(`kie.api_key`, credential ref `kie.conformance`); the unauthorized case swaps the
`CredentialResolver` for the synthetic `kieConformanceInvalidApiKey`.

### The creates are irreversible [#the-creates-are-irreversible]

**Each create case submits a real task that spends Kie credits, and the connector cannot cancel or
delete it.** Both are therefore `write-irreversible`: neither runs under
`allowWrites: 'reversible'`, and a runner starts each only when a person names its exact id (the
live runner's `--allow-irreversible kie.tasks.create-image-task` or
`--allow-irreversible kie.tasks.create-video-task`). Nothing is cleaned up afterwards.

* The prompts name the `runId` seed (`yolk-conformance <runId>: ...`), a per-invocation `run-<hex>`
  value (the fixtures replay with `run-synthetic`; the live runner generates a fresh one every time
  and never takes it as a flag), so each run's tasks are distinct.
* The create, its classification, and the decoding of its observed answer run together without
  interruption; an interruption waits for the answer.
* A definitive rejection created nothing: an HTTP 4xx, or at HTTP 2xx an envelope 4xx (Kie answers
  most failures with HTTP 200 and a non-200 envelope `code`), other than 408 and Kie's 455 (service
  unavailable). The case fails without advice.
* Anything else that is not a 2xx with envelope `code` 200 and a non-empty `taskId` (a transport or
  decoding failure, no status, a 408, 455, or 5xx, an empty `taskId`) is ambiguous: a task may exist
  and spend credits. The case fails with `KieConformanceActionFailed` (`taskOutcome: 'unknown'`)
  naming the run id to look for in the Kie task log; when that happens while the case is being
  interrupted, the message is also handed to `ConformanceCleanupReporter`, which the live runner
  prints as a WARN line.

There is no leftover lookup: the connector reads no task listing, and there is nothing to clean up.

The shipped fixtures are synthetic (`evidence: 'unverified'`): `yolk_synthetic_task_*` task ids,
`example.com` URLs, and only the keys the connector decodes (an allowlist test refuses anything
else). In this repository, `pnpm conformance:kie` dry-runs by default;
`--live --owner-approved --account <label>` (refused whenever `CI` is non-empty) needs `KIE_API_KEY`
(refused before any request unless it has 16 to 256 letters, digits, `_`, or `-`) and the seeds of
the cases that will run. The four reads spend no credits; each create runs only with its exact
`--allow-irreversible` id (`--allow-writes` never starts one). `--record` stages verified recordings
in the gitignored `.conformance-recordings/kie/`; before promoting, replace each recorded 2xx body
wholesale with a minimal synthetic body. See
[Conformance APIs](../api-reference/conformance#connector-conformance) for the bridges.

For offline tests, the experimental [Kie emulator](../api-reference/emulators#kie-emulator)
(`@yolk-sdk/emulators/kie`) is a stateful, fixture-only stand-in that passes these cases, including
both creates (recorded in its state, never readable), without ever keeping or echoing an API key.
Its create route is a connector write whose evidence stays pending until an owner-approved live run
of the two create cases.


---

# LinkedIn search conformance

URL: /docs/connectors/linkedin-search

Experimental LinkedIn search conformance cases for tests and hand-run API checks.



LinkedIn search actions are documented in the [connectors package guide](./index) and the
[integrations reference](../integrations/connectors#linkedin-search). This page lists the
experimental conformance cases only.

## Conformance cases [#conformance-cases]

> **Experimental.** For tests and hand-run checks against the Exa and Enrich Layer APIs.

`@yolk-sdk/connectors/linkedin-search/conformance` exports conformance cases for
`@yolk-sdk/conformance/runner`. Every case runs the real connector actions
(`linkedin_search.search` through Exa, `linkedin_search.profile` and `linkedin_search.email`
through Enrich Layer) over the connector ports, and checks one wire claim the connector relies on.
Answers the actions decode only partly, or not at all (the profile is returned as any JSON value),
are observed at the `ConnectorHttpClient` port the host provides; the cases send no request of
their own. **Every case is a read**: the connector has no write action, so nothing is created,
nothing needs cleaning up, and there is no leftover lookup. The claims are as currently understood;
none is observed live yet.

| Case id                                            | Safety | Seeds              | Claim (as currently understood)                                                                                                                                             |
| -------------------------------------------------- | ------ | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `linkedin-search.search.people-results`            | `read` | `searchQuery`      | Exa accepts the bearer key (unverified) and answers 1 to 10 results, every decoded field a string, never null (unverified); each carries a `url` (a usefulness expectation) |
| `linkedin-search.search.num-results-limit`         | `read` | `searchQuery`      | A control search with `numResults: 3` answers more than 2 people (a precondition); the same query with `numResults: 2` answers 1 or 2                                       |
| `linkedin-search.profile.get-profile`              | `read` | `profileUrl`       | Enrich Layer accepts `linkedin_profile_url` (unverified) and answers a non-empty JSON object                                                                                |
| `linkedin-search.email.lookup-answer`              | `read` | `profileUrl`       | The answer carries an `email` (string or null) or a numeric `email_queue_count` (which one, unverified), and the connector never reports `status: "unknown"`                |
| `linkedin-search.errors.exa-unauthorized`          | `read` | none               | An unknown Exa key answers a 4xx status (unverified: 401), never 2xx or 5xx                                                                                                 |
| `linkedin-search.errors.enrich-layer-unauthorized` | `read` | `profileUrl`       | An unknown Enrich Layer key answers a 4xx status for the profile and the email lookup (unverified: 401), never 2xx or 5xx                                                   |
| `linkedin-search.errors.profile-not-found`         | `read` | `absentProfileUrl` | A profile URL that names no profile answers a 4xx status (unverified: 404), never an empty 2xx profile                                                                      |

Claims no live run has settled yet, marked "(unverified: ...)" in each case's `wire`:

* Exa accepts the API key as `Authorization: Bearer <key>`, which the connector sends (Exa
  documents `x-api-key`).
* Exa omits a missing `author`, `publishedDate`, or `title` rather than answering `null`. The
  connector decodes each of `title`, `url`, `text`, `publishedDate`, and `author` as an optional
  string, so a `null` fails the whole search with `validation_failed`; the case names every null
  field it finds.
* Enrich Layer still accepts the Proxycurl-era `linkedin_profile_url` query parameter that both
  Enrich Layer actions send.
* Which of the two shapes an email lookup answers (an `email` or a queued `email_queue_count`), and
  that a queued lookup answers a number rather than `email_queue_count: null`, which the connector
  would fail to decode.
* An unknown Exa or Enrich Layer key answers HTTP 401, and a profile URL that names no profile
  answers HTTP 404. The cases check only the 4xx class: the connector maps no status specially.

The quirks the cases protect:

* `linkedin_search.profile` returns any 2xx JSON body as the profile, so a missing profile or a
  refused key must come back as a non-2xx status; a 2xx error envelope would be returned as a
  profile. The error cases therefore require a 4xx status, never a 2xx and not a 5xx.
* `linkedin_search.email` reports an answer with neither `email` nor `email_queue_count` as
  `status: "unknown"`, and passes an answered `status` through unchanged. The email case requires
  one of the two fields and checks the connector's own result: its `status` must never be
  `unknown`, whether it falls back to it or Enrich Layer answered it.
* `linkedin_search.search` sends `category: "people"`, `type: "auto"`, `contents: { text: true }`,
  and `numResults` (default 10, a positive integer passed through without a cap). There is no
  paging: one request answers every result. The limit case sends two searches for the seeded query:
  a control with `numResults: 3` (one more than the limit, the smallest paid control), which must
  answer more than 2 people (a `precondition:` mismatch otherwise, since only then can an ignored
  limit show), and then the same query with `numResults: 2`.
* `linkedin_search.profile` returns the 2xx body unchanged as `profile`. That is a property of the
  connector, not a wire claim, so the profile case does not check it.

Not covered: rate limiting. The connector maps every non-2xx answer, 429 included, to the action's
failure code (`linkedin_search_failed`, `linkedin_profile_failed`, `linkedin_email_failed`) with
the HTTP status and the raw body as `underlying`; it reads no `Retry-After` header and sets no
`retryAfterMs`. A practice run cannot provoke a 429 without flooding the APIs, so no case claims it;
a unit test pins the connector's 429 mapping instead. The email lookup for a profile that does not
exist is not covered either: which answer it gets (a 404, or a 2xx with `email: null`) is unknown.

`LinkedInSearchConformanceConfig` holds the seeds: `searchQuery` (an Exa people query that matches
more than two people), `profileUrl` (a public `https://…/in/<slug>` profile URL Enrich Layer can
enrich), and `absentProfileUrl` (a well-formed `https://…/in/<slug>` URL that names no profile). For
`profileUrl`, use a profile whose owner consented to the lookup, for example the repository owner's
own. The case schema accepts any host, so the synthetic fixtures replay on `linkedin.example.com`;
the live runner requires `linkedin.com` profile URLs, so the not-found case exercises a missing
profile rather than URL validation. Cases never hard-code account or people data, and a missing seed
fails the case with a `precondition:` mismatch before any request. Credentials bind through
`linkedInSearchConformanceIntegration()` (`linkedin-search.exa_api_key` with credential ref
`linkedin-search.conformance.exa`, `linkedin-search.enrich_layer_api_key` with credential ref
`linkedin-search.conformance.enrich-layer`);
`linkedInSearchConformanceCredentials({ exaApiKey, enrichLayerApiKey })` keys the two API keys by
slot id for `staticCredentialResolverLayer`. The error cases swap the `CredentialResolver` for one
synthetic key the provider cannot know.

The shipped fixtures are synthetic (`evidence: 'unverified'`): every person, company, and profile
URL is obviously synthetic (`Synthetic Person 01`, `Example Synthetic Co`,
`https://linkedin.example.com/in/synthetic-person-01`), email addresses are on `example.com`, and
no fixture carries an API key or an `authorization` header. Every 2xx fixture body keeps only the
keys and types its case reads, and in this repository a strict allowlist test
(`packages/connectors/test/linkedin-search-conformance.test.ts`, whose comment lists exactly what
it enforces) refuses anything in a 2xx body, request query, or seed that is not obviously
synthetic.

In this repository, `pnpm conformance:linkedin-search` dry-runs by default;
`--live --owner-approved --account <label>` (refused whenever `CI` is non-empty) needs both keys
from the environment only, never a flag: `EXA_API_KEY` and `ENRICH_LAYER_API_KEY`, each refused
before any request unless it has 16 to 256 letters, digits, `_`, or `-`. Neither provider has a
sandbox: these are real, paid keys (use dedicated low-credit ones), and the lookups touch real
people. A live run therefore needs the repository owner's approval even though every case is a read.
Every line a live run prints is redacted of both keys, and `--record` refuses to stage, or print a
review checklist for, any recording, rendered file, or checklist line that carries either key (raw,
percent-encoded, escaped, or base64-encoded), naming which key it found (never the key itself).
Recordings that pass are staged only in the gitignored `.conformance-recordings/linkedin-search/`,
each with its own provider's base URL as `endpoint`, and the review checklist lists every string
value they hold.

**Staged recordings hold real third parties' personal data, and this repository is public.**
Search results name other people, and a profile can carry names, work history, other people's
names and profile links, phone numbers, and image URLs. Never scrub them field by field: replace
each recorded 2xx body wholesale with a minimal synthetic body that keeps only the keys and types
the case reads, with obviously synthetic values (`Synthetic Person 01`,
`https://linkedin.example.com/in/synthetic-person-01`, `example.com` addresses), and replace the
seeded URLs and query in the requests and `seeds.ts` the same way. See
[Conformance APIs](../api-reference/conformance#connector-conformance) for the bridges.

For offline tests, the experimental
[LinkedIn search emulator](../api-reference/emulators#linkedin-search-emulator)
(`@yolk-sdk/emulators/linkedin-search`) is a stateful, fixture-only stand-in for the Exa and Enrich
Layer routes that passes these cases through the real connector actions over the connector ports.
Each answer is a fixture's, byte for byte: the searches the fixtures record (`numResults` 10, 3, and
2 for the seeded query), the seeded profile and its email, the recorded 404 for the seeded absent
profile, and the recorded 401 for a key its seed marks as rejected on that provider (by default the
synthetic invalid keys the two unauthorized cases send). It never keeps or echoes the API key a
request carries as its bearer, a rejected one included (it holds only per-provider digests of the
rejected keys).


---

# Microsoft conformance

URL: /docs/connectors/microsoft

Experimental Microsoft Graph conformance cases for tests and hand-run practice-tenant checks.



Microsoft Outlook, OneDrive, SharePoint and Teams actions are documented in the
[connectors package guide](./index) and the
[integrations reference](../integrations/connectors#microsoft). This page lists the experimental
conformance cases only. `onedrive.resolve_sharing_link`, the Teams channel post and reply sends,
`teams.list_chats` with `lastMessagePreview`, the `modifiedSince` filter, and the host-only
`downloadTeamsMeetingTranscript` have no case yet.

## Conformance cases [#conformance-cases]

> **Experimental.** For tests and hand-run checks against a Microsoft 365 practice tenant.

`@yolk-sdk/connectors/microsoft/conformance` exports conformance cases for
`@yolk-sdk/conformance/runner`. Outlook, OneDrive, SharePoint site, and Teams cases run the real
connector actions. &#x2A;*The
connector has no calendar actions yet:** the calendar cases send raw Graph v1.0 requests through the
same connector ports and pin expected Graph behaviour (unverified until a live run) for hosts and
the emulator. The claims are as currently understood; none is observed live yet.

| Case id                                            | Safety               | Seeds                                                       | Claim (as currently understood)                                                                                                                                                                                                                               |
| -------------------------------------------------- | -------------------- | ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `microsoft.calendar.list-range-returns-events`     | `read`               | `calendarRangeStart`, `calendarRangeEnd`, `calendarEventId` | A calendar view over a populated range returns its events (an empty success is the failure mode); every event overlaps the range as UTC instants                                                                                                              |
| `microsoft.calendar.timestamp-precision`           | `read`               | range seeds, `calendarEventId`, `calendarEventStart`        | Event times come back as seven-digit fractional `dateTime` values (`2026-09-23T12:00:00.0000000`) naming the same instant as the ISO seed; compare instants                                                                                                   |
| `microsoft.calendar.create-returns-event-id`       | `write-reversible`   | none                                                        | Creating an event returns an id that works for GET, PATCH, and DELETE; GET after DELETE is a 404                                                                                                                                                              |
| `microsoft.calendar.cancel-semantics`              | `write-reversible`   | none                                                        | After cancel, GET is a 404 and DELETE a no-op or 404; no attendees, so nothing is sent. Unverified: Graph documents cancel for organizer meetings; if it refuses an attendee-less event, the case becomes manual-only (it would send invitations)             |
| `microsoft.outlook.attachments-listing`            | `read`               | `attachmentMessageId`                                       | Listing returns attachment ids (inline included) that retrieve the same file attachments                                                                                                                                                                      |
| `microsoft.outlook.attachment-content-id`          | `read`               | `attachmentMessageId`                                       | The listing carries no `contentId`; retrieving the inline file attachment returns it                                                                                                                                                                          |
| `microsoft.outlook.paging-next-link`               | `read`               | `pagingFolderId`                                            | A folder larger than the page size (2) returns a `nextLink` the connector accepts and that leads to new messages                                                                                                                                              |
| `microsoft.outlook.immutable-id-survives-move`     | `write-reversible`   | none                                                        | With the immutable-id preference the connector sends, a draft moved to Deleted Items keeps its id                                                                                                                                                             |
| `microsoft.outlook.concurrent-writes-same-message` | `write-reversible`   | none                                                        | Two concurrent draft updates: at least one wins; a loser fails with 409 or 404, never a 5xx                                                                                                                                                                   |
| `microsoft.onedrive.create-folder-roundtrip`       | `write-reversible`   | `driveParentItemId`                                         | A created folder is listed under its parent, deletes cleanly, and GET is then a 404                                                                                                                                                                           |
| `microsoft.onedrive.copy-accepted-monitor`         | `write-reversible`   | `driveId`, `driveParentItemId`, `copySourceItemId`          | A copy answers 202 with one monitor `Location` the connector accepts, completes, and the copy appears in the destination                                                                                                                                      |
| `microsoft.sharepoint.search-finds-site`           | `read`               | `siteSearchQuery`, `siteId`                                 | A keyword site search lists the seeded site; every site id has the three comma-separated parts `sharepoint.list_site_drives` sends literally                                                                                                                  |
| `microsoft.sharepoint.site-drives-libraries`       | `read`               | `siteId`                                                    | The site's drives each have an id, at least one is a `documentLibrary`, and a `null` description decodes                                                                                                                                                      |
| `microsoft.teams.chats-list-members`               | `read`               | none                                                        | Listed chats carry their members (`$expand=members`); `teams.get_chat` with the first listed id returns that chat with members                                                                                                                                |
| `microsoft.teams.chat-messages-paging`             | `read`               | `chatId`                                                    | A chat larger than the page size (2) answers a first page of 1 or 2 messages (Graph may answer fewer than `$top`) and a `nextLink` the connector accepts (Graph may name the chat id unencoded) that leads to new messages; a listed message reads back by id |
| `microsoft.teams.team-channels`                    | `read`               | `teamId`, `channelId`                                       | The joined teams list the seeded team, and the team and its listed channel read back by id as listed                                                                                                                                                          |
| `microsoft.teams.channel-message-replies`          | `read`               | `teamId`, `channelId`, `channelMessageId`                   | Channel listings hold top-level posts only; the seeded post names its team and channel; its replies name it in `replyToId`                                                                                                                                    |
| `microsoft.teams.meeting-transcripts`              | `read`               | `meetingJoinWebUrl`                                         | The join link finds a meeting carrying that link, and its transcripts name that meeting id                                                                                                                                                                    |
| `microsoft.teams.send-chat-message`                | `write-irreversible` | `sendChatId`, `runId`                                       | A plain-text message naming the run id posts as the escaped HTML the connector sent (unverified: Graph may normalize it) and reads back by its id; the message stays in the chat                                                                              |

`MicrosoftConformanceConfig` holds the seeds; `mailbox`, `calendarId`, and `driveId` are optional
(`/me`, the default calendar, and `/me/drive` otherwise). `runId` is the send case's
invocation-unique run id (`run-` then lower-case letters, digits, and hyphens): replay uses the
fixtures' `run-synthetic`, and the repository runner generates a fresh one per invocation. Cases
never hard-code account data, and a missing seed fails the case with a `precondition:` mismatch
before any request. Credentials bind through `microsoftConformanceIntegration` (`microsoft.oauth`,
credential ref `microsoft.conformance`); for a delegated token, set the credential's `accountId` to
the `mailbox` seed so Outlook actions keep ordinary scopes.

Every write-reversible case creates its own event, recipient-free draft, or folder (named with the
`yolk-conformance` marker) and registers its id for cleanup before any claim runs; the create and
the registration are not interruptible (nor is a move that may change a draft's id, with its
registration), and neither the runner nor the bridges set a request timeout, so a hanging create
delays an interruption until it answers. Cleanup is automatic when the id is recoverable: the case
removes the item again (also after a failed assertion or an interruption), keeps it registered
until a 404 proves the removal where Graph allows that check, and also removes a draft under the new
id if a move changed it. A failed removal fails the case with `MicrosoftConformanceRestoreFailed`;
remove the item by hand if it still exists. Some creates need manual recovery because no id is
recoverable: a create that succeeds without an id fails with `MicrosoftConformanceRestoreFailed`,
and an ambiguous create (a transport or decoding failure, no status, HTTP 408, or HTTP 5xx) fails with
`MicrosoftConformanceActionFailed` (`createOutcome: 'unknown'`, keeping its code and status). Both
messages carry the advice; look for `yolk-conformance` items and remove them by hand. A failed
removal, an id-less create, or an ambiguous create raised while the case is being interrupted is
also handed, with its full message, to `ConformanceCleanupReporter` from
`@yolk-sdk/connectors/conformance` (default: `Effect.logWarning`), since the interruption may
replace it (an ambiguous create's report starts with the case id, since several cases share one
create action); a definitive create rejection created nothing and is not reported. The repository
runner (`pnpm conformance:microsoft`) turns a first Ctrl-C into an interruption and prints these
reports on stderr as `WARN` lines. Like the shared runners, it prints every line of a live run (the
report, `WARN` lines, the run's own failure, staging output) with the live access token redacted,
since Graph can echo it into a field a case reports. Removed folders stay in the OneDrive recycle bin, and permanently
deleted drafts may be kept by retention policies. No case sends mail or invitations.

`microsoft.teams.send-chat-message` is `write-irreversible`: it posts one real message to the seeded
send chat (`sendChatId`, a dedicated practice chat kept apart from the paging `chatId`, so the
paging chat stays unchanged) that the connector cannot remove, so a live target runs it only when
its exact id is in `allowIrreversible` (the repository runner's `--allow-irreversible
microsoft.teams.send-chat-message`; `--allow-writes reversible` never starts it). Its text names the
run id (`yolk-conformance <runId>: ...`), which the runner prints before any case. The send is not
interruptible; an ambiguous send (a transport or decoding failure, no status, HTTP 408, or HTTP 5xx)
fails with `MicrosoftConformanceActionFailed` (`sendOutcome: 'unknown'`) naming the run id to look
for in the chat, also through `ConformanceCleanupReporter` when the case is being interrupted; a
definitive 4xx rejection other than HTTP 408 posted nothing. The send never follows a redirect
(`redirect: 'manual'`, `credentials: 'omit'`), so a 3xx is a definitive rejection too and the
message is never posted twice. The Teams and SharePoint site cases need the delegated scopes of
their actions (`Sites.Read.All`, `Chat.Read`, `Team.ReadBasic.All`, `Channel.ReadBasic.All`,
`ChannelMessage.Read.All`, `OnlineMeetings.Read`, `OnlineMeetingTranscript.Read.All`, and
`ChatMessage.Send` for the send); their fixtures are shaped from the Microsoft Graph v1.0 docs
examples, and each fixture's note names its pages.

The shipped fixtures are synthetic (`evidence: 'unverified'`). See
[Conformance APIs](../api-reference/conformance#connector-conformance) for the bridges.

For offline tests, the experimental
[Microsoft Graph emulator](../api-reference/emulators#microsoft-graph-emulator)
(`@yolk-sdk/emulators/microsoft`) is a stateful stand-in that passes these cases through real
connector actions and raw calendar requests over the connector ports.


---

# Notion conformance

URL: /docs/connectors/notion

Experimental Notion conformance cases for tests and hand-run practice-workspace checks.



Notion actions are documented in the [connectors package guide](./index) and the
[integrations reference](../integrations/connectors#notion). This page lists the experimental
conformance cases only.

## Conformance cases [#conformance-cases]

> **Experimental.** For tests and hand-run checks against a practice Notion workspace.

`@yolk-sdk/connectors/notion/conformance` exports conformance cases for
`@yolk-sdk/conformance/runner`. Every case runs the real connector actions over the connector ports
and checks one wire claim the connector relies on. &#x2A;*Every connector action sends
`Notion-Version: 2025-09-03`**; the pinned-version case observes that header at the
`ConnectorHttpClient` port and sends no request of its own. The claims are as currently understood;
none is observed live yet.

| Case id                                | Safety             | Seeds                           | Claim (as currently understood)                                                                                                                                |
| -------------------------------------- | ------------------ | ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `notion.search.cursor-paging`          | `read`             | `searchQuery`                   | `page_size: 1` answers `has_more` and a string `next_cursor`; following it returns new pages and ends with `next_cursor: null` present                         |
| `notion.api.pinned-version-accepted`   | `read`             | none                            | `notion.get_bot_user` sends one request carrying `Notion-Version: 2025-09-03`, and Notion answers the bot user                                                 |
| `notion.errors.error-envelope`         | `read`             | none                            | Errors carry `{ object: "error", status, code, message }` (404 `object_not_found`, 400 `validation_error`); the connector keeps the status and the message     |
| `notion.pages.title-plain-text`        | `read`             | `titlePageId`, `titlePageTitle` | A page has one `title` property of rich text items with `type: "text"` and `plain_text`, joining to the seeded title                                           |
| `notion.blocks.children-cursor-paging` | `read`             | `blocksPageId`                  | `page_size=2` block children answer `object: "list"`, `type: "block"`, `has_more`, and `next_cursor`; following it returns the rest, ending with a null cursor |
| `notion.pages.property-item-paging`    | `read`             | `propertyPageId`, `propertyId`  | Notion accepts a `%XX`-escaped property id percent-encoded again (unverified), and a long property pages item by item (`type: "property_item"`)                |
| `notion.data-sources.database-split`   | `read`             | `databaseId`                    | Under 2025-09-03 a database lists its `data_sources`; the data source holds the schema, and its rows have a `data_source_id` parent (parent shapes unverified) |
| `notion.pages.archive-in-trash`        | `write-reversible` | `parentPageId`                  | `archived: true` answers `archived: true` (`in_trash` not checked); `notion.get_page` still answers (not 404) with `archived: true` (unverified)               |

Claims no live run has settled yet, marked "(unverified: ...)" in each case's `wire`:

* Notion accepts a property id that already contains `%XX` escapes when the connector
  percent-encodes it again (`Syn%3Ap` sent as `Syn%253Ap`); the property's own `next_url` uses the
  single-encoded form. The `propertyId` seed must contain such an escape and be read from the page.
* A data source's `parent` is `{ type: "database_id", database_id }`.
* A data source row's `parent` is `{ type: "data_source_id", data_source_id }`.
* Under 2025-09-03 an archive response still carries `archived` next to `in_trash`.
* A trashed page stays readable through `notion.get_page` (not 404).

`NotionConformanceConfig` holds the seed ids (every seeded page and database must be shared with the
integration). Cases never hard-code account data, and a missing seed fails the case with a
`precondition:` mismatch before any request. Credentials bind through
`notionConformanceIntegration` (`notion.api_token`, credential ref `notion.conformance`).

The write case creates its own page (titled with the `yolk-conformance` marker) under
`parentPageId` and registers its id for cleanup before any claim runs; the create and the
registration are not interruptible, and neither the runner nor the bridges set a request timeout,
so a hanging create delays an interruption until it answers. Any response showing the page trashed
(`archived` or `in_trash` true), or a not-found read after a successful archive, counts as trashed,
so an unverified readback claim that turns out false fails the claim, not the cleanup. Otherwise
the cleanup trashes the page (also after a failed assertion or a fiber interruption) and checks that
`notion.get_page` reports `archived: true`. A failed cleanup fails the case with `NotionConformanceRestoreFailed`, and an
ambiguous create (a transport or decoding failure, no status, HTTP 408, or HTTP 5xx) fails with
`NotionConformanceActionFailed` (`createOutcome: 'unknown'`); both messages carry manual-recovery
advice. Trashed pages stay restorable in the workspace trash until they are deleted from there.

In the live runner, the first SIGINT or SIGTERM (Ctrl-C) interrupts the run fiber, and the cleanup
is attempted before the process exits; no further case starts. The cleanup is not confirmed:

* A cleanup that fails, or a create whose outcome is unknown, while the case is being interrupted
  prints its full message as a WARN line (through the case's `ConformanceCleanupReporter`). The run
  still ends as a plain interruption (exit code 130): the WARN line is the record of the problem.
* After the interruption, the runner repeats the leftover search below.

One Ctrl-C reaches every process of the foreground group, and the wrappers relay it, so further
signals within a second count as the same keypress. A signal a second or more later exits at once
and may skip the cleanup, as does killing the process. Run live runs as
`pnpm conformance:notion …` (pnpm waits for the runner and exits with its code; observed with
pnpm 11) or `./node_modules/.bin/tsx scripts/run-notion-conformance.ts …`. Avoid
`pnpm exec tsx …`: on Ctrl-C it returns to the prompt at once (observed), so the WARN and leftover
lines print after the prompt, `$?` is pnpm's own code rather than the runner's, and a second Ctrl-C
no longer reaches the runner; stop it with `kill -TERM <pid>`, using the pid the first-signal
message prints, at least a second after the first signal.

Before the write case, the runner (`findNotionConformanceLeftovers`) searches read-only for pages titled
`yolk-conformance page...` that are not in the trash and prints a WARN line for each. The search is
bounded and best effort: it reads at most 10 search pages of 100 results, and Notion's search index
can lag behind recent writes. It never trashes them. Check each one, and
trash it by hand when no run is using it.

The shipped fixtures are synthetic (`evidence: 'unverified'`). In this repository,
`pnpm conformance:notion` dry-runs by default; `--live --owner-approved --account <label>` (refused
whenever `CI` is non-empty) needs `NOTION_API_TOKEN` and the seeds, `--allow-writes reversible` adds
the write case, and `--record` stages verified recordings only in the gitignored
`.conformance-recordings/notion/` for manual scrubbing and promotion. See
[Conformance APIs](../api-reference/conformance#connector-conformance) for the bridges.

For offline tests, the experimental
[Notion emulator](../api-reference/emulators#notion-emulator) (`@yolk-sdk/emulators/notion`) is a
stateful, fixture-only stand-in at `Notion-Version: 2025-09-03` that passes these cases through
the real connector actions over the connector ports. The leftover lookup fails against it on a clean
workspace and after the write case: no fixture records a search answer without matches or with a
trashed page, so the emulator answers it not-emulated (HTTP 400) and the runner prints its
lookup-failed `WARN`.


---

# Cloudflare R2 conformance

URL: /docs/connectors/r2-storage

Experimental port-level R2 conformance cases over the host R2Presigner and R2ObjectClient.



The R2 action and host-only object helpers are documented in the
[connectors package guide](./index), [Transfer connector files](./files), and the
[integrations reference](../integrations/connectors#cloudflare-r2). This page lists the experimental
conformance cases only.

## Conformance cases [#conformance-cases]

> **Experimental.** For tests and hand-run checks against a practice bucket through a host
> implementation of the R2 ports.

The R2 connector never talks to R2 itself: `r2_storage.upload_url` asks the host `R2Presigner` for a
presigned PUT URL, and the host-only `getR2Object`, `createR2Object`, and `updateR2Object` go
through the host `R2ObjectClient`. `@yolk-sdk/connectors/r2-storage/conformance` exports port-level
cases for `@yolk-sdk/conformance/runner` that run that real connector code over those ports, plus
`CredentialResolver` and `R2ConformanceConfig` seeds, and check one port claim the connector
relies on each. Port calls are observed by wrapping the ports the host provides. The claims are as
currently understood; none is observed live yet, and the fixtures are synthetic `PortFixture`s.

| Case id                            | Safety               | Seeds                             | Claim (as currently understood)                                                                                                                                                                                                                                                                              |
| ---------------------------------- | -------------------- | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `r2.presign.put-upload-url`        | `read`               | `endpoint`, `bucket`, `runId`     | One `presignPutObject` call with the configured endpoint and bucket, the key, the content type, and both credentials; the URL is an https SigV4 URL for that bucket and key, signed for the access key id the connector passed, with `X-Amz-Expires` from 1 to 604800 and `content-type` signed (unverified) |
| `r2.objects.get-max-bytes`         | `read`               | `endpoint`, `bucket`, `objectKey` | `get` receives the budget's `maxBytes`; below the object size the port itself fails `response_too_large` (code unverified) instead of answering the bytes                                                                                                                                                    |
| `r2.objects.get-expected-etag`     | `read`               | `endpoint`, `bucket`, `objectKey` | `get` with the current etag answers exactly the same bytes; with a stale etag the port fails `conflict`, never the object or an empty success                                                                                                                                                                |
| `r2.objects.get-missing-not-found` | `read`               | `endpoint`, `bucket`, `runId`     | `get` of a key nothing wrote fails `not_found` at the port, never an empty success                                                                                                                                                                                                                           |
| `r2.objects.create-if-absent`      | `write-irreversible` | `endpoint`, `bucket`, `runId`     | `put` with `condition: absent` creates the object; a second create of the same key fails `conflict` instead of overwriting                                                                                                                                                                                   |
| `r2.objects.update-if-match`       | `write-irreversible` | `endpoint`, `bucket`, `runId`     | `put` with a stale etag condition fails `conflict`; with the current etag it answers a new etag (unverified) and the new bytes                                                                                                                                                                               |

Claims no live run has settled yet, marked "(unverified: ...)" in each case's `wire`:

* An R2 host signs path-style URLs (`https://<endpoint host>/<bucket>/<key>`); the case also
  accepts the bucket as a subdomain of the endpoint host.
* The host signs the content type (`X-Amz-SignedHeaders` lists `content-type`), so an upload with
  another type is refused. The connector passes `contentType` to the presigner for exactly this;
  the AWS SDK v3 presigner signs it when the command sets it.
* A host enforcing `maxBytes` fails with `response_too_large`. The port contract only says hosts
  enforce the actual streamed bytes; the connector's own post-buffer check uses that code.
* R2 answers a different ETag when the content of a single PUT changes (the MD5 ETag).

What the presign case cannot observe: a SigV4 query-signed URL does not name its HTTP method, so
"PUT" is only the port's own method (`presignPutObject`, the only one it has); only an upload
through the URL would prove it, and no connector port uploads through a presigned URL. The port
takes no expiry, so the host chooses it; the case checks only that `X-Amz-Expires` is within the
SigV4 limit (7 days). Presigning is local signing: nothing is sent to R2.

`R2ConformanceConfig` holds the seeds: `endpoint` (the S3-compatible endpoint origin, `https`
only), `bucket`, `objectKey` (an existing object of 2 bytes to 1 MB), and `runId`. Cases never
hard-code account data, and a missing seed fails the case with a `precondition:` mismatch before
any port call. Credentials bind through `r2ConformanceIntegration(endpoint, bucket)` (the
`r2-storage.access_key_id` and `r2-storage.secret_access_key` slots, credential refs
`r2ConformanceCredentialRefs`); the presign case sets a synthetic `publicUrl`
(`r2ConformancePublicUrl`).

### Writes are irreversible [#writes-are-irreversible]

**The connector has no delete for R2 objects**, so an object a case writes cannot be removed
through it. Both write cases are therefore `write-irreversible`: they never run under
`allowWrites: 'reversible'`, and a runner starts them only when a person names their exact ids.

* They write only keys under `yolk-conformance/<runId>/`, never a seeded key. The fixtures replay
  with `run-synthetic`. No R2 runner ships, so **the host running the cases live must generate a
  fresh `run-<hex>` for every invocation** (for example `run-` plus 8 random hex digits), never take
  it from a flag or reuse one: a reused id makes the absent-only create answer `conflict`, so the
  write cases fail without writing (definitive). Each run leaves `create-if-absent.txt` and
  `update-if-match.txt` there; delete them by hand when no run is using them.
* Stored bytes are compared exactly (length and every byte), never through a text decoder.
* Each put, the decoding of its answer, and its classification run together without interruption.
  A put counts as having reached the port as soon as the host's `put` is invoked (even when it
  throws), so only a refusal by the connector itself counts as "nothing sent".
* Port failures carry no HTTP status (the connector keeps only the code), so the case classifies a
  put through the shared write-exit classifier this way: a failure before the port was called (the
  connector refused the input) and a port `conflict` (the condition failed: HTTP 412, or a binding
  answering `null`) are definitive, nothing was written; **any other port failure is ambiguous**:
  the object may have been written anyway, and the case fails with `R2ConformanceActionFailed`
  (`writeOutcome: 'unknown'`) naming the exact bucket and key to check by hand, also through
  `ConformanceCleanupReporter` when the case is being interrupted.

There is nothing to clean up and no leftover lookup: `R2ObjectClient` cannot list keys. Look under
`yolk-conformance/` in the practice bucket by hand.

### Presigned URLs in fixtures [#presigned-urls-in-fixtures]

A presigned URL carries its credential in the query string (`X-Amz-Credential` names the access key
id, `X-Amz-Signature` is the signature, `X-Amz-Security-Token` a session token). Committed fixtures
may carry only the synthetic placeholders `r2ConformanceSyntheticSignature` and the whole
`r2ConformanceSyntheticCredential` (`yolk-synthetic-access-key-id/20260930/auto/s3/aws4_request`),
which are exactly the SigV4 entries of the frozen `syntheticPortCredentialParams` of
`@yolk-sdk/conformance/fixture` (one source: the R2 constants are read from it). Run **both** scans
on every R2 fixture:

* The shared `scanPortFixtureForSecrets` finds every credential query parameter in a JSON string,
  the note, or the failure message on its own, and refuses it unless its whole raw value (up to
  `&`, `#`, whitespace, `"`, `<`, `>`, or the end; a raw `?` or `'` and encoded delimiters such as
  `%3F`, `%26`, `%23`, or `%20` stay inside it), percent-decoded, is exactly the placeholder for
  that parameter name. A placeholder with anything appended inside the value, under another
  parameter such as `token=`, or with another date or region is refused; text after a boundary is
  not part of the value and is judged on its own. It also refuses any `accessKeyId`,
  `secretAccessKey`, or `sessionToken` field.
* `findR2PortFixtureSecrets` is the fail-closed backstop for what the shared scan cannot read
  (percent-encoded or escaped names). In every string (and JSON key) it first blanks out the
  canonical placeholder occurrences: `?` or `&` (or the start of the string), `X-Amz-Signature` or
  `X-Amz-Credential` spelled in raw ASCII (any letter case), `=`, and exactly the value the fixtures
  and the scrubber write (`yolk-synthetic-signature`, or the credential with its `/` encoded as
  `%2F`), followed by `&`, `#`, whitespace, `"`, `<`, `>`, or the end. It then searches what remains
  raw and in every variant reachable with up to three rounds of percent-decoding and up to three
  rounds of escape-decoding (JSON `\uXXXX`, `\xXX`, `\\` as one backslash, and numeric HTML
  character references such as `&#88;`), in any order, and refuses ANY case-insensitive occurrence
  of `x-amz-signature`, `x-amz-credential`, or `x-amz-security-token`, with or without `=` or a
  value. So any other value, an encoded or escaped name (even with the exact placeholder), a fully
  or doubly percent-encoded URL, a name escaped by `JSON.stringify` (once or twice) or by an HTML
  serializer, and a credential name mentioned in prose are all refused. It searches every string of
  the fixture (`id`, `port`, `method`, `note`, `observed.account`, the request, the response, and
  the failure code and message), JSON keys included. Deliberate obfuscation (base64, other
  encodings, deeper nesting) is out of scope: a person reviews every recording before promoting it.
  Keep committed notes and messages free of credential names.

`scrubR2PortFixture` rewrites a fixture recorded from a live host before a person promotes it: it
removes credential fields and rewrites every presigned URL in the request, the response, the note,
and the failure message (whole strings and `http(s)://` URLs embedded in text) to the placeholders
(the whole credential is replaced, so a recorded date and region are not kept).
**It does not rewrite percent-encoded or `&amp;`-escaped URLs**, so rerun both scans after
scrubbing and remove whatever they still find by hand. The replayed presign case resolves the
access key credential to `r2ConformanceSyntheticAccessKeyId`, so a scrubbed URL still names the key
the connector passed. The bridge never hands the credentials to a backend: presigner requests are
built without `accessKeyId` and `secretAccessKey` (and `redactPortPayload` strips those names too),
and object requests drop the integration.

For tests, `r2PortsLayerFromBackend` turns any plain-JSON backend
`{ call(port, method, request) }` into both port layers, and `makeR2ReplayBackend(fixtures)`
returns `{ backend, ledger }`:

```ts
import {
  makeR2ReplayBackend,
  r2ConformanceFixtures,
  r2PortsLayerFromBackend
} from '@yolk-sdk/connectors/r2-storage/conformance'

const replay = makeR2ReplayBackend(r2ConformanceFixtures)
const r2Layer = r2PortsLayerFromBackend(replay.backend)
```

The fixture-driven fake in [`@yolk-sdk/emulators/r2`](../api-reference/emulators#r2-emulator) is
itself a backend: pass it directly (`r2PortsLayerFromBackend(makeR2Emulator())`). It keeps a bucket
that decides which fixture answers, so all six cases also run in sequence on one emulator. None of
these (the bridge, the replay backend, or the emulator) is a production adapter. Live verification
needs a host implementation of `R2Presigner` and `R2ObjectClient` connected to a practice bucket:
the connectors package ships no SigV4 signer or S3 client, and the shared connector runner records
HTTP wire fixtures, not port fixtures, so no live R2 runner ships in the repository. See
[Conformance APIs](../api-reference/conformance#connector-conformance) for the fixture type.


---

# Telegram conformance

URL: /docs/connectors/telegram

Experimental Telegram conformance cases for tests and hand-run practice-bot checks.



Telegram actions are documented in the [connectors package guide](./index) and the
[integrations reference](../integrations/connectors#telegram). This page lists the experimental
conformance cases only.

## Conformance cases [#conformance-cases]

> **Experimental.** For tests and hand-run checks against a practice bot and chat.

`@yolk-sdk/connectors/telegram/conformance` exports conformance cases for
`@yolk-sdk/conformance/runner`. Every case runs the real connector actions, or the host-only
`downloadTelegramFile` helper, over the connector ports, and checks one wire claim the connector
relies on. The Telegram actions (`telegram.validate`, `telegram.send_message`) read only the HTTP
status of Bot API answers, never the body's `ok` field, so the cases observe that field at the port
the host provides; they send no request of their own. The host-only `downloadTelegramFile` does
decode the `getFile` result (`file_id`, `file_path`, and the optional `file_size`). The claims are as
currently understood; none is observed live yet.

| Case id                          | Safety               | Seeds             | Claim (as currently understood)                                                                                                                          |
| -------------------------------- | -------------------- | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `telegram.validate.get-chat`     | `read`               | `chatId`          | `telegram.validate` is one POST `getChat` (not `getMe`), answered 2xx with `ok: true` for a chat the bot is in                                           |
| `telegram.errors.error-envelope` | `read`               | `chatId`          | An absent chat and a token that names no bot both answer a 4xx status (not 200, not 5xx) with `ok: false` (exact 4xx unverified; other fields unchecked) |
| `telegram.files.get-file-path`   | `read`               | `fileId`          | `getFile` echoes the `file_id` (unverified) and a relative `file_path`; the file URL answers exactly `file_size` bytes (the seed must report a size)     |
| `telegram.messages.send-message` | `write-irreversible` | `chatId`, `runId` | `sendMessage` answers 2xx with `ok: true`, still accepting `disable_web_page_preview` (unverified); the message stays                                    |

Claims no live run has settled yet, marked "(unverified: ...)" in each case's `wire`:

* `getChat` for a chat the bot is not a member of answers 400 (`chat not found`).
* `getChat` with a token that names no bot answers 401 or 404.
* `getFile` echoes the `file_id` it was given rather than another valid id for the same file;
  `downloadTelegramFile` fails with `invalid_metadata` otherwise.
* `sendMessage` still accepts the deprecated `disable_web_page_preview` field (Bot API 7.0 replaced
  it with `link_preview_options`), which the connector sends on every message.

Not covered: `sendMessage` rate limiting. The connector maps HTTP 429 to `telegram_rate_limited`
without reading `parameters.retry_after`, and a practice run cannot provoke a 429 without flooding
the chat, so no case claims it; the send case treats a 429 as a definitive rejection.

The error-envelope case checks the part of the envelope the connector's status-only reading depends
on: an error comes back as a 4xx status, never as `200` with `ok: false` (which the connector would
report as success) and not as a 5xx (which the send case treats as an unknown outcome). It does not
check `error_code`, `description`, or `parameters`, which the connector never reads.

`downloadTelegramFile` treats `file_size` as optional and checks the byte count only when it is
present. The get-file case therefore requires, as a `precondition:`, a seeded file whose `getFile`
answer reports `file_size`, so the byte-count check is exercised; a size-less answer is a seed
problem, not a claim failure.

`TelegramConformanceConfig` holds the seeds: `chatId` (an integer chat id or `@username` of a
practice chat the bot is a member of), `fileId` (the `file_id` of a small plain UTF-8 text file, at
most 1 MB, the bot received, whose `getFile` answer reports its size), and `runId`. Cases never
hard-code account data, and a missing seed fails the case with a `precondition:` mismatch before any
request. Credentials bind through
`telegramConformanceIntegration(chatId)` (`telegram.bot_token`, credential ref
`telegram.conformance`, integration config `chatId`). The bot token is part of every Bot API URL:
hosts must never log those URLs, and case failures never carry one.

### The send is irreversible [#the-send-is-irreversible]

**`telegram.messages.send-message` posts a real message to the seeded chat, and the connector cannot
delete it** (it has no delete action). The case is therefore `write-irreversible`: it never runs
under `allowWrites: 'reversible'`, and a runner starts it only when a person names its exact id
(`allowIrreversible: ['telegram.messages.send-message']`; the live runner's
`--allow-irreversible telegram.messages.send-message`). Nothing is cleaned up afterwards.

* The message text is `yolk-conformance <runId>: synthetic conformance message, safe to ignore`.
  The `runId` seed is a per-invocation `run-<hex>` value (the fixtures replay with `run-synthetic`;
  the live runner generates a fresh one every time and never takes it as a flag), so each run's
  message is distinct.
* The send, the decoding of its observed answer, and its classification run together without
  interruption; an interruption waits for the answer. Neither the runner nor the bridges set a
  request timeout.
* A definitive rejection (HTTP 4xx other than 408; 429 included) sent nothing: the case fails
  without advice. A 408 (request timeout) counts as ambiguous.
* An ambiguous outcome (a transport or decoding failure, no status, HTTP 408 or 5xx, or a 2xx
  whose body does not carry `ok: true`, which the connector itself would report as sent) may have
  delivered the message anyway: the case fails with `TelegramConformanceActionFailed`
  (`sendOutcome: 'unknown'`) naming the exact text to look for in the chat. When that happens while
  the case is being interrupted, the message is also handed to `ConformanceCleanupReporter`, which
  the live runner prints as a WARN line.

There is no leftover lookup: the Bot API cannot list the messages a bot sent, and there is nothing
to clean up.

In the live runner, the first SIGINT or SIGTERM (Ctrl-C) interrupts the run fiber; a send already in
flight completes first, and no further case starts. The interruption messages point at the chat:
a message the send case posted stays there, starting with `yolk-conformance run-`, and nothing
else is created (there is no leftover advice). When the send is enabled, the runner prints the run
id before any case runs, so the message can be found even after a forced exit. Further signals
within a second count as the same keypress; a later one exits at once. Run live runs as
`pnpm conformance:telegram …` or
`./node_modules/.bin/tsx scripts/run-telegram-conformance.ts …`, not `pnpm exec tsx …`, which returns
to the prompt at once on Ctrl-C.

The shipped fixtures are synthetic (`evidence: 'unverified'`), and their URLs carry the synthetic
`telegramConformanceReplayBotToken` (`123456789:yolk-synthetic-replay-token`). In this repository,
`pnpm conformance:telegram` dry-runs by default; `--live --owner-approved --account <label>`
(refused whenever `CI` is non-empty) needs `TELEGRAM_BOT_TOKEN` (refused before any request unless
it has the `<bot id>:<secret>` shape) and the seeds, and
`--allow-irreversible telegram.messages.send-message` adds the send (`--allow-writes` never does).
`--record` replaces the live bot token with the replay token in every recorded URL, then refuses to
stage, or print a review checklist for, any recording in which the token or its secret part
survives anywhere: URLs, request and response headers, request bodies, text bodies, decoded base64
bodies, stream chunks reassembled as bytes, and every JSON string value after parsing (so `\u`
escapes are undone). It looks for each raw, percent-encoded, `\u`/`\x`/HTML-escaped, and
base64-encoded (standard and URL-safe, at every byte alignment, including MIME-style
folded base64).

What the guard can inspect is an allowlist: **strict UTF-8 text without NUL characters**. Any body,
decoded `bodyBase64`, or reassembled chunk stream that does not decode as strict UTF-8 (a
`TextDecoder` with `fatal: true`), or that contains a NUL, is refused as uninspectable whatever it
contains: binary files, compressed files of any format, images, and UTF-16 text alike, as well as
undecodable base64. **The `fileId` seed must therefore name a plain UTF-8 text file**; any other
download refuses the recording (the case itself still runs and reports normally). Recordings that
pass are staged only in the gitignored `.conformance-recordings/telegram/` for manual scrubbing and
promotion. See
[Conformance APIs](../api-reference/conformance#connector-conformance) for the bridges.

For offline tests, the experimental [Telegram emulator](../api-reference/emulators#telegram-emulator)
(`@yolk-sdk/emulators/telegram`) is a stateful, fixture-only stand-in that passes these cases,
including the send (recorded in its state, never delivered), without ever keeping or echoing the
bot token from the URL path.


---

# Todoist conformance

URL: /docs/connectors/todoist

Experimental Todoist conformance cases for tests and hand-run practice-account checks.



Todoist actions are documented in the [connectors package guide](./index) and the
[integrations reference](../integrations/connectors#todoist). This page lists the experimental
conformance cases only.

## Conformance cases [#conformance-cases]

> **Experimental.** For tests and hand-run checks against a practice Todoist account.

`@yolk-sdk/connectors/todoist/conformance` exports conformance cases for
`@yolk-sdk/conformance/runner`. Every case runs the real connector actions over the connector ports
against the Todoist API v1 (`https://api.todoist.com/api/v1`), and checks one wire claim the
connector relies on. The claims are as currently understood; none is observed live yet.

| Case id                                  | Safety             | Seeds                    | Claim (as currently understood)                                                                                                                         |
| ---------------------------------------- | ------------------ | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `todoist.tasks.list-cursor-paging`       | `read`             | `pagingProjectId`        | `limit=2` answers at most two tasks and a string `next_cursor`; the cursor with the same `project_id` returns the rest, ending with `next_cursor: null` |
| `todoist.errors.not-found-envelope`      | `read`             | none                     | An unknown task id answers HTTP 404 (`todoist_not_found`) with a JSON `error` string that ends the connector message (both unverified)                  |
| `todoist.labels.task-labels-are-names`   | `read`             | `labeledTaskId`          | A task's `labels` are label names, each the `name` of a personal label `todoist.list_labels` returns                                                    |
| `todoist.projects.list-cursor-paging`    | `read`             | `pagingProjectId`        | The leftover lookup's `limit=200` listing answers every project once, the paging project among them; `limit=1` pages chain to the same projects         |
| `todoist.tasks.lifecycle-close`          | `write-reversible` | `workProjectId`, `runId` | Create, get, and update answer the task; `close_task` answers 2xx; `list_tasks` then omits the closed task (active tasks only)                          |
| `todoist.tasks.due-dates`                | `write-reversible` | `workProjectId`, `runId` | `due_date` and `due_datetime`, as the connector sends them, answer a task whose `due.date` starts with `2030-01-15` (timed form unverified)             |
| `todoist.projects.parent-id`             | `write-reversible` | `workProjectId`, `runId` | `create_project` with a parent answers `parent_id`, and `get_project` reads it back                                                                     |
| `todoist.projects.delete-then-not-found` | `write-reversible` | `workProjectId`, `runId` | After `delete_project`, `get_project` answers 404 and a task that was in it answers not found (both unverified)                                         |

Claims no live run has settled yet, marked "(unverified: ...)" in each case's `wire`:

* An unknown, well-formed task id answers HTTP 404, not 400.
* The API v1 error body is `{ error, error_code, error_extra, error_tag, http_code }`; the connector
  uses the first non-empty string of `error`, `message`, `error_description`, `error_tag`.
* A timed due (`due_datetime` `2030-01-15T12:00:00Z`) keeps its day at the start of `due.date` in the
  account's time zone (noon UTC stays on that day from UTC-12 to UTC+11). Use a practice account
  whose time zone is in that range: in UTC+12 to UTC+14 the timed due can land on the 16th and the
  case fails without any connector fault.
* A deleted project answers 404 rather than a body marked `is_deleted`.
* Deleting a project deletes its tasks.
* The project listing includes sub-projects (the leftover lookup needs it for the case projects
  under the work project).

The due-dates case checks that the due was applied, and nothing more: after each call the answer's
`due` must be an object whose `date` starts with `2030-01-15`, so a due field Todoist ignored (for
example an answer with `due: null`) fails it. `TodoistTask.due` reaches hosts untyped and the
connector reads nothing inside it, so the case does not claim how Todoist represents a due
(`is_recurring`, or where a timed due keeps its time).

The last two claims matter to the write cases' own cleanup, in different ways:

* **Project absence is verified by every cleanup.** Each write case deletes its project by id and
  then requires `todoist.get_project` to answer not found. If a deleted project answered anything
  else, every write case would report `TodoistConformanceRestoreFailed` (check by hand) rather than
  pass silently.
* **Task removal is not.** The cleanup never looks for the tasks a case created: it relies,
  unverified, on Todoist deleting a project's tasks with it. Only the delete case checks that, by looking up its
  task after deleting the project; if the task survived, that case fails its claim (a mismatch, not a
  restore failure), and the other write cases' cleanups would still pass while leaving their tasks
  behind. The delete case's failure names the surviving task's id; look for `yolk-conformance task`
  tasks by hand if it ever fails that way.

`TodoistConformanceConfig` holds the seed ids and the `runId`. Cases never hard-code account data,
and a missing seed fails the case with a `precondition:` mismatch before any request. Credentials
bind through `todoistConformanceIntegration` (`todoist.api_token`, credential ref
`todoist.conformance`). The personal labels on the `labeledTaskId` task must be listed by
`todoist.list_labels` (shared-only labels are not).

Every write case creates its own project `yolk-conformance-<runId>-<case>` under `workProjectId`
and works only inside it. The `runId` seed makes that namespace unique per invocation: the fixtures
replay with `run-synthetic`, and the live runner generates a fresh random id every time (it is never
a flag). The cleanup is attempted and verified under these conditions:

* The project create request, its decoding, and the registration of the created project's id run
  together without interruption, and so does every later write (task create, update, close,
  project delete): an aborted request could otherwise land after the cleanup. Neither the runner
  nor the bridges set a request timeout, so a hanging request delays an interruption until it
  answers.
* A definitive create rejection (HTTP 4xx other than 408, for example the account's project limit)
  proves the case created nothing: it fails and deletes **nothing**.
* An ambiguous create (a transport or decoding failure, no status, HTTP 408, or HTTP 5xx) may still
  have created the project, and the case never learned its id: it fails with
  `TodoistConformanceActionFailed` (`createOutcome: 'unknown'`) naming the exact project to check by
  hand. Project names are not unique, so the case never deletes by name. An ambiguous task create
  names the task the same way; it would sit inside the case project, which the cleanup deletes.
* After a successful create, the cleanup deletes the project **by id** (a not-found answer proves it
  gone) and checks that `todoist.get_project` then answers not found. It also runs after a failed
  assertion or a fiber interruption. A failed cleanup fails with `TodoistConformanceRestoreFailed`
  naming the project and its id.
* A create that answers a project without the requested run-scoped name or with the id of a seeded
  project, or a task outside the case project, is never deleted: the case fails with
  `TodoistConformanceCleanupRefused` naming it. The project's `parent_id` is not an ownership rule:
  a fresh project answered under another parent fails the parent-id claim and is still deleted by
  id.

Todoist's free plan limits the number of active projects; each write case holds one extra project
while it runs.

In the live runner, the first SIGINT or SIGTERM (Ctrl-C) interrupts the run fiber, and the running
case's cleanup is attempted before the process exits; no further case starts. The cleanup is not
confirmed:

* A cleanup that fails, or a create whose outcome is unknown, while the case is being interrupted
  prints its full message, with the exact project, as a WARN line (through the case's
  `ConformanceCleanupReporter`). The run still ends as a plain interruption (exit code 130): the
  WARN line is the record of the problem.
* After the interruption, the runner repeats the leftover lookup below and print a WARN line for every `yolk-conformance-run-*` project still
  present.

One Ctrl-C reaches every process of the foreground group, and the wrappers relay it, so further
signals within a second count as the same keypress. A signal a second or more later exits at once
and may skip the cleanup, as does killing the process. Run live runs as
`pnpm conformance:todoist …` or `./node_modules/.bin/tsx scripts/run-todoist-conformance.ts …`.
Avoid `pnpm exec tsx …`: on Ctrl-C it returns to the prompt at once, so later lines print after the
prompt; stop the runner with `kill -TERM <pid>`, using the pid the first-signal message prints.

Before any write case, the runner lists projects read-only (`findTodoistConformanceLeftovers`) and
prints a WARN line for each active project whose name starts with `yolk-conformance-run-`
(`todoistConformanceRunProjectPrefix`) that an earlier run left behind, wherever it sits; a failed
lookup prints its failure code. The lookup is bounded, not exhaustive: it reads at most 20 listing
pages of 200 projects each. It never deletes them. Check each one, and delete it by hand when no run
is using it. Every valid `runId` starts with `run-`, so the lookup covers every run.

The shipped fixtures are synthetic (`evidence: 'unverified'`). In this repository,
`pnpm conformance:todoist` dry-runs by default; `--live --owner-approved --account <label>` (refused
whenever `CI` is non-empty) needs `TODOIST_API_TOKEN` and the seeds, `--allow-writes reversible`
adds the write cases, and `--record` stages verified recordings only in the gitignored
`.conformance-recordings/todoist/` for manual scrubbing and promotion. There are no
write-irreversible Todoist cases. See
[Conformance APIs](../api-reference/conformance#connector-conformance) for the bridges.

For offline tests, the experimental [Todoist emulator](../api-reference/emulators#todoist-emulator)
(`@yolk-sdk/emulators/todoist`) is a stateful, fixture-only stand-in that passes these cases
through the real connector actions over the connector ports. The project paging case records the
leftover lookup's project listing, so against the emulator the lookup runs: it finds nothing on
the default seed and reports a `yolk-conformance-run-*` project the emulator holds.


---

# Cookbook

URL: /docs/cookbook

Practical recipes for combining Yolk packages in an app.



## Build a stateless `/api/agent` route [#build-a-stateless-apiagent-route]

1. Accept a request containing `AgentMessage[]`.
2. Decode/validate at the route boundary.
3. Resolve enabled tools for the user/session.
4. Call `runRuntime({ _tag: 'Transcript', ... }, config)`.
5. Provide provider, loop, context transformer, and tool executor layers.
6. Encode each `AgentEvent` as NDJSON or SSE.

Use this shape for simple chat where the client sends the full transcript every turn.

## Build a durable session runtime [#build-a-durable-session-runtime]

1. Implement `SessionEventStore` against your DB, Durable Object storage, or append log.
2. On new input, call `runRuntime({ _tag: 'AppendInput', ... }, config)`.
3. On approval/question response, call `runRuntime({ _tag: 'AppendHitlResponse', ... }, config)`.
4. Replay stored events to rebuild transcript and client state.

Use this shape when reconnect, resume, HITL, or server-owned transcript state matters.

## Add remote MCP tools to an agent [#add-remote-mcp-tools-to-an-agent]

1. Load host-owned MCP server config.
2. Call `listMcpTools` or `listRemoteMcpServerTools`.
3. Register each returned `def` as a tool with `decodeOutput: mcpToolOutputDecoder` (or pass the
   defs into the loop yourself).
4. When the model calls one, call `callMcpServerTool`; outside `resolveTools`, pass
   `fileCapture: makeToolFileCapture({ store })` so its blobs are stored, not lost.
5. Return the resulting Yolk `ToolResult` (`structuredContent` `{ value, files }`) to the loop.

Persist MCP server config and credentials outside the package.

## Add knowledge search [#add-knowledge-search]

1. Implement `SearchIndexStore`.
2. Provide extractor, chunker, embedder, and summarizer layers.
3. Ingest documents with `ingestKnowledgeDocument`.
4. Search with `searchKnowledge`.
5. Optionally expose `makeKnowledgeLookupTool` to the agent.

Resolve search scope from your authenticated app context.

## Add external API actions [#add-external-api-actions]

1. Create or choose a connector.
2. Build a `ConnectorIntegration` with config and credential refs.
3. Provide `CredentialResolver` and `ConnectorHttpClient`.
4. Invoke actions directly or expose them with `makeConnectorToolModule`.

Store raw credentials only in host-owned secret storage.

## Add command execution [#add-command-execution]

1. Choose a sandbox provider layer, such as Vercel Sandbox.
2. Provide durable sandbox state storage.
3. Scope `sandboxSessionId` to your user/session/run.
4. Expose `makeSandboxToolModule` only where command execution is allowed.
5. Add approval, audit, cleanup, and UI.


---

# Add a tool

URL: /docs/guides/add-tool

Define a typed tool with Effect Schema and pass it to an agent loop.



Tools let the model ask your app to do work.

## Define the tool [#define-the-tool]

```ts
import { Effect, Schema } from 'effect'
import { makeTool } from '@yolk-sdk/agent/tools'

const WeatherParams = Schema.Struct({
  city: Schema.String
})

const Weather = Schema.Struct({
  city: Schema.String,
  condition: Schema.String
})

export const weatherTool = makeTool({
  name: 'get_weather',
  description: 'Get the current weather for a city.',
  parameters: WeatherParams,
  output: Weather,
  access: 'read',
  // Optional: model-facing prose. Without it the model sees the compact JSON of the output.
  render: weather => `Weather in ${weather.city}: ${weather.condition}`,
  execute: ({ params }) => Effect.succeed({ output: { city: params.city, condition: 'sunny' } })
})
```

`makeTool` uses your Effect Schema to validate model input and generate the JSON Schema exposed to the model. The advertised document may add root `type: "object"` to typeless object-only `anyOf`/`oneOf` unions for strict upstreams; execution still validates against your original Schema.

With `output`, `execute` returns `{ output }`: Yolk encodes it with the schema's JSON codec into `structuredContent` (what code mode scripts read) and shows the model `render(value, files)` or, by default, the compact JSON of the encoding. Tools without `output` return `{ content }` (text, plus file parts). File fields are `ToolFile` ([Typed outputs and file fields](../agent/tools-hitl#typed-outputs-and-file-fields)).

## Resolve tools for a request [#resolve-tools-for-a-request]

```ts
import { Effect } from 'effect'
import { resolveTools } from '@yolk-sdk/agent/tools'

const toolModule = {
  id: 'weather',
  tools: [weatherTool]
}

const toolSet = await Effect.runPromise(resolveTools([toolModule], requestContext))
```

Pass `toolSet.tools` into `run` or `runRuntime`. Use `toolSet.execute` inside your `ToolExecutor` layer.

## Access levels [#access-levels]

| Access        | Use for                                            |
| ------------- | -------------------------------------------------- |
| `read`        | search, fetch, inspect                             |
| `write`       | create/update external state                       |
| `destructive` | shell commands, delete, send irreversible messages |

The SDK records access. Your host decides whether to approve, deny, log, or hide a tool.


---

# Build a chat route

URL: /docs/guides/build-chat-route

Create a Next.js route that accepts Yolk messages and streams NDJSON agent events.



This guide builds the route your UI can call for a stateless chat turn.

## Install [#install]

```bash
pnpm add @yolk-sdk/agent@canary effect@4.2.0
```

## Route shape [#route-shape]

Your route should:

1. decode the request body into app-owned input
2. resolve enabled tools for that user/session
3. call `runRuntime` with `_tag: 'Transcript'`
4. provide provider/tool Effect layers
5. stream each `AgentEvent` as NDJSON

## Minimal route [#minimal-route]

```ts
import { Effect, Layer, Stream } from 'effect'
import { runRuntime } from '@yolk-sdk/agent/runtime'
import { makeToolExecutorLayer, resolveTools } from '@yolk-sdk/agent/tools'

const encoder = new TextEncoder()

export async function POST(request: Request) {
  const input = await request.json()
  const toolSet = await Effect.runPromise(
    resolveTools([HostToolModule], { sessionId: input.sessionId })
  )

  const events = runRuntime(
    {
      _tag: 'Transcript',
      sessionId: input.sessionId,
      messages: input.messages
    },
    {
      systemPrompt: 'You are a helpful assistant.',
      tools: toolSet.tools,
      model: input.model ?? 'gpt-5.5'
    }
  )

  const RuntimeLayer = Layer.mergeAll(AppAgentLayerWithoutTools, makeToolExecutorLayer(toolSet))

  const body = new ReadableStream<Uint8Array>({
    start(controller) {
      Effect.runPromise(
        events.pipe(
          Stream.runForEach(event =>
            Effect.sync(() => {
              controller.enqueue(encoder.encode(`${JSON.stringify(event)}\n`))
            })
          ),
          Effect.provide(RuntimeLayer)
        )
      ).then(
        () => controller.close(),
        error => controller.error(error)
      )
    }
  })

  return new Response(body, {
    headers: { 'content-type': 'application/x-ndjson' }
  })
}
```

`HostToolModule` and `AppAgentLayerWithoutTools` are yours. Resolve tools from server-side policy, then provide `makeToolExecutorLayer(toolSet)` alongside your provider, loop config, and context transformer layers.

## Production checklist [#production-checklist]

* validate `input.messages` before calling the runtime
* choose tools from server-side policy, not client input
* keep provider secrets server-side
* map thrown stream errors to safe terminal `AgentError` events
* set cache headers to disable buffering

## Related APIs [#related-apis]

* `runRuntime` from `@yolk-sdk/agent/runtime`
* `AgentEvent`, `AgentMessage` from `@yolk-sdk/agent/protocol`
* `streamAgentEventStreamUntilTerminal` from `@yolk-sdk/agent/client`


---

# Implement durable compaction

URL: /docs/guides/durable-compaction

Keep full session history while sending compacted context to models.



Durable compaction lets long-lived agents keep their complete raw transcript for UI, audit, and
export while sending a smaller projected context to the model.

Use this guide when your app stores agent conversations in a database, append log, Durable Object,
or workflow-owned state.

## What you will build [#what-you-will-build]

You will build a host-owned compaction layer with this shape:

```txt
raw history      = append-only messages and compaction rows
model context    = latest checkpoint message + messages after it
runtime writes   = newly created messages only
summary storage  = durable compaction payload, not a synthetic transcript message
```

Yolk provides protocol helpers, planning helpers, checkpoint formatting, transcript formatting, and
one-shot context-overflow retry. Your app owns storage, summary generation, thresholds, auth, and
active-run guards.

## Prerequisites [#prerequisites]

* A server-owned transcript or session log.
* A model provider layer for normal model calls.
* A transaction or compare-and-set guard for appending messages.
* A place to store compaction payloads beside messages.

## Install [#install]

```bash
pnpm add @yolk-sdk/agent@canary effect@4.2.0
```

## Design the ledger [#design-the-ledger]

Store raw protocol messages and compaction payloads as first-class rows. Do not overwrite older
messages with the summary.

This is a host-owned shape, not an SDK schema:

```ts
import type { AgentMessage } from '@yolk-sdk/agent/protocol'

type HostConversationEntry =
  | {
      readonly kind: 'message'
      readonly sessionId: string
      readonly revision: number
      readonly seq: number
      readonly message: AgentMessage
      readonly runId?: string
    }
  | {
      readonly kind: 'compaction'
      readonly sessionId: string
      readonly revision: number
      readonly seq: number
      readonly compaction: HostCompactionPayload
      readonly runId?: string
    }

type HostCompactionPayload =
  | {
      readonly _tag: 'Completed'
      readonly reason: 'auto' | 'manual' | 'overflow'
      readonly summary: string
      readonly recent: string
      readonly compactedThroughSeq: number
      readonly createdAtMs: number
      readonly tokensBefore?: number
      readonly tokensAfter?: number
    }
  | {
      readonly _tag: 'Failed'
      readonly reason: 'auto' | 'manual' | 'overflow'
      readonly message: string
      readonly createdAtMs: number
    }
```

Production stores usually also keep a small session state row with the active revision, next sequence
number, usage, active run id, and HITL state.

## Project messages for the model [#project-messages-for-the-model]

Before any completed compaction exists, send the full active transcript. After compaction, send one
synthetic checkpoint message plus messages appended after the compaction row. The projection below
expects rows already filtered to one session's active revision and sorted by ascending `seq`.

This fragment shows the projection:

```ts
import { makeCompactionCheckpointMessage } from '@yolk-sdk/agent/compaction'
import type { AgentMessage } from '@yolk-sdk/agent/protocol'

const projectMessagesForModel = (
  rows: ReadonlyArray<HostConversationEntry>
): ReadonlyArray<AgentMessage> => {
  const latestCompaction = rows
    .filter(row => row.kind === 'compaction' && row.compaction._tag === 'Completed')
    .at(-1)
  const messages = rows.filter(row => row.kind === 'message')

  if (latestCompaction === undefined) {
    return messages.map(row => row.message)
  }

  const checkpoint = makeCompactionCheckpointMessage({
    summary: latestCompaction.compaction.summary,
    recent: latestCompaction.compaction.recent,
    createdAtMs: latestCompaction.compaction.createdAtMs
  })
  const laterMessages = messages
    .filter(row => row.seq > latestCompaction.seq)
    .map(row => row.message)

  return [checkpoint, ...laterMessages]
}
```

Do not persist the checkpoint returned by `makeCompactionCheckpointMessage` as a raw message. It is a
model-input projection only.

If you use [host instructions](/docs/agent/loop-runtime#host-instructions) (for example the code
mode catalog), keep the instruction messages the checkpoint folds away: put
`latestInstructionMessages(compacted)` from `@yolk-sdk/agent/protocol` after the checkpoint, minus
keys that `laterMessages` already carry. The loop compares instruction state with the full
transcript and never re-appends them.

## Plan when to compact [#plan-when-to-compact]

Use the same token estimate you use for model-context warnings. `planWindowCompaction` keeps a recent
tail and avoids splitting tool results away from recent assistant tool calls.

This fragment plans an automatic compaction:

```ts
import {
  contextBudgetStatus,
  estimateAgentMessagesTokens,
  makeContextBudget,
  planWindowCompaction
} from '@yolk-sdk/agent/compaction'
import type { AgentMessage } from '@yolk-sdk/agent/protocol'

const budget = makeContextBudget({
  contextWindowTokens: 200_000,
  reservedOutputTokens: 8_000,
  warningRatio: 0.75,
  compactionRatio: 0.9
})

declare const hostCountTextTokens: (text: string) => number

const estimateTokens = (messages: ReadonlyArray<AgentMessage>) =>
  estimateAgentMessagesTokens(messages, {
    countTextTokens: hostCountTextTokens
  })

const planCompaction = (messages: ReadonlyArray<AgentMessage>) => {
  const inputTokens = estimateTokens(messages)

  if (contextBudgetStatus(inputTokens, budget) !== 'compact') {
    return { _tag: 'Skip' as const }
  }

  return planWindowCompaction(messages, {
    thresholdTokens: budget.compactionInputTokens,
    estimateTokens
  })
}
```

The planner does not call a model. It only chooses which messages to summarize and which messages to
keep as recent context. Without `countTextTokens`, Yolk uses a provider-neutral character heuristic
plus fixed message and media overhead. A synchronous host tokenizer improves selected message text,
reasoning, and host tool-call estimates only. Exact provider-request accounting must also include the
system prompt, tool definitions, vendor framing, and a safety margin. Reuse the same
`estimateTokens` function for warnings, planning, transformers, and before/after checks.

## Generate and store a summary [#generate-and-store-a-summary]

Generate the summary with your app's provider configuration, then persist it as a compaction row.

Use `formatAgentMessagesForCompaction` to serialize messages into summary input. It includes user
text, assistant text/reasoning, host and provider tool calls/results, and truncated tool parameters
and results. This format is intentionally lossy: it omits message envelope metadata, structured tool
result content, and error flags. Supply a host formatter when those fields matter to the summary.

This fragment shows the summary boundary:

```ts
import {
  compactionSummarySourceMessages,
  formatAgentMessagesForCompaction,
  makeCompactionCheckpointMessage
} from '@yolk-sdk/agent/compaction'

const summarizeAndPersist = async (input: {
  readonly plan: Extract<ReturnType<typeof planCompaction>, { readonly _tag: 'Compact' }>
  readonly previousCompaction?: {
    readonly summary: string
    readonly recent: string
  }
  readonly expectedSeq: number
}) => {
  const messagesForSummary = compactionSummarySourceMessages({
    hasPreviousSummary: input.previousCompaction !== undefined,
    messages: input.plan.compactedMessages
  })
  const formattedHistory = formatAgentMessagesForCompaction(messagesForSummary)
  const summary = await hostSummarizeCompaction({
    previousSummary: input.previousCompaction?.summary,
    previousRecent: input.previousCompaction?.recent,
    history: formattedHistory
  })
  const recent = formatAgentMessagesForCompaction(input.plan.recentMessages)
  const createdAtMs = Date.now()
  const payload = {
    _tag: 'Completed' as const,
    reason: 'auto' as const,
    summary,
    recent,
    compactedThroughSeq: input.expectedSeq,
    createdAtMs,
    tokensBefore: input.plan.beforeTokens,
    tokensAfter: estimateTokens([makeCompactionCheckpointMessage({ summary, recent, createdAtMs })])
  }

  if (payload.tokensAfter >= input.plan.beforeTokens) {
    return { _tag: 'Skipped' as const }
  }

  await hostAppendCompaction({
    expectedSeq: input.expectedSeq,
    payload
  })

  return { _tag: 'Compacted' as const, payload }
}
```

`hostSummarizeCompaction` and `hostAppendCompaction` are app-owned. Your storage append should verify
the active run id and expected sequence so a stale run cannot compact or append to a newer transcript.
When a previous compaction exists, the summarizer must fold both its `summary` and `recent` text into
the new summary before the leading synthetic checkpoint is dropped.

## Retry provider context overflow once [#retry-provider-context-overflow-once]

Providers can still reject a request when their exact token accounting differs from your estimate.
Wrap the provider with `makeContextOverflowRetryProvider` to compact and retry once when the provider
raises `LLMError` with `cause: 'context_overflow'`.

This fragment wires the retry wrapper:

```ts
import { Effect, Ref } from 'effect'
import { makeContextOverflowRetryProvider } from '@yolk-sdk/agent/compaction'

const messagesRef = await Effect.runPromise(Ref.make(projectedMessages))
const retryProvider = await Effect.runPromise(
  makeContextOverflowRetryProvider({
    provider: appProvider,
    messagesRef,
    compact: messages =>
      maybeCompactAndProject({
        reason: 'overflow',
        messages
      })
  })
)
```

The compactor returns either:

```ts
type ContextOverflowRetryCompactionResult =
  | { readonly _tag: 'Compacted'; readonly messages: ReadonlyArray<AgentMessage> }
  | { readonly _tag: 'Skipped'; readonly messages: ReadonlyArray<AgentMessage> }
```

If compaction succeeds, Yolk retries the provider call once with the compacted messages. If compaction
is skipped or the compactor fails, the original overflow fails normally. A retry-provider failure,
including a second overflow, propagates from the retry stream.
The retry budget resets for each `provider.stream(...)` call and only intercepts tagged `LLMError`
values with `cause: 'context_overflow'`. `messagesRef` is an optional host side channel; the wrapper
updates it after successful compaction but does not persist or replace runtime transcript state.

Use this wrapper only when the provider reports context overflow before emitting deltas. It does not
retract already-emitted text/usage or emit compaction lifecycle events before starting the retry.

For private media, put host authorization/signing **inside** this retry wrapper. The compactor then
works on refs, and each provider attempt resolves fresh URLs from its effective context. See
[Resolve private attachments](./private-attachments) for the tested composition and limits.

## Persist only new messages [#persist-only-new-messages]

When a model or tool step finishes, append only messages created by that step:

* user input rows from user actions
* assistant message rows from model steps
* tool-result rows from tool steps
* partial created messages from failure paths

Never persist `projectMessagesForModel(...)` back into the raw ledger. That projection may contain a
synthetic checkpoint that is not part of the user-visible transcript.

## Handle edits and deletes [#handle-edits-and-deletes]

For destructive transcript mutations, create a new revision rather than rewriting old rows. The new
revision can contain the edited transcript and no compaction rows. Old revisions remain available for
audit or debugging.

This rule keeps compaction simple: the active revision has one append cursor, and the latest completed
compaction in that revision defines model context.

## Verify the integration [#verify-the-integration]

1. Set a low test threshold and append enough messages to trigger compaction.
2. Confirm the raw transcript remains unchanged and a completed compaction payload is appended.
3. Confirm the next provider request starts with one synthetic checkpoint plus later messages.
4. Script one pre-emission `context_overflow` and confirm the host compactor runs once.
5. Script a second overflow and confirm it terminates without another retry.

The expected result is a complete durable transcript, bounded provider input, and at most one
overflow compaction retry per provider stream.

## Production checklist [#production-checklist]

* Keep raw messages append-only.
* Store completed and failed compactions as ledger entries, not raw messages.
* Project checkpoints only at model/provider boundaries.
* Keep the latest instruction message of each key after the checkpoint when you use host
  instructions.
* Guard compaction writes with active run id and expected sequence.
* Ignore failed compaction rows during projection.
* Merge previous compactions by passing both `previousSummary` and `previousRecent`, then drop the
  leading checkpoint from the new summary input.
* Compact before model calls and once on provider `context_overflow`.
* Surface compaction markers in your UI, but keep ledger rows as source of truth.

## Related APIs [#related-apis]

See [Agent APIs](../api-reference/agent#compaction) for the public compaction surface.

* `planWindowCompaction`
* `makeCompactionCheckpointMessage`
* `formatAgentMessagesForCompaction`
* `compactionSummarySourceMessages`
* `makeContextOverflowRetryProvider`
* `estimateAgentMessagesTokens`


---

# Implement a session store

URL: /docs/guides/durable-session-store

Back append-mode runtime with a database or append log.



Use `SessionEventStore` when the server owns transcript state and clients resume by session/run id.

## Store contract [#store-contract]

```ts
import { Effect, Layer } from 'effect'
import {
  SessionEventStore,
  appendRuntimeSessionEventsToLog,
  type RuntimeSessionEventLog,
  type SessionEventStoreApi
} from '@yolk-sdk/agent/runtime'
```

The store has two methods:

| Method            | Purpose                                                       |
| ----------------- | ------------------------------------------------------------- |
| `load(sessionId)` | read one session event log                                    |
| `append(input)`   | append runtime events, optionally checking `expectedRevision` |

## Minimal adapter shape [#minimal-adapter-shape]

```ts
const makeSessionStoreLayer = (db: HostSessionDb) =>
  Layer.succeed(
    SessionEventStore,
    SessionEventStore.of({
      load: sessionId => db.loadSessionLog(sessionId),
      append: input =>
        db.withSerializableTransaction(
          Effect.gen(function* () {
            const current = yield* db.loadOrCreateSessionLog(input.sessionId)

            if (
              input.expectedRevision !== undefined &&
              input.expectedRevision !== current.revision
            ) {
              return yield* db.failRevisionConflict(input.sessionId)
            }

            const next = appendRuntimeSessionEventsToLog(current, input)
            yield* db.saveSessionLog(next)

            return next
          })
        )
    } satisfies SessionEventStoreApi)
  )
```

`HostSessionDb` is app-owned. It should persist `RuntimeSessionEventLog` rows or an equivalent append-only representation.

## Use append mode [#use-append-mode]

```ts
import { runRuntime } from '@yolk-sdk/agent/runtime'

const events = runRuntime(
  {
    _tag: 'AppendInput',
    sessionId,
    runId,
    input: userMessage,
    expectedRevision
  },
  runtimeConfig
)
```

The runtime loads the log, appends input/run events, streams the agent, then appends completed, awaiting-input, or failed run events.

## Resume HITL [#resume-hitl]

```ts
const events = runRuntime(
  {
    _tag: 'AppendHitlResponse',
    sessionId,
    runId,
    response,
    expectedRevision
  },
  runtimeConfig
)
```

Your route must verify the response matches a pending request for the authenticated user/session before calling the runtime.

## Recovery path [#recovery-path]

On process restart, call `latestIncompleteRuntimeRun(log.events)`. If it returns a run, mark it interrupted or resume from your durable workflow/run system.

## Production notes [#production-notes]

* Use `expectedRevision` to reject stale writes.
* Store event ids/revisions monotonically.
* Persist terminal states before telling clients the run is settled.
* Never trust client-provided tool definitions or pending HITL ids.
* Keep app auth and session ownership outside the SDK store.


---

# Add human-in-the-loop

URL: /docs/guides/hitl

Pause for approvals, questions, typed inputs, or action-backed interactions.



Yolk models HITL in protocol, not UI. That means the same loop can pause in Next.js, Workers, WebSockets, or Vercel Workflows.

## How it works [#how-it-works]

1. The model calls a tool requiring approval, the built-in question tool, a typed input tool, or an action-backed interaction.
2. The loop emits `AgentAwaitingInput` with pending requests.
3. Your UI renders the matching controls. Input forms use `InputRequest.input.kind`; action-backed editors use `InteractionRequest.interaction.kind`.
4. Your app validates and resumes with typed `HitlResponse` values. `InteractionResponse` requires an additional host-owned atomic acceptance step before resume; raw responses never authorize actions.

## What the host owns [#what-the-host-owns]

* matching pending request ids (Workflow hosts: match the named pause; see [HITL resume](../vercel-workflows/hitl-resume#name-the-pause-an-answer-is-for))
* route auth
* UI copy and controls
* audit logs
* approval policy
* timeout/cancel UX

## Runtime modes [#runtime-modes]

For stateless routes, pass `toolSet.inputs` into the server's loop/runtime configuration and
include `hitlResponses` in the next `runRuntime` config. For durable sessions, use `_tag: 'AppendHitlResponse'` so the response is appended to the session event log.

For schema-backed forms, follow [Collect typed input](../agent/tools-hitl#collect-typed-input).
Pass `toolSet.inputs` alongside `toolSet.tools` into loop/runtime configuration; serializable tool
definitions alone cannot validate responses. Keep input forms pending until server acceptance.

## Show what an approval changes [#show-what-an-approval-changes]

Give approval-gated tools a `changePreview` hook (`makeTool({ approval, changePreview })`) and pass
`approvalPreviews: toolSet.approvalPreviews` to loop/runtime configuration. Pending approval
requests then carry a tool-agnostic before → after `preview`; render it, or fall back to the raw
arguments when `previewError` is set. The same hook previews staged plan reviews. Follow
[Preview the change](../agent/tools-hitl#preview-the-change).

## Execute a reviewed action [#execute-a-reviewed-action]

Use `makeInteractionTool`, not `makeInputTool`, when the user edits values and chooses a
server-defined action that should execute without another model turn or approval. Follow
[Authorize one action](../agent/tools-hitl#authorize-one-action) for the complete host contract.

Authenticate and validate before atomically accepting one immutable submission/cancellation.
Resolve with the scoped `interactionHost`, and pass both `toolSet.interactions` and
`toolSet.interactionHost` to loop/runtime config. Durable preflight first calls
`loadInteractionReceipts` and passes the snapshots to `prepareToolBatch`. All pending siblings
still fence dispatch. `AppendHitlResponse` only logs a response; it is not acceptance authority.

Keep submission pending until server acceptance, and acceptance active until a real outcome.
An unknown outcome is not definite failure or permission to retry. Hosts own reconciliation.
Voice and background execution do not support action-backed interactions.

A plan review (`makePlanReviewTool`) is an action-backed interaction too: a person reviews a code
mode script's staged approval-gated calls once and selects the calls to apply. Follow
[Review a staged plan](../agent/tools-hitl#review-a-staged-plan).

## Finish calls that paused for input [#finish-calls-that-paused-for-input]

Some calls pause after they were made: a remote MCP server asks a form before it finishes. The
tool stores the pause host-side and returns `makeInputRequiredToolResult`, an error result marked
`{ code: 'input_required', inputRequired: { reviewToolName, pauseIds } }`. The model then calls the
input review interaction (`makeInputReviewTool`, default `review_input({ pauseIds })`, renderer
`input_review`): your host loads the stored pauses through `InputReviewHost`, a person answers each
form (action `submit` with `{ answers }`, one per pause), and the action resumes each pause once,
reporting it `completed`, `input_required` (asked again), `not_sent`, or `unknown`
(`InputReviewOutcome`). Follow
[Finish calls that paused for input](../agent/tools-hitl#finish-calls-that-paused-for-input).

## Related APIs [#related-apis]

* `AgentAwaitingInput` from `@yolk-sdk/agent/protocol`
* `ToolApprovalRequest` from `@yolk-sdk/agent/protocol`
* `QuestionRequest` from `@yolk-sdk/agent/protocol`
* `InputRequest` from `@yolk-sdk/agent/protocol`
* `InputResponse` from `@yolk-sdk/agent/protocol`
* `InteractionRequest`, `InteractionResponse`, `InteractionHost` from `@yolk-sdk/agent/protocol`
* `validateInteractionSubmission` from `@yolk-sdk/agent/protocol`
* `makeInteractionTool` from `@yolk-sdk/agent/tools`
* `makePlanReviewTool`, `previewStoredToolPlan` from `@yolk-sdk/agent/tools`
* `makeInputRequiredToolResult`, `toolInputRequired` from `@yolk-sdk/agent/protocol`
* `makeInputReviewTool`, `InputReviewHost`, `InputPauseResolution`, `InputReviewOutcome` from `@yolk-sdk/agent/tools`
* `ToolChangePreview`, `groupToolChangePreviews` from `@yolk-sdk/agent/tools`
* `loadInteractionReceipts` from `@yolk-sdk/agent/loop`
* `plainHitlResponse` from `@yolk-sdk/agent/protocol`
* `questionResponseStructuredContent` from `@yolk-sdk/agent/protocol`
* `inputResponseStructuredContent` from `@yolk-sdk/agent/protocol`
* `toolRunsFromHitlRequests` from `@yolk-sdk/agent/client`


---

# Persist a session

URL: /docs/guides/persist-session

Use append-backed runtime requests when the server owns transcript state.



Use append-backed runtime when a run must survive reconnects, browser reloads, or human-in-the-loop pauses.

## Implement a store [#implement-a-store]

Production apps implement `SessionEventStore` against a database, Durable Object, or append log.

```ts
import { SessionEventStore } from '@yolk-sdk/agent/runtime'
```

The store must support loading a session event log and appending new events with revision checks.

## Append user input [#append-user-input]

```ts
import { runRuntime } from '@yolk-sdk/agent/runtime'
import { UserMessage } from '@yolk-sdk/agent/protocol'

const events = runRuntime(
  {
    _tag: 'AppendInput',
    sessionId: 'session_123',
    runId: 'run_123',
    input: UserMessage.make({ content: 'Continue' })
  },
  runtimeConfig
)
```

The runtime appends input, starts the run, replays prior messages, streams events, and appends terminal run state.

## Resume HITL [#resume-hitl]

```ts
const events = runRuntime(
  {
    _tag: 'AppendHitlResponse',
    sessionId: 'session_123',
    runId: 'run_124',
    response
  },
  runtimeConfig
)
```

The runtime verifies the response matches a pending request before continuing.

## Client rule [#client-rule]

Durable clients should de-dupe events by `eventId` when available and resume from the last known stream index.


---

# Resolve private attachments

URL: /docs/guides/private-attachments

Keep opaque file references in history and resolve native media for each provider request.



Persist private files as opaque `Ref` sources. Resolve them to fresh, provider-readable URLs only
in a request-local copy of the transcript. Yolk walks protocol content and lowers supported media;
your host owns authorization, storage, signing, retention, and file policy.

Install matching canary packages and Effect:

```bash
pnpm add @yolk-sdk/agent@canary effect@4.2.0
```

## Store refs, not transport payloads [#store-refs-not-transport-payloads]

This host integration fragment creates a native tool result after the host has authorized,
validated, and stored a PDF and image. The IDs are illustrative opaque handles, not URLs or
credentials. The transcript must also contain the matching assistant host tool call `read-1`.

```ts
import {
  DocumentPart,
  ImagePart,
  TextPart,
  ToolResultMessage,
  refAttachmentSource
} from '@yolk-sdk/agent/protocol'

const result = ToolResultMessage.make({
  toolCallId: 'read-1',
  content: [
    TextPart.make({ text: 'Retrieved the document and image.' }),
    DocumentPart.make({
      source: refAttachmentSource('attachment-pdf'),
      mimeType: 'application/pdf',
      filename: 'brief.pdf'
    }),
    ImagePart.make({
      source: refAttachmentSource('attachment-image'),
      mimeType: 'image/png',
      filename: 'photo.png'
    })
  ]
})
```

Return these semantic parts from your host tool rather than JSON-stringifying base64 or a signed
URL. Keep raw connector bytes and expiring URLs out of durable messages, `structuredContent`,
annotations, logs, and compaction summaries. Envelope fields are model-visible context, not a
place for hidden authorization state.

## Resolve immediately before each provider attempt [#resolve-immediately-before-each-provider-attempt]

`resolveMessageAttachmentSources(message, resolver)` walks one `AgentMessage`.
`resolveMessagesAttachmentSources(messages, resolver)` walks a message list in order. Both build
new messages without mutating history. They preserve envelope and part metadata, reasoning/tool-call
order, and nested assistant `ProviderToolResultPart.result.content`.

The existing `resolveContentAttachmentSources` handles a single `Content`. All three accept an
`AttachmentSourceResolver<E, R>` and preserve its Effect error and environment types. The resolver
receives every media part, including `Url` and `InlineBase64` sources; it decides which to keep,
replace, or reject. Calls are sequential, with no SDK deduplication or cache. Opaque tool parameters,
structured results, annotations, and provider metadata are preserved, not recursively interpreted
as content. Decode untrusted transcripts with `AgentMessage` before invoking these typed helpers.

This fragment wires host-owned authorization and signing around a provider. Supply the declared
host functions and provide their Effect services at your application boundary. The signing function
must check the current caller's ownership/access, trusted stored MIME/size metadata, and applicable
file policy before issuing a short-lived URL; possession of a ref alone is not authorization.

```ts
import { Effect, Stream } from 'effect'
import {
  LLMError,
  LLMProvider,
  type LLMEvent,
  type LLMProviderError,
  type LLMRequest
} from '@yolk-sdk/agent/loop'
import {
  resolveMessagesAttachmentSources,
  type AttachmentContentPart,
  type AttachmentSourceResolver,
  type UrlAttachmentSource
} from '@yolk-sdk/agent/protocol'

declare const hostProvider: {
  readonly stream: (request: LLMRequest) => Stream.Stream<LLMEvent, LLMProviderError>
}
declare const hostCheckAttachmentBudget: (request: LLMRequest) => Effect.Effect<void, LLMError>
declare const hostAuthorizeAndSign: (
  part: AttachmentContentPart
) => Effect.Effect<UrlAttachmentSource, LLMError>

const resolveSource: AttachmentSourceResolver<LLMError> = part =>
  part.source._tag === 'Ref' ? hostAuthorizeAndSign(part) : Effect.succeed(part.source)

const resolvingProvider = LLMProvider.of({
  stream: request =>
    Stream.unwrap(
      Effect.gen(function* () {
        // Use the effective model and messages, including the post-compaction retry.
        yield* hostCheckAttachmentBudget(request)
        const messages = yield* resolveMessagesAttachmentSources(request.messages, resolveSource)
        return hostProvider.stream({ ...request, messages })
      })
    )
})
```

Map expected host failures to a safe `LLMError` before returning from these callbacks; do not include
private refs, signed URLs, credentials, or raw upstream errors in its message. The pass-through
branch is appropriate only if the host already validated non-Ref sources. Reject untrusted external
URLs or inline payloads there when your policy requires it.

This wrapper is a **host integration pattern**, not an automatically installed SDK service. Keep
budget/cache state request-local. If repeated refs are deduplicated by the host, authorize every
occurrence's metadata and account for repeated model-visible media according to the chosen model's
limits; never reuse signed URLs across requests.

## Put resolution inside overflow retry [#put-resolution-inside-overflow-retry]

Compose in this order:

```text
project/compact refs -> overflow retry -> host budget/auth/signing -> provider transport
```

Extend the preceding fragment with the existing one-shot retry helper:

```ts
import {
  makeContextOverflowRetryProvider,
  type ContextOverflowRetryCompactor
} from '@yolk-sdk/agent/compaction'

declare const hostCompact: ContextOverflowRetryCompactor

const providerEffect = makeContextOverflowRetryProvider({
  provider: resolvingProvider,
  compact: hostCompact
})
```

On overflow, the compactor receives the unresolved request messages. After successful compaction,
resolution runs again on the retained refs immediately before the second attempt. Later requests
also sign afresh. Do not wrap the retry provider with a resolver on the outside: that signs only
once and exposes transient URLs to compaction. A `ContextTransformer` alone does not guarantee
fresh resolution for retries initiated inside a provider wrapper.

Keep the durable transcript separate from projected context. If you use the retry helper's optional
`messagesRef`, it receives the compactor's output, which should still contain refs, not signed URLs.
The wrapper does not write durable history or update runtime state automatically. Place resolution
inside any other host-owned retry mechanism that reissues a provider request, too. Transport-internal
retries that do not re-enter this wrapper cannot refresh signing; configure their lifetime/policy
accordingly.

Use overflow retry only for pre-emission overflow errors. It retries once, does not retract already
emitted deltas, and does not retry a second overflow. See [durable compaction](./durable-compaction).

## Respect provider and file limits [#respect-provider-and-file-limits]

* Codex lowers image/document tool results to native `input_image`/`input_file` function outputs.
  Claude lowers images and URL/base64 PDFs to nested tool-result blocks; inline text documents
  become text blocks. Text and media can be mixed in the same result.
* Resolution is not capability conversion. Both adapters reject unresolved image/document refs and
  audio tool results. Claude also rejects non-PDF, non-text documents. Supported MIME types,
  dimensions, page counts, byte budgets, URL accessibility, and model capabilities remain host checks.
* Generic OpenAI chat opts into native PDF user-message parts with `supportsPdfAttachments`; Gateway
  defaults it on. Their URL-PDF lowering performs a host-side GET through the supplied `HttpClient`
  and buffers the response before provider submission. Enforce authorization, redirect/destination
  policy, streamed limits, timeouts, safe logs, and credential isolation there, or use validated
  inline bytes. Set Gateway `supportsPdfAttachments: false` when that boundary is unavailable.
* Assistant media is traversed for protocol reuse, but Claude/Codex assistant text lowering still
  rejects media. Nested provider tool results are preserved by the helper, not newly replayed as
  native vendor tool results by those adapters.
* Office/text extraction and archive-inflation limits (or wiring `@yolk-sdk/extractors`),
  scanning, private storage, and cleanup stay app-owned. Do not put a whole email materializer or extraction
  dependency into the agent loop.

### Bound connector downloads before buffering [#bound-connector-downloads-before-buffering]

Gmail and Outlook already expose attachment metadata and base64 retrieval. Gmail's optional discovery
size is a nonnegative integer; malformed optional sizes are omitted. Outlook file retrieval requires
Graph's file-attachment discriminator; item/reference attachments remain metadata-only.

`ConnectorHttpClient` is a host-supplied string/JSON port, not a bounded downloader. In the host HTTP
adapter, enforce an actual streamed-byte ceiling **before** returning `ConnectorHttpResponse.body`.
Use separate configurable bounds for ordinary/error responses and successful attachment retrieval.
If selecting a larger allowance by route, match the exact trusted HTTPS origin, method, and attachment
retrieval path—not any URL containing `attachments`. Do not enlarge list/metadata or error bounds.

For a decoded-byte budget `B`, padded base64 needs up to `4 * ceil(B / 3)` ASCII bytes. The **whole
encoded JSON body** additionally includes metadata, escaping, and framing: choose a bounded allowance
for that overhead. Validate both budgets as finite, nonnegative safe integers and ensure their
arithmetic stays safe. Count actual body bytes (including multibyte metadata), not JS string length
or just `Content-Length`; abort/cancel when the limit is crossed, including when headers are missing
or misleading. If transport decompresses responses, bound the decompressed stream as well.

After syntax validation and before decoding, check encoded content length; then validate actual
decoded bytes, canonical encoding if required by your host, MIME, and per-file/aggregate limits.
Provider-declared sizes are hints, not proof of actual byte length. Legacy base64 action outputs
(`data`, `contentBase64`) are unchecked strings: the host validates them when it decodes. Zero-byte
retrieval is allowed by the connectors; whether empty files are usable is host policy.

Prefer the new [host-only connector byte helpers](../connectors/files) when materializing files.
They leave existing base64 actions unchanged. `downloadGmailAttachment` validates the base64url
alphabet, padding and actual decoded size (unused pad bits are accepted); Outlook uses raw `/$value` after a bounded discriminator read;
IMAP/POP3 can implement optional `EmailClient.getAttachmentBytes` without base64 roundtrips.
`ConnectorBinaryHttpClient` budgets must still be enforced while streaming by the host. None of
these helpers performs app storage, authorizes model access, or adds raw bytes to tool JSON.

## Verify your host wiring [#verify-your-host-wiring]

Use a fake provider and signer, with no live storage or mailbox calls:

1. Resolve private PDF/image refs in mixed user, assistant, and tool-result protocol content; compare
   metadata and ordering before/after, including nested provider tool results.
2. Script a pre-emission overflow, compact away an old attachment, and verify fresh URLs and budgets
   only for the retained context on retry. Repeat the request and re-run the same stream.
3. Confirm stored messages and compactor inputs still contain refs, and authorization failure prevents
   provider invocation. Verify a second overflow fails without a third attempt.
4. Test transport at its encoded-byte limit and one byte over, with missing/misleading headers and
   multibyte metadata. Verify cancellation and unchanged ordinary/error limits.

See [Agent APIs](../api-reference/agent#protocol) and the [connector catalog](../integrations/connectors).


---

# Build a React chat UI

URL: /docs/guides/react-chat-ui

Use headless React helpers for streaming, stop, retry, edit, regenerate, and HITL controls.



`@yolk-sdk/agent/react` is headless. It manages agent chat state; your app renders the UI.

## Install [#install]

```bash
pnpm add @yolk-sdk/agent@canary effect@4.2.0 react react-dom
```

## Client component [#client-component]

```tsx
'use client'

import { useState } from 'react'
import { Option, Predicate } from 'effect'
import { agentStatusRetry } from '@yolk-sdk/agent/protocol'
import { buildAgentChatItems, useAgentChat } from '@yolk-sdk/agent/react'

export function AgentChat() {
  const [input, setInput] = useState('')
  const chat = useAgentChat({
    sessionId: 'browser-session',
    endpoint: '/api/agent',
    model: 'gpt-5.5'
  })
  const items = buildAgentChatItems({
    messages: chat.chatMessages,
    isRunning: chat.isRunning,
    activeToolLabel: Option.none(),
    retryInfo: agentStatusRetry(chat.status)
  })

  return (
    <form
      onSubmit={event => {
        event.preventDefault()
        const result = chat.submitText(input)
        if (result._tag === 'Submitted') setInput('')
      }}
    >
      <ol>
        {items.map(item => (
          <li key={item.id}>{renderChatItem(item)}</li>
        ))}
      </ol>
      {Predicate.isTagged(chat.status, 'Failed') ? <p role="alert">{chat.status.message}</p> : null}
      <input
        value={input}
        disabled={!chat.canSubmitText(input)}
        onChange={event => setInput(event.target.value)}
      />
      <button type="submit" disabled={!chat.canSubmitText(input)}>
        Send
      </button>
      <button type="button" disabled={!chat.isRunning} onClick={chat.stop}>
        Stop
      </button>
    </form>
  )
}
```

`renderChatItem` is app-owned. Switch on `item._tag` and render your own message, tool, retry, status, and error components.

### Render host-authored messages [#render-host-authored-messages]

`UserMessage` and `AssistantMessage` items carry their message's envelope (`createdAtMs`,
`author`, `annotations`, each only when set), from live events and from snapshots rebuilt with
`buildAgentChatMessages` alike. A host that writes its own assistant messages, for example a note
after a background check, marks them with `annotations` and renders them differently:

```tsx
const renderChatItem = (item: AgentChatItem) => {
  if (item._tag === 'AssistantMessage' && item.annotations?.source === 'background_check') {
    return <CheckMarker at={item.createdAtMs} content={item.content} /> // app-owned
  }
  // ...
}
```

Annotations are model-visible context ([Protocol](../agent/protocol)): keep them short and never
put instructions in them. Other items of the same message (reasoning, tool runs) share its
`messageId`.

## HITL controls [#hitl-controls]

When `chat.isWaiting` is true (`chat.status` is `Blocked`), render approval/question/input controls
from tool run items. `chat.status.kind` says whether the run needs a `permission` or a `question`
(see [Agent status](../agent/status)). These are alternative fragments; use the method matching the
pending request:

```ts
chat.submitToolApprovalResponse(approvalResponse)
chat.submitQuestionResponse(questionResponse)
chat.submitInputResponse(inputResponse)
```

Build response values from `@yolk-sdk/agent/protocol` after matching the pending request id in your UI
state. Render typed inputs by `InputRequest.input.kind` using host-owned forms, and keep them pending
until server acceptance rather than creating optimistic results. See
[Collect typed input](../agent/tools-hitl#collect-typed-input) for handler wiring and correction.

## Durable streams [#durable-streams]

Use `useAgentChat` for normal browser chats. For replayed durable event logs, use `applyAgentEventToChatProjection` directly so overlapping chunks de-dupe by `eventId`.

## UX checklist [#ux-checklist]

* Disable submit while running or awaiting HITL.
* Keep stop local: it aborts the current browser stream. Server-side cancellation is a separate route.
* Show retry state from `agentStatusRetry(chat.status)` and failures from `Failed` statuses.
* Keep approval/question/input controls accessible and auditable.
* Never render raw provider error bodies.


---

# Stream to React

URL: /docs/guides/stream-react

Connect a browser chat UI to a Yolk route with client and React helpers.



Use `@yolk-sdk/agent/client` to consume a stream, then project events into UI state with `@yolk-sdk/agent/react`.

## Install [#install]

```bash
pnpm add @yolk-sdk/agent@canary react react-dom effect@4.2.0
```

## Consume a route stream [#consume-a-route-stream]

```ts
import { Stream } from 'effect'
import { streamAgentEventStreamUntilTerminal } from '@yolk-sdk/agent/client'

const stream = streamAgentEventStreamUntilTerminal({
  endpoint: '/api/agent',
  sessionId: 'browser-session',
  messages
})

for await (const event of Stream.toAsyncIterable(stream)) {
  // project into UI state
}
```

## Build replay-safe state [#build-replay-safe-state]

```ts
import { Stream } from 'effect'
import {
  applyAgentEventToChatProjection,
  makeAgentChatEventProjectionState
} from '@yolk-sdk/agent/react'
import { streamAgentEventStreamUntilTerminal } from '@yolk-sdk/agent/client'

let projection = makeAgentChatEventProjectionState()
const stream = streamAgentEventStreamUntilTerminal({
  endpoint: '/api/agent',
  sessionId: 'browser-session',
  messages
})

for await (const event of Stream.toAsyncIterable(stream)) {
  projection = applyAgentEventToChatProjection(projection, event)
}
```

Use projection state for durable streams where reconnect may replay overlapping events. Use simpler reducers only for ephemeral one-shot streams.

## What your UI owns [#what-your-ui-owns]

Yolk is headless. You render the input, message list, attachment UX, retry state, stop button, approval prompts, and question prompts.


---

# Test with emulators

URL: /docs/guides/testing-with-emulators

Run integrations and conformance cases offline against service emulators.



> **Experimental.** `@yolk-sdk/conformance` and `@yolk-sdk/emulators` may change in any canary
> release. Both are new after `0.1.0-canary.95`; keep every `@yolk-sdk/*` package on the same
> version, and use emulators in tests and local development only.

Use emulators when your host app's tests should exercise the real connector, provider, or MCP
client code without calling the outside service. This guide covers the host side: wiring an
emulator into your own tests, running the conformance cases against it, and the rules you must
respect. The [Emulator APIs](../api-reference/emulators) and
[Conformance APIs](../api-reference/conformance) pages hold the full per-service detail.

## Cases, emulators, and evidence [#cases-emulators-and-evidence]

* A **conformance case** is a small Effect program that states one claim about how a provider
  behaves on the wire (`docs` versus `wire`), with a `safety` of `read`, `write-reversible`, or
  `write-irreversible`. The same case runs against replayed fixtures, an emulator, or a live
  practice account; only the layers change.
* A **fixture** is a committed recording of the exchanges a case relies on. Fixtures hold synthetic
  or scrubbed data only.
* An **emulator** is a stand-in that answers from those committed fixtures. The Dropbox, Notion,
  Todoist, Telegram, GitHub, Google, LinkedIn search, MCP, email, R2, OpenCode Go, and
  subscription-usage emulators are fixture-only: they never invent an answer. Fortnox and Microsoft
  Graph add a few documented extrapolations, and the model-route emulators (Gateway, OpenAI,
  Anthropic, Codex, Grok) generate synthetic output or scripted turns in the recorded wire shapes.
  Each emulator passes its service's conformance cases offline, so the cases prove that the
  emulator matches the claims your code relies on.
* **Evidence** says how far to trust a claim. An emulated route is `unverified` when it follows
  synthetic placeholders and `verified` when it follows a live recording, dated by the route's
  `observedAt`; fixtures make the same distinction with their own dates. Responses from an
  unverified HTTP route carry `x-emulator-evidence: unverified`; the email and R2 port fakes record
  the evidence on each ledger entry instead. Unverified connector write routes are **pending**:
  the Yolk repository holds them in a time-bounded allowlist until an owner-approved live run
  verifies them. See [Evidence](../api-reference/emulators#evidence) for the current state of each
  route.

A passing test against an emulator shows that your code agrees with the recorded claims. It does
not show that the live provider still behaves that way.

## Test an integration in-process [#test-an-integration-in-process]

This runnable example runs the real GitHub connector against the in-process GitHub emulator in a
Vitest test. It lists labels, absorbs a rate limit, and shows a refused request.

Install (Node 22 or later):

```bash
pnpm add @yolk-sdk/connectors@canary @yolk-sdk/agent@canary effect@4.2.0
pnpm add -D @yolk-sdk/emulators@canary @yolk-sdk/conformance@canary vitest
```

`test/github-emulator.test.ts`:

```ts
import { Effect, Layer } from 'effect'
import { afterEach, beforeEach, expect, it } from 'vitest'
import {
  BearerTokenCredential,
  makeCredentialBinding,
  makeIntegration,
  type ConnectorHttpClient,
  type CredentialResolver
} from '@yolk-sdk/connectors'
import {
  connectorHttpClientsFromEffectHttpClientLayer,
  staticCredentialResolverLayer
} from '@yolk-sdk/connectors/conformance'
import {
  githubConnectorId,
  githubCreateIssueAction,
  githubListLabelsAction,
  githubTokenSlotId
} from '@yolk-sdk/connectors/github'
import {
  githubEmulatorOrigin,
  makeGithubEmulator,
  type GithubEmulator
} from '@yolk-sdk/emulators/github'
import { EmulatorRoute, InProcessHttpClient } from '@yolk-sdk/emulators/router'

// The practice repository the emulator's default seed holds.
const integration = makeIntegration({
  connectorId: githubConnectorId,
  config: { owner: 'yolk-synthetic', repo: 'conformance-practice' },
  credentialBindings: [
    makeCredentialBinding({ slotId: githubTokenSlotId, credentialRef: 'test-github-token' })
  ]
})

let github: GithubEmulator

beforeEach(async () => {
  github = await makeGithubEmulator()
})

afterEach(async () => {
  await github.close()
})

// Run the real connector over an HttpClient that calls the emulator in-process.
const run = <A, E>(effect: Effect.Effect<A, E, ConnectorHttpClient | CredentialResolver>) =>
  Effect.runPromise(
    effect.pipe(
      Effect.provide(
        Layer.mergeAll(
          connectorHttpClientsFromEffectHttpClientLayer.pipe(
            Layer.provide(
              InProcessHttpClient.layer([EmulatorRoute.handler(githubEmulatorOrigin, github.fetch)])
            )
          ),
          staticCredentialResolverLayer(
            BearerTokenCredential.make({ token: 'synthetic-github-test-token' })
          )
        )
      )
    )
  )

const listLabels = githubListLabelsAction.executeTyped({ integration, input: { perPage: 2 } })

it('lists labels from the seeded repository', async () => {
  expect(await run(listLabels)).toMatchObject({ _tag: 'Success', value: { hasNextPage: true } })
  expect(
    github.ledger.entries().map(entry => `${entry.method} ${entry.route} ${entry.status}`)
  ).toEqual(['GET /repos/{owner}/{repo}/labels 200'])
})

it('surfaces a 429 with retry-after, then answers the retry', async () => {
  github.faults.add({ kind: 'status', status: 429, headers: { 'retry-after': '7' }, count: 1 })

  expect(await run(listLabels)).toMatchObject({
    _tag: 'Failure',
    error: { code: 'github_rate_limited', status: 429, retryAfterMs: 7000 }
  })
  expect(await run(listLabels)).toMatchObject({ _tag: 'Success' })
  expect(github.ledger.entries().map(entry => [entry.status, entry.fault])).toEqual([
    [429, 'status'],
    [200, undefined]
  ])
})

it('refuses an unrecorded request and writes nothing; reset restores the seed', async () => {
  const seed = github.snapshot()

  const createIssue = (extra: { readonly labels?: ReadonlyArray<string> }) =>
    githubCreateIssueAction.executeTyped({
      integration,
      input: { title: 'yolk-test issue', body: 'Synthetic.', ...extra }
    })

  // No fixture records a create with labels: one ledgered 400 not-emulated.
  expect(await run(createIssue({ labels: ['bug'] }))).toMatchObject({
    _tag: 'Failure',
    error: { status: 400 }
  })
  // Assert that it was refused, not the exact reason text, which may be reworded.
  expect(github.ledger.entries()[0]?.notEmulated).toEqual(expect.any(String))
  expect(github.snapshot()).toEqual(seed)

  // The recorded create flow is emulated; reset() puts the seed back.
  expect(await run(createIssue({}))).toMatchObject({ _tag: 'Success', value: { number: 42 } })
  await github.reset()
  expect(github.snapshot()).toEqual(seed)
  expect(github.ledger.entries()).toEqual([])
})
```

Run:

```bash
pnpm exec vitest run test/github-emulator.test.ts
```

Expected result: `3 passed`. No request leaves the process, and the token is never stored or
written to the ledger.

`InProcessHttpClient.layer` calls the emulator's `fetch` handler directly. Your code keeps calling
the real origin (`https://api.github.com`), and a request to an origin without a route fails with
an `HttpClientError` that names only the origin.

## Serve an emulator on loopback [#serve-an-emulator-on-loopback]

Use `@yolk-sdk/emulators/node` when the code under test must go through a real socket, for
example to check streaming or your own `FetchHttpClient` stack. `EmulatedHttpClient` rewrites the
routed origin to the loopback server. The server binds only to `127.0.0.1`.

Fragment (inside an async test):

```ts
import { Layer } from 'effect'
import { FetchHttpClient } from 'effect/http'
import { githubEmulatorOrigin, makeGithubEmulator } from '@yolk-sdk/emulators/github'
import { startFetchHandlerServer } from '@yolk-sdk/emulators/node'
import { EmulatedHttpClient, EmulatorRoute } from '@yolk-sdk/emulators/router'

const github = await makeGithubEmulator()
const server = await startFetchHandlerServer(github.fetchOn(githubEmulatorOrigin))

const httpLayer = EmulatedHttpClient.layer([
  EmulatorRoute.url(githubEmulatorOrigin, server.url)
]).pipe(Layer.provide(FetchHttpClient.layer))

// ... run the code under test with httpLayer, then:
await server.close()
await github.close()
```

The rewrite loses the origin. The Dropbox, Notion, GitHub, Google, LinkedIn search, and MCP
emulators answer each route only on its recorded origin, so serve their `fetchOn(origin)` rather
than `fetch`, with one server per origin for the services that have two (Dropbox, Google, LinkedIn
search, and MCP with its `afloat` profile). The Fortnox, Microsoft Graph, Todoist, Telegram, model-route, and OpenCode Go emulators
have no `fetchOn`: serve their `fetch`. Microsoft Graph serves both of its origins from one server.
Each emulator's [reference section](../api-reference/emulators) names its origins. In Effect tests,
`serveFetchHandler` is the scoped variant.

## Seeds and profiles [#seeds-and-profiles]

The connector, MCP, email, and R2 emulators start from a typed seed. The default seed holds the
fixtures' synthetic entities, so the fixture seeds of the conformance cases (for example
`githubConformanceFixtureSeeds`) match it. Most connector emulators take a `profile` (`default` or
`empty`; Fortnox has its own profiles), and the other seed keys replace parts of it; LinkedIn
search and MCP take no profile. The emulators that mint timestamps (Fortnox, Microsoft Graph,
Dropbox, Notion, Todoist, Telegram, GitHub, Google) take an injectable `now` clock that keeps them
deterministic. Each emulator's reference section lists its seed keys.

Fragment:

```ts
const github = await makeGithubEmulator({
  seed: { profile: 'empty' },
  now: () => Date.parse('2026-01-01T12:00:00Z')
})

await github.seed({ profile: 'default' }) // replace the state; reset() now restores this
await github.reset()
```

An invalid seed fails with the emulator's input-invalid error, such as
`GithubEmulatorInputInvalid`. On the connector and MCP emulators, `snapshot()` returns a deep copy
of the state.

## Faults and retries [#faults-and-retries]

On the HTTP connector emulators (Fortnox through LinkedIn search in the
[table](#available-emulators)) and MCP, `faults.add` adds a status fault: matching requests answer
an error status instead of the route's answer, so nothing is written. `match` narrows it by
`method` and `path` (a trailing `*` makes a prefix) and, except on Fortnox and Microsoft Graph, by
`route` (a manifest route template); `count` limits how many requests it answers. MCP also takes
`truncate-after-chunks`, and the model-route and OpenCode Go emulators take their own status and
chunk faults, matched by `path` and `model`.

The email and R2 port fakes take `{ kind: 'failure', method, match?, count?, failure }` instead
(R2 also names the `port`): a call to that method whose request contains `match` as a deep subset
answers `failure`, and no state changes. See [Email](../api-reference/emulators#email-emulator) and
[R2](../api-reference/emulators#r2-emulator).

A 429 fault with `retry-after` reaches the GitHub connector as `github_rate_limited` with
`retryAfterMs`; each emulator's reference section names the code its connector or provider maps it
to. Connector actions return that failure and do not retry by themselves, so retry policy stays
host-owned. A fault with `count: 1` proves that your retry succeeds on the next attempt, as in the
second test above.

On every HTTP connector emulator and MCP, a fault is chosen only for a request the emulator would
answer, so a refused request never uses one up and a misplaced fault stays listed in
`faults.list()` instead of passing silently. On Fortnox and Microsoft Graph, a refusal is the
provider's error envelope (a 404 for an unknown id, or a 400 or 409 for a state or value the route
refuses) rather than the shared `{ error: { type: 'not_emulated' } }` 400, and it uses up no fault
either.

## Drills [#drills]

Drill knobs are test-only. The Microsoft Graph, Dropbox, Notion, Todoist, Telegram, GitHub, Google,
LinkedIn search, and MCP emulators take a `drills` option, and Fortnox takes `quirks`. Each knob
makes the emulator disagree with one conformance claim, so the matching case fails. Most knobs are
booleans; Microsoft's `timestampPrecisionDigits` is a number. Use drills to prove that a case can
fail against your setup, not to model provider behaviour. See the conformance example below for a
drill run.

## Read the ledger and the control plane [#read-the-ledger-and-the-control-plane]

On the fixture-only stateful emulators (Dropbox, Notion, Todoist, Telegram, GitHub, Google,
LinkedIn search, and MCP), `ledger.entries()` records every request in arrival order: method,
path, route template, query and body with credential-named keys redacted, status, evidence, any
`fault`, and, for a refusal, the `notEmulated` reason. All of them except Todoist and Telegram also
record the non-credential headers they check. Other ledgers differ:

* Fortnox ledgers queries and bodies as sent, without redaction.
* Microsoft Graph redacts credential-named keys and records the `Prefer` header.
* Neither Fortnox nor Microsoft Graph has a `notEmulated` field: their refusals appear as
  provider-envelope statuses (such as 401, 404, or 400).
* The model-route, email, and R2 ledgers have their own shapes.

Each emulator's reference section describes its ledger. `coverage()` lists each manifest route
with its request count and case ids.

The HTTP emulators also serve a control plane under `/_emulate/*` from the same fetch handler. On
the connector and MCP emulators it serves `ledger` (`GET`, `DELETE`), `faults` (`GET`, `POST`,
`DELETE`), `reset` (`POST`), `state` (`GET`), `seed` (`POST`), and `coverage` (`GET`). The
model-route emulators serve `script` instead of `seed`, and the emulators built from several parts
(OpenCode Go, and the usage part of Anthropic, Codex, and xAI) serve each part under
`/_emulate/<part>/*`. Use the control plane when the test process does not hold the emulator
object, for example when another process runs the code under test.

Fragment (with `server` from the loopback fragment):

```ts
const control = (path: string, init?: RequestInit) =>
  fetch(`${server.url}/_emulate/${path}`, init).then(response => response.json())

await control('faults', {
  method: 'POST',
  headers: { 'content-type': 'application/json' },
  body: JSON.stringify({ kind: 'status', status: 503, match: { method: 'POST' }, count: 1 })
})
const { entries } = await control('ledger')
await control('reset', { method: 'POST' })
```

## Reset between tests [#reset-between-tests]

On the connector and MCP emulators, `reset()` restores the current seed and clears the ledger,
faults, and runtime data such as cursors and sessions. Create one emulator per test, as in the
example, or call `reset()` in `beforeEach`. Run write flows sequentially on one emulator: some
emulators, such as [Todoist](../api-reference/emulators#todoist-emulator), accept only the one
created item a fixture records at a time, and refuse a second one until the first is gone or the
emulator is reset.

## Unexpected requests fail loudly [#unexpected-requests-fail-loudly]

Emulators fail closed. On the fixture-only emulators, a request that no fixture records is
answered with one ledgered **400 not-emulated** (`{ error: { type: 'not_emulated', message } }`)
before anything is written and before any fault is chosen. That includes other routes, other query
parameters or body keys, unknown ids, cursors the emulator did not issue, and, on the emulators
that check the origin (Dropbox, Notion, GitHub, Google, LinkedIn search, MCP), another origin.
GitHub, Google, LinkedIn search, MCP, Todoist, and Telegram ledger a request on no emulated route
shape with constant text only (`/<unrecognised>`). Fortnox and Microsoft Graph refuse in the
provider's error envelope (404 for an unknown route, 400 for an unsupported query or body), and
the model-route emulators answer an unknown route with a 404. Each emulator's reference section
lists exactly what it accepts.

A connector may map that 400 to an ordinary validation code (`github_validation` for GitHub), so
assert the ledger as well as the result:

```ts
// Fragment: fails the test when the code under test sent anything no fixture records.
expect(github.ledger.entries().filter(entry => entry.notEmulated !== undefined)).toEqual([])
```

The email and R2 emulators are port-level fakes: they answer `{ notEmulated: { reason } }`
instead of an HTTP 400.

## Run the conformance cases against an emulator [#run-the-conformance-cases-against-an-emulator]

Run a service's cases with `runConformance`, giving each case fresh connector ports over a fresh
emulator. The runner builds `layer(testCase)` once per case in its own scope, so a scoped layer
that creates the emulator, as below, opens and closes one per case. An emulator created outside
the `layer` factory, or captured in one shared `Layer.succeed` value, is not rebuilt: its state is
shared across cases.

Fragment (a Vitest test, with the imports of the runnable example plus these):

```ts
import {
  GithubConformanceConfig,
  githubConformanceCases,
  githubConformanceFixtureSeeds
} from '@yolk-sdk/connectors/github/conformance'
import {
  conformanceReportFailed,
  formatConformanceReport,
  runConformance
} from '@yolk-sdk/conformance/runner'
import { type GithubEmulatorOptions } from '@yolk-sdk/emulators/github'

const githubCasePorts = (options: GithubEmulatorOptions = {}) =>
  Layer.unwrap(
    Effect.acquireRelease(
      Effect.promise(() => makeGithubEmulator(options)),
      github => Effect.promise(() => github.close())
    ).pipe(
      Effect.map(github =>
        Layer.mergeAll(
          connectorHttpClientsFromEffectHttpClientLayer.pipe(
            Layer.provide(
              InProcessHttpClient.layer([EmulatorRoute.handler(githubEmulatorOrigin, github.fetch)])
            )
          ),
          staticCredentialResolverLayer(
            BearerTokenCredential.make({ token: 'synthetic-github-test-token' })
          ),
          Layer.succeed(GithubConformanceConfig, githubConformanceFixtureSeeds)
        )
      )
    )
  )

it('passes every GitHub case against the emulator', async () => {
  const report = await Effect.runPromise(
    runConformance(githubConformanceCases, {
      target: { kind: 'in-process' },
      layer: () => githubCasePorts()
    })
  )

  expect(conformanceReportFailed(report), formatConformanceReport(report)).toBe(false)
})

it('fails exactly the drilled case', async () => {
  const report = await Effect.runPromise(
    runConformance(githubConformanceCases, {
      target: { kind: 'in-process' },
      layer: () => githubCasePorts({ drills: { contentUnfolded: true } })
    })
  )

  expect(report.results.filter(result => result.status === 'failed').map(r => r.id)).toEqual([
    'github.contents.base64-file'
  ])
})
```

Every case runs on `in-process` and `emulated` targets, write cases included, because nothing real
happens there. A case that no live run has observed carries an `unverified-case` warning, as the
GitHub cases do. Use `{ kind: 'emulated' }` with the loopback layer for the socket path.

A failure against an emulator means that the SDK code, the case, and the emulator's copy of the
fixtures no longer agree. Common causes are an SDK upgrade whose requests changed shape (look for
`notEmulated` in the ledger), a seed that does not match the case's config, or an intended drill.
It says nothing new about the live provider. A failure against a live practice account is the
signal that the provider changed.

## What emulators do not do [#what-emulators-do-not-do]

* **No invented answers.** The fixture-only emulators refuse anything a fixture does not record,
  including empty pages or empty search results where no fixture records one, and listings no
  fixture shows. They never guess a
  status or an error envelope.
* **Limited leftover lookups.** The read-only GitHub, Google, and Todoist
  `find*ConformanceLeftovers` lookups send only reads a read case records, so they run against the
  emulator and report a leftover the state holds. The Google draft search and free-text event
  query are recorded only empty, so they fail not-emulated once the state holds a draft or an event
  that might match (the event cases leave their cancelled run events). The Dropbox and Notion
  lookups fail against the default seed (no fixture records an empty listing or search), but report
  a leftover in a recorded shape that a seed or an earlier case left behind. The repository runners
  report a failed lookup as a lookup-failed `WARN`, not as leftovers.
* **No delivery.** Sends such as the Telegram message or the Gmail practice send are recorded in
  the emulator's state and never delivered anywhere.
* **No production use.** The Fortnox through MCP subpaths and the loopback server are Node only,
  and the router layers refuse to build when `NODE_ENV` is `production`.

## Credentials [#credentials]

* Use synthetic credentials only, never a real token. Emulators are test stand-ins, not
  secret-scrubbing boundaries.
* Use a credential each emulator recognises. GitHub, Google, LinkedIn search, and MCP accept only
  a synthetic bearer in the `b64token` form their sections define (see
  [GitHub](../api-reference/emulators#github-emulator)). `synthetic-github-test-token` qualifies;
  a UUID or an all-hex key does not. Such a bearer also suits the other bearer emulators.
  Telegram takes a synthetic `<digits>:<secret>` bot token instead. The MCP `afloat` profile
  (`https://useafloat.com`) takes `afloat_` followed by such a bearer, for example
  `afloat_synthetic-key-0001`.
* Send the credential only where the provider expects it, such as the `Authorization` bearer or
  Telegram's bot token in the path. There it is never stored or ledgered.
* Checks for a credential repeated elsewhere in a request differ by emulator:
  * GitHub, Google, and LinkedIn search refuse a repeat in the path, query, recorded headers, or
    body.
  * MCP also checks every other header.
  * Todoist and Telegram check the path, query, and body.
  * Dropbox, Notion, Fortnox, Microsoft Graph, and the model routes do not check repeats, so a
    credential sent elsewhere can reach the ledger (Fortnox ledgers queries and bodies unredacted).
* MCP's guarantee has precise limits: some emulator constants and control-plane data are not
  checked. See [MCP](../api-reference/emulators#mcp-emulator).
* The `/_emulate/*` control plane is the host's own trusted surface. Seed and fault data you give
  it is stored and returned as given, so never put a secret in a seed, fault body, or header.

## Live runs [#live-runs]

Emulators and replay cover everyday tests. Run the cases live only by hand, against practice
accounts you own, with the account owner's approval; never in CI.

* In your host, run the same cases with your own `HttpClient` and
  `target: { kind: 'live', account }`. Live targets always run `read` cases. They run a
  `write-reversible` case only with `allowWrites: 'reversible'`, and a `write-irreversible` case
  only when its exact id is in `allowIrreversible`. The two gates are independent: `allowWrites`
  never starts an irreversible case, and leaving it out does not stop one listed in
  `allowIrreversible`. See the [runner safety policy](../api-reference/conformance#runner).
* In the Yolk repository, the `pnpm conformance:<id>` runners (for example
  `pnpm conformance:github`) dry-run by default: they print the plan without a network call or a
  credential read. `--live --owner-approved --account <label>` is refused whenever `CI` is set.
  Recordings from a live run are promoted by hand and scrubbed, so committed fixtures stay
  synthetic.

Each service's runner flags, seeds, and cleanup rules are on its page under
[Connectors](../connectors) and in [Conformance APIs](../api-reference/conformance).

## Available emulators [#available-emulators]

Import an explicit subpath; there is no root export.

| Subpath                               | Stands in for                                         | Used with                                                                       | Reference                                                              |
| ------------------------------------- | ----------------------------------------------------- | ------------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
| `@yolk-sdk/emulators/router`          | Routing only                                          | Any Effect `HttpClient` code                                                    | [Router](../api-reference/emulators#router)                            |
| `@yolk-sdk/emulators/node`            | Loopback server                                       | `EmulatedHttpClient`                                                            | [Node server](../api-reference/emulators#node-server)                  |
| `@yolk-sdk/emulators/gateway`         | Vercel AI Gateway chat completions and classifier     | `@yolk-sdk/agent/providers/vercel/ai-gateway-provider`, `ai-gateway-classifier` | [Gateway](../api-reference/emulators#gateway-emulator)                 |
| `@yolk-sdk/emulators/openai`          | OpenAI Chat Completions                               | `@yolk-sdk/agent/providers/openai/provider`                                     | [OpenAI](../api-reference/emulators#openai-emulator)                   |
| `@yolk-sdk/emulators/anthropic`       | Anthropic Messages and Claude usage                   | `@yolk-sdk/agent/providers/anthropic/claude-provider`                           | [Anthropic](../api-reference/emulators#anthropic-emulator)             |
| `@yolk-sdk/emulators/codex`           | ChatGPT Codex Responses and usage                     | `@yolk-sdk/agent/providers/openai/codex-provider`                               | [Responses](../api-reference/emulators#responses-emulators)            |
| `@yolk-sdk/emulators/xai`             | xAI Grok CLI proxy Responses and billing              | `@yolk-sdk/agent/providers/xai/grok-provider`                                   | [Responses](../api-reference/emulators#responses-emulators)            |
| `@yolk-sdk/emulators/opencode`        | OpenCode Go chat, Messages, Responses, and usage      | `@yolk-sdk/agent/providers/opencode/go-provider`                                | [OpenCode Go](../api-reference/emulators#opencode-go-emulator)         |
| `@yolk-sdk/emulators/email`           | `EmailClient` port (fake backend)                     | `@yolk-sdk/connectors/email`                                                    | [Email](../api-reference/emulators#email-emulator)                     |
| `@yolk-sdk/emulators/r2`              | `R2Presigner` and `R2ObjectClient` ports              | `@yolk-sdk/connectors/r2-storage`                                               | [R2](../api-reference/emulators#r2-emulator)                           |
| `@yolk-sdk/emulators/fortnox`         | Fortnox `/3` API                                      | `@yolk-sdk/connectors/fortnox`                                                  | [Fortnox](../api-reference/emulators#fortnox-emulator)                 |
| `@yolk-sdk/emulators/microsoft`       | Microsoft Graph (Outlook, OneDrive, calendar)         | `@yolk-sdk/connectors/microsoft`                                                | [Microsoft](../api-reference/emulators#microsoft-graph-emulator)       |
| `@yolk-sdk/emulators/dropbox`         | Dropbox `/2` RPC and upload                           | `@yolk-sdk/connectors/dropbox`                                                  | [Dropbox](../api-reference/emulators#dropbox-emulator)                 |
| `@yolk-sdk/emulators/notion`          | Notion `/v1`                                          | `@yolk-sdk/connectors/notion`                                                   | [Notion](../api-reference/emulators#notion-emulator)                   |
| `@yolk-sdk/emulators/todoist`         | Todoist API v1                                        | `@yolk-sdk/connectors/todoist`                                                  | [Todoist](../api-reference/emulators#todoist-emulator)                 |
| `@yolk-sdk/emulators/telegram`        | Telegram Bot API                                      | `@yolk-sdk/connectors/telegram`                                                 | [Telegram](../api-reference/emulators#telegram-emulator)               |
| `@yolk-sdk/emulators/github`          | GitHub REST                                           | `@yolk-sdk/connectors/github`                                                   | [GitHub](../api-reference/emulators#github-emulator)                   |
| `@yolk-sdk/emulators/google`          | Gmail, Calendar, and Drive                            | `@yolk-sdk/connectors/google`                                                   | [Google](../api-reference/emulators#google-emulator)                   |
| `@yolk-sdk/emulators/linkedin-search` | Exa and Enrich Layer                                  | `@yolk-sdk/connectors/linkedin-search`                                          | [LinkedIn search](../api-reference/emulators#linkedin-search-emulator) |
| `@yolk-sdk/emulators/mcp`             | Two synthetic MCP servers, Afloat and Figma endpoints | `@yolk-sdk/mcp/client`, `@yolk-sdk/connectors/{afloat,figma}/conformance`       | [MCP](../api-reference/emulators#mcp-emulator)                         |
| `@yolk-sdk/emulators/kie`             | Kie Market API task read and create                   | `@yolk-sdk/connectors/kie`                                                      | [Kie](../api-reference/emulators#kie-emulator)                         |


---

# Test an agent

URL: /docs/guides/testing

Use package fakes to test loops, tools, streams, and integrations without provider calls.



Use `@yolk-sdk/agent/loop/testing` for deterministic loop tests.

## Test a text response [#test-a-text-response]

```ts
import { Effect, Layer, Stream } from 'effect'
import { ContextTransformer, LoopConfig, run } from '@yolk-sdk/agent/loop'
import { FauxProvider, Reply, TestToolExecutor } from '@yolk-sdk/agent/loop/testing'
import { UserMessage } from '@yolk-sdk/agent/protocol'

const TestLayer = Layer.mergeAll(
  FauxProvider.layer(Reply.text('Hello.')),
  TestToolExecutor.layer({}),
  LoopConfig.defaultLayer,
  ContextTransformer.identity
)

const events = await Effect.runPromise(
  run({
    messages: [UserMessage.make({ content: 'Hi' })],
    systemPrompt: 'Be concise.',
    tools: [],
    model: 'test-model'
  }).pipe(Stream.runCollect, Effect.provide(TestLayer))
)
```

## Test tool calls [#test-tool-calls]

Use `Reply.toolCall(...)` to make the fake provider request a tool, then use `TestToolExecutor.layer(...)` to return canned results.

## Integration tests [#integration-tests]

For package integrations, fake the boundary ports:

* fake `ConnectorHttpClient`
* fake `CredentialResolver`
* fake `SearchIndexStore`
* fake `KnowledgeEmbedder`
* `makeFakeSandboxLayer`
* `makeInMemorySandboxStateStoreLayer`

To run the real connector, provider, or MCP client code against a stand-in for the outside
service instead, see [Test with emulators](./testing-with-emulators).


---

# Harness package

URL: /docs/harness

Own agent run lifecycle with a host drain, claims, inbox admission, and optional recovery.



Use `@yolk-sdk/harness` when you need process-local run ownership, coalesced wakes, and crash claims. The model/tool loop stays in `@yolk-sdk/agent/loop`. This package does not add a Vercel Workflow driver.

`@yolk-sdk/harness` is introduced after `0.1.0-canary.76`. It is unavailable in `0.1.0-canary.76` and earlier. Choose a newer matching canary once available. Keep every `@yolk-sdk/*` dependency on the same version.

```bash
pnpm add @yolk-sdk/harness@canary @yolk-sdk/agent@canary effect@4.2.0
```

## Run a memory host with a custom drain [#run-a-memory-host-with-a-custom-drain]

Omitting `drain` uses a no-op (`Effect.void`). `driver.run` then only claims and releases ownership. Attach host work with a custom drain. `Inbox.takePromotable` requires that drain's live `drainToken`.

Setup:

```bash
pnpm add @yolk-sdk/harness@canary effect@4.2.0
pnpm add -D tsx
```

Filename: `drain-example.mts`

```ts
import { Effect } from 'effect'
import { admit, Driver, type Drain } from '@yolk-sdk/harness/driver'
import { makeInMemoryHarnessLayer } from '@yolk-sdk/harness/driver/memory'
import { Inbox } from '@yolk-sdk/harness/inbox'

const drain: Drain = (runId, _force, scope, context) =>
  Effect.gen(function* () {
    const inbox = yield* Inbox
    const item = yield* inbox.takePromotable(runId, scope, context.drainToken)
    if (item === undefined) {
      yield* Effect.sync(() => {
        console.log(`no work for ${runId}`)
      })
      return
    }
    yield* Effect.sync(() => {
      console.log(`drained ${item.id} for ${runId}`)
    })
  })

const program = Effect.gen(function* () {
  yield* admit({
    id: 'item_1',
    runId: 'run_1',
    delivery: 'input',
    kind: 'input'
  })
  const driver = yield* Driver
  yield* driver.awaitIdle('run_1')
}).pipe(Effect.provide(makeInMemoryHarnessLayer({ drain })))

await Effect.runPromise(program)
```

Run:

```bash
pnpm exec tsx drain-example.mts
```

Expected output:

```txt
drained item_1 for run_1
```

## Feature subpaths [#feature-subpaths]

| Subpath                                   | Purpose                                                               |
| ----------------------------------------- | --------------------------------------------------------------------- |
| `@yolk-sdk/harness`                       | Tiny root                                                             |
| `@yolk-sdk/harness/coordinator`           | Process-local doorbell coordinator                                    |
| `@yolk-sdk/harness/store`                 | `RunStore` claim/release                                              |
| `@yolk-sdk/harness/inbox`                 | Admission / steer / queue items; in-memory HITL park tokens           |
| `@yolk-sdk/harness/driver`                | `Driver`, `makeHarness`, `makeDriverLayer`, `admit`                   |
| `@yolk-sdk/harness/driver/memory`         | In-memory driver and harness layer                                    |
| `@yolk-sdk/harness/driver/durable-object` | Snapshot claim store plus driver for Durable Object storage           |
| `@yolk-sdk/harness/outcome`               | Classify one model/tool attempt after that invocation's inner retries |

See [Harness APIs](../api-reference/harness) for export tables.

## Shared instance, ack, and stop [#shared-instance-ack-and-stop]

Ownership is per shared Driver instance. The host or platform supplies cross-process exclusivity and quiesces producers before closing that instance.

`interrupt` / `stop` acknowledge **request delivery** when the interruption-request fiber is joined. That is not owner settlement. `awaitIdle` is quiescence, not a success receipt. `run` observes start and settlement failures.

* User `stop` (or generic `interrupt` with reason `user`) is terminal at the captured owner's settlement and releases a leftover claim after that owner has actually settled.
* Shutdown interrupt keeps the claim.
* A drain defect releases the claim, except while the run has a Ready park (answers no drain acknowledged): the claim stays, including when a successor woken behind the defect skips and succeeds, and a later `resumeSuspended` in the same process re-delivers them under `maxResumeAttempts`. Nothing retries on its own, so hosts that want in-process recovery after a crashed continuation run `resumeSuspended` during runtime, not only at boot. After a restart the in-memory park is gone; the host rebuilds it from its checkpoint.

## Setup and recovery [#setup-and-recovery]

Startup is explicit:

1. Build one shared Driver / Inbox / Store.
2. Restore host-owned waiting checkpoints through `run` / `pause`.
3. Call `Driver.resumeSuspended` before exposing ingress.

`resumeSuspended` is a finite current-snapshot sweep, not a Layer boot loop. Candidate IDs are hints, not durable incarnation IDs. Recovery is at-least-once, never exactly-once. Active candidates and candidates with blocked parks are skipped; the sweep does not release every persisted claim.

`maxResumeAttempts` is a finite nonnegative safe integer. The default is `10`. Exhausted eligible claims are released and those IDs are returned in `exhausted`. `0` schedules, drains, and increments nothing: the sweep still releases eligible candidates as exhausted. Zero is not a nonmutating pause that preserves those claims.

## Drain token, HITL, and storage [#drain-token-hitl-and-storage]

Host drains receive `DrainContext.drainToken` (branded `DrainToken`) and must pass it to `pause`
and `Inbox.takePromotable`. Park state/admission use a distinct `ParkGeneration`; both schema/type
companions are exported from `@yolk-sdk/harness/inbox`. They remain plain strings on the wire and
are nominal distinctions only—not proof of freshness or ownership. `takePromotable` rejects missing, empty, inactive, stale, or wrong-run tokens by returning `undefined` and leaving the queue unchanged. `pause` returns `Parked` or `Stale`; wrong or stale tokens are `Stale`. `pause` takes a non-empty request id list (`Array.NonEmptyReadonlyArray<string>`): a park with no request ids would be Ready at once and keep the claim with nothing to wake the run. Map `AwaitingInput.requests` (non-empty) with Effect's `Array.map`.

Hosts persist typed HITL payloads by item id. Inbox stores only opaque generation, request ids, and response item ids. Memory Inbox park state is process-lifetime only.

Claim snapshots are not transcript storage. `makeDurableObjectDriverLayer` requires host `load` / `save` callbacks and persists claimed ids plus resume counts. That adapter still constructs an in-memory Inbox. It does not persist queued input, parked HITL, host closures, or automatically reconstruct work.

## Outcomes [#outcomes]

`attemptModelTurn` classifies **one `runModelTurn` invocation** after that stream's configured loop/provider retries. It does not add an outer retry loop. Hosts that own physical-attempt scheduling should pass `LoopConfig.maxRetries: 0` and skip retry decorators.

Incomplete streams (`LLMError.responseIssue === 'missing_done'`) become `RecoverFull` before output or `Continue` after partial text/reasoning/completed calls. Content-filter and other nonretryable terminals stay failed. `onEvent` sink errors, compact errors, Abort, and mixed defect/interrupt Causes are not classified as provider `Retry` / `Continue`. `Completed` and `Continue` carry `usageUnavailable: true` when the model stream ended without its usage report.

See [Loop and runtime](../agent/loop-runtime) for collectors and [Harness composition](../vercel-workflows/harness-composition) for Workflow hosts.

## What the host provides [#what-the-host-provides]

Your app owns tools, prompts, auth, concrete Store/Inbox adapters, HITL payload persistence, transcript storage, cross-process exclusivity, and `'use workflow'` / `'use step'` files. Cloudflare and Next example policy is host-owned, not SDK surface.


---

# Knowledge package

URL: /docs/knowledge

Store simple durable knowledge, inject pinned context, search chunks, and expose lookup/manage tools.



Use `@yolk-sdk/knowledge` when your app needs durable agent-readable knowledge.

Knowledge is intentionally small:

```txt
KnowledgeDocument
  id
  slug
  title
  purpose
  origin
  content
  summary?
  errorMessage?
  reviewedAt?
  metadata?
  status: processing | ready | error
  availability: pinned | searchable | archived
  createdAt
  updatedAt
```

`KnowledgeSource` separately models `File`, `Url`, or `Text` ingestion origins. Construct them with
`KnowledgeFileSource.make`, `KnowledgeUrlSource.make`, and `KnowledgeTextSource.make` from
`@yolk-sdk/knowledge/documents`.
`IndexedKnowledgeDocument` carries that source plus indexing status and optional
title/summary/error/hash/count metadata. It is distinct from the content-oriented
`KnowledgeDocument` above.

Status and availability are independent:

* `processing`: indexing, not ready for prompt/search
* `ready`: usable when availability allows
* `error`: retained with an ingestion/indexing failure
* `pinned`: host may inject into startup context and search
* `searchable`: host may expose through search
* `archived`: retained but normally excluded

The helpers do not enforce this policy automatically. Pass only selected documents to
`buildKnowledgeContext`, and filter status/availability in your `SearchIndexStore` adapter.

Install:

```bash
pnpm add @yolk-sdk/knowledge@canary @yolk-sdk/agent@canary effect@4.2.0
```

## Use pinned knowledge as context [#use-pinned-knowledge-as-context]

```ts
import { buildKnowledgeContext } from '@yolk-sdk/knowledge'

const context = buildKnowledgeContext({
  documents,
  maxCharacters: 6000
})
```

Add the resulting text to your system prompt. Your app chooses which documents are pinned.

## Ingest a document into search [#ingest-a-document-into-search]

`ingestKnowledgeDocument` updates an `IndexedKnowledgeDocument`: it upserts `processing`, extracts,
chunks, embeds and summarizes, replaces chunks, then marks the index record `ready`. It does not
update `KnowledgeStore` automatically.

Fragment; `loadedSource` and service layers are host-owned:

```ts
import { KnowledgeDocumentId, KnowledgeScopeId } from '@yolk-sdk/knowledge/documents'
import { ingestKnowledgeDocument } from '@yolk-sdk/knowledge/ingestion'

const program = ingestKnowledgeDocument({
  scopeId: KnowledgeScopeId.make('workspace-docs'),
  documentId: KnowledgeDocumentId.make('doc_123'),
  source: loadedSource
})
```

Provide these layers from your app:

* `SearchIndexStore`
* `KnowledgeExtractor`
* `KnowledgeChunker`
* `KnowledgeEmbedder`
* `KnowledgeSummarizer`

The pipeline is not a cross-operation transaction. Your `SearchIndexStore` owns atomic chunk
replacement, rollback policy, and ready/error filtering. Failures retain their stage on
`KnowledgeIngestionError` and trigger a best-effort `markDocumentError` call with the message.

## Search documents [#search-documents]

```ts
import { Effect } from 'effect'
import { KnowledgeScopeId, KnowledgeSearchScope } from '@yolk-sdk/knowledge/documents'
import { searchKnowledge } from '@yolk-sdk/knowledge/search'

const results = await Effect.runPromise(
  searchKnowledge({
    scope: KnowledgeSearchScope.make({ id: KnowledgeScopeId.make('workspace-docs') }),
    query: 'How do agent tools work?',
    limit: 5,
    mode: 'hybrid',
    contextChunks: 1
  }).pipe(Effect.provide(HostKnowledgeSearchLayer))
)
```

The value `KnowledgeSearchScope` is the single-id constructor (tag `KnowledgeScope`).
`KnowledgeSearchScopes.make({ ids })` covers multiple ids. The type `KnowledgeSearchScope` is the union.

Scope and document identities use distinct `KnowledgeScopeId` / `KnowledgeDocumentId` schemas
from `@yolk-sdk/knowledge/documents`. `.make` is for trusted values; Effect-decode request and
persisted IDs with `Schema.decodeUnknownEffect` before entering store, chunking, or ingestion
contracts. Both remain non-empty trimmed strings on the wire. Branding does not prove scope
membership or authorization.

The package defines the search contract. Your app implements the store and embedding provider.

## Expose tools [#expose-tools]

```ts
import { makeKnowledgeLookupTool, makeKnowledgeManageTool } from '@yolk-sdk/knowledge/agent'

const lookupTool = makeKnowledgeLookupTool(lookupHandlers)
const manageTool = makeKnowledgeManageTool(manageHandlers)
```

Use `knowledge_lookup` for search/get and `knowledge_manage` for explicit saves, pins, archives, renames, or deletes. Your app owns authorization and scope resolution.

Both tools declare an output schema (`KnowledgeLookupOutput`, `KnowledgeManageOutput`) and return
its JSON encoding as `structuredContent` next to the text, which code mode scripts receive:

* lookup: `{ operation: 'search', results }` or `{ operation: 'get', document }`, with ISO date
  strings in documents;
* manage: `{ operation, document }`, where `document` is `{ id, slug, title }`.


---

# Ingest knowledge

URL: /docs/knowledge/ingestion-pipeline

Wire extraction, chunking, embeddings, summarization, and search storage into the ingestion pipeline.



`@yolk-sdk/knowledge` defines contracts. Your app provides concrete providers and stores.

## Install [#install]

```bash
pnpm add @yolk-sdk/knowledge@canary @yolk-sdk/agent@canary effect@4.2.0
```

## Pipeline shape [#pipeline-shape]

`ingestKnowledgeDocument` requires these Effect services:

| Service               | Host provides                                                               |
| --------------------- | --------------------------------------------------------------------------- |
| `SearchIndexStore`    | scope/document/chunk persistence and search                                 |
| `KnowledgeExtractor`  | extraction/normalization from caller-loaded `LoadedKnowledgeSource.content` |
| `KnowledgeChunker`    | text chunking; `DefaultKnowledgeChunkerLive` is available                   |
| `KnowledgeEmbedder`   | embedding provider                                                          |
| `KnowledgeSummarizer` | title/summary provider; use `NoopKnowledgeSummarizerLive` for simple hosts  |

For PDF, DOCX, XLSX, PPTX, and text bytes, `@yolk-sdk/extractors` can provide `KnowledgeExtractor`
(fragment):

```ts
import { Layer } from 'effect'
import { FileKnowledgeExtractorLayer } from '@yolk-sdk/extractors/knowledge'
import { FileExtractorLayer } from '@yolk-sdk/extractors/node'

const HostExtractorLayer = FileKnowledgeExtractorLayer.pipe(Layer.provide(FileExtractorLayer))
```

`@yolk-sdk/extractors/node` is server-only, and XLSX needs the optional SheetJS peer. See
[Extract file text](../integrations/file-extraction) for install, limits, worker isolation, and
errors.

## Ingest a document [#ingest-a-document]

Fragment; supply the host layers and `loadedSource` below:

```ts
import { Effect, Layer } from 'effect'
import { DefaultKnowledgeChunkerLive } from '@yolk-sdk/knowledge/chunking'
import { KnowledgeDocumentId, KnowledgeScopeId } from '@yolk-sdk/knowledge/documents'
import { NoopKnowledgeSummarizerLive } from '@yolk-sdk/knowledge/summarization'
import { ingestKnowledgeDocument } from '@yolk-sdk/knowledge/ingestion'

const KnowledgeLayer = Layer.mergeAll(
  HostSearchIndexStoreLayer,
  HostExtractorLayer,
  DefaultKnowledgeChunkerLive(),
  HostEmbedderLayer,
  NoopKnowledgeSummarizerLive
)

await Effect.runPromise(
  ingestKnowledgeDocument({
    scopeId: KnowledgeScopeId.make('workspace-docs'),
    documentId: KnowledgeDocumentId.make('doc_123'),
    source: loadedSource,
    contentHash: 'sha256:...'
  }).pipe(Effect.provide(KnowledgeLayer))
)
```

`DefaultKnowledgeChunkerLive` splits with `gpt-tokenizer`'s `o200k_base` encoding, about 2 MB of
code. It loads lazily: importing `@yolk-sdk/knowledge/chunking` or `./ingestion` and providing the
layer evaluate none of it, and the first chunked document loads it once per process or Worker
isolate. Providing the layer on every request is cheap. To count tokens or chunk text yourself, run
the Effects `countKnowledgeChunkTokens(text)` and `chunkKnowledgeText(input, maxTokens)` from the
same subpath.

`loadedSource` is host-owned source metadata/content from `@yolk-sdk/knowledge/extraction`.
The package does not fetch `Url` sources or resolve `File.ref`; load bytes/text before ingestion.
`KnowledgeFileBlobStore` is not consumed automatically by `ingestKnowledgeDocument`.

## What ingestion does [#what-ingestion-does]

1. Upserts an `IndexedKnowledgeDocument` with `processing` status.
2. Extracts source text and metadata.
3. Chunks text using `maxTokens` or the default chunk size.
4. Embeds chunks and summarizes concurrently.
5. Verifies one embedding exists per chunk, then calls `replaceDocumentChunks`.
6. Marks the index document `ready` with title, summary, token count, and chunk count.

On failure, the returned `KnowledgeIngestionError` carries a `store`, `extract`, `chunk`, `embed`,
or `summarize` stage. The pipeline best-effort calls `markDocumentError` with the error message; if
that call also fails, it preserves the original failure.

The calls are not one package-owned transaction. `SearchIndexStore.replaceDocumentChunks` names
the replacement operation, but the host adapter owns its atomicity and rollback behavior. For
example, a later `markDocumentReady` failure may leave replaced chunks beside an `error` status
unless the adapter coordinates those writes. Ingestion does not update the separate
`KnowledgeStore` document automatically.

Use `.make` for these trusted example constants. Decode request/persisted IDs with
`Schema.decodeUnknownEffect(KnowledgeScopeId)` / `Schema.decodeUnknownEffect(KnowledgeDocumentId)`;
your store adapter must return those branded types too. JSON remains plain strings, and host
permission checks remain necessary.

## Search after ingestion [#search-after-ingestion]

Fragment continuing the setup above:

```ts
import { KnowledgeSearchScope } from '@yolk-sdk/knowledge/documents'
import { searchKnowledge } from '@yolk-sdk/knowledge/search'

const results = await Effect.runPromise(
  searchKnowledge({
    scope: KnowledgeSearchScope.make({ id: KnowledgeScopeId.make('workspace-docs') }),
    query: 'How do approvals work?',
    mode: 'hybrid',
    limit: 5,
    contextChunks: 1
  }).pipe(Effect.provide(KnowledgeLayer))
)
```

Hybrid mode combines vector and text search with reciprocal-rank fusion.

## Add as an agent tool [#add-as-an-agent-tool]

```ts
import { Effect } from 'effect'
import { makeKnowledgeLookupTool } from '@yolk-sdk/knowledge/agent'

const lookupTool = makeKnowledgeLookupTool(HostKnowledgeLookupHandlers)
```

Resolve this tool with `@yolk-sdk/agent/tools` and pass it to the loop.

## Production notes [#production-notes]

* Check permissions before choosing `scope`.
* Keep scope ids tenant-safe and host-owned.
* Store embedding model/dimensions in host-owned config.
* Filter search to host-approved `ready` records and active availability; the search helper does
  not enforce document status or availability.
* Re-ingest on content hash changes.
* Treat archived knowledge as retained but normally excluded from active search.


---

# MCP auth, local servers, and server policy

URL: /docs/mcp/auth-local-server

Configure remote auth headers, Node-only local stdio, and tool-only MCP servers safely.



MCP is infrastructure. Your app owns server config, credentials, auth, product policy, and enabled tools.

## Remote auth [#remote-auth]

Pass host-resolved headers into remote config:

```ts
import { Effect } from 'effect'
import { FetchHttpClient } from 'effect/http'
import { listRemoteMcpServerTools } from '@yolk-sdk/mcp/client'

const tools = await Effect.runPromise(
  listRemoteMcpServerTools({
    name: 'figma',
    type: 'remote',
    url: 'https://mcp.figma.com/mcp',
    headers: {
      authorization: `Bearer ${figmaAccessToken}`
    }
  }).pipe(Effect.provide(FetchHttpClient.layer))
)
```

Remote MCP requires HTTPS by default. `http://localhost` is only for explicit dev policy.

## Local stdio [#local-stdio]

Use `@yolk-sdk/mcp/client/node` only from Node hosts. It imports `@effect/platform-node`, an optional
peer of `@yolk-sdk/mcp` (`~4.2.0`): install it at the same version as `effect`.

```ts
import { execPath } from 'node:process'
import { Effect } from 'effect'
import { listLocalMcpServerToolsNode } from '@yolk-sdk/mcp/client/node'

const tools = await Effect.runPromise(
  listLocalMcpServerToolsNode(
    {
      name: 'local-files',
      type: 'local',
      command: [execPath, './mcp-server.mjs'],
      environment: {
        EXAMPLE_TOKEN: token
      }
    },
    {
      securityPolicy: {
        allowLocalServers: true,
        allowDevHttpLocalhost: false
      }
    }
  )
)
```

Local stdio uses explicit environment only; host environment inheritance is disabled. Prefer an
absolute executable such as `execPath`. If a bare executable or `/usr/bin/env` shebang is required,
pass an explicitly allowlisted `PATH`; never pass the host process environment wholesale.

The client keeps the server's stdin open until it has its answers, and reads every stdout line as
one JSON-RPC message (MCP `2025-11-25`, stdio transport). It answers a server `ping` with an empty
result, answers any other server request with JSON-RPC error `-32601` (it declares no client
capability), and ignores notifications such as `notifications/message`. A line that is not a
JSON-RPC message (including a request or notification whose `params` is not an object) fails the
operation; write logs to stderr, which the client ignores.

## Tool name mapping [#tool-name-mapping]

MCP tool names become model-visible Yolk tool names by prefixing the sanitized server name:

```txt
server: docs
mcp tool: search
agent tool: docs_search
```

When executing a model tool call, map `call.name` back to the resolved MCP tool and call by raw `mcpToolName`.

## Full MCP v2 server policy [#full-mcp-v2-server-policy]

The official `Client`, `McpServer`, `createMcpHandler`, MRTR, subscriptions, and protocol helpers are exported from `@yolk-sdk/mcp/client`, `@yolk-sdk/mcp/server`, and `@yolk-sdk/mcp/core`.

For HTTP servers:

* Validate `Origin` and `Host` before `createMcpHandler().fetch`.
* Authenticate every stateless request; do not rely on connection or session identity.
* Partition `cacheScope: 'private'` entries by authorization context.
* Integrity-protect MRTR `requestState` when it affects authorization, resource access, or business logic.
* Treat self-reported client/server identity and tool annotations as untrusted.

## Tool-only MCP server [#tool-only-mcp-server]

Expose app-approved Yolk tools over MCP:

```ts
import { makeMcpToolServer } from '@yolk-sdk/mcp/server'

const server = makeMcpToolServer({
  name: 'yolk-tools',
  version: '0.1.0',
  tools: approvedTools
})
```

The adapter serves stateless MCP `2026-07-28` and initialize-based legacy HTTP clients for `tools/list` and `tools/call`; a `2026-07-28` `subscriptions/listen` answers its acknowledgement and `complete`. No tool call outlives `handleHttpRequest` (see [Expose Yolk tools through MCP](./index#expose-yolk-tools-through-mcp)). It does not own routes, auth, resources, prompts, or deployment. Use the official `McpServer` exports for the full core protocol.

## Policy checklist [#policy-checklist]

* Persist server config outside the SDK.
* Resolve credentials server-side.
* Filter enabled tools per user/session.
* Keep local servers disabled unless a Node host explicitly allows them.
* Audit tool calls and preserve MCP `isError` / `structuredContent`.
* Never let browser clients submit arbitrary MCP server configs directly to execution.


---

# MCP package

URL: /docs/mcp

List MCP tools, call them, or expose Yolk-compatible tools through MCP.



Use `@yolk-sdk/mcp` when your app needs to connect an agent to Model Context Protocol servers.

For auth, local stdio, and server policy, see [MCP auth, local servers, and server policy](./auth-local-server).

Install:

```bash
pnpm add @yolk-sdk/mcp@canary @yolk-sdk/agent@canary effect@4.2.0
```

## Connect with the full MCP v2 client [#connect-with-the-full-mcp-v2-client]

Use the official client API for tools, resources, prompts, completions, MRTR, subscriptions, response caching, and OAuth protocol helpers:

```ts
import { Client, StreamableHTTPClientTransport } from '@yolk-sdk/mcp/client'

const client = new Client(
  { name: 'my-app', version: '1.0.0' },
  { versionNegotiation: { mode: 'auto' } }
)

await client.connect(new StreamableHTTPClientTransport(new URL('https://example.com/mcp')))

const tools = await client.listTools()
const resources = await client.listResources()
const prompts = await client.listPrompts()
```

`mode: 'auto'` prefers stateless MCP `2026-07-28` and falls back to initialize-based servers. Use `{ pin: '2026-07-28' }` for modern-only behavior. The upstream `Client` default remains legacy for compatibility.

Import official wire schemas from `@yolk-sdk/mcp/core`. Import Node stdio transports from `@yolk-sdk/mcp/client/node` and `@yolk-sdk/mcp/server/node`.

## List remote MCP tools for a Yolk agent [#list-remote-mcp-tools-for-a-yolk-agent]

```ts
import { Effect } from 'effect'
import { FetchHttpClient } from 'effect/http'
import type { McpRemoteServerConfig } from '@yolk-sdk/mcp/client'
import { listRemoteMcpServerTools } from '@yolk-sdk/mcp/client'

const config = {
  name: 'docs',
  type: 'remote',
  url: 'https://example.com/mcp'
} satisfies McpRemoteServerConfig

const tools = await Effect.runPromise(
  listRemoteMcpServerTools(config).pipe(Effect.provide(FetchHttpClient.layer))
)
```

Each item contains:

* `serverName`
* original `mcpToolName`
* Yolk `ToolDef` as `def`

Pass `tools.map(tool => tool.def)` into the agent loop.

## Call a remote MCP tool [#call-a-remote-mcp-tool]

```ts
import { makeToolFileCapture } from '@yolk-sdk/agent/tools'
import { callRemoteMcpServerTool } from '@yolk-sdk/mcp/client'

const result = await Effect.runPromise(
  callRemoteMcpServerTool({
    config,
    mcpToolName: 'search',
    toolCallId: 'call_123',
    params: { query: 'Yolk SDK' },
    // Stores the call's blobs, images and audio (`store` is your FileStoreApi).
    fileCapture: makeToolFileCapture({ store })
  }).pipe(Effect.provide(FetchHttpClient.layer))
)
```

The result is a Yolk `ToolResult`, ready to feed back into the agent loop. Its `structuredContent`
is `{ value, files }`: `value` is the server's `structuredContent` (checked against the listed
`outputSchema`), else the text of its text blocks and embedded text resources, parsed once when it
is one JSON object or array; `files` are its blobs, images and audio as `FileRef` (or
`FileUnavailable`). Inside a `resolveTools` registration the files are stored through the
resolution's `files`; a call made anywhere else (a route, a resume) passes `fileCapture`, or every
file is `FileUnavailable` (`no file store`) and the blob is lost: MCP blobs cannot be fetched again.
Registrations built from listed tools set `decodeOutput: mcpToolOutputDecoder`
([Add MCP tools](../integrations/mcp-tools)).

## Confirm tool calls with form elicitation [#confirm-tool-calls-with-form-elicitation]

Some servers confirm destructive tools with MCP form elicitation over multi round-trip requests
(MRTR, protocol `2026-07-28`): the first `tools/call` answers an `InputRequiredResult` (a form plus
an opaque `requestState`), and the client retries the same call with the user's decision. Yolk
models this for durable hosts: nothing blocks waiting for a person.

Opt in with `elicitation: { form: true }`. The listing and the resumable call functions then declare
`elicitation.form` in the per-request `_meta` client capabilities of a modern connection (never in a
legacy `initialize`). `callRemoteMcpServerToolResumable` answers a typed outcome:

An integration fragment: `collectDecision` stands for the host's own flow (persist the pause, show
the form to a person, await their answer, possibly in another process). Never auto-accept a
confirmation; when no person decides, answer `decline` or `cancel`.

```ts
import { makeToolFileCapture } from '@yolk-sdk/agent/tools'
import {
  callRemoteMcpServerToolResumable,
  resumeRemoteMcpServerToolCall,
  type McpClientOptions,
  type McpElicitationResponse,
  type McpFormElicitation
} from '@yolk-sdk/mcp/client'

// Host-owned: renders the form, waits for a person, and returns their decision.
declare const collectDecision: (form: McpFormElicitation) => Promise<McpElicitationResponse>

const options: McpClientOptions = { elicitation: { form: true } }

// The resume runs outside `resolveTools` (a HITL route, another process): pass a capture, or the
// resumed result's blobs are `FileUnavailable` and lost (`store` is your FileStoreApi).
const call = {
  config,
  mcpToolName: 'delete-invoice',
  toolCallId: 'call_123',
  params,
  options,
  fileCapture: makeToolFileCapture({ store })
}

const outcome = await Effect.runPromise(
  callRemoteMcpServerToolResumable(call).pipe(Effect.provide(FetchHttpClient.layer))
)

if (outcome._tag === 'InputRequired') {
  // Persist `outcome.inputRequired` first: the decision may take hours and another process.
  const pending = outcome.inputRequired
  const entries: Array<[string, McpElicitationResponse]> = []

  for (const form of pending.elicitations) {
    // One decision per form, keyed by `form.key`, from a person.
    entries.push([form.key, await collectDecision(form)])
  }

  // `Object.fromEntries` keeps any server key as an own property (even `__proto__`).
  const responses = Object.fromEntries(entries)

  const resumed = await Effect.runPromise(
    resumeRemoteMcpServerToolCall({ ...call, inputRequired: pending, responses }).pipe(
      Effect.provide(FetchHttpClient.layer)
    )
  )
}
```

`McpInputRequired` is a Schema class: encode it with `Schema.encodeUnknownEffect` to persist it and
decode it in another process. Each `McpFormElicitation` carries the server's `key`, `message`, and
`requestedSchema` (flat primitive properties, kept as received). The pause is bound to its call
(`mcpToolName`, `argumentsDigest`) and carries the listed tool definition. Answer every elicitation
with `accept` (with `content`), `decline`, or `cancel`; decisions are checked against each form
(type (integer vs number), `required`, `const`, `enum`, titled `oneOf`, `minLength`/`maxLength`, `format` (email, uri, date, date-time), `minimum`/`maximum`, `items.enum`, titled `items.anyOf`, `minItems`/`maxItems`) before sending, and the server validates them again. The
resume is re-sent as a new request on a new connection with the same tool call, the exact
`requestState`, and the decisions as `inputResponses`. It lists nothing: the pause's tool definition
(`name`, `inputSchema`, `outputSchema`) drives header mirroring and the structured-output check, and
an invalid one fails `malformed` before sending. With that definition the official client does not
re-list and retry after a `HEADER_MISMATCH` (`-32020`), so a server that changed the tool's
`x-mcp-header` declarations since the pause answers `McpError` (`cause: 'protocol'`). The server
may pause again.

Failures are typed. `McpInputRequiredError` covers a `malformed` or `too_large` pause. The default
bound is 256 KiB of JSON and 16 requests; set `elicitation.maxInputRequiredBytes` to a positive
integer (checked before connecting). It applies separately to the server-provided pause (checked
after the body is buffered, without the tool definition) and to the listed tool definition (checked
before the call, so an oversized definition fails with nothing sent and never strands a pause). It
also covers an `unsupported_request` (URL mode,
sampling, roots, or any input without the opt-in), `invalid_responses` and `mismatched_resume`
(another tool or other arguments; both checked before sending), and `unsupported_era` (resuming on a
legacy connection). The pause is decoded from the raw `input_required` response as the server sent it:
the response the official client resolves the call with (matched by its own `Number(id)` coercion;
an id not identical to the call's fails `malformed`), captured at the transport before the client
normalises it. A non-string `requestState` or non-object `inputRequests` fails `malformed` instead of
passing as a valid or load-shedding pause; responses with other ids are ignored. Formats are checked
by syntax: RFC 3339 dates (a leap second only at `23:59:60` UTC), an absolute RFC 3986 URI (IPv6
literals per its grammar; not WHATWG URL parsing), and a pragmatic
mailbox (a dot-atom local part, `@`, a hostname of at least two labels). MCP `-32021` becomes
`McpClientCapabilityRequiredError` with `requiredCapabilities`. A server that reports a missing
capability as a tool error (for example Afloat's `CLIENT_CAPABILITY_REQUIRED`) answers a `Complete`
outcome with `isError: true`.

Legacy (pre-`2026-07-28`) elicitation is a server-initiated request that must be answered while the
call is open, so it is not supported: an opted-in host never declares elicitation on a legacy
connection. `callRemoteMcpServerTool` keeps its behavior and never declares it.

In an agent session, a registration stores the pause and returns an input-required result, and a
person answers through the input review interaction: see
[Finish calls that ask for input](../integrations/mcp-tools#finish-calls-that-ask-for-input).

## Use local stdio MCP [#use-local-stdio-mcp]

Use `@yolk-sdk/mcp/client/node` only in Node hosts:

See [MCP auth, local servers, and server policy](./auth-local-server#local-stdio) for a runnable Node
example, explicit environment rules, and the required `allowLocalServers` opt-in.

Worker/browser code should stay on `@yolk-sdk/mcp/client`.

## Build a full MCP v2 server [#build-a-full-mcp-v2-server]

Use `McpServer` and `createMcpHandler` for tools, resources, prompts, completions, MRTR, and subscriptions:

```ts
import { McpServer, createMcpHandler } from '@yolk-sdk/mcp/server'

const handler = createMcpHandler(() => {
  const server = new McpServer({ name: 'my-server', version: '1.0.0' })
  // Register tools, resources, and prompts here.
  return server
})

export default { fetch: handler.fetch }
```

`createMcpHandler` serves stateless MCP `2026-07-28` and legacy initialize-based HTTP clients. Put deployment authentication plus `Origin` and `Host` validation in front of `handler.fetch`.

## Expose Yolk tools through MCP [#expose-yolk-tools-through-mcp]

Use `makeMcpToolServer` from `@yolk-sdk/mcp/server` to expose a tool-only Yolk adapter. Its HTTP entrypoint accepts both modern and legacy requests. Use the official `McpServer` surface when you need other core capabilities.

A request that carries `MCP-Protocol-Version` with a body over `maxRequestBodySize` (default 4 MiB) is answered `413`; a host that accepts larger bodies passes its own cap to `makeMcpToolServer`. The header-less JSON path reads the body unbounded, so the host caps it.

To ask the user before a tool runs, give the tool an `approval` policy and the server `approvals` (a signing key of at least 32 bytes and the request's authenticated principal). The first call answers an MCP form elicitation over multi round-trip requests (`2026-07-28`), one required approve/deny choice (never an empty form, which some clients accept without showing it), with a signed, expiring `requestState`; only a retry that approves it for the same principal, tool, arguments and prompt runs the tool, with an `approvalId` to run it at most once. The prompt is built again on the retry, so build it deterministically: an accept of a prompt that changed since the user saw it runs nothing. To ask a form instead (yes/no, one choice, or a multi-select of titled options), build the tool with `makeMcpServerElicitedTool` and `mcpServerForm`: `execute` gets the answer decoded with the form's schema, and an answer that does not fit asks again. Clients that do not declare form elicitation get an error result, and 2025-era requests are not offered approval or elicited tools. See the [package README](https://github.com/magoz/yolk-sdk/blob/main/packages/mcp/README.md#ask-the-user-before-a-tool-runs).

### Forward a remote tool's forms [#forward-a-remote-tools-forms]

A tool that proxies a remote MCP tool can pass the remote server's form elicitation on to this
server's own client. Give it `forward: true` (an `McpServerForwardingTool`, optionally with its own
`approval`) and the server `approvals`. `execute(call, round)` runs one round and answers the remote
`McpToolCallOutcome`:

Fragment: `remoteConfig`, `def`, and the `HttpClient` layer are host-owned.

```ts
import { Effect } from 'effect'
import {
  callRemoteMcpServerToolResumable,
  resumeRemoteMcpServerToolCall
} from '@yolk-sdk/mcp/client'
import { McpForwardRound, McpServerError, type McpServerTool } from '@yolk-sdk/mcp/server'

const proxyDelete: McpServerTool = {
  def,
  forward: true,
  execute: (call, round) => {
    const remote = {
      config: remoteConfig,
      mcpToolName: 'delete',
      toolCallId: call.id,
      params: call.params
    }

    return McpForwardRound.$match(round, {
      // Opt into elicitation only when this server can forward a pause.
      Initial: ({ clientElicitation }) =>
        callRemoteMcpServerToolResumable({
          ...remote,
          options: clientElicitation ? { elicitation: { form: true } } : {}
        }),
      // Key once-only resumption on `roundId` (host-owned).
      Resume: ({ inputRequired, responses }) =>
        resumeRemoteMcpServerToolCall({
          ...remote,
          inputRequired,
          responses,
          options: { elicitation: { form: true } }
        })
    }).pipe(
      Effect.provide(httpClientLayer),
      Effect.mapError(error => new McpServerError({ message: error.message, cause: 'tool_error' }))
    )
  }
}
```

* `McpForwardRound.Initial({ clientElicitation, approvalId })` calls the remote tool.
  `clientElicitation` is true only on a `2026-07-28` request that declares form elicitation, with
  `approvals` configured: without it, a remote server that needs input refuses to run instead of
  pausing a call nobody can answer.
* A remote pause is answered as this server's own `InputRequiredResult` (the remote forms under
  their keys) with a `requestState` signed (not encrypted) by the approvals key under its own
  binding. It holds the tool, the arguments digest, the pause's `roundId` and expiry (`ttlSeconds`
  after it was forwarded), the approval id, and the remote pause, at most
  `mcpForwardMaxStateBytes` (64 KiB) of JSON. The client can read the remote forms and
  `requestState`.
* `McpForwardRound.Resume({ roundId, inputRequired, responses, approvalId })` runs only for a round
  whose verified state matches the call and answers every forwarded form (checked against the
  forms); other rounds are asked again in the same round (same `roundId` and expiry). A state that
  does not verify, or expired, answers `forwardStaleMessage` and calls nothing (with `approval`, the
  approval is asked again). The server keeps no state, so a replayed answered round arrives again
  with the same `roundId`: key once-only resumption on it.
* The host may answer a duplicate key (a retried accept on `approvalId`, a retried `Resume` on
  `roundId`) with the outcome it stored. A remote pause's `roundId` is derived from the approval or
  round it came from and the pause itself, so a replayed pause is forwarded again under the same
  `roundId` and still resumes once. A replay is accepted only while its origin (the approval or
  round state) is still valid, and the replayed pause then gets a fresh expiry. A first round
  without `approval` has no key, and its pause gets a random `roundId`.
* With `approval`, the tool is offered like an approval tool: the approval round runs first and
  every forward round carries its `approvalId`. Without it, the tool is listed everywhere; 2025-era
  requests and the header-less JSON path run only `Initial` with `clientElicitation: false`.
* A remote pause that cannot be forwarded answers an error result: `forwardUnsupportedMessage` (the
  client cannot answer forms), `forwardEmptyPauseMessage` (a pause without a form),
  `forwardOversizedMessage`, or `forwardMalformedMessage`.

No tool call outlives `handleHttpRequest`'s Effect, so you can provide its requirements from a scoped request layer. When an answer other than `subscriptions/listen` is an SSE stream (always for 2025-era requests), it is read to its end first and returned with the same status, headers and events (a read failure answers 500 with `-32603`), and a tool still running when the Effect ends is interrupted and awaited. A `subscriptions/listen` request is answered with its acknowledgement and a `complete` result: this server has no change notifications to stream. For requests that carry `MCP-Protocol-Version`, a client cancellation (on Streamable HTTP, closing the response stream) interrupts the tool's Effect.

## Conformance cases [#conformance-cases]

`@yolk-sdk/mcp/conformance` (experimental) holds nine read-only conformance cases that check the
wire claims the remote client relies on, against any MCP server you point them at, plus the opt-in
`mcpElicitationDeclarationCase` for hosts that declare form elicitation and the opt-in
`mcpServerPingCase` for legacy servers that ping their clients. See
[MCP conformance](../api-reference/conformance#mcp-conformance).

## Security defaults [#security-defaults]

Remote MCP requires HTTPS by default. Localhost HTTP is an explicit dev policy. Local stdio receives explicit env only and does not inherit host process env by default.


---

# Add code mode

URL: /docs/integrations/code-mode

Let the model write one short script that calls many tools and returns only what matters.



Code mode gives the model one tool, `codemode`, whose only input is a JavaScript program. The
script calls your resolved tools as `await tools.<id>(args)`, filters and aggregates their results
inside a confined sandbox, and returns a small value. Nested results never enter the conversation;
only the script output and return value do. Use it for paginated, bulk, and aggregate work that
would otherwise cost one model turn per tool call.

Install:

```bash
pnpm add @yolk-sdk/codemode@canary @yolk-sdk/agent@canary effect@4.2.0
```

Requires Node.js 22.19 or later. The executors are server-only: `./node` on Node, `./cloudflare`
in a Cloudflare Worker.

## Subpaths [#subpaths]

| Subpath                         | Use for                                                                                                                                                                           |
| ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `@yolk-sdk/codemode`            | `makeCodeModeTool` (with the `stage` global for staged plans), the `CodeModeExecutor` interface, catalog and search helpers, `codeModeStoreFromToolResults`, `makeClassifierTool` |
| `@yolk-sdk/codemode/node`       | `makePiCodeModeExecutor`: a fresh QuickJS (WebAssembly) VM in a worker thread per script                                                                                          |
| `@yolk-sdk/codemode/cloudflare` | `makeDynamicWorkerCodeModeExecutor`: a fresh Dynamic Worker isolate without network access per script ([Cloudflare Workers](#cloudflare-workers))                                 |

## Set up [#set-up]

Add the code mode tool next to your other tool modules. This fragment assumes host-owned
`HostContext`, `hostModules`, and `hostContext` values.

```ts
import { Effect } from 'effect'
import { resolveTools } from '@yolk-sdk/agent/tools'
import { makeCodeModeTool } from '@yolk-sdk/codemode'
import { makePiCodeModeExecutor } from '@yolk-sdk/codemode/node'

// Module scope: one executor per process, so its concurrency cap is per process.
const executor = makePiCodeModeExecutor({ maxConcurrentExecutions: 4 })

const codemode = makeCodeModeTool<HostContext>({ executor })

const program = Effect.gen(function* () {
  const toolSet = yield* resolveTools(
    [{ id: 'codemode', tools: [codemode] }, ...hostModules],
    hostContext
  )

  return toolSet
})
```

Pass `toolSet.tools` and the executor layer to the loop as usual. By default the resolved
`codemode` definition lists the tools scripts can call; with many or changing tools, deliver that
catalog as an instruction instead (see [Deliver the catalog as instructions](#deliver-the-catalog-as-instructions)).

### Cloudflare Workers [#cloudflare-workers]

A Worker cannot start the pi executor's worker thread. Run scripts in Dynamic Workers instead: each
execution loads a fresh isolate with no network access through a Worker Loader binding, evaluates
the same prelude, tools guard, and rejection codes as the Node executor, and calls your tools back
over RPC.

```ts
import { env } from 'cloudflare:workers'
import { makeCodeModeTool } from '@yolk-sdk/codemode'
import { makeDynamicWorkerCodeModeExecutor } from '@yolk-sdk/codemode/cloudflare'

// The binding is read when a script runs, so the executor can live at module scope.
const executor = makeDynamicWorkerCodeModeExecutor({ loader: () => env.LOADER })

const codemode = makeCodeModeTool<HostContext>({ executor })
```

Declare the Worker Loader binding in the Worker's configuration (`"worker_loaders": [{ "binding":
"LOADER" }]` in Wrangler; the binding name is yours). `memoryLimitBytes` and a concurrency cap do
not apply.

* `cpuMs` (default 500) becomes the isolate's CPU limit and is the real ceiling of a script; a
  script past it fails with a `timeout`. The timeout and abort signal only answer the caller early:
  a synchronous loop keeps running until its CPU limit.
* An execution that ends at its CPU limit (or times out, or is aborted) keeps the output the script
  printed before its last tool or global call, which is when output reaches your Worker; output
  printed after that call is lost.
* When an execution ends, tool calls still pending are rejected at once and their signal aborts,
  and later calls are rejected without running, so an unawaited call never keeps a Dynamic Worker
  in flight (Cloudflare allows 4 per request, 10 per Durable Object).
* Loader and isolate failures reach the caller as fixed messages, never the runtime's error text
  (see [Log executor failures](#log-executor-failures)).
* Every execution loads one Dynamic Worker, and each is billed.
* A tool's `streamedArgument` (for example `file_save`'s `content`) of 64 Ki characters or more
  reaches your Worker as a byte stream beside the call, never as one JSON string; the tool reads it
  with `toolStreamedArgument`. Counting and encoding it is the script's CPU.

### Log executor failures [#log-executor-failures]

Both executors answer their own failures (not the script's) with fixed messages, so runtime error
text, which may carry host details or secrets, never reaches the script or the model. Pass
`onInternalError` to log the original error:

```ts
const executor = makeDynamicWorkerCodeModeExecutor({
  loader: () => env.LOADER,
  // Host logs only: `cause` may carry secrets.
  onInternalError: ({ stage, cause }) => logger.error('code mode executor failed', { stage, cause })
})
```

`stage` is `load` (the sandbox could not be created or loaded), `isolate` (it failed while
running), `cpu-limit` (a Dynamic Worker past its CPU limit), or `host-call` (a Dynamic Worker
call's RPC to your Worker failed). `makePiCodeModeExecutor` takes the same option and reports `load`
and `isolate`. It is called once per such failure, never for script errors, tool rejections,
timeouts, or aborts, and whatever it throws is ignored. A script can fake a `host-call` report (its
isolate sends it), so at most 10 are accepted per execution.

### Next.js [#nextjs]

Keep the engine out of the bundle so its worker file and `quickjs.wasm` stay on disk:

```ts title="next.config.ts"
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  serverExternalPackages: ['@yolk-sdk/codemode', '@earendil-works/pi-codemode', 'quickjs-wasi']
}

export default nextConfig
```

Next file tracing then includes the worker file and the wasm module automatically. If you bundle
the engine anyway, pass `wasm` and `workerUrl` to `makePiCodeModeExecutor`.

### Vercel Workflow [#vercel-workflow]

Run the code mode call inside your tool-batch step (`'use step'`), like any other tool call. Never
run scripts inside a `'use workflow'` function: the workflow sandbox cannot host the engine, every
nested call would become durable events, and a busy loop could not be stopped.

* Pass `deadline` so the script timeout fits the step's remaining function budget. The timeout is
  clamped to the deadline minus 5 seconds and never drops below 1 second.
* Steps are at-least-once: supply a durable tool ledger (see
  [Survive step re-execution](#survive-step-re-execution)). Step retry settings alone do not stop a
  redelivered step from running the script again.
* The step output holds the bounded script result and the bounded nested-call record, never raw
  nested results.

```ts
const codemode = makeCodeModeTool<HostContext>({
  executor,
  deadline: context => context.stepDeadlineMs // epoch milliseconds, host-owned
})
```

## Choose what scripts can call [#choose-what-scripts-can-call]

Exposure is set on each tool with `callableBy` and, for code-mode-only tools, `discovery`:

| Setting                                         | Model calls it | Scripts call it | In the `codemode` description                                              |
| ----------------------------------------------- | -------------- | --------------- | -------------------------------------------------------------------------- |
| `callableBy: 'all'` (default)                   | yes            | yes             | one line: how scripts call it and what it resolves to (outside the budget) |
| `callableBy: 'model'`                           | yes            | no              | no                                                                         |
| `callableBy: 'codemode'`, `discovery: 'listed'` | no             | yes             | TypeScript declaration, within the inline budget                           |
| `callableBy: 'codemode'`, `discovery: 'search'` | no             | yes             | never; scripts find it with `searchTools()`                                |
| `callableBy: 'codemode'`, `discovery: 'pinned'` | no             | yes             | TypeScript declaration, always, outside the inline budget                  |

An `all` tool with `loading: 'deferred'` (see [Defer rarely used tools](../agent/tools-hitl#defer-rarely-used-tools))
is not in the model's context until loaded, so the catalog treats it like a `search` tool.

```ts
import { Effect } from 'effect'
import { makeTool } from '@yolk-sdk/agent/tools'

// With `output`, explicit type arguments are three: context, parameters, output.
const listInvoices = makeTool<HostContext, typeof ListInvoicesParams, typeof InvoicePage>({
  name: 'list_invoices',
  description: 'List invoices, newest first, one page at a time.',
  parameters: ListInvoicesParams, // host-owned Effect Schema
  output: InvoicePage, // calls resolve to the JSON encoding of this shape
  access: 'read',
  callableBy: 'codemode',
  discovery: 'search',
  execute: ({ params }) => listInvoicePage(params).pipe(Effect.map(page => ({ output: page })))
})
```

* Approval, input, interaction, and background tools, and the `question` and `subagent` tools,
  never run from code mode. Marking them `all` behaves as `model`; marking them `codemode` fails
  resolution, except an approval-gated tool you mark `staging`, which may be
  [stage-only](#stage-only-tools). Stageable tools can be staged for one review instead (see
  [Stage approval-gated writes](#stage-approval-gated-writes)).
* `codemode`-only tools are never sent to model providers.
* Listed tools fill an inline budget (default 3,000 estimated tokens) fairly across tool modules:
  each round every module places its cheapest remaining tool. `all` tools are already declared to
  the model, so their lines sit outside the budget.
* `search` tools contribute nothing to the description: no namespace heading, hint, or count.
  Adding or removing them, even a whole module of them, leaves the description byte-identical and
  the prompt cache intact. One fixed line always tells scripts to find unlisted tools with
  `searchTools()` (each hit has its call signature) or `describeNamespace()`.
* Give a module a `description` (`{ id, description, tools }`) to show it under the module's
  heading, return it from `describeNamespace()`, and make it searchable.
* Tools that poll (no timers in scripts) should stay `callableBy: 'model'` until they offer a wait
  parameter.

### Connector and MCP tools [#connector-and-mcp-tools]

Generated tools take the same exposure (`callableBy`, `discovery`, `loading`) through an `exposure`
option: one value for every tool, or a resolver per tool. Connector modules resolve per action (`(actionId, action) => exposure`, where
`action` carries the declared `access`); MCP definitions resolve per listed tool
(`(tool, serverName) => exposure`). This marks every connector action as a code-mode-only search
tool:

```ts
import { makeConnectorToolModule } from '@yolk-sdk/connectors/agent'
import { GithubConnector } from '@yolk-sdk/connectors/github'

const github = makeConnectorToolModule<HostContext>(GithubConnector, {
  integration: githubIntegration, // host-owned
  layer: connectorLayer, // host-owned
  exposure: { callableBy: 'codemode', discovery: 'search' }
})
```

For MCP, pass `exposure` to `mcpToolToToolDef` or in the listing options; each resolved `def`
then carries it:

```ts
import { listMcpServerTools } from '@yolk-sdk/mcp/client'

const tools = listMcpServerTools(serverConfig, {
  exposure: tool =>
    tool.annotations?.['readOnlyHint'] === true
      ? { callableBy: 'codemode', discovery: 'search' }
      : { callableBy: 'model' }
})
```

The fail-closed rules above still apply: resolution fails when an exposure contradicts the tool
(for example `codemode` on a non-stageable registration that requires approval).

## Deliver the catalog as instructions [#deliver-the-catalog-as-instructions]

`makeCodeModeTool({ executor, catalog: 'instructions' })` keeps the `codemode` description
invariant and delivers the catalog as a host instruction instead: every namespace with its tool
count and description, `listed` tools within the inline budget, and `pinned` tools always. A
changed catalog is appended to the conversation, whole, so connecting or disconnecting tools never
rewrites the cached request prefix (tool definitions and earlier messages).

```ts
const codemode = makeCodeModeTool<HostContext>({ executor, catalog: 'instructions' })

const toolSet =
  yield * resolveTools([{ id: 'codemode', tools: [codemode] }, ...hostModules], hostContext)

// run() appends the catalog instruction when it changed:
run({ messages, systemPrompt, tools: toolSet.tools, instructions: toolSet.instructions, model })
```

* Durable hosts driving `runModelTurn` append and persist
  `instructionMessages(transcript, toolSet.instructions)` from `@yolk-sdk/agent/loop` before each
  model step (see [Host instructions](../agent/loop-runtime#host-instructions)).
* Hosts that cannot append messages to their conversation can render the instruction into the
  system prompt (`instruction.render(instruction.state)`, only while `instruction.state` is defined:
  `undefined` renders the removal notice); a catalog change then invalidates the cache from the
  system prompt on.
* Custom compaction must keep `latestInstructionMessages(...)` after its summary, as window
  compaction does. `catalog: 'description'` (the default) keeps the catalog in the description.

## What scripts see [#what-scripts-see]

* `code` is the body of an async function: top-level `await` and `return` work. Simple TypeScript
  annotations are stripped; enums and namespaces are rejected with a clear error.
* `tools.<id>(args)` runs the tool through the resolved tool set with your host context: inputs are
  decoded, disabled tools stay unavailable, and registration wrappers run. A tool with an output
  schema resolves to its declared value (a typed result without a value rejects with
  `returned an invalid result`); a tool without one resolves to its text (`string`). A call rejects
  with an `Error` when the tool returns an error result, with `error.code` when the tool reports a
  code. Unknown names suggest close matches. Calls still running when the script ends are cancelled.
* Files are typed fields of results: `FileRef { fileId, name, mimeType, size }` or
  `FileUnavailable { unavailable, name, mimeType }`. Script values never contain file labels. Pass
  the `fileId`s to other tools; file bytes never enter the script ([Move files between
  tools](./files)).
* Arguments make a JSON round trip, and the tool decodes them exactly as it decodes model calls:
  * The argument is read once, the way `JSON.stringify` reads it (each getter and `toJSON` runs
    once), into a checked JSON copy, and that copy is what the call sends.
  * A key set to `undefined` is absent, and `null` on an optional argument means absent.
  * An unknown key rejects the call with a hint that names the keys allowed there.
  * Values JSON would silently change reject inside the script before the call is made (it never
    runs and is not recorded): `NaN`, `Infinity`, invalid `Date`s, `undefined` or functions in
    arrays, `Map`, `Set`, functions, symbols, bigints, cycles, and class instances. For example
    `tools.search: argument at limit is NaN; pass a finite number or omit the key`.
  * Values with `toJSON` pass as their JSON, checked by the same rules: a valid `Date` becomes its
    ISO string. An error thrown by a getter or `toJSON` rejects the call with that error.
  * An argument with more than 100000 values or nested more than 64 levels deep is rejected too
    (`tools.search: argument has more than 100000 values; split the work across calls`).
  * The checks use built-ins captured before the script runs, and the copy has no prototypes, so
    a script that changes `Array.prototype`, `Date`, or other built-ins cannot change what is
    checked or sent.
* A rejected call's message starts with the call's label: `tools.<id>`, or `tools["<name>"]` for a
  tool whose identifier an earlier tool already uses (scripts call it by that name when the name
  is still free; a tool whose identifier and name are both taken is unreachable). Error results,
  argument rejections, `beforeNestedCall` failures, and the `maxNestedCalls` limit read
  `<label>: <message>`. Only the message and `error.code` (a tool's error code, or the code of a
  `CodeModeNestedCallRefused`) cross into the script. `ToolResult.nestedCalls` records the tool's
  own message without the prefix.
* A nested call that is interrupted rejects with `<label> was cancelled.`; one whose tool fails
  with a defect rejects with `<label> failed unexpectedly.` and is recorded as `error`.
* A nested call that [paused for a person's input](../agent/tools-hitl#finish-calls-that-paused-for-input)
  (an MCP server asking a form) rejects like any error result, with
  `error.code === 'input_required'`. It has not completed. Whether or not
  the script caught the rejection, the result's `structuredContent.codemode.inputRequired` lists
  every such pause (`ToolInputRequiredRef`s `{ reviewToolName, pauseIds }`, merged per review tool),
  and a notice after the bounded output names the review call, for example
  `review_input({"pauseIds":["p1"]})`. Work that needs the value continues in a new script from the
  review result, never by calling the tool again.
* Globals: `text()`, `console.log()`, `image()`, `exit()`, `ALL_TOOLS`,
  `searchTools(query, { limit?, namespace? })`, `describeTool(name)`, `describeNamespace(name)`,
  and `store(key, value)` / `load(key)`. `searchTools` hits include a one-line `signature`
  (argument and result types), so scripts call a found tool without `describeTool`. The
  description tells the model to call a tool whose exact name it already knows without searching,
  and never to call a tool in the same script that found it (an unseen hit could be a write).
  Large fetched data can be kept with `store()` and filtered later instead of fetched again.
* No Node.js, network, filesystem, `require`, `fetch`, or timers.

The result starts with `Script completed` or `Script failed`, then the wall time, the output in
order, and the JSON return value. A failed script keeps its partial output, the error, and the tool
calls already made, which are not undone. `ToolResult.nestedCalls` records every nested call (id,
name, compact arguments, status, duration, truncated error, usage) for your audit log, up to
`maxNestedCalls` entries, with per-status `counts` over all calls; the model never sees it.
`toolResultMessageFromResult` drops `nestedCalls` and `usage`, and the loop does not add
`ToolResult.usage` (nested and classifier token spend) to run usage; read both from the `ToolResult`
or tool events. `ToolResult.usageIncomplete: true` means that sum under-counts: a nested call
reported incomplete usage (its own `usageIncomplete`, kept on its record), for example a
classification the classifier answered without usage.

## Survive step re-execution [#survive-step-re-execution]

Resolve tools with a durable ledger (`resolveTools(modules, context, { ledger: { store } })`, see
[Ledger writes](../agent/tools-hitl#ledger-writes-for-re-executed-steps)). The `codemode` call is
itself ledgered, so a re-executed call never runs its script again:

* Completed earlier: the stored result is returned.
* Still running in another execution: the call waits for it, up to `maxWaitMs` or `deadline`.
* Abandoned (the earlier execution crashed): an interrupted error result lists that script's
  ledgered nested calls as applied, failed, or unknown (started without a recorded result), says
  they were not undone, and asks the model to verify before repeating work.
  The model sees the text listing; hosts get the same entries in `structuredContent.codemode`:

  ```ts
  // structuredContent of an interrupted result (CodeModeStructuredContent)
  type Interrupted = {
    codemode: {
      ok: false
      interrupted: true
      interruptedCalls: {
        // In sequence order. args: compact JSON, cut with a trailing '…' (then no longer JSON).
        calls: Array<{
          key: string // ledger key, `<toolCallId>/<seq>`
          toolName: string
          args: string
          status: 'applied' | 'failed' | 'unknown'
        }>
        complete: boolean // false when calls were dropped or arguments cut (here or by the ledger)
        counts: { applied: number; failed: number; unknown: number } // every entry, dropped too
      }
    }
  }
  ```

  It is plain JSON (`CodeModeStructuredContent`, `CodeModeInterruptedCalls`) bounded like
  `nestedCalls`: at most `maxNestedCalls` calls, 8 KiB of arguments per call, 32 KiB in total.
  `failed` means the call recorded a `ToolError` or an error result; `unknown` means it started
  without a recorded result and may have been applied. When the ledger cannot list the nested
  calls, the result stays interrupted, tells the model they may already have been applied, and
  carries `interruptedCallsUnavailable: true` instead of `interruptedCalls`.

Nested write calls are ledgered under `<toolCallId>/<seq>` and receive `idempotencyKey`. Calls the
ledger policy skips (by default read-only calls) are not listed. Scripts are never replayed.

## Stage approval-gated writes [#stage-approval-gated-writes]

Bulk work on an approval-gated tool would otherwise need one approval per call. Mark the tool
stageable, and a script can record the calls into a plan that a person reviews once, unticking any
they do not want. Nothing runs while the script runs.

```ts
import { Effect } from 'effect'
import { ToolApprovalPolicy } from '@yolk-sdk/agent/protocol'
import { makePlanReviewTool, makeTool, resolveTools } from '@yolk-sdk/agent/tools'

const updateRecord = makeTool<HostContext, typeof UpdateRecordParams>({
  name: 'update_record',
  description: 'Update the fields of a record.',
  parameters: UpdateRecordParams, // host-owned Effect Schema, for example { id, status }
  access: 'write',
  approval: ToolApprovalPolicy.make({ mode: 'manual' }),
  // Optional, side-effect free: the before → after diff shown on approvals and plan reviews.
  changePreview: ({ params, context }) => describeRecordChange(context, params), // host-owned
  staging: {
    // Optional, side-effect free. A precheck failure rejects the person's selection.
    precheck: ({ params, context }) => assertStillExpected(context, params) // host-owned
  },
  execute: ({ params, context, idempotencyKey }) => applyUpdate(context, params, idempotencyKey)
})

const toolSet = Effect.gen(function* () {
  return yield* resolveTools(
    [{ id: 'host', tools: [codemode, makePlanReviewTool<HostContext>()] }, recordsModule],
    hostContext,
    {
      interactionHost: scopedReceipts, // host-owned InteractionHost
      plans: { store: planStore }, // host-owned ToolPlanStore, scoped to the conversation
      ledger: { store: ledgerStore }
    }
  )
})
```

`makeInMemoryToolPlanStore` is the reference store for tests; production stores persist plans
(`Schema.toCodecJson(ToolPlan)`) where later turns can read them. A script then stages calls:

```js
const records = await tools.list_records({ status: 'draft' })
for (const record of records) {
  await stage('update_record', { id: record.id, status: 'published' })
}
return records.length
```

* `stage(name, args)` validates the arguments with the tool's decoder and resolves to
  `{ staged: true, key, index }`. It executes and ledgers nothing.
* Once a script stages, it may only run `read` tools; a script that already ran a write tool
  cannot stage. Duplicate calls (same tool and arguments) are rejected. A plan holds at most 500
  calls and 1 MiB of arguments (`plans: { maxCalls, maxArgsBytes }`). The code mode option
  `staging: { maxCalls }` can only lower it. Calls past a limit are rejected, never truncated.
* A successful script saves the plan once and its result tells the model to call
  `review_plan({ planId, planDigest })`; hosts read `structuredContent.codemode.plan`
  (`{ id, digest, count, reviewToolName }`). A failed script discards its staged calls.
* `stage` exists only when the resolution has `plans`, an `interactionHost`, and one plan review
  tool. Voice and subagent resolutions without them never get it. `staging: false` turns it off for
  one code mode tool.

The review is an [action-backed interaction](../agent/tools-hitl#review-a-staged-plan): render the
`tool_plan_review` kind, accept `{ selectedKeys }`, and resume as for any interaction. Yolk then
applies exactly the selected calls in staged order, once; a call that pauses for input is reported
`input_required` and does not stop the apply. Each staged call is previewed with the
tool's `changePreview`, the same [change preview](../agent/tools-hitl#preview-the-change) direct
approvals show.

**Per-call authority:** applied plan calls do not pass through `beforeNestedCall` or decorators
around your `ToolExecutor`: they run inside the review action. Pass the same per-call authorizer as
`makePlanReviewTool({ beforeCall })`; it is the only per-call host hook for applied calls.

### Stage-only tools [#stage-only-tools]

A stageable approval-gated tool may be `callableBy: 'codemode'` (usually with
`discovery: 'search'`): it is never declared to the model and costs no context. Scripts find it
with `searchTools()` (hits carry `stageOnly: true` and the `stage()` signature), read it with `describeTool()` (rendered as the
`stage()` call), and can only `stage()` it; a direct `tools.<name>()` call rejects with a hint to
stage it. Resolution warns when a stage-only tool resolves without `plans`, where it would be
unreachable. Model-callable stageable tools (`callableBy: 'all'`, deferred or not) are searchable,
describable, and stageable from scripts the same way; deferred ones are not named in the
description's Stageable list.

## Make tools ready for code mode [#make-tools-ready-for-code-mode]

Scripts can only use what a tool declares and returns. For each tool scripts may call:

* Declare `output` (an Effect Schema) and return `{ output: value }`: Yolk encodes it with
  `Schema.toCodecJson(output)` (so `Chunk` and `DateTime` reach scripts as arrays and ISO strings)
  and a value that does not encode fails the call. Files are `ToolFile` fields: return
  `new FileBytes({ bytes, name, mimeType })` and scripts get a `FileRef`. Tools without `output`
  return `{ content }`, and scripts get their text. Fail with `modelVisibleToolError({ code })` to
  give scripts `error.code`. See [ADR 0013](https://github.com/magoz/yolk-sdk/blob/main/docs/adr/0013-typed-tool-results.md).
* `resolveTools` checks every typed result against its output schema before scripts see it (excess
  properties rejected); a value that does not match makes the call reject with
  `returned an invalid result`. Raw registrations that set `def.outputSchema` supply
  `decodeOutput` (`toolOutputDecoder(schema)`, or `mcpToolOutputDecoder` for MCP tools), or
  resolution fails with `output_validation_required`.
* Give each module a `description` (`{ id, description, tools }`): scripts read it under the
  namespace heading, from `describeNamespace()`, and through `searchTools()`.
* Custom `invalidParamsMessage` callbacks should end with
  `withToolArgumentsErrorHint(message, error)` from `@yolk-sdk/agent/tools`, so an unknown key names
  the allowed keys and a number or boolean sent as a string names the literal to send (the default
  message already does).
* Keep polling, outbound-message, and human-in-the-loop tools `callableBy: 'model'`.

Package tools follow these rules: connector modules take the connector `description` (override with
the `description` option) and return JSON-encoded action results, knowledge tools declare
`KnowledgeLookupOutput`/`KnowledgeManageOutput`, and the sandbox tool declares `SandboxToolOutput`.

## Keep state between scripts [#keep-state-between-scripts]

`store()` writes from successful scripts come back in
`structuredContent.codemode.storeWrites`. Rebuild the store from the transcript and pass it back
with `loadStore`; this works the same in stateless routes, Workflow steps, and Durable Objects:

```ts
import { Effect } from 'effect'
import { codeModeStoreFromToolResults, makeCodeModeTool } from '@yolk-sdk/codemode'

const codemode = makeCodeModeTool<HostContext>({
  executor,
  // `{ toolName, result }` for prior tool results, oldest first (host-owned lookup).
  loadStore: context => Effect.succeed(codeModeStoreFromToolResults(context.priorToolResults))
})
```

`codeModeStoreFromToolResults` applies only results whose `toolName` is the code mode tool's name
(default `codemode`; pass `{ toolName }` if you renamed it), so another tool cannot inject store
writes by returning code-mode-shaped `structuredContent`. Transcript `ToolResultMessage`s carry no
tool name: pair each with the name of the assistant tool call it answers.

Values are small JSON only: 256 KiB per value and 1 MiB in total (characters of JSON, as the engine
counts them). Scripts get an error beyond them, and the rebuilt store drops offending writes and
keeps the previous value.

## Classify items from scripts [#classify-items-from-scripts]

`makeClassifierTool` exposes a [classifier model](../agent/classifier-models) as a `codemode` +
`listed` read tool named `classify`. Scripts classify one item per call; calls beyond
`maxConcurrency` (default 100 per script, keyed by the parent tool call id) queue. All scripts
together also share a process cap: `processLimiter` defaults to `defaultClassifierProcessLimiter`
(200 concurrent classifications per process, shared by every classifier tool); build a separate
one with `makeClassifierConcurrencyLimiter(max)` or pass `false` to disable it.

```ts
import { Effect } from 'effect'
import { ClassifierModel } from '@yolk-sdk/agent/classification'
import { makeClassifierTool } from '@yolk-sdk/codemode'

const classifyTool = Effect.gen(function* () {
  const model = yield* ClassifierModel

  return makeClassifierTool<HostContext>({ classify: model, maxConcurrency: 100 })
})
```

A script can then triage a whole inbox in one tool call:

```js
const messages = await tools.list_messages({ folder: 'inbox', limit: 50 })
const results = await Promise.all(
  messages.map(message =>
    tools.classify({
      state: { subject: message.subject, from: message.from },
      questions: { urgent: { type: 'boolean', instructions: 'Does this need a reply today?' } }
    })
  )
)
return messages.filter((_, index) => results[index].answers.urgent.probability > 0.7).map(m => m.id)
```

Each call reports token usage on the nested-call record; the cost (`costUsd`) stays in the
classifier result's `structuredContent.usage`. Classifier errors reject the call with a safe
message. The classifier tool is a `read` marked `invokesModel: true`, so
[`readOnlyNestedCallGate`](#allow-only-reads) refuses it unless its `admitModelCall` admits it.

## Run a script outside a model turn [#run-a-script-outside-a-model-turn]

A host can run a script itself, with no model and no tool call, for example a background check on a
schedule. `runCodeModeScript` runs it over the same tools, dispatch path, limits, deadline clamp,
store, and nested-call hooks as the `codemode` tool (which runs every script through it), and
returns what happened as data instead of model-visible text.

```ts
import { Effect } from 'effect'
import { resolveTools } from '@yolk-sdk/agent/tools'
import { readOnlyNestedCallGate, runCodeModeScript } from '@yolk-sdk/codemode'
import { makePiCodeModeExecutor } from '@yolk-sdk/codemode/node'

const executor = makePiCodeModeExecutor()

const runCheck = (checkId: string, code: string, state: unknown) =>
  Effect.gen(function* () {
    const toolSet = yield* resolveTools(hostModules, hostContext) // host-owned

    const result = yield* runCodeModeScript({
      executor,
      code,
      // Nested calls get ids `<parentCallId>/<seq>` (their ledger keys): pick an id unique per run.
      nested: toolSet.nestedExecutor({ parentCallId: checkId }),
      parentCallId: checkId,
      store: { state }, // the script reads it with load('state')
      limits: { timeoutMs: 60_000 },
      beforeNestedCall: readOnlyNestedCallGate()
    })

    // A refused call fails the check even when the script caught the rejection.
    if (result.calls.some(call => call.refusal !== undefined)) return { failed: 'refused call' }

    return result.ok ? { value: result.value } : { failed: result.error.message }
  })
```

* `ResolvedToolSet.nestedExecutor({ parentCallId })` gives the nested tool access a nested-access
  registration gets, bound to `parentCallId` instead of a tool call: the same `tools` (code-mode
  callable, outside the fail-closed set), `execute` (decoding, registration wrappers, the ledger),
  and `access`. It never offers staging: a staged plan needs a model turn to review it.
* The result: `ok`; `value` (the script's JSON return value) and `storeWrites` when it succeeded,
  `error` (`kind`, `message`) when it failed; `output` (text and images, unbounded); `calls` (every
  nested call with its id, arguments, status, effective access, error, and `refusal`);
  `nestedCalls` (the bounded record), `usage`, `usageIncomplete`, `inputRequired`, `timeoutMs` and
  `wallTimeMs`. It never fails; interrupting the effect aborts the script and cancels running
  nested calls.
* `deadline` is epoch milliseconds, as for the tool; `store` is what `load(key)` reads. Pass inputs
  such as a carried-over state through `store`.
* The `codemode` tool keeps the return value in its model-visible text only:
  `structuredContent.codemode` stays `{ ok, storeWrites?, plan?, inputRequired? }`, because it is
  persisted with the transcript and an unbounded value would grow it. Hosts that need the value run
  the script with `runCodeModeScript`.

### Allow only reads [#allow-only-reads]

`readOnlyNestedCallGate(options?)` is a ready-made `beforeNestedCall` for `runCodeModeScript` or
`makeCodeModeTool`. It admits a call only when its effective access is `read` (a registration's
`isReadCall` counts, so a `list` call of a `write` tool passes) and the tool is neither
approval-gated nor marked [`invokesModel`](../agent/tools-hitl#mark-tools-that-call-a-model). It
fails closed: a tool without effective access is refused. Every refusal is a
`CodeModeNestedCallRefused` whose `code` the script sees as `error.code` and the call's `refusal`
keeps:

| Code                | Refused call                                                 |
| ------------------- | ------------------------------------------------------------ |
| `unavailable`       | the resolution has no such script-callable tool              |
| `approval_required` | the tool is approval-gated                                   |
| `invokes_model`     | the tool calls a model when it runs (for example `classify`) |
| `not_read`          | the call's effective access is `write` or `destructive`      |

Two options relax one check each. Both are predicates over the same input as `beforeNestedCall`
(`{ call, tool, access }`) and admit when they return `true`:

* `admit` relaxes only the access check, for a write the host knows only reads (for example a remote
  tool its server marks read-only): `readOnlyNestedCallGate({ admit: ({ tool }) => readOnlyRemoteTools.has(tool.def.name) })`.
* `admitModelCall` relaxes only the model check, for model calls whose cost the host accepts, such as
  a bounded `classify` but not an open-ended child run:
  `readOnlyNestedCallGate({ admitModelCall: ({ tool }) => tool.def.name === 'classify' })`. It is
  asked only about tools marked `invokesModel`. An admitted call still has to read (effective
  access `read`, or `admit`), so a write marked `invokesModel` is still refused as `not_read`;
  approval-gated and unavailable tools stay refused.

A hook that throws or dies (an `admit` or `admitModelCall` that throws included) refuses the call
too, with the message `The call could not be admitted.` and no code, so counting `refusal`s counts
it.
Your own `beforeNestedCall` hooks receive the same input (`call`, `tool`, `access`, and with
`makeCodeModeTool` the `context`) and may fail with a plain message or a
`new CodeModeNestedCallRefused({ code, message })`.

## Limits [#limits]

| Limit              | Default | Notes                                                                                 |
| ------------------ | ------- | ------------------------------------------------------------------------------------- |
| `timeoutMs`        | 120000  | includes nested calls and queue time; clamped by `deadline`                           |
| `memoryLimitBytes` | 64 MiB  | VM heap cap; allocations beyond it fail inside the script                             |
| `maxNestedCalls`   | 256     | later calls reject and do not run; also sizes the `nestedCalls` record (at most 4096) |
| `maxOutputChars`   | 40000   | the result keeps the head and tail with an omission marker in between                 |
| `maxImages`        | 8       | later images are dropped with an omission note                                        |
| `maxImageBytes`    | 4 MiB   | base64 image data in total; an image beyond it is dropped with a note                 |

Set them with `makeCodeModeTool({ limits: { ... } })`. The executor's `maxConcurrentExecutions`
(default 4) caps concurrent scripts per executor; Fluid compute shares instances between requests.
If an executor does not stop at `timeoutMs`, the tool returns a `timeout` failure 5 seconds later
and aborts the executor's signal.

## Security notes [#security-notes]

* Scripts run in a fresh QuickJS VM compiled to WebAssembly, in a fresh worker thread. The only
  capability is calling the injected tools and helpers; timeouts, aborts, and runaway regular
  expressions stop the worker without blocking your event loop.

* Nested calls are ordinary tool calls with your host context. Code mode adds no permissions:
  the tools you expose to scripts are the authority you grant, and the `codemode` tool itself is
  `write` access.

* Decorators you wrap around the `ToolExecutor` (outside `ResolvedToolSet.execute`), such as a
  per-call run-admission or stop check, see only the `codemode` call, never the nested calls of its
  script. Put per-call checks in `beforeNestedCall` or in registration-level wrappers, and the same
  check in the plan review's `beforeCall` for staged calls:

  ```ts
  const codemode = makeCodeModeTool<HostContext>({
    executor,
    // Fails with a message to reject the nested call; it is recorded as an error and never runs.
    beforeNestedCall: ({ call, context }) => assertRunActive(context, call), // host-owned
    // Observes each admitted call: outcome 'success' | 'failure' | 'interrupted'. A failing hook
    // (even one that throws) is logged and never changes the call's result.
    afterNestedCall: ({ call, outcome, durationMs, context }) =>
      auditNestedCall(context, call, outcome, durationMs) // host-owned
  })
  ```

* A script fails once it has printed 16 Mi characters or 100,000 `text()`, `image()` and
  `console.*` items, on both executors. The result is bounded afterwards (`maxOutputChars`,
  `maxImages`, `maxImageBytes`).

* Built-ins are frozen and built-in globals are read-only before the script runs, on both
  executors, so scripts cannot patch them (assignments fail silently, or throw in strict code).

* The worker inherits a copy of the host's `process.env`. Scripts cannot read it (the VM has no
  `process`), but keep that in mind for engine-level vulnerabilities.

* The VM's clock and `Math.random` come from the engine's WASI shim.

* Approvals inside scripts are not supported; approval-gated tools never run from code mode. Staged
  calls run only after a person accepts a plan review, through the same execute path and ledger.

* Node prints one `ExperimentalWarning` per process for `stripTypeScriptTypes`.

## Other runtimes [#other-runtimes]

`CodeModeExecutor` is a plain interface. Hosts on Workers or other runtimes can supply their own
engine and keep the same tool, catalog, store, and result handling. Custom executors must apply the
same argument rules as the pi executor (see [What scripts see](#what-scripts-see)) and prefix
rejections with `CodeModeExecutorTool.callLabel`, which `makeCodeModeTool` sets.


---

# Add connector tools

URL: /docs/integrations/connector-tool

Turn typed external API actions into agent tools.



Use connectors when you want reusable actions over external services.

See [Connectors catalog](./connectors) for built-in modules and action ids.

## Build an integration [#build-an-integration]

```ts
import { makeCredentialBinding, makeIntegration } from '@yolk-sdk/connectors'
import { TelegramBotTokenSlot } from '@yolk-sdk/connectors/telegram'

const integration = makeIntegration({
  connectorId: 'telegram',
  config: { chatId: '123456' },
  credentialBindings: [
    makeCredentialBinding({
      slotId: TelegramBotTokenSlot.id,
      credentialRef: 'telegram-bot-token'
    })
  ]
})
```

## Expose connector actions as tools [#expose-connector-actions-as-tools]

```ts
import { makeConnectorToolModule } from '@yolk-sdk/connectors/agent'
import { TelegramConnector } from '@yolk-sdk/connectors/telegram'

const telegramTools = makeConnectorToolModule(TelegramConnector, {
  integration,
  layer: HostConnectorLayer,
  access: action => (action === 'telegram.send_message' ? 'write' : 'read')
})
```

Your `HostConnectorLayer` provides credentials and HTTP execution. When `access` is omitted, the
adapter uses the action's declared `read`, `write`, or `destructive` access and falls back to `read`
for legacy actions without metadata. A host-provided value or resolver overrides action metadata.
Microsoft and Google Drive actions declare write/destructive access where applicable. Generic email
declares reads as `read`, IMAP draft/read-state/restore actions as `write`, and trash/SMTP submission
as `destructive`. Its mailbox-state actions require optional host adapter methods; keep
explicit host classification for other connectors until their actions do.

The module's `description` is the connector's `description` (override it with the `description`
option); code mode shows it under the module's heading. Each tool declares the action's
`outputSchema`, and a successful call returns its JSON encoding (`Schema.toCodecJson`) as both
`structuredContent` and the text content: `Chunk`s become arrays and dates ISO strings. Fields not
declared in `outputSchema` are not returned (Effect `toCodecJson` encoding drops undeclared keys and
requires JSON values for `Schema.Unknown`). A value that does not encode fails the call with an
`execution` error. Provider failures return an error result
whose `structuredContent` is the JSON-encoded `ProviderFailure` (a non-JSON `underlying` is dropped).

## Use directly without an agent [#use-directly-without-an-agent]

```ts
import { Effect } from 'effect'

const result = await Effect.runPromise(
  TelegramConnector.invoke({
    integration,
    action: 'telegram.send_message',
    input: { message: 'Hello from Yolk' }
  }).pipe(Effect.provide(HostConnectorLayer))
)
```


---

# Connectors catalog

URL: /docs/integrations/connectors

Built-in connector modules, credential slots, config keys, and action ids.



Connectors are typed external API actions. Use them directly or adapt them into agent tools with `@yolk-sdk/connectors/agent`.

## Summary [#summary]

| Connector       | Import                                 | Credential slots                             | Config keys                                        | Capabilities                                                                                                               |
| --------------- | -------------------------------------- | -------------------------------------------- | -------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| Afloat          | `@yolk-sdk/connectors/afloat`          | `AfloatApiKeyCredentialSlot`                 | none                                               | `afloat.mcp_auth`                                                                                                          |
| Dropbox         | `@yolk-sdk/connectors/dropbox`         | Dropbox OAuth slots                          | none                                               | metadata + file-management + host download                                                                                 |
| Generic email   | `@yolk-sdk/connectors/email`           | incoming and SMTP credential slots           | incoming/SMTP protocol, host, port, security       | list, get, draft, send, IMAP message state                                                                                 |
| Figma           | `@yolk-sdk/connectors/figma`           | `FigmaOAuthCredentialSlot`                   | none                                               | `figma.mcp_auth`                                                                                                           |
| Fortnox         | `@yolk-sdk/connectors/fortnox`         | Fortnox OAuth slots                          | none                                               | company, customers, invoices, suppliers, articles, prices, cost centers, payments, offers, print, inbox, settings, profile |
| GitHub          | `@yolk-sdk/connectors/github`          | `GithubTokenSlot`, `GithubUploadTokenSlot`   | `owner`, `repo`                                    | issue, PR, review, merge, repo context actions                                                                             |
| Google          | `@yolk-sdk/connectors/google`          | Google OAuth slots                           | none                                               | Gmail + Calendar + Drive actions                                                                                           |
| Kie             | `@yolk-sdk/connectors/kie`             | `KieApiKeySlot`                              | none                                               | image + video generation tasks, task status                                                                                |
| LinkedIn search | `@yolk-sdk/connectors/linkedin-search` | `ExaApiKeySlot`, `EnrichLayerApiKeySlot`     | none                                               | search, profile, email                                                                                                     |
| Microsoft       | `@yolk-sdk/connectors/microsoft`       | Microsoft OAuth slots                        | `mailboxAccessMode`, `oneDriveAccessMode` optional | Outlook, OneDrive, SharePoint sites, and Teams through Graph                                                               |
| Notion          | `@yolk-sdk/connectors/notion`          | `NotionApiTokenSlot`                         | none                                               | Notion workspace/content actions                                                                                           |
| Cloudflare R2   | `@yolk-sdk/connectors/r2-storage`      | `R2AccessKeyIdSlot`, `R2SecretAccessKeySlot` | `endpoint`, `bucket`, `publicUrl` optional         | presigned upload URL                                                                                                       |
| Telegram        | `@yolk-sdk/connectors/telegram`        | `TelegramBotTokenSlot`                       | `chatId`                                           | send, validate                                                                                                             |
| Todoist         | `@yolk-sdk/connectors/todoist`         | `TodoistApiTokenSlot`                        | none                                               | project/task/label actions                                                                                                 |

### Input numbers [#input-numbers]

Number inputs are integers or finite numbers, so tool schemas never offer the non-finite values that
[tool arguments reject](../agent/tools-hitl#optional-arguments-null-and-unknown-keys). Counts and
page sizes are integers of at least 1, and some have upper bounds. For example, Gmail and Google
Calendar `maxResults` and LinkedIn search `numResults` have none (Gmail and Calendar clamp larger
values), Notion `pageSize` is at most 100, which Notion enforces, and Todoist `limit` is at most
200, like its comment list. Todoist `priority` is an integer from 1 to 4 and `duration` an integer
of at least 1. Google Drive, Dropbox, generic email and Fortnox page sizes keep their existing
bounds. A value outside an input's bounds fails as a validation error before any request.

## Afloat [#afloat]

Use Afloat when you want to turn a host-owned Afloat API key into remote MCP connection data.
The connector returns the canonical endpoint and required MCP `2026-07-28` protocol version. Keep
`afloat.mcp_auth` server-side; hosts should discover tools through `@yolk-sdk/mcp/client` and own
agent access, approval, and file-handling policy.

| Action id         | What it does                                                       |
| ----------------- | ------------------------------------------------------------------ |
| `afloat.mcp_auth` | builds Afloat remote MCP server URL, protocol version, and API key |

## Figma [#figma]

Use Figma when you want to turn host-owned Figma OAuth credentials into remote MCP auth data.

Return optional `refreshToken`, `clientId`, and `clientSecret` from the host's runtime
`OAuthCredential`; never place them in persisted integration config.

| Action id        | What it does                                                             |
| ---------------- | ------------------------------------------------------------------------ |
| `figma.mcp_auth` | builds Figma remote MCP server URL, tokens, and optional MCP client info |

## Fortnox [#fortnox]

`FortnoxConnector` exposes 102 actions (51 `read`, 32 `write`, 19 `destructive`). Deletes, payment
bookkeeping, creating a voucher, and offer lifecycle actions are `destructive` because the Fortnox
API cannot undo them.
Sending, booking, cancelling, or crediting a customer invoice is not exposed and must remain
separately approval-gated by the host. The core record actions:

| Action id                                                         | What it does                                          |
| ----------------------------------------------------------------- | ----------------------------------------------------- |
| `fortnox.get_company_information`                                 | read company information                              |
| `fortnox.list_customers` / `fortnox.get_customer`                 | list or retrieve customers                            |
| `fortnox.create_customer` / `fortnox.update_customer`             | create or update customers                            |
| `fortnox.list_invoices` / `fortnox.get_invoice`                   | list or retrieve customer invoices and available rows |
| `fortnox.create_invoice` / `fortnox.update_invoice`               | create or update customer invoices                    |
| `fortnox.list_suppliers` / `fortnox.get_supplier`                 | list or retrieve suppliers                            |
| `fortnox.list_supplier_invoices` / `fortnox.get_supplier_invoice` | list or retrieve supplier invoices by GivenNumber     |
| `fortnox.list_supplier_invoice_files`                             | list archive file IDs connected to a supplier invoice |

All resource-scoped OAuth slots share `fortnox.oauth`. Required record scope hints are `companyinformation`,
`customer`, `invoice`, `supplier`, and `supplierinvoice`. Opt-in file slots are
`FortnoxConnectFileOAuthCredentialSlot` (`connectfile`) and `FortnoxArchiveOAuthCredentialSlot`
(`archive`); they are **not** included in `FortnoxCombinedOAuthCredentialSlot`. Nine more opt-in
resource slots, also outside the combined slot, cover articles (`article`), price lists and prices
(`price`), cost centers (`costcenter`), payments (`payment`), offers (`offer`), print templates
(`print`), the inbox (`inbox`), company settings and registers (`settings`), and the token's user
profile (`profile`), and `bookkeeping` covers financial years, accounts, voucher series, vouchers,
and SIE files; see [Read and write Fortnox records](../connectors/fortnox) for their actions.
**Fortnox scopes grant read and write**; action metadata distinguishes reads, writes, and
destructive actions. Hosts provide HTTP and current Fortnox OAuth credentials,
with no integration config keys.

List actions support page/limit, one resource-specific search pair, and global selection fields.
They return runtime Chunks and normalized pagination. Resource fields retain provider spelling and
monetary types. Create inputs require `Name` for customers or `CustomerNumber` for invoices;
Fortnox assigns the corresponding number. Update inputs carry `CustomerNumber` or `DocumentNumber`.
See [Read and write Fortnox records](../connectors/fortnox) for setup, inputs, selected fields,
consent limitations, and failure handling.

## Dropbox [#dropbox]

Dropbox exports `DropboxOAuthCredentialSlot`, action-scoped
`DropboxMetadataReadOAuthCredentialSlot`, `DropboxContentReadOAuthCredentialSlot`, and
`DropboxContentWriteOAuthCredentialSlot`, plus `DropboxCombinedOAuthCredentialSlot`. Every slot
uses the same `dropbox.oauth` binding id. Metadata actions request `files.metadata.read`;
file-management actions request `files.content.write`; the host-only download helper requests
`files.content.read`. The combined slot hints all three.

| Action id                      | What it does                                |
| ------------------------------ | ------------------------------------------- |
| `dropbox.list_folder`          | list a folder or begin a recursive listing  |
| `dropbox.list_folder_continue` | continue a folder listing from its cursor   |
| `dropbox.search`               | search file and folder metadata             |
| `dropbox.search_continue`      | continue a search from its cursor           |
| `dropbox.get_metadata`         | get file, folder, or deleted-entry metadata |
| `dropbox.create_folder`        | create a folder                             |
| `dropbox.move`                 | move a file or folder                       |
| `dropbox.copy`                 | copy a file or folder                       |
| `dropbox.delete`               | delete a file or folder                     |

Use `path: ''` or omit `path` with `dropbox.list_folder` to address the Dropbox API root. Continue
while `hasMore` is true. File metadata outputs use camelCase fields and a normalized
`type: 'file' | 'folder' | 'deleted'` discriminant.

The host owns OAuth code exchange, refresh, credential storage, consent, and Dropbox App Folder
versus Full Dropbox configuration. Binary upload and download **actions** are not part of this
module because the portable connector HTTP port carries string bodies; do not base64-encode file
content through these actions. Original-byte download is a separate host helper, not an action.
Host-only create/update are documented in [Transfer connector files](../connectors/files).

### Host-only Dropbox original-byte download [#host-only-dropbox-original-byte-download]

`downloadDropboxFile` from `@yolk-sdk/connectors/dropbox` returns original file bytes. It is not
registered on `DropboxConnector` and is never serialized by `makeConnectorToolModule`. It mirrors
[`downloadOneDriveItem`](#host-only-onedrive-original-byte-download).

```ts
import { downloadDropboxFile } from '@yolk-sdk/connectors/dropbox'

// Fragment: host-owned integration and a file id or path from discovery.
const download = downloadDropboxFile(
  integration,
  { path: selectedFile.id },
  { maxBytes: 20 * 1024 * 1024, maxErrorBodyBytes: 16 * 1024 }
)
```

The budgets are trusted host configuration, not tool parameters. Provide the existing
`CredentialResolver` and a compliant `ConnectorBinaryHttpClient` layer; default Dropbox actions
still use only `ConnectorHttpClient`. `path` is one Dropbox `/path`, bare `id:`, folder-ID-relative
path (`id:folder-id/child.txt`), `rev:`, or `ns:` value from discovery, never a share link.
Folder-ID-relative downloads return the child's own file ID. The helper sends a single `GET` to the Dropbox content endpoint,
rejects every redirect, takes served metadata from the `Dropbox-API-Result` header, and fails
non-downloadable entries such as Paper docs with `not_downloadable`. Hosts must materialize, scan,
and extract the `Uint8Array`; do not put raw bytes into generic model tool JSON. See
[Integration APIs](../api-reference/integrations#connectors) and
[Troubleshooting](../troubleshooting) for adapter and error details. Dropbox's official
[content-download protocol](https://www.dropbox.com/developers/documentation/http/documentation#content-download-endpoints)
and [path formats](https://www.dropbox.com/developers/documentation/http/documentation#path-formats)
describe GET support, argument/result headers, and folder-ID-relative addressing.

## Generic email [#generic-email]

`@yolk-sdk/connectors/email` exposes portable protocol-neutral actions. Hosts provide an
`EmailClient` Effect layer backed by their chosen IMAP, POP3, SMTP, TLS, and MIME libraries; the
package does not bundle those libraries.

| Action id                   | What it does                                                 | Access        |
| --------------------------- | ------------------------------------------------------------ | ------------- |
| `email.list_messages`       | list normalized messages with an opaque cursor               | `read`        |
| `email.get_message`         | fetch one normalized message                                 | `read`        |
| `email.get_attachment`      | retrieve one attachment; as an agent tool, a file (`fileId`) | `read`        |
| `email.create_draft`        | append a message draft to an IMAP mailbox                    | `write`       |
| `email.send_message`        | submit a normalized message to the SMTP server               | `destructive` |
| `email.set_read`            | mark an IMAP message read or unread                          | `write`       |
| `email.set_flag`            | flag/unflag an IMAP message for follow-up                    | `write`       |
| `email.trash`               | move an IMAP message to trash                                | `destructive` |
| `email.untrash`             | move an IMAP message out of trash                            | `write`       |
| `email.move`                | move an IMAP message to any folder                           | `write`       |
| `email.modify_labels`       | add/remove IMAP keyword labels                               | `write`       |
| `email.batch_set_read`      | batch mark read/unread                                       | `write`       |
| `email.batch_set_flag`      | batch flag/unflag                                            | `write`       |
| `email.batch_move`          | batch move to one folder                                     | `write`       |
| `email.batch_trash`         | batch move to trash                                          | `destructive` |
| `email.batch_untrash`       | batch restore from trash                                     | `write`       |
| `email.batch_modify_labels` | batch add/remove IMAP keywords                               | `write`       |
| `email.delete_permanently`  | permanently delete identified messages                       | `destructive` |

Incoming actions require `incomingHost` and use `EmailIncomingCredentialSlot`. They default to
`incomingProtocol: 'imap'`, `incomingSecurity: 'tls'`, and port `993`; POP3 with TLS defaults to
`995`. Optional `folder` works with IMAP and fails deterministically with POP3. SMTP send requires
`smtpHost` and `EmailSmtpCredentialSlot`; it defaults to `smtpProtocol: 'smtp'`,
`smtpSecurity: 'starttls'`, and port `587` (`tls` defaults to `465`). Override ports with an integer
or numeric string from `1` through `65535`. Security is explicit: `none`, `starttls`, or `tls`.

The two slots may bind separate host credential refs or the same ref. Resolve credentials immediately
before transport calls. Both slots require `UsernamePasswordCredential`; use the provider-specific
Google or Microsoft connectors for their OAuth flows. Message list/get outputs contain normalized
addresses, body text/HTML, and attachment metadata, never raw MIME. Summaries and full messages
also expose optional `isRead` and `isFlagged`; omission means unknown/unavailable. List input accepts
matching optional filters. Filtered requests require optional `EmailClient.listMessagesFiltered`
and never fall back to `listMessages`; POP3 rejects filters before credential resolution. Successful
list output is schema-validated.

When attachment metadata includes `id`, pass it with the parent `messageId` to
`email.get_attachment`. The output repeats normalized metadata and exposes decoded file bytes—not
MIME transfer-encoded text—as base64 in `contentBase64`; decoded `size` is a non-negative
integer. As an agent tool the bytes become a file (`fileId`, ADR 0009) and the output keeps only
the metadata. Existing `EmailClient` implementations may omit the optional `getAttachment` method;
invoking the action then fails with a typed validation error. Successful host output is
schema-validated at the connector boundary before it is returned. Hosts that implement it own MIME
parsing, base64 encoding, size limits, durable storage, and content scanning. IMAP adapters should fetch the selected part without marking
the message read when supported. POP3 has no standard partial-part retrieval, so adapters may fetch
the whole stable UIDL-addressed message before extracting the part. POP3 rejects `folder`; omit it
for attachment retrieval.

`email.modify_labels` takes `{ messageId, folder?, addLabels?, removeLabels? }` with at least
one label list. It requires IMAP and optional `EmailClient.modifyLabels` host support; missing
support produces a typed validation error without breaking existing adapters. The incoming
credential is used and `folder` defaults to `INBOX`. Labels must be ASCII IMAP keyword atoms,
not system flags such as `\Seen`; spaces, control characters and IMAP atom specials are rejected.
Hosts check `PERMANENTFLAGS` and apply UID `STORE` additions/removals while preserving unrelated
keywords and system flags. Removals win on overlap. Hosts return `{ messageId, labels }` with
`labels` as an Effect `Chunk`; list/get messages may expose optional `labels` arrays. There is no
standalone IMAP label catalog: assignment creates keyword usage, removal clears usage. POP3 and
SMTP cannot persist labels. Hosts own partial-write reconciliation; the SDK has no socket adapter.

`email.move` takes `{ messageId, folder?, destinationFolder }` with a required destination folder
and returns the destination plus the new message ID when the host can map it. Source `folder`
defaults to `INBOX`. It requires IMAP and optional `EmailClient.move` host support; hosts use UID
`MOVE` when advertised, otherwise `COPY` plus `\Deleted` with a UID-scoped expunge, preserving flags
and owning partial-move reconciliation. Identical source/destination folders are rejected before
dispatch. Destination UIDs differ from source UIDs: use the returned ID or re-list the destination.

`email.create_draft` requires IMAP, accepts drafts without recipients, and uses the incoming
credential. Optional `folder` selects the mailbox. When omitted, the host adapter discovers a
mailbox advertised with `\Drafts` by the IMAP SPECIAL-USE extension and may fall back to `Drafts`.
The port owns MIME generation and `APPEND` with the `\Draft` flag. Output is
`{ saved: true, folder, draftId? }`; `draftId` is optional because servers without UIDPLUS may not
return `APPENDUID`. When present, it is opaque; UIDPLUS adapters must encode both UIDVALIDITY and UID,
never a bare UID. POP3 rejects draft creation.

`email.get_message` returns required `headers` name/value pairs alongside the normalized body,
including `List-Unsubscribe` when the mail carries it. Hosts fetch them via IMAP
`BODY.PEEK[HEADER]` or POP3 `TOP` without marking the message read; an empty array is valid only
when the server response contains no headers. Successful host output is schema-validated, so a
missing `headers` array fails. List summaries carry no headers.

List message `id` values are opaque adapter identifiers that callers pass unchanged to
`email.get_message`. POP3 adapters must use UIDL or another stable mapping rather than transient
sequence numbers. An omitted IMAP `folder` means `INBOX`; POP3 uses its single mailbox. Adapters
return deterministic newest-first pages. Cursors are opaque and scoped to the integration, protocol,
folder, and ordering; mailbox changes may invalidate them. SMTP input needs at least one recipient
across `to`, `cc`, and `bcc`. `{ accepted: true }` confirms server submission acceptance only, not
delivery. `email.send_message` also accepts optional `saveToSentItems` (default: save when possible)
and `sentFolder`. When saving is requested and the incoming account uses IMAP, the connector passes
IMAP Sent-copy details with the SMTP request so the host can store the same submitted bytes without
resubmission; the output `sentCopy` reports `saved | failed | skipped | unsupported`. A Sent-save
failure after acceptance never means the message was not sent: do not resend.

### Mark read/unread and move to/from trash [#mark-readunread-and-move-tofrom-trash]

These actions require IMAP and the incoming credential. POP3 is rejected before adapter calls;
SMTP cannot manage mailbox state. Hosts opt in through optional `EmailClient.setRead`, `trash`,
`untrash`, and `move` methods. Existing adapters remain compatible; invoking a missing method returns a
typed validation error. All successful mutation outputs are schema-validated.

* `email.set_read`: `{ messageId, isRead, folder? }`. Set `isRead` to `true` for read or `false`
  for unread. The connector defaults `folder` to `INBOX`. Hosts add/remove only the `\Seen` flag
  using UID `STORE`, preserving all other flags, and return `{ messageId, isRead }` after success.
* `email.set_flag`: `{ messageId, isFlagged, folder? }`. Set `isFlagged` to `true` to star for
  follow-up or `false` to unstar. Hosts add/remove only the `\Flagged` flag using UID `STORE`,
  preserving all other flags, check `PERMANENTFLAGS` first, and return `{ messageId, isFlagged }`.
* `email.trash`: `{ messageId, folder?, trashFolder? }`. Source `folder` defaults to `INBOX`.
  Hosts use `trashFolder` or discover a `\Trash` SPECIAL-USE mailbox with a host-configured fallback.
* `email.untrash`: `{ messageId, folder?, destinationFolder? }`. Here `folder` is the source
  trash mailbox; if omitted, hosts discover it. `destinationFolder` defaults to `INBOX`, **not**
  the original folder. Supply an explicit destination to restore elsewhere.
* `email.move`: `{ messageId, folder?, destinationFolder }` with a required destination folder.
  Source `folder` defaults to `INBOX`; identical source/destination folders are rejected before
  dispatch. Returns the destination and the new message ID when the host can map it.

The six explicit batch actions use `messageIds` (1-100 unique nonempty values), one source folder,
and the same payload/defaults as their single-message counterparts. Optional host methods are
`batchSetRead`, `batchSetFlag`, `batchMove`, `batchTrash`, `batchUntrash`, and `batchModifyLabels`.
Successful output reports every requested ID in `messageIds` order as `succeeded`, `failed`,
`unknown`, or `not_attempted`, with an optional sanitized code and exact summary counts. Every
succeeded result from `email.batch_move`, `email.batch_trash`, or `email.batch_untrash` must include destination
`folder`; `movedMessageId` is optional and must only be supplied when the adapter knows the
destination UIDVALIDITY/UID mapping (omit it and re-list the destination otherwise, never reusing
a stale source UID). The connector validates successful host output; raw provider
errors must not be exposed. Missing methods fail clearly while legacy adapters remain valid.

`email.delete_permanently` separately accepts `{ messageIds, folder? }`, defaults the source to
`INBOX`, and uses optional `EmailClient.deletePermanently`. Hosts permanently remove exactly those
UID-scoped messages and never issue blanket `EXPUNGE`. Approval is host policy, and SDK success does
not promise erasure from backups, retention, journaling, or compliance systems.

Hosts perform UID `MOVE` or a safe per-message copy/delete fallback. Never use blanket `EXPUNGE`,
permanent deletion, or merely set `\Deleted` as a substitute for a trash move. Return a failure
when trash discovery is missing/ambiguous, folders are identical, or a safe move is unavailable.
Trash/untrash return `{ moved: true, folder, messageId? }` (`EmailMoveMessageOutput`), where `folder`
is the destination and optional `messageId` identifies the moved message there. UIDPLUS mappings
must include destination UIDVALIDITY and UID. If no reliable ID mapping exists, omit it and re-list
the destination. Hosts own partial-move reconciliation; never blindly reuse a source UID or retry
a potentially completed copy/delete.

## Google [#google]

Google exports a generic `GoogleOAuthCredentialSlot`, action-scoped OAuth slots, and
`GoogleCombinedOAuthCredentialSlot` for broad-consent hosts. Every slot uses the same `google.oauth`
binding id, so one host credential can cover selected Gmail, Calendar, and Drive actions when its
consent includes those scopes.

Drive-specific slots use least-privilege consent hints:

| Slot                                             | Scope                                     |
| ------------------------------------------------ | ----------------------------------------- |
| `GoogleDriveMetadataReadonlyOAuthCredentialSlot` | `drive.metadata.readonly`                 |
| `GoogleDriveFileOAuthCredentialSlot`             | `drive.file`                              |
| `GoogleDriveReadonlyOAuthCredentialSlot`         | `drive.readonly`                          |
| `GoogleCombinedOAuthCredentialSlot`              | Gmail, Calendar, and default Drive scopes |
| `GoogleOAuthCredentialSlot`                      | none declared                             |

`drive.metadata.readonly` is a restricted scope that can read metadata across the authorized
Drive. `drive.file` is non-sensitive and permits create/update/delete only for files the app created
or that a user explicitly opened/shared with the app. `GoogleDriveReadonlyOAuthCredentialSlot` is
host-only content consent for Drive byte helpers (`contentAccess: 'readonly'`) and is **not** part
of `GoogleCombinedOAuthCredentialSlot`. Hosts that need mutations across arbitrary
existing files own broader restricted-scope consent, verification, and authorization policy. The
connector never manages OAuth callbacks, token refresh, storage, or consent UI.

### Gmail actions [#gmail-actions]

| Action id                   | What it does                                              |
| --------------------------- | --------------------------------------------------------- |
| `gmail.search`              | search Gmail messages                                     |
| `gmail.get_message`         | fetch one message                                         |
| `gmail.list`                | list messages                                             |
| `gmail.list_threads`        | list threads (id, snippet, historyId)                     |
| `gmail.list_drafts`         | list drafts                                               |
| `gmail.get_thread`          | fetch normalized thread                                   |
| `gmail.list_labels`         | list labels                                               |
| `gmail.create_label`        | create a user label                                       |
| `gmail.get_label`           | get label details                                         |
| `gmail.update_label`        | rename/update label visibility                            |
| `gmail.delete_label`        | delete a user label                                       |
| `gmail.modify_labels`       | add/remove labels                                         |
| `gmail.set_starred`         | star/unstar a message                                     |
| `gmail.set_read`            | mark a message read/unread                                |
| `gmail.batch_set_read`      | batch mark read/unread                                    |
| `gmail.batch_set_starred`   | batch star/unstar                                         |
| `gmail.batch_modify_labels` | batch add/remove labels                                   |
| `gmail.batch_trash`         | batch move to trash                                       |
| `gmail.batch_untrash`       | batch restore trashed messages                            |
| `gmail.delete_permanently`  | permanently delete messages                               |
| `gmail.trash`               | move a message to trash                                   |
| `gmail.untrash`             | restore a trashed message                                 |
| `gmail.draft_compose`       | create a draft                                            |
| `gmail.draft_update`        | update a draft                                            |
| `gmail.draft_delete`        | delete a draft                                            |
| `gmail.draft_reply`         | create a reply draft                                      |
| `gmail.send_message`        | submit host-generated MIME for sending                    |
| `gmail.list_attachments`    | list attachment metadata                                  |
| `gmail.get_attachment`      | fetch one attachment; as an agent tool, a file (`fileId`) |
| `gmail.list_send_as`        | list send-as aliases                                      |
| `gmail.list_accounts`       | list accessible Gmail accounts                            |

Label creation takes `{ name, messageListVisibility?, labelListVisibility? }`. Get/delete take
`{ id }`; update takes `{ id, name?, messageListVisibility?, labelListVisibility? }` with at least
one changed field. Visibility values are `show | hide` and
`labelShow | labelShowIfUnread | labelHide`, respectively. Reads use `gmail.readonly`; lifecycle
mutations and message assignment reuse `gmail.modify`. System labels cannot be renamed or deleted.
Delete returns `{ id, deleted: true }`; it deletes the label, not messages. Assign/remove labels
with `gmail.modify_labels` and `{ messageId, addLabelIds?, removeLabelIds? }`. Star/unstar with
`gmail.set_starred` and `{ messageId, isStarred }`, which assigns the `STARRED` system label. Mark
read/unread with `gmail.set_read` and `{ messageId, isRead }`, which flips the `UNREAD` system label
via `gmail.modify` consent and returns the normalized message with `isRead`/`isFlagged` derived from
`labelIds`. `gmail.search`, `gmail.list`, and `gmail.list_threads` accept optional
`isRead`/`isFlagged` boolean filters composed into the Gmail query (`is:read`/`is:unread`,
`is:starred`/`-is:starred`) alongside any raw query. `gmail.list_threads` takes the `gmail.list`
input (`query`, `labelId`, `maxResults`, `pageToken`, `isRead`, `isFlagged`) and returns decoded
`{ threads?: [{ id, snippet?, historyId? }], nextPageToken?, resultSizeEstimate? }` through the
`gmail.readonly` slot; failures map like the other Gmail reads (`gmail_list_threads_failed`
otherwise).

Batch actions take `{ messageIds, ... }` with 1-100 unique nonempty path-safe IDs and return
complete per-ID outcomes (`succeeded`, `failed`, `unknown`, `not_attempted`) in `messageIds` order,
with exact summary counts and sanitized codes only. Gmail executes individually addressed requests
sequentially (never the bulk endpoints, whose empty success cannot establish per-ID outcomes):
`gmail.batch_set_read`, `gmail.batch_set_starred`, `gmail.batch_modify_labels` (removals win,
labels are never created, each delta capped at 100), `gmail.batch_trash`, and
`gmail.batch_untrash`. `gmail.delete_permanently` issues individual `DELETE` requests (only 204
confirms success; 404 is a definitive rejection) and requires opt-in full-mail
(`https://mail.google.com/`) consent, which is never added to combined/default consent. It is
immediate permanent deletion, not trash, and claims no backup erasure.

### Gmail draft bodies [#gmail-draft-bodies]

`gmail.draft_compose`, `gmail.draft_update`, and `gmail.draft_reply` take an optional
`contentType: 'text' | 'html'` next to `body` (`text` when omitted, as on the Outlook draft
actions). A `text` body is sent as 7-bit `multipart/alternative`: a text/plain part with the exact
body (line breaks as CRLF) and a text/html part derived from it (HTML-escaped, `<br>` per line
break, runs of spaces kept, `http(s)` URLs linked to themselves, inside one `<div dir="ltr">`), both
`charset=UTF-8` and quoted-printable with lines of at most 76 characters. Gmail web opens a
text/plain-only draft in its plain-text composer and hard-wraps it at about 70 columns when a person
sends it; the HTML alternative keeps it in rich mode, so the HTML that recipients' mail clients
show keeps each paragraph unwrapped. (On send, Gmail web regenerates the text/plain alternative from
the HTML and wraps it at about 76 columns, as it does for any message composed there.) Write each
paragraph as one line. An `html` body is sent as a single quoted-printable text/html part.
`gmail.get_thread` prefers the text/plain part, so reading a text draft back answers its body.

### Gmail draft attachments [#gmail-draft-attachments]

The three draft actions also take optional `attachments`: an array of
`{ filename, mimeType, contentBase64 }` (`GmailDraftAttachment`), the `filename`/`mimeType` pair
`gmail.list_attachments` reports and the standard-base64 `contentBase64` `gmail.get_attachment`
returns when invoked directly, so a host can attach a fetched attachment again unchanged. As agent
tools, `get_attachment` returns a file (`fileId`) instead (pass the listed `filename` and
`mimeType` to name it) and the draft actions do not take `fileId`s yet.

* Limits: at most 10 attachments (`gmailDraftAttachmentsMaxItems`), at most 25 MiB decoded in total
  (`gmailDraftAttachmentsMaxBytes`), and at most 35 MiB of decoded MIME
  (`gmailDraftMessageMaxBytes`, Gmail's media upload cap).
* `filename`: 1 to 255 characters, no control characters, `/`, `\`, bidirectional controls, line
  separators, or lone surrogates, not only dots. `mimeType`: `type/subtype` without parameters;
  `multipart/*` and `message/*` are refused (send an `.eml` as `application/octet-stream`).
  `contentBase64`: canonical padded standard base64, no line breaks. An empty array means no
  attachments.
* The draft body becomes 7-bit `multipart/mixed` (boundary `=_yolk-draft-mixed`): the body exactly
  as [above](#gmail-draft-bodies) first, then one base64 part per attachment, in order, with lines
  of at most 76 characters; non-ASCII or long names use RFC 2047 `name` and RFC 2231 `filename*`.
  Headers, send-as checks, and the reply's recipients, `Re:` subject, `In-Reply-To`, `References`,
  and thread stay as without attachments.
* It is written with one simple multipart media upload, never retried:
  `POST https://gmail.googleapis.com/upload/gmail/v1/users/me/drafts?uploadType=multipart` (an
  update: `PUT .../drafts/{id}?uploadType=multipart`), `multipart/related` with the JSON draft
  metadata (`{ message: { threadId? } }` or `{ id, message: {} }`) and then the `message/rfc822`
  MIME. Host HTTP adapters must forward that body exactly as UTF-8 and accept outgoing bodies up to
  about 35 MiB. Header text left unencoded (such as a non-ASCII address) is uploaded as UTF-8, the
  same bytes the JSON `raw` request would carry.
* An oversized draft fails with a `validation_failed` `ConnectorError` whose `underlying` is
  `{ outcome: 'rejected', retryable: false, reason: 'too_large' }`, before credentials or any
  request for compose and update. A reply checks its body MIME before any request and the whole
  message after reading the original (its headers come from it), before writing anything. Provider
  answers map to the usual `gmail_draft_*_failed` failures.
* Without attachments, drafts are written exactly as before through the JSON endpoint.
  `gmail.draft_update` replaces the whole message: attachments not sent again are removed.

### Submit a reviewed Gmail message [#submit-a-reviewed-gmail-message]

`gmail.send_message` accepts `{ raw, threadId? }`, where `raw` is a complete RFC 5322 MIME
message encoded as canonical padded or unpadded base64url. The action sends exactly one request,
never resumable and never retried. 7-bit MIME is forwarded unchanged in one simple multipart upload
to `POST https://gmail.googleapis.com/upload/gmail/v1/users/me/messages/send?uploadType=multipart`
(`multipart/related`: JSON metadata with `threadId` only when provided, then a `message/rfc822`
part); MIME with any byte `>= 0x80` keeps the JSON `raw` request. Decoded MIME above 35 MiB
(`gmailSendMessageMaxBytes`) fails before credentials or network with a `validation_failed`
`ConnectorError` whose `underlying` is `{ outcome: 'rejected', retryable: false, reason: 'too_large' }`.
Prefer quoted-printable or base64 transfer encodings for large messages. Host HTTP adapters must
preserve the `multipart/related` content type and forward the string body exactly (CRLF line
endings, no re-encoding) and accept outgoing bodies up to about 35 MiB. The host builds the MIME, protects against header injection, binds the sender account,
validates recipients, bounds size, and obtains explicit send authorization. The SDK does not parse
MIME or check send-as aliases. Prefer a host-owned reviewed interaction over exposing this raw
send action directly to the model. Its access metadata is `destructive`. Gmail routes to the MIME
To/Cc/Bcc headers, not a separate SMTP envelope; retain Bcc when encoding the submitted MIME.

For a reply, the host must include `In-Reply-To` and `References` using RFC Message-IDs, plus a
matching Subject and the Gmail `threadId`; Gmail resource IDs are not RFC Message-IDs. Changing
the subject can start a new conversation. See Google's [threading requirements](https://developers.google.com/workspace/gmail/api/guides/threads).

`GoogleGmailSendOAuthCredentialSlot` shares `google.oauth` and hints the least-privilege
`gmail.send` scope. Google's [send API](https://developers.google.com/workspace/gmail/api/reference/rest/v1/users.messages/send)
also accepts existing `gmail.compose`, `gmail.modify`, or `https://mail.google.com/` grants. The
action first inspects OAuth scope metadata through the scope-free binding, then re-resolves
through an operation slot selecting send first, otherwise an existing compose/modify/full-mail
grant. Strict host resolvers still enforce the selected slot; the initial inspection never grants
permission. Bearer credentials or missing scope metadata fall back to the send slot. No additional
consent is requested and the combined slot is unchanged.

Success is `{ accepted: true, id, threadId? }`: submission, **not delivery**. Recognized HTTP
rejections return `gmail_send_message_rejected`; ambiguous HTTP responses return
`gmail_send_message_unknown`. Both omit retry hints and include
`underlying: { outcome: 'rejected' | 'unknown', retryable: false }`. Transport failures or malformed
success acknowledgements are typed `ConnectorError`s with the unknown metadata; a host request
timeout after dispatch is a transport failure with the same unknown outcome. No automatic
retry occurs. An unconfirmed send may already have taken effect: reconcile mailbox state before
proposing another send. A deterministic Message-ID is not an idempotency guarantee.

### Fetch a normalized Gmail thread [#fetch-a-normalized-gmail-thread]

`gmail.get_thread` requires `{ threadId, format }`, where `format` is `full`, `metadata`, or
`minimal`. Use `full` when decoded message bodies are required. With `format: 'metadata'`, optional
`metadataHeaders` (1 to 50 header names, sent as repeated `metadataHeaders` query parameters) asks
Gmail for only those headers, and each message keeps exactly the selected headers instead of the
default allowlist below. `gmail.get_message` takes the same optional `metadataHeaders`. Any other
format with `metadataHeaders` fails input validation before any request.

The action returns `GmailThreadOutput`. Each `GmailThreadMessage` includes selected root headers,
attachment metadata, and an optional decoded message `body` with `bodyMimeType`. Plain text is
preferred when available; otherwise HTML is used. Gmail answers each part's `body.data` already
transfer-decoded, so the part's `Content-Transfer-Encoding` is never applied again. Text and nested-message attachments do not enter
the message body. Selected headers are `Bcc`, `Cc`, `Date`, `Delivered-To`, `From`, `In-Reply-To`,
`Message-ID`, `References`, `Reply-To`, `Subject`, and `To`.

Raw MIME and attachment content are intentionally omitted. Optional attachment `size` values are
nonnegative integers; invalid sizes from Gmail MIME discovery (`-1`, `1.5`, `null`, `"12"`, missing)
are omitted rather than exposed as byte counts, and valid siblings including zero are kept. Null /
array-shaped / non-object parts are skipped. `message/rfc822` stays an attachment. Public thread
output classes and `gmail.get_attachment` (`size` plus base64url `data`) are unchanged.

Internal MIME `payload` for `gmail.get_thread` and `gmail.list_attachments` admits `Schema.Json` after
JSON parse. `Schema.Json` requires finite numbers, so raw HTTP JSON `1e999` becomes `Infinity` and
rejects the whole payload (`ConnectorError` `validation_failed`, `Invalid response shape`). That is
not a general collapse of malformed optional MIME fields. Do not demonstrate overflow with
`JSON.stringify(Infinity)` (that becomes `null` and would omit size). Hosts must still validate
actual bytes and cannot treat metadata as a download limit.
See [private attachments](../guides/private-attachments#bound-connector-downloads-before-buffering)
for separate streamed encoded-body and decoded-file limits in the host HTTP adapter.

Use `gmail.list_attachments` with one
`messageId` for metadata-only discovery without fetching a whole thread; metadata includes
inline/content-ID details when Gmail supplies them. `attachmentId` is optional because Gmail may
return inline attachment data instead. When present, pass the parent message `id`
as `messageId` plus `attachmentId` to `gmail.get_attachment`. Its typed output preserves Gmail's
`size` and base64url `data`, then adds `messageId`, `attachmentId`, and standard-base64
`contentBase64`. Omitted inline data is not retrievable through that action.

### Calendar actions [#calendar-actions]

| Action id                 | What it does                      |
| ------------------------- | --------------------------------- |
| `calendar.list_events`    | list calendar events              |
| `calendar.create_event`   | create an event                   |
| `calendar.list_calendars` | list calendars                    |
| `calendar.get_event`      | fetch one event                   |
| `calendar.update_event`   | update an event                   |
| `calendar.delete_event`   | delete an event                   |
| `calendar.list_accounts`  | list accessible Calendar accounts |

For `calendar.create_event` and `calendar.update_event`, each `start`/`end` boundary uses exactly
one non-empty field: `{ date, timeZone? }` for an all-day value or `{ dateTime, timeZone? }` for a
date-time value. Null, empty, missing, and dual `date`/`dateTime` boundaries fail validation before
the provider request.

`calendar.update_event` is a PATCH: omitted fields stay unchanged, but `attendees`, when given,
replaces the whole guest list.

Google's default for API writes notifies no guests (Google notes some emails might still be
sent). `calendar.create_event`, `calendar.update_event`, and `calendar.delete_event` accept an
optional `sendUpdates`, sent as Google's `sendUpdates` query parameter, never in the event body:
`all` notifies every guest, `externalOnly` only guests who do not use Google Calendar, and `none`
nobody (Google warns `none` can stop the event syncing to guests' other calendars or lose it for some guests). Omitting it
normally sends no invitation, update, or cancellation email.

### Drive actions [#drive-actions]

| Action id             | What it does                                         | Access        |
| --------------------- | ---------------------------------------------------- | ------------- |
| `drive.list_files`    | list file/folder metadata, optionally under a parent | `read`        |
| `drive.search_files`  | search file names and indexed text                   | `read`        |
| `drive.get_file`      | fetch metadata by file id                            | `read`        |
| `drive.create_folder` | create a root or child folder                        | `write`       |
| `drive.trash_file`    | move a file or folder to trash                       | `destructive` |
| `drive.delete_file`   | permanently delete without moving to trash           | `destructive` |

List and search outputs contain `files`, optional `nextPageToken`, and optional
`incompleteSearch`. Pass the token back through `pageToken`. Trashed files are excluded by default;
set `includeTrashed: true` to include them. Search accepts a plain `query` and applies it to Drive
file names and indexed text rather than exposing raw Drive query syntax.

Set optional `driveId` to search or list one shared drive through `corpora=drive`. Drive requests
send current shared-drive support parameters, and returned file metadata may include `driveId`,
`resourceKey`, and operation `capabilities`. Pass `resourceKey` with get/trash/delete or
`parentResourceKey` with parent-scoped list/search/create; the connector forwards it through
`X-Goog-Drive-Resource-Keys` for protected link-shared files. The host should check and enforce
capabilities before destructive calls; Google still applies ownership, shared-drive role,
administrator, and per-file rules.

`drive.trash_file` is the reversible default. `drive.delete_file` bypasses trash and permanently
removes the item; deleting a folder can also remove owned descendants. Binary downloads and exports use separate host-only helpers; uploads are not added. See
[Transfer connector files](../connectors/files) for content consent and host transport. Hosts own
Google Picker or equivalent per-file authorization.

Google references: [files.list](https://developers.google.com/workspace/drive/api/reference/rest/v3/files/list), [search syntax](https://developers.google.com/workspace/drive/api/guides/search-files), [create folders](https://developers.google.com/workspace/drive/api/guides/folder), [trash and delete](https://developers.google.com/workspace/drive/api/guides/delete), [shared drives](https://developers.google.com/workspace/drive/api/guides/enable-shareddrives), [resource keys](https://developers.google.com/workspace/drive/api/guides/resource-keys), and [OAuth scopes](https://developers.google.com/workspace/drive/api/guides/api-specific-auth).

## Microsoft [#microsoft]

Use `@yolk-sdk/connectors/microsoft` for Microsoft Outlook mail, OneDrive files, SharePoint site
libraries, and Microsoft Teams chats, channels and meeting transcripts. These workloads share Microsoft Graph v1.0 as the API and OAuth resource boundary, plus
the same `microsoft.oauth` credential binding. The connector does not use the retired Outlook REST
endpoint, direct Exchange Online APIs, or legacy OneDrive APIs. The sole exception is the
pre-authenticated Outlook attachment upload-session URLs that Graph issues to
`addOutlookAttachment`, contacted without Authorization.

All OAuth slots use the shared `microsoft.oauth` binding id:

| Slot                                                  | Permission hint                                          |
| ----------------------------------------------------- | -------------------------------------------------------- |
| `MicrosoftOutlookReadOAuthCredentialSlot`             | `Mail.Read`                                              |
| `MicrosoftOutlookWriteOAuthCredentialSlot`            | `Mail.ReadWrite`                                         |
| `MicrosoftOutlookSendOAuthCredentialSlot`             | `Mail.Send`                                              |
| `MicrosoftOutlookSharedReadOAuthCredentialSlot`       | `Mail.Read.Shared`                                       |
| `MicrosoftOutlookSharedWriteOAuthCredentialSlot`      | `Mail.ReadWrite.Shared`                                  |
| `MicrosoftOutlookSharedSendOAuthCredentialSlot`       | `Mail.Send.Shared`                                       |
| `MicrosoftOneDriveReadOAuthCredentialSlot`            | `Files.Read`                                             |
| `MicrosoftOneDriveWriteOAuthCredentialSlot`           | `Files.ReadWrite`                                        |
| `MicrosoftOneDriveReadAllOAuthCredentialSlot`         | `Files.Read.All`                                         |
| `MicrosoftOneDriveWriteAllOAuthCredentialSlot`        | `Files.ReadWrite.All`                                    |
| `MicrosoftSharePointSitesReadOAuthCredentialSlot`     | `Sites.Read.All`                                         |
| `MicrosoftTeamsChatReadOAuthCredentialSlot`           | `Chat.Read`                                              |
| `MicrosoftTeamsChatSendOAuthCredentialSlot`           | `ChatMessage.Send`                                       |
| `MicrosoftTeamsTeamReadOAuthCredentialSlot`           | `Team.ReadBasic.All`                                     |
| `MicrosoftTeamsChannelReadOAuthCredentialSlot`        | `Channel.ReadBasic.All`                                  |
| `MicrosoftTeamsChannelMessageReadOAuthCredentialSlot` | `ChannelMessage.Read.All` (admin consent)                |
| `MicrosoftTeamsChannelMessageSendOAuthCredentialSlot` | `ChannelMessage.Send`                                    |
| `MicrosoftTeamsMeetingReadOAuthCredentialSlot`        | `OnlineMeetings.Read`                                    |
| `MicrosoftTeamsTranscriptReadOAuthCredentialSlot`     | `OnlineMeetingTranscript.Read.All` (admin consent)       |
| `MicrosoftOutlookCategoryReadOAuthCredentialSlot`     | `MailboxSettings.Read`                                   |
| `MicrosoftOutlookCategoryWriteOAuthCredentialSlot`    | `MailboxSettings.ReadWrite`                              |
| `MicrosoftCombinedOAuthCredentialSlot`                | mail and file scopes, excluding categories, sites, Teams |
| `MicrosoftOAuthCredentialSlot`                        | none declared                                            |

Inputs default to the signed-in mailbox through `/me`. Set optional `mailbox` to a user ID or user
principal name to target an Exchange Online shared/delegated mailbox through `/users/{mailbox}`.
For message actions, the connector then requests the matching Shared slot, unless the explicit `mailbox` matches the
connected user identity (`OAuthCredential.accountId`, case-insensitive), which keeps the ordinary
`Mail.*` slot on the same `/users/{mailbox}` path. The same `mailbox` must accompany an opaque
`nextLink` so the resolver receives the appropriate mailbox consent hint. Populate `accountId` with
the same Graph user ID or `userPrincipalName` callers pass as `mailbox`; the comparison ignores case
only, not whitespace, and does not resolve aliases or equate IDs with principal names. Explicit
mailboxes in delegated mode resolve the scope-free `microsoft.oauth` identity slot first, then the
selected operation slot. The identity lookup does not authorize the operation.

For delegated reads and writes, the signed-in user needs the corresponding Exchange shared-folder
or Full Access grant. Sending from another mailbox requires Exchange **Send As** or **Send on
Behalf** rights; this connector's `/users/{mailbox}` send path also requires Full Access.

For application tokens, set integration config `mailboxAccessMode` to `application` and always pass
`mailbox`. The connector then selects non-Shared `Mail.Read`, `Mail.ReadWrite`, or `Mail.Send`
application-permission hints. Scope application access to approved mailboxes with host/admin policy,
such as Exchange Online RBAC for Applications.

Hosts own Entra app registration, OAuth authority/tenant selection, consent, callbacks, token
refresh, credential storage, and Exchange mailbox authorization. Use action-scoped slots for
least-privilege consent. A single credential can cover Outlook and OneDrive when it has both the
required `Mail.*` and `Files.*` grants.

### Outlook actions [#outlook-actions]

| Action id                         | What it does                                                   |
| --------------------------------- | -------------------------------------------------------------- |
| `outlook.list_messages`           | list mailbox or folder messages with opaque Graph paging       |
| `outlook.search_messages`         | search messages with Microsoft Graph mail `$search` syntax     |
| `outlook.get_message`             | fetch one message with text body and headers                   |
| `outlook.list_attachments`        | list attachment metadata, including inline attachments         |
| `outlook.get_attachment`          | fetch one file attachment; as an agent tool, a file (`fileId`) |
| `outlook.create_draft`            | create a new message draft                                     |
| `outlook.create_reply_draft`      | create a reply draft preserving Graph-generated quoted history |
| `outlook.update_draft`            | edit recipients, subject, and full body on an existing draft   |
| `outlook.send_mail`               | submit a new message for sending                               |
| `outlook.send_draft`              | submit an existing draft for sending                           |
| `outlook.reply`                   | send the reviewed reply in one request, no draft in between    |
| `outlook.set_read`                | mark a message read or unread                                  |
| `outlook.set_flag`                | flag/unflag a message for follow-up                            |
| `outlook.trash`                   | move a message to Deleted Items                                |
| `outlook.untrash`                 | move a message from Deleted Items to inbox or another folder   |
| `outlook.move_message`            | move a message to any folder                                   |
| `outlook.list_categories`         | list master categories                                         |
| `outlook.create_category`         | create a master category                                       |
| `outlook.delete_category`         | delete a master category                                       |
| `outlook.get_category`            | get one master category                                        |
| `outlook.update_category`         | update a master category color                                 |
| `outlook.set_categories`          | replace or clear message category names                        |
| `outlook.modify_categories`       | add/remove message category names                              |
| `outlook.batch_set_read`          | batch mark read/unread                                         |
| `outlook.batch_set_flag`          | batch flag/unflag for follow-up                                |
| `outlook.batch_move`              | batch move to a folder                                         |
| `outlook.batch_trash`             | batch move to Deleted Items                                    |
| `outlook.batch_untrash`           | batch restore from Deleted Items                               |
| `outlook.batch_modify_categories` | batch add/remove category names                                |
| `outlook.delete_permanently`      | permanently delete messages                                    |

Attaching files to a draft is host-only, not an action: call `addOutlookAttachment` from
`@yolk-sdk/connectors/microsoft` after `outlook.create_draft`/`outlook.create_reply_draft` and
before `outlook.send_draft`. See [Transfer connector files](../connectors/files#attach-a-file-to-an-outlook-draft).

#### Categories [#categories]

List takes `{ mailbox?, top?, nextLink? }` and returns `{ categories, nextLink? }`, with an Effect
`Chunk` of categories (`id`, `displayName`, optional `color`). Create takes
`{ mailbox?, displayName, color? }`, where color is `none` or `preset0` through `preset24`.
Delete takes `{ mailbox?, categoryId }` and returns `{ id, deleted: true }` without decoding
Graph's empty 204 body. The name is immutable; deleting a master category does not remove its
name from existing message assignments. `outlook.get_category` takes `{ mailbox?, categoryId }`
and returns the typed category. `outlook.update_category` takes `{ mailbox?, categoryId, color }`
and PATCHes only the color.

Master-category list and mutations require opt-in `MailboxSettings.Read` and
`MailboxSettings.ReadWrite`, respectively, sharing `microsoft.oauth`. These are not in the
existing combined slot. There are no `.Shared` mailbox-settings scopes; delegated access to
another mailbox's settings remains subject to Graph authorization. Application mode requires an
explicit `mailbox`. List accepts the same null/blank placeholders as message lists; replay
`nextLink` unchanged with the same mailbox. Only that Graph v1.0 category collection is accepted.

Assign names, **not category IDs**, using `outlook.set_categories` with
`{ messageId, mailbox?, categories }`; `[]` clears all names. `outlook.modify_categories` takes
`{ messageId, mailbox?, addCategories?, removeCategories? }` with at least one list. It reads
current categories, merges names (deduped by exact case-sensitive match, removals win), and PATCHes
the result. Invalid/failed
reads never trigger a PATCH. Both calls use `Mail.ReadWrite` or `Mail.ReadWrite.Shared` and
preserve the existing own-mailbox/application guards and immutable-ID headers. Neither action
creates master categories automatically. The merge is **non-atomic**: hosts must serialize
competing updates, and the SDK makes no retry or compare-and-swap guarantee.

Outlook messages report `isRead` plus follow-up flag state as `isFlagged` (`flagged` is true;
`notFlagged` and `complete` are false; anything else asserts nothing). `outlook.list_messages`
accepts optional `isRead`/`isFlagged` booleans composed into `$filter` (`isRead eq true|false`,
`flag/flagStatus eq 'flagged'`, `flag/flagStatus ne 'flagged'`) alongside any raw filter; typed
filters cannot be combined with `nextLink`.

Batch actions take `{ messageIds, mailbox?, ... }` with 1-100 unique nonempty path-safe IDs and
return complete per-ID outcomes in `messageIds` order with exact summary counts and sanitized codes
only, executed through Graph JSON batching with at most 20 subrequests per sequential envelope,
unique correlation IDs, per-subrequest immutable-ID preferences, and responses matched by correlation
ID (never position or outer status). `outlook.batch_set_read` and `outlook.batch_set_flag` PATCH
individually addressed messages; `outlook.batch_move`, `outlook.batch_trash` (to `deleteditems`),
and `outlook.batch_untrash` (from Deleted Items, defaulting to `inbox`) POST to `/move` and report
the provider-returned message ID plus actual `parentFolderId` on success, never a fabricated
destination. `outlook.batch_modify_categories` reads current categories per chunk (a failed read
leaves that message `not_attempted` instead of erasing categories) then PATCHes the exact
case-sensitive merge. `outlook.delete_permanently` POSTs `permanentDelete` (documented 204
establishes success); items enter Recoverable Items/Purges, so retention or holds may still
preserve them and this is not compliance erasure.

#### Unsubscribe from mailing lists and report spam [#unsubscribe-from-mailing-lists-and-report-spam]

No provider exposes unsubscribe as an API; use the required message headers instead. Read headers
with `gmail.get_message` (`full` or `metadata` format via `payload.headers`; or `gmail.get_thread`
with `format: 'metadata'` and `metadataHeaders: ['List-Unsubscribe', 'List-Unsubscribe-Post']`;
without a selection `gmail.get_thread` returns only its fixed selected-header allowlist, never
`List-Unsubscribe`), `outlook.get_message`, or `email.get_message`, then call the pure
`parseUnsubscribeMethods(headers)` helper from `@yolk-sdk/connectors` (no IO) to get `mailto`
address methods and HTTP methods with a `oneClick` flag from `List-Unsubscribe-Post`. Executing a
method stays host-owned: send `mailto:` removals through `outlook.send_mail`, `email.send_message`,
or host-generated MIME via `gmail.send_message` (reusing the URI `subject` when present, after host
authorization), and perform HTTP methods with a host network call — plain GET, or POST with
`List-Unsubscribe-Post: List-Unsubscribe=One-Click` for one-click endpoints. Verify authentication
results (DKIM covering the list headers) before automatic one-click POSTs and apply the same
public-network policy as other host fetches. Never route publisher URLs through the provider
`ConnectorHttpClient` port; that port is for provider APIs under host transport policy.

Report spam with existing actions and no new code: add the `SPAM` label through
`gmail.modify_labels`, move to the `junkemail` well-known folder through
`outlook.move_message`, or move to the server's Junk mailbox through `email.move` with an
explicit destination folder (there is no `\Junk` special-use discovery; use the server's advertised
name such as `Junk` or `Spam`).

#### Edit a draft [#edit-a-draft]

`outlook.update_draft` takes `{ messageId, mailbox?, to?, cc?, bcc?, subject?, body?, contentType? }`.
It requires at least one editable field; `contentType` alone is invalid. Omitted fields remain
unchanged and empty recipient arrays clear them. `body` is the **complete replacement**, not text
to prepend, so include any quoted history you want to retain. The default content type is `text`;
select `html` explicitly for HTML. No whitespace is rewritten.

The action issues one Graph PATCH and returns the updated identified draft as `OutlookMessage`.
Graph enforces draft-only edits. Existing own/shared/application mailbox write permissions and
immutable-ID headers apply. This is a `write` action, never a send operation. After-dispatch HTTP
failures (`outlook_update_draft_failed`) and typed failures preserve the draft ID in
`underlying: { draftId, retryable: false, recovery: 'read_edit_existing_draft' }` without provider
bodies or retry hints. Read the same draft using its original mailbox before another edit or send.

There is no compare-and-swap guarantee. Updating a draft and then calling `outlook.send_draft`
is **not atomic**: another mailbox client can change it between requests. Hosts own serialization
and review of the full final content, including any quoted history. Do not infer that the
interaction receipt makes the provider's draft immutable.

#### Send a reviewed reply [#send-a-reviewed-reply]

`outlook.reply` takes `{ messageId, mailbox?, to, cc, bcc, subject, body, contentType? }`,
where `messageId` identifies the original message. All three recipient arrays are required and
sent explicitly, including empty ones, so no recipient field is left implicit in the request;
`to` must hold at least one address. `body` is the caller's complete string, preserved
exactly with no appended quote, subject prefix, or recipient inference. The default content type
is `text`; select `html` explicitly for HTML. The action issues one Graph `POST .../reply` with
`{ message: { subject, body, toRecipients, ccRecipients, bccRecipients } }` and never sets
`comment` or `from`: the mailbox selects the authorized sender path and Graph chooses the
mailbox identity. Existing own/shared/application mailbox send permissions and immutable-ID
headers apply. This is a `destructive` action.

Prefer it over `outlook.update_draft` followed by `outlook.send_draft` for dispatching a reviewed
reply: placing the reviewed fields in the send request avoids an intermediate mutable draft that
another mailbox client could edit between requests. Only HTTP 202 Accepted counts as accepted
(`{ accepted: true }`); Graph documents saving replies in Sent Items. Other HTTP statuses return
`outlook_reply_rejected` or `outlook_reply_unknown` failures with
`underlying: { outcome: 'rejected' | 'unknown', retryable: false }`. After-dispatch transport
failures are typed `ConnectorError`s with the unknown metadata. Neither includes retry hints or
provider bodies. Acceptance is not delivery, and success carries no message ID or exactly-once
claim. Reconcile before considering another send.

#### Reply drafts and recovery [#reply-drafts-and-recovery]

`outlook.create_reply_draft` creates a bodyless reply draft, then prepends the supplied text or HTML
to Graph-generated quoted history and saves it. Supply only the new reply, not the original quote.
Text replies preserve quote content, not its original HTML formatting.

This is a multi-step write. Once a draft ID is known, post-create HTTP failures return
`outlook_create_reply_draft_partial` with the HTTP `status` but no `retryAfterMs`, including for 429.
A read-back without the requested body format uses the same partial-failure code: `status` is the
last Graph response status and can be 2xx. Branch on the failure code/recovery metadata, not HTTP
status alone. Both these failures and post-create typed `ConnectorError`s carry
`underlying: { draftId, retryable: false, recovery: 'read_edit_existing_draft' }`. Inspect this
metadata before applying any retry policy: read and edit the existing draft using the original
`mailbox`, **never repeat the create action**. A failed response can follow a successful save.
If creation's response is lost or lacks a usable ID, reconcile mailbox state before attempting
another creation. The SDK neither retries creation nor deletes a partially completed draft.

#### Optional Outlook read inputs [#optional-outlook-read-inputs]

`outlook.list_messages` and `outlook.search_messages` accept omitted, `null`, or blank optional
strings for `mailbox`, `folderId`, and `nextLink`; list also accepts these placeholders for `filter`
and `orderBy`. Decoding normalizes them to `undefined`, preserving non-blank strings unchanged.
`top` accepts omission or `null` for the provider default; explicit values must be integers from
1 to 1000. Search still requires a string `query`, and application access still requires a
non-blank `mailbox`. These rules apply to direct connector calls and generated agent tools, not
other Outlook actions.

List and search outputs expose Graph's complete `@odata.nextLink` as `nextLink`. Pass it back
unchanged; repeat `mailbox` for explicit-mailbox continuations and `folderId` for folder
continuations. The connector accepts only global Graph v1.0 links for the selected mailbox and
folder collection. Read and draft-returning requests
use Graph immutable IDs; `outlook.get_message` requests text for the full body plus required
`internetMessageHeaders` (name/value pairs: `List-Unsubscribe`, `References`, and authentication
results when the message carries them; an empty array when Graph returns none, as for Sent Items
and drafts). List, draft, and mutation responses return the base message without headers. A draft
ID can still change when sent, which is a documented immutable-ID exception.

`outlook.list_attachments` returns normalized metadata with `kind: 'file' | 'item' | 'reference' |
'unknown'`; unlike `hasAttachments`, listing also discovers inline attachments. The list query
selects base attachment properties only and accepts explicit null `lastModifiedDateTime` values.
Do not expect `contentId` in list results; use `outlook.get_attachment` on the individual file
attachment when you need `cid:` mapping.
It accepts `top` and
returns an opaque `nextLink`; pass that link back unchanged with the same `messageId` and `mailbox`.
Use `outlook.get_attachment` with a returned file attachment ID. It requires a Graph file attachment
with string `contentBytes` (not checked as base64: whoever decodes it validates it) and returns
required `contentBase64`. Item and reference attachments
remain available only as list metadata and are rejected by this action. Hosts own base64 decoding, size limits,
durable storage, and content scanning.

#### Read state, flags, trash, and move [#read-state-flags-trash-and-move]

`outlook.set_read` accepts `{ messageId, isRead, mailbox? }`: `true` marks read and `false` marks
unread via Graph `PATCH`. `outlook.set_flag` accepts `{ messageId, isFlagged, mailbox? }` and
PATCHes `flag.flagStatus` to `flagged` or `notFlagged` for follow-up. `outlook.trash` accepts `{ messageId, mailbox? }` and calls Graph `/move`
with destination `deleteditems`, never permanent deletion. `outlook.untrash` accepts
`{ messageId, mailbox?, destinationFolderId? }` and moves from Deleted Items to `inbox` by default,
or the specified folder ID/well-known name. It neither infers the original folder nor recovers
permanently deleted messages. `outlook.move_message` accepts
`{ messageId, mailbox?, destinationFolderId }` with a required destination and moves the message
there. The source folder is not an input, so the connector performs no same-folder check; Graph
decides the outcome. A `deleteditems` destination matches `outlook.trash`: hosts gating on access
should override accordingly.

All four return the updated `OutlookMessage` and request immutable IDs. Use the returned `id`
for subsequent operations. Permission hints are `Mail.ReadWrite` for the signed-in mailbox,
matching connected-user mailboxes, and application mode, or `Mail.ReadWrite.Shared` for other
explicit delegated mailboxes. Application mode
still requires `mailbox`; hosts own consent and Exchange grants. Read-state, restore, and move actions
have `write` access; trash has `destructive` access.

Send actions return `{ accepted: true }` for Graph's `202 Accepted`. Acceptance confirms submission,
not processing or delivery.

### OneDrive actions [#onedrive-actions]

OneDrive inputs default to `/me/drive`; set `driveId` to target `/drives/{driveId}`. Default
delegated mode uses least-privilege `Files.Read` or `Files.ReadWrite`. Set integration config
`oneDriveAccessMode` to `delegated_all` to select `Files.Read.All` or `Files.ReadWrite.All` for
broader delegated access. Application-token hosts set it to `application`, must provide `driveId`,
and use the same `Files.*.All` permission hints. The host owns admin consent and application access
policy.

| Action id                       | What it does                                                            |
| ------------------------------- | ----------------------------------------------------------------------- |
| `onedrive.list_items`           | list root or folder children with opaque Graph paging                   |
| `onedrive.search_items`         | search names, metadata, and indexed content                             |
| `onedrive.get_item`             | fetch metadata by stable DriveItem id                                   |
| `onedrive.resolve_sharing_link` | resolve a sharing link to its DriveItem, with `parentReference.driveId` |
| `onedrive.create_folder`        | create a root or child folder with conflict behavior                    |
| `onedrive.move_item`            | move an item within one drive; `write`; optional `ifMatch`              |
| `onedrive.copy_item`            | accept an asynchronous copy; `write`; `accepted` is not completed       |
| `onedrive.get_copy_status`      | poll one copy monitor; `read`; send no credential to the monitor URL    |
| `onedrive.delete_item`          | move a file or folder to the recycle bin, optionally by ETag            |

`onedrive.move_item` sends a same-drive `PATCH` with a destination parent ID and optional rename.
It does not move across drives or invent copy-then-delete. Moving to drive root requires the root
folder's actual item ID, not the literal `root` alias. `onedrive.copy_item` returns
`{ status: 'accepted', monitorUrl }` after Graph `202`; name conflicts can still fail later.
Conflict modes are non-destructive `fail` (default) and `rename`. Destructive `replace` is not
exposed. `onedrive.get_copy_status` performs one poll and requires the host HTTP adapter to honor
`redirect: 'manual'` and `credentials: 'omit'`. Treat monitor URLs as secrets. A manual `303` means
completed; do not follow or expose its `Location`. Hosts own approval, cadence, expiry, retries,
and reconciliation.

`onedrive.resolve_sharing_link` takes a OneDrive or SharePoint sharing link exactly as received
(https on `*.sharepoint.com`, `1drv.ms`, or `onedrive.live.com`), encodes it as Graph's `u!` share
id (`oneDriveSharingUrlShareId`), and sends `GET /shares/{shareId}/driveItem` with
`Prefer: redeemSharingLinkIfNecessary`, so access is granted for that request only and the link is
never redeemed. The returned item's `parentReference.driveId` and `id` address it in the other
OneDrive actions and `downloadOneDriveItem`; those later requests still need the user's own access
to the item. Sharing links usually point at files other people own, which delegated `Files.Read`
does not reach for work or school accounts, so both delegated modes ask for `Files.Read.All`;
`application` asks for `Files.ReadWrite.All`. Graph's permission table lists `Files.ReadWrite` as
the least privileged delegated permission for this API (unverified: whether delegated
`Files.Read.All` alone resolves links to files other people own).

Pass list/search `nextLink` values back unchanged. Repeat `driveId` for explicit-drive
continuations and `parentItemId` for folder-list continuations. The connector validates the global
Graph origin and selected OneDrive collection before replaying a link.

The current OneDrive **action set** still excludes binary download, upload, and resumable upload
sessions: its HTTP port is string/JSON-oriented. Original-byte download is a separate host helper,
not an action. Host-only create/update use a separate write port; resumable sessions remain unimplemented.

### SharePoint actions [#sharepoint-actions]

SharePoint team-site document libraries are drives too. The SharePoint actions find their drive
IDs; the OneDrive actions then read them through `driveId`. Both use
`MicrosoftSharePointSitesReadOAuthCredentialSlot` (`Sites.Read.All`, Graph's least privileged
permission for site search, delegated and application alike), which stays out of the combined slot.
Reading the libraries' items with delegated tokens also needs `Files.Read.All` (or
`Sites.Read.All`) in the token: delegated `Files.Read` covers only the signed-in user's own files
for work or school accounts. Keep `oneDriveAccessMode` at `delegated`: the OneDrive read slots still
ask for `Files.Read`, Graph honors every scope the token carries, and `delegated_all` would also
make writes ask for `Files.ReadWrite.All`. `sharepoint.list_site_drives` uses the site slot rather
than Graph's listed `Files.Read` to keep site discovery on one opt-in slot, including for site ids
from a resolved item's `parentReference.siteId`. Graph site search is
not available for personal Microsoft accounts. The SharePoint actions and
`onedrive.resolve_sharing_link` do not require `driveId` in `application` mode.

| Action id                     | What it does                                                       |
| ----------------------------- | ------------------------------------------------------------------ |
| `sharepoint.search_sites`     | search the sites the signed-in user can access, with opaque paging |
| `sharepoint.list_site_drives` | list one site's document libraries (drives) by site id             |

Site ids have the form `{hostname},{site-collection-id},{web-id}`; the connector keeps the commas
literal in the request path. Outputs omit properties Graph sends as `null`. Pass `nextLink` values
back unchanged (with the same `siteId` for drive listings); the connector replays only links to
the same Graph collection.

### Teams actions [#teams-actions]

The Teams actions (`src/microsoft/teams.ts`) read and send as the signed-in user with delegated
permissions only; each uses its own opt-in slot (table above), none of which the combined slot
includes, so hosts can show each action only while the token carries its permission. Graph
supports none of them for personal Microsoft accounts. `ChannelMessage.Read.All` and
`OnlineMeetingTranscript.Read.All` need tenant admin consent even as delegated permissions; Entra
fails the whole authorization request when one requested permission lacks consent, so a host that
requests them with other Microsoft scopes makes that consent a prerequisite of the whole sign-in.

| Action id                            | What it does                                                                  |
| ------------------------------------ | ----------------------------------------------------------------------------- |
| `teams.list_chats`                   | list the user's chats with members (default) or the latest message preview    |
| `teams.get_chat`                     | get one chat with up to 25 members                                            |
| `teams.list_chat_messages`           | list a chat's messages, most recently changed first; optional `modifiedSince` |
| `teams.get_chat_message`             | get one chat message                                                          |
| `teams.send_chat_message`            | send a plain-text message to an existing chat; `destructive`                  |
| `teams.list_joined_teams`            | list the teams the user belongs to                                            |
| `teams.get_team`                     | get one team's name, description and archived state                           |
| `teams.list_channels`                | list a team's channels the user can see                                       |
| `teams.get_channel`                  | get one channel                                                               |
| `teams.list_channel_messages`        | list a channel's top-level posts                                              |
| `teams.get_channel_message`          | get one channel post                                                          |
| `teams.list_channel_message_replies` | list one post's replies                                                       |
| `teams.send_channel_message`         | post a plain-text message with an optional subject; `destructive`             |
| `teams.reply_to_channel_message`     | reply in plain text to a channel post; `destructive`                          |
| `teams.find_online_meeting`          | find a meeting the user organized or was invited to by its join link          |
| `teams.list_meeting_transcripts`     | list one meeting's transcripts                                                |

Sends take plain text: the connector escapes it, turns line breaks into `<br>` and posts an HTML
body (Graph documents no line-break handling for `text` bodies), so markup and mentions are not
supported. The escaped body is limited to `teamsMessageMaxBytes` (28 KiB), well below Teams' about
100 KB per post, and an over-limit message fails validation before any request. Message outputs
keep Graph's body (`contentType` and `content`, usually HTML), sender (`from` with `kind` user,
application or device), attachments' metadata, mentions, and `messageType` and `deletedDateTime`,
so system events and deleted messages stay recognizable. Outputs omit properties Graph sends as
`null`. Pass `nextLink` values back unchanged with the same ids; the connector replays only links
to the same Graph collection (ids compared decoded, since Graph may echo them either way; a `/me`
collection's link may name the user as `/users/{id}`).

Graph has no delegated way to list meetings. Take the join link from a calendar event
(`onlineMeeting.joinUrl`) or a meeting chat (`onlineMeetingJoinWebUrl`), pass it to
`teams.find_online_meeting` (only `https://teams.microsoft.com` links; the filter quotes it), then
list transcripts by the returned meeting id. Transcripts need the meeting to be transcribed, on the
user's calendar and not expired; tenants that turn off Graph access to transcripts answer 403.

`downloadTeamsMeetingTranscript` is a host-only download like `downloadOneDriveItem`: it reads the
transcript's metadata (its id must match), then `content?$format=text/vtt` through the binary port,
returning WebVTT bytes (`teamsTranscriptMimeType`) or a typed `ConnectorFileTransferError`. The
Teams reads and the chat send have unverified conformance cases and fixture-only emulator routes
([Microsoft conformance](../connectors/microsoft#conformance-cases)); the channel sends and the
transcript download have none yet.

### Host-only OneDrive original-byte download [#host-only-onedrive-original-byte-download]

`downloadOneDriveItem` from `@yolk-sdk/connectors/microsoft` returns original file bytes. It is not
registered on `MicrosoftConnector` and is never serialized by `makeConnectorToolModule`.

```ts
import { downloadOneDriveItem } from '@yolk-sdk/connectors/microsoft'

// Fragment: host-owned integration and selected item IDs from discovery.
const download = downloadOneDriveItem(
  integration,
  { itemId: selectedItem.id, driveId: selectedItem.parentReference?.driveId },
  { maxBytes: 20 * 1024 * 1024, maxMetadataBytes: 1024 * 1024, maxErrorBodyBytes: 16 * 1024 }
)
```

The budgets are trusted host configuration, not tool parameters. Provide the existing
`CredentialResolver` and a compliant `ConnectorBinaryHttpClient` layer; default Microsoft actions
still use only `ConnectorHttpClient`. IDs come from discovery (`itemId`, optional `driveId`).
SharePoint files need a document-library drive ID: discover it with the
[SharePoint actions](#sharepoint-actions) or `onedrive.resolve_sharing_link`.
Hosts must materialize, scan, and extract the `Uint8Array`; do not put raw bytes into generic
model tool JSON. See [Integration APIs](../api-reference/integrations#connectors) and
[Troubleshooting](../troubleshooting) for adapter and error details.

The built-in endpoint targets the global Microsoft cloud; it does not currently configure
national-cloud Graph hosts.

Microsoft references: [Outlook mail API overview](https://learn.microsoft.com/en-us/graph/outlook-mail-concept-overview), [shared/delegated folders](https://learn.microsoft.com/en-us/graph/outlook-share-messages-folders), [OneDrive overview](https://learn.microsoft.com/en-us/graph/onedrive-concept-overview), [DriveItem addressing](https://learn.microsoft.com/en-us/graph/onedrive-addressing-driveitems), [list children](https://learn.microsoft.com/en-us/graph/api/driveitem-list-children?view=graph-rest-1.0), and [search DriveItems](https://learn.microsoft.com/en-us/graph/api/driveitem-search?view=graph-rest-1.0), [access shared items](https://learn.microsoft.com/en-us/graph/api/shares-get?view=graph-rest-1.0), [search sites](https://learn.microsoft.com/en-us/graph/api/site-search?view=graph-rest-1.0), [list a site's drives](https://learn.microsoft.com/en-us/graph/api/drive-list?view=graph-rest-1.0), [list chats](https://learn.microsoft.com/en-us/graph/api/chat-list?view=graph-rest-1.0), [send a chat message](https://learn.microsoft.com/en-us/graph/api/chat-post-messages?view=graph-rest-1.0), [list channel messages](https://learn.microsoft.com/en-us/graph/api/channel-list-messages?view=graph-rest-1.0), [get an online meeting](https://learn.microsoft.com/en-us/graph/api/onlinemeeting-get?view=graph-rest-1.0), and [list transcripts](https://learn.microsoft.com/en-us/graph/api/onlinemeeting-list-transcripts?view=graph-rest-1.0).

## Kie [#kie]

| Action id               | What it does                                                            | Access  |
| ----------------------- | ----------------------------------------------------------------------- | ------- |
| `kie.create_image_task` | submit a GPT Image 2 task (image-to-image when `inputUrls` are given)   | `write` |
| `kie.create_video_task` | submit a Wan 2.7 image-to-video task from a first frame or a first clip | `write` |
| `kie.get_task`          | read a task's state, raw `resultJson`, result URLs, and failure detail  | `read`  |

All actions use `KieApiKeySlot` (`kie.api_key`, sent as a bearer token). Generation is
asynchronous: the create actions return a `taskId` (each task spends Kie credits) and
`kie.get_task` polls it. `callBackUrl` is an action input (model-supplied when the action is a
tool); hosts that allow it own the webhook and its verification, and hosts that must pin it strip
or override it. Code-mode scripts have no timers, so expose `kie.get_task` with
`callableBy: 'model'` ([code mode polling gap](https://github.com/magoz/yolk-sdk/blob/main/docs/adr/0002-code-mode.md#known-gap-polling)). Input
URLs are fetched by Kie, so the connector checks only that they are absolute http(s) URLs without
credentials. Kie answers most failures with HTTP 200 and a non-200 envelope `code`; the connector
returns those, and non-2xx statuses, as `ProviderFailure`s (`kie_unauthorized`,
`kie_insufficient_credits`, `kie_validation`, `kie_rate_limited`, `kie_generation_failed`, ...).
A task in state `fail` is a successful read carrying `failCode` and `failMsg`. Result URLs expire
(Kie keeps generated files for 14 days).

## LinkedIn search [#linkedin-search]

| Action id                 | What it does                                  | Credential              |
| ------------------------- | --------------------------------------------- | ----------------------- |
| `linkedin_search.search`  | search LinkedIn people results through Exa    | `ExaApiKeySlot`         |
| `linkedin_search.profile` | fetch a LinkedIn profile through Enrich Layer | `EnrichLayerApiKeySlot` |
| `linkedin_search.email`   | fetch or queue a LinkedIn email lookup        | `EnrichLayerApiKeySlot` |

## Notion [#notion]

| Action family | Action ids                                                                                                           |
| ------------- | -------------------------------------------------------------------------------------------------------------------- |
| Search        | `notion.search`                                                                                                      |
| Pages         | `notion.get_page`, `notion.create_page`, `notion.update_page`, `notion.get_page_content`, `notion.get_page_property` |
| Blocks        | `notion.append_blocks`, `notion.update_block`, `notion.delete_block`, `notion.get_block`                             |
| Databases     | `notion.get_database`, `notion.query_database`, `notion.create_database`, `notion.update_database`                   |
| Data sources  | `notion.get_data_source`, `notion.query_data_source`, `notion.create_data_source`, `notion.update_data_source`       |
| Users         | `notion.list_users`, `notion.get_user`, `notion.get_bot_user`                                                        |
| Comments      | `notion.create_comment`, `notion.list_comments`                                                                      |

## Cloudflare R2 [#cloudflare-r2]

| Action id               | What it does                                                            |
| ----------------------- | ----------------------------------------------------------------------- |
| `r2_storage.upload_url` | create a presigned PUT upload URL through a host-provided `R2Presigner` |

R2 presigning is host-provided. The connector does not bundle an AWS SDK.

## GitHub [#github]

`GithubConnector` is scoped to integration config `owner`/`repo`; action inputs never carry
either. `github.token` accepts an installation token, PAT, or OAuth token. Every action declares
access metadata; `delete_issue_comment` and `merge_pull_request` are `destructive`, and merges
require `expectedHeadSha`.

| Action family | Action ids (`github.*`)                                                                                                                                                                                                                                                                                                                                    |
| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Issues        | `search_issues`, `list_issues`, `get_issue`, `create_issue`, `update_issue`, `lock_issue`, `unlock_issue`, `add_assignees`, `remove_assignees`, `list_assignees`, `list_issue_timeline`                                                                                                                                                                    |
| Comments      | `list_issue_comments`, `create_issue_comment`, `update_issue_comment`, `delete_issue_comment`, `list_labels`, `add_labels`, `remove_label`, `list_milestones`, `create_reaction`                                                                                                                                                                           |
| Structure     | `list_sub_issues`, `add_sub_issue`, `remove_sub_issue`, `list_issue_dependencies`, `add_blocked_by`, `remove_blocked_by`, `list_issue_types`, `list_issue_fields`, `set_issue_field_values`                                                                                                                                                                |
| Pull requests | `list_pull_requests`, `get_pull_request`, `list_pull_request_files`, `list_pull_request_commits`, `get_pull_request_checks`, `list_pull_request_reviews`, `list_pull_request_review_comments`, `create_pull_request`, `update_pull_request`, `request_reviewers`, `create_pull_request_review`, `create_pull_request_review_comment`, `merge_pull_request` |
| Repository    | `compare_commits`, `list_releases`, `get_file_contents`, `search_code`                                                                                                                                                                                                                                                                                     |

Host-only helpers, not actions: `createGithubAppInstallationToken` mints GitHub App installation
tokens with a WebCrypto-signed JWT, and `uploadGithubAttachment` uploads images/videos through
GitHub's undocumented user-attachments endpoint with a user token (`github.upload_token`).

## Telegram [#telegram]

| Action id               | What it does                       |
| ----------------------- | ---------------------------------- |
| `telegram.send_message` | send text to configured chat       |
| `telegram.validate`     | validate bot token and chat config |

## Todoist [#todoist]

| Action family | Action ids                                                                                                                          |
| ------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| Tasks         | `todoist.list_tasks`, `todoist.create_task`, `todoist.close_task`, `todoist.get_task`, `todoist.update_task`, `todoist.delete_task` |
| Projects      | `todoist.list_projects`, `todoist.create_project`, `todoist.get_project`, `todoist.update_project`, `todoist.delete_project`        |
| Comments      | `todoist.list_comments`                                                                                                             |
| Labels        | `todoist.list_labels`                                                                                                               |

## Host-only file transfers [#host-only-file-transfers]

See [Transfer connector files](../connectors/files) for all download/export and create/update APIs,
provider-specific concurrency and limits, consent and network enforcement. Raw bytes do not enter
action arrays. The metadata actions `fortnox.list_supplier_invoice_files` and
`todoist.list_comments` declare read access; Fortnox offer previews and inbox files move through
host-only helpers.

## Custom connectors [#custom-connectors]

Use `defineConnector`, `defineAction`, `CredentialSlot`, and `makeIntegration` from `@yolk-sdk/connectors` to build app-specific connectors. Then expose them to agents with `makeConnectorToolModule`.


---

# Extract file text

URL: /docs/integrations/file-extraction

Turn PDF, DOCX, XLSX, PPTX, and text files into bounded, sanitized text, and feed it to knowledge ingestion.



`@yolk-sdk/extractors` turns file bytes your app already has into sanitized text with metadata.
It gives you one Effect service, `FileExtractor`, a Node implementation that parses PDF, DOCX,
XLSX, and PPTX in worker threads with size and time limits, and an adapter that plugs it into
[knowledge ingestion](../knowledge/ingestion-pipeline). Uploads, auth, storage, and what you do
with the text stay in your app.

## Install [#install]

```bash
pnpm add @yolk-sdk/extractors@canary effect@4.2.0
```

With knowledge ingestion:

```bash
pnpm add @yolk-sdk/extractors@canary @yolk-sdk/knowledge@canary effect@4.2.0
```

Only if you extract `.xlsx` files, add SheetJS from its CDN (not the npm `xlsx` package):

```bash
pnpm add https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz
```

Requires Node.js 22 or later. `@yolk-sdk/extractors/node` is server-only.

SheetJS (`xlsx >=0.20.3`) is an optional peer, loaded only when an XLSX file is extracted. The
npm `xlsx` package stops at 0.18.5, which has CVE-2023-30533 and CVE-2024-22363; fixed releases
are published only on `cdn.sheetjs.com`. Because the peer is optional, it never arrives
transitively: each host adds it directly. pnpm records the tarball URL and integrity hash in the
lockfile. Other formats never load SheetJS.

## Subpaths [#subpaths]

| Subpath                                       | Runtime          | Use for                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| --------------------------------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `@yolk-sdk/extractors`                        | runtime-portable | the `FileExtractor` service tag and `FileExtractorApi` type; types `FileInput`, `ExtractedFile`, `ExtractedFileMetadata`, `ExtractedFileFormat`, `OfficeFileFormat`, `FileExtractorError`; `fileFormatFor`, `extractedFileFormats`, `isOfficeFileFormat`; `defaultFileExtractorLimits` and the `FileExtractorLimits` schema; `sanitizeExtractedText`; errors and `FileExtractionFailureReason`; `minimumSheetJsVersion`, `sheetJsInstallCommand` |
| `@yolk-sdk/extractors/node`                   | Node, server     | `FileExtractorLayer`, `makeFileExtractorLayer(options)`, `defaultWorkerIsolation`, `normalizeOfficeArchive`; types `FileExtractorOptions`, `FileExtractorIsolation`, `WorkerIsolationOptions`, `OfficeArchiveLimits`, `SheetJsLoader`; also re-exports `FileExtractor` and `FileExtractorApi`                                                                                                                                                    |
| `@yolk-sdk/extractors/knowledge`              | runtime-portable | `FileKnowledgeExtractorLayer` and `makeFileKnowledgeExtractor`: a `@yolk-sdk/knowledge/extraction` `KnowledgeExtractor` backed by the `FileExtractor` in context                                                                                                                                                                                                                                                                                 |
| `@yolk-sdk/extractors/node/extraction-worker` | Node worker      | the worker entry the Node layer starts; do not import it directly (see [Next.js](#nextjs))                                                                                                                                                                                                                                                                                                                                                       |

The root and `./knowledge` import no parsers and no Node built-ins, so code that only needs the
contract (for example a service that receives a `FileExtractor` from context) can run anywhere.

## Extract a file [#extract-a-file]

Create `extract.mts` (the `.mts` extension makes it an ES module, so top-level `await` works in
any project):

```ts title="extract.mts"
import { readFile } from 'node:fs/promises'
import { basename } from 'node:path'
import { Effect } from 'effect'
import { FileExtractor } from '@yolk-sdk/extractors'
import { FileExtractorLayer } from '@yolk-sdk/extractors/node'

const path = process.argv[2] ?? 'notes.txt'

const program = Effect.gen(function* () {
  const extractor = yield* FileExtractor
  const bytes = new Uint8Array(yield* Effect.promise(() => readFile(path)))

  return yield* extractor.extract({ filename: basename(path), mediaType: '', bytes })
}).pipe(Effect.provide(FileExtractorLayer))

const extracted = await Effect.runPromise(program)

console.log(extracted.metadata)
console.log(extracted.content)
```

Create a text file and run the script:

```bash
printf 'Quarterly   notes\r\n\r\n\r\n\r\nRevenue grew.\r\n' > notes.txt
pnpm dlx tsx extract.mts notes.txt
```

You should see the metadata and the sanitized text (line endings normalized, repeated spaces and
blank lines collapsed):

```txt
{ format: 'text', title: 'notes.txt' }
Quarterly notes

Revenue grew.
```

Pass a `.pdf`, `.docx`, `.pptx`, or `.xlsx` path to parse it in a worker thread. A workbook with
one sheet named `Q1` prints `{ format: 'xlsx', title: 'report.xlsx', sheetNames: [ 'Q1' ] }`
followed by a `# Q1` section of CSV rows.

In a server, `bytes` comes from your upload or storage layer. `mediaType` can be the upload's
media type or `''`. The extractor copies the input before a parser reads it, so your buffer is
never detached.

## Formats and output [#formats-and-output]

The format comes from the filename extension (`txt`, `md`, `markdown`, `csv`, `json`, `pdf`,
`docx`, `xlsx`, `pptx`), then the media type, then any `text/*` media type as plain text.
`fileFormatFor` exposes the same rule. Anything else fails with `UnsupportedFileFormatError`.

| Format                            | Where it is read      | Text                                                                             | Metadata                                 |
| --------------------------------- | --------------------- | -------------------------------------------------------------------------------- | ---------------------------------------- |
| `text`, `markdown`, `csv`, `json` | calling thread        | UTF-8 decoded                                                                    | `title` = filename                       |
| `pdf`                             | worker thread (unpdf) | text of all pages                                                                | PDF `Title` if set, `pageCount`          |
| `docx`                            | worker thread         | raw text (mammoth)                                                               | `title` = filename                       |
| `xlsx`                            | worker thread         | one `# <sheet>` section per worksheet with CSV rows; external links `text <url>` | workbook title or filename, `sheetNames` |
| `pptx`                            | worker thread         | slide text by slide part number, then speaker notes                              | `title` = filename                       |

With the default isolation, only PDF, DOCX, XLSX, and PPTX are parsed in worker threads. Text
formats are only decoded and sanitized in the calling thread; no parser reads them. Chart sheets
appear in `sheetNames` but get no text section.

All text goes through `sanitizeExtractedText`: line endings are normalized, control characters
dropped, and runs of spaces, dots, and blank lines collapsed. An empty result fails with
`FileExtractionError`. XLSX cells show their cached values; formulas are never evaluated, so a
formula cell without a cached value is empty. See the
[package README](https://github.com/magoz/yolk-sdk/tree/main/packages/extractors#readme) for the
full XLSX and Office archive rules.

## Limits [#limits]

`makeFileExtractorLayer({ limits })` overrides any of `defaultFileExtractorLimits` (fragment):
`FileExtractorLayer` uses the defaults. Invalid values are a defect when the layer is built, not a
typed failure.

```ts
import { makeFileExtractorLayer } from '@yolk-sdk/extractors/node'

const FileExtractorLive = makeFileExtractorLayer({
  limits: { maxInputBytes: 10 * 1024 * 1024, maxXlsxCellVisits: 50_000 }
})
```

| Limit                   | Default | Bounds                                                                     |
| ----------------------- | ------- | -------------------------------------------------------------------------- |
| `maxInputBytes`         | 50 MiB  | input size, every format                                                   |
| `maxArchiveEntries`     | 10,000  | ZIP entries in DOCX, XLSX, PPTX                                            |
| `maxExpandedBytes`      | 50 MiB  | inflated bytes of an Office archive, counted while inflating               |
| `maxXlsxSheets`         | 100     | worksheets                                                                 |
| `maxXlsxCellVisits`     | 100,000 | cells inside every sheet's declared range, absent cells included           |
| `maxXlsxTextCharacters` | 512 Ki  | XLSX text, annotations and the omission marker included; at least 62       |
| `maxXlsxHyperlinks`     | 10,000  | hyperlinks read per workbook; extra links are dropped from the text output |

Exceeding a limit fails the extraction with `FileExtractionError`. Hyperlinks that do not fit the
text budget or the hyperlink cap are the exception: the cell is written plain and the text ends
with one `[Some hyperlinks omitted: …]` marker.

## Worker isolation [#worker-isolation]

Each PDF, DOCX, XLSX, and PPTX extraction runs in a fresh Node `worker_threads` worker. Only the
extracted text and metadata come back. Pass an `isolation` object to change the defaults
(`defaultWorkerIsolation`) (fragment):

```ts
import { makeFileExtractorLayer } from '@yolk-sdk/extractors/node'

const FileExtractorLive = makeFileExtractorLayer({
  isolation: { maxOldGenerationSizeMb: 512, timeoutMs: 60_000, maxConcurrentWorkers: 2 }
})
```

| `isolation` option         | Default                  | Bounds                                                           |
| -------------------------- | ------------------------ | ---------------------------------------------------------------- |
| `maxOldGenerationSizeMb`   | 256                      | V8 old-generation heap of each worker                            |
| `maxYoungGenerationSizeMb` | 32                       | V8 young-generation heap of each worker                          |
| `stackSizeMb`              | 4                        | stack of each worker                                             |
| `timeoutMs`                | 30,000                   | wall-clock time per worker (a real timer, at most 2³¹−1 ms)      |
| `maxConcurrentWorkers`     | 4                        | this layer's share of the pool of 4 workers per JavaScript realm |
| `maxQueueWaitMs`           | the layer's `timeoutMs`  | wait for a worker slot (at most 2³¹−1 ms), then fail with `busy` |
| `workerUrl`                | the package's own worker | the worker entry, for hosts that bundle or relocate the package  |

* **One pool per realm.** Every layer in a JavaScript realm (the main thread, or each worker
  thread that builds the layer) shares one pool of 4 workers, however often the layer is built.
  `maxConcurrentWorkers` (1 to 4) can only lower a layer's share. Slots are handed out first come,
  first served.
* **What the worker bounds.** V8 heap, stack, and running time. A worker that runs out of heap,
  times out, cannot start, or exits without a result is terminated and the extraction fails with
  a `reason`. There is no fallback to parsing in-process.
* **What it does not bound.** Process memory (RSS) and memory outside the V8 heap, such as
  Buffers, inflated archive parts, and PDF.js decoded data. Those are limited only by the input
  and expanded-size limits. Your platform's memory limit is the outer bound: four workers at the
  default heap add up to about 1 GB of V8 heap, so size the host for that plus your own load, or
  lower the limits.

`isolation: 'none'` parses in the calling thread, for runtimes without worker threads. It is
unsafe for untrusted input: a crafted file can exhaust the process heap or block the event loop.
It is also the only mode that accepts a `loadSheetJs` or `loadMammoth` function (for example
mammoth's browser build); passing one with worker isolation is a defect when the layer is built.

## Errors and failure reasons [#errors-and-failure-reasons]

`extract` fails with one of three tagged errors (the `FileExtractorError` union):

| Error                        | When                                                                                   | Fields                                                          |
| ---------------------------- | -------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
| `UnsupportedFileFormatError` | neither the extension nor the media type maps to a supported format                    | `filename`, `mediaType`                                         |
| `FileExtractionError`        | the file is unreadable, invalid, over a limit, or empty, or the worker stopped         | `message` (safe to show users), `format`, `reason`, `cause`     |
| `SheetJsUnavailableError`    | an XLSX file arrived but SheetJS is missing, not a SheetJS build, or older than 0.20.3 | `reason` (`missing`, `invalid`, `outdated`), `installedVersion` |

`SheetJsUnavailableError` is host misconfiguration, not a bad upload. Its message includes
`sheetJsInstallCommand`. Office archive failures (`OfficeArchiveError`) reach you as
`FileExtractionError` with the archive error as `cause`; `OfficeArchiveError` itself is only
returned by `normalizeOfficeArchive`.

`FileExtractionError.reason` (`FileExtractionFailureReason`) is set only when a worker was stopped
or never admitted:

| `reason`             | Meaning                                                 | Typical host response                                                    |
| -------------------- | ------------------------------------------------------- | ------------------------------------------------------------------------ |
| `resource-limit`     | the worker ran out of its V8 heap                       | reject the file, or raise `maxOldGenerationSizeMb` if your memory allows |
| `timeout`            | the worker exceeded `timeoutMs` and was terminated      | reject the file, or retry; it may time out again with the same limits    |
| `worker-unavailable` | the worker could not start (missing or unloadable file) | fix deployment: see [Next.js](#nextjs) and `workerUrl`                   |
| `worker-failed`      | the worker crashed, exited, or sent a malformed message | log and reject the file                                                  |
| `busy`               | no worker slot freed up within `maxQueueWaitMs`         | retry later; no worker was started                                       |

No `reason` means the extraction itself failed, usually because the file is unreadable, invalid,
too large, or empty.

Fragment, mapping errors to host responses inside the program above:

```ts
import { Effect } from 'effect'

const handled = program.pipe(
  Effect.catchTags({
    UnsupportedFileFormatError: error => Effect.fail(`Unsupported file: ${error.filename}`),
    FileExtractionError: error =>
      Effect.fail(error.reason === 'busy' ? 'Try again shortly' : error.message),
    SheetJsUnavailableError: error => Effect.die(error) // host misconfiguration
  })
)
```

## Feed knowledge ingestion [#feed-knowledge-ingestion]

`FileKnowledgeExtractorLayer` provides `KnowledgeExtractor` from the `FileExtractor` in context.
Give it the Node layer and include the result in the layers you provide to
`ingestKnowledgeDocument` (fragment):

```ts
import { Layer } from 'effect'
import { FileKnowledgeExtractorLayer } from '@yolk-sdk/extractors/knowledge'
import { FileExtractorLayer } from '@yolk-sdk/extractors/node'

const KnowledgeExtractorLive = FileKnowledgeExtractorLayer.pipe(Layer.provide(FileExtractorLayer))
```

* String `content` passes through unchanged; blank text fails.
* Bytes are extracted with the format chosen from the source name (`File` name or ref, `Url`
  path, `Text` label) and media type (`LoadedKnowledgeSource.mediaType`, then the `File` source's,
  then `text/plain` for `Text` sources).
* The extracted title becomes the document title. `format`, `pageCount`, and `sheetNames` merge
  under the source's own metadata, so your keys win.
* Failures become `KnowledgeExtractionError` with the original error as `cause`.

Use `makeFileKnowledgeExtractor(extractor)` when you already hold a `FileExtractorApi` value. See
[Ingest knowledge](../knowledge/ingestion-pipeline) for the rest of the pipeline.

## Next.js [#nextjs]

The Node layer starts its worker from the package's `dist/node/extraction-worker.mjs`, a
self-contained file whose only other import is the optional `xlsx` peer. Keep both packages
unbundled in server code:

```ts title="next.config.ts"
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  serverExternalPackages: ['@yolk-sdk/extractors', 'xlsx']
}

export default nextConfig
```

With the package external, Next.js 16 (Turbopack) output file tracing includes the worker; this
was checked with an `output: 'standalone'` build. If a bundler moves the
Node module into a chunk of another name, there is no default worker: extraction fails closed with
`reason: 'worker-unavailable'` and starts nothing. Then copy
`@yolk-sdk/extractors/node/extraction-worker` somewhere with `xlsx` resolvable beside it and pass
its URL as `isolation.workerUrl`. If your tracer misses `dist/node/extraction-worker.mjs`, add it
(and `xlsx`) with `outputFileTracingIncludes`.

## Host responsibilities [#host-responsibilities]

* Upload size, auth, and per-user quota policy; storage of the original files.
* Limits that fit your runtime's memory and the model context you feed the text to. The worker
  limits bound V8 heap and time, not the process.
* Installing SheetJS from the CDN when XLSX extraction is needed.
* Deciding what happens to the text: knowledge ingestion, attachments, or other use.
* Deployment config that keeps the worker file on disk (see [Next.js](#nextjs)).

## Boundaries [#boundaries]

* The package is domain-free: no upload, auth, storage, or product concepts.
* `@yolk-sdk/extractors/knowledge` is the only bridge to `@yolk-sdk/knowledge`; the knowledge
  package never imports extractors.

## Next [#next]

* [Ingest knowledge](../knowledge/ingestion-pipeline)
* [Add knowledge search](./knowledge-search)
* [Packages](../reference/packages)


---

# Move files between tools

URL: /docs/integrations/files

Capture file bytes from tool results once and let the agent move them by fileId to upload URLs, download links, and the sandbox.



Agents often need to take a file from one tool and give it to another: an email attachment to an
upload URL, a sandbox report to an email, an MCP export to cloud storage. Yolk does this with a
claim check ([ADR 0009](https://github.com/magoz/yolk-sdk/blob/main/docs/adr/0009-file-claim-check.md)):
tool resolution stores the bytes once, the model and code mode scripts only see a short `fileId`,
and file tools turn the `fileId` back into bytes or a link where it is needed. Bytes never pass
through the model, scripts, the tool ledger, or the transcript.

## Install [#install]

```bash
pnpm add @yolk-sdk/files@canary @yolk-sdk/agent@canary effect@4.2.0
```

Available from `0.1.0-canary.114`. The package is runtime-neutral (Web Crypto, no Node builtins).

## How it works [#how-it-works]

1. A typed tool returns bytes in a file field of its output: declare `output` with a `ToolFile`
   field and return `new FileBytes({ bytes, name, mimeType })` (both from
   `@yolk-sdk/agent/protocol`; `view: true` also shows the model an image or document). Tools
   without `output` may return a `FilePart` (`filePartFromBytes`) in their content. Connector
   actions with `fileOutput` (`gmail.get_attachment`, `outlook.get_attachment`,
   `email.get_attachment`, `fortnox.get_sie_file`) and MCP blobs, images and audio already do.
2. `resolveTools(modules, context, { files: { store } })` stores the bytes before the ledger sees
   the result. The value holds a `FileRef { fileId, name, mimeType, size }` where the bytes were,
   the model sees a label such as `[file file_…: Faktura_225.pdf, application/pdf, 89 KB]`, and
   `ToolResult.files` lists the descriptors.
3. The agent passes the `fileId` to a tool that needs the file.

### Files the host already stored [#files-the-host-already-stored]

A tool that wrote the file to the store itself (for example a connector download streamed straight
to object storage, so the host never holds the whole file) returns
`new FileStored({ fileId, name, mimeType, size })` in the `ToolFile` field instead of the bytes; a
`FileDescriptor` from its own write constructs it directly. Capture never stores or reads it: it
checks the file with `store.head(fileId)` and answers the same `FileRef`, label and
`ToolResult.files` entry as `FileBytes` with the same content would get. A file the store's scope
does not hold (never written, a malformed id, or a `fileId` of another scope) answers
`FileUnavailable` `not found`, one stored with another size `size mismatch`, never a reference to a
missing file. Write the object where the store's `head` finds it: with `makeObjectStorageFileStore`,
the key `<prefix>/<scope>/<fileId>` (`prefix` defaults to `files`; `fileId` from `fileIdFor` with
the content's sha256) and the URI-encoded `name` and the hex `sha256` in its metadata, as `put`
writes them. The `fileId` depends on the sha256 of the whole content, so a streaming host writes to
a temporary key while hashing, then copies the object to its final key. A `FileStored` cannot be
viewed by the model; return `FileBytes` with `view: true` for that.

Without `files`, over `maxFileBytes` (default 100 MiB, also for a `FileStored`), or when storing
fails, a file field becomes `FileUnavailable { unavailable: reason, name, mimeType }` and the model
sees a `[file not captured (reason): …]` label: base64 never falls through to the model. Inline
images, documents and audio the model views keep their source and also get a stored copy and a
label.

## Store [#store]

Fragment; your app supplies `r2ObjectStorage`, `workspaceId` and `sessionId`:

```ts
import { makeObjectStorageFileStore } from '@yolk-sdk/files'

const store = makeObjectStorageFileStore({
  storage: r2ObjectStorage, // your ObjectStorageApi: put, head, get, signGet, deletePrefix
  scope: `${workspaceId}/${sessionId}` // host-derived, never from the model
})
```

Keys are `files/<scope>/<fileId>`, with the name and sha256 in object metadata: no database. The
`fileId` is derived from the scope and the content hash, so replays and duplicates write nothing,
and a `fileId` from another scope never resolves. `deleteScopeFiles({ storage, scope })` removes a
scope's files, for example with its session. Scope segments are `/`-separated and use only
`A-Z a-z 0-9 . _ -` (no `.` or `..` segments); the store throws for an invalid scope, so check
untrusted values with `isValidFileScope`.

## Tools [#tools]

Fragment; your app supplies `modules`, `context`, the transport and the sandbox:

```ts
import { Effect } from 'effect'
import { resolveTools } from '@yolk-sdk/agent/tools'
import { makeFileToolModule } from '@yolk-sdk/files'

const toolSet = Effect.gen(function* () {
  return yield* resolveTools(
    [...modules, makeFileToolModule({ store, transport: guardedUploadTransport, sandbox })],
    context,
    { files: { store } }
  )
})
```

| Tool                | Input                          | Does                                                                         |
| ------------------- | ------------------------------ | ---------------------------------------------------------------------------- |
| `file_upload`       | `{ fileId, url, headers? }`    | `PUT`s the file to an https URL, for example a presigned upload URL          |
| `file_url`          | `{ fileId, ttlMinutes? }`      | Signs a temporary download link (default one hour, at most seven days)       |
| `file_save`         | `{ name, content, mimeType? }` | Saves text (JSON, CSV, Markdown, plain text) as a file                       |
| `file_to_sandbox`   | `{ fileId, path? }`            | Copies the file into the sandbox workspace (default `files/<fileId>/<name>`) |
| `file_from_sandbox` | `{ path, name?, mimeType? }`   | Turns a workspace file into a `fileId`                                       |

All five are `write` tools without approval. `file_save` stores text the model or a script
produced as UTF-8 (MIME type from the name's extension, else `text/plain`; content over
`maxTransferBytes` is `invalid_input`); the same content returns the same `fileId`. `file_upload`
exists only with a `FileUploadTransportApi`, and the sandbox tools only with a sandbox that has `writeFile`/`readFile`
(the `@yolk-sdk/sandbox` Vercel layer has them). `file_upload` results and errors name the
destination host, never the URL. A network failure during an upload is an unknown outcome: the
agent is told to check the destination before retrying.

`makeFileToolModule` also takes `maxTransferBytes` (default 50 MiB: `file_upload` and the sandbox
tools read the whole file into memory, so a captured file larger than this cannot be transferred,
and `file_save` stores at most this many bytes), `defaultUrlTtlSeconds` (default one hour, clamped to one minute to seven days) and `isEnabled`.

`file_upload` streams instead when your store has the optional `FileStoreApi.stream` and your
transport the optional `putStream`: the file goes out as the store reads it (`content-length` its
size), never held in memory, so `maxTransferBytes` does not bound it. A read that breaks midway fails
the call as cut short, told apart from the transport's unknown outcome. `makeObjectStorageFileStore`
has `stream` when your `ObjectStorageApi` has the optional `getStream` (the object's bytes as a
scoped stream, for example the body of an R2 or S3 `GET`, cancelled when the scope closes); each
stream is held to the stored size.

A script on the Dynamic Worker executor sends a long `file_save` content (64 Ki characters or more)
as a stream beside the call, never as one JSON string your Worker holds (`streamedArgument`, ADR
0022\): the call's arguments, its ledger entry and its `nestedCalls` record hold a placeholder.
`file_save` stores it through your store's optional `FileStoreApi.putStream` (the same `fileId`
`put` answers for the same bytes) when it has one, a chunk held at a time and no bound but your
store's: implementing `putStream` opts that path out of `maxTransferBytes`, so your store (and the
script's own memory and CPU limit) bound it. Otherwise it reads the content whole within
`maxTransferBytes`. A content cut short (the
script hit its CPU limit) saves nothing.

## From a code mode script [#from-a-code-mode-script]

Scripts read file fields as `FileRef` (or `FileUnavailable`), never labels, so one script moves a
Gmail attachment to an MCP server's presigned upload URL (script fragment; the IDs come from earlier
calls; `get_attachment` and MCP tools resolve to `{ value, files }`):

```js
const attachment = await tools['gmail.get_attachment']({ messageId, attachmentId, filename })
const file = attachment.files[0]
if ('unavailable' in file) return `not stored: ${file.unavailable}`
const upload = await tools.mcp_afloat_create_receipt_upload({
  contentLength: file.size,
  contentType: file.mimeType
})
await tools.file_upload({
  fileId: file.fileId,
  url: upload.value.url,
  headers: upload.value.headers
})
```

A script that computed data saves it as a file for a tool that takes `fileIds`, instead of the
model copying the data into the next call (`file_save` resolves to `{ fileId, name, mimeType, size }`):

```js
const saved = await tools.file_save({ name: 'totals.json', content: JSON.stringify(totals) })
return saved.fileId
```

## Your app owns [#your-app-owns]

* the `ObjectStorageApi` over private storage and the scope (give a subagent a store bound to the
  same scope to share files);
* which surfaces get `files` and the file module (for example not automatic continuations);
* a guarded `FileUploadTransportApi`: public addresses only (checked on the resolved IP), TLS
  verified, no redirects, no cookies or ambient credentials, no logging of the URL. An unguarded
  transport allows SSRF;
* claiming and ledgering the `write` tools, retention, and download UI.

Connector sinks such as Gmail draft attachments do not take `fileId`s yet; attach files through
your own tools until they do.


---

# Available integrations

URL: /docs/integrations

What Yolk ships today: model providers, connector modules, MCP, knowledge, sandbox, and workflow adapters.



Yolk integrations are package-owned adapters you can plug into your host-owned auth, storage, policy, and UI.

## Model providers [#model-providers]

| Provider                           | Use when                                                                  | Import                                                   |
| ---------------------------------- | ------------------------------------------------------------------------- | -------------------------------------------------------- |
| OpenAI-compatible chat completions | You have an API key and want a generic OpenAI-compatible chat endpoint    | `@yolk-sdk/agent/providers/openai/provider`              |
| Vercel AI Gateway                  | You want Vercel routing across opaque `provider/model` ids                | `@yolk-sdk/agent/providers/vercel/ai-gateway-provider`   |
| Vercel AI Gateway classifier       | You want typed [classifier model](../agent/classifier-models) answers     | `@yolk-sdk/agent/providers/vercel/ai-gateway-classifier` |
| OpenCode Go                        | You use a Go API key with Chat Completions, Messages, or Responses models | `@yolk-sdk/agent/providers/opencode/go-provider`         |
| OpenAI Codex                       | You use Codex OAuth, Responses, or subscription-allowance snapshots       | `@yolk-sdk/agent/providers/openai/codex-provider`        |
| Anthropic Claude Code              | You use Claude OAuth, model requests, or subscription-allowance snapshots | `@yolk-sdk/agent/providers/anthropic/claude-provider`    |
| xAI Grok subscription              | You use Grok model requests or subscription-allowance snapshots           | `@yolk-sdk/agent/providers/xai/grok-provider`            |
| Test provider                      | You need deterministic tests without network calls                        | `@yolk-sdk/agent/loop/testing`                           |

See [Model providers](./model-providers).

## Connector modules [#connector-modules]

| Connector        | Capabilities                                                                                                        | Import                                 |
| ---------------- | ------------------------------------------------------------------------------------------------------------------- | -------------------------------------- |
| Afloat           | remote MCP auth data                                                                                                | `@yolk-sdk/connectors/afloat`          |
| Dropbox          | file metadata, search, file management, and host-only file download                                                 | `@yolk-sdk/connectors/dropbox`         |
| Generic email    | IMAP reads/drafts/message state/labels, POP3 reads, and SMTP submission                                             | `@yolk-sdk/connectors/email`           |
| Figma            | remote MCP auth data                                                                                                | `@yolk-sdk/connectors/figma`           |
| Fortnox          | company, customers, invoices, suppliers, articles, prices, cost centers, payments, offers, inbox, settings, profile | `@yolk-sdk/connectors/fortnox`         |
| GitHub           | one repo's issues, pull requests, reviews, merge, repository context                                                | `@yolk-sdk/connectors/github`          |
| Google           | Gmail, Calendar, and Drive                                                                                          | `@yolk-sdk/connectors/google`          |
| Kie              | GPT Image 2 and Wan 2.7 generation tasks, task status                                                               | `@yolk-sdk/connectors/kie`             |
| LinkedIn search  | Exa people search, Enrich Layer profile/email lookup                                                                | `@yolk-sdk/connectors/linkedin-search` |
| Microsoft        | Outlook mail and OneDrive files through Microsoft Graph                                                             | `@yolk-sdk/connectors/microsoft`       |
| Notion           | search, pages, blocks, databases, data sources, users, comments                                                     | `@yolk-sdk/connectors/notion`          |
| Cloudflare R2    | presigned upload URL                                                                                                | `@yolk-sdk/connectors/r2-storage`      |
| Telegram         | send message, validate bot/chat                                                                                     | `@yolk-sdk/connectors/telegram`        |
| Todoist          | projects, tasks, labels                                                                                             | `@yolk-sdk/connectors/todoist`         |
| Custom connector | any Effect-native action set                                                                                        | `@yolk-sdk/connectors`                 |

See [Connectors catalog](./connectors), [Transfer connector files](../connectors/files), and [Add connector tools](./connector-tool).
Host-only byte helpers cover downloads/exports and explicit Dropbox/OneDrive/R2 create/update;
file bytes remain outside generic action serialization.

## Runtime/platform integrations [#runtimeplatform-integrations]

| Integration                                | What ships                                                                                                                                                        | Import                                                                                |
| ------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
| MCP full-core client                       | MCP `2026-07-28` tools, resources, prompts, completions, MRTR, subscriptions, caching, OAuth helpers, and legacy negotiation                                      | `@yolk-sdk/mcp/client`                                                                |
| MCP local stdio                            | Node-only full-core stdio transport plus Yolk convenience helpers                                                                                                 | `@yolk-sdk/mcp/client/node`                                                           |
| MCP full-core server                       | Dual-era HTTP, resources, prompts, completions, MRTR, and subscriptions                                                                                           | `@yolk-sdk/mcp/server`                                                                |
| MCP stdio server                           | Node-only dual-era `serveStdio`                                                                                                                                   | `@yolk-sdk/mcp/server/node`                                                           |
| MCP Yolk tool server                       | Expose Yolk tools through a minimal dual-era MCP server                                                                                                           | `@yolk-sdk/mcp/server`                                                                |
| Knowledge search                           | document schemas, pinned context, ingestion/search contracts, lookup/manage tool helpers                                                                          | `@yolk-sdk/knowledge/*`                                                               |
| [File extraction](./file-extraction)       | bounded text extraction; PDF/DOCX/XLSX/PPTX parse in Node worker threads; a `KnowledgeExtractor` adapter                                                          | `@yolk-sdk/extractors`, `@yolk-sdk/extractors/node`, `@yolk-sdk/extractors/knowledge` |
| [Files](./files)                           | file claim check: object-storage file store; move captured files (`fileId`) to upload URLs, links and the sandbox                                                 | `@yolk-sdk/files`                                                                     |
| [Subscription pools](./subscription-pools) | several accounts of one provider as one `LLMProvider`: expiring-first routing and failover on spent quota                                                         | `@yolk-sdk/pool`, `@yolk-sdk/pool/store`                                              |
| Sandbox execution                          | core sandbox service, one destructive agent tool                                                                                                                  | `@yolk-sdk/sandbox`, `@yolk-sdk/sandbox/agent`                                        |
| Vercel Sandbox                             | concrete sandbox provider layer                                                                                                                                   | `@yolk-sdk/sandbox/vercel`                                                            |
| Code mode                                  | model-written scripts that call your resolved tools in a confined QuickJS sandbox, stage approval-gated writes for one review, plus a classifier tool for scripts | `@yolk-sdk/codemode`, `@yolk-sdk/codemode/node`, `@yolk-sdk/codemode/cloudflare`      |
| Vercel Workflows                           | durable workflow loop contract                                                                                                                                    | `@yolk-sdk/vercel-workflows`                                                          |
| Harness                                    | run lifecycle: claims, inbox, drains, and optional recovery. Introduced after `0.1.0-canary.76`.                                                                  | `@yolk-sdk/harness`                                                                   |

See [Add code mode](./code-mode) to let one script replace many tool-call turns.

## Not included [#not-included]

Yolk does not ship database adapters, auth routes, token storage, vector database providers, product permissions, or UI components. Those stay host-owned so the SDK remains reusable.


---

# Add knowledge search

URL: /docs/integrations/knowledge-search

Ingest documents, search them, and expose results as an agent tool.



Use this when agents need access to app documents, notes, files, or durable memory.

## Ingest documents [#ingest-documents]

Fragment; supply `loadedSource` and `HostKnowledgeLayer` from your app:

```ts
import { Effect } from 'effect'
import { KnowledgeDocumentId, KnowledgeScopeId } from '@yolk-sdk/knowledge/documents'
import { ingestKnowledgeDocument } from '@yolk-sdk/knowledge/ingestion'

await Effect.runPromise(
  ingestKnowledgeDocument({
    scopeId: KnowledgeScopeId.make('workspace-docs'),
    documentId: KnowledgeDocumentId.make('doc_123'),
    source: loadedSource
  }).pipe(Effect.provide(HostKnowledgeLayer))
)
```

These are trusted example constants. Decode external/persisted IDs with
`Schema.decodeUnknownEffect` before passing them to branded contracts; see
[Knowledge identities](../knowledge#search-documents). Your app still checks permissions.

Your app provides extraction, chunking, embedding, summarization, and store layers.
For file bytes, `@yolk-sdk/extractors/knowledge` can provide the extraction layer; see
[Ingestion pipeline](../knowledge/ingestion-pipeline).
The pipeline updates `SearchIndexStore`, not `KnowledgeStore`, and is not a cross-operation
transaction; your adapter owns atomic chunk replacement and rollback policy.

## Search [#search]

```ts
import { Effect } from 'effect'
import { searchKnowledge } from '@yolk-sdk/knowledge/search'

const results = await Effect.runPromise(
  searchKnowledge({
    scope,
    query: 'How does HITL work?',
    mode: 'hybrid',
    limit: 5,
    contextChunks: 1
  }).pipe(Effect.provide(HostKnowledgeLayer))
)
```

Filter the store to host-approved `ready` documents with active availability. The search helper
does not apply status or availability policy itself.

## Expose as tool [#expose-as-tool]

```ts
import { Effect } from 'effect'
import { makeKnowledgeLookupTool } from '@yolk-sdk/knowledge/agent'

const tool = makeKnowledgeLookupTool(HostKnowledgeLookupHandlers)
```

Resolve the tool with `@yolk-sdk/agent/tools` and pass it to the loop.


---

# Add MCP tools

URL: /docs/integrations/mcp-tools

List MCP server tools and feed them into a Yolk agent loop.



Use this when your app lets users configure remote or local MCP servers.

## List tools [#list-tools]

```ts
import { Effect } from 'effect'
import { FetchHttpClient } from 'effect/http'
import type { McpRemoteServerConfig } from '@yolk-sdk/mcp/client'
import { listRemoteMcpServerTools } from '@yolk-sdk/mcp/client'

const server = {
  name: 'docs',
  type: 'remote',
  url: 'https://example.com/mcp'
} satisfies McpRemoteServerConfig

const mcpTools = await Effect.runPromise(
  listRemoteMcpServerTools(server).pipe(Effect.provide(FetchHttpClient.layer))
)

const toolDefs = mcpTools.map(tool => tool.def)
const toolByName = new Map(mcpTools.map(tool => [tool.def.name, tool]))
```

Pass `toolDefs` into `run` or `runRuntime`, or register them as tools (below).

## Register them as tools [#register-them-as-tools]

Each listed tool declares `ToolDef.outputSchema` `{ value, files }`
([ADR 0013](https://github.com/magoz/yolk-sdk/blob/main/docs/adr/0013-typed-tool-results.md)), so
its registration sets `decodeOutput: mcpToolOutputDecoder`: `resolveTools` checks every result
with it (and fails with `output_validation_required` without it).

```ts
import { ToolError } from '@yolk-sdk/agent/loop'
import type { ToolModule, ToolRegistration } from '@yolk-sdk/agent/tools'
import {
  callRemoteMcpServerTool,
  mcpToolOutputDecoder,
  type McpResolvedTool
} from '@yolk-sdk/mcp/client'

type HostContext = { readonly userId: string } // your app's context

const registration = (resolved: McpResolvedTool): ToolRegistration<HostContext> => ({
  def: resolved.def,
  access: 'read', // host policy, for example from `resolved.annotations`
  decodeOutput: mcpToolOutputDecoder,
  execute: ({ call }) =>
    callRemoteMcpServerTool({
      config: server,
      mcpToolName: resolved.mcpToolName,
      toolCallId: call.id,
      params: call.params
    }).pipe(
      Effect.provide(FetchHttpClient.layer),
      Effect.mapError(
        error => new ToolError({ tool: call.name, message: error.message, cause: 'execution' })
      )
    )
})

const mcpModule: ToolModule<HostContext> = { id: 'mcp-docs', tools: mcpTools.map(registration) }
```

## What a call returns [#what-a-call-returns]

A successful call's `structuredContent` is `{ value, files }`, and code mode scripts resolve to it:

* `value` is the server's `structuredContent` (checked against the listed `outputSchema`), else
  the text of its text blocks and embedded text resources (`resource` with `text`), in order,
  parsed once when it is one JSON object or array, else the text, `null` without text.
  `resource_link` blocks never enter it.
* `files` are its blobs, images and audio as `FileRef` (or `FileUnavailable` when no store is
  configured, the file is too large, or storing failed).

The model sees the server's content: a result without blobs, images or audio exactly as before;
otherwise images and audio stay viewable media exactly as the server sent them (their inline data
reaches providers that accept media), each followed by its file label once stored, and blob
resources become file labels, so a blob's base64 never reaches the model
([Move files between tools](./files)).

Files are stored when the call runs. Inside a registration, `resolveTools` stores them through its
`files` option. A call made anywhere else (your own `ToolExecutor`, a route resuming
`resumeRemoteMcpServerToolCall`, a direct `callLocalMcpServerTool`) passes
`fileCapture: makeToolFileCapture({ store })` from `@yolk-sdk/agent/tools`; without it every file
is `FileUnavailable` (`no file store`) and the blob is lost (MCP blobs cannot be fetched again).

Local stdio calls list the tools first in the same session and check `structuredContent` against
the listed `outputSchema` before trusting it; a listing that fails or lacks the tool runs the call
without that check.

## Finish calls that ask for input [#finish-calls-that-ask-for-input]

A server can pause a `tools/call` with a form (MCP form elicitation over `2026-07-28` multi
round-trip requests, see [Confirm tool calls with form elicitation](../mcp#confirm-tool-calls-with-form-elicitation)).
In an agent session the registration stores the pause and returns an input-required result; a
person answers the form through the input review interaction, which resumes the remote call once
([Finish calls that paused for input](../agent/tools-hitl#finish-calls-that-paused-for-input)).

Fragment continuing the registration above: `pauseStore` (session-scoped pause storage with an
atomic claim) is host-owned.

```ts
import * as Schema from 'effect/Schema'
import { InteractionValidationError, makeInputRequiredToolResult } from '@yolk-sdk/agent/protocol'
import {
  inputReviewToolName,
  makeInputReviewTool,
  type InputPause,
  type InputReviewHost
} from '@yolk-sdk/agent/tools'
import {
  callRemoteMcpServerToolResumable,
  McpElicitationResponses,
  toMcpInputResponses,
  type McpInputRequired
} from '@yolk-sdk/mcp/client'

// One stored pause per paused call: the remote pause and the call it resumes.
type McpPause = InputPause & {
  readonly inputRequired: McpInputRequired
  readonly toolCallId: string
  readonly params: unknown
}

const registration = (resolved: McpResolvedTool): ToolRegistration<HostContext> => ({
  def: resolved.def,
  access: 'write', // host policy
  decodeOutput: mcpToolOutputDecoder,
  execute: ({ call }) =>
    callRemoteMcpServerToolResumable({
      config: server,
      mcpToolName: resolved.mcpToolName,
      toolCallId: call.id,
      params: call.params,
      options: { elicitation: { form: true } }
    }).pipe(
      Effect.flatMap(outcome =>
        outcome._tag === 'Complete'
          ? Effect.succeed(outcome.result)
          : pauseStore.save({ call, inputRequired: outcome.inputRequired }).pipe(
              Effect.map(pauseId =>
                makeInputRequiredToolResult({
                  toolCallId: call.id,
                  content: `${server.name} asks for input before ${call.name} can finish.`,
                  reviewToolName: inputReviewToolName,
                  pauseIds: [pauseId]
                })
              )
            )
      ),
      Effect.provide(FetchHttpClient.layer),
      Effect.mapError(
        error => new ToolError({ tool: call.name, message: error.message, cause: 'execution' })
      )
    )
})

const decodeAnswer = Schema.decodeUnknownEffect(McpElicitationResponses)

const mcpPauses: InputReviewHost<McpPause> = {
  load: pauseIds => pauseStore.loadWaiting(pauseIds), // in this session, still waiting, in order
  // One answer per pause: its responses keyed by form `key`, checked against the forms.
  validateAnswer: ({ pause, answer }) =>
    decodeAnswer(answer).pipe(
      Effect.flatMap(responses =>
        toMcpInputResponses({ server: server.name, inputRequired: pause.inputRequired, responses })
      ),
      Effect.asVoid,
      Effect.mapError(error => new InteractionValidationError({ message: error.message }))
    ),
  // Claim, then resumeRemoteMcpServerToolCall, then record (below).
  resume: input => pauseStore.resumeOnce(input),
  recorded: input => pauseStore.recorded(input)
}

const reviewInput = makeInputReviewTool<HostContext, McpPause>({ host: mcpPauses })
```

`resume` claims the pause for `submissionId` before sending, then calls
`resumeRemoteMcpServerToolCall({ config, mcpToolName, toolCallId, params, options, inputRequired, responses })`
with the stored call and the person's responses, records the resolution, and returns it:

* `Complete` becomes `InputPauseResolution.Completed({ result })`.
* `InputRequired` (the server asked again): store the new pause and return
  `InputPauseResolution.InputRequired({ pauseIds: [newPauseId] })`.
* A failure checked before sending (`McpInputRequiredError` `invalid_responses` or
  `mismatched_resume`), or a refusal before sending (the target changed, or the pause was already
  answered), is `NotSent({ message })`.
* Any other failure after the claim is `Unknown({ message })`: the call may have run. Never send a
  claimed pause again; `recorded` reports what was recorded after a crash.

The review action provides the resolution's file capture (`resolveTools` `files`), so a resume run
in `resume`'s Effect stores its blobs like a registration's; a resume run elsewhere passes
`fileCapture`.

## Host responsibilities [#host-responsibilities]

Persist server config, credentials, auth headers, and allow/deny policy in your app. Keep local stdio behind Node-only hosts via `@yolk-sdk/mcp/client/node`.


---

# Model providers

URL: /docs/integrations/model-providers

Available LLM provider adapters and OAuth helper surfaces.



Provider adapters implement `LLMProvider` for the agent loop. They translate Yolk messages/tools into vendor requests and normalize text, reasoning, tool calls, usage, retries, and provider errors back into Yolk events.

For copy-paste provider layer setup, see [Use model providers](./provider-setup).

## Available providers [#available-providers]

| Provider               | Factory                            | Auth               | Notes                                                                                                               |
| ---------------------- | ---------------------------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------- |
| OpenAI-compatible chat | `makeOpenAiProviderLayer`          | API key            | Chat Completions-style endpoint; `OpenAiProviderLayer` can read its API key and output limit through Effect Config. |
| Vercel AI Gateway      | `makeVercelAiGatewayProviderLayer` | API key or OIDC    | OpenAI-compatible Gateway endpoint with provider routing and model fallbacks.                                       |
| OpenCode Go            | `makeOpenCodeGoProviderLayer`      | API key            | Host-selected Chat Completions, Messages, or Responses protocol.                                                    |
| OpenAI Codex           | `makeOpenAiCodexProviderLayer`     | `OAuthAccessToken` | Responses API adapter with reasoning summaries and OAuth broker helpers.                                            |
| Anthropic Claude Code  | `makeAnthropicClaudeProviderLayer` | `OAuthAccessToken` | Claude Code-compatible adapter with Claude OAuth broker helpers.                                                    |
| xAI Grok subscription  | `makeXAiGrokProviderLayer`         | `OAuthAccessToken` | Responses adapter for Grok consumer subscriptions through the xAI CLI proxy.                                        |
| Faux provider          | `FauxProvider.layer(...)`          | none               | Test-only deterministic provider from `@yolk-sdk/agent/loop/testing`.                                               |

Provider output-token limits are host-owned when supported. OpenAI-compatible chat, Vercel AI
Gateway, OpenCode Go, Anthropic, and Grok require limits; ChatGPT Codex does not expose one. Yolk does not
maintain a model-limit catalog or apply hidden fallbacks.

## OpenAI-compatible chat [#openai-compatible-chat]

```ts
import { Layer, Redacted } from 'effect'
import { FetchHttpClient } from 'effect/http'
import { makeOpenAiProviderLayer } from '@yolk-sdk/agent/providers/openai/provider'

const ProviderLayer = makeOpenAiProviderLayer({
  apiKey: Redacted.make(hostOpenAiApiKey),
  maxCompletionTokens: hostModelConfig.maxOutputTokens
}).pipe(Layer.provide(FetchHttpClient.layer))
```

Use `chatCompletionsUrl` for generic OpenAI-compatible endpoints. Prefer the dedicated adapter below
for correct Vercel Gateway error attribution and routing options. The native endpoint receives
`reasoningEffort` as `reasoning_effort`; a compatible endpoint needs `reasoningEffortFormat`, or a
request with an effort fails with a `validation_error`.

## Vercel AI Gateway [#vercel-ai-gateway]

This is a server-side configuration fragment. The host supplies credentials and model policy:

```ts
import { Layer, Redacted } from 'effect'
import { FetchHttpClient } from 'effect/http'
import { makeVercelAiGatewayProviderLayer } from '@yolk-sdk/agent/providers/vercel/ai-gateway-provider'

const ProviderLayer = makeVercelAiGatewayProviderLayer({
  apiKey: Redacted.make(hostGatewayApiKeyOrOidcToken),
  maxCompletionTokens: hostModelConfig.maxOutputTokens,
  fallbackModels: hostFallbackModelIds,
  routing: { order: ['vertex', 'anthropic'] },
  extraHeaders: {
    'http-referer': hostPublicAppUrl,
    'x-title': hostAppName
  }
}).pipe(Layer.provide(FetchHttpClient.layer))
```

The adapter uses `https://ai-gateway.vercel.sh/v1/chat/completions` and defaults to a single JSON
completion. Set factory option `streaming: true` for SSE deltas. Independently set
`reasoningContent: true` to preserve compatible models' `reasoning_content` output (and the normalized `reasoning` thinking field some gateways emit, with `reasoning_content` taking precedence) and assistant
replay; streamed reasoning then surfaces as reasoning events, and replay spends input tokens.
Both options default to false. It lowers `maxCompletionTokens` to Gateway `max_tokens`. A run-level
`reasoningEffort` becomes `{ reasoning: { effort } }` by default; `reasoningEffortFormat: 'reasoning-effort'` sends the literal field instead (e.g. for DeepSeek-style hosts, with an optional `thinking: { type: 'enabled' | 'disabled' }` toggle merged into the request body), and `'omit'` never sends the effort and never fails. The host must
offer only effort values supported by its selected model. Pass model ids such as `provider/model`;
query Vercel's model catalog instead of hard-coding an SDK model union. `VercelAiGatewayProviderLayer` tries
`AI_GATEWAY_API_KEY`, then `VERCEL_OIDC_TOKEN`, and also reads integer
`AI_GATEWAY_MAX_COMPLETION_TOKENS`. Required auth and JSON headers override `extraHeaders`. Override
`chatCompletionsUrl` only with a trusted proxy because it receives the Bearer credential. Gateway
`finish_reason` values `length` and `content_filter` fail as non-retryable `invalid_response` rather
than reporting partial or filtered output as complete.

Gateway enables native PDF user-message parts by default; set `supportsPdfAttachments: false` to
disable them. URL-backed PDFs are fetched and buffered by the host-provided `HttpClient` before the
Gateway request, so hosts must authorize destinations, bound the download, control redirects and
credentials, and sanitize logs. See [Bound PDF attachment fetches](./provider-setup#bound-pdf-attachment-fetches).

## OpenCode Go [#opencode-go]

Use `makeOpenCodeGoProviderLayer` from `@yolk-sdk/agent/providers/opencode/go-provider` with a
redacted API key, explicit `protocol`, and host-owned `maxOutputTokens`. See
[Go configuration](./provider-setup#opencode-go).

| Protocol           | Endpoint suffix     | Authentication | Transport                                       |
| ------------------ | ------------------- | -------------- | ----------------------------------------------- |
| `chat-completions` | `/chat/completions` | Bearer API key | SSE (`streaming: true`), normalized into events |
| `messages`         | `/messages`         | `x-api-key`    | SSE or JSON response                            |
| `responses`        | `/responses`        | Bearer API key | SSE or JSON response                            |

All endpoints default to `https://opencode.ai/inference/go/v1`. Choose the protocol advertised for the
selected model in [OpenCode's Go catalog](https://opencode.ai/docs/go/#endpoints); model availability
can change. Pass the API model ID without the `opencode-go/` CLI prefix. Yolk neither fetches the
catalog nor infers protocols or limits from model names.

Messages uses native system instructions and tool names, not Claude Code OAuth fingerprints.
Responses supports a host output limit and does not send Codex account or originator headers.
Go pins each `x-opencode-session` to one upstream server, so a retry under the same session reaches
the server that just failed. When a response is malformed (a Chat Completions parser code such as
`invalid_stream_json`, a chat response that is not SSE, or a chat or Responses stream missing its
terminal event) before any event was emitted, the adapter sends the request once more under
`<session>.reroute`, giving up that request's cached prefix; model decisions such as `length` are
never retried. Go requires `x-opencode-session` on every request (Chat Completions refuse one
without it with 400 `MissingSessionID`), and caches prompts per session. The session is the request
`cacheKey`, else the `x-opencode-session` extra header; a request with neither gets a fresh id of
its own, so it is accepted but shares no cache with other requests. Pass `cacheKey` to cache a
conversation. For a stuck upstream server, wrap the Go provider with `withFirstEventDeadline` (from
`@yolk-sdk/agent/loop`; suggested `timeoutMs` `defaultFirstEventTimeoutMs`, 90 s), under your
fallback route if you have one, or set `LoopConfig.firstEventTimeoutMs`: a stream with no output
within it is sent again once under the same session, as Go asks for a stable one per conversation,
and a second stall fails non-retryable (`responseIssue: 'first_event_timeout'`), for the fallback
model. Errors read `OpenCode Go <cause>`, plus `: returned <status>` for a failed HTTP response, in
Yolk's words only, beside `provider.kind`, `provider.status` and `provider.providerCode`. A Messages
or Responses stream cut before its terminal event that is not re-routed (output had begun, or the
re-routed request was cut too) fails as non-retryable `invalid_response` with
`responseIssue: 'missing_done'`, the loop's incomplete stream (Responses keep
`providerCode: 'incomplete_stream'`).

Go reports safe failures under provider ID `opencode_go`. Credentials, model capabilities, supported
reasoning efforts, allowance polling/persistence, and UI remain host-owned. Read allowance with
`fetchOpenCodeGoSubscriptionUsage` from `@yolk-sdk/agent/providers/opencode/usage`.

## OpenAI Codex [#openai-codex]

```ts
import { Layer } from 'effect'
import { FetchHttpClient } from 'effect/http'
import { makeOpenAiCodexProviderLayer } from '@yolk-sdk/agent/providers/openai/codex-provider'

const ProviderLayer = makeOpenAiCodexProviderLayer({
  token: hostOAuthAccessToken,
  defaultReasoningEffort: 'medium',
  reasoningSummary: 'auto'
}).pipe(Layer.provide(FetchHttpClient.layer))
```

The ChatGPT subscription endpoint rejects vendor `max_output_tokens`, so the adapter does not expose
an output-token limit. The optional deprecated `maxOutputTokens` field is ignored for compatibility.

Codex completes a final response (streamed `response.completed` or a JSON body) whose `output` is
missing or misses a required key, decided from the decode issue (a missing key under `output`),
never from the error message. It reads `output` item by item: valid items still count, so a function
call the stream never emitted still runs, and the stop reason is `tool_use` when any call was
emitted, otherwise `stop`; items that do not decode are dropped. A function call that does not decode
must replay one the stream already emitted (same `call_id` or item `id`), and a message that does not
decode and carries text must be one whose text already streamed: otherwise the response fails as a non-retryable
`invalid_response`, since ending the turn would lose that call or answer. The response's `usage` is
reported when it decodes; a streamed `Done` is marked `usageUnavailable` only when it is missing or
does not decode. Unrelated invalid responses still fail. A stream cut before `response.completed` also completes (EOF
compatibility), so Codex never reports `missing_done`; this is not generic kernel `missing_done`
recovery and does not replay tools.

OAuth helpers live in `@yolk-sdk/agent/providers/openai` and the exact `@yolk-sdk/agent/providers/openai/codex` subpath:

* `makeOpenAiCodexBrokerRequest`
* `makeOpenAiCodexTokenBrokerClient`
* `toOpenAiCodexOAuthAccessToken`
* `openAiCodexProviderId`
* OpenAI Codex OAuth URLs/constants
* `fetchOpenAiCodexSubscriptionUsage` from `@yolk-sdk/agent/providers/openai/codex-usage`

## xAI Grok subscription [#xai-grok-subscription]

Configuration fragment (the host supplies the token, model policy, and HTTP layer):

```ts
import { Layer } from 'effect'
import { FetchHttpClient } from 'effect/http'
import { makeXAiGrokProviderLayer } from '@yolk-sdk/agent/providers/xai/grok-provider'

const ProviderLayer = makeXAiGrokProviderLayer({
  token: hostOAuthAccessToken,
  maxOutputTokens: hostModelConfig.maxOutputTokens,
  clientVersion: hostGrokCliClientVersion
}).pipe(Layer.provide(FetchHttpClient.layer))
```

`clientVersion` is required and sent as `x-grok-client-version`: the CLI proxy version-gates
requests and rejects missing or outdated client versions with HTTP 426. The host owns the value and
should keep it current with the minimum Grok CLI version the proxy accepts.

Grok requires `response.completed`: a stream that ends without it emits no `Done` and fails as
non-retryable `invalid_response` with `providerCode: 'incomplete_stream'` and
`responseIssue: 'missing_done'`, the loop's incomplete stream (earlier releases left
`responseIssue` unset), so harness hosts continue or recover the turn instead of failing the run.

This adapter sends consumer OAuth credentials only to the xAI CLI proxy by default. It does not use
`XAI_API_KEY` or `https://api.x.ai/v1`. OAuth helpers live in
`@yolk-sdk/agent/providers/xai` and `@yolk-sdk/agent/providers/xai/grok`:

* `makeXAiGrokAuthorizationUrl`
* `makeXAiGrokBrokerRequest`
* `makeXAiGrokTokenBrokerClient`
* `parseXAiGrokAuthorizationCode`
* `toXAiGrokOAuthAccessToken`
* `xAiGrokProviderId`
* Grok browser-PKCE/device-flow URLs and constants
* `fetchXAiGrokSubscriptionUsage` from `@yolk-sdk/agent/providers/xai/usage`

The public xAI CLI client uses a fixed loopback callback. The package exports browser-PKCE and
device-flow constants only; your host must implement the callback listener or complete device-code
request/polling, state/nonce and PKCE verification, token exchange, refresh serialization, secure
storage, token freshness/provider checks, and model discovery. Only override `responsesUrl` with a
trusted proxy because it receives the OAuth bearer. xAI controls the public CLI OAuth client and the
private, unsupported proxy contract; both may change and should be used only when permitted by xAI's
terms.

## Anthropic Claude Code [#anthropic-claude-code]

```ts
import { Layer } from 'effect'
import { FetchHttpClient } from 'effect/http'
import { makeAnthropicClaudeProviderLayer } from '@yolk-sdk/agent/providers/anthropic/claude-provider'

const ProviderLayer = makeAnthropicClaudeProviderLayer({
  token: hostOAuthAccessToken,
  maxTokens: hostModelConfig.maxOutputTokens
}).pipe(Layer.provide(FetchHttpClient.layer))
```

Like native Messages, Claude requires `message_stop`: a stream that ends without it, even after a
`message_delta` with a stop reason, emits no `Done` and fails as non-retryable `invalid_response`
with `responseIssue: 'missing_done'` (earlier releases completed it as a normal answer).

OAuth helpers live in `@yolk-sdk/agent/providers/anthropic` and the exact `@yolk-sdk/agent/providers/anthropic/claude` subpath:

* `makeAnthropicClaudeAuthorizationUrl`
* `makeAnthropicClaudeBrokerRequest`
* `makeAnthropicClaudeTokenBrokerClient`
* `parseAnthropicClaudeAuthorizationCode`
* `toAnthropicClaudeOAuthAccessToken`
* `anthropicClaudeProviderId`
* Claude OAuth URLs/constants
* `fetchAnthropicClaudeSubscriptionUsage` from `@yolk-sdk/agent/providers/anthropic/usage`

### Thinking [#thinking]

Claude Opus 5 and later think by default but return thinking blocks without text unless asked.
`thinking: { display: 'summarized' }` requests adaptive thinking summaries, streamed as reasoning
deltas. Optional `prefixMismatchBehavior` (`'drop_block'` or `'error'`, sent with the
`thinking-binding-controls-2026-08-01` beta) decides what Anthropic does with replayed thinking whose
earlier system prompt, tools or messages changed. Without `thinking`, no `thinking` field is sent.

Either way the provider keeps each thinking block's signature, or a redacted block's data, on
`AssistantReasoningPart.replay` and sends the turn back exactly as produced on later requests, so
tool-use turns keep their reasoning. Never edit, truncate or reorder a reasoning part that has
`replay` (Anthropic rejects modified thinking); hosts that rewrite history per request can skip parts
whose `replay.provider` is `anthropicClaudeReasoningReplayProvider`. Reasoning from another provider
is never sent to Claude, and native Messages transports neither capture nor replay signatures.

## Prompt caching [#prompt-caching]

Agent turns resend the whole conversation, so every adapter asks its provider to reuse the repeated
prefix. It is always on:

| Provider           | What the adapter sends                                                                 |
| ------------------ | -------------------------------------------------------------------------------------- |
| Anthropic          | `cache_control` on the last tool, the conversation end, and the previous request's end |
| OpenAI Codex, Grok | `prompt_cache_key` plus the session header (`session-id`, `x-grok-conv-id`)            |
| Vercel AI Gateway  | `providerOptions.gateway.caching: 'auto'` and `x-session-affinity`                     |
| OpenCode Go        | `x-opencode-session`, required (see above); Messages also gets the Anthropic markers   |

Pass a stable conversation identity such as the session id as `cacheKey` on `run`, `runRuntime`, or
`LLMRequest`; it travels in HTTP headers, so keep it printable ASCII. The generic OpenAI-compatible
chat provider sends nothing unless its config sets `cacheKeyHeaders`. Claude caches entries for five
minutes; set `promptCacheTtl: '1h'` on `makeAnthropicClaudeProviderLayer` for sessions that idle
between turns.

A cache hit needs a byte-identical prefix. Keep the system prompt and tool list stable within a
conversation and never rewrite earlier messages per request: put per-request facts such as fresh
signed URLs or the current time in `LLMRequest.turnContext`. Adapters append it after the
conversation (Anthropic after every breakpoint; Gateway's automatic markers still read the prefix
before it). Loop hosts set it by decorating `LLMProvider`. `LLMRequest.toolChoice: 'none'` forbids
tool calls but keeps the tool definitions; on Anthropic a changed `tool_choice` invalidates the
cached messages. Read the outcome from `AgentInputUsage.cacheRead` and `cacheWrite`. See
`docs/adr/0008-prompt-caching.md` in the repository for the design.

## Read subscription allowance [#read-subscription-allowance]

Claude, Codex, Grok, and OpenCode Go subscription connections can expose current allowance percentages and
reset windows. Claude normalizes aggregate five-hour and seven-day windows plus model-scoped
weekly limits (`seven-day-<model>`, with `models` naming the model they limit); Codex normalizes primary
and secondary rate-limit windows; Grok normalizes its aggregate shared credit allowance. Additional
provider-specific buckets are ignored. The usage adapters use private provider endpoints, so treat
snapshots as best-effort and keep failures isolated from core agent execution. Each fetcher accepts
an optional `url` that replaces the default endpoint; point it only at a trusted proxy or a local
emulator, because the credential is sent there.

This server-side fragment reads Codex allowance using a fresh host-owned token:

```ts
import { Effect } from 'effect'
import { FetchHttpClient } from 'effect/http'
import { fetchOpenAiCodexSubscriptionUsage } from '@yolk-sdk/agent/providers/openai/codex-usage'

const snapshotEffect = fetchOpenAiCodexSubscriptionUsage(hostOAuthAccessToken, {
  requestTimeoutMs: 10_000
}).pipe(Effect.provide(FetchHttpClient.layer))
```

Use `fetchAnthropicClaudeSubscriptionUsage` for Claude. For Grok, call
`fetchXAiGrokSubscriptionUsage(token, { xAiUserId, clientVersion })`. `xAiUserId` must be the
authenticated xAI `user_id`; the adapter does not reinterpret generic `OAuthAccessToken.accountId`.
`clientVersion` must truthfully identify your host integration rather than impersonate an official
Grok release. The adapter reports its programmatic request as `headless`.

For Go, call `fetchOpenCodeGoSubscriptionUsage(Redacted.make(hostOpenCodeGoApiKey), options)` from
`@yolk-sdk/agent/providers/opencode/usage`. Unlike the OAuth adapters, it uses a Bearer API key at
`https://opencode.ai/inference/go/v1/usage`. The API key must belong to the subscription's user and workspace;
403 means the key is not entitled to Go usage. It returns `five-hour`, `seven-day`, and `monthly`
windows, preserving the provider's absolute reset times. Monthly resets are subscription-anniversary
based, not calendar-month boundaries. Missing/invalid percentages are omitted rather than filled
with zero. No browser cookies or console scraping are needed.

Claude and Go now set `windowDurationMinutes` on their fixed rolling windows (300 for `five-hour`,
10080 for `seven-day`), as Codex and Grok already did; Go's `monthly` window has none.

Shared snapshot and safe error schemas live in
`@yolk-sdk/agent/providers/subscription-usage`. Hosts own polling, credential refresh, labels,
persistence, stale-data policy, thresholds, notifications, and UI. These snapshots report
subscription allowance, not protocol `AgentUsage` token accounting.

When an account-wide subscription quota is spent, the provider fails the request as `rate_limit`
and may attach `ProviderErrorInfo.quotaResetsAtMs` (epoch milliseconds of the reset). Claude reads
it from its rate-limit headers, and Responses providers from a `usage_limit_reached` error (which
ChatGPT Codex sends). It is absent for transient rate limits, a Claude model-scoped limit alone, and
a reset that is missing, in the past, or more than a year ahead. To spread requests over several accounts of one provider and fail over
when one runs out, see [Share subscription accounts](./subscription-pools).

## Test provider [#test-provider]

```ts
import { FauxProvider, Reply } from '@yolk-sdk/agent/loop/testing'

const ProviderLayer = FauxProvider.layer(Reply.text('Hello from a deterministic test.'))
```

Use this in tests and examples only. It is not a runtime provider.

## Host responsibilities [#host-responsibilities]

* Store and refresh provider credentials.
* Choose models per user/session/run.
* Provide `HttpClient` and provider layers to the loop.
* Keep raw provider error bodies and secrets out of protocol events.
* Persist usage and typed provider failure metadata if your app needs it.


---

# Use model providers

URL: /docs/integrations/provider-setup

Wire OpenAI-compatible, Vercel AI Gateway, OpenCode Go, Codex, Claude, or Grok provider layers into an agent loop.



Provider layers implement `LLMProvider`. Your app chooses the provider, model id, credentials, HTTP layer, and policy.

Provider output-token limits are host-owned when the endpoint supports them. OpenAI-compatible chat,
Vercel AI Gateway, OpenCode Go, Anthropic, and Grok require limits; ChatGPT Codex does not expose one. Yolk does
not infer model limits or apply hidden fallbacks.

## Install [#install]

```bash
pnpm add @yolk-sdk/agent@canary effect@4.2.0
```

## OpenAI-compatible chat [#openai-compatible-chat]

Use this for OpenAI Chat Completions or compatible gateways.

```ts
import { Layer, Redacted } from 'effect'
import { FetchHttpClient } from 'effect/http'
import { makeOpenAiProviderLayer } from '@yolk-sdk/agent/providers/openai/provider'

const OpenAiLayer = makeOpenAiProviderLayer({
  apiKey: Redacted.make(hostOpenAiApiKey),
  maxCompletionTokens: hostModelConfig.maxOutputTokens
}).pipe(Layer.provide(FetchHttpClient.layer))
```

Use `chatCompletionsUrl` for generic OpenAI-compatible endpoints. Run-level `reasoningEffort` goes
to the native endpoint as `reasoning_effort`. A compatible endpoint needs `reasoningEffortFormat`
(`'reasoning-effort'` or `'reasoning-object'`); without it, a request with an effort fails with a
`validation_error` rather than being sent without it. `reasoningEffortFormat: 'omit'` never sends
the effort and never fails: use it for a model without reasoning (which rejects the field) when the
host shares one effort setting across models.

## Vercel AI Gateway [#vercel-ai-gateway]

Use this for Vercel's OpenAI-compatible Gateway endpoint and `provider/model` routing.

```ts
import { Layer, Redacted } from 'effect'
import { FetchHttpClient } from 'effect/http'
import { makeVercelAiGatewayProviderLayer } from '@yolk-sdk/agent/providers/vercel/ai-gateway-provider'

const GatewayLayer = makeVercelAiGatewayProviderLayer({
  apiKey: Redacted.make(hostGatewayApiKeyOrOidcToken),
  maxCompletionTokens: hostModelConfig.maxOutputTokens,
  fallbackModels: hostFallbackModelIds,
  routing: { only: hostAllowedGatewayProviders }
}).pipe(Layer.provide(FetchHttpClient.layer))
```

The factory defaults to one JSON completion. Add `streaming: true` for SSE deltas and, independently,
`reasoningContent: true` to retain compatible models' reasoning output and assistant replay. Both
options default to false; replayed reasoning spends input tokens. These are explicit factory options,
not env-backed switches.

The factory sends `maxCompletionTokens` as Gateway `max_tokens`. Run-level `reasoningEffort` is
forwarded as `{ reasoning: { effort } }` by default; `reasoningEffortFormat: 'reasoning-effort'` sends the literal field instead (e.g. for DeepSeek-style hosts, with an optional `thinking: { type: 'enabled' | 'disabled' }` toggle merged into the request body), and `'omit'` never sends the effort and never fails, for a model without reasoning behind a shared effort setting. The host must restrict its
choices to efforts supported by the selected model. The env-backed `VercelAiGatewayProviderLayer`
reads `AI_GATEWAY_API_KEY`, falls back to
`VERCEL_OIDC_TOKEN`, and requires `AI_GATEWAY_MAX_COMPLETION_TOKENS`. The factory also accepts
`extraHeaders` for optional `http-referer` and `x-title` attribution. Required authorization and JSON
headers cannot be overridden. A custom `chatCompletionsUrl` must be a trusted proxy because it
receives the Bearer credential.

## OpenCode Go [#opencode-go]

Server-side configuration fragment; the host supplies the API key and model policy:

```ts
import { Layer, Redacted } from 'effect'
import { FetchHttpClient } from 'effect/http'
import { makeOpenCodeGoProviderLayer } from '@yolk-sdk/agent/providers/opencode/go-provider'

const GoLayer = makeOpenCodeGoProviderLayer({
  apiKey: Redacted.make(hostOpenCodeGoApiKey),
  protocol: 'messages',
  maxOutputTokens: hostModelConfig.maxOutputTokens
}).pipe(Layer.provide(FetchHttpClient.layer))
```

Choose `chat-completions`, `messages`, or `responses` to match the selected Go model's
[advertised endpoint](https://opencode.ai/docs/go/#endpoints). Supply the unprefixed API model ID in
the loop request. The factory validates a nonempty key and positive safe-integer limit when the
layer builds. It does not read environment variables or perform OAuth. Hosts using environment
configuration should load the key with `Config.Redacted` inside `Effect.gen`.

`maxOutputTokens` becomes `max_tokens` for Chat Completions/Messages or `max_output_tokens` for
Responses. Request `reasoningEffort` becomes `reasoning_effort` for chat, `output_config.effort` for
Messages (omitting `minimal`, rejecting `none`), or Responses `reasoning.effort`. Responses also sends
`summary: 'auto'` when effort is present; configure `reasoningSummary` to select another summary mode.
Only offer efforts supported by your model. Chat emits and replays provider `reasoning_content` (and host-normalized `reasoning`).

Optional `extraHeaders` cannot replace required protocol headers, even with different casing.
Override `baseUrl` only with a trusted proxy: it receives the API key. Messages and Responses require
explicit stream completion; truncated responses do not count as success. Chat defaults to one JSON
response before emitting events; set `streaming: true` on `OpenAiProviderConfig` to request
incremental `chat.completion.chunk` SSE deltas with usage instead. Unterminated chat streams fail
`invalid_response` without `Done`. OpenCode Go chat always streams. Only enable streaming against
endpoints that serve chat SSE. This adapter adds no model picker, catalog fetching,
credential persistence, or automatic subscription-allowance polling.

Read allowance on your host's schedule (server-side fragment):

```ts
import { Effect, Redacted } from 'effect'
import { FetchHttpClient } from 'effect/http'
import { fetchOpenCodeGoSubscriptionUsage } from '@yolk-sdk/agent/providers/opencode/usage'

const usageEffect = fetchOpenCodeGoSubscriptionUsage(Redacted.make(hostOpenCodeGoApiKey), {
  requestTimeoutMs: 10_000
}).pipe(Effect.provide(FetchHttpClient.layer))
```

The best-effort snapshot has `five-hour`, `seven-day`, and `monthly` used-percentage windows when
available. The fetcher defaults to `openCodeGoSubscriptionUsageUrl` (override `url` only with a
trusted proxy or local emulator, since it receives the API key), rejects redirects, and returns shared
`ProviderSubscriptionUsageError` variants without raw HTTP bodies or credential-bearing traces.
Use provider reset timestamps and keep allowance failures separate from inference; do not derive
subscription usage from token totals.

## OpenAI Codex [#openai-codex]

Use this for Codex OAuth/token-broker flows and the Responses API.

```ts
import { Layer } from 'effect'
import { FetchHttpClient } from 'effect/http'
import { makeOpenAiCodexProviderLayer } from '@yolk-sdk/agent/providers/openai/codex-provider'

const CodexLayer = makeOpenAiCodexProviderLayer({
  token: hostOAuthAccessToken,
  defaultReasoningEffort: 'low',
  reasoningSummary: 'auto'
}).pipe(Layer.provide(FetchHttpClient.layer))
```

The ChatGPT subscription endpoint rejects vendor `max_output_tokens`, so the adapter does not expose
an output-token limit. The optional deprecated `maxOutputTokens` field is ignored for compatibility.

OAuth helpers live in `@yolk-sdk/agent/providers/openai` and `@yolk-sdk/agent/providers/openai/codex`.

## xAI Grok subscription [#xai-grok-subscription]

Use this for consumer Grok subscriptions through xAI's CLI Responses proxy.

Configuration fragment (the host supplies the token, model policy, and HTTP layer):

```ts
import { Layer } from 'effect'
import { FetchHttpClient } from 'effect/http'
import { makeXAiGrokProviderLayer } from '@yolk-sdk/agent/providers/xai/grok-provider'

const GrokLayer = makeXAiGrokProviderLayer({
  token: hostOAuthAccessToken,
  maxOutputTokens: hostModelConfig.maxOutputTokens,
  clientVersion: hostGrokCliClientVersion
}).pipe(Layer.provide(FetchHttpClient.layer))
```

The required `clientVersion` is sent as `x-grok-client-version`; the CLI proxy rejects missing or
outdated client versions with HTTP 426.

OAuth and broker helpers live in `@yolk-sdk/agent/providers/xai` and
`@yolk-sdk/agent/providers/xai/grok`. The package exports browser-PKCE and device-flow constants, not
a complete device polling service. The host must implement the chosen authorization flow, serialize
refreshes, persist replacement refresh tokens, verify token provider/freshness, and select an
available subscription model. The adapter defaults to the xAI CLI proxy rather than the developer
API-key endpoint. Treat a custom `responsesUrl` as a trusted credential-bearing proxy. xAI controls
the public CLI OAuth client and private, unsupported proxy contract; both may change and should be
used only when permitted by xAI's terms. Best-effort allowance snapshots are available from
`@yolk-sdk/agent/providers/xai/usage`; the fetcher requires the authenticated xAI `user_id` and your
host integration's truthful version as explicit options.

## Anthropic Claude Code [#anthropic-claude-code]

Use this for Claude OAuth/token-broker flows and Claude Code-compatible requests.

```ts
import { Layer } from 'effect'
import { FetchHttpClient } from 'effect/http'
import { makeAnthropicClaudeProviderLayer } from '@yolk-sdk/agent/providers/anthropic/claude-provider'

const ClaudeLayer = makeAnthropicClaudeProviderLayer({
  token: hostOAuthAccessToken,
  maxTokens: hostModelConfig.maxOutputTokens
}).pipe(Layer.provide(FetchHttpClient.layer))
```

OAuth helpers live in `@yolk-sdk/agent/providers/anthropic` and `@yolk-sdk/agent/providers/anthropic/claude`.

Add `thinking: { display: 'summarized' }` to stream thinking summaries from models that think by
default (Opus 5 and later). Signed thinking is replayed unchanged either way; see
[Thinking](./model-providers#thinking).

Anthropic prompt-too-long responses are non-retryable `context_overflow` failures. If your host owns
durable compaction, wrap the provider with `makeContextOverflowRetryProvider` to compact and retry
once. See [Implement durable compaction](../guides/durable-compaction).

Claude responses that stop at `max_tokens` fail as non-retryable `invalid_response`; they do not emit
normal completion. Increase `maxTokens`, request a shorter response, or adjust host output policy.

The transport identifies as a pinned Claude Code release (`anthropicClaudeCodeVersion`). Anthropic
rejects newer models for outdated versions; see
[claude\_code\_version\_too\_old](../troubleshooting#claude-rejects-a-model-with-claude_code_version_too_old).

## Provide the layer [#provide-the-layer]

Merge the provider with your loop/tool layers:

```ts
import { Layer } from 'effect'
import { ContextTransformer, LoopConfig } from '@yolk-sdk/agent/loop'
import { makeToolExecutorLayer } from '@yolk-sdk/agent/tools'

const AppAgentLayer = Layer.mergeAll(
  OpenAiLayer,
  makeToolExecutorLayer(toolSet),
  LoopConfig.defaultLayer,
  ContextTransformer.identity
)
```

Then provide `AppAgentLayer` to `run` or `runRuntime`.

## Capability notes [#capability-notes]

| Provider              | Media notes                                                                                                |
| --------------------- | ---------------------------------------------------------------------------------------------------------- |
| OpenAI-compatible     | text, image URLs/data URLs, inline text documents; PDF parts opt in with `supportsPdfAttachments`          |
| Vercel AI Gateway     | OpenAI-compatible text, tools, image URLs/data URLs, text documents, native PDF file parts by default      |
| OpenCode Go           | Protocol/model-dependent: chat images and text documents; Messages images/PDFs; Responses images/documents |
| OpenAI Codex          | text, reasoning, tools, image URLs/data URLs, document data/files                                          |
| Anthropic Claude Code | text, reasoning, tools, images, PDF URL/base64, inline text documents                                      |
| xAI Grok subscription | text, reasoning, tools; can encode model-dependent image URL/data input                                    |

### Bound PDF attachment fetches [#bound-pdf-attachment-fetches]

Generic OpenAI-compatible chat supports native PDF user-message and tool-result parts only when
`supportsPdfAttachments: true`; Vercel AI Gateway enables the same behavior by default and accepts
`supportsPdfAttachments: false` to disable it. Tool-result images and documents are lowered to
origin-labeled, untrusted supplementary user content after the complete tool-result block, without
changing canonical history. Assistant media remains unsupported on this Chat Completions path.

For a URL-backed PDF, Yolk uses the host-provided `HttpClient` to perform the GET and buffer the
response before sending base64 file data to the provider. Gateway does not fetch the source URL.
Authorize attachment URLs and enforce destination and redirect policy, streamed-byte limits,
timeouts, cancellation, and safe logging in that HTTP boundary. Do not let a shared client attach
provider credentials, cookies, or ambient auth to attachment destinations. The SDK's resolver does
not provide those guarantees; materialize authorized files as validated inline bytes when the host
cannot supply a bounded transport. Resolve `Ref` sources before the provider attempt and choose a
model whose advertised capabilities include PDFs. See
[Resolve private attachments](../guides/private-attachments) and
[Media input rejected](../troubleshooting#media-input-rejected).

Codex preserves text, image, and document tool results as native function output content. Claude
preserves text, images, inline text documents, and URL/base64 PDFs as nested tool-result content.
Resolve host-owned attachment refs before provider execution; rich tool results do not support
audio.

Set model capabilities in your request config so unsupported inputs fail before provider execution.

## Host responsibilities [#host-responsibilities]

* Store and refresh API keys/OAuth tokens.
* Choose provider/model per run.
* Provide `HttpClient` and provider layer at the server boundary.
* Keep raw provider errors and secrets out of protocol events.
* Persist typed usage and safe `ProviderErrorInfo` if your app needs accounting.


---

# Add sandbox execution

URL: /docs/integrations/sandbox

Let an agent run commands inside a scoped sandbox session.



Use sandbox execution for coding agents, file generation, test runs, and previews.

## Run a command [#run-a-command]

```ts
import { Effect, Layer } from 'effect'
import { Sandbox } from '@yolk-sdk/sandbox'
import { makeInMemorySandboxStateStoreLayer } from '@yolk-sdk/sandbox/testing'
import { makeVercelSandboxLayer } from '@yolk-sdk/sandbox/vercel'

const SandboxLayer = makeVercelSandboxLayer({
  sandboxSessionId: 'user-session-123',
  ports: [3000]
}).pipe(Layer.provide(makeInMemorySandboxStateStoreLayer()))

const result = await Effect.runPromise(
  Effect.gen(function* () {
    const sandbox = yield* Sandbox
    return yield* sandbox.run({ command: 'pnpm test' })
  }).pipe(Effect.provide(SandboxLayer))
)
```

On Cloudflare Workers, use `makeCloudflareSandboxLayer` from `@yolk-sdk/sandbox/cloudflare`
instead; see [Cloudflare Containers](../sandbox/cloudflare).

## Add the agent tool [#add-the-agent-tool]

```ts
import { Effect } from 'effect'
import { makeSandboxToolModule } from '@yolk-sdk/sandbox/agent'

const sandboxToolModule = await Effect.runPromise(
  makeSandboxToolModule({
    workspaceDescription: 'Temporary workspace for this run.',
    previewPorts: [3000]
  }).pipe(Effect.provide(SandboxLayer))
)
```

The sandbox tool is `destructive`. Add approvals and audit logs before enabling it for broad use.

The tool declares `SandboxToolOutput` as its output: `structuredContent` carries `exitCode`,
`durationMs`, `timedOut`, `truncated`, `workspaceReset`, optional `backgroundId`, the same bounded
`stdout` and `stderr` slices as the text, `previewUrls`, and `state`. A non-zero exit or timeout is
still an error result.

## Move files in and out [#move-files-in-and-out]

The Vercel and Cloudflare layers implement the optional `writeFile`/`readFile` on `Sandbox` for workspace-relative
paths. To let the agent copy files between tools and the workspace, pass the sandbox to
`makeFileToolModule` from `@yolk-sdk/files`; see [Move files between tools](./files).


---

# Share subscription accounts

URL: /docs/integrations/subscription-pools

Serve several accounts of one provider as one LLMProvider, spending the quota that resets soonest first and failing over when an account runs out.



A subscription account (for example a Claude Max or ChatGPT plan) has usage windows: a five-hour
limit, a weekly limit, sometimes per-model limits. With several accounts of one provider,
`@yolk-sdk/pool` serves them as one `LLMProvider`
([ADR 0011](https://github.com/magoz/yolk-sdk/blob/main/docs/adr/0011-subscription-pools.md)):

* each request goes to the account whose longest usage window (usually the weekly one) resets
  soonest and still has quota, so quota that would reset unused is spent first (expiring-first);
* without fresh usage readings, a route stays on the account that served it last (sticky
  fill-first);
* when an account runs out of quota or its credentials are rejected before any output, it cools
  down and the same request moves to the next account.

## Install [#install]

```bash
pnpm add @yolk-sdk/pool@canary @yolk-sdk/agent@canary effect@4.2.0
```

Available from `0.1.0-canary.116`. The package is runtime-neutral.

| Subpath                | Purpose                                                                                 |
| ---------------------- | --------------------------------------------------------------------------------------- |
| `@yolk-sdk/pool`       | `makePool`, the pure ranking (`rankPool`, `staleQuotaCooldowns`), Schemas, and errors   |
| `@yolk-sdk/pool/store` | `PoolStoreApi` port, `makeMemoryPoolStore`, and the `poolStoreContract` semantics cases |

## Build a pool [#build-a-pool]

This server-side fragment assumes `claudeWork` and `claudePersonal` are `LLMProvider` services you
built, one per account with its credentials, and `workToken` is that account's fresh OAuth token:

```ts
import { Effect, Layer } from 'effect'
import { LLMProvider } from '@yolk-sdk/agent/loop'
import { fetchAnthropicClaudeSubscriptionUsage } from '@yolk-sdk/agent/providers/anthropic/usage'
import { makePool } from '@yolk-sdk/pool'
import { makeMemoryPoolStore } from '@yolk-sdk/pool/store'

const program = Effect.gen(function* () {
  const pool = yield* makePool({
    id: 'claude',
    accounts: [
      // LLMProvider services you build, one per account and its credentials.
      { id: 'claude-work', priority: 1, provider: claudeWork },
      { id: 'claude-personal', provider: claudePersonal }
    ],
    // Serverless hosts implement PoolStoreApi on their database.
    store: makeMemoryPoolStore()
  })

  // The loop's provider: innermost, under your retry or attachment wrappers.
  const llm = Layer.succeed(LLMProvider, pool.provider)

  // On your own schedule (cron, background job), never per request.
  yield* pool.recordReading('claude-work', yield* fetchAnthropicClaudeSubscriptionUsage(workToken))

  // For a settings page: pins, active cooldowns, readings.
  const state = yield* pool.state
})
```

Accounts must be interchangeable for the requests the pool serves (same provider, same models).
The pool never sees tokens: each account's provider carries its own credentials.

| `makePool` option     | Meaning                                                               |
| --------------------- | --------------------------------------------------------------------- |
| `id`                  | pool id; pins are keyed by pool id and route                          |
| `accounts[].id`       | unique within the store; cooldowns and readings are keyed by it       |
| `accounts[].priority` | breaks ranking ties and orders fill-first, higher first (default 0)   |
| `accounts[].provider` | the account's `LLMProvider` service                                   |
| `store`               | a `PoolStoreApi` (`makeMemoryPoolStore` for one process)              |
| `maxAgeMs`            | how old a reading may be and still rank accounts (default 30 minutes) |
| `reservePercent`      | quota left untouched on every window, from 0 to below 100 (default 0) |

Readings come from the usage helpers in
[Read subscription allowance](./model-providers#read-subscription-allowance). A window with
`models` limits only those models, and a window without `windowDurationMinutes` (OpenCode Go's
month) can block a used-up account but never ranks. Readings older than `maxAgeMs` (default 30
minutes) are ignored.

## Failover and retries [#failover-and-retries]

| Failure before the first event                            | Pool                                                                                           |
| --------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
| `rate_limit` with `quotaResetsAtMs` (Claude, Codex quota) | Cooldown until the reset, next account                                                         |
| `rate_limit` with `retryAfterMs` of 30 minutes or more    | Cooldown for that long, next account                                                           |
| `auth`                                                    | 30-minute cooldown, next account                                                               |
| anything else, or any failure after an event              | Unchanged to the caller; the loop retries it only when it is retryable and nothing was emitted |
| every account out on quota                                | `rate_limit`, `retryable: false`, earliest quota reset                                         |
| every account out on rejected credentials only            | `auth` (`provider_error`), `retryable: false`                                                  |

The loop's own retry calls the pool again, which picks again; the pool never retries transient
errors itself, so attempts never multiply. A request without a model id fails `validation_error`.

## Store [#store]

`PoolStoreApi` holds pins (per pool and route), one cooldown per account, and the latest reading
per account. Implementations must be atomic per key (`movePin` is a compare-and-set).

`putCooldown` over an existing cooldown: one that ended before the other began gives way to it;
two that overlap merge into the later end and its kind (on a tie, the later start's; on a full tie,
quota), with the later `startedAtMs` of the two (the newest failure), so a reading taken before
that failure never clears it. A kept quota
cooldown records the end of an auth failure it absorbed as `authUntilMs`; readings do not clear it
before then (a reading cannot vouch for the rejected credential). `clearCooldown` removes only the
observed `PoolQuotaCooldown` (same `startedAtMs` and `authUntilMs`), never a `PoolAuthCooldown`.
Two requests failing on one account write concurrently, so merge in one atomic statement, not a
read followed by a write: for example an upsert that sets the greatest start, picks the end and
kind with a `CASE` on which ends later (then which started later, then quota), and sets
`authUntilMs` to the greatest auth end of the two (an auth cooldown's end, a quota cooldown's
`authUntilMs`) when the kept one is quota and that end is after the merged start, else null.

Run every case of `poolStoreContract` against a fresh store of your implementation in your tests.
Store failures never fail a request: the pool routes fill-first without state and logs a warning.

## What you own [#what-you-own]

* Credentials: one refresher per OAuth grant (refresh tokens rotate). Separate logins of the same
  account are separate grants.
* Readings: poll each account's usage with the subscription usage fetchers on a schedule and call
  `recordReading`.
* Which accounts form a pool, labels, alerts, and UI.


---

# Deploy with Vercel Workflows

URL: /docs/integrations/vercel-workflow

Orchestrate a durable agent run with host-owned model and tool steps.



Use `@yolk-sdk/vercel-workflows` when a run can outlive one request or pause for human input.

## Workflow wrapper [#workflow-wrapper]

```ts
import { createHook } from 'workflow'
import { runVercelAgentWorkflow } from '@yolk-sdk/vercel-workflows'

export async function runAgentWorkflow(input: { request: unknown; context: unknown }) {
  'use workflow'

  return await runVercelAgentWorkflow({
    input,
    runModelStep,
    runToolBatchStep,
    closeStream,
    writeError,
    awaitInput: async awaitingInput => {
      using hook = createHook<unknown>({ token: awaitingInput.hookToken })
      return await hook
    }
  })
}
```

`runModelStep`, `closeStream`, and `writeError` are app-owned `'use step'` functions.
`runToolBatchStep` may also be a step, or it may orchestrate separate tool steps and independent
child Workflow starts. Keep provider calls, tool IO, storage, and Effect work inside steps; do not
wrap a whole child loop in one parent step. See
[Independent child orchestration](../vercel-workflows/step-contracts#independent-child-orchestration).

## Code mode [#code-mode]

Run [code mode](./code-mode#vercel-workflow) calls inside your tool-batch step, never in the
`'use workflow'` function. Executor decorators applied outside `ResolvedToolSet.execute`, such as a
Workflow stop or run-admission check, do not see nested calls; pass the same check to
`makeCodeModeTool` as `beforeNestedCall`.

Calls applied from a [staged tool plan](../agent/tools-hitl#review-a-staged-plan) bypass both
those decorators and `beforeNestedCall`: pass the same check to `makePlanReviewTool` as
`beforeCall`. A step redelivered while a plan applies waits for the running apply when the review
step is resolved with the same tool ledger scope on every delivery; keep ledger entries as long as
the review receipts.

## Tool steps run at least once [#tool-steps-run-at-least-once]

Vercel's queue can deliver a tool-batch step again after a crash, or while the first execution is
still running, even with the default `noWorkflowStepRetry`. Supply a durable tool ledger, scoped
to the Workflow run, where your step resolves tools:

```ts
// Fragment from your tool-batch step module. `modules`, `context`, `makeRunToolLedger`,
// `workflowRunId`, and `stepDeadlineMs` are host-owned.
import { Effect } from 'effect'
import { resolveTools } from '@yolk-sdk/agent/tools'

// Inside the 'use step' function:
const toolSet = await Effect.runPromise(
  resolveTools(modules, context, {
    ledger: { store: makeRunToolLedger(workflowRunId), deadline: () => stepDeadlineMs }
  })
)
```

`makeRunToolLedger` is your `ToolLedgerStore` (for example Postgres); see
[Ledger writes](../agent/tools-hitl#ledger-writes-for-re-executed-steps). Ledgered calls (by
default every non-`read` tool plus the built-in `subagent` tool, code mode scripts included) then
return their stored result, wait for the running execution, or report that an abandoned call may
already have been applied; they never run twice under the same ledger key. Include custom
delegation tools with `isLedgered`. Read calls still re-run. The package itself never builds tool
sets, so there is nothing to configure on `runVercelAgentWorkflow`.

`deadline` bounds only waiting for a duplicate execution; it does not stop a call that runs.
Recording a call's outcome can take up to about 15 s after the call returns (three 5 s attempts),
so set `stepDeadlineMs` to leave that finalization time before the function budget ends. Keep
the store's operations interruptible (for example `Effect.tryPromise` passing the `AbortSignal` to
the driver): the ledger's timeouts cannot cut uninterruptible store work.

## Durable stream rule [#durable-stream-rule]

Use distinct finalization paths:

```txt
AgentEnd: durable completion commit -> AgentEnd -> closeStream
AgentError: failure commit/mapping -> AgentError -> writeError-owned close
AgentAwaitingInput: persist pending HITL -> emit pause -> release writer lock, do not close -> resume
```

Use `sequenceDurableAgentEvent` for deterministic event ids without IO,
`writeDurableAgentEvent` for id + NDJSON write, and `commitThenWriteTerminalEvent` for terminal
barriers. The helper never decides closure from an event tag. The loop closes only successful runs;
`writeError` must write the safe final error and close failure paths.


---

# Architecture

URL: /docs/reference/architecture

Package boundaries and dependency direction.



Yolk packages are reusable mechanics. Apps provide product policy.

```txt
host app / runtime / UI
  -> @yolk-sdk/agent
  -> @yolk-sdk/mcp
  -> @yolk-sdk/knowledge
  -> @yolk-sdk/connectors
  -> @yolk-sdk/sandbox
  -> @yolk-sdk/codemode
  -> @yolk-sdk/extractors
  -> @yolk-sdk/files
  -> @yolk-sdk/pool
  -> @yolk-sdk/vercel-workflows
  -> @yolk-sdk/harness

host tests / fixture scripts
  -> @yolk-sdk/conformance (experimental)
  -> @yolk-sdk/emulators (experimental)
```

Rules of thumb:

* packages expose contracts and helpers
* apps own auth, storage, prompts, providers, enabled tools, approvals, and UI
* use explicit subpaths
* keep provider/platform-specific code behind provider/platform subpaths

## Dependency direction [#dependency-direction]

* `agent/protocol` is the shared wire vocabulary.
* `agent/loop` is stateless and provider/tool-service driven.
* `agent/runtime` adds generic session orchestration, not app persistence.
* `mcp` adapts MCP tools/results to agent protocol, but the loop stays MCP-agnostic.
* `knowledge`, `connectors`, and `sandbox` expose optional agent adapters behind explicit subpaths.
* `codemode` builds on the agent tool contract (`callableBy`, nested tool access) and depends only on `agent` among Yolk packages; its root is runtime-neutral, the Node pi executor lives behind `codemode/node`, and the Dynamic Worker executor behind `codemode/cloudflare`. `agent` never imports it.
* `extractors` turns uploaded files into bounded text. Its root is runtime-portable (contract, errors, limits, and the `FileExtractor` tag), the Node parsers live behind `extractors/node`, and only `extractors/knowledge` imports `knowledge` (`extractors/knowledge -> knowledge`); `knowledge` never imports it. SheetJS is an optional peer installed from the SheetJS CDN.
* `files` builds on the agent tool contract (capture in `agent/tools` stores `FilePart` bytes through a host `FileStoreApi`) and depends only on `agent`; the sandbox is a structural port that `sandbox` satisfies, and storage and the upload transport are host ports. `agent` never imports it.
* `pool` wraps several `LLMProvider`s into one and depends only on `agent` (`agent/loop`, `agent/protocol`, `agent/providers/subscription-usage`); its store is a host port. `agent` never imports it.
* `vercel-workflows` stays generic over serializable `unknown` payloads and does not import agent protocol.
* `harness` owns run lifecycle (claims, inbox, drains). It is not the agent loop and does not add a Workflow driver.
* `conformance` (experimental) depends only on `effect`: it records, replays, and fault-injects HTTP wire fixtures for tests, defines port fixtures for non-HTTP host ports (such as `EmailClient`), defines conformance cases, and runs them behind a safety policy; it never performs network I/O itself. Provider fixture and case modules such as `agent/providers/vercel/conformance` import it; runtime code does not.
* `emulators` (experimental) depends on `effect` and never imports other Yolk packages: emulators follow the recorded fixture wire shapes and name the conformance cases behind each route. `router` swaps `HttpClient` layers to reach them; `email` and `r2` are plain-JSON fake `EmailClient` and `R2Presigner` / `R2ObjectClient` backends that connectors bridge structurally (connectors never import emulators); only the `node`, `fortnox`, `microsoft`, `dropbox`, `notion`, `todoist`, `telegram`, `github`, `google`, `linkedin-search`, and `mcp` subpaths use Node builtins, and only `fortnox`, `microsoft`, `dropbox`, `notion`, `todoist`, `telegram`, `github`, `google`, `linkedin-search`, and `mcp` use the upstream `@emulators/core` runtime (pinned exactly).

Strict boundaries let the packages fit many hosts: Next.js, Workers, Durable Objects, Workflows, CLIs, and tests.


---

# Host responsibilities

URL: /docs/reference/host-responsibilities

What your app must provide around Yolk SDK contracts.



| Area       | Host owns                                                                                  |
| ---------- | ------------------------------------------------------------------------------------------ |
| Identity   | users, workspaces, tenants, route ownership                                                |
| Storage    | transcripts, append logs, DB schema, object storage, tokens                                |
| Compaction | summary prompts, durable compaction payloads, model-context projection                     |
| Providers  | model choice, output-token limits, credentials, refresh, broker routes, error UX           |
| Tools      | enabled tools, approval policy, authorization, audit, durable tool-call ledger store/scope |
| Knowledge  | extraction (or wire `@yolk-sdk/extractors`), embeddings, search store, permissions, scopes |
| Connectors | credential storage/encryption/refresh/revoke, OAuth callbacks                              |
| Files      | file store and scope (`ObjectStorageApi`), guarded upload transport, retention, surfaces   |
| Pools      | accounts and their credentials, usage polling (`recordReading`), `PoolStoreApi` store, UI  |
| Sandbox    | session scope, env/secrets, cleanup, approval, diffs                                       |
| Harness    | drain work, Store/Inbox adapters, HITL payloads, claim snapshots, recovery policy          |
| UI         | chat rendering, uploads, HITL controls, retry/stop/error states                            |
| Deployment | Next routes, Worker/DO wiring, Workflow steps/hooks, cron cleanup                          |

Yolk does not model app users, billing, projects, product permissions, or persistence schema.

Use app-owned adapters around SDK contracts instead.


---

# Packages

URL: /docs/reference/packages

Package roles and explicit public subpaths.



| Package                      | Use for                                                                                                                |
| ---------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| `@yolk-sdk/agent`            | agent protocol, loop, runtime, client, React, tools, providers, OAuth, skillset, voice                                 |
| `@yolk-sdk/mcp`              | MCP v2 full-core client/server, protocol schemas, and Yolk tool adapters                                               |
| `@yolk-sdk/knowledge`        | knowledge documents, pinned context, search, ingestion, lookup/manage tools                                            |
| `@yolk-sdk/connectors`       | external API actions, credentials, connector-to-agent-tool adapter                                                     |
| `@yolk-sdk/sandbox`          | sandbox execution plane, Vercel and Cloudflare Containers adapters, agent sandbox tool                                 |
| `@yolk-sdk/codemode`         | code mode tool: scripts that call the resolved tools, classifier tool, Node pi and Cloudflare Dynamic Worker executors |
| `@yolk-sdk/extractors`       | bounded text extraction (PDF, DOCX, XLSX, PPTX, text) and a knowledge extractor adapter                                |
| `@yolk-sdk/files`            | file claim check: object-storage file store and tools that move captured files by `fileId`                             |
| `@yolk-sdk/pool`             | subscription account pools: several accounts of one provider as one `LLMProvider`                                      |
| `@yolk-sdk/vercel-workflows` | durable Workflow orchestration contracts, and a Workflow-compatible runtime on Cloudflare Durable Objects              |
| `@yolk-sdk/harness`          | run lifecycle: coordinator, store, inbox, and pluggable drivers (not the agent loop)                                   |
| `@yolk-sdk/conformance`      | experimental: record, replay, and fault-inject HTTP wire fixtures; port fixtures; run conformance cases                |
| `@yolk-sdk/emulators`        | experimental: service emulators and `HttpClient` routing to them for tests                                             |

Package roots stay tiny. Import feature APIs from explicit subpaths.

## `@yolk-sdk/agent` [#yolk-sdkagent]

| Subpath                                                  | Purpose                                                                                                       |
| -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
| `@yolk-sdk/agent/protocol`                               | wire messages, events, content, tools, usage, HITL                                                            |
| `@yolk-sdk/agent/loop`                                   | stateless LLM/tool loop and services                                                                          |
| `@yolk-sdk/agent/loop/testing`                           | faux provider and test tool executor                                                                          |
| `@yolk-sdk/agent/runtime`                                | transcript and append-backed runtime orchestration                                                            |
| `@yolk-sdk/agent/client`                                 | HTTP/NDJSON transport and client reducer helpers                                                              |
| `@yolk-sdk/agent/compaction`                             | budgets, token estimates, checkpoints, formatting, overflow retry                                             |
| `@yolk-sdk/agent/classification`                         | classifier model contract: typed questions, answers, usage, errors, `classify`                                |
| `@yolk-sdk/agent/tools`                                  | tool registry, `makeTool`, `makeInputTool`, `makeInteractionTool`, question/subagent modules, tool ledger     |
| `@yolk-sdk/agent/chat`                                   | chat projection, reducer, render model and their Schemas, without React                                       |
| `@yolk-sdk/agent/react`                                  | headless chat hook; re-exports `@yolk-sdk/agent/chat`                                                         |
| `@yolk-sdk/agent/oauth`                                  | provider-neutral access-token and broker contracts                                                            |
| `@yolk-sdk/agent/providers/openai`                       | Codex OAuth and token broker helpers                                                                          |
| `@yolk-sdk/agent/providers/openai/codex`                 | Codex request and auth helpers                                                                                |
| `@yolk-sdk/agent/providers/openai/codex-usage`           | Codex subscription-allowance snapshots                                                                        |
| `@yolk-sdk/agent/providers/openai/codex-provider`        | Codex LLM provider factory                                                                                    |
| `@yolk-sdk/agent/providers/openai/provider`              | OpenAI-compatible LLM provider factory                                                                        |
| `@yolk-sdk/agent/providers/openai/conformance`           | OpenAI chat, Codex Responses, and Codex usage fixtures (synthetic placeholders) and their conformance cases   |
| `@yolk-sdk/agent/providers/openai/realtime`              | OpenAI Realtime session config and event codecs                                                               |
| `@yolk-sdk/agent/providers/openai/speech`                | OpenAI text-to-speech and transcription adapters                                                              |
| `@yolk-sdk/agent/providers/vercel/ai-gateway-provider`   | Vercel AI Gateway Chat Completions provider factory                                                           |
| `@yolk-sdk/agent/providers/vercel/ai-gateway-classifier` | Vercel AI Gateway classifier (`/v1/evaluate`) layer                                                           |
| `@yolk-sdk/agent/providers/vercel/conformance`           | Vercel AI Gateway wire fixtures (verified chat recordings, synthetic classifier placeholders) and their cases |
| `@yolk-sdk/agent/providers/opencode/go-provider`         | OpenCode Go Chat Completions, Messages, and Responses provider                                                |
| `@yolk-sdk/agent/providers/opencode/usage`               | OpenCode Go subscription-allowance snapshots                                                                  |
| `@yolk-sdk/agent/providers/opencode/conformance`         | OpenCode Go wire fixtures (synthetic placeholders) and the conformance cases they back                        |
| `@yolk-sdk/agent/providers/anthropic`                    | Claude OAuth and token broker helpers                                                                         |
| `@yolk-sdk/agent/providers/anthropic/claude`             | Claude request and auth helpers                                                                               |
| `@yolk-sdk/agent/providers/anthropic/usage`              | Claude subscription-allowance snapshots                                                                       |
| `@yolk-sdk/agent/providers/anthropic/claude-provider`    | Claude LLM provider factory                                                                                   |
| `@yolk-sdk/agent/providers/anthropic/conformance`        | Anthropic Messages wire fixtures (synthetic placeholders) and the conformance cases they back                 |
| `@yolk-sdk/agent/providers/xai`                          | Grok subscription OAuth and broker helpers                                                                    |
| `@yolk-sdk/agent/providers/xai/grok`                     | Grok subscription request and auth helpers                                                                    |
| `@yolk-sdk/agent/providers/xai/grok-provider`            | Grok subscription LLM provider factory                                                                        |
| `@yolk-sdk/agent/providers/xai/usage`                    | Grok subscription-allowance snapshots                                                                         |
| `@yolk-sdk/agent/providers/xai/conformance`              | Grok Responses wire fixtures (synthetic placeholders) and the conformance cases they back                     |
| `@yolk-sdk/agent/providers/subscription-usage`           | Shared allowance snapshot and safe error schemas                                                              |
| `@yolk-sdk/agent/skillset`                               | portable skills and slash-command parsing                                                                     |
| `@yolk-sdk/agent/voice`                                  | voice protocol, controller, tool handler, projection, speech contracts                                        |
| `@yolk-sdk/agent/voice/browser`                          | browser WebRTC voice transport                                                                                |
| `@yolk-sdk/agent/voice/react`                            | headless `useYolkVoice` React hook                                                                            |

## Other public subpaths [#other-public-subpaths]

| Package                      | Subpaths                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `@yolk-sdk/mcp`              | `client`, `client/node`, `conformance` (experimental), `core`, `protocol`, `server`, `server/node`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `@yolk-sdk/knowledge`        | `agent`, `context`, `store`, `search`, `documents`, `files`, `chunking`, `embeddings`, `errors`, `extraction`, `ingestion`, `summarization`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `@yolk-sdk/connectors`       | `agent`, `afloat`, `afloat/conformance` (experimental), `conformance` (experimental), `dropbox`, `dropbox/conformance` (experimental), `email`, `email/conformance` (experimental), `figma`, `figma/conformance` (experimental), `fortnox`, `fortnox/conformance` (experimental), `github`, `github/conformance` (experimental), `google`, `google/conformance` (experimental), `kie`, `kie/conformance` (experimental), `linkedin-search`, `linkedin-search/conformance` (experimental), `microsoft`, `microsoft/conformance` (experimental), `notion`, `notion/conformance` (experimental), `r2-storage`, `r2-storage/conformance` (experimental), `telegram`, `telegram/conformance` (experimental), `todoist`, `todoist/conformance` (experimental) |
| `@yolk-sdk/sandbox`          | `agent`, `vercel`, `cloudflare`, `testing`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `@yolk-sdk/codemode`         | root, `node`, `cloudflare`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `@yolk-sdk/extractors`       | root, `node`, `knowledge`, `node/extraction-worker` (worker entry; not imported directly)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `@yolk-sdk/files`            | root                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `@yolk-sdk/pool`             | root, `store`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `@yolk-sdk/vercel-workflows` | root, `workflow`, `effect`, `testing`, `cloudflare`, `cloudflare/workflow`, `cloudflare/api`, `cloudflare/directives`, `cloudflare/vite`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `@yolk-sdk/harness`          | `coordinator`, `store`, `inbox`, `driver`, `driver/memory`, `driver/durable-object`, `outcome`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `@yolk-sdk/conformance`      | `fixture`, `replay`, `record`, `case`, `runner` (no root export)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `@yolk-sdk/emulators`        | `router`, `gateway`, `openai`, `anthropic`, `codex`, `xai`, `opencode`, `email`, `r2`, `node`, `fortnox`, `microsoft`, `dropbox`, `notion`, `todoist`, `telegram`, `github`, `google`, `linkedin-search`, `mcp`, `kie` (no root export)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |

## Import rule [#import-rule]

Prefer the narrowest subpath:

```ts
import { runRuntime } from '@yolk-sdk/agent/runtime'
import { makeTool } from '@yolk-sdk/agent/tools'
import { listRemoteMcpServerTools } from '@yolk-sdk/mcp/client'
```

See the package pages for deeper API notes:

* [Agent](../agent)
* [MCP](../mcp)
* [Knowledge](../knowledge)
* [Connectors](../connectors)
* [Sandbox](../sandbox)
* [Code mode](../integrations/code-mode)
* [File extraction](../integrations/file-extraction)
* [Files](../integrations/files)
* [Subscription pools](../integrations/subscription-pools)
* [Vercel Workflows](../vercel-workflows)
* [Harness](../harness)


---

# Protocol glossary

URL: /docs/reference/protocol

Core transcript and event terms used across Yolk packages.



| Term                    | Meaning                                                                                                      |
| ----------------------- | ------------------------------------------------------------------------------------------------------------ |
| `UserMessage`           | user-authored transcript message                                                                             |
| `AssistantAgentMessage` | assistant/model-authored message with text, reasoning, and tool calls                                        |
| `ToolResultMessage`     | host-authored result for a tool call                                                                         |
| `AgentMessage`          | union of user, assistant, and tool-result messages                                                           |
| `AgentEvent`            | stream event emitted by loop/runtime/client surfaces                                                         |
| `UserMessageEvent`      | replay-safe event for host-promoted user input in durable streams                                            |
| `ToolDef`               | model-visible tool name, description, parameters, and approval (and staging) metadata                        |
| `ToolCall`              | model request to execute a host tool; `id` and `name` are non-empty trimmed strings                          |
| `ToolResult`            | host result returned to the model                                                                            |
| `AgentAwaitingInput`    | logical terminal pause state for approvals/questions                                                         |
| `AgentStatus`           | one run status: `Idle`, `Working`, `Blocked`, `Done`, or `Failed` (OSC 7501 terms)                           |
| `FilePart`              | file bytes a tool yields for other tools to move; the model only sees its label                              |
| `fileId`                | `file_…` handle of a captured file (`ToolResult.files` lists them)                                           |
| `ToolFile`              | a typed tool's `output` file field: `FileBytes` or `FileStored` in, `FileRef` or `FileUnavailable` out       |
| `FileBytes`             | the bytes, name and MIME type a typed tool returns in a `ToolFile` field (`view: true` also shows the model) |
| `FileStored`            | a file the host already stored, returned in a `ToolFile` field without its bytes (checked with `head`)       |
| `FileRef`               | a stored file as scripts see it: `{ fileId, name, mimeType, size }`                                          |
| `FileUnavailable`       | a file field whose bytes were not stored: `{ unavailable: reason, name, mimeType }`                          |
| `ToolChangePreview`     | tool-agnostic before → after diff of one call, shown on approvals and plan reviews                           |

See [Agent protocol](../agent/protocol) for examples.


---

# Cloudflare Containers

URL: /docs/sandbox/cloudflare

Run the Sandbox service on Cloudflare Containers through a Durable Object.



`@yolk-sdk/sandbox/cloudflare` provides the same `Sandbox` service as the Vercel layer on
Cloudflare Containers. The agent's Worker calls `CloudflareSandbox`, a Durable Object class your
Worker exports and binds to a container application, over RPC. Each object runs one container;
every sandbox command and file transfer is an `exec` in it.

## Configure the Worker [#configure-the-worker]

Export the class from the Worker entry:

```ts
export { CloudflareSandbox } from '@yolk-sdk/sandbox/cloudflare'
```

Then, in Alchemy or wrangler:

* declare `CloudflareSandbox` as a SQLite Durable Object class and bind it (e.g. as `SANDBOX`);
* attach it to a container application with the `durable_object` scheduling policy;
* give each image an id. `ctx.container.images` maps those ids to digest-pinned references, and
  the layer's `image` names one of them. One class can carry several images, such as a
  `SessionSandbox` workspace image and a `Browser` image.

The image's own command should keep the container alive (`CMD ["sleep", "infinity"]`). It needs
`bash` and `sh`, and `git` for a Git source.

## Provide the layer [#provide-the-layer]

```ts
import { Layer } from 'effect'
import { DisposableSandboxLifecycle, SandboxResources } from '@yolk-sdk/sandbox'
import { makeCloudflareSandboxLayer } from '@yolk-sdk/sandbox/cloudflare'

const SandboxLayer = makeCloudflareSandboxLayer({
  sandboxSessionId: 'user_123:session_456',
  namespace: () => env.SANDBOX,
  image: 'SessionSandbox',
  resources: SandboxResources.make({ vcpus: 2 }),
  lifecycle: DisposableSandboxLifecycle.make({
    idleTtlMs: 30 * 60_000,
    maxLifetimeMs: 45 * 60_000
  }),
  env: { NODE_ENV: 'development' },
  internet: true
}).pipe(Layer.provide(HostSandboxStateStoreLayer))
```

| Option           | Default            | Meaning                                        |
| ---------------- | ------------------ | ---------------------------------------------- |
| `image`          | required           | Image id (key of `ctx.container.images`)       |
| `resources`      | 2 vCPUs            | `vcpu`, with 2 GiB memory per vCPU             |
| `diskMb`         | `16384`            | Container disk                                 |
| `lifecycle`      | disposable 30m/45m | Idle TTL and, when disposable, max lifetime    |
| `source`         | empty              | `Empty`, `Git`, or `Tarball` (no snapshots)    |
| `env`            | none               | Set on the container and on every command      |
| `internet`       | `true`             | Outbound internet access (`enableInternet`)    |
| `workspaceRoot`  | `/workspace`       | Absolute workspace directory                   |
| `maxOutputBytes` | `1048576`          | Bytes of stdout and of stderr kept per command |

The object is engine-only: these settings travel with every call and apply when it starts a
container. A running container keeps its settings, except that another `image` restarts it, so
give each image its own `sandboxSessionId`.

Commands run through `exec`, which does not see the image's Dockerfile `ENV`. Set the environment
commands need in `env`.

## Workspace lifetime [#workspace-lifetime]

The workspace lives only while the container runs. Every start gets a boot id, stored in
`CloudflareSandboxState.bootId`; when a later call is answered by another boot (the container
stopped, idled out, passed its max lifetime, or was destroyed) the result reports
`workspaceReset: true`.

* Disposable: the object's alarm destroys the container after `idleTtlMs` without calls (never
  while a command runs) or at `maxLifetimeMs` after its start.
* Persistent: idle stop only. Files still do not survive a stop: this adapter takes no snapshots.

The platform inactivity timeout is set to the idle TTL too; if the platform stops the container
sooner, the next call starts a new one and reports the reset.

## Differences from the Vercel adapter [#differences-from-the-vercel-adapter]

* No preview URLs: `previewUrls` is always `[]`.
* No snapshot source (`CloudflareSandboxInitialSource` excludes it).
* Git sources clone inside the container; credentials reach only that `git` process's
  environment. Tarball sources (`.tar.gz`) are downloaded by the object and unpacked from stdin,
  so the container needs no internet access for them.
* No allow/deny network policy: `internet: false` turns outbound internet off entirely. To filter
  HTTP egress, subclass `CloudflareSandbox` and route the container's outbound HTTP through a
  Worker you control in `containerStarted` (for example with
  `this.ctx.container.interceptAllOutboundHttp(...)`).
* A timeout SIGKILLs the command and, best effort, its process tree.
* Bytes cross Workers RPC, so keep file transfers and `maxOutputBytes` well under the RPC message
  limit (32 MiB).


---

# Sandbox package

URL: /docs/sandbox

Run commands in sandbox sessions and expose one destructive agent tool.



Use `@yolk-sdk/sandbox` when an agent needs an isolated workspace for commands, scripts, or generated files.

For lifecycle, source, env, ports, and approval policy, see [Sandbox lifecycle and safety](./lifecycle-safety).
On Cloudflare Workers, see [Cloudflare Containers](./cloudflare).

Install:

```bash
pnpm add @yolk-sdk/sandbox@canary @yolk-sdk/agent@canary effect@4.2.0
```

## Run a command [#run-a-command]

```ts
import { Effect, Layer } from 'effect'
import { Sandbox } from '@yolk-sdk/sandbox'
import { makeInMemorySandboxStateStoreLayer } from '@yolk-sdk/sandbox/testing'
import { makeVercelSandboxLayer } from '@yolk-sdk/sandbox/vercel'

const SandboxLayer = makeVercelSandboxLayer({ sandboxSessionId: 'user-session-123' }).pipe(
  Layer.provide(makeInMemorySandboxStateStoreLayer())
)

const program = Effect.gen(function* () {
  const sandbox = yield* Sandbox
  return yield* sandbox.run({ command: 'node --version' })
}).pipe(Effect.provide(SandboxLayer))

const result = await Effect.runPromise(program)
```

Production apps should replace the in-memory state store with durable storage.

## Add the agent tool [#add-the-agent-tool]

```ts
import { Effect } from 'effect'
import { makeSandboxToolModule } from '@yolk-sdk/sandbox/agent'

const sandboxTools = await Effect.runPromise(
  makeSandboxToolModule({
    workspaceDescription: 'A temporary Node.js workspace.',
    lifecycleDescription: 'Disposable sandbox; files may reset after expiry.',
    previewPorts: [3000]
  }).pipe(Effect.provide(SandboxLayer))
)
```

Resolve `sandboxTools` with `@yolk-sdk/agent/tools`, pass the tool definitions into the loop, and provide a `Sandbox` layer to the tool executor.

## Core command results [#core-command-results]

`Sandbox.run` returns `SandboxCommandResult`. Command failures are result data, not transport failures:

* nonzero exit code sets `exitCode`
* timeout sets `timedOut`
* workspace recreation sets `workspaceReset`

## Workspace path types [#workspace-path-types]

Raw command `cwd` inputs remain strings. `normalizeWorkspaceCwd` returns a
`NormalizedWorkspaceCwd` branded string; both are exported from `@yolk-sdk/sandbox`. The normalizer
resolves dot segments and rejects absolute paths, NUL, and workspace escape. It preserves whitespace
that belongs to remaining directory names. The brand records lexical validation, not filesystem
or symlink confinement.

`SandboxApi` may also transfer files: `writeFile({ path, bytes })` and `readFile({ path, maxBytes })`
take workspace-relative paths (`normalizeWorkspacePath` returns a `NormalizedWorkspacePath`).
Absolute paths and escapes fail with `SandboxInputError` `invalid_path`, a missing file with
`file_not_found`, and a read past `maxBytes` with `file_too_large`. The Vercel and Cloudflare
layers implement both; custom `VercelSandboxHandle`s need `readFile`. `@yolk-sdk/files` uses them for
[`file_to_sandbox` and `file_from_sandbox`](../integrations/files).

## Agent tool results [#agent-tool-results]

The `@yolk-sdk/sandbox/agent` adapter converts command failures into agent tool results:

* nonzero exit code returns a tool result with `isError: true`
* timeout returns a tool result with `isError: true`
* provider/config/state failures become safe `ToolError`s

## What the host provides [#what-the-host-provides]

Your app owns the scoped `sandboxSessionId`, durable state store, env/secrets, source/snapshot/git policy, cleanup, auth, approvals, UI, diffs, commits, PRs, and audit logs.


---

# Sandbox lifecycle and safety

URL: /docs/sandbox/lifecycle-safety

Configure Vercel Sandbox lifecycle, source, environment, ports, and agent approval policy.



The sandbox package exposes execution mechanics. Your app owns safety policy.

`@yolk-sdk/sandbox/vercel` is Node/server-only because `@vercel/sandbox` imports Node built-ins.
Browser and Worker code may use provider-free core types but must call a host execution endpoint
instead of importing the Vercel adapter. Cloudflare Workers can use the
[Cloudflare Containers adapter](./cloudflare) instead.

## Vercel layer [#vercel-layer]

```ts
import { Layer } from 'effect'
import { makeInMemorySandboxStateStoreLayer } from '@yolk-sdk/sandbox/testing'
import { GitSandboxInitialSource } from '@yolk-sdk/sandbox'
import { makeVercelSandboxLayer } from '@yolk-sdk/sandbox/vercel'

const SandboxLayer = makeVercelSandboxLayer({
  sandboxSessionId: 'user_123:session_456',
  source: GitSandboxInitialSource.make({
    url: 'https://github.com/example/repo.git',
    revision: 'main'
  }),
  env: {
    NODE_ENV: 'development'
  },
  ports: [3000, 5173],
  resources: { vcpus: 2 },
  runtime: 'node24'
}).pipe(Layer.provide(makeInMemorySandboxStateStoreLayer()))
```

Replace the in-memory state store with durable app storage in production.

## Lifecycle defaults [#lifecycle-defaults]

| Setting             | Default                        |
| ------------------- | ------------------------------ |
| lifecycle           | disposable                     |
| idle TTL            | 30 minutes                     |
| max lifetime        | 45 minutes                     |
| command timeout     | 120 seconds                    |
| max command timeout | 600 seconds                    |
| ports               | `3000`, `5173`, `4321`, `8000` |
| workspace root      | `/vercel/sandbox`              |

Expired disposable state recreates before command execution and returns `workspaceReset: true`.
Persistent state instead reattaches the stable named sandbox so Vercel can resume the latest
persisted filesystem; it recreates only when the provider no longer has that sandbox.

## Source options [#source-options]

| Source                         | Use for                                |
| ------------------------------ | -------------------------------------- |
| `EmptySandboxInitialSource`    | blank workspace                        |
| `GitSandboxInitialSource`      | clone a public or tokenized repository |
| `SnapshotSandboxInitialSource` | restore a provider snapshot            |
| `TarballSandboxInitialSource`  | hydrate from an archive                |

Choose source per trusted server policy, not from raw client input.
Git credentials use optional `GitSandboxBasicAuth`, so username/password are always supplied
together. The Vercel layer runs on a managed `runtime` (default `node24`) or a Vercel Container
Registry `image` (the project's own, or one another team shares, such as
`team/project/repo@sha256:…`), never both; either applies to empty, Git, and tarball creation, and
snapshots boot their own saved environment.

## Agent tool [#agent-tool]

```ts
import { Effect } from 'effect'
import { makeSandboxToolModule } from '@yolk-sdk/sandbox/agent'

const sandboxTools = await Effect.runPromise(
  makeSandboxToolModule({
    workspaceDescription: 'Temporary workspace for this coding task.',
    lifecycleDescription: 'Disposable sandbox; files may reset after expiry.',
    previewPorts: [3000, 5173]
  }).pipe(Effect.provide(SandboxLayer))
)
```

The tool is named `sandbox` and has `destructive` access.

## Safety checklist [#safety-checklist]

* Require approval before enabling the sandbox tool broadly.
* Scope `sandboxSessionId` by user/session/workspace.
* Do not inject long-lived secrets into disposable sandboxes.
* Restrict env/secrets to the minimum needed for the task.
* Reject privileged commands in app policy if your product needs it.
* Show diffs and command logs before committing/pushing generated work.
* Clean up expired disposable sandboxes on a schedule.

## Result semantics [#result-semantics]

Command failures are result data:

| Result field     | Meaning                                                 |
| ---------------- | ------------------------------------------------------- |
| `exitCode`       | `null` for timeout/unknown, otherwise process exit code |
| `timedOut`       | command exceeded timeout and was killed                 |
| `workspaceReset` | state was recreated before command                      |
| `previewUrls`    | provider preview URLs for configured ports              |
| `backgroundId`   | long-running background command id                      |

Provider/state/config failures become safe `ToolError`s that the agent loop renders as failed tool results.


---

# Cloudflare runtime

URL: /docs/vercel-workflows/cloudflare

Run Vercel Workflow code on Cloudflare Workers with one Durable Object per run.



The `@yolk-sdk/vercel-workflows/cloudflare*` subpaths run code written for Vercel Workflow
(`'use workflow'`, `'use step'`, `workflow`, `workflow/api`) on Cloudflare Workers without a Vercel
backend. `runVercelAgentWorkflow` and your own workflow and step functions run unchanged.

## How a run executes [#how-a-run-executes]

Each run lives in its own `WorkflowRun` Durable Object, named by its run id.

* The workflow body runs in memory in the run's object. Step outcomes, hook payloads, and fired
  sleeps are journaled in the object's SQLite storage, so after an eviction the body replays to
  where it was without re-running finished steps.
* Values cross durable boundaries as devalue text, as on Vercel: `Date`, `Map`, `Set`, typed
  arrays, `undefined`, and errors with their name, message, stack, cause, `fatal`, and `retryAfter`.
* Steps are at-least-once. A step cut off by an eviction runs again when the object's step guard
  alarm replays the run. A step's `maxRetries` (default 3) bounds retries with exponential backoff;
  `RetryableError` waits for its `retryAfter`; `FatalError` is never retried; an exhausted step
  throws a `FatalError` whose `cause` is the last error.
* Hook tokens follow Vercel's rules. One live hook holds a token at a time, and a hook-index object
  (`hook:<token>`) routes `resumeHook` to the run whose live hook holds it. A run decides its new
  hooks once its body is idle, after the disposals it made since: a hook whose token another live
  hook (of any run, its own included) still holds is refused, and awaiting it rejects with
  `HookConflictError` (`token`, `conflictingRunId`) while the holder keeps the token. A token is
  free again once its hook is disposed or its run ends. `resumeHook` succeeds for every payload
  sent to a live hook (`await hook` reads the first) and rejects with `HookNotFoundError` when no
  live hook holds the token, including a new hook the index has not granted yet: retry while the
  pause is pending.
* Unlike Vercel, which decides at the run's next durable suspension, the runtime decides at the
  next macrotask, so dispose the previous hook before any `await` that yields to the event loop. A
  hook is read once (awaiting it again gives the first payload), and `getConflict()` is not
  provided.
* `sleep(duration)` stores its wake time and arms the object's alarm.
* `getWritable()` in a step appends to the run's stream; `getRun(runId).getReadable({ startIndex })`
  follows it live and `getTailIndex()` returns the last chunk's index.
* `run.cancel()` stops the run where it waits; `returnValue` rejects with
  `WorkflowRunCancelledError`. A step still running gets its signal aborted (reason a
  `WorkflowRunCancelledError`): read it with `getStepSignal()` from
  `@yolk-sdk/vercel-workflows/cloudflare/workflow` (not part of `workflow`'s types) and pass it to
  the step's fetch or model call so it ends with the run. Its outcome is dropped either way, a step
  waiting to retry stops at once, and the run's execution ends once its steps are done.

The drop-in modules cover `createHook`, `sleep`, `getWritable`, `getStepMetadata`,
`getWorkflowMetadata`, `FatalError`, and `RetryableError` (`workflow`, plus the Cloudflare-only
`getStepSignal`), and `start`, `getRun`, and `resumeHook` (`workflow/api`, plus the
Cloudflare-only `startWithRunId`, `prepareRun`, `createRunId` and `isRunId`). `defineHook`,
webhooks, and `fetch` are not provided; `start` ignores `attributes`.

## Prepare a run ahead of its start [#prepare-a-run-ahead-of-its-start]

Every run gets a new `WorkflowRun` object, so a start pays for creating the object and evaluating
the workflow's module in its fresh isolate (about a second for a large runtime on Cloudflare).
When you know a run is coming (someone is typing a message), warm its object first. These are
Cloudflare-only exports of `@yolk-sdk/vercel-workflows/cloudflare/api` (import them from there:
`workflow/api`'s types do not declare them):

```ts
import { createRunId, prepareRun, startWithRunId } from '@yolk-sdk/vercel-workflows/cloudflare/api'

// While the person types: pick the next run's id, keep it, and warm its object.
const runId = createRunId()
await prepareRun(sessionWorkflow, runId)

// On send: start under that id. Claim the id once (for example a compare-and-set in your
// database) so only one caller starts under it.
const started = await startWithRunId(sessionWorkflow, [input], { runId })

if (started.status === 'taken') {
  // Another run lives under this id: start yours under a new id.
}
```

* `prepareRun(workflow, runId)` loads the workflow's module and the modules registered with
  `registerRunPreloads({ name: () => import('./runtime') })` (from
  `@yolk-sdk/vercel-workflows/cloudflare`, called at the Worker entry's module scope; list what a run
  loads anyway, such as a runtime its steps import lazily, and keep them plain `import()`s: every
  `prepareRun` calls them again) in the run's object. It stores nothing, so an object prepared and never started
  costs only its preparation and is evicted after a few idle minutes. Calling it again on a warm
  object is cheap and keeps it resident.
* `startWithRunId(workflow, args, { runId })` starts the run only when no run lives under the id
  and answers `{ status: 'created', run }`. Otherwise it changes nothing: `alreadyStarted` (with
  `run`) when that run has the same workflow and arguments, most likely your own earlier call whose
  answer was lost, so treat it as yours and do not start the same input again; `taken` (no handle)
  when it is another run. Use each id for one start, retries included.
* Run ids are `wrun_` and 32 hex digits (`createRunId`, `isRunId`); other ids are refused.

## Configure the Worker [#configure-the-worker]

The Worker needs:

* the `nodejs_compat` compatibility flag (the runtime uses `AsyncLocalStorage`);
* a Durable Object binding named `WORKFLOW_RUNS` to the `WorkflowRun` class, declared as a SQLite
  class in its migrations (`new_sqlite_classes: ["WorkflowRun"]`);
* the class exported from its entry module.

```ts title="worker.ts"
import { registerRunPreloads, registerWorkflowModules } from '@yolk-sdk/vercel-workflows/cloudflare'

export { WorkflowRun } from '@yolk-sdk/vercel-workflows/cloudflare'

// Load workflow modules when a run needs them, not at startup: evaluating a large runtime in the
// Worker's global scope can exceed its startup CPU limit. Keys are paths relative to the Vite root.
registerWorkflowModules({
  'app/agent-workflow.ts': () => import('./app/agent-workflow.ts')
})

// Optional, for `prepareRun`: what a prepared run object loads ahead of its start. Register both
// here, at the entry's module scope: a run object's fresh isolate sees only what evaluating the
// Worker's modules registered.
registerRunPreloads({
  runtime: () => import('./app/agent-runtime.ts')
})
```

`app/agent-workflow.ts` stands for your module with `'use workflow'` functions.

## Configure Vite [#configure-vite]

Compile the directives with `workflowDirectives`, and resolve `workflow` and `workflow/api` to the
Cloudflare modules in every server environment, for your code and for packages (this one included)
that import them:

```ts title="vite.config.ts"
import { fileURLToPath } from 'node:url'
import { defineConfig, type Plugin } from 'vite'
import { workflowDirectives } from '@yolk-sdk/vercel-workflows/cloudflare/vite'

const cloudflareModule = (subpath: string) =>
  fileURLToPath(import.meta.resolve(`@yolk-sdk/vercel-workflows/cloudflare/${subpath}`))

const workflowModules = new Map([
  ['workflow', cloudflareModule('workflow')],
  ['workflow/api', cloudflareModule('api')]
])

const cloudflareWorkflow = (): Plugin => ({
  name: 'app:cloudflare-workflow',
  enforce: 'pre',
  resolveId(source) {
    return this.environment.name === 'client' ? null : (workflowModules.get(source) ?? null)
  }
})

export default defineConfig({
  plugins: [cloudflareWorkflow(), workflowDirectives() /* , your Cloudflare/framework plugins */]
})
```

`workflowDirectives` compiles top-level `async function` declarations whose body starts with
`'use step'` or `'use workflow'`, in every environment but `client` and outside `node_modules`. A
workflow's id is `<module path>#<function name>`, relative to `root` (default: Vite's root). Runs
store the id, so moving or renaming a workflow module strands its in-flight runs.

All `./cloudflare*` modules share the run context and the workflow registry: load each of them once
per Worker (one resolved copy of the package).

## Start and read runs [#start-and-read-runs]

Host code keeps using `workflow/api` (or `VercelWorkflows.layer` from
`@yolk-sdk/vercel-workflows/effect`, which calls it):

```ts
import { getRun, resumeHook, start } from 'workflow/api'

const run = await start(agentWorkflow, [input])
const stream = getRun(run.runId).getReadable({ startIndex: 0 })

await resumeHook(token, answer)
```

`agentWorkflow`, `input`, `token`, and `answer` are host-owned values.


---

# Harness composition

URL: /docs/vercel-workflows/harness-composition

Compose a finalized model collector with Vercel Workflows, and why harness outcomes are not drop-in.



Use this recipe when a durable Vercel Workflow should run one **finalized** model turn per step. The
Next example already does that. `@yolk-sdk/harness/outcome` is an optional classification API for
hosts that choose recovery policy explicitly. It is not the current Next Workflow implementation,
not a line-reduction adapter, and not a Workflow Driver.

## Two compositions [#two-compositions]

| Path                  | What it does                                                                                                        | Status             |
| --------------------- | ------------------------------------------------------------------------------------------------------------------- | ------------------ |
| Finalized collector   | `collectModelTurn(runModelTurn(...))` inside a host `'use step'`, then `runVercelAgentWorkflow`                     | Current Next host  |
| Optional outcome seam | `attemptModelTurn` / `attemptToolBatch` inside a host step, plus explicit recovery, checkpoint, and wire projection | Future host policy |

Do not mix them accidentally. Substituting harness outcomes into the current Next model step would
change failure handling, tool admission, retry scheduling, and compaction, not merely wrap the same
collector.

The Next host lives in `examples/next/lib/agents/workflow-runtime/`. Read
[`agent-workflow-steps.ts`](https://github.com/magoz/yolk-sdk/blob/main/examples/next/lib/agents/workflow-runtime/agent-workflow-steps.ts)
for the collector and
[`run-agent-workflow.ts`](https://github.com/magoz/yolk-sdk/blob/main/examples/next/lib/agents/workflow-runtime/run-agent-workflow.ts)
for orchestration rather than copying that host into your app.

## Current Next recipe [#current-next-recipe]

`runVercelAgentWorkflow` is generic orchestration over host callbacks. The package does not import
agent protocol types or `@yolk-sdk/harness`. The host owns:

* finalized model collection
* provider admission
* transcript, usage, and tool-call serialization onto plain wire state
* tool-batch aggregation and independent children
* HITL hook tokens and response validation

The `'use workflow'` body stays the [generic wrapper](./step-contracts#wrapper). Concrete `'use step'`
functions live in the host. Next's directive wrappers dynamically import the runtime implementation
so Node-only provider, MCP, and tool dependencies stay out of the Workflow bundle. See
[`run-agent-workflow.ts`](https://github.com/magoz/yolk-sdk/blob/main/examples/next/lib/agents/workflow-runtime/run-agent-workflow.ts).

Fragment. `HostModelStepRuntime` and `./host-model-step-runtime` are host-owned placeholders, not
SDK exports:

```ts
export async function runHostModelStep(
  ...args: Parameters<HostModelStepRuntime['runHostModelStep']>
) {
  'use step'
  const runtime = await import('./host-model-step-runtime')
  return await runtime.runHostModelStep(...args)
}
runHostModelStep.maxRetries = 0
```

Inside that runtime step, fold one finalized turn with decoded cumulative usage. Fragment.
`hostDecodeUsage`, `hostModelTurnConfig`, `hostWriteEvent`, and `hostLoopLayer` are host-owned:

```ts
import { Effect } from 'effect'
import { collectModelTurn, runModelTurn } from '@yolk-sdk/agent/loop'

const initialUsage = yield * hostDecodeUsage(input.state.usage)
const { assistantMessage, toolCalls, usage, stopReason } =
  yield *
  collectModelTurn(runModelTurn(hostModelTurnConfig), {
    initialUsage,
    onEvent: hostWriteEvent
  }).pipe(Effect.provide(hostLoopLayer))
```

`collectModelTurn` projects a successful collection to a finalized `ModelTurnResult` and re-fails
unsuccessful collection outcomes. Partial output is not a continuation.

The step must project **accumulated** wire state, not the new assistant message alone: prior
`messages` and `createdMessages` plus the current assistant, cumulative `usage` (decoded
`initialUsage` plus this turn), carried `eventSequence` after durable writes, and `done` from the
finalized stop reason. Decode those fields from the incoming step state; encode the next values onto
the Workflow result. Protocol classes and Effects stay inside the step.

Keep provider clients and tool closures inside `'use step'` functions. Workflow args and state stay
JSON-serializable wire data. Do not call `Effect.runPromise` in the `'use workflow'` body. Do not
construct `@yolk-sdk/harness` Driver, Inbox, or Coordinator there.

Host tool orchestration may call `orchestrateWorkflowToolBatch` and independent Workflow `start`
children. Whole-batch preflight, ordered `ToolResultMessage` merge, child admission, and Stop policy
stay host-owned. See [Independent child orchestration](./step-contracts#independent-child-orchestration)
and [HITL resume](./hitl-resume).

## Missing Done is a model-step failure [#missing-done-is-a-model-step-failure]

A provider stream that ends without `Done` fails as `LLMError` `invalid_response` /
`retryable: false` with `responseIssue: 'missing_done'`. The current Next collector surfaces that as
the existing structured `ModelStepFailed` path:

* partial text does not become a Workflow continuation or a second provider request
* a completed tool-call input does not dispatch that tool or start a child
* `writeError` owns the terminal `AgentError` and close; `closeStream` is not used

A model result with `done: false` and no tool calls is only a generic transport capability for
host-promoted input. It does not define retry timing, partial-assistant repair, recovery budgets, or
safe tool admission. See [Model step](./step-contracts#model-step).

## Inner retries versus host scheduling [#inner-retries-versus-host-scheduling]

| Layer                                      | What it retries                                                                         |
| ------------------------------------------ | --------------------------------------------------------------------------------------- |
| `@yolk-sdk/agent/loop` `runModelTurn`      | Retryable LLM errors inside one invocation (`LoopConfig.maxRetries`)                    |
| Workflow step `maxRetries`                 | Platform re-execution of the whole step; Next streamed steps set `0`                    |
| `attemptModelTurn` `Retry` / `RecoverFull` | Classification after the inner stream; the host must schedule the next physical attempt |

Incomplete `missing_done` streams are not retryable, so they do not consume the inner
`runModelTurn` budget. `attemptModelTurn` classifies **one** `runModelTurn` invocation after that
stream's configured loop/provider retries. It does not add another retry loop. Hosts that own
physical-attempt scheduling should pass `LoopConfig.maxRetries: 0` and skip retry decorators.
Looping on `Retry` / `RecoverFull` inside the same Workflow step would stack scheduling on top of
retries the collector already ran. See [Retry policy](./step-contracts#retry-policy).

## Continue is not tool execution [#continue-is-not-tool-execution]

`attemptModelTurn` may return `Continue` with partial text/reasoning and completed tool calls after
output has started. Harness continuation **does not execute those tools** and does not invent
message IDs.

Mapping `Continue.toolCalls` into a Workflow model result (`done: false` plus `toolCalls`) would
dispatch tools from an incomplete model turn. If a host opts into `Continue`, it must keep those
calls off the ordinary `runToolBatchStep` path until a later finalized turn.

## Optional outcome seam [#optional-outcome-seam]

You may call `attemptModelTurn` / `attemptToolBatch` &#x2A;*inside a host `'use step'`** only when that
host also owns:

* recovery scheduling (retry, continue without tools, or fail)
* a checkpoint that can persist compacted messages **and** `overflowCompactionAttempt`
* a projection from outcomes onto the Workflow wire result (`done`, ordered tool results, HITL
  `awaitingInput`)

This is not current Next policy. Next keeps the finalized collector visible in the model step.
Workflow loop state is transcript, usage, turn, sequence, and `done`. It is not a harness recovery
checkpoint.

Fragment. `hostPersistCompacted`, `hostScheduleRetry`, `hostLoopLayer`, and `hostCheckpoint` are
host-owned placeholders, not SDK exports. Keep this inside a `'use step'` function:

```ts
import { Effect } from 'effect'
import { attemptModelTurn } from '@yolk-sdk/harness/outcome'

const outcome = await Effect.runPromise(
  attemptModelTurn(hostModelTurnConfig, {
    onEvent: hostWriteEvent,
    overflowCompactionAttempt: hostCheckpoint.overflowCompactionAttempt,
    compact: hostCompact
  }).pipe(Effect.provide(hostLoopLayer))
)

switch (outcome._tag) {
  case 'Completed':
    return hostProjectCompleted(outcome)
  case 'Continue':
    return hostScheduleContinueWithoutTools(outcome)
  case 'Retry':
  case 'RecoverFull':
    return hostScheduleRetry(outcome)
  case 'Compacted':
    await hostPersistCompacted({
      messages: outcome.messages,
      overflowCompactionAttempt: outcome.overflowCompactionAttempt
    })
    return hostScheduleRetry(outcome)
}
```

Durable `Compacted` is persist-then-retry. Store the compacted messages and the incremented count,
then pass that count on the next attempt. Omitting or resetting the count has no cross-invocation
budget. Compact is allowed once by default (`overflowCompactionAttempt` `0` → `1`). Overflow after
published output, or after the budget is spent, is terminal. Do not also wrap the same path with
`makeContextOverflowRetryProvider` from `@yolk-sdk/agent/compaction`; that helper is in-process
silent compact-and-retry before published output.

`attemptToolBatch` returns completed calls or pending HITL plus usage. It does not return ordered
`ToolResultMessage`s, event sequence, child lifecycle, or this host's nested-usage rules. Keep host
aggregation if you need those. Pending HITL fences the whole batch.

HITL still uses Workflow `createHook` plus host token/auth/validation.
`matchHitlResponse` / `resumeHitlIfMatched` only check protocol identity. They do not replace hook
lifecycle. See [HITL resume](./hitl-resume) and [Add human-in-the-loop](../guides/hitl).

## Terminal close and tests [#terminal-close-and-tests]

Successful `AgentEnd` closes through `closeStream`. Failure `AgentError` closes through
`writeError`. See [Terminal barrier](./step-contracts#terminal-barrier).

Host tests should drive the actual Workflow entrypoint with fake provider, store, and platform
boundaries, and assert execution traces rather than source strings. See [Test Workflows](./testing).


---

# HITL resume

URL: /docs/vercel-workflows/hitl-resume

Pause a Workflow run for approvals/questions and resume with validated responses.



HITL in Vercel Workflows is a handoff between your tool step, the Workflow hook, and your resume route.

## Pause from the tool step [#pause-from-the-tool-step]

Return `awaitingInput` from `runToolBatchStep`:

```ts
return {
  messages: [],
  createdMessages: input.createdMessages,
  awaitingInput: {
    hookToken: `agent:${runId}:hitl:${input.turn ?? 0}:${input.hitlResponses?.length ?? 0}`,
    requests: pendingRequests,
    messages: input.createdMessages,
    usage: input.usage,
    turns: input.turn ?? 0,
    eventSequence: nextEventSequence
  },
  eventSequence: nextEventSequence
}
```

Use one token per pause: no earlier pause of the run may have used it. The turn plus the number of
answers the batch already took is unique per pause; a token built only from pending request ids
repeats when a request re-pends after an invalid answer, and one token per run or session is reused
by every pause. A disposed hook frees its token and `resumeHook` routes by token alone, so a reused
token hands a late duplicate of an earlier answer (a client retry, a double submit) to the next
pause as its answer. The loop does not check tokens. A token another live hook still holds when
the run suspends (another run's pause, or a hook of this run not yet disposed) is refused: awaiting
the new hook fails with `HookConflictError`, and the loop returns `AwaitInputFailed`.

Filtering answers by request id at the hook boundary, as the Next example's `awaitInput` does
(discard an answer no pending request matches and wait on a fresh hook), also keeps a late
duplicate out of the batch. The token-per-pause rule still applies: answers that reached the hook
behind a discarded one are dropped with it, while `resumeHook` told their senders it succeeded.

Persist enough state for your UI and resume route to verify the request, including the pause's
token and its id: the `eventId` its `AgentAwaitingInput` event is about to get. Compute it with
`durableAgentEventId` from the `streamId`, `turn` and `eventSequence` you sequence that event with,
without an `executionId` (tool-batch events keep plain ids), so every execution of the step yields
the same id. Store the pause before you write the event, so a client never names a pause your route
does not know ([Name the pause](#name-the-pause-an-answer-is-for)). Steps run at least once: when a
re-executed step stores the same pause (same token) again, keep the existing record and any answer
already recorded for it. A host whose events carry no durable `eventId` gives the client nothing to
name: sequence the event with `writeDurableAgentEvent`, or give the pause another stored id the
client reads from the event.

To show approvers a before → after diff, pass `approvalPreviews: toolSet.approvalPreviews` to the
`prepareToolBatch` or `runToolBatch` call in your tool step; pending `ToolApprovalRequest`s of tools
with a `changePreview` hook then carry `preview`, or `previewError` (render the arguments instead).
Previews are recomputed whenever the batch reruns with siblings still pending, so render the latest
request per call. See [Preview the change](../agent/tools-hitl#preview-the-change).

## Wait in the workflow [#wait-in-the-workflow]

```ts
awaitInput: async awaitingInput => {
  using hook = createHook<unknown>({ token: awaitingInput.hookToken })
  return await hook
}
```

When the hook resolves, Yolk appends the decoded response to accumulated `hitlResponses` and reruns the same tool batch.

Mark the stored pause delivered when the workflow takes its answer: in `awaitInput`, once the hook
resolves with an answer you keep, run a step that marks the pause (by its token) delivered. Make the
mark idempotent and let a failed mark fail that step, so the platform retries it. Storing the run's
next pause also delivers the previous one, but nothing follows a run's last pause: without the
mark, its answer never settles, and a retry of it waits for a hook that is gone and ends in an
error instead of being reported as delivered.

`AgentAwaitingInput` ends the current client consumption window but not the Workflow run. Persist
pending state and emit it as a commit barrier; release the writer lock without final-closing the
Workflow stream before the hook resumes. `AwaitInputFailed` is final and invokes `writeError`, which
must write the safe error and close.

## Resume from a route [#resume-from-a-route]

Route fragment (host-owned helpers):

```ts
import { getRun, resumeHook } from 'workflow/api'
import { HookNotFoundError } from 'workflow/errors'

const run = getRun(runId)
const hitlResponse = await decodeSingleHitlResponse(hitlResponses)
// The pause this answers: the `eventId` of its `AgentAwaitingInput`, named by the client.
const pauseId = new URL(request.url).searchParams.get('pause')

if (pauseId === null) return refusedAnswerResponse('Name the pause this answers')

// Host-owned: records the answer durably for the stored pause `pauseId`, matched by that id only,
// with the stream tail before this first attempt.
// - The current pause: its first answer to a request it holds is recorded, and an identical retry
//   gets the same record (and the first attempt's tail index).
// - A delivered pause still in your bounded history: an identical answer is reported as delivered.
// - Anything else (a different answer, a request the pause does not hold, an unknown or evicted
//   pause) is refused, never recorded for the current pause.
const recorded = await recordHitlAnswer({
  runId,
  pauseId,
  response: hitlResponse,
  tailIndex: await run.getReadable({ startIndex: -1 }).getTailIndex()
})

if (recorded.status === 'refused') return refusedAnswerResponse(recorded.reason)

// Only a pending answer resumes; a delivered one is reported, never resumed again.
if (recorded.status === 'pending') {
  for (let attempt = 1; ; attempt++) {
    try {
      await resumeHook(recorded.hookToken, recorded.response)
      break
    } catch (error) {
      if (!HookNotFoundError.is(error)) throw error
      // The run moved past the pause: the recorded answer was already delivered.
      if (!(await isPausePending(runId, recorded.hookToken))) break
      // The hook does not exist yet: retry, bounded. Out of attempts, the answer stays recorded:
      // answer with a retryable status (for example 503) saying a retry of it is safe.
      if (attempt >= maxResumeAttempts) return answerRecordedRetryResponse(recorded)
      await delay(attempt * 250)
    }
  }
}

// Every retry of this answer streams the same continuation, from the recorded tail.
return recordedAnswerResponse(
  recorded,
  run.getReadable<Uint8Array>({ startIndex: recorded.tailIndex + 1 })
)
```

`hitlResponses` is the `@yolk-sdk/agent/client` request body field. Do not resume only by hook
token. Match run ownership, the named pause, and then request id, tool call id, and response type
against the requests that pause holds.

`resumeHook` success does not mean the answer was used. A hook accepts every payload until the
workflow disposes it, and `resumeHook` succeeds for each; `await hook` reads the first and the rest
are dropped with the hook. Two tabs answering the same pause both see success. So before resuming,
record the answer durably for the pause it names: an identical retry reuses the record, a different
answer is refused. Resume that pause's token with the recorded answer, and tell the user what was
recorded, not what `resumeHook` returned. Store the stream tail index with the first record: an
identical retry gets the first record's tail, and the response streams from
`recorded.tailIndex + 1`, so every retry of an answer replays the same continuation.

### Name the pause an answer is for [#name-the-pause-an-answer-is-for]

A request id alone does not say which pause an answer is for. A request pends again under the same
id after an invalid answer, and approval request ids are `approval:${call.id}`, which repeat when a
provider reuses a call id in a later turn. Matched by request id, a late retry of an earlier answer
can fill a later pause, and a new answer can be taken for an old one. So the client names the pause
it answers, and the route matches by that name only:

* The pause id is the `eventId` of the `AgentAwaitingInput` that asked. Your tool step computes it
  with `durableAgentEventId` and stores it with the pause before writing the event.
* The client remembers, per request id, the `eventId` of the latest `AgentAwaitingInput` holding
  that request, from every stream it reads (start, HITL resume, replay), and sends it with the
  answer. `useAgentChat` does this for you: it hands your transport the pause as `request.pause`.
  Without React, fold events with `rememberHitlPause` and read the pause with `hitlPauseFor` (both
  from `@yolk-sdk/agent/client`). Pass it as `pause` to
  `streamAgentRunHitlResponseEventStreamUntilTerminal`, which posts `{ hitlResponses }` to
  `endpoint?pause=<eventId>`; the tail reads that follow use `endpoint` without it.
* Record per named pause. Keep a bounded history of delivered pauses (pause id and recorded
  answer): an identical retry of a delivered pause is reported as delivered, without resuming. A
  pause becomes delivered when the workflow takes its answer (the idempotent mark in
  [Wait in the workflow](#wait-in-the-workflow)) or when the run stores its next pause.
* A re-executed tool step computes the same pause id (no `executionId`) and stores the same pause
  (same token) again: keep the existing record and its answer.
* Refuse an answer that names no pause, an unknown pause, or one evicted from the history. Never
  record it for the current pause. A refusal is final for that answer to that pause; the person can
  answer the request again for its later pause once that `AgentAwaitingInput` arrives.

Client fragment (`runId` is the run your start stream reported, `onRunId`):

```ts
const transport: AgentChatTransport = request => {
  const hitlResponse = request.hitlResponses?.[0]

  if (hitlResponse !== undefined && runId !== null) {
    return Stream.toAsyncIterable(
      streamAgentRunHitlResponseEventStreamUntilTerminal({
        endpoint: `/api/agent/workflow/${encodeURIComponent(runId)}`,
        hitlResponses: [hitlResponse],
        // The pause it answers; absent when no pause with an `eventId` asked for this request.
        pause: request.pause,
        signal: request.signal
      })
    )
  }

  return Stream.toAsyncIterable(
    streamAgentEventStreamUntilTerminal({ ...request, endpoint: '/api/agent/workflow' })
  )
}
```

`HookNotFoundError` means no hook is resumable under that token right now, not only that the hook
is gone:

* The hook does not exist yet. The tool step writes `AgentAwaitingInput` before the workflow
  replays and calls `createHook`, so a fast client can resume first.
* The token is wrong or unknown.
* The hook was disposed: the workflow already used an answer, possibly this one from an earlier
  attempt of the same resume (a retried request).
* The run ended.

While the stored pause is still pending, retry resuming the recorded answer a bounded number of
times. When the attempts run out, answer with a retryable status (for example 503) that says the
answer is recorded and retrying it is safe, not with the `HookNotFoundError`. Once the pause has
moved on (marked delivered, see [Wait in the workflow](#wait-in-the-workflow)), report the recorded
answer as delivered, not as an error.

## Event sequence rule [#event-sequence-rule]

Carry `eventSequence` through awaiting state and resumed tool results:

```txt
model step eventSequence -> awaitingInput.eventSequence -> resumed tool result eventSequence -> next model state
```

This keeps durable `eventId`s monotonic across pause/resume.

## Failure modes [#failure-modes]

| Failure                         | Result                                   |
| ------------------------------- | ---------------------------------------- |
| no `awaitInput` handler         | `AwaitInputFailed`                       |
| hook rejected                   | `AwaitInputFailed`                       |
| token held by another live hook | `AwaitInputFailed` (`HookConflictError`) |
| resume route denied             | workflow keeps waiting                   |
| no resumable hook for the token | `resumeHook` fails: `HookNotFoundError`  |
| tool batch fails after resume   | `ToolBatchStepFailed`                    |

Call `writeError` with safe terminal error events. Never include raw provider/tool secrets in resume errors.


---

# Vercel Workflows package

URL: /docs/vercel-workflows

Run durable agent loops with host-owned Workflow steps.



Use `@yolk-sdk/vercel-workflows` when an agent run can outlive one HTTP request and should resume through Vercel Workflows.

Install:

```bash
pnpm add @yolk-sdk/vercel-workflows@canary effect@4.2.0 workflow@^5.0.0-beta.42
```

## Wrap your Workflow [#wrap-your-workflow]

Your Workflow function stays in your app. Pass host-owned step functions into the package loop.

```ts
import { createHook } from 'workflow'
import { runVercelAgentWorkflow } from '@yolk-sdk/vercel-workflows'

export async function runAgentWorkflow(input: { request: unknown; context: unknown }) {
  'use workflow'

  return await runVercelAgentWorkflow({
    input,
    runModelStep,
    runToolBatchStep,
    closeStream,
    writeError,
    awaitInput: async awaitingInput => {
      using hook = createHook<unknown>({ token: awaitingInput.hookToken })
      return await hook
    }
  })
}
```

`runModelStep`, `closeStream`, and `writeError` are app-owned `'use step'` functions.
`runToolBatchStep` can be a step for ordinary tools, or a Workflow-safe orchestration callback
that invokes separate steps and independent child Workflow starts. Keep provider calls, tool IO,
persistence, telemetry, and Effect runtimes inside concrete steps, not orchestration code.
See [Independent child orchestration](./step-contracts#independent-child-orchestration).
When a model result is `done: false` with no tool calls, the package continues directly to the next
model step without invoking the tool-batch callback.

## Use Effect at route boundaries [#use-effect-at-route-boundaries]

Host routes can use `@yolk-sdk/vercel-workflows/effect` to start, replay, resume, and cancel runs with typed Effect errors while keeping Vercel's SDK underneath.

```ts
import { Effect } from 'effect'
import { VercelWorkflows } from '@yolk-sdk/vercel-workflows/effect'

const program = Effect.gen(function* () {
  const workflows = yield* VercelWorkflows
  const run = yield* workflows.start(runAgentWorkflow, [{ request, context }])
  const readable = yield* run.getReadable<Uint8Array>()

  return new Response(readable, {
    headers: { 'x-workflow-run-id': run.runId }
  })
}).pipe(Effect.provide(VercelWorkflows.layer))
```

Do not use the Effect API inside a `'use workflow'` function. Keep it in routes, actions, services, or tests.

## Resume HITL [#resume-hitl]

When `runToolBatchStep` returns `awaitingInput`, the package calls `awaitInput`, waits for the hook result, then reruns the same tool batch with accumulated HITL responses.

Your app owns hook tokens, route auth, response validation, and request matching. Give each pause
its own token, have each answer name its pause (the `eventId` of its `AgentAwaitingInput`; a request
id alone is ambiguous), and do not read `resumeHook` success as "the answer was used": record the
answer durably first ([HITL resume](./hitl-resume)).

## Emit replay-safe stream events [#emit-replay-safe-stream-events]

Use `sequenceDurableAgentEvent` to add deterministic ids without writing. Use
`writeDurableAgentEvent` when you want the same sequencing plus an NDJSON write:

```txt
${streamId}:${turn}:${eventSequence}
${streamId}:${turn}:${eventSequence}:${executionId}
```

Clients should de-dupe by `eventId` during resume/reconnect.

Every execution of a step starts from the same `eventSequence`, and a step can run more than once
(loop retries, platform retries, queue redelivery, Workflow 5.8 speculative execution). Pass an
`executionId` unique per execution of the step body, generated once at its start, such as
`${stepId}:${attempt}:${crypto.randomUUID()}` (`getStepMetadata()`'s `stepId` and `attempt` alone
repeat: speculative execution re-runs a discarded body under the same attempt, possibly beside it),
on every event the model call produces, from `LLMStreamStart` (required) through
`AssistantMessage`/`UsageUpdate`. The sequencer appends it to the id and sets it on the event with
the `streamId` and the step's `turn` as `executionTurn`, so a step's `turn` must be the turn its
model call streams (`runModelTurn`'s `turn`; a non-negative safe integer, or sequencing throws).
Leave it off host events (a promoted user message, the terminal event written after the commit); a
receipt replay rewrites only that terminal event.
Yolk clients then remove a superseded execution's output, drop its later events and late starts,
and, at `AgentEnd` or `AgentAwaitingInput`, show the committed answer and the calls the tool batch
ran for each turn in which a newer execution superseded an older one (limits: a turn retried after a
user message shows both answers; a client that connects mid-turn starts each execution's turn from
its first event (`executionTurn`), so it cannot tell which of two executions streaming at once
started later and shows the one it saw first as superseded until the terminal event; the committed
answer is matched by value across the run; call ids reused across turns can mix calls in model
events without `executionTurn` until the client sees a turn start). Tool-batch steps are out of scope (read calls are
not ledgered and can rerun differently). Upgrade clients with the server: older clients show both
executions back to back.

## Commit before protocol terminal events [#commit-before-protocol-terminal-events]

“Terminal” is a logical client boundary. Final callback ownership is:

```txt
AgentEnd: durable completion commit -> AgentEnd -> closeStream
AgentError: failure commit/mapping -> AgentError -> writeError-owned close
AgentAwaitingInput: persist pending HITL -> emit pause -> release writer lock, do not close -> resume
```

Use `commitThenWriteTerminalEvent` when a step must commit host state before writing the terminal
event. It cannot infer whether an event is Workflow-final and never closes the writer.

The workflow loop calls `closeStream` only on successful completion. Failure paths call `writeError`
best-effort; that callback must write the safe run-final error and close, including after a failed
success close.

## Next pages [#next-pages]

* [Step contracts](./step-contracts)
* [Routes](./routes)
* [HITL resume](./hitl-resume)
* [Testing](./testing)
* [Cloudflare runtime](./cloudflare): run the same Workflow code on Cloudflare Durable Objects


---

# Routes

URL: /docs/vercel-workflows/routes

Start, tail, resume, and cancel durable Workflow-backed agent runs.



Routes are app-owned. `@yolk-sdk/vercel-workflows` gives workflow orchestration, `@yolk-sdk/vercel-workflows/effect` gives Effect wrappers around public `workflow/api`, and `@yolk-sdk/agent/client` gives optional NDJSON transport helpers. Your app owns auth, run ownership, persistence, and response shape.

## Start a run [#start-a-run]

Effect route fragment:

```ts
import { Effect } from 'effect'
import { VercelWorkflows } from '@yolk-sdk/vercel-workflows/effect'
import { runAgentWorkflow } from './host-run-agent-workflow'

export const startProgram = (request: Request) =>
  Effect.gen(function* () {
    const workflows = yield* VercelWorkflows
    const body = yield* Effect.promise(() => request.json())
    const input = yield* Effect.promise(() => decodeStartRequest(body))
    yield* Effect.promise(() => assertCanStartRun(input))

    const run = yield* workflows.start(runAgentWorkflow, [
      {
        request: input.request,
        context: input.context
      }
    ])
    const readable = yield* run.getReadable<Uint8Array>()

    return new Response(readable, {
      headers: {
        'content-type': 'application/x-ndjson',
        'x-workflow-run-id': run.runId
      }
    })
  })
```

`decodeStartRequest` and `assertCanStartRun` are host functions. Do not trust client-provided tools, provider config, or workflow context.

## Tail an existing run [#tail-an-existing-run]

```ts
import { Effect } from 'effect'
import { VercelWorkflows } from '@yolk-sdk/vercel-workflows/effect'

export const tailProgram = (request: Request, runId: string) =>
  Effect.gen(function* () {
    const workflows = yield* VercelWorkflows
    yield* Effect.promise(() => assertCanReadRun(runId))
    const startIndex = startIndexFromRequest(request)
    const readable = yield* workflows.getReadable<Uint8Array>(runId, { startIndex })

    return new Response(readable, {
      headers: { 'content-type': 'application/x-ndjson' }
    })
  })
```

Clients can use `streamAgentRunEventStreamUntilTerminal` with this route.

At `AgentAwaitingInput`, clients reach a logical terminal boundary and should drain/release the HTTP
body without cancellation. The underlying Workflow writable remains open. After resume, tail from
the saved Workflow stream index so continued tool/model events append to the same run.

### Quiet runs [#quiet-runs]

A run writes nothing while its model thinks or a tool runs, and a client that resumes at the tail
reads nothing until the next event. Next.js sends a streamed response's headers only with its first
body chunk, so until then the client cannot even tell the route answered. The Yolk client reads
blank lines as heartbeats: they are not events and do not move the stream index, but they prove the
connection is alive, so the `idleReconnect: { idleTimeoutMs, maxAttempts }` option of the
`*UntilTerminal` helpers reconnects only after `idleTimeoutMs` of silence. Start the body with one
blank line and send another whenever the run has been quiet for well under the client's
`idleTimeoutMs` (a third of it leaves room for a late one). Insert them only between whole lines:
`writeDurableAgentEvent` writes one NDJSON line per chunk, so a stream of its chunks qualifies.

Heartbeats prove the route is alive, not that the run makes progress: if the Workflow readable
stalls while the route keeps beating, the client waits until the response ends (at the function's
maximum duration, for example) and then continues from its index. Without heartbeats it reconnects
every `idleTimeoutMs` instead, healthy quiet runs included.

```ts
const blankLine = new TextEncoder().encode('\n')

const withHeartbeats = (readable: ReadableStream<Uint8Array>, intervalMs: number) => {
  const reader = readable.getReader()
  let timer: ReturnType<typeof setTimeout> | undefined
  let open = true

  const stop = () => {
    open = false
    clearTimeout(timer)
  }

  const beatAfterQuiet = (controller: ReadableStreamDefaultController<Uint8Array>) => {
    clearTimeout(timer)
    timer = setTimeout(() => {
      // A connection still busy with earlier bytes needs no heartbeat.
      if (open && (controller.desiredSize ?? 0) > 0) controller.enqueue(blankLine)
      beatAfterQuiet(controller)
    }, intervalMs)
  }

  return new ReadableStream<Uint8Array>({
    start(controller) {
      controller.enqueue(blankLine)
      beatAfterQuiet(controller)
    },
    async pull(controller) {
      try {
        const result = await reader.read()

        if (!open) return

        if (result.done) {
          stop()
          controller.close()
        } else {
          controller.enqueue(result.value)
          beatAfterQuiet(controller)
        }
      } catch (error) {
        stop()
        controller.error(error)
      }
    },
    cancel(reason) {
      stop()

      return reader.cancel(reason)
    }
  })
}
```

Return `new Response(withHeartbeats(readable, intervalMs), { headers })`. Validate access and the
run before building it, so refusals keep their status: once the blank line is sent the status is
200, and a later failure can only end the body early.

## Resume HITL [#resume-hitl]

Route fragment (host-owned helpers):

```ts
import { Effect } from 'effect'
import { VercelWorkflows } from '@yolk-sdk/vercel-workflows/effect'

export const resumeProgram = (request: Request, runId: string) =>
  Effect.gen(function* () {
    const workflows = yield* VercelWorkflows
    yield* Effect.promise(() => assertCanResumeRun(runId))

    const body = yield* Effect.promise(() => request.json())
    const hitlResponse = yield* Effect.promise(() => decodeSingleHitlResponse(body.hitlResponses))
    // The pause this answers: the `eventId` of its `AgentAwaitingInput`, named by the client.
    const pauseId = new URL(request.url).searchParams.get('pause')

    if (pauseId === null) return refusedAnswerResponse('Name the pause this answers')

    const tailIndex = yield* workflows.tailIndex(runId)
    // Host-owned, as in HITL resume: records the answer for the named pause (with this tail index;
    // an identical retry gets the first record's), then resumes that pause's own hook token with
    // it, retrying a bounded number of times on `HookNotFoundError` while the pause is pending.
    // A delivered pause's identical answer is reported without resuming; the rest are refused.
    const recorded = yield* Effect.promise(() =>
      recordAndResumeHitlAnswer({ runId, pauseId, response: hitlResponse, tailIndex })
    )

    if (recorded.status === 'refused') return refusedAnswerResponse(recorded.reason)
    // Out of resume attempts: the answer stays recorded; a retryable 503 says retrying is safe.
    if (recorded.status === 'hook-pending') return answerRecordedRetryResponse(recorded)

    // Replay from the recorded tail, so every retry of this answer replays the same continuation.
    const readable = yield* workflows.getReadable<Uint8Array>(runId, {
      startIndex: recorded.tailIndex + 1
    })

    return new Response(readable, {
      headers: {
        'content-type': 'application/x-ndjson',
        'x-workflow-stream-tail-index': String(recorded.tailIndex)
      }
    })
  })
```

The helper-compatible request body is `{ hitlResponses }`; the client names the pause as the
`pause` query parameter of the POST (`?pause=<eventId>`, what
`streamAgentRunHitlResponseEventStreamUntilTerminal` sends for its `pause` option; tail reads carry
none). The resume side must verify the authenticated user owns the run,
match the response against the requests of the pause it names (never by request id alone), and
record it before resuming. The full record-then-resume code and its rules are in
[HITL resume](./hitl-resume#resume-from-a-route).

If your resume route returns `202` with no body, do not use `streamAgentRunHitlResponseEventStreamUntilTerminal`. POST the resume yourself, then call `streamAgentRunEventStreamUntilTerminal` on the tail route.

## Cancel a run [#cancel-a-run]

```ts
import { Effect } from 'effect'
import { VercelWorkflows } from '@yolk-sdk/vercel-workflows/effect'

export const cancelProgram = (runId: string) =>
  Effect.gen(function* () {
    const workflows = yield* VercelWorkflows
    yield* Effect.promise(() => assertCanCancelRun(runId))
    yield* workflows.cancel(runId)

    return new Response(null, { status: 204 })
  })
```

Cancellation is host/Vercel-owned. The package does not define a cancellation protocol event.

## Client helpers [#client-helpers]

Import these from `@yolk-sdk/agent/client`.

| Client API                                           | Route shape                                   |
| ---------------------------------------------------- | --------------------------------------------- |
| `streamAgentEventStreamUntilTerminal`                | starts run and follows continuation headers   |
| `streamAgentRunEventStreamUntilTerminal`             | reads an existing run tail                    |
| `streamAgentRunHitlResponseEventStreamUntilTerminal` | resumes HITL and follows returned/tail chunks |
| `cancelAgentRun`                                     | calls your cancel route                       |

## Headers [#headers]

Use the SDK header helpers from `@yolk-sdk/agent/client` on the client:

* `agentRunIdFromHeaders`
* `agentRunStreamTailIndexFromHeaders`
* `agentRunStreamStartIndexFromHeaders`
* `agentRunEndpointWithStartIndex`

Header meanings:

| Header                         | Meaning                                                               |
| ------------------------------ | --------------------------------------------------------------------- |
| `x-workflow-run-id`            | Vercel Workflow run id returned by your start route                   |
| `x-workflow-stream-tail-index` | Vercel stream chunk index immediately before the response body starts |

The stream tail index is for Vercel continuation chunks. It is distinct from durable agent `eventSequence`, which is part of replay-safe event ids.


---

# Step contracts

URL: /docs/vercel-workflows/step-contracts

Model, tool, stream, error, retry, and terminal contracts for Vercel Workflow agents.



`runVercelAgentWorkflow` is orchestration only. Your app provides all work as Workflow-safe callbacks.

## Wrapper [#wrapper]

```ts
import { createHook } from 'workflow'
import { runVercelAgentWorkflow } from '@yolk-sdk/vercel-workflows'

export async function runAgentWorkflow(input: { request: unknown; context: unknown }) {
  'use workflow'

  return await runVercelAgentWorkflow({
    input,
    maxTurns: 64,
    runModelStep,
    runToolBatchStep,
    closeStream,
    writeError,
    awaitInput: async awaitingInput => {
      using hook = createHook<unknown>({ token: awaitingInput.hookToken })
      return await hook
    }
  })
}
```

Keep provider calls, tool execution, persistence, telemetry, and Effect runtimes in `'use step'` callbacks, not in the `'use workflow'` body.

## Callback table [#callback-table]

| Callback           | Directive                      | Input                                                                                     | Output                                                                                 |
| ------------------ | ------------------------------ | ----------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
| `runModelStep`     | `'use step'`                   | `{ context, state }`                                                                      | model result with `done`, `messages`, `createdMessages`, `toolCalls`, `usage`, `turn`  |
| `runToolBatchStep` | step or workflow orchestration | `{ context, request, calls, createdMessages, hitlResponses, usage, turn, eventSequence }` | tool results, `awaitingInput`, or a wire-safe partial-progress `failure`               |
| `awaitInput`       | workflow body                  | awaiting-input payload                                                                    | one host-decoded HITL response that the package appends to accumulated `hitlResponses` |
| `closeStream`      | `'use step'`                   | none                                                                                      | closes the writer only; `AgentEnd` is written before it by the final model step        |
| `writeError`       | `'use step'`                   | unknown error                                                                             | writes safe final error and closes failure stream; best-effort, not retried            |

## Model step [#model-step]

Fragment:

```ts
async function runModelStep(input: VercelAgentWorkflowModelStepInput) {
  'use step'

  return await runHostModelTurn(input.state)
}
```

Rules:

* Return `done: true` when no tool batch is needed; the workflow closes the stream.
* Return `done: false` with ordered `toolCalls` when tools must run.
* A `done: false` result with no tool calls continues directly to the next model step without
  invoking `runToolBatchStep`; use this when host-promoted input already advanced model state.
* Put assistant/model-created messages in `createdMessages`.
* With [host instructions](/docs/agent/loop-runtime#host-instructions) (for example the code mode
  catalog), append `instructionMessages(transcript, instructions)` from `@yolk-sdk/agent/loop`
  before calling `runModelTurn`, and return them in `createdMessages` ahead of the assistant
  message; `runModelTurn` does not accept `instructions`.
* Carry `eventSequence` if the model step wrote durable stream events.

The Next example keeps that model result finalized: it folds `collectModelTurn(runModelTurn(...))`
and does not promote a missing `Done` into a Workflow continuation. See
[Harness composition](./harness-composition) for that recipe versus an optional
`@yolk-sdk/harness/outcome` policy.

## Tool batch step [#tool-batch-step]

Fragment:

```ts
async function runToolBatchStep(input: VercelAgentWorkflowToolBatchStepInput) {
  'use step'

  return await runHostToolBatch({
    calls: input.calls,
    hitlResponses: input.hitlResponses ?? [],
    eventSequence: input.eventSequence ?? 0
  })
}
```

Rules:

* Return one tool-result message per host tool call.
* Preserve original model tool-call order.
* Represent expected per-tool failures as result messages, not thrown step errors.
* If the step boundary catches a batch failure after sibling progress, return wire-safe `failure`,
  cumulative `usage`, and the latest `eventSequence`.
* Return `awaitingInput` when approvals/questions must pause the workflow.
* A background acknowledgement (`ToolResultMessage.acceptance`) is a normal result message for the
  original call: it carries no nested usage and must not be treated as completion. Make the host
  `BackgroundToolHost.accept` idempotent per call id so a retried tool step replays the same
  receipt instead of launching twice.

## Independent child orchestration [#independent-child-orchestration]

For independent children, `runToolBatchStep` may be a Workflow-safe orchestration callback instead
of one `'use step'` function. Use `orchestrateWorkflowToolBatch` to fence the whole batch with a
durable preflight, then invoke separate tool steps or Workflow 5 `start` calls. Do not wrap a whole
child loop in one parent step: nested step calls from a step execute inline.

Fragment inside a host `'use workflow'` function; `hostPreflightStep`, `hostReadChildStep`, and
`hostChildWorkflow` are host-owned placeholders, not SDK exports:

```ts
import { sleep } from 'workflow'
import { start } from 'workflow/api'
import { awaitWorkflowChild, orchestrateWorkflowToolBatch } from '@yolk-sdk/vercel-workflows'

const outcome = await orchestrateWorkflowToolBatch({
  calls: hostChildCalls,
  concurrency: 2,
  preflight: () => hostPreflightStep(hostChildCalls),
  execute: async call => {
    const child = await start(hostChildWorkflow, [call])
    return await awaitWorkflowChild({
      read: () => hostReadChildStep(child.runId),
      sleep: async () => {
        await sleep('1s')
      }
    })
  }
})
```

The preflight step returns `{ ready: false, value }` to pause without launching any call, or
`{ ready: true }` to allow dispatch. When using `prepareToolBatch` inside that step, any
`pendingRequests` fence **all** launches, including executable siblings. Preserve its synthetic
results and merge executed results by original call index.

The read step returns `{ done: false }` or `{ done: true, value }`; represent child failure as a
terminal value rather than polling forever. Keep reads short-lived and use Workflow `sleep`, not a
long `returnValue` poll inside a step. Effect, storage, and provider work remain inside steps.

Handle `outcome` before returning the loop's tool-batch result: `ready: true` may include
`failures` and only partial ordered `results`. On rejection, dispatch stops and active siblings
settle. Hosts map progress/failure into the loop's wire-safe result and never proceed to another
model turn with unmatched calls.

Hosts own admission, durable reservations/results, ownership checks, child HITL support, and Stop
policy. Background acceptance is not child completion; see [Background subagents](../agent/tools-hitl#background-subagents).

### Bounded child observations [#bounded-child-observations]

The fragment above polls without a ceiling. `awaitWorkflowChild` passes deterministic zero-based
indices to `read(attempt)` and `sleep(attempt)`: read zero, sleep zero if pending, read one, and so
on. Existing zero-argument callbacks remain valid; no timeout or backoff is added automatically.

Pass `attempt` into the host read step to enforce an observation budget, and use it in the sleep
callback for host-chosen capped backoff. At the ceiling, the read step returns
`{ done: true, value }` with the latest truthful still-running or unknown status and a recovery
handle. Here `done` means observation ended, not that the child completed or was cancelled.
Durable storage, authorization, terminal-state detection, and Stop policy remain host-owned.

When mapping that value into a nonterminal `subagent` tool result, use the matching logical ID and
[observation marker](../agent/tools-hitl#nonterminal-child-observations), rather than fabricating a
terminal child result or charging nested usage. The physical Workflow run id is a separate
host-owned recovery handle. See the [callback signatures](../api-reference/workflows#awaitworkflowchilda).

## Run result tags [#run-result-tags]

`runVercelAgentWorkflow` returns `VercelAgentWorkflowRunResult` values from
`@yolk-sdk/vercel-workflows` (`Data.taggedEnum` plain objects, `_tag` last). Construct or match
with `VercelAgentWorkflowRunResult.Completed({ turns, state })` and siblings, or
`VercelAgentWorkflowRunResult.$is('Completed')`. `settleWorkflowStep` returns
`WorkflowStepResult.Success({ value })` / `WorkflowStepResult.Failure({ error })`.

| Tag                   | Meaning                                                   |
| --------------------- | --------------------------------------------------------- |
| `Completed`           | model ended and `closeStream` succeeded                   |
| `ModelStepFailed`     | model step exhausted retries                              |
| `ToolBatchStepFailed` | tool batch step exhausted retries                         |
| `AwaitInputFailed`    | final HITL hook/resume failure; unlike a successful pause |
| `CloseStreamFailed`   | terminal model step succeeded but every close failed      |
| `MaxTurnsExceeded`    | loop exceeded `maxTurns`                                  |

## Retry policy [#retry-policy]

Default retry policy is `noWorkflowStepRetry` (`maxAttempts: 1`), except for `closeStream`, which
defaults to `defaultCloseStreamRetry` (`maxAttempts: 3`). Closing a Workflow stream is idempotent on
Vercel, so a close-only step's retry writes nothing. The platform redelivers a close step whose
function died; the loop retry matters after the step's platform attempts are used up, when the close
was applied but the step still failed (for example its completion was lost): a later attempt that
succeeds completes the run instead of reporting `CloseStreamFailed` for a stream the client saw end.
The loop retries any rejection, a `FatalError` thrown by `closeStream` too. Keep `closeStream`
close-only and safe to repeat, or pass `closeStreamRetry: noWorkflowStepRetry` to close once. Opt
into retries per callback:

```ts
await runVercelAgentWorkflow({
  input,
  runModelStep,
  runToolBatchStep,
  closeStream,
  writeError,
  modelStepRetry: { maxAttempts: 2 },
  toolBatchStepRetry: { maxAttempts: 2 },
  awaitInputRetry: { maxAttempts: 2 },
  closeStreamRetry: { maxAttempts: 2 }
})
```

Finite `maxAttempts` values are floored and clamped to at least `1`; non-finite values normalize to
`1`. Retries run immediately with no backoff. `writeError` is best-effort cleanup and is not retried.

One attempt does not stop platform retries (`fn.maxRetries`) or queue redelivery: a model or
tool-batch step can still run again after a failure or crash, or concurrently with a running
execution. See
[Tool steps run at least once](../integrations/vercel-workflow#tool-steps-run-at-least-once).

`maxTurns` accepts positive integers. Finite values are floored and clamped to at least `1`; omitted
or non-finite values use `defaultMaxWorkflowTurns`.

`eventId` de-dupe alone does not make a retried streamed step safe: a retried model step streams a
different answer from the same `eventSequence`. Give its live events an `executionId` per execution
and keep deterministic ids only for events every execution writes identically. See
[Emit replay-safe stream events](../vercel-workflows#emit-replay-safe-stream-events).

## Terminal barrier [#terminal-barrier]

Use `commitThenWriteTerminalEvent` when terminal events imply durable state is settled:

```ts
const result =
  yield *
  commitThenWriteTerminalEvent({
    terminal: agentEndEvent,
    commit: persistRunState,
    write: event => writeEvent(event),
    writeCommitError: error => writeEvent(toAgentErrorEvent(error))
  })
```

The helper never writes success terminal before `commit` succeeds, cannot infer finality from the
event tag, and never closes the writer. It may guard a resumable `AgentAwaitingInput` persistence
barrier; release the writer lock but leave the Workflow stream open in that case.

`writeCommitError` is typed as `(error: CommitError) => …`, where `CommitError` is the existing
generic on `commit`. The producer is `Effect.matchEffect` `onFailure`; defects do not enter the
callback. `CommitThenWriteTerminalEventResult` still carries `commitError` and `error` as
`unknown`. Existing `(error: unknown) => …` callbacks remain assignable.

`runVercelAgentWorkflow` invokes `closeStream` only after a model step returns `done: true`.
Failure paths call `writeError` and return without invoking `closeStream`; `writeError` must write
the safe final error and attempt to close that path. After `CloseStreamFailed` the stream may
already carry the committed `AgentEnd` (a close can apply while its step still fails), so a
`writeError` that records a failure must not replace a committed completion: check for the run's
committed completion (or compare-and-set against it) before recording the failure.


---

# Test Workflows

URL: /docs/vercel-workflows/testing

Test pure Workflow contracts and directive behavior for durable agent runs.



Test three layers: package loop contracts, host behavior against a platform emulator, and real
Workflow directives.

Tests whose import graph reaches `workflow`, and tests that execute steps with `TestWorkflowWorld`
(it loads the workflow runtime's serializer), must use Vitest's Node environment, not jsdom, because
Workflow 5 captures Node `URL` intrinsics when the module loads.

## Behavioral platform emulator [#behavioral-platform-emulator]

`@yolk-sdk/vercel-workflows/testing` exports `TestWorkflowWorld`. Use it to exercise host code
against run lifecycle, append-only stream replay, HTTP 409-style conflicts for writes after close
(closing again succeeds, as on Vercel), step retry attempts, hooks/resume, cancellation, and the
SDK seam consumed by `VercelWorkflows.layerFromSdk`.

This is a test fragment; initialize one world per test and mock the ambient module before importing
the host Workflow under test:

```ts
// @vitest-environment node
import { expect, it, vi } from 'vitest'
import { TestWorkflowWorld } from '@yolk-sdk/vercel-workflows/testing'

vi.mock('workflow', async () => {
  const { testWorkflowModule } = await import('@yolk-sdk/vercel-workflows/testing')
  return testWorkflowModule
})

it('runs host orchestration against Workflow behavior', async () => {
  const world = new TestWorkflowWorld()
  const doubledStep = world.step(async (value: number) => value * 2, 'double')
  const { runId } = world.start(doubledStep, [21])

  expect(world.status(runId)).toBe('pending')
  await world.settled(runId)
  expect(world.status(runId)).toBe('completed')
  await expect(world.sdk.getRun<number>(runId).returnValue).resolves.toBe(42)
})
```

`testWorkflowModule` delegates `getWritable`, `getWorkflowMetadata`, `getStepMetadata`, and
`createHook` to the active world's `AsyncLocalStorage` context, so host code runs unchanged. The
ambient mock does not apply platform retry policy by itself: wrap host step callbacks with
`world.step(...)` or call `world.runStep(...)` when the test must exercise retries and
`getStepMetadata().attempt`. Use `world.inspect(runId)` for stream closure, write-after-close
attempts, step attempts, status, run errors, `unstorableStepErrors` (`stepName`, `attempt`,
`error`), `discardedStepExecutions` ([Speculative execution](#speculative-execution)), and the
run's start `attributes` (`{}` without any; no `$parentRunId`/`$rootRunId`).
`world.sdk.start` checks them with the installed runtime's validator, so an attribute the platform
rejects fails the start there too. Use `world.sdk` with `VercelWorkflows.layerFromSdk` when testing
Effect route/service boundaries.

### Hooks [#hooks]

Hooks behave as on the platform. `world.resumeHook` (and `world.sdk.resumeHook`) succeeds for every
payload sent to a live hook; `await hook` reads the first, and the rest are dropped when `using`
disposes the hook. Once the hook is disposed, or its run ended, resuming its token fails with
`TestWorkflowHookNotFoundError` until a hook of any run takes the token again. So a test can show a
second answer being accepted and never used, or a late duplicate reaching the next pause that
reuses a token ([HITL resume](./hitl-resume)).

A token is held by one live hook at a time. The platform creates a hook when its run next
suspends, applying the disposals the run made since first; the world decides once the code that
created the hook yields (for example at its first `await`). If another live hook, in another run or
the same one, still holds the token then, the new hook is refused: awaiting it fails with
`TestWorkflowHookConflictError` (named `HookConflictError`, with `token`, `conflictingRunId`, and
the platform's message without its docs link), disposing it changes nothing, and the holder keeps
the token and its answers. So creating the next hook and then disposing the previous one before
awaiting works, while a step or other suspension in between leaves the next hook refused. Once the
holder is disposed or its run ends, a new hook takes the token.

The world differs from Vercel in two ways: a non-suspending `await` (such as
`await Promise.resolve()`) between creating the next hook and disposing the previous one refuses
the next hook here while Vercel accepts it, and a disposed hook frees its token (and answers
`TestWorkflowHookNotFoundError`) at once, while Vercel records the disposal at the run's next
suspension. The world does not model reading one hook more than once, nor the platform hook's
`getConflict()`.

### Step errors [#step-errors]

Step errors cross the platform boundary as they do in a deployment. `world.runStep` stores each
thrown value with the installed `workflow` runtime's step-error serializer and throws only the value
read back, so error tags, prototypes, and custom fields are gone and `cause` survives:

* A `FatalError` (named `FatalError`, or with `fatal: true`) is never retried; an `AbortError` is
  promoted to one, as the platform does.
* An exhausted step fails with the platform's `FatalError` whose `cause` is the last thrown value;
  its message reads `Step "<name>" failed after N retries: <message>`.
* A value the platform cannot store, such as an error with a class instance in its `cause` chain,
  never reaches the workflow body. The platform redelivers the step instead, so the world runs it
  again as the next attempt. Past the budget the step fails, without a cause, with
  `Step "<name>" exceeded max retries (N retries)`. `world.inspect(runId).unstorableStepErrors`
  lists every such value.

Carry anything the workflow body must read across the boundary as plain data, for example in an
error's `cause`, and assert `unstorableStepErrors` is empty in tests of your step failures.

### Speculative execution [#speculative-execution]

Workflow 5.8 may start the body of a step with `maxRetries > 0` before its start is recorded. When
that start is refused, the platform discards the body's outcome and runs the body again with the
same `getStepMetadata()`: same `stepId`, same `attempt`. Reproduce it with
`new TestWorkflowWorld({ discardStepExecution })`:

```ts
const world = new TestWorkflowWorld({ discardStepExecution: ({ attempt }) => attempt === 1 })
```

Before each attempt of a step with `maxRetries > 0` (never `maxRetries: 0`), the world calls
`discardStepExecution` with the step's metadata. On `true` it runs the body once and discards the
outcome: never stored, never retried, not counted in `stepAttempts`. That execution's stream writes
stay, as on the platform. The body then runs again with the same metadata, and that run is the
attempt; later attempts keep their numbers. At most one execution per attempt is discarded, and it
settles before the kept one starts, while the platform may run both at once, so a discarded body
that never settles blocks the step. `world.inspect(runId).discardedStepExecutions` lists them
(`stepName`, `stepId`, `attempt`, and `outcome`, an Effect `Result`: `Success` with the returned
value, `Failure` with the thrown one).
Use it to check that your model step's `executionId` differs between the two runs
([Emit replay-safe stream events](../vercel-workflows#emit-replay-safe-stream-events)).

## Pure contract tests [#pure-contract-tests]

Use normal Vitest tests for `runVercelAgentWorkflow` with fake callbacks.

```ts
import { expect, it } from 'vitest'
import { runVercelAgentWorkflow } from '@yolk-sdk/vercel-workflows'

it('continues from tool results', async () => {
  const result = await runVercelAgentWorkflow({
    input: { request: 'request-1', context: 'ctx-1' },
    runModelStep: async input =>
      input.state.turn === 1
        ? {
            done: false,
            messages: ['user', 'assistant'],
            createdMessages: ['assistant'],
            toolCalls: ['tool-a'],
            usage: { turns: 1 },
            turn: 1
          }
        : {
            done: true,
            messages: ['user', 'assistant', 'tool-result', 'final'],
            createdMessages: ['assistant', 'tool-result', 'final'],
            toolCalls: [],
            usage: { turns: 2 },
            turn: 2
          },
    runToolBatchStep: async input => ({
      messages: ['tool-result'],
      createdMessages: [...input.createdMessages, 'tool-result']
    }),
    closeStream: async () => undefined,
    writeError: async () => undefined
  })

  expect(result._tag).toBe('Completed')
})
```

## Directive tests [#directive-tests]

Use `@workflow/vitest` for files that exercise `'use workflow'`, `'use step'`, hooks, streams, and cancellation.

```ts
import { getRun, resumeHook, start } from 'workflow/api'
import { waitForHook } from '@workflow/vitest'
```

Cover:

* starting host Workflow functions with `start`
* reading stream chunks and replaying with `getRun(runId).getReadable({ startIndex })`
* waiting for hooks with `waitForHook`
* resuming with `resumeHook`
* cancellation with `getRun(runId).cancel()`

## Assertions to keep [#assertions-to-keep]

* A `done: false` model result with no tool calls continues directly to the next model step.
* One ordered tool-result message per tool call.
* HITL reruns the same tool batch with accumulated responses.
* Event sequence advances across model, tool, and HITL resume.
* Default retries are disabled, except the close step's (`defaultCloseStreamRetry`).
* Retried streamed steps have de-dupe-ready event ids; a model step's live events carry an
  `executionId` per execution, so a retry, or a speculative re-execution under the same attempt,
  never reuses an earlier execution's ids.
* Terminal write happens only after durable commit succeeds.
* `AgentEnd` closes through `closeStream`, and only there; a retried close re-closes harmlessly.
* Failure paths use `writeError`, not `closeStream`; a `writeError` rejection preserves the original
  structured failure result.
* `AgentAwaitingInput` does not close before resume; resumed execution can append and eventually
  close.
