holohq 0.0.0-stage → 0.2.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.
Files changed (116) hide show
  1. package/LICENSE +21 -0
  2. package/README.fr.md +145 -0
  3. package/README.md +144 -2
  4. package/bin/holohq.js +12 -0
  5. package/dist/server/server/actions/clone.js +36 -0
  6. package/dist/server/server/actions/newProject.js +40 -0
  7. package/dist/server/server/actions/publish.js +22 -0
  8. package/dist/server/server/app.js +46 -0
  9. package/dist/server/server/autostart.js +127 -0
  10. package/dist/server/server/autostartRun.js +96 -0
  11. package/dist/server/server/browser.js +24 -0
  12. package/dist/server/server/cache.js +24 -0
  13. package/dist/server/server/claude/floor.js +408 -0
  14. package/dist/server/server/claude/history.js +268 -0
  15. package/dist/server/server/claude/prompt.js +8 -0
  16. package/dist/server/server/cli/autostart.js +21 -0
  17. package/dist/server/server/cli/config.js +45 -0
  18. package/dist/server/server/cli/convention.js +51 -0
  19. package/dist/server/server/cli/io.js +1 -0
  20. package/dist/server/server/cli/main.js +129 -0
  21. package/dist/server/server/config.js +311 -0
  22. package/dist/server/server/demo/config.js +19 -0
  23. package/dist/server/server/demo/data.js +317 -0
  24. package/dist/server/server/demo/deps.js +36 -0
  25. package/dist/server/server/demo/floor.js +45 -0
  26. package/dist/server/server/demo/run.js +315 -0
  27. package/dist/server/server/demo/scan.js +21 -0
  28. package/dist/server/server/domain/home.js +85 -0
  29. package/dist/server/server/domain/journal.js +33 -0
  30. package/dist/server/server/domain/sprint.js +9 -0
  31. package/dist/server/server/exec.js +12 -0
  32. package/dist/server/server/floor/attribute.js +74 -0
  33. package/dist/server/server/floor/evidence.js +39 -0
  34. package/dist/server/server/git/status.js +45 -0
  35. package/dist/server/server/github/gh.js +27 -0
  36. package/dist/server/server/github/labels.js +65 -0
  37. package/dist/server/server/github/project.js +58 -0
  38. package/dist/server/server/github/repos.js +17 -0
  39. package/dist/server/server/github/write.js +91 -0
  40. package/dist/server/server/guard.js +18 -0
  41. package/dist/server/server/index.js +9 -0
  42. package/dist/server/server/launch.js +168 -0
  43. package/dist/server/server/paths.js +26 -0
  44. package/dist/server/server/preload.js +30 -0
  45. package/dist/server/server/projects/remote.js +13 -0
  46. package/dist/server/server/projects/scan.js +79 -0
  47. package/dist/server/server/routes/actions.js +89 -0
  48. package/dist/server/server/routes/autostart.js +21 -0
  49. package/dist/server/server/routes/conversations.js +21 -0
  50. package/dist/server/server/routes/detail.js +24 -0
  51. package/dist/server/server/routes/floor.js +77 -0
  52. package/dist/server/server/routes/home.js +64 -0
  53. package/dist/server/server/routes/launch.js +79 -0
  54. package/dist/server/server/routes/projects.js +75 -0
  55. package/dist/server/server/routes/remotes.js +30 -0
  56. package/dist/server/server/routes/setup.js +114 -0
  57. package/dist/server/server/routes/write.js +129 -0
  58. package/dist/server/server/setup/tools.js +37 -0
  59. package/dist/server/server/skills.js +69 -0
  60. package/dist/server/server/start.js +166 -0
  61. package/dist/server/server/static.js +49 -0
  62. package/dist/server/shared/color.js +59 -0
  63. package/dist/server/shared/errors.js +88 -0
  64. package/dist/server/shared/ideas.js +36 -0
  65. package/dist/server/shared/labels.js +36 -0
  66. package/dist/server/shared/repoName.js +13 -0
  67. package/dist/server/shared/themes.js +120 -0
  68. package/dist/server/shared/tiers.js +15 -0
  69. package/dist/server/shared/types.js +1 -0
  70. package/dist/web/assets/Globe-ighOFp2V.js +4273 -0
  71. package/dist/web/assets/index-ByHbMQJl.js +11 -0
  72. package/dist/web/assets/index-DgR2KpYV.css +1 -0
  73. package/dist/web/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
  74. package/dist/web/assets/jetbrains-mono-cyrillic-400-normal-ugxPyKxw.woff +0 -0
  75. package/dist/web/assets/jetbrains-mono-cyrillic-600-normal-8K4wrrwR.woff +0 -0
  76. package/dist/web/assets/jetbrains-mono-cyrillic-600-normal-EVf6-Yzo.woff2 +0 -0
  77. package/dist/web/assets/jetbrains-mono-greek-400-normal-B9oWc5Lo.woff +0 -0
  78. package/dist/web/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
  79. package/dist/web/assets/jetbrains-mono-greek-600-normal-H7WoG9Et.woff2 +0 -0
  80. package/dist/web/assets/jetbrains-mono-greek-600-normal-mc2nkWzM.woff +0 -0
  81. package/dist/web/assets/jetbrains-mono-latin-400-normal-6-qcROiO.woff +0 -0
  82. package/dist/web/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  83. package/dist/web/assets/jetbrains-mono-latin-600-normal-BfsvjouI.woff +0 -0
  84. package/dist/web/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
  85. package/dist/web/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
  86. package/dist/web/assets/jetbrains-mono-latin-ext-400-normal-fXTG6kC5.woff +0 -0
  87. package/dist/web/assets/jetbrains-mono-latin-ext-600-normal-BfB_LPfz.woff2 +0 -0
  88. package/dist/web/assets/jetbrains-mono-latin-ext-600-normal-DObL3zCW.woff +0 -0
  89. package/dist/web/assets/jetbrains-mono-vietnamese-400-normal-CqNFfHCs.woff +0 -0
  90. package/dist/web/assets/jetbrains-mono-vietnamese-600-normal-OWROknRo.woff +0 -0
  91. package/dist/web/assets/rajdhani-devanagari-500-normal-BPH8g_s8.woff +0 -0
  92. package/dist/web/assets/rajdhani-devanagari-500-normal-B_DH_jja.woff2 +0 -0
  93. package/dist/web/assets/rajdhani-devanagari-600-normal-BtY48IV_.woff +0 -0
  94. package/dist/web/assets/rajdhani-devanagari-600-normal-DhS7ScYx.woff2 +0 -0
  95. package/dist/web/assets/rajdhani-devanagari-700-normal-BQQOj9BB.woff2 +0 -0
  96. package/dist/web/assets/rajdhani-devanagari-700-normal-DBRwWuxA.woff +0 -0
  97. package/dist/web/assets/rajdhani-latin-500-normal-ByNUCHrt.woff2 +0 -0
  98. package/dist/web/assets/rajdhani-latin-500-normal-DfvNI-Td.woff +0 -0
  99. package/dist/web/assets/rajdhani-latin-600-normal-CXCVEoA9.woff2 +0 -0
  100. package/dist/web/assets/rajdhani-latin-600-normal-Dx02qI2_.woff +0 -0
  101. package/dist/web/assets/rajdhani-latin-700-normal-BPDUZo87.woff2 +0 -0
  102. package/dist/web/assets/rajdhani-latin-700-normal-e0Uj8ZlN.woff +0 -0
  103. package/dist/web/assets/rajdhani-latin-ext-500-normal-CyRWJZ5B.woff +0 -0
  104. package/dist/web/assets/rajdhani-latin-ext-500-normal-DiyUS11w.woff2 +0 -0
  105. package/dist/web/assets/rajdhani-latin-ext-600-normal-BleIgkPp.woff +0 -0
  106. package/dist/web/assets/rajdhani-latin-ext-600-normal-C9ZjJQAt.woff2 +0 -0
  107. package/dist/web/assets/rajdhani-latin-ext-700-normal-BPaQ7tlD.woff +0 -0
  108. package/dist/web/assets/rajdhani-latin-ext-700-normal-S6aYESQK.woff2 +0 -0
  109. package/dist/web/index.html +13 -0
  110. package/package.json +74 -4
  111. package/scripts/autostart.ps1 +28 -0
  112. package/scripts/start-hidden.vbs +12 -0
  113. package/templates/en/CLAUDE.md +18 -0
  114. package/templates/en/README.md +3 -0
  115. package/templates/fr/CLAUDE.md +18 -0
  116. package/templates/fr/README.md +3 -0
