@dotrino/terminal-agent 0.43.2 → 0.45.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/README.md +8 -2
- package/bin/terminal.js +146 -1
- package/claude.js +121 -0
- package/index.js +3 -0
- package/package.json +2 -1
- package/skills/hooks/terminal-note-stop.sh +18 -0
- package/skills/hooks/terminal-note-track.sh +17 -0
- package/skills/hooks/terminal-note.sh +14 -0
package/README.md
CHANGED
|
@@ -50,7 +50,10 @@ dotrino-terminal profiles [--json] # los perfiles (agentes con nombre) de
|
|
|
50
50
|
dotrino-terminal link [--name <n>] # enlazar un perfil con tu bóveda
|
|
51
51
|
dotrino-terminal rename <perfil> [nuevo] # renombrarlo (mueve su carpeta y para su agente; mismo aparato)
|
|
52
52
|
dotrino-terminal vscode [--name <n>] # la terminal embebida de VS Code abre consolas de aquí (--off lo deshace)
|
|
53
|
+
dotrino-terminal claude # Claude Code mantiene la tarjeta de su consola: skill + hooks en ~/.claude (--off lo deshace, --status lo dice)
|
|
53
54
|
dotrino-terminal desktop update [--check] # actualiza la app de escritorio: baja, verifica la firma e instala
|
|
55
|
+
dotrino-terminal agents [--json] # con qué versión corre el agente de cada perfil
|
|
56
|
+
dotrino-terminal restart [--name <n>] # para el agente para que arranque con la versión instalada (cierra sus consolas; --stale: solo los atrasados)
|
|
54
57
|
dotrino-terminal service install|uninstall|status [--name <n>] # el agente como servicio del usuario
|
|
55
58
|
```
|
|
56
59
|
|
|
@@ -121,8 +124,11 @@ programa que corre dentro (`--task`). En la tarjeta la tarea se ve y se quita, n
|
|
|
121
124
|
Sin `--id`, es la consola en la que corre la orden: el agente pone su id en
|
|
122
125
|
`DOTRINO_TERMINAL_CONSOLE`. Vive en memoria, como la consola: se va con ella. Hasta 4000 caracteres.
|
|
123
126
|
|
|
124
|
-
Para que un agente de IA la mantenga al día, el paquete trae un skill de Claude Code
|
|
125
|
-
`skills/dotrino-terminal-note
|
|
127
|
+
Para que un agente de IA la mantenga al día, el paquete trae un skill de Claude Code
|
|
128
|
+
(`skills/dotrino-terminal-note/`) y tres hooks (`skills/hooks/`): uno recuerda la tarjeta en cada
|
|
129
|
+
mensaje, otro apunta qué herramientas se usan y el tercero no deja terminar un turno con la tarjeta
|
|
130
|
+
vieja. `dotrino-terminal claude` los pone en `~/.claude` y los engancha en su `settings.json` sin
|
|
131
|
+
tocar lo demás (`claude.js`); `--off` quita exactamente eso. Fuera de una consola no hacen nada.
|
|
126
132
|
|
|
127
133
|
## Imágenes desde otro aparato
|
|
128
134
|
|
package/bin/terminal.js
CHANGED
|
@@ -19,6 +19,10 @@
|
|
|
19
19
|
* dotrino-terminal desktop update [--check] actualiza la app de escritorio (la ventana)
|
|
20
20
|
* dotrino-terminal updates [--json] [--desktop <versión>]
|
|
21
21
|
* qué versiones nuevas hay (del cliente y de la app)
|
|
22
|
+
* dotrino-terminal agents [--json] qué agente corre en cada perfil y con qué versión
|
|
23
|
+
* dotrino-terminal restart [--name <n>] [--stale] [--yes]
|
|
24
|
+
* para el agente (cierra sus consolas) para que arranque
|
|
25
|
+
* con la versión instalada
|
|
22
26
|
* dotrino-terminal service install|uninstall|status [--name <n>]
|
|
23
27
|
* el agente como servicio: arranca solo con la máquina
|
|
24
28
|
*
|
|
@@ -91,6 +95,11 @@ if (args.includes('-h') || args.includes('--help')) {
|
|
|
91
95
|
(--check solo mira si hay una)
|
|
92
96
|
dotrino-terminal updates [--json] dice si hay versión nueva de dotrino-terminal y de la app
|
|
93
97
|
(--desktop <versión> es la app que tienes; no instala nada)
|
|
98
|
+
dotrino-terminal agents [--json] qué agente corre en cada perfil, con qué versión y si va
|
|
99
|
+
por detrás de la instalada
|
|
100
|
+
dotrino-terminal restart [--name <n>] para el agente para que arranque con la versión instalada
|
|
101
|
+
(cierra TODAS sus consolas; --stale: solo los que van por
|
|
102
|
+
detrás, en todos los perfiles; --yes no pregunta)
|
|
94
103
|
dotrino-terminal service install [--name <n>] deja el agente como servicio de tu usuario: arranca
|
|
95
104
|
solo al encender la máquina, sin abrir ninguna ventana
|
|
96
105
|
dotrino-terminal service uninstall [--name <n>] lo quita (para el agente: cierra sus consolas)
|
|
@@ -126,11 +135,19 @@ Cerrar la ventana no cierra la consola: sigue abierta y se retoma después.`, `u
|
|
|
126
135
|
dotrino-terminal vscode [--name <n>] make the integrated terminal of VS Code (and VS Code
|
|
127
136
|
Insiders, VSCodium and Cursor) open consoles from here
|
|
128
137
|
dotrino-terminal vscode --off undo it
|
|
138
|
+
dotrino-terminal claude make Claude Code keep the card of the console it runs
|
|
139
|
+
in up to date (installs a skill and three hooks in ~/.claude)
|
|
140
|
+
dotrino-terminal claude --off undo it (--status says whether it is set)
|
|
129
141
|
dotrino-terminal desktop update update the desktop app (the window): downloads the
|
|
130
142
|
new version, checks its signature and installs it
|
|
131
143
|
(--check only looks for one)
|
|
132
144
|
dotrino-terminal updates [--json] say whether there is a new version of dotrino-terminal and of
|
|
133
145
|
the app (--desktop <version> is the app you have; installs nothing)
|
|
146
|
+
dotrino-terminal agents [--json] which agent runs in each profile, its version and whether
|
|
147
|
+
it is behind the installed one
|
|
148
|
+
dotrino-terminal restart [--name <n>] stop the agent so it starts with the installed version
|
|
149
|
+
(closes ALL its consoles; --stale: only the ones behind,
|
|
150
|
+
in every profile; --yes does not ask)
|
|
134
151
|
dotrino-terminal service install [--name <n>] run the agent as a service of your user: it starts
|
|
135
152
|
by itself when the machine boots, with no window open
|
|
136
153
|
dotrino-terminal service uninstall [--name <n>] remove it (stops the agent: closes its consoles)
|
|
@@ -184,6 +201,9 @@ async function agent (dir) {
|
|
|
184
201
|
// Un agente vivo sin socket es uno anterior a las ventanas (< 0.6.0): no se levanta otro
|
|
185
202
|
// encima (tendrían la misma llave), se dice.
|
|
186
203
|
const pid = Number((() => { try { return fs.readFileSync(path.join(dir, 'agent.pid'), 'utf8') } catch (_) { return '' } })())
|
|
204
|
+
// Un agente que se está yendo (`dotrino-terminal restart`) cierra su socket un instante antes
|
|
205
|
+
// de terminar: se le da ese instante antes de decir que es uno viejo.
|
|
206
|
+
for (const t0 = Date.now(); pid && alive(pid) && Date.now() - t0 < 3000;) await new Promise((r) => setTimeout(r, 100))
|
|
187
207
|
if (pid && alive(pid)) {
|
|
188
208
|
throw new Error(t(`hay un agente corriendo (pid ${pid}) que no acepta ventanas: es anterior a la 0.6.0. Reinícialo con la versión nueva.`,
|
|
189
209
|
`an agent is running (pid ${pid}) that does not accept windows: it predates 0.6.0. Restart it with the new version.`))
|
|
@@ -248,6 +268,41 @@ function vscode () {
|
|
|
248
268
|
if (!off) console.log(t('\nLas terminales nuevas del editor ya abren aquí. Si actualizas o cambias de Node, vuelve a correr esta orden.', '\nNew terminals in the editor now open here. If you update or switch Node, run this command again.'))
|
|
249
269
|
}
|
|
250
270
|
|
|
271
|
+
/**
|
|
272
|
+
* `dotrino-terminal claude`: que Claude Code mantenga la tarjeta «de qué va» de su consola (el
|
|
273
|
+
* skill y los hooks, `claude.js`). `--off` lo quita; `--status` dice si está puesto.
|
|
274
|
+
*/
|
|
275
|
+
async function claude () {
|
|
276
|
+
const { configureClaude, claudeStatus, HOOKS } = await import('../claude.js')
|
|
277
|
+
if (args.includes('--status')) {
|
|
278
|
+
const s = claudeStatus()
|
|
279
|
+
const all = s.skill && s.hooks.length === HOOKS.length && s.wired.length === HOOKS.length
|
|
280
|
+
const none = !s.skill && !s.hooks.length && !s.wired.length
|
|
281
|
+
if (args.includes('--json')) { console.log(JSON.stringify({ installed: all, ...s })); return }
|
|
282
|
+
console.log(all ? t('Instalado: Claude Code mantiene la tarjeta de sus consolas.', 'Installed: Claude Code keeps the card of its consoles.')
|
|
283
|
+
: none ? t('No está instalado. Se pone con: dotrino-terminal claude', 'Not installed. Set it with: dotrino-terminal claude')
|
|
284
|
+
: t('A medias: vuelve a correr «dotrino-terminal claude» para dejarlo entero.', 'Half set: run "dotrino-terminal claude" again to complete it.'))
|
|
285
|
+
return
|
|
286
|
+
}
|
|
287
|
+
const off = args.includes('--off')
|
|
288
|
+
let done
|
|
289
|
+
try { done = configureClaude({ off }) } catch (e) {
|
|
290
|
+
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.'))
|
|
291
|
+
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}`))
|
|
292
|
+
throw e
|
|
293
|
+
}
|
|
294
|
+
const what = off
|
|
295
|
+
? (done.changed ? t('quitado', 'removed') : t('no estaba', 'was not set'))
|
|
296
|
+
: (done.changed ? t('instalado', 'installed') : t('ya estaba', 'already set'))
|
|
297
|
+
console.log(` Claude Code ${what}`)
|
|
298
|
+
if (!off) {
|
|
299
|
+
console.log(` ${done.skill}`)
|
|
300
|
+
for (const h of done.hooks) console.log(` ${h}`)
|
|
301
|
+
console.log(` ${done.settings}`)
|
|
302
|
+
console.log(t('\nLas sesiones NUEVAS de Claude Code dentro de una consola de Dotrino Terminal ya mantienen su tarjeta. Fuera de una consola no hace nada.', '\nNEW Claude Code sessions inside a Dotrino Terminal console now keep its card. Outside a console it does nothing.'))
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
251
306
|
/**
|
|
252
307
|
* Qué versiones nuevas hay, sin instalar nada: del cliente (npm) y, con `--desktop <versión>`,
|
|
253
308
|
* de la app de escritorio. La app lo pregunta al arrancar (ella no tiene red). Cada una dice
|
|
@@ -326,6 +381,89 @@ async function openConsoles (dir) {
|
|
|
326
381
|
return r.list.length
|
|
327
382
|
}
|
|
328
383
|
|
|
384
|
+
/** Lo que se espera a que un agente diga su versión: uno anterior a la 0.45.0 no contesta. */
|
|
385
|
+
const VERSION_WAIT_MS = 1500
|
|
386
|
+
|
|
387
|
+
/**
|
|
388
|
+
* Los agentes de esta máquina, uno por perfil: si corre, con qué versión y cuántas consolas.
|
|
389
|
+
* `stale`: corre con una versión que no es la instalada (el paquete se actualizó y él sigue con
|
|
390
|
+
* la anterior hasta que se reinicie). `version: null`: no la dijo, así que es anterior a la 0.45.0.
|
|
391
|
+
*/
|
|
392
|
+
async function agentStates () {
|
|
393
|
+
const out = []
|
|
394
|
+
for (const p of await listProfiles()) {
|
|
395
|
+
let conn
|
|
396
|
+
try { conn = await connectLocal(p.dir) } catch (e) {
|
|
397
|
+
if (e.code !== 'ENOAGENT') throw e
|
|
398
|
+
out.push({ name: p.name, running: false, version: null, consoles: 0, stale: false })
|
|
399
|
+
continue
|
|
400
|
+
}
|
|
401
|
+
const v = await Promise.race([request(conn, { type: 'version' }, 'version'), new Promise((resolve) => setTimeout(() => resolve(null), VERSION_WAIT_MS))])
|
|
402
|
+
const l = await request(conn, { type: 'list' }, 'consoles')
|
|
403
|
+
conn.close()
|
|
404
|
+
if (l.type === 'fail') throw new Error(`${l.message} (${l.code})`)
|
|
405
|
+
const version = v && v.type === 'version' ? v.version : null
|
|
406
|
+
out.push({ name: p.name, running: true, version, consoles: l.list.length, stale: version !== VERSION })
|
|
407
|
+
}
|
|
408
|
+
return out
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/** `dotrino-terminal agents`: qué agente corre en cada perfil y si va por detrás de lo instalado. */
|
|
412
|
+
async function agents () {
|
|
413
|
+
const list = await agentStates()
|
|
414
|
+
if (args.includes('--json')) { console.log(JSON.stringify({ installed: VERSION, agents: list })); return }
|
|
415
|
+
for (const a of list) {
|
|
416
|
+
const what = !a.running ? t('parado', 'stopped')
|
|
417
|
+
: `${a.version || t('anterior a la 0.45.0', 'older than 0.45.0')} · ${a.consoles} ${t('consola(s)', 'console(s)')}${a.stale ? t(` · instalada la ${VERSION}: reinícialo con «dotrino-terminal restart --name ${a.name}»`, ` · ${VERSION} is installed: restart it with "dotrino-terminal restart --name ${a.name}"`) : ''}`
|
|
418
|
+
console.log(` ${a.name.padEnd(16)} ${what}`)
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/**
|
|
423
|
+
* `dotrino-terminal restart`: para el agente para que arranque con la versión instalada. Cierra
|
|
424
|
+
* TODAS sus consolas (las de las ventanas, las de un editor y las que miran otros aparatos), así
|
|
425
|
+
* que pregunta antes. `--stale`: solo los que van por detrás de lo instalado, en todos los perfiles.
|
|
426
|
+
*/
|
|
427
|
+
async function restart () {
|
|
428
|
+
const stale = args.includes('--stale')
|
|
429
|
+
const asked = opt('--name')
|
|
430
|
+
if (asked !== undefined && !isValidName(asked)) die(t(`nombre de perfil no válido: ${asked}`, `invalid profile name: ${asked}`))
|
|
431
|
+
const only = stale && asked === undefined ? null : path.basename(resolveInstance(LABEL, asked).dir)
|
|
432
|
+
const targets = (await agentStates()).filter((a) => a.running && (only === null || a.name === only) && (!stale || a.stale))
|
|
433
|
+
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 }
|
|
434
|
+
const dirOf = (name) => resolveInstance(LABEL, name).dir
|
|
435
|
+
// ¿Corre esta orden DENTRO de una consola de uno de esos agentes? Pararlo la cerraría a mitad
|
|
436
|
+
// de camino: el trabajo lo hace un proceso aparte.
|
|
437
|
+
const inside = targets.some((a) => !!process.env.DOTRINO_TERMINAL_PROFILE_DIR && samePath(process.env.DOTRINO_TERMINAL_PROFILE_DIR, dirOf(a.name)))
|
|
438
|
+
const open = targets.reduce((n, a) => n + a.consoles, 0)
|
|
439
|
+
if (open && !args.includes('--yes')) {
|
|
440
|
+
const ok = await ask(t(`Se van a cerrar ${open} consola(s)${inside ? ', esta incluida' : ''}. ¿Seguir? [s/N] `, `${open} console(s) will be closed${inside ? ', this one included' : ''}. Continue? [y/N] `))
|
|
441
|
+
if (!/^[sy]/i.test(ok)) die(t('No se reinició nada.', 'Nothing was restarted.'))
|
|
442
|
+
}
|
|
443
|
+
if (inside && !args.includes('--detached-step')) {
|
|
444
|
+
const self = fileURLToPath(import.meta.url)
|
|
445
|
+
spawn(process.execPath, [self, ...args.filter((a) => a !== '--yes'), '--yes', '--detached-step'], { detached: true, stdio: 'ignore', env: process.env }).unref()
|
|
446
|
+
console.log(t('Reiniciando. Esta consola se va a cerrar.', 'Restarting. This console is about to close.'))
|
|
447
|
+
return
|
|
448
|
+
}
|
|
449
|
+
const { serviceStatus } = await import('../service.js')
|
|
450
|
+
for (const a of targets) {
|
|
451
|
+
const dir = dirOf(a.name)
|
|
452
|
+
const pid = Number((() => { try { return fs.readFileSync(path.join(dir, 'agent.pid'), 'utf8') } catch (_) { return '' } })())
|
|
453
|
+
if (!pid || !alive(pid)) die(t(`el agente de «${a.name}» contesta pero no dejó su pid: páralo a mano.`, `the agent of "${a.name}" answers but left no pid: stop it by hand.`))
|
|
454
|
+
process.kill(pid, 'SIGTERM')
|
|
455
|
+
for (const t0 = Date.now(); alive(pid);) {
|
|
456
|
+
if (Date.now() - t0 > 5000) die(t(`el agente de «${a.name}» (pid ${pid}) no se detuvo: páralo a mano.`, `the agent of "${a.name}" (pid ${pid}) did not stop: stop it by hand.`))
|
|
457
|
+
await new Promise((r) => setTimeout(r, 100))
|
|
458
|
+
}
|
|
459
|
+
let service = false
|
|
460
|
+
try { service = serviceStatus({ name: a.name }).installed } catch (e) { if (e.code !== 'no-user-systemd' && e.code !== 'unsupported-platform') throw e }
|
|
461
|
+
console.log(service
|
|
462
|
+
? 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}.`)
|
|
463
|
+
: 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.`))
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
|
|
329
467
|
/** El agente como servicio del usuario (systemd en Linux, launchd en macOS). */
|
|
330
468
|
async function service () {
|
|
331
469
|
const action = args[1]
|
|
@@ -851,7 +989,11 @@ function interactive (conn, first, dir) {
|
|
|
851
989
|
if (ch === 'p') { conn.send({ type: 'resize', ...size() }); conn.send({ type: 'take' }); continue }
|
|
852
990
|
if (ch === 'n') {
|
|
853
991
|
if (send) { input(send); send = '' }
|
|
854
|
-
|
|
992
|
+
// En otra máquina (`--machine`) la carpeta de aquí no existe: sin `--cwd`, la consola
|
|
993
|
+
// nueva abre en su carpeta de inicio. Mandar la de aquí hacía que la rechazara
|
|
994
|
+
// (`bad-cwd`) y la ventana acababa en otra consola en vez de en una nueva.
|
|
995
|
+
const where = opt('--machine') ? (first.cwd ? { cwd: first.cwd } : {}) : { cwd: first.cwd || path.resolve(process.cwd()) }
|
|
996
|
+
switchTo({ type: 'open', ...where })
|
|
855
997
|
continue
|
|
856
998
|
}
|
|
857
999
|
send += ch === DETACH_PREFIX ? ch : DETACH_PREFIX + ch
|
|
@@ -888,8 +1030,11 @@ try {
|
|
|
888
1030
|
if (cmd === 'rename') { await rename(); process.exit(0) }
|
|
889
1031
|
if (cmd === 'lock') { await lock(); process.exit(0) }
|
|
890
1032
|
if (cmd === 'vscode') { vscode(); process.exit(0) }
|
|
1033
|
+
if (cmd === 'claude') { await claude(); process.exit(0) }
|
|
891
1034
|
if (cmd === 'desktop') { await desktop(); process.exit(0) }
|
|
892
1035
|
if (cmd === 'updates') { await updates(); process.exit(0) }
|
|
1036
|
+
if (cmd === 'agents') { await agents(); process.exit(0) }
|
|
1037
|
+
if (cmd === 'restart') { await restart(); process.exit(0) }
|
|
893
1038
|
if (cmd === 'service') { await service(); process.exit(0) }
|
|
894
1039
|
if (cmd === 'note') { await note(); process.exit(0) }
|
|
895
1040
|
const dir = opt('--dir') || dataDir(opt('--name'))
|
package/claude.js
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* claude.js — que Claude Code mantenga al día la tarjeta «de qué va» de su consola.
|
|
3
|
+
*
|
|
4
|
+
* `dotrino-terminal claude` deja en la carpeta de Claude Code del usuario (`~/.claude`):
|
|
5
|
+
* · el skill `dotrino-terminal-note` (cómo se usa `dotrino-terminal note --task`);
|
|
6
|
+
* · tres hooks, y sus entradas en `settings.json`: uno recuerda la tarjeta en cada mensaje, otro
|
|
7
|
+
* apunta qué herramientas se usan, y el tercero no deja terminar un turno con la tarjeta vieja.
|
|
8
|
+
* `--off` quita exactamente eso. Fuera de una consola de Dotrino Terminal los hooks no hacen nada.
|
|
9
|
+
*
|
|
10
|
+
* Es la misma idea que `editors.js` con VS Code: una orden que se puede repetir y deshacer, y que
|
|
11
|
+
* no toca lo demás del archivo del usuario.
|
|
12
|
+
*/
|
|
13
|
+
import fs from 'node:fs'
|
|
14
|
+
import os from 'node:os'
|
|
15
|
+
import path from 'node:path'
|
|
16
|
+
import { fileURLToPath } from 'node:url'
|
|
17
|
+
|
|
18
|
+
export const SKILL = 'dotrino-terminal-note'
|
|
19
|
+
/** Cada hook: su archivo y el evento de Claude Code en que corre. */
|
|
20
|
+
export const HOOKS = [
|
|
21
|
+
{ file: 'terminal-note.sh', event: 'UserPromptSubmit' },
|
|
22
|
+
{ file: 'terminal-note-track.sh', event: 'PreToolUse' },
|
|
23
|
+
{ file: 'terminal-note-stop.sh', event: 'Stop' },
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
const fail = (code, message) => Object.assign(new Error(message), { code })
|
|
27
|
+
const source = () => path.join(path.dirname(fileURLToPath(import.meta.url)), 'skills')
|
|
28
|
+
|
|
29
|
+
/** ¿Es `command` el hook `file`? Por el archivo, lo llame como lo llame (con o sin comillas). */
|
|
30
|
+
const runs = (command, file) => typeof command === 'string' && new RegExp(`[/\\\\]hooks[/\\\\]${file.replace(/\./g, '\\.')}(["'\\s]|$)`).test(command)
|
|
31
|
+
|
|
32
|
+
function readSettings (file) {
|
|
33
|
+
if (!fs.existsSync(file)) return {}
|
|
34
|
+
let value
|
|
35
|
+
try { value = JSON.parse(fs.readFileSync(file, 'utf8')) } catch (e) { throw fail('bad-settings', `${file}: ${e.message}`) }
|
|
36
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) throw fail('bad-settings', `${file}: not an object`)
|
|
37
|
+
return value
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** `settings` sin las entradas de nuestros hooks (y sin los grupos o eventos que queden vacíos). */
|
|
41
|
+
function withoutHooks (settings) {
|
|
42
|
+
const hooks = settings.hooks
|
|
43
|
+
if (!hooks || typeof hooks !== 'object') return settings
|
|
44
|
+
const out = {}
|
|
45
|
+
for (const [event, groups] of Object.entries(hooks)) {
|
|
46
|
+
if (!Array.isArray(groups)) { out[event] = groups; continue }
|
|
47
|
+
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))
|
|
49
|
+
.filter((g) => !Array.isArray(g?.hooks) || g.hooks.length)
|
|
50
|
+
if (kept.length) out[event] = kept
|
|
51
|
+
}
|
|
52
|
+
const next = { ...settings, hooks: out }
|
|
53
|
+
if (!Object.keys(out).length) delete next.hooks
|
|
54
|
+
return next
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** ¿Está puesto? `{ skill, hooks: [archivos presentes], wired: [archivos con entrada en settings] }`. */
|
|
58
|
+
export function claudeStatus ({ home = os.homedir() } = {}) {
|
|
59
|
+
const dir = path.join(home, '.claude')
|
|
60
|
+
let settings = {}
|
|
61
|
+
try { settings = readSettings(path.join(dir, 'settings.json')) } catch (_) {}
|
|
62
|
+
const commands = Object.values(settings.hooks || {}).flat().flatMap((g) => g?.hooks || []).map((h) => h?.command)
|
|
63
|
+
return {
|
|
64
|
+
skill: fs.existsSync(path.join(dir, 'skills', SKILL, 'SKILL.md')),
|
|
65
|
+
hooks: HOOKS.filter((h) => fs.existsSync(path.join(dir, 'hooks', h.file))).map((h) => h.file),
|
|
66
|
+
wired: HOOKS.filter((h) => commands.some((c) => runs(c, h.file))).map((h) => h.file),
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Pone (o con `off`, quita) el skill y los hooks. Devuelve qué cambió.
|
|
72
|
+
* Sin `~/.claude` no hay Claude Code en esta cuenta: se dice (`no-claude`) y no se crea nada.
|
|
73
|
+
* Un `settings.json` que no se puede leer no se toca (`bad-settings`).
|
|
74
|
+
*/
|
|
75
|
+
export function configureClaude ({ off = false, home = os.homedir(), from = source() } = {}) {
|
|
76
|
+
const dir = path.join(home, '.claude')
|
|
77
|
+
if (!fs.existsSync(dir)) throw fail('no-claude', `${dir} does not exist`)
|
|
78
|
+
const settingsFile = path.join(dir, 'settings.json')
|
|
79
|
+
const before = readSettings(settingsFile)
|
|
80
|
+
const skillDir = path.join(dir, 'skills', SKILL)
|
|
81
|
+
const hooksDir = path.join(dir, 'hooks')
|
|
82
|
+
|
|
83
|
+
// Lo que ya está enganchado (lo llame como lo llame) se deja como está: no se duplica ni se mueve.
|
|
84
|
+
const wired = (file) => Object.values(before.hooks || {}).flat().flatMap((g) => g?.hooks || []).some((h) => runs(h?.command, file))
|
|
85
|
+
let next = before
|
|
86
|
+
if (off) next = withoutHooks(before)
|
|
87
|
+
else {
|
|
88
|
+
const hooks = { ...(before.hooks || {}) }
|
|
89
|
+
for (const h of HOOKS.filter((x) => !wired(x.file))) {
|
|
90
|
+
const file = path.join(hooksDir, h.file)
|
|
91
|
+
const command = `bash ${/\s/.test(file) ? JSON.stringify(file) : file}`
|
|
92
|
+
hooks[h.event] = [...(Array.isArray(hooks[h.event]) ? hooks[h.event] : []), { hooks: [{ type: 'command', command, timeout: 5 }] }]
|
|
93
|
+
}
|
|
94
|
+
next = { ...before, hooks }
|
|
95
|
+
}
|
|
96
|
+
const settingsChanged = JSON.stringify(before) !== JSON.stringify(next)
|
|
97
|
+
|
|
98
|
+
let filesChanged = false
|
|
99
|
+
if (off) {
|
|
100
|
+
for (const h of HOOKS) { const f = path.join(hooksDir, h.file); if (fs.existsSync(f)) { fs.rmSync(f); filesChanged = true } }
|
|
101
|
+
if (fs.existsSync(skillDir)) { fs.rmSync(skillDir, { recursive: true }); filesChanged = true }
|
|
102
|
+
} else {
|
|
103
|
+
const put = (src, dest, mode) => {
|
|
104
|
+
const want = fs.readFileSync(src)
|
|
105
|
+
if (fs.existsSync(dest) && fs.readFileSync(dest).equals(want)) return
|
|
106
|
+
fs.mkdirSync(path.dirname(dest), { recursive: true })
|
|
107
|
+
fs.writeFileSync(dest, want, { mode })
|
|
108
|
+
fs.chmodSync(dest, mode)
|
|
109
|
+
filesChanged = true
|
|
110
|
+
}
|
|
111
|
+
put(path.join(from, SKILL, 'SKILL.md'), path.join(skillDir, 'SKILL.md'), 0o644)
|
|
112
|
+
for (const h of HOOKS) put(path.join(from, 'hooks', h.file), path.join(hooksDir, h.file), 0o755)
|
|
113
|
+
}
|
|
114
|
+
if (settingsChanged) {
|
|
115
|
+
// De una vez (temporal + renombrar): Claude Code lee este archivo en cada sesión.
|
|
116
|
+
const tmp = `${settingsFile}.dotrino-${process.pid}`
|
|
117
|
+
fs.writeFileSync(tmp, JSON.stringify(next, null, 2) + '\n')
|
|
118
|
+
fs.renameSync(tmp, settingsFile)
|
|
119
|
+
}
|
|
120
|
+
return { changed: settingsChanged || filesChanged, settings: settingsFile, skill: skillDir, hooks: HOOKS.map((h) => path.join(hooksDir, h.file)) }
|
|
121
|
+
}
|
package/index.js
CHANGED
|
@@ -45,6 +45,7 @@ import { makeFar } from './far.js'
|
|
|
45
45
|
import { makeUploads } from './uploads.js'
|
|
46
46
|
|
|
47
47
|
const require = createRequire(import.meta.url)
|
|
48
|
+
const { version: VERSION } = require('./package.json')
|
|
48
49
|
|
|
49
50
|
/** Cuánto se espera al canal directo antes de mandar el historial por el proxio. */
|
|
50
51
|
export const HISTORY_WAIT_MS = 8000
|
|
@@ -186,6 +187,8 @@ export function serveSession (session, hub, { origin = 'remote', gate = null, up
|
|
|
186
187
|
return
|
|
187
188
|
}
|
|
188
189
|
if (!mayPass()) return
|
|
190
|
+
// Qué versión corre: tras actualizar el paquete, el agente en marcha sigue con la anterior.
|
|
191
|
+
if (msg.type === 'version') { session.send({ type: 'version', version: VERSION }); return }
|
|
189
192
|
if (msg.type === 'list') { session.send({ type: 'consoles', list: hub.list() }); return }
|
|
190
193
|
if (msg.type === 'open') {
|
|
191
194
|
takeSize(msg)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dotrino/terminal-agent",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.45.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": {
|
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
"access.js",
|
|
16
16
|
"far.js",
|
|
17
17
|
"editors.js",
|
|
18
|
+
"claude.js",
|
|
18
19
|
"consoles.js",
|
|
19
20
|
"desktop.js",
|
|
20
21
|
"link.js",
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# Stop: dentro de una consola de Dotrino Terminal, no deja terminar el turno con la tarjeta
|
|
3
|
+
# vieja. Si en este turno se usaron herramientas y la tarea no se puso DESPUÉS de la última, la
|
|
4
|
+
# tarjeta dice algo que ya no es cierto («Ahora: compilando» con todo terminado): se le devuelve
|
|
5
|
+
# a Claude para que la ponga al día. Una sola vez por parada (stop_hook_active), sin bucles.
|
|
6
|
+
[ -n "$DOTRINO_TERMINAL_CONSOLE" ] || exit 0
|
|
7
|
+
command -v dotrino-terminal >/dev/null 2>&1 || exit 0
|
|
8
|
+
input=$(cat)
|
|
9
|
+
case "$input" in *'"stop_hook_active":true'*|*'"stop_hook_active": true'*) exit 0 ;; esac
|
|
10
|
+
key="$HOME/.claude/hooks/state/note-$DOTRINO_TERMINAL_CONSOLE"
|
|
11
|
+
prompt=$(cat "$key.prompt" 2>/dev/null || echo 0)
|
|
12
|
+
tool=$(cat "$key.tool" 2>/dev/null || echo 0)
|
|
13
|
+
task=$(cat "$key.task" 2>/dev/null || echo 0)
|
|
14
|
+
# Sin herramientas en este turno no cambió nada: la tarjeta sigue valiendo.
|
|
15
|
+
[ "$tool" -gt "$prompt" ] || exit 0
|
|
16
|
+
[ "$task" -gt "$tool" ] && exit 0
|
|
17
|
+
echo "La tarjeta de esta consola quedó vieja: en este turno hiciste cosas y no pusiste la tarea después. Antes de terminar, ponla al día con \`dotrino-terminal note --task\` (lo que quedó hecho, y si terminaste o qué esperas; nada de «Ahora:» que ya no ocurre). Solo --task; no lo anuncies." >&2
|
|
18
|
+
exit 2
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# PreToolUse (todas las herramientas): dentro de una consola de Dotrino Terminal, apunta cuándo
|
|
3
|
+
# fue la última herramienta usada y cuándo la última vez que se puso la tarea de la tarjeta
|
|
4
|
+
# (`dotrino-terminal note --task`). Con eso, terminal-note-stop.sh sabe si la tarjeta quedó vieja.
|
|
5
|
+
[ -n "$DOTRINO_TERMINAL_CONSOLE" ] || exit 0
|
|
6
|
+
dir="$HOME/.claude/hooks/state"; key="$dir/note-$DOTRINO_TERMINAL_CONSOLE"
|
|
7
|
+
mkdir -p "$dir"
|
|
8
|
+
input=$(cat)
|
|
9
|
+
n=$(( $(cat "$key.n" 2>/dev/null || echo 0) + 1 )); echo "$n" > "$key.n"
|
|
10
|
+
case "$input" in
|
|
11
|
+
*'"tool_name":"Bash"'*|*'"tool_name": "Bash"'*)
|
|
12
|
+
case "$input" in
|
|
13
|
+
*'note --task'*) echo "$n" > "$key.task"; exit 0 ;;
|
|
14
|
+
esac ;;
|
|
15
|
+
esac
|
|
16
|
+
echo "$n" > "$key.tool"
|
|
17
|
+
exit 0
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# UserPromptSubmit: dentro de una consola de Dotrino Terminal, recuerda en cada mensaje que la
|
|
3
|
+
# tarjeta «de qué va» se mantiene al día. Fuera de una consola no dice nada.
|
|
4
|
+
# Lo instala `dotrino-terminal claude` (y lo quita `dotrino-terminal claude --off`).
|
|
5
|
+
[ -n "$DOTRINO_TERMINAL_CONSOLE" ] || exit 0
|
|
6
|
+
command -v dotrino-terminal >/dev/null 2>&1 || exit 0
|
|
7
|
+
# En qué momento empezó este turno (lo usa terminal-note-stop.sh). Un contador, no la hora: el
|
|
8
|
+
# `date` de macOS no da fracciones de segundo, y dos cosas en el mismo segundo no se ordenarían.
|
|
9
|
+
dir="$HOME/.claude/hooks/state"; key="$dir/note-$DOTRINO_TERMINAL_CONSOLE"
|
|
10
|
+
mkdir -p "$dir"
|
|
11
|
+
n=$(( $(cat "$key.n" 2>/dev/null || echo 0) + 1 )); echo "$n" > "$key.n"; echo "$n" > "$key.prompt"
|
|
12
|
+
cat <<'MSG'
|
|
13
|
+
[Dotrino Terminal] Esta sesión corre en una consola con tarjeta «de qué va». Mantén la tarea al día con `dotrino-terminal note --task … --title '<de qué va, en pocas palabras>'` (skill dotrino-terminal-note; el título es el nombre de la consola: el mismo mientras la tarea sea la misma, otro cuando cambie): al empezar lo que pide este mensaje, CADA VEZ que pase algo (un paso terminado, algo publicado, un fallo, un cambio de rumbo, quedar esperando algo) y al terminar. La última línea, siempre: `Modelo: <el modelo que eres>`. Solo `--task` y `--title`: las notas personales del dueño no se tocan. Sin anunciarlo en la respuesta.
|
|
14
|
+
MSG
|