@dotrino/remote-agent 0.34.0 → 0.36.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 CHANGED
@@ -38,8 +38,9 @@ Provee lo común — y **solo** eso:
38
38
  | `@dotrino/remote-agent` | isomórfico | `e2e` (`makeEphemeral`/`deriveKey`/`seal`/`open`) + constantes de protocolo |
39
39
  | `@dotrino/remote-agent/agent` | Node | `startRemoteAgent(opts)` |
40
40
  | `@dotrino/remote-agent/client` | navegador | `RemoteAgentClient` |
41
- | `@dotrino/remote-agent/link` | Node | `enroll`, `selfLink`, `isSelfLink`, `loadLink`, `saveLink`, `dataDir`, `parseQr`, `identityFromLink`, `clientLink`, `renewLink` |
41
+ | `@dotrino/remote-agent/link` | Node | `enroll`, `enrollInteractive` (pregunta la invitación en la terminal, 0.35.0), `selfLink`, `isSelfLink`, `loadLink`, `saveLink`, `dataDir`, `parseQr`, `identityFromLink`, `clientLink`, `renewLink` |
42
42
  | `@dotrino/remote-agent/discover` | navegador | `listAgentsByLabel`, `probeAgents` |
43
+ | `@dotrino/remote-agent/update` | Node | `startSelfUpdate`, `vaultHooks`: el agente se actualiza solo (CONVENCIONES §15) y se reinicia cuando está libre (0.36.0; necesita `@dotrino/update`) |
43
44
  | `@dotrino/remote-agent/instances` | Node | `resolveInstance`, `listInstances`, `lockInstance`, `instancesRoot` |
44
45
 
45
46
  ## Uso
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dotrino/remote-agent",
3
- "version": "0.34.0",
3
+ "version": "0.36.0",
4
4
  "description": "Middleware compartido del ecosistema Dotrino para apps de agente remoto cifrado punto a punto (handshake E2E, emparejamiento SAS con vault, revocación, descubrimiento). Lo consumen dotrino-terminal (PTY) y dotrino-ia (chat con IA).",
5
5
  "type": "module",
6
6
  "main": "./index.js",
@@ -37,6 +37,10 @@
37
37
  "./instances": {
38
38
  "types": "./types/src/instances.d.ts",
39
39
  "import": "./src/instances.js"
40
+ },
41
+ "./update": {
42
+ "types": "./types/src/update.d.ts",
43
+ "import": "./src/update.js"
40
44
  }
41
45
  },
42
46
  "files": [
@@ -77,14 +81,21 @@
77
81
  "peerDependencies": {
78
82
  "@dotrino/identity": ">=0.136.0",
79
83
  "@dotrino/proxy-client": ">=0.46.0",
80
- "@dotrino/vault": ">=0.115.0"
84
+ "@dotrino/vault": ">=0.115.0",
85
+ "@dotrino/update": ">=0.9.4"
81
86
  },
82
87
  "devDependencies": {
83
88
  "@dotrino/identity": "0.136.0",
84
89
  "@dotrino/proxy-client": "0.49.0",
85
- "@dotrino/vault": "0.115.0",
90
+ "@dotrino/vault": "0.121.2",
86
91
  "@types/node": "22.20.1",
87
92
  "@types/ws": "8.18.1",
88
- "typescript": "5.9.3"
93
+ "typescript": "5.9.3",
94
+ "@dotrino/update": "0.9.4"
95
+ },
96
+ "peerDependenciesMeta": {
97
+ "@dotrino/update": {
98
+ "optional": true
99
+ }
89
100
  }
90
101
  }
