@dotrino/terminal-agent 0.7.1 → 0.8.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/README.md +1 -0
- package/bin/terminal.js +134 -9
- package/index.js +5 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -29,6 +29,7 @@ dotrino-terminal attach <id> # retomar una
|
|
|
29
29
|
dotrino-terminal kill <id>
|
|
30
30
|
dotrino-terminal profiles [--json] # los perfiles (agentes con nombre) de esta máquina
|
|
31
31
|
dotrino-terminal link [--name <n>] # enlazar un perfil con tu bóveda
|
|
32
|
+
dotrino-terminal rename <perfil> [nuevo] # renombrarlo (mueve su carpeta y para su agente; mismo aparato)
|
|
32
33
|
```
|
|
33
34
|
|
|
34
35
|
Cerrar la ventana cierra su consola, como cualquier terminal; **Ctrl+] y luego d** la suelta
|
package/bin/terminal.js
CHANGED
|
@@ -8,6 +8,8 @@
|
|
|
8
8
|
* dotrino-terminal kill <id> [--name <n>] cierra una consola
|
|
9
9
|
* dotrino-terminal profiles [--json] los perfiles de esta máquina (enlazados o no)
|
|
10
10
|
* dotrino-terminal link [--name <n>] enlaza un perfil con tu bóveda
|
|
11
|
+
dotrino-terminal rename <perfil> [nuevo] renombra un perfil (para su agente: cierra sus consolas)
|
|
12
|
+
* dotrino-terminal rename <perfil> [nuevo] renombra un perfil (para su agente si corre)
|
|
11
13
|
*
|
|
12
14
|
* Un PERFIL es un agente con nombre (`~/.dotrino/agent/terminal-agent/<nombre>/`), enlazado a
|
|
13
15
|
* una bóveda o solo local. Cada consola vive en el agente de un perfil.
|
|
@@ -50,6 +52,7 @@ if (args.includes('-h') || args.includes('--help')) {
|
|
|
50
52
|
dotrino-terminal kill <id> [--name <n>] cierra una consola
|
|
51
53
|
dotrino-terminal profiles [--json] los perfiles de esta máquina
|
|
52
54
|
dotrino-terminal link [--name <n>] enlaza un perfil con tu bóveda
|
|
55
|
+
dotrino-terminal rename <perfil> [nuevo] renombra un perfil (para su agente: cierra sus consolas)
|
|
53
56
|
|
|
54
57
|
Dentro de una consola: Ctrl+] y luego d la suelta sin cerrarla.
|
|
55
58
|
Cerrar la ventana cierra la consola que abrió.`, `usage:
|
|
@@ -59,6 +62,7 @@ Cerrar la ventana cierra la consola que abrió.`, `usage:
|
|
|
59
62
|
dotrino-terminal kill <id> [--name <n>] close a console
|
|
60
63
|
dotrino-terminal profiles [--json] this machine's profiles
|
|
61
64
|
dotrino-terminal link [--name <n>] link a profile with your vault
|
|
65
|
+
dotrino-terminal rename <profile> [new] rename a profile (stops its agent: closes its consoles)
|
|
62
66
|
|
|
63
67
|
Inside a console: Ctrl+] then d detaches without closing it.
|
|
64
68
|
Closing the window closes the console it opened.`))
|
|
@@ -72,6 +76,9 @@ Closing the window closes the console it opened.`))
|
|
|
72
76
|
*/
|
|
73
77
|
const HOLD = Symbol('hold')
|
|
74
78
|
function die (msg) {
|
|
79
|
+
// Si la TTY ya estaba en crudo (ver `captureEarly`), se devuelve a normal para que el
|
|
80
|
+
// mensaje salga con sus saltos de línea.
|
|
81
|
+
try { if (process.stdin.isTTY) process.stdin.setRawMode(false) } catch (_) {}
|
|
75
82
|
process.stderr.write(msg + '\n')
|
|
76
83
|
if (process.env.DOTRINO_TERMINAL_HOLD !== '1' || !process.stdin.isTTY) process.exit(1)
|
|
77
84
|
process.stderr.write(t('\nPulsa una tecla para cerrar.', '\nPress any key to close.'))
|
|
@@ -81,6 +88,22 @@ function die (msg) {
|
|
|
81
88
|
throw HOLD // corta lo que venía detrás; el proceso sale con la tecla
|
|
82
89
|
}
|
|
83
90
|
|
|
91
|
+
/**
|
|
92
|
+
* Lo que se teclea MIENTRAS el cliente arranca (Node, y a veces levantar el agente). Con la TTY
|
|
93
|
+
* en modo normal, eso se repetía en pantalla a destiempo y luego la pantalla de la consola lo
|
|
94
|
+
* pisaba (un retorno de carro y a sobrescribir), y el agente lo descartaba porque aún no había
|
|
95
|
+
* consola. Ahora la TTY pasa a crudo nada más empezar, y lo tecleado se guarda y se manda
|
|
96
|
+
* entero cuando la consola está lista.
|
|
97
|
+
*/
|
|
98
|
+
const early = []
|
|
99
|
+
const earlyTap = (b) => early.push(b)
|
|
100
|
+
function captureEarly () {
|
|
101
|
+
if (!process.stdin.isTTY) return
|
|
102
|
+
process.stdin.setRawMode(true)
|
|
103
|
+
process.stdin.resume()
|
|
104
|
+
process.stdin.on('data', earlyTap)
|
|
105
|
+
}
|
|
106
|
+
|
|
84
107
|
/** El agente de esta máquina; si no hay ninguno escuchando, lo levanta y espera a que conteste. */
|
|
85
108
|
async function agent (dir) {
|
|
86
109
|
try { return await connectLocal(dir) } catch (e) { if (e.code !== 'ENOAGENT') throw e }
|
|
@@ -138,6 +161,87 @@ async function link () {
|
|
|
138
161
|
console.log(t(`Perfil «${name}» enlazado.`, `Profile "${name}" linked.`))
|
|
139
162
|
}
|
|
140
163
|
|
|
164
|
+
function ask (q) {
|
|
165
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
|
|
166
|
+
return new Promise((resolve) => rl.question(q, (a) => { rl.close(); resolve(a.trim()) }))
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Renombra un perfil: su carpeta, nada más. Es el mismo aparato con la misma llave, así que el
|
|
171
|
+
* acta no se entera ni hace falta volver a enrolar. El nombre es solo tuyo, de esta máquina.
|
|
172
|
+
*
|
|
173
|
+
* Si su agente está corriendo hay que pararlo (las ventanas lo encuentran por el socket de esa
|
|
174
|
+
* carpeta), y eso cierra sus consolas: si quedan abiertas, se dice cuántas y se pregunta.
|
|
175
|
+
*/
|
|
176
|
+
async function rename () {
|
|
177
|
+
const from = args[1]
|
|
178
|
+
if (!from) die(t('falta el perfil: dotrino-terminal rename <perfil> [nuevo]', 'missing profile: dotrino-terminal rename <profile> [new]'))
|
|
179
|
+
if (!isValidName(from)) die(t(`nombre no válido: «${from}»`, `invalid name: "${from}"`))
|
|
180
|
+
const { dir } = resolveInstance(LABEL, from)
|
|
181
|
+
if (!fs.existsSync(dir)) die(t(`no existe el perfil «${from}»`, `there is no profile "${from}"`))
|
|
182
|
+
let to = args[2] && !args[2].startsWith('-') ? args[2] : await ask(t(`Nuevo nombre para «${from}» (a-z, 0-9, -): `, `New name for "${from}" (a-z, 0-9, -): `))
|
|
183
|
+
if (!isValidName(to)) die(t(`nombre no válido: «${to}» (usa a-z, 0-9 y -, hasta 32)`, `invalid name: "${to}" (use a-z, 0-9 and -, up to 32)`))
|
|
184
|
+
if (to === from) die(t('es el mismo nombre', 'that is the same name'))
|
|
185
|
+
const target = resolveInstance(LABEL, to).dir
|
|
186
|
+
if (fs.existsSync(target)) die(t(`ya hay un perfil «${to}»`, `there is already a profile "${to}"`))
|
|
187
|
+
|
|
188
|
+
const pidFile = path.join(dir, 'agent.pid')
|
|
189
|
+
const pid = Number((() => { try { return fs.readFileSync(pidFile, 'utf8') } catch (_) { return '' } })())
|
|
190
|
+
const running = pid && alive(pid)
|
|
191
|
+
// ¿Corre esta orden DENTRO de una consola del perfil que se renombra? Entonces parar su
|
|
192
|
+
// agente cerraría esta misma consola a mitad de camino: el trabajo lo hace un proceso aparte.
|
|
193
|
+
const inside = !!process.env.DOTRINO_TERMINAL_PROFILE_DIR && samePath(process.env.DOTRINO_TERMINAL_PROFILE_DIR, dir)
|
|
194
|
+
if (running && !args.includes('--yes')) {
|
|
195
|
+
let open = 0
|
|
196
|
+
try {
|
|
197
|
+
const conn = await connectLocal(dir)
|
|
198
|
+
open = ((await request(conn, { type: 'list' }, 'consoles')).list || []).length
|
|
199
|
+
conn.close()
|
|
200
|
+
} catch (_) { /* agente viejo sin socket: igual hay que pararlo */ }
|
|
201
|
+
const others = open - (inside ? 1 : 0)
|
|
202
|
+
if (others > 0) {
|
|
203
|
+
const ok = await ask(t(`El perfil «${from}» tiene ${others} consola(s) abierta(s) más; renombrarlo las cierra. ¿Seguir? [s/N] `, `Profile "${from}" has ${others} more open console(s); renaming it closes them. Continue? [y/N] `))
|
|
204
|
+
if (!/^[sy]/i.test(ok)) die(t('No se renombró.', 'Not renamed.'))
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
if (running && inside && !args.includes('--detached-step')) {
|
|
208
|
+
const self = fileURLToPath(import.meta.url)
|
|
209
|
+
spawn(process.execPath, [self, 'rename', from, to, '--yes', '--detached-step'], { detached: true, stdio: 'ignore', env: process.env }).unref()
|
|
210
|
+
console.log(t(`Renombrando «${from}» → «${to}». Esta consola es de ese perfil y se va a cerrar; la ventana sigue en «${to}».`,
|
|
211
|
+
`Renaming "${from}" → "${to}". This console belongs to that profile and is about to close; the window continues in "${to}".`))
|
|
212
|
+
return
|
|
213
|
+
}
|
|
214
|
+
// PRIMERO se mueve la carpeta y DESPUÉS se para el agente: así quien estaba mirando ve que el
|
|
215
|
+
// perfil ya cambió de nombre cuando se le cae la conexión (y no lo confunde con un fallo).
|
|
216
|
+
// Mover la carpeta con el agente vivo no rompe nada: el socket y el pid se van con ella.
|
|
217
|
+
fs.renameSync(dir, target)
|
|
218
|
+
if (running) {
|
|
219
|
+
process.kill(pid, 'SIGTERM')
|
|
220
|
+
const t0 = Date.now()
|
|
221
|
+
while (alive(pid)) {
|
|
222
|
+
if (Date.now() - t0 > 5000) die(t(`renombrado, pero el agente (pid ${pid}) no se detuvo: páralo a mano`, `renamed, but the agent (pid ${pid}) did not stop: stop it by hand`))
|
|
223
|
+
await new Promise((r) => setTimeout(r, 100))
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
// Lo que dejó el agente viejo (su pid y su socket ya no atienden): el próximo arranca limpio.
|
|
227
|
+
fs.rmSync(path.join(target, 'agent.pid'), { force: true })
|
|
228
|
+
fs.rmSync(path.join(target, 'terminal.sock'), { force: true })
|
|
229
|
+
// La app de escritorio recuerda el último perfil elegido: si era este, pasa al nombre nuevo.
|
|
230
|
+
const last = lastProfileFile()
|
|
231
|
+
try { if (fs.readFileSync(last, 'utf8').trim() === from) fs.writeFileSync(last, to) } catch (_) { /* sin preferencia guardada */ }
|
|
232
|
+
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.`))
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function samePath (a, b) {
|
|
236
|
+
try { return fs.realpathSync(a) === fs.realpathSync(b) } catch (_) { return path.resolve(a) === path.resolve(b) }
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** La preferencia de la app de escritorio: el último perfil elegido en su menú. */
|
|
240
|
+
function lastProfileFile () {
|
|
241
|
+
const base = process.env.XDG_CONFIG_HOME || path.join(process.env.HOME || '', '.config')
|
|
242
|
+
return path.join(base, 'dotrino-terminal', 'last-profile')
|
|
243
|
+
}
|
|
244
|
+
|
|
141
245
|
/** Una pregunta y su respuesta, para `ls` y `kill`. */
|
|
142
246
|
function request (conn, msg, type) {
|
|
143
247
|
return new Promise((resolve) => {
|
|
@@ -163,7 +267,11 @@ async function list (conn) {
|
|
|
163
267
|
}
|
|
164
268
|
|
|
165
269
|
/** La ventana: la TTY enganchada a una consola del agente. */
|
|
166
|
-
function interactive (conn, first) {
|
|
270
|
+
function interactive (conn, first, dir) {
|
|
271
|
+
// Hasta que el agente diga `attached` no hay consola a la que escribir: se guarda.
|
|
272
|
+
let ready = false
|
|
273
|
+
let queued = ''
|
|
274
|
+
const input = (data) => { if (ready) conn.send({ type: 'input', data }); else queued += data }
|
|
167
275
|
if (!process.stdin.isTTY || !process.stdout.isTTY) die(t('dotrino-terminal necesita una terminal (TTY).', 'dotrino-terminal needs a terminal (TTY).'))
|
|
168
276
|
const out = process.stdout
|
|
169
277
|
let consoleId = null
|
|
@@ -201,18 +309,30 @@ function interactive (conn, first) {
|
|
|
201
309
|
|
|
202
310
|
conn.on('message', (m) => {
|
|
203
311
|
if (m.type === 'out' || m.type === 'replay') { out.write(filter(m.data)); return }
|
|
204
|
-
if (m.type === 'attached') {
|
|
312
|
+
if (m.type === 'attached') {
|
|
313
|
+
consoleId = m.id
|
|
314
|
+
onInfo(m.console)
|
|
315
|
+
// Ya hay consola: va lo que se tecleó mientras tanto, en orden y de una vez.
|
|
316
|
+
ready = true
|
|
317
|
+
if (queued) { conn.send({ type: 'input', data: queued }); queued = '' }
|
|
318
|
+
return
|
|
319
|
+
}
|
|
205
320
|
if (m.type === 'meta') { onInfo(m.console); return }
|
|
206
321
|
if (m.type === 'exit') { finish(m.code || 0); return }
|
|
207
322
|
if (m.type === 'fail') { finish(1, `dotrino-terminal: ${m.message} (${m.code})`) }
|
|
208
323
|
})
|
|
209
|
-
conn.on('close', () =>
|
|
324
|
+
conn.on('close', () => {
|
|
325
|
+
// Si se fue porque el perfil cambió de nombre (`rename`), no es un error: se dice y se sale.
|
|
326
|
+
if (!fs.existsSync(dir)) return finish(0, t('Este perfil cambió de nombre.', 'This profile was renamed.'))
|
|
327
|
+
finish(1, t('dotrino-terminal: el agente se detuvo.', 'dotrino-terminal: the agent stopped.'))
|
|
328
|
+
})
|
|
210
329
|
|
|
211
330
|
process.stdin.setRawMode(true)
|
|
212
331
|
process.stdin.resume()
|
|
332
|
+
process.stdin.off('data', earlyTap)
|
|
213
333
|
const decoder = new StringDecoder('utf8')
|
|
214
334
|
let prefixed = false
|
|
215
|
-
|
|
335
|
+
const onKeys = (buf) => {
|
|
216
336
|
// Ctrl+] abre el atajo: «d» suelta la consola, otro Ctrl+] manda uno literal, y cualquier
|
|
217
337
|
// otra tecla pasa tal cual, con su Ctrl+] delante. Las dos teclas pueden llegar juntas.
|
|
218
338
|
let send = ''
|
|
@@ -220,7 +340,7 @@ function interactive (conn, first) {
|
|
|
220
340
|
if (prefixed) {
|
|
221
341
|
prefixed = false
|
|
222
342
|
if (ch === 'd') {
|
|
223
|
-
if (send)
|
|
343
|
+
if (send) input(send)
|
|
224
344
|
conn.send({ type: 'detach' })
|
|
225
345
|
return finish(0, t(`Consola soltada. Para volver: dotrino-terminal attach ${consoleId}`, `Console detached. To return: dotrino-terminal attach ${consoleId}`))
|
|
226
346
|
}
|
|
@@ -228,8 +348,11 @@ function interactive (conn, first) {
|
|
|
228
348
|
} else if (ch === DETACH_PREFIX) prefixed = true
|
|
229
349
|
else send += ch
|
|
230
350
|
}
|
|
231
|
-
if (send)
|
|
232
|
-
}
|
|
351
|
+
if (send) input(send)
|
|
352
|
+
}
|
|
353
|
+
process.stdin.on('data', onKeys)
|
|
354
|
+
// Lo tecleado antes de llegar aquí pasa por el mismo camino (el atajo de soltar incluido).
|
|
355
|
+
for (const b of early.splice(0)) onKeys(b)
|
|
233
356
|
out.on('resize', () => conn.send({ type: 'resize', ...size() }))
|
|
234
357
|
// La ventana se cerró: el agente ve caer la conexión y mata la consola que abrimos.
|
|
235
358
|
for (const sig of ['SIGHUP', 'SIGTERM']) process.on(sig, () => { conn.close(); process.exit(0) })
|
|
@@ -240,7 +363,9 @@ function interactive (conn, first) {
|
|
|
240
363
|
try {
|
|
241
364
|
if (cmd === 'profiles') { await profiles(); process.exit(0) }
|
|
242
365
|
if (cmd === 'link') { await link(); process.exit(0) }
|
|
366
|
+
if (cmd === 'rename') { await rename(); process.exit(0) }
|
|
243
367
|
const dir = opt('--dir') || dataDir(opt('--name'))
|
|
368
|
+
if (cmd === 'open' || cmd === 'attach') captureEarly()
|
|
244
369
|
const conn = await agent(dir)
|
|
245
370
|
if (cmd === 'ls' || cmd === 'list') { await list(conn); conn.close() } else if (cmd === 'kill') {
|
|
246
371
|
if (!args[1]) die(t('falta el id: dotrino-terminal kill <id>', 'missing id: dotrino-terminal kill <id>'))
|
|
@@ -250,10 +375,10 @@ try {
|
|
|
250
375
|
conn.close()
|
|
251
376
|
} else if (cmd === 'attach') {
|
|
252
377
|
if (!args[1]) die(t('falta el id: dotrino-terminal attach <id> (mira «dotrino-terminal ls»)', 'missing id: dotrino-terminal attach <id> (see "dotrino-terminal ls")'))
|
|
253
|
-
interactive(conn, { type: 'attach', id: args[1] })
|
|
378
|
+
interactive(conn, { type: 'attach', id: args[1] }, dir)
|
|
254
379
|
} else if (cmd === 'open') {
|
|
255
380
|
// Como cualquier terminal: la consola abre en la carpeta donde estás (o en `--cwd`).
|
|
256
|
-
interactive(conn, { type: 'open', cwd: path.resolve(opt('--cwd') || process.cwd()) })
|
|
381
|
+
interactive(conn, { type: 'open', cwd: path.resolve(opt('--cwd') || process.cwd()) }, dir)
|
|
257
382
|
} else die(t(`orden desconocida: ${cmd} (mira --help)`, `unknown command: ${cmd} (see --help)`))
|
|
258
383
|
} catch (e) {
|
|
259
384
|
if (e !== HOLD) { try { die(`dotrino-terminal: ${e.message}`) } catch (_) {} }
|
package/index.js
CHANGED
|
@@ -51,7 +51,10 @@ export function makeHub (pty, opts = {}) {
|
|
|
51
51
|
return new ConsoleHub({
|
|
52
52
|
spawn: ({ cols, rows, cwd }) => pty.spawn(shell, [], {
|
|
53
53
|
name: 'xterm-256color', cols, rows,
|
|
54
|
-
cwd: cwd || os.homedir(),
|
|
54
|
+
cwd: cwd || os.homedir(),
|
|
55
|
+
// La carpeta del perfil viaja a la shell: `dotrino-terminal rename` sabe así si corre
|
|
56
|
+
// dentro del mismo perfil que renombra (y que parar su agente cerraría su consola).
|
|
57
|
+
env: { ...process.env, TERM: 'xterm-256color', ...(opts.dir ? { DOTRINO_TERMINAL_PROFILE_DIR: opts.dir } : {}) }
|
|
55
58
|
})
|
|
56
59
|
})
|
|
57
60
|
}
|
|
@@ -156,7 +159,7 @@ export function serveSession (session, hub, { origin = 'remote' } = {}) {
|
|
|
156
159
|
*/
|
|
157
160
|
export async function startAgent (opts = {}) {
|
|
158
161
|
const dir = opts.dir || dataDir()
|
|
159
|
-
const hub = makeHub(loadPty(), opts)
|
|
162
|
+
const hub = makeHub(loadPty(), { ...opts, dir })
|
|
160
163
|
const local = await listenLocal({ dir, serve: (session) => serveSession(session, hub, { origin: 'local' }) })
|
|
161
164
|
let remote = null
|
|
162
165
|
let stopped = false
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dotrino/terminal-agent",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.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": {
|