@mmmbuto/nexuscrew 0.8.9 → 0.8.10

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.
@@ -371,6 +371,17 @@ async function createBuiltinFleet(cfg = {}) {
371
371
  throw httpError(/duplicate/i.test(launch.stderr) ? 409 : 500, why);
372
372
  }
373
373
 
374
+ // `tmux new-session -d` can return 0 even when the launched CLI exits a
375
+ // moment later (missing login, bad model, incompatible provider). Without
376
+ // this readiness gate the PWA reported success and then showed nothing.
377
+ // Always verify liveness, including cells without a system prompt.
378
+ const readyMs = cfg.launchReadyMs != null ? cfg.launchReadyMs : 500;
379
+ const alive = await waitAlive(tmuxBin, cell.tmuxSession, { env: minimalEnv(), readyMs });
380
+ if (!alive) {
381
+ cache = { ...cache, at: 0 };
382
+ throw httpError(500, `client ${launchEngine.command} terminato subito: verifica login, provider, modello e argomenti dell'engine`);
383
+ }
384
+
374
385
  // (6) prompt send-keys: bracketed-paste best-effort, target = pane id esatto
375
386
  // (fallback al nome sessione con match esatto '=' se tmux non ha stampato l'id).
376
387
  let prompt = null;
@@ -379,7 +390,7 @@ async function createBuiltinFleet(cfg = {}) {
379
390
  const target = paneId.startsWith('%') ? paneId : `=${cell.tmuxSession}`;
380
391
  prompt = await injectPrompt(tmuxBin, cell.tmuxSession, cell.prompt, {
381
392
  env: minimalEnv(),
382
- readyMs: cfg.sendKeysReadyMs != null ? cfg.sendKeysReadyMs : 400,
393
+ readyMs: cfg.sendKeysReadyMs != null ? cfg.sendKeysReadyMs : readyMs,
383
394
  target,
384
395
  engine: launchEngine, cell, // per la redazione del reason se paste-buffer fallisce (§9h)
385
396
  });
package/lib/mcp/server.js CHANGED
@@ -71,6 +71,79 @@ function requireSession(session, tool) {
71
71
  );
72
72
  }
73
73
 
74
+ // Deck layout is stored column-major, while the UI is read row-major. Preserve
75
+ // the visual order so an agent sees the same neighbourhood as the operator.
76
+ function orderedDeckMembers(deck) {
77
+ const columns = deck && deck.layout && Array.isArray(deck.layout.columns)
78
+ ? deck.layout.columns : [];
79
+ const rows = Math.max(0, ...columns.map((column) => (
80
+ column && Array.isArray(column.tiles) ? column.tiles.length : 0
81
+ )));
82
+ const out = [];
83
+ for (let row = 0; row < rows; row += 1) {
84
+ for (const column of columns) {
85
+ const tile = column && Array.isArray(column.tiles) ? column.tiles[row] : null;
86
+ if (!tile || typeof tile.session !== 'string' || !tile.session) continue;
87
+ const member = { tmuxSession: tile.session };
88
+ if (typeof tile.node === 'string' && tile.node) member.node = tile.node;
89
+ if (typeof tile.ownerId === 'string' && NODE_ID_RE.test(tile.ownerId)) member.ownerId = tile.ownerId;
90
+ out.push(member);
91
+ }
92
+ }
93
+ return out;
94
+ }
95
+
96
+ const NODE_PART_RE = /^[a-z0-9-]{1,32}$/;
97
+ const NODE_ID_RE = /^[a-f0-9]{16,64}$/;
98
+ function fleetStatusPath(node) {
99
+ if (!node) return '/api/fleet/status';
100
+ const parts = String(node).split('/');
101
+ if (!parts.length || parts.some((part) => !NODE_PART_RE.test(part))
102
+ || new Set(parts).size !== parts.length) return null;
103
+ return `/api/route/${parts.map(encodeURIComponent).join('/')}/_/fleet/status`;
104
+ }
105
+
106
+ function fleetCellsBySession(payload) {
107
+ const out = new Map();
108
+ if (!payload || payload.available !== true || !Array.isArray(payload.cells)) return out;
109
+ for (const cell of payload.cells) {
110
+ if (!cell || typeof cell.tmuxSession !== 'string' || !cell.tmuxSession
111
+ || typeof cell.cell !== 'string' || !cell.cell) continue;
112
+ out.set(cell.tmuxSession, cell.cell);
113
+ }
114
+ return out;
115
+ }
116
+
117
+ function routePath(route, resource) {
118
+ if (!Array.isArray(route) || !route.length || route.length > 4
119
+ || route.some((part) => !NODE_PART_RE.test(part)) || new Set(route).size !== route.length) return null;
120
+ return `/api/route/${route.map(encodeURIComponent).join('/')}/_/${resource}`;
121
+ }
122
+
123
+ function topologyOwners(payload) {
124
+ const out = [];
125
+ const seen = new Set();
126
+ for (const node of (payload && Array.isArray(payload.nodes) ? payload.nodes : [])) {
127
+ if (!node || !NODE_ID_RE.test(String(node.instanceId || '')) || seen.has(node.instanceId)
128
+ || !Array.isArray(node.route) || !routePath(node.route, 'decks')) continue;
129
+ seen.add(node.instanceId);
130
+ out.push({
131
+ instanceId: node.instanceId,
132
+ route: [...node.route],
133
+ label: typeof node.label === 'string' && node.label ? node.label : (node.name || node.route.join(' › ')),
134
+ stale: node.stale === true,
135
+ });
136
+ }
137
+ return out;
138
+ }
139
+
140
+ function memberOwnerId(member, deckOwner, ownerTopology) {
141
+ if (member.ownerId && NODE_ID_RE.test(member.ownerId)) return member.ownerId;
142
+ if (!member.node) return deckOwner.instanceId;
143
+ const found = ownerTopology.find((node) => Array.isArray(node.route) && node.route.join('/') === member.node);
144
+ return found ? found.instanceId : null;
145
+ }
146
+
74
147
  // --- definizione tool (prefisso nc_ anti-collisione) ---------------------------
