@dotrino/terminal-agent 0.49.5 → 0.50.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.
Files changed (4) hide show
  1. package/downloads.js +80 -0
  2. package/far.js +29 -2
  3. package/index.js +16 -3
  4. package/package.json +2 -1
package/downloads.js ADDED
@@ -0,0 +1,80 @@
1
+ /**
2
+ * downloads.js — un archivo de ESTA máquina, para abrirlo en el aparato que mira la consola.
3
+ *
4
+ * Para qué: la consola enseña rutas (`/tmp/informe.pdf`, `~/fotos/a.png`) y desde el teléfono o
5
+ * el navegador no hay otra forma de ver ese archivo. El aparato la pide por la sesión (cifrada,
6
+ * como todo lo demás) y se le manda en trozos.
7
+ *
8
+ * Quien llega hasta aquí ya tiene una shell en la máquina, así que leer un archivo no le da nada
9
+ * que no tuviera con `cat`. Lo que se cuida es otra cosa: solo archivos normales (ni carpetas ni
10
+ * dispositivos) y con tope de tamaño, para que una ruta mal leída no se ponga a mandar gigas.
11
+ *
12
+ * Sin estado: cada trozo se pide con la ruta y su número (`seq`), y cada respuesta lleva el
13
+ * tamaño y la fecha del archivo; si cambian a mitad, quien pide lo ve y para.
14
+ */
15
+ import fs from 'node:fs'
16
+ import os from 'node:os'
17
+ import path from 'node:path'
18
+
19
+ /** Lo más que pesa un archivo que se manda. */
20
+ export const FETCH_MAX = 50 * 1024 * 1024
21
+ /** Lo que lleva cada trozo, antes del base64 (el mismo tamaño que las subidas del cliente). */
22
+ export const FETCH_CHUNK = 96 * 1024
23
+
24
+ const fail = (code, message) => Object.assign(new Error(message), { code })
25
+
26
+ /**
27
+ * La ruta absoluta de lo que se pide. `~` es la carpeta personal; una ruta relativa cuelga de
28
+ * `cwd` (la carpeta de la shell de la consola), y sin ella no se adivina: se dice.
29
+ */
30
+ export function resolvePath (p, cwd = null) {
31
+ if (typeof p !== 'string' || !p || p.length > 4096 || p.includes('\0')) throw fail('bad-fetch', 'fetch: needs a `path`')
32
+ const home = os.homedir()
33
+ const expand = (s) => s === '~' ? home : s.startsWith('~/') ? path.join(home, s.slice(2)) : s
34
+ const full = expand(p)
35
+ if (path.isAbsolute(full)) return path.normalize(full)
36
+ if (!cwd) throw fail('no-cwd', `fetch: ${p} is relative and the folder of the console is unknown`)
37
+ return path.resolve(expand(cwd), full)
38
+ }
39
+
40
+ /**
41
+ * Un trozo del archivo.
42
+ * @param {{ id: string, path: string, seq: number }} msg
43
+ * @param {string|null} cwd la carpeta de la consola enganchada, para las rutas relativas.
44
+ * @returns {{ id: string, seq: number, path: string, name: string, size: number, mtime: number, data: string, last?: true }}
45
+ */
46
+ export function readPiece (msg, cwd = null) {
47
+ const id = typeof msg.id === 'string' ? msg.id.slice(0, 64) : ''
48
+ const seq = msg.seq
49
+ if (!id || !Number.isInteger(seq) || seq < 0) throw fail('bad-fetch', 'fetch: needs `id`, `path` and `seq`')
50
+ const file = resolvePath(msg.path, cwd)
51
+ let st
52
+ try { st = fs.statSync(file) } catch (e) {
53
+ if (e.code === 'ENOENT' || e.code === 'ENOTDIR') throw fail('no-file', `no such file: ${file}`)
54
+ if (e.code === 'EACCES' || e.code === 'EPERM') throw fail('no-read', `not allowed to read: ${file}`)
55
+ throw e
56
+ }
57
+ if (st.isDirectory()) throw fail('is-dir', `that is a folder: ${file}`)
58
+ if (!st.isFile()) throw fail('not-file', `that is not a regular file: ${file}`)
59
+ if (st.size > FETCH_MAX) throw fail('too-big', `the file is over ${FETCH_MAX / 1024 / 1024} MB`)
60
+ const at = seq * FETCH_CHUNK
61
+ if (at > st.size || (at === st.size && st.size > 0)) throw fail('bad-fetch', 'fetch: that piece is past the end of the file')
62
+ const len = Math.min(FETCH_CHUNK, st.size - at)
63
+ const buf = Buffer.alloc(len)
64
+ let fd
65
+ try { fd = fs.openSync(file, 'r') } catch (e) {
66
+ if (e.code === 'EACCES' || e.code === 'EPERM') throw fail('no-read', `not allowed to read: ${file}`)
67
+ throw e
68
+ }
69
+ try {
70
+ let got = 0
71
+ while (got < len) {
72
+ const n = fs.readSync(fd, buf, got, len - got, at + got)
73
+ if (n === 0) break
74
+ got += n
75
+ }
76
+ if (got < len) throw fail('changed', 'the file got shorter while it was being sent')
77
+ } finally { fs.closeSync(fd) }
78
+ const last = at + len >= st.size
79
+ return { id, seq, path: file, name: path.basename(file), size: st.size, mtime: st.mtimeMs, data: buf.toString('base64'), ...(last ? { last: true } : {}) }
80
+ }
package/far.js CHANGED
@@ -84,7 +84,7 @@ async function connectReal ({ link, dir, sub }) {
84
84
  * @param {number} [opts.idleMs]
85
85
  * @param {number} [opts.answerMs]
86
86
  */
87
- export function makeFar ({ dir, loadLink, kind, discover = discoverReal, connect = connectReal, refreshMs = REFRESH_MS, discoverMs = DISCOVER_MS, idleMs = IDLE_MS, answerMs = ANSWER_MS }) {
87
+ 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) }) {
88
88
  /** sub → { sub, id, name, rc, consoles, locked, error } */
89
89
  const machines = new Map()
90
90
  /** sub → la clave que una ventana escribió bien (solo en memoria). */
@@ -96,6 +96,23 @@ export function makeFar ({ dir, loadLink, kind, discover = discoverReal, connect
96
96
  let idle = null
97
97
  let closed = false
98
98
 
99
+ /**
100
+ * LO QUE FALLA QUEDA ESCRITO, CON SU HORA. Sin esto, «no se pudo preguntar a tu bóveda» salía
101
+ * en la ventana y en `agent.log` no quedaba nada: ni cuándo, ni cuánto tardó, ni por qué
102
+ * (2026-11-04, dos minutos de Terminal sin conectar que no se pudieron explicar). Se escribe
103
+ * solo al CAMBIAR (falla, cambia de motivo o se recupera): el refresco va cada pocos segundos
104
+ * y una línea por vuelta ahogaría el log.
105
+ */
106
+ const lastError = new Map()
107
+ function report (what, err, ms) {
108
+ const code = err ? (err.code || 'error') : null
109
+ if ((lastError.get(what) ?? null) === code) return
110
+ const took = typeof ms === 'number' ? ` after ${ms} ms` : ''
111
+ if (code) log(`[far] ${new Date().toISOString()} ${what}: ${code}${took} · ${err.message || ''}`)
112
+ else log(`[far] ${new Date().toISOString()} ${what}: ok again${took}`)
113
+ if (code) lastError.set(what, code); else lastError.delete(what)
114
+ }
115
+
99
116
  const link = () => {
100
117
  const l = loadLink()
101
118
  if (!l) throw fail('not-linked', 'this machine is not linked to a vault, so it cannot see your other machines')
@@ -120,6 +137,7 @@ export function makeFar ({ dir, loadLink, kind, discover = discoverReal, connect
120
137
 
121
138
  /** Las consolas de una máquina, abriendo su conexión de control si hace falta. */
122
139
  async function readOne (m) {
140
+ const t0 = Date.now()
123
141
  try {
124
142
  if (!m.rc) m.rc = await connect({ link: link(), dir, sub: m.sub })
125
143
  let r = await ask(m.rc, { type: 'list' }, 'consoles')
@@ -133,21 +151,30 @@ export function makeFar ({ dir, loadLink, kind, discover = discoverReal, connect
133
151
  m.locked = r.code === 'locked'
134
152
  m.consoles = null
135
153
  m.error = m.locked ? null : { code: r.code, message: r.message }
154
+ report(`machine ${m.id}`, m.error, Date.now() - t0)
136
155
  return
137
156
  }
138
157
  m.locked = false; m.error = null; m.consoles = r.list
158
+ report(`machine ${m.id}`, null, Date.now() - t0)
139
159
  } catch (e) {
140
160
  // No contestó o la sesión cayó: la conexión se suelta y la próxima pasada abre otra.
141
161
  drop(m)
142
162
  m.consoles = null; m.locked = false
143
163
  m.error = { code: e.code || 'unreachable', message: e.message }
164
+ report(`machine ${m.id}`, m.error, Date.now() - t0)
144
165
  }
145
166
  }
146
167
 
147
168
  async function refresh () {
148
169
  const now = Date.now()
149
170
  if (now - discoveredAt >= discoverMs || !discoveredAt) {
150
- const found = await discover({ link: link(), dir, kind, state })
171
+ const t0 = Date.now()
172
+ let found
173
+ try { found = await discover({ link: link(), dir, kind, state }) } catch (e) {
174
+ report('vault (list of machines)', e, Date.now() - t0)
175
+ throw e
176
+ }
177
+ report('vault (list of machines)', null, Date.now() - t0)
151
178
  discoveredAt = Date.now()
152
179
  const alive = new Set(found.map((f) => f.sub))
153
180
  for (const [sub, m] of machines) if (!alive.has(sub)) { drop(m); machines.delete(sub) }
package/index.js CHANGED
@@ -21,12 +21,16 @@
21
21
  * { type:'unlock', code } (la clave de la máquina, si tiene: access.js) ·
22
22
  * { type:'file', up, seq, data, last? } (una imagen, en trozos base64 y en
23
23
  * orden; cada trozo se acusa con `filed`, y el último trae la `path` donde
24
- * quedó en esta máquina: uploads.js)
24
+ * quedó en esta máquina: uploads.js) ·
25
+ * { type:'fetch', id, path, seq } (un trozo de un archivo de esta máquina, para
26
+ * abrirlo en el aparato; una ruta relativa cuelga de la carpeta de la consola
27
+ * enganchada: downloads.js)
25
28
  * agente → cliente: { type:'consoles', list } · { type:'attached', id, fresh } ·
26
29
  * { type:'replay', id, data, last } · { type:'out', id, data } ·
27
30
  * { type:'exit', code, closedBy? } · { type:'fail', code, message, retryMs? } ·
28
31
  * { type:'unlocked' } · { type:'noted', console } ·
29
- * { type:'filed', up, seq, path? }
32
+ * { type:'filed', up, seq, path? } ·
33
+ * { type:'fetched', id, seq, path, name, size, mtime, data, last? }
30
34
  *
31
35
  * Con clave puesta, una sesión remota que no la ha escrito recibe `fail` con `code:'locked'`
32
36
  * a todo lo que pida; tras `unlock` vale para esa conexión. `bad-code` y `wait` traen
@@ -40,11 +44,12 @@ import { startRemoteAgent } from '@dotrino/remote-agent/agent'
40
44
  import { dataDir, loadLink, LABEL } from './link.js'
41
45
  import { listTransports, netReport } from '@dotrino/proxy-client'
42
46
  import { shortId } from './far.js'
43
- import { ConsoleHub, pieces, isTyped } from './consoles.js'
47
+ import { ConsoleHub, pieces, isTyped, cwdOf } from './consoles.js'
44
48
  import { listenLocal } from './local.js'
45
49
  import { makeGate } from './access.js'
46
50
  import { makeFar } from './far.js'
47
51
  import { makeUploads } from './uploads.js'
52
+ import { readPiece } from './downloads.js'
48
53
 
49
54
  const require = createRequire(import.meta.url)
50
55
  const { version: VERSION } = require('./package.json')
@@ -254,6 +259,14 @@ export function serveSession (session, hub, { origin = 'remote', gate = null, up
254
259
  }
255
260
  return
256
261
  }
262
+ // Un archivo de esta máquina, para abrirlo en el aparato (una ruta que salió en la consola).
263
+ if (msg.type === 'fetch') {
264
+ try { session.send({ type: 'fetched', ...readPiece(msg, current ? cwdOf(current.pty?.pid) : null) }) } catch (e) {
265
+ 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)
266
+ fail(e.code || 'fetch-failed', e.message)
267
+ }
268
+ return
269
+ }
257
270
  // El orden del panel: es de la máquina, así que lo ve igual cualquier pantalla.
258
271
  if (msg.type === 'move') {
259
272
  if (!hub.move(String(msg.id), msg.before == null ? null : String(msg.before))) return fail('no-console', 'that console no longer exists')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dotrino/terminal-agent",
3
- "version": "0.49.5",
3
+ "version": "0.50.1",
4
4
  "description": "Dotrino Terminal: las ventanas de esta máquina (dotrino-terminal) y su agente, que deja abrir esas mismas consolas desde los otros aparatos de tu cuenta, cifrado punto a punto.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -19,6 +19,7 @@
19
19
  "claude.js",
20
20
  "consoles.js",
21
21
  "desktop.js",
22
+ "downloads.js",
22
23
  "link.js",
23
24
  "local.js",
24
25
  "service.js",