@nice-code/commander 0.109.0 → 0.111.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/build/cli.mjs CHANGED
@@ -27,7 +27,11 @@ const GLOBAL_VALUE_FLAGS = new Set(["--config", "--timeout"]);
27
27
  * plain Map keeps only the last. The name still lands in `flags` so `unknownFlags` keeps rejecting
28
28
  * it on every command that does not accept it.
29
29
  */
30
- const REPEATABLE_VALUE_FLAGS = new Set(["--set", "--unset"]);
30
+ const REPEATABLE_VALUE_FLAGS = new Set([
31
+ "--set",
32
+ "--unset",
33
+ "--with"
34
+ ]);
31
35
  /**
32
36
  * Per-command flags that take a VALUE. Everything else is boolean — and that distinction is
33
37
  * load-bearing: a greedy "consume the next token" parse turned `up --no-wait demo` into
@@ -39,6 +43,7 @@ function parseCliArgs(argv) {
39
43
  const flags = /* @__PURE__ */ new Map();
40
44
  const repeated = /* @__PURE__ */ new Map();
41
45
  const positionals = [];
46
+ const passthrough = [];
42
47
  let command = null;
43
48
  let json = false;
44
49
  let noColor = false;
@@ -47,6 +52,10 @@ function parseCliArgs(argv) {
47
52
  let timeoutMs;
48
53
  for (let i = 0; i < argv.length; i += 1) {
49
54
  const token = argv[i];
55
+ if (token === "--") {
56
+ passthrough.push(...argv.slice(i + 1));
57
+ break;
58
+ }
50
59
  const eq = token.startsWith("--") ? token.indexOf("=") : -1;
51
60
  const arg = eq > 2 ? token.slice(0, eq) : token;
52
61
  const inlineValue = eq > 2 ? token.slice(eq + 1) : null;
@@ -109,7 +118,8 @@ function parseCliArgs(argv) {
109
118
  noColor,
110
119
  help,
111
120
  flags,
112
- repeated
121
+ repeated,
122
+ passthrough
113
123
  };
114
124
  if (configPath != null) args.configPath = configPath;
115
125
  if (timeoutMs != null) args.timeoutMs = timeoutMs;
@@ -152,7 +162,7 @@ function validStartStamp(value) {
152
162
  function isInstanceRecord(value) {
153
163
  if (value == null || typeof value !== "object" || Array.isArray(value)) return false;
154
164
  const record = value;
155
- return record.service === "nice-commander" && boundedString(record.instanceId) && boundedInt(record.generation, 0, Number.MAX_SAFE_INTEGER) && boundedInt(record.pid, 1, Number.MAX_SAFE_INTEGER) && boundedInt(record.port, 1, 65535) && boundedString(record.token) && boundedString(record.configKey) && boundedString(record.configRevisionHash) && boundedString(record.configPath) && boundedString(record.packageVersion) && boundedString(record.realmSchemaHash) && validStartStamp(record.startStamp) && (record.servesOwnClient == null || typeof record.servesOwnClient === "boolean") && record.protocolVersion === 7;
165
+ return record.service === "nice-commander" && boundedString(record.instanceId) && boundedInt(record.generation, 0, Number.MAX_SAFE_INTEGER) && boundedInt(record.pid, 1, Number.MAX_SAFE_INTEGER) && boundedInt(record.port, 1, 65535) && boundedString(record.token) && boundedString(record.configKey) && boundedString(record.configRevisionHash) && boundedString(record.configPath) && boundedString(record.packageVersion) && boundedString(record.realmSchemaHash) && validStartStamp(record.startStamp) && (record.servesOwnClient == null || typeof record.servesOwnClient === "boolean") && record.protocolVersion === 8;
156
166
  }
157
167
  async function writeInstanceRecord(path, record) {
158
168
  await mkdir(dirname(path), {
@@ -202,7 +212,7 @@ async function readSkewedInstanceRecord(path, expectedRealmSchemaHash) {
202
212
  if (!boundedInt(record["protocolVersion"], 0, Number.MAX_SAFE_INTEGER)) return null;
203
213
  if (!boundedInt(record["pid"], 1, Number.MAX_SAFE_INTEGER)) return null;
204
214
  if (!boundedInt(record["port"], 1, 65535)) return null;
205
- const sameProtocol = record["protocolVersion"] === 7;
215
+ const sameProtocol = record["protocolVersion"] === 8;
206
216
  const sameRealm = boundedString(record["realmSchemaHash"]) && record["realmSchemaHash"] === expectedRealmSchemaHash;
207
217
  if (sameProtocol && sameRealm) return null;
208
218
  return {
@@ -298,6 +308,31 @@ async function pingDaemon(record, timeoutMs = 2e3) {
298
308
  }
299
309
  }
300
310
  //#endregion
311
+ //#region src/config/flags.ts
312
+ /**
313
+ * An argument a shell-string `run` can take appended unquoted in sh, cmd and PowerShell alike.
314
+ * Anything else (spaces, quotes, `$`, `%`, `,`, `;`…) would need per-shell quoting.
315
+ */
316
+ const SHELL_PLAIN_ARG = /^[A-Za-z0-9_+=:./-]+$/;
317
+ /** `run` with `args` appended — after the argv, or after the shell string. */
318
+ function runWithArgs(run, args) {
319
+ if (args.length === 0) return run;
320
+ return typeof run === "string" ? `${run} ${args.join(" ")}` : [...run, ...args];
321
+ }
322
+ /** Requested names against a definition's declared flags; an undeclared name is an error. */
323
+ function resolveFlags(definition, names) {
324
+ const unknown = names.filter((name) => !definition.flags.some((flag) => flag.name === name));
325
+ if (unknown.length > 0) {
326
+ const declared = definition.flags.map((flag) => flag.name);
327
+ return { error: `"${definition.id}" declares no flag ${unknown.map((name) => `"${name}"`).join(", ")} — ` + (declared.length > 0 ? `its flags: ${declared.join(", ")}` : "it declares none") };
328
+ }
329
+ const on = definition.flags.filter((flag) => names.includes(flag.name));
330
+ return {
331
+ flags: on.map((flag) => flag.name),
332
+ args: on.flatMap((flag) => flag.args)
333
+ };
334
+ }
335
+ //#endregion
301
336
  //#region src/config/tags.ts
302
337
  /** `key=value` → `[key, value]`, or null when the term is not tag-shaped. */
303
338
  function parseTagTerm(term) {
@@ -833,6 +868,54 @@ function readEnvVarFields(declared, name, at, errors) {
833
868
  required: required === true
834
869
  };
835
870
  }
871
+ const MAX_FLAGS = 32;
872
+ function readFlags(raw, shellString, at, errors) {
873
+ if (raw == null) return [];
874
+ if (!Array.isArray(raw)) {
875
+ errors.push(`${at}.flags: expected an array of flag declarations`);
876
+ return [];
877
+ }
878
+ if (raw.length > MAX_FLAGS) errors.push(`${at}.flags: ${raw.length} entries exceeds the ${MAX_FLAGS} bound`);
879
+ const flags = [];
880
+ for (const [index, declared] of raw.entries()) {
881
+ const atF = `${at}.flags[${index}]`;
882
+ if (!isRecord(declared)) {
883
+ errors.push(`${atF}: expected an object`);
884
+ continue;
885
+ }
886
+ const name = declared["name"];
887
+ if (typeof name !== "string" || !COMMANDER_ID_PATTERN.test(name)) {
888
+ errors.push(`${atF}.name: must match ${COMMANDER_ID_PATTERN}`);
889
+ continue;
890
+ }
891
+ if (flags.some((existing) => existing.name === name)) {
892
+ errors.push(`${atF}.name: duplicate flag "${name}"`);
893
+ continue;
894
+ }
895
+ const description = declared["description"];
896
+ if (description != null && typeof description !== "string") {
897
+ errors.push(`${atF}.description: expected a string`);
898
+ continue;
899
+ }
900
+ const rawArgs = declared["args"] ?? [`--${name}`];
901
+ if (!Array.isArray(rawArgs) || rawArgs.length === 0 || rawArgs.some((arg) => typeof arg !== "string" || arg === "" || hasControlChars(arg))) {
902
+ errors.push(`${atF}.args: expected a non-empty array of non-empty strings`);
903
+ continue;
904
+ }
905
+ const args = rawArgs.filter((arg) => typeof arg === "string");
906
+ const unquotable = shellString ? args.find((arg) => !SHELL_PLAIN_ARG.test(arg)) : void 0;
907
+ if (unquotable != null) {
908
+ errors.push(`${atF}.args: ${JSON.stringify(unquotable)} would need shell quoting, and a shell-string \`run\` takes its flags unquoted — use the argv form of \`run\`, or a plain argument`);
909
+ continue;
910
+ }
911
+ flags.push({
912
+ name,
913
+ args,
914
+ ...typeof description === "string" ? { description } : {}
915
+ });
916
+ }
917
+ return flags;
918
+ }
836
919
  function isUrlCleanHttp(url) {
837
920
  try {
838
921
  const parsed = new URL(url);
@@ -1012,6 +1095,7 @@ function validateCommanderConfig(raw, anchor) {
1012
1095
  if (resolved != null) envVars.push(resolved);
1013
1096
  }
1014
1097
  for (const declared of envVars) if (declared.default != null) env[declared.name] = declared.default;
1098
+ const flags = readFlags(proc.flags, typeof proc.run === "string", at, errors);
1015
1099
  const tagEntries = Object.entries({
1016
1100
  ...config.defaults?.tags,
1017
1101
  ...proc.tags
@@ -1115,6 +1199,7 @@ function validateCommanderConfig(raw, anchor) {
1115
1199
  ...proc.shell != null ? { shell: proc.shell } : {},
1116
1200
  env,
1117
1201
  envVars,
1202
+ flags,
1118
1203
  stdin,
1119
1204
  tags,
1120
1205
  optIn: proc.optIn === true,
@@ -1307,6 +1392,28 @@ function selectOrExit(ctx, options) {
1307
1392
  if (!result.ok) throw new CliExit(EXIT.usage, result.errors.join("\n"));
1308
1393
  return result.selection;
1309
1394
  }
1395
+ /**
1396
+ * The one process a per-process option (`--with`, `-- args`) applies to: the selection must be
1397
+ * exactly its id — a flag set means nothing to a suite or a tag.
1398
+ */
1399
+ function singleProcessOrExit(ctx, option) {
1400
+ const [term, ...rest] = ctx.args.positionals;
1401
+ const definition = ctx.config.processes.find((proc) => proc.id === term);
1402
+ if (definition == null || rest.length > 0 || ctx.args.flags.has("--all")) throw new CliExit(EXIT.usage, `${option} applies to one process — select it by its id alone (\`${ctx.args.command} <id> ${option} …\`)`);
1403
+ return definition;
1404
+ }
1405
+ /** `--with a --with b` / `--with a,b`, resolved against the selected process's declared flags. */
1406
+ function flagsOrExit(ctx) {
1407
+ const raw = ctx.args.repeated.get("--with") ?? [];
1408
+ if (raw.length === 0) return null;
1409
+ const definition = singleProcessOrExit(ctx, "--with");
1410
+ const resolved = resolveFlags(definition, raw.flatMap((value) => value.split(",")).filter((name) => name !== ""));
1411
+ if ("error" in resolved) throw new CliExit(EXIT.usage, resolved.error);
1412
+ return {
1413
+ id: definition.id,
1414
+ ...resolved
1415
+ };
1416
+ }
1310
1417
  /** Suite stagger for a start: the widest stagger among the suites named in the terms. */
1311
1418
  function staggerFor(config, terms) {
1312
1419
  let stagger = 0;
@@ -1379,6 +1486,7 @@ function wsAcceptorCarrier(options) {
1379
1486
  carrierLabel: options.carrierLabel ?? "ws",
1380
1487
  secure: options.secure,
1381
1488
  send: options.send,
1489
+ close: options.close,
1382
1490
  upgrade: options.upgrade,
1383
1491
  isUpgrade: options.isUpgrade ?? ((request) => request.headers.get("Upgrade") === "websocket"),
1384
1492
  attachmentStore: options.attachmentStore
@@ -2432,16 +2540,16 @@ const err_wire_connect = err_nice.createChildDomain({
2432
2540
  */
2433
2541
  endpoint_answered_non_protocol: err({ message: ({ stage, expected, url, httpStatus, contentType, receivedKind, bodyPreview }) => {
2434
2542
  const received = httpStatus != null ? `an HTTP ${httpStatus}${contentType != null ? ` ${contentType}` : ""} response` : receivedKind != null ? `a "${receivedKind}" frame` : "a response it could not decode";
2435
- return `[${stage}] expected ${expected ?? "a nice-wire frame"} but received ${received} — the endpoint answered but is not speaking the nice-wire protocol (wrong URL, an intercepting proxy/WAF, or a different server)${url != null ? `. Dialed: ${url}` : ""}${bodyPreview != null ? `. Body: ${JSON.stringify(bodyPreview)}` : ""}.`;
2543
+ const diagnosis = httpStatus != null && httpStatus >= 500 ? "the server answered with an error instead of a nice-wire frame (check the server's logs: a crashed handler or an unavailable upstream answers this way)" : "the endpoint answered but is not speaking the nice-wire protocol (wrong URL, an intercepting proxy/WAF, or a different server)";
2544
+ return `[${stage}] expected ${expected ?? "a nice-wire frame"} but received ${received} — ` + diagnosis + `${url != null ? `. Dialed: ${url}` : ""}${bodyPreview != null ? `. Body: ${JSON.stringify(bodyPreview)}` : ""}.`;
2436
2545
  } }),
2437
2546
  /**
2438
- * Consumer feedback (meteor-connect-bridge W3) — **nothing answered**: DNS/refused/TLS/offline,
2439
- * or a socket that errored before it opened. The sibling of
2440
- * `endpoint_answered_non_protocol`, and the reason the two are separate ids: they need
2441
- * opposite developer responses (start the server / open the firewall, vs fix the URL or the
2442
- * proxy in front of it).
2547
+ * **No response was received**: DNS/refused/TLS/offline, a socket that errored before it
2548
+ * opened, or a response the platform hid from the caller (a CORS-blocked answer, a refused
2549
+ * WebSocket upgrade, an injected fetch/socket that threw). The sibling of
2550
+ * `endpoint_answered_non_protocol`, which carries the response it did see.
2443
2551
  */
2444
- endpoint_unreachable: err({ message: ({ url, carrierLabel, reason }) => `Could not reach ${url ?? (carrierLabel != null ? `the "${carrierLabel}" endpoint` : "the endpoint")}: ${reason} — nothing answered there (wrong host/port, the server is not running, or a firewall/offline network).` }),
2552
+ endpoint_unreachable: err({ message: ({ url, carrierLabel, reason }) => `Could not reach ${url ?? (carrierLabel != null ? `the "${carrierLabel}" endpoint` : "the endpoint")}: ${reason} — no response was received (a network, DNS or TLS failure; a response the browser blocked or hid, such as a CORS rejection or a refused WebSocket upgrade; or the fetch/socket implementation threw).` }),
2445
2553
  /**
2446
2554
  * The peer **is** a nice-code backend and refused the handshake for a reason that carries no
2447
2555
  * machine-readable id of its own (an older peer, a dictionary/security mismatch, a custom
@@ -2484,6 +2592,29 @@ const err_wire_connect = err_nice.createChildDomain({
2484
2592
  }
2485
2593
  });
2486
2594
  //#endregion
2595
+ //#region ../nice-wire/src/Connect/sanitizeEndpoint.ts
2596
+ /**
2597
+ * A destination safe to put in diagnostics. Credentials, query parameters, and fragments can carry
2598
+ * secrets (capability tokens, signed leases), so only the scheme, host, port, and path survive.
2599
+ */
2600
+ function sanitizeEndpoint(raw) {
2601
+ if (raw == null) return void 0;
2602
+ try {
2603
+ const url = new URL(raw);
2604
+ if (url.host !== "") {
2605
+ url.username = "";
2606
+ url.password = "";
2607
+ url.search = "";
2608
+ url.hash = "";
2609
+ return url.toString();
2610
+ }
2611
+ } catch {}
2612
+ const head = raw.split(/[?#]/, 1)[0] ?? "";
2613
+ const authority = /^([a-z][a-z\d+.-]*:)?\/\//i.exec(head);
2614
+ if (authority != null) return authority[0] + head.slice(authority[0].length).replace(/^[^/@]*@/, "");
2615
+ return head.replace(/^[^/]*@/, "");
2616
+ }
2617
+ //#endregion
2487
2618
  //#region ../nice-wire/src/Carrier/duplex/ws/ws_util.ts
2488
2619
  /**
2489
2620
  * Send a text or binary frame over a socket. A binary formatter may hand back a `Uint8Array` whose
@@ -2578,8 +2709,9 @@ function webSocketByteChannel(ws) {
2578
2709
  }
2579
2710
  /**
2580
2711
  * A failed dial, as a structured error the error pipeline (and a consumer's logs) can actually
2581
- * read. A socket that errors or closes *before* it opened means nothing answered, so it carries
2582
- * the same typed `endpoint_unreachable` id as the HTTP carrier's `fetch` rejection — that is what
2712
+ * read. A socket that errors or closes *before* it opened yields no readable response (the browser
2713
+ * also hides a refused upgrade's status), so it carries the same typed `endpoint_unreachable` id as
2714
+ * the HTTP carrier's `fetch` rejection — that is what
2583
2715
  * makes `EWireConnectFailureKind` trustworthy on both carriers rather than HTTP-only (feedback W3).
2584
2716
  */
2585
2717
  function dialFailedError(ws) {
@@ -2587,13 +2719,13 @@ function dialFailedError(ws) {
2587
2719
  }
2588
2720
  function unreachableError(ws, reason) {
2589
2721
  return err_wire_connect.fromId("endpoint_unreachable", {
2590
- url: ws.url != null && ws.url !== "" ? ws.url : void 0,
2722
+ url: ws.url != null && ws.url !== "" ? sanitizeEndpoint(ws.url) : void 0,
2591
2723
  carrierLabel: "ws",
2592
2724
  reason
2593
2725
  });
2594
2726
  }
2595
2727
  function describeSocket(ws) {
2596
- return ws.url != null && ws.url !== "" ? ws.url : "(no url)";
2728
+ return (ws.url != null && ws.url !== "" ? sanitizeEndpoint(ws.url) : void 0) ?? "(no url)";
2597
2729
  }
2598
2730
  /** Accept text + binary frames (ArrayBuffer / Uint8Array / Blob); Blobs are converted to a buffer. */
2599
2731
  async function normalizeFrame(data) {
@@ -2676,23 +2808,6 @@ function describeNonProtocolBody(raw) {
2676
2808
  return flattened.length > BODY_PREVIEW_LIMIT ? `${flattened.slice(0, BODY_PREVIEW_LIMIT)}…` : flattened;
2677
2809
  }
2678
2810
  /**
2679
- * A destination safe to put in diagnostics. Credentials, query parameters, and fragments can
2680
- * contain secrets, so connection errors retain only the scheme, host, port, and path.
2681
- */
2682
- function sanitizeEndpoint(raw) {
2683
- if (raw == null) return void 0;
2684
- try {
2685
- const url = new URL(raw);
2686
- url.username = "";
2687
- url.password = "";
2688
- url.search = "";
2689
- url.hash = "";
2690
- return url.toString();
2691
- } catch {
2692
- return raw.split(/[?#]/, 1)[0];
2693
- }
2694
- }
2695
- /**
2696
2811
  * Classify a dial failure. Reads typed ids only — the ids are raised at the layer that still holds
2697
2812
  * the evidence precisely so this never has to sniff message text.
2698
2813
  */
@@ -2705,12 +2820,12 @@ function classifyConnectFailure(error) {
2705
2820
  if (error.hasId("identity_pin_mismatch") || error.hasId("handshake_rejected")) return "handshake_rejected";
2706
2821
  return "unknown";
2707
2822
  }
2708
- /** The endpoint a failure names, when it carries one — the URL actually dialed. */
2823
+ /** The endpoint a failure names, when it carries one — the URL actually dialed, sanitized. */
2709
2824
  function endpointFromConnectFailure(error) {
2710
2825
  if (!err_wire_connect.isExact(error)) return void 0;
2711
- if (error.hasId("endpoint_answered_non_protocol")) return error.getContext("endpoint_answered_non_protocol").url;
2712
- if (error.hasId("endpoint_unreachable")) return error.getContext("endpoint_unreachable").url;
2713
- if (error.hasId("peer_identity_mismatch")) return error.getContext("peer_identity_mismatch").endpoint;
2826
+ if (error.hasId("endpoint_answered_non_protocol")) return sanitizeEndpoint(error.getContext("endpoint_answered_non_protocol").url);
2827
+ if (error.hasId("endpoint_unreachable")) return sanitizeEndpoint(error.getContext("endpoint_unreachable").url);
2828
+ if (error.hasId("peer_identity_mismatch")) return sanitizeEndpoint(error.getContext("peer_identity_mismatch").endpoint);
2714
2829
  }
2715
2830
  //#endregion
2716
2831
  //#region ../nice-wire/src/Connect/ConnectionTransportManager.ts
@@ -2745,81 +2860,110 @@ var ConnectionTransportManager$1 = class {
2745
2860
  const candidates = [];
2746
2861
  const unavailableTransports = [];
2747
2862
  for (const transport of this._transports) {
2748
- if (!transport.isAvailable(input)) {
2749
- unavailableTransports.push(transport);
2750
- continue;
2751
- }
2752
- const cacheKey = transport.getCacheKey(input);
2753
- if (cacheKey != null) {
2754
- const cached = this._cache.get(cacheKey);
2755
- if (cached != null) {
2756
- if (cached instanceof Promise) {
2863
+ let cacheKey = null;
2864
+ try {
2865
+ if (!transport.isAvailable(input)) {
2866
+ unavailableTransports.push(transport);
2867
+ continue;
2868
+ }
2869
+ cacheKey = transport.getCacheKey(input);
2870
+ if (cacheKey != null) {
2871
+ const cached = this._cache.get(cacheKey);
2872
+ if (cached != null) {
2873
+ if (cached instanceof Promise) {
2874
+ candidates.push({
2875
+ transport,
2876
+ promise: cached,
2877
+ cacheKey,
2878
+ fresh: false
2879
+ });
2880
+ continue;
2881
+ }
2757
2882
  candidates.push({
2758
2883
  transport,
2759
- promise: cached
2884
+ promise: Promise.resolve({
2885
+ ...cached,
2886
+ transport
2887
+ }),
2888
+ cacheKey,
2889
+ fresh: false
2890
+ });
2891
+ break;
2892
+ }
2893
+ }
2894
+ const statusInfo = transport.getTransport(input);
2895
+ if (statusInfo.status === "ready") {
2896
+ const readyData = statusInfo.readyData;
2897
+ if (cacheKey != null) {
2898
+ const key = cacheKey;
2899
+ const entry = {
2900
+ methods: readyData,
2901
+ transport
2902
+ };
2903
+ this._cache.set(key, entry);
2904
+ readyData.addOnDisconnectListener?.(() => {
2905
+ if (this._cache.get(key) === entry) this._cache.delete(key);
2760
2906
  });
2761
- continue;
2762
2907
  }
2763
2908
  candidates.push({
2764
2909
  transport,
2765
2910
  promise: Promise.resolve({
2766
- ...cached,
2911
+ methods: readyData,
2767
2912
  transport
2768
- })
2913
+ }),
2914
+ cacheKey,
2915
+ fresh: true
2769
2916
  });
2770
2917
  break;
2771
2918
  }
2772
- }
2773
- const statusInfo = transport.getTransport(input);
2774
- if (statusInfo.status === "ready") {
2775
- const readyData = statusInfo.readyData;
2776
- if (cacheKey != null) {
2777
- const entry = {
2778
- methods: readyData,
2779
- transport
2780
- };
2781
- this._cache.set(cacheKey, entry);
2782
- readyData.addOnDisconnectListener?.(() => {
2783
- if (this._cache.get(cacheKey) === entry) this._cache.delete(cacheKey);
2919
+ if (statusInfo.status === "unsupported") {
2920
+ unavailableTransports.push(transport);
2921
+ continue;
2922
+ }
2923
+ if (statusInfo.status === "initializing") {
2924
+ const key = cacheKey;
2925
+ const promise = statusInfo.initializationPromise.then((info) => {
2926
+ if (info.status === "failed") throw info.error;
2927
+ if (info.status === "unsupported") throw this._errors.unsupported([transport.type]);
2928
+ const readyData = info.readyData;
2929
+ const entry = {
2930
+ methods: readyData,
2931
+ transport
2932
+ };
2933
+ if (key != null) if (this._cache.get(key) === promise) {
2934
+ this._cache.set(key, entry);
2935
+ readyData.addOnDisconnectListener?.(() => {
2936
+ if (this._cache.get(key) === entry) this._cache.delete(key);
2937
+ });
2938
+ } else readyData.disconnect?.();
2939
+ return entry;
2940
+ }).catch((e) => {
2941
+ if (key != null && this._cache.get(key) === promise) this._cache.delete(key);
2942
+ throw e;
2943
+ });
2944
+ promise.catch(() => {});
2945
+ if (key != null) this._cache.set(key, promise);
2946
+ candidates.push({
2947
+ transport,
2948
+ promise,
2949
+ cacheKey: key,
2950
+ fresh: true
2784
2951
  });
2785
2952
  }
2953
+ } catch (e) {
2954
+ if (isDialUnavailable$1(e)) {
2955
+ if (candidates.length === 0) throw e;
2956
+ unavailableTransports.push(transport);
2957
+ continue;
2958
+ }
2959
+ const failed = Promise.reject(e);
2960
+ failed.catch(() => {});
2786
2961
  candidates.push({
2787
2962
  transport,
2788
- promise: Promise.resolve({
2789
- methods: readyData,
2790
- transport
2791
- })
2792
- });
2793
- break;
2794
- }
2795
- if (statusInfo.status === "unsupported") {
2796
- unavailableTransports.push(transport);
2797
- continue;
2798
- }
2799
- if (statusInfo.status === "initializing") {
2800
- const promise = statusInfo.initializationPromise.then((info) => {
2801
- if (info.status === "failed") throw info.error;
2802
- if (info.status === "unsupported") throw this._errors.unsupported([transport.type]);
2803
- const readyData = info.readyData;
2804
- const entry = {
2805
- methods: readyData,
2806
- transport
2807
- };
2808
- if (cacheKey != null) if (this._cache.get(cacheKey) === promise) {
2809
- this._cache.set(cacheKey, entry);
2810
- readyData.addOnDisconnectListener?.(() => {
2811
- if (this._cache.get(cacheKey) === entry) this._cache.delete(cacheKey);
2812
- });
2813
- } else readyData.disconnect?.();
2814
- return entry;
2815
- }).catch((e) => {
2816
- if (cacheKey != null && this._cache.get(cacheKey) === promise) this._cache.delete(cacheKey);
2817
- throw e;
2818
- });
2819
- if (cacheKey != null) this._cache.set(cacheKey, promise);
2820
- candidates.push({
2821
- transport,
2822
- promise
2963
+ promise: failed,
2964
+ cacheKey,
2965
+ fresh: true,
2966
+ callerThrew: true
2823
2967
  });
2824
2968
  }
2825
2969
  }
@@ -2829,31 +2973,79 @@ var ConnectionTransportManager$1 = class {
2829
2973
  }
2830
2974
  let lastError;
2831
2975
  let lastTransport;
2832
- for (const candidate of candidates) try {
2833
- return await candidate.promise;
2834
- } catch (e) {
2835
- if (err_wire_connect.isExact(e) && e.hasId("peer_identity_mismatch")) {
2836
- const context = e.getContext("peer_identity_mismatch");
2837
- const endpoint = sanitizeEndpoint(candidate.transport.getRouteInfo(input)?.url);
2838
- if (endpoint != null && context.endpoint == null) throw err_wire_connect.fromId("peer_identity_mismatch", {
2839
- ...context,
2840
- endpoint
2841
- }).withOriginError(e);
2842
- throw e;
2976
+ let lastCallerThrew = false;
2977
+ for (const candidate of candidates) {
2978
+ let ready;
2979
+ try {
2980
+ ready = await candidate.promise;
2981
+ } catch (e) {
2982
+ if (isTerminalSelectionError(e)) {
2983
+ this._abandonWarmUps(candidates, candidate);
2984
+ throw this._withDialedEndpoint(e, candidate.transport, input);
2985
+ }
2986
+ lastError = e;
2987
+ lastTransport = candidate.transport;
2988
+ lastCallerThrew = candidate.callerThrew === true;
2989
+ continue;
2843
2990
  }
2844
- if (err_wire_connect.isExact(e) && e.hasId("protocol_version_mismatch")) throw e;
2845
- lastError = e;
2846
- lastTransport = candidate.transport;
2991
+ ready.methods.onSelected?.();
2992
+ return ready;
2847
2993
  }
2848
2994
  if (err_wire_connect.isExact(lastError) && (lastError.hasId("dial_unavailable") || lastError.hasId("identity_pin_mismatch") || lastError.hasId("protocol_version_mismatch") || lastError.hasId("peer_identity_mismatch"))) throw lastError;
2995
+ if (lastCallerThrew && !err_wire_connect.isExact(lastError)) throw lastError;
2849
2996
  throw this._errors.initializationFailed(input, {
2850
2997
  cause: describeTransportFailure(lastError),
2851
- endpoint: endpointFromConnectFailure(lastError) ?? lastTransport?.getRouteInfo(input)?.url,
2998
+ endpoint: endpointFromConnectFailure(lastError) ?? routeEndpoint(lastTransport, input),
2852
2999
  kind: classifyConnectFailure(lastError),
2853
3000
  origin: lastError
2854
3001
  });
2855
3002
  }
3003
+ /**
3004
+ * Close the parallel warm-ups this selection started besides `failed`. Each one's cache slot is
3005
+ * released so a later dispatch re-dials; a warm-up still connecting closes itself when it lands.
3006
+ */
3007
+ _abandonWarmUps(candidates, failed) {
3008
+ for (const candidate of candidates) {
3009
+ if (candidate === failed || !candidate.fresh) continue;
3010
+ const key = candidate.cacheKey;
3011
+ if (key != null && this._cache.get(key) === candidate.promise) this._cache.delete(key);
3012
+ candidate.promise.then((entry) => {
3013
+ if (key == null) {
3014
+ entry.methods.disconnect?.();
3015
+ return;
3016
+ }
3017
+ const cached = this._cache.get(key);
3018
+ if (cached != null && !(cached instanceof Promise) && cached.methods === entry.methods) {
3019
+ this._cache.delete(key);
3020
+ entry.methods.disconnect?.();
3021
+ }
3022
+ }, () => {});
3023
+ }
3024
+ }
3025
+ /** Attach the sanitized dialed endpoint to a peer-identity mismatch that lacks one. */
3026
+ _withDialedEndpoint(error, transport, input) {
3027
+ if (!err_wire_connect.isExact(error) || !error.hasId("peer_identity_mismatch")) return error;
3028
+ const context = error.getContext("peer_identity_mismatch");
3029
+ if (context.endpoint != null) return error;
3030
+ const endpoint = routeEndpoint(transport, input);
3031
+ if (endpoint == null) return error;
3032
+ return err_wire_connect.fromId("peer_identity_mismatch", {
3033
+ ...context,
3034
+ endpoint
3035
+ }).withOriginError(error);
3036
+ }
2856
3037
  };
3038
+ const isDialUnavailable$1 = (error) => err_wire_connect.isExact(error) && error.hasId("dial_unavailable");
3039
+ const isTerminalSelectionError = (error) => err_wire_connect.isExact(error) && (error.hasId("peer_identity_mismatch") || error.hasId("protocol_version_mismatch"));
3040
+ /** The transport's sanitized route URL for diagnostics; a throwing route resolver yields none. */
3041
+ function routeEndpoint(transport, input) {
3042
+ if (transport == null) return void 0;
3043
+ try {
3044
+ return sanitizeEndpoint(transport.getRouteInfo(input)?.url);
3045
+ } catch {
3046
+ return;
3047
+ }
3048
+ }
2857
3049
  /**
2858
3050
  * A short, human-readable reason for a transport failing to connect — surfaced in the
2859
3051
  * consumer's initialization-failed message so the caller sees *why* (e.g. a rejected handshake) rather
@@ -8844,7 +9036,7 @@ function wrongHandshakeFrame(channel, expected, receivedKind) {
8844
9036
  return err_wire_connect.fromId("endpoint_answered_non_protocol", {
8845
9037
  stage: LINK_HANDSHAKE_STAGE,
8846
9038
  expected,
8847
- url: channel.label,
9039
+ url: sanitizeEndpoint(channel.label),
8848
9040
  receivedKind: `hs/${receivedKind}`
8849
9041
  });
8850
9042
  }
@@ -8894,6 +9086,32 @@ function startHeartbeat(channel, config, tap) {
8894
9086
  }
8895
9087
  };
8896
9088
  }
9089
+ function bindMux(mux, remoteIds, pipe, disconnectListeners, tap) {
9090
+ let attached = false;
9091
+ let closed = false;
9092
+ const held = [];
9093
+ disconnectListeners.push(() => {
9094
+ closed = true;
9095
+ held.length = 0;
9096
+ if (attached) mux.detach();
9097
+ });
9098
+ return {
9099
+ mux,
9100
+ dispatch: (frame) => {
9101
+ if (attached) return mux.dispatchIncoming(frame);
9102
+ if (peekProtocolPrefix(frame) == null) return false;
9103
+ if (!closed) held.push(frame);
9104
+ return true;
9105
+ },
9106
+ attach: () => {
9107
+ if (attached || closed) return;
9108
+ attached = true;
9109
+ mux.setRemoteProtocolIds(remoteIds());
9110
+ mux.attach(tap != null ? (bytes) => pipe.send(bytes, mux.protocolIdFor(bytes) ?? "protocol") : (bytes) => pipe.send(bytes));
9111
+ for (const frame of held.splice(0)) mux.dispatchIncoming(frame);
9112
+ }
9113
+ };
9114
+ }
8897
9115
  /**
8898
9116
  * Wrap a carrier so a **deliberate local** `close()` notifies the session immediately and exactly
8899
9117
  * once, rather than waiting for the platform's close event. On a real WebSocket that event lags a
@@ -8950,6 +9168,7 @@ function establishPlainDuplexSession(ctx) {
8950
9168
  const mux = ctx.mux;
8951
9169
  const heartbeat = ctx.heartbeat != null ? startHeartbeat(channel, ctx.heartbeat, tap) : void 0;
8952
9170
  if (heartbeat != null) disconnectListeners.push(heartbeat.stop);
9171
+ const muxBinding = mux == null ? void 0 : bindMux(mux, () => protocolsFromCaps(mux.localCaps()), pipe, disconnectListeners, tap);
8953
9172
  channel.attach({
8954
9173
  onMessage: (frame) => {
8955
9174
  heartbeat?.noteInbound();
@@ -8961,17 +9180,13 @@ function establishPlainDuplexSession(ctx) {
8961
9180
  });
8962
9181
  return;
8963
9182
  }
8964
- handleIncomingFrame(pipe, frame, mux, ctx.lane, port, tap);
9183
+ handleIncomingFrame(pipe, frame, muxBinding, ctx.lane, port, tap);
8965
9184
  },
8966
9185
  onClose: () => onChannelClosed(disconnectListeners, ctx.lane),
8967
9186
  onError: () => onChannelClosed(disconnectListeners, ctx.lane)
8968
9187
  });
8969
- if (mux != null) {
8970
- mux.setRemoteProtocolIds(protocolsFromCaps(mux.localCaps()));
8971
- mux.attach(tap != null ? (bytes) => pipe.send(bytes, mux.protocolIdFor(bytes) ?? "protocol") : (bytes) => pipe.send(bytes));
8972
- disconnectListeners.push(() => mux.detach());
8973
- }
8974
- return makeSession$1(channel, pipe, disconnectListeners, void 0);
9188
+ if (ctx.deferMuxAttach !== true) muxBinding?.attach();
9189
+ return makeSession$1(channel, pipe, disconnectListeners, void 0, muxBinding);
8975
9190
  }
8976
9191
  /**
8977
9192
  * Secure path: a single message handler feeds the handshake until it completes, then routes lane
@@ -9005,7 +9220,7 @@ async function establishSecureDuplexSession(ctx) {
9005
9220
  return;
9006
9221
  }
9007
9222
  if (active && session.pipe != null && session.port != null) {
9008
- handleIncomingFrame(session.pipe, frame, mux, ctx.lane, session.port, tap);
9223
+ handleIncomingFrame(session.pipe, frame, session.muxBinding, ctx.lane, session.port, tap);
9009
9224
  return;
9010
9225
  }
9011
9226
  if (typeof frame === "string") {
@@ -9035,7 +9250,7 @@ async function establishSecureDuplexSession(ctx) {
9035
9250
  const timeout = setTimeout(() => reject(nonProtocolFrame != null ? err_wire_connect.fromId("endpoint_answered_non_protocol", {
9036
9251
  stage: LINK_HANDSHAKE_STAGE,
9037
9252
  expected: "a handshake frame",
9038
- url: channel.label,
9253
+ url: sanitizeEndpoint(channel.label),
9039
9254
  bodyPreview: describeNonProtocolBody(nonProtocolFrame)
9040
9255
  }) : /* @__PURE__ */ new Error(`[${LINK_HANDSHAKE_STAGE}] timed out waiting for peer reply`)), HANDSHAKE_TIMEOUT_MS$1);
9041
9256
  handshakeWaiters.push((message) => {
@@ -9044,28 +9259,31 @@ async function establishSecureDuplexSession(ctx) {
9044
9259
  });
9045
9260
  });
9046
9261
  };
9047
- const { crypto, remoteCaps } = await runClientHandshake({
9048
- ...ctx,
9049
- channel
9050
- }, nextHandshakeMessage);
9051
- const pipe = makePipe(channel, crypto, tap);
9052
- const port = makeLanePort(channel, pipe);
9053
- session.pipe = pipe;
9054
- session.port = port;
9055
- if (mux != null) {
9056
- mux.setRemoteProtocolIds(protocolsFromCaps(remoteCaps));
9057
- mux.attach(tap != null ? (bytes) => pipe.send(bytes, mux.protocolIdFor(bytes) ?? "protocol") : (bytes) => pipe.send(bytes));
9058
- disconnectListeners.push(() => mux.detach());
9059
- }
9060
- ctx.lane.onAttach?.(port, { remoteCaps: remoteCaps ?? [] });
9061
- active = true;
9062
- for (const frame of pendingFrames) await handleIncomingFrame(pipe, frame, mux, ctx.lane, port, tap);
9063
- pendingFrames.length = 0;
9064
- if (ctx.heartbeat != null) {
9065
- heartbeat = startHeartbeat(channel, ctx.heartbeat, tap);
9066
- disconnectListeners.push(heartbeat.stop);
9067
- }
9068
- return makeSession$1(channel, pipe, disconnectListeners, remoteCaps);
9262
+ try {
9263
+ const { crypto, remoteCaps } = await runClientHandshake({
9264
+ ...ctx,
9265
+ channel
9266
+ }, nextHandshakeMessage);
9267
+ const pipe = makePipe(channel, crypto, tap);
9268
+ const port = makeLanePort(channel, pipe);
9269
+ session.pipe = pipe;
9270
+ session.port = port;
9271
+ const muxBinding = mux == null ? void 0 : bindMux(mux, () => protocolsFromCaps(remoteCaps), pipe, disconnectListeners, tap);
9272
+ session.muxBinding = muxBinding;
9273
+ if (ctx.deferMuxAttach !== true) muxBinding?.attach();
9274
+ ctx.lane.onAttach?.(port, { remoteCaps: remoteCaps ?? [] });
9275
+ active = true;
9276
+ for (const frame of pendingFrames) await handleIncomingFrame(pipe, frame, muxBinding, ctx.lane, port, tap);
9277
+ pendingFrames.length = 0;
9278
+ if (ctx.heartbeat != null) {
9279
+ heartbeat = startHeartbeat(channel, ctx.heartbeat, tap);
9280
+ disconnectListeners.push(heartbeat.stop);
9281
+ }
9282
+ return makeSession$1(channel, pipe, disconnectListeners, remoteCaps, muxBinding);
9283
+ } catch (error) {
9284
+ closeQuietly(channel);
9285
+ throw error;
9286
+ }
9069
9287
  }
9070
9288
  function makePipe(channel, crypto, tap) {
9071
9289
  return createFrameCryptoPipe({
@@ -9088,19 +9306,21 @@ function makeLanePort(channel, pipe) {
9088
9306
  isOpen: () => channel.isOpen()
9089
9307
  };
9090
9308
  }
9091
- function makeSession$1(channel, pipe, disconnectListeners, remoteCaps) {
9309
+ function closeQuietly(channel) {
9310
+ try {
9311
+ channel.close();
9312
+ } catch {}
9313
+ }
9314
+ function makeSession$1(channel, pipe, disconnectListeners, remoteCaps, muxBinding) {
9092
9315
  return {
9093
9316
  send: (frame) => pipe.send(frame),
9094
9317
  isOpen: () => channel.isOpen(),
9095
- close: () => {
9096
- try {
9097
- channel.close();
9098
- } catch {}
9099
- },
9318
+ close: () => closeQuietly(channel),
9100
9319
  addOnDisconnectListener: (listener) => {
9101
9320
  disconnectListeners.push(listener);
9102
9321
  },
9103
- remoteCaps
9322
+ remoteCaps,
9323
+ attachMux: muxBinding == null ? void 0 : () => muxBinding.attach()
9104
9324
  };
9105
9325
  }
9106
9326
  async function runClientHandshake(ctx, nextHandshakeMessage) {
@@ -9142,15 +9362,15 @@ async function runClientHandshake(ctx, nextHandshakeMessage) {
9142
9362
  };
9143
9363
  }
9144
9364
  /** Decrypt → mux dispatch → the lane. Awaited by the pre-ready flush so frame order holds. */
9145
- async function handleIncomingFrame(pipe, frame, mux, lane, port, tap) {
9365
+ async function handleIncomingFrame(pipe, frame, muxBinding, lane, port, tap) {
9146
9366
  const wireBytes = tap != null ? wireFrameByteSize(frame) : 0;
9147
9367
  const decoded = await pipe.decryptIncoming(frame);
9148
9368
  if (decoded === void 0) return;
9149
- if (mux?.dispatchIncoming(decoded)) {
9369
+ if (muxBinding?.dispatch(decoded)) {
9150
9370
  tap?.({
9151
9371
  dir: "in",
9152
9372
  bytes: wireBytes,
9153
- lane: mux.protocolIdFor(decoded) ?? "protocol"
9373
+ lane: muxBinding.mux.protocolIdFor(decoded) ?? "protocol"
9154
9374
  });
9155
9375
  return;
9156
9376
  }
@@ -9579,7 +9799,7 @@ async function exchangeHandshakeFrame(carrier, request, expected) {
9579
9799
  if (reply == null) throw err_wire_connect.fromId("endpoint_answered_non_protocol", {
9580
9800
  stage: HANDSHAKE_STAGE,
9581
9801
  expected,
9582
- url: carrier.label,
9802
+ url: sanitizeEndpoint(carrier.label),
9583
9803
  bodyPreview: describeNonProtocolBody(raw)
9584
9804
  });
9585
9805
  if (reply.k === "err") throw err_wire_connect.fromId("handshake_rejected", {
@@ -9593,13 +9813,14 @@ function nonProtocolReply(carrier, expected, receivedKind) {
9593
9813
  return err_wire_connect.fromId("endpoint_answered_non_protocol", {
9594
9814
  stage: HANDSHAKE_STAGE,
9595
9815
  expected,
9596
- url: carrier.label,
9816
+ url: sanitizeEndpoint(carrier.label),
9597
9817
  receivedKind
9598
9818
  });
9599
9819
  }
9600
9820
  /** Make a peer-bug message self-locating without inventing a typed id for it. */
9601
9821
  function at(carrier) {
9602
- return carrier.label != null ? ` (endpoint: ${carrier.label})` : "";
9822
+ const endpoint = sanitizeEndpoint(carrier.label);
9823
+ return endpoint != null ? ` (endpoint: ${endpoint})` : "";
9603
9824
  }
9604
9825
  function asString(frame) {
9605
9826
  if (typeof frame === "string") return frame;
@@ -9652,6 +9873,7 @@ var AcceptorSecureSession = class {
9652
9873
  t: "reject",
9653
9874
  reason: "server handshake failed; check server logs"
9654
9875
  }));
9876
+ this.config.close?.();
9655
9877
  } catch {}
9656
9878
  });
9657
9879
  }
@@ -9686,12 +9908,15 @@ var AcceptorSecureSession = class {
9686
9908
  });
9687
9909
  if (message.t === "hello") {
9688
9910
  this._helloChannels = message.channels;
9689
- this.config.send(encodeHandshakeMessage(await this._handshake.onHello(message)));
9911
+ const reply = await this._handshake.onHello(message);
9912
+ this.config.send(encodeHandshakeMessage(reply));
9913
+ if (reply.t === "reject") this._refuse();
9690
9914
  } else if (message.t === "prove") {
9691
9915
  const reply = await this._handshake.onProve(message);
9692
9916
  this.config.send(encodeHandshakeMessage(reply));
9693
9917
  const result = this._handshake.getResult();
9694
9918
  if (reply.t === "accept" && result != null) this._complete(result);
9919
+ else if (reply.t === "reject") this._refuse();
9695
9920
  }
9696
9921
  return;
9697
9922
  }
@@ -9699,6 +9924,11 @@ var AcceptorSecureSession = class {
9699
9924
  if (bytes === void 0) return;
9700
9925
  this.config.routeAction(bytes, wireBytes);
9701
9926
  }
9927
+ /** A refused handshake ends this connection: later frames are ignored and the socket closes. */
9928
+ _refuse() {
9929
+ this._handshakeFailed = true;
9930
+ this.config.close?.();
9931
+ }
9702
9932
  _complete(result) {
9703
9933
  this._authed = true;
9704
9934
  this._handshake = void 0;
@@ -9779,6 +10009,7 @@ const KEEPALIVE_PONG = "pong";
9779
10009
  */
9780
10010
  var WireAcceptor = class {
9781
10011
  _send;
10012
+ _close;
9782
10013
  _tap;
9783
10014
  _security;
9784
10015
  _lane;
@@ -9802,6 +10033,7 @@ var WireAcceptor = class {
9802
10033
  _gateWarned = /* @__PURE__ */ new Set();
9803
10034
  constructor(options) {
9804
10035
  this._send = options.send;
10036
+ this._close = options.close;
9805
10037
  this._tap = options.tap;
9806
10038
  this._security = options.security;
9807
10039
  this._lane = options.lane;
@@ -9966,6 +10198,7 @@ var WireAcceptor = class {
9966
10198
  extraCaps: this._protocolCaps(),
9967
10199
  noneAllowed: this._noneAllowed,
9968
10200
  send: (frame, tapLane) => this._writeTapped(connection, frame, tapLane ?? "handshake"),
10201
+ close: this._close == null ? void 0 : () => this._close?.(connection),
9969
10202
  tap: this._tap,
9970
10203
  onAuthenticated: (auth) => this._onAuthenticated(connection, auth),
9971
10204
  routePlain: (frame, wireBytes) => this._receivePlain(connection, frame, wireBytes),
@@ -9978,7 +10211,7 @@ var WireAcceptor = class {
9978
10211
  /** Bind + persist a connection's authenticated identity once its handshake completes. */
9979
10212
  _onAuthenticated(connection, auth) {
9980
10213
  if (this._disposed) return;
9981
- this._bind(connection, auth.client);
10214
+ this._bind(connection, auth.client, auth.securityLevel);
9982
10215
  this._levelByConn.set(connection, auth.securityLevel);
9983
10216
  this._lane.onAuthenticated?.(connection, auth);
9984
10217
  const advertisedIds = protocolsFromCaps(auth.remoteCaps);
@@ -10002,12 +10235,14 @@ var WireAcceptor = class {
10002
10235
  /**
10003
10236
  * Plain-path identity binding: bind the connection to a self-asserted client coordinate (the
10004
10237
  * lane decoded it off an inbound frame) and persist a fresh binding when the identity is new.
10005
- * Secure mode never calls this — the handshake binds the authenticated coordinate instead.
10238
+ * Secure mode never calls this — the handshake binds the authenticated coordinate instead. While
10239
+ * another live connection holds that coordinate through a handshake, pushes and
10240
+ * `connectionForClient` keep resolving to it; the plain claim takes over only once it drops.
10006
10241
  */
10007
10242
  bindPlainConnection(connection, client) {
10008
10243
  if (this._disposed) return;
10009
10244
  const isNewBinding = this._clientByConn.get(connection)?.stringId !== client.stringId;
10010
- this._bind(connection, client);
10245
+ this._bind(connection, client, "none");
10011
10246
  if (isNewBinding) this._persist(connection, {
10012
10247
  v: 1,
10013
10248
  client: client.toJsonObject(),
@@ -10027,11 +10262,12 @@ var WireAcceptor = class {
10027
10262
  console.warn(`[wire-acceptor] ignored a persisted connection binding of unknown schema version ${JSON.stringify(binding.v)} (expected 1) — treating the connection as fresh (err_nice_wire_connect.binding_version_mismatch).`);
10028
10263
  return;
10029
10264
  }
10030
- this._bind(connection, new RuntimeCoordinate(binding.client));
10031
- this._bindingByConn.set(connection, binding);
10032
- this._lane.restoreBindingState?.(connection, binding.lane);
10033
10265
  const secure = binding.secure;
10034
10266
  const security = this._security;
10267
+ const level = secure != null && security != null ? secure.securityLevel : "none";
10268
+ this._bind(connection, new RuntimeCoordinate(binding.client), level);
10269
+ this._bindingByConn.set(connection, binding);
10270
+ this._lane.restoreBindingState?.(connection, binding.lane);
10035
10271
  if (secure != null && security != null) {
10036
10272
  this._levelByConn.set(connection, secure.securityLevel);
10037
10273
  this._sessionFor(connection, security).rehydrate(secure);
@@ -10043,11 +10279,13 @@ var WireAcceptor = class {
10043
10279
  this._bindingByConn.set(connection, binding);
10044
10280
  this._onConnectionBound?.(connection, binding);
10045
10281
  }
10046
- _bind(connection, client) {
10282
+ _bind(connection, client, level) {
10047
10283
  const previous = this._clientByConn.get(connection);
10048
10284
  if (previous != null && previous.stringId !== client.stringId && this._connByClient.get(previous.stringId) === connection) this._connByClient.delete(previous.stringId);
10049
- this._connByClient.set(client.stringId, connection);
10050
10285
  this._clientByConn.set(connection, client);
10286
+ const holder = this._connByClient.get(client.stringId);
10287
+ if (level === "none" && holder != null && holder !== connection && this.levelFor(holder) !== "none") return;
10288
+ this._connByClient.set(client.stringId, connection);
10051
10289
  }
10052
10290
  /** Forget a connection (call on socket close) so stale entries don't misroute later traffic. */
10053
10291
  drop(connection) {
@@ -13770,10 +14008,14 @@ var ChannelConnector = class extends PeerLink {
13770
14008
  defaultLocalCoordinate: () => ActionRuntime.getDefault().coordinate
13771
14009
  });
13772
14010
  for (const transport of transports) {
14011
+ const securityLevel = transport._inboundSecurityLevel();
13773
14012
  const connection = transport._createConnection({ resolvers: {
13774
14013
  onIncomingActionDataJson: (json, reliability) => {
13775
14014
  if (reliability?.ack != null) this._applyAck(reliableStreamId(this.peer, json.domain, json.id, reliability.streamKey), reliability.ack);
13776
- this._emitIncoming(json);
14015
+ this._emitIncoming(json, {
14016
+ receiver: this,
14017
+ securityLevel
14018
+ });
13777
14019
  },
13778
14020
  onControlMessage: (message) => {
13779
14021
  const streamId = reliableStreamId(this.peer, message.domain, message.id, message.k);
@@ -14396,35 +14638,60 @@ var ActionRuntime = class {
14396
14638
  _addHandlers(handlers, options) {
14397
14639
  this._assertActive();
14398
14640
  this._assertNoDuplicateLocalExecutors(handlers);
14399
- for (const handler of handlers) {
14400
- let ownership = this._handlerOwnership.get(handler);
14401
- if (ownership == null) {
14402
- const handlerRouter = handler.getActionRouter();
14403
- ownership = {
14404
- persistent: false,
14405
- leases: /* @__PURE__ */ new Set()
14406
- };
14407
- try {
14408
- this.actionRouter.addDomainsFromOther(handlerRouter);
14409
- if (handler.handlerType === "peer") {
14410
- ownership.unbind = handler._setIncomingActionDataListener(this, (json, metadata) => this.resolveIncomingActionPayload(json, metadata));
14411
- this._registeredPeerHandlers.push(handler);
14412
- }
14413
- for (const key of handlerRouter.getRegisteredKeys()) this.actionRouter.addForKey(key, handler);
14414
- } catch (error) {
14415
- ownership.unbind?.();
14416
- this.actionRouter.removeRouteData(handler);
14417
- const peerIndex = this._registeredPeerHandlers.indexOf(handler);
14418
- if (peerIndex >= 0) this._registeredPeerHandlers.splice(peerIndex, 1);
14419
- throw error;
14641
+ const installed = [];
14642
+ const promoted = [];
14643
+ try {
14644
+ for (const handler of handlers) {
14645
+ let ownership = this._handlerOwnership.get(handler);
14646
+ if (ownership == null) {
14647
+ ownership = this._installHandler(handler);
14648
+ installed.push(handler);
14420
14649
  }
14421
- this._handlerOwnership.set(handler, ownership);
14650
+ if (options.persistent && !ownership.persistent) {
14651
+ ownership.persistent = true;
14652
+ promoted.push(ownership);
14653
+ }
14654
+ if (options.lease != null) ownership.leases.add(options.lease);
14422
14655
  }
14423
- if (options.persistent) ownership.persistent = true;
14424
- if (options.lease != null) ownership.leases.add(options.lease);
14656
+ } catch (error) {
14657
+ for (const ownership of promoted) ownership.persistent = false;
14658
+ for (const handler of installed) {
14659
+ const ownership = this._handlerOwnership.get(handler);
14660
+ if (ownership != null) this._uninstallHandler(handler, ownership);
14661
+ }
14662
+ throw error;
14425
14663
  }
14426
14664
  if (options.register) this._registerWithRoutedRoots();
14427
14665
  }
14666
+ _installHandler(handler) {
14667
+ const handlerRouter = handler.getActionRouter();
14668
+ const ownership = {
14669
+ persistent: false,
14670
+ leases: /* @__PURE__ */ new Set()
14671
+ };
14672
+ try {
14673
+ this.actionRouter.addDomainsFromOther(handlerRouter);
14674
+ if (handler.handlerType === "peer") {
14675
+ ownership.unbind = handler._setIncomingActionDataListener(this, (json, metadata) => this.resolveIncomingActionPayload(json, metadata));
14676
+ this._registeredPeerHandlers.push(handler);
14677
+ }
14678
+ for (const key of handlerRouter.getRegisteredKeys()) this.actionRouter.addForKey(key, handler);
14679
+ } catch (error) {
14680
+ this._uninstallHandler(handler, ownership);
14681
+ throw error;
14682
+ }
14683
+ this._handlerOwnership.set(handler, ownership);
14684
+ return ownership;
14685
+ }
14686
+ _uninstallHandler(handler, ownership) {
14687
+ ownership.unbind?.();
14688
+ this.actionRouter.removeRouteData(handler);
14689
+ if (handler.handlerType === "peer") {
14690
+ const peerIndex = this._registeredPeerHandlers.indexOf(handler);
14691
+ if (peerIndex >= 0) this._registeredPeerHandlers.splice(peerIndex, 1);
14692
+ }
14693
+ this._handlerOwnership.delete(handler);
14694
+ }
14428
14695
  _assertNoDuplicateLocalExecutors(handlers) {
14429
14696
  for (const handler of handlers) for (const domain of handler.getActionRouter().getDomains()) this.actionRouter.domainManager.assertCanAddDomain(domain);
14430
14697
  const staged = /* @__PURE__ */ new Map();
@@ -14441,11 +14708,7 @@ var ActionRuntime = class {
14441
14708
  for (const [handler, ownership] of this._handlerOwnership) {
14442
14709
  ownership.leases.delete(lease);
14443
14710
  if (ownership.persistent || ownership.leases.size > 0) continue;
14444
- ownership.unbind?.();
14445
- this.actionRouter.removeRouteData(handler);
14446
- const peerIndex = this._registeredPeerHandlers.indexOf(handler);
14447
- if (peerIndex >= 0) this._registeredPeerHandlers.splice(peerIndex, 1);
14448
- this._handlerOwnership.delete(handler);
14711
+ this._uninstallHandler(handler, ownership);
14449
14712
  }
14450
14713
  }
14451
14714
  /**
@@ -14568,29 +14831,21 @@ var ActionRuntime = class {
14568
14831
  const originClient = runningAction.context.originClient;
14569
14832
  if (originClient.envId === "_unset_" || originClient.isSameFor(this._coordinate).id) return;
14570
14833
  const arrival = runningAction.context._getReceiverMetadata();
14834
+ if (arrival != null && !(arrival.receiver instanceof PeerLink)) return;
14835
+ const arrivalLink = arrival?.receiver instanceof PeerLink ? arrival.receiver : void 0;
14571
14836
  runningAction.addUpdateListeners([(update) => {
14572
14837
  if (update.type === "finished" && update.finishType === "success") {
14573
14838
  if (this._disposed) return;
14574
- const returnHandler = arrival?.receiver instanceof PeerLink ? this._registeredPeerHandlers.includes(arrival.receiver) && arrival.receiver.canPush ? arrival.receiver : void 0 : this.getReturnHandlerForOrigin(originClient);
14575
- if (returnHandler == null || !canReturnToOrigin(arrival, returnHandler)) return;
14576
- returnHandler.sendReturnPayload(update.response, { targetLocalRuntime: this }).catch(() => {});
14839
+ const returnHandler = arrivalLink != null ? this._registeredPeerHandlers.includes(arrivalLink) && arrivalLink.canPush ? arrivalLink : void 0 : this.getReturnHandlerForOrigin(originClient);
14840
+ if (returnHandler == null) return;
14841
+ returnHandler.sendReturnPayload(update.response, {
14842
+ targetLocalRuntime: this,
14843
+ arrival
14844
+ }).catch(() => {});
14577
14845
  }
14578
14846
  }]);
14579
14847
  }
14580
14848
  };
14581
- /**
14582
- * May a result be routed back to the action's *claimed* origin over `returnHandler`?
14583
- *
14584
- * - No arrival facts (a locally dispatched action, or an advanced caller supplying its own wire):
14585
- * unchanged behaviour.
14586
- * - The frame arrived on this very handler: always — that is answering on the link it came from.
14587
- * - Otherwise the origin coordinate is only trustworthy when the arrival was authenticated; an
14588
- * unauthenticated claim must never select a different connection.
14589
- */
14590
- function canReturnToOrigin(arrival, returnHandler) {
14591
- if (arrival == null || arrival.receiver === returnHandler) return true;
14592
- return arrival.securityLevel != null && arrival.securityLevel !== "none";
14593
- }
14594
14849
  const runtimeState = {
14595
14850
  defaultLocalRuntime: void 0,
14596
14851
  assumedRuntimeInfo: void 0
@@ -14682,12 +14937,12 @@ var ActionLocalHandler = class extends ActionHandler {
14682
14937
  pushHandlerCuid(runningAction.cuid);
14683
14938
  try {
14684
14939
  const ran = await niceTryAsync(async () => {
14685
- const securityLevel = state.request.context._getReceiverMetadata()?.securityLevel;
14940
+ const metadata = state.request.context._getReceiverMetadata();
14686
14941
  const context = {
14687
14942
  runtime,
14688
14943
  origin: state.request.context.originClient,
14689
- authenticatedOrigin: securityLevel != null && securityLevel !== "none" ? state.request.context.originClient : void 0,
14690
- securityLevel,
14944
+ authenticatedOrigin: metadata?.originAuthenticated === true ? state.request.context.originClient : void 0,
14945
+ securityLevel: metadata?.securityLevel,
14691
14946
  reliability: state.request.context.reliability,
14692
14947
  run: (request, options) => runtime.run(request, options)
14693
14948
  };
@@ -15246,6 +15501,7 @@ var ChannelAcceptor = class extends PeerLink {
15246
15501
  const security = options.security;
15247
15502
  this.wireAcceptor = new WireAcceptor({
15248
15503
  send: options.send,
15504
+ close: options.close,
15249
15505
  tap: options.wireTap,
15250
15506
  security: security == null ? void 0 : {
15251
15507
  securityLevel: security.securityLevel,
@@ -15536,11 +15792,13 @@ var ChannelAcceptor = class extends PeerLink {
15536
15792
  _emitIncomingFromReceiver(wire, reliability, arrivalOverride) {
15537
15793
  const arrival = arrivalOverride ?? this._receiverMetadataByWire.get(wire);
15538
15794
  this._receiverMetadataByWire.delete(wire);
15795
+ const securityLevel = arrival?.securityLevel;
15539
15796
  this._emitIncoming(wire, {
15540
15797
  receiver: this,
15541
15798
  connection: arrival?.connection,
15542
15799
  bindingGeneration: arrival?.bindingGeneration,
15543
- securityLevel: arrival?.securityLevel,
15800
+ securityLevel,
15801
+ originAuthenticated: securityLevel != null && securityLevel !== "none",
15544
15802
  reliability
15545
15803
  });
15546
15804
  }
@@ -15809,10 +16067,10 @@ var ChannelAcceptor = class extends PeerLink {
15809
16067
  }
15810
16068
  }
15811
16069
  async sendReturnPayload(payload, config) {
15812
- const arrival = payload.context._getReceiverMetadata();
15813
- const connection = arrival?.receiver === this ? this._liveArrivalConnection(arrival) : this.wireAcceptor.connectionForClient(payload.context.originClient.stringId);
16070
+ const arrival = config.arrival ?? payload.context._getReceiverMetadata();
16071
+ const connection = arrival == null ? this.wireAcceptor.connectionForClient(payload.context.originClient.stringId) : arrival.receiver === this ? this._liveArrivalConnection(arrival) : void 0;
15814
16072
  if (connection == null) return false;
15815
- const bytes = this._sendPayload(connection, payload, config.targetLocalRuntime.coordinate);
16073
+ const bytes = this._sendPayload(connection, payload, config.targetLocalRuntime.coordinate, arrival?.reliability);
15816
16074
  this._reportServed(payload, bytes);
15817
16075
  return true;
15818
16076
  }
@@ -15869,11 +16127,11 @@ var ChannelAcceptor = class extends PeerLink {
15869
16127
  }).withOriginError(cause);
15870
16128
  }
15871
16129
  /** Encode + send one payload; returns the encoded frame's size so a logger can report it. */
15872
- _sendPayload(connection, payload, localClient, reliability) {
16130
+ _sendPayload(connection, payload, localClient, answered) {
15873
16131
  const encoding = this._connEncoding.get(connection) ?? "binary";
15874
- let rel = reliability;
15875
- if (rel == null && payload.type === "result") {
15876
- const streamKey = payload.context.reliability?.streamKey;
16132
+ let rel;
16133
+ if (payload.type === "result") {
16134
+ const streamKey = (answered ?? payload.context.reliability)?.streamKey;
15877
16135
  const streamId = reliableStreamId(payload.context.originClient, payload.domain, payload.id, streamKey);
15878
16136
  const receiver = this._persistedReceiver?.hasStream(streamId) ? this._persistedReceiver : this._inbox.hasStream(streamId) ? this._inbox : void 0;
15879
16137
  if (receiver != null) {
@@ -15948,6 +16206,7 @@ function createSecureChannelAcceptor(options) {
15948
16206
  };
15949
16207
  const baseOptions = {
15950
16208
  send: options.send,
16209
+ close: options.close,
15951
16210
  runtime: options.runtime,
15952
16211
  defaultTimeout: options.defaultTimeout,
15953
16212
  logger: options.logger,
@@ -15975,11 +16234,14 @@ function createSecureChannelAcceptor(options) {
15975
16234
  }
15976
16235
  //#endregion
15977
16236
  //#region ../nice-action/src/ActionRuntime/Transport/Carrier/Carrier.types.ts
15978
- /** Convert action routing data into wire's generic carrier dial shape. */
16237
+ /**
16238
+ * Convert action routing data into wire's generic carrier dial shape. The routing fields also stay at
16239
+ * the top level, so a carrier source written for the older `open(input: TTransportRouteParams)` shape
16240
+ * still reads `input.action`.
16241
+ */
15979
16242
  function toActionDialParams(input) {
15980
16243
  return {
15981
- localClient: input.localClient,
15982
- externalClient: input.externalClient,
16244
+ ...input,
15983
16245
  dialContext: input
15984
16246
  };
15985
16247
  }
@@ -16291,7 +16553,12 @@ function isSessionEnvelope(envelope) {
16291
16553
  * definition can be shared across multiple handlers — each handler builds its own live
16292
16554
  * {@link TransportConnection} via {@link TransportConnection._createConnection}.
16293
16555
  */
16294
- var Transport = class {};
16556
+ var Transport = class {
16557
+ /** @internal The security level frames received over this transport were protected at. */
16558
+ _inboundSecurityLevel() {
16559
+ return "none";
16560
+ }
16561
+ };
16295
16562
  //#endregion
16296
16563
  //#region ../nice-action/src/ActionRuntime/Transport/SecureSession/establishExchangeSession.ts
16297
16564
  /** Plain path (no handshake/token): every action rides a bare `act` envelope, plaintext both ways. */
@@ -16412,11 +16679,15 @@ var ExchangeConnection = class extends TransportConnection {
16412
16679
  * can't deliver an unsolicited frame (the runtime never picks it for the return path).
16413
16680
  */
16414
16681
  var ExchangeTransport = class ExchangeTransport extends Transport {
16415
- options;
16416
16682
  type = "exchange";
16683
+ options;
16417
16684
  constructor(options) {
16418
16685
  super();
16419
- this.options = options;
16686
+ if (options.getCacheKey != null && options.getTransportCacheKey != null) throw err_nice_action.fromId("conflicting_connect_options", { detail: "ExchangeTransport: pass only `getCacheKey`; `getTransportCacheKey` is deprecated" });
16687
+ this.options = {
16688
+ ...options,
16689
+ getCacheKey: options.getCacheKey ?? options.getTransportCacheKey
16690
+ };
16420
16691
  }
16421
16692
  static create(options) {
16422
16693
  return new ExchangeTransport(options);
@@ -16650,11 +16921,17 @@ var LinkConnection = class extends TransportConnection {
16650
16921
  * or an in-memory pipe. Reported with an overridable carrier label in the devtools (defaults to "link").
16651
16922
  */
16652
16923
  var LinkTransport = class LinkTransport extends Transport {
16653
- options;
16654
16924
  type = "duplex";
16925
+ options;
16655
16926
  constructor(options) {
16656
16927
  super();
16657
- this.options = options;
16928
+ if (options.getCacheKey != null && options.getTransportCacheKey != null) throw err_nice_action.fromId("conflicting_connect_options", { detail: "LinkTransport: pass only `getCacheKey`; `getTransportCacheKey` is deprecated" });
16929
+ if (options.heartbeat != null && options.linkKeepalive != null) throw err_nice_action.fromId("conflicting_connect_options", { detail: "LinkTransport: pass only `heartbeat`; `linkKeepalive` is deprecated" });
16930
+ this.options = {
16931
+ ...options,
16932
+ getCacheKey: options.getCacheKey ?? options.getTransportCacheKey,
16933
+ heartbeat: options.heartbeat ?? options.linkKeepalive
16934
+ };
16658
16935
  }
16659
16936
  static create(options) {
16660
16937
  return new LinkTransport(options);
@@ -16677,6 +16954,9 @@ var LinkTransport = class LinkTransport extends Transport {
16677
16954
  })
16678
16955
  }) }, ctx.resolvers);
16679
16956
  }
16957
+ _inboundSecurityLevel() {
16958
+ return this.options.security?.securityLevel ?? "none";
16959
+ }
16680
16960
  getRouteInfo(input) {
16681
16961
  if (this.options.getRouteInfo != null) return this.options.getRouteInfo(input);
16682
16962
  return {
@@ -16829,6 +17109,8 @@ function warnOnSharedConnectionIdentity(runtime, peer, identity) {
16829
17109
  */
16830
17110
  function connectChannel(runtime, channel, options) {
16831
17111
  if (options.carriers == null === (options.transports == null)) throw err_nice_action.fromId("conflicting_connect_options", { detail: "connectChannel requires exactly one of `carriers` or deprecated `transports`" });
17112
+ if (options.reconnect != null && options.keepLinkAlive != null) throw err_nice_action.fromId("conflicting_connect_options", { detail: "connectChannel: pass only `reconnect`; `keepLinkAlive` is deprecated" });
17113
+ if (options.heartbeat != null && options.linkKeepalive != null) throw err_nice_action.fromId("conflicting_connect_options", { detail: "connectChannel: pass only `heartbeat`; `linkKeepalive` is deprecated" });
16832
17114
  const transports = options.carriers?.map((carrier) => ({
16833
17115
  carrier,
16834
17116
  secure: carrier.secure,
@@ -16995,7 +17277,8 @@ var ExchangeAcceptor = class {
16995
17277
  const startedAt = Date.now();
16996
17278
  const result = await (await this._runtime._handleActionPayloadWireFromReceiver(wire, {
16997
17279
  receiver: this,
16998
- securityLevel: request.securityLevel
17280
+ securityLevel: request.securityLevel,
17281
+ originAuthenticated: client != null && request.securityLevel !== "none"
16999
17282
  })).waitForResultPayload();
17000
17283
  const resultWire = result.toJsonObject();
17001
17284
  if (report != null) {
@@ -17381,6 +17664,7 @@ function serveChannel(runtimeOrChannel, channelOrOptions, legacyOptions) {
17381
17664
  verifyKeyResolver: secure.verifyKeyResolver,
17382
17665
  securityLevel,
17383
17666
  send: carrier.send,
17667
+ close: carrier.close,
17384
17668
  defaultTimeout: options.defaultTimeout,
17385
17669
  resolveChannel,
17386
17670
  logger: options.logger,
@@ -17391,6 +17675,7 @@ function serveChannel(runtimeOrChannel, channelOrOptions, legacyOptions) {
17391
17675
  }) : createChannelAcceptor({
17392
17676
  createFormatMessage: channel.createCodec,
17393
17677
  send: carrier.send,
17678
+ close: carrier.close,
17394
17679
  runtime,
17395
17680
  defaultTimeout: options.defaultTimeout,
17396
17681
  logger: options.logger,
@@ -20500,6 +20785,21 @@ function createWriteHandle() {
20500
20785
  //#endregion
20501
20786
  //#region ../nice-realm/src/RealmClient/RealmClient.ts
20502
20787
  enablePatches();
20788
+ function createStepGuard() {
20789
+ let failure;
20790
+ return {
20791
+ run(step) {
20792
+ try {
20793
+ step();
20794
+ } catch (error) {
20795
+ failure ??= { error };
20796
+ }
20797
+ },
20798
+ rethrow() {
20799
+ if (failure != null) throw failure.error;
20800
+ }
20801
+ };
20802
+ }
20503
20803
  /** The durable-write backlog cap (§4): past this many unconfirmed reassert frames, new reassert
20504
20804
  * writes reject loudly instead of growing memory for the length of the outage. */
20505
20805
  const MAX_REASSERT_PENDING_FRAMES = 256;
@@ -20584,12 +20884,16 @@ function connectRealm(realm, options) {
20584
20884
  if (status === next) return;
20585
20885
  status = next;
20586
20886
  if (next === "live") hasBeenLive = true;
20587
- for (const listener of [...statusListeners]) listener(next, { hasBeenLive });
20588
- devtools?.onStatus?.(next, { hasBeenLive });
20589
- if (next === "detached") rejectHydrateQueue();
20887
+ const guard = createStepGuard();
20888
+ if (next === "detached") guard.run(rejectHydrateQueue);
20889
+ for (const listener of [...statusListeners]) guard.run(() => listener(next, { hasBeenLive }));
20890
+ guard.run(() => devtools?.onStatus?.(next, { hasBeenLive }));
20891
+ guard.rethrow();
20590
20892
  };
20591
20893
  let pending = [];
20592
20894
  const hydrateQueue = [];
20895
+ /** Set from the hydrate's `confirmedVersion` until its queue drains: new writes queue behind. */
20896
+ let hydrating = false;
20593
20897
  let nextSeq = 0;
20594
20898
  let flushScheduled = false;
20595
20899
  let projecting = false;
@@ -21075,7 +21379,7 @@ function connectRealm(realm, options) {
21075
21379
  if (queued.expiryTimer != null) clearTimeout(queued.expiryTimer);
21076
21380
  rejectUnsent(queued.controller, queued.kind, error, queued.intentName);
21077
21381
  };
21078
- const mustQueueUntilHydrate = () => confirmedVersion === -1 || hydrateQueue.length > 0;
21382
+ const mustQueueUntilHydrate = () => confirmedVersion === -1 || hydrating;
21079
21383
  const queueUntilHydrate = (queuedWrite, durability) => {
21080
21384
  const controller = createWriteHandle();
21081
21385
  if (status === "detached") return rejectUnsent(controller, queuedWrite.kind, neverHydratedError(), queuedWrite.intentName);
@@ -21089,8 +21393,10 @@ function connectRealm(realm, options) {
21089
21393
  const index = hydrateQueue.indexOf(queued);
21090
21394
  if (index < 0) return;
21091
21395
  hydrateQueue.splice(index, 1);
21092
- rejectQueued(queued, neverHydratedError());
21093
- notifyPending();
21396
+ const guard = createStepGuard();
21397
+ guard.run(() => rejectQueued(queued, neverHydratedError()));
21398
+ guard.run(notifyPending);
21399
+ guard.rethrow();
21094
21400
  }, expiryMs);
21095
21401
  unrefTimer(queued.expiryTimer);
21096
21402
  }
@@ -21098,26 +21404,36 @@ function connectRealm(realm, options) {
21098
21404
  notifyPending();
21099
21405
  return controller.handle;
21100
21406
  };
21101
- const drainHydrateQueue = () => {
21407
+ const runQueued = (queued) => {
21408
+ if (queued.expiryTimer != null) clearTimeout(queued.expiryTimer);
21409
+ const { controller } = queued;
21410
+ let sent;
21411
+ try {
21412
+ sent = queued.run();
21413
+ } catch (cause) {
21414
+ console.error(`${warnTag()} a write queued before the first hydrate threw`, cause);
21415
+ rejectQueued(queued, castNiceError(cause));
21416
+ return;
21417
+ }
21418
+ const settled = sent;
21419
+ settled.then(controller.confirm, () => {
21420
+ if (settled.error != null) controller.reject(settled.error);
21421
+ });
21422
+ };
21423
+ /** Runs every queued write; a throwing app callback is held by `guard` and strands nothing. */
21424
+ const drainHydrateQueue = (guard) => {
21102
21425
  for (let queued = hydrateQueue.shift(); queued != null; queued = hydrateQueue.shift()) {
21103
- if (queued.expiryTimer != null) clearTimeout(queued.expiryTimer);
21104
- const { controller } = queued;
21105
- let sent;
21106
- try {
21107
- sent = queued.run();
21108
- } catch (cause) {
21109
- console.error(`${warnTag()} a write queued before the first hydrate threw`, cause);
21110
- rejectQueued(queued, castNiceError(cause));
21111
- continue;
21112
- }
21113
- const settled = sent;
21114
- settled.then(controller.confirm, () => {
21115
- if (settled.error != null) controller.reject(settled.error);
21116
- });
21426
+ const next = queued;
21427
+ guard.run(() => runQueued(next));
21117
21428
  }
21429
+ guard.run(notifyPending);
21118
21430
  };
21119
21431
  const rejectHydrateQueue = () => {
21120
- for (const queued of hydrateQueue.splice(0)) rejectQueued(queued, neverHydratedError());
21432
+ if (hydrateQueue.length === 0) return;
21433
+ const guard = createStepGuard();
21434
+ for (const queued of hydrateQueue.splice(0)) guard.run(() => rejectQueued(queued, neverHydratedError()));
21435
+ guard.run(notifyPending);
21436
+ guard.rethrow();
21121
21437
  };
21122
21438
  const enqueueWrite = (patches, writeOptions) => {
21123
21439
  const durability = writeOptions?.durability;
@@ -21378,15 +21694,23 @@ function connectRealm(realm, options) {
21378
21694
  };
21379
21695
  localMaxPatchesCeiling = void 0;
21380
21696
  warnOnIdentityMismatch(frame.avatar);
21381
- setStatus("live");
21382
- if (helloInFlight) recordRttSample(Date.now() - helloSentAt);
21383
- helloInFlight = false;
21384
- if (!isFirstHydrate && realm.transient.length > 0 && options.assertOnAttach != null && !hasPendingSystemAssert()) enqueueSystemAssert(confirmed);
21385
- revalidateAndResendPending();
21386
- project({ fullReplace: true });
21387
- if (options.assertOnAttach != null && !hasPendingSystemAssert()) applyUpdate(options.assertOnAttach);
21388
- drainHydrateQueue();
21697
+ hydrating = true;
21698
+ const guard = createStepGuard();
21699
+ try {
21700
+ guard.run(() => setStatus("live"));
21701
+ if (helloInFlight) recordRttSample(Date.now() - helloSentAt);
21702
+ helloInFlight = false;
21703
+ if (!isFirstHydrate && realm.transient.length > 0 && options.assertOnAttach != null && !hasPendingSystemAssert()) guard.run(() => enqueueSystemAssert(confirmed));
21704
+ guard.run(revalidateAndResendPending);
21705
+ guard.run(() => project({ fullReplace: true }));
21706
+ const assertOnAttach = options.assertOnAttach;
21707
+ if (assertOnAttach != null && !hasPendingSystemAssert()) guard.run(() => applyUpdate(assertOnAttach));
21708
+ } finally {
21709
+ drainHydrateQueue(guard);
21710
+ hydrating = false;
21711
+ }
21389
21712
  checkReownWatch();
21713
+ guard.rethrow();
21390
21714
  return;
21391
21715
  }
21392
21716
  case REALM_FRAME_KIND.keyDict:
@@ -21784,10 +22108,12 @@ function connectRealm(realm, options) {
21784
22108
  port.send(bye);
21785
22109
  } catch {}
21786
22110
  helloInFlight = false;
21787
- setStatus("detached");
22111
+ const guard = createStepGuard();
22112
+ guard.run(() => setStatus("detached"));
21788
22113
  options.connection.release();
21789
- for (const frame of pending.splice(0)) settleReject(frame, err_realm.fromId("frame_too_stale", { basisVersion: frame.basisVersion }));
21790
- project();
22114
+ for (const frame of pending.splice(0)) guard.run(() => settleReject(frame, err_realm.fromId("frame_too_stale", { basisVersion: frame.basisVersion })));
22115
+ guard.run(() => project());
22116
+ guard.rethrow();
21791
22117
  }
21792
22118
  };
21793
22119
  devtools?.handleReady?.({
@@ -22739,7 +23065,8 @@ function unwrapOptional(node) {
22739
23065
  }
22740
23066
  const OMIT = {
22741
23067
  value: void 0,
22742
- anyVisible: false
23068
+ anyVisible: false,
23069
+ structural: false
22743
23070
  };
22744
23071
  /** Does `path` pass through a record entry? Its containers are then data, not structure. */
22745
23072
  function underRecordEntry(schemaRoot, path) {
@@ -22752,19 +23079,21 @@ function underRecordEntry(schemaRoot, path) {
22752
23079
  function pruneNode(ctx, node, value, path, inEntry = underRecordEntry(ctx.schemaRoot, path)) {
22753
23080
  if (value === void 0) return OMIT;
22754
23081
  const inner = unwrapOptional(node);
23082
+ const required = node.kind !== "optional";
22755
23083
  if (inner.kind === "object") {
22756
23084
  const out = {};
22757
23085
  let anyVisible = false;
23086
+ let structural = false;
22758
23087
  for (const [key, child] of Object.entries(inner.entries)) {
22759
23088
  const pruned = pruneNode(ctx, child, value[key], [...path, key], inEntry);
22760
- if (pruned.anyVisible) {
22761
- out[key] = pruned.value;
22762
- anyVisible = true;
22763
- }
23089
+ if (pruned.anyVisible || pruned.structural) out[key] = pruned.value;
23090
+ if (pruned.anyVisible) anyVisible = true;
23091
+ if (pruned.structural) structural = true;
22764
23092
  }
22765
23093
  return {
22766
23094
  value: out,
22767
- anyVisible
23095
+ anyVisible,
23096
+ structural: required && structural
22768
23097
  };
22769
23098
  }
22770
23099
  if (inner.kind === "record") {
@@ -22777,17 +23106,37 @@ function pruneNode(ctx, node, value, path, inEntry = underRecordEntry(ctx.schema
22777
23106
  anyVisible = true;
22778
23107
  }
22779
23108
  }
22780
- const structural = !inEntry && ctx.trie.reachesBeneath(path);
23109
+ const structural = required && !inEntry && ctx.trie.reachesBeneath(path);
22781
23110
  return {
22782
23111
  value: out,
22783
- anyVisible: anyVisible || structural || leafVisible(ctx, path)
23112
+ anyVisible: anyVisible || leafVisible(ctx, path),
23113
+ structural
22784
23114
  };
22785
23115
  }
22786
23116
  return leafVisible(ctx, path) ? {
22787
23117
  value,
22788
- anyVisible: true
23118
+ anyVisible: true,
23119
+ structural: false
22789
23120
  } : OMIT;
22790
23121
  }
23122
+ /**
23123
+ * Whether the avatar holds `path`'s parent, so a structure-only patch there reveals nothing: true
23124
+ * unless an optional sits between the top level and `path` that neither state shows the avatar.
23125
+ */
23126
+ function holdsParent(ctx, path, states) {
23127
+ for (let depth = path.length - 1; depth >= 2; depth--) {
23128
+ const ancestorPath = path.slice(0, depth);
23129
+ const ancestor = schemaNodeAtPath(ctx.schemaRoot, ancestorPath);
23130
+ if (ancestor?.kind !== "optional") continue;
23131
+ return states.some((state) => state != null && pruneNode(ctx, ancestor, getAtPath$1(state, ancestorPath), ancestorPath).anyVisible);
23132
+ }
23133
+ return true;
23134
+ }
23135
+ /** A sliced patch target ships for its visible content, or as structure inside a held parent. */
23136
+ function patchTargetShips(ctx, pruned, path, states) {
23137
+ if (pruned.anyVisible) return true;
23138
+ return pruned.structural && holdsParent(ctx, path, states);
23139
+ }
22791
23140
  /** The avatar's sliced view of the whole state — the hydrate payload. */
22792
23141
  function sliceStateForAvatar(ctx, state) {
22793
23142
  const out = {};
@@ -22799,9 +23148,10 @@ function sliceStateForAvatar(ctx, state) {
22799
23148
  * possibly with a pruned value (a subtree patch spanning mixed-visibility leaves sends each
22800
23149
  * audience only its slice). `statePrev` (pre-commit) drives `remove` expansion; a replay path may
22801
23150
  * pass `undefined` — a `remove` that can't be proven invisible is then included (removing a key
22802
- * the avatar never had must be a client-side no-op).
23151
+ * the avatar never had must be a client-side no-op). `stateAfter` (post-commit), with `statePrev`,
23152
+ * decides whether the avatar holds an optional ancestor of a structure-only container patch.
22803
23153
  */
22804
- function slicePatchForAvatar(ctx, patch, statePrev) {
23154
+ function slicePatchForAvatar(ctx, patch, statePrev, stateAfter) {
22805
23155
  const path = patch.path;
22806
23156
  const node = schemaNodeAtPath(ctx.schemaRoot, path);
22807
23157
  if (node == null) return void 0;
@@ -22810,10 +23160,10 @@ function slicePatchForAvatar(ctx, patch, statePrev) {
22810
23160
  if (patch.op === "remove") {
22811
23161
  const prev = statePrev == null ? void 0 : getAtPath$1(statePrev, path);
22812
23162
  if (prev === void 0) return patch;
22813
- return pruneNode(ctx, node, prev, [...path]).anyVisible ? patch : void 0;
23163
+ return patchTargetShips(ctx, pruneNode(ctx, node, prev, [...path]), path, [statePrev, stateAfter]) ? patch : void 0;
22814
23164
  }
22815
23165
  const pruned = pruneNode(ctx, node, patch.value, [...path]);
22816
- if (!pruned.anyVisible) return void 0;
23166
+ if (!patchTargetShips(ctx, pruned, path, [statePrev, stateAfter])) return void 0;
22817
23167
  return {
22818
23168
  op: patch.op,
22819
23169
  path,
@@ -23081,7 +23431,7 @@ var RealmServerEngine = class {
23081
23431
  sliced.push(sliceTransientRefreshForAvatar(this._sliceCtx(avatar), patch));
23082
23432
  continue;
23083
23433
  }
23084
- const slicedPatch = slicePatchForAvatar(this._sliceCtx(avatar), patch, void 0);
23434
+ const slicedPatch = slicePatchForAvatar(this._sliceCtx(avatar), patch, void 0, this._state);
23085
23435
  if (slicedPatch != null) sliced.push(slicedPatch);
23086
23436
  }
23087
23437
  this._sendPatchesFrame(conn, sliced, options.lastKnownVersion, this._version);
@@ -23685,6 +24035,7 @@ var RealmServerEngine = class {
23685
24035
  }
23686
24036
  _broadcast(namePatches, statePrev, fromVersion, toVersion) {
23687
24037
  if (this._connections.size === 0) return;
24038
+ const stateAfter = this._state;
23688
24039
  const cache = /* @__PURE__ */ new Map();
23689
24040
  for (const conn of this._connections.values()) {
23690
24041
  const groupKey = `${viewSignatureKey(conn.avatar)}/${conn.slot}`;
@@ -23692,7 +24043,7 @@ var RealmServerEngine = class {
23692
24043
  if (chunks === void 0) {
23693
24044
  const sliced = [];
23694
24045
  for (const patch of namePatches) {
23695
- const slicedPatch = slicePatchForAvatar(this._sliceCtx(conn.avatar), patch, statePrev);
24046
+ const slicedPatch = slicePatchForAvatar(this._sliceCtx(conn.avatar), patch, statePrev, stateAfter);
23696
24047
  if (slicedPatch != null) sliced.push(slicedPatch);
23697
24048
  }
23698
24049
  chunks = sliced.length === 0 ? null : this._encodePatchesChunked(sliced, conn.slot, fromVersion, toVersion);
@@ -24186,7 +24537,8 @@ function commanderStatePaths(dataDir, configKey) {
24186
24537
  ingestSeqPath: join(stateDir, "ingest-seq"),
24187
24538
  envOverridesPath: join(stateDir, "env-overrides.json"),
24188
24539
  savedFiltersPath: join(stateDir, "saved-filters.json"),
24189
- lastStartsPath: join(stateDir, "last-starts.json")
24540
+ lastStartsPath: join(stateDir, "last-starts.json"),
24541
+ taskDurationsPath: join(stateDir, "task-durations.json")
24190
24542
  };
24191
24543
  }
24192
24544
  async function ensureStateDir(paths) {
@@ -24251,6 +24603,8 @@ const commanderStatusRealm = defineRealm({
24251
24603
  pid: t.optional(t.number()),
24252
24604
  startedAt: t.optional(t.number()),
24253
24605
  lastStartedAt: t.optional(t.number()),
24606
+ flags: t.array(t.string()),
24607
+ estimatedMs: t.optional(t.number()),
24254
24608
  sawOutputAt: t.optional(t.number()),
24255
24609
  lastTask: t.optional(t.object({
24256
24610
  outcome: t.string(),
@@ -24307,6 +24661,11 @@ const commanderStatusRealm = defineRealm({
24307
24661
  values: t.optional(t.array(t.string())),
24308
24662
  source: t.string(),
24309
24663
  value: t.optional(t.string())
24664
+ })),
24665
+ flags: t.array(t.object({
24666
+ name: t.string(),
24667
+ args: t.string(),
24668
+ description: t.optional(t.string())
24310
24669
  }))
24311
24670
  })
24312
24671
  })),
@@ -24466,7 +24825,7 @@ var CommanderDaemonBootError = class extends Error {
24466
24825
  * a live dev environment, and an upgrade must never be the thing that kills one.
24467
24826
  */
24468
24827
  async function replaceSkewedDaemon(paths, skewed) {
24469
- const daemonLabel = `the daemon for this config (pid ${skewed.pid}, build ${skewed.packageVersion}, protocol v${skewed.protocolVersion}) predates this CLI (protocol v7${skewed.skew === "realm-schema" ? ", different status schema" : ""})`;
24828
+ const daemonLabel = `the daemon for this config (pid ${skewed.pid}, build ${skewed.packageVersion}, protocol v${skewed.protocolVersion}) predates this CLI (protocol v8${skewed.skew === "realm-schema" ? ", different status schema" : ""})`;
24470
24829
  let liveIds;
24471
24830
  try {
24472
24831
  liveIds = (await openProcessLedger({
@@ -24696,8 +25055,50 @@ function checkStart(value) {
24696
25055
  if (wait != null) input.wait = wait;
24697
25056
  if (staggerMs != null) input.staggerMs = staggerMs;
24698
25057
  if (replaceSame != null) input.replaceSame = replaceSame;
25058
+ if (record["flags"] != null) {
25059
+ const flags = checkFlagsById(record["flags"]);
25060
+ if (typeof flags === "string") return `flags${flags}`;
25061
+ input.flags = flags;
25062
+ }
24699
25063
  return input;
24700
25064
  }
25065
+ function checkFlagsById(value) {
25066
+ const record = asRecord(value);
25067
+ if (record == null) return ": expected an object keyed by process id";
25068
+ const checked = {};
25069
+ for (const [id, names] of Object.entries(record)) {
25070
+ const list = asIdList(names);
25071
+ if (list == null) return `[${JSON.stringify(id)}]: expected an array of flag names`;
25072
+ checked[id] = list;
25073
+ }
25074
+ return checked;
25075
+ }
25076
+ function checkNoteRuns(value) {
25077
+ const runs = asRecord(value)?.["runs"];
25078
+ if (!Array.isArray(runs)) return "runs: expected an array";
25079
+ const checked = [];
25080
+ for (const entry of runs) {
25081
+ const run = asRecord(entry);
25082
+ if (run == null) return "runs: expected objects";
25083
+ const { id, startedAt, durationMs } = run;
25084
+ const flags = asIdList(run["flags"]);
25085
+ if (typeof id !== "string" || id === "") return "runs: id expected a process id";
25086
+ if (typeof startedAt !== "number" || !Number.isFinite(startedAt)) return "runs: startedAt expected epoch ms";
25087
+ if (flags == null) return "runs: flags expected an array of flag names";
25088
+ if (durationMs != null && (typeof durationMs !== "number" || !(durationMs >= 0))) return "runs: durationMs expected a non-negative number";
25089
+ checked.push(typeof durationMs === "number" ? {
25090
+ id,
25091
+ startedAt,
25092
+ flags,
25093
+ durationMs
25094
+ } : {
25095
+ id,
25096
+ startedAt,
25097
+ flags
25098
+ });
25099
+ }
25100
+ return { runs: checked };
25101
+ }
24701
25102
  function checkSetEnv(value) {
24702
25103
  const record = asRecord(value);
24703
25104
  if (record == null) return "expected an object";
@@ -24889,6 +25290,7 @@ const commanderControlDomain = createActionRootDomain({ domain: "commander" }).c
24889
25290
  saveFilter: actionSchema().input({ schema: handSchema(checkSaveFilter) }).output({ schema: handSchema(checkOk) }),
24890
25291
  removeFilter: actionSchema().input({ schema: handSchema(checkRemoveFilter) }).output({ schema: handSchema(checkOk) }),
24891
25292
  setEnv: actionSchema().input({ schema: handSchema(checkSetEnv) }).output({ schema: handSchema(checkEnvReport) }),
25293
+ noteRuns: actionSchema().input({ schema: handSchema(checkNoteRuns) }).output({ schema: handSchema(checkOk) }),
24892
25294
  reloadConfig: actionSchema().input({ schema: handSchema(checkEmpty) }).output({ schema: handSchema(checkReloadResult) }),
24893
25295
  shutdown: actionSchema().input({ schema: handSchema(checkEmpty) }).output({ schema: handSchema(checkOk) })
24894
25296
  }
@@ -24934,7 +25336,7 @@ async function findDaemon(config) {
24934
25336
  async function findSkewedDaemon(config) {
24935
25337
  const skewed = await readSkewedInstanceRecord(commanderStatePaths(resolveCommanderDataDir(), config.configKey).instanceRecordPath, commanderStatusRealm.schemaHash);
24936
25338
  if (skewed == null || !pidAlive$1(skewed.pid)) return null;
24937
- const difference = skewed.skew === "protocol" ? `speaks protocol v${skewed.protocolVersion}; this build speaks v7` : "was started before an upgrade changed the status schema";
25339
+ const difference = skewed.skew === "protocol" ? `speaks protocol v${skewed.protocolVersion}; this build speaks v8` : "was started before an upgrade changed the status schema";
24938
25340
  return {
24939
25341
  message: `the daemon for this config (pid ${skewed.pid}, port ${skewed.port}, build ${skewed.packageVersion}) ${difference} — this CLI (build ${await commanderPackageVersion()}) cannot talk to it. Run \`nice-commander shutdown\` (it stops a daemon from any build), then retry.`,
24940
25342
  pid: skewed.pid,
@@ -25044,7 +25446,7 @@ async function connectDaemon(handle) {
25044
25446
  const payload = await (await runtime.handleActionPayload(request)).waitForResultPayload();
25045
25447
  if (!payload.result.ok) throw new CliExit(EXIT.failure, `action "${action}" rejected by the daemon`);
25046
25448
  const report = parseActionReport(payload.result.output);
25047
- if (report == null) throw new CliExit(EXIT.failure, `the daemon answered "${action}" with something this CLI does not recognise — protocol ${record.protocolVersion} vs 7`);
25449
+ if (report == null) throw new CliExit(EXIT.failure, `the daemon answered "${action}" with something this CLI does not recognise — protocol ${record.protocolVersion} vs 8`);
25048
25450
  return report;
25049
25451
  },
25050
25452
  setEnv: async (input) => {
@@ -25054,6 +25456,10 @@ async function connectDaemon(handle) {
25054
25456
  const warnings = payload.result.output.warnings;
25055
25457
  return Array.isArray(warnings) ? warnings.filter((entry) => typeof entry === "string") : [];
25056
25458
  },
25459
+ noteRuns: async (input) => {
25460
+ const request = commanderControlDomain.actionForId("noteRuns").request(input);
25461
+ if (!(await (await runtime.handleActionPayload(request)).waitForResultPayload()).result.ok) throw new CliExit(EXIT.failure, `action "noteRuns" rejected by the daemon`);
25462
+ },
25057
25463
  shutdown: async () => {
25058
25464
  const request = commanderControlDomain.actionForId("shutdown").request({});
25059
25465
  if (!(await (await runtime.handleActionPayload(request)).waitForResultPayload()).result.ok) throw new CliExit(EXIT.failure, `action "shutdown" rejected by the daemon`);
@@ -25168,11 +25574,13 @@ async function cmdUp(ctx) {
25168
25574
  "--no-wait",
25169
25575
  "--dry-run",
25170
25576
  "--replace-same",
25577
+ "--with",
25171
25578
  "--all",
25172
25579
  "--any"
25173
25580
  ]);
25174
25581
  if (bad != null) throw new CliExit(EXIT.usage, bad);
25175
25582
  const selection = selectOrExit(ctx, { bare: "default" });
25583
+ const flags = flagsOrExit(ctx);
25176
25584
  if (ctx.args.flags.has("--dry-run")) {
25177
25585
  const { out } = ctx;
25178
25586
  if (out.json) out.printJson(selection);
@@ -25197,7 +25605,8 @@ async function cmdUp(ctx) {
25197
25605
  ids: selection.ordered,
25198
25606
  wait,
25199
25607
  ...staggerMs > 0 ? { staggerMs } : {},
25200
- ...replaceSame ? { replaceSame } : {}
25608
+ ...replaceSame ? { replaceSame } : {},
25609
+ ...flags != null ? { flags: { [flags.id]: flags.flags } } : {}
25201
25610
  }));
25202
25611
  return printReport(ctx.out, report, client.state());
25203
25612
  } finally {
@@ -25208,6 +25617,7 @@ async function controlVerb(ctx, verb) {
25208
25617
  const known = verb === "restart" ? [
25209
25618
  "--no-wait",
25210
25619
  "--replace-same",
25620
+ "--with",
25211
25621
  "--all",
25212
25622
  "--any"
25213
25623
  ] : ["--all", "--any"];
@@ -25222,11 +25632,13 @@ async function controlVerb(ctx, verb) {
25222
25632
  extraIds: Object.keys(client.state().processes ?? {}).filter((id) => !declared.has(id))
25223
25633
  });
25224
25634
  const replaceSame = ctx.args.flags.has("--replace-same");
25635
+ const flags = verb === "restart" ? flagsOrExit(ctx) : null;
25225
25636
  const report = await withProgress(client, ctx.out, new Set(selection.ordered), () => verb === "stop" ? client.control("stop", { ids: selection.ordered }) : client.control("restart", {
25226
25637
  ids: selection.ordered,
25227
25638
  wait: !ctx.args.flags.has("--no-wait"),
25228
25639
  staggerMs: staggerFor(ctx.config, ctx.args.positionals),
25229
- ...replaceSame ? { replaceSame } : {}
25640
+ ...replaceSame ? { replaceSame } : {},
25641
+ ...flags != null ? { flags: { [flags.id]: flags.flags } } : {}
25230
25642
  }));
25231
25643
  return printReport(ctx.out, report, client.state());
25232
25644
  } finally {
@@ -25329,7 +25741,7 @@ function reportSignalShutdown(ctx, result, why, reports) {
25329
25741
  }
25330
25742
  //#endregion
25331
25743
  //#region src/daemon/envOverrides.ts
25332
- const STORE_VERSION$1 = 1;
25744
+ const STORE_VERSION$3 = 1;
25333
25745
  /** A knob is a port or a log level, not a payload. Bounds keep a mistake from becoming a file. */
25334
25746
  const MAX_VALUE_LENGTH = 4096;
25335
25747
  const EMPTY_ENV_OVERRIDES = Object.freeze({});
@@ -25365,7 +25777,7 @@ async function writeEnvOverrides(path, overrides) {
25365
25777
  mode: 448
25366
25778
  });
25367
25779
  const store = {
25368
- version: STORE_VERSION$1,
25780
+ version: STORE_VERSION$3,
25369
25781
  processes: Object.fromEntries(Object.entries(overrides).filter(([, values]) => Object.keys(values).length > 0).map(([id, values]) => [id, { ...values }]))
25370
25782
  };
25371
25783
  const temp = `${path}.${process.pid}.tmp`;
@@ -26321,6 +26733,7 @@ async function cmdList(ctx) {
26321
26733
  endpoints: proc.endpoints,
26322
26734
  url: proc.url ?? null,
26323
26735
  envVars: proc.envVars,
26736
+ flags: proc.flags,
26324
26737
  optIn: proc.optIn
26325
26738
  })),
26326
26739
  suites: Object.fromEntries(Object.entries(config.suites).map(([name, { name: _name, ...suite }]) => [name, suite])),
@@ -26382,6 +26795,12 @@ async function cmdExplain(ctx) {
26382
26795
  selection.ordered.forEach((id, index) => {
26383
26796
  out.print(` ${index + 1}. ${id}`);
26384
26797
  });
26798
+ const flagged = ctx.config.processes.filter((proc) => selection.direct.includes(proc.id) && proc.flags.length > 0);
26799
+ if (flagged.length > 0) out.print("flags:");
26800
+ for (const proc of flagged) for (const flag of proc.flags) {
26801
+ const about = flag.description != null ? ` — ${flag.description}` : "";
26802
+ out.print(` ${proc.id} --with ${flag.name} appends ${flag.args.join(" ")}${about}`);
26803
+ }
26385
26804
  if (!ctx.args.flags.has("--env")) {
26386
26805
  out.print(out.paint("gray", "env: `explain <sel> --env` shows each id's spawn environment"));
26387
26806
  return EXIT.ok;
@@ -26634,6 +27053,91 @@ async function cmdLogs(ctx) {
26634
27053
  }
26635
27054
  }
26636
27055
  //#endregion
27056
+ //#region src/daemon/lastStarts.ts
27057
+ const STORE_VERSION$2 = 1;
27058
+ /** Newest first, capped at `MAX_LAST_STARTS`. */
27059
+ function bounded$1(entries) {
27060
+ return Object.fromEntries([...entries].sort(([, a], [, b]) => b - a).slice(0, 256));
27061
+ }
27062
+ /** Missing, unreadable or corrupt all read as "nothing started yet" — never a reason to fail a boot. */
27063
+ async function readLastStarts(path) {
27064
+ try {
27065
+ const parsed = JSON.parse(await readFile(path, "utf8"));
27066
+ if (parsed == null || typeof parsed !== "object" || !("processes" in parsed)) return {};
27067
+ const processes = parsed.processes;
27068
+ if (processes == null || typeof processes !== "object" || Array.isArray(processes)) return {};
27069
+ return bounded$1(Object.entries(processes).filter((entry) => typeof entry[1] === "number" && Number.isFinite(entry[1])));
27070
+ } catch {
27071
+ return {};
27072
+ }
27073
+ }
27074
+ async function writeLastStarts(path, lastStarts) {
27075
+ await mkdir(dirname(path), {
27076
+ recursive: true,
27077
+ mode: 448
27078
+ });
27079
+ const temp = `${path}.${process.pid}.tmp`;
27080
+ const store = {
27081
+ version: STORE_VERSION$2,
27082
+ processes: bounded$1(Object.entries(lastStarts))
27083
+ };
27084
+ await writeFile(temp, `${JSON.stringify(store, null, 2)}\n`, {
27085
+ encoding: "utf8",
27086
+ mode: 384
27087
+ });
27088
+ await rename(temp, path);
27089
+ }
27090
+ //#endregion
27091
+ //#region src/daemon/taskDurations.ts
27092
+ const STORE_VERSION$1 = 1;
27093
+ /** Each flag set keeps its own samples — `dev-reset+hosted` runs as long as it runs, not as `dev-reset`. */
27094
+ function durationKey(id, flags) {
27095
+ return [id, ...flags].join("+");
27096
+ }
27097
+ /** `durations` with one more sample under `key`, which moves to the newest end of the bound. */
27098
+ function withDuration(durations, key, ms) {
27099
+ const samples = [...durations[key] ?? [], ms].slice(-3);
27100
+ const rest = Object.entries(durations).filter(([existing]) => existing !== key);
27101
+ return Object.fromEntries([...rest, [key, samples]].slice(-256));
27102
+ }
27103
+ /** The mean of the samples, or null with nothing to go on. */
27104
+ function estimateMs(samples) {
27105
+ if (samples == null || samples.length === 0) return null;
27106
+ return Math.round(samples.reduce((total, ms) => total + ms, 0) / samples.length);
27107
+ }
27108
+ /** Missing, unreadable or corrupt all read as "no history yet" — never a reason to fail a boot. */
27109
+ async function readTaskDurations(path) {
27110
+ try {
27111
+ const parsed = JSON.parse(await readFile(path, "utf8"));
27112
+ if (parsed == null || typeof parsed !== "object" || !("tasks" in parsed)) return {};
27113
+ const tasks = parsed.tasks;
27114
+ if (tasks == null || typeof tasks !== "object" || Array.isArray(tasks)) return {};
27115
+ const entries = Object.entries(tasks).flatMap(([key, samples]) => {
27116
+ if (!Array.isArray(samples)) return [];
27117
+ const valid = samples.filter((ms) => typeof ms === "number" && Number.isFinite(ms) && ms >= 0);
27118
+ return valid.length > 0 ? [[key, valid.slice(-3)]] : [];
27119
+ });
27120
+ return Object.fromEntries(entries.slice(-256));
27121
+ } catch {
27122
+ return {};
27123
+ }
27124
+ }
27125
+ async function writeTaskDurations(path, durations) {
27126
+ await mkdir(dirname(path), {
27127
+ recursive: true,
27128
+ mode: 448
27129
+ });
27130
+ const temp = `${path}.${process.pid}.tmp`;
27131
+ await writeFile(temp, `${JSON.stringify({
27132
+ version: STORE_VERSION$1,
27133
+ tasks: durations
27134
+ }, null, 2)}\n`, {
27135
+ encoding: "utf8",
27136
+ mode: 384
27137
+ });
27138
+ await rename(temp, path);
27139
+ }
27140
+ //#endregion
26637
27141
  //#region src/run/scheduler.ts
26638
27142
  async function runTaskPool(options) {
26639
27143
  const { failFast } = options;
@@ -26744,6 +27248,36 @@ function startPump(out, proc) {
26744
27248
  }
26745
27249
  };
26746
27250
  }
27251
+ /**
27252
+ * What this run ran reaches the "recently started" order and the task estimates — through the
27253
+ * daemon when one is up (it owns those stores while it runs), else straight into the stores.
27254
+ */
27255
+ async function noteForegroundRuns(config, paths, runs) {
27256
+ if (runs.length === 0) return;
27257
+ try {
27258
+ const handle = await findDaemon(config);
27259
+ if (handle != null) {
27260
+ const client = await connectDaemon(handle);
27261
+ try {
27262
+ await client.noteRuns({ runs: [...runs] });
27263
+ } finally {
27264
+ client.dispose();
27265
+ }
27266
+ return;
27267
+ }
27268
+ let lastStarts = await readLastStarts(paths.lastStartsPath);
27269
+ let durations = await readTaskDurations(paths.taskDurationsPath);
27270
+ for (const run of runs) {
27271
+ if ((lastStarts[run.id] ?? 0) < run.startedAt) lastStarts = {
27272
+ ...lastStarts,
27273
+ [run.id]: run.startedAt
27274
+ };
27275
+ if (run.durationMs != null) durations = withDuration(durations, durationKey(run.id, run.flags), run.durationMs);
27276
+ }
27277
+ await writeLastStarts(paths.lastStartsPath, lastStarts);
27278
+ await writeTaskDurations(paths.taskDurationsPath, durations);
27279
+ } catch {}
27280
+ }
26747
27281
  /** Let the last lines flush, then close every pump — the only way each one is guaranteed to end. */
26748
27282
  async function drainPumps(pumps, graceMs = 250) {
26749
27283
  if (pumps.length === 0) return;
@@ -26755,10 +27289,18 @@ async function cmdRun(ctx) {
26755
27289
  const bad = unknownFlags(ctx.args.flags, [
26756
27290
  "--parallel",
26757
27291
  "--fail-fast",
27292
+ "--with",
26758
27293
  "--all",
26759
27294
  "--any"
26760
27295
  ]);
26761
27296
  if (bad != null) throw new CliExit(EXIT.usage, bad);
27297
+ const flags = flagsOrExit(ctx);
27298
+ const passthrough = ctx.args.passthrough;
27299
+ const target = passthrough.length > 0 ? singleProcessOrExit(ctx, "--") : null;
27300
+ const unquotable = typeof target?.run === "string" ? passthrough.find((arg) => !SHELL_PLAIN_ARG.test(arg)) : void 0;
27301
+ if (target != null && unquotable != null) throw new CliExit(EXIT.usage, `"${target.id}" runs through a shell, where ${JSON.stringify(unquotable)} would need quoting — pass plain arguments, or declare a flag for it`);
27302
+ /** The one id `--with` / `--` select gets its flags' arguments, then the raw ones. */
27303
+ const extraArgs = (id) => [...flags?.id === id ? flags.args : [], ...target?.id === id ? passthrough : []];
26762
27304
  const parallel = numericFlag(ctx.args.flags, "--parallel");
26763
27305
  if (parallel != null && typeof parallel === "object") throw new CliExit(EXIT.usage, parallel.error);
26764
27306
  const selection = selectOrExit(ctx, { bare: "required" });
@@ -26807,7 +27349,7 @@ async function cmdRun(ctx) {
26807
27349
  }
26808
27350
  return createNiceProcess({
26809
27351
  id: def.id,
26810
- run: def.run,
27352
+ run: runWithArgs(def.run, extraArgs(def.id)),
26811
27353
  ...def.shell != null ? { shell: def.shell } : {},
26812
27354
  cwd: def.cwd,
26813
27355
  env: effectiveEnv(def, overrides),
@@ -26849,6 +27391,16 @@ async function cmdRun(ctx) {
26849
27391
  if (await Promise.race([graceful.then(() => true), new Promise((settle) => setTimeout(() => settle(false), TIMEOUT_STOP_GRACE_MS))])) return;
26850
27392
  for (const proc of procs) if (proc.pid != null) forceKillTree(proc.pid);
26851
27393
  };
27394
+ const ran = [];
27395
+ const noteStart = (def) => {
27396
+ const run = {
27397
+ id: def.id,
27398
+ startedAt: Date.now(),
27399
+ flags: flags?.id === def.id ? flags.flags : []
27400
+ };
27401
+ ran.push(run);
27402
+ return run;
27403
+ };
26852
27404
  const runTask = async (def) => {
26853
27405
  const proc = procFor(def.id);
26854
27406
  if (!single) out.print(`${out.paint("cyan", "▸")} ${out.accent(def.id, def.id)} running…`);
@@ -26860,8 +27412,10 @@ async function cmdRun(ctx) {
26860
27412
  });
26861
27413
  let timer = null;
26862
27414
  let timedOut = false;
27415
+ let run = null;
26863
27416
  try {
26864
27417
  await proc.start();
27418
+ run = noteStart(def);
26865
27419
  if (def.timeoutMs != null) {
26866
27420
  timer = setTimeout(() => {
26867
27421
  timedOut = true;
@@ -26890,6 +27444,7 @@ async function cmdRun(ctx) {
26890
27444
  }
26891
27445
  const code = proc.lastExit?.code ?? (proc.state === "succeeded" ? 0 : 1);
26892
27446
  const failed = code !== 0;
27447
+ if (!failed && run != null && passthrough.length === 0) run.durationMs = Date.now() - run.startedAt;
26893
27448
  out.print(failed ? `${out.paint("red", "✗")} ${out.accent(def.id, def.id)} exit ${code}` : `${out.paint("green", "✓")} ${out.accent(def.id, def.id)} ok`);
26894
27449
  return {
26895
27450
  id: def.id,
@@ -26978,6 +27533,7 @@ async function cmdRun(ctx) {
26978
27533
  }
26979
27534
  const proc = procFor(def.id);
26980
27535
  await proc.start();
27536
+ noteStart(def);
26981
27537
  if (!single) out.print(`${out.paint("cyan", "▸")} ${out.accent(def.id, def.id)} started (pid ${proc.pid ?? "?"})`);
26982
27538
  }
26983
27539
  if (services.length > 0 && !(failFast && failures.length > 0)) {
@@ -27000,6 +27556,7 @@ async function cmdRun(ctx) {
27000
27556
  } finally {
27001
27557
  process.removeListener("SIGINT", onSigint);
27002
27558
  await Promise.allSettled(procs.filter((proc) => !TERMINAL_STATES.has(proc.state)).map((proc) => proc.stop()));
27559
+ await noteForegroundRuns(config, paths, ran);
27003
27560
  }
27004
27561
  }
27005
27562
  //#endregion
@@ -27398,16 +27955,19 @@ bare down/restart/logs/run always require a selection — omission never means -
27398
27955
  * block followed by every entry, in this order.
27399
27956
  */
27400
27957
  const COMMAND_HELP = [
27401
- ["up", ` up [sel] [--no-wait] [--dry-run] [--replace-same]
27958
+ ["up", ` up [sel] [--no-wait] [--dry-run] [--replace-same] [--with <flag>]
27402
27959
  start: deps auto-included, DAG order, live progress;
27403
- a ready service prints its URL. --replace-same lets a
27960
+ a ready service prints its URL. --with turns on a
27961
+ flag the selected process declares (repeat it, or
27962
+ a,b) — one id only. --replace-same lets a
27404
27963
  start take an exclusive port from a STRAY — this same
27405
27964
  command in the same cwd, started outside the daemon
27406
27965
  (a stranger on the port still refuses). --json reports
27407
27966
  every id's outcome, state, pid and endpoints as data.`],
27408
27967
  ["down", " down <sel> stop (reverse-DAG order)"],
27409
- ["restart", ` restart <sel> [--no-wait] [--replace-same]
27410
- stop + start`],
27968
+ ["restart", ` restart <sel> [--no-wait] [--replace-same] [--with <flag>]
27969
+ stop + start, with the flags of the run it replaces
27970
+ unless --with names others`],
27411
27971
  ["status", " status [--watch] table from the live status realm"],
27412
27972
  ["logs", " logs <sel> [-f] merged interleaved tail with colored id prefixes"],
27413
27973
  ["list", " list config introspection (processes, suites, warnings)"],
@@ -27416,9 +27976,12 @@ const COMMAND_HELP = [
27416
27976
  ["env", ` env [sel] [--set N=V] [--unset N] declared env vars and their values; --clear drops
27417
27977
  overrides. A set value is STICKY: it applies to every
27418
27978
  later start until cleared, and never restarts anything.`],
27419
- ["run", ` run <sel> [--parallel N] [--fail-fast] foreground, no daemon; tasks = local CI shape
27979
+ ["run", ` run <sel> [--parallel N] [--fail-fast] [--with <flag>] [-- <args>]
27980
+ foreground, no daemon; tasks = local CI shape
27420
27981
  (a suite supplies its own parallel/fail-fast),
27421
27982
  a single id gets raw inherited stdio (interactive).
27983
+ --with turns on declared flags; anything after --
27984
+ is appended to that one id's command as-is.
27422
27985
  --fail-fast = stop at the FIRST failure and stop the
27423
27986
  survivors; without it every task still runs, every
27424
27987
  failure is reported, and the exit code is still
@@ -27508,7 +28071,7 @@ async function withTimeout(ctx, run) {
27508
28071
  async function main() {
27509
28072
  const argv = process.argv.slice(2);
27510
28073
  if (argv[0] === "daemon") {
27511
- const { runCommanderDaemon } = await import("./main-CWWlV2U5.mjs");
28074
+ const { runCommanderDaemon } = await import("./main-DSPhWTfM.mjs");
27512
28075
  return runCommanderDaemon(argv.slice(1));
27513
28076
  }
27514
28077
  const parsed = parseCliArgs(argv);
@@ -27516,6 +28079,10 @@ async function main() {
27516
28079
  process.stderr.write(`nice-commander: ${parsed.error}\n`);
27517
28080
  return EXIT.usage;
27518
28081
  }
28082
+ if (parsed.passthrough.length > 0 && parsed.command !== "run") {
28083
+ process.stderr.write("nice-commander: arguments after `--` go to a foreground `run` only — a daemon start appends only the flags a process declares (`--with <flag>`)\n");
28084
+ return EXIT.usage;
28085
+ }
27519
28086
  if (parsed.help || parsed.command === "help") {
27520
28087
  process.stdout.write(helpFor(parsed.command === "help" ? null : parsed.command));
27521
28088
  return EXIT.ok;
@@ -27553,6 +28120,6 @@ main().then((code) => {
27553
28120
  process.exitCode = EXIT.failure;
27554
28121
  });
27555
28122
  //#endregion
27556
- export { createRealmServerEngine as A, overrideFingerprint as B, commanderRuntimeError as C, resolveCommanderDataDir as D, ensureStateDir as E, createMemoryStorageAdapter_json as F, withDependencies as G, loadCommanderConfigFile as H, wsAcceptorCarrier as I, recordDaemonAlive as J, savedFilterId as K, validateCommanderConfig as L, serveChannel as M, createDefaultServeLogger as N, findDaemonProcesses as O, RuntimeCoordinate as P, effectiveEnv as R, commanderStatusRealm as S, commanderStatePaths as T, orderByDependency as U, hashCanonical as V, stopSetWithDependencies as W, writeInstanceRecord as X, removeInstanceRecord as Y, COMMANDER_LOGS_PATH as _, parseLogsClientMessage as a, COMMANDER_TICKET_PROTOCOL_PREFIX as b, identifyEndpointOwner as c, countOverrides as d, readEnvOverrides as f, COMMANDER_HEALTH_PATH as g, COMMANDER_BOOTSTRAP_PATH as h, runTaskPool as i, httpAcceptorCarrier as j, createRealmAcceptor as k, signalStray as l, commanderControlDomain as m, readSavedFilters as n, ancestors as o, commanderChannel as p, readInstanceRecord as q, writeSavedFilters as r, createPortInspector as s, mutateSavedFilters as t, applyEnvMutation as u, COMMANDER_SHUTDOWN_PATH as v, commanderPackageVersion as w, COMMANDER_WS_PATH as x, COMMANDER_TICKET_PATH as y, envVarViews as z };
28123
+ export { savedFilterId as $, commanderRuntimeError as A, createDefaultServeLogger as B, COMMANDER_HEALTH_PATH as C, COMMANDER_TICKET_PROTOCOL_PREFIX as D, COMMANDER_TICKET_PATH as E, findDaemonProcesses as F, effectiveEnv as G, createMemoryStorageAdapter_json as H, createRealmAcceptor as I, hashCanonical as J, envVarViews as K, createRealmServerEngine as L, commanderStatePaths as M, ensureStateDir as N, COMMANDER_WS_PATH as O, resolveCommanderDataDir as P, withDependencies as Q, httpAcceptorCarrier as R, COMMANDER_BOOTSTRAP_PATH as S, COMMANDER_SHUTDOWN_PATH as T, wsAcceptorCarrier as U, RuntimeCoordinate as V, validateCommanderConfig as W, orderByDependency as X, loadCommanderConfigFile as Y, stopSetWithDependencies as Z, applyEnvMutation as _, durationKey as a, writeInstanceRecord as at, commanderChannel as b, withDuration as c, writeLastStarts as d, resolveFlags as et, parseLogsClientMessage as f, signalStray as g, identifyEndpointOwner as h, runTaskPool as i, removeInstanceRecord as it, commanderPackageVersion as j, commanderStatusRealm as k, writeTaskDurations as l, createPortInspector as m, readSavedFilters as n, readInstanceRecord as nt, estimateMs as o, ancestors as p, overrideFingerprint as q, writeSavedFilters as r, recordDaemonAlive as rt, readTaskDurations as s, mutateSavedFilters as t, runWithArgs as tt, readLastStarts as u, countOverrides as v, COMMANDER_LOGS_PATH as w, commanderControlDomain as x, readEnvOverrides as y, serveChannel as z };
27557
28124
 
27558
28125
  //# sourceMappingURL=cli.mjs.map