@ignitionai/cogitator 0.1.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 (75) hide show
  1. package/README.md +44 -0
  2. package/dist/extensions/index.js +63 -0
  3. package/dist/src/agents.js +238 -0
  4. package/dist/src/board.js +277 -0
  5. package/dist/src/cli.js +71 -0
  6. package/dist/src/config.js +7 -0
  7. package/dist/src/conversations.js +41 -0
  8. package/dist/src/cron.js +227 -0
  9. package/dist/src/db.js +128 -0
  10. package/dist/src/default-agent.js +154 -0
  11. package/dist/src/file-changes.js +113 -0
  12. package/dist/src/history.js +88 -0
  13. package/dist/src/json-files.js +18 -0
  14. package/dist/src/mcp-env.js +29 -0
  15. package/dist/src/mcp-server.js +167 -0
  16. package/dist/src/paths.js +22 -0
  17. package/dist/src/pi.js +23 -0
  18. package/dist/src/pool.js +183 -0
  19. package/dist/src/registry.js +171 -0
  20. package/dist/src/schemas.js +134 -0
  21. package/dist/src/server.js +829 -0
  22. package/dist/src/session-lines.js +27 -0
  23. package/dist/src/skills-import.js +167 -0
  24. package/dist/src/spawn.js +39 -0
  25. package/dist/src/spawner.js +28 -0
  26. package/dist/src/workspace-files.js +93 -0
  27. package/dist/src/workspaces.js +81 -0
  28. package/package.json +60 -0
  29. package/web/dist/assets/index-BoKe95MT.js +12 -0
  30. package/web/dist/assets/index-SltX54ZZ.css +1 -0
  31. package/web/dist/assets/inter-cyrillic-400-normal-HOLc17fK.woff +0 -0
  32. package/web/dist/assets/inter-cyrillic-400-normal-obahsSVq.woff2 +0 -0
  33. package/web/dist/assets/inter-cyrillic-500-normal-BasfLYem.woff2 +0 -0
  34. package/web/dist/assets/inter-cyrillic-500-normal-CxZf_p3X.woff +0 -0
  35. package/web/dist/assets/inter-cyrillic-600-normal-4D_pXhcN.woff +0 -0
  36. package/web/dist/assets/inter-cyrillic-600-normal-CWCymEST.woff2 +0 -0
  37. package/web/dist/assets/inter-cyrillic-ext-400-normal-BQZuk6qB.woff2 +0 -0
  38. package/web/dist/assets/inter-cyrillic-ext-400-normal-DQukG94-.woff +0 -0
  39. package/web/dist/assets/inter-cyrillic-ext-500-normal-B0yAr1jD.woff2 +0 -0
  40. package/web/dist/assets/inter-cyrillic-ext-500-normal-BmqWE9Dz.woff +0 -0
  41. package/web/dist/assets/inter-cyrillic-ext-600-normal-Bcila6Z-.woff +0 -0
  42. package/web/dist/assets/inter-cyrillic-ext-600-normal-Dfes3d0z.woff2 +0 -0
  43. package/web/dist/assets/inter-greek-400-normal-B4URO6DV.woff2 +0 -0
  44. package/web/dist/assets/inter-greek-400-normal-q2sYcFCs.woff +0 -0
  45. package/web/dist/assets/inter-greek-500-normal-BIZE56-Y.woff2 +0 -0
  46. package/web/dist/assets/inter-greek-500-normal-Xzm54t5V.woff +0 -0
  47. package/web/dist/assets/inter-greek-600-normal-BZpKdvQh.woff +0 -0
  48. package/web/dist/assets/inter-greek-600-normal-plRanbMR.woff2 +0 -0
  49. package/web/dist/assets/inter-greek-ext-400-normal-DGGRlc-M.woff2 +0 -0
  50. package/web/dist/assets/inter-greek-ext-400-normal-KugGGMne.woff +0 -0
  51. package/web/dist/assets/inter-greek-ext-500-normal-2j5mBUwD.woff +0 -0
  52. package/web/dist/assets/inter-greek-ext-500-normal-C4iEst2y.woff2 +0 -0
  53. package/web/dist/assets/inter-greek-ext-600-normal-B8X0CLgF.woff +0 -0
  54. package/web/dist/assets/inter-greek-ext-600-normal-DRtmH8MT.woff2 +0 -0
  55. package/web/dist/assets/inter-latin-400-normal-C38fXH4l.woff2 +0 -0
  56. package/web/dist/assets/inter-latin-400-normal-CyCys3Eg.woff +0 -0
  57. package/web/dist/assets/inter-latin-500-normal-BL9OpVg8.woff +0 -0
  58. package/web/dist/assets/inter-latin-500-normal-Cerq10X2.woff2 +0 -0
  59. package/web/dist/assets/inter-latin-600-normal-CiBQ2DWP.woff +0 -0
  60. package/web/dist/assets/inter-latin-600-normal-LgqL8muc.woff2 +0 -0
  61. package/web/dist/assets/inter-latin-ext-400-normal-77YHD8bZ.woff +0 -0
  62. package/web/dist/assets/inter-latin-ext-400-normal-C1nco2VV.woff2 +0 -0
  63. package/web/dist/assets/inter-latin-ext-500-normal-BxGbmqWO.woff +0 -0
  64. package/web/dist/assets/inter-latin-ext-500-normal-CV4jyFjo.woff2 +0 -0
  65. package/web/dist/assets/inter-latin-ext-600-normal-CIVaiw4L.woff +0 -0
  66. package/web/dist/assets/inter-latin-ext-600-normal-D2bJ5OIk.woff2 +0 -0
  67. package/web/dist/assets/inter-vietnamese-400-normal-Bbgyi5SW.woff +0 -0
  68. package/web/dist/assets/inter-vietnamese-400-normal-DMkecbls.woff2 +0 -0
  69. package/web/dist/assets/inter-vietnamese-500-normal-DOriooB6.woff2 +0 -0
  70. package/web/dist/assets/inter-vietnamese-500-normal-mJboJaSs.woff +0 -0
  71. package/web/dist/assets/inter-vietnamese-600-normal-BuLX-rYi.woff +0 -0
  72. package/web/dist/assets/inter-vietnamese-600-normal-Cc8MFFhd.woff2 +0 -0
  73. package/web/dist/favicon.png +0 -0
  74. package/web/dist/icon.png +0 -0
  75. package/web/dist/index.html +16 -0
