@stitchwire/client 0.0.0-stage → 0.31.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.
Files changed (78) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +296 -2
  3. package/dist/chunk-d3248e3w.js +728 -0
  4. package/dist/chunk-mva06nh4.js +709 -0
  5. package/dist/contracts.d.ts +1 -0
  6. package/dist/contracts.js +84 -0
  7. package/dist/enrollment.d.ts +1 -0
  8. package/dist/enrollment.js +503 -0
  9. package/dist/index.d.ts +1 -0
  10. package/dist/index.js +1680 -0
  11. package/dist/types/client/src/contracts.d.ts +1 -0
  12. package/dist/types/client/src/enrollment.d.ts +11 -0
  13. package/dist/types/client/src/index.d.ts +1 -0
  14. package/dist/types/contracts/src/door/client-error.d.ts +20 -0
  15. package/dist/types/contracts/src/door/common.d.ts +3 -0
  16. package/dist/types/contracts/src/door/event-lifecycle.d.ts +22 -0
  17. package/dist/types/contracts/src/door/local-contract.d.ts +466 -0
  18. package/dist/types/contracts/src/door/paths.d.ts +17 -0
  19. package/dist/types/contracts/src/door/request-bounds.d.ts +4 -0
  20. package/dist/types/contracts/src/door/requests.d.ts +47 -0
  21. package/dist/types/contracts/src/door/results.d.ts +319 -0
  22. package/dist/types/contracts/src/door/status.d.ts +859 -0
  23. package/dist/types/contracts/src/door/streams.d.ts +226 -0
  24. package/dist/types/contracts/src/enrollment/fleet-admission.d.ts +413 -0
  25. package/dist/types/contracts/src/enrollment/outcome.d.ts +29 -0
  26. package/dist/types/contracts/src/enrollment/request.d.ts +281 -0
  27. package/dist/types/contracts/src/enrollment/result.d.ts +713 -0
  28. package/dist/types/contracts/src/fleet/bundle.d.ts +209 -0
  29. package/dist/types/contracts/src/fleet/identity.d.ts +4 -0
  30. package/dist/types/contracts/src/fleet/manifest.d.ts +71 -0
  31. package/dist/types/contracts/src/fleet/status.d.ts +56 -0
  32. package/dist/types/contracts/src/peer-contract.d.ts +78 -0
  33. package/dist/types/contracts/src/protocol/bounds.d.ts +37 -0
  34. package/dist/types/contracts/src/protocol/broker-health.d.ts +384 -0
  35. package/dist/types/contracts/src/protocol/event.d.ts +222 -0
  36. package/dist/types/contracts/src/protocol/failure.d.ts +146 -0
  37. package/dist/types/contracts/src/protocol/identity.d.ts +11 -0
  38. package/dist/types/contracts/src/protocol/json-bounds.d.ts +6 -0
  39. package/dist/types/contracts/src/protocol/lane-url.d.ts +16 -0
  40. package/dist/types/contracts/src/protocol/paths.d.ts +7 -0
  41. package/dist/types/contracts/src/protocol/payload.d.ts +25 -0
  42. package/dist/types/contracts/src/protocol/presence.d.ts +66 -0
  43. package/dist/types/contracts/src/protocol/release.d.ts +61 -0
  44. package/dist/types/contracts/src/protocol/result.d.ts +41 -0
  45. package/dist/types/contracts/src/protocol/rpc.d.ts +106 -0
  46. package/dist/types/contracts/src/protocol/schema-parse.d.ts +23 -0
  47. package/dist/types/contracts/src/protocol/stream.d.ts +290 -0
  48. package/dist/types/contracts/src/protocol/topic.d.ts +185 -0
  49. package/dist/types/contracts/src/service/budgets.d.ts +3 -0
  50. package/dist/types/contracts/src/service/contract-descriptor.d.ts +9 -0
  51. package/dist/types/contracts/src/service/contracts.d.ts +430 -0
  52. package/dist/types/contracts/src/service/declaration.d.ts +122 -0
  53. package/dist/types/contracts/src/service/diagnostics.d.ts +104 -0
  54. package/dist/types/contracts/src/service/owner-route-path.d.ts +11 -0
  55. package/dist/types/contracts/src/service/policy-schema.d.ts +154 -0
  56. package/dist/types/contracts/src/service/request-bounds.d.ts +5 -0
  57. package/dist/types/contracts/src/service/service-contract.d.ts +112 -0
  58. package/dist/types/local-client/src/broker-health.d.ts +18 -0
  59. package/dist/types/local-client/src/client.d.ts +377 -0
  60. package/dist/types/local-client/src/contracts.d.ts +112 -0
  61. package/dist/types/local-client/src/declarations.d.ts +57 -0
  62. package/dist/types/local-client/src/door-paths.d.ts +18 -0
  63. package/dist/types/local-client/src/errno.d.ts +6 -0
  64. package/dist/types/local-client/src/error-chain.d.ts +25 -0
  65. package/dist/types/local-client/src/errors.d.ts +39 -0
  66. package/dist/types/local-client/src/event-sequence.d.ts +4 -0
  67. package/dist/types/local-client/src/feed.d.ts +8 -0
  68. package/dist/types/local-client/src/http.d.ts +20 -0
  69. package/dist/types/local-client/src/index.d.ts +13 -0
  70. package/dist/types/local-client/src/ingress.d.ts +31 -0
  71. package/dist/types/local-client/src/operation.d.ts +37 -0
  72. package/dist/types/local-client/src/options.d.ts +18 -0
  73. package/dist/types/local-client/src/paths.d.ts +52 -0
  74. package/dist/types/local-client/src/readers.d.ts +143 -0
  75. package/dist/types/local-client/src/service.d.ts +33 -0
  76. package/dist/types/local-client/src/status-readers.d.ts +756 -0
  77. package/dist/types/local-client/src/unary.d.ts +10 -0
  78. package/package.json +58 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Max Listov
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,297 @@
1
- # Temporary Holding Version
1
+ # @stitchwire/client
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Optional typed Node/Bun client for the current Stitchwire local Unix door. One agent per
4
+ machine owns the broker connections. This package starts no daemon, opens no network
5
+ listener, reads no token file and retries nothing automatically. Importing it does not start an
6
+ agent: it talks to the one already running on the machine.
7
+
8
+ Install the SDK from npm.
9
+
10
+ ```sh
11
+ bun add @stitchwire/client
12
+ # or
13
+ npm install @stitchwire/client
14
+ ```
15
+
16
+ For offline verification or local development, build and test a local tarball with
17
+ `bun run check:client-package` from the repository root and install the packed archive path.
18
+
19
+ ```ts
20
+ import { createWireClient, defaultWireSocketPath } from '@stitchwire/client';
21
+
22
+ // The agent's default door; a remote caller's input never chooses this path.
23
+ using wire = createWireClient({ socketPath: defaultWireSocketPath() });
24
+ const result = await wire.invokeService({
25
+ to: 'worker',
26
+ service: 'example.catalog',
27
+ revision: '1',
28
+ operation: 'lookup',
29
+ payload: JSON.stringify({ key: 'example' }),
30
+ timeoutMs: 2_000,
31
+ });
32
+ if (result.outcome.status === 'failure') {
33
+ // Unknown delivery is not evidence that the owner did not execute the operation.
34
+ console.error(
35
+ result.outcome.code,
36
+ result.outcome.delivery,
37
+ result.outcome.transportCause,
38
+ result.outcome.retryAfterMs,
39
+ );
40
+ } else {
41
+ // Receipt is not domain success. Validate status and payload with the OWNER client/schema.
42
+ console.log(result.outcome.httpStatus, result.outcome.payload);
43
+ }
44
+ ```
45
+
46
+ `defaultWireSocketPath()` resolves `~/.local/state/stitchwire/agent.sock` unless
47
+ `STITCHWIRE_AGENT_SOCKET` or `STITCHWIRE_STATE_DIR` is set; it does not probe for a running agent.
48
+ The service above is an example, not an install command.
49
+ The agent, owner binding and service-read or exact operation grants must already be provisioned by
50
+ the operator.
51
+
52
+ ## API
53
+
54
+ - `invokeService({to, service, revision, operation, payload, timeoutMs}, {signal?})`: generic operation, separate transport outcome and opaque owner JSON.
55
+ - `serviceDescriptorFromContract(contract, policy)`: derives operation ids, exact static paths and stream transport
56
+ facts and the required `read` or `write` effect from each owner endpoint. Set `responseBytes`
57
+ to a map of operation names to byte limits for exceptions to the 262144-byte default.
58
+ - `createServiceFetch(wire, {to, descriptor, baseUrl})`: injected owner ClientFetch. Virtual
59
+ paths select only declared operations; unary and contract-stream responses share this adapter,
60
+ with no network fallback or automatic grants. Request bodies are consumed only up to the
61
+ operation's byte ceiling. `WireServiceError.outcome` preserves delivery certainty, refusal,
62
+ retry hint and diagnostic, while `WireServiceError.transportCause` exposes the validated route
63
+ cause directly.
64
+
65
+ - `createServiceIngress({descriptor, handler, bodyTimeoutMs?})`: the owner's side of the same door. It returns a fetch
66
+ handler for the node's envelope POST; the owner serves it on its Unix socket. Anything the descriptor
67
+ does not declare (another service or revision, an unknown operation, `v` other than 1, a body that is
68
+ not JSON or a payload past the operation's `requestBytes`) is answered HTTP 400 `{"error":"invalid-request","detail":"…"}`
69
+ and never reaches `handler`. Everything else reaches `handler` as `POST <operation path>` with the payload
70
+ as its JSON body and the node's cancellation on `request.signal`.
71
+ `bodyTimeoutMs` (integer, 1 to 30000) is the deadline for reading the envelope: a body not complete
72
+ by then is cancelled and answered 400 `invalid-request` ("service envelope was not read within its
73
+ deadline") without calling `handler`. It defaults to the longest budget the descriptor declares (a
74
+ stream operation counts its `lifetimeMs`), since the node refuses a call longer than its operation's
75
+ budget. It ends when the envelope is read: `handler`, streamed responses and the node's cancellation
76
+ on `request.signal` are not under it. Create the ingress once per descriptor, not per request.
77
+ - `serviceCaller(context)`: `{caller, operation, id, traceId}` of the request `createServiceIngress` built,
78
+ `undefined` for any other request, including a copy or clone of one and a request carrying the same
79
+ headers. `context` is the Stitchkit endpoint context (a handler, `authorize`, `beforeHandle` or `onError`);
80
+ the value travels in Stitchkit's `defineRequestIngress` channel.
81
+
82
+ The node agent dispatches only to an owner socket that is `0600` in a directory no other user can enter. Bind
83
+ it with Stitchkit's `bindUnixSocket` (`stitchkit/files`, 0.123.4 or later), which makes the socket `0600` from the
84
+ moment it exists: `bindUnixSocket({ path, mode: 0o600 }, (unix) => Bun.serve({ unix, fetch: ingress }))`, or
85
+ `createServer({ unix: { path, mode: 0o600 }, … })` for a Stitchkit server. A socket takes the process umask at
86
+ bind, so a `chmod` after `listen` leaves it on disk with the wider mode until the `chmod` runs, and the node agent
87
+ or a release check that finds it then refuses it.
88
+
89
+ An owner package can publish the non-authorizing `{descriptor, baseUrl}` composition. The descriptor
90
+ already carries the exact static route derived from the owner contract; consumers do not repeat it.
91
+ The application supplies only the operator-selected target and the already configured Wire client:
92
+
93
+ ```ts
94
+ import { createWireClient, defaultWireSocketPath } from '@stitchwire/client';
95
+
96
+ using wire = createWireClient({ socketPath: defaultWireSocketPath() });
97
+ const result = await wire.invokeService({
98
+ to: 'worker',
99
+ service: 'example.catalog',
100
+ revision: '1',
101
+ operation: 'lookup',
102
+ payload: JSON.stringify({ key: 'example' }),
103
+ timeoutMs: 2_000,
104
+ });
105
+ ```
106
+
107
+ The source checkout's `examples/service/run.ts` includes the actual owner
108
+ contract, Stitchkit typed client, two brokers, agents, binding and negative authorization gate.
109
+ Its owner client uses `createServiceFetch`; this lower-level snippet assumes that setup exists.
110
+
111
+ An owner's installer checks the declaration file it is about to write with `parseServiceDeclaration(value)`,
112
+ which returns `{ok: true, value}` or `{ok: false, detail}`. The node agent runs this same function on every
113
+ declaration file it polls, so the schema verdict and its one-line reason are the node's, with no copy of the
114
+ contract on the owner's side. The node also refuses a service outside its granted namespaces or colliding with a
115
+ binding it already has; the function does not know the node, so those two checks are made by the node (or by
116
+ `stitchwire config validate service <path> --node <node.json>`). The package also exports `ServiceDeclarationSchema`, `ServiceBindingSchema`,
117
+ `ServiceDescriptorSchema`, `ServiceLimitsSchema` and the limits `SERVICE_MAX_REQUEST_BYTES`,
118
+ `SERVICE_DEFAULT_REQUEST_BYTES`, `SERVICE_MAX_RESPONSE_BYTES`, `SERVICE_MAX_TIMEOUT_MS`,
119
+ `SERVICE_MAX_INFLIGHT`, `SERVICE_MAX_DECLARATION_BYTES` and `SERVICE_MAX_DESCRIPTOR_BYTES`. A route path
120
+ (an operation's `path`, a binding's `endpointPath`) starts with `/`, has no empty, `.` or `..` segment and no
121
+ trailing `/`. The same schema check is available without writing a file: `stitchwire config validate service <path>`.
122
+
123
+ The metadata does not grant access, select a Unix socket or allow an arbitrary remote path.
124
+ Agent policy stores the owner `descriptorPath`; broker and target replicas grant service-wide reads
125
+ or exact operations.
126
+ Owner clients may wrap a `WireServiceError`; delivery certainty remains on the typed cause and
127
+ must not trigger replay when it is `unknown`.
128
+
129
+ The SDK takes Stitchkit and Zod from the consumer as peers (the supported ranges are in its package manifest): its schemas are handed to Stitchkit, so both must be the consumer's one copy. Stitchkit owns Unix I/O, contract stream
130
+ framing/terminal validation and pull-driven response bodies. Wire adds routing credit, cancellation
131
+ and total transport budgets without parsing the owner's domain frames.
132
+ Wire owns protocol decoding and failure mapping; it never starts a daemon. Internal framework
133
+ types do not leak into the public declarations. Packed NodeNext checks run without skipLibCheck.
134
+
135
+ - `call({ to, argv, stdin?, timeoutMs? }, { signal? })`: complete typed result, including refusal and `transportCause`.
136
+ - `status({ signal? })`: roster, declared profiles and local runtime health; no polling. A lane that
137
+ is not connected carries `lastFailure` — the transport message, its timestamp and whether it is
138
+ terminal. The client requires the complete runtime observation of its own door revision, including logical
139
+ event readers and separately sampled lane handle counts; a mixed client/runtime
140
+ revision fails explicitly.
141
+ - `peerObservation({ to, route?, mode? }, { signal? })`: native observation or explicit outcome.
142
+ - `publish({ topic, bootId, seq, data, observedAt?, cursor? }, { signal? })`: acknowledgement; disconnected lanes receive bounded pre-dispatch grace.
143
+ - `stream({ to, profile, args?, stdin?, cursor?, timeoutMs? }, { signal? })`: lazy `WireFeed`.
144
+ - `subscribe({ topic, resume?, lifecycle? }, { signal? })`: lazy `WireFeed`, no implicit SDK reconnect/resync.
145
+ - `close()` / `Symbol.dispose`: abort all active work and close idle connections.
146
+
147
+ `WireFeed` is an async iterator with `close()`. Start reading with `next()` or `for await`.
148
+ It permits only one pending `next()`. Breaking the loop, `return()`, abort or client close
149
+ releases the socket, including while waiting on a quiet topic. `close()` is synchronous;
150
+ await a pending read's rejection or `return()` when cleanup completion matters.
151
+
152
+ ```ts
153
+ const feed = wire.stream({ to: 'worker', profile: 'declared-logs', timeoutMs: 30_000 });
154
+ for await (const item of feed) {
155
+ if (item.kind === 'chunk') console.log(new TextDecoder().decode(item.data));
156
+ else if (item.kind === 'error') console.error(item.frame.failure, item.frame.refusal);
157
+ else console.log(item.frame.reason, item.frame.cursor);
158
+ }
159
+ ```
160
+
161
+ Stream items are `chunk | end | error`; event items are `event | gap | error` and,
162
+ when requested with `lifecycle: true`, `subscription`. The item TYPE follows that option:
163
+ without it `subscribe` returns `WireFeed<EventFlowItem>`, so a data-only reader has no
164
+ `subscription` case to write and a member added to the full union does not move its
165
+ exhaustive `switch`. The narrowing applies only where the option's value is known at the
166
+ call site — a `boolean` variable or a whole `SubscribeRequest` value widens to
167
+ `WireFeed<EventItem>`, because narrowing those would be a claim about runtime the call
168
+ site cannot support. A `subscription` frame arriving on a feed that did not request one
169
+ is refused as `invalid-response` rather than delivered.
170
+ Each preserves its validated `frame`. Payload items additionally expose decoded `Uint8Array`
171
+ `data`. A gap, including `nextBootId`, is delivered to the consumer. The owner decides when
172
+ and how to fetch a snapshot or resume a durable journal; this package does not invent it.
173
+
174
+ `subscribe` validates continuity across frames with constant memory for the topic's single
175
+ declared producer. A fresh feed anchors at its first observed sequence, not necessarily zero.
176
+ A resumed feed starts after its supplied cursor. Range gaps account for missing sequences;
177
+ resume uncertainty at or behind the cursor does not move it. A boot-change names the only
178
+ allowed successor; its old range is broker high-water, not delivered position. Old-boot tail
179
+ may arrive from another lane until the successor begins. A named successor can be empty or
180
+ start mid-epoch. Duplicate/skipped events, changed producer/subscription and unnamed boot
181
+ changes throw `invalid-response`. The SDK does not reconnect, replay or fetch owner state.
182
+
183
+ The current SDK requires `failure`, `refusal`, `retryAfterMs` and nullable `transportCause` on
184
+ refusal-bearing wire envelopes and rejects missing or contradictory classifications.
185
+ `transportCause` is the shared machine
186
+ classification for route loss; raw-door clients branch on it rather than parse `detail` text.
187
+ See the source checkout's `docs/architecture/client-composition.md` for the two owner-client
188
+ recipes and `docs/architecture/sdk-adoption.md` for the exact distribution procedure.
189
+
190
+ ## Broker health, contracts, topic helpers and drop-in declarations
191
+
192
+ - **Broker `/health` reader:** `brokerHealthUrl(laneUrl)` converts `ws://`/`wss://`/`http://`/`https://` lane URLs to `/health` under the one lane rule the agent and enrollment apply: no credentials, query or fragment, and plain `http:`/`ws:` only to loopback (`127.0.0.0/8`, `::1`, `localhost`), so `readBrokerHealth` does not read a remote broker over plain text. `readBrokerHealth(laneUrl, options?)` performs a bounded GET (`8s` default timeout, `8 MiB` default cap, `redirect: 'error'`, strict UTF-8) validated by `BrokerHealthSchema`; a body that is not JSON is `invalid-response` with the parse error as its cause. A broker of an earlier release that writes no `transport`, `application`, `bundle` or `admission` block is read without it: those fields are optional in `BrokerHealth`.
193
+ - **Browser-safe contracts (`@stitchwire/client/contracts`):** zero `node:*`, `stitchkit`, `process` or `Buffer` dependencies — exports forward-compatible Zod readers of `/status` and `/health` (`StatusResultSchema`, `BrokerHealthSchema`, `AuditStatusSchema`, `LaneStatusSchema`, `FleetNodeStatusSchema`, `FleetEditionStatusSchema`, `FleetConfigStateSchema`), `PeerResultSchema` (it drops fields it does not know, while its values stay closed), authoring schemas (`ServiceDeclarationSchema`, `TopicDescriptorSchema`, `TopicProfileSchema`, `ServiceBindingSchema`, `ServiceDescriptorSchema`), failure code enums (`ClientErrorCodeSchema`, `ServiceFailureCodeSchema`) and pure helpers (`brokerHealthUrl`, `parseServiceDeclaration`, `parseTopicDescriptor`, `isTopicInNamespace`, `isTopicAuthorized`).
194
+ - **Error chain inspection:** `extractWireServiceError(error)` and `extractWireClientError(error)` walk `.cause` safely — cycle-guarded, 16 links deep by default (the outermost error included; the optional second argument changes it), ignoring `AggregateError.errors`, matched by `instanceof`, so an error from a second copy of the package is not recognised, and never throwing: a link whose property or prototype traps throw ends the walk with no match; `wireErrorCode(error)` returns `{ source: 'service' | 'client', code }` of the nearest one — the two code spaces overlap (`timeout`, `cancelled`, `unavailable`, …), and `source` tells a service's refusal from a local failure.
195
+ - **Local path discovery:** `defaultConfigDir(options?)`, `defaultStateDir(options?)`, `defaultWireSocketPath(options?)`, `defaultNodeConfigPath(options?)`, `defaultServiceDropInDir(options?)` and `defaultEventDropInDir(options?)` resolve the one layout Stitchwire installs on macOS and Linux — `<home>/.config/stitchwire/node.json` and `<home>/.local/state/stitchwire/agent.sock`, a system unit included (pass its user's home as `homeDir`). There is no second, system-wide door such as `/run/stitchwire/wire.sock`: a unit that serves the door elsewhere names that path as `agentSocket` in its `node.json`, and its consumers pass the same path as `socketPath` (or `STITCHWIRE_AGENT_SOCKET`). `STITCHWIRE_AGENT_SOCKET`, `STITCHWIRE_STATE_DIR` and `STITCHWIRE_CONFIG_DIR` are read at call time, verbatim, and must be absolute paths (a relative one is a `RangeError`: it would resolve against each process's own working directory); an empty one counts as unset. An agent whose `node.json` names another `agentSocket` is reached only there. Only a file named `node.json` has default drop-in directories (`services.d/`, `events.d/` beside it). This package never reads `node.json` or broker tokens.
196
+ - **Drop-in declarations without touching `node.json`:** `writeServiceDeclarationFile`, `removeServiceDeclarationFile`, `writeTopicDescriptorFile` and `removeTopicDescriptorFile` validate the owner's value against the agent's exact schemas and atomically write it as given (no defaults filled in) as a `0600` file in the `services.d/` or `events.d/` directory. A directory the SDK creates is `0700`; an existing one is used as it is and must be owned by the writer and not writable by group or others, or the write is refused; the agent reads it on its next poll, with no `node.json` edit and no restart. Requirements: an agent of runtime 0.57.0 or newer (an older one reads no drop-in directory); the writer runs as the agent's user (the agent reads only files owned by its own uid and writable by nobody else); a `node.json` that sets `services.dropInDir`/`events.dropInDir` must be matched by passing `dropInDir`; `dropInDir` and `configPath` must be absolute paths (a relative one is `invalid-request`). A written file is not yet a loaded declaration: confirm it in `status()` — `services.declarations.descriptors` / `events.declarations.descriptors` list each file by `path` with its `state`, and `refused` names one the node will not serve. Failures: `invalid-request` (bad name or value), `limit` (size), `permission` (access denied, or a directory/file the agent would refuse), `transport` (any other filesystem failure: no space, read-only filesystem, I/O).
197
+
198
+ ## Node identity
199
+
200
+ A node's id is answered without reading `node.json`, which holds the node's broker tokens. On the
201
+ machine: `(await wire.status()).nodeId`. From another machine, run the CLI there (over SSH):
202
+ `stitchwire status --json` prints the running agent's status, `nodeId` included; with the agent
203
+ stopped, `stitchwire config inspect node <path>` prints the file's `nodeId` with credentials as
204
+ digests only. Neither answer carries a token.
205
+
206
+ ## Enrollment contract
207
+
208
+ `@stitchwire/client/enrollment` is a separate entry with the schemas and types of node
209
+ enrollment: node and admission requests, operations, phases, failure codes, material and the
210
+ result of `stitchwire enroll`, plus the request and result of a fleet operator's admission entry.
211
+ An orchestrator builds requests and parses results with these exports instead of a hand-written
212
+ copy, so a contract change surfaces at its type check rather than as `invalid-request` on the
213
+ target. It is contract only: no runtime, credentials or execution. The main entry does not
214
+ include it.
215
+
216
+ ```ts
217
+ import { EnrollmentNodeRequestSchema, EnrollmentResultSchema } from '@stitchwire/client/enrollment';
218
+ ```
219
+
220
+ ## Quiet subscription readiness
221
+
222
+ ```ts
223
+ for await (const item of wire.subscribe({ topic: 'example.changes', lifecycle: true })) {
224
+ if (item.kind === 'subscription') {
225
+ console.log(item.frame.subscriptionId, item.frame.subscriptionState, item.frame.lanes);
226
+ } else if (item.kind === 'event') {
227
+ console.log(item.data);
228
+ } else if (item.kind === 'error') {
229
+ console.error(item.frame.failure, item.frame.refusal);
230
+ } else {
231
+ console.log(item.frame.reason);
232
+ }
233
+ }
234
+ ```
235
+
236
+ `opening` proves local logical admission with no acknowledged broker lanes; `ready`
237
+ proves admission on the named lanes for this handle. HTTP headers/keepalive do not
238
+ confirm admission. Losing every acknowledged lane returns `opening`; a broker reconnect
239
+ ACK restores `ready` without a domain event. These transitions do not prove producer
240
+ presence, data freshness or domain validity. A consumer may clear an earlier transport
241
+ error on `ready`, never a payload error. Guard callbacks by the consumer's own generation.
242
+
243
+ This observation requires runtime 0.39.2 or newer supporting Door 5. An unsupported
244
+ request fails explicitly; the SDK never retries without lifecycle. Broker/agent rollout
245
+ is coordinated by the operator before consumer adoption. Data-only readers need no change.
246
+
247
+ ## Failure semantics
248
+
249
+ Remote refusal and command exit are **results**, not thrown local connection errors.
250
+ `WireClientError` describes local failures: `invalid-request`, `closed`, `capacity`,
251
+ `cancelled`, `timeout`, `unavailable`, `permission`, `transport`, `http`, `unsupported`,
252
+ `version`, `invalid-response`, `limit`, `unexpected-eof`.
253
+
254
+ Its `delivery` is `not-sent` or `unknown`. **Unknown does not mean failed execution.**
255
+ Especially after an unreadable publication acknowledgement, never blindly republish.
256
+ No method retries, falls back to CLI/SSH or silently converts failure into empty data.
257
+ `metadata` contains internal diagnostic context; do not forward it to an end-user UI.
258
+ Unary failures include `metadata.timing`: UTC start, monotonic elapsed/header time,
259
+ configured deadline, phase and caller-abort state. These describe the local attempt,
260
+ not proof of broker acceptance or an instruction to retry.
261
+
262
+ Readers ignore additive object fields. A foreign version on versioned responses is a named
263
+ `version` error. Status carries the local door version; publication acknowledgement remains an
264
+ unversioned exact response. Malformed required fields fail explicitly, without replay.
265
+
266
+ The readers of `/status` (`status()`, `StatusResultSchema`) and `/health` (`readBrokerHealth`,
267
+ `BrokerHealthSchema`) and their parts (`AuditStatusSchema`, `LaneStatusSchema`, `FleetNodeStatusSchema`,
268
+ `FleetEditionStatusSchema`, `FleetConfigStateSchema`) also read an enumerated value they do not know
269
+ — written by an agent or broker of a newer release — as `unrecognized`. It is distinct from every
270
+ value a writer sends, `unknown` included, so an exhaustive `switch` over such a field has a case for
271
+ it, and a decision must treat it as unknown or failed, never as fine. These readers do not bound how
272
+ many nodes a list holds; the response body is bounded by bytes. Results of calls, streams,
273
+ publications and peer observations still refuse a value they do not know.
274
+
275
+ ## Bounds and lifecycle
276
+
277
+ - Default RPC/stream duration 30s; explicit duration 1s–15min. Local total deadline allows
278
+ 10s for delivery of the remote terminal. Status uses the header/open timeout (default 10s).
279
+ - Publication deadline defaults to 30s and caps the whole response. Peer observation adds
280
+ the native 2s observation bound to the open timeout.
281
+ - Data-only subscriptions have a header deadline. With `lifecycle: true`, `openTimeoutMs`
282
+ bounds the first acknowledged broker lane, including time after HTTP headers. Once ready,
283
+ quiet intervals have no inactivity deadline. Cancel explicitly.
284
+ - Default 32 active requests, configurable 1–256; excess requests fail without a hidden queue.
285
+ - Maximum JSON response 52 MiB (covers escaped bounded stdout/stderr); publication ack 16 KiB.
286
+ - Maximum NDJSON line 512 KiB, stream payload total 256 MiB. Limits can be reduced through
287
+ `maxResponseBytes` and `maxFrameBytes`. The parser is pull-driven.
288
+
289
+ Typed item-framed streams use Stitchkit's strict newline and terminal completion policy.
290
+ Packed stalled-reader gates verify bounded backpressure plateaus (`2/512` and `6/512` frames) and
291
+ multi-megabyte continuous subscriptions (600 frames across 26 MiB on one request without a lifetime
292
+ cutoff) on both Bun and Node. No `node:http` streaming fallback, implicit replay or inactivity
293
+ workaround exists.
294
+
295
+ The SDK version is independent from the agent/broker release, but each SDK declares one exact local
296
+ door revision. Raw HTTP consumers must implement that same current contract. Node 22.3.0+ and Bun
297
+ 1.4.4+; ESM only, not a browser transport.