> ## Documentation Index
> Fetch the complete documentation index at: https://iii.dev/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Upgrading from 0.26.x to 0.27.x

> Every iii SDK replaces the Channels API with streams in call payloads and results, VM workers become explicit in worker-compose.yaml, and iii call resolves in default without -n. Upgrade the project once, then move each worker's channel code when you upgrade its SDK.

iii 0.27 changes every SDK: TypeScript (Node and browser), Python, Rust, and Go. Streaming between
functions no longer has an API of its own: a stream is a value of a call. Put a file, a readable, or
a generator in a payload or a result, and the function on the other side receives an `InputStream`
to read; put a writable or a file to create there, and it receives an `OutputStream` to write.

* **The Channels API is removed from all five SDKs.** `createChannel`, `ChannelReader`,
  `ChannelWriter`, `readerRef`, and `writerRef` (Python `create_channel`, `create_channel_async`,
  `reader_ref`, `writer_ref`; Rust `iii_sdk::helpers::create_channel` and `iii_sdk::channel::*`; Go
  `CreateChannel`, `Channel`, `ChannelReader`, `ChannelWriter`, `OpenReader`, `OpenWriter`, and
  `ExtractChannelRefs`; the browser's `createChannel`, `Channel`, `ChannelReader`, and
  `ChannelWriter`) give way to `InputStream` and `OutputStream`, and to `iii.pipe()` for an explicit
  pipe. This is a breaking change with no deprecated aliases.
