hopdeck 0.0.0-stage → 1.2.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/lib/history.js ADDED
@@ -0,0 +1,149 @@
1
+ 'use strict';
2
+ // Historial de Claude Code (~/.claude/projects): lectura de sesiones con caché, y agrupación por proyecto.
3
+ const fs = require('fs');
4
+ const os = require('os');
5
+ const path = require('path');
6
+ const { baseName, tidy } = require('./text');
7
+
8
+ const CONFIG_DIR = process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude');
9
+
10
+ function textOf(content) {
11
+ if (typeof content === 'string') return content;
12
+ if (Array.isArray(content)) {
13
+ const b = content.find((x) => x && x.type === 'text' && typeof x.text === 'string');
14
+ return b ? b.text : '';
15
+ }
16
+ return '';
17
+ }
18
+
19
+ // Caché del índice: solo se vuelven a leer las sesiones cuya fecha/tamaño cambió.
20
+ const CACHE_FILE = process.env.HOPDECK_CACHE || path.join(os.homedir(), '.hopdeck-cache.json');
21
+ // Sube la versión cuando cambie cómo se lee una sesión: así las cachés ya guardadas se reconstruyen en vez de repetir resultados antiguos.
22
+ const CACHE_VERSION = 2;
23
+ let CACHE = null, cacheDirty = false, cacheSeen = null;
24
+ /** Empieza un escaneo: las entradas de la caché que no se vean se descartan al terminar. */
25
+ const beginScan = () => { cacheSeen = new Set(); };
26
+ const endScan = () => { cacheSave(); cacheSeen = null; };
27
+ function cacheLoad() {
28
+ if (CACHE) return CACHE;
29
+ try { const j = JSON.parse(fs.readFileSync(CACHE_FILE, 'utf8')); CACHE = j && j.v === CACHE_VERSION && j.files ? j : { v: CACHE_VERSION, files: {} }; } catch { CACHE = { v: CACHE_VERSION, files: {} }; }
30
+ return CACHE;
31
+ }
32
+ function cacheSave() {
33
+ if (!CACHE) return;
34
+ if (cacheSeen) for (const f of Object.keys(CACHE.files)) if (!cacheSeen.has(f)) { delete CACHE.files[f]; cacheDirty = true; }
35
+ if (!cacheDirty) return;
36
+ // la caché contiene títulos y primeros mensajes: permisos solo para el usuario
37
+ try { fs.writeFileSync(CACHE_FILE + '.tmp', JSON.stringify(CACHE), { mode: 0o600 }); fs.renameSync(CACHE_FILE + '.tmp', CACHE_FILE); } catch { /* sin permisos */ }
38
+ cacheDirty = false;
39
+ }
40
+
41
+ /** ¿La línea JSON es de ese tipo? (tolera espacios; Claude escribe JSON compacto) */
42
+ const isType = (line, t) => line.includes(`"type":"${t}"`) || new RegExp(`"type"\\s*:\\s*"${t}"`).test(line);
43
+
44
+ function readSession(file) {
45
+ let st;
46
+ try { st = fs.statSync(file); } catch { return null; }
47
+ const cache = cacheLoad(); if (cacheSeen) cacheSeen.add(file);
48
+ const hit = cache.files[file];
49
+ if (hit && hit.m === st.mtimeMs && hit.z === st.size) return hit.d ? { ...hit.d, file, mtime: st.mtimeMs } : null;
50
+ const d = parseSession(file, st);
51
+ cache.files[file] = { m: st.mtimeMs, z: st.size, d: d ? { id: d.id, title: d.title, first: d.first, cwd: d.cwd } : null };
52
+ cacheDirty = true;
53
+ return d;
54
+ }
55
+
56
+ /**
57
+ * Recorre el principio del archivo por bloques, línea a línea, hasta que `onLine` devuelva true (ya tiene lo que busca)
58
+ * o se llegue a HEAD_MAX bytes. Antes solo se leían los primeros 64 KB: si el primer mensaje llevaba una imagen
59
+ * (una línea de cientos de KB) caía fuera y la conversación se descartaba por no tener título.
60
+ */
61
+ function scanHead(fd, size, onLine) {
62
+ const CHUNK = 128 * 1024, HEAD_MAX = 4 * 1024 * 1024;
63
+ let pos = 0, carry = Buffer.alloc(0);
64
+ while (pos < size && pos < HEAD_MAX) {
65
+ const buf = Buffer.alloc(Math.min(CHUNK, size - pos));
66
+ const n = fs.readSync(fd, buf, 0, buf.length, pos);
67
+ if (!n) break;
68
+ pos += n;
69
+ const data = carry.length ? Buffer.concat([carry, buf.subarray(0, n)]) : buf.subarray(0, n);
70
+ let start = 0, nl;
71
+ while ((nl = data.indexOf(10, start)) >= 0) { // se parte por bytes y se decodifica la línea completa: un carácter de varios bytes nunca queda cortado
72
+ if (onLine(data.toString('utf8', start, nl)) === true) return;
73
+ start = nl + 1;
74
+ }
75
+ carry = data.subarray(start);
76
+ }
77
+ if (pos >= size && carry.length) onLine(carry.toString('utf8')); // última línea sin salto final
78
+ }
79
+
80
+ function parseSession(file, st) {
81
+ let fd;
82
+ try { fd = fs.openSync(file, 'r'); } catch { return null; }
83
+ try {
84
+ const TAIL = 160 * 1024;
85
+ let cwd = '', first = '', custom = '', ai = '';
86
+ scanHead(fd, st.size, (line) => {
87
+ if (!line) return false;
88
+ const wantCwd = !cwd && line.includes('"cwd"');
89
+ const wantUser = !first && isType(line, 'user');
90
+ const wantTitle = line.includes('-title"');
91
+ if (wantCwd || wantUser || wantTitle) {
92
+ let j; try { j = JSON.parse(line); } catch { j = null; }
93
+ if (j) {
94
+ if (wantCwd && j.cwd) cwd = j.cwd;
95
+ if (j.type === 'custom-title' && j.customTitle) custom = j.customTitle;
96
+ if (j.type === 'ai-title' && j.aiTitle) ai = j.aiTitle;
97
+ if (wantUser && j.type === 'user' && !j.isMeta && !j.isSidechain) {
98
+ const t = tidy(textOf(j.message && j.message.content));
99
+ if (t && !t.startsWith('<') && !t.startsWith('[Request interrupted')) first = t.slice(0, 300);
100
+ }
101
+ }
102
+ }
103
+ return !!(cwd && first); // con la carpeta y el primer mensaje ya no hace falta leer más del principio
104
+ });
105
+ // los títulos más recientes están al final del archivo
106
+ const len = Math.min(st.size, TAIL), tb = Buffer.alloc(len);
107
+ fs.readSync(fd, tb, 0, len, st.size - len);
108
+ const tail = tb.toString('utf8').split('\n');
109
+ if (st.size > len) tail.shift(); // primera línea cortada
110
+ let tCustom = '', tAi = '';
111
+ for (let i = tail.length - 1; i >= 0; i--) {
112
+ const line = tail[i];
113
+ if (!line.includes('-title"')) continue;
114
+ let j; try { j = JSON.parse(line); } catch { continue; }
115
+ if (!tCustom && j.type === 'custom-title' && j.customTitle) tCustom = j.customTitle;
116
+ if (!tAi && j.type === 'ai-title' && j.aiTitle) tAi = j.aiTitle;
117
+ if (tCustom) break;
118
+ }
119
+ const title = tidy(tCustom || custom || tAi || ai || first || '');
120
+ if (!title) return null; // sesión vacía
121
+ return { id: path.basename(file, '.jsonl'), file, title, first, cwd, mtime: st.mtimeMs };
122
+ } catch { return null; } finally { try { fs.closeSync(fd); } catch { /* */ } }
123
+ }
124
+
125
+ function decodeDir(name) { // mejor esfuerzo si ninguna sesión trae cwd
126
+ if (/^[A-Za-z]--/.test(name)) return name[0] + ':\\' + name.slice(3).replace(/-/g, '\\');
127
+ return name.replace(/-/g, '/');
128
+ }
129
+
130
+ function projectDirs() {
131
+ const root = path.join(CONFIG_DIR, 'projects');
132
+ try { return fs.readdirSync(root, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => path.join(root, d.name)); } catch { return []; }
133
+ }
134
+
135
+ function buildProject(dir) {
136
+ let files = [];
137
+ try { files = fs.readdirSync(dir).filter((f) => f.endsWith('.jsonl')); } catch { return null; }
138
+ const sessions = files.map((f) => readSession(path.join(dir, f))).filter(Boolean);
139
+ if (!sessions.length) return null;
140
+ sessions.sort((a, b) => b.mtime - a.mtime);
141
+ const seen = {};
142
+ for (const x of sessions) { const k = x.title + '|' + x.first; seen[k] = (seen[k] || 0) + 1; }
143
+ for (const x of sessions) x.dup = seen[x.title + '|' + x.first] > 1;
144
+ const key = path.basename(dir);
145
+ const cwd = (sessions.find((s) => s.cwd) || {}).cwd || decodeDir(key);
146
+ return { key, cwd, name: baseName(cwd), sessions, mtime: sessions[0].mtime };
147
+ }
148
+
149
+ module.exports = { CONFIG_DIR, CACHE_FILE, textOf, isType, cacheLoad, cacheSave, beginScan, endScan, readSession, parseSession, decodeDir, projectDirs, buildProject };
package/lib/i18n.js ADDED
@@ -0,0 +1,78 @@
1
+ 'use strict';
2
+ // Textos de la interfaz (español / inglés). El idioma sale de HOPDECK_LANG o del sistema.
3
+ const LANG = (process.env.HOPDECK_LANG || process.env.LC_ALL || process.env.LANG ||
4
+ Intl.DateTimeFormat().resolvedOptions().locale || 'en').toLowerCase().startsWith('es') ? 'es' : 'en';
5
+ const T = {
6
+ es: {
7
+ projects: 'PROYECTOS', sessions: 'SESIONES', newChat: 'Nueva conversación',
8
+ now: 'ahora', min: 'min', h: 'h', d: 'd', w: 'sem', mo: 'mes',
9
+ sess: (n) => `${n} ${n === 1 ? 'sesión' : 'sesiones'}`,
10
+ k: { move: 'mover', open: 'abrir', resume: 'reanudar', back: 'volver', neu: 'nueva', find: 'buscar', quit: 'salir' },
11
+ searchHint: 'enter aceptar · esc limpiar',
12
+ noMatch: 'Sin resultados', small: 'Agranda la terminal (mín. 70×12)',
13
+ missing: 'La carpeta ya no existe', mkAsk: '⏎ otra vez para crear', mkFail: 'No se pudo crear', current: 'carpeta actual',
14
+ noClaude: 'No se encontró el comando "claude". ¿Está instalado y en el PATH?',
15
+ pressKey: 'Pulsa una tecla para volver…',
16
+ exited: (c) => `La conversación terminó (código ${c})`, closed: (t) => `Conversación cerrada: ${t}`, confirmClose: 'Está trabajando. Pulsa c otra vez para cerrarla', notOpen: 'No hay ninguna conversación abierta que cerrar',
17
+ noImages: 'Esta conversación no tiene imágenes', findImgs: 'Buscando imágenes…', decoding: 'Preparando imagen…',
18
+ imgNoPrev: 'No se puede previsualizar este formato', imgHint: '← → navegar o abrir en el visor esc cerrar', imgFolder: 'Imágenes abiertas en el visor',
19
+ more: (n) => `mostrar ${n} más…`, busyRename: 'Cierra la conversación antes de renombrarla', renameLbl: 'nombre',
20
+ copied: (n) => `Copiado (${n} caracteres)`, archMsg: 'Archivada (H para verlas)', unarchMsg: 'Desarchivada', qsHint: 'saltar a cualquier conversación',
21
+ prevHint: '⏎ reanudar esta conversación', noPrev: 'Sin mensajes para mostrar',
22
+ bar6: 'ocultar lista', bar7: 'mostrar lista', deep: 'contenido', pathPrompt: 'nombre de la nueva carpeta', mkIn: 'se crea en', fbTitle: 'Elegir carpeta', fbHere: 'Abrir chat aquí', fbNew: 'Nueva carpeta aquí…', fbUp: 'Subir un nivel', fbProj: 'proyecto', fbHint: '⏎ entrar · ␣ abrir · / buscar · . ocultas', fbDrives: 'Este equipo', fbRecent: 'reciente', hoverMiss: (n) => `[Image #${n}]: aún no está en el historial`, fbEmpty: 'Sin subcarpetas', badId: 'Identificador de sesión no válido',
23
+ offerQ: '¿Quieres poder abrir Hopdeck escribiendo claude?', offerInfo: 'Se añade una función a tu perfil de shell, con copia de seguridad (para quitarla: hopdeck uninstall). Responder que no no cambia nada: Hopdeck se abre igualmente y puedes usarlo siempre con el comando hopdeck.', offerKeys: '[Enter] Sí, instalar el atajo [n] No, gracias [m] Más tarde', offerNo: 'Atajo no instalado. Si cambias de idea: hopdeck install', offerLater: 'Te lo volveré a preguntar la próxima vez.', offerDone: 'Hecho. Abre una terminal nueva para activarlo.', offerFail: 'No se pudo modificar tu perfil. Puedes intentarlo luego con: hopdeck install', offerCont: 'Pulsa una tecla para continuar…',
24
+ dcNodeOld: (v) => `Node ${v}: se necesita Node 22 o superior`, dcNodeOldHint: 'Con versiones anteriores el ratón no funciona en Windows. Actualiza Node: https://nodejs.org',
25
+ dcHist: (n, p) => `Historial de Claude: ${n} proyectos en ${p}`, dcNoHist: (p) => `No hay historial en ${p}`, dcNoHistHint: 'Usa Claude Code una vez, o define CLAUDE_CONFIG_DIR.',
26
+ dcClaude: (p) => `claude encontrado: ${p}`, dcNoClaude: 'No se encuentra "claude" en el PATH', dcInstallWin: 'Instálalo: irm https://claude.ai/install.ps1 | iex', dcInstallUnix: 'Instálalo: curl -fsSL https://claude.ai/install.sh | bash',
27
+ dcTmux: 'tmux disponible → vista dividida con tmux', dcEmbed: 'Terminal embebido disponible (node-pty + xterm) → vista dividida',
28
+ dcNone: 'Sin tmux ni terminal embebido → vista a pantalla completa', dcNoneWin: 'Ejecuta npm install dentro de la carpeta del paquete.', dcNoneUnix: 'Instala tmux (brew install tmux / sudo apt install tmux).',
29
+ dcShort: 'Atajo instalado: escribir "claude" abre Hopdeck', dcNoShort: 'Atajo no instalado', dcNoShortHint: 'Ejecuta: hopdeck install', dcNoCmdHint: 'Primero crea el comando (npm install -g hopdeck, o npm link si clonaste el repositorio) y luego ejecuta: hopdeck install', dcPrefs: (a, b) => `Preferencias: ${a} · caché: ${b}`, bakMsg: (f) => `Copia de seguridad de tu perfil: ${f}`,
30
+ wtOk: 'Windows Terminal: Ctrl+V está reasignado (se pueden pegar imágenes)', wtBad: 'Windows Terminal: Ctrl+V solo pega texto, no imágenes', wtUnknown: 'Windows Terminal: no pude leer su settings.json para revisar Ctrl+V',
31
+ wtHint: 'Para pegar imágenes con Ctrl+V añade en "actions" de settings.json:\n { "command": { "action": "sendInput", "input": "\\u001bv" }, "keys": "ctrl+v" }\n (el texto se sigue pegando con Ctrl+Shift+V). Alternativa sin tocar nada: Alt+V.',
32
+ hiddenMsg: 'Proyecto oculto. Pulsa H para ver los ocultos.', pinMsg: 'Fijado arriba ★',
33
+ help: ['Teclas', '↑↓ j k mover', '⏎ → l abrir / desplegar', '← h volver / plegar', 'n nueva conversación',
34
+ '/ buscar (Tab: contenido)', 'p fijar proyecto ★', 'x H ocultar / ver ocultos', 'o abrir una carpeta',
35
+ 'c F6 cerrar el chat abierto', 'i F7 ver imágenes del chat', 'R a renombrar / archivar', 'Ctrl+P F5 saltar a cualquier chat', '[ ] ancho de la lista', 'r recargar',
36
+ 'F1 F2 foco lista / chat', 'F3 copiar texto (ratón)', 'F4 ocultar la lista', 'q salir'],
37
+ bar4: 'copiar texto', bar5: 'ratón', up: (n, pct) => `↑ ${n} líneas${pct >= 0 ? ` (${pct}%)` : ''} · PgDn/End`, loading: 'Cargando proyectos', opening: 'Abriendo conversación', close: 'cerrar', idle1: 'Elige una conversación', idle2: 'Usa ↑↓ y ⏎ en el panel izquierdo',
38
+ idle3: 'F1 proyectos · F2 chat', bar1: 'proyectos', bar2: 'chat', bar3: 'minimizar',
39
+ inside: 'Ya estás dentro de Hopdeck (F1 para ir a la lista de proyectos).',
40
+ },
41
+ en: {
42
+ projects: 'PROJECTS', sessions: 'SESSIONS', newChat: 'New conversation',
43
+ now: 'now', min: 'min', h: 'h', d: 'd', w: 'w', mo: 'mo',
44
+ sess: (n) => `${n} ${n === 1 ? 'session' : 'sessions'}`,
45
+ k: { move: 'move', open: 'open', resume: 'resume', back: 'back', neu: 'new', find: 'search', quit: 'quit' },
46
+ searchHint: 'enter accept · esc clear',
47
+ noMatch: 'No results', small: 'Make the terminal bigger (min 70×12)',
48
+ missing: 'That folder no longer exists', mkAsk: '⏎ again to create', mkFail: 'Could not create', current: 'current folder',
49
+ noClaude: 'Could not find the "claude" command. Is it installed and on PATH?',
50
+ pressKey: 'Press any key to go back…',
51
+ exited: (c) => `The conversation ended (code ${c})`, closed: (t) => `Conversation closed: ${t}`, confirmClose: 'It is working. Press c again to close it', notOpen: 'There is no open conversation to close',
52
+ noImages: 'This conversation has no images', findImgs: 'Looking for images…', decoding: 'Preparing image…',
53
+ imgNoPrev: 'This format cannot be previewed', imgHint: '← → browse o open in viewer esc close', imgFolder: 'Images opened in the viewer',
54
+ more: (n) => `show ${n} more…`, busyRename: 'Close the conversation before renaming it', renameLbl: 'name',
55
+ copied: (n) => `Copied (${n} chars)`, archMsg: 'Archived (H to show)', unarchMsg: 'Unarchived', qsHint: 'jump to any conversation',
56
+ prevHint: '⏎ resume this conversation', noPrev: 'No messages to show',
57
+ bar6: 'hide list', bar7: 'show list', deep: 'content', pathPrompt: 'new folder name', mkIn: 'created in', fbTitle: 'Pick a folder', fbHere: 'Open chat here', fbNew: 'New folder here…', fbUp: 'Go up', fbProj: 'project', fbHint: '⏎ enter · ␣ open · / find · . hidden', fbDrives: 'This PC', fbRecent: 'recent', hoverMiss: (n) => `[Image #${n}]: not in the history yet`, fbEmpty: 'No subfolders', badId: 'Invalid session id',
58
+ offerQ: 'Do you want to open Hopdeck by typing claude?', offerInfo: 'A function is added to your shell profile, with a backup (to remove it: hopdeck uninstall). Answering no changes nothing: Hopdeck opens anyway and you can always use the hopdeck command.', offerKeys: '[Enter] Yes, install the shortcut [n] No, thanks [m] Later', offerNo: 'Shortcut not installed. If you change your mind: hopdeck install', offerLater: 'I will ask you again next time.', offerDone: 'Done. Open a new terminal to activate it.', offerFail: 'Could not modify your profile. You can try later with: hopdeck install', offerCont: 'Press any key to continue…',
59
+ dcNodeOld: (v) => `Node ${v}: Node 22 or newer is required`, dcNodeOldHint: 'With older versions the mouse does not work on Windows. Update Node: https://nodejs.org',
60
+ dcHist: (n, p) => `Claude history: ${n} projects in ${p}`, dcNoHist: (p) => `No history found in ${p}`, dcNoHistHint: 'Use Claude Code once, or set CLAUDE_CONFIG_DIR.',
61
+ dcClaude: (p) => `claude found: ${p}`, dcNoClaude: '"claude" not found in PATH', dcInstallWin: 'Install it: irm https://claude.ai/install.ps1 | iex', dcInstallUnix: 'Install it: curl -fsSL https://claude.ai/install.sh | bash',
62
+ dcTmux: 'tmux available → split view with tmux', dcEmbed: 'Embedded terminal available (node-pty + xterm) → split view',
63
+ dcNone: 'No tmux or embedded terminal → full-screen view', dcNoneWin: 'Run npm install inside the package folder.', dcNoneUnix: 'Install tmux (brew install tmux / sudo apt install tmux).',
64
+ dcShort: 'Shortcut installed: typing "claude" opens Hopdeck', dcNoShort: 'Shortcut not installed', dcNoShortHint: 'Run: hopdeck install', dcNoCmdHint: 'First create the command (npm install -g hopdeck, or npm link if you cloned the repo), then run: hopdeck install', dcPrefs: (a, b) => `Preferences: ${a} · cache: ${b}`, bakMsg: (f) => `Backup of your profile: ${f}`,
65
+ wtOk: 'Windows Terminal: Ctrl+V is remapped (images can be pasted)', wtBad: 'Windows Terminal: Ctrl+V only pastes text, not images', wtUnknown: 'Windows Terminal: could not read its settings.json to check Ctrl+V',
66
+ wtHint: 'To paste images with Ctrl+V add to "actions" in settings.json:\n { "command": { "action": "sendInput", "input": "\\u001bv" }, "keys": "ctrl+v" }\n (text can still be pasted with Ctrl+Shift+V). No-config alternative: Alt+V.',
67
+ hiddenMsg: 'Project hidden. Press H to show hidden ones.', pinMsg: 'Pinned on top ★',
68
+ help: ['Keys', '↑↓ j k move', '⏎ → l open / expand', '← h back / collapse', 'n new conversation',
69
+ '/ search (Tab: content)', 'p pin project ★', 'x H hide / show hidden', 'o open a folder',
70
+ 'c F6 close the open chat', 'i F7 view the chat images', 'R a rename / archive', 'Ctrl+P F5 jump to any chat', '[ ] list width', 'r reload',
71
+ 'F1 F2 focus list / chat', 'F3 copy text (mouse)', 'F4 hide the list', 'q quit'],
72
+ bar4: 'copy text', bar5: 'mouse', up: (n, pct) => `↑ ${n} lines${pct >= 0 ? ` (${pct}%)` : ''} · PgDn/End`, loading: 'Loading projects', opening: 'Opening conversation', close: 'close', idle1: 'Pick a conversation', idle2: 'Use ↑↓ and ⏎ in the left pane',
73
+ idle3: 'F1 projects · F2 chat', bar1: 'projects', bar2: 'chat', bar3: 'minimize',
74
+ inside: 'You are already inside Hopdeck (F1 jumps to the project list).',
75
+ },
76
+ }[LANG];
77
+
78
+ module.exports = { LANG, T };
package/lib/images.js ADDED
@@ -0,0 +1,168 @@
1
+ 'use strict';
2
+ // Imágenes del historial: extracción de bloques base64, decodificación PNG/JPEG y dibujo con medios bloques (▀).
3
+ const fs = require('fs');
4
+ const readline = require('readline');
5
+ const { TRUE, R } = require('./style');
6
+
7
+ function collectImages(content, out, depth = 0) {
8
+ if (!Array.isArray(content) || depth > 3) return;
9
+ for (const b of content) {
10
+ if (!b) continue;
11
+ if (b.type === 'image' && b.source && b.source.type === 'base64' && typeof b.source.data === 'string' && b.source.data.length < 24e6) {
12
+ out.push({ media: b.source.media_type || 'image/png', data: b.source.data });
13
+ } else if (Array.isArray(b.content)) collectImages(b.content, out, depth + 1); // imágenes dentro de resultados de herramientas
14
+ }
15
+ }
16
+
17
+
18
+ async function extractImages(file, max = 200) {
19
+ const out = []; let bytes = 0;
20
+ const rl = readline.createInterface({ input: fs.createReadStream(file, { encoding: 'utf8' }), crlfDelay: Infinity });
21
+ try {
22
+ for await (const line of rl) {
23
+ if (!/"type"\s*:\s*"image"/.test(line)) continue;
24
+ let j; try { j = JSON.parse(line); } catch { continue; }
25
+ if (j.type !== 'user' && j.type !== 'assistant') continue; // Claude Code guarda cada imagen otra vez en líneas internas (api-request-blob): se ignoran
26
+ const c = j.message && j.message.content, local = [];
27
+ collectImages(c, local);
28
+ // "[Image #N]" del texto del mensaje ↔ imágenes del mismo mensaje (en orden)
29
+ const nums = [];
30
+ if (j.type === 'user' && Array.isArray(c)) for (const b of c) if (b && b.type === 'text' && typeof b.text === 'string') for (const m of b.text.matchAll(/\[Image #(\d+)\]/g)) nums.push(+m[1]);
31
+ local.forEach((im, i) => { if (nums.length === local.length) im.n = nums[i]; out.push(im); });
32
+ for (const im of local) bytes += im.data.length;
33
+ if (out.length >= max || bytes > 400e6) break;
34
+ }
35
+ } finally { rl.close(); }
36
+ return out;
37
+ }
38
+
39
+
40
+ /**
41
+ * Busca en el historial la imagen "[Image #n]" recorriendo todo el archivo (sin el límite de `extractImages`).
42
+ * Solo conserva la que coincide, así que no gasta memoria en el resto. Devuelve null si no existe.
43
+ */
44
+ async function findImageByNumber(file, n) {
45
+ const rl = readline.createInterface({ input: fs.createReadStream(file, { encoding: 'utf8' }), crlfDelay: Infinity });
46
+ let seen = 0, numbered = false, byNum = null, byIdx = null;
47
+ try {
48
+ for await (const line of rl) {
49
+ if (!/"type"\s*:\s*"image"/.test(line)) continue;
50
+ let j; try { j = JSON.parse(line); } catch { continue; }
51
+ if (j.type !== 'user' && j.type !== 'assistant') continue; // Claude Code guarda cada imagen otra vez en líneas internas (api-request-blob): se ignoran
52
+ const c = j.message && j.message.content, local = [];
53
+ collectImages(c, local);
54
+ const nums = [];
55
+ if (j.type === 'user' && Array.isArray(c)) for (const b of c) if (b && b.type === 'text' && typeof b.text === 'string') for (const m of b.text.matchAll(/\[Image #(\d+)\]/g)) nums.push(+m[1]);
56
+ local.forEach((im, i) => {
57
+ seen++;
58
+ if (nums.length === local.length) { numbered = true; if (nums[i] === n) byNum = im; }
59
+ if (seen === n) byIdx = im;
60
+ });
61
+ if (byNum) break;
62
+ }
63
+ } finally { rl.close(); }
64
+ return byNum || (numbered ? null : byIdx);
65
+ }
66
+
67
+ /** Decodificador PNG mínimo (sin dependencias): 8/16 bits, paleta, gris, RGB(A); sin entrelazado. */
68
+ function decodePNG(buf) {
69
+ if (buf.length < 33 || buf.readUInt32BE(0) !== 0x89504e47) return null;
70
+ let pos = 8, w = 0, h = 0, depth = 0, ctype = 0, inter = 0, plte = null, trns = null; const idat = [];
71
+ while (pos + 8 <= buf.length) {
72
+ const len = buf.readUInt32BE(pos), type = buf.toString('latin1', pos + 4, pos + 8), data = buf.subarray(pos + 8, pos + 8 + len);
73
+ pos += 12 + len;
74
+ if (type === 'IHDR') { w = data.readUInt32BE(0); h = data.readUInt32BE(4); depth = data[8]; ctype = data[9]; inter = data[12]; }
75
+ else if (type === 'PLTE') plte = data; else if (type === 'tRNS') trns = data;
76
+ else if (type === 'IDAT') idat.push(data); else if (type === 'IEND') break;
77
+ }
78
+ const ch = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 }[ctype];
79
+ if (!w || !h || inter !== 0 || !ch || w * h > 40e6 || (ctype === 3 && !plte)) return null;
80
+ const raw = require('zlib').inflateSync(Buffer.concat(idat));
81
+ const bpp = Math.max(1, (ch * depth) >> 3), stride = Math.ceil((w * ch * depth) / 8);
82
+ if (raw.length < (stride + 1) * h) return null;
83
+ const px = Buffer.alloc(stride * h);
84
+ for (let y = 0; y < h; y++) {
85
+ const f = raw[y * (stride + 1)], src = y * (stride + 1) + 1, dst = y * stride, prev = dst - stride;
86
+ for (let x = 0; x < stride; x++) {
87
+ const a = x >= bpp ? px[dst + x - bpp] : 0, b = y > 0 ? px[prev + x] : 0, c = x >= bpp && y > 0 ? px[prev + x - bpp] : 0;
88
+ let v = raw[src + x];
89
+ if (f === 1) v += a; else if (f === 2) v += b; else if (f === 3) v += (a + b) >> 1;
90
+ else if (f === 4) { const pp = a + b - c, pa = Math.abs(pp - a), pb = Math.abs(pp - b), pc = Math.abs(pp - c); v += pa <= pb && pa <= pc ? a : pb <= pc ? b : c; }
91
+ px[dst + x] = v & 255;
92
+ }
93
+ }
94
+ const rgba = new Uint8Array(w * h * 4), max = (1 << Math.min(depth, 8)) - 1;
95
+ for (let y = 0; y < h; y++) {
96
+ const row = y * stride;
97
+ const get = (i) => {
98
+ if (depth === 8) return px[row + i];
99
+ if (depth === 16) return px[row + i * 2];
100
+ const per = 8 / depth; return (px[row + ((i / per) | 0)] >> (8 - depth - (i % per) * depth)) & max;
101
+ };
102
+ for (let x = 0; x < w; x++) {
103
+ let r, g, b, a = 255;
104
+ if (ctype === 2) { r = get(x * 3); g = get(x * 3 + 1); b = get(x * 3 + 2); }
105
+ else if (ctype === 6) { r = get(x * 4); g = get(x * 4 + 1); b = get(x * 4 + 2); a = get(x * 4 + 3); }
106
+ else if (ctype === 3) { const k = get(x); r = plte[k * 3]; g = plte[k * 3 + 1]; b = plte[k * 3 + 2]; if (trns && k < trns.length) a = trns[k]; }
107
+ else { const v = depth < 8 ? Math.round((get(x * (ctype === 4 ? 2 : 1)) * 255) / max) : get(x * (ctype === 4 ? 2 : 1)); r = g = b = v; if (ctype === 4) a = get(x * 2 + 1); }
108
+ const o = (y * w + x) * 4; rgba[o] = r; rgba[o + 1] = g; rgba[o + 2] = b; rgba[o + 3] = a;
109
+ }
110
+ }
111
+ return { w, h, rgba };
112
+ }
113
+
114
+ /** PNG (propio) o JPEG (si está jpeg-js). Devuelve { w, h, rgba } o null. */
115
+ function decodeImage(img) {
116
+ const buf = Buffer.from(img.data, 'base64');
117
+ try {
118
+ if (buf.length > 8 && buf.readUInt32BE(0) === 0x89504e47) return decodePNG(buf);
119
+ if (buf[0] === 0xff && buf[1] === 0xd8) {
120
+ let jpeg; try { jpeg = require('jpeg-js'); } catch { return null; }
121
+ const d = jpeg.decode(buf, { useTArray: true, formatAsRGBA: true, maxMemoryUsageInMB: 512 });
122
+ return { w: d.width, h: d.height, rgba: d.data };
123
+ }
124
+ } catch { /* formato corrupto */ }
125
+ return null;
126
+ }
127
+
128
+ /** Reduce con filtro de caja y compone sobre un fondo oscuro. Devuelve RGB (3 bytes por píxel). */
129
+ function scaleBox(src, w, h, tw, th) {
130
+ const out = new Uint8Array(tw * th * 3);
131
+ for (let ty = 0; ty < th; ty++) {
132
+ const y0 = Math.floor((ty * h) / th), y1 = Math.max(y0 + 1, Math.floor(((ty + 1) * h) / th));
133
+ for (let tx = 0; tx < tw; tx++) {
134
+ const x0 = Math.floor((tx * w) / tw), x1 = Math.max(x0 + 1, Math.floor(((tx + 1) * w) / tw));
135
+ let r = 0, g = 0, b = 0, n = 0;
136
+ for (let y = y0; y < y1; y++) {
137
+ let i = (y * w + x0) * 4;
138
+ for (let x = x0; x < x1; x++, i += 4) { const a = src[i + 3] / 255; r += src[i] * a + 28 * (1 - a); g += src[i + 1] * a + 28 * (1 - a); b += src[i + 2] * a + 30 * (1 - a); n++; }
139
+ }
140
+ const o = (ty * tw + tx) * 3; out[o] = r / n; out[o + 1] = g / n; out[o + 2] = b / n;
141
+ }
142
+ }
143
+ return out;
144
+ }
145
+
146
+ function fitSize(w, h, maxW, maxH2) {
147
+ const k = Math.min(maxW / w, maxH2 / h, 2);
148
+ return { tw: Math.max(1, Math.floor(w * k)), th: Math.max(2, Math.floor(h * k) & ~1) };
149
+ }
150
+
151
+ const c256 = (rgb, o) => { const q = (v) => Math.round((v / 255) * 5); return 16 + 36 * q(rgb[o]) + 6 * q(rgb[o + 1]) + q(rgb[o + 2]); };
152
+ /** Cada fila de texto = 2 filas de píxeles: ▀ con color de letra = píxel de arriba y de fondo = píxel de abajo. */
153
+ function halfBlocks(rgb, tw, th2) {
154
+ const rows = [];
155
+ for (let y = 0; y < th2; y += 2) {
156
+ let line = '';
157
+ for (let x = 0; x < tw; x++) {
158
+ const t = (y * tw + x) * 3, hasB = y + 1 < th2, b = ((y + 1) * tw + x) * 3;
159
+ line += (TRUE
160
+ ? `\x1b[38;2;${rgb[t]};${rgb[t + 1]};${rgb[t + 2]}` + (hasB ? `;48;2;${rgb[b]};${rgb[b + 1]};${rgb[b + 2]}` : '') + 'm'
161
+ : `\x1b[38;5;${c256(rgb, t)}` + (hasB ? `;48;5;${c256(rgb, b)}` : '') + 'm') + '▀';
162
+ }
163
+ rows.push(line + R);
164
+ }
165
+ return rows;
166
+ }
167
+
168
+ module.exports = { collectImages, extractImages, findImageByNumber, decodePNG, decodeImage, scaleBox, fitSize, halfBlocks };
package/lib/keys.js ADDED
@@ -0,0 +1,47 @@
1
+ 'use strict';
2
+ // Teclado: separar secuencias de teclas, nombres de teclas y edición de una línea con cursor.
3
+ const clamp = (n, a, b) => Math.max(a, Math.min(b, n));
4
+
5
+ function parseKeys(s) {
6
+ const ks = []; let i = 0;
7
+ while (i < s.length) {
8
+ if (s[i] === '\x1b') {
9
+ if (s[i + 1] === '[' || s[i + 1] === 'O') {
10
+ let j = i + 2; while (j < s.length && !/[A-Za-z~]/.test(s[j])) j++;
11
+ ks.push(s.slice(i, j + 1)); i = j + 1;
12
+ } else { ks.push('\x1b'); i++; }
13
+ } else { const ch = String.fromCodePoint(s.codePointAt(i)); ks.push(ch); i += ch.length; }
14
+ }
15
+ return ks;
16
+ }
17
+
18
+ const KEYMAP = {
19
+ '\x1b[A': 'up', '\x1bOA': 'up', '\x1b[B': 'down', '\x1bOB': 'down', '\x1b[C': 'right', '\x1bOC': 'right',
20
+ '\x1b[D': 'left', '\x1bOD': 'left', '\x1b[5~': 'pgup', '\x1b[6~': 'pgdn', '\x1b[H': 'home', '\x1b[1~': 'home',
21
+ '\x1b[17~': 'f6', '\x1b[18~': 'f7', '\x10': 'ctrlp', '\x1b[15~': 'f5', '\x1b[I': 'focus', '\x1bOP': 'f1', '\x1b[11~': 'f1', '\x1bOQ': 'f2', '\x1b[12~': 'f2', '\x1b[F': 'end', '\x1b[4~': 'end', '\r': 'enter', '\n': 'enter', '\x1b': 'esc', '\x7f': 'bs', '\b': 'bs', '\x03': 'ctrlc',
22
+ };
23
+
24
+
25
+ const printable = (k) => k.length > 0 && k.charCodeAt(0) >= 32 && k.charCodeAt(0) !== 127; // ignora Supr, F-teclas y otras secuencias
26
+
27
+ /** Edición de una línea con cursor. Devuelve { s, pos } o null si la tecla no es de edición. */
28
+ function editBuf(str, pos, k, raw) {
29
+ const a = [...str]; pos = clamp(Number.isFinite(pos) ? pos : a.length, 0, a.length);
30
+ if (k === 'left') pos = Math.max(0, pos - 1);
31
+ else if (k === 'right') pos = Math.min(a.length, pos + 1);
32
+ else if (k === 'home' || raw === '\x1bOH' || raw === '\x01') pos = 0;
33
+ else if (k === 'end' || raw === '\x1bOF' || raw === '\x05') pos = a.length;
34
+ else if (k === 'bs') { if (pos > 0) { a.splice(pos - 1, 1); pos--; } }
35
+ else if (raw === '\x1b[3~') a.splice(pos, 1); // Supr
36
+ else if (raw === '\x15') { a.splice(0, pos); pos = 0; } // Ctrl+U: borrar hasta el inicio
37
+ else if (!KEYMAP[raw] && printable(k)) { a.splice(pos, 0, k); pos++; }
38
+ else return null;
39
+ return { s: a.join(''), pos };
40
+ }
41
+
42
+ // Con Node 18 en Windows, F1–F5 llegan con la forma de la consola de Linux (ESC [ [ A … E) y no como ESC O P… / ESC [ 15 ~.
43
+ const CONSOLE_FKEYS = { '\x1b[[A': '\x1bOP', '\x1b[[B': '\x1bOQ', '\x1b[[C': '\x1bOR', '\x1b[[D': '\x1bOS', '\x1b[[E': '\x1b[15~' };
44
+ /** Convierte las teclas de función de la consola de Linux a la forma estándar de xterm que usa el resto del programa. */
45
+ const normalizeKeys = (s) => s.replace(/\x1b\[\[[A-E]/g, (m) => CONSOLE_FKEYS[m]);
46
+
47
+ module.exports = { parseKeys, KEYMAP, printable, editBuf, normalizeKeys };
package/lib/style.js ADDED
@@ -0,0 +1,62 @@
1
+ 'use strict';
2
+ // Colores ANSI, tema claro/oscuro y utilidades de ancho visual (emoji / CJK = 2 columnas).
3
+ const TRUE = /truecolor|24bit/i.test(process.env.COLORTERM || '') || !!process.env.WT_SESSION;
4
+ const NOCOL = !!process.env.NO_COLOR; // https://no-color.org
5
+ // tema: HOPDECK_THEME=light|dark; si no, se intenta deducir de COLORFGBG (fondo claro termina en ;7 o ;15)
6
+ const LIGHT = process.env.HOPDECK_THEME ? process.env.HOPDECK_THEME === 'light' : /;(7|15)$/.test(process.env.COLORFGBG || '');
7
+ const fg = (r, g, b, n) => (NOCOL ? '' : TRUE ? `\x1b[38;2;${r};${g};${b}m` : `\x1b[38;5;${n}m`);
8
+ const bg = (r, g, b, n) => (NOCOL ? '' : TRUE ? `\x1b[48;2;${r};${g};${b}m` : `\x1b[48;5;${n}m`);
9
+ const R = '\x1b[0m';
10
+ const C = LIGHT ? {
11
+ brand: fg(190, 85, 50, 166), accent: fg(79, 70, 229, 62), text: fg(38, 38, 44, 235), dim: fg(105, 105, 114, 242),
12
+ faint: fg(190, 190, 196, 250), ok: fg(28, 128, 68, 29), warn: fg(168, 104, 16, 130),
13
+ selOn: bg(232, 234, 252, 189), selOff: bg(234, 234, 238, 255), bold: NOCOL ? '' : '\x1b[1m', ital: NOCOL ? '' : '\x1b[3m',
14
+ } : {
15
+ brand: fg(217, 119, 87, 173), accent: fg(129, 140, 248, 105), text: fg(232, 230, 227, 253), dim: fg(128, 128, 134, 244),
16
+ faint: fg(78, 78, 84, 239), ok: fg(126, 196, 143, 114), warn: fg(224, 175, 104, 179),
17
+ selOn: bg(38, 40, 64, 236), selOff: bg(34, 34, 36, 235), bold: NOCOL ? '' : '\x1b[1m', ital: NOCOL ? '' : '\x1b[3m',
18
+ };
19
+
20
+ // ancho visual (emoji / CJK = 2 columnas)
21
+ function cw(c) {
22
+ if (c < 0x300) return 1;
23
+ if ((c >= 0x300 && c <= 0x36f) || (c >= 0x200b && c <= 0x200f) || c === 0xfe0f) return 0;
24
+ if ((c >= 0x1100 && c <= 0x115f) || (c >= 0x2e80 && c <= 0xa4cf) || (c >= 0xac00 && c <= 0xd7a3) ||
25
+ (c >= 0xf900 && c <= 0xfaff) || (c >= 0xfe30 && c <= 0xfe6f) || (c >= 0xff00 && c <= 0xff60) ||
26
+ (c >= 0xffe0 && c <= 0xffe6) || (c >= 0x1f300 && c <= 0x1faff)) return 2;
27
+ return 1;
28
+ }
29
+ const strW = (s) => { let w = 0; for (const ch of s) w += cw(ch.codePointAt(0)); return w; };
30
+
31
+ /**
32
+ * Quita de un texto externo (títulos, mensajes, rutas del historial) todo lo que el terminal interpretaría:
33
+ * caracteres de control y secuencias de escape (cambiar el título, escribir en el portapapeles con OSC 52…)
34
+ * y los controles de dirección Unicode que sirven para disfrazar texto.
35
+ */
36
+ // eslint-disable-next-line no-control-regex
37
+ const clean = (t) => String(t == null ? '' : t).replace(/[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g, '');
38
+
39
+ /** Ajusta segmentos [[texto, estilo]] a un ancho exacto (si no cabe, corta y termina en …; si sobra, rellena). */
40
+ function fit(segs, width, base = '') {
41
+ if (width <= 0) return '';
42
+ segs = segs.map(([t, st]) => [clean(t), st]); // el texto externo nunca llega al terminal con caracteres de control
43
+ let total = 0;
44
+ for (const [t] of segs) total += strW(t);
45
+ const limit = total > width ? width - 1 : width; // se reserva una celda para la …
46
+ let out = '', used = 0, cut = false, lastSt = '';
47
+ for (const [text, st = ''] of segs) {
48
+ let piece = '';
49
+ for (const ch of text) {
50
+ const w = cw(ch.codePointAt(0));
51
+ if (used + w > limit) { cut = true; break; }
52
+ piece += ch; used += w;
53
+ }
54
+ out += base + st + piece + R; lastSt = st;
55
+ if (cut) break;
56
+ }
57
+ if (total > width) { out += base + lastSt + '…' + R; used += 1; }
58
+ if (used < width) out += base + ' '.repeat(width - used) + R;
59
+ return out;
60
+ }
61
+
62
+ module.exports = { TRUE, NOCOL, LIGHT, fg, bg, R, C, cw, strW, fit, clean };
package/lib/text.js ADDED
@@ -0,0 +1,43 @@
1
+ 'use strict';
2
+ // Texto: nombres de carpeta, rutas cortas, búsqueda difusa y ajuste de línea.
3
+ const os = require('os');
4
+ const { strW } = require('./style');
5
+
6
+ const baseName = (p) => p.split(/[\\/]/).filter(Boolean).pop() || p;
7
+ const tidy = (s) => s.replace(/\s+/g, ' ').trim();
8
+ const home = os.homedir();
9
+ const shortPath = (p) => (p.startsWith(home) ? '~' + p.slice(home.length) : p);
10
+
11
+ /** Coincidencia difusa: cada palabra de la consulta debe aparecer como subsecuencia. -1 si no coincide. */
12
+ function fuzzy(q, text) {
13
+ const t = text.toLowerCase(); let total = 0;
14
+ for (const term of q.toLowerCase().split(/\s+/).filter(Boolean)) {
15
+ let pos = -1, run = 0, score = 0;
16
+ const sub = t.indexOf(term);
17
+ if (sub >= 0) { total += 10 + term.length * 3 - Math.min(sub, 30) / 3; continue; }
18
+ for (const ch of term) {
19
+ const i = t.indexOf(ch, pos + 1);
20
+ if (i < 0) return -1;
21
+ run = i === pos + 1 ? run + 1 : 0; score += 1 + run; pos = i;
22
+ }
23
+ total += score;
24
+ }
25
+ return total;
26
+ }
27
+
28
+ function wrapText(text, width) {
29
+ const out = []; let line = '';
30
+ for (const word of text.split(/\s+/).filter(Boolean)) {
31
+ let w = word;
32
+ while (strW(w) > width) { // palabra más larga que la línea
33
+ if (line) { out.push(line); line = ''; }
34
+ let piece = ''; for (const ch of w) { if (strW(piece + ch) > width) break; piece += ch; }
35
+ out.push(piece); w = w.slice(piece.length);
36
+ }
37
+ if (!line) line = w; else if (strW(line + ' ' + w) <= width) line += ' ' + w; else { out.push(line); line = w; }
38
+ }
39
+ if (line) out.push(line);
40
+ return out;
41
+ }
42
+
43
+ module.exports = { baseName, tidy, home, shortPath, fuzzy, wrapText };
@@ -0,0 +1,41 @@
1
+ 'use strict';
2
+ // Windows Terminal: ¿Ctrl+V solo pega texto? (impide pegar imágenes en Claude). Usado por `hopdeck doctor`.
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const cp = require('child_process');
6
+
7
+ /** Quita comentarios y comas finales de un JSON con comentarios (settings.json de Windows Terminal). */
8
+ function stripJsonc(t) {
9
+ let o = '', i = 0, str = false;
10
+ while (i < t.length) {
11
+ const c = t[i], d = t[i + 1];
12
+ if (str) { o += c; if (c === '\\') { o += d || ''; i += 2; continue; } if (c === '"') str = false; i++; continue; }
13
+ if (c === '"') { str = true; o += c; i++; }
14
+ else if (c === '/' && d === '/') { while (i < t.length && t[i] !== '\n') i++; }
15
+ else if (c === '/' && d === '*') { i += 2; while (i < t.length && !(t[i] === '*' && t[i + 1] === '/')) i++; i += 2; }
16
+ else { o += c; i++; }
17
+ }
18
+ return o.replace(/,(\s*[}\]])/g, '$1');
19
+ }
20
+ /** ¿Qué hace Ctrl+V en Windows Terminal? 'paste' (pega texto: no deja pasar imágenes), 'custom' (reasignado) o null si no se puede leer. */
21
+ function wtCtrlV(text) {
22
+ let j; try { j = JSON.parse(stripJsonc(text)); } catch { return null; }
23
+ const list = [...(Array.isArray(j.actions) ? j.actions : []), ...(Array.isArray(j.keybindings) ? j.keybindings : [])];
24
+ const mine = list.filter((a) => a && [].concat(a.keys || []).some((k) => String(k).toLowerCase() === 'ctrl+v'));
25
+ if (!mine.length) return 'paste'; // sin reasignar: Windows Terminal usa su atajo por defecto (pegar)
26
+ const defs = new Map(list.filter((x) => x && x.id && x.command !== undefined).map((x) => [x.id, x.command]));
27
+ const last = mine[mine.length - 1];
28
+ const c = last.command !== undefined ? last.command : last.id ? (/PasteFromClipboard$/i.test(last.id) ? 'paste' : defs.get(last.id)) : undefined; // formato nuevo: la tecla apunta a una acción por "id"
29
+ return c === 'paste' || (c && typeof c === 'object' && c.action === 'paste') ? 'paste' : 'custom';
30
+ }
31
+ function wtSettingsFile() {
32
+ let base = process.env.LOCALAPPDATA;
33
+ if (!base && process.env.WSL_DISTRO_NAME) { try { base = cp.execFileSync('wslpath', ['-u', cp.execFileSync('cmd.exe', ['/c', 'echo %LOCALAPPDATA%'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim()], { encoding: 'utf8' }).trim(); } catch { /* */ } }
34
+ if (!base) return null;
35
+ const cands = [];
36
+ try { for (const d of fs.readdirSync(path.join(base, 'Packages'))) if (/^Microsoft\.WindowsTerminal/.test(d)) cands.push(path.join(base, 'Packages', d, 'LocalState', 'settings.json')); } catch { /* */ }
37
+ cands.push(path.join(base, 'Microsoft', 'Windows Terminal', 'settings.json'));
38
+ return cands.find((f) => fs.existsSync(f)) || null;
39
+ }
40
+
41
+ module.exports = { stripJsonc, wtCtrlV, wtSettingsFile };