@nice-code/commander 0.90.0 → 0.92.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/README.md CHANGED
@@ -47,6 +47,10 @@ bunx nice-commander down dev
47
47
  Every acting command takes the same selector — ids, group names, or `tag=value` terms (AND across
48
48
  terms). `up --dry-run` and `explain` show exactly what would be touched, without touching it.
49
49
 
50
+ The GUI’s **shutdown daemon** button stops every task and service managed by that daemon,
51
+ including processes hidden by filters or groups, then exits the daemon. Confirm the dialog to
52
+ proceed. Run `nice-commander ui` to start it again.
53
+
50
54
  ## What it does that a script does not
51
55
 
52
56
  - **`dependsOn` waits for *ready*, not for *spawned*** — a real readiness contract (port, HTTP,
@@ -64,6 +68,13 @@ terms). `up --dry-run` and `explain` show exactly what would be touched, without
64
68
  Node ≥ 22 or Bun. The web UI is pre-built into the package; Vite and React are not installed on
65
69
  your machine. Built on [`@nice-code/process`](https://www.npmjs.com/package/@nice-code/process).
66
70
 
71
+ `bunx nice-commander` follows the executable's Node shebang, so it still needs Node ≥ 22.
72
+ Use `bunx --bun nice-commander` to explicitly run with Bun. An older Node can serve the UI
73
+ but fail its authenticated WebSocket handshake, leaving the CLI and browser waiting for the
74
+ status realm. After upgrading your runtime, run `nice-commander shutdown` (this stops managed
75
+ processes), then retry, so an existing daemon is replaced too. No extra environment variables
76
+ are needed.
77
+
67
78
  ## Developing the web UI (`bun run dev`)
68
79
 
69
80
  Editing the UI needs a fast loop, so the package ships a dev harness: `bun run dev` (from
package/build/cli.cjs CHANGED
@@ -4922,6 +4922,22 @@ var RuntimeCoordinate = class RuntimeCoordinate {
4922
4922
  withPersistentId(perId) {
4923
4923
  return this.specify({ perId });
4924
4924
  }
4925
+ /**
4926
+ * Derive a **per-connection** identity: same env and persistent id, with `connectionId` folded into
4927
+ * the per-boot `insId`. For a runtime that opens *several duplex links to the same peer* — a store
4928
+ * socket and a jobs socket on one backend — where one identity for both is a silent misroute: an
4929
+ * acceptor binds a connection by the full coordinate string, so two links presenting the same one
4930
+ * are indistinguishable and the peer's return path picks whichever bound first.
4931
+ *
4932
+ * Folding rather than replacing is the point: the runtime's `insId` stays the per-boot epoch
4933
+ * reliable delivery needs (see {@link IRuntimeCoordinateSpecifics.insId}), so a per-connection id may
4934
+ * safely be a *stable* label (`"jobs"`) — it discriminates connections without pinning the epoch.
4935
+ * Reached from `connectChannel`'s `connectionId` option; rarely called directly.
4936
+ */
4937
+ withConnectionId(connectionId) {
4938
+ if (connectionId.length === 0 || /[[\]:~]/.test(connectionId)) throw new Error(`RuntimeCoordinate.withConnectionId: "${connectionId}" is not a usable connection id — it must be non-empty and free of \`[\`, \`]\`, \`:\` and \`~\` (the coordinate's own string-form separators).`);
4939
+ return this.specify({ insId: `${this.insId ?? "_"}~${connectionId}` });
4940
+ }
4925
4941
  constructor({ envId, perId, insId }) {
4926
4942
  this.envId = envId;
4927
4943
  this.perId = perId;
@@ -9201,6 +9217,8 @@ var AcceptorSecureSession = class {
9201
9217
  _pipe;
9202
9218
  _authed = false;
9203
9219
  _plain = false;
9220
+ _handshakeStarted = false;
9221
+ _handshakeFailed = false;
9204
9222
  /** The channel tags the client advertised in its `hello`, captured for the handler's codec selection. */
9205
9223
  _helloChannels;
9206
9224
  /** Serializes inbound processing (handshake + decryption are async). */
@@ -9214,7 +9232,19 @@ var AcceptorSecureSession = class {
9214
9232
  * acceptor and carried through here because only the decrypted frame reveals its lane.
9215
9233
  */
9216
9234
  receive(frame, wireBytes) {
9217
- this._inboundChain = this._inboundChain.then(() => this._receive(frame, wireBytes)).catch((err) => console.error("[ws-server] failed to process inbound frame", err));
9235
+ this._inboundChain = this._inboundChain.then(() => {
9236
+ if (!this._handshakeFailed) return this._receive(frame, wireBytes);
9237
+ }).catch((err) => {
9238
+ console.error("[ws-server] failed to process inbound frame", err);
9239
+ if (!this._handshakeStarted || this._authed || this._handshakeFailed) return;
9240
+ this._handshakeFailed = true;
9241
+ try {
9242
+ this.config.send(encodeHandshakeMessage({
9243
+ t: "reject",
9244
+ reason: "server handshake failed; check server logs"
9245
+ }));
9246
+ } catch {}
9247
+ });
9218
9248
  }
9219
9249
  async _receive(frame, wireBytes) {
9220
9250
  if (this._plain) {
@@ -9235,6 +9265,7 @@ var AcceptorSecureSession = class {
9235
9265
  bytes: wireBytes ?? 0,
9236
9266
  lane: "handshake"
9237
9267
  });
9268
+ this._handshakeStarted = true;
9238
9269
  await this.config.link.initialize();
9239
9270
  if (this._handshake == null) this._handshake = createServerHandshake({
9240
9271
  link: this.config.link,
@@ -13120,6 +13151,13 @@ const RELIABLE_CONNECT_RETRY_MS = 1e3;
13120
13151
  * (so `connectChannel` and a realm-only `createWireClient` are one connection implementation).
13121
13152
  */
13122
13153
  var ChannelConnector = class extends PeerLink {
13154
+ /**
13155
+ * This connection's own identity when it was given one (`connectChannel`'s `connectionId`), used
13156
+ * in place of the local runtime's coordinate as the origin stamped on outgoing frames — matching
13157
+ * the identity the handshake bound, so the peer's return path finds *this* socket. `undefined` ⇒
13158
+ * the connection speaks as the runtime, which is the single-link default.
13159
+ */
13160
+ _connectionIdentity;
13123
13161
  _defaultTimeout;
13124
13162
  _reliableTimeout;
13125
13163
  /**
@@ -13197,15 +13235,16 @@ var ChannelConnector = class extends PeerLink {
13197
13235
  _controlMethods;
13198
13236
  /** Stream-level reliable-delivery observers (see {@link TReliableStreamEvent}). */
13199
13237
  _reliableEventListeners = /* @__PURE__ */ new Set();
13200
- constructor({ runtimeCoordinate: peerSpecifier, transports, defaultTimeout, reliableActionTimeout, wireMux, localCoordinate, securityLevel, keepLinkAlive }) {
13238
+ constructor({ runtimeCoordinate: peerSpecifier, transports, defaultTimeout, reliableActionTimeout, wireMux, localCoordinate, connectionIdentity, securityLevel, keepLinkAlive }) {
13201
13239
  super(peerSpecifier);
13240
+ this._connectionIdentity = connectionIdentity;
13202
13241
  this._defaultTimeout = defaultTimeout ?? 1e4;
13203
13242
  this._reliableTimeout = reliableActionTimeout ?? DEFAULT_RELIABLE_ACTION_TIMEOUT;
13204
13243
  this._wire = new WireClient({
13205
13244
  createManager: (cache) => new ConnectionTransportManager(cache),
13206
13245
  mux: wireMux,
13207
13246
  peer: this.peerClient,
13208
- localCoordinate,
13247
+ localCoordinate: connectionIdentity ?? localCoordinate,
13209
13248
  securityLevel,
13210
13249
  canPush: transports.some((transport) => transport.type === "duplex"),
13211
13250
  keepLinkAlive,
@@ -13243,7 +13282,7 @@ var ChannelConnector = class extends PeerLink {
13243
13282
  * `err_wire_connect`).
13244
13283
  */
13245
13284
  async connect(config) {
13246
- await this._wire.connect({ localCoordinate: config?.targetLocalRuntime?.coordinate });
13285
+ await this._wire.connect({ localCoordinate: this._connectionIdentity ?? config?.targetLocalRuntime?.coordinate });
13247
13286
  }
13248
13287
  /**
13249
13288
  * Tear down the (possibly half-open) duplex link and immediately re-dial it (DESYNC F6 / Phase
@@ -13263,7 +13302,8 @@ var ChannelConnector = class extends PeerLink {
13263
13302
  }
13264
13303
  async handleActionRequest(action, config) {
13265
13304
  const localRuntime = config?.targetLocalRuntime ?? ActionRuntime.getDefault();
13266
- const localClient = localRuntime.coordinate;
13305
+ const localClient = this._connectionIdentity ?? localRuntime.coordinate;
13306
+ if (this._connectionIdentity != null) action.context._setOriginClient(this._connectionIdentity);
13267
13307
  const incomingTimeout = config?.timeout ?? this._defaultTimeout;
13268
13308
  const parentCuid = peekHandlerCuid();
13269
13309
  const callSite = action._callSite ?? (/* @__PURE__ */ new Error()).stack;
@@ -13563,7 +13603,7 @@ var ChannelConnector = class extends PeerLink {
13563
13603
  * Returns `true` if the payload was sent, `false` if no suitable transport was available.
13564
13604
  */
13565
13605
  async sendReturnPayload(payload, config) {
13566
- const localClient = config.targetLocalRuntime.coordinate;
13606
+ const localClient = this._connectionIdentity ?? config.targetLocalRuntime.coordinate;
13567
13607
  try {
13568
13608
  const { methods } = await this._wire.getReadyTransport({
13569
13609
  action: payload,
@@ -13819,6 +13859,7 @@ var ActionRuntime = class {
13819
13859
  reliableActionTimeout: options.reliableActionTimeout,
13820
13860
  wireMux: options.wireMux,
13821
13861
  localCoordinate: this.coordinate,
13862
+ connectionIdentity: options.connectionIdentity,
13822
13863
  securityLevel: options.securityLevel,
13823
13864
  keepLinkAlive: options.keepLinkAlive
13824
13865
  });
@@ -15904,7 +15945,7 @@ function transport(options) {
15904
15945
  security = {
15905
15946
  securityLevel: options.securityLevel ?? "authenticated",
15906
15947
  link,
15907
- localCoordinate: options.runtime.coordinate.toJsonObject(),
15948
+ localCoordinate: (options.identity ?? options.runtime.coordinate).toJsonObject(),
15908
15949
  dictionaryVersion: channel.dictionaryVersion,
15909
15950
  channelTags: channel.tags,
15910
15951
  mux: options.mux
@@ -15985,6 +16026,34 @@ function defineChannel(options = {}) {
15985
16026
  };
15986
16027
  }
15987
16028
  /**
16029
+ * Identities already dialled per (runtime, peer) — the check behind the several-links-one-identity
16030
+ * warning below. Keyed off the runtime weakly so a torn-down runtime takes its entry with it.
16031
+ */
16032
+ const dialledIdentities = /* @__PURE__ */ new WeakMap();
16033
+ /**
16034
+ * The several-duplex-links trap (Vibenode feedback §1): a second `connectChannel` from one runtime to
16035
+ * one peer presenting the *same* identity is invisible to the acceptor — it binds connections by the
16036
+ * full coordinate string — so replies and pushes for both links go back over whichever bound first and
16037
+ * the other socket's traffic hangs until it times out. Silent, and it looks like a backend stall.
16038
+ *
16039
+ * Warn at dial time rather than at the misroute: this fires deterministically at setup, before any
16040
+ * traffic, and names the fix. Duplex connections only — the caller gates on that.
16041
+ */
16042
+ function warnOnSharedConnectionIdentity(runtime, peer, identity) {
16043
+ let byPeer = dialledIdentities.get(runtime);
16044
+ if (byPeer == null) {
16045
+ byPeer = /* @__PURE__ */ new Map();
16046
+ dialledIdentities.set(runtime, byPeer);
16047
+ }
16048
+ const identities = byPeer.get(peer.stringId) ?? /* @__PURE__ */ new Set();
16049
+ byPeer.set(peer.stringId, identities);
16050
+ if (identities.has(identity.stringId)) {
16051
+ console.warn(`connectChannel: this runtime already has a connection to [${peer.stringId}] dialling as [${identity.stringId}]. The peer binds each connection by that identity, so it cannot tell the two apart: every reply and push for both goes back over whichever connected first, and the other link's traffic hangs until it times out. Give each connection its own \`connectionId\` (e.g. \`connectChannel(runtime, jobsChannel, { connectionId: "jobs", … })\`) — or, if they carry the same routes over one link, use \`connectChannels\`.`);
16052
+ return;
16053
+ }
16054
+ identities.add(identity.stringId);
16055
+ }
16056
+ /**
15988
16057
  * Open a connection to a peer from a single call — the dial-out dual of `serveChannel`. The channel is
15989
16058
  * the single source of truth for *what* is routed (`toAcceptor` domains forwarded to the peer,
15990
16059
  * `toConnector` pushes handled locally from `onPush`); the call binds the shared facts — the channel's
@@ -16004,10 +16073,12 @@ function defineChannel(options = {}) {
16004
16073
  function connectChannel(runtime, channel, options) {
16005
16074
  const securityLevel = options.securityLevel ?? "authenticated";
16006
16075
  const anySecure = options.transports.some((transport) => transport.secure ?? true);
16076
+ const connectionIdentity = options.connectionId != null ? runtime.coordinate.withConnectionId(options.connectionId) : void 0;
16077
+ if (options.transports.some((descriptor) => !isExchangeCarrierSource(descriptor.carrier))) warnOnSharedConnectionIdentity(runtime, options.peer, connectionIdentity ?? runtime.coordinate);
16007
16078
  const { mux: wireMux, link, resolveLinkKeepalive, wireTap } = assembleWireConnectionParts({
16008
16079
  callerName: "connectChannel",
16009
16080
  peer: options.peer,
16010
- identity: runtime.coordinate,
16081
+ identity: connectionIdentity ?? runtime.coordinate,
16011
16082
  mux: options.wireMux,
16012
16083
  protocols: options.protocols,
16013
16084
  anySecure,
@@ -16023,6 +16094,7 @@ function connectChannel(runtime, channel, options) {
16023
16094
  carrier: descriptor.carrier,
16024
16095
  channel,
16025
16096
  runtime,
16097
+ identity: connectionIdentity,
16026
16098
  secure: descriptor.secure ?? true,
16027
16099
  link,
16028
16100
  securityLevel: descriptor.securityLevel ?? securityLevel,
@@ -16044,7 +16116,8 @@ function connectChannel(runtime, channel, options) {
16044
16116
  reliableActionTimeout: options.reliableActionTimeout,
16045
16117
  wireMux,
16046
16118
  securityLevel: connectionSecurityLevel,
16047
- keepLinkAlive: options.keepLinkAlive
16119
+ keepLinkAlive: options.keepLinkAlive,
16120
+ connectionIdentity
16048
16121
  });
16049
16122
  if (options.onReliableEvent != null) handler.addReliableEventListener(options.onReliableEvent);
16050
16123
  if (options.onLinkEvent != null) handler.addLinkEventListener(options.onLinkEvent);
@@ -23275,6 +23348,13 @@ async function commanderPackageVersion() {
23275
23348
  return cached;
23276
23349
  }
23277
23350
  //#endregion
23351
+ //#region src/daemon/runtime.ts
23352
+ /** Check before advertising a daemon whose HTTP works but whose wire handshake cannot run. */
23353
+ function commanderRuntimeError() {
23354
+ const runtime = process.versions.bun == null ? `Node ${process.version}` : `Bun ${process.versions.bun}`;
23355
+ if (process.versions.bun == null && Number(process.versions.node.split(".")[0]) < 22 || globalThis.crypto?.subtle == null || typeof globalThis.WebSocket !== "function") return `nice-commander requires Node >=22 or a current Bun with Web Crypto and WebSocket support; running ${runtime} (${process.execPath}). Upgrade Node, or run \`bunx --bun nice-commander\`. Plain \`bunx\` follows the binary's node shebang. If a daemon is already running, run \`nice-commander shutdown\` before retrying; shutdown stops its managed processes.`;
23356
+ }
23357
+ //#endregion
23278
23358
  //#region src/protocol/statusRealm.ts
23279
23359
  /**
23280
23360
  * Read-only viewer for every authenticated identity — control authority lives in the ticket
@@ -23508,6 +23588,8 @@ async function replaceSkewedDaemon(paths, skewed) {
23508
23588
  }
23509
23589
  }
23510
23590
  async function ensureDaemon(options) {
23591
+ const runtimeError = commanderRuntimeError();
23592
+ if (runtimeError != null) throw new Error(runtimeError);
23511
23593
  const dataDir = options.dataDir != null ? (0, node_path.resolve)(options.dataDir) : resolveCommanderDataDir();
23512
23594
  const paths = commanderStatePaths(dataDir, options.config.configKey);
23513
23595
  const timeoutMs = options.handshakeTimeoutMs ?? HANDSHAKE_TIMEOUT_MS;
@@ -23782,6 +23864,20 @@ const commanderChannel = defineChannel({
23782
23864
  toConnector: []
23783
23865
  });
23784
23866
  //#endregion
23867
+ //#region src/protocol/waitForStatusRealm.ts
23868
+ /** Retain cold-start retries, but report a failed dial instead of hiding it behind hydration. */
23869
+ async function waitForStatusRealm(connector, realm, timeoutMs) {
23870
+ let connectionError;
23871
+ connector.connect().catch((error) => {
23872
+ connectionError = error;
23873
+ });
23874
+ try {
23875
+ await realm.whenLive({ timeoutMs });
23876
+ } catch (error) {
23877
+ throw realm.attachError ?? connectionError ?? error;
23878
+ }
23879
+ }
23880
+ //#endregion
23785
23881
  //#region src/cli/daemonClient.ts
23786
23882
  /** The running daemon for this config, or null (dead record, failed ping, nothing on disk). */
23787
23883
  async function findDaemon(config) {
@@ -23848,6 +23944,8 @@ async function mintTicket(record) {
23848
23944
  return body.ticket;
23849
23945
  }
23850
23946
  async function connectDaemon(handle) {
23947
+ const runtimeError = commanderRuntimeError();
23948
+ if (runtimeError != null) throw new CliExit(EXIT.failure, runtimeError);
23851
23949
  const { record } = handle;
23852
23950
  if (record.realmSchemaHash !== commanderStatusRealm.schemaHash) throw new CliExit(EXIT.failure, `the daemon for this config (pid ${record.pid}, build ${record.packageVersion}) was started before an upgrade changed the status schema — this CLI (build ${await commanderPackageVersion()}) cannot read its state. Run \`nice-commander shutdown\` (it stops a daemon from any build), then retry.`);
23853
23951
  const ticket = await mintTicket(record);
@@ -23881,12 +23979,12 @@ async function connectDaemon(handle) {
23881
23979
  connection: realmConnection(connector),
23882
23980
  assertOnAttach: () => {}
23883
23981
  });
23884
- connector.connect().catch(() => {});
23885
23982
  try {
23886
- await realm.whenLive({ timeoutMs: 1e4 });
23887
- } catch {
23983
+ await waitForStatusRealm(connector, realm, 1e4);
23984
+ } catch (error) {
23985
+ realm.detach();
23888
23986
  connector.dispose();
23889
- const reason = realm.attachError != null ? String(realm.attachError) : "timeout";
23987
+ const reason = String(error);
23890
23988
  const hint = reason.includes("schema_mismatch") ? ` The daemon (pid ${record.pid}, build ${record.packageVersion}) and this CLI were built from different realm definitions — run \`nice-commander shutdown\` (it stops a daemon from any build), then retry.` : "";
23891
23989
  throw new CliExit(EXIT.failure, `could not attach the status realm (${reason}).${hint}`);
23892
23990
  }
@@ -25468,7 +25566,7 @@ async function withTimeout(ctx, run) {
25468
25566
  async function main() {
25469
25567
  const argv = process.argv.slice(2);
25470
25568
  if (argv[0] === "daemon") {
25471
- const { runCommanderDaemon } = await Promise.resolve().then(() => require("./main-Cf9OmhIY.cjs"));
25569
+ const { runCommanderDaemon } = await Promise.resolve().then(() => require("./main-B_0GjEIc.cjs"));
25472
25570
  return runCommanderDaemon(argv.slice(1));
25473
25571
  }
25474
25572
  const parsed = parseCliArgs(argv);
@@ -25524,6 +25622,7 @@ exports.applyEnvMutation = applyEnvMutation;
25524
25622
  exports.commanderChannel = commanderChannel;
25525
25623
  exports.commanderControlDomain = commanderControlDomain;
25526
25624
  exports.commanderPackageVersion = commanderPackageVersion;
25625
+ exports.commanderRuntimeError = commanderRuntimeError;
25527
25626
  exports.commanderStatePaths = commanderStatePaths;
25528
25627
  exports.commanderStatusRealm = commanderStatusRealm;
25529
25628
  exports.countOverrides = countOverrides;