@dotrino/terminal-agent 0.54.0 → 0.55.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/editors.js CHANGED
@@ -28,6 +28,7 @@ export const EDITORS = [
28
28
  ]
29
29
 
30
30
  /** Un error con `code`: quien lo recibe decide por el código, no por la frase. */
31
+ /** @type {(code: string, message: string) => Error & { code: string }} */
31
32
  const fail = (code, message) => Object.assign(new Error(message), { code })
32
33
 
33
34
  /** `linux`, `osx` o `windows`: el sufijo de las claves de terminal de VS Code. Otro sistema no se atiende. */
@@ -52,12 +53,23 @@ export function findEditors (base = configBase()) {
52
53
  .filter((e) => fs.existsSync(path.dirname(e.settings)))
53
54
  }
54
55
 
55
- /** El perfil de terminal: Node, el script del cliente y, si se pidió, el perfil de Dotrino. */
56
+ /**
57
+ * El perfil de terminal: Node, el script del cliente y, si se pidió, el perfil de Dotrino.
58
+ * @param {{ node: string, script: string, name?: string | null }} o
59
+ * @returns {{ path: string, args: string[] }}
60
+ */
56
61
  export function terminalProfile ({ node, script, name }) {
57
62
  return { path: node, args: name ? [script, '--name', name] : [script] }
58
63
  }
59
64
 
