@ts-pf/protocol 0.2.2 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/PROTOCOL.md CHANGED
@@ -1,9 +1,48 @@
1
- # ts-pf RPC Protocol 1 (revision 1.1)
1
+ # ts-pf RPC Protocol 1 (revision 1.2)
2
2
 
3
3
  Canonical JSON envelope language for ts-pf. Same `{ "input" }`, `{ "ok": true, "output" }`, `{ "ok": false, "error": { "code", "message", "data?" } }` on every pipe. Discriminator is `error.code`. Implementable from TypeScript, Kotlin, Swift, or any HTTP client.
4
4
 
5
5
  The default binding is HTTP Fetch (POST JSON). Optional codecs wrap the same envelopes as HTTP bodies. Optional message transports carry the same envelopes as JSON text frames.
6
6
 
7
+ ## Conventions
8
+
9
+ The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in BCP 14 [RFC 2119](https://www.rfc-editor.org/rfc/rfc2119) [RFC 8174](https://www.rfc-editor.org/rfc/rfc8174) when, and only when, they appear in all capitals, as shown here.
10
+
11
+ The frame-handling tables under [Message transports](#message-transports-optional) are normative as written: each row is the action a conforming peer takes. Sections marked **non-normative** are advice.
12
+
13
+ A **local failure** is one a client raises itself because no protocol result arrived: an abort, a lost connection, a timeout, or a frame it could not accept. It never crosses the wire, and how a client reports it is up to the client. Where this document quotes a local failure's message (`Request aborted`, `Connection closed`, `Network error`, `Invalid response`), that is the TypeScript reference client's wording; other clients may word it differently. The reference client's conventions are collected in the [TypeScript reference client](#appendix-typescript-reference-client) appendix.
14
+
15
+ ## HTTP client checklist
16
+
17
+ Everything a JSON-over-HTTP client needs. Streams, files, and SSE are optional.
18
+
19
+ - `POST {prefix}/{procedure.path}` with `Content-Type: application/json` and body `{ "input": … }`; omit `input` (or send `null`) for no input. → [HTTP Fetch binding](#http-fetch-binding-default)
20
+ - Send `x-ts-pf-protocol: 1` on every request. → [HTTP Fetch binding](#http-fetch-binding-default)
21
+ - If the response carries `x-ts-pf-protocol` with any other value, do not decode the body; fail the call. → [Classifying an HTTP response](#classifying-an-http-response)
22
+ - Decode the body as an envelope: `"ok": true` → `output` (optional); `"ok": false` → `error`. → [Classifying an HTTP response](#classifying-an-http-response)
23
+ - A body that does not decode is a **transport failure**, never an application outcome: do not read "not found", "unauthenticated", or "forbidden" off the HTTP status. Retrying 5xx / 408 / 429 / network errors is optional, and only for calls that are safe to repeat (every call is a POST). → [Classifying an HTTP response](#classifying-an-http-response)
24
+ - On failure, switch on `error.code`, not the HTTP status. Handle unknown codes with a catch-all. → [Protocol errors](#protocol-errors)
25
+ - Do not retry `BAD_REQUEST` `Unsupported protocol version`: the server speaks another wire major. → [Versioning](#versioning)
26
+ - Optional streams: an `application/jsonl` response is one envelope per line and ends at EOF; a `text/event-stream` response ends at `event: close` (EOF without it is a failure); an `"ok": false` line or `event: error` ends the stream as a failure. → [Message streams](#message-streams-optional), [SSE](#sse-optional)
27
+ - Check your client against `conformance/http.json` (and `http-stream.json` if it reads streams). → [Conformance](#conformance)
28
+
29
+ ## WebSocket client checklist
30
+
31
+ The same envelopes as multiplexed JSON text frames. The same list applies to stdio and `MessagePort`, minus the close codes.
32
+
33
+ - One compact JSON object per WebSocket **text** message; never binary. → [Framing](#framing)
34
+ - Send `{ "type": "hello", "v": 1 }` first (optionally with `meta`, e.g. `{ "authorization": "Bearer …" }`). Send no `call` until `hello-ok`. → [Handshake](#handshake), [Authenticating with `hello.meta`](#authenticating-with-hellometa-non-normative)
35
+ - Accept `hello-ok` only when `v` is the JSON number `1`; anything else fails the connect. On `hello-error`, fail the connect with its `error`. Close if neither arrives within your timeout. → [Handshake](#handshake)
36
+ - Do not retry a `hello-error` `Unsupported protocol version`. → [Reconnecting](#reconnecting-non-normative)
37
+ - Call ids are non-empty **strings**, unique among your in-flight calls. Do not reuse an id you cancelled (nothing confirms the server stopped). → [Frame types](#frame-types), [Cancel and mid-stream errors](#cancel-and-mid-stream-errors)
38
+ - You cannot tell a unary procedure from a stream before it answers: the first frame for an id decides. `result` → unary; `item` or `done` → the call resolves as a stream. → [First frame (client)](#first-frame-client)
39
+ - Terminal frames are `result` and `done`; at most one per id (none after you cancel). In a stream, `result` `"ok": false` is the failure and no `done` follows. → [Multiplex](#multiplex), [Output streams](#output-streams)
40
+ - Ignore frames for ids that are not in flight (for example `item` / `done` after a unary `result`), and frames of an unknown type for an in-flight id. → [Multiplex](#multiplex), [Legal sequences](#legal-sequences)
41
+ - On a local timeout, abort, or `break` out of a stream, send `{ "type": "cancel", "id" }`. No frame acknowledges it; ignore any frames that still arrive for that id. → [Cancel and mid-stream errors](#cancel-and-mid-stream-errors)
42
+ - A message that is not JSON, parses to a non-object, or is an invalid frame with no usable `id` closes the connection; a binary message closes it with `1002`. → [Multiplex](#multiplex), [Close codes](#close-codes-websocket)
43
+ - Streams do not survive a reconnect: resubscribe after the next `hello-ok`. → [Reconnecting](#reconnecting-non-normative)
44
+ - Check your client against `conformance/ws.json`. → [Conformance](#conformance)
45
+
7
46
  ## Envelope
8
47
 
9
48
  Request value:
@@ -42,9 +81,9 @@ Procedure path is the nested router keys joined by `/`. Example: `planet.find`
42
81
 
43
82
  v1 accepts **POST only**. Other methods return HTTP 405 with `error.code: "METHOD_NOT_ALLOWED"`. A deployment may add a GET bridge in front of the handler (`GET {prefix}/{procedure.path}?input=<JSON>` rewritten to this POST); that is outside the v1 wire, and v1 clients and servers do not depend on it.
44
83
 
45
- Servers read the request header `x-ts-pf-protocol`. Absent → accept (plain HTTP clients). Present and equal to `1` (after trimming surrounding whitespace) → accept. Any other value → HTTP 400 with `error.code: "BAD_REQUEST"` and `message: "Unsupported protocol version"`; the response still carries `x-ts-pf-protocol: 1`. The check runs after the method check and before the body is read.
84
+ Servers read the request header `x-ts-pf-protocol`. Absent → accept (plain HTTP clients). Present and equal to `1` (after trimming surrounding whitespace) → accept. Any other value → the server MUST answer HTTP 400 with `error.code: "BAD_REQUEST"` and `message: "Unsupported protocol version"`; the response still carries `x-ts-pf-protocol: 1`. The check runs after the method check and before the body is read.
46
85
 
47
- Clients send `x-ts-pf-protocol: 1` on every request. A response whose `x-ts-pf-protocol` is present and not `1` must not be decoded; the TypeScript client rejects it with `INTERNAL`, the HTTP status, and message `Unsupported protocol version (x-ts-pf-protocol: <value>)` — it is not a local failure, because the response came from a server. A response without the header follows the `Non-RPC response` rule below.
86
+ Clients SHOULD send `x-ts-pf-protocol: 1` on every request. A client reads the response as described in [Classifying an HTTP response](#classifying-an-http-response).
48
87
 
49
88
  Success:
50
89
 
@@ -66,6 +105,22 @@ x-ts-pf-protocol: 1
66
105
  { "ok": false, "error": { "code": "NOT_FOUND", "message": "...", "data": { "id": 1 } } }
67
106
  ```
68
107
 
108
+ ## Classifying an HTTP response
109
+
110
+ A client decides what an HTTP response means from its headers and body, not from its status. Proxies, load balancers, gateways, and CDNs answer with statuses of their own (an HTML 404, a 502, a 413 from a body-size limit) that carry no ts-pf meaning.
111
+
112
+ 1. **Version header.** A response whose `x-ts-pf-protocol` is present and, after trimming surrounding whitespace, is not `1` MUST NOT be decoded. It came from a server of another wire major; the client fails the call without reading the body.
113
+ 2. **Envelope.** Otherwise the response is a ts-pf result only if its body decodes as an envelope: it parses as JSON to an object (not an array, not `null`), and either
114
+ - `"ok"` is `true` — success; `output` is optional and an omitted `output` means no value; or
115
+ - `"ok"` is `false` and `error` is present and is not `null` or a JSON primitive — failure.
116
+
117
+ Clients SHOULD additionally require `error` to be an object (not an array) whose `code` is a non-empty string and whose `message` is a string, and MAY additionally require `Content-Type: application/json`. Other keys are ignored.
118
+ 3. **Transport failure.** A response whose body does not decode is a **transport failure**. A client MUST NOT turn it into an application-level outcome (not found, unauthenticated, forbidden, validation failed, …) from the HTTP status alone. It MAY retry by status class: 5xx, 408, and 429 responses, and network errors that produced no response at all. Only retry a call the application knows is safe to repeat; ts-pf calls are POSTs and may write.
119
+ 4. **Headerless responses.** A response without `x-ts-pf-protocol` whose body decodes is trusted as a result. A cross-origin browser client cannot read the header at all unless the server lists it in `Access-Control-Expose-Headers`, so the header's absence alone is not a transport failure.
120
+ 5. **Streams.** A response with `Content-Type: application/jsonl` or `text/event-stream` to a client that accepts streams is classified by that content type, before any line is read: the call has succeeded with a stream (see [Message streams](#message-streams-optional) and [SSE](#sse-optional)). Each JSONL line, and the `data` of each SSE `message` / `error` event, is then decoded as an envelope as in step 2. Blank JSONL lines are ignored, and an SSE event with no `data` (other than `close`) carries nothing. A line that does not decode MUST end the stream with a failure; it MUST NOT be skipped or delivered as an item. A response with any other content type is classified by steps 2–4.
121
+
122
+ A decoded failure envelope is the server's answer whatever the HTTP status: switch on `error.code` ([Protocol errors](#protocol-errors)).
123
+
69
124
  ## Protocol errors
70
125
 
71
126
  | Code | Status | When |
@@ -77,37 +132,26 @@ x-ts-pf-protocol: 1
77
132
  | `PAYLOAD_TOO_LARGE` | 413 | Request body larger than the configured handler limit |
78
133
  | `INTERNAL` | 500 | Unknown throw. A unary output schema failure is also 500 (server bug). Output schema checks are optional. |
79
134
 
80
- The discriminator is `error.code`. HTTP status is unary transport only; it is not in the JSON body. The TypeScript `PFError.status` is optional transport metadata, never identity (see [`status` on the TypeScript client](#status-on-the-typescript-client)).
135
+ The discriminator is `error.code`. HTTP status is unary transport only; it is not in the JSON body.
81
136
 
82
- The table above is a **closed** set. Procedure-declared codes are application-defined strings with optional `data`. `VALIDATION` is the only protocol code with a specified `data` shape: `{ issues: { message, path }[] }` where `path` is `(string | number)[]`. Other protocol codes omit `data`. `INTERNAL` never includes a stack or output-schema issues. Servers may skip output schema checks. When a server checks a unary output schema and it fails, the code is `INTERNAL` and `data` is omitted. When a server checks a stream item and it fails, the code is `VALIDATION` with `issues`, in-band after the stream has started.
137
+ The table above is a **closed** set. Procedure-declared codes are application-defined strings with optional `data`. `VALIDATION` is the only protocol code with a specified `data` shape: `{ issues: { message, path }[] }` where `path` is `(string | number)[]`. Other protocol codes omit `data`. `INTERNAL` MUST NOT include a stack or output-schema issues. Servers MAY skip output schema checks. When a server checks a unary output schema and it fails, the code is `INTERNAL` and `data` is omitted. When a server checks a stream item and it fails, the code is `VALIDATION` with `issues`, in-band after the stream has started.
83
138
 
84
- Unknown `code` values are valid JSON; clients must catch-all. A procedure may reuse `NOT_FOUND` for a missing entity. Do not redeclare `VALIDATION`, `INTERNAL`, `BAD_REQUEST`, `METHOD_NOT_ALLOWED`, or `PAYLOAD_TOO_LARGE`.
139
+ Unknown `code` values are valid JSON; clients MUST handle them (a catch-all branch). A procedure may reuse `NOT_FOUND` for a missing entity. Do not redeclare `VALIDATION`, `INTERNAL`, `BAD_REQUEST`, `METHOD_NOT_ALLOWED`, or `PAYLOAD_TOO_LARGE`.
85
140
 
86
141
  After a stream starts, HTTP status stays 200; the same `{ ok: false, error }` object appears as a JSONL line, SSE `event: error`, or a message-transport `{ "type": "result", "ok": false, "error": … }` frame. Switch on `code`, not HTTP status.
87
142
 
88
- TypeScript `PFError`, `instanceof`, and `asResult` are JS conveniences. They are not required to consume the API. Any HTTP client parses this envelope.
89
-
90
- Contract-declared error codes use the status on the error definition when the HTTP binding sends a unary failure; a declared code with no `status` is sent as HTTP 400 (`httpStatus()` in `@ts-pf/http`).
143
+ Contract-declared error codes use the status on the error definition when the HTTP binding sends a unary failure; a declared code with no `status` is sent as HTTP 400.
91
144
 
92
- ### `status` on the TypeScript client
93
-
94
- `PFError.status` is `number | undefined`. It is set only where a transport really has one. Switch on `error.code`; treat `status` as a hint and guard it (`err.status ?? 400`).
145
+ ## Versioning
95
146
 
96
- | Transport | `status` on the rejected `PFError` |
97
- |---|---|
98
- | HTTP unary failure (`FetchLink`) | The HTTP response status (declared `NOT_FOUND { status: 404 }` → `404`; declared code without `status` → `400`; protocol codes → the table above) |
99
- | HTTP after a stream started (JSONL line / SSE `event: error`) | `undefined` (the response was already 200) |
100
- | WebSocket / stdio / MessagePort | `undefined` (no HTTP status on a frame; `errorFromEnvelope` does not synthesize one) |
101
- | Local failure (`localFailure`, `isLocalFailure`) | `0` with `local: true` |
102
- | In-process `createLocalClient` | The declared `ErrorDef.status` when there is one, else `undefined` |
147
+ Header `x-ts-pf-protocol` and `v` on `hello` / `hello-ok` carry the **wire major**, currently `1`; the header is its decimal string. JSON is the default content type and the envelope above does not change for JSON calls. Other content types are codec-defined (see [Binary attachments](#binary-attachments-optional), [Message streams](#message-streams-optional), and [SSE](#sse-optional)). A codec may stream the HTTP body without changing this envelope. Optional [message transports](#message-transports-optional) carry the same major as `v: 1` on `hello` instead of this header.
103
148
 
104
- The TypeScript client maps **local** failures (never got a protocol result) to `INTERNAL` with `local: true` and `status: 0`. `local` and `status` are TypeScript client conventions, not protocol fields, and are **not** on the wire. `isLocalFailure` is `local === true`. Abort uses message `Request aborted`. Network throws keep `error.message` and set `Error.cause` to the thrown value (Node’s `ECONNREFUSED` is then `error.cause.cause`). HTTP responses **without** `x-ts-pf-protocol` that fail `decodeResponse` become `INTERNAL` with the HTTP status and message `Non-RPC response (HTTP …)` — do not surface codec `BAD_REQUEST` 400 for proxy HTML. Codec `PFError` is rethrown only when `x-ts-pf-protocol` is present and equal to `1` (truncated JSONL/SSE at decode time, malformed ts-pf JSON); a different value is never decoded (see [HTTP Fetch binding](#http-fetch-binding-default)). `toJSON()` still omits `status`, `cause`, and `local`.
149
+ **Revisions.** This document has a revision number (this is 1.2). Revisions are additive and keep the wire major: a peer cannot tell 1.0 from 1.1 or 1.2 on the wire. Additive means a 1.x sender emits a new key, frame type, header, or content type only when the user opted in, and a 1.0 receiver that does not understand it fails **that call** (`BAD_REQUEST`), never the connection and never silently. Receivers MUST NOT reject a value that 1.0 defined as valid. Bump the wire major only when the JSON envelope, a required frame field, or the handshake changes.
105
150
 
106
- ## Versioning
151
+ A client SHOULD NOT retry a call or connection that failed with `BAD_REQUEST` `Unsupported protocol version` (HTTP 400 or `hello-error`): the server speaks another wire major and answers the same way every time.
107
152
 
108
- Header `x-ts-pf-protocol` and `v` on `hello` / `hello-ok` carry the **wire major**, currently `1` (`PROTOCOL_MAJOR`; the header is its decimal string, `PROTOCOL_VERSION`). JSON is the default content type and the envelope above does not change for JSON calls. Other content types are codec-defined (see [Binary attachments](#binary-attachments-optional), [Message streams](#message-streams-optional), and [SSE](#sse-optional)). A codec may stream the HTTP body (`ReadableStream`) without changing this envelope. Optional [message transports](#message-transports-optional) carry the same major as `v: 1` on `hello` instead of this header.
109
-
110
- **Revisions.** This document has a revision number (this is 1.1). Revisions are additive and keep the wire major: a peer cannot tell 1.0 from 1.1 on the wire. Additive means a 1.x sender emits a new key, frame type, header, or content type only when the user opted in, and a 1.0 receiver that does not understand it fails **that call** (`BAD_REQUEST`), never the connection and never silently. Receivers must not reject a value that 1.0 defined as valid. Bump the wire major only when the JSON envelope, a required frame field, or the handshake changes.
153
+ - **1.1** — servers read the request `x-ts-pf-protocol` (another value is `BAD_REQUEST` `Unsupported protocol version`), clients do not decode a response carrying another value, and the advisory content negotiation paragraph below.
154
+ - **1.2** — no new frame, key, header, or code. It adds [Classifying an HTTP response](#classifying-an-http-response), the RFC 2119 [conventions](#conventions), the [HTTP](#http-client-checklist) and [WebSocket](#websocket-client-checklist) client checklists, the [TypeScript reference client](#appendix-typescript-reference-client) appendix, the [conformance fixtures](#conformance), the WebSocket [close-code ranges](#close-codes-websocket), the non-normative [reconnecting](#reconnecting-non-normative) and [`hello.meta.authorization`](#authenticating-with-hellometa-non-normative) notes, `hello-error` carrying the application error a server raised while accepting `hello` ([Handshake](#handshake)), and `BAD_REQUEST` for a stream procedure called on an endpoint whose codec cannot carry streams ([Message streams](#message-streams-optional)).
111
155
 
112
156
  **Content negotiation.** Clients MAY send `Accept` listing the response media types they can decode (`application/json`, `application/jsonl`, `text/event-stream`). Servers MAY use it to choose the framing of a streamed response and MUST ignore it when they cannot satisfy it (never 406; the JSON failure envelope is always `application/json`). `Content-Type` on the request selects the request codec as today.
113
157
 
@@ -121,7 +165,7 @@ JSON-only clients can ignore this section. The envelope keys stay `{ "input" }`,
121
165
  | One or more `File`/`Blob` values | `multipart/form-data` | Envelope in part `rpc` plus numbered file parts |
122
166
  | Any failure | `application/json` | Failure envelope above |
123
167
 
124
- A server that accepts multipart must still accept `application/json` so existing JSON clients keep working.
168
+ A server that accepts multipart MUST still accept `application/json` so existing JSON clients keep working.
125
169
 
126
170
  ### Multipart request
127
171
 
@@ -178,9 +222,11 @@ JSON-only clients can ignore this section. A **root** `AsyncIterable` (async gen
178
222
 
179
223
  HTTP status for an accepted stream is **200**. Status cannot change after the first byte; later errors are in-band. Nested streams and file values inside stream items are `BAD_REQUEST`.
180
224
 
225
+ An endpoint whose body encoding cannot carry streams (JSON-only or multipart) MUST answer a call to a procedure whose input or output is a stream with HTTP 400, `error.code: "BAD_REQUEST"`, and `message: "Stream procedure requires a streaming codec"`, as a JSON failure envelope with `x-ts-pf-protocol: 1`. It MUST NOT answer such a call with a 200 non-stream body. A server that knows the procedure streams from its contract answers before reading the body or running the procedure; otherwise it answers when the procedure returns a stream, and closes that stream unread.
226
+
181
227
  Output:
182
228
 
183
- Streamed bodies (JSONL and SSE) SHOULD send `Cache-Control: no-cache, no-transform` and `X-Accel-Buffering: no`. `FetchHandler` sets these when the codec body is a `ReadableStream`.
229
+ Streamed bodies (JSONL and SSE) SHOULD send `Cache-Control: no-cache, no-transform` and `X-Accel-Buffering: no`.
184
230
 
185
231
  ```
186
232
  HTTP/1.1 200
@@ -204,7 +250,7 @@ x-ts-pf-protocol: 1
204
250
  {"input":{"chunk":2}}
205
251
  ```
206
252
 
207
- EOF is a successful close. There is no `done` field on the envelope.
253
+ EOF is a successful close. There is no `done` field on the envelope. A line that does not decode as an envelope ends the stream as a failure ([Classifying an HTTP response](#classifying-an-http-response), step 5).
208
254
 
209
255
  `text/event-stream` is optional output framing of these same lines. See [SSE](#sse-optional). Do not bump `x-ts-pf-protocol` for that framing.
210
256
 
@@ -268,9 +314,9 @@ Then the body ends. Do not send `close` after `error`.
268
314
  | `close` | successful EOF | none. Framing only — not an envelope |
269
315
  | comment (`:`) | keepalive / header flush | n/a |
270
316
 
271
- `data:` JSON is byte-identical to a JSONL line. Close is an explicit event so a truncated TCP close is not success; EOF without `close` after the stream started is `INTERNAL`. Comments may be sent immediately (to flush headers) and periodically (~15s) to defeat idle proxies. No `id:` or `retry:` in v1.
317
+ `data:` JSON is byte-identical to a JSONL line. Close is an explicit event so a truncated TCP close is not success: a client MUST treat EOF without `close` after the stream started as a failure. Comments may be sent immediately (to flush headers) and periodically (~15s) to defeat idle proxies. No `id:` or `retry:` in v1.
272
318
 
273
- The TypeScript client parses `fetch` response bodies. Native `EventSource` is not an RPC client (GET-only, no custom headers, auto-reconnects).
319
+ An RPC client reads the `fetch` response body. Native `EventSource` is not an RPC client (GET-only, no custom headers, auto-reconnects).
274
320
 
275
321
  ```bash
276
322
  curl -N -X POST "$HOST/rpc/chat" \
@@ -288,7 +334,7 @@ These bindings are not HTTP:
288
334
 
289
335
  - Files / `multipart/form-data` are Fetch-only. See [Binary attachments](#binary-attachments-optional). Do not invent a binary attachment framing here.
290
336
  - SSE (`text/event-stream`) is Fetch-only. See [SSE](#sse-optional). Do not send SSE over a socket.
291
- - HTTP status is Fetch-only. It is not a field on a frame.
337
+ - HTTP status is Fetch-only. It is not a field on a frame, and a receiver MUST NOT reconstruct one from `error.code`.
292
338
  - `METHOD_NOT_ALLOWED` is Fetch-only. There is no HTTP method on a frame.
293
339
  - Procedure-declared `.errors()` `status` is Fetch-only. Every client, including TypeScript, switches on `error.code`.
294
340
 
@@ -296,7 +342,7 @@ These bindings are not HTTP:
296
342
 
297
343
  ### Framing
298
344
 
299
- Logical frames are compact JSON objects. All three bindings send **JSON text**. Pretty-printed JSON is forbidden (`JSON.stringify` of a compact object never emits a raw unescaped newline, so NDJSON is safe).
345
+ Logical frames are compact JSON objects. All three bindings send **JSON text**. Senders MUST NOT pretty-print (`JSON.stringify` of a compact object never emits a raw unescaped newline, so NDJSON is safe).
300
346
 
301
347
  | Binding | Byte / message framing |
302
348
  |---|---|
@@ -332,7 +378,7 @@ A well-behaved peer never sends the wrong direction. After `ready`, treat a wron
332
378
 
333
379
  | Field | Rule |
334
380
  |---|---|
335
- | `id` | Non-empty string. `"1"` is fine; `1` (number) is invalid; `""` is invalid. A client *may* use a decimal counter. A server **must not** `Number(id)`. After a terminal frame, the same string may be reused for a new call. |
381
+ | `id` | Non-empty string. `"1"` is fine; `1` (number) is invalid; `""` is invalid. A client MAY use a decimal counter. A server MUST NOT treat it as a number (`Number(id)`). After a terminal frame, the same string may be reused for a new call. |
336
382
  | `path` | Array of strings (may be empty). Not `"planet/find"`. A non-string element is invalid. |
337
383
  | `v` | JSON number. Handshake uses the version check below. `"1"` is not a number. |
338
384
  | `ok` | Boolean. Required on `result`. |
@@ -352,9 +398,10 @@ HTTP equivalent of header `x-ts-pf-protocol: 1`. Hello is not a `call` and has n
352
398
 
353
399
  ```json
354
400
  { "type": "hello", "v": 1 }
355
- { "type": "hello", "v": 1, "meta": { "token": "…" } }
401
+ { "type": "hello", "v": 1, "meta": { "authorization": "Bearer …" } }
356
402
  { "type": "hello-ok", "v": 1 }
357
403
  { "type": "hello-error", "error": { "code": "BAD_REQUEST", "message": "Unsupported protocol version" } }
404
+ { "type": "hello-error", "error": { "code": "UNAUTHORIZED", "message": "Session expired" } }
358
405
  ```
359
406
 
360
407
  **Server connection states:** `waiting-hello` → `ready` → `closed`.
@@ -377,10 +424,12 @@ HTTP equivalent of header `x-ts-pf-protocol: 1`. Hello is not a `call` and has n
377
424
 
378
425
  | Condition | Action |
379
426
  |---|---|
380
- | Valid `hello` (`v === 1`, no extra keys), and this is the **first** hello | Stay `waiting-hello`. Accept the hello (context factory, if any). **Success:** send `{ "type": "hello-ok", "v": 1 }`, go `ready`, then and only then deliver **later** frames. **Throw:** send `{ "type": "hello-error", "error": { "code": "INTERNAL", "message": "Internal server error" } }` (no stack, no factory message) and close. Do not send `hello-ok`. |
427
+ | Valid `hello` (`v === 1`, no extra keys), and this is the **first** hello | Stay `waiting-hello`. Accept the hello (context factory, if any). **Success:** send `{ "type": "hello-ok", "v": 1 }`, go `ready`, then and only then deliver **later** frames. **Failure:** send `hello-error` and close; do not send `hello-ok`. The `error` is mapped exactly as a procedure's thrown error is ([Cancel and mid-stream errors](#cancel-and-mid-stream-errors)): a deliberate application error (a TypeScript `PFError`) is sent as its `{ "code", "message", "data"? }`; any other throw sends exactly `{ "type": "hello-error", "error": { "code": "INTERNAL", "message": "Internal server error" } }` (no stack, no factory message). |
381
428
  | Any other object (`type: "call"`, extra keys on `hello` with `v === 1`, missing `v`, frames that arrive **while accept is outstanding**, …) | `{ "type": "hello-error", "error": { "code": "BAD_REQUEST", "message": "Expected hello" } }` then close. If `type` is `"hello"` and this is not the numeric `v !== 1` case above, the message is `Invalid hello` instead. If accept is in flight, **abandon** it (ignore its later settle; do not send `hello-ok` if it succeeds after close). |
382
429
 
383
- Optional hello timeout (TypeScript default `10_000` ms; `0` = none): if still `waiting-hello` when the timer fires (including during accept), close with no frame, abandon accept.
430
+ A server refuses a connection it will not serve by failing the accept with an application error, for example `{ "code": "UNAUTHORIZED", "message": "Session expired" }` for a missing or expired credential. The client receives that code instead of a bare close.
431
+
432
+ Optional hello timeout: if still `waiting-hello` when the timer fires (including during accept), close with no frame, abandon accept.
384
433
 
385
434
  **Client connection states:** `connecting` → `handshaking` → `ready` → `closed`.
386
435
 
@@ -397,11 +446,17 @@ If `JSON.parse` produced an object with `type: "hello-ok"`, check `v` the same w
397
446
  | Received while `handshaking` | Action |
398
447
  |---|---|
399
448
  | Valid `hello-ok` (`v === 1`) | Become `ready`. |
400
- | Valid `hello-error` | Fail the connect with that `error` (typically `BAD_REQUEST` / `INTERNAL`, not status 0). Close. |
449
+ | Valid `hello-error` | Fail the connect with that `error` (`BAD_REQUEST`, `INTERNAL`, or an application code such as `UNAUTHORIZED`), not as a local failure. Close. |
401
450
  | Anything else parsed (wrong type, extra keys, invalid `v` as above) | Fail the connect as a local `Invalid response`. Close. |
402
- | Unparseable / close / timeout | Fail the connect as a local `Network error` or `Connection closed`. |
451
+ | Unparseable / close / timeout | Fail the connect as a local failure (`Network error` or `Connection closed`). |
452
+
453
+ On a client hello timeout, fail the connect locally, then close. A client that disables its timeout relies on the caller aborting or closing the connection.
403
454
 
404
- On hello timeout: local `Network error`, then close. Callers who disable the timeout must abort via `AbortSignal` or close the connection.
455
+ #### Authenticating with `hello.meta` (non-normative)
456
+
457
+ `meta` is free-form and untrusted. For a credential, the recommended convention is `meta.authorization` carrying the same value an HTTP client puts in the `Authorization` header (`"Bearer <token>"`), so a server can use one parser for its HTTP and socket endpoints. Browsers cannot set headers on a WebSocket upgrade, so `meta` is the portable carrier; send it over `wss:` only. The server checks it while accepting the hello and refuses with a `hello-error` carrying an application code (for example `UNAUTHORIZED`).
458
+
459
+ The credential is fixed for the life of the connection. Rotating it without reconnecting is deferred to a later revision; to present a new credential, reconnect.
405
460
 
406
461
  ### Multiplex
407
462
 
@@ -416,17 +471,19 @@ After a terminal frame, the id is free for reuse. Until then:
416
471
  |---|---|
417
472
  | Duplicate `call` for an in-flight id | **Ignore.** Do not emit `result` on that id. Do not replace the running call. Do not close the connection (other ids must survive a buggy peer). Well-behaved clients never reuse an in-flight id. |
418
473
  | Unknown / invalid frame whose `id` is in-flight | **Ignore.** Do not settle that call. Do not send a second `result`. |
419
- | Unknown / invalid frame whose `id` is a non-empty string **not** in-flight | Send `{ "type": "result", "id", "ok": false, "error": { "code": "BAD_REQUEST", "message": "…" } }`. That *is* the terminal frame for a call that never started. |
474
+ | Unknown / invalid frame whose `id` is a non-empty string **not** in-flight | Server: send `{ "type": "result", "id", "ok": false, "error": { "code": "BAD_REQUEST", "message": "…" } }`. That *is* the terminal frame for a call that never started. Client: ignore it (there is no call to settle). |
420
475
  | Unknown / invalid frame with no usable id, **after `ready`** | Close. No `hello-error` (handshake is over). |
421
476
  | `JSON.parse` throw, non-object, non-string WS/port payload, binary WS frame, inbound over-limit | **Always close.** No id extraction, no regex, no partial parse. **Exception in `waiting-hello` only:** if `JSON.parse` succeeded as an object, send `hello-error` `BAD_REQUEST` then close (even when the object is not a valid frame). |
422
477
 
478
+ A client ignores every frame whose `id` is not one of its in-flight calls, valid or not: a late frame after a terminal frame or after `cancel`, or a frame for an id it never used.
479
+
423
480
  A hostile peer cannot cancel an in-flight call by reusing its id or sending `{ "type": "nope", "id" }`. They can still send `{ "type": "cancel", "id" }` — that is the documented cancel path.
424
481
 
425
482
  The connection keeps reading frames while a call runs. Two in-flight ids complete independently.
426
483
 
427
484
  #### Backpressure
428
485
 
429
- No frame acknowledges `item` or `in-item`, and no frame carries a window; flow control in wire major 1 is the transport's. A sender SHOULD NOT pull the next value from the producing iterator until the transport has drained the previous frame of that id (`bufferedAmount` under a high-water mark, `write()` accepted or `drain` fired). A receiver MAY stop reading the transport while a per-id queue is over a local high-water mark; pausing is connection-wide, so one slow consumer delays every id on that connection. On a transport the receiver cannot pause (`MessagePort`, a browser `WebSocket`) receiver memory is bounded only by the peer's behaviour; a receiver may `cancel` a stream it cannot keep up with.
486
+ No frame acknowledges `item` or `in-item`, and no frame carries a window; flow control in wire major 1 is the transport's. A sender SHOULD NOT pull the next value from the producing iterator until the transport has drained the previous frame of that id (`bufferedAmount` under a high-water mark, `write()` accepted or `drain` fired). A receiver MAY stop reading the transport while a per-id queue is over a local high-water mark; pausing is connection-wide, so one slow consumer delays every id on that connection. On a transport the receiver cannot pause (`MessagePort`, a browser `WebSocket`) receiver memory is bounded only by the peer's behaviour; a receiver MAY `cancel` a stream it cannot keep up with.
430
487
 
431
488
  A sender MAY give up on a peer that does not drain within a timeout. That is a server-side condition, not a protocol code: the server sends `{ "type": "result", "id", "ok": false, "error": { "code": "INTERNAL", "message": "Peer did not drain within <n> ms" } }` as the terminal frame for that id (after the items already handed to the transport; no `done`), stops the procedure as if cancelled, and keeps the connection open. A client that gives up on a server that does not drain its `in-item` frames fails the call locally and sends `cancel`. A 1.x receiver already ignores an unknown frame type with an in-flight `id` (table above), so a future credit frame is harmless to it; one for an id that has already terminated would draw `BAD_REQUEST`, so a later major must never send credit after a terminal frame.
432
489
 
@@ -445,7 +502,7 @@ Option omitted = **unlimited in both directions** (same as Fetch without a reque
445
502
  | Intended outbound frame | If it cannot be sent (oversize or cannot stringify) |
446
503
  |---|---|
447
504
  | `result` / `item` / `done` for an **open** id, whether or not items have started | Peer sees `{ "type": "result", "id", "ok": false, "error": { "code": "PAYLOAD_TOO_LARGE", "message": "Frame too large" } }` (oversize) or `{ "type": "result", "id", "ok": false, "error": { "code": "INTERNAL", "message": "Internal server error" } }` (stringify). Then stop. **No `done`.** If that error frame also cannot be sent → close. |
448
- | `hello` / `hello-ok` / `hello-error` / `cancel` / `call` / `in-item` / `in-done` | No substitute frame. A client `call` that cannot be sent fails that call with `PAYLOAD_TOO_LARGE` or `INTERNAL` (stringify; `isLocalFailure` is false). A hello that cannot be sent fails connect as local `Network error`, then close. |
505
+ | `hello` / `hello-ok` / `hello-error` / `cancel` / `call` / `in-item` / `in-done` | No substitute frame. A client `call` that cannot be sent fails that call with `PAYLOAD_TOO_LARGE` (oversize) or `INTERNAL` (stringify). A hello that cannot be sent fails the connect locally, then close. |
449
506
 
450
507
  ### Unary call
451
508
 
@@ -460,7 +517,7 @@ Option omitted = **unlimited in both directions** (same as Fetch without a reque
460
517
  - `METHOD_NOT_ALLOWED` is not used.
461
518
  - `cancel` of an unknown / already-finished id is a no-op.
462
519
 
463
- Sequence: `C: call` then `S: result ok:true | result ok:false`. Optional: `C: cancel` after `call` and before the terminal. After cancel, the server stops; no further frames for this id.
520
+ Sequence: `C: call` then `S: result ok:true | result ok:false`. Optional: `C: cancel` after `call` and before the terminal. After cancel, the server stops; no further frames for this id. No frame acknowledges `cancel`: the client treats the call as finished when it sends `cancel` and ignores any frames that still arrive for that id. Because nothing confirms the server has let go of the id, a client SHOULD NOT reuse a cancelled id (a server still holding it ignores the new `call` as a duplicate).
464
521
 
465
522
  HTTP distinguishes unary vs stream via `Content-Type`. Message frames have no content type. The client uses the **first inbound frame for that id**.
466
523
 
@@ -472,16 +529,18 @@ After sending `call` (and while possibly sending `in-item` / `in-done` if `call.
472
529
  |---|---|
473
530
  | `result` `ok: true` | Resolve to `output` (possibly `undefined`). Unary done. |
474
531
  | `result` `ok: false` | Reject with that `error`. |
475
- | `item` | Resolve to an async iterable whose first `next()` yields this `output`; then continue in `streaming-out`. |
476
- | `done` | Resolve to an async iterable that immediately completes (empty stream; JSONL uses EOF, multiplex cannot). |
532
+ | `item` | Resolve the call as a stream whose first item is this `output` (an async iterable in TypeScript); then continue in `streaming-out`. |
533
+ | `done` | Resolve the call as an empty stream that is already complete (JSONL uses EOF, multiplex cannot). |
477
534
  | `cancel` / `call` / `hello*` / `in-item` / `in-done` | Reject this call as local `Invalid response`. Do not close the connection. Ignore further frames for this id. |
478
535
  | Peer close before any frame | Reject as local `Connection closed`. |
479
536
 
480
- The call promise is not itself async-iterable. For output streams it **resolves to** an async iterable (same DX as JSONL: `const tokens = await client.planet.chat(...)` then `for await`).
537
+ A frame with this `id` whose `type` this document does not define, or one that fails decode, is not a first frame (unlike the defined types in the wrong direction above): it is ignored as in [Multiplex](#multiplex), and the call keeps waiting.
481
538
 
482
- #### `streaming-out` (after the promise resolved to an async iterable)
539
+ The call's result is not itself the stream: for output streams it **resolves to** a stream the caller then reads (in TypeScript, `const tokens = await client.planet.chat(...)` then `for await`, the same as JSONL).
483
540
 
484
- Further frames drive the **iterator**, not the call promise.
541
+ #### `streaming-out` (after the call resolved to a stream)
542
+
543
+ Further frames drive the **stream**, not the call's result.
485
544
 
486
545
  | Event | Action |
487
546
  |---|---|
@@ -490,7 +549,7 @@ Further frames drive the **iterator**, not the call promise.
490
549
  | `result` `ok: false` | **Reject the iterator** with that `error`. This is the legal mid-stream error, **not** the “in-flight → ignore” rule. No `done`. |
491
550
  | `result` `ok: true` / unknown type / extra `done` / `item` after `done` | Illegal. **Ignore** (do not close the connection; do not reject a second time). Well-behaved servers never send these. |
492
551
  | Peer close / client close | Reject the iterator as local `Connection closed` if not already done. |
493
- | User `break` / iterator `return()` / `throw()` | Send `{ "type": "cancel", "id" }` (not `in-done`, not `done`). Stop reading frames for this id. The server sees `cancel` and stops emitting. |
552
+ | Caller stops reading early (TypeScript: `break`, iterator `return()` / `throw()`) | Send `{ "type": "cancel", "id" }` (not `in-done`, not `done`). Stop reading frames for this id. The server sees `cancel` and stops emitting. |
494
553
 
495
554
  `for-await` `break` and iterator `return()` are the Fetch-body-cancel equivalent.
496
555
 
@@ -543,7 +602,7 @@ C: in-item* / in-done
543
602
  S: item* / done | result ok:false
544
603
  ```
545
604
 
546
- **Illegal** (peer must not send; receiver: if the id is in-flight **and this is not a legal `streaming-out` `result ok: false`**, **ignore**; if this is the first frame, `Invalid response` / `BAD_REQUEST` as in the first-frame table):
605
+ **Illegal** (peer must not send; receiver: if the id is in-flight **and this is not a legal `streaming-out` `result ok: false`**, **ignore**; if this is the first frame, `Invalid response` / `BAD_REQUEST` as in the first-frame table; once the id has terminated, the frame is for an id not in flight and the client ignores it):
547
606
 
548
607
  - `result ok: true` after an `item` or `done`
549
608
  - `item` or `done` after a unary `result`
@@ -579,7 +638,7 @@ Nested streams and `File` / `Blob` values inside items are `BAD_REQUEST`.
579
638
  { "type": "in-done", "id": "1" }
580
639
  ```
581
640
 
582
- The server must accept `in-item` for that id as soon as `call` is accepted (the next-turn item must not be lost). Backpressure is the transport's; see "Backpressure" under Multiplex. No credit-based flow control in v1. Cancel of the call aborts both sides.
641
+ The server MUST accept `in-item` for that id as soon as `call` is accepted (an item sent right after the `call` must not be lost). Backpressure is the transport's; see "Backpressure" under Multiplex. No credit-based flow control in v1. Cancel of the call aborts both sides.
583
642
 
584
643
  ### Cancel and mid-stream errors
585
644
 
@@ -590,33 +649,95 @@ The server must accept `in-item` for that id as soon as `call` is accepted (the
590
649
  | Declared / protocol `error` from the procedure or from a stream `next()` | Send `{ "type": "result", "id", "ok": false, "error": { "code", "message", "data?" } }`. Declared codes survive. Status is **not** on the wire. Do not send `done`. If already cancelled, send nothing. |
591
650
  | Unknown throw | `{ "type": "result", "id", "ok": false, "error": { "code": "INTERNAL", "message": "Internal server error" } }`. If cancelled, still invoke any local error hook, send nothing. |
592
651
  | Abort after client `cancel` (generator checks `signal` and throws `AbortError`) | Send **nothing**. Prefer silence. Do not encode `INTERNAL`. |
593
- | Client abort while **in flight** (a `call` was sent) | Send `{ "type": "cancel", "id" }`. Reject local as `Request aborted`. Ignore late `result` / `item` / `done`. |
594
- | Client abort **before hello-ok** (no id yet) | Local `Request aborted`. Do **not** send `cancel`. Do **not** close the connection unless hello itself failed (timeout / `hello-error` / peer close). Other `call`s may still wait for the same `ready`. |
652
+ | Client abort while **in flight** (a `call` was sent) | Send `{ "type": "cancel", "id" }`. Reject locally (`Request aborted`). Ignore late `result` / `item` / `done`. |
653
+ | Client abort **before hello-ok** (no id yet) | Reject locally (`Request aborted`). Do **not** send `cancel`. Do **not** close the connection unless hello itself failed (timeout / `hello-error` / peer close). Other `call`s may still wait for the same `ready`. |
595
654
  | Output-stream cancel (iterator `return()` / `throw()` / `AbortSignal`) | Client sends `{ "type": "cancel", "id" }` (not `in-done`). Server aborts, stops emitting, ends any input queue. |
596
655
  | Input generator throw / early `return()` | Client sends `{ "type": "cancel", "id" }` (not `in-done`). Same server cancel path. |
597
656
 
598
- ### Local failure vs protocol failure
657
+ A client keeps three outcomes apart: a **local failure** (no protocol result arrived; see [Conventions](#conventions)), a **failure envelope** from the server (switch on `error.code`; declared and protocol codes alike), and protocol `INTERNAL` from the server (a server-side failure, not a local one). Message transports carry no HTTP status; a client that exposes a status field leaves it empty on this pipe.
658
+
659
+ ### Close codes (WebSocket)
660
+
661
+ The protocol uses two standard close codes: `1000` (normal closure — an explicit close, the close after a `hello-error`, a hello timeout, a malformed or oversize text message) and `1002` (protocol error — a binary or other non-string message). The close code is advisory: the reason for a failure travels in frames (`hello-error`, `result`).
662
+
663
+ - **4900–4999 are reserved for this protocol** (for example, a future code for a version mismatch that must not be retried, or for a hello timeout). Applications MUST NOT send them.
664
+ - **4400–4499 are RECOMMENDED for applications**, mirroring HTTP status: `4401` unauthenticated, `4403` forbidden, `4429` rate limited, and so on. Use them to end a live connection for an application reason after `hello-ok` (a revoked session, a ban), with a short reason string. Before `hello-ok`, refuse with a `hello-error` carrying an application code instead.
665
+
666
+ ### Reconnecting (non-normative)
667
+
668
+ There is no session resumption: a new connection starts with `hello`, and no id, call, or stream carries over.
669
+
670
+ - **Streams do not survive a reconnect.** A dropped connection ends every in-flight call and stream with a local failure. Resubscribe (call the stream procedure again) after the new `hello-ok`.
671
+ - **Stream delivery is at most once.** Items sent while the connection was down are lost, and nothing replays them. An application that needs gap-free state re-syncs after resubscribing: for example, the stream's first item says "subscribed", the client then fetches the current state with a unary call, and applies later items on top of that snapshot (discarding items older than it, by a version or timestamp the application puts in them).
672
+ - **Never retry `Unsupported protocol version`** (a `hello-error`, or HTTP `BAD_REQUEST` with that message): the server speaks another wire major and answers the same way every time. Surface it.
673
+ - **Back off between attempts**, exponentially and with jitter (for example a random delay between 0 and `min(cap, base × 2^attempt)`), and reset the attempt count once a connection has reached `hello-ok` and stayed up. Without jitter, a server restart draws every client back at the same instant.
674
+ - Credentials are fixed at `hello` ([Authenticating with `hello.meta`](#authenticating-with-hellometa-non-normative)); a new credential means a new connection.
675
+
676
+ ## Conformance
599
677
 
600
- The TypeScript client maps **local** failures (never got a protocol result) to `INTERNAL` with `local: true` and `status: 0`. Those fields are TypeScript client conventions, **not** protocol fields, and are **not** on the wire. Do not add them to the [protocol errors](#protocol-errors) status table. `isLocalFailure` is `local === true`.
678
+ Language-neutral test vectors for this document live in [`conformance/`](https://github.com/crobinson42/ts-pf/tree/main/packages/protocol/conformance) next to it, and ship in the `@ts-pf/protocol` npm package: `http.json` (unary JSON requests and response classification), `http-stream.json` (`application/jsonl` output streams), and `ws.json` (WebSocket frame scripts, which also cover stdio and `MessagePort` minus binary messages and close codes). They are plain JSON data, not schemas. A client in any language replays them against its own code, with no server and no network; the directory's `README.md` defines the format, how a runner replays each file, and how to report results.
601
679
 
602
- Clients distinguish three ways:
680
+ Each file carries `"protocol": 1` and the `"revision"` of this document it was written against, and each case cites the sections it checks. Where a case and this document disagree, this document wins. The TypeScript reference client (`FetchLink`, `FetchLink` with `StreamCodec`, `WsLink`) replays every file in this repository's CI. Test against a pinned package version, for example `https://cdn.jsdelivr.net/npm/@ts-pf/protocol@<version>/conformance/ws.json` (the fixtures README lists the options).
603
681
 
604
- 1. `isLocalFailure` (`local: true`) — never got a protocol result
605
- 2. `error.code` — declared / protocol codes from the envelope
606
- 3. `INTERNAL` without `local` — protocol `INTERNAL`
682
+ For a walkthrough of building a client in another language from this document (models, transport, response classification, streams, fixtures, drift), see the guide [Clients in other languages](https://github.com/crobinson42/ts-pf/blob/main/docs/other-languages.md).
607
683
 
608
- Declared `.errors()` `status` is Fetch-only. Mid-stream Fetch JSONL keeps HTTP 200. Message transports do **not** reconstruct HTTP status from `error.code`; the TypeScript `PFError.status` is `undefined` on this pipe (there is no default). Non-JS clients ignore `status` and switch on `error.code`. Do not copy `status: 200`.
684
+ ## Appendix: TypeScript reference client
685
+
686
+ Non-normative. These are the conventions of the TypeScript packages (`@ts-pf/client`, `@ts-pf/client-http`, `@ts-pf/message-client`, and the servers they talk to). They are not protocol fields, they are **not** on the wire, and other clients need not copy them. `PFError`, `isPFError`, and `asResult` are JavaScript conveniences; any HTTP client parses the envelope.
687
+
688
+ ### Constants
689
+
690
+ `PROTOCOL_MAJOR` (`1`) in `@ts-pf/protocol` is the wire major; `PROTOCOL_VERSION` (`'1'`) is its decimal string, the `x-ts-pf-protocol` value. A declared code's HTTP status comes from `httpStatus()` in `@ts-pf/http` (protocol codes → the table above, else the declared `status ?? 400`).
691
+
692
+ ### Local failures
693
+
694
+ The TypeScript client maps a local failure to a `PFError` with `code: 'INTERNAL'`, `local: true`, and `status: 0`. `isLocalFailure(error)` is `local === true` (never `status === 0`). Network throws keep `error.message` and set `Error.cause` to the thrown value (Node's `ECONNREFUSED` is then `error.cause.cause`). `toJSON()` omits `status`, `cause`, and `local`, so a server can never make a client think a failure was local.
609
695
 
610
696
  | Event | TypeScript `PFError` | `isLocalFailure` |
611
697
  |---|---|---|
612
- | `AbortSignal` while a `call` is in flight | `INTERNAL`, `local: true`, status `0`, message `Request aborted`, `cause` set; send `{ "type": "cancel", "id" }` | true |
698
+ | `AbortSignal` while a call is in flight | `INTERNAL`, `local: true`, status `0`, message `Request aborted`, `cause` set; message transports send `cancel` | true |
613
699
  | `AbortSignal` while waiting on `ready` (no id) | `INTERNAL`, `local: true`, status `0`, message `Request aborted`, `cause` set; no `cancel`; connection stays up | true |
614
- | Peer disconnect mid-call | `INTERNAL`, `local: true`, status `0`, message `Connection closed`, `cause` set | true |
615
- | Hello timeout / connect fail / hello stringify fail | `INTERNAL`, `local: true`, status `0`, message `Network error`, `cause` set; close | true |
616
- | Malformed frame from peer with no usable id (connection closes) | Inflight: `INTERNAL`, `local: true`, status `0`, message `Invalid response` or `Connection closed`, `cause` set | true |
700
+ | HTTP network error (no response) | `INTERNAL`, `local: true`, status `0`, the thrown error's message (or `Network error`), `cause` set | true |
701
+ | Peer disconnect mid-call | `INTERNAL`, `local: true`, status `0`, message `Connection closed`; `cause` only when the transport reported an error | true |
702
+ | Hello timeout / connect fail / hello stringify fail | `INTERNAL`, `local: true`, status `0`, message `Network error` (a `WsLink` socket `error` event before open: `Network error` with the event as `cause`; a close before open: `Connection closed`); close | true |
703
+ | Malformed frame from peer with no usable id (connection closes) | Inflight: `INTERNAL`, `local: true`, status `0`, message `Connection closed` (`Invalid response` / `Network error` during the handshake) | true |
617
704
  | First frame for an id is illegal | `INTERNAL`, `local: true`, status `0`, message `Invalid response`; that call only | true |
705
+ | `hello-ok` with another `v` | `INTERNAL`, `local: true`, status `0`, message `Invalid response`; close | true |
618
706
  | Protocol `result` `{ "ok": false, "error" }` | code / message / data from the envelope; `status` is `undefined` | false |
619
- | `NOT_FOUND` / `VALIDATION` / `BAD_REQUEST` from the server | as envelope | false |
620
- | Version mismatch `hello-error` | `BAD_REQUEST` from the envelope (if received) or `local: true` if the connection closed first | depends |
707
+ | `hello-error` (version mismatch, `INTERNAL`, or an application code from the server's context factory) | code / message / data from the envelope (or `local: true` if the connection closed first) | false |
621
708
  | Client refused to send oversize / could not stringify a `call` | `PAYLOAD_TOO_LARGE` or `INTERNAL` (stringify) | false |
622
709
 
710
+ ### Status on a rejected error
711
+
712
+ `PFError.status` is `number | undefined`: transport metadata, never identity, with no default. Switch on `error.code`; treat `status` as a hint and guard it (`err.status ?? 400`).
713
+
714
+ | Transport | `status` on the rejected `PFError` |
715
+ |---|---|
716
+ | HTTP unary failure (`FetchLink`) | The HTTP response status (declared `NOT_FOUND { status: 404 }` → `404`; declared code without `status` → `400`; protocol codes → the table above). A codec decode failure rethrown under `x-ts-pf-protocol: 1` keeps the codec's `400` |
717
+ | HTTP after a stream started (JSONL line / SSE `event: error`) | `undefined` (the response was already 200); a line that does not decode throws the codec's `BAD_REQUEST` with `400` |
718
+ | WebSocket / stdio / MessagePort | `undefined` (no HTTP status on a frame; `errorFromEnvelope` does not synthesize one) |
719
+ | Local failure (`localFailure`, `isLocalFailure`) | `0` with `local: true` |
720
+ | In-process `createLocalClient` | The declared `ErrorDef.status` when there is one, else `undefined` |
721
+
722
+ ### HTTP (`FetchLink`)
723
+
724
+ `FetchLink` sends `x-ts-pf-protocol: 1` on every request and classifies responses as follows. None of these is a local failure, because each response came from a server; `RetryPlugin` therefore does not retry them by default.
725
+
726
+ | Response | Rejected `PFError` |
727
+ |---|---|
728
+ | `x-ts-pf-protocol` present and not `1` | `INTERNAL`, the HTTP status, message `Unsupported protocol version (x-ts-pf-protocol: <value>)`, `cause` = the `Response`; body unread |
729
+ | No `x-ts-pf-protocol`, body does not decode | `INTERNAL`, the HTTP status, message `Non-RPC response (HTTP <status>)`, `cause` = the decode error. A proxy's HTML 404 never surfaces as `NOT_FOUND` or as the codec's `BAD_REQUEST` |
730
+ | `x-ts-pf-protocol: 1`, body does not decode | The codec's own `PFError` (`BAD_REQUEST` `Invalid JSON`, `Response body must be a JSON object`, `Invalid RPC envelope`, or `Unsupported content type` from the stream codecs), else `INTERNAL` `Invalid response` with the HTTP status |
731
+ | Decoded failure envelope | code / message / data from the envelope, `status` = the HTTP status |
732
+
733
+ `JSONCodec` does not look at the response `Content-Type`; `StreamCodec` and `SseCodec` accept `application/json` (or no content type), `application/jsonl`, and (SSE) `text/event-stream`, and reject others as `Unsupported content type`. A stream response resolves the call at once; a JSONL line or SSE event that does not decode makes the iterator throw the codec's `BAD_REQUEST`, an SSE `error` event whose `data` is a success envelope throws `INTERNAL` `Invalid error event`, and EOF without `event: close` throws `INTERNAL` `Stream truncated`. Unknown SSE event names and comments are skipped. JSONL EOF is success.
734
+
735
+ Retries are a `CallPlugin`: `createClient` retries nothing by default, and `RetryPlugin`'s default predicate is `isLocalFailure` (network errors and lost connections; never an abort), so it never retries a 5xx, 408, or 429 response unless you pass `retry`. Cross-origin browser clients read `x-ts-pf-protocol` only when the server exposes it (`CORSPlugin` `exposeHeaders: ['x-ts-pf-protocol']`).
736
+
737
+ ### Message transports
738
+
739
+ `MessageSession` defaults its hello timeout to `10_000` ms on both client and server (`helloTimeoutMs`; `0` disables it). On the server, the per-connection context factory (`bind(..., { context })`) is the hello accept: a thrown `PFError` becomes the `hello-error` (through `toWireError`, the same mapping as a handler's error), and any other throw becomes `INTERNAL` / `Internal server error`. `HandlerOptions.onError` sees the non-`PFError` throws only, as it does for handlers. `WsHandler.bind(...)` returns a handle whose `close(code?, reason?)` closes the socket with that code (default `1000`) before the session tears down; `PortHandler`, `StdioHandler`, and `DuplexHandler` handles take `close()` (those pipes have no close codes). The TypeScript packages send only `1000` and `1002` themselves. The client side does not surface the close code: calls fail with a local `Connection closed`, so an app that wants the code passes its own `socket` to `WsLink` and listens for `close` on it. `WsLink` / `PortLink` / `StdioLink` / `DuplexLink` take the hello `meta` as the `meta` option.
740
+
741
+ ### Server side (`FetchHandler`)
742
+
743
+ `FetchHandler` sets `Cache-Control: no-cache, no-transform` and `X-Accel-Buffering: no` when the codec body is a `ReadableStream`, and `x-ts-pf-protocol: 1` on every response it builds.
package/README.md CHANGED
@@ -41,16 +41,31 @@ localFailure('Request aborted') // INTERNAL with local: true, status 0 (never on
41
41
 
42
42
  The discriminator is JSON `error.code`. `status`, `cause`, and `local` never appear in the envelope (`toJSON` omits them).
43
43
 
44
- Two helpers the transports share, for codecs and adapters of your own: `toWireError(error)` is the `error` object of a failure envelope for any thrown value — a `PFError`'s `toJSON()`, anything else a fixed `{ code: 'INTERNAL', message: 'Internal server error' }` with no stack or message leak (log the original yourself). `isAsyncIterable(value)` is the one answer to "is this a stream" (a non-null object or function with a `Symbol.asyncIterator` function; a `ReadableStream` counts on Node, so exclude it at a site that wants bytes). `defined(obj)` returns a shallow copy without the keys whose value is `undefined`, typed with those keys optional — the one helper for forwarding optional fields under `exactOptionalPropertyTypes` (`{ ...required, ...defined({ signal }) }`).
44
+ Detect a failure with `isPFError(error)` rather than `instanceof PFError`: it also matches a `PFError` from another installed copy of this package (version skew, or a bundler that inlined one), through a brand on `PFError.prototype`.
45
45
 
46
- Wire spec: [`PROTOCOL.md`](https://github.com/crobinson42/ts-pf/blob/main/packages/protocol/PROTOCOL.md) (also shipped in this package). Happy path: [root README](https://github.com/crobinson42/ts-pf#readme).
46
+ Two helpers the transports share, for codecs and adapters of your own: `toWireError(error)` is the `error` object of a failure envelope for any thrown value — a `PFError`'s `toJSON()`, anything else a fixed `{ code: 'INTERNAL', message: 'Internal server error' }` with no stack or message leak (log the original yourself). The message transports use it for the `hello-error` of a refused connection too, so a `PFError` thrown from a message handler's context factory reaches the client as its code. `isAsyncIterable(value)` is the one answer to "is this a stream" (a non-null object or function with a `Symbol.asyncIterator` function; a `ReadableStream` counts on Node, so exclude it at a site that wants bytes). `defined(obj)` returns a shallow copy without the keys whose value is `undefined`, typed with those keys optional — the one helper for forwarding optional fields under `exactOptionalPropertyTypes` (`{ ...required, ...defined({ signal }) }`).
47
+
48
+ Wire spec: [`PROTOCOL.md`](https://github.com/crobinson42/ts-pf/blob/main/packages/protocol/PROTOCOL.md), revision 1.2 (also shipped in this package). It is written for implementers in any language: RFC 2119 keywords, one-screen HTTP and WebSocket client checklists, the rule for classifying an HTTP response (a body that does not decode as an envelope is a transport failure, never an application outcome read off the HTTP status), WebSocket close-code ranges, and the TypeScript client's own conventions (`local`, `status: 0`, error messages) in an appendix. Building a client in another language: the guide [Clients in other languages](https://github.com/crobinson42/ts-pf/blob/main/docs/other-languages.md). Happy path: [root README](https://github.com/crobinson42/ts-pf#readme).
49
+
50
+ Conformance fixtures: [`conformance/`](https://github.com/crobinson42/ts-pf/tree/main/packages/protocol/conformance) (also shipped in this package) holds language-neutral JSON test vectors versioned with the spec revision — `http.json` (unary requests and response classification), `http-stream.json` (JSONL streams), and `ws.json` (WebSocket frame scripts). A client written in any language replays them against its own code to prove it follows `PROTOCOL.md`; the directory's `README.md` is the runner spec. They are data, not schemas. The TypeScript clients are tested against the same files. TypeScript runners can import them typed:
51
+
52
+ ```ts
53
+ import { httpConformance, wsConformance } from '@ts-pf/protocol/conformance'
54
+
55
+ for (const testCase of httpConformance.cases) {
56
+ // testCase.request → call your client; testCase.expectRequest → check what it sent;
57
+ // testCase.response → answer it; testCase.expect → check what the caller saw.
58
+ }
59
+ ```
47
60
 
48
61
  ## API
49
62
 
50
63
  - `PFError`, `PFErrorInit`, `isPFError`, `localFailure`, `ProtocolErrorCode`
51
64
  - `PROTOCOL_MAJOR` (`1`, the wire major: `v` on message `hello`), `PROTOCOL_VERSION` (`'1'`, its string: the `x-ts-pf-protocol` header value), `RpcRequest`, `RpcResponse`, `RpcSuccess`, `RpcFailure`, `PFResultPromise`
52
65
  - `toWireError`, `isAsyncIterable`
66
+ - `isUnexpectedError(error)` — `true` for a non-`PFError` or an `INTERNAL` `PFError` (no `cause` unwrapping): what `FetchHandler` and `@ts-pf/mcp` log by default when no `onError` is given, for a custom `onError` that keeps the same filter
53
67
  - `defined`, `Defined` — `defined(obj)` drops the keys whose value is `undefined`, so `{ ...required, ...defined({ signal }) }` builds an `exactOptionalPropertyTypes` option bag without one spread per field
68
+ - `@ts-pf/protocol/conformance`: `httpConformance`, `httpStreamConformance`, `wsConformance` (the `conformance/*.json` fixtures, typed) and their types `ConformanceFile`, `HttpCase`, `HttpExpect`, `HttpStreamExpect`, `HttpStreamEnd`, `WsCase`, `WsStep`, `WsExpectation`, `ConformanceRequest`, `ConformanceError`, `JsonValue`
54
69
 
55
70
  ## Agent skills
56
71