@nice-code/commander 0.70.2 → 0.71.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
@@ -20,6 +20,12 @@ var __require = /* @__PURE__ */ createRequire(import.meta.url);
20
20
  //#region src/cli/args.ts
21
21
  const GLOBAL_VALUE_FLAGS = new Set(["--config", "--timeout"]);
22
22
  /**
23
+ * Flags that ACCUMULATE instead of overwriting. `env --set A=1 --set B=2` has to mean both, and a
24
+ * plain Map keeps only the last. The name still lands in `flags` so `unknownFlags` keeps rejecting
25
+ * it on every command that does not accept it.
26
+ */
27
+ const REPEATABLE_VALUE_FLAGS = new Set(["--set", "--unset"]);
28
+ /**
23
29
  * Per-command flags that take a VALUE. Everything else is boolean — and that distinction is
24
30
  * load-bearing: a greedy "consume the next token" parse turned `up --no-wait demo` into
25
31
  * `--no-wait="demo"` with NO positionals, which fell through to `defaultSelection` and started
@@ -28,6 +34,7 @@ const GLOBAL_VALUE_FLAGS = new Set(["--config", "--timeout"]);
28
34
  const COMMAND_VALUE_FLAGS = new Set(["--parallel"]);
29
35
  function parseCliArgs(argv) {
30
36
  const flags = /* @__PURE__ */ new Map();
37
+ const repeated = /* @__PURE__ */ new Map();
31
38
  const positionals = [];
32
39
  let command = null;
33
40
  let json = false;
@@ -59,6 +66,16 @@ function parseCliArgs(argv) {
59
66
  else help = true;
60
67
  continue;
61
68
  }