65
+ /**
66
+ * El `settings.json` leído (JSON con comentarios): un objeto, o lanza `bad-settings`.
67
+ * @param {string} text
68
+ * @param {string} file
69
+ * @returns {Record<string, unknown>}
70
+ */
60
71
  function check (text, file) {
72
+ /** @type {import('jsonc-parser').ParseError[]} */
61
73
  const errors = []
62
74
  const value = parse(text, errors, { allowTrailingComma: true })
63
75
  if (errors.length || (text.trim() && (typeof value !== 'object' || value === null || Array.isArray(value)))) {
@@ -67,8 +79,14 @@ function check (text, file) {
67
79
  return value || {}
68
80
  }
69
81
 
82
+ /** @param {string} text */
70
83
  const formatting = (text) => ({ formattingOptions: /\n\t/.test(text) ? { insertSpaces: false, tabSize: 1 } : { insertSpaces: true, tabSize: 2 } })
71
84
 
85
+ /**
86
+ * @param {string} text
87
+ * @param {import('jsonc-parser').JSONPath} keyPath
88
+ * @param {unknown} value
89
+ */
72
90
  function set (text, keyPath, value) {
73
91
  return applyEdits(text, modify(text, keyPath, value, formatting(text)))
74
92
  }
@@ -76,6 +94,8 @@ function set (text, keyPath, value) {
76
94
  /**
77
95
  * El texto de `settings.json` con el perfil puesto (`profile`) o quitado (`profile: null`).
78
96
  * Al quitar, el perfil por defecto solo se toca si era el nuestro.
97
+ * @param {string} text
98
+ * @param {{ profile: { path: string, args: string[] } | null, platform?: string, file?: string }} o
79
99
  */
80
100
  export function applyToSettings (text, { profile, platform = platformKey(), file = 'settings.json' }) {
81
101
  const src = text.trim() ? text : '{}\n'
@@ -98,6 +118,7 @@ export function applyToSettings (text, { profile, platform = platformKey(), file
98
118
  /**
99
119
  * Lo aplica a cada editor instalado. Devuelve `[{ name, settings, changed }]`. Sin ninguno,
100
120
  * lanza `no-editor`; un `settings.json` que no se puede leer lanza `bad-settings` y no se toca.
121
+ * @param {{ profile: { path: string, args: string[] } | null, base?: string, platform?: string }} o
101
122
  */
102
123
  export function configureEditors ({ profile, base = configBase(), platform = platformKey() }) {
103
124
  const editors = findEditors(base)
package/far-messages.js CHANGED
@@ -8,10 +8,12 @@
8
8
  * @param {(es: string, en: string) => string} t elige el idioma
9
9
  */
10
10
  export function farMessage (r, t) {
11
- return ({
11
+ /** @type {Record<string, string>} */
12
+ const texts = {
12
13
  'not-linked': t('esta máquina no está enlazada con tu bóveda, así que no ve tus otras máquinas. Enlázala con: dotrino-terminal link', 'this machine is not linked to your vault, so it cannot see your other machines. Link it with: dotrino-terminal link'),
13
14
  'no-record': t('no se pudo preguntar a tu bóveda qué máquinas tienes. Comprueba que esté encendida y que esta máquina tenga conexión.', 'could not ask your vault which machines you have. Check that it is on and that this machine is online.'),
14
15
  'no-machine': t('no hay ninguna máquina encendida con ese id o nombre (mira «dotrino-terminal machines»).', 'no machine with that id or name is on (see "dotrino-terminal machines").'),
15
16
  'ambiguous-machine': t('hay más de una máquina con ese nombre: usa su id (mira «dotrino-terminal machines»).', 'more than one machine has that name: use its id (see "dotrino-terminal machines").')
16
- })[r.code] || `${r.message} (${r.code})`
17
+ }
18
+ return texts[r.code ?? ''] || `${r.message} (${r.code})`
17
19
  }
package/far.js CHANGED
@@ -39,12 +39,28 @@ export const IDLE_MS = 60_000
39
39
  /** Lo que se espera la respuesta de una máquina antes de darla por apagada. */
40
40
  export const ANSWER_MS = 8000
41
41
 
42
+ /** @type {(code: string, message: string) => Error & { code: string }} */
42
43
  const fail = (code, message) => Object.assign(new Error(message), { code })
43
44
 
45
+ /** @typedef {import('./types/agent.js').SessionLike} SessionLike */
46
+ /** @typedef {import('./types/agent.js').ConsoleInfo} ConsoleInfo */
47
+ /** Una máquina de la cuenta con agente de terminal encendido. */
48
+ /** @typedef {{ sub: string, id: string, name: string }} Found */
49
+ /**
50
+ * Lo que se sabe de una máquina: su conexión de control (si está abierta), sus consolas, si
51
+ * pide clave y el último fallo.
52
+ * @typedef {Found & { rc: RemoteAgentClient | null, consoles: ConsoleInfo[] | null, locked: boolean, error: { code: string, message: string } | null }} Machine
53
+ */
54
+ /** @typedef {{ probe: import('@dotrino/proxy-client').WebSocketProxyClient | null, askedVaultAt?: number }} DiscoverState */
55
+
44
56
  /** `AB12-CD34`, como sale en `dotrino-vault members`. */
45
57
  export const shortId = keyLabel
46
58
 
47
- /** Las máquinas con agente de terminal encendido, con el transporte de verdad. */
59
+ /**
60
+ * Las máquinas con agente de terminal encendido, con el transporte de verdad.
61
+ * @param {{ link: DotrinoDeviceLink, dir: string, kind: string, state: DiscoverState }} o
62
+ * @returns {Promise<Found[]>}
63
+ */
48
64
  async function discoverReal ({ link, dir, kind, state }) {
49
65
  const cl = clientLink(link, { dir })
50
66
  const fresh = !state.askedVaultAt || Date.now() - state.askedVaultAt >= MEMBERS_MS
@@ -57,6 +73,7 @@ async function discoverReal ({ link, dir, kind, state }) {
57
73
  await state.probe.connect()
58
74
  }
59
75
  const found = await probeAgents(state.probe, members.map((m) => m.sub))
76
+ /** @type {Found[]} */
60
77
  const out = []
61
78
  for (const m of members) {
62
79
  if (found.get(m.sub)?.kind !== kind) continue
@@ -65,7 +82,11 @@ async function discoverReal ({ link, dir, kind, state }) {
65
82
  return out
66
83
  }
67
84
 
68
- /** Una sesión con el agente de otra máquina. */
85
+ /**
86
+ * Una sesión con el agente de otra máquina.
87
+ * @param {{ link: DotrinoDeviceLink, dir: string, sub: string, loadLink?: () => DotrinoDeviceLink | null }} o
88
+ * @returns {Promise<RemoteAgentClient>}
89
+ */
69
90
  async function connectReal ({ link, dir, sub, loadLink }) {
70
91
  // EL ACTA DE CONFIANZA DE ESTE AGENTE, leída del disco en cada saludo: la mantiene al día su
71
92
  // lado de agente (cada 5 min y con los avisos de la bóveda). Sin ella el cliente le pedía el
@@ -73,7 +94,7 @@ async function connectReal ({ link, dir, sub, loadLink }) {
73
94
  // máquina (2026-11-04). Si con ella no pasa, el cliente sí pregunta a la bóveda.
74
95
  const trustedActa = () => {
75
96
  const l = loadLink?.() || link
76
- return l?.actaTrusted === true && l.acta ? l.acta : null
97
+ return l?.actaTrusted === true && l.acta ? /** @type {object} */ (l.acta) : null
77
98
  }
78
99
  const rc = new RemoteAgentClient(clientLink(link, { dir }), { agentPubkey: sub, trustedActa })
79
100
  await rc.connect()
@@ -83,25 +104,31 @@ async function connectReal ({ link, dir, sub, loadLink }) {
83
104
  /**
84
105
  * @param {object} opts
85
106
  * @param {string} opts.dir la carpeta del enlace de este agente.
86
- * @param {() => object|null} opts.loadLink el enlace, leído cada vez (puede aparecer después).
107
+ * @param {() => DotrinoDeviceLink|null} opts.loadLink el enlace, leído cada vez (puede aparecer después).
87
108
  * @param {string} opts.kind el tipo de agente que se busca (`terminal-agent`).
88
- * @param {Function} [opts.discover] para las pruebas.
89
- * @param {Function} [opts.connect] para las pruebas.
109
+ * @param {typeof discoverReal} [opts.discover] para las pruebas.
110
+ * @param {typeof connectReal} [opts.connect] para las pruebas.
90
111
  * @param {number} [opts.refreshMs]
91
112
  * @param {number} [opts.discoverMs]
92
113
  * @param {number} [opts.idleMs]
93
114
  * @param {number} [opts.answerMs]
115
+ * @param {(line: string) => void} [opts.log]
94
116
  */
95
117
  export function makeFar ({ dir, loadLink, kind, discover = discoverReal, connect = connectReal, refreshMs = REFRESH_MS, discoverMs = DISCOVER_MS, idleMs = IDLE_MS, answerMs = ANSWER_MS, log = (line) => console.error(line) }) {
96
118
  /** sub → { sub, id, name, rc, consoles, locked, error } */
119
+ /** @type {Map<string, Machine>} */
97
120
  const machines = new Map()
98
121
  /** sub → la clave que una ventana escribió bien (solo en memoria). */
122
+ /** @type {Map<string, string>} */
99
123
  const codes = new Map()
124
+ /** @type {DiscoverState} */
100
125
  const state = { probe: null }
101
126
  let discoveredAt = 0
102
127
  let refreshedAt = 0
128
+ /** @type {Promise<void> | null} */
103
129
  let refreshing = null
104
- let idle = null
130
+ /** @type {ReturnType<typeof setTimeout> | undefined} */
131
+ let idle
105
132
  let closed = false
106
133
 
107
134
  /**
@@ -111,12 +138,19 @@ export function makeFar ({ dir, loadLink, kind, discover = discoverReal, connect
111
138
  * solo al CAMBIAR (falla, cambia de motivo o se recupera): el refresco va cada pocos segundos
112
139
  * y una línea por vuelta ahogaría el log.
113
140
  */
141
+ /** @type {Map<string, string>} */
114
142
  const lastError = new Map()
115
- function report (what, err, ms) {
143
+ /**
144
+ * @param {string} what
145
+ * @param {{ code?: string, message?: string } | null | unknown} failure
146
+ * @param {number} [ms]
147
+ */
148
+ function report (what, failure, ms) {
149
+ const err = /** @type {{ code?: string, message?: string } | null} */ (failure)
116
150
  const code = err ? (err.code || 'error') : null
117
151
  if ((lastError.get(what) ?? null) === code) return
118
152
  const took = typeof ms === 'number' ? ` after ${ms} ms` : ''
119
- if (code) log(`[far] ${new Date().toISOString()} ${what}: ${code}${took} · ${err.message || ''}`)
153
+ if (code) log(`[far] ${new Date().toISOString()} ${what}: ${code}${took} · ${err?.message || ''}`)
120
154
  else log(`[far] ${new Date().toISOString()} ${what}: ok again${took}`)
121
155
  if (code) lastError.set(what, code); else lastError.delete(what)
122
156
  }
@@ -127,7 +161,13 @@ export function makeFar ({ dir, loadLink, kind, discover = discoverReal, connect
127
161
  return l
128
162
  }
129
163
 
130
- /** Una pregunta por la conexión de control de una máquina, y su respuesta (o `fail`). */
164
+ /**
165
+ * Una pregunta por la conexión de control de una máquina, y su respuesta (o `fail`).
166
+ * @param {RemoteAgentClient} rc
167
+ * @param {object} msg
168
+ * @param {string} type
169
+ * @returns {Promise<any>} la respuesta de la máquina (`type` o `fail`)
170
+ */
131
171
  function ask (rc, msg, type) {
132
172
  return new Promise((resolve, reject) => {
133
173
  const off = rc.on('message', (m) => { if (m?.type === type || m?.type === 'fail') { done(); resolve(m) } })
@@ -138,12 +178,16 @@ export function makeFar ({ dir, loadLink, kind, discover = discoverReal, connect
138
178
  })
139
179
  }
140
180
 
181
+ /** @param {Machine} m */
141
182
  function drop (m) {
142
183
  try { m.rc?.close() } catch (_) {}
143
184
  m.rc = null
144
185
  }
145
186
 
146
- /** Las consolas de una máquina, abriendo su conexión de control si hace falta. */
187
+ /**
188
+ * Las consolas de una máquina, abriendo su conexión de control si hace falta.
189
+ * @param {Machine} m
190
+ */
147
191
  async function readOne (m) {
148
192
  const t0 = Date.now()
149
193
  try {
@@ -168,7 +212,7 @@ export function makeFar ({ dir, loadLink, kind, discover = discoverReal, connect
168
212
  // No contestó o la sesión cayó: la conexión se suelta y la próxima pasada abre otra.
169
213
  drop(m)
170
214
  m.consoles = null; m.locked = false
171
- m.error = { code: e.code || 'unreachable', message: e.message }
215
+ m.error = { code: /** @type {Thrown} */ (e).code || 'unreachable', message: /** @type {Thrown} */ (e).message }
172
216
  report(`machine ${m.id}`, m.error, Date.now() - t0)
173
217
  }
174
218
  }
@@ -236,7 +280,11 @@ export function makeFar ({ dir, loadLink, kind, discover = discoverReal, connect
236
280
  return snapshot()
237
281
  }
238
282
 
239
- /** La máquina que se nombró: por su llave, por su id (`AB12-CD34`) o por su nombre. */
283
+ /**
284
+ * La máquina que se nombró: por su llave, por su id (`AB12-CD34`) o por su nombre.
285
+ * @param {unknown} ref
286
+ * @returns {Promise<Machine>}
287
+ */
240
288
  async function resolve (ref) {
241
289
  const want = String(ref || '').trim()
242
290
  if (!want) throw fail('no-machine', 'which machine?')
@@ -256,44 +304,57 @@ export function makeFar ({ dir, loadLink, kind, discover = discoverReal, connect
256
304
  /**
257
305
  * La ventana pasa a hablar con otra máquina: todo lo que mande va allí y todo lo que venga
258
306
  * de allí vuelve, tal cual. Contesta `{ type:'via', machine }` cuando el tubo está puesto.
307
+ * @param {SessionLike} session
308
+ * @param {unknown} ref
259
309
  */
260
310
  async function via (session, ref) {
311
+ /** @type {object[]} */
261
312
  const queue = []
313
+ /** @type {RemoteAgentClient | null} */
262
314
  let rc = null
263
315
  let gone = false
316
+ /** @type {string | null} */
264
317
  let typed = null // la clave que se acaba de mandar, hasta saber si valió
265
318
  // La ventana se cerró. Antes de cortar se SUELTA la consola: la otra máquina no ve caer
266
319
  // esta conexión hasta que se le agota la espera, y mientras tanto la consola seguía
267
320
  // saliendo «abierta desde otro aparato» sin nadie mirándola.
268
321
  const bye = () => {
269
322
  gone = true
270
- if (!rc) return
271
- const end = () => { try { rc.close() } catch (_) {} }
272
- rc.send({ type: 'detach' }).then(end, end)
323
+ const conn = rc
324
+ if (!conn) return
325
+ const end = () => { try { conn.close() } catch (_) {} }
326
+ conn.send({ type: 'detach' }).then(end, end)
273
327
  }
274
328
  session.on('close', bye)
329
+ /** @param {any} msg lo que manda la ventana, tal cual */
275
330
  const forward = (msg) => {
276
331
  if (msg?.type === 'unlock') typed = String(msg.code ?? '')
277
- rc.send(msg).catch((e) => session.send({ type: 'fail', code: e.code || 'far-send', message: e.message }))
332
+ // Solo se reenvía con la conexión abierta: antes, los mensajes esperan en `queue`.
333
+ if (!rc) throw new Error('far: forwarding before the connection is up')
334
+ rc.send(msg).catch((/** @type {Thrown} */ e) => session.send({ type: 'fail', code: e.code || 'far-send', message: e.message }))
278
335
  }
279
336
  session.on('message', (msg) => { if (rc) forward(msg); else queue.push(msg) })
337
+ /** @type {Machine} */
280
338
  let m
339
+ /** @type {RemoteAgentClient} */
340
+ let conn
281
341
  try {
282
342
  m = await resolve(ref)
283
- rc = await connect({ link: link(), dir, sub: m.sub, loadLink })
343
+ rc = conn = await connect({ link: link(), dir, sub: m.sub, loadLink })
284
344
  } catch (e) {
285
- session.send({ type: 'fail', code: e.code || 'unreachable', message: e.message })
345
+ session.send({ type: 'fail', code: /** @type {Thrown} */ (e).code || 'unreachable', message: /** @type {Thrown} */ (e).message })
286
346
  return
287
347
  }
288
- if (gone) { try { rc.close() } catch (_) {} return }
348
+ if (gone) { try { conn.close() } catch (_) {} return }
349
+ /** @type {string | null} */
289
350
  let attached = null // la consola que mira la ventana allí
290
- rc.on('message', (p) => {
351
+ conn.on('message', (p) => {
291
352
  if (p?.type === 'attached') attached = p.id
292
353
  if (p?.type === 'unlocked' && typed != null) { codes.set(m.sub, typed); typed = null }
293
354
  if (p?.type === 'fail' && (p.code === 'bad-code' || p.code === 'wait')) typed = null
294
355
  session.send(p)
295
356
  })
296
- rc.on('error', (e) => session.send({ type: 'fail', code: e.code || 'far-error', message: e.message }))
357
+ conn.on('error', (e) => session.send({ type: 'fail', code: e.code || 'far-error', message: e.message }))
297
358
  // LA SESIÓN CON LA OTRA MÁQUINA SE PERDIÓ y se abrió otra: o la máquina se reinició, o la
298
359
  // sesión venció (una hora sin mensajes, SESSION_IDLE_MS: una consola quieta; la otra máquina
299
360
  // lo avisa en el momento, remote-agent ≥ 0.27). Se pregunta a la sesión nueva:
@@ -302,25 +363,29 @@ export function makeFar ({ dir, loadLink, kind, discover = discoverReal, connect
302
363
  // 2026-10-27). Antes el panel la reenviaba solo y las consolas seguían a la vista.
303
364
  // - la consola de la ventana sigue allí: solo venció la sesión, la ventana se vuelve a enganchar.
304
365
  // - no está: la máquina se reinició y sus consolas ya no existen. Se dice; no se inventa otra.
305
- rc.on('resumed', () => {
306
- ask(rc, { type: 'list' }, 'consoles').then((r) => {
366
+ conn.on('resumed', () => {
367
+ ask(conn, { type: 'list' }, 'consoles').then((r) => {
307
368
  if (r.type === 'fail' && r.code === 'locked') {
308
369
  codes.delete(m.sub)
309
370
  const panel = machines.get(m.sub)
310
371
  if (panel) { drop(panel); panel.consoles = null; panel.locked = true; panel.error = null }
311
372
  session.send({ type: 'fail', code: 'locked-again', message: 'that machine asks for its code again' })
312
- } else if (r.type === 'consoles' && attached && r.list.some((c) => c.id === attached)) {
373
+ } else if (r.type === 'consoles' && attached && r.list.some((/** @type {ConsoleInfo} */ c) => c.id === attached)) {
313
374
  session.send({ type: 'fail', code: 'session-resumed', message: 'the session with that machine was renewed' })
314
375
  } else {
315
376
  session.send({ type: 'fail', code: 'machine-restarted', message: 'that machine restarted: its consoles are gone' })
316
377
  }
317
- }, (e) => session.send({ type: 'fail', code: e.code || 'unreachable', message: e.message }))
378
+ }, (/** @type {Thrown} */ e) => session.send({ type: 'fail', code: e.code || 'unreachable', message: e.message }))
318
379
  })
319
380
  session.send({ type: 'via', machine: { sub: m.sub, id: m.id, name: m.name } })
320
381
  for (const msg of queue.splice(0)) forward(msg)
321
382
  }
322
383
 
323
- /** Una orden suelta a otra máquina (cerrar una consola, moverla, su nota), sin ventana. */
384
+ /**
385
+ * Una orden suelta a otra máquina (cerrar una consola, moverla, su nota), sin ventana.
386
+ * @param {unknown} ref
387
+ * @param {object} msg
388
+ */
324
389
  async function send (ref, msg) {
325
390
  const m = await resolve(ref)
326
391
  if (!m.rc) await readOne(m)
package/index.js CHANGED
@@ -52,8 +52,13 @@ import { makeUploads } from './uploads.js'
52
52
  import { readPiece } from './downloads.js'
53
53
 
54
54
  const require = createRequire(import.meta.url)
55
+ /** @type {{ version: string }} */
55
56
  const { version: VERSION } = require('./package.json')
56
57
 
58
+ /** @typedef {import('./types/agent.js').Viewer} Viewer */
59
+ /** @typedef {import('./types/agent.js').SessionLike} SessionLike */
60
+ /** @typedef {ReturnType<typeof makeFar>} Far */
61
+
57
62
  /** Cuánto se espera al canal directo antes de mandar el historial por el proxio. */
58
63
  export const HISTORY_WAIT_MS = 8000
59
64
 
@@ -71,21 +76,27 @@ export const LINK_POLL_MS = 2000
71
76
  /** Cada cuánto se reintenta la parte remota cuando no pudo arrancar (sin red, proxio caído). */
72
77
  const REMOTE_RETRY_MS = 15_000
73
78
 
79
+ /** @returns {typeof import('node-pty')} */
74
80
  export function loadPty () {
75
81
  // node-pty (Microsoft, el de VS Code) ≥ 1.2 trae los binarios DENTRO del paquete para Linux,
76
82
  // macOS y Windows: no compila ni descarga nada al instalarse (funciona con ignore-scripts).
77
83
  // Antes: @homebridge/node-pty-prebuilt-multiarch, que los bajaba al instalar con
78
84
  // prebuild-install, abandonado (npm avisaba «deprecated»).
79
85
  try { return require('node-pty') } catch (e) {
80
- throw new Error('PTY module missing. Reinstall the agent: `npx @dotrino/terminal-agent` (' + e.message + ')')
86
+ throw new Error('PTY module missing. Reinstall the agent: `npx @dotrino/terminal-agent` (' + /** @type {Thrown} */ (e).message + ')')
81
87
  }
82
88
  }
83
89
 
90
+ /** @param {unknown} p */
84
91
  const isDir = (p) => {
85
92
  try { return typeof p === 'string' && path.isAbsolute(p) && fs.statSync(p).isDirectory() } catch (_) { return false }
86
93
  }
87
94
 
88
- /** Las consolas de este agente, sobre el PTY. Exportada para las pruebas. */
95
+ /**
96
+ * Las consolas de este agente, sobre el PTY. Exportada para las pruebas.
97
+ * @param {typeof import('node-pty')} pty
98
+ * @param {{ shell?: string, quietMs?: number, dir?: string }} [opts]
99
+ */
89
100
  export function makeHub (pty, opts = {}) {
90
101
  const shell = opts.shell || process.env.SHELL || (process.platform === 'win32' ? 'powershell.exe' : 'bash')
91
102
  return new ConsoleHub({
@@ -114,17 +125,19 @@ export function makeHub (pty, opts = {}) {
114
125
  * teléfono, redimensionar la ventana). Escribir o dar foco no cambia nada.
115
126
  * Exportada para las pruebas.
116
127
  *
117
- * @param {object} session
128
+ * @param {SessionLike} session
118
129
  * @param {ConsoleHub} hub
119
- * @param {{ origin?: 'local'|'remote', gate?: ReturnType<typeof makeGate>, uploadsDir?: string }} [opts]
130
+ * @param {{ origin?: 'local'|'remote', gate?: ReturnType<typeof makeGate> | null, uploadsDir?: string | null }} [opts]
120
131
  * `gate`: la clave de la máquina (access.js). Solo se le pide a las sesiones remotas.
121
132
  * `uploadsDir`: dónde se guardan las imágenes que manda esta sesión (uploads.js). Sin ella,
122
133
  * mandar una imagen falla con `no-uploads`.
123
134
  */
124
135
  export function serveSession (session, hub, { origin = 'remote', gate = null, uploadsDir = null } = {}) {
136
+ /** @type {import('./consoles.js').Console | null} */
125
137
  let current = null
126
138
  const uploads = uploadsDir ? makeUploads(uploadsDir) : null
127
139
  let size = { cols: 80, rows: 24 }
140
+ /** @type {Viewer} */
128
141
  const viewer = {
129
142
  origin,
130
143
  device: session.device || null,
@@ -136,6 +149,7 @@ export function serveSession (session, hub, { origin = 'remote', gate = null, up
136
149
  onMeta: (info) => { session.send({ type: 'meta', console: info }) }
137
150
  }
138
151
  const release = () => { if (current) { current.detach(viewer); current = null } }
152
+ /** @type {(code: string, message: string, extra?: object) => unknown} */
139
153
  const fail = (code, message, extra = {}) => session.send({ type: 'fail', code, message, ...extra })
140
154
  // La clave de la máquina: una vez escrita vale para ESTA conexión.
141
155
  let unlocked = false
@@ -144,14 +158,20 @@ export function serveSession (session, hub, { origin = 'remote', gate = null, up
144
158
  if (origin !== 'remote' || !gate || unlocked) return true
145
159
  try {
146
160
  if (!gate.required()) return true
147
- } catch (e) { fail(e.code || 'access-unreadable', e.message); return false }
161
+ } catch (e) { fail(/** @type {Thrown} */ (e).code || 'access-unreadable', /** @type {Thrown} */ (e).message); return false }
148
162
  fail('locked', 'this machine asks for its code')
149
163
  return false
150
164
  }
165
+ /** @param {any} msg lo que llegó de la sesión */
151
166
  const takeSize = (msg) => { if (msg.cols && msg.rows) { size = { cols: msg.cols, rows: msg.rows }; viewer.size = size } }
152
167
  // La etiqueta con la que se presenta quien mira (una ventana de la app de escritorio).
168
+ /** @param {any} msg lo que llegó de la sesión */
153
169
  const takeTag = (msg) => { if (typeof msg.tag === 'string') viewer.tag = msg.tag.slice(0, 64) }
154
170
 
171
+ /**
172
+ * @param {import('./consoles.js').Console} c
173
+ * @param {{ fresh: boolean, keep?: boolean }} o
174
+ */
155
175
  async function attachTo (c, { fresh, keep = false }) {
156
176
  release()
157
177
  current = c
@@ -159,7 +179,7 @@ export function serveSession (session, hub, { origin = 'remote', gate = null, up
159
179
  // son cientos de KB y, mandada ya, da toda la vuelta por el proxio (medido: 381 KB por el
160
180
  // proxio en cada enganche). La pantalla sola son unos pocos KB y se ve igual de rápido; el
161
181
  // historial sale en cuanto abre el directo (`sendHistory`). No se espera a nada para pintar.
162
- const later = origin === 'remote' && typeof session.whenDirect === 'function' && !session.direct() && c.hasHistory()
182
+ const later = origin === 'remote' && typeof session.whenDirect === 'function' && !session.direct?.() && c.hasHistory()
163
183
  const snapshot = await c.attach(viewer, later ? { scrollback: 0 } : {})
164
184
  // Mientras se hacía la foto la sesión se fue, soltó la consola o pidió otra: esta ya no es la
165
185
  // suya. Quedarse enganchado dejaba un mirón FANTASMA (la consola salía «abierta en otro
@@ -179,15 +199,16 @@ export function serveSession (session, hub, { origin = 'remote', gate = null, up
179
199
  if (current !== c) return
180
200
  await session.send({ type: 'attached', id: c.id, fresh, console: c.info() })
181
201
  // Sin esperarlo (pintar no espera a nada), y un fallo aquí no puede tumbar el agente: se dice.
182
- if (later) sendHistory(c).catch((e) => console.error('[terminal-agent] could not send the history of console', c.id, '-', e?.message || e))
202
+ if (later) sendHistory(c).catch((/** @type {Thrown} */ e) => console.error('[terminal-agent] could not send the history of console', c.id, '-', e?.message || e))
183
203
  }
184
204
 
185
205
  /**
186
206
  * El historial que `attachTo` dejó para después. Sale cuando abre el canal directo; si en
187
207
  * `HISTORY_WAIT_MS` no abrió, sale igual por el proxio: llegar tarde es mejor que no llegar.
208
+ * @param {import('./consoles.js').Console} c
188
209
  */
189
210
  async function sendHistory (c) {
190
- await session.whenDirect(HISTORY_WAIT_MS)
211
+ await session.whenDirect?.(HISTORY_WAIT_MS)
191
212
  if (current !== c) return // ya mira otra, o se fue
192
213
  const full = await c.history(viewer)
193
214
  if (full == null || current !== c) return
@@ -208,7 +229,7 @@ export function serveSession (session, hub, { origin = 'remote', gate = null, up
208
229
  if (gate.required()) gate.check(msg.code, viewer.device)
209
230
  unlocked = true
210
231
  session.send({ type: 'unlocked' })
211
- } catch (e) { fail(e.code || 'access-unreadable', e.message, e.retryMs ? { retryMs: e.retryMs } : {}) }
232
+ } catch (e) { fail(/** @type {Thrown} */ (e).code || 'access-unreadable', /** @type {Thrown} */ (e).message, /** @type {Thrown} */ (e).retryMs ? { retryMs: /** @type {Thrown} */ (e).retryMs } : {}) }
212
233
  return
213
234
  }
214
235
  if (!mayPass()) return
@@ -261,16 +282,16 @@ export function serveSession (session, hub, { origin = 'remote', gate = null, up
261
282
  if (msg.type === 'file') {
262
283
  if (!uploads) return fail('no-uploads', 'this agent has nowhere to keep images')
263
284
  try { session.send({ type: 'filed', ...uploads.take(msg) }) } catch (e) {
264
- if (!e.code) console.error('[terminal-agent] could not keep an image:', e.message)
265
- fail(e.code || 'file-failed', e.message)
285
+ if (!/** @type {Thrown} */ (e).code) console.error('[terminal-agent] could not keep an image:', /** @type {Thrown} */ (e).message)
286
+ fail(/** @type {Thrown} */ (e).code || 'file-failed', /** @type {Thrown} */ (e).message)
266
287
  }
267
288
  return
268
289
  }
269
290
  // Un archivo de esta máquina, para abrirlo en el aparato (una ruta que salió en la consola).
270
291
  if (msg.type === 'fetch') {
271
292
  try { session.send({ type: 'fetched', ...readPiece(msg, current ? cwdOf(current.pty?.pid) : null) }) } catch (e) {
272
- if (!e.code || !['bad-fetch', 'no-cwd', 'no-file', 'no-read', 'is-dir', 'not-file', 'too-big', 'changed'].includes(e.code)) console.error('[terminal-agent] could not send a file:', e.message)
273
- fail(e.code || 'fetch-failed', e.message)
293
+ if (!/** @type {Thrown} */ (e).code || !['bad-fetch', 'no-cwd', 'no-file', 'no-read', 'is-dir', 'not-file', 'too-big', 'changed'].includes(/** @type {Thrown} */ (e).code)) console.error('[terminal-agent] could not send a file:', /** @type {Thrown} */ (e).message)
294
+ fail(/** @type {Thrown} */ (e).code || 'fetch-failed', /** @type {Thrown} */ (e).message)
274
295
  }
275
296
  return
276
297
  }
@@ -294,20 +315,33 @@ export function serveSession (session, hub, { origin = 'remote', gate = null, up
294
315
  * El uso de red de este agente: cada conexión con otro aparato, por qué camino va (directo,
295
316
  * TURN o el proxio) y cuánto pasó por cada uno. El mismo informe que el modal de red del topbar.
296
317
  * Una máquina de la cuenta sale con su nombre; cualquier otro aparato, con su id.
318
+ * @param {Far} far
297
319
  */
298
320
  export async function netOf (far) {
299
321
  const transports = await Promise.all(listTransports().map(async (c) => {
300
- try { return await c.stats() } catch (e) { return { url: c.url, error: e?.message || String(e) } }
322
+ // `url` existe en el cliente (client.js) pero el .d.ts de proxy-client no lo declara.
323
+ try { return await c.stats() } catch (e) { return { url: /** @type {{ url: string }} */ (/** @type {unknown} */ (c)).url, error: /** @type {Thrown} */ (e)?.message || String(e) } }
301
324
  }))
302
325
  const names = new Map(far.known().map((m) => [m.id, m.name ? `${m.name} ${m.id}` : m.id]))
326
+ /** @param {string} pubkey */
303
327
  const label = async (pubkey) => { const id = await shortId(pubkey); return names.get(id) || id }
304
328
  return { transports, report: await netReport(transports, { label }) }
305
329
  }
306
330
 
331
+ /**
332
+ * @param {SessionLike} session
333
+ * @param {ConsoleHub} hub
334
+ * @param {Far} far
335
+ * @param {{ uploadsDir?: string | null }} [opts]
336
+ */
307
337
  export function serveLocal (session, hub, far, { uploadsDir = null } = {}) {
338
+ /** @type {Record<'message' | 'close', ((msg?: any) => void)[]>} */
308
339
  const h = { message: [], close: [] }
309
- const inner = { device: null, send: (p) => session.send(p), on (ev, cb) { h[ev]?.push(cb); return this } }
340
+ /** @type {SessionLike} */
341
+ const inner = { device: null, send: (/** @type {object} */ p) => session.send(p), on (/** @type {'message' | 'close'} */ ev, /** @type {(msg?: any) => void} */ cb) { h[ev]?.push(cb); return this } }
342
+ /** @param {Thrown} e */
310
343
  const failed = (e) => session.send({ type: 'fail', code: e.code || 'far-error', message: e.message })
344
+ /** @type {'far' | 'hub' | null} */
311
345
  let mode = null
312
346
  session.on('message', (msg) => {
313
347
  if (!msg || typeof msg !== 'object') return
@@ -338,13 +372,14 @@ export function serveLocal (session, hub, far, { uploadsDir = null } = {}) {
338
372
  * @param {string} [opts.shell] shell a lanzar (default $SHELL).
339
373
  * @param {boolean} [opts.quiet]
340
374
  * @param {()=>void} [opts.onRevoked]
341
- * @param {(remote:object)=>void} [opts.onLinked] se enlazó mientras corría y ya atiende a otros aparatos.
375
+ * @param {(remote:import('@dotrino/remote-agent/agent').RemoteAgent)=>void} [opts.onLinked] se enlazó mientras corría y ya atiende a otros aparatos.
342
376
  * @param {(e:Error)=>void} [opts.onLinkError] se enlazó, pero la parte remota no arrancó.
343
- * @returns {Promise<{ consoles: ConsoleHub, socket: string, remote: object|null, machineId: string|null, close: ()=>void }>}
377
+ * @returns {Promise<{ consoles: ConsoleHub, socket: string, remote: import('@dotrino/remote-agent/agent').RemoteAgent|null, machineId: string|null, close: ()=>void }>}
344
378
  */
345
379
  export async function startAgent (opts = {}) {
346
380
  const dir = opts.dir || dataDir()
347
381
  const hub = makeHub(loadPty(), { ...opts, dir })
382
+ /** @type {import('@dotrino/remote-agent/agent').RemoteAgent | null} */
348
383
  let remote = null
349
384
  // TRES CLAVES MAL SEGUIDAS DE UN MISMO APARATO: se reporta a la bóveda, que se lo pone en
350
385
  // la mesa a quien aprueba (bloquear o ignorar). El freno local ya está puesto; esto es el
@@ -371,6 +406,7 @@ export async function startAgent (opts = {}) {
371
406
  onRevoked: () => { hub.killAll(); opts.onRevoked?.() },
372
407
  onSession: (session) => serveSession(session, hub, { origin: 'remote', gate, uploadsDir })
373
408
  })
409
+ /** @type {ReturnType<typeof setInterval> | null} */
374
410
  let watcher = null
375
411
  if (loadLink(dir)) {
376
412
  try { remote = await startRemote() } catch (e) {
@@ -378,34 +414,34 @@ export async function startAgent (opts = {}) {
378
414
  // una terminal no puede depender de internet. Antes el agente moría aquí y, con la
379
415
  // máquina enlazada, no se podía abrir ni una consola local. La parte remota se
380
416
  // reintenta por detrás hasta que salga; mientras, se dice.
381
- console.error(`[terminal-agent] the remote side did not start (${e.message}); local windows work, retrying every ${REMOTE_RETRY_MS / 1000} s`)
382
- opts.onLinkError?.(e)
417
+ console.error(`[terminal-agent] the remote side did not start (${/** @type {Thrown} */ (e).message}); local windows work, retrying every ${REMOTE_RETRY_MS / 1000} s`)
418
+ opts.onLinkError?.(/** @type {Thrown} */ (e))
383
419
  let trying = false
384
- watcher = setInterval(() => {
420
+ const timer = watcher = setInterval(() => {
385
421
  if (trying) return
386
422
  trying = true
387
423
  startRemote().then((r) => {
388
424
  if (stopped) { r.close(); return }
389
- clearInterval(watcher); watcher = null
425
+ clearInterval(timer); watcher = null
390
426
  remote = r
391
427
  opts.onLinked?.(r)
392
428
  }).catch(() => {}).finally(() => { trying = false })
393
429
  }, REMOTE_RETRY_MS)
394
- watcher.unref()
430
+ timer.unref()
395
431
  }
396
432
  } else {
397
433
  // Sin enlace: se mira cada poco si aparece (`dotrino-terminal link` desde una ventana).
398
434
  // Al aparecer se enciende la parte remota SIN reiniciar, así las consolas abiertas siguen.
399
- watcher = setInterval(() => {
435
+ const timer = watcher = setInterval(() => {
400
436
  if (!loadLink(dir)) return
401
- clearInterval(watcher); watcher = null
437
+ clearInterval(timer); watcher = null
402
438
  startRemote().then((r) => {
403
439
  if (stopped) { r.close(); return }
404
440
  remote = r
405
441
  opts.onLinked?.(r)
406
442
  }).catch((e) => opts.onLinkError?.(e))
407
443
  }, LINK_POLL_MS)
408
- watcher.unref()
444
+ timer.unref()
409
445
  }
410
446
  // Parar el agente sí mata las consolas: sin agente no hay quién las atienda.
411
447
  return {
package/link.js CHANGED
@@ -19,6 +19,8 @@ export const LABEL = 'terminal-agent'
19
19
  /**
20
20
  * La carpeta del enlace. `DOTRINO_TERMINAL_DIR` fuerza una concreta (un contenedor); si no,
21
21
  * la de la instancia `name` (sin nombre se busca y solo se exige con empate).
22
+ * @param {string | null} [name]
23
+ * @returns {string}
22
24
  */
23
25
  export function dataDir (name) {
24
26
  if (process.env.DOTRINO_TERMINAL_DIR) return process.env.DOTRINO_TERMINAL_DIR
@@ -35,6 +37,10 @@ export function enroll ({ qr, dir = dataDir(), label = LABEL, onChallenge }) {
35
37
  return raEnroll({ qr, dir, label, onChallenge })
36
38
  }
37
39
 
40
+ /**
41
+ * @param {string} q
42
+ * @returns {Promise<string>}
43
+ */
38
44
  function ask (q) {
39
45
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
40
46
  return new Promise((resolve) => rl.question(q, (a) => { rl.close(); resolve(a) }))
@@ -44,6 +50,7 @@ function ask (q) {
44
50
  * Enlaza la carpeta `dir` con la bóveda, preguntando en la terminal: la invitación de
45
51
  * `dotrino-vault pair` y, mientras se espera, el código que hay que aprobar. Lo usan el
46
52
  * agente (`dotrino-terminal-agent enroll`) y las ventanas (`dotrino-terminal link`).
53
+ * @param {string} dir
47
54
  */
48
55
  export async function linkInteractive (dir) {
49
56
  if (!process.stdin.isTTY) {
@@ -76,9 +83,11 @@ export async function linkInteractive (dir) {
76
83
  */
77
84
  export async function listProfiles () {
78
85
  const root = instancesRoot(LABEL)
86
+ /** @type {string[]} */
79
87
  let names = []
80
88
  try { names = fs.readdirSync(root).filter((n) => isValidName(n) && fs.statSync(path.join(root, n)).isDirectory()) } catch (_) {}
81
89
  if (!names.length) names = [DEFAULT_NAME]
90
+ /** @type {{ name: string, dir: string, linked: boolean, id: string|null, vault: string|null, scope: string[] }[]} */
82
91
  const out = []
83
92
  for (const name of names.sort()) {
84
93
  const dir = path.join(root, name)