@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/build/cli.mjs CHANGED
@@ -4923,6 +4923,22 @@ var RuntimeCoordinate = class RuntimeCoordinate {
4923
4923
  withPersistentId(perId) {
4924
4924
  return this.specify({ perId });
4925
4925
  }
4926
+ /**
4927
+ * Derive a **per-connection** identity: same env and persistent id, with `connectionId` folded into
4928
+ * the per-boot `insId`. For a runtime that opens *several duplex links to the same peer* — a store
4929
+ * socket and a jobs socket on one backend — where one identity for both is a silent misroute: an
4930
+ * acceptor binds a connection by the full coordinate string, so two links presenting the same one
4931
+ * are indistinguishable and the peer's return path picks whichever bound first.
4932
+ *
4933
+ * Folding rather than replacing is the point: the runtime's `insId` stays the per-boot epoch
4934
+ * reliable delivery needs (see {@link IRuntimeCoordinateSpecifics.insId}), so a per-connection id may
4935
+ * safely be a *stable* label (`"jobs"`) — it discriminates connections without pinning the epoch.
4936
+ * Reached from `connectChannel`'s `connectionId` option; rarely called directly.
4937
+ */
4938
+ withConnectionId(connectionId) {
4939
+ 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).`);
4940
+ return this.specify({ insId: `${this.insId ?? "_"}~${connectionId}` });
4941
+ }
4926
4942
  constructor({ envId, perId, insId }) {
4927
4943
  this.envId = envId;
4928
4944
  this.perId = perId;
@@ -9202,6 +9218,8 @@ var AcceptorSecureSession = class {
9202
9218
  _pipe;
9203
9219
  _authed = false;
9204
9220
  _plain = false;
9221
+ _handshakeStarted = false;
9222
+ _handshakeFailed = false;
9205
9223
  /** The channel tags the client advertised in its `hello`, captured for the handler's codec selection. */
9206
9224
  _helloChannels;
9207
9225
  /** Serializes inbound processing (handshake + decryption are async). */
@@ -9215,7 +9233,19 @@ var AcceptorSecureSession = class {
9215
9233
  * acceptor and carried through here because only the decrypted frame reveals its lane.
9216
9234
  */
9217
9235
  receive(frame, wireBytes) {
9218
- this._inboundChain = this._inboundChain.then(() => this._receive(frame, wireBytes)).catch((err) => console.error("[ws-server] failed to process inbound frame", err));
9236
+ this._inboundChain = this._inboundChain.then(() => {
9237
+ if (!this._handshakeFailed) return this._receive(frame, wireBytes);
9238
+ }).catch((err) => {
9239
+ console.error("[ws-server] failed to process inbound frame", err);
9240
+ if (!this._handshakeStarted || this._authed || this._handshakeFailed) return;
9241
+ this._handshakeFailed = true;
9242
+ try {
9243
+ this.config.send(encodeHandshakeMessage({
9244
+ t: "reject",
9245
+ reason: "server handshake failed; check server logs"
9246
+ }));
9247
+ } catch {}
9248
+ });
9219
9249
  }
9220
9250
  async _receive(frame, wireBytes) {
9221
9251
  if (this._plain) {
@@ -9236,6 +9266,7 @@ var AcceptorSecureSession = class {
9236
9266
  bytes: wireBytes ?? 0,
9237
9267
  lane: "handshake"
9238
9268
  });
9269
+ this._handshakeStarted = true;
9239
9270
  await this.config.link.initialize();
9240
9271
  if (this._handshake == null) this._handshake = createServerHandshake({
9241
9272
  link: this.config.link,
@@ -13121,6 +13152,13 @@ const RELIABLE_CONNECT_RETRY_MS = 1e3;
13121
13152
  * (so `connectChannel` and a realm-only `createWireClient` are one connection implementation).
13122
13153
  */
13123
13154
  var ChannelConnector = class extends PeerLink {
13155
+ /**
13156
+ * This connection's own identity when it was given one (`connectChannel`'s `connectionId`), used
13157
+ * in place of the local runtime's coordinate as the origin stamped on outgoing frames — matching
13158
+ * the identity the handshake bound, so the peer's return path finds *this* socket. `undefined` ⇒
13159
+ * the connection speaks as the runtime, which is the single-link default.
13160
+ */
13161
+ _connectionIdentity;
13124
13162
  _defaultTimeout;
13125
13163
  _reliableTimeout;
13126
13164
  /**
@@ -13198,15 +13236,16 @@ var ChannelConnector = class extends PeerLink {
13198
13236
  _controlMethods;
13199
13237
  /** Stream-level reliable-delivery observers (see {@link TReliableStreamEvent}). */
13200
13238
  _reliableEventListeners = /* @__PURE__ */ new Set();
13201
- constructor({ runtimeCoordinate: peerSpecifier, transports, defaultTimeout, reliableActionTimeout, wireMux, localCoordinate, securityLevel, keepLinkAlive }) {
13239
+ constructor({ runtimeCoordinate: peerSpecifier, transports, defaultTimeout, reliableActionTimeout, wireMux, localCoordinate, connectionIdentity, securityLevel, keepLinkAlive }) {
13202
13240
  super(peerSpecifier);
13241
+ this._connectionIdentity = connectionIdentity;
13203
13242
  this._defaultTimeout = defaultTimeout ?? 1e4;
13204
13243
  this._reliableTimeout = reliableActionTimeout ?? DEFAULT_RELIABLE_ACTION_TIMEOUT;
13205
13244
  this._wire = new WireClient({
13206
13245
  createManager: (cache) => new ConnectionTransportManager(cache),
13207
13246
  mux: wireMux,
13208
13247
  peer: this.peerClient,
13209
- localCoordinate,
13248
+ localCoordinate: connectionIdentity ?? localCoordinate,
13210
13249
  securityLevel,
13211
13250
  canPush: transports.some((transport) => transport.type === "duplex"),
13212
13251
  keepLinkAlive,
@@ -13244,7 +13283,7 @@ var ChannelConnector = class extends PeerLink {
13244
13283
  * `err_wire_connect`).
13245
13284
  */
13246
13285
  async connect(config) {
13247
- await this._wire.connect({ localCoordinate: config?.targetLocalRuntime?.coordinate });
13286
+ await this._wire.connect({ localCoordinate: this._connectionIdentity ?? config?.targetLocalRuntime?.coordinate });
13248
13287
  }
13249
13288
  /**
13250
13289
  * Tear down the (possibly half-open) duplex link and immediately re-dial it (DESYNC F6 / Phase
@@ -13264,7 +13303,8 @@ var ChannelConnector = class extends PeerLink {
13264
13303
  }
13265
13304
  async handleActionRequest(action, config) {
13266
13305
  const localRuntime = config?.targetLocalRuntime ?? ActionRuntime.getDefault();
13267
- const localClient = localRuntime.coordinate;
13306
+ const localClient = this._connectionIdentity ?? localRuntime.coordinate;
13307
+ if (this._connectionIdentity != null) action.context._setOriginClient(this._connectionIdentity);
13268
13308
  const incomingTimeout = config?.timeout ?? this._defaultTimeout;
13269
13309
  const parentCuid = peekHandlerCuid();
13270
13310
  const callSite = action._callSite ?? (/* @__PURE__ */ new Error()).stack;
@@ -13564,7 +13604,7 @@ var ChannelConnector = class extends PeerLink {
13564
13604
  * Returns `true` if the payload was sent, `false` if no suitable transport was available.
13565
13605
  */
13566
13606
  async sendReturnPayload(payload, config) {
13567
- const localClient = config.targetLocalRuntime.coordinate;
13607
+ const localClient = this._connectionIdentity ?? config.targetLocalRuntime.coordinate;
13568
13608
  try {
13569
13609
  const { methods } = await this._wire.getReadyTransport({
13570
13610
  action: payload,
@@ -13820,6 +13860,7 @@ var ActionRuntime = class {
13820
13860
  reliableActionTimeout: options.reliableActionTimeout,
13821
13861
  wireMux: options.wireMux,
13822
13862
  localCoordinate: this.coordinate,
13863
+ connectionIdentity: options.connectionIdentity,
13823
13864
  securityLevel: options.securityLevel,
13824
13865
  keepLinkAlive: options.keepLinkAlive
13825
13866
  });
@@ -15905,7 +15946,7 @@ function transport(options) {
15905
15946
  security = {
15906
15947
  securityLevel: options.securityLevel ?? "authenticated",
15907
15948
  link,
15908
- localCoordinate: options.runtime.coordinate.toJsonObject(),
15949
+ localCoordinate: (options.identity ?? options.runtime.coordinate).toJsonObject(),
15909
15950
  dictionaryVersion: channel.dictionaryVersion,
15910
15951
  channelTags: channel.tags,
15911
15952
  mux: options.mux
@@ -15986,6 +16027,34 @@ function defineChannel(options = {}) {
15986
16027
  };
15987
16028
  }
15988
16029
  /**
16030
+ * Identities already dialled per (runtime, peer) — the check behind the several-links-one-identity
16031
+ * warning below. Keyed off the runtime weakly so a torn-down runtime takes its entry with it.
16032
+ */
16033
+ const dialledIdentities = /* @__PURE__ */ new WeakMap();
16034
+ /**
16035
+ * The several-duplex-links trap (Vibenode feedback §1): a second `connectChannel` from one runtime to
16036
+ * one peer presenting the *same* identity is invisible to the acceptor — it binds connections by the
16037
+ * full coordinate string — so replies and pushes for both links go back over whichever bound first and
16038
+ * the other socket's traffic hangs until it times out. Silent, and it looks like a backend stall.
16039
+ *
16040
+ * Warn at dial time rather than at the misroute: this fires deterministically at setup, before any
16041
+ * traffic, and names the fix. Duplex connections only — the caller gates on that.
16042
+ */
16043
+ function warnOnSharedConnectionIdentity(runtime, peer, identity) {
16044
+ let byPeer = dialledIdentities.get(runtime);
16045
+ if (byPeer == null) {
16046
+ byPeer = /* @__PURE__ */ new Map();
16047
+ dialledIdentities.set(runtime, byPeer);
16048
+ }
16049
+ const identities = byPeer.get(peer.stringId) ?? /* @__PURE__ */ new Set();
16050
+ byPeer.set(peer.stringId, identities);
16051
+ if (identities.has(identity.stringId)) {
16052
+ 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\`.`);
16053
+ return;
16054
+ }
16055
+ identities.add(identity.stringId);
16056
+ }
16057
+ /**
15989
16058
  * Open a connection to a peer from a single call — the dial-out dual of `serveChannel`. The channel is
15990
16059
  * the single source of truth for *what* is routed (`toAcceptor` domains forwarded to the peer,
15991
16060
  * `toConnector` pushes handled locally from `onPush`); the call binds the shared facts — the channel's
@@ -16005,10 +16074,12 @@ function defineChannel(options = {}) {
16005
16074
  function connectChannel(runtime, channel, options) {
16006
16075
  const securityLevel = options.securityLevel ?? "authenticated";
16007
16076
  const anySecure = options.transports.some((transport) => transport.secure ?? true);
16077
+ const connectionIdentity = options.connectionId != null ? runtime.coordinate.withConnectionId(options.connectionId) : void 0;
16078
+ if (options.transports.some((descriptor) => !isExchangeCarrierSource(descriptor.carrier))) warnOnSharedConnectionIdentity(runtime, options.peer, connectionIdentity ?? runtime.coordinate);
16008
16079
  const { mux: wireMux, link, resolveLinkKeepalive, wireTap } = assembleWireConnectionParts({
16009
16080
  callerName: "connectChannel",
16010
16081
  peer: options.peer,
16011
- identity: runtime.coordinate,
16082
+ identity: connectionIdentity ?? runtime.coordinate,
16012
16083
  mux: options.wireMux,
16013
16084
  protocols: options.protocols,
16014
16085
  anySecure,
@@ -16024,6 +16095,7 @@ function connectChannel(runtime, channel, options) {
16024
16095
  carrier: descriptor.carrier,
16025
16096
  channel,
16026
16097
  runtime,
16098
+ identity: connectionIdentity,
16027
16099
  secure: descriptor.secure ?? true,
16028
16100
  link,
16029
16101
  securityLevel: descriptor.securityLevel ?? securityLevel,
@@ -16045,7 +16117,8 @@ function connectChannel(runtime, channel, options) {
16045
16117
  reliableActionTimeout: options.reliableActionTimeout,
16046
16118
  wireMux,
16047
16119
  securityLevel: connectionSecurityLevel,
16048
- keepLinkAlive: options.keepLinkAlive
16120
+ keepLinkAlive: options.keepLinkAlive,
16121
+ connectionIdentity
16049
16122
  });
16050
16123
  if (options.onReliableEvent != null) handler.addReliableEventListener(options.onReliableEvent);
16051
16124
  if (options.onLinkEvent != null) handler.addLinkEventListener(options.onLinkEvent);
@@ -23276,6 +23349,13 @@ async function commanderPackageVersion() {
23276
23349
  return cached;
23277
23350
  }
23278
23351
  //#endregion
23352
+ //#region src/daemon/runtime.ts
23353
+ /** Check before advertising a daemon whose HTTP works but whose wire handshake cannot run. */
23354
+ function commanderRuntimeError() {
23355
+ const runtime = process.versions.bun == null ? `Node ${process.version}` : `Bun ${process.versions.bun}`;
23356
+ 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.`;
23357
+ }
23358
+ //#endregion
23279
23359
  //#region src/protocol/statusRealm.ts
23280
23360
  /**
23281
23361
  * Read-only viewer for every authenticated identity — control authority lives in the ticket
@@ -23509,6 +23589,8 @@ async function replaceSkewedDaemon(paths, skewed) {
23509
23589
  }
23510
23590
  }
23511
23591
  async function ensureDaemon(options) {
23592
+ const runtimeError = commanderRuntimeError();
23593
+ if (runtimeError != null) throw new Error(runtimeError);
23512
23594
  const dataDir = options.dataDir != null ? resolve(options.dataDir) : resolveCommanderDataDir();
23513
23595
  const paths = commanderStatePaths(dataDir, options.config.configKey);
23514
23596
  const timeoutMs = options.handshakeTimeoutMs ?? HANDSHAKE_TIMEOUT_MS;
@@ -23783,6 +23865,20 @@ const commanderChannel = defineChannel({
23783
23865
  toConnector: []
23784
23866
  });
23785
23867
  //#endregion
23868
+ //#region src/protocol/waitForStatusRealm.ts
23869
+ /** Retain cold-start retries, but report a failed dial instead of hiding it behind hydration. */
23870
+ async function waitForStatusRealm(connector, realm, timeoutMs) {
23871
+ let connectionError;
23872
+ connector.connect().catch((error) => {
23873
+ connectionError = error;
23874
+ });
23875
+ try {
23876
+ await realm.whenLive({ timeoutMs });
23877
+ } catch (error) {
23878
+ throw realm.attachError ?? connectionError ?? error;
23879
+ }
23880
+ }
23881
+ //#endregion
23786
23882
  //#region src/cli/daemonClient.ts
23787
23883
  /** The running daemon for this config, or null (dead record, failed ping, nothing on disk). */
23788
23884
  async function findDaemon(config) {
@@ -23849,6 +23945,8 @@ async function mintTicket(record) {
23849
23945
  return body.ticket;
23850
23946
  }
23851
23947
  async function connectDaemon(handle) {
23948
+ const runtimeError = commanderRuntimeError();
23949
+ if (runtimeError != null) throw new CliExit(EXIT.failure, runtimeError);
23852
23950
  const { record } = handle;
23853
23951
  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.`);
