@nice-code/commander 0.110.0 → 0.112.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/cli.mjs CHANGED
@@ -27,7 +27,11 @@ const GLOBAL_VALUE_FLAGS = new Set(["--config", "--timeout"]);
27
27
  * plain Map keeps only the last. The name still lands in `flags` so `unknownFlags` keeps rejecting
28
28
  * it on every command that does not accept it.
29
29
  */
30
- const REPEATABLE_VALUE_FLAGS = new Set(["--set", "--unset"]);
30
+ const REPEATABLE_VALUE_FLAGS = new Set([
31
+ "--set",
32
+ "--unset",
33
+ "--with"
34
+ ]);
31
35
  /**
32
36
  * Per-command flags that take a VALUE. Everything else is boolean — and that distinction is
33
37
  * load-bearing: a greedy "consume the next token" parse turned `up --no-wait demo` into
@@ -39,6 +43,7 @@ function parseCliArgs(argv) {
39
43
  const flags = /* @__PURE__ */ new Map();
40
44
  const repeated = /* @__PURE__ */ new Map();
41
45
  const positionals = [];
46
+ const passthrough = [];
42
47
  let command = null;
43
48
  let json = false;
44
49
  let noColor = false;
@@ -47,6 +52,10 @@ function parseCliArgs(argv) {
47
52
  let timeoutMs;
48
53
  for (let i = 0; i < argv.length; i += 1) {
49
54
  const token = argv[i];
55
+ if (token === "--") {
56
+ passthrough.push(...argv.slice(i + 1));
57
+ break;
58
+ }
50
59
  const eq = token.startsWith("--") ? token.indexOf("=") : -1;
51
60
  const arg = eq > 2 ? token.slice(0, eq) : token;
52
61
  const inlineValue = eq > 2 ? token.slice(eq + 1) : null;
@@ -109,7 +118,8 @@ function parseCliArgs(argv) {
109
118
  noColor,
110
119
  help,
111
120
  flags,
112
- repeated
121
+ repeated,
122
+ passthrough
113
123
  };
114
124
  if (configPath != null) args.configPath = configPath;
115
125
  if (timeoutMs != null) args.timeoutMs = timeoutMs;
@@ -152,7 +162,7 @@ function validStartStamp(value) {
152
162
  function isInstanceRecord(value) {
153
163
  if (value == null || typeof value !== "object" || Array.isArray(value)) return false;
154
164
  const record = value;
155
- return record.service === "nice-commander" && boundedString(record.instanceId) && boundedInt(record.generation, 0, Number.MAX_SAFE_INTEGER) && boundedInt(record.pid, 1, Number.MAX_SAFE_INTEGER) && boundedInt(record.port, 1, 65535) && boundedString(record.token) && boundedString(record.configKey) && boundedString(record.configRevisionHash) && boundedString(record.configPath) && boundedString(record.packageVersion) && boundedString(record.realmSchemaHash) && validStartStamp(record.startStamp) && (record.servesOwnClient == null || typeof record.servesOwnClient === "boolean") && record.protocolVersion === 7;
165
+ return record.service === "nice-commander" && boundedString(record.instanceId) && boundedInt(record.generation, 0, Number.MAX_SAFE_INTEGER) && boundedInt(record.pid, 1, Number.MAX_SAFE_INTEGER) && boundedInt(record.port, 1, 65535) && boundedString(record.token) && boundedString(record.configKey) && boundedString(record.configRevisionHash) && boundedString(record.configPath) && boundedString(record.packageVersion) && boundedString(record.realmSchemaHash) && validStartStamp(record.startStamp) && (record.servesOwnClient == null || typeof record.servesOwnClient === "boolean") && record.protocolVersion === 8;
156
166
  }
157
167
  async function writeInstanceRecord(path, record) {
158
168
  await mkdir(dirname(path), {
@@ -202,7 +212,7 @@ async function readSkewedInstanceRecord(path, expectedRealmSchemaHash) {
202
212
  if (!boundedInt(record["protocolVersion"], 0, Number.MAX_SAFE_INTEGER)) return null;
203
213
  if (!boundedInt(record["pid"], 1, Number.MAX_SAFE_INTEGER)) return null;
204
214
  if (!boundedInt(record["port"], 1, 65535)) return null;
205
- const sameProtocol = record["protocolVersion"] === 7;
215
+ const sameProtocol = record["protocolVersion"] === 8;
206
216
  const sameRealm = boundedString(record["realmSchemaHash"]) && record["realmSchemaHash"] === expectedRealmSchemaHash;
207
217
  if (sameProtocol && sameRealm) return null;
208
218
  return {
@@ -298,6 +308,31 @@ async function pingDaemon(record, timeoutMs = 2e3) {
298
308
  }
299
309
  }
300
310
  //#endregion
311
+ //#region src/config/flags.ts
312
+ /**
313
+ * An argument a shell-string `run` can take appended unquoted in sh, cmd and PowerShell alike.
314
+ * Anything else (spaces, quotes, `$`, `%`, `,`, `;`…) would need per-shell quoting.
315
+ */
316
+ const SHELL_PLAIN_ARG = /^[A-Za-z0-9_+=:./-]+$/;
317
+ /** `run` with `args` appended — after the argv, or after the shell string. */
318
+ function runWithArgs(run, args) {
319
+ if (args.length === 0) return run;
320
+ return typeof run === "string" ? `${run} ${args.join(" ")}` : [...run, ...args];
321
+ }
322
+ /** Requested names against a definition's declared flags; an undeclared name is an error. */
323
+ function resolveFlags(definition, names) {
324
+ const unknown = names.filter((name) => !definition.flags.some((flag) => flag.name === name));
325
+ if (unknown.length > 0) {
326
+ const declared = definition.flags.map((flag) => flag.name);
327
+ return { error: `"${definition.id}" declares no flag ${unknown.map((name) => `"${name}"`).join(", ")} — ` + (declared.length > 0 ? `its flags: ${declared.join(", ")}` : "it declares none") };
328
+ }
329
+ const on = definition.flags.filter((flag) => names.includes(flag.name));
330
+ return {
331
+ flags: on.map((flag) => flag.name),
332
+ args: on.flatMap((flag) => flag.args)
333
+ };
334
+ }
335
+ //#endregion
301
336
  //#region src/config/tags.ts
302
337
  /** `key=value` → `[key, value]`, or null when the term is not tag-shaped. */
303
338
  function parseTagTerm(term) {
@@ -833,6 +868,54 @@ function readEnvVarFields(declared, name, at, errors) {
833
868
  required: required === true
834
869
  };
835
870
  }
871
+ const MAX_FLAGS = 32;
872
+ function readFlags(raw, shellString, at, errors) {
873
+ if (raw == null) return [];
874
+ if (!Array.isArray(raw)) {
875
+ errors.push(`${at}.flags: expected an array of flag declarations`);
876
+ return [];
877
+ }
878
+ if (raw.length > MAX_FLAGS) errors.push(`${at}.flags: ${raw.length} entries exceeds the ${MAX_FLAGS} bound`);
879
+ const flags = [];
880
+ for (const [index, declared] of raw.entries()) {
881
+ const atF = `${at}.flags[${index}]`;
882
+ if (!isRecord(declared)) {
883
+ errors.push(`${atF}: expected an object`);
884
+ continue;
885
+ }
886
+ const name = declared["name"];
887
+ if (typeof name !== "string" || !COMMANDER_ID_PATTERN.test(name)) {
888
+ errors.push(`${atF}.name: must match ${COMMANDER_ID_PATTERN}`);
889
+ continue;
890
+ }
891
+ if (flags.some((existing) => existing.name === name)) {
892
+ errors.push(`${atF}.name: duplicate flag "${name}"`);
893
+ continue;
894
+ }
895
+ const description = declared["description"];
896
+ if (description != null && typeof description !== "string") {
897
+ errors.push(`${atF}.description: expected a string`);
898
+ continue;
899
+ }
900
+ const rawArgs = declared["args"] ?? [`--${name}`];
901
+ if (!Array.isArray(rawArgs) || rawArgs.length === 0 || rawArgs.some((arg) => typeof arg !== "string" || arg === "" || hasControlChars(arg))) {
902
+ errors.push(`${atF}.args: expected a non-empty array of non-empty strings`);
903
+ continue;
904
+ }
905
+ const args = rawArgs.filter((arg) => typeof arg === "string");
906
+ const unquotable = shellString ? args.find((arg) => !SHELL_PLAIN_ARG.test(arg)) : void 0;
907
+ if (unquotable != null) {
908
+ errors.push(`${atF}.args: ${JSON.stringify(unquotable)} would need shell quoting, and a shell-string \`run\` takes its flags unquoted — use the argv form of \`run\`, or a plain argument`);
909
+ continue;
910
+ }
911
+ flags.push({
912
+ name,
913
+ args,
914
+ ...typeof description === "string" ? { description } : {}
915
+ });
916
+ }
917
+ return flags;
918
+ }
836
919
  function isUrlCleanHttp(url) {
837
920
  try {
838
921
  const parsed = new URL(url);
@@ -1012,6 +1095,7 @@ function validateCommanderConfig(raw, anchor) {
1012
1095
  if (resolved != null) envVars.push(resolved);
1013
1096
  }
1014
1097
  for (const declared of envVars) if (declared.default != null) env[declared.name] = declared.default;
1098
+ const flags = readFlags(proc.flags, typeof proc.run === "string", at, errors);
1015
1099
  const tagEntries = Object.entries({
1016
1100
  ...config.defaults?.tags,
1017
1101
  ...proc.tags
@@ -1115,6 +1199,7 @@ function validateCommanderConfig(raw, anchor) {
1115
1199
  ...proc.shell != null ? { shell: proc.shell } : {},
1116
1200
  env,
1117
1201
  envVars,
1202
+ flags,
1118
1203
  stdin,
1119
1204
  tags,
1120
1205
  optIn: proc.optIn === true,
@@ -1307,6 +1392,28 @@ function selectOrExit(ctx, options) {
1307
1392
  if (!result.ok) throw new CliExit(EXIT.usage, result.errors.join("\n"));
1308
1393
  return result.selection;
1309
1394
  }
1395
+ /**
1396
+ * The one process a per-process option (`--with`, `-- args`) applies to: the selection must be
1397
+ * exactly its id — a flag set means nothing to a suite or a tag.
1398
+ */
1399
+ function singleProcessOrExit(ctx, option) {
1400
+ const [term, ...rest] = ctx.args.positionals;
1401
+ const definition = ctx.config.processes.find((proc) => proc.id === term);
1402
+ if (definition == null || rest.length > 0 || ctx.args.flags.has("--all")) throw new CliExit(EXIT.usage, `${option} applies to one process — select it by its id alone (\`${ctx.args.command} <id> ${option} …\`)`);
1403
+ return definition;
1404
+ }
1405
+ /** `--with a --with b` / `--with a,b`, resolved against the selected process's declared flags. */
1406
+ function flagsOrExit(ctx) {
1407
+ const raw = ctx.args.repeated.get("--with") ?? [];
1408
+ if (raw.length === 0) return null;
1409
+ const definition = singleProcessOrExit(ctx, "--with");
1410
+ const resolved = resolveFlags(definition, raw.flatMap((value) => value.split(",")).filter((name) => name !== ""));
1411
+ if ("error" in resolved) throw new CliExit(EXIT.usage, resolved.error);
1412
+ return {
1413
+ id: definition.id,
1414
+ ...resolved
1415
+ };
1416
+ }
1310
1417
  /** Suite stagger for a start: the widest stagger among the suites named in the terms. */
1311
1418
  function staggerFor(config, terms) {
1312
1419
  let stagger = 0;
@@ -4616,6 +4723,7 @@ var ClientCryptoKeyLink = class {
4616
4723
  localVerifyKeyPair;
4617
4724
  linkedClientKeys = /* @__PURE__ */ new Map();
4618
4725
  storage;
4726
+ storageAdapter;
4619
4727
  identityMode;
4620
4728
  initialized = false;
4621
4729
  initializePromise;
@@ -4623,9 +4731,18 @@ var ClientCryptoKeyLink = class {
4623
4731
  localVerifyKeyPairPromise;
4624
4732
  constructor({ storageAdapter, identityMode } = {}) {
4625
4733
  if (storageAdapter != null) this.storage = createTypedStorage({ storageAdapter });
4734
+ this.storageAdapter = storageAdapter;
4626
4735
  this.identityMode = identityMode ?? "lazy";
4627
4736
  }
4628
4737
  /**
4738
+ * A namespace of this identity's own store (same backing storage, `prefix` appended), for state
4739
+ * that belongs to this identity and must go wherever its keys go — e.g. a connector's established
4740
+ * sessions. `undefined` when the link has no storage.
4741
+ */
4742
+ scopedStorage(prefix) {
4743
+ return this.storageAdapter?.withKeyPrefix(prefix);
4744
+ }
4745
+ /**
4629
4746
  * Loads the local key pairs and any linked client public keys from storage (when a storage
4630
4747
  * adapter was provided), generating and persisting fresh local key pairs if none exist yet.
4631
4748
  *
@@ -9539,6 +9656,12 @@ function assembleWireConnectionParts(options) {
9539
9656
  }
9540
9657
  //#endregion
9541
9658
  //#region ../nice-wire/src/Connect/exchangeEnvelope.ts
9659
+ /**
9660
+ * The `err` id an acceptor sends when it refused the session itself (expired, tampered or
9661
+ * wrong-key ticket, or an act at the wrong level) — before any lane ran, so the connector may
9662
+ * drop the session, handshake again and resend the same act.
9663
+ */
9664
+ const WIRE_EXCHANGE_SESSION_REFUSED = "session_refused";
9542
9665
  function encodeExchange(envelope) {
9543
9666
  return JSON.stringify(envelope);
9544
9667
  }
@@ -9567,33 +9690,261 @@ function hasEnvelopeKind(value) {
9567
9690
  return typeof value === "object" && value != null && "k" in value;
9568
9691
  }
9569
9692
  //#endregion
9693
+ //#region ../nice-wire/src/SecureSession/exchangeTicketSeal.ts
9694
+ const SEALED_ENVELOPE_LENGTH = 2;
9695
+ function createExchangeTicketSealer(link, options = {}) {
9696
+ let keyPromise;
9697
+ const getKey = () => {
9698
+ if (keyPromise == null) keyPromise = link.deriveLocalSealKey({ version: options.version }).catch((err) => {
9699
+ keyPromise = void 0;
9700
+ throw err;
9701
+ });
9702
+ return keyPromise;
9703
+ };
9704
+ return {
9705
+ async seal(value, ttlMs) {
9706
+ const { nonce, ciphertext } = await encryptBytesWithAesGcmKey({
9707
+ dataToEncrypt: pack({
9708
+ v: value,
9709
+ exp: Date.now() + ttlMs
9710
+ }),
9711
+ aesGcmKey: await getKey()
9712
+ });
9713
+ return bytesToBase64(pack([nonce, ciphertext]));
9714
+ },
9715
+ async open(blob) {
9716
+ try {
9717
+ const envelope = unpack(base64ToBytes(blob));
9718
+ if (!Array.isArray(envelope) || envelope.length !== SEALED_ENVELOPE_LENGTH) return void 0;
9719
+ const [nonce, ciphertext] = envelope;
9720
+ if (!(nonce instanceof Uint8Array) || !(ciphertext instanceof Uint8Array)) return void 0;
9721
+ const payload = unpack(await decryptBytesWithAesGcmKey({
9722
+ dataToDecrypt: {
9723
+ nonce,
9724
+ ciphertext
9725
+ },
9726
+ aesGcmKey: await getKey()
9727
+ }));
9728
+ if (payload == null || typeof payload.exp !== "number" || payload.exp < Date.now()) return;
9729
+ return payload.v;
9730
+ } catch {
9731
+ return;
9732
+ }
9733
+ }
9734
+ };
9735
+ }
9736
+ //#endregion
9737
+ //#region ../nice-wire/src/Connect/exchangeSessionShelf.ts
9738
+ /** Lapse a little before the acceptor would, so a request is never sent on its last second. */
9739
+ function expiryFor(receivedAt, ttlMs) {
9740
+ if (ttlMs == null || !(ttlMs > 0)) return void 0;
9741
+ return receivedAt + ttlMs - Math.min(6e4, ttlMs / 10);
9742
+ }
9743
+ function stateFromRecord(link, record) {
9744
+ const crypto = record.km != null ? createActionFrameCrypto({
9745
+ link,
9746
+ keyMaterial: record.km
9747
+ }) : void 0;
9748
+ return {
9749
+ token: record.t,
9750
+ crypto,
9751
+ expiresAt: record.exp,
9752
+ record
9753
+ };
9754
+ }
9755
+ function isLapsed(state) {
9756
+ return state.expiresAt != null && Date.now() >= state.expiresAt;
9757
+ }
9758
+ /**
9759
+ * One session's lifecycle: at most one handshake in flight, shared by every caller; a refused or
9760
+ * lapsed session is replaced once, however many requests noticed it.
9761
+ */
9762
+ var ExchangeSessionSlot = class {
9763
+ _entry;
9764
+ current(initial, replacement) {
9765
+ const entry = this._entry;
9766
+ if (entry == null) return this._start(initial);
9767
+ if (entry.state != null && isLapsed(entry.state)) return this.renew(entry.state, replacement);
9768
+ return entry.promise;
9769
+ }
9770
+ renew(stale, replacement) {
9771
+ const entry = this._entry;
9772
+ if (entry != null && entry.state !== stale) return entry.promise;
9773
+ return this._start(replacement);
9774
+ }
9775
+ _start(establish) {
9776
+ const entry = { promise: establish() };
9777
+ this._entry = entry;
9778
+ entry.promise.then((state) => {
9779
+ entry.state = state;
9780
+ }, () => {
9781
+ if (this._entry === entry) this._entry = void 0;
9782
+ });
9783
+ return entry.promise;
9784
+ }
9785
+ };
9786
+ /** A session source for one transport alone — today's behaviour, plus renewal on refusal. */
9787
+ function privateSessionSource(handshake) {
9788
+ const slot = new ExchangeSessionSlot();
9789
+ return {
9790
+ current: () => slot.current(handshake, handshake),
9791
+ renew: (stale) => slot.renew(stale, handshake)
9792
+ };
9793
+ }
9794
+ const STORE_KEY = "sessions";
9795
+ const SEAL_VERSION = "connector-exchange-session/v1";
9796
+ /**
9797
+ * Every session one crypto identity holds with its peers, keyed by peer identity: shared in memory
9798
+ * by all of the link's transports, and kept in the link's own storage so a reload restores it.
9799
+ * Stored copies are sealed with a key derived from the link's private key — useless to another
9800
+ * device, and unopenable once the identity is reset.
9801
+ */
9802
+ var ExchangeSessionShelf = class {
9803
+ _link;
9804
+ _slots = /* @__PURE__ */ new Map();
9805
+ _storage;
9806
+ _sealer;
9807
+ constructor(_link) {
9808
+ this._link = _link;
9809
+ this._storage = _link.scopedStorage("wire-exchange/");
9810
+ this._sealer = createExchangeTicketSealer(_link, { version: SEAL_VERSION });
9811
+ }
9812
+ source(key, handshake) {
9813
+ let slot = this._slots.get(key);
9814
+ if (slot == null) {
9815
+ slot = new ExchangeSessionSlot();
9816
+ this._slots.set(key, slot);
9817
+ }
9818
+ const held = slot;
9819
+ const handshakeAndKeep = async () => {
9820
+ const state = await handshake();
9821
+ await this._keep(key, state).catch(() => void 0);
9822
+ return state;
9823
+ };
9824
+ const restoreOrHandshake = async () => {
9825
+ return await this._restore(key).catch(() => void 0) ?? await handshakeAndKeep();
9826
+ };
9827
+ const replace = async () => {
9828
+ await this._forget(key).catch(() => void 0);
9829
+ return await handshakeAndKeep();
9830
+ };
9831
+ return {
9832
+ current: () => held.current(restoreOrHandshake, replace),
9833
+ renew: (stale) => held.renew(stale, replace)
9834
+ };
9835
+ }
9836
+ async _restore(key) {
9837
+ const storage = this._storage;
9838
+ if (storage == null) return void 0;
9839
+ const stored = (await storage.getJson(STORE_KEY))?.[key];
9840
+ if (stored == null || stored.exp <= Date.now()) return void 0;
9841
+ await this._link.initialize();
9842
+ const record = await this._sealer.open(stored.sealed);
9843
+ if (record == null || typeof record.t !== "string") return void 0;
9844
+ return stateFromRecord(this._link, record);
9845
+ }
9846
+ async _keep(key, state) {
9847
+ const storage = this._storage;
9848
+ const record = state.record;
9849
+ if (storage == null || record?.exp == null) return;
9850
+ const ttl = record.exp - Date.now();
9851
+ if (ttl <= 0) return;
9852
+ const sealed = await this._sealer.seal(record, ttl);
9853
+ await this._update(storage, (sessions) => ({
9854
+ ...sessions,
9855
+ [key]: {
9856
+ exp: record.exp ?? 0,
9857
+ sealed
9858
+ }
9859
+ }));
9860
+ }
9861
+ async _forget(key) {
9862
+ const storage = this._storage;
9863
+ if (storage == null) return;
9864
+ await this._update(storage, (sessions) => {
9865
+ const { [key]: _dropped, ...rest } = sessions;
9866
+ return rest;
9867
+ });
9868
+ }
9869
+ async _update(storage, change) {
9870
+ await storage.updateJsonOrDef(STORE_KEY, {}, (current) => {
9871
+ const now = Date.now();
9872
+ const live = {};
9873
+ for (const [key, entry] of Object.entries(change(current))) if (entry.exp > now) live[key] = entry;
9874
+ return live;
9875
+ });
9876
+ }
9877
+ };
9878
+ const shelves = /* @__PURE__ */ new WeakMap();
9879
+ /**
9880
+ * The source a secure exchange draws its session from: shared by peer identity when the config asks
9881
+ * for reuse and names the peer, private to this transport otherwise.
9882
+ */
9883
+ function exchangeSessionSource(secure, lane, handshake) {
9884
+ const peer = secure.expectedPeer;
9885
+ if (secure.reuseExchangeSessions !== true || peer == null) return privateSessionSource(handshake);
9886
+ let shelf = shelves.get(secure.link);
9887
+ if (shelf == null) {
9888
+ shelf = new ExchangeSessionShelf(secure.link);
9889
+ shelves.set(secure.link, shelf);
9890
+ }
9891
+ const key = JSON.stringify([
9892
+ secure.localCoordinate.envId,
9893
+ secure.localCoordinate.perId ?? null,
9894
+ peer.envId,
9895
+ peer.perId ?? null,
9896
+ secure.securityLevel,
9897
+ lane.dictionaryVersion,
9898
+ [...lane.channels ?? []].sort()
9899
+ ]);
9900
+ return shelf.source(key, handshake);
9901
+ }
9902
+ //#endregion
9570
9903
  //#region ../nice-wire/src/Connect/exchangeSession.ts
9571
9904
  const textEncoder$1 = new TextEncoder();
9572
9905
  const textDecoder$1 = new TextDecoder();
9906
+ const PLAIN_STATE = {};
9573
9907
  /** Plain path (no handshake/token): every wire rides a bare `act` envelope, plaintext both ways. */
9574
9908
  function establishPlainExchangeSession(carrier) {
9575
- return makeSession(carrier, {});
9909
+ return makeSession(carrier, {
9910
+ current: async () => PLAIN_STATE,
9911
+ renew: async () => PLAIN_STATE
9912
+ });
9576
9913
  }
9577
9914
  /**
9578
- * Secure path: run the handshake (two exchanges) once at bring-up, then reuse the token + crypto.
9579
- * The lane supplies the handshake payload (`dictionaryVersion`/`channels`, E5 — emitted under the
9580
- * byte-frozen wire names; the version is signed into the challenge).
9915
+ * Secure path: run the handshake (two exchanges) at bring-up — or restore a kept session — then
9916
+ * reuse the token + crypto. The lane supplies the handshake payload (`dictionaryVersion`/`channels`,
9917
+ * E5 — emitted under the byte-frozen wire names; the version is signed into the challenge).
9581
9918
  */
9582
9919
  async function establishSecureExchangeSession(ctx) {
9583
- const state = await runConnectorExchangeHandshake(ctx.carrier, ctx.secure, ctx.lane);
9584
- return makeSession(ctx.carrier, state);
9585
- }
9586
- function makeSession(carrier, state) {
9587
- const runExchange = async (wire, opts) => {
9588
- const request = await buildRequestEnvelope(state, wire);
9589
- return carrier.exchange(encodeExchange(request), { signal: opts?.signal });
9920
+ const source = exchangeSessionSource(ctx.secure, ctx.lane, () => runConnectorExchangeHandshake(ctx.carrier, ctx.secure, ctx.lane));
9921
+ await source.current();
9922
+ return makeSession(ctx.carrier, source, ctx.secure.localCoordinate.insId);
9923
+ }
9924
+ function makeSession(carrier, source, insId) {
9925
+ const post = async (state, wire, signal) => {
9926
+ const request = await buildRequestEnvelope(state, wire, insId);
9927
+ return decodeExchangeReply(asString(await carrier.exchange(encodeExchange(request), { signal })));
9928
+ };
9929
+ const roundTrip = async (wire, signal) => {
9930
+ const state = await source.current();
9931
+ const reply = await post(state, wire, signal);
9932
+ if (reply?.k !== "err" || reply.id !== "session_refused" || state.token == null) return {
9933
+ state,
9934
+ reply
9935
+ };
9936
+ const renewed = await source.renew(state);
9937
+ return {
9938
+ state: renewed,
9939
+ reply: await post(renewed, wire, signal)
9940
+ };
9590
9941
  };
9591
9942
  return {
9592
9943
  send: async (wire, opts) => {
9593
- await runExchange(wire, opts);
9944
+ await roundTrip(wire, opts?.signal);
9594
9945
  },
9595
9946
  exchange: async (wire, opts) => {
9596
- const reply = decodeExchangeReply(asString(await runExchange(wire, opts)));
9947
+ const { state, reply } = await roundTrip(wire, opts?.signal);
9597
9948
  if (reply == null) return {
9598
9949
  ok: false,
9599
9950
  reason: "malformed_reply"
@@ -9615,18 +9966,21 @@ function makeSession(carrier, state) {
9615
9966
  }
9616
9967
  };
9617
9968
  }
9618
- async function buildRequestEnvelope(state, wire) {
9969
+ async function buildRequestEnvelope(state, wire, insId) {
9970
+ const i = state.token != null ? insId : void 0;
9619
9971
  if (state.crypto != null) {
9620
9972
  const ciphertext = await state.crypto.encryptFrame(textEncoder$1.encode(JSON.stringify(wire)));
9621
9973
  return {
9622
9974
  k: "act",
9623
9975
  t: state.token,
9976
+ i,
9624
9977
  c: bytesToBase64(ciphertext)
9625
9978
  };
9626
9979
  }
9627
9980
  return {
9628
9981
  k: "act",
9629
9982
  t: state.token,
9983
+ i,
9630
9984
  w: wire
9631
9985
  };
9632
9986
  }
@@ -9669,14 +10023,13 @@ async function runConnectorExchangeHandshake(carrier, secure, lane) {
9669
10023
  if (accept.t !== "accept") throw nonProtocolReply(carrier, "an accept frame", `hs/${accept.t}`);
9670
10024
  if (acceptReply.t == null) throw new Error(`[${HANDSHAKE_STAGE}] accept missing session token${at(carrier)}`);
9671
10025
  const result = await handshake.onAccept(accept);
9672
- const crypto = result.securityLevel === "encrypted" && result.encryptionKeyMaterial != null ? createActionFrameCrypto({
9673
- link: secure.link,
9674
- keyMaterial: result.encryptionKeyMaterial
9675
- }) : void 0;
9676
- return {
9677
- token: acceptReply.t,
9678
- crypto
9679
- };
10026
+ const keyMaterial = result.securityLevel === "encrypted" ? result.encryptionKeyMaterial : void 0;
10027
+ return stateFromRecord(secure.link, {
10028
+ t: acceptReply.t,
10029
+ level: result.securityLevel,
10030
+ km: keyMaterial,
10031
+ exp: expiryFor(Date.now(), acceptReply.ttl)
10032
+ });
9680
10033
  }
9681
10034
  const HANDSHAKE_STAGE = "exchange-handshake";
9682
10035
  /**
@@ -10262,50 +10615,6 @@ var WireAcceptor = class {
10262
10615
  }
10263
10616
  };
10264
10617
  //#endregion
10265
- //#region ../nice-wire/src/SecureSession/exchangeTicketSeal.ts
10266
- const SEALED_ENVELOPE_LENGTH = 2;
10267
- function createExchangeTicketSealer(link, options = {}) {
10268
- let keyPromise;
10269
- const getKey = () => {
10270
- if (keyPromise == null) keyPromise = link.deriveLocalSealKey({ version: options.version }).catch((err) => {
10271
- keyPromise = void 0;
10272
- throw err;
10273
- });
10274
- return keyPromise;
10275
- };
10276
- return {
10277
- async seal(value, ttlMs) {
10278
- const { nonce, ciphertext } = await encryptBytesWithAesGcmKey({
10279
- dataToEncrypt: pack({
10280
- v: value,
10281
- exp: Date.now() + ttlMs
10282
- }),
10283
- aesGcmKey: await getKey()
10284
- });
10285
- return bytesToBase64(pack([nonce, ciphertext]));
10286
- },
10287
- async open(blob) {
10288
- try {
10289
- const envelope = unpack(base64ToBytes(blob));
10290
- if (!Array.isArray(envelope) || envelope.length !== SEALED_ENVELOPE_LENGTH) return void 0;
10291
- const [nonce, ciphertext] = envelope;
10292
- if (!(nonce instanceof Uint8Array) || !(ciphertext instanceof Uint8Array)) return void 0;
10293
- const payload = unpack(await decryptBytesWithAesGcmKey({
10294
- dataToDecrypt: {
10295
- nonce,
10296
- ciphertext
10297
- },
10298
- aesGcmKey: await getKey()
10299
- }));
10300
- if (payload == null || typeof payload.exp !== "number" || payload.exp < Date.now()) return;
10301
- return payload.v;
10302
- } catch {
10303
- return;
10304
- }
10305
- }
10306
- };
10307
- }
10308
- //#endregion
10309
10618
  //#region ../nice-wire/src/Connect/WireExchangeAcceptor.ts
10310
10619
  /** The default session-ticket lifetime — see {@link IWireExchangeAcceptorOptions.sessionTtlMs}. */
10311
10620
  const DEFAULT_SESSION_TTL_MS = 720 * 60 * 1e3;
@@ -10375,11 +10684,17 @@ var WireExchangeAcceptor = class {
10375
10684
  m: encodeHandshakeMessage(reply)
10376
10685
  };
10377
10686
  const pending = handshake.exportPending();
10378
- if (pending == null) return {
10687
+ const dv = this._dictionaryVersion(message.channels);
10688
+ if (pending == null || dv == null) return {
10379
10689
  k: "err",
10380
10690
  message: "handshake produced no continuation state"
10381
10691
  };
10382
- const hsc = await this._sealer.seal(pending, HANDSHAKE_CONTINUATION_TTL_MS);
10692
+ const continuation = {
10693
+ ...pending,
10694
+ dv,
10695
+ ch: message.channels
10696
+ };
10697
+ const hsc = await this._sealer.seal(continuation, HANDSHAKE_CONTINUATION_TTL_MS);
10383
10698
  return {
10384
10699
  k: "hs",
10385
10700
  m: encodeHandshakeMessage(reply),
@@ -10391,11 +10706,12 @@ var WireExchangeAcceptor = class {
10391
10706
  k: "err",
10392
10707
  message: "prove missing continuation token"
10393
10708
  };
10394
- const pending = await this._sealer.open(request.hsc);
10395
- if (pending == null) return {
10709
+ const continuation = await this._sealer.open(request.hsc);
10710
+ if (continuation == null) return {
10396
10711
  k: "err",
10397
10712
  message: "invalid or expired continuation token"
10398
10713
  };
10714
+ const { dv, ch, ...pending } = continuation;
10399
10715
  const handshake = this._makeHandshake();
10400
10716
  await handshake.restorePending(pending);
10401
10717
  const reply = await handshake.onProve(message);
@@ -10404,13 +10720,16 @@ var WireExchangeAcceptor = class {
10404
10720
  const ticket = {
10405
10721
  client: result.remote,
10406
10722
  securityLevel: result.securityLevel,
10407
- keyMaterial: result.encryptionKeyMaterial
10723
+ keyMaterial: result.encryptionKeyMaterial,
10724
+ dv,
10725
+ ch
10408
10726
  };
10409
10727
  const t = await this._sealer.seal(ticket, this._sessionTtlMs);
10410
10728
  return {
10411
10729
  k: "hs",
10412
10730
  m: encodeHandshakeMessage(reply),
10413
- t
10731
+ t,
10732
+ ttl: this._sessionTtlMs
10414
10733
  };
10415
10734
  }
10416
10735
  return {
@@ -10423,6 +10742,10 @@ var WireExchangeAcceptor = class {
10423
10742
  message: `unexpected handshake message ${message.t}`
10424
10743
  };
10425
10744
  }
10745
+ _dictionaryVersion(channels) {
10746
+ const version = this._lane.dictionaryVersion;
10747
+ return typeof version === "function" ? version({ channels: channels == null ? void 0 : [...channels] }) : version;
10748
+ }
10426
10749
  async _handleAction(request) {
10427
10750
  let client;
10428
10751
  let crypto;
@@ -10430,24 +10753,30 @@ var WireExchangeAcceptor = class {
10430
10753
  let securityLevel = "none";
10431
10754
  if (request.t != null) {
10432
10755
  const ticket = await this._sealer.open(request.t);
10433
- if (ticket == null) return {
10434
- k: "err",
10435
- message: "unknown or expired session token"
10436
- };
10437
- client = new RuntimeCoordinate(ticket.client);
10756
+ if (ticket == null) return refused("unknown or expired session token");
10757
+ if (ticket.dv != null && ticket.dv !== this._dictionaryVersion(ticket.ch)) return refused("session was agreed under another dictionary version");
10758
+ client = new RuntimeCoordinate(typeof request.i === "string" ? {
10759
+ ...ticket.client,
10760
+ insId: request.i
10761
+ } : ticket.client);
10438
10762
  securityLevel = ticket.securityLevel;
10439
- crypto = ticket.securityLevel === "encrypted" && ticket.keyMaterial != null ? createActionFrameCrypto({
10440
- link: this._security.link,
10441
- keyMaterial: ticket.keyMaterial
10442
- }) : void 0;
10443
- if ("c" in request) {
10444
- if (crypto == null) return {
10445
- k: "err",
10446
- message: "session is not encrypted"
10447
- };
10448
- const plain = await crypto.decryptFrame(base64ToBytes(request.c));
10449
- wire = JSON.parse(textDecoder.decode(plain));
10450
- } else wire = request.w;
10763
+ if (ticket.securityLevel === "encrypted") {
10764
+ if (!("c" in request)) return refused("encrypted session refuses a plaintext act");
10765
+ if (ticket.keyMaterial == null) return refused("encrypted session has no key material");
10766
+ crypto = createActionFrameCrypto({
10767
+ link: this._security.link,
10768
+ keyMaterial: ticket.keyMaterial
10769
+ });
10770
+ try {
10771
+ const plain = await crypto.decryptFrame(base64ToBytes(request.c));
10772
+ wire = JSON.parse(textDecoder.decode(plain));
10773
+ } catch {
10774
+ return refused("undecryptable act");
10775
+ }
10776
+ } else {
10777
+ if ("c" in request) return refused("session is not encrypted");
10778
+ wire = request.w;
10779
+ }
10451
10780
  } else {
10452
10781
  if (!this._noneAllowed || "c" in request) return {
10453
10782
  k: "err",
@@ -10465,7 +10794,7 @@ var WireExchangeAcceptor = class {
10465
10794
  k: "err",
10466
10795
  message: laneReply.message
10467
10796
  };
10468
- if (crypto != null && "c" in request) return {
10797
+ if (crypto != null) return {
10469
10798
  k: "act",
10470
10799
  c: bytesToBase64(await crypto.encryptFrame(textEncoder.encode(JSON.stringify(laneReply.wire))))
10471
10800
  };
@@ -10481,6 +10810,13 @@ var WireExchangeAcceptor = class {
10481
10810
  });
10482
10811
  }
10483
10812
  };
10813
+ function refused(message) {
10814
+ return {
10815
+ k: "err",
10816
+ message,
10817
+ id: WIRE_EXCHANGE_SESSION_REFUSED
10818
+ };
10819
+ }
10484
10820
  //#endregion
10485
10821
  //#region ../nice-wire/src/codec/controlFrame.ts
10486
10822
  /** msgpack map (object) first-byte prefixes — fixmap `0x80–0x8f`, map16 `0xde`, map32 `0xdf`. */
@@ -16874,6 +17210,7 @@ function transport(options) {
16874
17210
  link,
16875
17211
  localCoordinate: (options.identity ?? options.runtime.coordinate).toJsonObject(),
16876
17212
  expectedPeer: options.expectedPeer?.toJsonObject(),
17213
+ reuseExchangeSessions: options.reuseExchangeSessions,
16877
17214
  dictionaryVersion: channel.dictionaryVersion,
16878
17215
  channelTags: channel.tags,
16879
17216
  mux: options.mux
@@ -17041,6 +17378,7 @@ function connectChannel(runtime, channel, options) {
17041
17378
  secure: descriptor.secure ?? true,
17042
17379
  link,
17043
17380
  securityLevel: descriptor.securityLevel ?? securityLevel,
17381
+ reuseExchangeSessions: options.reuseExchangeSessions,
17044
17382
  available: descriptor.available,
17045
17383
  label: descriptor.label,
17046
17384
  mux: wireMux,
@@ -24430,7 +24768,8 @@ function commanderStatePaths(dataDir, configKey) {
24430
24768
  ingestSeqPath: join(stateDir, "ingest-seq"),
24431
24769
  envOverridesPath: join(stateDir, "env-overrides.json"),
24432
24770
  savedFiltersPath: join(stateDir, "saved-filters.json"),
24433
- lastStartsPath: join(stateDir, "last-starts.json")
24771
+ lastStartsPath: join(stateDir, "last-starts.json"),
24772
+ taskDurationsPath: join(stateDir, "task-durations.json")
24434
24773
  };
24435
24774
  }
24436
24775
  async function ensureStateDir(paths) {
@@ -24495,6 +24834,8 @@ const commanderStatusRealm = defineRealm({
24495
24834
  pid: t.optional(t.number()),
24496
24835
  startedAt: t.optional(t.number()),
24497
24836
  lastStartedAt: t.optional(t.number()),
24837
+ flags: t.array(t.string()),
24838
+ estimatedMs: t.optional(t.number()),
24498
24839
  sawOutputAt: t.optional(t.number()),
24499
24840
  lastTask: t.optional(t.object({
24500
24841
  outcome: t.string(),
@@ -24551,6 +24892,11 @@ const commanderStatusRealm = defineRealm({
24551
24892
  values: t.optional(t.array(t.string())),
24552
24893
  source: t.string(),
24553
24894
  value: t.optional(t.string())
24895
+ })),
24896
+ flags: t.array(t.object({
24897
+ name: t.string(),
24898
+ args: t.string(),
24899
+ description: t.optional(t.string())
24554
24900
  }))
24555
24901
  })
24556
24902
  })),
@@ -24710,7 +25056,7 @@ var CommanderDaemonBootError = class extends Error {
24710
25056
  * a live dev environment, and an upgrade must never be the thing that kills one.
24711
25057
  */
24712
25058
  async function replaceSkewedDaemon(paths, skewed) {
24713
- 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" : ""})`;
25059
+ 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" : ""})`;
24714
25060
  let liveIds;
24715
25061
  try {
24716
25062
  liveIds = (await openProcessLedger({
@@ -24940,8 +25286,50 @@ function checkStart(value) {
24940
25286
  if (wait != null) input.wait = wait;
24941
25287
  if (staggerMs != null) input.staggerMs = staggerMs;
24942
25288
  if (replaceSame != null) input.replaceSame = replaceSame;
25289
+ if (record["flags"] != null) {
25290
+ const flags = checkFlagsById(record["flags"]);
25291
+ if (typeof flags === "string") return `flags${flags}`;
25292
+ input.flags = flags;
25293
+ }
24943
25294
  return input;
24944
25295
  }
25296
+ function checkFlagsById(value) {
25297
+ const record = asRecord(value);
25298
+ if (record == null) return ": expected an object keyed by process id";
25299
+ const checked = {};
25300
+ for (const [id, names] of Object.entries(record)) {
25301
+ const list = asIdList(names);
25302
+ if (list == null) return `[${JSON.stringify(id)}]: expected an array of flag names`;
25303
+ checked[id] = list;
25304
+ }
25305
+ return checked;
25306
+ }
25307
+ function checkNoteRuns(value) {
25308
+ const runs = asRecord(value)?.["runs"];
25309
+ if (!Array.isArray(runs)) return "runs: expected an array";
25310
+ const checked = [];
25311
+ for (const entry of runs) {
25312
+ const run = asRecord(entry);
25313
+ if (run == null) return "runs: expected objects";
25314
+ const { id, startedAt, durationMs } = run;
25315
+ const flags = asIdList(run["flags"]);
25316
+ if (typeof id !== "string" || id === "") return "runs: id expected a process id";
25317
+ if (typeof startedAt !== "number" || !Number.isFinite(startedAt)) return "runs: startedAt expected epoch ms";
25318
+ if (flags == null) return "runs: flags expected an array of flag names";
25319
+ if (durationMs != null && (typeof durationMs !== "number" || !(durationMs >= 0))) return "runs: durationMs expected a non-negative number";
25320
+ checked.push(typeof durationMs === "number" ? {
25321
+ id,
25322
+ startedAt,
25323
+ flags,
25324
+ durationMs
25325
+ } : {
25326
+ id,
25327
+ startedAt,
25328
+ flags
25329
+ });
25330
+ }
25331
+ return { runs: checked };
25332
+ }
24945
25333
  function checkSetEnv(value) {
24946
25334
  const record = asRecord(value);
24947
25335
  if (record == null) return "expected an object";
@@ -25133,6 +25521,7 @@ const commanderControlDomain = createActionRootDomain({ domain: "commander" }).c
25133
25521
  saveFilter: actionSchema().input({ schema: handSchema(checkSaveFilter) }).output({ schema: handSchema(checkOk) }),
25134
25522
  removeFilter: actionSchema().input({ schema: handSchema(checkRemoveFilter) }).output({ schema: handSchema(checkOk) }),
25135
25523
  setEnv: actionSchema().input({ schema: handSchema(checkSetEnv) }).output({ schema: handSchema(checkEnvReport) }),
25524
+ noteRuns: actionSchema().input({ schema: handSchema(checkNoteRuns) }).output({ schema: handSchema(checkOk) }),
25136
25525
  reloadConfig: actionSchema().input({ schema: handSchema(checkEmpty) }).output({ schema: handSchema(checkReloadResult) }),
25137
25526
  shutdown: actionSchema().input({ schema: handSchema(checkEmpty) }).output({ schema: handSchema(checkOk) })
25138
25527
  }
@@ -25178,7 +25567,7 @@ async function findDaemon(config) {
25178
25567
  async function findSkewedDaemon(config) {
25179
25568
  const skewed = await readSkewedInstanceRecord(commanderStatePaths(resolveCommanderDataDir(), config.configKey).instanceRecordPath, commanderStatusRealm.schemaHash);
25180
25569
  if (skewed == null || !pidAlive$1(skewed.pid)) return null;
25181
- const difference = skewed.skew === "protocol" ? `speaks protocol v${skewed.protocolVersion}; this build speaks v7` : "was started before an upgrade changed the status schema";
25570
+ const difference = skewed.skew === "protocol" ? `speaks protocol v${skewed.protocolVersion}; this build speaks v8` : "was started before an upgrade changed the status schema";
25182
25571
  return {
25183
25572
  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.`,
25184
25573
  pid: skewed.pid,
@@ -25288,7 +25677,7 @@ async function connectDaemon(handle) {
25288
25677
  const payload = await (await runtime.handleActionPayload(request)).waitForResultPayload();
25289
25678
  if (!payload.result.ok) throw new CliExit(EXIT.failure, `action "${action}" rejected by the daemon`);
25290
25679
  const report = parseActionReport(payload.result.output);
25291
- if (report == null) throw new CliExit(EXIT.failure, `the daemon answered "${action}" with something this CLI does not recognise — protocol ${record.protocolVersion} vs 7`);
25680
+ if (report == null) throw new CliExit(EXIT.failure, `the daemon answered "${action}" with something this CLI does not recognise — protocol ${record.protocolVersion} vs 8`);
25292
25681
  return report;
25293
25682
  },
25294
25683
  setEnv: async (input) => {
@@ -25298,6 +25687,10 @@ async function connectDaemon(handle) {
25298
25687
  const warnings = payload.result.output.warnings;
25299
25688
  return Array.isArray(warnings) ? warnings.filter((entry) => typeof entry === "string") : [];
25300
25689
  },
25690
+ noteRuns: async (input) => {
25691
+ const request = commanderControlDomain.actionForId("noteRuns").request(input);
25692
+ if (!(await (await runtime.handleActionPayload(request)).waitForResultPayload()).result.ok) throw new CliExit(EXIT.failure, `action "noteRuns" rejected by the daemon`);
25693
+ },
25301
25694
  shutdown: async () => {
25302
25695
  const request = commanderControlDomain.actionForId("shutdown").request({});
25303
25696
  if (!(await (await runtime.handleActionPayload(request)).waitForResultPayload()).result.ok) throw new CliExit(EXIT.failure, `action "shutdown" rejected by the daemon`);
@@ -25412,11 +25805,13 @@ async function cmdUp(ctx) {
25412
25805
  "--no-wait",
25413
25806
  "--dry-run",
25414
25807
  "--replace-same",
25808
+ "--with",
25415
25809
  "--all",
25416
25810
  "--any"
25417
25811
  ]);
25418
25812
  if (bad != null) throw new CliExit(EXIT.usage, bad);
25419
25813
  const selection = selectOrExit(ctx, { bare: "default" });
25814
+ const flags = flagsOrExit(ctx);
25420
25815
  if (ctx.args.flags.has("--dry-run")) {
25421
25816
  const { out } = ctx;
25422
25817
  if (out.json) out.printJson(selection);
@@ -25441,7 +25836,8 @@ async function cmdUp(ctx) {
25441
25836
  ids: selection.ordered,
25442
25837
  wait,
25443
25838
  ...staggerMs > 0 ? { staggerMs } : {},
25444
- ...replaceSame ? { replaceSame } : {}
25839
+ ...replaceSame ? { replaceSame } : {},
25840
+ ...flags != null ? { flags: { [flags.id]: flags.flags } } : {}
25445
25841
  }));
25446
25842
  return printReport(ctx.out, report, client.state());
25447
25843
  } finally {
@@ -25452,6 +25848,7 @@ async function controlVerb(ctx, verb) {
25452
25848
  const known = verb === "restart" ? [
25453
25849
  "--no-wait",
25454
25850
  "--replace-same",
25851
+ "--with",
25455
25852
  "--all",
25456
25853
  "--any"
25457
25854
  ] : ["--all", "--any"];
@@ -25466,11 +25863,13 @@ async function controlVerb(ctx, verb) {
25466
25863
  extraIds: Object.keys(client.state().processes ?? {}).filter((id) => !declared.has(id))
25467
25864
  });
25468
25865
  const replaceSame = ctx.args.flags.has("--replace-same");
25866
+ const flags = verb === "restart" ? flagsOrExit(ctx) : null;
25469
25867
  const report = await withProgress(client, ctx.out, new Set(selection.ordered), () => verb === "stop" ? client.control("stop", { ids: selection.ordered }) : client.control("restart", {
25470
25868
  ids: selection.ordered,
25471
25869
  wait: !ctx.args.flags.has("--no-wait"),
25472
25870
  staggerMs: staggerFor(ctx.config, ctx.args.positionals),
25473
- ...replaceSame ? { replaceSame } : {}
25871
+ ...replaceSame ? { replaceSame } : {},
25872
+ ...flags != null ? { flags: { [flags.id]: flags.flags } } : {}
25474
25873
  }));
25475
25874
  return printReport(ctx.out, report, client.state());
25476
25875
  } finally {
@@ -25573,7 +25972,7 @@ function reportSignalShutdown(ctx, result, why, reports) {
25573
25972
  }
25574
25973
  //#endregion
25575
25974
  //#region src/daemon/envOverrides.ts
25576
- const STORE_VERSION$1 = 1;
25975
+ const STORE_VERSION$3 = 1;
25577
25976
  /** A knob is a port or a log level, not a payload. Bounds keep a mistake from becoming a file. */
25578
25977
  const MAX_VALUE_LENGTH = 4096;
25579
25978
  const EMPTY_ENV_OVERRIDES = Object.freeze({});
@@ -25609,7 +26008,7 @@ async function writeEnvOverrides(path, overrides) {
25609
26008
  mode: 448
25610
26009
  });
25611
26010
  const store = {
25612
- version: STORE_VERSION$1,
26011
+ version: STORE_VERSION$3,
25613
26012
  processes: Object.fromEntries(Object.entries(overrides).filter(([, values]) => Object.keys(values).length > 0).map(([id, values]) => [id, { ...values }]))
25614
26013
  };
25615
26014
  const temp = `${path}.${process.pid}.tmp`;
@@ -26565,6 +26964,7 @@ async function cmdList(ctx) {
26565
26964
  endpoints: proc.endpoints,
26566
26965
  url: proc.url ?? null,
26567
26966
  envVars: proc.envVars,
26967
+ flags: proc.flags,
26568
26968
  optIn: proc.optIn
26569
26969
  })),
26570
26970
  suites: Object.fromEntries(Object.entries(config.suites).map(([name, { name: _name, ...suite }]) => [name, suite])),
@@ -26626,6 +27026,12 @@ async function cmdExplain(ctx) {
26626
27026
  selection.ordered.forEach((id, index) => {
26627
27027
  out.print(` ${index + 1}. ${id}`);
26628
27028
  });
27029
+ const flagged = ctx.config.processes.filter((proc) => selection.direct.includes(proc.id) && proc.flags.length > 0);
27030
+ if (flagged.length > 0) out.print("flags:");
27031
+ for (const proc of flagged) for (const flag of proc.flags) {
27032
+ const about = flag.description != null ? ` — ${flag.description}` : "";
27033
+ out.print(` ${proc.id} --with ${flag.name} appends ${flag.args.join(" ")}${about}`);
27034
+ }
26629
27035
  if (!ctx.args.flags.has("--env")) {
26630
27036
  out.print(out.paint("gray", "env: `explain <sel> --env` shows each id's spawn environment"));
26631
27037
  return EXIT.ok;
@@ -26878,6 +27284,91 @@ async function cmdLogs(ctx) {
26878
27284
  }
26879
27285
  }
26880
27286
  //#endregion
27287
+ //#region src/daemon/lastStarts.ts
27288
+ const STORE_VERSION$2 = 1;
27289
+ /** Newest first, capped at `MAX_LAST_STARTS`. */
27290
+ function bounded$1(entries) {
27291
+ return Object.fromEntries([...entries].sort(([, a], [, b]) => b - a).slice(0, 256));
27292
+ }
27293
+ /** Missing, unreadable or corrupt all read as "nothing started yet" — never a reason to fail a boot. */
27294
+ async function readLastStarts(path) {
27295
+ try {
27296
+ const parsed = JSON.parse(await readFile(path, "utf8"));
27297
+ if (parsed == null || typeof parsed !== "object" || !("processes" in parsed)) return {};
27298
+ const processes = parsed.processes;
27299
+ if (processes == null || typeof processes !== "object" || Array.isArray(processes)) return {};
27300
+ return bounded$1(Object.entries(processes).filter((entry) => typeof entry[1] === "number" && Number.isFinite(entry[1])));
27301
+ } catch {
27302
+ return {};
27303
+ }
27304
+ }
27305
+ async function writeLastStarts(path, lastStarts) {
27306
+ await mkdir(dirname(path), {
27307
+ recursive: true,
27308
+ mode: 448
27309
+ });
27310
+ const temp = `${path}.${process.pid}.tmp`;
27311
+ const store = {
27312
+ version: STORE_VERSION$2,
27313
+ processes: bounded$1(Object.entries(lastStarts))
27314
+ };
27315
+ await writeFile(temp, `${JSON.stringify(store, null, 2)}\n`, {
27316
+ encoding: "utf8",
27317
+ mode: 384
27318
+ });
27319
+ await rename(temp, path);
27320
+ }
27321
+ //#endregion
27322
+ //#region src/daemon/taskDurations.ts
27323
+ const STORE_VERSION$1 = 1;
27324
+ /** Each flag set keeps its own samples — `dev-reset+hosted` runs as long as it runs, not as `dev-reset`. */
27325
+ function durationKey(id, flags) {
27326
+ return [id, ...flags].join("+");
27327
+ }
27328
+ /** `durations` with one more sample under `key`, which moves to the newest end of the bound. */
27329
+ function withDuration(durations, key, ms) {
27330
+ const samples = [...durations[key] ?? [], ms].slice(-3);
27331
+ const rest = Object.entries(durations).filter(([existing]) => existing !== key);
27332
+ return Object.fromEntries([...rest, [key, samples]].slice(-256));
27333
+ }
27334
+ /** The mean of the samples, or null with nothing to go on. */
27335
+ function estimateMs(samples) {
27336
+ if (samples == null || samples.length === 0) return null;
27337
+ return Math.round(samples.reduce((total, ms) => total + ms, 0) / samples.length);
27338
+ }
27339
+ /** Missing, unreadable or corrupt all read as "no history yet" — never a reason to fail a boot. */
27340
+ async function readTaskDurations(path) {
27341
+ try {
27342
+ const parsed = JSON.parse(await readFile(path, "utf8"));
27343
+ if (parsed == null || typeof parsed !== "object" || !("tasks" in parsed)) return {};
27344
+ const tasks = parsed.tasks;
27345
+ if (tasks == null || typeof tasks !== "object" || Array.isArray(tasks)) return {};
27346
+ const entries = Object.entries(tasks).flatMap(([key, samples]) => {
27347
+ if (!Array.isArray(samples)) return [];
27348
+ const valid = samples.filter((ms) => typeof ms === "number" && Number.isFinite(ms) && ms >= 0);
27349
+ return valid.length > 0 ? [[key, valid.slice(-3)]] : [];
27350
+ });
27351
+ return Object.fromEntries(entries.slice(-256));
27352
+ } catch {
27353
+ return {};
27354
+ }
27355
+ }
27356
+ async function writeTaskDurations(path, durations) {
27357
+ await mkdir(dirname(path), {
27358
+ recursive: true,
27359
+ mode: 448
27360
+ });
27361
+ const temp = `${path}.${process.pid}.tmp`;
27362
+ await writeFile(temp, `${JSON.stringify({
27363
+ version: STORE_VERSION$1,
27364
+ tasks: durations
27365
+ }, null, 2)}\n`, {
27366
+ encoding: "utf8",
27367
+ mode: 384
27368
+ });
27369
+ await rename(temp, path);
27370
+ }
27371
+ //#endregion
26881
27372
  //#region src/run/scheduler.ts
26882
27373
  async function runTaskPool(options) {
26883
27374
  const { failFast } = options;
@@ -26988,6 +27479,36 @@ function startPump(out, proc) {
26988
27479
  }
26989
27480
  };
26990
27481
  }
27482
+ /**
27483
+ * What this run ran reaches the "recently started" order and the task estimates — through the
27484
+ * daemon when one is up (it owns those stores while it runs), else straight into the stores.
27485
+ */
27486
+ async function noteForegroundRuns(config, paths, runs) {
27487
+ if (runs.length === 0) return;
27488
+ try {
27489
+ const handle = await findDaemon(config);
27490
+ if (handle != null) {
27491
+ const client = await connectDaemon(handle);
27492
+ try {
27493
+ await client.noteRuns({ runs: [...runs] });
27494
+ } finally {
27495
+ client.dispose();
27496
+ }
27497
+ return;
27498
+ }
27499
+ let lastStarts = await readLastStarts(paths.lastStartsPath);
27500
+ let durations = await readTaskDurations(paths.taskDurationsPath);
27501
+ for (const run of runs) {
27502
+ if ((lastStarts[run.id] ?? 0) < run.startedAt) lastStarts = {
27503
+ ...lastStarts,
27504
+ [run.id]: run.startedAt
27505
+ };
27506
+ if (run.durationMs != null) durations = withDuration(durations, durationKey(run.id, run.flags), run.durationMs);
27507
+ }
27508
+ await writeLastStarts(paths.lastStartsPath, lastStarts);
27509
+ await writeTaskDurations(paths.taskDurationsPath, durations);
27510
+ } catch {}
27511
+ }
26991
27512
  /** Let the last lines flush, then close every pump — the only way each one is guaranteed to end. */
26992
27513
  async function drainPumps(pumps, graceMs = 250) {
26993
27514
  if (pumps.length === 0) return;
@@ -26999,10 +27520,18 @@ async function cmdRun(ctx) {
26999
27520
  const bad = unknownFlags(ctx.args.flags, [
27000
27521
  "--parallel",
27001
27522
  "--fail-fast",
27523
+ "--with",
27002
27524
  "--all",
27003
27525
  "--any"
27004
27526
  ]);
27005
27527
  if (bad != null) throw new CliExit(EXIT.usage, bad);
27528
+ const flags = flagsOrExit(ctx);
27529
+ const passthrough = ctx.args.passthrough;
27530
+ const target = passthrough.length > 0 ? singleProcessOrExit(ctx, "--") : null;
27531
+ const unquotable = typeof target?.run === "string" ? passthrough.find((arg) => !SHELL_PLAIN_ARG.test(arg)) : void 0;
27532
+ 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`);
27533
+ /** The one id `--with` / `--` select gets its flags' arguments, then the raw ones. */
27534
+ const extraArgs = (id) => [...flags?.id === id ? flags.args : [], ...target?.id === id ? passthrough : []];
27006
27535
  const parallel = numericFlag(ctx.args.flags, "--parallel");
27007
27536
  if (parallel != null && typeof parallel === "object") throw new CliExit(EXIT.usage, parallel.error);
27008
27537
  const selection = selectOrExit(ctx, { bare: "required" });
@@ -27051,7 +27580,7 @@ async function cmdRun(ctx) {
27051
27580
  }
27052
27581
  return createNiceProcess({
27053
27582
  id: def.id,
27054
- run: def.run,
27583
+ run: runWithArgs(def.run, extraArgs(def.id)),
27055
27584
  ...def.shell != null ? { shell: def.shell } : {},
27056
27585
  cwd: def.cwd,
27057
27586
  env: effectiveEnv(def, overrides),
@@ -27093,6 +27622,16 @@ async function cmdRun(ctx) {
27093
27622
  if (await Promise.race([graceful.then(() => true), new Promise((settle) => setTimeout(() => settle(false), TIMEOUT_STOP_GRACE_MS))])) return;
27094
27623
  for (const proc of procs) if (proc.pid != null) forceKillTree(proc.pid);
27095
27624
  };
27625
+ const ran = [];
27626
+ const noteStart = (def) => {
27627
+ const run = {
27628
+ id: def.id,
27629
+ startedAt: Date.now(),
27630
+ flags: flags?.id === def.id ? flags.flags : []
27631
+ };
27632
+ ran.push(run);
27633
+ return run;
27634
+ };
27096
27635
  const runTask = async (def) => {
27097
27636
  const proc = procFor(def.id);
27098
27637
  if (!single) out.print(`${out.paint("cyan", "▸")} ${out.accent(def.id, def.id)} running…`);
@@ -27104,8 +27643,10 @@ async function cmdRun(ctx) {
27104
27643
  });
27105
27644
  let timer = null;
27106
27645
  let timedOut = false;
27646
+ let run = null;
27107
27647
  try {
27108
27648
  await proc.start();
27649
+ run = noteStart(def);
27109
27650
  if (def.timeoutMs != null) {
27110
27651
  timer = setTimeout(() => {
27111
27652
  timedOut = true;
@@ -27134,6 +27675,7 @@ async function cmdRun(ctx) {
27134
27675
  }
27135
27676
  const code = proc.lastExit?.code ?? (proc.state === "succeeded" ? 0 : 1);
27136
27677
  const failed = code !== 0;
27678
+ if (!failed && run != null && passthrough.length === 0) run.durationMs = Date.now() - run.startedAt;
27137
27679
  out.print(failed ? `${out.paint("red", "✗")} ${out.accent(def.id, def.id)} exit ${code}` : `${out.paint("green", "✓")} ${out.accent(def.id, def.id)} ok`);
27138
27680
  return {
27139
27681
  id: def.id,
@@ -27222,6 +27764,7 @@ async function cmdRun(ctx) {
27222
27764
  }
27223
27765
  const proc = procFor(def.id);
27224
27766
  await proc.start();
27767
+ noteStart(def);
27225
27768
  if (!single) out.print(`${out.paint("cyan", "▸")} ${out.accent(def.id, def.id)} started (pid ${proc.pid ?? "?"})`);
27226
27769
  }
27227
27770
  if (services.length > 0 && !(failFast && failures.length > 0)) {
@@ -27244,6 +27787,7 @@ async function cmdRun(ctx) {
27244
27787
  } finally {
27245
27788
  process.removeListener("SIGINT", onSigint);
27246
27789
  await Promise.allSettled(procs.filter((proc) => !TERMINAL_STATES.has(proc.state)).map((proc) => proc.stop()));
27790
+ await noteForegroundRuns(config, paths, ran);
27247
27791
  }
27248
27792
  }
27249
27793
  //#endregion
@@ -27642,16 +28186,19 @@ bare down/restart/logs/run always require a selection — omission never means -
27642
28186
  * block followed by every entry, in this order.
27643
28187
  */
27644
28188
  const COMMAND_HELP = [
27645
- ["up", ` up [sel] [--no-wait] [--dry-run] [--replace-same]
28189
+ ["up", ` up [sel] [--no-wait] [--dry-run] [--replace-same] [--with <flag>]
27646
28190
  start: deps auto-included, DAG order, live progress;
27647
- a ready service prints its URL. --replace-same lets a
28191
+ a ready service prints its URL. --with turns on a
28192
+ flag the selected process declares (repeat it, or
28193
+ a,b) — one id only. --replace-same lets a
27648
28194
  start take an exclusive port from a STRAY — this same
27649
28195
  command in the same cwd, started outside the daemon
27650
28196
  (a stranger on the port still refuses). --json reports
27651
28197
  every id's outcome, state, pid and endpoints as data.`],
27652
28198
  ["down", " down <sel> stop (reverse-DAG order)"],
27653
- ["restart", ` restart <sel> [--no-wait] [--replace-same]
27654
- stop + start`],
28199
+ ["restart", ` restart <sel> [--no-wait] [--replace-same] [--with <flag>]
28200
+ stop + start, with the flags of the run it replaces
28201
+ unless --with names others`],
27655
28202
  ["status", " status [--watch] table from the live status realm"],
27656
28203
  ["logs", " logs <sel> [-f] merged interleaved tail with colored id prefixes"],
27657
28204
  ["list", " list config introspection (processes, suites, warnings)"],
@@ -27660,9 +28207,12 @@ const COMMAND_HELP = [
27660
28207
  ["env", ` env [sel] [--set N=V] [--unset N] declared env vars and their values; --clear drops
27661
28208
  overrides. A set value is STICKY: it applies to every
27662
28209
  later start until cleared, and never restarts anything.`],
27663
- ["run", ` run <sel> [--parallel N] [--fail-fast] foreground, no daemon; tasks = local CI shape
28210
+ ["run", ` run <sel> [--parallel N] [--fail-fast] [--with <flag>] [-- <args>]
28211
+ foreground, no daemon; tasks = local CI shape
27664
28212
  (a suite supplies its own parallel/fail-fast),
27665
28213
  a single id gets raw inherited stdio (interactive).
28214
+ --with turns on declared flags; anything after --
28215
+ is appended to that one id's command as-is.
27666
28216
  --fail-fast = stop at the FIRST failure and stop the
27667
28217
  survivors; without it every task still runs, every
27668
28218
  failure is reported, and the exit code is still
@@ -27752,7 +28302,7 @@ async function withTimeout(ctx, run) {
27752
28302
  async function main() {
27753
28303
  const argv = process.argv.slice(2);
27754
28304
  if (argv[0] === "daemon") {
27755
- const { runCommanderDaemon } = await import("./main-CWWlV2U5.mjs");
28305
+ const { runCommanderDaemon } = await import("./main-DSPhWTfM.mjs");
27756
28306
  return runCommanderDaemon(argv.slice(1));
27757
28307
  }
27758
28308
  const parsed = parseCliArgs(argv);
@@ -27760,6 +28310,10 @@ async function main() {
27760
28310
  process.stderr.write(`nice-commander: ${parsed.error}\n`);
27761
28311
  return EXIT.usage;
27762
28312
  }
28313
+ if (parsed.passthrough.length > 0 && parsed.command !== "run") {
28314
+ 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");
28315
+ return EXIT.usage;
28316
+ }
27763
28317
  if (parsed.help || parsed.command === "help") {
27764
28318
  process.stdout.write(helpFor(parsed.command === "help" ? null : parsed.command));
27765
28319
  return EXIT.ok;
@@ -27797,6 +28351,6 @@ main().then((code) => {
27797
28351
  process.exitCode = EXIT.failure;
27798
28352
  });
27799
28353
  //#endregion
27800
- export { createRealmServerEngine as A, overrideFingerprint as B, commanderRuntimeError as C, resolveCommanderDataDir as D, ensureStateDir as E, createMemoryStorageAdapter_json as F, withDependencies as G, loadCommanderConfigFile as H, wsAcceptorCarrier as I, recordDaemonAlive as J, savedFilterId as K, validateCommanderConfig as L, serveChannel as M, createDefaultServeLogger as N, findDaemonProcesses as O, RuntimeCoordinate as P, effectiveEnv as R, commanderStatusRealm as S, commanderStatePaths as T, orderByDependency as U, hashCanonical as V, stopSetWithDependencies as W, writeInstanceRecord as X, removeInstanceRecord as Y, COMMANDER_LOGS_PATH as _, parseLogsClientMessage as a, COMMANDER_TICKET_PROTOCOL_PREFIX as b, identifyEndpointOwner as c, countOverrides as d, readEnvOverrides as f, COMMANDER_HEALTH_PATH as g, COMMANDER_BOOTSTRAP_PATH as h, runTaskPool as i, httpAcceptorCarrier as j, createRealmAcceptor as k, signalStray as l, commanderControlDomain as m, readSavedFilters as n, ancestors as o, commanderChannel as p, readInstanceRecord as q, writeSavedFilters as r, createPortInspector as s, mutateSavedFilters as t, applyEnvMutation as u, COMMANDER_SHUTDOWN_PATH as v, commanderPackageVersion as w, COMMANDER_WS_PATH as x, COMMANDER_TICKET_PATH as y, envVarViews as z };
28354
+ export { savedFilterId as $, commanderRuntimeError as A, createDefaultServeLogger as B, COMMANDER_HEALTH_PATH as C, COMMANDER_TICKET_PROTOCOL_PREFIX as D, COMMANDER_TICKET_PATH as E, findDaemonProcesses as F, effectiveEnv as G, createMemoryStorageAdapter_json as H, createRealmAcceptor as I, hashCanonical as J, envVarViews as K, createRealmServerEngine as L, commanderStatePaths as M, ensureStateDir as N, COMMANDER_WS_PATH as O, resolveCommanderDataDir as P, withDependencies as Q, httpAcceptorCarrier as R, COMMANDER_BOOTSTRAP_PATH as S, COMMANDER_SHUTDOWN_PATH as T, wsAcceptorCarrier as U, RuntimeCoordinate as V, validateCommanderConfig as W, orderByDependency as X, loadCommanderConfigFile as Y, stopSetWithDependencies as Z, applyEnvMutation as _, durationKey as a, writeInstanceRecord as at, commanderChannel as b, withDuration as c, writeLastStarts as d, resolveFlags as et, parseLogsClientMessage as f, signalStray as g, identifyEndpointOwner as h, runTaskPool as i, removeInstanceRecord as it, commanderPackageVersion as j, commanderStatusRealm as k, writeTaskDurations as l, createPortInspector as m, readSavedFilters as n, readInstanceRecord as nt, estimateMs as o, ancestors as p, overrideFingerprint as q, writeSavedFilters as r, recordDaemonAlive as rt, readTaskDurations as s, mutateSavedFilters as t, runWithArgs as tt, readLastStarts as u, countOverrides as v, COMMANDER_LOGS_PATH as w, commanderControlDomain as x, readEnvOverrides as y, serveChannel as z };
27801
28355
 
27802
28356
  //# sourceMappingURL=cli.mjs.map