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