75
148
  // annotations.readOnlyHint:true sui tool che non mutano nulla (§1).
76
149
  const TOOLS = [
@@ -176,6 +249,94 @@ const TOOLS = [
176
249
  return { sessions, fleet };
177
250
  },
178
251
  },
252
+ {
253
+ name: 'nc_deck',
254
+ description: 'Contesto read-only del deck della sessione chiamante: restituisce i deck che la contengono e i relativi membri con nome cella Fleet, sessione tmux e route.',
255
+ inputSchema: { type: 'object', properties: {} },
256
+ annotations: { readOnlyHint: true },
257
+ async handler(_args, ctx) {
258
+ const tmuxSession = requireSession(await ctx.session(), 'nc_deck');
259
+ const [config, topology, localDecks] = await Promise.all([
260
+ ctx.api('GET', '/api/config'), ctx.api('GET', '/api/topology'), ctx.api('GET', '/api/decks'),
261
+ ]);
262
+ const localNodeId = String(config && config.instanceId || '');
263
+ if (!NODE_ID_RE.test(localNodeId)) throw new Error('instanceId locale non disponibile');
264
+ if (!localDecks || !Array.isArray(localDecks.decks)) throw new Error('risposta deck non valida');
265
+
266
+ const remotes = topologyOwners(topology).filter((owner) => !owner.stale && owner.instanceId !== localNodeId);
267
+ const viewerById = new Map([[localNodeId, []], ...remotes.map((owner) => [owner.instanceId, owner.route])]);
268
+ const sources = [{
269
+ owner: { instanceId: localNodeId, route: [], label: 'Local' },
270
+ ownerTopology: topologyOwners(topology), decks: localDecks.decks,
271
+ }];
272
+ await Promise.all(remotes.map(async (owner) => {
273
+ const decksPath = routePath(owner.route, 'decks');
274
+ const topologyPath = routePath(owner.route, 'topology');
275
+ if (!decksPath || !topologyPath) return;
276
+ try {
277
+ const [deckPayload, ownerTopology] = await Promise.all([
278
+ ctx.api('GET', decksPath), ctx.api('GET', topologyPath).catch(() => ({ nodes: [] })),
279
+ ]);
280
+ if (deckPayload && Array.isArray(deckPayload.decks)) {
281
+ sources.push({ owner, ownerTopology: topologyOwners(ownerTopology), decks: deckPayload.decks });
282
+ }
283
+ } catch (_) { /* owner offline/withdrawn: no stale deck disclosure */ }
284
+ }));
285
+
286
+ const decks = [];
287
+ for (const source of sources) {
288
+ for (const deck of source.decks) {
289
+ if (!deck || typeof deck.name !== 'string') continue;
290
+ const members = orderedDeckMembers(deck).map((member) => ({
291
+ ...member,
292
+ ownerId: memberOwnerId(member, source.owner, source.ownerTopology),
293
+ }));
294
+ if (!members.some((member) => member.ownerId === localNodeId && member.tmuxSession === tmuxSession)) continue;
295
+ decks.push({
296
+ id: `${source.owner.instanceId}:${deck.name}`,
297
+ name: deck.name,
298
+ owner: { instanceId: source.owner.instanceId, route: source.owner.route.length ? source.owner.route.join('/') : 'local', label: source.owner.label },
299
+ members,
300
+ });
301
+ }
302
+ }
303
+ decks.sort((a, b) => a.owner.route.localeCompare(b.owner.route) || a.name.localeCompare(b.name));
304
+
305
+ if (!decks.length) return { tmuxSession, nodeId: localNodeId, decks: [] };
306
+
307
+ const routes = new Set(['']);
308
+ for (const deck of decks) for (const member of deck.members) {
309
+ const route = member.ownerId && viewerById.has(member.ownerId)
310
+ ? viewerById.get(member.ownerId).join('/') : null;
311
+ member.viewerRoute = route;
312
+ if (route !== null) routes.add(route);
313
+ }
314
+ const cellsByRoute = new Map();
315
+ await Promise.all([...routes].map(async (route) => {
316
+ const apiPath = fleetStatusPath(route);
317
+ if (!apiPath) return;
318
+ try { cellsByRoute.set(route, fleetCellsBySession(await ctx.api('GET', apiPath))); }
319
+ catch (_) { cellsByRoute.set(route, new Map()); }
320
+ }));
321
+
322
+ return {
323
+ tmuxSession, nodeId: localNodeId,
324
+ decks: decks.map((deck) => ({
325
+ id: deck.id, name: deck.name, owner: deck.owner,
326
+ members: deck.members.map((member) => {
327
+ const route = member.viewerRoute;
328
+ return {
329
+ cell: route === null ? null : (cellsByRoute.get(route)?.get(member.tmuxSession) || null),
330
+ tmuxSession: member.tmuxSession,
331
+ ownerId: member.ownerId,
332
+ route: route === null ? 'unavailable' : (route || 'local'),
333
+ self: member.ownerId === localNodeId && member.tmuxSession === tmuxSession,
334
+ };
335
+ }),
336
+ })),
337
+ };
338
+ },
339
+ },
179
340
  {
180
341
  name: 'nc_inbox',
181
342
  description: 'Elenca i file ricevuti nell\'inbox NexusCrew di questa sessione (read-only).',
@@ -1,20 +1,22 @@
1
1
  'use strict';
2
- // lib/nodes/commands.js — subcomandi CLI `nodes` e `node` (design §3, §4, §4b).
2
+ // lib/nodes/commands.js — implementation helpers for the authenticated PWA.
3
3
  //
4
- // nodes add/list/remove/test/up/down/restart/set-token + node on/off.
4
+ // Nodes add/list/remove/test/up/down/restart/set-token. These helpers are not
5
+ // advertised as public CLI commands.
5
6
  // Invarianti:
6
7
  // - token per-nodo MAI loggati/stampati (redazione sempre; set-token li legge
7
8
  // da stdin/env, mai da argv -> niente segreti in `ps`).
8
9
  // - NEXUSCREW_READONLY blocca le MUTAZIONI DI CONFIG (add/remove/set-token/
9
- // on/off), non list/test/status/up/down/restart (lifecycle tunnel, non config).
10
+ // configuration), while the Settings routes separately gate process lifecycle.
10
11
  // - niente shell interpolation: ssh-keygen via execFile (argv), tunnel via spawn argv.
11
12
  const fs = require('node:fs');
13
+ const net = require('node:net');
12
14
  const os = require('node:os');
13
15
  const path = require('node:path');
14
16
  const { execFileSync } = require('node:child_process');
15
17
  const store = require('./store.js');
16
18
  const tunnel = require('./tunnel.js');
17
- const { resolvePaths, loadPort, DEFAULT_PORT } = require('../cli/url.js');
19
+ const { resolvePaths, DEFAULT_PORT } = require('../cli/url.js');
18
20
 
19
21
  const LOCAL_PORT_BASE = 43001; // porte locali stabili per i forward (design: stabili da nodes.json)
20
22
 
@@ -38,6 +40,49 @@ function assignLocalPort(st) {
38
40
  return p;
39
41
  }
40
42
 
43
+ function bindLocalPort(port, createServerImpl = net.createServer) {
44
+ return new Promise((resolve, reject) => {
45
+ const server = createServerImpl();
46
+ const onError = (error) => {
47
+ server.removeListener('listening', onListening);
48
+ reject(error);
49
+ };
50
+ const onListening = () => {
51
+ server.removeListener('error', onError);
52
+ if (typeof server.unref === 'function') server.unref();
53
+ let released = false;
54
+ resolve({
55
+ port,
56
+ release: () => new Promise((done) => {
57
+ if (released) return done();
58
+ released = true;
59
+ try { server.close(() => done()); } catch (_) { done(); }
60
+ }),
61
+ });
62
+ };
63
+ server.once('error', onError);
64
+ server.once('listening', onListening);
65
+ server.listen({ host: '127.0.0.1', port, exclusive: true });
66
+ });
67
+ }
68
+
69
+ // Selezione OS-aware per il pairing: nodes.json evita collisioni logiche, il
70
+ // bind reale evita porte gia' occupate da processi estranei. La socket resta
71
+ // riservata fino all'avvio del supervisor SSH e viene poi rilasciata una volta.
72
+ async function reserveLocalPort(st, opts = {}) {
73
+ const used = new Set((st.nodes || []).map((n) => n.localPort));
74
+ const createServerImpl = opts.createServerImpl || net.createServer;
75
+ for (let port = opts.start || LOCAL_PORT_BASE; port <= 65535; port += 1) {
76
+ if (used.has(port)) continue;
77
+ try { return await bindLocalPort(port, createServerImpl); }
78
+ catch (error) {
79
+ if (error && (error.code === 'EADDRINUSE' || error.code === 'EACCES')) continue;
80
+ throw error;
81
+ }
82
+ }
83
+ throw new Error('nessuna porta locale disponibile per il tunnel');
84
+ }
85
+
41
86
  function defaultKeyPath(home, name) {
42
87
  return path.join(home, '.nexuscrew', 'keys', `${name}_ed25519`);
43
88
  }
@@ -59,24 +104,6 @@ function ensureKey(keyPath, name, opts = {}) {
59
104
  return fs.readFileSync(pubPath, 'utf8').trim();
60
105
  }
61
106
 
62
- // Scrittura atomica di config.json preservando il resto (per roles).
63
- function writeConfigRole(configPath, key, value) {
64
- let cfg = {};
65
- try { const c = JSON.parse(fs.readFileSync(configPath, 'utf8')); if (c && typeof c === 'object') cfg = c; } catch (_) {}
66
- const roles = (cfg.roles && typeof cfg.roles === 'object') ? cfg.roles : {};
67
- cfg.roles = { client: !!roles.client, node: !!roles.node };
68
- cfg.roles[key] = value;
69
- const dir = path.dirname(configPath);
70
- fs.mkdirSync(dir, { recursive: true });
71
- const tmp = path.join(dir, `.${path.basename(configPath)}.${process.pid}.tmp`);
72
- try {
73
- fs.writeFileSync(tmp, `${JSON.stringify(cfg, null, 2)}\n`, { mode: 0o600 });
74
- fs.chmodSync(tmp, 0o600);
75
- fs.renameSync(tmp, configPath);
76
- } catch (e) { try { fs.unlinkSync(tmp); } catch (_) {} throw e; }
77
- return cfg.roles;
78
- }
79
-
80
107
  // Legge il token remoto da fonte NON-argv: opts.token (test) > env > stdin.
81
108
  // MAI da flag CLI: il token comparirebbe in `ps`/history.
82
109
  function readSecretToken(opts) {
@@ -93,7 +120,7 @@ function nodesAdd(opts) {
93
120
  const { home, nodesPath } = resolveNodePaths(opts);
94
121
  const name = opts.name;
95
122
  const ssh = opts.ssh;
96
- if (!name) { log('usage: nexuscrew nodes add <name> --ssh user@host [--ssh-port N] [--remote-port N] [--key path] [--local-port N]'); return { code: 1, reason: 'name mancante' }; }
123
+ if (!name) { log('nodes add: name mancante (configura il nodo dalla PWA)'); return { code: 1, reason: 'name mancante' }; }
97
124
  if (!ssh) { log('nodes add: --ssh user@host obbligatorio'); return { code: 1, reason: 'ssh mancante' }; }
98
125
 
99
126
  const remotePort = opts.remotePort ? Number(opts.remotePort) : DEFAULT_PORT;
@@ -159,7 +186,6 @@ function nodesList(opts) {
159
186
  const view = store.redactStore(st); // MAI il token
160
187
  const nodes = view.nodes.map((n) => ({ ...n, tunnel: tunnel.readTunnelState(home, n.name) }));
161
188
  const out = { nodeId: view.nodeId, nodes };
162
- if (view.rendezvous) out.rendezvous = view.rendezvous;
163
189
 
164
190
  if (opts.json) { log(JSON.stringify(out, null, 2)); return { code: 0, nodes }; }
165
191
  if (nodes.length === 0) { log('nodes: (nessun nodo)'); return { code: 0, nodes }; }
@@ -175,7 +201,7 @@ function nodesRemove(opts) {
175
201
  if (isReadonly(opts)) { log('nodes remove: READONLY, mutazione bloccata'); return { code: 1, reason: 'readonly' }; }
176
202
  const { home, nodesPath } = resolveNodePaths(opts);
177
203
  const name = opts.name;
178
- if (!name) { log('usage: nexuscrew nodes remove <name>'); return { code: 1 }; }
204
+ if (!name) { log('nodes remove: name mancante'); return { code: 1 }; }
179
205
  const st = store.loadStore(nodesPath);
180
206
  if (!st) { log('nodes remove: nessun nodes.json valido'); return { code: 1 }; }
181
207
  let next;
@@ -207,15 +233,16 @@ async function nodesTest(opts) {
207
233
  const log = opts.log || console.log;
208
234
  const { home, nodesPath } = resolveNodePaths(opts);
209
235
  const name = opts.name;
210
- if (!name) { log('usage: nexuscrew nodes test <name>'); return { code: 1 }; }
236
+ if (!name) { log('nodes test: name mancante'); return { code: 1 }; }
211
237
  const st = store.loadStore(nodesPath);
212
238
  const node = st ? store.getNode(st, name) : null;
213
239
  if (!node) { log(`nodes test: nodo sconosciuto "${name}"`); return { code: 1, result: 'unknown-node' }; }
214
240
 
215
241
  const state = tunnel.readTunnelState(home, name);
216
242
  if (state.status !== 'up') {
217
- log(`nodes test [${name}]: TUNNEL DOWN — avvia con \`nexuscrew nodes up ${name}\``);
218
- return { code: 1, result: 'tunnel-down' };
243
+ const diagnostic = tunnel.diagnoseTunnel(home, node, state);
244
+ log(`nodes test [${name}]: ${diagnostic.code.toUpperCase()} ${diagnostic.detail}${diagnostic.hint ? ` · ${diagnostic.hint}` : ''}`);
245
+ return { code: 1, result: 'tunnel-down', diagnostic };
219
246
  }
220
247
 
221
248
  const httpProbe = opts.httpProbe || defaultHttpProbe;
@@ -226,13 +253,17 @@ async function nodesTest(opts) {
226
253
  try { health = await httpProbe(`${base}/`, {}); }
227
254
  catch (e) { health = { ok: false, error: e && e.message }; }
228
255
  if (!health || !health.ok) {
229
- log(`nodes test [${name}]: HEALTH KO — tunnel up ma il server remoto non risponde (${(health && health.error) || 'no 2xx'})`);
230
- return { code: 1, result: 'health-ko' };
256
+ const diagnostic = tunnel.diagnoseTunnel(home, node);
257
+ const realCause = diagnostic.code !== 'transport-ready' ? diagnostic.detail : ((health && health.error) || 'server HTTP non raggiungibile');
258
+ log(`nodes test [${name}]: HEALTH KO — ${realCause}${diagnostic.hint ? ` · ${diagnostic.hint}` : ''}`);
259
+ return { code: 1, result: 'health-ko', diagnostic: diagnostic.code === 'transport-ready'
260
+ ? { stage: 'http', code: 'peer-http-unreachable', detail: realCause, hint: 'verifica la porta NexusCrew contenuta nel link' }
261
+ : diagnostic };
231
262
  }
232
263
 
233
264
  // token: GET /api/config con Bearer del nodo -> 200 ok, 401 token KO.
234
265
  if (!node.token) {
235
- log(`nodes test [${name}]: TOKEN ASSENTEsalva il token remoto con \`nexuscrew nodes set-token ${name}\``);
266
+ log(`nodes test [${name}]: ASSOCIAZIONE INCOMPLETArimuovi il nodo e ripeti il pairing dalla PWA`);
236
267
  return { code: 1, result: 'token-missing' };
237
268
  }
238
269
  let authed;
@@ -242,7 +273,7 @@ async function nodesTest(opts) {
242
273
  log(`nodes test [${name}]: OK — tunnel up, health ok, token valido`);
243
274
  return { code: 0, result: 'ok' };
244
275
  }
245
- log(`nodes test [${name}]: TOKEN KO — il token remoto salvato non e' valido (status ${(authed && authed.status) || '?'}); ruota con \`nexuscrew nodes set-token ${name}\``);
276
+ log(`nodes test [${name}]: CREDENZIALE KO — il pairing non e' piu' valido (status ${(authed && authed.status) || '?'}); ripeti il pairing dalla PWA`);
246
277
  return { code: 1, result: 'token-ko' };
247
278
  }
248
279
 
@@ -256,11 +287,18 @@ async function defaultHttpProbe(url, headers) {
256
287
  function loadNodeOrFail(opts, log) {
257
288
  const { home, nodesPath } = resolveNodePaths(opts);
258
289
  const name = opts.name;
259
- if (!name) { log('usage: nexuscrew nodes up|down|restart <name>'); return null; }
290
+ if (!name) { log('nodes: name mancante'); return null; }
260
291
  const st = store.loadStore(nodesPath);
261
292
  const node = st ? store.getNode(st, name) : null;
262
293
  if (!node) { log(`nodes: nodo sconosciuto "${name}"`); return null; }
263
- return { home, node };
294
+ return { home, nodesPath, store: st, node };
295
+ }
296
+
297
+ function persistAutostart(ctx, enabled) {
298
+ const next = store.updateNode(ctx.store, ctx.node.name, { autostart: enabled });
299
+ store.atomicWriteStore(ctx.nodesPath, next);
300
+ ctx.store = next;
301
+ ctx.node = store.getNode(next, ctx.node.name);
264
302
  }
265
303
 
266
304
  function nodesUp(opts) {
@@ -268,29 +306,35 @@ function nodesUp(opts) {
268
306
  const ctx = loadNodeOrFail(opts, log);
269
307
  if (!ctx) return { code: 1 };
270
308
  if (ctx.node.direction === 'inbound') return { code: 0, started: false, inbound: true };
309
+ if (opts.persistAutostart === true && ctx.node.autostart !== true) {
310
+ try { persistAutostart(ctx, true); }
311
+ catch (e) { log(`nodes up [${ctx.node.name}]: impossibile salvare l'avvio automatico — ${e.message}`); return { code: 1, reason: 'autostart write failed' }; }
312
+ }
271
313
  const r = tunnel.startForward({ home: ctx.home, node: ctx.node, localAppPort: opts.localAppPort, spawnImpl: opts.spawnImpl, spawnSyncImpl: opts.spawnSyncImpl, sshBin: opts.sshBin, logFd: opts.logFd });
272
314
  if (r.started) {
273
315
  log(`nodes up [${ctx.node.name}]: tunnel avviato (pid ${r.pid}, local ${ctx.node.localPort})`);
274
- return { code: 0, started: true, pid: r.pid };
316
+ return { code: 0, started: true, pid: r.pid, diagnostic: tunnel.diagnoseTunnel(ctx.home, ctx.node) };
275
317
  }
276
318
  if (r.reason === 'already running') {
277
319
  log(`nodes up [${ctx.node.name}]: gia' attivo (pid ${r.pid})`);
278
- return { code: 0, started: false, pid: r.pid };
320
+ return { code: 0, started: false, pid: r.pid, diagnostic: tunnel.diagnoseTunnel(ctx.home, ctx.node) };
279
321
  }
280
322
  // failure esplicita (ssh mancante / spawn error): surfacciata a CLI e Settings API.
281
323
  log(`nodes up [${ctx.node.name}]: avvio tunnel fallito — ${r.reason}`);
282
- return { code: 1, started: false, reason: r.reason };
324
+ return { code: 1, started: false, reason: r.reason, diagnostic: tunnel.diagnoseTunnel(ctx.home, ctx.node) };
283
325
  }
284
326
 
285
327
  function nodesDown(opts) {
286
328
  const log = opts.log || console.log;
287
- const { home, nodesPath } = resolveNodePaths(opts);
288
- const name = opts.name;
289
- if (!name) { log('usage: nexuscrew nodes down <name>'); return { code: 1 }; }
290
- const st = store.loadStore(nodesPath);
291
- if (!st || !store.getNode(st, name)) { log(`nodes down: nodo sconosciuto "${name}"`); return { code: 1 }; }
292
- const r = tunnel.stopTunnel({ home, name });
293
- log(`nodes down [${name}]: ${r.stopped ? `fermato (pid ${r.pid})` : r.reason}`);
329
+ const ctx = loadNodeOrFail(opts, log);
330
+ if (!ctx) return { code: 1 };
331
+ if (ctx.node.direction === 'inbound') return { code: 0, stopped: false, inbound: true };
332
+ if (opts.persistAutostart === true && ctx.node.autostart !== false) {
333
+ try { persistAutostart(ctx, false); }
334
+ catch (e) { log(`nodes down [${ctx.node.name}]: impossibile salvare lo stop — ${e.message}`); return { code: 1, reason: 'autostart write failed' }; }
335
+ }
336
+ const r = tunnel.stopTunnel({ home: ctx.home, name: ctx.node.name });
337
+ log(`nodes down [${ctx.node.name}]: ${r.stopped ? `fermato (pid ${r.pid})` : r.reason}`);
294
338
  return { code: 0, stopped: r.stopped };
295
339
  }
296
340
 
@@ -298,16 +342,17 @@ function nodesRestart(opts) {
298
342
  const log = opts.log || console.log;
299
343
  const ctx = loadNodeOrFail(opts, log);
300
344
  if (!ctx) return { code: 1 };
301
- const args = tunnel.buildForwardArgs(ctx.node);
302
- const r = tunnel.restartTunnel({ home: ctx.home, name: ctx.node.name, args, spawnImpl: opts.spawnImpl, spawnSyncImpl: opts.spawnSyncImpl, sshBin: opts.sshBin, logFd: opts.logFd });
345
+ if (ctx.node.direction === 'inbound') return { code: 0, started: false, inbound: true };
346
+ tunnel.stopTunnel({ home: ctx.home, name: ctx.node.name });
347
+ const r = tunnel.startForward({ home: ctx.home, node: ctx.node, localAppPort: opts.localAppPort, spawnImpl: opts.spawnImpl, spawnSyncImpl: opts.spawnSyncImpl, sshBin: opts.sshBin, logFd: opts.logFd });
303
348
  if (r.started) {
304
349
  log(`nodes restart [${ctx.node.name}]: tunnel riavviato (pid ${r.pid})`);
305
- return { code: 0, started: true, pid: r.pid };
350
+ return { code: 0, started: true, pid: r.pid, diagnostic: tunnel.diagnoseTunnel(ctx.home, ctx.node) };
306
351
  }
307
352
  // dopo stop+start, 'already running' non e' atteso: qualunque !started e' un problema
308
353
  // esplicito (ssh mancante / spawn error), surfacciato a CLI e Settings API.
309
354
  log(`nodes restart [${ctx.node.name}]: riavvio tunnel fallito — ${r.reason || 'sconosciuto'}`);
310
- return { code: 1, started: false, reason: r.reason || 'spawn failed' };
355
+ return { code: 1, started: false, reason: r.reason || 'spawn failed', diagnostic: tunnel.diagnoseTunnel(ctx.home, ctx.node) };
311
356
  }
312
357
 
313
358
  // --- nodes set-token (aggiorna il token remoto; MAI da argv) ----------------
@@ -316,7 +361,7 @@ function nodesSetToken(opts) {
316
361
  if (isReadonly(opts)) { log('nodes set-token: READONLY, mutazione bloccata'); return { code: 1, reason: 'readonly' }; }
317
362
  const { nodesPath } = resolveNodePaths(opts);
318
363
  const name = opts.name;
319
- if (!name) { log('usage: nexuscrew nodes set-token <name> (token da stdin o env NEXUSCREW_NODE_TOKEN)'); return { code: 1 }; }
364
+ if (!name) { log('nodes set-token: name mancante'); return { code: 1 }; }
320
365
  const st = store.loadStore(nodesPath);
321
366
  if (!st || !store.getNode(st, name)) { log(`nodes set-token: nodo sconosciuto "${name}"`); return { code: 1 }; }
322
367
  const token = readSecretToken(opts);
@@ -329,83 +374,10 @@ function nodesSetToken(opts) {
329
374
  return { code: 0, name };
330
375
  }
331
376
 
332
- // --- node on|off (ruolo "nodo raggiungibile", reverse tunnel) ---------------
333
- function nodeOn(opts) {
334
- const log = opts.log || console.log;
335
- if (isReadonly(opts)) { log('node on: READONLY, mutazione bloccata'); return { code: 1, reason: 'readonly' }; }
336
- const { home, configPath, nodesPath } = resolveNodePaths(opts);
337
-
338
- // Gate permitlisten (§7 advisory a): il ruolo node richiede reverse tunnel con
339
- // permitlisten sul rendezvous (OpenSSH >=7.8). Se la versione e' nota ed e'
340
- // troppo vecchia -> rifiuta PRIMA di abilitare. Ignota -> warn, non blocca.
341
- const v = (opts.sshVersion || tunnel.readSshVersion)(opts.spawnSyncImpl);
342
- const supp = tunnel.sshSupportsPermitlisten(v);
343
- if (supp === false) {
344
- log(`node on: OpenSSH ${v.major}.${v.minor} < 7.8 — permitlisten non supportato dal client; il ruolo node NON e' abilitabile con questa toolchain`);
345
- return { code: 1, reason: 'permitlisten' };
346
- }
347
- if (supp === null) log('node on: versione OpenSSH non determinabile — verifica che il rendezvous supporti permitlisten (>=7.8)');
348
-
349
- // Configurazione rendezvous opzionale (flags) o gia' presente in nodes.json.
350
- let st;
351
- try { st = store.loadOrInitStore(nodesPath); }
352
- catch (e) { log(`node on: ${e.message}`); return { code: 1 }; }
353
-
354
- if (opts.rendezvousSsh) {
355
- const localPort = loadPort(opts); // porta nexus locale da esporre
356
- const publishedPort = opts.publishedPort ? Number(opts.publishedPort) : localPort;
357
- const keyPath = opts.key || path.join(home, '.nexuscrew', 'keys', 'rendezvous_ed25519');
358
- let pub;
359
- try { pub = ensureKey(keyPath, 'rendezvous', opts); }
360
- catch (e) { log(`node on: generazione chiave rendezvous fallita (${e.message})`); return { code: 1 }; }
361
- let next;
362
- try { next = store.setRendezvous(st, { ssh: opts.rendezvousSsh, publishedPort, localPort, keyPath }); }
363
- catch (e) { log(`node on: ${e.message}`); return { code: 1 }; }
364
- store.atomicWriteStore(nodesPath, next);
365
- st = next;
366
- log(`node on: rendezvous configurato (${opts.rendezvousSsh}, published ${publishedPort} <- local ${localPort})`);
367
- log('Incolla nel ~/.ssh/authorized_keys del RENDEZVOUS (lato reverse, chiave dedicata):');
368
- // permitlisten vincola i -R alla SOLA porta pubblicata (loopback esplicito).
369
- log(`restrict,port-forwarding,permitlisten="127.0.0.1:${publishedPort}",command="/bin/false" ${pub}`);
370
- } else if (!st.rendezvous) {
371
- log('node on: nessun rendezvous configurato — passa --rendezvous user@host [--published-port N] [--key path]');
372
- return { code: 1, reason: 'no rendezvous' };
373
- }
374
-
375
- // Avvia un supervisor detached per il reverse tunnel. Il supervisor ritenta
376
- // con backoff: al primo setup può partire prima che la pubkey sia stata
377
- // incollata sul rendezvous e convergerà automaticamente appena autorizzata.
378
- const tr = tunnel.startReverse({
379
- home, rendezvous: st.rendezvous,
380
- spawnImpl: opts.spawnImpl, spawnSyncImpl: opts.spawnSyncImpl,
381
- sshBin: opts.sshBin, logFd: opts.logFd,
382
- });
383
- if (!tr.started && tr.reason !== 'already running') {
384
- log(`node on: reverse tunnel non avviato — ${tr.reason || 'errore sconosciuto'}; ruolo NON abilitato`);
385
- return { code: 1, reason: 'reverse tunnel failed' };
386
- }
387
-
388
- const roles = writeConfigRole(configPath, 'node', true);
389
- log(`node on: ruolo node ABILITATO (roles: client=${roles.client} node=${roles.node}, reverse pid=${tr.pid})`);
390
- return { code: 0, roles, tunnel: { started: !!tr.started, pid: tr.pid } };
391
- }
392
-
393
- function nodeOff(opts) {
394
- const log = opts.log || console.log;
395
- if (isReadonly(opts)) { log('node off: READONLY, mutazione bloccata'); return { code: 1, reason: 'readonly' }; }
396
- const { home, configPath } = resolveNodePaths(opts);
397
- const roles = writeConfigRole(configPath, 'node', false);
398
- // Ferma un eventuale reverse tunnel attivo (best-effort, non tocca la config rendezvous).
399
- try { tunnel.stopTunnel({ home, name: tunnel.REVERSE_NAME }); } catch (_) {}
400
- log(`node off: ruolo node DISABILITATO (roles: client=${roles.client} node=${roles.node})`);
401
- return { code: 0, roles };
402
- }
403
-
404
377
  module.exports = {
405
378
  nodesAdd, nodesList, nodesRemove, nodesTest,
406
379
  nodesUp, nodesDown, nodesRestart, nodesSetToken,
407
- nodeOn, nodeOff,
408
380
  // helper esposti per test/riuso
409
- assignLocalPort, defaultKeyPath, ensureKey, writeConfigRole, readSecretToken,
381
+ assignLocalPort, bindLocalPort, reserveLocalPort, defaultKeyPath, ensureKey, readSecretToken,
410
382
  resolveNodePaths, defaultHttpProbe,
411
383
  };
@@ -30,23 +30,29 @@ function clearHealthCache() { cache.clear(); }
30
30
  // onesto). outbound down/401 -> 'down'/'degraded'.
31
31
  function tunnelFromHealth(h) {
32
32
  if (!h) return { status: 'unknown', managed: false };
33
- if (h.status === 'passive') return { status: 'passive', managed: false };
34
- if (h.transport === 'up' && h.auth === 'ok') return { status: 'up', managed: h.managed !== false };
35
- if (h.transport === 'up' && h.auth === 'failed') return { status: 'degraded', managed: h.managed !== false };
36
- if (h.transport === 'up') return { status: 'degraded', managed: h.managed !== false };
37
- if (h.transport === 'down') return { status: 'down', managed: h.managed !== false };
33
+ const used = h.transportEngine ? { transport: h.transportEngine } : {};
34
+ if (h.status === 'passive') return { status: 'passive', managed: false, ...used };
35
+ if (h.transport === 'up' && h.auth === 'ok') return { status: 'up', managed: h.managed !== false, ...used };
36
+ if (h.transport === 'up' && h.auth === 'failed') return { status: 'degraded', managed: h.managed !== false, ...used };
37
+ if (h.transport === 'up') return { status: 'degraded', managed: h.managed !== false, ...used };
38
+ if (h.transport === 'down') return { status: 'down', managed: h.managed !== false, ...used };
38
39
  return { status: 'unknown', managed: false }; // inbound / unknown
39
40
  }
40
41
 
41
42
  async function nodeHealth({ node, home, fetchImpl, now = Date.now(), force = false }) {
42
43
  if (!node || typeof node !== 'object') return null;
43
- const cacheKey = `${home || ''}\0${node.direction || 'outbound'}\0${node.name}\0${node.localPort}\0${node.nodeId || ''}\0${node.rolesKnown === true}\0${node.roles?.node === true}`;
44
+ const cacheKey = `${home || ''}\0${node.direction || 'outbound'}\0${node.name}\0${node.localPort}\0${node.nodeId || ''}\0${node.shared === true}\0${node.rolesKnown === true}\0${node.roles?.node === true}`;
44
45
  const cached = !force && cache.get(cacheKey);
45
46
  if (cached && (now - cached.at) < TTL_MS) return cached.health;
46
47
 
47
48
  let health;
48
49
  if (node.direction === 'inbound') {
49
- if (!node.token) {
50
+ if (node.shared !== true) {
51
+ health = {
52
+ transport: 'unknown', auth: 'unknown', reachability: 'unknown', status: 'passive',
53
+ detail: 'client privato collegato (Share disattivato)', expected: true, managed: false, at: now,
54
+ };
55
+ } else if (!node.token) {
50
56
  health = {
51
57
  transport: 'unknown', auth: 'unknown', reachability: 'unknown', status: 'degraded',
52
58
  detail: 'peer inbound senza credenziale federation — re-pair', managed: false, at: now,
@@ -70,22 +76,24 @@ async function nodeHealth({ node, home, fetchImpl, now = Date.now(), force = fal
70
76
  } else {
71
77
  const ts = nodesTunnel.readTunnelState(home, node.name);
72
78
  if (ts.status !== 'up') {
73
- health = {
74
- transport: 'down', auth: 'unknown', reachability: 'unknown', status: 'down',
75
- detail: ts.reason ? `tunnel down (${ts.reason})` : 'tunnel down',
76
- managed: ts.managed !== false, at: now,
77
- };
79
+ const diagnostic = nodesTunnel.diagnoseTunnel(home, node, ts);
80
+ health = {
81
+ transport: 'down', auth: 'unknown', reachability: 'unknown', status: 'down',
82
+ detail: diagnostic.detail, code: diagnostic.code, stage: diagnostic.stage,
83
+ ...(diagnostic.hint ? { hint: diagnostic.hint } : {}),
84
+ transportEngine: ts.transport || 'ssh', managed: ts.managed !== false, at: now,
85
+ };
78
86
  } else if (!node.token) {
79
87
  health = {
80
88
  transport: 'up', auth: 'unknown', reachability: 'unknown', status: 'degraded',
81
89
  detail: 'tunnel up, credenziali federation assenti (token mancante) — re-pair',
82
- managed: true, at: now,
90
+ transportEngine: ts.transport || 'ssh', managed: true, at: now,
83
91
  };
84
92
  } else {
85
93
  const probed = await probeHealth({
86
94
  port: node.localPort, token: node.token, expectedInstanceId: node.nodeId || null, fetchImpl, now,
87
95
  });
88
- health = { ...probed, managed: true };
96
+ health = { ...probed, transportEngine: ts.transport || 'ssh', managed: true };
89
97
  }
90
98
  }
91
99
  cache.set(cacheKey, { health, at: now });