@dotrino/terminal-agent 0.53.0 → 0.54.1

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/bin/terminal.js CHANGED
@@ -55,12 +55,17 @@ import { farMessage as farMessageFor } from '../far-messages.js'
55
55
  import { hasAccessCode, setAccessCode, clearAccessCode, MIN_LENGTH } from '../access.js'
56
56
  import { configureEditors, terminalProfile } from '../editors.js'
57
57
 
58
+ /** @type {{ version: string }} */
58
59
  const { version: VERSION } = createRequire(import.meta.url)('../package.json')
60
+ /** La conexión con el agente de esta máquina (`local.js`). */
61
+ /** @typedef {Awaited<ReturnType<typeof connectLocal>>} Conn */
59
62
  const args = process.argv.slice(2)
60
63
  const cmd = args[0] && !args[0].startsWith('-') ? args[0] : 'open'
64
+ /** @param {string} name */
61
65
  const opt = (name) => { const i = args.indexOf(name); return i >= 0 ? args[i + 1] : undefined }
62
66
 
63
67
  const es = /^es/i.test(process.env.LC_ALL || process.env.LC_MESSAGES || process.env.LANG || '')
68
+ /** @type {(esText: string, enText: string) => string} */
64
69
  const t = (esText, enText) => (es ? esText : enText)
65
70
 
66
71
  const DETACH_PREFIX = '\x1d' // Ctrl+]
@@ -173,6 +178,10 @@ Closing the window does not close the console: it stays open and can be picked u
173
178
  * error desaparecería con la ventana sin que nadie lo leyera.
174
179
  */
175
180
  const HOLD = Symbol('hold')