69
+ if (REPEATABLE_VALUE_FLAGS.has(arg)) {
70
+ const value = inlineValue ?? argv[i + 1];
71
+ if (value == null || value.startsWith("--")) return { error: `flag ${arg} needs a value` };
72
+ const values = repeated.get(arg) ?? [];
73
+ values.push(value);
74
+ repeated.set(arg, values);
75
+ flags.set(arg, value);
76
+ if (inlineValue == null) i += 1;
77
+ continue;
78
+ }
62
79
  if (arg.startsWith("--")) {
63
80
  if (inlineValue != null) {
64
81
  flags.set(arg, inlineValue);
@@ -88,7 +105,8 @@ function parseCliArgs(argv) {
88
105
  json,
89
106
  noColor,
90
107
  help,
91
- flags
108
+ flags,
109
+ repeated
92
110
  };
93
111
  if (configPath != null) args.configPath = configPath;
94
112
  if (timeoutMs != null) args.timeoutMs = timeoutMs;
@@ -319,6 +337,148 @@ function hashCanonical(value, length = 16) {
319
337
  function configKeyFor(name, configRealpath) {
320
338
  return `${name}-${hashCanonical(configRealpath, 8)}`;
321
339
  }
340
+ //#endregion
341
+ //#region src/config/envVars.ts
342
+ /**
343
+ * Names that hold credentials often enough that publishing one by accident is the bigger risk.
344
+ * Matched case-insensitively; `secret: false` is the explicit opt-out.
345
+ */
346
+ const SECRET_NAME = /(^|_)(SECRETS?|TOKENS?|PASSWORD|PASSWD|CREDENTIALS?|APIKEY)|_KEY$/i;
347
+ function looksSecret(name) {
348
+ return SECRET_NAME.test(name);
349
+ }
350
+ /**
351
+ * The overrides that would actually apply to this process. Only DECLARED names survive: an entry
352
+ * for a variable the config no longer declares is inert and never reaches a child. That filter is
353
+ * the safety property behind letting the UI write here at all.
354
+ */
355
+ function appliedOverrides(definition, overrides) {
356
+ const stored = overrides[definition.id];
357
+ const applied = {};
358
+ if (stored == null) return applied;
359
+ for (const declared of definition.envVars) {
360
+ const value = stored[declared.name];
361
+ if (value != null) applied[declared.name] = value;
362
+ }
363
+ return applied;
364
+ }
365
+ /** The env a spawn would use right now: the config's resolved `env` with overrides layered on. */
366
+ function effectiveEnv(definition, overrides) {
367
+ const applied = appliedOverrides(definition, overrides);
368
+ return Object.keys(applied).length === 0 ? definition.env : {
369
+ ...definition.env,
370
+ ...applied
371
+ };
372
+ }
373
+ /** Drift key: two starts share it exactly when they would spawn with the same overrides. */
374
+ function overrideFingerprint(definition, overrides) {
375
+ return hashCanonical(appliedOverrides(definition, overrides), 12);
376
+ }
377
+ function envVarViews(definition, overrides, baseEnv) {
378
+ const applied = appliedOverrides(definition, overrides);
379
+ return definition.envVars.map((declared) => {
380
+ const override = applied[declared.name];
381
+ const source = override != null ? "override" : declared.default != null ? "default" : baseEnv[declared.name] != null ? "inherited" : "unset";
382
+ const value = source === "override" ? override : source === "default" ? declared.default : null;
383
+ const view = {
384
+ name: declared.name,
385
+ secret: declared.secret,
386
+ required: declared.required,
387
+ source
388
+ };
389
+ if (declared.description != null) view.description = declared.description;
390
+ if (declared.values != null) view.values = [...declared.values];
391
+ if (value != null && !declared.secret) view.value = value;
392
+ return view;
393
+ });
394
+ }
395
+ /** A `required` variable with nothing to fill it — a start would run without something it needs. */
396
+ function missingRequired(definition, overrides, baseEnv) {
397
+ return envVarViews(definition, overrides, baseEnv).filter((view) => view.required && view.source === "unset").map((view) => view.name);
398
+ }
399
+ /**
400
+ * Keep only what the config can justify. Setting a value requires a DECLARED variable on a known
401
+ * process — that filter is what makes the UI's write path safe. Removing is always allowed, even
402
+ * for a name or id the config no longer knows: otherwise a stale entry could never be cleared.
403
+ */
404
+ function checkEnvMutations(config, input) {
405
+ const byId = new Map(config.processes.map((proc) => [proc.id, proc]));
406
+ const mutations = {};
407
+ const warnings = [];
408
+ for (const [id, values] of Object.entries(input.processes)) {
409
+ const definition = byId.get(id);
410
+ const accepted = {};
411
+ for (const [name, value] of Object.entries(values)) {
412
+ if (value == null) {
413
+ accepted[name] = null;
414
+ continue;
415
+ }
416
+ if (definition == null) {
417
+ warnings.push(`"${id}": no such process`);
418
+ continue;
419
+ }
420
+ const declared = definition.envVars.find((candidate) => candidate.name === name);
421
+ if (declared == null) {
422
+ warnings.push(`"${id}" does not declare ${name} — add it to \`envVars\` in the config`);
423
+ continue;
424
+ }
425
+ if (declared.values != null && !declared.values.includes(value)) {
426
+ warnings.push(`"${id}" ${name}: expected one of ${declared.values.join(", ")}`);
427
+ continue;
428
+ }
429
+ accepted[name] = value;
430
+ }
431
+ if (Object.keys(accepted).length > 0) mutations[id] = accepted;
432
+ }
433
+ return {
434
+ mutations,
435
+ clear: [...input.clear ?? []],
436
+ warnings
437
+ };
438
+ }
439
+ /**
440
+ * Overrides that moved a value the config also spent on an endpoint. Declaring `PORT` with a
441
+ * default of 3000 and then overriding it to 3005 leaves the endpoint, the readiness probe and
442
+ * every link still on 3000 — the process binds happily and everything pointing at it is wrong.
443
+ * Detected by coincidence of value rather than by the name, so it needs no special case for PORT.
444
+ */
445
+ function overridesOffEndpoint(definition, overrides) {
446
+ const ports = new Set(definition.endpoints.map((endpoint) => endpoint.port));
447
+ const off = [];
448
+ for (const [name, value] of Object.entries(appliedOverrides(definition, overrides))) {
449
+ const declared = definition.envVars.find((candidate) => candidate.name === name)?.default;
450
+ if (declared == null || value === declared || !ports.has(Number(declared))) continue;
451
+ off.push({
452
+ name,
453
+ value,
454
+ port: Number(declared)
455
+ });
456
+ }
457
+ return off;
458
+ }
459
+ /**
460
+ * Stored overrides the config can no longer explain. Deliberately kept rather than pruned — a
461
+ * process renamed mid-edit should not silently eat the value you set — so they are reported by
462
+ * `env` and `doctor` instead, and `--clear` is what removes them.
463
+ */
464
+ function staleOverrides(config, overrides) {
465
+ const byId = new Map(config.processes.map((proc) => [proc.id, proc]));
466
+ const stale = [];
467
+ for (const [id, values] of Object.entries(overrides)) {
468
+ const definition = byId.get(id);
469
+ for (const name of Object.keys(values)) if (definition == null) stale.push({
470
+ id,
471
+ name,
472
+ reason: "unknown process"
473
+ });
474
+ else if (!definition.envVars.some((declared) => declared.name === name)) stale.push({
475
+ id,
476
+ name,
477
+ reason: "not declared"
478
+ });
479
+ }
480
+ return stale;
481
+ }
322
482
  /** C0/DEL/C1 control characters have no business in tag keys/values or env keys. */
323
483
  function hasControlChars(value) {
324
484
  for (let i = 0; i < value.length; i += 1) {
@@ -331,6 +491,39 @@ const MAX_TAGS = 32;
331
491
  function isRecord(value) {
332
492
  return typeof value === "object" && value != null && !Array.isArray(value);
333
493
  }
494
+ /** `=` would split the child's environment block; control chars have no business in a key. */
495
+ function isEnvName(value) {
496
+ return value !== "" && !value.includes("=") && !hasControlChars(value);
497
+ }
498
+ /** The optional half of a declaration, or null when one of its fields was malformed. */
499
+ function readEnvVarFields(declared, name, at, errors) {
500
+ const before = errors.length;
501
+ const description = declared["description"];
502
+ if (description != null && typeof description !== "string") errors.push(`${at}.description: expected a string`);
503
+ const fallback = declared["default"];
504
+ if (fallback != null && typeof fallback !== "string") errors.push(`${at}.default: expected a string (an environment value is always text)`);
505
+ const rawValues = declared["values"];
506
+ let values;
507
+ if (rawValues != null) if (!Array.isArray(rawValues) || rawValues.some((entry) => typeof entry !== "string")) errors.push(`${at}.values: expected an array of strings`);
508
+ else if (rawValues.length === 0) errors.push(`${at}.values: an empty set can never be satisfied`);
509
+ else {
510
+ values = [...rawValues];
511
+ if (typeof fallback === "string" && !values.includes(fallback)) errors.push(`${at}.default: ${JSON.stringify(fallback)} is not one of ${values.join(", ")}`);
512
+ }
513
+ const secret = declared["secret"];
514
+ if (secret != null && typeof secret !== "boolean") errors.push(`${at}.secret: expected a boolean`);
515
+ const required = declared["required"];
516
+ if (required != null && typeof required !== "boolean") errors.push(`${at}.required: expected a boolean`);
517
+ if (errors.length !== before) return null;
518
+ return {
519
+ name,
520
+ ...typeof description === "string" ? { description } : {},
521
+ ...typeof fallback === "string" ? { default: fallback } : {},
522
+ ...values != null ? { values } : {},
523
+ secret: typeof secret === "boolean" ? secret : looksSecret(name),
524
+ required: required === true
525
+ };
526
+ }
334
527
  function isUrlCleanHttp(url) {
335
528
  try {
336
529
  const parsed = new URL(url);
@@ -438,9 +631,34 @@ function validateCommanderConfig(raw, anchor) {
438
631
  if (!existsSync(cwd) || !statSync(cwd).isDirectory()) errors.push(`${at}.cwd: "${proc.cwd}" does not exist or is not a directory`);
439
632
  const env = {};
440
633
  if (proc.env != null) if (!isRecord(proc.env)) errors.push(`${at}.env: expected a record of string | null`);
441
- else for (const [key, value] of Object.entries(proc.env)) if (key === "" || key.includes("=") || hasControlChars(key)) errors.push(`${at}.env: invalid key ${JSON.stringify(key)}`);
634
+ else for (const [key, value] of Object.entries(proc.env)) if (!isEnvName(key)) errors.push(`${at}.env: invalid key ${JSON.stringify(key)}`);
442
635
  else if (typeof value !== "string" && value !== null) errors.push(`${at}.env[${JSON.stringify(key)}]: expected string | null`);
443
636
  else env[key] = value;
637
+ const envVars = [];
638
+ if (proc.envVars != null) if (!Array.isArray(proc.envVars)) errors.push(`${at}.envVars: expected an array of declarations (a fixed map goes in \`env\`)`);
639
+ else for (const [varIndex, declared] of proc.envVars.entries()) {
640
+ const atV = `${at}.envVars[${varIndex}]`;
641
+ if (!isRecord(declared)) {
642
+ errors.push(`${atV}: expected an object`);
643
+ continue;
644
+ }
645
+ const name = declared["name"];
646
+ if (typeof name !== "string" || !isEnvName(name)) {
647
+ errors.push(`${atV}.name: expected an environment variable name`);
648
+ continue;
649
+ }
650
+ if (envVars.some((existing) => existing.name === name)) {
651
+ errors.push(`${atV}.name: duplicate declaration of "${name}"`);
652
+ continue;
653
+ }
654
+ if (name in env) {
655
+ errors.push(`${atV}.name: "${name}" is also in \`env\` — declare it in one place`);
656
+ continue;
657
+ }
658
+ const resolved = readEnvVarFields(declared, name, atV, errors);
659
+ if (resolved != null) envVars.push(resolved);
660
+ }
661
+ for (const declared of envVars) if (declared.default != null) env[declared.name] = declared.default;
444
662
  const tags = {
445
663
  ...config.defaults?.tags,
446
664
  ...proc.tags
@@ -532,6 +750,7 @@ function validateCommanderConfig(raw, anchor) {
532
750
  run: proc.run,
533
751
  ...proc.shell != null ? { shell: proc.shell } : {},
534
752
  env,
753
+ envVars,
535
754
  stdin,
536
755
  tags,
537
756
  dependsOn,
@@ -21921,7 +22140,8 @@ function commanderStatePaths(dataDir, configKey) {
21921
22140
  logsDir: join(stateDir, "logs"),
21922
22141
  upLockPath: join(stateDir, "up.lock"),
21923
22142
  bootLogPath: join(stateDir, "daemon-boot.log"),
21924
- ingestSeqPath: join(stateDir, "ingest-seq")
22143
+ ingestSeqPath: join(stateDir, "ingest-seq"),
22144
+ envOverridesPath: join(stateDir, "env-overrides.json")
21925
22145
  };
21926
22146
  }
21927
22147
  async function ensureStateDir(paths) {
@@ -21958,7 +22178,7 @@ function validStartStamp(value) {
21958
22178
  function isInstanceRecord(value) {
21959
22179
  if (value == null || typeof value !== "object" || Array.isArray(value)) return false;
21960
22180
  const record = value;
21961
- 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) && validStartStamp(record.startStamp) && record.protocolVersion === 1;
22181
+ 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) && validStartStamp(record.startStamp) && record.protocolVersion === 2;
21962
22182
  }
21963
22183
  async function writeInstanceRecord(path, record) {
21964
22184
  await mkdir(dirname(path), {
@@ -22003,7 +22223,7 @@ async function readForeignInstanceRecord(path) {
22003
22223
  const record = parsed;
22004
22224
  if (record["service"] !== "nice-commander") return null;
22005
22225
  if (!boundedInt(record["protocolVersion"], 0, Number.MAX_SAFE_INTEGER)) return null;
22006
- if (record["protocolVersion"] === 1) return null;
22226
+ if (record["protocolVersion"] === 2) return null;
22007
22227
  if (!boundedInt(record["pid"], 1, Number.MAX_SAFE_INTEGER)) return null;
22008
22228
  if (!boundedInt(record["port"], 1, 65535)) return null;
22009
22229
  return {
@@ -22013,6 +22233,15 @@ async function readForeignInstanceRecord(path) {
22013
22233
  packageVersion: boundedString(record["packageVersion"]) ? record["packageVersion"] : "unknown"
22014
22234
  };
22015
22235
  }
22236
+ /** Liveness only — enough to say "something is there", never enough to authorize a kill (C1). */
22237
+ function pidAlive$1(pid) {
22238
+ try {
22239
+ process.kill(pid, 0);
22240
+ return true;
22241
+ } catch (error) {
22242
+ return error.code === "EPERM";
22243
+ }
22244
+ }
22016
22245
  /**
22017
22246
  * Is this record's daemon still the process it claims to be? pid alive AND startStamp equal —
22018
22247
  * an unreadable stamp answers false (a reused pid must never be trusted).
@@ -22045,7 +22274,7 @@ async function pingDaemon(record, timeoutMs = 2e3) {
22045
22274
  //#region src/daemon/lockfile.ts
22046
22275
  const LOCK_RETRY_LIMIT = 250;
22047
22276
  const LOCK_RETRY_MS = 40;
22048
- function pidAlive$1(pid) {
22277
+ function pidAlive(pid) {
22049
22278
  if (!Number.isInteger(pid) || pid <= 0) return false;
22050
22279
  try {
22051
22280
  process.kill(pid, 0);
@@ -22108,7 +22337,7 @@ async function withCommanderLock(path, action) {
22108
22337
  try {
22109
22338
  current = JSON.parse(await readFile(path, "utf8"));
22110
22339
  } catch {}
22111
- if (current?.pid != null && current.id != null && !pidAlive$1(current.pid)) {
22340
+ if (current?.pid != null && current.id != null && !pidAlive(current.pid)) {
22112
22341
  await stealStaleLock(path, current.id);
22113
22342
  continue;
22114
22343
  }
@@ -22163,15 +22392,6 @@ var CommanderDaemonBootError = class extends Error {
22163
22392
  this.name = "CommanderDaemonBootError";
22164
22393
  }
22165
22394
  };
22166
- /** Liveness only — enough to say "something is there", never enough to authorize a kill (C1). */
22167
- function pidAlive(pid) {
22168
- try {
22169
- process.kill(pid, 0);
22170
- return true;
22171
- } catch (error) {
22172
- return error.code === "EPERM";
22173
- }
22174
- }
22175
22395
  async function ensureDaemon(options) {
22176
22396
  const dataDir = options.dataDir != null ? resolve(options.dataDir) : resolveCommanderDataDir();
22177
22397
  const paths = commanderStatePaths(dataDir, options.config.configKey);
@@ -22187,7 +22407,7 @@ async function ensureDaemon(options) {
22187
22407
  }
22188
22408
  if (existing == null) {
22189
22409
  const foreign = await readForeignInstanceRecord(paths.instanceRecordPath);
22190
- if (foreign != null && pidAlive(foreign.pid)) throw new Error(`a nice-commander daemon speaking protocol v${foreign.protocolVersion} (package ${foreign.packageVersion}) is already running for this config — pid ${foreign.pid}, port ${foreign.port}. This build speaks v1 and cannot talk to it. Stop it with that version's \`nice-commander shutdown\`, or end pid ${foreign.pid} yourself; if it is already gone, remove ${paths.instanceRecordPath}.`);
22410
+ if (foreign != null && pidAlive$1(foreign.pid)) throw new Error(`a nice-commander daemon speaking protocol v${foreign.protocolVersion} (package ${foreign.packageVersion}) is already running for this config — pid ${foreign.pid}, port ${foreign.port}. This build speaks v2 and cannot talk to it. Stop it with that version's \`nice-commander shutdown\`, or end pid ${foreign.pid} yourself; if it is already gone, remove ${paths.instanceRecordPath}.`);
22191
22411
  }
22192
22412
  await ensureStateDir(paths);
22193
22413
  const bootFd = openSync(paths.bootLogPath, "w", 384);
@@ -22301,6 +22521,40 @@ function checkStart(value) {
22301
22521
  if (staggerMs != null) input.staggerMs = staggerMs;
22302
22522
  return input;
22303
22523
  }
22524
+ function checkSetEnv(value) {
22525
+ const record = asRecord(value);
22526
+ if (record == null) return "expected an object";
22527
+ const processes = asRecord(record["processes"]);
22528
+ if (processes == null) return "processes: expected an object keyed by process id";
22529
+ const checked = {};
22530
+ for (const [id, values] of Object.entries(processes)) {
22531
+ const entries = asRecord(values);
22532
+ if (entries == null) return `processes[${JSON.stringify(id)}]: expected an object`;
22533
+ const mutations = {};
22534
+ for (const [name, entry] of Object.entries(entries)) {
22535
+ if (entry !== null && typeof entry !== "string") return `processes[${JSON.stringify(id)}][${JSON.stringify(name)}]: expected string | null`;
22536
+ mutations[name] = entry;
22537
+ }
22538
+ checked[id] = mutations;
22539
+ }
22540
+ const clear = record["clear"];
22541
+ if (clear == null) return { processes: checked };
22542
+ const ids = asIdList(clear);
22543
+ return ids == null ? "clear: expected an array of process ids" : {
22544
+ processes: checked,
22545
+ clear: ids
22546
+ };
22547
+ }
22548
+ function checkEnvReport(value) {
22549
+ const record = asRecord(value);
22550
+ if (record == null || record["ok"] !== true) return "expected { ok: true }";
22551
+ const warnings = record["warnings"];
22552
+ if (!Array.isArray(warnings) || !warnings.every((entry) => typeof entry === "string")) return "warnings: expected an array of strings";
22553
+ return {
22554
+ ok: true,
22555
+ warnings
22556
+ };
22557
+ }
22304
22558
  function checkIds(value) {
22305
22559
  const record = asRecord(value);
22306
22560
  if (record == null) return "expected an object";
@@ -22386,6 +22640,7 @@ const commanderControlDomain = createActionRootDomain({ domain: "commander" }).c
22386
22640
  start: actionSchema().input({ schema: handSchema(checkStart) }).output({ schema: handSchema(checkReport) }),
22387
22641
  stop: actionSchema().input({ schema: handSchema(checkIds) }).output({ schema: handSchema(checkReport) }),
22388
22642
  restart: actionSchema().input({ schema: handSchema(checkStart) }).output({ schema: handSchema(checkReport) }),
22643
+ setEnv: actionSchema().input({ schema: handSchema(checkSetEnv) }).output({ schema: handSchema(checkEnvReport) }),
22389
22644
  reloadConfig: actionSchema().input({ schema: handSchema(checkEmpty) }).output({ schema: handSchema(checkReloadResult) }),
22390
22645
  shutdown: actionSchema().input({ schema: handSchema(checkEmpty) }).output({ schema: handSchema((value) => value != null && value.ok === true ? { ok: true } : "expected { ok: true }") })
22391
22646
  }
@@ -22422,6 +22677,7 @@ const commanderStatusRealm = defineRealm({
22422
22677
  })),
22423
22678
  stale: t.boolean(),
22424
22679
  removed: t.boolean(),
22680
+ envDrift: t.boolean(),
22425
22681
  blockedBy: t.optional(t.string()),
22426
22682
  degradedBy: t.array(t.string()),
22427
22683
  unreadyReason: t.optional(t.string()),
@@ -22443,6 +22699,15 @@ const commanderStatusRealm = defineRealm({
22443
22699
  port: t.number(),
22444
22700
  ownership: t.string(),
22445
22701
  url: t.optional(t.string())
22702
+ })),
22703
+ envVars: t.array(t.object({
22704
+ name: t.string(),
22705
+ description: t.optional(t.string()),
22706
+ secret: t.boolean(),
22707
+ required: t.boolean(),
22708
+ values: t.optional(t.array(t.string())),
22709
+ source: t.string(),
22710
+ value: t.optional(t.string())
22446
22711
  }))
22447
22712
  })
22448
22713
  })),
@@ -22466,8 +22731,10 @@ async function findDaemon(config) {
22466
22731
  /** Read-only commands' daemon-or-report: never starts anything, exit 3 when not running. */
22467
22732
  async function requireDaemon(config) {
22468
22733
  const handle = await findDaemon(config);
22469
- if (handle == null) throw new CliExit(EXIT.notRunning, `daemon not running for "${config.name}" (start one with \`up\`)`);
22470
- return handle;
22734
+ if (handle != null) return handle;
22735
+ const foreign = await readForeignInstanceRecord(commanderStatePaths(resolveCommanderDataDir(), config.configKey).instanceRecordPath);
22736
+ if (foreign != null && pidAlive$1(foreign.pid)) throw new CliExit(EXIT.notRunning, `a nice-commander daemon speaking protocol v${foreign.protocolVersion} (package ${foreign.packageVersion}) is running for this config — pid ${foreign.pid}, port ${foreign.port}. This build speaks v2 and cannot read its state. Stop it with that version's \`nice-commander shutdown\`, then \`up\` again.`);
22737
+ throw new CliExit(EXIT.notRunning, `daemon not running for "${config.name}" (start one with \`up\`)`);
22471
22738
  }
22472
22739
  /** `up`/`ui`'s spawn-or-reuse; the daemon child reruns THIS bin (`daemon` subcommand). */
22473
22740
  async function ensureDaemonRunning(config) {
@@ -22546,9 +22813,16 @@ async function connectDaemon(handle) {
22546
22813
  const payload = await (await runtime.handleActionPayload(request)).waitForResultPayload();
22547
22814
  if (!payload.result.ok) throw new CliExit(EXIT.failure, `action "${action}" rejected by the daemon`);
22548
22815
  const report = parseActionReport(payload.result.output);
22549
- if (report == null) throw new CliExit(EXIT.failure, `the daemon answered "${action}" with something this CLI does not recognise — protocol ${record.protocolVersion} vs 1`);
22816
+ if (report == null) throw new CliExit(EXIT.failure, `the daemon answered "${action}" with something this CLI does not recognise — protocol ${record.protocolVersion} vs 2`);
22550
22817
  return report;
22551
22818
  },
22819
+ setEnv: async (input) => {
22820
+ const request = commanderControlDomain.actionForId("setEnv").request(input);
22821
+ const payload = await (await runtime.handleActionPayload(request)).waitForResultPayload();
22822
+ if (!payload.result.ok) throw new CliExit(EXIT.failure, `action "setEnv" rejected by the daemon`);
22823
+ const warnings = payload.result.output.warnings;
22824
+ return Array.isArray(warnings) ? warnings.filter((entry) => typeof entry === "string") : [];
22825
+ },
22552
22826
  shutdown: async () => {
22553
22827
  const request = commanderControlDomain.actionForId("shutdown").request({});
22554
22828
  if (!(await (await runtime.handleActionPayload(request)).waitForResultPayload()).result.ok) throw new CliExit(EXIT.failure, `action "shutdown" rejected by the daemon`);
@@ -22700,6 +22974,85 @@ async function cmdShutdown(ctx) {
22700
22974
  }
22701
22975
  }
22702
22976
  //#endregion
22977
+ //#region src/daemon/envOverrides.ts
22978
+ const STORE_VERSION = 1;
22979
+ /** A knob is a port or a log level, not a payload. Bounds keep a mistake from becoming a file. */
22980
+ const MAX_VALUE_LENGTH = 4096;
22981
+ const EMPTY_ENV_OVERRIDES = Object.freeze({});
22982
+ function readable(value) {
22983
+ if (value == null || typeof value !== "object") return null;
22984
+ const processes = value.processes;
22985
+ if (processes == null || typeof processes !== "object" || Array.isArray(processes)) return null;
22986
+ const clean = {};
22987
+ for (const [id, values] of Object.entries(processes)) {
22988
+ if (values == null || typeof values !== "object" || Array.isArray(values)) continue;
22989
+ const entries = {};
22990
+ for (const [name, entry] of Object.entries(values)) if (typeof entry === "string" && entry.length <= MAX_VALUE_LENGTH) entries[name] = entry;
22991
+ if (Object.keys(entries).length > 0) clean[id] = entries;
22992
+ }
22993
+ return clean;
22994
+ }
22995
+ /**
22996
+ * Missing, unreadable or corrupt all read as "no overrides". A bad file must never block a start:
22997
+ * the config alone is always enough to run, and the surfaces that report overrides say when the
22998
+ * store could not be read.
22999
+ */
23000
+ async function readEnvOverrides(path) {
23001
+ try {
23002
+ return readable(JSON.parse(await readFile(path, "utf8"))) ?? EMPTY_ENV_OVERRIDES;
23003
+ } catch {
23004
+ return EMPTY_ENV_OVERRIDES;
23005
+ }
23006
+ }
23007
+ /** 0600 and atomic — it can hold a token, and a half-written file must never be read as empty. */
23008
+ async function writeEnvOverrides(path, overrides) {
23009
+ await mkdir(dirname(path), {
23010
+ recursive: true,
23011
+ mode: 448
23012
+ });
23013
+ const store = {
23014
+ version: STORE_VERSION,
23015
+ processes: Object.fromEntries(Object.entries(overrides).filter(([, values]) => Object.keys(values).length > 0).map(([id, values]) => [id, { ...values }]))
23016
+ };
23017
+ const temp = `${path}.${process.pid}.tmp`;
23018
+ await writeFile(temp, `${JSON.stringify(store, null, 2)}\n`, {
23019
+ encoding: "utf8",
23020
+ mode: 384
23021
+ });
23022
+ await rename(temp, path);
23023
+ }
23024
+ /** Pure: the store that results from applying `change`. Empty processes are pruned. */
23025
+ function mutateEnvOverrides(current, change) {
23026
+ const next = {};
23027
+ for (const [id, values] of Object.entries(current)) next[id] = { ...values };
23028
+ for (const id of change.clear ?? []) delete next[id];
23029
+ for (const [id, values] of Object.entries(change.mutations ?? {})) {
23030
+ const entries = next[id] ?? {};
23031
+ for (const [name, value] of Object.entries(values)) if (value == null) delete entries[name];
23032
+ else entries[name] = value;
23033
+ if (Object.keys(entries).length > 0) next[id] = entries;
23034
+ else delete next[id];
23035
+ }
23036
+ return next;
23037
+ }
23038
+ /**
23039
+ * Read → check against the config → mutate → write, atomically enough for a file two surfaces
23040
+ * touch. The one implementation behind both writers, so the daemon's `setEnv` and the CLI's
23041
+ * no-daemon path can never diverge on what they accept.
23042
+ */
23043
+ async function applyEnvMutation(path, config, input) {
23044
+ const checked = checkEnvMutations(config, input);
23045
+ const next = mutateEnvOverrides(await readEnvOverrides(path), checked);
23046
+ await writeEnvOverrides(path, next);
23047
+ return {
23048
+ overrides: next,
23049
+ warnings: checked.warnings
23050
+ };
23051
+ }
23052
+ function countOverrides(overrides) {
23053
+ return Object.values(overrides).reduce((total, values) => total + Object.keys(values).length, 0);
23054
+ }
23055
+ //#endregion
22703
23056
  //#region src/cli/commands/doctor.ts
22704
23057
  function formatAge(ms) {
22705
23058
  if (ms < 6e4) return `${Math.round(ms / 1e3)}s`;
@@ -22798,6 +23151,14 @@ async function diagnose(ctx, handle) {
22798
23151
  report.info.push(`ledger quarantine: ${quarantined.length} record(s) a reap refused to kill` + (quarantined.length > recent.length ? ` (newest ${recent.length} shown)` : ""));
22799
23152
  for (const entry of recent) report.warnings.push(`quarantined "${entry.record.id}" (pid ${entry.record.pid}): ${entry.reason} — never killed on an ambiguous identity; verify it yourself before ending it`);
22800
23153
  }
23154
+ const overrides = await readEnvOverrides(paths.envOverridesPath);
23155
+ const overrideCount = countOverrides(overrides);
23156
+ if (overrideCount > 0) report.info.push(`env overrides: ${overrideCount} set in ${paths.envOverridesPath} — they apply to every start (\`nice-commander env\` lists them, \`--clear\` drops them)`);
23157
+ for (const entry of staleOverrides(config, overrides)) report.warnings.push(`env override ${entry.id}.${entry.name} is stored but inert (${entry.reason}) — clear it with \`env ${entry.id} --clear\``);
23158
+ for (const proc of config.processes) {
23159
+ for (const name of missingRequired(proc, overrides, process.env)) report.warnings.push(`"${proc.id}" requires ${name} and nothing supplies it — set it with \`env ${proc.id} --set ${name}=…\``);
23160
+ for (const off of overridesOffEndpoint(proc, overrides)) report.warnings.push(`"${proc.id}" ${off.name}=${off.value} but its endpoint and readiness are still on ${off.port} — it will bind somewhere nothing points at`);
23161
+ }
22801
23162
  const capability = detectCapability();
22802
23163
  report.info.push(`tree ownership: ${capability.treeMechanism}`);
22803
23164
  for (const note of capability.notes) report.warnings.push(note);
@@ -22848,6 +23209,128 @@ async function cmdDoctor(ctx) {
22848
23209
  return EXIT.ok;
22849
23210
  }
22850
23211
  //#endregion
23212
+ //#region src/cli/commands/env.ts
23213
+ /** `NAME=VALUE` for `--set`. */
23214
+ function parseAssignments(values) {
23215
+ const parsed = {};
23216
+ for (const entry of values) {
23217
+ const eq = entry.indexOf("=");
23218
+ if (eq <= 0) return { error: `--set expects NAME=VALUE, got ${JSON.stringify(entry)}` };
23219
+ parsed[entry.slice(0, eq)] = entry.slice(eq + 1);
23220
+ }
23221
+ return parsed;
23222
+ }
23223
+ function parseNames(values) {
23224
+ for (const entry of values) if (entry.includes("=")) return { error: `--unset expects a NAME, got ${JSON.stringify(entry)}` };
23225
+ return [...values];
23226
+ }
23227
+ function describeValue(view) {
23228
+ if (view.secret) return view.source === "unset" ? "-" : "••••••";
23229
+ return view.value ?? (view.source === "inherited" ? "(the daemon's env)" : "-");
23230
+ }
23231
+ function renderProcess(out, definition, views) {
23232
+ out.print(out.paint("bold", definition.id));
23233
+ if (views.length === 0) {
23234
+ out.print(out.paint("gray", " declares no env vars — add `envVars` to the config to tune it"));
23235
+ return;
23236
+ }
23237
+ out.print(out.table([
23238
+ " NAME",
23239
+ "VALUE",
23240
+ "SOURCE",
23241
+ "NOTES"
23242
+ ], views.map((view) => [
23243
+ ` ${view.name}`,
23244
+ describeValue(view),
23245
+ view.source,
23246
+ [
23247
+ view.description,
23248
+ view.required && view.source === "unset" ? out.paint("red", "required, unset") : null,
23249
+ view.values != null ? `one of: ${view.values.join(", ")}` : null
23250
+ ].filter((note) => note != null).join(" · ")
23251
+ ])));
23252
+ }
23253
+ async function cmdEnv(ctx) {
23254
+ const bad = unknownFlags(ctx.args.flags, [
23255
+ "--set",
23256
+ "--unset",
23257
+ "--clear",
23258
+ "--all"
23259
+ ]);
23260
+ if (bad != null) throw new CliExit(EXIT.usage, bad);
23261
+ const sets = parseAssignments(ctx.args.repeated.get("--set") ?? []);
23262
+ if ("error" in sets) throw new CliExit(EXIT.usage, sets.error);
23263
+ const unsets = parseNames(ctx.args.repeated.get("--unset") ?? []);
23264
+ if ("error" in unsets) throw new CliExit(EXIT.usage, unsets.error);
23265
+ const clearing = ctx.args.flags.get("--clear") === true;
23266
+ const mutating = Object.keys(sets).length > 0 || unsets.length > 0 || clearing;
23267
+ const { out, config } = ctx;
23268
+ const paths = commanderStatePaths(resolveCommanderDataDir(), config.configKey);
23269
+ const definitions = mutating || ctx.args.positionals.length > 0 || ctx.args.flags.has("--all") ? idsToDefinitions(ctx, selectOrExit(ctx, { bare: "required" }).direct) : config.processes.filter((proc) => proc.envVars.length > 0);
23270
+ const handle = mutating ? await findDaemon(config) : null;
23271
+ const client = handle == null ? null : await connectDaemon(handle);
23272
+ try {
23273
+ const result = mutating ? await mutate(ctx, paths.envOverridesPath, client, {
23274
+ processes: Object.fromEntries(definitions.map((definition) => [definition.id, {
23275
+ ...sets,
23276
+ ...Object.fromEntries(unsets.map((name) => [name, null]))
23277
+ }])),
23278
+ ...clearing ? { clear: definitions.map((definition) => definition.id) } : {}
23279
+ }) : {
23280
+ overrides: await readEnvOverrides(paths.envOverridesPath),
23281
+ warnings: []
23282
+ };
23283
+ const views = new Map(definitions.map((definition) => [definition.id, envVarViews(definition, result.overrides, process.env)]));
23284
+ const stale = staleOverrides(config, result.overrides);
23285
+ if (out.json) {
23286
+ out.printJson({
23287
+ overridesPath: paths.envOverridesPath,
23288
+ processes: definitions.map((definition) => ({
23289
+ id: definition.id,
23290
+ envVars: views.get(definition.id) ?? []
23291
+ })),
23292
+ stale,
23293
+ warnings: result.warnings
23294
+ });
23295
+ return result.warnings.length > 0 ? EXIT.failure : EXIT.ok;
23296
+ }
23297
+ for (const definition of definitions) {
23298
+ renderProcess(out, definition, views.get(definition.id) ?? []);
23299
+ out.print();
23300
+ }
23301
+ const total = countOverrides(result.overrides);
23302
+ if (total > 0) out.print(out.paint("gray", `${total} sticky override(s) — they apply to every start until \`nice-commander env <sel> --clear\`.`));
23303
+ if (client != null) {
23304
+ const processes = client.state().processes;
23305
+ for (const definition of definitions) {
23306
+ if (processes[definition.id]?.envDrift !== true) continue;
23307
+ out.print(out.paint("yellow", `${definition.id} is running with the previous values — restart it`));
23308
+ }
23309
+ }
23310
+ for (const definition of definitions) for (const off of overridesOffEndpoint(definition, result.overrides)) out.warn(out.paint("yellow", `⚠ ${definition.id} ${off.name}=${off.value} but its endpoint and readiness are still on ${off.port} — it will bind somewhere nothing points at`));
23311
+ for (const entry of stale) out.warn(out.paint("yellow", `⚠ stored override ${entry.id}.${entry.name} is inert (${entry.reason}) — \`env ${entry.id} --clear\` removes it`));
23312
+ for (const warning of result.warnings) out.warn(out.paint("yellow", `⚠ ${warning}`));
23313
+ return result.warnings.length > 0 ? EXIT.failure : EXIT.ok;
23314
+ } finally {
23315
+ client?.dispose();
23316
+ }
23317
+ }
23318
+ function idsToDefinitions(ctx, ids) {
23319
+ return ctx.config.processes.filter((proc) => ids.includes(proc.id));
23320
+ }
23321
+ /**
23322
+ * The daemon owns the store while it is alive, so a live one does the write — two writers would
23323
+ * race, and its in-memory view would go stale the instant we wrote behind its back.
23324
+ */
23325
+ async function mutate(ctx, path, client, input) {
23326
+ if (client == null) return applyEnvMutation(path, ctx.config, input);
23327
+ const warnings = await client.setEnv(input);
23328
+ return {
23329
+ overrides: await readEnvOverrides(path),
23330
+ warnings
23331
+ };
23332
+ }
23333
+ //#endregion
22851
23334
  //#region src/cli/commands/inspect.ts
22852
23335
  async function cmdList(ctx) {
22853
23336
  const bad = unknownFlags(ctx.args.flags, []);
@@ -22865,7 +23348,8 @@ async function cmdList(ctx) {
22865
23348
  tags: proc.tags,
22866
23349
  dependsOn: proc.dependsOn,
22867
23350
  endpoints: proc.endpoints,
22868
- url: proc.url ?? null
23351
+ url: proc.url ?? null,
23352
+ envVars: proc.envVars
22869
23353
  })),
22870
23354
  groups: Object.fromEntries(Object.entries(config.groups).map(([name, group]) => [name, {
22871
23355
  ids: group.ids,
@@ -23233,6 +23717,7 @@ async function cmdRun(ctx) {
23233
23717
  });
23234
23718
  if (parallel != null && !defs.some((def) => def.kind === "task")) out.warn(out.paint("yellow", "note: --parallel applies to tasks; this selection has none — ignored."));
23235
23719
  const paths = commanderStatePaths(resolveCommanderDataDir(), config.configKey);
23720
+ const overrides = await readEnvOverrides(paths.envOverridesPath);
23236
23721
  const ledger = openProcessLedger({
23237
23722
  dir: paths.stateDir,
23238
23723
  namespace: paths.ledgerNamespace,
@@ -23269,7 +23754,7 @@ async function cmdRun(ctx) {
23269
23754
  run: def.run,
23270
23755
  ...def.shell != null ? { shell: def.shell } : {},
23271
23756
  cwd: def.cwd,
23272
- env: def.env,
23757
+ env: effectiveEnv(def, overrides),
23273
23758
  kind: def.kind,
23274
23759
  ...ready != null ? { ready } : {},
23275
23760
  stop: def.stop,
@@ -23479,6 +23964,7 @@ function notesFor(proc) {
23479
23964
  if (proc.degradedBy.length > 0) notes.push(`degraded by ${proc.degradedBy.join(", ")}`);
23480
23965
  if (proc.unreadyReason != null) notes.push(`unready: ${proc.unreadyReason}`);
23481
23966
  if (proc.stale) notes.push("stale (config changed — restart to apply)");
23967
+ if (proc.envDrift) notes.push("env override changed — restart to apply");
23482
23968
  if (proc.removed) notes.push("removed from config");
23483
23969
  if (proc.capability?.degraded === true) notes.push(proc.capability.treeMechanism);
23484
23970
  return notes.join("; ");
@@ -23635,6 +24121,9 @@ commands:
23635
24121
  logs <sel> [-f] merged interleaved tail with colored id prefixes
23636
24122
  list config introspection (processes, groups, warnings)
23637
24123
  explain [sel] expanded ids, auto-included deps, DAG order
24124
+ env [sel] [--set N=V] [--unset N] declared env vars and their values; --clear drops
24125
+ overrides. A set value is STICKY: it applies to every
24126
+ later start until cleared, and never restarts anything.
23638
24127
  run <sel> [--parallel N] [--fail-fast] foreground, no daemon; tasks = local CI shape,
23639
24128
  a single id gets raw inherited stdio (interactive)
23640
24129
  ui ensure the daemon and open the browser (prints URL)
@@ -23652,6 +24141,7 @@ const COMMANDS = {
23652
24141
  logs: cmdLogs,
23653
24142
  list: cmdList,
23654
24143
  explain: cmdExplain,
24144
+ env: cmdEnv,
23655
24145
  run: cmdRun,
23656
24146
  ui: cmdUi,
23657
24147
  doctor: cmdDoctor,
@@ -23689,7 +24179,7 @@ async function withTimeout(ctx, run) {
23689
24179
  async function main() {
23690
24180
  const argv = process.argv.slice(2);
23691
24181
  if (argv[0] === "daemon") {
23692
- const { runCommanderDaemon } = await import("./main-r_PeNn4s.mjs");
24182
+ const { runCommanderDaemon } = await import("./main-BUB2LNcg.mjs");
23693
24183
  return runCommanderDaemon(argv.slice(1));
23694
24184
  }
23695
24185
  const parsed = parseCliArgs(argv);
@@ -23733,6 +24223,6 @@ main().then((code) => {
23733
24223
  process.exitCode = EXIT.failure;
23734
24224
  });
23735
24225
  //#endregion
23736
- export { withDependencies as A, createDefaultServeLogger as C, validateCommanderConfig as D, createMemoryStorageAdapter_json as E, loadCommanderConfigFile as O, serveChannel as S, RuntimeCoordinate as T, resolveCommanderDataDir as _, COMMANDER_BOOTSTRAP_PATH as a, httpAcceptorCarrier as b, COMMANDER_TICKET_PATH as c, readInstanceRecord as d, recordDaemonAlive as f, ensureStateDir as g, commanderStatePaths as h, commanderControlDomain as i, orderByDependency as k, COMMANDER_TICKET_PROTOCOL_PREFIX as l, writeInstanceRecord as m, commanderStatusRealm as n, COMMANDER_HEALTH_PATH as o, removeInstanceRecord as p, commanderChannel as r, COMMANDER_LOGS_PATH as s, parseLogsClientMessage as t, COMMANDER_WS_PATH as u, createRealmAcceptor as v, ActionRuntime as w, wsAcceptorCarrier as x, createRealmServerEngine as y };
24226
+ export { validateCommanderConfig as A, httpAcceptorCarrier as C, ActionRuntime as D, createDefaultServeLogger as E, orderByDependency as F, withDependencies as I, envVarViews as M, overrideFingerprint as N, RuntimeCoordinate as O, loadCommanderConfigFile as P, createRealmServerEngine as S, serveChannel as T, writeInstanceRecord as _, commanderStatusRealm as a, resolveCommanderDataDir as b, COMMANDER_BOOTSTRAP_PATH as c, COMMANDER_TICKET_PATH as d, COMMANDER_TICKET_PROTOCOL_PREFIX as f, removeInstanceRecord as g, recordDaemonAlive as h, readEnvOverrides as i, effectiveEnv as j, createMemoryStorageAdapter_json as k, COMMANDER_HEALTH_PATH as l, readInstanceRecord as m, applyEnvMutation as n, commanderChannel as o, COMMANDER_WS_PATH as p, countOverrides as r, commanderControlDomain as s, parseLogsClientMessage as t, COMMANDER_LOGS_PATH as u, commanderStatePaths as v, wsAcceptorCarrier as w, createRealmAcceptor as x, ensureStateDir as y };
23737
24227
 
23738
24228
  //# sourceMappingURL=cli.mjs.map