package/src/link.js CHANGED
@@ -179,6 +179,49 @@ export async function enroll ({ qr, label = 'remote-agent', dir = dataDir(), ns
179
179
  return link
180
180
  }
181
181
 
182
+ /**
183
+ * ENLAZAR PREGUNTANDO EN LA TERMINAL: pide la invitación de `dotrino-vault pair`, la canjea y,
184
+ * mientras espera, enseña el código que hay que aprobar en la bóveda. Es lo que corre un agente
185
+ * la primera vez (`dotrino-terminal-agent`, `dotrino-remote-desktop-agent`): antes cada uno
186
+ * traía su copia. La copy de la terminal va en español, como la de los comandos que la usan.
187
+ *
188
+ * Lanza `no-tty` sin terminal delante (un servicio): enlazar necesita a alguien que pegue la
189
+ * invitación y apruebe el código.
190
+ *
191
+ * @param {{ dir: string, label: string, input?: NodeJS.ReadableStream, output?: NodeJS.WritableStream }} opts
192
+ * @returns {Promise<AgentLink>}
193
+ */
194
+ export async function enrollInteractive ({ dir, label, input = process.stdin, output = process.stdout }) {
195
+ if (!(/** @type {any} */ (input)).isTTY && input === process.stdin) {
196
+ throw Object.assign(new Error('this machine is not linked, and linking needs an interactive terminal. Run it once in a terminal, then start it as a service.'), { code: 'no-tty' })
197
+ }
198
+ const say = (/** @type {string} */ t) => { output.write(t + '\n') }
199
+ const readline = await import('node:readline')
200
+ /** @param {string} q @returns {Promise<string>} */
201
+ const ask = (q) => {
202
+ const rl = readline.createInterface({ input, output })
203
+ return new Promise((resolve) => rl.question(q, (a) => { rl.close(); resolve(a) }))
204
+ }
205
+ say('Enlazar esta máquina con tu bóveda.')
206
+ say('En el PC de tu bóveda corre `dotrino-vault pair` y copia la invitación.\n')
207
+ const qr = await parseQr(await ask('Pega la invitación y pulsa Enter:\n> '))
208
+ say('\nConectando…')
209
+ const link = await enroll({
210
+ qr,
211
+ dir,
212
+ label,
213
+ onChallenge: ({ deviceId, code }) => {
214
+ say('\n Escribe ESTE código en tu bóveda para aprobar esta máquina:')
215
+ say(` código: ${code}`)
216
+ say(` máquina: ${deviceId}`)
217
+ say(` (en el PC de la bóveda: dotrino-vault approve ${code})\n`)
218
+ say(' Esperando la aprobación…')
219
+ }
220
+ })
221
+ say('\n ✓ Máquina enlazada.\n')
222
+ return link
223
+ }
224
+
182
225
  /**
183
226
  * UNA IDENTIDAD PROPIA, SIN BÓVEDA. El aparato cumple el rol cuando no hay pieza dedicada:
184
227
  * crea sus llaves (firma y cifrado) y un acta de génesis autofirmada donde él es el único
@@ -449,4 +492,4 @@ export function clientLink (link, opts) {
449
492
  return { id: identityFromLink(link, opts), cert: link.cert, iss: link.iss, proxy: link.proxy || DEFAULT_PROXY }
450
493
  }
451
494
 
452
- export default { dataDir, loadLink, saveLink, parseQr, enroll, selfLink, isSelfLink, identityFromLink, clientLink, renewLink, renewalReason, storeRenewedCert, refreshChain }
495
+ export default { dataDir, loadLink, saveLink, parseQr, enroll, enrollInteractive, selfLink, isSelfLink, identityFromLink, clientLink, renewLink, renewalReason, storeRenewedCert, refreshChain }
package/src/update.js ADDED
@@ -0,0 +1,103 @@
1
+ /**
2
+ * update.js — un agente SE ACTUALIZA SOLO (CONVENCIONES §15, dueño 2026-10-08).
3
+ *
4
+ * Lo común de todos los agentes que se instalan por npm (`terminal-agent`,
5
+ * `remote-desktop-agent`…): mirar, verificar e instalar lo hace `@dotrino/update/npm`; a quién
6
+ * se pregunta y a quién se avisa, `@dotrino/vault/service`. Aquí se juntan las dos piezas con
7
+ * lo que sí es común a los agentes: el enlace vive en una carpeta y se lee en cada llamada, y
8
+ * el agente solo se reinicia cuando no está atendiendo a nadie.
9
+ *
10
+ * Lo propio de cada agente se le pasa: su paquete, su repo, cómo se llaman sus releases y
11
+ * cuándo está ocupado (`busy`: la terminal cuenta consolas abiertas; el escritorio, gente
12
+ * mirando).
13
+ */
14
+ import { watchSelfUpdateNpm } from '@dotrino/update/npm'
15
+ import { vaultUpdateHooks } from '@dotrino/vault/service'
16
+ import { loadLink } from './link.js'
17
+
18
+ /** Cada cuánto se mira si ya está libre para reiniciar con la versión instalada. */
19
+ export const IDLE_CHECK_MS = 60_000
20
+
21
+ /** @type {(code: string, message: string) => Error & { code: string }} */
22
+ const fail = (code, message) => Object.assign(new Error(message), { code })
23
+
24
+ /**
25
+ * Lo que un agente le dice a SU bóveda sobre actualizarse: los tres ganchos de
26
+ * `vaultUpdateHooks`, armados EN CADA LLAMADA con el enlace leído del disco. El papel se renueva
27
+ * mientras el agente corre, y el agente puede arrancar sin enlace y enlazarse después: una
28
+ * conexión fijada al arrancar se quedaría vieja.
29
+ *
30
+ * @param {{ dir: string, product: string, log?: (m: string) => void, load?: (dir: string) => any, make?: typeof vaultUpdateHooks }} o
31
+ * @returns {import('@dotrino/vault/service').UpdateHooks}
32
+ */
33
+ export function vaultHooks ({ dir, product, log = console.log, load = loadLink, make = vaultUpdateHooks }) {
34
+ const now = () => {
35
+ const link = load(dir)
36
+ if (!link?.device || !link.cert || !link.iss) return null
37
+ return make({ product, log, proxyUrl: link.proxy || 'wss://proxy.dotrino.com', masterPubkey: link.iss, device: link.device, cert: link.cert })
38
+ }
39
+ return {
40
+ // true = sí · false = no, o pasó el día sin respuesta · lanza = no se pudo preguntar.
41
+ /** @param {import('@dotrino/vault/service').UpdateInfo} u */
42
+ async mayUpdate (u) {
43
+ const h = now()
44
+ // Sin enlace no hay a quién preguntar. No es un «no»: se dice y se reintenta.
45
+ if (!h) throw fail('not-linked', 'this agent is not linked to a vault, so there is nobody to ask')
46
+ return h.mayUpdate(u)
47
+ },
48
+ // Sin enlace no hay bóveda a la que contárselo: no es un fallo que reintentar.
49
+ /** @param {import('@dotrino/vault/service').UpdateInfo} u */
50
+ async onUpdated (u) { await now()?.onUpdated(u) },
51
+ /** @param {import('@dotrino/vault/service').UpdateInfo} u */
52
+ async onNeedsRoot (u) { await now()?.onNeedsRoot(u) }
53
+ }
54
+ }
55
+
56
+ /**
57
+ * Enciende la autoactualización de un agente que ya corre.
58
+ *
59
+ * La versión nueva se instala en cuanto sale, pero el agente solo se va cuando `busy()` da 0:
60
+ * tumbarle a alguien lo que está usando para estrenar una versión es justo lo contrario de lo
61
+ * que se quiere. Y sin quien lo levante (systemd, pm2) no se va nunca: irse sería apagarle el
62
+ * servicio al usuario.
63
+ *
64
+ * @param {{
65
+ * pkg: string, repo: string, tag: (version: string) => string, label: string,
66
+ * dir: string, version: string, busy: () => number, close: () => unknown,
67
+ * exit?: (code: number) => void, log?: (m: string) => void, watch?: typeof watchSelfUpdateNpm,
68
+ * hooks?: import('@dotrino/vault/service').UpdateHooks, idleCheckMs?: number
69
+ * }} o
70
+ * `label`: con qué se presenta en el log (`terminal-agent`). `busy`: cuánto está atendiendo
71
+ * ahora (consolas, gente mirando). `close`: cerrar lo suyo antes de salir.
72
+ * @returns {() => void} para dejar de mirar
73
+ */
74
+ export function startSelfUpdate ({ pkg, repo, tag, label, dir, version, busy, close, exit = (code) => process.exit(code), log = console.log, watch = watchSelfUpdateNpm, hooks = vaultHooks({ dir, product: pkg, log }), idleCheckMs = IDLE_CHECK_MS }) {
75
+ /** @type {ReturnType<typeof setInterval> | null} */
76
+ let waiting = null
77
+ /** @param {string} v */
78
+ const restart = async (v) => {
79
+ log(`[${label}] restarting to run ${v}`)
80
+ try { await close() } catch (_) {}
81
+ exit(0)
82
+ }
83
+ const stop = watch({
84
+ pkg,
85
+ current: version,
86
+ repo,
87
+ tag,
88
+ dir,
89
+ ...hooks,
90
+ onInstalled: ({ version: v, restart: supervised }) => {
91
+ if (!supervised) return
92
+ if (!busy()) { restart(v); return }
93
+ if (waiting) return
94
+ log(`[${label}] ${v} is installed · busy (${busy()}), so it restarts when it is free`)
95
+ const timer = waiting = setInterval(() => { if (!busy()) { clearInterval(timer); waiting = null; restart(v) } }, idleCheckMs)
96
+ timer.unref?.()
97
+ },
98
+ log
99
+ })
100
+ return () => { if (waiting) { clearInterval(waiting); waiting = null } stop?.() }
101
+ }
102
+
103
+ export default { startSelfUpdate, vaultHooks, IDLE_CHECK_MS }
@@ -88,6 +88,24 @@ export function enroll({ qr, label, dir, ns, onChallenge, timeoutMs }?: {
88
88
  }) => void) | undefined;