@@ -0,0 +1,96 @@
1
+ import { dirname } from 'node:path';
2
+ import { autostartPlan, forSystemd } from './autostart.js';
3
+ /** Active (`on`) ou retire (`off`) le démarrage automatique ; `steps` est le journal anglais (utilisé par le CLI). */
4
+ export async function runAutostart(mode, deps) {
5
+ const steps = [];
6
+ const written = [];
7
+ const runCmd = async (c) => {
8
+ steps.push(`> ${[c.cmd, ...c.args].join(' ')}`);
9
+ const { stdout } = await deps.exec(c.cmd, c.args);
10
+ if (stdout.trim())
11
+ steps.push(stdout.trim());
12
+ };
13
+ if (mode === 'on' && deps.pkg.split(/[\\/]/).includes('_npx')) {
14
+ return { ok: false, code: 'autostartFailed', detail: 'holohq is running from the npx cache, which is temporary. Run "npm i -g holohq" first, then "holohq autostart on".', steps };
15
+ }
16
+ try {
17
+ const { platform } = deps;
18
+ let plan = autostartPlan(platform, { node: deps.node, entry: deps.entry, home: deps.home, env: deps.env, pkg: deps.pkg });
19
+ if (platform !== 'win32' && platform !== 'darwin')
20
+ plan = forSystemd(plan, deps.has('systemctl'));
21
+ if (mode === 'on') {
22
+ for (const f of plan.files) {
23
+ steps.push(`Writing ${f.path}`);
24
+ await deps.fs.mkdir(dirname(f.path));
25
+ await deps.fs.writeFile(f.path, f.content);
26
+ written.push(f.path);
27
+ }
28
+ for (const c of plan.commands)
29
+ await runCmd(c);
30
+ // Le démarrage est enregistré : un échec du lancement immédiat ne l'annule pas.
31
+ for (const c of plan.start) {
32
+ try {
33
+ await runCmd(c);
34
+ }
35
+ catch (e) {
36
+ steps.push(`Could not start HoloHQ now (${e instanceof Error ? e.message : String(e)}); it will start at next logon.`);
37
+ }
38
+ }
39
+ steps.push('Autostart enabled.');
40
+ }
41
+ else {
42
+ for (const c of plan.remove.commands) {
43
+ try {
44
+ await runCmd(c);
45
+ }
46
+ catch (e) {
47
+ steps.push(`Ignored: ${e instanceof Error ? e.message : String(e)}`);
48
+ }
49
+ }
50
+ for (const p of plan.remove.files) {
51
+ steps.push(`Removing ${p}`);
52
+ await deps.fs.rm(p);
53
+ }
54
+ steps.push('Autostart disabled.');
55
+ }
56
+ return { ok: true, steps };
57
+ }
58
+ catch (e) {
59
+ // Échec de `on` : on retire ce qu'on a écrit, pour qu'un démarrage « raté » ne se charge pas à la prochaine ouverture de session.
60
+ if (mode === 'on')
61
+ for (const p of written)
62
+ await deps.fs.rm(p).catch(() => { });
63
+ return { ok: false, code: 'autostartFailed', detail: e instanceof Error ? e.message : String(e), steps };
64
+ }
65
+ }
66
+ /** execFile sans shell, sans fenêtre console, avec délai maximal (la requête ne reste jamais suspendue). */
67
+ export function makeExec(execFileFn) {
68
+ return (cmd, args) => new Promise((resolve, reject) => {
69
+ execFileFn(cmd, args, { windowsHide: true, timeout: 30000 }, (err, stdout) => (err ? reject(err) : resolve({ stdout: String(stdout) })));
70
+ });
71
+ }
72
+ /** Dépendances réelles (le CLI et le serveur) : execFile sans shell, vrai système de fichiers. */
73
+ export async function realAutostartDeps() {
74
+ const [{ execFile }, { mkdir, rm, writeFile }, { homedir }, { pathLookup }, { pkgPath, pkgRoot }] = await Promise.all([
75
+ import('node:child_process'),
76
+ import('node:fs/promises'),
77
+ import('node:os'),
78
+ import('./launch.js'),
79
+ import('./paths.js'),
80
+ ]);
81
+ return {
82
+ platform: process.platform,
83
+ env: process.env,
84
+ home: homedir(),
85
+ node: process.execPath,
86
+ entry: pkgPath('dist/server/server/index.js'),
87
+ pkg: pkgRoot(),
88
+ exec: makeExec(execFile),
89
+ fs: {
90
+ mkdir: async (p) => void (await mkdir(p, { recursive: true })),
91
+ writeFile: (p, c) => writeFile(p, c, 'utf8'),
92
+ rm: (p) => rm(p, { force: true }),
93
+ },
94
+ has: pathLookup(process.env, process.platform),
95
+ };
96
+ }
@@ -0,0 +1,24 @@
1
+ import { spawn } from 'node:child_process';
2
+ const URL_RE = /^http:\/\/localhost:\d{1,5}\/$/;
3
+ /** Commande d'ouverture du navigateur par défaut. L'URL doit être exactement http://localhost:<port>/ (aucun métacaractère possible). */
4
+ export function browserCommand(platform, url) {
5
+ if (!URL_RE.test(url))
6
+ throw new Error(`Refusing to open unexpected URL: ${url}`);
7
+ if (platform === 'win32')
8
+ return { cmd: 'cmd.exe', args: ['/c', 'start', '""', url] };
9
+ if (platform === 'darwin')
10
+ return { cmd: 'open', args: [url] };
11
+ return { cmd: 'xdg-open', args: [url] };
12
+ }
13
+ /** Ouvre l'URL dans le navigateur, détaché ; best-effort (un échec n'arrête pas le serveur). */
14
+ export function openBrowser(url, onError = () => { }) {
15
+ try {
16
+ const { cmd, args } = browserCommand(process.platform, url);
17
+ const child = spawn(cmd, args, { detached: true, stdio: 'ignore', windowsHide: true });
18
+ child.on('error', (e) => onError(`Could not open the browser (${cmd}): ${e.message}`));
19
+ child.unref();
20
+ }
21
+ catch (e) {
22
+ onError(e instanceof Error ? e.message : String(e));
23
+ }
24
+ }
@@ -0,0 +1,24 @@
1
+ // Cache GitHub mémoire (TTL en ms, horloge injectée).
2
+ const store = new Map();
3
+ export async function cached(key, ttlMs, now, load) {
4
+ const t = now().getTime();
5
+ const hit = store.get(key);
6
+ if (hit && t - hit.at < ttlMs)
7
+ return hit.value;
8
+ const value = load();
9
+ store.set(key, { at: t, value });
10
+ try {
11
+ return await value;
12
+ }
13
+ catch (e) {
14
+ if (store.get(key)?.value === value)
15
+ store.delete(key);
16
+ throw e;
17
+ }
18
+ }
19
+ export function clearCaches() {
20
+ store.clear();
21
+ }
22
+ export function forgetCached(key) {
23
+ store.delete(key);
24
+ }
@@ -0,0 +1,408 @@
1
+ import { readFile, readdir, stat } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { evidenceOf } from '../floor/evidence.js';
4
+ import { cleanText, oneLine, readRange } from './history.js';
5
+ export const WORKING_MS = 10 * 60_000;
6
+ export const WAITING_MS = 15 * 60_000;
7
+ export const VISIBLE_MS = 60 * 60_000;
8
+ export const TAIL_BYTES = 262_144;
9
+ /** Plafond d'une lecture élargie, quand une fin de fichier jamais lue ne contient aucun enregistrement significatif. */
10
+ export const WIDE_BYTES = 2 * 1024 * 1024;
11
+ /** `finished` ne compte plus si le sous-agent a écrit au moins ce temps après sa fiche : sa session l'a repris. */
12
+ export const RESUMED_MS = 10_000;
13
+ /** Un sous-agent terminé ou trop ancien n'est revérifié qu'à cet intervalle. */
14
+ export const COLD_MS = 15_000;
15
+ export const ACTION_MAX = 40;
16
+ const PATHS_MAX = 20;
17
+ /** Outils qui attendent une réponse de l'utilisateur tant que leur résultat n'est pas écrit. */
18
+ const ASKING_TOOLS = new Set(['AskUserQuestion', 'ExitPlanMode']);
19
+ function blocksOf(rec) {
20
+ const content = rec.message?.content;
21
+ return Array.isArray(content) ? content.filter((b) => !!b && typeof b === 'object') : [];
22
+ }
23
+ /** Texte brut d'un message `user` (chaîne ou blocs `text`). */
24
+ function rawText(rec) {
25
+ const content = rec.message?.content;
26
+ if (typeof content === 'string')
27
+ return content;
28
+ return blocksOf(rec).map(b => (b.type === 'text' && typeof b.text === 'string' ? b.text : '')).join(' ');
29
+ }
30
+ /** Résume la fin d'une transcription. `cutAtStart` : le texte commence au milieu d'une ligne, la première est ignorée. */
31
+ export function parseTail(text, opts) {
32
+ const lines = text.split('\n');
33
+ if (opts.cutAtStart)
34
+ lines.shift();
35
+ let turn = null;
36
+ let action = null;
37
+ const asked = new Map();
38
+ let customTitle = null;
39
+ let aiTitle = null;
40
+ let promptTitle = null;
41
+ let entrypoint = null;
42
+ let cwd = null;
43
+ const paths = [];
44
+ /** Un enregistrement du tour en cours, ou le début d'un nouveau (début inconnu s'il précède le texte lu). */
45
+ const open = (at) => { turn = { open: true, startedAt: turn ? (turn.open ? turn.startedAt : at) : null, at }; };
46
+ const close = (at) => {
47
+ turn = { open: false, startedAt: turn?.startedAt ?? null, at };
48
+ action = null;
49
+ asked.clear();
50
+ };
51
+ for (const line of lines) {
52
+ if (!line.trim())
53
+ continue;
54
+ let rec;
55
+ try {
56
+ const v = JSON.parse(line);
57
+ if (!v || typeof v !== 'object')
58
+ continue;
59
+ rec = v;
60
+ }
61
+ catch {
62
+ continue;
63
+ }
64
+ const type = rec.type;
65
+ if (typeof rec.entrypoint === 'string')
66
+ entrypoint = rec.entrypoint;
67
+ if (typeof rec.cwd === 'string')
68
+ cwd = rec.cwd;
69
+ if (type === 'custom-title' && typeof rec.customTitle === 'string')
70
+ customTitle = oneLine(rec.customTitle) || customTitle;
71
+ else if (type === 'ai-title' && typeof rec.aiTitle === 'string')
72
+ aiTitle = oneLine(rec.aiTitle) || aiTitle;
73
+ else if (type === 'last-prompt' && typeof rec.lastPrompt === 'string')
74
+ promptTitle = cleanText(rec.lastPrompt) ?? promptTitle;
75
+ const at = rec.timestamp;
76
+ if (typeof at !== 'string')
77
+ continue;
78
+ if (type === 'user') {
79
+ if (rec.isMeta)
80
+ continue;
81
+ const results = blocksOf(rec).filter(b => b.type === 'tool_result');
82
+ const text = rawText(rec);
83
+ if (results.length) {
84
+ for (const b of results)
85
+ asked.delete(b.tool_use_id);
86
+ open(at);
87
+ }
88
+ else if (text.trimStart().startsWith('[Request interrupted by user')) {
89
+ close(at);
90
+ }
91
+ else {
92
+ // Demande tapée : elle ouvre un tour, ou s'ajoute au tour en cours ; une notification de Claude Code n'est pas une réponse.
93
+ if (!turn?.open)
94
+ action = null;
95
+ if (cleanText(text))
96
+ asked.clear();
97
+ turn = { open: true, startedAt: turn?.open ? turn.startedAt : at, at };
98
+ }
99
+ }
100
+ else if (type === 'assistant') {
101
+ const msg = rec.message;
102
+ // Une réponse fabriquée par Claude Code (erreur d'API) clôt le tour : plus rien ne travaille.
103
+ const closed = msg?.stop_reason === 'end_turn' || rec.isApiErrorMessage === true || msg?.model === '<synthetic>';
104
+ for (const b of blocksOf(rec)) {
105
+ if (b.type !== 'tool_use' || typeof b.name !== 'string')
106
+ continue;
107
+ const input = b.input && typeof b.input === 'object' ? b.input : {};
108
+ action = actionOf({ name: b.name, input });
109
+ if (ASKING_TOOLS.has(b.name))
110
+ asked.set(b.id, at);
111
+ const cited = evidenceOf(b.name, input);
112
+ if (cited.length)
113
+ paths.push(cited);
114
+ }
115
+ if (closed)
116
+ close(at);
117
+ else
118
+ open(at);
119
+ }
120
+ else if (type === 'system' && rec.subtype === 'turn_duration') {
121
+ close(at);
122
+ }
123
+ }
124
+ return {
125
+ turn, action, asking: [...asked.values()].pop() ?? null, title: customTitle ?? aiTitle ?? promptTitle, entrypoint, cwd,
126
+ paths: paths.slice(-PATHS_MAX).reverse(),
127
+ };
128
+ }
129
+ const basename = (p) => p.split(/[\\/]/).filter(Boolean).pop() ?? p;
130
+ const str = (v) => (typeof v === 'string' && v ? v : null);
131
+ const clip = (s) => {
132
+ if (s === null)
133
+ return null;
134
+ const chars = [...s.replace(/\s+/g, ' ').trim()];
135
+ return chars.length > ACTION_MAX ? chars.slice(0, ACTION_MAX - 1).join('') + '…' : chars.join('');
136
+ };
137
+ function hostOf(url) {
138
+ if (typeof url !== 'string')
139
+ return null;
140
+ try {
141
+ return new URL(url).hostname || null;
142
+ }
143
+ catch {
144
+ return null;
145
+ }
146
+ }
147
+ /** Libellé court de ce que fait un outil : un verbe et une cible d'au plus `ACTION_MAX` caractères. */
148
+ export function actionOf(tool) {
149
+ const { name, input } = tool;
150
+ const make = (verb, target) => ({ verb, target: clip(target) });
151
+ switch (name) {
152
+ case 'Edit':
153
+ case 'Write':
154
+ case 'MultiEdit':
155
+ case 'NotebookEdit': {
156
+ const p = str(input.file_path) ?? str(input.notebook_path);
157
+ return make('edit', p && basename(p));
158
+ }
159
+ case 'Read': {
160
+ const p = str(input.file_path);
161
+ return make('read', p && basename(p));
162
+ }
163
+ case 'Bash':
164
+ case 'PowerShell': return make('run', str(input.description));
165
+ case 'Grep':
166
+ case 'Glob': return make('search', str(input.pattern));
167
+ case 'Agent':
168
+ case 'Task': return make('delegate', str(input.description));
169
+ case 'WebFetch': return make('web', hostOf(input.url));
170
+ case 'WebSearch': return make('web', str(input.query));
171
+ default: return make('other', name.split('__').filter(Boolean).pop() ?? name);
172
+ }
173
+ }
174
+ /** Faux seulement pour les sessions pilotées par un SDK (`sdk-cli`, `sdk-ts`…). */
175
+ export function isInteractive(entrypoint) {
176
+ return !(entrypoint ?? '').startsWith('sdk-');
177
+ }
178
+ /** État d'une session d'après son dernier tour ; null : ne plus l'afficher. */
179
+ export function sessionState(s, now, o) {
180
+ if (!s.turn)
181
+ return null;
182
+ const age = now.getTime() - Date.parse(s.turn.at);
183
+ if (s.asking && o.interactive)
184
+ return age < VISIBLE_MS ? { state: 'waiting', since: s.asking } : null;
185
+ if (s.turn.open && age < WORKING_MS)
186
+ return { state: 'working', since: s.turn.startedAt ?? s.turn.at };
187
+ if (!s.turn.open && o.interactive && age < WAITING_MS)
188
+ return { state: 'waiting', since: s.turn.at };
189
+ if (age < VISIBLE_MS)
190
+ return { state: 'resting', since: s.turn.at };
191
+ return null;
192
+ }
193
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
194
+ const SUBAGENT_FILE = /^agent-(.+)\.jsonl$/;
195
+ /**
196
+ * Lecteur de l'étage : sessions et sous-agents Claude Code récents, lus dans le dossier des projets.
197
+ * Au mieux : ne lève jamais. Un fichier inchangé (chemin, taille, date) n'est pas relu. Les caches ne gardent que ce que
198
+ * le dernier passage a utilisé.
199
+ */
200
+ export function createFloorReader(opts) {
201
+ const read = opts.read ?? readRange;
202
+ const statOf = opts.stat ?? stat;
203
+ const tails = new Map();
204
+ const metas = new Map();
205
+ /** Sous-agents terminés ou trop anciens : date de leur dernière vérification. */
206
+ const cold = new Map();
207
+ /** Chemins utilisés par le passage en cours. */
208
+ const used = new Set();
209
+ /** Sessions dont un sous-agent travaillait au dernier passage : à regarder même si plus rien n'est récent chez elles. */
210
+ let busy = new Set();
211
+ /** Dernier passage qui a regardé les sous-agents de toutes les sessions (au premier, puis tous les `WORKING_MS`). */
212
+ let deepAt = -Infinity;
213
+ /**
214
+ * Résumé de la fin d'un fichier. Sans enregistrement significatif dans cette fin : le résumé précédent reste vrai si tout
215
+ * l'ajout a été lu ; sinon, une seule lecture plus large. `birth` : début connu de l'agent, faute de voir celui du tour.
216
+ */
217
+ async function tailOf(path, { size, mtimeMs }, birth) {
218
+ used.add(path);
219
+ const prev = tails.get(path);
220
+ if (prev && prev.size === size && prev.mtimeMs === mtimeMs)
221
+ return prev.value;
222
+ const summary = async (bytes) => {
223
+ const start = Math.max(0, size - bytes);
224
+ return { start, value: parseTail((await read(path, start, size)).toString('utf8'), { cutAtStart: start > 0 }) };
225
+ };
226
+ try {
227
+ let { start, value } = await summary(TAIL_BYTES);
228
+ const known = prev && prev.size <= size && start <= prev.size ? prev.value : null;
229
+ if (!value.turn && !known && start > 0)
230
+ ({ value } = await summary(WIDE_BYTES));
231
+ if (known) {
232
+ value = { ...value, title: value.title ?? known.title, entrypoint: value.entrypoint ?? known.entrypoint, cwd: value.cwd ?? known.cwd };
233
+ if (!value.turn)
234
+ value = { ...value, turn: known.turn, action: known.action, asking: known.asking, paths: known.paths };
235
+ }
236
+ if (value.turn && value.turn.startedAt === null) {
237
+ // Début hors de la fin lue : celui du tour déjà suivi, sinon la naissance de l'agent, sinon maintenant. Il ne bouge plus ensuite.
238
+ const { at } = value.turn;
239
+ const last = prev?.value.turn;
240
+ const same = last?.open && Date.parse(at) - Date.parse(last.at) < WORKING_MS;
241
+ value = { ...value, turn: { ...value.turn, startedAt: (same ? last.startedAt : null) ?? (birth && birth <= at ? birth : at) } };
242
+ }
243
+ tails.set(path, { size, mtimeMs, value });
244
+ return value;
245
+ }
246
+ catch {
247
+ return null;
248
+ }
249
+ }
250
+ async function metaOf(path) {
251
+ used.add(path);
252
+ try {
253
+ const s = await statOf(path);
254
+ const hit = metas.get(path);
255
+ if (hit && hit.size === s.size && hit.mtimeMs === s.mtimeMs)
256
+ return hit.value;
257
+ let value = null;
258
+ try {
259
+ const m = JSON.parse(await readFile(path, 'utf8'));
260
+ if (m && typeof m === 'object') {
261
+ value = { role: str(m.agentType), task: str(m.description), model: str(m.model), finished: m.finished === true, at: s.mtimeMs };
262
+ }
263
+ }
264
+ catch { /* fiche illisible : comme absente */ }
265
+ metas.set(path, { size: s.size, mtimeMs: s.mtimeMs, value });
266
+ return value;
267
+ }
268
+ catch {
269
+ return null;
270
+ }
271
+ }
272
+ async function scan() {
273
+ const now = opts.now();
274
+ let dirs;
275
+ try {
276
+ dirs = await readdir(opts.root, { withFileTypes: true });
277
+ }
278
+ catch (e) {
279
+ return e.code === 'ENOENT' ? { readable: true, agents: [] } : { readable: false };
280
+ }
281
+ used.clear();
282
+ const deep = now.getTime() - deepAt >= WORKING_MS;
283
+ if (deep)
284
+ deepAt = now.getTime();
285
+ const agents = [];
286
+ const nowBusy = new Set();
287
+ for (const d of dirs) {
288
+ if (!d.isDirectory())
289
+ continue;
290
+ const folder = join(opts.root, d.name);
291
+ let entries;
292
+ try {
293
+ entries = await readdir(folder, { withFileTypes: true });
294
+ }
295
+ catch {
296
+ continue;
297
+ }
298
+ // Par session : sa transcription et son dossier, s'ils existent (aucun `stat` perdu d'avance).
299
+ const found = new Map();
300
+ for (const ent of entries) {
301
+ const file = ent.isFile() && ent.name.endsWith('.jsonl');
302
+ const id = file ? ent.name.slice(0, -6) : ent.name;
303
+ if (!UUID.test(id) || (!file && !ent.isDirectory()))
304
+ continue;
305
+ const f = found.get(id) ?? { file: false, dir: false };
306
+ found.set(id, file ? { ...f, file } : { ...f, dir: true });
307
+ }
308
+ for (const [id, has] of found) {
309
+ const out = await scanSession(folder, id, has, now, deep);
310
+ if (out.some(a => a.kind === 'subagent' && a.state === 'working'))
311
+ nowBusy.add(id);
312
+ agents.push(...out);
313
+ }
314
+ }
315
+ busy = nowBusy;
316
+ for (const cache of [tails, metas, cold])
317
+ for (const path of cache.keys())
318
+ if (!used.has(path))
319
+ cache.delete(path);
320
+ return { readable: true, agents };
321
+ }
322
+ async function scanSession(folder, id, has, now, deep) {
323
+ const fresh = (s) => s !== null && now.getTime() - s.mtimeMs < VISIBLE_MS;
324
+ const look = async (path) => { try {
325
+ return await statOf(path);
326
+ }
327
+ catch {
328
+ return null;
329
+ } };
330
+ const file = join(folder, `${id}.jsonl`);
331
+ const subDir = join(folder, id, 'subagents');
332
+ const own = has.file ? await look(file) : null;
333
+ if (!fresh(own) && !busy.has(id) && !(has.dir && (deep || fresh(await look(subDir)))))
334
+ return [];
335
+ const children = [];
336
+ let names = [];
337
+ if (has.dir)
338
+ try {
339
+ names = await readdir(subDir);
340
+ }
341
+ catch { /* pas de sous-agents */ }
342
+ for (const name of names) {
343
+ const m = SUBAGENT_FILE.exec(name);
344
+ if (!m)
345
+ continue;
346
+ const path = join(subDir, name);
347
+ const metaPath = join(subDir, `agent-${m[1]}.meta.json`);
348
+ if (now.getTime() - (cold.get(path) ?? -Infinity) < COLD_MS) {
349
+ used.add(path).add(metaPath);
350
+ continue;
351
+ }
352
+ cold.delete(path);
353
+ const rest = () => { cold.set(path, now.getTime()); used.add(path); };
354
+ const s = await look(path);
355
+ if (!fresh(s)) {
356
+ rest();
357
+ continue;
358
+ }
359
+ const meta = await metaOf(metaPath);
360
+ const over = (at) => meta?.finished === true && at <= meta.at + RESUMED_MS;
361
+ if (over(s.mtimeMs)) {
362
+ rest();
363
+ continue;
364
+ }
365
+ const tail = await tailOf(path, s, s.birthtimeMs > 0 ? new Date(s.birthtimeMs).toISOString() : null);
366
+ if (!tail?.turn || over(Date.parse(tail.turn.at)))
367
+ continue;
368
+ const st = sessionState(tail, now, { interactive: false });
369
+ if (!st)
370
+ continue;
371
+ children.push({
372
+ id: `agent-${m[1]}`, kind: 'subagent', parentId: id, state: st.state, title: null,
373
+ role: meta?.role ?? null, model: meta?.model ?? null, task: meta?.task ?? null,
374
+ action: st.state === 'working' ? tail.action : null,
375
+ since: st.since, updatedAt: tail.turn.at, cwd: tail.cwd, paths: tail.paths,
376
+ });
377
+ }
378
+ // Une vieille session sans sous-agent vivant n'est pas lue.
379
+ if (!own || (!fresh(own) && !children.length))
380
+ return [];
381
+ const summary = await tailOf(file, own, null);
382
+ for (const c of children)
383
+ c.cwd ??= summary?.cwd ?? null;
384
+ const working = children.filter(c => c.state === 'working').sort((a, b) => Date.parse(b.updatedAt) - Date.parse(a.updatedAt));
385
+ const state = summary ? sessionState(summary, now, { interactive: isInteractive(summary.entrypoint) }) : null;
386
+ // Un sous-agent n'est listé que si sa session l'est.
387
+ if (!summary || (!state && !working.length))
388
+ return [];
389
+ // Elle délègue : elle travaille, sauf si elle attend la réponse à une question.
390
+ const delegates = working.length > 0 && !(summary.asking && state?.state === 'waiting');
391
+ const parent = {
392
+ id, kind: 'session', parentId: null, title: summary.title, role: null, model: null, task: null,
393
+ state: delegates ? 'working' : state.state,
394
+ action: delegates
395
+ ? (working[0].task ? actionOf({ name: 'Agent', input: { description: working[0].task } }) : { verb: 'delegate', target: null })
396
+ : state.state === 'working' ? summary.action : null,
397
+ since: delegates ? summary.turn?.startedAt ?? working[0].since : state.since,
398
+ updatedAt: summary.turn?.at ?? working[0].updatedAt, cwd: summary.cwd, paths: summary.paths,
399
+ };
400
+ return [parent, ...children];
401
+ }
402
+ // Une seule lecture à la fois : les appels simultanés partagent la même promesse.
403
+ let inflight = null;
404
+ return () => {
405
+ inflight ??= scan().catch(() => ({ readable: false })).finally(() => { inflight = null; });
406
+ return inflight;
407
+ };
408
+ }