@@ -0,0 +1,829 @@
1
+ import { execFile } from "node:child_process";
2
+ import { EventEmitter } from "node:events";
3
+ import { existsSync, statSync, readFileSync } from "node:fs";
4
+ import { dirname, extname, join, normalize } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { createServer } from "node:http";
7
+ import { HOST } from "./config.js";
8
+ import { packageVersion, piVersion } from "./pi.js";
9
+ import { API_PROTOCOLS, deleteProvider, listProviders, listSkills, mcpAdapterDetected, readMcp, upsertProvider, validateMcpConfig, writeMcp, } from "./registry.js";
10
+ import { applyAgent, createAgent, deleteAgent, getAgent, listAgents, unapplyAgent, updateAgent, validateAgent, getDefaultAgentId, setDefaultAgent, } from "./agents.js";
11
+ import { createTask, deleteTask, getTask, listRuns, listTasks, updateTask, } from "./cron.js";
12
+ import { createConversation, deleteConversation, getConversation, listConversations, setConversationModel, setConversationTitle, } from "./conversations.js";
13
+ import { makeSpawner } from "./spawner.js";
14
+ import { readHistory, readEntries } from "./history.js";
15
+ import { readFileChanges, readFileEvents, readFileDetail } from "./file-changes.js";
16
+ import { workspaceTree, readWorkspaceFile } from "./workspace-files.js";
17
+ import { listCards, createCardGh, updateCardGh, moveCardGh, addCommentGh, closeCardGh, } from "./board.js";
18
+ import { importSkills } from "./skills-import.js";
19
+ import { agentInputSchema, conversationCreateSchema, messageSchema, modelSwitchSchema, providerUpsertSchema, scheduleCreateSchema, scheduleUpdateSchema, skillImportSchema, workspaceCreateSchema, workspaceUpdateSchema, boardCardSchema, boardCommentSchema, } from "./schemas.js";
20
+ import { spawnConfigFromPreset } from "./spawn.js";
21
+ import { browseDir, createWorkspace, deleteWorkspace, getWorkspace, listWorkspaces, updateWorkspace, } from "./workspaces.js";
22
+ // ---------- Statique ----------
23
+ /** Localise web/dist en remontant depuis le module (marche en dev src/ comme en prod dist/src/ ou en paquet npm). */
24
+ function findWebDist() {
25
+ let dir = dirname(fileURLToPath(import.meta.url));
26
+ for (let i = 0; i < MAX_WEB_DIST_LOOKUP; i++) {
27
+ const candidate = join(dir, "web", "dist");
28
+ if (existsSync(join(candidate, "index.html")))
29
+ return candidate;
30
+ const parent = dirname(dir);
31
+ if (parent === dir)
32
+ break;
33
+ dir = parent;
34
+ }
35
+ return null;
36
+ }
37
+ const MAX_WEB_DIST_LOOKUP = 6;
38
+ const CONTENT_TYPES = {
39
+ ".html": "text/html; charset=utf-8",
40
+ ".js": "text/javascript; charset=utf-8",
41
+ ".css": "text/css; charset=utf-8",
42
+ ".svg": "image/svg+xml",
43
+ ".png": "image/png",
44
+ ".json": "application/json",
45
+ ".woff2": "font/woff2",
46
+ };
47
+ /** Sert le build statique de l'UI ; SPA fallback vers index.html.
48
+ * Le dossier est résolu à chaque requête : un build web peut être (re)généré après le démarrage. */
49
+ function serveStatic(res, pathname) {
50
+ const root = findWebDist();
51
+ if (!root)
52
+ return false;
53
+ const rel = pathname === "/" ? "index.html" : pathname;
54
+ const file = normalize(join(root, rel));
55
+ if (!file.startsWith(root))
56
+ return false; // pas de traversal
57
+ const target = existsSync(file) && statSync(file).isFile() ? file : join(root, "index.html");
58
+ if (!existsSync(target))
59
+ return false;
60
+ res.writeHead(200, { "content-type": CONTENT_TYPES[extname(target)] ?? "application/octet-stream" });
61
+ res.end(readFileSync(target));
62
+ return true;
63
+ }
64
+ function sendJson(res, status, body) {
65
+ res.writeHead(status, { "content-type": "application/json" });
66
+ res.end(JSON.stringify(body));
67
+ }
68
+ /** Répond 404 et renvoie null — garde d'existence commune à toutes les routes paramétrées. */
69
+ function notFound(res, what) {
70
+ sendJson(res, 404, { error: `${what} introuvable` });
71
+ return null;
72
+ }
73
+ function matchRoute(routes, method, pathname) {
74
+ const uSeg = pathname.split("/").filter(Boolean);
75
+ for (const [routeMethod, pattern, handler] of routes) {
76
+ if (routeMethod !== method)
77
+ continue;
78
+ const pSeg = pattern.split("/").filter(Boolean);
79
+ if (pSeg.length !== uSeg.length)
80
+ continue;
81
+ const params = {};
82
+ let matches = true;
83
+ for (const [i, segment] of pSeg.entries()) {
84
+ const actual = uSeg[i];
85
+ if (segment.startsWith(":"))
86
+ params[segment.slice(1)] = decodeURIComponent(actual);
87
+ else if (segment !== actual) {
88
+ matches = false;
89
+ break;
90
+ }
91
+ }
92
+ if (matches)
93
+ return { handler, params };
94
+ }
95
+ return null;
96
+ }
97
+ const MAX_BODY_BYTES = 1_000_000;
98
+ function readBody(req) {
99
+ return new Promise((resolve, reject) => {
100
+ let size = 0;
101
+ const chunks = [];
102
+ req.on("data", (c) => {
103
+ size += c.length;
104
+ if (size > MAX_BODY_BYTES) {
105
+ reject(new Error("body trop volumineux"));
106
+ req.destroy();
107
+ return;
108
+ }
109
+ chunks.push(c);
110
+ });
111
+ req.on("end", () => {
112
+ if (!chunks.length)
113
+ return resolve({});
114
+ try {
115
+ resolve(JSON.parse(Buffer.concat(chunks).toString("utf8")));
116
+ }
117
+ catch {
118
+ reject(new Error("JSON invalide"));
119
+ }
120
+ });
121
+ req.on("error", reject);
122
+ });
123
+ }
124
+ /** Valide un body brut contre un schéma zod ; répond 400 et renvoie null si invalide. */
125
+ function parseBody(res, schema, body) {
126
+ const result = schema.safeParse(body ?? {});
127
+ if (!result.success) {
128
+ sendJson(res, 400, {
129
+ error: "entrée invalide",
130
+ issues: result.error.issues.map((i) => `${i.path.join(".") || "body"}: ${i.message}`),
131
+ });
132
+ return null;
133
+ }
134
+ return result.data;
135
+ }
136
+ const SSE_HEADERS = {
137
+ "content-type": "text/event-stream",
138
+ "cache-control": "no-cache",
139
+ connection: "keep-alive",
140
+ };
141
+ /** Ouvre un flux SSE et renvoie l'émetteur (`initial` = premier événement, ex. session_file). */
142
+ function openSse(res, initial) {
143
+ res.writeHead(200, SSE_HEADERS);
144
+ const send = (event) => {
145
+ res.write(`data: ${JSON.stringify(event)}\n\n`);
146
+ };
147
+ if (initial !== undefined)
148
+ send(initial);
149
+ return send;
150
+ }
151
+ const MAX_SSE_LISTENERS = 100;
152
+ // ---------- Auth pi ----------
153
+ const AUTH_CHECK_TIMEOUT_MS = 15_000;
154
+ /** Checker auth réel pour la route validate (la fonction validateAgent reste injectable pour les tests). */
155
+ function checkAuthReadyFor(provider) {
156
+ return new Promise((resolve) => {
157
+ execFile("pi", ["auth", "check", "--provider", provider, "--json"], { timeout: AUTH_CHECK_TIMEOUT_MS }, (err, stdout) => {
158
+ try {
159
+ resolve(JSON.parse(stdout).status === "ready");
160
+ }
161
+ catch {
162
+ resolve(err ? false : null);
163
+ }
164
+ });
165
+ });
166
+ }
167
+ /** Résout le :id d'une route en entité, ou répond 404 et renvoie null. */
168
+ function requireWorkspace(deps, ctx) {
169
+ return getWorkspace(deps.db, ctx.params.id) ?? notFound(ctx.res, "workspace");
170
+ }
171
+ function requireConversation(deps, ctx) {
172
+ return getConversation(deps.db, ctx.params.id) ?? notFound(ctx.res, "conversation");
173
+ }
174
+ function requireAgent(deps, ctx) {
175
+ return getAgent(deps.db, ctx.params.id) ?? notFound(ctx.res, "agent");
176
+ }
177
+ // ---------- Groupes de routes ----------
178
+ /** Registry pi : providers, skills, MCP user-level. */
179
+ function registryRoutes(deps) {
180
+ const { paths } = deps;
181
+ return [
182
+ ["GET", "/api/providers", async (ctx) => {
183
+ sendJson(ctx.res, 200, { providers: await listProviders(paths) });
184
+ }],
185
+ ["POST", "/api/providers", (ctx) => {
186
+ const b = parseBody(ctx.res, providerUpsertSchema, ctx.body);
187
+ if (!b)
188
+ return;
189
+ if (!b.id)
190
+ return sendJson(ctx.res, 400, { error: "id requis", issues: ["id: requis"] });
191
+ const { error } = upsertProvider(paths, b.id, b);
192
+ if (error)
193
+ return sendJson(ctx.res, 400, { error });
194
+ sendJson(ctx.res, 201, { ok: true });
195
+ }],
196
+ ["PUT", "/api/providers/:id", (ctx) => {
197
+ const b = parseBody(ctx.res, providerUpsertSchema, ctx.body);
198
+ if (!b)
199
+ return;
200
+ const { error } = upsertProvider(paths, ctx.params.id, b);
201
+ if (error)
202
+ return sendJson(ctx.res, 400, { error });
203
+ sendJson(ctx.res, 200, { ok: true });
204
+ }],
205
+ ["DELETE", "/api/providers/:id", (ctx) => {
206
+ deleteProvider(paths, ctx.params.id);
207
+ sendJson(ctx.res, 200, { ok: true });
208
+ }],
209
+ ["GET", "/api/skills", (ctx) => {
210
+ sendJson(ctx.res, 200, { skills: listSkills(paths) });
211
+ }],
212
+ ["POST", "/api/skills/import", async (ctx) => {
213
+ const b = parseBody(ctx.res, skillImportSchema, ctx.body);
214
+ if (!b)
215
+ return;
216
+ const destRoot = paths.skillsDirs[0] ?? join(paths.piAgentDir, "skills");
217
+ const result = await importSkills(b.source, destRoot, b.overwrite === true);
218
+ if (result.error && result.imported.length === 0)
219
+ return sendJson(ctx.res, 400, { error: result.error });
220
+ sendJson(ctx.res, 200, { ...result, dest: destRoot, skills: listSkills(paths) });
221
+ }],
222
+ ["GET", "/api/mcp", (ctx) => {
223
+ sendJson(ctx.res, 200, readMcp(paths));
224
+ }],
225
+ ["PUT", "/api/mcp", (ctx) => {
226
+ const invalid = validateMcpConfig(ctx.body);
227
+ if (invalid)
228
+ return sendJson(ctx.res, 400, { error: invalid });
229
+ writeMcp(paths, ctx.body);
230
+ sendJson(ctx.res, 200, { ok: true });
231
+ }],
232
+ ];
233
+ }
234
+ /** Presets d'agents + apply/unapply des définitions herdr. */
235
+ function agentRoutes(deps) {
236
+ const { db, paths } = deps;
237
+ return [
238
+ ["GET", "/api/agents", (ctx) => {
239
+ sendJson(ctx.res, 200, { agents: listAgents(db) });
240
+ }],
241
+ ["POST", "/api/agents", (ctx) => {
242
+ const input = parseBody(ctx.res, agentInputSchema, ctx.body);
243
+ if (!input)
244
+ return;
245
+ const preset = createAgent(db, input);
246
+ sendJson(ctx.res, 201, { agent: preset, apply: applyAgent(paths, preset) });
247
+ }],
248
+ ["GET", "/api/agents/:id", (ctx) => {
249
+ const agent = requireAgent(deps, ctx);
250
+ if (!agent)
251
+ return;
252
+ sendJson(ctx.res, 200, { agent });
253
+ }],
254
+ ["PUT", "/api/agents/:id", (ctx) => {
255
+ const input = parseBody(ctx.res, agentInputSchema, ctx.body);
256
+ if (!input)
257
+ return;
258
+ const preset = updateAgent(db, ctx.params.id, input);
259
+ if (!preset)
260
+ return notFound(ctx.res, "agent");
261
+ sendJson(ctx.res, 200, { agent: preset, apply: applyAgent(paths, preset) });
262
+ }],
263
+ ["DELETE", "/api/agents/:id", (ctx) => {
264
+ const existing = requireAgent(deps, ctx);
265
+ if (!existing)
266
+ return;
267
+ deleteAgent(db, existing.id);
268
+ sendJson(ctx.res, 200, { ok: true, unapplied: unapplyAgent(paths, existing.slug) });
269
+ }],
270
+ ["POST", "/api/agents/:id/validate", async (ctx) => {
271
+ const preset = requireAgent(deps, ctx);
272
+ if (!preset)
273
+ return;
274
+ sendJson(ctx.res, 200, await validateAgent(paths, preset, checkAuthReadyFor));
275
+ }],
276
+ ["POST", "/api/agents/:id/default", (ctx) => {
277
+ if (!setDefaultAgent(db, ctx.params.id))
278
+ return notFound(ctx.res, "agent");
279
+ sendJson(ctx.res, 200, { ok: true });
280
+ }],
281
+ ];
282
+ }
283
+ /** Workspaces (dossier de projet) + file-picker + arborescence read-only. */
284
+ function workspaceRoutes(deps) {
285
+ const { db } = deps;
286
+ return [
287
+ ["GET", "/api/workspaces", (ctx) => {
288
+ sendJson(ctx.res, 200, { workspaces: listWorkspaces(db) });
289
+ }],
290
+ ["POST", "/api/workspaces", (ctx) => {
291
+ const b = parseBody(ctx.res, workspaceCreateSchema, ctx.body);
292
+ if (!b)
293
+ return;
294
+ const { workspace, error } = createWorkspace(db, b);
295
+ if (error)
296
+ return sendJson(ctx.res, 400, { error });
297
+ sendJson(ctx.res, 201, { workspace });
298
+ }],
299
+ ["PUT", "/api/workspaces/:id", (ctx) => {
300
+ const b = parseBody(ctx.res, workspaceUpdateSchema, ctx.body);
301
+ if (!b)
302
+ return;
303
+ if (!requireWorkspace(deps, ctx))
304
+ return;
305
+ // updateWorkspace ne renvoie null que si l'agent par défaut visé n'existe pas
306
+ const workspace = updateWorkspace(db, ctx.params.id, b);
307
+ if (!workspace)
308
+ return sendJson(ctx.res, 400, { error: "agent par défaut introuvable" });
309
+ sendJson(ctx.res, 200, { workspace });
310
+ }],
311
+ ["DELETE", "/api/workspaces/:id", (ctx) => {
312
+ if (!deleteWorkspace(db, ctx.params.id))
313
+ return notFound(ctx.res, "workspace");
314
+ sendJson(ctx.res, 200, { ok: true }); // les sessions pi survivent sur disque
315
+ }],
316
+ ["GET", "/api/fs/browse", (ctx) => {
317
+ const result = browseDir(ctx.query.get("path"));
318
+ if ("error" in result)
319
+ return sendJson(ctx.res, 400, { error: result.error });
320
+ sendJson(ctx.res, 200, result);
321
+ }],
322
+ ["GET", "/api/workspaces/:id/tree", (ctx) => {
323
+ const ws = requireWorkspace(deps, ctx);
324
+ if (!ws)
325
+ return;
326
+ sendJson(ctx.res, 200, { root: ws.dir, tree: workspaceTree(ws.dir) });
327
+ }],
328
+ ["GET", "/api/workspaces/:id/file", (ctx) => {
329
+ const ws = requireWorkspace(deps, ctx);
330
+ if (!ws)
331
+ return;
332
+ const path = ctx.query.get("path");
333
+ if (!path)
334
+ return sendJson(ctx.res, 400, { error: "path requis" });
335
+ const { file, error } = readWorkspaceFile(ws.dir, path);
336
+ if (error)
337
+ return sendJson(ctx.res, 400, { error });
338
+ sendJson(ctx.res, 200, { file });
339
+ }],
340
+ // Activité agrégée du workspace (toutes conversations confondues)
341
+ ["GET", "/api/workspaces/:id/activity", (ctx) => {
342
+ const ws = requireWorkspace(deps, ctx);
343
+ if (!ws)
344
+ return;
345
+ const convs = db
346
+ .prepare(`SELECT id, session_file FROM conversation
347
+ WHERE workspace_id = ? AND session_file IS NOT NULL
348
+ ORDER BY updated_at DESC LIMIT ?`)
349
+ .all(ws.id, WORKSPACE_CONVERSATION_SCAN);
350
+ const { files, totals } = aggregateFileChanges(convs);
351
+ sendJson(ctx.res, 200, { files, totals, conversations: convs.length });
352
+ }],
353
+ // Feed chronologique d'un workspace (toutes conversations fusionnées)
354
+ ["GET", "/api/workspaces/:id/feed", (ctx) => {
355
+ const ws = requireWorkspace(deps, ctx);
356
+ if (!ws)
357
+ return;
358
+ const convs = db
359
+ .prepare(`SELECT id, title, session_file FROM conversation
360
+ WHERE workspace_id = ? AND session_file IS NOT NULL
361
+ ORDER BY updated_at DESC LIMIT ?`)
362
+ .all(ws.id, WORKSPACE_CONVERSATION_SCAN);
363
+ const events = convs.flatMap((c) => readFileEvents(c.session_file, FEED_EVENTS_PER_CONVERSATION).map((e) => ({
364
+ ...e,
365
+ hunks: undefined, // le feed n'a pas besoin du contenu
366
+ conversationId: c.id,
367
+ conversationTitle: c.title || "(sans titre)",
368
+ })));
369
+ events.sort((a, b) => b.at.localeCompare(a.at));
370
+ sendJson(ctx.res, 200, { events: events.slice(0, FEED_MAX_EVENTS), conversations: convs.length });
371
+ }],
372
+ ];
373
+ }
374
+ const WORKSPACE_CONVERSATION_SCAN = 20;
375
+ const FEED_EVENTS_PER_CONVERSATION = 200;
376
+ const FEED_MAX_EVENTS = 100;
377
+ const AGGREGATED_FILES_MAX = 100;
378
+ /** Fusionne les changements de plusieurs conversations (dernier passage par chemin). */
379
+ function aggregateFileChanges(convs) {
380
+ const merged = new Map();
381
+ for (const c of convs) {
382
+ for (const f of readFileChanges(c.session_file)) {
383
+ const existing = merged.get(f.path);
384
+ if (!existing) {
385
+ merged.set(f.path, { ...f, lastConversationId: c.id });
386
+ continue;
387
+ }
388
+ existing.edits += f.edits;
389
+ existing.additions += f.additions;
390
+ existing.deletions += f.deletions;
391
+ existing.kind = existing.kind === "write" ? "write" : f.kind;
392
+ if (f.lastAt > existing.lastAt) {
393
+ existing.lastAt = f.lastAt;
394
+ existing.lastConversationId = c.id;
395
+ }
396
+ }
397
+ }
398
+ const files = [...merged.values()]
399
+ .sort((a, b) => b.lastAt.localeCompare(a.lastAt))
400
+ .slice(0, AGGREGATED_FILES_MAX);
401
+ const totals = files.reduce((acc, f) => ({ additions: acc.additions + f.additions, deletions: acc.deletions + f.deletions }), { additions: 0, deletions: 0 });
402
+ return { files, totals };
403
+ }
404
+ /** Board kanban — réplique des GitHub Issues du repo (sidecar local pour les extras Cogitator). */
405
+ function boardRoutes(deps) {
406
+ const { db } = deps;
407
+ return [
408
+ ["GET", "/api/workspaces/:id/board", async (ctx) => {
409
+ const ws = requireWorkspace(deps, ctx);
410
+ if (!ws)
411
+ return;
412
+ const result = await listCards(ws.dir);
413
+ if ("error" in result)
414
+ return sendJson(ctx.res, 400, { error: result.error });
415
+ sendJson(ctx.res, 200, { cards: result.cards });
416
+ }],
417
+ ["POST", "/api/workspaces/:id/board/cards", async (ctx) => {
418
+ const ws = requireWorkspace(deps, ctx);
419
+ if (!ws)
420
+ return;
421
+ const input = parseBody(ctx.res, boardCardSchema, ctx.body);
422
+ if (!input)
423
+ return;
424
+ const result = await createCardGh(ws.dir, toCardWrite(input));
425
+ if ("error" in result)
426
+ return sendJson(ctx.res, 400, { error: result.error });
427
+ sendJson(ctx.res, 201, { card: result.card });
428
+ }],
429
+ ["PUT", "/api/workspaces/:id/board/cards/:cardId", async (ctx) => {
430
+ const ws = requireWorkspace(deps, ctx);
431
+ if (!ws)
432
+ return;
433
+ const input = parseBody(ctx.res, boardCardSchema, ctx.body);
434
+ if (!input)
435
+ return;
436
+ const result = await updateCardGh(ws.dir, cardNumber(ctx), toCardWrite(input));
437
+ if ("error" in result)
438
+ return sendJson(ctx.res, 400, { error: result.error });
439
+ sendJson(ctx.res, 200, { card: result.card });
440
+ }],
441
+ ["POST", "/api/workspaces/:id/board/cards/:cardId/move", async (ctx) => {
442
+ const ws = requireWorkspace(deps, ctx);
443
+ if (!ws)
444
+ return;
445
+ const b = (ctx.body ?? {});
446
+ if (!b.status)
447
+ return sendJson(ctx.res, 400, { error: "status requis" });
448
+ const result = await moveCardGh(ws.dir, cardNumber(ctx), b.status);
449
+ if ("error" in result)
450
+ return sendJson(ctx.res, 400, { error: result.error });
451
+ sendJson(ctx.res, 200, { card: result.card });
452
+ }],
453
+ ["POST", "/api/workspaces/:id/board/cards/:cardId/comments", async (ctx) => {
454
+ const ws = requireWorkspace(deps, ctx);
455
+ if (!ws)
456
+ return;
457
+ const input = parseBody(ctx.res, boardCommentSchema, ctx.body);
458
+ if (!input)
459
+ return;
460
+ const result = await addCommentGh(ws.dir, cardNumber(ctx), input.text, input.author ?? "user");
461
+ if ("error" in result)
462
+ return sendJson(ctx.res, 400, { error: result.error });
463
+ sendJson(ctx.res, 200, { card: result.card });
464
+ }],
465
+ // Lancer l'agent assigné sur un ticket : conversation dans le workspace + lien carte + in_progress
466
+ ["POST", "/api/workspaces/:id/board/cards/:cardId/start", async (ctx) => {
467
+ const ws = requireWorkspace(deps, ctx);
468
+ if (!ws)
469
+ return;
470
+ const started = await startCardWork(deps, ws, cardNumber(ctx), (ctx.body ?? {}).extra);
471
+ if ("error" in started)
472
+ return sendJson(ctx.res, started.status, { error: started.error });
473
+ sendJson(ctx.res, 201, started);
474
+ }],
475
+ ["DELETE", "/api/workspaces/:id/board/cards/:cardId", async (ctx) => {
476
+ const ws = requireWorkspace(deps, ctx);
477
+ if (!ws)
478
+ return;
479
+ const result = await closeCardGh(ws.dir, cardNumber(ctx));
480
+ if ("error" in result)
481
+ return sendJson(ctx.res, 400, { error: result.error });
482
+ sendJson(ctx.res, 200, { ok: true, note: "issue fermée (GitHub ne supprime pas)" });
483
+ }],
484
+ // Activité agrégée d'une carte (conversations liées)
485
+ ["GET", "/api/workspaces/:id/board/cards/:cardId/activity", async (ctx) => {
486
+ const ws = requireWorkspace(deps, ctx);
487
+ if (!ws)
488
+ return;
489
+ const found = await findCard(ws.dir, cardNumber(ctx));
490
+ if ("error" in found)
491
+ return sendJson(ctx.res, found.status, { error: found.error });
492
+ const totals = { additions: 0, deletions: 0, files: 0 };
493
+ const perConversation = [];
494
+ for (const convId of found.card.conversation_ids) {
495
+ const conv = db.prepare("SELECT session_file FROM conversation WHERE id = ?").get(convId);
496
+ if (!conv?.session_file)
497
+ continue;
498
+ const changes = readFileChanges(conv.session_file);
499
+ const additions = changes.reduce((n, f) => n + f.additions, 0);
500
+ const deletions = changes.reduce((n, f) => n + f.deletions, 0);
501
+ totals.additions += additions;
502
+ totals.deletions += deletions;
503
+ totals.files += changes.length;
504
+ perConversation.push({ conversationId: convId, additions, deletions });
505
+ }
506
+ sendJson(ctx.res, 200, { totals, perConversation });
507
+ }],
508
+ ];
509
+ }
510
+ const cardNumber = (ctx) => Number(ctx.params.cardId);
511
+ /** Le body d'une carte couvre create et update : un seul mapping vers CardWrite. */
512
+ function toCardWrite(input) {
513
+ return {
514
+ title: input.title,
515
+ description: input.description,
516
+ status: input.status,
517
+ priority: input.priority,
518
+ labels: input.labels,
519
+ assignee_agent_id: input.assignee_agent_id,
520
+ conversation_ids: input.conversation_ids,
521
+ blocks: input.blocks,
522
+ blocked_by: input.blocked_by,
523
+ };
524
+ }
525
+ /** Retrouve une carte par numéro d'issue, ou l'erreur HTTP à renvoyer. */
526
+ async function findCard(wsDir, number) {
527
+ const listed = await listCards(wsDir);
528
+ if ("error" in listed)
529
+ return { error: listed.error, status: 400 };
530
+ const card = listed.cards.find((c) => c.number === number);
531
+ return card ? { card } : { error: "carte introuvable", status: 404 };
532
+ }
533
+ /** Ticket → conversation pilotée par l'agent assigné, puis carte déplacée en in_progress. */
534
+ async function startCardWork(deps, ws, number, extra) {
535
+ const found = await findCard(ws.dir, number);
536
+ if ("error" in found)
537
+ return found;
538
+ const { card } = found;
539
+ if (!card.assignee_agent_id)
540
+ return { error: "carte sans agent assigné — assigne un agent Cogitator d'abord", status: 400 };
541
+ const preset = getAgent(deps.db, card.assignee_agent_id);
542
+ if (!preset)
543
+ return { error: "agent assigné introuvable (supprimé ?)", status: 400 };
544
+ const conv = createConversation(deps.db, {
545
+ workspaceId: ws.id,
546
+ agentId: preset.id,
547
+ spawn: spawnConfigFromPreset(preset),
548
+ });
549
+ setConversationTitle(deps.db, conv.id, `#${card.number} ${card.title}`);
550
+ const titled = getConversation(deps.db, conv.id);
551
+ await deps.spawner.ensure(titled);
552
+ await deps.pool.prompt(titled.id, ticketPrompt(card, extra));
553
+ const moved = await moveCardGh(ws.dir, card.number, "in_progress");
554
+ if ("error" in moved)
555
+ return { conversation: titled, card };
556
+ const linked = await updateCardGh(ws.dir, card.number, {
557
+ title: moved.card.title,
558
+ conversation_ids: [...new Set([...card.conversation_ids, conv.id])],
559
+ });
560
+ return { conversation: titled, card: "error" in linked ? moved.card : linked.card };
561
+ }
562
+ function ticketPrompt(card, extra) {
563
+ return [
564
+ `Ticket #${card.number} — ${card.title}`,
565
+ card.description ? `\n${card.description}` : "",
566
+ extra ? `\nPrécision : ${extra}` : "",
567
+ `\n(issue GitHub : ${card.url} — mets à jour le board au besoin via les outils cogitator_board_*)`,
568
+ ].join("");
569
+ }
570
+ /** Snapshot de spawn d'un preset (O6 du contrat) — partagé avec le cron via spawn.js. */
571
+ /** Conversations : création (agent hérité ou provider libre), SSE par session, messages. */
572
+ function conversationRoutes(deps) {
573
+ const { db, pool } = deps;
574
+ return [
575
+ ["GET", "/api/conversations", (ctx) => {
576
+ const workspaceId = ctx.query.get("workspace_id");
577
+ sendJson(ctx.res, 200, { conversations: listConversations(db, workspaceId ?? undefined) });
578
+ }],
579
+ ["POST", "/api/conversations", async (ctx) => {
580
+ const b = parseBody(ctx.res, conversationCreateSchema, ctx.body);
581
+ if (!b)
582
+ return;
583
+ const resolved = resolveSpawnTarget(deps, b);
584
+ if ("error" in resolved)
585
+ return sendJson(ctx.res, resolved.status, { error: resolved.error });
586
+ let conv = createConversation(db, { workspaceId: b.workspace_id ?? null, agentId: resolved.agentId, spawn: resolved.spawn });
587
+ const prompt = b.prompt?.trim();
588
+ if (prompt) {
589
+ await deps.spawner.ensure(conv);
590
+ await pool.prompt(conv.id, prompt);
591
+ setConversationTitle(db, conv.id, prompt);
592
+ conv = getConversation(db, conv.id);
593
+ }
594
+ sendJson(ctx.res, 201, { conversation: conv });
595
+ }],
596
+ ["GET", "/api/conversations/:id", (ctx) => {
597
+ const conv = requireConversation(deps, ctx);
598
+ if (!conv)
599
+ return;
600
+ sendJson(ctx.res, 200, { conversation: conv, live: pool.isLive(conv.id) });
601
+ }],
602
+ ["GET", "/api/conversations/:id/events", async (ctx) => {
603
+ const conv = requireConversation(deps, ctx);
604
+ if (!conv)
605
+ return;
606
+ const spawned = await deps.spawner.ensure(conv);
607
+ const send = openSse(ctx.res, { type: "session", sessionFile: spawned.sessionFile ?? conv.session_file });
608
+ const subs = deps.sseSubs.get(conv.id) ?? new Set();
609
+ deps.sseSubs.set(conv.id, subs);
610
+ subs.add(send);
611
+ ctx.req.on("close", () => {
612
+ subs.delete(send);
613
+ });
614
+ }],
615
+ ["GET", "/api/conversations/:id/history", (ctx) => {
616
+ const conv = requireConversation(deps, ctx);
617
+ if (!conv)
618
+ return;
619
+ const sessionFile = conv.session_file ?? "";
620
+ sendJson(ctx.res, 200, { messages: readHistory(sessionFile), entries: readEntries(sessionFile) });
621
+ }],
622
+ ["GET", "/api/conversations/:id/files", (ctx) => {
623
+ const conv = requireConversation(deps, ctx);
624
+ if (!conv)
625
+ return;
626
+ sendJson(ctx.res, 200, { files: readFileChanges(conv.session_file ?? "") });
627
+ }],
628
+ ["GET", "/api/conversations/:id/file", (ctx) => {
629
+ const conv = requireConversation(deps, ctx);
630
+ if (!conv)
631
+ return;
632
+ const path = ctx.query.get("path");
633
+ if (!path)
634
+ return sendJson(ctx.res, 400, { error: "path requis" });
635
+ sendJson(ctx.res, 200, { path, operations: readFileDetail(conv.session_file ?? "", path) });
636
+ }],
637
+ ["POST", "/api/conversations/:id/messages", async (ctx) => {
638
+ const conv = requireConversation(deps, ctx);
639
+ if (!conv)
640
+ return;
641
+ const b = parseBody(ctx.res, messageSchema, ctx.body);
642
+ if (!b)
643
+ return;
644
+ const text = (b.text ?? "").trim();
645
+ await deps.spawner.ensure(conv);
646
+ await pool.prompt(conv.id, text, b.images);
647
+ if (text)
648
+ setConversationTitle(db, conv.id, text);
649
+ sendJson(ctx.res, 200, { ok: true });
650
+ }],
651
+ ["POST", "/api/conversations/:id/stop", async (ctx) => {
652
+ const conv = requireConversation(deps, ctx);
653
+ if (!conv)
654
+ return;
655
+ await pool.abort(conv.id);
656
+ sendJson(ctx.res, 200, { ok: true });
657
+ }],
658
+ ["POST", "/api/conversations/:id/model", async (ctx) => {
659
+ const conv = requireConversation(deps, ctx);
660
+ if (!conv)
661
+ return;
662
+ const b = parseBody(ctx.res, modelSwitchSchema, ctx.body);
663
+ if (!b)
664
+ return;
665
+ await pool.setModel(conv.id, b.provider, b.id);
666
+ const spawn = { ...JSON.parse(conv.spawn_args || "{}"), provider: b.provider, model: b.id };
667
+ setConversationModel(db, conv.id, b.provider, b.id, spawn);
668
+ sendJson(ctx.res, 200, { ok: true });
669
+ }],
670
+ ["DELETE", "/api/conversations/:id", async (ctx) => {
671
+ const conv = requireConversation(deps, ctx);
672
+ if (!conv)
673
+ return;
674
+ await pool.evict(conv.id);
675
+ deleteConversation(db, conv.id);
676
+ sendJson(ctx.res, 200, { ok: true }); // le .jsonl pi survit sur disque (I5)
677
+ }],
678
+ ];
679
+ }
680
+ /** Choisit l'agent (preset explicite, hérité du workspace, ou défaut global) ou le provider libre. */
681
+ function resolveSpawnTarget(deps, b) {
682
+ const { db } = deps;
683
+ const workspace = b.workspace_id ? getWorkspace(db, b.workspace_id) : null;
684
+ if (b.workspace_id && !workspace)
685
+ return { error: "workspace introuvable", status: 404 };
686
+ // héritage : agent par défaut du workspace quand rien de précisé
687
+ const agentId = b.agent_id ?? (b.provider ? null : workspace?.default_agent_id ?? null);
688
+ if (agentId) {
689
+ const preset = getAgent(db, agentId);
690
+ if (!preset)
691
+ return { error: "agent introuvable", status: 404 };
692
+ return { agentId: preset.id, spawn: spawnConfigFromPreset(preset) };
693
+ }
694
+ if (b.provider && b.model) {
695
+ return {
696
+ agentId: null,
697
+ spawn: {
698
+ provider: b.provider, model: b.model, thinking: b.thinking ?? null,
699
+ systemPrompt: b.system_prompt, skills: b.skills, tools: b.tools, mcpServers: b.mcp_servers,
700
+ },
701
+ };
702
+ }
703
+ // repli : agent par défaut global (le Majordome si seedé)
704
+ const fallbackId = getDefaultAgentId(db);
705
+ if (!fallbackId)
706
+ return { error: "aucun agent par défaut — précise agent_id ou provider+model", status: 400 };
707
+ const preset = getAgent(db, fallbackId);
708
+ if (!preset)
709
+ return { error: "agent introuvable", status: 404 };
710
+ return { agentId: preset.id, spawn: spawnConfigFromPreset(preset) };
711
+ }
712
+ /** Tâches planifiées (cron) + historique de runs. */
713
+ function scheduleRoutes(deps) {
714
+ const { db, cron } = deps;
715
+ return [
716
+ ["GET", "/api/schedules", (ctx) => {
717
+ sendJson(ctx.res, 200, { schedules: listTasks(db) });
718
+ }],
719
+ ["POST", "/api/schedules", (ctx) => {
720
+ const b = parseBody(ctx.res, scheduleCreateSchema, ctx.body);
721
+ if (!b)
722
+ return;
723
+ const { task, error } = createTask(db, b);
724
+ if (error)
725
+ return sendJson(ctx.res, 400, { error });
726
+ sendJson(ctx.res, 201, { schedule: task });
727
+ }],
728
+ ["PUT", "/api/schedules/:id", (ctx) => {
729
+ const b = parseBody(ctx.res, scheduleUpdateSchema, ctx.body);
730
+ if (!b)
731
+ return;
732
+ const task = updateTask(db, ctx.params.id, b);
733
+ if (!task)
734
+ return sendJson(ctx.res, 400, { error: "schedule introuvable ou expression cron invalide" });
735
+ sendJson(ctx.res, 200, { schedule: task });
736
+ }],
737
+ ["DELETE", "/api/schedules/:id", (ctx) => {
738
+ if (!deleteTask(db, ctx.params.id))
739
+ return notFound(ctx.res, "schedule");
740
+ sendJson(ctx.res, 200, { ok: true });
741
+ }],
742
+ ["POST", "/api/schedules/:id/run", (ctx) => {
743
+ if (!cron)
744
+ return sendJson(ctx.res, 503, { error: "cron indisponible" });
745
+ const task = getTask(db, ctx.params.id);
746
+ if (!task)
747
+ return notFound(ctx.res, "schedule");
748
+ // fire-and-forget : le run est tracé et observable via /runs + /events
749
+ void cron.fireNow(task.id).catch(() => undefined);
750
+ sendJson(ctx.res, 202, { ok: true });
751
+ }],
752
+ ["GET", "/api/schedules/:id/runs", (ctx) => {
753
+ const limit = Number(ctx.query.get("limit") ?? DEFAULT_RUNS_LIMIT);
754
+ sendJson(ctx.res, 200, { runs: listRuns(db, ctx.params.id, Number.isFinite(limit) ? limit : DEFAULT_RUNS_LIMIT) });
755
+ }],
756
+ ];
757
+ }
758
+ const DEFAULT_RUNS_LIMIT = 50;
759
+ function healthRoute(deps) {
760
+ const { dbPath, dbVersion, paths, pool } = deps;
761
+ return ["GET", "/api/health", (ctx) => {
762
+ sendJson(ctx.res, 200, {
763
+ ok: true,
764
+ version: packageVersion(),
765
+ pi_version: piVersion(),
766
+ sessions_active: pool.size,
767
+ mcp_adapter_detected: mcpAdapterDetected(paths),
768
+ db: { path: dbPath, version: dbVersion },
769
+ });
770
+ }];
771
+ }
772
+ export function createApp(opts) {
773
+ const { db, paths, pool, cron } = opts;
774
+ const events = opts.events ?? new EventEmitter();
775
+ events.setMaxListeners(MAX_SSE_LISTENERS);
776
+ // Fan-out des événements pi vers les abonnés SSE par conversation
777
+ const sseSubs = new Map();
778
+ pool.onEvent((convId, event) => {
779
+ for (const send of sseSubs.get(convId) ?? [])
780
+ send(event);
781
+ });
782
+ const deps = {
783
+ db,
784
+ dbPath: opts.dbPath,
785
+ dbVersion: opts.dbVersion,
786
+ paths,
787
+ pool,
788
+ cron,
789
+ events,
790
+ sseSubs,
791
+ spawner: makeSpawner({ db, pool, paths }),
792
+ };
793
+ const routes = [
794
+ healthRoute(deps),
795
+ ...registryRoutes(deps),
796
+ ...agentRoutes(deps),
797
+ ...workspaceRoutes(deps),
798
+ ...boardRoutes(deps),
799
+ ...conversationRoutes(deps),
800
+ ...scheduleRoutes(deps),
801
+ // Events global (SSE) — les runs cron et les statuts de conversation
802
+ ["GET", "/api/events", (ctx) => {
803
+ const send = openSse(ctx.res);
804
+ events.on("event", send);
805
+ ctx.req.on("close", () => events.off("event", send));
806
+ }],
807
+ ];
808
+ return createServer(async (req, res) => {
809
+ const url = new URL(req.url ?? "/", `http://${HOST}`);
810
+ if (!url.pathname.startsWith("/api/")) {
811
+ if (serveStatic(res, url.pathname))
812
+ return;
813
+ res.writeHead(404, { "content-type": "text/plain" });
814
+ res.end("not found");
815
+ return;
816
+ }
817
+ try {
818
+ const body = req.method === "POST" || req.method === "PUT" ? await readBody(req) : {};
819
+ const found = matchRoute(routes, req.method ?? "GET", url.pathname);
820
+ if (!found)
821
+ return sendJson(res, 404, { error: `not found: ${url.pathname}` });
822
+ await found.handler({ params: found.params, query: url.searchParams, body, req, res });
823
+ }
824
+ catch (err) {
825
+ sendJson(res, 500, { error: err instanceof Error ? err.message : String(err) });
826
+ }
827
+ });
828
+ }
829
+ export { sendJson, API_PROTOCOLS };