89
89
  timeoutMs?: number | undefined;
90
90
  }): Promise<AgentLink>;
91
+ /**
92
+ * ENLAZAR PREGUNTANDO EN LA TERMINAL: pide la invitación de `dotrino-vault pair`, la canjea y,
93
+ * mientras espera, enseña el código que hay que aprobar en la bóveda. Es lo que corre un agente
94
+ * la primera vez (`dotrino-terminal-agent`, `dotrino-remote-desktop-agent`): antes cada uno
95
+ * traía su copia. La copy de la terminal va en español, como la de los comandos que la usan.
96
+ *
97
+ * Lanza `no-tty` sin terminal delante (un servicio): enlazar necesita a alguien que pegue la
98
+ * invitación y apruebe el código.
99
+ *
100
+ * @param {{ dir: string, label: string, input?: NodeJS.ReadableStream, output?: NodeJS.WritableStream }} opts
101
+ * @returns {Promise<AgentLink>}
102
+ */
103
+ export function enrollInteractive({ dir, label, input, output }: {
104
+ dir: string;
105
+ label: string;
106
+ input?: NodeJS.ReadableStream;
107
+ output?: NodeJS.WritableStream;
108
+ }): Promise<AgentLink>;
91
109
  /**
92
110
  * UNA IDENTIDAD PROPIA, SIN BÓVEDA. El aparato cumple el rol cuando no hay pieza dedicada:
93
111
  * crea sus llaves (firma y cifrado) y un acta de génesis autofirmada donde él es el único
@@ -220,6 +238,7 @@ declare namespace _default {
220
238
  export { saveLink };
221
239
  export { parseQr };
222
240
  export { enroll };
241
+ export { enrollInteractive };
223
242
  export { selfLink };
224
243
  export { isSelfLink };
225
244
  export { identityFromLink };
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Lo que un agente le dice a SU bóveda sobre actualizarse: los tres ganchos de
3
+ * `vaultUpdateHooks`, armados EN CADA LLAMADA con el enlace leído del disco. El papel se renueva
4
+ * mientras el agente corre, y el agente puede arrancar sin enlace y enlazarse después: una
5
+ * conexión fijada al arrancar se quedaría vieja.
6
+ *
7
+ * @param {{ dir: string, product: string, log?: (m: string) => void, load?: (dir: string) => any, make?: typeof vaultUpdateHooks }} o
8
+ * @returns {import('@dotrino/vault/service').UpdateHooks}
9
+ */
10
+ export function vaultHooks({ dir, product, log, load, make }: {
11
+ dir: string;
12
+ product: string;
13
+ log?: (m: string) => void;
14
+ load?: (dir: string) => any;
15
+ make?: typeof vaultUpdateHooks;
16
+ }): import("@dotrino/vault/service").UpdateHooks;
17
+ /**
18
+ * Enciende la autoactualización de un agente que ya corre.
19
+ *
20
+ * La versión nueva se instala en cuanto sale, pero el agente solo se va cuando `busy()` da 0:
21
+ * tumbarle a alguien lo que está usando para estrenar una versión es justo lo contrario de lo
22
+ * que se quiere. Y sin quien lo levante (systemd, pm2) no se va nunca: irse sería apagarle el
23
+ * servicio al usuario.
24
+ *
25
+ * @param {{
26
+ * pkg: string, repo: string, tag: (version: string) => string, label: string,
27
+ * dir: string, version: string, busy: () => number, close: () => unknown,
28
+ * exit?: (code: number) => void, log?: (m: string) => void, watch?: typeof watchSelfUpdateNpm,
29
+ * hooks?: import('@dotrino/vault/service').UpdateHooks, idleCheckMs?: number
30
+ * }} o
31
+ * `label`: con qué se presenta en el log (`terminal-agent`). `busy`: cuánto está atendiendo
32
+ * ahora (consolas, gente mirando). `close`: cerrar lo suyo antes de salir.
33
+ * @returns {() => void} para dejar de mirar
34
+ */
35
+ export function startSelfUpdate({ pkg, repo, tag, label, dir, version, busy, close, exit, log, watch, hooks, idleCheckMs }: {
36
+ pkg: string;
37
+ repo: string;
38
+ tag: (version: string) => string;
39
+ label: string;
40
+ dir: string;
41
+ version: string;
42
+ busy: () => number;
43
+ close: () => unknown;
44
+ exit?: (code: number) => void;
45
+ log?: (m: string) => void;
46
+ watch?: typeof watchSelfUpdateNpm;
47
+ hooks?: import("@dotrino/vault/service").UpdateHooks;
48
+ idleCheckMs?: number;
49
+ }): () => void;
50
+ /** Cada cuánto se mira si ya está libre para reiniciar con la versión instalada. */
51
+ export const IDLE_CHECK_MS: 60000;
52
+ declare namespace _default {
53
+ export { startSelfUpdate };
54
+ export { vaultHooks };
55
+ export { IDLE_CHECK_MS };
56
+ }
57
+ export default _default;
58
+ import { vaultUpdateHooks } from '@dotrino/vault/service';
59
+ import { watchSelfUpdateNpm } from '@dotrino/update/npm';