23854
23952
  const ticket = await mintTicket(record);
@@ -23882,12 +23980,12 @@ async function connectDaemon(handle) {
23882
23980
  connection: realmConnection(connector),
23883
23981
  assertOnAttach: () => {}
23884
23982
  });
23885
- connector.connect().catch(() => {});
23886
23983
  try {
23887
- await realm.whenLive({ timeoutMs: 1e4 });
23888
- } catch {
23984
+ await waitForStatusRealm(connector, realm, 1e4);
23985
+ } catch (error) {
23986
+ realm.detach();
23889
23987
  connector.dispose();
23890
- const reason = realm.attachError != null ? String(realm.attachError) : "timeout";
23988
+ const reason = String(error);
23891
23989
  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.` : "";
23892
23990
  throw new CliExit(EXIT.failure, `could not attach the status realm (${reason}).${hint}`);
23893
23991
  }
@@ -25469,7 +25567,7 @@ async function withTimeout(ctx, run) {
25469
25567
  async function main() {
25470
25568
  const argv = process.argv.slice(2);
25471
25569
  if (argv[0] === "daemon") {
25472
- const { runCommanderDaemon } = await import("./main-O9jpzqPH.mjs");
25570
+ const { runCommanderDaemon } = await import("./main-Gp2uG70g.mjs");
25473
25571
  return runCommanderDaemon(argv.slice(1));
25474
25572
  }
25475
25573
  const parsed = parseCliArgs(argv);
@@ -25513,6 +25611,6 @@ main().then((code) => {
25513
25611
  process.exitCode = EXIT.failure;
25514
25612
  });
25515
25613
  //#endregion
25516
- export { overrideFingerprint as A, createDefaultServeLogger as C, validateCommanderConfig as D, createMemoryStorageAdapter_json as E, recordDaemonAlive as F, removeInstanceRecord as I, writeInstanceRecord as L, orderByDependency as M, withDependencies as N, effectiveEnv as O, readInstanceRecord as P, serveChannel as S, RuntimeCoordinate as T, resolveCommanderDataDir as _, commanderChannel as a, httpAcceptorCarrier as b, COMMANDER_HEALTH_PATH as c, COMMANDER_TICKET_PROTOCOL_PREFIX as d, COMMANDER_WS_PATH as f, ensureStateDir as g, commanderStatePaths as h, readEnvOverrides as i, loadCommanderConfigFile as j, envVarViews as k, COMMANDER_LOGS_PATH as l, commanderPackageVersion as m, applyEnvMutation as n, commanderControlDomain as o, commanderStatusRealm as p, countOverrides as r, COMMANDER_BOOTSTRAP_PATH as s, parseLogsClientMessage as t, COMMANDER_TICKET_PATH as u, createRealmAcceptor as v, ActionRuntime as w, wsAcceptorCarrier as x, createRealmServerEngine as y };
25614
+ export { envVarViews as A, serveChannel as C, createMemoryStorageAdapter_json as D, RuntimeCoordinate as E, readInstanceRecord as F, recordDaemonAlive as I, removeInstanceRecord as L, loadCommanderConfigFile as M, orderByDependency as N, validateCommanderConfig as O, withDependencies as P, writeInstanceRecord as R, wsAcceptorCarrier as S, ActionRuntime as T, ensureStateDir as _, commanderChannel as a, createRealmServerEngine as b, COMMANDER_HEALTH_PATH as c, COMMANDER_TICKET_PROTOCOL_PREFIX as d, COMMANDER_WS_PATH as f, commanderStatePaths as g, commanderPackageVersion as h, readEnvOverrides as i, overrideFingerprint as j, effectiveEnv as k, COMMANDER_LOGS_PATH as l, commanderRuntimeError as m, applyEnvMutation as n, commanderControlDomain as o, commanderStatusRealm as p, countOverrides as r, COMMANDER_BOOTSTRAP_PATH as s, parseLogsClientMessage as t, COMMANDER_TICKET_PATH as u, resolveCommanderDataDir as v, createDefaultServeLogger as w, httpAcceptorCarrier as x, createRealmAcceptor as y };
25517
25615
 
25518
25616
  //# sourceMappingURL=cli.mjs.map