181
+ /**
182
+ * @param {string} msg
183
+ * @returns {never}
184
+ */
176
185
  function die (msg) {
177
186
  // Si la TTY ya estaba en crudo (ver `captureEarly`), se devuelve a normal para que el
178
187
  // mensaje salga con sus saltos de línea.
@@ -193,7 +202,9 @@ function die (msg) {
193
202
  * consola. Ahora la TTY pasa a crudo nada más empezar, y lo tecleado se guarda y se manda
194
203
  * entero cuando la consola está lista.
195
204
  */
205
+ /** @type {Buffer[]} */
196
206
  const early = []
207
+ /** @param {Buffer} b */
197
208
  const earlyTap = (b) => early.push(b)
198
209
  function captureEarly () {
199
210
  if (!process.stdin.isTTY) return
@@ -202,11 +213,15 @@ function captureEarly () {
202
213
  process.stdin.on('data', earlyTap)
203
214
  }
204
215
 
205
- /** El agente de esta máquina; si no hay ninguno escuchando, lo levanta y espera a que conteste. */
216
+ /**
217
+ * El agente de esta máquina; si no hay ninguno escuchando, lo levanta y espera a que conteste.
218
+ * @param {string} dir
219
+ * @returns {Promise<Conn>}
220
+ */
206
221
  async function agent (dir) {
207
222
  try { return await connectLocal(dir) } catch (e) {
208
- if (e.code === 'EAGENTACCESS') throw new Error(t(`el agente de este perfil corre con otros permisos y no deja entrar a esta ventana (${e.cause?.code}). Reinícialo: dotrino-terminal restart`, `this profile's agent runs with other permissions and does not let this window in (${e.cause?.code}). Restart it: dotrino-terminal restart`))
209
- if (e.code !== 'ENOAGENT') throw e
223
+ if (/** @type {Thrown} */ (e).code === 'EAGENTACCESS') throw new Error(t(`el agente de este perfil corre con otros permisos y no deja entrar a esta ventana (${/** @type {Thrown} */ (e).cause?.code}). Reinícialo: dotrino-terminal restart`, `this profile's agent runs with other permissions and does not let this window in (${/** @type {Thrown} */ (e).cause?.code}). Restart it: dotrino-terminal restart`))
224
+ if (/** @type {Thrown} */ (e).code !== 'ENOAGENT') throw e
210
225
  }
211
226
  // Un agente vivo sin socket es uno anterior a las ventanas (< 0.6.0): no se levanta otro
212
227
  // encima (tendrían la misma llave), se dice.
@@ -226,7 +241,8 @@ async function agent (dir) {
226
241
  const cli = fs.realpathSync(fileURLToPath(new URL('./cli.js', import.meta.url)))
227
242
  if (!(!opt('--dir') && !process.env.DOTRINO_TERMINAL_DIR && startService({ name: path.basename(dir), dir, cli }))) {
228
243
  const fd = fs.openSync(log, 'a', 0o600)
229
- const extra = opt('--name') ? ['--name', opt('--name')] : []
244
+ const name = opt('--name')
245
+ const extra = name ? ['--name', name] : []
230
246
  // Sin TTY: si la máquina no está enlazada, el agente atiende solo a las ventanas locales.
231
247
  // `windowsHide`: en Windows un proceso aparte abre su propia ventana de consola.
232
248
  const child = spawn(process.execPath, [cli, ...extra], { detached: true, windowsHide: true, stdio: ['ignore', fd, fd], env: process.env })
@@ -236,7 +252,7 @@ async function agent (dir) {
236
252
  const t0 = Date.now()
237
253
  while (Date.now() - t0 < 10000) {
238
254
  await new Promise((r) => setTimeout(r, 100))
239
- try { return await connectLocal(dir) } catch (e) { if (e.code !== 'ENOAGENT') throw e }
255
+ try { return await connectLocal(dir) } catch (e) { if (/** @type {Thrown} */ (e).code !== 'ENOAGENT') throw e }
240
256
  }
241
257
  throw new Error(t(`el agente no arrancó; mira ${log}`, `the agent did not start; see ${log}`))
242
258
  }
@@ -244,8 +260,9 @@ async function agent (dir) {
244
260
  /** `--tag <t>`: cómo se presenta esta ventana en la lista de quién mira (la app de escritorio). */
245
261
  const tag = () => (opt('--tag') ? { tag: opt('--tag') } : {})
246
262
 
263
+ /** @param {number} pid */
247
264
  function alive (pid) {
248
- try { process.kill(pid, 0); return true } catch (e) { return e.code === 'EPERM' }
265
+ try { process.kill(pid, 0); return true } catch (e) { return /** @type {Thrown} */ (e).code === 'EPERM' }
249
266
  }
250
267
 
251
268
  async function profiles () {
@@ -265,9 +282,9 @@ function vscode () {
265
282
  const profile = off ? null : terminalProfile({ node: process.execPath, script: fs.realpathSync(fileURLToPath(import.meta.url)), name })
266
283
  let done
267
284
  try { done = configureEditors({ profile }) } catch (e) {
268
- if (e.code === 'no-editor') die(t('no encontré VS Code, VS Code Insiders, VSCodium ni Cursor en esta cuenta.', 'could not find VS Code, VS Code Insiders, VSCodium or Cursor in this account.'))
269
- if (e.code === 'bad-settings') die(t(`no se pudo leer la configuración y no se tocó nada: ${e.message}`, `could not read the settings and nothing was changed: ${e.message}`))
270
- if (e.code === 'unsupported-platform') die(t('esto solo está para Linux, macOS y Windows.', 'this is only available on Linux, macOS and Windows.'))
285
+ if (/** @type {Thrown} */ (e).code === 'no-editor') die(t('no encontré VS Code, VS Code Insiders, VSCodium ni Cursor en esta cuenta.', 'could not find VS Code, VS Code Insiders, VSCodium or Cursor in this account.'))
286
+ if (/** @type {Thrown} */ (e).code === 'bad-settings') die(t(`no se pudo leer la configuración y no se tocó nada: ${/** @type {Thrown} */ (e).message}`, `could not read the settings and nothing was changed: ${/** @type {Thrown} */ (e).message}`))
287
+ if (/** @type {Thrown} */ (e).code === 'unsupported-platform') die(t('esto solo está para Linux, macOS y Windows.', 'this is only available on Linux, macOS and Windows.'))
271
288
  throw e
272
289
  }
273
290
  for (const d of done) {
@@ -298,8 +315,8 @@ async function claude () {
298
315
  const off = args.includes('--off')
299
316
  let done
300
317
  try { done = configureClaude({ off }) } catch (e) {
301
- if (e.code === 'no-claude') die(t('no encontré Claude Code en esta cuenta (no existe ~/.claude). Ábrelo una vez y repite.', 'could not find Claude Code in this account (~/.claude does not exist). Open it once and try again.'))
302
- if (e.code === 'bad-settings') die(t(`no se pudo leer la configuración de Claude Code y no se tocó nada: ${e.message}`, `could not read Claude Code's settings and nothing was changed: ${e.message}`))
318
+ if (/** @type {Thrown} */ (e).code === 'no-claude') die(t('no encontré Claude Code en esta cuenta (no existe ~/.claude). Ábrelo una vez y repite.', 'could not find Claude Code in this account (~/.claude does not exist). Open it once and try again.'))
319
+ if (/** @type {Thrown} */ (e).code === 'bad-settings') die(t(`no se pudo leer la configuración de Claude Code y no se tocó nada: ${/** @type {Thrown} */ (e).message}`, `could not read Claude Code's settings and nothing was changed: ${/** @type {Thrown} */ (e).message}`))
303
320
  throw e
304
321
  }
305
322
  const what = off
@@ -321,10 +338,15 @@ async function claude () {
321
338
  */
322
339
  async function updates () {
323
340
  const { latestVersion, isNewer } = await import('@dotrino/update')
341
+ /**
342
+ * @param {string} current
343
+ * @param {() => Promise<{ ok: true, version: string } | { ok: false, reason: string }>} ask
344
+ */
324
345
  const one = async (current, ask) => {
325
346
  const r = await ask()
326
347
  return r.ok ? { current, latest: r.version, newer: isNewer(r.version, current) } : { current, error: r.reason }
327
348
  }
349
+ /** @type {Record<string, { current: string, latest?: string, newer?: boolean, error?: string }>} */
328
350
  const out = { agent: await one(VERSION, () => latestVersion({ source: 'npm', pkg: '@dotrino/terminal-agent', product: 'dotrino-terminal', version: VERSION })) }
329
351
  const app = opt('--desktop')
330
352
  if (app) {
@@ -332,6 +354,7 @@ async function updates () {
332
354
  out.desktop = await one(app, () => latestDesktop({ version: app }))
333
355
  }
334
356
  if (args.includes('--json')) { console.log(JSON.stringify(out)); return }
357
+ /** @type {(name: string, x: { current: string, latest?: string, newer?: boolean, error?: string }) => void} */
335
358
  const say = (name, x) => console.log(x.error
336
359
  ? t(`${name}: no se pudo mirar (${x.error}).`, `${name}: could not check (${x.error}).`)
337
360
  : x.newer ? t(`${name}: hay ${x.latest} y tienes ${x.current}.`, `${name}: ${x.latest} is out and you have ${x.current}.`)
@@ -340,7 +363,10 @@ async function updates () {
340
363
  if (out.desktop) say(t('La app', 'The app'), out.desktop)
341
364
  }
342
365
 
343
- /** Dónde está la app de escritorio, si no lo dijo quien llama: la del PATH. */
366
+ /**
367
+ * Dónde está la app de escritorio, si no lo dijo quien llama: la del PATH.
368
+ * @param {string} name
369
+ */
344
370
  function findDesktop (name) {
345
371
  for (const d of (process.env.PATH || '').split(path.delimiter)) {
346
372
  if (!d) continue
@@ -361,6 +387,7 @@ async function desktop () {
361
387
  const exe = opt('--exe') || findDesktop(process.platform === 'win32' ? `${BINARY}.exe` : BINARY)
362
388
  const check = args.includes('--check')
363
389
  if (!exe && !check) die(t(`no encontré ${BINARY} en esta máquina. Bájala de https://terminal.dotrino.com/`, `could not find ${BINARY} on this machine. Get it from https://terminal.dotrino.com/`))
390
+ /** @type {(step: string, d: { version?: string, current?: string, name?: string, repo?: string, kind?: string }) => void} */
364
391
  const say = (step, d) => {
365
392
  if (step === 'latest') console.log(d.current ? t(`Publicada: ${d.version} · esta: ${d.current}`, `Published: ${d.version} · this one: ${d.current}`) : t(`Publicada: ${d.version}`, `Published: ${d.version}`))
366
393
  if (step === 'download') console.log(t(`Bajando ${d.name} y comprobando su firma…`, `Downloading ${d.name} and checking its signature…`))
@@ -368,14 +395,16 @@ async function desktop () {
368
395
  if (step === 'install' && (d.kind === 'deb' || d.kind === 'rpm') && process.getuid?.() !== 0) console.log(t('Instalar un paquete del sistema pide tu contraseña:', 'Installing a system package asks for your password:'))
369
396
  }
370
397
  console.log(t('Mirando qué hay publicado…', 'Checking what is published…'))
371
- const r = await updateDesktop({ exe, current, check, say })
398
+ const r = await updateDesktop({ exe: exe ?? undefined, current, check, say })
372
399
  if (!r.ok) {
373
- const why = {
400
+ /** @type {Record<string, string>} */
401
+ const texts = {
374
402
  'could-not-check': t(`No se pudo mirar (${r.reason}). No es que estés al día: es que no se sabe.`, `Could not check (${r.reason}). That does not mean you are up to date: it is unknown.`),
375
403
  'node-too-old': t(`NO se instala nada: con este Node (${process.version}) no se puede comprobar la firma. Hace falta Node 22.12 o más reciente (o 20.19): https://nodejs.org`, `Nothing is installed: this Node (${process.version}) cannot check the signature. It needs Node 22.12 or newer (or 20.19): https://nodejs.org`),
376
404
  NO_VERIFIER: t('NO se instala nada: a este programa le falta la pieza que comprueba la firma. Reinstálalo con: npm install -g @dotrino/terminal-agent', 'Nothing is installed: this program is missing the piece that checks the signature. Reinstall it with: npm install -g @dotrino/terminal-agent'),
377
405
  'not-writable': t(`NO se instala nada: no puedo escribir donde está la app (${r.reason}). Bájala de https://terminal.dotrino.com/`, `Nothing is installed: I cannot write where the app is (${r.reason}). Get it from https://terminal.dotrino.com/`)
378
- }[r.code] || t(`NO se instala nada: ${r.reason}`, `Nothing is installed: ${r.reason}`)
406
+ }
407
+ const why = texts[r.code] || t(`NO se instala nada: ${r.reason}`, `Nothing is installed: ${r.reason}`)
379
408
  die(r.file ? `${why}\n${t('El archivo, ya comprobado, quedó en', 'The file, already checked, is at')} ${r.file}` : why)
380
409
  }
381
410
  if (r.updated) console.log(t(`\nInstalada la ${r.version}. Las ventanas abiertas siguen con la anterior: cierra Dotrino Terminal y vuelve a abrirla. Tus consolas no se cierran.`, `\nInstalled ${r.version}. Open windows keep the old one: quit Dotrino Terminal and open it again. Your consoles stay open.`))
@@ -383,10 +412,14 @@ async function desktop () {
383
412
  else console.log(t(`La app está al día (${current}).`, `The app is up to date (${current}).`))
384
413
  }
385
414
 
386
- /** Cuántas consolas tiene abiertas el agente de esa carpeta (0 si no hay agente). */
415
+ /**
416
+ * Cuántas consolas tiene abiertas el agente de esa carpeta (0 si no hay agente).
417
+ * @param {string} dir
418
+ * @returns {Promise<number>}
419
+ */
387
420
  async function openConsoles (dir) {
388
421
  let conn
389
- try { conn = await connectLocal(dir) } catch (e) { if (e.code === 'ENOAGENT') return 0; throw e }
422
+ try { conn = await connectLocal(dir) } catch (e) { if (/** @type {Thrown} */ (e).code === 'ENOAGENT') return 0; throw e }
390
423
  const r = await request(conn, { type: 'list' }, 'consoles')
391
424
  conn.close()
392
425
  if (r.type === 'fail') throw new Error(`${r.message} (${r.code})`)
@@ -406,7 +439,7 @@ async function agentStates () {
406
439
  for (const p of await listProfiles()) {
407
440
  let conn
408
441
  try { conn = await connectLocal(p.dir) } catch (e) {
409
- if (e.code !== 'ENOAGENT') throw e
442
+ if (/** @type {Thrown} */ (e).code !== 'ENOAGENT') throw e
410
443
  out.push({ name: p.name, running: false, version: null, consoles: 0, stale: false })
411
444
  continue
412
445
  }
@@ -443,6 +476,7 @@ async function restart () {
443
476
  const only = stale && asked === undefined ? null : path.basename(resolveInstance(LABEL, asked).dir)
444
477
  const targets = (await agentStates()).filter((a) => a.running && (only === null || a.name === only) && (!stale || a.stale))
445
478
  if (!targets.length) { console.log(stale ? t('Ningún agente va por detrás de lo instalado.', 'No agent is behind what is installed.') : t('Ese perfil no tiene un agente corriendo.', 'That profile has no agent running.')); return }
479
+ /** @param {string} name */
446
480
  const dirOf = (name) => resolveInstance(LABEL, name).dir
447
481
  // ¿Corre esta orden DENTRO de una consola de uno de esos agentes? Pararlo la cerraría a mitad
448
482
  // de camino: el trabajo lo hace un proceso aparte.
@@ -469,7 +503,7 @@ async function restart () {
469
503
  await new Promise((r) => setTimeout(r, 100))
470
504
  }
471
505
  let service = false
472
- try { service = serviceStatus({ name: a.name, dir }).installed } catch (e) { if (e.code !== 'no-user-systemd' && e.code !== 'unsupported-platform') throw e }
506
+ try { service = serviceStatus({ name: a.name, dir }).installed } catch (e) { if (/** @type {Thrown} */ (e).code !== 'no-user-systemd' && /** @type {Thrown} */ (e).code !== 'unsupported-platform') throw e }
473
507
  console.log(service
474
508
  ? t(`«${a.name}»: agente detenido (${a.consoles} consola(s) cerradas). Su servicio lo vuelve a levantar con la ${VERSION}.`, `"${a.name}": agent stopped (${a.consoles} console(s) closed). Its service starts it again with ${VERSION}.`)
475
509
  : t(`«${a.name}»: agente detenido (${a.consoles} consola(s) cerradas). Arranca con la ${VERSION} al abrir una ventana.`, `"${a.name}": agent stopped (${a.consoles} console(s) closed). It starts with ${VERSION} when you open a window.`))
@@ -486,7 +520,7 @@ async function network () {
486
520
  const { dir } = resolveInstance(LABEL, asked)
487
521
  let conn
488
522
  try { conn = await connectLocal(dir) } catch (e) {
489
- if (e.code !== 'ENOAGENT') throw e
523
+ if (/** @type {Thrown} */ (e).code !== 'ENOAGENT') throw e
490
524
  console.log(t('Este perfil no tiene un agente corriendo: no hay conexiones.', 'This profile has no agent running: there are no connections.'))
491
525
  return
492
526
  }
@@ -510,7 +544,12 @@ async function service () {
510
544
  const { dir } = resolveInstance(LABEL, asked)
511
545
  const name = path.basename(dir)
512
546
  const { installService, uninstallService, serviceStatus } = await import('../service.js')
513
- const explain = (e) => {
547
+ /**
548
+ * @param {unknown} caught
549
+ * @returns {never}
550
+ */
551
+ const explain = (caught) => {
552
+ const e = /** @type {Thrown} */ (caught)
514
553
  if (e.code === 'no-user-systemd') die(t('esta sesión no tiene systemd de usuario, que es donde se pone el servicio. No se instaló nada.', 'this session has no systemd user manager, which is where the service goes. Nothing was installed.'))
515
554
  if (e.code === 'unsupported-platform') die(t('esto solo está para Linux, macOS y Windows.', 'this is only available on Linux, macOS and Windows.'))
516
555
  throw e
@@ -572,7 +611,7 @@ async function link () {
572
611
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
573
612
  const taken = (await listProfiles()).filter((p) => p.linked).map((p) => p.name)
574
613
  const suggestion = taken.includes('default') ? '' : 'default'
575
- name = await new Promise((resolve) => rl.question(t(`Nombre del perfil (a-z, 0-9, -)${suggestion ? ` [${suggestion}]` : ''}: `, `Profile name (a-z, 0-9, -)${suggestion ? ` [${suggestion}]` : ''}: `), (a) => { rl.close(); resolve(a.trim() || suggestion) }))
614
+ name = await /** @type {Promise<string>} */ (new Promise((resolve) => rl.question(t(`Nombre del perfil (a-z, 0-9, -)${suggestion ? ` [${suggestion}]` : ''}: `, `Profile name (a-z, 0-9, -)${suggestion ? ` [${suggestion}]` : ''}: `), (a) => { rl.close(); resolve(a.trim() || suggestion) })))
576
615
  }
577
616
  if (!isValidName(name)) die(t(`nombre no válido: «${name}» (usa a-z, 0-9 y -, hasta 32)`, `invalid name: "${name}" (use a-z, 0-9 and -, up to 32)`))
578
617
  const { dir } = resolveInstance(LABEL, name)
@@ -582,12 +621,20 @@ async function link () {
582
621
  console.log(t(`Perfil «${name}» enlazado.`, `Profile "${name}" linked.`))
583
622
  }
584
623
 
624
+ /**
625
+ * @param {string} q
626
+ * @returns {Promise<string>}
627
+ */
585
628
  function ask (q) {
586
629
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
587
630
  return new Promise((resolve) => rl.question(q, (a) => { rl.close(); resolve(a.trim()) }))
588
631
  }
589
632
 
590
- /** Pregunta algo que no debe verse al teclearlo. Solo en una TTY: una clave no se pasa por una tubería. */
633
+ /**
634
+ * Pregunta algo que no debe verse al teclearlo. Solo en una TTY: una clave no se pasa por una tubería.
635
+ * @param {string} q
636
+ * @returns {Promise<string>}
637
+ */
591
638
  function askHidden (q) {
592
639
  if (!process.stdin.isTTY) die(t('la clave se teclea: hace falta una terminal', 'the code is typed: a terminal is needed'))
593
640
  process.stdout.write(q)
@@ -595,7 +642,7 @@ function askHidden (q) {
595
642
  process.stdin.resume()
596
643
  return new Promise((resolve) => {
597
644
  let typed = ''
598
- const onData = (b) => {
645
+ const onData = (/** @type {Buffer} */ b) => {
599
646
  // Una tecla que no es texto (flechas, Fin, el teclado numérico SIN Bloq Num) llega como una
600
647
  // secuencia de escape: se descarta entera. Antes solo se saltaba el ESC y el resto («[F»)
601
648
  // entraba en la clave sin que se viera, así que la clave guardada no era la tecleada.
@@ -711,6 +758,10 @@ async function rename () {
711
758
  console.log(t(`Perfil «${from}» → «${to}». Es el mismo aparato: no hace falta volver a enrolar.`, `Profile "${from}" → "${to}". Same device: no need to enroll again.`))
712
759
  }
713
760
 
761
+ /**
762
+ * @param {string} a
763
+ * @param {string} b
764
+ */
714
765
  function samePath (a, b) {
715
766
  try { return fs.realpathSync(a) === fs.realpathSync(b) } catch (_) { return path.resolve(a) === path.resolve(b) }
716
767
  }
@@ -721,7 +772,13 @@ function lastProfileFile () {
721
772
  return path.join(base, 'dotrino-terminal', 'last-profile')
722
773
  }
723
774
 
724
- /** Una pregunta y su respuesta, para `ls` y `kill`. */
775
+ /**
776
+ * Una pregunta y su respuesta, para `ls` y `kill`.
777
+ * @param {Conn} conn
778
+ * @param {object} msg
779
+ * @param {string} type
780
+ * @returns {Promise<any>} lo que contestó el agente (`type` o `fail`), sin comprobar
781
+ */
725
782
  function request (conn, msg, type) {
726
783
  return new Promise((resolve) => {
727
784
  conn.on('message', (m) => { if (m.type === type || m.type === 'fail') resolve(m) })
@@ -732,14 +789,22 @@ function request (conn, msg, type) {
732
789
  /** Lo que se espera a que el agente conteste por otra máquina (descubrirla y saludarla). */
733
790
  const FAR_WAIT_MS = 40_000
734
791
  /** Una pregunta sobre las otras máquinas. Un agente anterior a la 0.38 no la entiende y calla: se dice. */
792
+ /**
793
+ * @param {Conn} conn
794
+ * @param {object} msg
795
+ * @param {string} type
796
+ * @returns {Promise<any>}
797
+ */
735
798
  async function farRequest (conn, msg, type) {
736
799
  const r = await Promise.race([request(conn, msg, type), new Promise((resolve) => setTimeout(() => resolve(null), FAR_WAIT_MS))])
737
800
  if (!r) die(t('el agente de esta máquina no contestó. Si es anterior a la 0.38 no sabe de otras máquinas: actualízalo y reinícialo.', 'this machine\'s agent did not answer. If it predates 0.38 it knows nothing about other machines: update and restart it.'))
738
801
  return r
739
802
  }
803
+ /** @param {{ code?: string, message?: string }} r */
740
804
  const farMessage = (r) => farMessageFor(r, t)
741
805
 
742
806
  /** `dotrino-terminal machines`: las otras máquinas de la cuenta que están encendidas, y sus consolas. */
807
+ /** @param {Conn} conn */
743
808
  async function machines (conn) {
744
809
  const r = await farRequest(conn, { type: 'machines' }, 'machines')
745
810
  if (r.type === 'fail') die(`dotrino-terminal: ${farMessage(r)}`)
@@ -748,7 +813,7 @@ async function machines (conn) {
748
813
  for (const m of r.list) {
749
814
  const state = m.locked ? t('pide su clave', 'asks for its code') : m.error ? t('no contesta', 'not answering') : `${m.consoles.length} ${t('consolas', 'consoles')}`
750
815
  console.log(`${m.id} ${m.name || ''} · ${state}`)
751
- for (const c of m.consoles || []) console.log(` ${c.id} ${age(Date.now() - c.createdAt).padStart(4)} ${c.viewers} ${t('mirando', 'watching')} ${c.title || ''}`)
816
+ for (const c of /** @type {import('../types/agent.js').ConsoleInfo[]} */ (m.consoles || [])) console.log(` ${c.id} ${age(Date.now() - c.createdAt).padStart(4)} ${c.viewers} ${t('mirando', 'watching')} ${c.title || ''}`)
752
817
  }
753
818
  }
754
819
 
@@ -756,6 +821,8 @@ async function machines (conn) {
756
821
  * `--machine <id|nombre>`: esta conexión pasa a hablar con OTRA máquina de la cuenta (el agente
757
822
  * de aquí hace de puente, `far.js`). A partir de ahí todo es igual que en local. Si la otra
758
823
  * máquina tiene clave, se pide aquí, antes de seguir.
824
+ * @param {Conn} conn
825
+ * @param {string} ref
759
826
  */
760
827
  async function goVia (conn, ref) {
761
828
  const r = await farRequest(conn, { type: 'via', machine: ref }, 'via')
@@ -776,17 +843,19 @@ async function goVia (conn, ref) {
776
843
  if (probe.type === 'fail') die(`dotrino-terminal: ${probe.message} (${probe.code})`)
777
844
  }
778
845
 
846
+ /** @param {number} ms */
779
847
  const age = (ms) => {
780
848
  const s = Math.round(ms / 1000)
781
849
  return s < 60 ? `${s}s` : s < 3600 ? `${Math.round(s / 60)}m` : `${Math.round(s / 3600)}h`
782
850
  }
783
851
 
852
+ /** @param {Conn} conn */
784
853
  async function list (conn) {
785
854
  const { list } = await request(conn, { type: 'list' }, 'consoles')
786
855
  if (args.includes('--json')) { console.log(JSON.stringify(list, null, 2)); return }
787
856
  if (!list.length) { console.log(t('No hay consolas abiertas.', 'No open consoles.')); return }
788
857
  for (const c of list) {
789
- const remote = c.watchers.filter((w) => w.origin === 'remote').length
858
+ const remote = /** @type {import('../types/agent.js').ConsoleInfo} */ (c).watchers.filter((w) => w.origin === 'remote').length
790
859
  const who = `${c.viewers} ${t('mirando', 'watching')}${remote ? ` (${remote} ${t('desde otro aparato', 'from another device')})` : ''}`
791
860
  console.log(` ${c.id} ${c.origin.padEnd(6)} ${age(Date.now() - c.createdAt).padStart(4)} ${who} ${c.title || ''}`)
792
861
  }
@@ -807,6 +876,7 @@ async function note () {
807
876
  const dir = opt('--dir') || (opt('--name') ? dataDir(opt('--name')) : process.env.DOTRINO_TERMINAL_PROFILE_DIR || dataDir())
808
877
  const valued = new Set(['--id', '--dir', '--name', '--add', '--task', '--title'])
809
878
  const flags = new Set([...valued, '--clear', '--json'])
879
+ /** @type {string[]} */
810
880
  const words = []
811
881
  for (let i = 1; i < args.length; i++) {
812
882
  if (valued.has(args[i])) { i++; continue }
@@ -820,11 +890,16 @@ async function note () {
820
890
  const add = opt('--add') === '-' ? stdin() : opt('--add')
821
891
  const task = opt('--task') === '-' ? stdin() : opt('--task')
822
892
  const title = opt('--title')
893
+ /** @type {Conn} */
823
894
  let conn
824
895
  try { conn = await connectLocal(dir) } catch (e) {
825
- if (e.code !== 'ENOAGENT') throw e
896
+ if (/** @type {Thrown} */ (e).code !== 'ENOAGENT') throw e
826
897
  die(t('el agente de este perfil no está corriendo.', 'this profile\'s agent is not running.'))
827
898
  }
899
+ /**
900
+ * @param {object} msg
901
+ * @returns {Promise<import('../types/agent.js').ConsoleInfo>}
902
+ */
828
903
  const ask = async (msg) => {
829
904
  const r = await Promise.race([request(conn, msg, 'noted'), new Promise((resolve) => setTimeout(() => resolve(null), 5000))])
830
905
  // Un agente anterior a la 0.36 no conoce la orden y no contesta: se dice, no se da por hecho.
@@ -865,7 +940,12 @@ const PASTE_KEY = '\x16'
865
940
  /** Los fallos que contesta la máquina a una subida: son de la subida, no cierran la ventana. */
866
941
  const UPLOAD_FAILS = new Set(['not-image', 'too-big', 'bad-file', 'no-uploads', 'file-failed'])
867
942
 
868
- /** La ventana: la TTY enganchada a una consola del agente. */
943
+ /**
944
+ * La ventana: la TTY enganchada a una consola del agente.
945
+ * @param {Conn} conn
946
+ * @param {{ type: 'open' | 'attach', id?: string, cwd?: string, tag?: string }} first lo que se pide al empezar
947
+ * @param {string} dir
948
+ */
869
949
  function interactive (conn, first, dir) {
870
950
  // Hasta que el agente diga `attached` no hay consola a la que escribir: se guarda.
871
951
  let ready = false
@@ -874,29 +954,35 @@ function interactive (conn, first, dir) {
874
954
  // hasta que se abra una (Ctrl+] n, el «+» de la app) o se pase a una (Ctrl+] a<id>). Lo que se
875
955
  // teclee ahí no va a ningún sitio: se descarta, no se guarda para una consola que aún no existe.
876
956
  let empty = false
957
+ /** @param {string} data */
877
958
  const input = (data) => { if (ready) conn.send({ type: 'input', data }); else if (!empty) queued += data }
878
959
  if (!process.stdin.isTTY || !process.stdout.isTTY) die(t('dotrino-terminal necesita una terminal (TTY).', 'dotrino-terminal needs a terminal (TTY).'))
879
960
  const out = process.stdout
961
+ /** @type {string | null} */
880
962
  let consoleId = null
881
963
  let shellTitle = ''
882
964
  let subject = ''
965
+ /** @type {Set<string>} */
883
966
  let remote = new Set()
884
967
  let ending = false
885
968
 
886
969
  // Lo que se dice un momento en el título (mandar una imagen): la pantalla es del programa.
887
970
  let status = ''
888
- let statusTimer = null
971
+ /** @type {ReturnType<typeof setTimeout> | undefined} */
972
+ let statusTimer
889
973
  const showTitle = () => {
890
974
  const base = subject || shellTitle || 'Dotrino Terminal'
891
975
  const mark = remote.size ? ` ● ${t('abierta desde otro aparato', 'open on another device')}${remote.size > 1 ? ` ×${remote.size}` : ''}` : ''
892
976
  out.write(`\x1b]2;${base}${mark}${status ? ` · ${status}` : ''}\x07`)
893
977
  }
978
+ /** @type {(text: string, ms?: number) => void} */
894
979
  const say = (text, ms = 0) => {
895
980
  clearTimeout(statusTimer)
896
981
  status = text
897
982
  showTitle()
898
983
  if (ms) statusTimer = setTimeout(() => { status = ''; showTitle() }, ms)
899
984
  }
985
+ /** @param {import('../types/agent.js').ConsoleInfo | null | undefined} info */
900
986
  const onInfo = (info) => {
901
987
  if (!info) return
902
988
  // El título que puso el programa (`note --title`) manda sobre el de la shell.
@@ -918,6 +1004,7 @@ function interactive (conn, first, dir) {
918
1004
  const filter = titleFilter((title) => { shellTitle = title; showTitle() })
919
1005
  const size = () => ({ cols: out.columns || 80, rows: out.rows || 24 })
920
1006
 
1007
+ /** @type {(code: number, note?: string) => void} */
921
1008
  const finish = (code, note) => {
922
1009
  if (ending) return
923
1010
  ending = true
@@ -954,7 +1041,9 @@ function interactive (conn, first, dir) {
954
1041
  switching = false; recovering = false
955
1042
  request(conn, { type: 'list' }, 'consoles').then((r) => {
956
1043
  if (r.type !== 'consoles') return // un `fail`: ya lo atendió el manejador
957
- const rest = r.list.filter((c) => c.id !== closed)
1044
+ /** @type {import('../types/agent.js').ConsoleInfo[]} */
1045
+ const all = r.list
1046
+ const rest = all.filter((c) => c.id !== closed)
958
1047
  // Desatendida EN ESTA MÁQUINA: que la mire otro aparato no la hace atendida aquí.
959
1048
  const other = rest.find((c) => !c.watchers.length) || rest.find((c) => !c.watchers.some((w) => w.origin === 'local')) || rest[0]
960
1049
  if (other) return switchTo({ type: 'attach', id: other.id })
@@ -968,11 +1057,13 @@ function interactive (conn, first, dir) {
968
1057
  // ¿El programa pidió pegado entre corchetes? Así recibe la ruta de una imagen como algo
969
1058
  // pegado, que es como Claude Code reconoce un archivo.
970
1059
  let bracketed = false
1060
+ /** @param {string} data */
971
1061
  const watchModes = (data) => {
972
1062
  const all = [...String(data).matchAll(/\x1b\[\?2004([hl])/g)]
973
1063
  if (all.length) bracketed = all[all.length - 1][1] === 'h'
974
1064
  }
975
1065
  // La subida en curso: sus respuestas (`filed`, o un `fail` suyo) son de ella y de nadie más.
1066
+ /** @type {((m: any) => void) | null} */
976
1067
  let uploadReply = null
977
1068
  conn.on('message', (m) => {
978
1069
  if (m.type === 'replay' && !clean) { clean = true; out.write('\x1b[H\x1b[2J') }
@@ -1037,9 +1128,11 @@ function interactive (conn, first, dir) {
1037
1128
  process.stdin.off('data', earlyTap)
1038
1129
  const decoder = new StringDecoder('utf8')
1039
1130
  let prefixed = false
1131
+ /** @type {string | null} */
1040
1132
  let collecting = null // tras Ctrl+] a: el id de la consola, hasta Enter
1041
1133
  // Cambiar de consola SIN salir: por la misma conexión, y con la pantalla en limpio para que la
1042
1134
  // repetición de la otra consola no se pinte encima. Lo tecleado mientras tanto se guarda.
1135
+ /** @param {{ type: 'open' | 'attach', id?: string, cwd?: string }} msg */
1043
1136
  const switchTo = (msg) => {
1044
1137
  wasEmpty = empty
1045
1138
  empty = false
@@ -1048,6 +1141,7 @@ function interactive (conn, first, dir) {
1048
1141
  out.write('\x1bc') // RIS: pantalla, historial y modos, de cero
1049
1142
  conn.send({ ...msg, ...size(), ...tag() })
1050
1143
  }
1144
+ /** @param {Buffer} buf */
1051
1145
  const onKeys = (buf) => {
1052
1146
  // Ctrl+] abre el atajo: «d» suelta la consola, «n» abre otra nueva, «a<id>⏎» pasa a esa
1053
1147
  // consola (lo usa el panel de la app de escritorio), otro Ctrl+] manda uno literal, y
@@ -1101,6 +1195,7 @@ function interactive (conn, first, dir) {
1101
1195
  // salía nada. Si aquí hay una imagen, se sube (la misma subida que usa el teléfono) y se pega
1102
1196
  // la ruta donde quedó. Sin imagen, Ctrl+V sigue su camino, como siempre.
1103
1197
  let pasting = false
1198
+ /** @type {(msg: object) => Promise<any>} */
1104
1199
  const ask = (msg) => new Promise((resolve) => {
1105
1200
  const timer = setTimeout(() => { uploadReply = null; resolve({ type: 'fail', code: 'timeout', message: 'the machine did not answer (its agent may predate 0.43)' }) }, 20000)
1106
1201
  uploadReply = (m) => { clearTimeout(timer); resolve(m) }
@@ -1112,7 +1207,7 @@ function interactive (conn, first, dir) {
1112
1207
  try {
1113
1208
  let bytes
1114
1209
  try { bytes = await clipboardImage() } catch (e) {
1115
- say(t(`no pude leer el portapapeles (${e.code})`, `could not read the clipboard (${e.code})`), 8000)
1210
+ say(t(`no pude leer el portapapeles (${/** @type {Thrown} */ (e).code})`, `could not read the clipboard (${/** @type {Thrown} */ (e).code})`), 8000)
1116
1211
  input(PASTE_KEY)
1117
1212
  return
1118
1213
  }
@@ -1123,7 +1218,7 @@ function interactive (conn, first, dir) {
1123
1218
  input(bracketed ? `\x1b[200~${text}\x1b[201~` : text)
1124
1219
  say(t('imagen enviada', 'image sent'), 3000)
1125
1220
  } catch (e) {
1126
- say(t(`no se pudo mandar la imagen: ${e.message} (${e.code || '?'})`, `could not send the image: ${e.message} (${e.code || '?'})`), 10000)
1221
+ say(t(`no se pudo mandar la imagen: ${/** @type {Thrown} */ (e).message} (${/** @type {Thrown} */ (e).code || '?'})`, `could not send the image: ${/** @type {Thrown} */ (e).message} (${/** @type {Thrown} */ (e).code || '?'})`), 10000)
1127
1222
  } finally { pasting = false }
1128
1223
  }
1129
1224
  process.stdin.on('data', onKeys)
@@ -1184,5 +1279,5 @@ try {
1184
1279
  interactive(conn, { type: 'open', ...cwd, ...tag() }, dir)
1185
1280
  } else die(t(`orden desconocida: ${cmd} (mira --help)`, `unknown command: ${cmd} (see --help)`))
1186
1281
  } catch (e) {
1187
- if (e !== HOLD) { try { die(`dotrino-terminal: ${e.message}`) } catch (_) {} }
1282
+ if (e !== HOLD) { try { die(`dotrino-terminal: ${/** @type {Thrown} */ (e).message}`) } catch (_) {} }
1188
1283
  }
package/claude.js CHANGED
@@ -23,40 +23,63 @@ export const HOOKS = [
23
23
  { file: 'terminal-note-stop.sh', event: 'Stop' },
24
24
  ]
25
25
 
26
+ /** @type {(code: string, message: string) => Error & { code: string }} */
26
27
  const fail = (code, message) => Object.assign(new Error(message), { code })
28
+ /**
29
+ * El `settings.json` de Claude Code: un JSON del usuario, así que todo lo de dentro se comprueba.
30
+ * @typedef {{ type?: string, command?: string, timeout?: number }} HookEntry
31
+ * @typedef {{ hooks?: HookEntry[], [k: string]: unknown }} HookGroup
32
+ * @typedef {{ hooks?: Record<string, HookGroup[]>, [k: string]: unknown }} Settings
33
+ */
34
+
27
35
  const source = () => path.join(path.dirname(fileURLToPath(import.meta.url)), 'skills')
28
36
 
29
37
  /** ¿Es `command` el hook `file`? Por el archivo, lo llame como lo llame (con o sin comillas). */
38
+ /** @type {(command: unknown, file: string) => boolean} */
30
39
  const runs = (command, file) => typeof command === 'string' && new RegExp(`[/\\\\]hooks[/\\\\]${file.replace(/\./g, '\\.')}(["'\\s]|$)`).test(command)
31
40
 
41
+ /**
42
+ * @param {string} file
43
+ * @returns {Settings}
44
+ */
32
45
  function readSettings (file) {
33
46
  if (!fs.existsSync(file)) return {}
34
47
  let value
35
- try { value = JSON.parse(fs.readFileSync(file, 'utf8')) } catch (e) { throw fail('bad-settings', `${file}: ${e.message}`) }
48
+ try { value = JSON.parse(fs.readFileSync(file, 'utf8')) } catch (e) { throw fail('bad-settings', `${file}: ${/** @type {Thrown} */ (e).message}`) }
36
49
  if (!value || typeof value !== 'object' || Array.isArray(value)) throw fail('bad-settings', `${file}: not an object`)
37
50
  return value
38
51
  }
39
52
 
40
53
  /** `settings` sin las entradas de nuestros hooks (y sin los grupos o eventos que queden vacíos). */
54
+ /**
55
+ * @param {Settings} settings
56
+ * @returns {Settings}
57
+ */
41
58
  function withoutHooks (settings) {
42
59
  const hooks = settings.hooks
43
60
  if (!hooks || typeof hooks !== 'object') return settings
61
+ /** @type {Record<string, HookGroup[]>} */
44
62
  const out = {}
45
63
  for (const [event, groups] of Object.entries(hooks)) {
46
64
  if (!Array.isArray(groups)) { out[event] = groups; continue }
47
65
  const kept = groups
48
- .map((g) => (Array.isArray(g?.hooks) ? { ...g, hooks: g.hooks.filter((h) => !HOOKS.some((x) => runs(h?.command, x.file))) } : g))
66
+ .map((/** @type {HookGroup} */ g) => (Array.isArray(g?.hooks) ? { ...g, hooks: g.hooks.filter((h) => !HOOKS.some((x) => runs(h?.command, x.file))) } : g))
49
67
  .filter((g) => !Array.isArray(g?.hooks) || g.hooks.length)
50
68
  if (kept.length) out[event] = kept
51
69
  }
70
+ /** @type {Settings} */
52
71
  const next = { ...settings, hooks: out }
53
72
  if (!Object.keys(out).length) delete next.hooks
54
73
  return next
55
74
  }
56
75
 
57
76
  /** ¿Está puesto? `{ skill, hooks: [archivos presentes], wired: [archivos con entrada en settings] }`. */
77
+ /**
78
+ * @param {{ home?: string }} [opts]
79
+ */
58
80
  export function claudeStatus ({ home = os.homedir() } = {}) {
59
81
  const dir = path.join(home, '.claude')
82
+ /** @type {Settings} */
60
83
  let settings = {}
61
84
  try { settings = readSettings(path.join(dir, 'settings.json')) } catch (_) {}
62
85
  const commands = Object.values(settings.hooks || {}).flat().flatMap((g) => g?.hooks || []).map((h) => h?.command)
@@ -71,6 +94,7 @@ export function claudeStatus ({ home = os.homedir() } = {}) {
71
94
  * Pone (o con `off`, quita) el skill y los hooks. Devuelve qué cambió.
72
95
  * Sin `~/.claude` no hay Claude Code en esta cuenta: se dice (`no-claude`) y no se crea nada.
73
96
  * Un `settings.json` que no se puede leer no se toca (`bad-settings`).
97
+ * @param {{ off?: boolean, home?: string, from?: string }} [opts]
74
98
  */
75
99
  export function configureClaude ({ off = false, home = os.homedir(), from = source() } = {}) {
76
100
  const dir = path.join(home, '.claude')
@@ -81,6 +105,7 @@ export function configureClaude ({ off = false, home = os.homedir(), from = sour
81
105
  const hooksDir = path.join(dir, 'hooks')
82
106
 
83
107
  // Lo que ya está enganchado (lo llame como lo llame) se deja como está: no se duplica ni se mueve.
108
+ /** @param {string} file */
84
109
  const wired = (file) => Object.values(before.hooks || {}).flat().flatMap((g) => g?.hooks || []).some((h) => runs(h?.command, file))
85
110
  let next = before
86
111
  if (off) next = withoutHooks(before)
@@ -100,6 +125,7 @@ export function configureClaude ({ off = false, home = os.homedir(), from = sour
100
125
  for (const h of HOOKS) { const f = path.join(hooksDir, h.file); if (fs.existsSync(f)) { fs.rmSync(f); filesChanged = true } }
101
126
  if (fs.existsSync(skillDir)) { fs.rmSync(skillDir, { recursive: true }); filesChanged = true }
102
127
  } else {
128
+ /** @type {(src: string, dest: string, mode: number) => void} */
103
129
  const put = (src, dest, mode) => {
104
130
  const want = fs.readFileSync(src)
105
131
  if (fs.existsSync(dest) && fs.readFileSync(dest).equals(want)) return