@ts-pf/protocol 0.1.0-beta.0

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 ADDED
@@ -0,0 +1,596 @@
1
+ # ts-pf RPC Protocol v1
2
+
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
+
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
+
7
+ ## Envelope
8
+
9
+ Request value:
10
+
11
+ ```json
12
+ { "input": { "id": 1 } }
13
+ ```
14
+
15
+ Procedures with no input may omit `input` or send `null`.
16
+
17
+ Success:
18
+
19
+ ```json
20
+ { "ok": true, "output": { "id": 1, "name": "Earth" } }
21
+ ```
22
+
23
+ Failure:
24
+
25
+ ```json
26
+ { "ok": false, "error": { "code": "NOT_FOUND", "message": "...", "data": { "id": 1 } } }
27
+ ```
28
+
29
+ The procedure address is the nested router keys as `string[]` (HTTP joins them with `/`; message frames send the array).
30
+
31
+ ## HTTP Fetch binding (default)
32
+
33
+ ```
34
+ POST {prefix}/{procedure.path}
35
+ Content-Type: application/json
36
+ x-ts-pf-protocol: 1
37
+
38
+ { "input": { "id": 1 } }
39
+ ```
40
+
41
+ Procedure path is the nested router keys joined by `/`. Example: `planet.find` → `/rpc/planet/find` when the prefix is `/rpc`.
42
+
43
+ v1 accepts **POST only**. Other methods return HTTP 405 with `error.code: "METHOD_NOT_ALLOWED"`.
44
+
45
+ Success:
46
+
47
+ ```
48
+ HTTP 200
49
+ Content-Type: application/json
50
+ x-ts-pf-protocol: 1
51
+
52
+ { "ok": true, "output": { "id": 1, "name": "Earth" } }
53
+ ```
54
+
55
+ Failure:
56
+
57
+ ```
58
+ HTTP 4xx/5xx
59
+ Content-Type: application/json
60
+ x-ts-pf-protocol: 1
61
+
62
+ { "ok": false, "error": { "code": "NOT_FOUND", "message": "...", "data": { "id": 1 } } }
63
+ ```
64
+
65
+ ## Protocol errors
66
+
67
+ | Code | Status | When |
68
+ |---|---|---|
69
+ | `BAD_REQUEST` | 400 | Invalid JSON or envelope |
70
+ | `VALIDATION` | 422 | Input schema failed. `error.data.issues` is `{ message, path }[]` |
71
+ | `NOT_FOUND` | 404 | Prefix matched, procedure missing |
72
+ | `METHOD_NOT_ALLOWED` | 405 | Non-POST |
73
+ | `PAYLOAD_TOO_LARGE` | 413 | Request body larger than the configured handler limit |
74
+ | `INTERNAL` | 500 | Unknown throw. Output schema failures also use 500 (server bug). |
75
+
76
+ The discriminator is `error.code`. HTTP status is unary transport only; it is not in the JSON body.
77
+
78
+ 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.
79
+
80
+ 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`.
81
+
82
+ 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.
83
+
84
+ TypeScript `PFError`, `instanceof`, and `asResult` are JS conveniences. They are not required to consume the API. Any HTTP client parses this envelope.
85
+
86
+ Contract-declared error codes use the status on the error definition.
87
+
88
+ 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 (truncated JSONL/SSE at decode time, malformed ts-pf JSON). `toJSON()` still omits `status`, `cause`, and `local`.
89
+
90
+ ## Versioning
91
+
92
+ Header `x-ts-pf-protocol` is `1`. 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 version as `v: 1` on `hello` instead of this header. Bump the header only if the JSON contract breaks.
93
+
94
+ ## Binary attachments (optional)
95
+
96
+ JSON-only clients can ignore this section. The envelope keys stay `{ "input" }`, `{ "ok": true, "output" }`, and `{ "ok": false, "error" }`. Files are extra HTTP parts, not a different RPC.
97
+
98
+ | Condition | Content-Type | Body |
99
+ |---|---|---|
100
+ | No files in the value tree | `application/json` | Envelope above |
101
+ | One or more `File`/`Blob` values | `multipart/form-data` | Envelope in part `rpc` plus numbered file parts |
102
+ | Any failure | `application/json` | Failure envelope above |
103
+
104
+ A server that accepts multipart must still accept `application/json` so existing JSON clients keep working.
105
+
106
+ ### Multipart request
107
+
108
+ ```
109
+ POST {prefix}/{procedure.path}
110
+ Content-Type: multipart/form-data; boundary=----ts-pf
111
+ x-ts-pf-protocol: 1
112
+
113
+ ------ts-pf
114
+ Content-Disposition: form-data; name="rpc"
115
+ Content-Type: application/json
116
+
117
+ {"input":{"name":"Earth","photo":{"$pf":"file","id":"0"}}}
118
+ ------ts-pf
119
+ Content-Disposition: form-data; name="0"; filename="earth.png"
120
+ Content-Type: image/png
121
+
122
+ <bytes>
123
+ ------ts-pf--
124
+ ```
125
+
126
+ - Part `rpc` is the JSON envelope. There is no sibling `files` / `maps` field.
127
+ - File parts are named with decimal ids `"0"`, `"1"`, … matching the placeholder `id`.
128
+ - `filename` is the portable name (strip path segments). Unnamed blobs may use `blob`.
129
+ - Part `Content-Type` is the MIME type (`application/octet-stream` if omitted).
130
+ - Part order is not significant. Missing or extra file parts are `BAD_REQUEST`.
131
+ - `{ "$pf": "file", "id": "..." }` in a JSON-only body is `BAD_REQUEST`. `$pf` is reserved when using this content type.
132
+
133
+ Root-level file input:
134
+
135
+ ```json
136
+ {"input":{"$pf":"file","id":"0"}}
137
+ ```
138
+
139
+ Success responses use the same framing; part `rpc` is `{ "ok": true, "output": ... }`.
140
+
141
+ ```bash
142
+ curl -X POST "$HOST/rpc/planet/create" \
143
+ -H "x-ts-pf-protocol: 1" \
144
+ -F 'rpc={"input":{"name":"Earth","photo":{"$pf":"file","id":"0"}}};type=application/json' \
145
+ -F '0=@earth.png;type=image/png'
146
+ ```
147
+
148
+ ## Message streams (optional)
149
+
150
+ JSON-only clients can ignore this section. A **root** `AsyncIterable` (async generator) is a sequence of the same envelopes, one compact JSON value per line.
151
+
152
+ | Condition | Content-Type | Body |
153
+ |---|---|---|
154
+ | No stream | `application/json` | Envelope above |
155
+ | Root stream input or output | `application/jsonl` | One envelope per line |
156
+ | Failure **before** the stream starts | `application/json` | Failure envelope above |
157
+ | Failure **after** the stream starts | `application/jsonl` | `{ "ok": false, "error": … }` line, then EOF |
158
+
159
+ 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`.
160
+
161
+ Output:
162
+
163
+ 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`.
164
+
165
+ ```
166
+ HTTP/1.1 200
167
+ Content-Type: application/jsonl
168
+ Cache-Control: no-cache, no-transform
169
+ X-Accel-Buffering: no
170
+ x-ts-pf-protocol: 1
171
+
172
+ {"ok":true,"output":{"token":"Hel"}}
173
+ {"ok":true,"output":{"token":"lo"}}
174
+ ```
175
+
176
+ Input (the procedure input **is** the stream):
177
+
178
+ ```
179
+ POST {prefix}/{procedure.path}
180
+ Content-Type: application/jsonl
181
+ x-ts-pf-protocol: 1
182
+
183
+ {"input":{"chunk":1}}
184
+ {"input":{"chunk":2}}
185
+ ```
186
+
187
+ EOF is a successful close. There is no `done` field on the envelope.
188
+
189
+ `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.
190
+
191
+ ```bash
192
+ # JSON input, JSONL output
193
+ curl -N -X POST "$HOST/rpc/chat" \
194
+ -H "x-ts-pf-protocol: 1" \
195
+ -H "content-type: application/json" \
196
+ -d '{"input":{"prompt":"hi"}}'
197
+
198
+ # JSONL input
199
+ curl -N -X POST "$HOST/rpc/ingest" \
200
+ -H "x-ts-pf-protocol: 1" \
201
+ -H "content-type: application/jsonl" \
202
+ --data-binary $'{"input":{"chunk":1}}\n{"input":{"chunk":2}}\n'
203
+ ```
204
+
205
+ ## SSE (optional)
206
+
207
+ JSON-only clients can ignore this section. SSE is **output-only** framing of the same envelopes as [message streams](#message-streams-optional). Input streams stay `application/jsonl`. Request `Content-Type: text/event-stream` is `BAD_REQUEST`.
208
+
209
+ | Condition | Content-Type |
210
+ |---|---|
211
+ | Unary / pre-stream failure | `application/json` |
212
+ | Root stream input | `application/jsonl` |
213
+ | Root stream output | `text/event-stream` |
214
+
215
+ ```
216
+ HTTP/1.1 200
217
+ Content-Type: text/event-stream
218
+ Cache-Control: no-cache, no-transform
219
+ X-Accel-Buffering: no
220
+ x-ts-pf-protocol: 1
221
+
222
+ :
223
+
224
+ event: message
225
+ data: {"ok":true,"output":{"token":"Hel"}}
226
+
227
+ event: message
228
+ data: {"ok":true,"output":{"token":"lo"}}
229
+
230
+ event: close
231
+
232
+ ```
233
+
234
+ Mid-stream failure (HTTP already 200):
235
+
236
+ ```
237
+ event: error
238
+ data: {"ok":false,"error":{"code":"INTERNAL","message":"upstream died"}}
239
+
240
+ ```
241
+
242
+ Then the body ends. Do not send `close` after `error`.
243
+
244
+ | SSE `event` | Meaning | `data` |
245
+ |---|---|---|
246
+ | `message` | yield | success envelope (one compact JSON line) |
247
+ | `error` | in-band failure, then stop | failure envelope |
248
+ | `close` | successful EOF | none. Framing only — not an envelope |
249
+ | comment (`:`) | keepalive / header flush | n/a |
250
+
251
+ `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.
252
+
253
+ The TypeScript client parses `fetch` response bodies. Native `EventSource` is not an RPC client (GET-only, no custom headers, auto-reconnects).
254
+
255
+ ```bash
256
+ curl -N -X POST "$HOST/rpc/chat" \
257
+ -H "x-ts-pf-protocol: 1" \
258
+ -H "content-type: application/json" \
259
+ -d '{"input":{"prompt":"hi"}}'
260
+ # response: text/event-stream
261
+ ```
262
+
263
+ ## Message transports (optional)
264
+
265
+ JSON-HTTP clients can ignore this section. The same RPC runs over WebSocket, stdio, or MessagePort as multiplexed JSON **text** frames. Envelope keys inside those frames stay `{ "input" }`, `{ "ok": true, "output" }`, and `{ "ok": false, "error": { "code", "message", "data?" } }`. The discriminator is still `error.code`.
266
+
267
+ These bindings are not HTTP:
268
+
269
+ - Files / `multipart/form-data` are Fetch-only. See [Binary attachments](#binary-attachments-optional). Do not invent a binary attachment framing here.
270
+ - SSE (`text/event-stream`) is Fetch-only. See [SSE](#sse-optional). Do not send SSE over a socket.
271
+ - HTTP status is Fetch-only. It is not a field on a frame.
272
+ - `METHOD_NOT_ALLOWED` is Fetch-only. There is no HTTP method on a frame.
273
+ - Procedure-declared `.errors()` `status` is Fetch-only. Every client, including TypeScript, switches on `error.code`.
274
+
275
+ `v: 1` on `hello` / `hello-ok` is the same protocol version as header `x-ts-pf-protocol: 1`. Different carrier, same number.
276
+
277
+ ### Framing
278
+
279
+ 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).
280
+
281
+ | Binding | Byte / message framing |
282
+ |---|---|
283
+ | WebSocket | One JSON string per WebSocket **text** message. Binary frames: close with no parse. Close code `1002`. |
284
+ | MessagePort | One JSON string per `postMessage`. Not structured clone of the object. Non-string data: close with no parse. |
285
+ | stdio | UTF-8 NDJSON. Split on `\n`. Strip an optional trailing `\r` and surrounding whitespace on **every** line (so `\r\n` works, matching HTTP JSONL). Empty lines ignored. Trailing partial line on EOF: if non-empty after that strip, treat it as a complete frame; if it fails decode, close. |
286
+
287
+ ### Frame types
288
+
289
+ | `type` | Allowed keys | Required |
290
+ |---|---|---|
291
+ | `hello` | `type`, `v`, `meta` | `v` |
292
+ | `hello-ok` | `type`, `v` | `v` |
293
+ | `hello-error` | `type`, `error` | `error` |
294
+ | `call` | `type`, `id`, `path`, `input`, `stream` | `id`, `path` |
295
+ | `result` | `type`, `id`, `ok`, `output`, `error` | `id`, `ok` |
296
+ | `cancel` | `type`, `id` | `id` |
297
+ | `item` | `type`, `id`, `output` | `id` |
298
+ | `done` | `type`, `id` | `id` |
299
+ | `in-item` | `type`, `id`, `input` | `id` |
300
+ | `in-done` | `type`, `id` | `id` |
301
+
302
+ A present key that is not in the allow-list is invalid. Missing a required field is invalid. Include a decoded `id` on a decode failure only when it is already a non-empty string.
303
+
304
+ Each type travels one way:
305
+
306
+ | Direction | `type` |
307
+ |---|---|
308
+ | Client → server | `hello`, `call`, `cancel`, `in-item`, `in-done` |
309
+ | Server → client | `hello-ok`, `hello-error`, `result`, `item`, `done` |
310
+
311
+ A well-behaved peer never sends the wrong direction. After `ready`, treat a wrong-direction frame as an unknown type. Decode may still succeed if the shape is valid; the receiver then applies the [first-frame](#first-frame-client) / [multiplex](#multiplex) ignore rules. A wrong-direction frame with a usable `id` that is not a legal next event is ignored, or `Invalid response` if it is the first frame for that id. Do not invent a new error code.
312
+
313
+ | Field | Rule |
314
+ |---|---|
315
+ | `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. |
316
+ | `path` | Array of strings (may be empty). Not `"planet/find"`. A non-string element is invalid. |
317
+ | `v` | JSON number. Handshake uses the version check below. `"1"` is not a number. |
318
+ | `ok` | Boolean. Required on `result`. |
319
+ | `stream` | Literal `true` or omitted. `false`, `1`, `"true"` are invalid. |
320
+ | `input` on `call` | Omitted or `null` means no input (same as JSON HTTP). Any other JSON value is the input. **Invalid if `stream` is `true` and `input` is present** (including `null`). |
321
+ | `output` on `result` with `ok: true` | Optional. Omitted ⇒ `undefined`. Must not be present when `ok: false`. |
322
+ | `error` on `result` | Required when `ok: false`. Must not be present when `ok: true`. |
323
+ | `error` object | Keys only `code`, `message`, `data?`. `code` is a non-empty string. `message` is a string (may be empty). Extra keys on `error` are invalid. No `status`. No `cause`. |
324
+ | Extra keys on a known `type` | Invalid. |
325
+ | `meta` on `hello` | Any JSON value, untrusted. Omit when the client did not send it. |
326
+
327
+ Omit `input` / `output` / `data` / `meta` / `stream` when they have no value. Never send JSON `undefined`. Void procedures therefore emit `{"type":"result","id":"1","ok":true}`. Receivers treat omitted `output` as `undefined`.
328
+
329
+ ### Handshake
330
+
331
+ HTTP equivalent of header `x-ts-pf-protocol: 1`. Hello is not a `call` and has no `id`.
332
+
333
+ ```json
334
+ { "type": "hello", "v": 1 }
335
+ { "type": "hello", "v": 1, "meta": { "token": "…" } }
336
+ { "type": "hello-ok", "v": 1 }
337
+ { "type": "hello-error", "error": { "code": "BAD_REQUEST", "message": "Unsupported protocol version" } }
338
+ ```
339
+
340
+ **Server connection states:** `waiting-hello` → `ready` → `closed`.
341
+
342
+ **Order is locked:** valid hello → server accepts it (may await a per-connection context factory) → `hello-ok`. The server stays in `waiting-hello` until that accept settles. Do **not** buffer `call` frames during the wait. A well-behaved client does not send `call` until `hello-ok`. A `call` during `waiting-hello` is `Expected hello` then close.
343
+
344
+ `waiting-hello` inbound:
345
+
346
+ 1. Inbound over-limit / binary / non-string / `JSON.parse` throw / parsed value is not a non-array object → **close with no frame**.
347
+ 2. Else `JSON.parse` produced an object. Look at `type` and `v` **before** treating the object as a fully valid frame.
348
+ 3. If `type` is `"hello"`, check `v`:
349
+
350
+ | `v` after `JSON.parse` | Action |
351
+ |---|---|
352
+ | Not a JSON number (missing, `"1"`, `true`, `null`, …) | `{ "type": "hello-error", "error": { "code": "BAD_REQUEST", "message": "Invalid hello" } }` then close. |
353
+ | JSON number and `v === 1` | Valid hello **if** the rest of the object is a legal `hello` (no extra keys). Then accept (row below). Extra keys / other field errors still `Invalid hello`. |
354
+ | JSON number and `v !== 1` (including `2`, `0`, `1.5`) | `{ "type": "hello-error", "error": { "code": "BAD_REQUEST", "message": "Unsupported protocol version" } }` then close. Numeric mismatch wins over extra keys. |
355
+
356
+ 4. Branch on the rest:
357
+
358
+ | Condition | Action |
359
+ |---|---|
360
+ | 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`. |
361
+ | 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). |
362
+
363
+ 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.
364
+
365
+ **Client connection states:** `connecting` → `handshaking` → `ready` → `closed`.
366
+
367
+ The client sends `hello` as soon as the duplex is open. `call` waits for `ready`.
368
+
369
+ If `JSON.parse` produced an object with `type: "hello-ok"`, check `v` the same way (numeric `v !== 1` is a version mismatch). The client does not send `hello-error`; it fails `ready` locally:
370
+
371
+ | `v` on `hello-ok` | Action |
372
+ |---|---|
373
+ | JSON number and `v === 1`, otherwise valid | Become `ready`. |
374
+ | Not a JSON number | Fail the connect as a local `Invalid response`. Close. |
375
+ | JSON number and `v !== 1` (including `2`, `0`, `1.5`) | Fail the connect as a local `Invalid response`. Close. |
376
+
377
+ | Received while `handshaking` | Action |
378
+ |---|---|
379
+ | Valid `hello-ok` (`v === 1`) | Become `ready`. |
380
+ | Valid `hello-error` | Fail the connect with that `error` (typically `BAD_REQUEST` / `INTERNAL`, not status 0). Close. |
381
+ | Anything else parsed (wrong type, extra keys, invalid `v` as above) | Fail the connect as a local `Invalid response`. Close. |
382
+ | Unparseable / close / timeout | Fail the connect as a local `Network error` or `Connection closed`. |
383
+
384
+ On hello timeout: local `Network error`, then close. Callers who disable the timeout must abort via `AbortSignal` or close the connection.
385
+
386
+ ### Multiplex
387
+
388
+ **At most one terminal frame per id.** Terminal frames are:
389
+
390
+ - `{ "type": "result", … }` (unary success, unary / application / protocol error, or mid-stream error)
391
+ - `{ "type": "done", "id" }` (successful output-stream EOF)
392
+
393
+ After a terminal frame, the id is free for reuse. Until then:
394
+
395
+ | Event | Action |
396
+ |---|---|
397
+ | 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. |
398
+ | Unknown / invalid frame whose `id` is in-flight | **Ignore.** Do not settle that call. Do not send a second `result`. |
399
+ | 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. |
400
+ | Unknown / invalid frame with no usable id, **after `ready`** | Close. No `hello-error` (handshake is over). |
401
+ | `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). |
402
+
403
+ 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.
404
+
405
+ The connection keeps reading frames while a call runs. Two in-flight ids complete independently.
406
+
407
+ ### Size limits
408
+
409
+ Option omitted = **unlimited in both directions** (same as Fetch without a request-limit plugin).
410
+
411
+ **Inbound** (every received string / stdio line buffer):
412
+
413
+ 1. Measure UTF-8 byte length.
414
+ 2. If a max is set and `length` exceeds it → **close**. Do not `JSON.parse`. Do not extract an id. Do not send `PAYLOAD_TOO_LARGE`.
415
+ 3. For stdio: if the *unterminated* line buffer exceeds the max before `\n` → close, drop the buffer.
416
+
417
+ **Outbound** is what peers see. `PAYLOAD_TOO_LARGE` is the protocol code reused from HTTP 413; the HTTP meaning does not apply on this transport. Do not leak serializer messages (`Do not know how to serialize a BigInt`) onto the wire.
418
+
419
+ | Intended outbound frame | If it cannot be sent (oversize or cannot stringify) |
420
+ |---|---|
421
+ | `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. |
422
+ | `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. |
423
+
424
+ ### Unary call
425
+
426
+ ```json
427
+ { "type": "call", "id": "1", "path": ["planet", "find"], "input": { "id": 1 } }
428
+ { "type": "result", "id": "1", "ok": true, "output": { "id": 1, "name": "Earth" } }
429
+ { "type": "result", "id": "1", "ok": false, "error": { "code": "NOT_FOUND", "message": "...", "data": { "id": 1 } } }
430
+ { "type": "cancel", "id": "1" }
431
+ ```
432
+
433
+ - Unknown path → `NOT_FOUND` (same as Fetch after a prefix match).
434
+ - `METHOD_NOT_ALLOWED` is not used.
435
+ - `cancel` of an unknown / already-finished id is a no-op.
436
+
437
+ 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.
438
+
439
+ HTTP distinguishes unary vs stream via `Content-Type`. Message frames have no content type. The client uses the **first inbound frame for that id**.
440
+
441
+ #### First frame (client)
442
+
443
+ After sending `call` (and while possibly sending `in-item` / `in-done` if `call.stream === true`), wait for the first inbound frame with this `id`:
444
+
445
+ | First frame | Client action |
446
+ |---|---|
447
+ | `result` `ok: true` | Resolve to `output` (possibly `undefined`). Unary done. |
448
+ | `result` `ok: false` | Reject with that `error`. |
449
+ | `item` | Resolve to an async iterable whose first `next()` yields this `output`; then continue in `streaming-out`. |
450
+ | `done` | Resolve to an async iterable that immediately completes (empty stream; JSONL uses EOF, multiplex cannot). |
451
+ | `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. |
452
+ | Peer close before any frame | Reject as local `Connection closed`. |
453
+
454
+ 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`).
455
+
456
+ #### `streaming-out` (after the promise resolved to an async iterable)
457
+
458
+ Further frames drive the **iterator**, not the call promise.
459
+
460
+ | Event | Action |
461
+ |---|---|
462
+ | `item` | Yield `output` (omitted → `undefined`). |
463
+ | `done` | Complete the iterator. |
464
+ | `result` `ok: false` | **Reject the iterator** with that `error`. This is the legal mid-stream error, **not** the “in-flight → ignore” rule. No `done`. |
465
+ | `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. |
466
+ | Peer close / client close | Reject the iterator as local `Connection closed` if not already done. |
467
+ | 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. |
468
+
469
+ `for-await` `break` and iterator `return()` are the Fetch-body-cancel equivalent.
470
+
471
+ #### Input-stream send path
472
+
473
+ | Event | Action |
474
+ |---|---|
475
+ | Input is an async iterable | Send `call` with `"stream": true` and **no** `input`. Then pull the generator: each yield → `in-item`; normal completion → `in-done`. Start immediately; do not wait for a server frame. |
476
+ | Input generator **throws** or `return()` before normal completion | Send `{ "type": "cancel", "id" }` (**not** `in-done`). Throw is not a successful close. Stop sending `in-item`. |
477
+ | Any **terminal** inbound frame (`result` or `done`) or local cancel | **Stop** sending `in-item` / `in-done`. The server ignores late `in-*` after a terminal. |
478
+ | Server `result` before client `in-done` | Legal (the procedure does not wait for EOF). Client stops `in-item`. |
479
+
480
+ #### Legal sequences
481
+
482
+ **Unary** (no `stream` on `call`, output is a value):
483
+
484
+ ```
485
+ C: call
486
+ S: result ok:true | result ok:false
487
+ ```
488
+
489
+ **Output-only stream** (`call` without `stream`, output is an async iterable):
490
+
491
+ ```
492
+ C: call
493
+ S: item* done
494
+ | item* result ok:false // mid-stream error; NO done
495
+ | result ok:false // failed before the first item (still a result, not item)
496
+ ```
497
+
498
+ Empty successful stream: `done` with zero `item`s.
499
+
500
+ **Input-only stream** (`call.stream: true`, output is a value):
501
+
502
+ ```
503
+ C: call stream:true
504
+ C: in-item* in-done
505
+ S: result ok:true | result ok:false
506
+ ```
507
+
508
+ `in-item` / `in-done` may be sent immediately after `call`. The server starts the procedure with an async-iterable input as soon as `call` is accepted (does not wait for `in-done`).
509
+
510
+ **Duplex** (input stream + output stream). `in-item` and `item` **interleave** on one id:
511
+
512
+ ```
513
+ C: call stream:true
514
+ C: in-item*
515
+ S: item*
516
+ C: in-item* / in-done
517
+ S: item* / done | result ok:false
518
+ ```
519
+
520
+ **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):
521
+
522
+ - `result ok: true` after an `item` or `done`
523
+ - `item` or `done` after a unary `result`
524
+ - `item` after `done`
525
+ - `done` after `result ok: false`
526
+ - `done` after `done`
527
+ - second `result` of any kind
528
+ - `call.stream: true` together with `input`
529
+ - `stream: false` / `stream: 1`
530
+ - `in-item` after `in-done`
531
+ - second `in-done`
532
+ - `in-item` or `in-done` for an id whose `call` did not have `stream: true`
533
+
534
+ Late frames after a terminal (including after client cancel) are ignored. They do not close the connection.
535
+
536
+ ### Output streams
537
+
538
+ ```json
539
+ { "type": "item", "id": "1", "output": { "token": "Hel" } }
540
+ { "type": "item", "id": "1", "output": { "token": "lo" } }
541
+ { "type": "done", "id": "1" }
542
+ ```
543
+
544
+ Mid-stream failure: `{ "type": "result", "id": "1", "ok": false, "error": { … } }` then stop. **Do not send `done` after error.** Same as JSONL (failure line, then EOF) and SSE (no `close` after `error`).
545
+
546
+ Nested streams and `File` / `Blob` values inside items are `BAD_REQUEST`.
547
+
548
+ ### Input streams
549
+
550
+ ```json
551
+ { "type": "call", "id": "1", "path": ["planet", "ingest"], "stream": true }
552
+ { "type": "in-item", "id": "1", "input": { "chunk": 1 } }
553
+ { "type": "in-done", "id": "1" }
554
+ ```
555
+
556
+ 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 implicit (JS queue / pipe buffer). No credit-based flow control in v1. Cancel of the call aborts both sides.
557
+
558
+ ### Cancel and mid-stream errors
559
+
560
+ **No frames for this id after cancel or after a terminal frame.** A late procedure completion must not send.
561
+
562
+ | Catch | Action |
563
+ |---|---|
564
+ | 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. |
565
+ | Unknown throw | `{ "type": "result", "id", "ok": false, "error": { "code": "INTERNAL", "message": "Internal server error" } }`. If cancelled, still invoke any local error hook, send nothing. |
566
+ | Abort after client `cancel` (generator checks `signal` and throws `AbortError`) | Send **nothing**. Prefer silence. Do not encode `INTERNAL`. |
567
+ | Client abort while **in flight** (a `call` was sent) | Send `{ "type": "cancel", "id" }`. Reject local as `Request aborted`. Ignore late `result` / `item` / `done`. |
568
+ | 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`. |
569
+ | Output-stream cancel (iterator `return()` / `throw()` / `AbortSignal`) | Client sends `{ "type": "cancel", "id" }` (not `in-done`). Server aborts, stops emitting, ends any input queue. |
570
+ | Input generator throw / early `return()` | Client sends `{ "type": "cancel", "id" }` (not `in-done`). Same server cancel path. |
571
+
572
+ ### Local failure vs protocol failure
573
+
574
+ 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`.
575
+
576
+ Clients distinguish three ways:
577
+
578
+ 1. `isLocalFailure` (`local: true`) — never got a protocol result
579
+ 2. `error.code` — declared / protocol codes from the envelope
580
+ 3. `INTERNAL` without `local` — protocol `INTERNAL`
581
+
582
+ 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` default is 400. Non-JS clients ignore `status` and switch on `error.code`. Do not copy `status: 200`.
583
+
584
+ | Event | TypeScript `PFError` | `isLocalFailure` |
585
+ |---|---|---|
586
+ | `AbortSignal` while a `call` is in flight | `INTERNAL`, `local: true`, status `0`, message `Request aborted`, `cause` set; send `{ "type": "cancel", "id" }` | true |
587
+ | `AbortSignal` while waiting on `ready` (no id) | `INTERNAL`, `local: true`, status `0`, message `Request aborted`, `cause` set; no `cancel`; connection stays up | true |
588
+ | Peer disconnect mid-call | `INTERNAL`, `local: true`, status `0`, message `Connection closed`, `cause` set | true |
589
+ | Hello timeout / connect fail / hello stringify fail | `INTERNAL`, `local: true`, status `0`, message `Network error`, `cause` set; close | true |
590
+ | 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 |
591
+ | First frame for an id is illegal | `INTERNAL`, `local: true`, status `0`, message `Invalid response`; that call only | true |
592
+ | Protocol `result` `{ "ok": false, "error" }` | code / message / data from the envelope; `status` defaults to 400 | false |
593
+ | `NOT_FOUND` / `VALIDATION` / `BAD_REQUEST` from the server | as envelope | false |
594
+ | Version mismatch `hello-error` | `BAD_REQUEST` from the envelope (if received) or `local: true` if the connection closed first | depends |
595
+ | Client refused to send oversize / could not stringify a `call` | `PAYLOAD_TOO_LARGE` or `INTERNAL` (stringify) | false |
596
+
package/README.md ADDED
@@ -0,0 +1,7 @@
1
+ # @ts-pf/protocol
2
+
3
+ Portable JSON envelope, `PFError`, and `PROTOCOL_VERSION`. No HTTP server, no schemas, no codecs.
4
+
5
+ Agent skill: [`skills/ts-pf-protocol/`](skills/ts-pf-protocol/). Sync with `npx skills experimental_sync -y`.
6
+
7
+ Wire spec: [`PROTOCOL.md`](PROTOCOL.md).
@@ -0,0 +1,21 @@
1
+ export declare const PROTOCOL_VERSION = "1";
2
+ export type RpcRequest = {
3
+ input?: unknown;
4
+ };
5
+ export type RpcSuccess<T = unknown> = {
6
+ ok: true;
7
+ output: T;
8
+ };
9
+ export type RpcFailure = {
10
+ ok: false;
11
+ error: {
12
+ code: string;
13
+ message: string;
14
+ data?: unknown;
15
+ };
16
+ };
17
+ export type RpcResponse<T = unknown> = RpcSuccess<T> | RpcFailure;
18
+ export interface PFResultPromise<T, E> extends Promise<T> {
19
+ readonly '~pfError'?: E;
20
+ }
21
+ //# sourceMappingURL=envelope.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"envelope.d.ts","sourceRoot":"","sources":["../src/envelope.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,gBAAgB,MAAM,CAAA;AAEnC,MAAM,MAAM,UAAU,GAAG;IAAE,KAAK,CAAC,EAAE,OAAO,CAAA;CAAE,CAAA;AAE5C,MAAM,MAAM,UAAU,CAAC,CAAC,GAAG,OAAO,IAAI;IAAE,EAAE,EAAE,IAAI,CAAC;IAAC,MAAM,EAAE,CAAC,CAAA;CAAE,CAAA;AAE7D,MAAM,MAAM,UAAU,GAAG;IACvB,EAAE,EAAE,KAAK,CAAA;IACT,KAAK,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,OAAO,CAAA;KAAE,CAAA;CACzD,CAAA;AAED,MAAM,MAAM,WAAW,CAAC,CAAC,GAAG,OAAO,IAAI,UAAU,CAAC,CAAC,CAAC,GAAG,UAAU,CAAA;AAEjE,MAAM,WAAW,eAAe,CAAC,CAAC,EAAE,CAAC,CAAE,SAAQ,OAAO,CAAC,CAAC,CAAC;IACvD,QAAQ,CAAC,UAAU,CAAC,EAAE,CAAC,CAAA;CACxB"}
@@ -0,0 +1,2 @@
1
+ export const PROTOCOL_VERSION = '1';
2
+ //# sourceMappingURL=envelope.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"envelope.js","sourceRoot":"","sources":["../src/envelope.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,gBAAgB,GAAG,GAAG,CAAA"}
@@ -0,0 +1,31 @@
1
+ export type PFErrorInit<TCode extends string = string, TData = unknown> = {
2
+ code: TCode;
3
+ status?: number;
4
+ message?: string;
5
+ data?: TData;
6
+ cause?: unknown;
7
+ local?: true;
8
+ };
9
+ export declare class PFError<TCode extends string = string, TData = unknown> extends Error {
10
+ readonly code: TCode;
11
+ readonly status: number;
12
+ readonly data?: TData;
13
+ readonly local?: true;
14
+ constructor(init: PFErrorInit<TCode, TData>);
15
+ toJSON(): {
16
+ code: TCode;
17
+ message: string;
18
+ data?: TData;
19
+ };
20
+ }
21
+ export declare function isPFError(value: unknown): value is PFError;
22
+ export declare function localFailure(message: string, cause?: unknown): PFError;
23
+ export declare const ProtocolErrorCode: {
24
+ readonly BAD_REQUEST: "BAD_REQUEST";
25
+ readonly VALIDATION: "VALIDATION";
26
+ readonly NOT_FOUND: "NOT_FOUND";
27
+ readonly INTERNAL: "INTERNAL";
28
+ readonly METHOD_NOT_ALLOWED: "METHOD_NOT_ALLOWED";
29
+ readonly PAYLOAD_TOO_LARGE: "PAYLOAD_TOO_LARGE";
30
+ };
31
+ //# sourceMappingURL=error.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error.d.ts","sourceRoot":"","sources":["../src/error.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,WAAW,CAAC,KAAK,SAAS,MAAM,GAAG,MAAM,EAAE,KAAK,GAAG,OAAO,IAAI;IACxE,IAAI,EAAE,KAAK,CAAA;IACX,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,IAAI,CAAC,EAAE,KAAK,CAAA;IACZ,KAAK,CAAC,EAAE,OAAO,CAAA;IACf,KAAK,CAAC,EAAE,IAAI,CAAA;CACb,CAAA;AAED,qBAAa,OAAO,CAClB,KAAK,SAAS,MAAM,GAAG,MAAM,EAC7B,KAAK,GAAG,OAAO,CACf,SAAQ,KAAK;IACb,QAAQ,CAAC,IAAI,EAAE,KAAK,CAAA;IACpB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,QAAQ,CAAC,IAAI,CAAC,EAAE,KAAK,CAAA;IACrB,QAAQ,CAAC,KAAK,CAAC,EAAE,IAAI,CAAA;gBAET,IAAI,EAAE,WAAW,CAAC,KAAK,EAAE,KAAK,CAAC;IAkB3C,MAAM,IAAI;QAAE,IAAI,EAAE,KAAK,CAAC;QAAC,OAAO,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,KAAK,CAAA;KAAE;CAUzD;AAED,wBAAgB,SAAS,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,OAAO,CAE1D;AAED,wBAAgB,YAAY,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO,GAAG,OAAO,CAQtE;AAED,eAAO,MAAM,iBAAiB;;;;;;;CAOpB,CAAA"}
package/dist/error.js ADDED
@@ -0,0 +1,55 @@
1
+ export class PFError extends Error {
2
+ code;
3
+ status;
4
+ data;
5
+ local;
6
+ constructor(init) {
7
+ const message = init.message ?? init.code;
8
+ if ('cause' in init) {
9
+ super(message, { cause: init.cause });
10
+ }
11
+ else {
12
+ super(message);
13
+ }
14
+ this.name = 'PFError';
15
+ this.code = init.code;
16
+ this.status = init.status ?? 400;
17
+ if (init.data !== undefined) {
18
+ this.data = init.data;
19
+ }
20
+ if (init.local === true) {
21
+ this.local = true;
22
+ }
23
+ }
24
+ toJSON() {
25
+ const json = {
26
+ code: this.code,
27
+ message: this.message,
28
+ };
29
+ if (this.data !== undefined) {
30
+ json.data = this.data;
31
+ }
32
+ return json;
33
+ }
34
+ }
35
+ export function isPFError(value) {
36
+ return value instanceof PFError;
37
+ }
38
+ export function localFailure(message, cause) {
39
+ return new PFError({
40
+ code: 'INTERNAL',
41
+ status: 0,
42
+ local: true,
43
+ message,
44
+ ...(cause !== undefined ? { cause } : {}),
45
+ });
46
+ }
47
+ export const ProtocolErrorCode = {
48
+ BAD_REQUEST: 'BAD_REQUEST',
49
+ VALIDATION: 'VALIDATION',
50
+ NOT_FOUND: 'NOT_FOUND',
51
+ INTERNAL: 'INTERNAL',
52
+ METHOD_NOT_ALLOWED: 'METHOD_NOT_ALLOWED',
53
+ PAYLOAD_TOO_LARGE: 'PAYLOAD_TOO_LARGE',
54
+ };
55
+ //# sourceMappingURL=error.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error.js","sourceRoot":"","sources":["../src/error.ts"],"names":[],"mappings":"AASA,MAAM,OAAO,OAGX,SAAQ,KAAK;IACJ,IAAI,CAAO;IACX,MAAM,CAAQ;IACd,IAAI,CAAQ;IACZ,KAAK,CAAO;IAErB,YAAY,IAA+B;QACzC,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,IAAI,IAAI,CAAC,IAAI,CAAA;QACzC,IAAI,OAAO,IAAI,IAAI,EAAE,CAAC;YACpB,KAAK,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC,CAAA;QACvC,CAAC;aAAM,CAAC;YACN,KAAK,CAAC,OAAO,CAAC,CAAA;QAChB,CAAC;QACD,IAAI,CAAC,IAAI,GAAG,SAAS,CAAA;QACrB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAA;QACrB,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,IAAI,GAAG,CAAA;QAChC,IAAI,IAAI,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;YAC5B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAA;QACvB,CAAC;QACD,IAAI,IAAI,CAAC,KAAK,KAAK,IAAI,EAAE,CAAC;YACxB,IAAI,CAAC,KAAK,GAAG,IAAI,CAAA;QACnB,CAAC;IACH,CAAC;IAED,MAAM;QACJ,MAAM,IAAI,GAAmD;YAC3D,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,OAAO,EAAE,IAAI,CAAC,OAAO;SACtB,CAAA;QACD,IAAI,IAAI,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;YAC5B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAA;QACvB,CAAC;QACD,OAAO,IAAI,CAAA;IACb,CAAC;CACF;AAED,MAAM,UAAU,SAAS,CAAC,KAAc;IACtC,OAAO,KAAK,YAAY,OAAO,CAAA;AACjC,CAAC;AAED,MAAM,UAAU,YAAY,CAAC,OAAe,EAAE,KAAe;IAC3D,OAAO,IAAI,OAAO,CAAC;QACjB,IAAI,EAAE,UAAU;QAChB,MAAM,EAAE,CAAC;QACT,KAAK,EAAE,IAAI;QACX,OAAO;QACP,GAAG,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KAC1C,CAAC,CAAA;AACJ,CAAC;AAED,MAAM,CAAC,MAAM,iBAAiB,GAAG;IAC/B,WAAW,EAAE,aAAa;IAC1B,UAAU,EAAE,YAAY;IACxB,SAAS,EAAE,WAAW;IACtB,QAAQ,EAAE,UAAU;IACpB,kBAAkB,EAAE,oBAAoB;IACxC,iBAAiB,EAAE,mBAAmB;CAC9B,CAAA"}
@@ -0,0 +1,3 @@
1
+ export { type PFResultPromise, PROTOCOL_VERSION, type RpcFailure, type RpcRequest, type RpcResponse, type RpcSuccess, } from './envelope.js';
2
+ export { isPFError, localFailure, PFError, type PFErrorInit, ProtocolErrorCode, } from './error.js';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,eAAe,EACpB,gBAAgB,EAChB,KAAK,UAAU,EACf,KAAK,UAAU,EACf,KAAK,WAAW,EAChB,KAAK,UAAU,GAChB,MAAM,eAAe,CAAA;AACtB,OAAO,EACL,SAAS,EACT,YAAY,EACZ,OAAO,EACP,KAAK,WAAW,EAChB,iBAAiB,GAClB,MAAM,YAAY,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { PROTOCOL_VERSION, } from './envelope.js';
2
+ export { isPFError, localFailure, PFError, ProtocolErrorCode, } from './error.js';
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,gBAAgB,GAKjB,MAAM,eAAe,CAAA;AACtB,OAAO,EACL,SAAS,EACT,YAAY,EACZ,OAAO,EAEP,iBAAiB,GAClB,MAAM,YAAY,CAAA"}
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@ts-pf/protocol",
3
+ "version": "0.1.0-beta.0",
4
+ "description": "Portable JSON RPC envelope, PFError, and PROTOCOL_VERSION",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/crobinson42/ts-pf.git",
9
+ "directory": "packages/protocol"
10
+ },
11
+ "homepage": "https://github.com/crobinson42/ts-pf/tree/main/packages/protocol#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/crobinson42/ts-pf/issues"
14
+ },
15
+ "type": "module",
16
+ "sideEffects": false,
17
+ "exports": {
18
+ ".": {
19
+ "types": "./src/index.ts",
20
+ "import": "./src/index.ts"
21
+ }
22
+ },
23
+ "publishConfig": {
24
+ "access": "public",
25
+ "exports": {
26
+ ".": {
27
+ "types": "./dist/index.d.ts",
28
+ "import": "./dist/index.js"
29
+ }
30
+ }
31
+ },
32
+ "files": [
33
+ "dist",
34
+ "PROTOCOL.md",
35
+ "skills"
36
+ ],
37
+ "scripts": {
38
+ "build": "tsc -p tsconfig.build.json",
39
+ "test": "vitest run",
40
+ "type-check": "tsc --noEmit",
41
+ "lint": "biome check src tests"
42
+ }
43
+ }
@@ -0,0 +1,42 @@
1
+ ---
2
+ name: ts-pf-protocol
3
+ description: Use when throwing or handling ts-pf PFError, localFailure, PROTOCOL_VERSION, or the JSON RPC envelope. Triggers: @ts-pf/protocol, PFError, isPFError, localFailure, ProtocolErrorCode.
4
+ ---
5
+
6
+ # @ts-pf/protocol
7
+
8
+ Portable JSON envelope and `PFError`. No HTTP server, no schemas, no codecs.
9
+
10
+ Install: `npm i @ts-pf/protocol@beta`
11
+
12
+ Link for agents: `npx skills experimental_sync -y`
13
+
14
+ Wire spec ships as `PROTOCOL.md` in this package.
15
+
16
+ ## Do
17
+
18
+ ```ts
19
+ import { PFError, isPFError, localFailure } from '@ts-pf/protocol'
20
+
21
+ throw new PFError({ code: 'UNAUTHORIZED', status: 401, message: 'Nope' })
22
+ // localFailure('Request aborted') → INTERNAL, local: true, status: 0 (not on the wire)
23
+ ```
24
+
25
+ Envelope: `{ input }`, `{ ok: true, output }`, `{ ok: false, error: { code, message, data? } }`. Discriminator is JSON `error.code`. `status` is a TS/HTTP hint, not identity.
26
+
27
+ ## API
28
+
29
+ - `PFError`, `PFErrorInit`, `isPFError`, `localFailure`, `ProtocolErrorCode`
30
+ - `PROTOCOL_VERSION`, `RpcRequest`, `RpcResponse`, `RpcSuccess`, `RpcFailure`, `PFResultPromise`
31
+
32
+ ## Pair with
33
+
34
+ - App errors in handlers: `ts-pf-server` (`errors.CODE()` or `PFError`)
35
+ - Client narrowing: `ts-pf-client` (`asResult`, `isLocalFailure`)
36
+ - HTTP status map: `ts-pf-http` (`httpStatus`)
37
+
38
+ ## Don't
39
+
40
+ - `JSONCodec`, `RpcCodec`, `PROTOCOL_HEADER`, or `FetchHandler` here.
41
+ - Put `status`, `cause`, or `local` in the JSON envelope (`toJSON` omits them).
42
+ - Redeclare `VALIDATION`, `INTERNAL`, `BAD_REQUEST`, `METHOD_NOT_ALLOWED`, `PAYLOAD_TOO_LARGE` on `.errors()`.