* **The wire is unchanged.** A 0.26 engine serves 0.27 SDKs, and a ref has the same JSON in every
  SDK, so workers on 0.26 and 0.27 SDKs work together in one project. For streaming, the 0.27 engine
  changes only the text of its `payload_too_large` errors, which now link to
  [Streaming / Payload size](https://iii.dev/docs/creating-workers/streaming.md#payload-size), as the errors of every
  0.27 SDK do.
* **VM workers are explicit in `worker-compose.yaml`.** A container that runs in a microVM now says
  so in its `scripts`, and Compose rewrites a 0.26 file on its next run. A project with a VM worker
  also follows [Upgrading VM workers from 0.26.x](https://iii.dev/docs/upgrading/explicit-vm-workers.md).
* **Container keys are directory names.** A key that starts with `.` or holds `/`, among others,
  loaded in 0.26 and now fails with `INVALID_CONTAINER_KEY`.
* **`iii call` resolves in `default` without `-n`**, also in a script that Compose starts. See
  [`iii call`](#iii-call).

## Before you upgrade

### Who needs to migrate

Every project, once, for the changes in [Upgrade the project](#upgrade-the-project): the compose
file and the scripts that run `iii call`. For streaming, only the workers whose SDK you upgrade to
0.27, and in them only the code that uses channels. A project that keeps its SDKs on 0.26 needs no
streaming change, an engine upgrade alone changes nothing for streaming, and you can move one worker
at a time.

### Upgrade the project

Do this once per project, before the first run of the 0.27 `iii`:

1. Stop the project, and commit `worker-compose.yaml` and `worker-compose.lock`. The 0.27 Compose
   rewrites the containers that 0.26 ran in a VM on its next run, and a rewritten file no longer
   loads in 0.26: the commit is your way back.
2. Rename each container key that is empty or blank, holds `/` or `\`, starts with `.`, or holds a
   NUL, such as `.internal` or `a/b`, and the `start_after` entries that name it. A container key is
   now also the name of its directories, `.iii/build/<key>/` and `.iii/workers/<key>/`, so such a
   key fails with `INVALID_CONTAINER_KEY` in any project, with or without a VM worker.
3. If the project has VM workers, a registry `bundle` or a `path://` worker whose `iii.worker.yaml`
   sets `runtime.base_image`, follow [Upgrading VM workers from 0.26.x](https://iii.dev/docs/upgrading/explicit-vm-workers.md). It
   covers the sandbox adapter, which must be a 0.5 release, and the containers that must stay on the
   host.
4. Add `-n <namespace>` to each `iii call` in a script that targets a function of the project's
   namespace, as in [`iii call`](#iii-call).

### Compatibility

| SDK | On a 0.26 engine |
| - | - |
| **0.26 SDK** | Unchanged. |
| **0.27 SDK** | Everything works. Streams use `engine::channels::create` and the `/ws/channels` sockets, which the 0.26 engine already serves: no engine upgrade is needed. |

### Mixed fleets

A ref is the same JSON whichever SDK sent it, so a stream crosses SDK versions. What the receiving
worker gets depends on its SDK:

| A stream or a ref sent | Reaches a 0.27 worker as | Reaches a 0.26 TypeScript, Python, or browser worker as | Reaches a 0.26 Go or Rust worker as |
| - | - | - | - |
| in a call payload | an `InputStream` or an `OutputStream` | a `ChannelReader` or a `ChannelWriter` | the ref JSON |
| in a function's result | an `InputStream` or an `OutputStream` | the ref JSON | the ref JSON |

The 0.27 lifecycle rules apply on the 0.27 side only. A handler on a 0.26 SDK that receives a writer
still has to close it, and a 0.27 caller that passed it a sink waits until it does: its call
resolves only after the sink has received the whole stream. If the 0.26 handler never opens the
writer, the call fails with `TIMEOUT` when its timeout expires, and the SDK aborts the sink.

A 0.26 TypeScript or Python writer that closes without writing anything never opens its socket, so
its reader, on any SDK version, waits until the engine expires the pipe. This is 0.26 behavior: a
0.27 writer opens the socket to close it, so its reader sees an empty stream at once. Upgrade the
writing side to fix it.

### Payload size with older SDKs and engines

When a worker registers, the engine gives it one of two receive limits for JSON messages. For the
limits, see [Streaming / Payload size](https://iii.dev/docs/creating-workers/streaming.md#payload-size). A worker on a
Rust, Node, Python, or Go SDK from 0.25.0 declares the `large-messages.v1` protocol feature and gets
the larger limit.

These rules apply to older SDKs and to older engines:

* **A worker on an older Rust, Node, Python, or Go SDK does not declare the feature.** The engine
  then sets the limit from the SDK version that the worker reports. The worker gets the larger limit
  when the version is 0.24.5 or later. It gets the smaller limit when the version is missing, when
  the engine cannot read it, or when it is older than 0.24.5.
* **The engine reads the version as semver or as PEP 440.** Examples of semver are `0.24.6` and
  `0.25.0-rc.5`. Examples of PEP 440 are `0.25.0rc5` and `0.24.5.post1`. A pre-release of 0.24.5 is
  older than 0.24.5.
* **A Rust worker can report its own version.** SDKs 0.24.5 through 0.25.0-rc.5 do not declare
  `large-messages.v1`. A Rust worker on one of these SDKs can set `WorkerMetadata.version` to its
  own version. If that version is older than 0.24.5, the worker gets the smaller limit. Upgrade the
  worker to SDK 0.25.0 or later.
* **The engine accepts the large single frames that SDKs before 0.24.5 send.** The engine accepts a
  message as one frame or as fragments.
* **An engine from before the receive limit check does not check the limit of the target.** It sends
  each message as one frame. A worker on an older SDK can then disconnect. Use an engine and SDKs
  from the same release, or newer.

### Find what to change

Search each worker for the removed APIs. A few hits, such as `sendMessage` on another library's
socket, may be unrelated:

```bash theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
# TypeScript and JavaScript
git grep -nE 'createChannel|ChannelReader|ChannelWriter|readerRef|writerRef|iii-sdk/channel|extractChannelRefs|isChannelRef|StreamChannelRef|ChannelDirection|ChannelItem|sendMessage|onMessage|\.(reader|writer|request_body|response)\.stream' -- '*.ts' '*.tsx' '*.js' '*.mjs' '*.cjs'

# Python
git grep -nE 'create_channel|ChannelReader|ChannelWriter|reader_ref|writer_ref|iii\.channel|extract_channel_refs|is_channel_ref|StreamChannelRef|ChannelDirection|ChannelItem|send_message|on_message|close_async' -- '*.py'

# Rust
git grep -nE 'create_channel|ChannelReader|ChannelWriter|reader_ref|writer_ref|iii_sdk::channel|extract_channel_refs|is_channel_ref|StreamChannelRef|ChannelDirection|ChannelItem|send_message|on_message' -- '*.rs'

# Go
git grep -nE 'CreateChannel|OpenReader|OpenWriter|ChannelReader|ChannelWriter|ExtractChannelRefs|ReaderRef|WriterRef|SendMessage|OnMessage|NextBinary|ErrResponseClosed|NewStreamResponse|iiihttp\.Wrap\(' -- '*.go'

# Browser (iii-browser-sdk)
git grep -nE 'createChannel|ChannelReader|ChannelWriter|readerRef|writerRef|extractChannelRefs|isChannelRef|StreamChannelRef|ChannelDirection|ChannelItem|sendMessage|sendBinary|onMessage|onBinary|iii-browser-sdk/helpers' -- '*.ts' '*.tsx' '*.js' '*.mjs'
```

Then work through the sections below:

1. [Send a stream](#send-a-stream) where a caller creates a channel and passes its `readerRef`.
2. [Return a stream](#return-a-stream) or
   [write into the caller's sink](#write-into-the-callers-sink) where a caller creates a channel and
   passes its `writerRef`.
3. [HTTP `request_body` and `response`](#http-request_body-and-response) in route handlers that
   stream.
4. [Messages](#messages) where code calls `sendMessage` or `onMessage`.
5. [Abort](#abort) where a writer destroys its stream or is dropped on failure.
6. [Ref helpers](#ref-helpers-move-to-the-protocol-module) where code finds refs by hand.
7. [`createChannel` to `iii.pipe()`](#createchannel-to-iiipipe) where a pipe has to exist before its
   data.
8. [The browser SDK](#the-browser-sdk) for a page that streams.
9. Check the [behavior changes](#behavior-changes), [`iii call`](#iii-call), and the
   [checklist](#checklist).

## What changed

| 0.26 | 0.27 |
| - | - |
| TypeScript: `createChannel(worker, bufferSize?)` from `iii-sdk/helpers` | a source or a sink in the payload, or `worker.pipe({ bufferSize })` |
| TypeScript: `Channel`, `ChannelReader`, `ChannelWriter`, and the `iii-sdk/channel` subpath | `InputStream` and `OutputStream` from `iii-sdk` |
| TypeScript: `channel.readerRef`, `channel.writerRef` in a payload | the stream itself in the payload: a source, a sink, `pipe.input`, or `pipe.output` |
| TypeScript: `reader.stream` (a Node `Readable`), `reader.readAll()` | iterate the `InputStream`, `await input.bytes()`, or `input.toReadable()` |
| TypeScript: `writer.stream.write(chunk)`, `writer.stream.end()`, `writer.close()` | `await output.write(chunk)`, `await output.close()`, or `output.toWritable()` |
| TypeScript: `writer.sendMessage(text)`, `reader.onMessage(callback)` | `await output.send(value)`, `for await (const msg of input.messages())` |
| TypeScript: `writer.stream.destroy()` | `await output.abort(reason)`, or throw from the handler |
| TypeScript: `extractChannelRefs`, `isChannelRef`, `ChannelDirection`, `ChannelItem` from `iii-sdk/helpers` | the same names from `iii-sdk/protocol`, with `StreamChannelRef` |
| Python: `create_channel(worker)`, `create_channel_async(worker)` from `iii.helpers` | a source or a sink in the payload, or `worker.pipe()`, `await worker.pipe_async()` |
| Python: `Channel`, `ChannelReader`, `ChannelWriter` from `iii`, `iii.helpers`, and `iii.channel` | `InputStream` and `OutputStream` from `iii` |
| Python: `channel.reader_ref.model_dump()`, `channel.writer_ref.model_dump()` in a payload | the stream itself in the payload |
| Python: `await writer.write(data)`, `writer.close()`, `await writer.close_async()` | `await output.write(data)`, `await output.close()` |
| Python: `writer.send_message(text)`, `await writer.send_message_async(text)`, `reader.on_message(callback)` | `await output.send(value)`, `async for msg in input.messages()` |
| Python: `async for chunk in reader`, `await reader.read_all()` | the same on an `InputStream` |
| Python: `extract_channel_refs`, `is_channel_ref`, `ChannelDirection`, `ChannelItem`, `StreamChannelRef` | the same names from `iii.protocol` |
| Rust: `iii_sdk::helpers::create_channel(&worker, buffer_size)` | a source or a sink in the payload, or `worker.pipe().await?` |
| Rust: `iii_sdk::channel::{Channel, ChannelReader, ChannelWriter}`, `ChannelReader::new(&address, &r)`, `ChannelWriter::new(&address, &r)` | `InputStream` and `OutputStream` fields in your input and output types, from `iii_sdk` |
| Rust: `writer.send_message(&text)`, `reader.on_message(callback)` | `output.send(&value).await`, `input.messages::<T>()` |
| Rust: drop the writer without `close()` to abort | `output.abort(reason).await`, or return `Err` from the handler |
| Rust: `iii_sdk::helpers::{extract_channel_refs, is_channel_ref, ChannelDirection, ChannelItem}`, `iii_sdk::channel::StreamChannelRef` | the same names from `iii_sdk::protocol` |
| Go: `client.CreateChannel(ctx, bufferSize)` | a source or a sink in the payload, or `client.Pipe(ctx)` |
| Go: `channel.ReaderRef`, `channel.WriterRef` in a payload | the stream itself in the payload: `iii.InputStreamFromReader`, `iii.InputStreamFromBytes`, `iii.OutputStreamToWriter`, or an end of `client.Pipe` |
| Go: `iii.ExtractChannelRefs(data)`, `client.OpenReader(ref)`, `client.OpenWriter(ref)` | `*iii.InputStream` and `*iii.OutputStream` fields in the struct you unmarshal into |
| Go: `reader.NextBinary(ctx)`, `reader.ReadAll(ctx)`, `reader.Close()` | `input.Read(p)` (an `io.Reader`), `input.ReadAll(ctx)`, `input.Lines(ctx)`, `input.Frames(ctx)`, `input.Cancel()` |
| Go: `writer.Write(ctx, data)`, `writer.Close()` | `output.Write(ctx, data)`, `output.Close()`, or `output.Writer(ctx)` |
| Go: `writer.SendMessage(ctx, text)`, `reader.OnMessage(callback)` | `output.Send(ctx, value)`, `for msg, err := range input.Messages(ctx)` |
| Go: `writer.Close()` after a failed `Write` to abort | `output.Abort(reason)`, or return an error from the handler |
| Go: `iii.StreamChannelRef`, `iii.ChannelDirection` | unchanged, in package `iii`; `ExtractChannelRefs` is removed |
| Browser: `createChannel(worker, bufferSize?)` from `iii-browser-sdk/helpers` | a source or a sink in the payload, or `worker.pipe({ bufferSize })` |
| Browser: `Channel`, `ChannelReader`, `ChannelWriter`, `channel.readerRef`, `channel.writerRef` | `InputStream` and `OutputStream` from `iii-browser-sdk`, and the stream itself in the payload |
| Browser: `writer.sendBinary(data)`, `writer.sendMessage(text)`, `writer.close()` | `await output.write(data)`, `await output.send(value)`, `await output.close()` |
| Browser: `reader.onBinary(callback)`, `reader.onMessage(callback)`, `await reader.readAll()` | `for await (const chunk of input)`, `for await (const msg of input.messages())`, `await input.bytes()` |
| Browser: `extractChannelRefs`, `isChannelRef`, `ChannelDirection`, `ChannelItem` from `iii-browser-sdk/helpers`, `StreamChannelRef` from `iii-browser-sdk` | the same names from `iii-browser-sdk/protocol` |
| an abort on read: Node stream `'error'`, Python `ConnectionError`, Rust `Err`, Go `websocket.CloseError` | `StreamAbortedError` (TypeScript, browser, Python), `Error::StreamAborted` (Rust), `*iii.InvocationError` (Go), code `STREAM_ABORTED` |

The SDK also detects streams in what it sends and turns refs back into streams in what it receives,
in handler input and, new in 0.27, in call results. See
[Using iii / Streaming](https://iii.dev/docs/using-iii/streaming.md) for the full API.

## Send a stream

Put the source in the payload. The SDK creates the pipe, sends the ref, and pumps the data while the
call runs, so the caller no longer writes a channel next to the call. The handler reads the field
the same way as before, without `.stream` in TypeScript. The payload field keeps its name: it is
your function's contract.

> [tab] Node / TypeScript
>
> **Before (0.26)**
>
> ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> import { createReadStream } from "node:fs";
> import type { ChannelReader } from "iii-sdk/channel";
> import { createChannel } from "iii-sdk/helpers";
>
> // Caller
> const channel = await createChannel(worker);
> createReadStream("report.csv").pipe(channel.writer.stream);
> const result = await worker.call({
>   function_id: "files::process",
>   payload: { filename: "report.csv", reader: channel.readerRef },
> });
>
> // Handler
> worker.registerFunction("files::process", async (input: { reader: ChannelReader }) => {
>   let bytes = 0;
>   for await (const chunk of input.reader.stream) bytes += chunk.length;
>   return { bytes };
> });
> ```
>
> **After (0.27)**
>
> ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> import { createReadStream } from "node:fs";
> import type { InputStream } from "iii-sdk";
>
> // Caller
> const result = await worker.call({
>   function_id: "files::process",
>   payload: { filename: "report.csv", reader: createReadStream("report.csv") },
> });
>
> // Handler
> worker.registerFunction("files::process", async (input: { reader: InputStream }) => {
>   let bytes = 0;
>   for await (const chunk of input.reader) bytes += chunk.length;
>   return { bytes };
> });
> ```

> [tab] Python
>
> **Before (0.26)**
>
> ```python theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> import asyncio
>
> from iii.helpers import create_channel_async
>
> # Caller: write the channel while the call reads it
> channel = await create_channel_async(worker)
>
>
> async def upload() -> None:
>     with open("report.csv", "rb") as f:
>         while chunk := f.read(64 * 1024):
>             await channel.writer.write(chunk)
>     await channel.writer.close_async()
>
>
> _, result = await asyncio.gather(
>     upload(),
>     worker.call_async(
>         {
>             "function_id": "files::process",
>             "payload": {"filename": "report.csv", "reader": channel.reader_ref.model_dump()},
>         }
>     ),
> )
>
>
> # Handler
> async def process(payload: dict) -> dict:
>     total = 0
>     async for chunk in payload["reader"]:
>         total += len(chunk)
>     return {"bytes": total}
> ```
>
> **After (0.27)**
>
> ```python theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> from iii import InputStream
>
> # Caller
> result = await worker.call_async(
>     {
>         "function_id": "files::process",
>         "payload": {"filename": "report.csv", "reader": InputStream.from_file("report.csv")},
>     }
> )
>
>
> # Handler: unchanged, payload["reader"] is an InputStream
> async def process(payload: dict) -> dict:
>     reader: InputStream = payload["reader"]
>     total = 0
>     async for chunk in reader:
>         total += len(chunk)
>     return {"bytes": total}
> ```

> [tab] Rust
>
> **Before (0.26)**
>
> ```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> use iii_sdk::channel::ChannelReader;
> use iii_sdk::helpers::{create_channel, extract_channel_refs, ChannelDirection};
>
> // Caller: write the channel while the call reads it
> let data = tokio::fs::read("report.csv").await?;
> let channel = create_channel(&worker, None).await?;
> let upload = async {
>     channel.writer.write(&data).await?;
>     channel.writer.close().await
> };
> let call = worker.call(CallRequest::new(
>     "files::process",
>     json!({ "filename": "report.csv", "reader": channel.reader_ref }),
> ));
> let (_, result) = tokio::try_join!(upload, call)?;
>
> // Handler: find the ref by hand and open it with the engine address
> let address = worker.address().to_string();
> worker.register_function(
>     "files::process",
>     RegisterFunction::new_async(move |input: Value| {
>         let address = address.clone();
>         async move {
>             let refs = extract_channel_refs(&input);
>             let (_, reader_ref) = refs
>                 .iter()
>                 .find(|(key, r)| key == "reader" && matches!(r.direction, ChannelDirection::Read))
>                 .ok_or_else(|| Error::Handler("missing reader channel ref".into()))?;
>             let bytes = ChannelReader::new(&address, reader_ref).read_all().await?.len();
>             Ok(json!({ "bytes": bytes }))
>         }
>     }),
> );
> ```
>
> **After (0.27)**
>
> ```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> use iii_sdk::InputStream;
> use tokio::fs::File;
>
> // Caller
> let result = worker
>     .call(CallRequest::new(
>         "files::process",
>         json!({
>             "filename": "report.csv",
>             "reader": InputStream::from_reader(File::open("report.csv").await?),
>         }),
>     ))
>     .await?;
>
> // Handler: a typed field, no ref lookup and no engine address
> #[derive(Deserialize, JsonSchema)]
> struct Upload {
>     reader: InputStream,
> }
>
> worker.register_function(
>     "files::process",
>     RegisterFunction::new_async(|upload: Upload| async move {
>         let bytes = upload.reader.read_all().await?.len();
>         Ok::<_, Error>(json!({ "bytes": bytes }))
>     }),
> );
> ```

> [tab] Go
>
> **Before (0.26)**
>
> ```go theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> // Caller: write the channel while the call reads it
> data, err := os.ReadFile("report.csv")
> if err != nil {
> 	return err
> }
> channel, err := worker.CreateChannel(ctx, nil)
> if err != nil {
> 	return err
> }
> go func() {
> 	_ = channel.Writer.Write(ctx, data)
> 	_ = channel.Writer.Close()
> }()
> payload, err := json.Marshal(map[string]any{"filename": "report.csv", "reader": channel.ReaderRef})
> if err != nil {
> 	return err
> }
> result, err := worker.Call(ctx, iii.CallRequest{FunctionID: "files::process", Payload: payload})
>
> // Handler: find the ref by hand and open it
> worker.RegisterFunction("files::process", func(ctx context.Context, data json.RawMessage) (any, error) {
> 	refs, err := iii.ExtractChannelRefs(data)
> 	if err != nil {
> 		return nil, err
> 	}
> 	reader := worker.OpenReader(refs["reader"])
> 	defer reader.Close()
> 	body, err := reader.ReadAll(ctx)
> 	if err != nil {
> 		return nil, err
> 	}
> 	return map[string]int{"bytes": len(body)}, nil
> })
> ```
>
> **After (0.27)**
>
> ```go theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> // Caller
> file, err := os.Open("report.csv")
> if err != nil {
> 	return err
> }
> payload, err := json.Marshal(map[string]any{"filename": "report.csv", "reader": iii.InputStreamFromReader(file)})
> if err != nil {
> 	return err
> }
> result, err := worker.Call(ctx, iii.CallRequest{FunctionID: "files::process", Payload: payload})
>
> // Handler: a typed field, no ref lookup
> type upload struct {
> 	Reader *iii.InputStream `json:"reader"`
> }
>
> iii.RegisterFunctionTyped(worker, "files::process", func(ctx context.Context, in upload) (map[string]int64, error) {
> 	bytes, err := io.Copy(io.Discard, in.Reader)
> 	if err != nil {
> 		return nil, err
> 	}
> 	return map[string]int64{"bytes": bytes}, nil
> })
> ```

## Return a stream

In 0.26, refs in a result were not turned into readers, so a function that produced a stream needed
its caller to create a channel and pass a `writerRef` in. In 0.27 the function returns the stream
and the caller reads it from the result. The caller no longer passes a writer, so this changes the
function's payload: move its callers in the same change. When the caller has a place for the bytes,
such as a file, [pass a sink](#write-into-the-callers-sink) instead.

> [tab] Node / TypeScript
>
> **Before (0.26)**
>
> ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> import { once } from "node:events";
> import type { ChannelWriter } from "iii-sdk/channel";
> import { createChannel } from "iii-sdk/helpers";
>
> // Caller: create the channel and pass the writer ref in
> const channel = await createChannel(worker);
> const done = worker.call({
>   function_id: "reports::export",
>   payload: { report_id: "r-42", writer: channel.writerRef },
> });
> done.catch(() => {});
> for await (const chunk of channel.reader.stream) render(chunk);
> await done;
>
> // Handler: write into the caller's channel
> worker.registerFunction(
>   "reports::export",
>   async (input: { report_id: string; writer: ChannelWriter }) => {
>     for await (const row of db.rows(input.report_id)) {
>       if (!input.writer.stream.write(`${row.id},${row.total}\n`)) {
>         await once(input.writer.stream, "drain");
>       }
>     }
>     input.writer.stream.end();
>     return { ok: true };
>   },
> );
> ```
>
> **After (0.27)**
>
> ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> import type { InputStream } from "iii-sdk";
>
> async function* csvLines(reportId: string) {
>   for await (const row of db.rows(reportId)) yield `${row.id},${row.total}\n`;
> }
>
> // Handler: return the stream
> worker.registerFunction("reports::export", async (input: { report_id: string }) => ({
>   csv: csvLines(input.report_id),
> }));
>
> // Caller: the field arrives as an InputStream
> const { csv }: { csv: InputStream } = await worker.call({
>   function_id: "reports::export",
>   payload: { report_id: "r-42" },
> });
> for await (const line of csv.lines()) render(line);
> ```

> [tab] Python
>
> **Before (0.26)**
>
> ```python theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> import asyncio
>
> from iii.helpers import create_channel_async
>
> # Caller: create the channel and pass the writer ref in
> channel = await create_channel_async(worker)
> call = asyncio.create_task(
>     worker.call_async(
>         {
>             "function_id": "reports::export",
>             "payload": {"report_id": "r-42", "writer": channel.writer_ref.model_dump()},
>         }
>     )
> )
> async for chunk in channel.reader:
>     render(chunk)
> await call
>
>
> # Handler: write into the caller's channel
> async def export(payload: dict) -> dict:
>     writer = payload["writer"]
>     async for row in db.rows(payload["report_id"]):
>         await writer.write(f"{row.id},{row.total}\n".encode())
>     await writer.close_async()
>     return {"ok": True}
> ```
>
> **After (0.27)**
>
> ```python theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> async def csv_lines(report_id: str):
>     async for row in db.rows(report_id):
>         yield f"{row.id},{row.total}\n".encode()
>
>
> # Handler: return the stream
> async def export(payload: dict) -> dict:
>     return {"csv": csv_lines(payload["report_id"])}
>
>
> # Caller: the field arrives as an InputStream
> result = await worker.call_async(
>     {"function_id": "reports::export", "payload": {"report_id": "r-42"}}
> )
> async for line in result["csv"].lines():
>     render(line)
> ```

> [tab] Rust
>
> **Before (0.26)**
>
> ```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> use iii_sdk::helpers::create_channel;
>
> // Caller: create the channel, pass the writer ref in, read the other end
> let channel = create_channel(&worker, None).await?;
> let call = worker.call(CallRequest::new(
>     "reports::export",
>     json!({ "report_id": "r-42", "writer": channel.writer_ref }),
> ));
> let read = channel.reader.read_all();
> let (_, csv) = tokio::try_join!(call, read)?;
>
> // Handler: find the writer ref, open it with the engine address, write, and close
> ```
>
> **After (0.27)**
>
> ```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> use bytes::Bytes;
> use futures::TryStreamExt;
> use iii_sdk::InputStream;
>
> #[derive(Deserialize, JsonSchema)]
> struct ExportRequest {
>     report_id: String,
> }
>
> #[derive(Serialize, Deserialize, JsonSchema)]
> struct Export {
>     csv: InputStream,
> }
>
> // Handler: return the stream
> worker.register_function(
>     "reports::export",
>     RegisterFunction::new_async(|req: ExportRequest| async move {
>         let lines = db
>             .rows(req.report_id)
>             .map_ok(|row| Bytes::from(format!("{},{}\n", row.id, row.total)));
>         Ok::<_, Error>(Export { csv: InputStream::from_stream(lines) })
>     }),
> );
>
> // Caller: the field arrives as an InputStream
> let export: Export = serde_json::from_value(
>     worker
>         .call(CallRequest::new("reports::export", json!({ "report_id": "r-42" })))
>         .await?,
> )?;
> let csv = export.csv.read_all().await?;
> ```

> [tab] Go
>
> **Before (0.26)**
>
> ```go theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> // Caller: create the channel, pass the writer ref in, read the other end
> channel, err := worker.CreateChannel(ctx, nil)
> if err != nil {
> 	return err
> }
> payload, err := json.Marshal(map[string]any{"report_id": "r-42", "writer": channel.WriterRef})
> if err != nil {
> 	return err
> }
> done := make(chan error, 1)
> go func() {
> 	_, err := worker.Call(ctx, iii.CallRequest{FunctionID: "reports::export", Payload: payload})
> 	done <- err
> }()
> csv, err := channel.Reader.ReadAll(ctx)
> if err != nil {
> 	return err
> }
> if err := <-done; err != nil {
> 	return err
> }
>
> // Handler: find the writer ref, open it, write, and close
> worker.RegisterFunction("reports::export", func(ctx context.Context, data json.RawMessage) (any, error) {
> 	var req struct {
> 		ReportID string `json:"report_id"`
> 	}
> 	if err := json.Unmarshal(data, &req); err != nil {
> 		return nil, err
> 	}
> 	refs, err := iii.ExtractChannelRefs(data)
> 	if err != nil {
> 		return nil, err
> 	}
> 	writer := worker.OpenWriter(refs["writer"])
> 	for _, line := range csvLines(req.ReportID) {
> 		if err := writer.Write(ctx, []byte(line)); err != nil {
> 			_ = writer.Close() // a Close after a failed Write aborts the stream
> 			return nil, err
> 		}
> 	}
> 	return map[string]bool{"ok": true}, writer.Close()
> })
> ```
>
> **After (0.27)**
>
> ```go theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> type exportRequest struct {
> 	ReportID string `json:"report_id"`
> }
>
> type export struct {
> 	CSV *iii.InputStream `json:"csv"`
> }
>
> // Handler: return the stream
> iii.RegisterFunctionTyped(worker, "reports::export", func(ctx context.Context, req exportRequest) (export, error) {
> 	pr, pw := io.Pipe()
> 	go func() {
> 		// nil ends the stream, an error aborts it
> 		pw.CloseWithError(writeCSV(pw, req.ReportID))
> 	}()
> 	return export{CSV: iii.InputStreamFromReader(pr)}, nil
> })
>
> // Caller: the field arrives as an *iii.InputStream
> out, err := worker.Call(ctx, iii.CallRequest{
> 	FunctionID: "reports::export",
> 	Payload:    json.RawMessage(`{"report_id":"r-42"}`),
> })
> if err != nil {
> 	return err
> }
> var res export
> if err := json.Unmarshal(out, &res); err != nil {
> 	return err
> }
> csv, err := res.CSV.ReadAll(ctx)
> ```

## Write into the caller's sink

When the caller copied the reader end of its channel into a file or another writable, pass that sink
in the payload instead. The handler receives an `OutputStream`, and the caller's call resolves once
the sink has received everything.

> [tab] Node / TypeScript
>
> **Before (0.26)**
>
> ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> import { createWriteStream } from "node:fs";
> import { pipeline } from "node:stream/promises";
> import type { ChannelWriter } from "iii-sdk/channel";
> import { createChannel } from "iii-sdk/helpers";
>
> // Caller: pass the writer ref, copy the reader end into the file
> const channel = await createChannel(worker);
> await Promise.all([
>   worker.call({
>     function_id: "reports::render-pdf",
>     payload: { report_id: "r-42", out: channel.writerRef },
>   }),
>   pipeline(channel.reader.stream, createWriteStream("r-42.pdf")),
> ]);
>
> // Handler
> worker.registerFunction(
>   "reports::render-pdf",
>   async (input: { report_id: string; out: ChannelWriter }) => {
>     for await (const page of renderPages(input.report_id)) input.out.stream.write(page);
>     input.out.stream.end();
>   },
> );
> ```
>
> **After (0.27)**
>
> ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> import { createWriteStream } from "node:fs";
> import type { OutputStream } from "iii-sdk";
>
> // Caller: pass the file; the call resolves once it is written
> await worker.call({
>   function_id: "reports::render-pdf",
>   payload: { report_id: "r-42", out: createWriteStream("r-42.pdf") },
> });
>
> // Handler: returning closes `out`, throwing aborts it
> worker.registerFunction(
>   "reports::render-pdf",
>   async (input: { report_id: string; out: OutputStream }) => {
>     for await (const page of renderPages(input.report_id)) await input.out.write(page);
>   },
> );
> ```

> [tab] Python
>
> **Before (0.26)**
>
> ```python theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> import asyncio
>
> from iii.helpers import create_channel_async
>
> # Caller: pass the writer ref, copy the reader end into the file
> channel = await create_channel_async(worker)
>
>
> async def save() -> None:
>     with open("r-42.pdf", "wb") as f:
>         async for chunk in channel.reader:
>             f.write(chunk)
>
>
> await asyncio.gather(
>     worker.call_async(
>         {
>             "function_id": "reports::render-pdf",
>             "payload": {"report_id": "r-42", "out": channel.writer_ref.model_dump()},
>         }
>     ),
>     save(),
> )
>
>
> # Handler
> async def render_pdf(payload: dict) -> None:
>     out = payload["out"]
>     async for page in render_pages(payload["report_id"]):
>         await out.write(page)
>     await out.close_async()
> ```
>
> **After (0.27)**
>
> ```python theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> from iii import OutputStream
>
> # Caller: pass the file; the call resolves once it is written
> await worker.call_async(
>     {
>         "function_id": "reports::render-pdf",
>         "payload": {"report_id": "r-42", "out": OutputStream.to_file("r-42.pdf")},
>     }
> )
>
>
> # Handler: returning closes `out`, raising aborts it
> async def render_pdf(payload: dict) -> None:
>     out: OutputStream = payload["out"]
>     async for page in render_pages(payload["report_id"]):
>         await out.write(page)
> ```

> [tab] Rust
>
> **Before (0.26)**
>
> ```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> use iii_sdk::helpers::create_channel;
>
> // Caller: pass the writer ref, copy the reader end into the file
> let channel = create_channel(&worker, None).await?;
> let call = worker.call(CallRequest::new(
>     "reports::render-pdf",
>     json!({ "report_id": "r-42", "out": channel.writer_ref }),
> ));
> let read = channel.reader.read_all();
> let (_, pdf) = tokio::try_join!(call, read)?;
> tokio::fs::write("r-42.pdf", pdf).await?;
> ```
>
> **After (0.27)**
>
> ```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> use iii_sdk::OutputStream;
> use tokio::fs::File;
>
> // Caller: pass the file; the call resolves once it is written
> worker
>     .call(CallRequest::new(
>         "reports::render-pdf",
>         json!({
>             "report_id": "r-42",
>             "out": OutputStream::to_writer(File::create("r-42.pdf").await?),
>         }),
>     ))
>     .await?;
>
> // Handler: Ok closes `out`, Err aborts it
> #[derive(Deserialize, JsonSchema)]
> struct RenderPdf {
>     report_id: String,
>     out: OutputStream,
> }
>
> worker.register_function(
>     "reports::render-pdf",
>     RegisterFunction::new_async(|req: RenderPdf| async move {
>         for page in render_pages(&req.report_id).await? {
>             req.out.write(&page).await?;
>         }
>         Ok::<_, Error>(())
>     }),
> );
> ```

> [tab] Go
>
> **Before (0.26)**
>
> ```go theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> // Caller: pass the writer ref, read the reader end into the file
> channel, err := worker.CreateChannel(ctx, nil)
> if err != nil {
> 	return err
> }
> payload, err := json.Marshal(map[string]any{"report_id": "r-42", "out": channel.WriterRef})
> if err != nil {
> 	return err
> }
> done := make(chan error, 1)
> go func() {
> 	_, err := worker.Call(ctx, iii.CallRequest{FunctionID: "reports::render-pdf", Payload: payload})
> 	done <- err
> }()
> pdf, err := channel.Reader.ReadAll(ctx)
> if err != nil {
> 	return err
> }
> if err := <-done; err != nil {
> 	return err
> }
> if err := os.WriteFile("r-42.pdf", pdf, 0o644); err != nil {
> 	return err
> }
>
> // Handler: open the writer ref the caller passed
> worker.RegisterFunction("reports::render-pdf", func(ctx context.Context, data json.RawMessage) (any, error) {
> 	refs, err := iii.ExtractChannelRefs(data)
> 	if err != nil {
> 		return nil, err
> 	}
> 	writer := worker.OpenWriter(refs["out"])
> 	for _, page := range renderPages("r-42") {
> 		if err := writer.Write(ctx, page); err != nil {
> 			_ = writer.Close() // a Close after a failed Write aborts the stream
> 			return nil, err
> 		}
> 	}
> 	return nil, writer.Close()
> })
> ```
>
> **After (0.27)**
>
> ```go theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> // Caller: pass the file; the call returns once it is written
> file, err := os.Create("r-42.pdf")
> if err != nil {
> 	return err
> }
> defer file.Close() // the SDK closes it when the stream ends; this covers a failed call
> payload, err := json.Marshal(map[string]any{"report_id": "r-42", "out": iii.OutputStreamToWriter(file)})
> if err != nil {
> 	return err
> }
> if _, err := worker.Call(ctx, iii.CallRequest{FunctionID: "reports::render-pdf", Payload: payload}); err != nil {
> 	return err
> }
>
> // Handler: returning closes Out, an error aborts it
> type renderPDF struct {
> 	ReportID string            `json:"report_id"`
> 	Out      *iii.OutputStream `json:"out"`
> }
>
> worker.RegisterFunction("reports::render-pdf", func(ctx context.Context, data json.RawMessage) (any, error) {
> 	var req renderPDF
> 	if err := json.Unmarshal(data, &req); err != nil {
> 		return nil, err
> 	}
> 	for _, page := range renderPages(req.ReportID) {
> 		if err := req.Out.Write(ctx, page); err != nil {
> 			return nil, err
> 		}
> 	}
> 	return nil, nil
> })
> ```

A sink takes bytes only: messages the handler sends on the `OutputStream` are dropped, and the call
still succeeds. If the caller also read the channel's messages (`onMessage`), pass the output of a
[pipe](#createchannel-to-iiipipe) instead and read its input.

## HTTP `request_body` and `response`

The HTTP worker still passes a route's request body and response as refs in `request_body` and
`response`, and it reads the status and the headers from the same JSON messages. Only their SDK
types change: `request_body` is an `InputStream` and `response` is an `OutputStream`. The
`request_body` of the TypeScript `HttpRequest` and `StreamRequest` types and of the Python
`StreamRequest` is an `InputStream` too. In Go, the `RequestBody` of `iiihttp.Request`,
`iiihttp.InternalRequest`, and `iiihttp.StreamRequest` is an `*iii.InputStream`, and
`InternalRequest.Response` is an `*iii.OutputStream`.

> [tab] Node / TypeScript
>
> **Before (0.26)**
>
> ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> import type { ChannelReader, ChannelWriter } from "iii-sdk/channel";
>
> type Echo = { request_body: ChannelReader; response: ChannelWriter };
>
> worker.registerFunction("files::echo", async ({ request_body, response }: Echo) => {
>   response.sendMessage(JSON.stringify({ type: "set_status", status_code: 200 }));
>   response.sendMessage(
>     JSON.stringify({ type: "set_headers", headers: { "content-type": "text/plain" } }),
>   );
>   for await (const chunk of request_body.stream) response.stream.write(chunk);
>   response.stream.end();
> });
> ```
>
> **After (0.27)**
>
> ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> import type { InputStream, OutputStream } from "iii-sdk";
>
> type Echo = { request_body: InputStream; response: OutputStream };
>
> worker.registerFunction("files::echo", async ({ request_body, response }: Echo) => {
>   await response.send({ type: "set_status", status_code: 200 });
>   await response.send({ type: "set_headers", headers: { "content-type": "text/plain" } });
>   for await (const chunk of request_body) await response.write(chunk);
>   // Returning closes the response.
> });
> ```

> [tab] Python
>
> **Before (0.26)**
>
> ```python theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> import json
>
>
> async def echo(req: dict) -> None:
>     response = req["response"]
>     await response.send_message_async(json.dumps({"type": "set_status", "status_code": 200}))
>     await response.send_message_async(
>         json.dumps({"type": "set_headers", "headers": {"content-type": "text/plain"}})
>     )
>     async for chunk in req["request_body"]:
>         await response.write(chunk)
>     await response.close_async()
> ```
>
> **After (0.27)**
>
> ```python theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> from iii import OutputStream
>
>
> async def echo(req: dict) -> None:
>     response: OutputStream = req["response"]
>     await response.send({"type": "set_status", "status_code": 200})
>     await response.send({"type": "set_headers", "headers": {"content-type": "text/plain"}})
>     async for chunk in req["request_body"]:
>         await response.write(chunk)
>     # Returning closes the response.
> ```

> [tab] Rust
>
> **Before (0.26)**
>
> ```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> use iii_sdk::channel::{ChannelReader, ChannelWriter};
> use iii_sdk::helpers::extract_channel_refs;
>
> let address = worker.address().to_string();
> worker.register_function(
>     "files::echo",
>     RegisterFunction::new_async(move |input: Value| {
>         let address = address.clone();
>         async move {
>             let refs = extract_channel_refs(&input);
>             let find = |name: &str| {
>                 refs.iter()
>                     .find(|(key, _)| key == name)
>                     .map(|(_, r)| r.clone())
>                     .ok_or_else(|| Error::Handler(format!("missing {name}")))
>             };
>             let body = ChannelReader::new(&address, &find("request_body")?).read_all().await?;
>             let response = ChannelWriter::new(&address, &find("response")?);
>             response
>                 .send_message(&json!({ "type": "set_status", "status_code": 200 }).to_string())
>                 .await?;
>             response.write(&body).await?;
>             response.close().await?;
>             Ok(Value::Null)
>         }
>     }),
> );
> ```
>
> **After (0.27)**
>
> ```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> use iii_sdk::{InputStream, OutputStream};
>
> #[derive(Deserialize, JsonSchema)]
> struct Echo {
>     request_body: InputStream,
>     response: OutputStream,
> }
>
> worker.register_function(
>     "files::echo",
>     RegisterFunction::new_async(|req: Echo| async move {
>         let body = req.request_body.read_all().await?;
>         req.response.send(&json!({ "type": "set_status", "status_code": 200 })).await?;
>         req.response.write(&body).await?;
>         // Ok closes the response.
>         Ok::<_, Error>(())
>     }),
> );
> ```

> [tab] Go
>
> **Before (0.26)**
>
> ```go theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> // iiihttp is github.com/iii-hq/iii/sdk/packages/go/iii/helpers/http
> worker.RegisterFunction("files::echo", func(ctx context.Context, data json.RawMessage) (any, error) {
> 	var req iiihttp.InternalRequest
> 	if err := json.Unmarshal(data, &req); err != nil {
> 		return nil, err
> 	}
> 	body, err := worker.OpenReader(req.RequestBody).ReadAll(ctx)
> 	if err != nil {
> 		return nil, err
> 	}
> 	response := worker.OpenWriter(req.Response)
> 	if err := response.SendMessage(ctx, `{"type":"set_status","status_code":200}`); err != nil {
> 		_ = response.Close()
> 		return nil, err
> 	}
> 	if err := response.Write(ctx, body); err != nil {
> 		_ = response.Close()
> 		return nil, err
> 	}
> 	return nil, response.Close()
> })
> ```
>
> **After (0.27)**
>
> ```go theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> // iiihttp is github.com/iii-hq/iii/sdk/packages/go/iii/helpers/http
> worker.RegisterFunction("files::echo", func(ctx context.Context, data json.RawMessage) (any, error) {
> 	var req iiihttp.InternalRequest
> 	if err := json.Unmarshal(data, &req); err != nil {
> 		return nil, err
> 	}
> 	if err := req.Response.Send(ctx, map[string]any{"type": "set_status", "status_code": 200}); err != nil {
> 		return nil, err
> 	}
> 	if _, err := io.Copy(req.Response.Writer(ctx), req.RequestBody); err != nil {
> 		return nil, err
> 	}
> 	// Returning closes the response.
> 	return nil, nil
> })
> ```

A route handler that returns a buffered response (`{ status_code, body }`) without touching
`response` needs no change: the HTTP worker calls a route through an observer, and in that case the
SDK leaves an untouched `response` alone when the handler returns a value.

### Streaming response helpers

The `StreamResponse` helpers (the `res` of the TypeScript `http()` wrapper, of the Python
`StreamResponse`, and of the Go `iiihttp.Wrap`) wrap the `OutputStream` now. In TypeScript and
Python, every method that writes is asynchronous:

| 0.26 | 0.27 |
| - | - |
| TypeScript: `res.status(code)`, `res.headers(h)` returned nothing | `await res.status(code)`, `await res.headers(h)` |
| TypeScript: `res.stream.write(chunk)`, `res.close()` | `await res.write(chunk)`, `await res.close()` (`res.stream` stays, a `Writable`) |
| Python: `res.stream` (a writable wrapper), `res.close()` | `await res.write(data)`, `await res.close()`; `res.stream` is removed |
| Python: `res.writer` was a `ChannelWriter` | `res.writer` is the `OutputStream` |
| Go: `iiihttp.Wrap(client, fn)` | `iiihttp.Wrap(fn)`: the request's streams carry their client |
| Go: `iiihttp.NewStreamResponse(ctx, *iii.ChannelWriter)` | `iiihttp.NewStreamResponse(ctx, *iii.OutputStream)`, and `res.Stream()` returns it |
| Go: a write after `res.Close()` returned `iiihttp.ErrResponseClosed` | it fails with an `*iii.InvocationError` with the code `iii.CodeStreamClosed` |

In Go, `Status`, `Headers`, `Write`, and `Close` keep their signatures. `Wrap` closes the response
when the handler returns and aborts it when the handler fails, as before:

**Before (0.26)**

```go theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
worker.RegisterFunction("files::echo", iiihttp.Wrap(worker, func(ctx context.Context, req *iiihttp.StreamRequest, res *iiihttp.StreamResponse) (any, error) {
	if err := res.Status(200); err != nil {
		return nil, err
	}
	_, err := io.Copy(res, req)
	return nil, err
}))
```

**After (0.27)**

```go theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
worker.RegisterFunction("files::echo", iiihttp.Wrap(func(ctx context.Context, req *iiihttp.StreamRequest, res *iiihttp.StreamResponse) (any, error) {
	if err := res.Status(200); err != nil {
		return nil, err
	}
	_, err := io.Copy(res, req) // returning closes the response, an error aborts it
	return nil, err
}))
```

## Messages

`send` takes a value and sends it as JSON in one text frame, so drop your own `JSON.stringify` or
`json.dumps`. `messages()` parses each text frame, and yields a frame that is not JSON as its raw
string, so messages from a writer on a 0.26 SDK that sent plain text still arrive. A reader on a
0.26 SDK receives what `send` wrote as JSON text: a bare string arrives quoted.

> [tab] Node / TypeScript
>
> **Before (0.26)**
>
> ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> // Writer
> input.progress.sendMessage(JSON.stringify({ percent: 50 }));
>
> // Reader
> channel.reader.onMessage((msg) => update(JSON.parse(msg)));
> ```
>
> **After (0.27)**
>
> ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> // Writer
> await input.progress.send({ percent: 50 });
>
> // Reader
> for await (const msg of progress.messages<{ percent: number }>()) update(msg);
> ```

> [tab] Python
>
> **Before (0.26)**
>
> ```python theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> # Writer
> await payload["progress"].send_message_async(json.dumps({"percent": 50}))
>
> # Reader
> channel.reader.on_message(lambda msg: update(json.loads(msg)))
> ```
>
> **After (0.27)**
>
> ```python theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> # Writer
> await payload["progress"].send({"percent": 50})
>
> # Reader
> async for msg in progress.messages():
>     update(msg)
> ```

> [tab] Rust
>
> **Before (0.26)**
>
> ```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> // Writer
> writer.send_message(&serde_json::to_string(&Progress { percent: 50 })?).await?;
>
> // Reader
> reader
>     .on_message(|msg| {
>         if let Ok(progress) = serde_json::from_str::<Progress>(&msg) {
>             update(progress);
>         }
>     })
>     .await;
> ```
>
> **After (0.27)**
>
> ```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> use futures::TryStreamExt;
>
> // Writer
> req.progress.send(&Progress { percent: 50 }).await?;
>
> // Reader
> let mut messages = progress.messages::<Progress>();
> while let Some(progress) = messages.try_next().await? {
>     update(progress);
> }
> ```

> [tab] Go
>
> **Before (0.26)**
>
> ```go theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> // Writer
> if err := writer.SendMessage(ctx, `{"percent":50}`); err != nil {
> 	return err
> }
>
> // Reader
> channel.Reader.OnMessage(func(msg string) {
> 	var p struct {
> 		Percent int `json:"percent"`
> 	}
> 	if json.Unmarshal([]byte(msg), &p) == nil {
> 		update(p.Percent)
> 	}
> })
> ```
>
> **After (0.27)**
>
> ```go theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> // Writer
> if err := req.Progress.Send(ctx, map[string]int{"percent": 50}); err != nil {
> 	return err
> }
>
> // Reader
> for msg, err := range progress.Messages(ctx) {
> 	if err != nil {
> 		return err
> 	}
> 	var p struct {
> 		Percent int `json:"percent"`
> 	}
> 	if json.Unmarshal(msg, &p) == nil {
> 		update(p.Percent)
> 	}
> }
> ```

A reader that needs both the bytes and the messages, in order, iterates `frames()`.

## Abort

In 0.26 each SDK aborted differently: Node with `writer.stream.destroy()` and no argument, Rust by
dropping the writer without `close()`, Go with a `Close()` after a failed `Write`, and Python and
the browser had no abort call. In 0.27 the SDK aborts for you in the common cases, and
`abort(reason)` is one call everywhere:

* A source the SDK pumps (a generator, a readable, a file) that fails aborts its stream.
* A handler that throws aborts every received `OutputStream` it has written to.
* `await output.abort(reason)` aborts on purpose. If the stream's socket never opened, it opens it
  first, so the reader always learns of the failure.

A handler that throws before it touched a received `OutputStream` leaves that stream alone, as in
0.26: the caller learns of the failure from the call's error.

The reader gets a typed error after the data that was already sent.

> [tab] Node / TypeScript
>
> **Before (0.26)**
>
> ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> // Writer
> try {
>   for await (const page of renderPages(id)) input.out.stream.write(page);
> } catch (err) {
>   input.out.stream.destroy(); // no argument: destroy(err) crashes the worker
>   throw err;
> }
> input.out.stream.end();
>
> // Reader: the stream emits 'error', so the loop throws
> for await (const chunk of channel.reader.stream) save(chunk);
> ```
>
> **After (0.27)**
>
> ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> import { StreamAbortedError } from "iii-sdk";
>
> // Writer: throwing aborts `out`; returning closes it
> for await (const page of renderPages(id)) await input.out.write(page);
>
> // Reader
> try {
>   for await (const chunk of body) save(chunk);
> } catch (err) {
>   if (err instanceof StreamAbortedError) discard(); // err.code is "STREAM_ABORTED"
>   throw err;
> }
> ```

> [tab] Python
>
> **Before (0.26)**
>
> ```python theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> # Writer: no abort call; a writer garbage-collected without close() aborts
> async for page in render_pages(report_id):
>     await out.write(page)
> await out.close_async()
>
> # Reader
> try:
>     async for chunk in channel.reader:
>         save(chunk)
> except ConnectionError:
>     discard()
>     raise
> ```
>
> **After (0.27)**
>
> ```python theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> from iii import StreamAbortedError
>
> # Writer: raising aborts `out`, returning closes it; out.abort(reason) aborts on purpose
> async for page in render_pages(report_id):
>     await out.write(page)
>
> # Reader
> try:
>     async for chunk in body:
>         save(chunk)
> except StreamAbortedError:  # err.code is "STREAM_ABORTED"
>     discard()
>     raise
> ```

> [tab] Rust
>
> **Before (0.26)**
>
> ```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> // Writer: drop it without close() to abort
> for page in pages {
>     if let Err(err) = writer.write(&page).await {
>         drop(writer);
>         return Err(err);
>     }
> }
> writer.close().await?;
> ```
>
> **After (0.27)**
>
> ```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> // Writer: Err from the handler aborts `out`; Ok closes it; out.abort(reason) aborts on purpose
> for page in pages {
>     req.out.write(&page).await?;
> }
>
> // Reader
> match body.read_all().await {
>     Ok(data) => save(data),
>     Err(err @ Error::StreamAborted { .. }) => {
>         discard();
>         return Err(err);
>     }
>     Err(err) => return Err(err),
> }
> ```

> [tab] Go
>
> **Before (0.26)**
>
> ```go theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> // Writer: a Close after a failed Write aborts the stream
> for _, page := range pages {
> 	if err := writer.Write(ctx, page); err != nil {
> 		_ = writer.Close()
> 		return nil, err
> 	}
> }
> if err := writer.Close(); err != nil {
> 	return nil, err
> }
>
> // Reader: an abort is a websocket.CloseError
> data, err := reader.ReadAll(ctx)
> var closeErr websocket.CloseError
> if errors.As(err, &closeErr) {
> 	discard()
> }
> ```
>
> **After (0.27)**
>
> ```go theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> // Writer: returning an error aborts Out; Out.Abort(reason) aborts on purpose
> for _, page := range pages {
> 	if err := req.Out.Write(ctx, page); err != nil {
> 		return nil, err
> 	}
> }
>
> // Reader
> data, err := body.ReadAll(ctx)
> var streamErr *iii.InvocationError
> if errors.As(err, &streamErr) && streamErr.Code == iii.CodeStreamAborted {
> 	discard()
> }
> ```

The reader's `reason` is the engine's description of the close, such as
`channel writer aborted: closed with code 1011`: the engine does not relay the writer's own reason.
Report the cause in the call's error or result. A caller that passed a sink gets the abort as its
call's error, with the code `STREAM_ABORTED`, even when the function returned.

## Ref helpers move to the protocol module

The SDK now finds refs and turns them into streams, so most code that called `extractChannelRefs` or
`isChannelRef` can drop it. Code that still works with the raw ref JSON, such as a router that
inspects payloads, imports the helpers from the low-level protocol module:

| 0.26 | 0.27 |
| - | - |
| `import { extractChannelRefs, isChannelRef, ChannelDirection, ChannelItem } from "iii-sdk/helpers"` | `import { extractChannelRefs, isChannelRef, ChannelDirection, ChannelItem } from "iii-sdk/protocol"` |
| `import type { StreamChannelRef } from "iii-sdk/channel"` | `import type { StreamChannelRef } from "iii-sdk/protocol"` |
| `from iii.helpers import extract_channel_refs, is_channel_ref, ChannelDirection, ChannelItem` | `from iii.protocol import extract_channel_refs, is_channel_ref, ChannelDirection, ChannelItem` |
| `from iii.channel import StreamChannelRef` | `from iii.protocol import StreamChannelRef` |
| `use iii_sdk::helpers::{extract_channel_refs, is_channel_ref, ChannelDirection, ChannelItem};` | `use iii_sdk::protocol::{extract_channel_refs, is_channel_ref, ChannelDirection, ChannelItem};` |
| `use iii_sdk::channel::StreamChannelRef;` | `use iii_sdk::protocol::StreamChannelRef;` |
| `import { extractChannelRefs, isChannelRef, ChannelDirection, ChannelItem } from "iii-browser-sdk/helpers"` | `import { extractChannelRefs, isChannelRef, ChannelDirection, ChannelItem } from "iii-browser-sdk/protocol"` |
| `import type { StreamChannelRef } from "iii-browser-sdk"` | `import type { StreamChannelRef } from "iii-browser-sdk/protocol"` |

In Go, `iii.StreamChannelRef` and `iii.ChannelDirection` stay in package `iii`, and
`iii.ExtractChannelRefs` is removed: unmarshal the raw ref JSON into an `iii.StreamChannelRef`.

The helpers see refs as JSON. A handler on a 0.27 SDK receives streams, not refs, so call them on
the raw JSON you hold, such as a value read from storage.

## `createChannel` to `iii.pipe()`

Most channels become a value in the payload or the result, as above. Keep an explicit pipe when the
stream has to exist before its data, when it goes to a call made later, or for a two-way session
(two pipes). `iii.pipe()` returns its two ends, `input` and `output`; put the end the other side
uses in the payload, where 0.26 code put a ref.

> [tab] Node / TypeScript
>
> **Before (0.26)**
>
> ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> import { createChannel } from "iii-sdk/helpers";
>
> const channel = await createChannel(worker, 64);
> const done = worker.call({
>   function_id: "llm::complete",
>   payload: { prompt, tokens: channel.writerRef },
> });
> channel.reader.onMessage((msg) => print(JSON.parse(msg).token));
> await channel.reader.readAll();
> await done;
> ```
>
> **After (0.27)**
>
> ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> const { input, output } = await worker.pipe({ bufferSize: 64 });
> const done = worker.call({
>   function_id: "llm::complete",
>   payload: { prompt, tokens: output },
> });
> // A handler that fails before it writes leaves `output` open: stop reading when the call fails.
> done.catch(() => input.cancel());
> try {
>   for await (const { token } of input.messages<{ token: string }>()) print(token);
> } finally {
>   await done; // when the call failed, this throws its error instead of the read's
> }
> ```

> [tab] Python
>
> **Before (0.26)**
>
> ```python theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> from iii.helpers import create_channel_async
>
> channel = await create_channel_async(worker)
> payload = {"prompt": prompt, "tokens": channel.writer_ref.model_dump()}
> ```
>
> **After (0.27)**
>
> ```python theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> import asyncio
>
> pipe = await worker.pipe_async()  # worker.pipe() outside asyncio
>
>
> async def complete() -> None:
>     try:
>         await worker.call_async(
>             {"function_id": "llm::complete", "payload": {"prompt": prompt, "tokens": pipe.output}}
>         )
>     except Exception:
>         # A handler that fails before it writes leaves the output open: stop reading.
>         await pipe.input.cancel()
>         raise
>
>
> # Start the call before reading: nothing writes the output until the handler runs
> call = asyncio.create_task(complete())
> try:
>     async for message in pipe.input.messages():
>         print(message["token"], end="")
> finally:
>     await call  # when the call failed, this raises its error instead of the read's
> ```

> [tab] Rust
>
> **Before (0.26)**
>
> ```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> use iii_sdk::helpers::create_channel;
>
> let channel = create_channel(&worker, None).await?;
> let payload = json!({ "prompt": prompt, "tokens": channel.writer_ref });
> ```
>
> **After (0.27)**
>
> ```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> let pipe = worker.pipe().await?;
> let payload = json!({ "prompt": prompt, "tokens": pipe.output });
> let mut messages = pipe.input.messages::<Token>();
> ```

> [tab] Go
>
> **Before (0.26)**
>
> ```go theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> channel, err := worker.CreateChannel(ctx, nil)
> if err != nil {
> 	return err
> }
> payload, err := json.Marshal(map[string]any{"prompt": prompt, "tokens": channel.WriterRef})
> ```
>
> **After (0.27)**
>
> ```go theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> input, output, err := worker.Pipe(ctx)
> if err != nil {
> 	return err
> }
> payload, err := json.Marshal(map[string]any{"prompt": prompt, "tokens": output})
> if err != nil {
> 	return err
> }
> messages := input.Messages(ctx)
> ```

| 0.26 channel | 0.27 pipe |
| - | - |
| `channel.writer` | `pipe.output`, an `OutputStream` |
| `channel.reader` | `pipe.input`, an `InputStream` |
| `channel.readerRef` in a payload | `pipe.input` in the payload |
| `channel.writerRef` in a payload | `pipe.output` in the payload |

In Go, `client.Pipe(ctx)` returns the two ends as `(input, output, err)`: `channel.Writer` becomes
`output`, `channel.Reader` becomes `input`, and the ends go in the payload where `channel.ReaderRef`
and `channel.WriterRef` went. In the browser, `createChannel(worker, bufferSize)` becomes
`worker.pipe({ bufferSize })`.

The worker that calls `pipe()` owns the pipe, as with `createChannel`: keep it connected until the
other side has attached.

## The browser SDK

The browser SDK follows the TypeScript API, with Web streams only. A `File` or a `Blob` from an
`<input type="file">`, a `ReadableStream` such as `response.body` of a `fetch`, and an async
generator are sources. A `WritableStream`, such as the one a File System Access handle returns from
`createWritable()`, is a sink.

Send a file from a page:

**Before (0.26)**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
import { createChannel } from "iii-browser-sdk/helpers";

// Caller: write the file into the channel while the call reads it
const channel = await createChannel(worker);
const call = worker.call({
  function_id: "files::process",
  payload: { filename: file.name, reader: channel.readerRef },
});
channel.writer.sendBinary(new Uint8Array(await file.arrayBuffer()));
channel.writer.close();
const result = await call;
```

**After (0.27)**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
// Caller: the File is the stream
const result = await worker.call({
  function_id: "files::process",
  payload: { filename: file.name, reader: file },
});
```

Read a stream that a function returns:

**Before (0.26)**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
import { createChannel } from "iii-browser-sdk/helpers";

// Caller: pass the writer ref in, read the other end
const channel = await createChannel(worker);
const call = worker.call({
  function_id: "reports::export",
  payload: { report_id: "r-42", writer: channel.writerRef },
});
const csv = new TextDecoder().decode(await channel.reader.readAll());
await call;
for (const line of csv.split("\n")) if (line) render(line);
```

**After (0.27)**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
import type { InputStream } from "iii-browser-sdk";

// Caller: the field arrives as an InputStream
const { csv }: { csv: InputStream } = await worker.call({
  function_id: "reports::export",
  payload: { report_id: "r-42" },
});
for await (const line of csv.lines()) render(line);
```

There is no `toReadable()` or `toWritable()` in the browser: `toWebStream()` returns the Web stream
of an `InputStream` or an `OutputStream`. `abort(reason)` closes the stream's socket with code 4011,
because a browser can only send 1000 or a code from 3000 to 4999. The engine treats it as an abort,
so a reader on any 0.27 SDK gets `STREAM_ABORTED`, with the reason
`channel writer aborted: closed with code 4011`.

## Behavior changes

Beyond the renamed API, these rules are new for a worker on a 0.27 SDK:

* **A received `OutputStream` is closed when the handler returns, and aborted when it throws.** A
  0.26 handler that returned and kept writing in the background calls `keepOpen()` (Python and Rust
  `keep_open()`, Go `KeepOpen()`) first, and then closes or aborts the stream itself. A stream the
  handler never touched is closed as well when it returns, except in a call through an observer (an
  HTTP route, for example), where it is closed only when the handler returns nothing.
* **A received `InputStream` that the handler started reading and did not finish is cancelled when
  the handler returns.** Finish reading before returning: a read still running after it, in a
  background task for example, fails with `STREAM_CLOSED`.
* **Refs in call results arrive as streams.** In 0.26 a ref in a result stayed JSON. Code that read
  a ref out of a result and opened it now receives an `InputStream` or an `OutputStream` instead.
* **A stream has one reader.** A second read of the same `InputStream` fails; call `tee()` before
  the first read for copies in the same process. Go has no `tee()`: copy the bytes with
  `io.TeeReader` or `io.MultiWriter` as you read.
* **Streams need a live call.** A call sent with `CallAction.Enqueue` (Go
  `iii.EnqueueAction(queue)`) and a stream or a ref anywhere in its payload is refused before it is
  sent, with the code `STREAM_NOT_ALLOWED`. Store the data and enqueue its key. `CallAction.Void` is
  allowed.
* **Observers receive `StreamInfo`.** When an observer captures the `input` or `output` of a call
  that carried a stream, its target receives `{ stream: true, direction, id }` in that field (Go
  `iii.StreamInfo`). A 0.26 TypeScript, Python, or browser target got a live reader there, and a
  0.26 Go target got the ref; opening either raced the observed function for the bytes. See
  [Observe a stream](https://iii.dev/docs/using-iii/streaming.md#observe-a-stream).
* **Rust streams bind lazily.** An `InputStream` or `OutputStream` decoded from JSON binds to the
  handler's worker inside a handler, and to the only client in the process elsewhere. A process with
  several clients calls `stream.bind(&worker)` before using a stream decoded outside a handler.
* **Go streams bind lazily too.** A stream unmarshalled from a handler's input or from a call's
  result binds to that client. One unmarshalled from other JSON binds to the only client in the
  process; with several, call `stream.Bind(worker)` before using it.
* **The `payload_too_large` error links to the new page:**
  `https://iii.dev/docs/creating-workers/streaming#payload-size`.

## `iii call`

The 0.27 `iii call` changes for scripts:

* **Without `-n`, `iii call` resolves in `default`.** In 0.26 it took the namespace of
  `III_NAMESPACE` when that variable was set, and Compose sets it for every process it starts. A
  `scripts` line, or a script it runs, reached a function of the project's namespace with a plain
  `iii call <function>`. In 0.27 that call looks in `default` and does not find the function. Name
  the namespace with `iii call -n <namespace> <function>`. A project in `default` needs no change,
  and neither does a call to a function in `default`, such as the engine's `sandbox::build` and
  `sandbox::start`.
* **Arguments that cannot make a call exit with `2`.**
* **A function that fails prints its `Error:` JSON on one line** when standard error is not a
  terminal, so a script can parse it. Other failures print plain text.

## Checklist

* [ ] Commit `worker-compose.yaml` and `worker-compose.lock` before the first run of the 0.27 `iii`
* [ ] Rename each container key that fails with `INVALID_CONTAINER_KEY`, and the `start_after`
  entries that name it
* [ ] In a project with VM workers, follow [Upgrading VM workers from 0.26.x](https://iii.dev/docs/upgrading/explicit-vm-workers.md)
* [ ] Add `-n <namespace>` to each `iii call` in a script that targets a function outside `default`
* [ ] Upgrade one worker's SDK at a time; workers on 0.26 SDKs keep working unchanged on the same
  engine
* [ ] Replace each `createChannel` / `create_channel` / `create_channel_async` whose writer feeds a
  call with the source itself in the payload
* [ ] Replace each `writerRef` / `writer_ref` passed in for a function to fill with a returned
  stream, or with a sink in the payload, and move that function's callers in the same change
* [ ] Type stream fields as `InputStream` and `OutputStream`; in Rust, replace
  `extract_channel_refs` and `ChannelReader::new` / `ChannelWriter::new` with typed struct
  fields; in Go, replace `ExtractChannelRefs`, `OpenReader`, and `OpenWriter` with
  `*iii.InputStream` and `*iii.OutputStream` fields
* [ ] In Go, wrap what you send with `iii.InputStreamFromReader`, `iii.InputStreamFromBytes`, or
  `iii.OutputStreamToWriter`, and change `iiihttp.Wrap(client, fn)` to `iiihttp.Wrap(fn)`
* [ ] In the browser, pass a `Blob`, a `File`, or a `ReadableStream` in the payload instead of
  writing a channel
* [ ] Replace `reader.stream` and `writer.stream` with the stream itself, `write`, or the native
  bridges (`toReadable`, `toWritable`)
* [ ] Replace `sendMessage` / `send_message` with `send`, and `onMessage` / `on_message` with
  `messages()`, without your own JSON encoding
* [ ] Replace `writer.stream.destroy()`, dropping a Rust writer, and a Go `Close()` after a failed
  `Write` with `abort(reason)` or a throw, and catch `StreamAbortedError` (Rust
  `Error::StreamAborted`, Go an `*iii.InvocationError` with `iii.CodeStreamAborted`) where you
  caught the old errors
* [ ] Remove explicit closes the handler no longer needs, and call `keepOpen()` (Go `KeepOpen()`)
  where a handler keeps writing after it returns
* [ ] Import `extractChannelRefs`, `isChannelRef`, `StreamChannelRef`, `ChannelDirection`, and
  `ChannelItem` from the protocol module
* [ ] Move calls queued with `CallAction.Enqueue` that carried a ref to stored data and a key
* [ ] Update observer targets that read a captured stream field to expect a `StreamInfo`

> [!NOTE]
>
> To call functions with streams, see [Using iii / Streaming](https://iii.dev/docs/using-iii/streaming.md). To write
> functions that receive and return streams, see [Creating workers /
> Streaming](https://iii.dev/docs/creating-workers/streaming.md). For how a stream works, see [Understanding iii /
> Streaming](https://iii.dev/docs/understanding-iii/streaming.md). For each SDK's API, see the SDK reference:
> [Node](https://iii.dev/docs/reference/sdk-node.md), [Python](https://iii.dev/docs/reference/sdk-python.md), [Rust](https://iii.dev/docs/reference/sdk-rust.md),
> [Go](https://iii.dev/docs/reference/sdk-go.md), and [Browser](https://iii.dev/docs/reference/sdk-browser.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.