@dotrino/terminal-agent 0.16.0 → 0.17.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/bin/terminal.js CHANGED
@@ -319,10 +319,13 @@ function interactive (conn, first, dir) {
319
319
  // primeros milisegundos (antes de pasar a crudo), y entonces todo se pintaba corrido: el cursor
320
320
  // acababa en la columna 0 o encima del prompt. Por eso, antes de la primera, en limpio.
321
321
  let clean = false
322
+ let switching = false // se pidió pasar a otra consola y aún no contestó
323
+ let recovering = false // falló el cambio: se está repintando la que había
322
324
  conn.on('message', (m) => {
323
325
  if (m.type === 'replay' && !clean) { clean = true; out.write('\x1b[H\x1b[2J') }
324
326
  if (m.type === 'out' || m.type === 'replay') { out.write(filter(m.data)); return }
325
327
  if (m.type === 'attached') {
328
+ switching = false; recovering = false
326
329
  consoleId = m.id
327
330
  onInfo(m.console)
328
331
  // Ya hay consola: va lo que se tecleó mientras tanto, en orden y de una vez.
@@ -331,8 +334,32 @@ function interactive (conn, first, dir) {
331
334
  return
332
335
  }
333
336
  if (m.type === 'meta') { onInfo(m.console); return }
334
- if (m.type === 'exit') { finish(m.code || 0); return }
335
- if (m.type === 'fail') { finish(1, `dotrino-terminal: ${m.message} (${m.code})`) }
337
+ if (m.type === 'exit') {
338
+ // LA CERRÓ OTRA PANTALLA (el teléfono, la web, el panel de otra ventana): esta ventana no
339
+ // se va — nadie aquí pidió cerrarla, y cerrarla dejaba al usuario sin ventana y sin forma
340
+ // de abrir otra consola. Se abre una nueva y se dice. Si la shell terminó sola (`exit`) o
341
+ // la cerró esta misma ventana, la ventana se cierra, como cualquier terminal.
342
+ if (m.closedBy === 'other') {
343
+ consoleId = null
344
+ switchTo({ type: 'open', cwd: first.cwd || path.resolve(process.cwd()) })
345
+ out.write(`\x1b[2m${t('Otra pantalla cerró esta consola. Esta es una nueva.', 'Another screen closed this console. This is a new one.')}\x1b[0m\r\n`)
346
+ return
347
+ }
348
+ finish(m.code || 0)
349
+ return
350
+ }
351
+ if (m.type === 'fail') {
352
+ // FALLÓ UN CAMBIO DE CONSOLA (la que se pidió ya no existe: el panel de la app iba un
353
+ // instante por detrás). El agente rechaza ANTES de soltar la actual, así que esta ventana
354
+ // sigue en la suya: se vuelve a pintar y se sigue. Terminar aquí cerraba la ventana entera
355
+ // por elegir una entrada caducada. Solo es fatal si falla al arrancar, o al repintar.
356
+ if (switching && consoleId && !recovering) {
357
+ switching = false; recovering = true
358
+ conn.send({ type: 'attach', id: consoleId, ...size(), ...tag() })
359
+ return
360
+ }
361
+ finish(1, `dotrino-terminal: ${m.message} (${m.code})`)
362
+ }
336
363
  })
337
364
  conn.on('close', () => {
338
365
  // Si se fue porque el perfil cambió de nombre (`rename`), no es un error: se dice y se sale.
@@ -350,6 +377,7 @@ function interactive (conn, first, dir) {
350
377
  // repetición de la otra consola no se pinte encima. Lo tecleado mientras tanto se guarda.
351
378
  const switchTo = (msg) => {
352
379
  ready = false
380
+ switching = true
353
381
  out.write('\x1bc') // RIS: pantalla, historial y modos, de cero
354
382
  conn.send({ ...msg, ...size(), ...tag() })
355
383
  }
package/consoles.js CHANGED
@@ -24,10 +24,37 @@ export const SCROLLBACK = 1000
24
24
  /** Tamaño máximo de cada trozo de la repetición: el proxio corta los mensajes a 1 MB. */
25
25
  export const REPLAY_CHUNK = 64 * 1024
26
26
 
27
+ // ¿ESTÁ TRABAJANDO? Lo que el panel enseña con un color por consola.
28
+ // · Si el programa lo dice en el TÍTULO, manda eso. Claude Code lo hace (medido el 2026-10-06
29
+ // con la 2.1.291): «✳ tema» esperando, «◐ tema» / «◑ tema» alternando mientras trabaja.
30
+ // · Si no lo dice (otro agente, un comando): salida SOSTENIDA que no es eco de lo tecleado es
31
+ // trabajo, y el silencio es que terminó.
32
+ // «Terminó» (`doneAt`) queda marcado hasta que alguien entra a la consola o teclea en ella: es
33
+ // lo que avisa de que un agente acabó mientras mirabas otra cosa. Una campana (BEL) lo marca igual.
34
+ const BUSY_GLYPHS = /^[\u25d0-\u25d3\u25f4-\u25f7\u2800-\u28ff]/ // ◐◑◒◓ ◴◵◶◷ y los girasoles braille
35
+ const IDLE_GLYPHS = /^\u2733/ // ✳
36
+ /** Lo que dice el título: true (trabajando), false (esperando) o null (el programa no lo dice). */
37
+ export function titleSignal (title) {
38
+ const t = String(title || '')
39
+ if (BUSY_GLYPHS.test(t)) return true
40
+ if (IDLE_GLYPHS.test(t)) return false
41
+ return null
42
+ }
43
+ const ECHO_MS = 400 // salida tan pegada a una tecla es su eco, no trabajo
44
+ const SUSTAIN_MS = 1500 // salida propia durante este rato = está trabajando
45
+ const GAP_MS = 1000 // un hueco mayor que este corta la racha: no era salida seguida
46
+ // EL RESPALDO, para quien no lo dice en el título (OpenCode, un comando cualquiera): si la
47
+ // pantalla no cambia en este rato, la consola está quieta. Un minuto por defecto (dueño,
48
+ // 2026-10-06): un programa que piensa en silencio unos segundos no debe darse por terminado.
49
+ // `DOTRINO_TERMINAL_IDLE_SECONDS` lo cambia; quien lo dice en el título no espera a esto.
50
+ export const QUIET_MS = Math.max(1, Number(process.env.DOTRINO_TERMINAL_IDLE_SECONDS) || 60) * 1000
51
+ const MIN_TASK_MS = 3000 // menos que esto no fue «una tarea»: no se marca como terminada
52
+
27
53
  const randomId = () => [...crypto.getRandomValues(new Uint8Array(8))].map((x) => x.toString(16).padStart(2, '0')).join('')
28
54
 
29
55
  class Console {
30
- constructor ({ id, n, pty, cols, rows, origin }) {
56
+ constructor ({ id, n, pty, cols, rows, origin, quietMs = QUIET_MS }) {
57
+ this.quietMs = quietMs
31
58
  this.id = id
32
59
  this.n = n // su número, fijo mientras viva (ver ConsoleHub.create)
33
60
  this.pty = pty
@@ -49,7 +76,44 @@ class Console {
49
76
  this.screen = new Terminal({ cols, rows, scrollback: SCROLLBACK, allowProposedApi: true })
50
77
  this.serializer = new SerializeAddon()
51
78
  this.screen.loadAddon(this.serializer)
52
- this.screen.onTitleChange((t) => { this.title = String(t).slice(0, 200); this._meta() })
79
+ this.busy = false // ¿trabajando ahora?
80
+ this.busySince = 0
81
+ this.doneAt = null // terminó (o pidió atención) y nadie lo ha atendido
82
+ this.lastInput = 0
83
+ this._titleSays = null // lo último que dijo el título (true/false), o null si no lo dice
84
+ this._outSince = 0 // desde cuándo hay salida propia seguida
85
+ this._lastOwnOut = 0
86
+ this._quiet = null
87
+ this.screen.onTitleChange((t) => {
88
+ this.title = String(t).slice(0, 200)
89
+ const says = titleSignal(this.title)
90
+ const before = this._titleSays
91
+ this._titleSays = says
92
+ // Cuando el programa lo dice, manda él; si DEJA de decirlo (salió), ya no está trabajando.
93
+ // Un título que nunca dijo nada (el de la shell) no toca lo que se dedujo de la salida.
94
+ let changed = false
95
+ if (says !== null) changed = this._setBusy(says)
96
+ else if (before !== null) changed = this._setBusy(false)
97
+ if (!changed) this._meta()
98
+ })
99
+ this.screen.onBell(() => { this.doneAt = Date.now(); this._meta() })
100
+ }
101
+
102
+ /** Cambia «trabajando». Al dejar de trabajar tras una tarea de verdad, queda como terminada. */
103
+ _setBusy (v) {
104
+ if (v === this.busy) return false
105
+ const now = Date.now()
106
+ this.busy = v
107
+ if (v) { this.busySince = now; this.doneAt = null } else if (now - this.busySince >= MIN_TASK_MS) this.doneAt = now
108
+ this._meta()
109
+ return true
110
+ }
111
+
112
+ /** Alguien atendió la consola (entró o tecleó): ya no está «terminada sin atender». */
113
+ _attended () {
114
+ if (this.doneAt == null) return
115
+ this.doneAt = null
116
+ this._meta()
53
117
  }
54
118
 
55
119
  /** Avisa a todos los que miran de que cambió quién mira o el título. */
@@ -60,12 +124,26 @@ class Console {
60
124
 
61
125
  /** Lo que sale de la shell: a la pantalla sin pantalla y a quien esté mirando. */
62
126
  _out (data) {
63
- this.lastActive = Date.now()
127
+ const now = Date.now()
128
+ this.lastActive = now
129
+ // Sin señal en el título: salida propia y sostenida = trabajando; el silencio lo apaga.
130
+ if (this._titleSays === null) {
131
+ if (now - this.lastInput > ECHO_MS) {
132
+ // SOSTENIDA = seguida: dos ráfagas sueltas (el prompt que se redibuja al cambiar el
133
+ // tamaño, y otra cosa segundos después) no son un programa trabajando.
134
+ if (!this._outSince || now - this._lastOwnOut > GAP_MS) this._outSince = now
135
+ this._lastOwnOut = now
136
+ if (now - this._outSince >= SUSTAIN_MS) this._setBusy(true)
137
+ }
138
+ clearTimeout(this._quiet)
139
+ this._quiet = setTimeout(() => { this._outSince = 0; if (this._titleSays === null) this._setBusy(false) }, this.quietMs)
140
+ this._quiet.unref?.()
141
+ }
64
142
  this.screen.write(data)
65
143
  for (const v of this.viewers) v.onOut(data)
66
144
  }
67
145
 
68
- write (data) { this.lastActive = Date.now(); this.pty.write(data) }
146
+ write (data) { this.lastActive = this.lastInput = Date.now(); this._attended(); this.pty.write(data) }
69
147
 
70
148
  resize (cols, rows) {
71
149
  if (!cols || !rows) return
@@ -95,6 +173,7 @@ class Console {
95
173
  const snapshot = this.serializer.serialize()
96
174
  this.viewers.delete(buffering)
97
175
  this.viewers.add(viewer)
176
+ this.doneAt = null // quien entra, la atiende (el `_meta` de abajo lo cuenta)
98
177
  resolve(snapshot + pending.join(''))
99
178
  this._meta()
100
179
  })
@@ -151,7 +230,7 @@ class Console {
151
230
  const watchers = [...this.viewers].filter((v) => v.origin).map((v) => ({ origin: v.origin, device: v.device || null, tag: v.tag || null }))
152
231
  const d = this.decider()
153
232
  const sizeBy = d ? { origin: d.origin || null, device: d.device || null, tag: d.tag || null, pinned: !!d && d === this.pinnedViewer() } : null
154
- return { id: this.id, n: this.n, sizeBy, origin: this.origin, title: this.title, cols: this.cols, rows: this.rows, createdAt: this.createdAt, lastActive: this.lastActive, viewers: this.viewers.size, watchers }
233
+ return { id: this.id, n: this.n, activity: this.busy ? 'busy' : 'idle', doneAt: this.doneAt, sizeBy, origin: this.origin, title: this.title, cols: this.cols, rows: this.rows, createdAt: this.createdAt, lastActive: this.lastActive, viewers: this.viewers.size, watchers }
155
234
  }
156
235
  }
157
236
 
@@ -164,8 +243,9 @@ export class ConsoleHub {
164
243
  * @param {{ spawn:(opts:{cols:number,rows:number,cwd:string|null})=>any }} opts
165
244
  * `spawn` lanza la shell (un PTY con `onData`, `onExit`, `write`, `resize`, `kill`).
166
245
  */
167
- constructor ({ spawn }) {
246
+ constructor ({ spawn, quietMs = QUIET_MS }) {
168
247
  this._spawn = spawn
248
+ this._quietMs = quietMs
169
249
  this.consoles = new Map()
170
250
  }
171
251
 
@@ -178,12 +258,16 @@ export class ConsoleHub {
178
258
  let n = 1
179
259
  while (used.has(n)) n++
180
260
  const pty = this._spawn({ cols, rows, cwd })
181
- const c = new Console({ id, n, pty, cols, rows, origin })
261
+ const c = new Console({ id, n, pty, cols, rows, origin, quietMs: this._quietMs })
182
262
  pty.onData((d) => c._out(d))
183
263
  pty.onExit(({ exitCode }) => {
184
264
  c.exited = true
265
+ clearTimeout(c._quiet)
185
266
  this.consoles.delete(id)
186
- for (const v of c.viewers) v.onExit(exitCode)
267
+ // A cada pantalla se le dice si la consola la cerró OTRA (`byOther`): la shell que termina
268
+ // sola, o la que cierra la propia pantalla, no lo es. Quien mira decide con eso si se va
269
+ // (una ventana cuya shell hizo `exit`) o si sigue (se la cerraron desde otro aparato).
270
+ for (const v of c.viewers) v.onExit(exitCode, { byOther: c.killed === true && c.killedBy !== v })
187
271
  c.viewers.clear()
188
272
  try { c.screen.dispose() } catch (_) {}
189
273
  })
@@ -195,9 +279,12 @@ export class ConsoleHub {
195
279
 
196
280
  list () { return [...this.consoles.values()].map((c) => c.info()).sort((a, b) => a.n - b.n) }
197
281
 
198
- kill (id) {
282
+ /** Cierra una consola. `by`: la pantalla (viewer) que lo pide, para decirle a las DEMÁS que no fueron ellas. */
283
+ kill (id, by = null) {
199
284
  const c = this.consoles.get(id)
200
285
  if (!c) return false
286
+ c.killed = true
287
+ c.killedBy = by
201
288
  try { c.pty.kill() } catch (_) {}
202
289
  return true
203
290
  }
package/index.js CHANGED
@@ -16,7 +16,7 @@
16
16
  * { type:'close' } (mata la consola enganchada) · { type:'kill', id }
17
17
  * agente → cliente: { type:'consoles', list } · { type:'attached', id, fresh } ·
18
18
  * { type:'replay', id, data, last } · { type:'out', data } ·
19
- * { type:'exit', code } · { type:'fail', code, message }
19
+ * { type:'exit', code, closedBy? } · { type:'fail', code, message }
20
20
  */
21
21
  import fs from 'node:fs'
22
22
  import os from 'node:os'
@@ -52,6 +52,7 @@ const isDir = (p) => {
52
52
  export function makeHub (pty, opts = {}) {
53
53
  const shell = opts.shell || process.env.SHELL || (process.platform === 'win32' ? 'powershell.exe' : 'bash')
54
54
  return new ConsoleHub({
55
+ ...(opts.quietMs ? { quietMs: opts.quietMs } : {}),
55
56
  spawn: ({ cols, rows, cwd }) => pty.spawn(shell, [], {
56
57
  name: 'xterm-256color', cols, rows,
57
58
  cwd: cwd || os.homedir(),
@@ -87,7 +88,8 @@ export function serveSession (session, hub, { origin = 'remote' } = {}) {
87
88
  origin,
88
89
  device: session.device || null,
89
90
  onOut: (data) => { session.send({ type: 'out', data }) },
90
- onExit: (code) => { current = null; owned = null; session.send({ type: 'exit', code }) },
91
+ // `closedBy: 'other'`: la cerró otra pantalla (no esta, ni la shell por su cuenta).
92
+ onExit: (code, why) => { current = null; owned = null; session.send({ type: 'exit', code, ...(why?.byOther ? { closedBy: 'other' } : {}) }) },
91
93
  onMeta: (info) => { session.send({ type: 'meta', console: info }) }
92
94
  }
93
95
  const release = () => { if (current) { current.detach(viewer); current = null } }
@@ -139,13 +141,13 @@ export function serveSession (session, hub, { origin = 'remote' } = {}) {
139
141
  if (msg.type === 'resize') { takeSize(msg); current?.sizeFrom(viewer); return }
140
142
  // ⤢ «Esta pantalla manda en el tamaño» (on) o soltarlo (off).
141
143
  if (msg.type === 'pin') { current?.pin(viewer, !!msg.on); return }
142
- if (msg.type === 'close') { if (current) hub.kill(current.id); return }
143
- if (msg.type === 'kill') { if (!hub.kill(msg.id)) fail('no-console', 'that console no longer exists') }
144
+ if (msg.type === 'close') { if (current) hub.kill(current.id, viewer); return }
145
+ if (msg.type === 'kill') { if (!hub.kill(msg.id, viewer)) fail('no-console', 'that console no longer exists') }
144
146
  })
145
147
  session.on('close', () => {
146
148
  const mine = owned && owned === current ? owned : null
147
149
  release()
148
- if (mine) hub.kill(mine.id)
150
+ if (mine) hub.kill(mine.id, viewer)
149
151
  })
150
152
  }
151
153
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dotrino/terminal-agent",
3
- "version": "0.16.0",
3
+ "version": "0.17.0",
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": {