@cortexkit/subc-client 0.17.0 → 0.18.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.
@@ -0,0 +1,447 @@
1
+ /**
2
+ * The launch nonce: the secret the daemon gives each module it spawns, which
3
+ * the module presents to be admitted as itself.
4
+ *
5
+ * On macOS and Linux the daemon hands it over through a pipe rather than the
6
+ * environment, because any process of the same user can read another
7
+ * process's initial environment (`ps eww`). The pipe's read end is descriptor
8
+ * 3 in the module and `SUBC_LAUNCH_NONCE_FD` names it as `<fd>:<inode>`.
9
+ * {@link launchNonce} reads that descriptor once, closes it, and caches the
10
+ * value for the life of the process. While modules move over, the daemon also
11
+ * keeps setting the environment copy (`SUBC_LAUNCH_NONCE`), which
12
+ * {@link launchNonce} reads when no descriptor is named. Windows has no
13
+ * descriptor handoff, so there only the environment copy is read.
14
+ *
15
+ * This mirrors the Rust accessor in `subc-os` (`subc_os::launch_nonce`): the
16
+ * same checks in the same order, the same error names and messages.
17
+ */
18
+
19
+ import { closeSync, fstatSync, readSync, type BigIntStats } from "node:fs";
20
+
21
+ /** The environment copy of the nonce, kept only while modules move to the descriptor. */
22
+ export const SUBC_LAUNCH_NONCE_ENV = "SUBC_LAUNCH_NONCE";
23
+
24
+ /**
25
+ * Names the descriptor holding the nonce, as `<fd>:<inode>`. The inode names
26
+ * the pipe itself, so the reader can tell it from an unrelated descriptor that
27
+ * happens to have the same number. A process a module spawns inherits this
28
+ * variable but not the pipe, and without the inode it would read and close
29
+ * whatever that process has at the number.
30
+ */
31
+ export const SUBC_LAUNCH_NONCE_FD_ENV = "SUBC_LAUNCH_NONCE_FD";
32
+
33
+ /** The descriptor number the daemon gives the pipe's read end in the module. */
34
+ export const LAUNCH_NONCE_FD = 3;
35
+
36
+ /** Where a process got its launch nonce from, as modules report it in provenance. */
37
+ export type LaunchNonceSource = "fd" | "env";
38
+
39
+ /** The nonce this process was launched with, and where it came from. */
40
+ export interface LaunchNonce {
41
+ readonly value: string;
42
+ readonly source: LaunchNonceSource;
43
+ }
44
+
45
+ /**
46
+ * Why the descriptor named by `SUBC_LAUNCH_NONCE_FD` gave no nonce. The names
47
+ * are the Rust `LaunchNonceError` variants.
48
+ *
49
+ * None of these falls back to the environment copy. A named descriptor that
50
+ * cannot be read means the handoff went wrong, or that this process inherited
51
+ * the variable from a module without inheriting the pipe; reading the
52
+ * environment instead would hide the first and defeat the second.
53
+ */
54
+ export type LaunchNonceErrorKind =
55
+ /** The variable is not `<fd>:<inode>`. */
56
+ | "Malformed"
57
+ /** Nothing is open at that number: what a process spawned by a module sees. */
58
+ | "NotOpen"
59
+ /** The descriptor is open but is not a pipe. It was left alone. */
60
+ | "NotAPipe"
61
+ /** The descriptor is a pipe, but not the one named. It was left alone. */
62
+ | "WrongPipe"
63
+ /** The named pipe holds no bytes. It was left open and nothing was consumed. */
64
+ | "Empty"
65
+ /** Reading the named pipe failed. */
66
+ | "Unreadable"
67
+ /** The named pipe held bytes that are not UTF-8. */
68
+ | "NotUtf8";
69
+
70
+ export interface LaunchNonceErrorDetails {
71
+ /** The descriptor number, for every kind except `Malformed`. */
72
+ fd?: number;
73
+ /** The OS error number, for `NotOpen` and (when known) `Unreadable`. */
74
+ errno?: number;
75
+ /** The variable's text, for `Malformed`. */
76
+ value?: string;
77
+ /** The inodes compared, for `WrongPipe`. */
78
+ expectedInode?: bigint;
79
+ foundInode?: bigint;
80
+ }
81
+
82
+ // This file sticks to syntax Node can strip without transforming (no
83
+ // constructor parameter properties, no enums), so tests can run it directly
84
+ // under Node as well as Bun.
85
+ export class LaunchNonceError extends Error {
86
+ override readonly name = "LaunchNonceError";
87
+ readonly kind: LaunchNonceErrorKind;
88
+ readonly fd: number | undefined;
89
+ readonly errno: number | undefined;
90
+ readonly value: string | undefined;
91
+ readonly expectedInode: bigint | undefined;
92
+ readonly foundInode: bigint | undefined;
93
+
94
+ constructor(kind: LaunchNonceErrorKind, message: string, details: LaunchNonceErrorDetails = {}) {
95
+ super(message);
96
+ this.kind = kind;
97
+ this.fd = details.fd;
98
+ this.errno = details.errno;
99
+ this.value = details.value;
100
+ this.expectedInode = details.expectedInode;
101
+ this.foundInode = details.foundInode;
102
+ }
103
+ }
104
+
105
+ /**
106
+ * Whether `error` is a {@link LaunchNonceError}, including one thrown by another
107
+ * copy of this package sharing the process-wide cache, which `instanceof`
108
+ * would not recognise.
109
+ */
110
+ export function isLaunchNonceError(error: unknown): error is LaunchNonceError {
111
+ return (
112
+ error instanceof Error &&
113
+ error.name === "LaunchNonceError" &&
114
+ typeof (error as { kind?: unknown }).kind === "string"
115
+ );
116
+ }
117
+
118
+ /**
119
+ * This process's launch nonce and where it came from, or `undefined` when
120
+ * neither variable is set (or the environment copy is empty): the process was
121
+ * not started by the daemon. Throws the cached {@link LaunchNonceError} when a
122
+ * named descriptor could not be taken.
123
+ *
124
+ * The first call decides, and every later call returns the same answer
125
+ * without touching the descriptor or the environment again. So every reader
126
+ * in a process must come through here: after the first read closes the
127
+ * descriptor, its number is the next one the process hands out, and a second
128
+ * independent reader would read and close some unrelated socket or file. The
129
+ * cache is shared with every other copy of this package loaded in the same
130
+ * JavaScript realm (see {@link PROCESS_CELL_KEY}); a worker thread is its own
131
+ * realm and has its own cache, so read it on the main thread.
132
+ *
133
+ * - When `SUBC_LAUNCH_NONCE_FD` is set (not on Windows), the descriptor it
134
+ * names is taken only if it is a pipe with the named inode and holds bytes;
135
+ * it is then read to end of file and closed. Anything else throws and leaves
136
+ * the descriptor as it was, and never falls back to the environment.
137
+ * - Otherwise the value of `SUBC_LAUNCH_NONCE` is used.
138
+ *
139
+ * It never changes `process.env`. Removing either variable would break any
140
+ * other reader in the process still on the environment copy.
141
+ *
142
+ * Call it before the process spawns anything. Until the first read the
143
+ * descriptor is inheritable (it has to be, to survive the daemon's exec), so a
144
+ * child spawned earlier would inherit the pipe.
145
+ *
146
+ * It assumes the write end of the pipe was closed before this process started,
147
+ * as the daemon's handoff does. Node and Bun cannot ask how many bytes a pipe
148
+ * holds without reading it (the Rust accessor uses the FIONREAD ioctl), so the
149
+ * emptiness check is a first read: at end of file it returns no bytes and
150
+ * consumes nothing. If some other process still held the write end open, an
151
+ * empty pipe would block that read instead of reporting `Empty`.
152
+ */
153
+ export function launchNonce(): LaunchNonce | undefined {
154
+ return unwrap(processCell().result());
155
+ }
156
+
157
+ /**
158
+ * {@link launchNonce} without the throw: `undefined` for no nonce and for a
159
+ * refused descriptor alike. For readers that treat a refusal as "no
160
+ * identity", such as the consumer's route open.
161
+ */
162
+ export function launchNonceOrUndefined(): LaunchNonce | undefined {
163
+ const result = processCell().result();
164
+ return result.ok ? result.nonce ?? undefined : undefined;
165
+ }
166
+
167
+ type CachedResult =
168
+ | { readonly ok: true; readonly nonce: LaunchNonce | null }
169
+ | { readonly ok: false; readonly error: LaunchNonceError };
170
+
171
+ /**
172
+ * The shape stored under {@link PROCESS_CELL_KEY}. Other versions of this
173
+ * package read it, so it only ever gains members.
174
+ */
175
+ interface SharedLaunchNonceCell {
176
+ result(): CachedResult;
177
+ }
178
+
179
+ /**
180
+ * Where the process-wide cell lives. A registry symbol rather than a module
181
+ * variable, because a module's dependencies often install two copies of this
182
+ * package. With a cache per copy, the second copy would look at the
183
+ * descriptor after the first had closed it, refuse, and so fail to register
184
+ * the module with the daemon.
185
+ */
186
+ const PROCESS_CELL_KEY = Symbol.for("@cortexkit/subc-client/launch-nonce/v1");
187
+
188
+ function processCell(): SharedLaunchNonceCell {
189
+ const global = globalThis as { [PROCESS_CELL_KEY]?: SharedLaunchNonceCell };
190
+ let cell = global[PROCESS_CELL_KEY];
191
+ if (cell === undefined) {
192
+ cell = new LaunchNonceCell((key) => process.env[key]);
193
+ global[PROCESS_CELL_KEY] = cell;
194
+ }
195
+ return cell;
196
+ }
197
+
198
+ /**
199
+ * Forgets the process-wide answer, so the next {@link launchNonce} reads again.
200
+ * For tests that change the environment between cases; never for modules,
201
+ * where a second read is exactly what the cache exists to prevent.
202
+ */
203
+ export function resetLaunchNonceForTests(): void {
204
+ delete (globalThis as { [PROCESS_CELL_KEY]?: SharedLaunchNonceCell })[PROCESS_CELL_KEY];
205
+ }
206
+
207
+ function unwrap(result: CachedResult): LaunchNonce | undefined {
208
+ if (!result.ok) throw result.error;
209
+ return result.nonce ?? undefined;
210
+ }
211
+
212
+ /** What the accessor reads from fstat: the file type and the raw st_ino. */
213
+ export type LaunchNonceStat = (fd: number) => Pick<BigIntStats, "isFIFO" | "ino">;
214
+
215
+ /**
216
+ * A launch nonce read at most once. The process has one, behind
217
+ * {@link launchNonce}; tests make their own with a stand-in for the
218
+ * environment, the platform, and fstat.
219
+ */
220
+ export class LaunchNonceCell implements SharedLaunchNonceCell {
221
+ private cached: CachedResult | undefined;
222
+ /** How many times this cell has taken a descriptor. At most one. */
223
+ descriptorReads = 0;
224
+ private readonly lookup: (key: string) => string | undefined;
225
+ private readonly platform: NodeJS.Platform;
226
+ private readonly stat: LaunchNonceStat;
227
+
228
+ constructor(
229
+ lookup: (key: string) => string | undefined,
230
+ platform: NodeJS.Platform = process.platform,
231
+ stat: LaunchNonceStat = (fd) => fstatSync(fd, { bigint: true }),
232
+ ) {
233
+ this.lookup = lookup;
234
+ this.platform = platform;
235
+ this.stat = stat;
236
+ }
237
+
238
+ result(): CachedResult {
239
+ if (this.cached === undefined) this.cached = this.read();
240
+ return this.cached;
241
+ }
242
+
243
+ /** The cached value, reading it first if no caller has yet; throws a refusal. */
244
+ get(): LaunchNonce | undefined {
245
+ return unwrap(this.result());
246
+ }
247
+
248
+ private read(): CachedResult {
249
+ if (this.platform !== "win32") {
250
+ const named = this.lookup(SUBC_LAUNCH_NONCE_FD_ENV);
251
+ if (named !== undefined) {
252
+ try {
253
+ return { ok: true, nonce: this.readDescriptor(named) };
254
+ } catch (error) {
255
+ if (error instanceof LaunchNonceError) return { ok: false, error };
256
+ throw error;
257
+ }
258
+ }
259
+ }
260
+ const value = this.lookup(SUBC_LAUNCH_NONCE_ENV);
261
+ return { ok: true, nonce: value ? makeLaunchNonce(value, "env") : null };
262
+ }
263
+
264
+ private readDescriptor(text: string): LaunchNonce {
265
+ const { fd, expectedInode } = parseFdValue(text);
266
+
267
+ // Check what the descriptor is before taking ownership of it. Reading and
268
+ // closing a descriptor that belongs to other code in this process would
269
+ // break that code, and a process that inherited the variable without the
270
+ // descriptor may well have something else at this number.
271
+ let stat: Pick<BigIntStats, "isFIFO" | "ino">;
272
+ try {
273
+ stat = this.stat(fd);
274
+ } catch (error) {
275
+ const errno = errnoOf(error) ?? 0;
276
+ throw new LaunchNonceError(
277
+ "NotOpen",
278
+ `${SUBC_LAUNCH_NONCE_FD_ENV} names descriptor ${fd}, which is not open (errno ${errno}); ` +
279
+ "a process spawned by a module inherits the variable but not the descriptor",
280
+ { fd, errno },
281
+ );
282
+ }
283
+ if (!stat.isFIFO()) {
284
+ throw new LaunchNonceError(
285
+ "NotAPipe",
286
+ `${SUBC_LAUNCH_NONCE_FD_ENV} names descriptor ${fd}, which is not a pipe; left it untouched`,
287
+ { fd },
288
+ );
289
+ }
290
+ // Node reports st_ino as a signed 64-bit value, and macOS pipe inodes use
291
+ // the top bit, so they come back negative. The variable carries the
292
+ // unsigned value (the Rust daemon writes `st_ino as u64`).
293
+ const foundInode = BigInt.asUintN(64, stat.ino);
294
+ if (foundInode !== expectedInode) {
295
+ throw new LaunchNonceError(
296
+ "WrongPipe",
297
+ `${SUBC_LAUNCH_NONCE_FD_ENV} names descriptor ${fd} with inode ${expectedInode}, but it has ` +
298
+ `inode ${foundInode}; left it untouched`,
299
+ { fd, expectedInode, foundInode },
300
+ );
301
+ }
302
+
303
+ // Node and Bun have no FIONREAD (the ioctl the Rust accessor uses to count
304
+ // the waiting bytes without reading them), so the first read is the
305
+ // emptiness check. With the write end closed, as the daemon leaves it, an
306
+ // empty pipe answers end of file: zero bytes, nothing consumed, and the
307
+ // descriptor stays open. A non-blocking descriptor with a writer still
308
+ // open answers EAGAIN, which likewise consumed nothing. Do not replace
309
+ // this with fstat's size: macOS reports the waiting byte count there for
310
+ // an anonymous pipe, but 0 for a mkfifo pipe, and Linux reports 0 for
311
+ // every pipe.
312
+ const chunk = Buffer.alloc(256);
313
+ let got: number;
314
+ try {
315
+ got = readSync(fd, chunk, 0, chunk.length, null);
316
+ } catch (error) {
317
+ if (isWouldBlock(error)) throw emptyError(fd);
318
+ throw unreadableError(fd, errnoOf(error));
319
+ }
320
+ if (got === 0) throw emptyError(fd);
321
+
322
+ // From here the descriptor is this process's to consume: it is the pipe
323
+ // the daemon named by inode, and every reader goes through this one cell,
324
+ // which reaches this line at most once.
325
+ this.descriptorReads += 1;
326
+ const parts: Buffer[] = [Buffer.from(chunk.subarray(0, got))];
327
+ try {
328
+ for (;;) {
329
+ const n = readSync(fd, chunk, 0, chunk.length, null);
330
+ if (n === 0) break;
331
+ parts.push(Buffer.from(chunk.subarray(0, n)));
332
+ }
333
+ } catch (error) {
334
+ throw unreadableError(fd, errnoOf(error));
335
+ } finally {
336
+ closeQuietly(fd);
337
+ }
338
+ let value: string;
339
+ try {
340
+ value = new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(parts));
341
+ } catch {
342
+ throw new LaunchNonceError(
343
+ "NotUtf8",
344
+ `the launch nonce pipe at descriptor ${fd} held bytes that are not UTF-8`,
345
+ { fd },
346
+ );
347
+ }
348
+ return makeLaunchNonce(value, "fd");
349
+ }
350
+ }
351
+
352
+ const U64_MAX = (1n << 64n) - 1n;
353
+ const I32_MAX = 2 ** 31 - 1;
354
+
355
+ /**
356
+ * Parse `<fd>:<inode>` exactly as the Rust accessor does: split at the first
357
+ * colon; the descriptor is decimal with an optional `+` or `-` sign and must
358
+ * fit a signed 32-bit integer and not be negative; the inode is decimal with
359
+ * an optional `+` and must fit an unsigned 64-bit integer.
360
+ */
361
+ function parseFdValue(text: string): { fd: number; expectedInode: bigint } {
362
+ const malformed = () =>
363
+ new LaunchNonceError(
364
+ "Malformed",
365
+ `${SUBC_LAUNCH_NONCE_FD_ENV}=${JSON.stringify(text)} is not <fd>:<inode>`,
366
+ { value: text },
367
+ );
368
+ const colon = text.indexOf(":");
369
+ if (colon < 0) throw malformed();
370
+ const fdText = text.slice(0, colon);
371
+ const inodeText = text.slice(colon + 1);
372
+ if (!/^[+-]?\d+$/.test(fdText) || !/^\+?\d+$/.test(inodeText)) throw malformed();
373
+ const fdBig = BigInt(fdText);
374
+ if (fdBig < 0n || fdBig > BigInt(I32_MAX)) throw malformed();
375
+ const expectedInode = BigInt(inodeText);
376
+ if (expectedInode > U64_MAX) throw malformed();
377
+ return { fd: Number(fdBig), expectedInode };
378
+ }
379
+
380
+ /**
381
+ * Holds the value in a private field behind a getter, so logging, inspecting
382
+ * or serialising the object does not print the secret; the Rust type's Debug
383
+ * output redacts it the same way.
384
+ */
385
+ class RedactedLaunchNonce implements LaunchNonce {
386
+ readonly source: LaunchNonceSource;
387
+ readonly #value: string;
388
+
389
+ constructor(value: string, source: LaunchNonceSource) {
390
+ this.#value = value;
391
+ this.source = source;
392
+ Object.freeze(this);
393
+ }
394
+
395
+ get value(): string {
396
+ return this.#value;
397
+ }
398
+
399
+ toJSON(): { source: LaunchNonceSource } {
400
+ return { source: this.source };
401
+ }
402
+
403
+ [Symbol.for("nodejs.util.inspect.custom")](): string {
404
+ return `LaunchNonce { value: <${this.#value.length} bytes redacted>, source: "${this.source}" }`;
405
+ }
406
+ }
407
+
408
+ function makeLaunchNonce(value: string, source: LaunchNonceSource): LaunchNonce {
409
+ return new RedactedLaunchNonce(value, source);
410
+ }
411
+
412
+ function emptyError(fd: number): LaunchNonceError {
413
+ return new LaunchNonceError(
414
+ "Empty",
415
+ `the launch nonce pipe at descriptor ${fd} is empty; left it untouched`,
416
+ { fd },
417
+ );
418
+ }
419
+
420
+ function unreadableError(fd: number, errno: number | undefined): LaunchNonceError {
421
+ // `Some(n)` / `None` is how the Rust message prints an optional errno.
422
+ const shown = errno === undefined ? "None" : `Some(${errno})`;
423
+ return new LaunchNonceError(
424
+ "Unreadable",
425
+ `could not read the launch nonce from descriptor ${fd} (errno ${shown})`,
426
+ { fd, errno },
427
+ );
428
+ }
429
+
430
+ function isWouldBlock(error: unknown): boolean {
431
+ const code = (error as { code?: unknown } | null)?.code;
432
+ return code === "EAGAIN" || code === "EWOULDBLOCK";
433
+ }
434
+
435
+ /** Node and Bun report errno negated (libuv style); the Rust errors carry it positive. */
436
+ function errnoOf(error: unknown): number | undefined {
437
+ const errno = (error as { errno?: unknown } | null)?.errno;
438
+ return typeof errno === "number" ? Math.abs(errno) : undefined;
439
+ }
440
+
441
+ function closeQuietly(fd: number): void {
442
+ try {
443
+ closeSync(fd);
444
+ } catch {
445
+ // Nothing useful can be done if closing the consumed pipe fails.
446
+ }
447
+ }
package/src/provider.ts CHANGED
@@ -4,7 +4,6 @@ import { AuthError, authenticateClient } from "./auth.js";
4
4
  import {
5
5
  DEFAULT_RECONNECT_BACKOFF,
6
6
  isEstablishedRouteDead,
7
- SUBC_LAUNCH_NONCE_ENV,
8
7
  SUBC_MODULE_ID_ENV,
9
8
  type BindIdentity,
10
9
  type ReconnectBackoff,
@@ -24,6 +23,13 @@ import {
24
23
  PROTOCOL_VERSION,
25
24
  type Frame,
26
25
  } from "./envelope.js";
26
+ import {
27
+ isLaunchNonceError,
28
+ launchNonce as processLaunchNonce,
29
+ launchNonceOrUndefined,
30
+ type LaunchNonceError,
31
+ type LaunchNonceSource,
32
+ } from "./launch-nonce.js";
27
33
  import {
28
34
  belongsToConnection,
29
35
  createRouteHandle,
@@ -74,6 +80,35 @@ export interface ManifestInput {
74
80
  provides: ProviderRoleInput[];
75
81
  consumes: ConsumerRoleInput[];
76
82
  bindings: BindingsInput;
83
+ /**
84
+ * Facts about the running build, sent in HELLO only when declared. When it is
85
+ * declared without `launch_nonce_source`, the provider fills that field in
86
+ * from the launch nonce it sends.
87
+ */
88
+ provenance?: ManifestProvenance;
89
+ }
90
+
91
+ /**
92
+ * Build provenance a module declares in its manifest; mirrors
93
+ * `ManifestProvenance` in subc-protocol. Every field is optional and is left
94
+ * off the wire when unset. Omit a field you cannot know rather than sending a
95
+ * placeholder such as "unknown".
96
+ */
97
+ export interface ManifestProvenance {
98
+ build_git_sha?: string;
99
+ /** Why `build_git_sha` is unavailable; an open set of reasons. */
100
+ build_git_sha_absence_reason?: string;
101
+ build_lock_digest?: string;
102
+ /** The subc-protocol crate version this module's wire vocabulary matches. */
103
+ wire_crate_version?: string;
104
+ store_schema_version?: string;
105
+ /**
106
+ * Where the running module read its launch nonce from: `fd` (the pipe the
107
+ * daemon hands over as descriptor 3) or `env` (the environment variable kept
108
+ * while modules move to the pipe). A fact about the running process, not
109
+ * the build. Filled in by the provider when left unset.
110
+ */
111
+ launch_nonce_source?: LaunchNonceSource;
77
112
  }
78
113
 
79
114
  export type ProviderRoleInput =
@@ -262,16 +297,19 @@ export interface SubcProviderConnectOptions {
262
297
  onConnectionState?: (event: ProviderConnectionState) => void | Promise<void>;
263
298
  /**
264
299
  * The one-time launch nonce to echo in HELLO for a reserved module. Defaults to
265
- * the `SUBC_LAUNCH_NONCE` environment variable subc injects on spawn; pass
266
- * explicitly to override. Omitted from the wire when empty (non-reserved modules).
300
+ * the process's launch nonce (see `launchNonce`: the descriptor subc hands
301
+ * over, or the `SUBC_LAUNCH_NONCE` environment copy), and `connect()` rejects
302
+ * with code `launch_nonce_unavailable` when a named descriptor is refused.
303
+ * Pass explicitly to override. Omitted from the wire when empty
304
+ * (non-reserved modules).
267
305
  */
268
306
  launchNonce?: string;
269
307
  /**
270
308
  * Whether an unexpected connection drop starts a reconnect-and-re-register
271
309
  * cycle (`true`) or ends serving and resolves {@link SubcProvider.closed}
272
310
  * (`false`). Defaults to `false` when the process runs under the daemon's
273
- * supervision (both `SUBC_MODULE_ID` and `SUBC_LAUNCH_NONCE` are set and
274
- * non-empty in its environment, the pair the daemon injects at spawn), since
311
+ * supervision (`SUBC_MODULE_ID` is set and the process has a launch nonce,
312
+ * the pair the daemon injects at spawn), since
275
313
  * the daemon owns a supervised module's restarts and waits for it to exit;
276
314
  * `true` otherwise, so plugins and other self-connecting providers keep
277
315
  * reconnecting. A daemon GOODBYE and `close()` end serving regardless.
@@ -1343,7 +1381,22 @@ function normalizeProviderConnectOptions(opts: SubcProviderConnectOptions): Norm
1343
1381
  // spawns a module; together they mark the process as supervised, and the nonce
1344
1382
  // is also what HELLO echoes for a reserved module_id.
1345
1383
  const envModuleId = nonEmpty(process.env[SUBC_MODULE_ID_ENV]);
1346
- const envLaunchNonce = nonEmpty(process.env[SUBC_LAUNCH_NONCE_ENV]);
1384
+ // The nonce comes from the process-wide accessor, which reads the daemon's
1385
+ // descriptor at most once. A refused descriptor fails the connect, unless the
1386
+ // caller supplied the nonce itself, in which case it only means "not
1387
+ // supervised".
1388
+ let processNonce: string | undefined;
1389
+ if (opts.launchNonce === undefined) {
1390
+ try {
1391
+ processNonce = processLaunchNonce()?.value;
1392
+ } catch (error) {
1393
+ if (isLaunchNonceError(error)) throw launchNonceUnavailable(error);
1394
+ throw error;
1395
+ }
1396
+ } else {
1397
+ processNonce = launchNonceOrUndefined()?.value;
1398
+ }
1399
+ const envLaunchNonce = nonEmpty(processNonce);
1347
1400
  const supervised = envModuleId !== undefined && envLaunchNonce !== undefined;
1348
1401
  return {
1349
1402
  connectionFile: opts.connectionFile,
@@ -1371,6 +1424,22 @@ function normalizedControlOps(controlOps: string[] | null | undefined): string[]
1371
1424
  return [...merged];
1372
1425
  }
1373
1426
 
1427
+ /**
1428
+ * The typed HELLO failure for a refused launch-nonce descriptor. The message
1429
+ * matches the Rust SDK's `SubcModuleError::LaunchNonce`; `detail.kind` and
1430
+ * `cause` carry the accessor's error.
1431
+ */
1432
+ function launchNonceUnavailable(error: LaunchNonceError): SubcProviderError {
1433
+ const wrapped = new SubcProviderError(
1434
+ `launch nonce unavailable: ${error.message}`,
1435
+ "launch_nonce_unavailable",
1436
+ "terminal",
1437
+ { kind: error.kind },
1438
+ );
1439
+ wrapped.cause = error;
1440
+ return wrapped;
1441
+ }
1442
+
1374
1443
  function buildHelloFrame(opts: NormalizedSubcProviderConnectOptions): Frame {
1375
1444
  const nonce = opts.launchNonce;
1376
1445
  return buildFrame(
@@ -1380,7 +1449,7 @@ function buildHelloFrame(opts: NormalizedSubcProviderConnectOptions): Frame {
1380
1449
  0,
1381
1450
  HELLO_CORR,
1382
1451
  encodeJson({
1383
- manifest: normalizeManifest(opts.manifest),
1452
+ manifest: normalizeManifest(opts.manifest, nonce),
1384
1453
  protocol_ver: PROTOCOL_VERSION,
1385
1454
  control_ops: normalizedControlOps(opts.controlOps),
1386
1455
  // Echo the one-time launch nonce subc injects for a reserved module
@@ -1481,7 +1550,11 @@ function bindRejection(decision: BindDecision | undefined): { code: string; mess
1481
1550
  };
1482
1551
  }
1483
1552
 
1484
- function normalizeManifest(manifest: ManifestInput): ManifestInput {
1553
+ /**
1554
+ * The manifest exactly as HELLO sends it. Exported for the conformance tests,
1555
+ * not from the package entry.
1556
+ */
1557
+ export function normalizeManifest(manifest: ManifestInput, sentNonce: string | undefined): ManifestInput {
1485
1558
  return {
1486
1559
  module_id: manifest.module_id,
1487
1560
  module_version: manifest.module_version,
@@ -1504,9 +1577,37 @@ function normalizeManifest(manifest: ManifestInput): ManifestInput {
1504
1577
  optional: [...manifest.bindings.identity.optional],
1505
1578
  },
1506
1579
  },
1580
+ ...(manifest.provenance === undefined
1581
+ ? {}
1582
+ : { provenance: normalizeProvenance(manifest.provenance, sentNonce) }),
1507
1583
  };
1508
1584
  }
1509
1585
 
1586
+ function normalizeProvenance(provenance: ManifestProvenance, sentNonce: string | undefined): ManifestProvenance {
1587
+ const out: ManifestProvenance = {};
1588
+ if (provenance.build_git_sha !== undefined) out.build_git_sha = provenance.build_git_sha;
1589
+ if (provenance.build_git_sha_absence_reason !== undefined) {
1590
+ out.build_git_sha_absence_reason = provenance.build_git_sha_absence_reason;
1591
+ }
1592
+ if (provenance.build_lock_digest !== undefined) out.build_lock_digest = provenance.build_lock_digest;
1593
+ if (provenance.wire_crate_version !== undefined) out.wire_crate_version = provenance.wire_crate_version;
1594
+ if (provenance.store_schema_version !== undefined) out.store_schema_version = provenance.store_schema_version;
1595
+ const source = provenance.launch_nonce_source ?? launchNonceSourceOf(sentNonce);
1596
+ if (source !== undefined) out.launch_nonce_source = source;
1597
+ return out;
1598
+ }
1599
+
1600
+ /**
1601
+ * Where the nonce HELLO sends came from, as the Rust SDK reports it: the
1602
+ * accessor's source when the accessor holds that same nonce, and nothing when
1603
+ * HELLO sends none or the caller supplied a different one.
1604
+ */
1605
+ function launchNonceSourceOf(sentNonce: string | undefined): LaunchNonceSource | undefined {
1606
+ if (sentNonce === undefined) return undefined;
1607
+ const nonce = launchNonceOrUndefined();
1608
+ return nonce !== undefined && nonce.value === sentNonce ? nonce.source : undefined;
1609
+ }
1610
+
1510
1611
  function normalizeProviderRole(role: ProviderRoleInput): ProviderRoleInput {
1511
1612
  switch (role.role) {
1512
1613
  case "tool_provider":