@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,113 @@
1
+ import { parseJsonLine, readSessionLines } from "./session-lines.js";
2
+ const TEXT_CAP = 3000;
3
+ /** Fenêtre de relecture du transcript pour les événements fichier. */
4
+ const FILE_EVENTS_LINES_SCAN = 3000;
5
+ /** Une opération edit/write reconnue par ses noms d'outils pi. */
6
+ const FILE_TOOLS = new Set(["edit", "write"]);
7
+ function cap(s) {
8
+ return s.length > TEXT_CAP ? s.slice(0, TEXT_CAP) + "\n… (tronqué)" : s;
9
+ }
10
+ function countLines(s) {
11
+ if (!s)
12
+ return 0;
13
+ return s.split("\n").filter((l) => l.length > 0).length;
14
+ }
15
+ /** Parse le .jsonl et retourne les événements edit/write dans l'ordre chronologique. */
16
+ export function readFileEvents(sessionFile, limit = 500) {
17
+ const events = [];
18
+ for (const line of readSessionLines(sessionFile, FILE_EVENTS_LINES_SCAN)) {
19
+ const entry = parseJsonLine(line);
20
+ if (!entry || entry.type !== "message")
21
+ continue;
22
+ const msg = entry.message;
23
+ if (msg.role !== "assistant" || !Array.isArray(msg.content))
24
+ continue;
25
+ const at = typeof entry.timestamp === "string" ? entry.timestamp : "";
26
+ for (const block of msg.content) {
27
+ if (block?.type !== "toolCall")
28
+ continue;
29
+ const name = block.name;
30
+ if (typeof name !== "string" || !FILE_TOOLS.has(name))
31
+ continue;
32
+ let args = {};
33
+ try {
34
+ args = typeof block.arguments === "string"
35
+ ? JSON.parse(block.arguments)
36
+ : block.arguments;
37
+ }
38
+ catch {
39
+ continue;
40
+ }
41
+ const path = typeof args.path === "string" ? args.path : null;
42
+ if (!path)
43
+ continue;
44
+ if (name === "write") {
45
+ const content = typeof args.content === "string" ? args.content : "";
46
+ events.push({
47
+ path, kind: "write", at,
48
+ additions: countLines(content), deletions: 0,
49
+ hunks: [{ old: "", new: cap(content) }],
50
+ });
51
+ }
52
+ else {
53
+ // pi : { path, edits: [{ oldText, newText }] } ; variantes oldString/newString tolérées
54
+ const subs = Array.isArray(args.edits) ? args.edits : [args];
55
+ events.push({ path, kind: "edit", at, ...countEditHunks(subs) });
56
+ }
57
+ }
58
+ }
59
+ return events.slice(-limit);
60
+ }
61
+ /** Additionne les hunks d'une opération edit (additions/deletions par ligne nouvelle/ancienne). */
62
+ function countEditHunks(subs) {
63
+ const hunks = [];
64
+ let additions = 0;
65
+ let deletions = 0;
66
+ for (const sub of subs) {
67
+ const oldText = firstString(sub, "oldText", "oldString");
68
+ const newText = firstString(sub, "newText", "newString");
69
+ hunks.push({ old: cap(oldText), new: cap(newText) });
70
+ additions += countLines(newText);
71
+ deletions += countLines(oldText);
72
+ }
73
+ return { additions, deletions, hunks };
74
+ }
75
+ /** Première des clés présentes dont la valeur est une chaîne (variantes de nommage pi). */
76
+ function firstString(source, ...keys) {
77
+ for (const key of keys) {
78
+ const value = source[key];
79
+ if (typeof value === "string")
80
+ return value;
81
+ }
82
+ return "";
83
+ }
84
+ /** Agrège les événements par chemin (ordre anti-chronologique via lastAt). */
85
+ export function readFileChanges(sessionFile, limit = 500) {
86
+ const byPath = new Map();
87
+ for (const e of readFileEvents(sessionFile, limit * 2)) {
88
+ const existing = byPath.get(e.path);
89
+ if (existing) {
90
+ existing.edits += 1;
91
+ existing.additions += e.additions;
92
+ existing.deletions += e.deletions;
93
+ existing.kind = existing.kind === "write" ? "write" : e.kind;
94
+ if (e.at > existing.lastAt)
95
+ existing.lastAt = e.at;
96
+ }
97
+ else {
98
+ byPath.set(e.path, {
99
+ path: e.path, kind: e.kind, edits: 1,
100
+ additions: e.additions, deletions: e.deletions, lastAt: e.at,
101
+ });
102
+ }
103
+ }
104
+ return [...byPath.values()]
105
+ .sort((a, b) => b.lastAt.localeCompare(a.lastAt))
106
+ .slice(0, limit);
107
+ }
108
+ /** Détail d'un fichier : toutes les opérations qui le touchent (pour le diff). */
109
+ export function readFileDetail(sessionFile, path, limit = 50) {
110
+ return readFileEvents(sessionFile, limit * 3)
111
+ .filter((e) => e.path === path)
112
+ .slice(-limit);
113
+ }
@@ -0,0 +1,88 @@
1
+ import { parseJsonLine, readSessionLines } from "./session-lines.js";
2
+ const RESULT_CAP = 4000;
3
+ /** Fenêtre de relecture du transcript (nombre de lignes les plus récentes). */
4
+ const HISTORY_LINES_SCAN = 2000;
5
+ function extractText(content) {
6
+ if (!Array.isArray(content))
7
+ return typeof content === "string" ? content : "";
8
+ return content
9
+ .filter((b) => b?.type === "text" && typeof b.text === "string")
10
+ .map((b) => b.text)
11
+ .join("");
12
+ }
13
+ function prettyArgs(args) {
14
+ try {
15
+ const s = typeof args === "string" ? args : JSON.stringify(args, null, 2);
16
+ return s.length > RESULT_CAP ? s.slice(0, RESULT_CAP) + "\n… (tronqué)" : s;
17
+ }
18
+ catch {
19
+ return String(args);
20
+ }
21
+ }
22
+ function blockIsError(content) {
23
+ if (!Array.isArray(content))
24
+ return false;
25
+ return content.some((b) => b?.isError === true);
26
+ }
27
+ /** Parse le .jsonl pi en entrées ordonnées : user / assistant / thinking / tool (avec résultat). */
28
+ export function readEntries(sessionFile, limit = 300) {
29
+ const out = [];
30
+ const pendingTools = new Map(); // toolCallId → index dans out
31
+ for (const line of readSessionLines(sessionFile, HISTORY_LINES_SCAN)) {
32
+ const entry = parseJsonLine(line);
33
+ if (!entry || entry.type !== "message")
34
+ continue;
35
+ const msg = entry.message;
36
+ const content = msg.content;
37
+ if (msg.role === "user") {
38
+ const text = extractText(content).trim();
39
+ if (text)
40
+ out.push({ type: "user", text });
41
+ continue;
42
+ }
43
+ if (msg.role === "assistant" && Array.isArray(content)) {
44
+ for (const block of content) {
45
+ if (block?.type === "thinking" && typeof block.thinking === "string" && block.thinking.trim()) {
46
+ out.push({ type: "thinking", text: block.thinking });
47
+ }
48
+ else if (block?.type === "text" && typeof block.text === "string" && block.text.trim()) {
49
+ const last = out[out.length - 1];
50
+ if (last?.type === "assistant")
51
+ last.text += (last.text ? "\n" : "") + block.text;
52
+ else
53
+ out.push({ type: "assistant", text: block.text });
54
+ }
55
+ else if (block?.type === "toolCall") {
56
+ const id = typeof block.id === "string" ? block.id : `tool-${out.length}`;
57
+ pendingTools.set(id, out.length);
58
+ out.push({
59
+ type: "tool",
60
+ id,
61
+ name: typeof block.name === "string" ? block.name : "outil",
62
+ args: prettyArgs(block.arguments),
63
+ });
64
+ }
65
+ }
66
+ continue;
67
+ }
68
+ if (msg.role === "toolResult" && Array.isArray(content)) {
69
+ // pi stocke le toolCallId au niveau du message (pas du block)
70
+ const callId = typeof msg.toolCallId === "string" ? msg.toolCallId : undefined;
71
+ const index = callId !== undefined ? pendingTools.get(callId) : undefined;
72
+ const text = extractText(content);
73
+ const capped = text.length > RESULT_CAP ? text.slice(0, RESULT_CAP) + "\n… (tronqué)" : text;
74
+ if (index !== undefined && out[index]?.type === "tool") {
75
+ const tool = out[index];
76
+ tool.result = capped;
77
+ tool.isError = entry.isError === true || blockIsError(content);
78
+ }
79
+ }
80
+ }
81
+ return out.slice(-limit);
82
+ }
83
+ /** Compat : liste plate role/text (user + assistant uniquement). */
84
+ export function readHistory(sessionFile, limit = 200) {
85
+ return readEntries(sessionFile, limit)
86
+ .filter((e) => e.type === "user" || e.type === "assistant")
87
+ .map((e) => ({ role: e.type, text: e.text }));
88
+ }
@@ -0,0 +1,18 @@
1
+ import { copyFileSync, existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
2
+ /** Lit un JSON tolérant (fichier absent → fallback). */
3
+ export function readJson(path, fallback) {
4
+ try {
5
+ return JSON.parse(readFileSync(path, "utf8"));
6
+ }
7
+ catch {
8
+ return fallback;
9
+ }
10
+ }
11
+ /** Écriture atomique : tmp + rename, backup `.bak` de l'ancien. */
12
+ export function atomicWriteJson(path, value) {
13
+ const tmp = `${path}.tmp-${process.pid}`;
14
+ writeFileSync(tmp, JSON.stringify(value, null, 2) + "\n");
15
+ if (existsSync(path))
16
+ copyFileSync(path, `${path}.bak`);
17
+ renameSync(tmp, path);
18
+ }
@@ -0,0 +1,29 @@
1
+ /** Nom de la variable d'environnement qui transporte les serveurs MCP d'un preset vers la session pi. */
2
+ export const MCP_ENV_VAR = "COGITATOR_MCP";
3
+ /** Sérialise les entrées pour l'env (seules les entrées valides passent : name + command|url). */
4
+ export function encodeMcpEnv(entries) {
5
+ const valid = entries.filter((e) => e.name && (e.command || e.url));
6
+ return valid.length ? JSON.stringify(valid) : undefined;
7
+ }
8
+ /** Parse l'env côté extension ; null si absent/invalide. */
9
+ export function decodeMcpEnv(raw) {
10
+ if (!raw)
11
+ return null;
12
+ let parsed;
13
+ try {
14
+ parsed = JSON.parse(raw);
15
+ }
16
+ catch {
17
+ return null;
18
+ }
19
+ if (!Array.isArray(parsed))
20
+ return null;
21
+ const out = [];
22
+ for (const item of parsed) {
23
+ if (!item || typeof item !== "object" || !item.name || (!item.command && !item.url))
24
+ continue;
25
+ const { name, ...config } = item;
26
+ out.push({ name, config });
27
+ }
28
+ return out;
29
+ }
@@ -0,0 +1,167 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Serveur MCP Cogitator (stdio) — expose l'API Cogitator en outils pour les agents pi.
4
+ * Transporte toutes les requêtes vers le serveur HTTP local (COGITATOR_URL).
5
+ *
6
+ * C'est le mécanisme du "Majordome" : un agent pi qui manipule Cogitator
7
+ * (agents, crons, workspaces, conversations) via des outils MCP natifs.
8
+ */
9
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
10
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
11
+ import { z } from "zod";
12
+ import { BASE_URL } from "./config.js";
13
+ import { packageVersion } from "./pi.js";
14
+ import { CARD_PRIORITIES, CARD_STATUSES, thinkingSchema } from "./schemas.js";
15
+ const BASE = BASE_URL;
16
+ async function call(method, path, body) {
17
+ const res = await fetch(`${BASE}${path}`, {
18
+ method,
19
+ headers: body !== undefined ? { "content-type": "application/json" } : undefined,
20
+ body: body !== undefined ? JSON.stringify(body) : undefined,
21
+ });
22
+ const data = (await res.json().catch(() => ({})));
23
+ if (!res.ok)
24
+ throw new Error(data.error ?? `HTTP ${res.status}`);
25
+ return data;
26
+ }
27
+ const server = new McpServer({
28
+ name: "cogitator",
29
+ version: packageVersion(),
30
+ });
31
+ /** Enveloppe un outil : résultat JSON en texte, erreur remontée à l'agent (jamais d'exception brute). */
32
+ function addTool(name, description, inputSchema, fn) {
33
+ server.registerTool(name, { description, inputSchema }, async (args) => {
34
+ try {
35
+ return { content: [{ type: "text", text: JSON.stringify(await fn(args), null, 2) }] };
36
+ }
37
+ catch (err) {
38
+ return { content: [{ type: "text", text: `Erreur: ${err instanceof Error ? err.message : String(err)}` }], isError: true };
39
+ }
40
+ });
41
+ }
42
+ // ---------- Agents ----------
43
+ addTool("cogitator_list_agents", "Liste les presets d'agents Cogitator (sans prompts).", {}, () => call("GET", "/api/agents"));
44
+ addTool("cogitator_get_agent", "Détail complet d'un agent (prompt, skills, MCP, subagents).", { id: z.string() }, (a) => call("GET", `/api/agents/${a.id}`));
45
+ addTool("cogitator_create_agent", "Crée un agent (preset) : provider+modèle+thinking+skills+MCP+prompt+subagents. Génère les définitions herdr au save.", {
46
+ name: z.string().describe("Nom d'affichage"),
47
+ provider: z.string().describe("ex: openai, deepseek, kimi-coding"),
48
+ model: z.string().describe("id du modèle dans le provider"),
49
+ description: z.string().optional(),
50
+ thinking: thinkingSchema.optional(),
51
+ system_prompt: z.string().optional().describe("Prompt de scope de l'agent"),
52
+ skills: z.array(z.string()).optional().describe("Chemins absolus de skills"),
53
+ tools: z.array(z.string()).optional().describe("Allowlist d'outils (absent = tous)"),
54
+ }, (a) => call("POST", "/api/agents", a));
55
+ addTool("cogitator_update_agent", "Modifie un agent existant (mêmes champs que create, écrase la config).", {
56
+ id: z.string(),
57
+ name: z.string(),
58
+ provider: z.string(),
59
+ model: z.string(),
60
+ description: z.string().optional(),
61
+ thinking: thinkingSchema.nullable().optional(),
62
+ system_prompt: z.string().optional(),
63
+ skills: z.array(z.string()).optional(),
64
+ tools: z.array(z.string()).nullable().optional(),
65
+ }, (a) => {
66
+ const { id, ...body } = a;
67
+ return call("PUT", `/api/agents/${id}`, body);
68
+ });
69
+ addTool("cogitator_delete_agent", "Supprime un agent et ses définitions herdr noo-*.", { id: z.string() }, (a) => call("DELETE", `/api/agents/${a.id}`));
70
+ addTool("cogitator_validate_agent", "Valide un agent (provider/modèle du catalogue, skills, MCP, auth).", { id: z.string() }, (a) => call("POST", `/api/agents/${a.id}/validate`));
71
+ addTool("cogitator_set_default_agent", "Définit l'agent par défaut global (utilisé quand une conversation ne précise rien).", { id: z.string() }, (a) => call("POST", `/api/agents/${a.id}/default`));
72
+ // ---------- Schedules (cron) ----------
73
+ addTool("cogitator_list_schedules", "Liste les tâches cron (avec prochain run calculé).", {}, () => call("GET", "/api/schedules"));
74
+ addTool("cogitator_create_schedule", "Crée une tâche cron : un prompt tiré contre un agent à heure fixe.", {
75
+ name: z.string(),
76
+ cron_expr: z.string().describe("5 champs: min heure jour mois jour-sem — ex: '0 9 * * 1-5'"),
77
+ prompt: z.string(),
78
+ agent_id: z.string(),
79
+ workspace_id: z.string(),
80
+ output_policy: z.enum(["append_session", "new_session"]).optional(),
81
+ busy_policy: z.enum(["skip", "queue", "kill"]).optional(),
82
+ catchup: z.boolean().optional(),
83
+ }, (a) => call("POST", "/api/schedules", a));
84
+ addTool("cogitator_update_schedule", "Modifie une tâche cron (champs partiels, enabled inclus).", {
85
+ id: z.string(),
86
+ name: z.string().optional(),
87
+ cron_expr: z.string().optional(),
88
+ prompt: z.string().optional(),
89
+ output_policy: z.enum(["append_session", "new_session"]).optional(),
90
+ busy_policy: z.enum(["skip", "queue", "kill"]).optional(),
91
+ catchup: z.boolean().optional(),
92
+ enabled: z.boolean().optional(),
93
+ }, (a) => {
94
+ const { id, ...body } = a;
95
+ return call("PUT", `/api/schedules/${id}`, body);
96
+ });
97
+ addTool("cogitator_delete_schedule", "Supprime une tâche cron et l'historique de ses runs.", { id: z.string() }, (a) => call("DELETE", `/api/schedules/${a.id}`));
98
+ addTool("cogitator_fire_schedule", "Déclenche immédiatement une tâche cron.", { id: z.string() }, (a) => call("POST", `/api/schedules/${a.id}/run`));
99
+ addTool("cogitator_list_runs", "Historique des runs d'une tâche cron (status, session, erreur).", { id: z.string() }, (a) => call("GET", `/api/schedules/${a.id}/runs`));
100
+ // ---------- Workspaces ----------
101
+ addTool("cogitator_list_workspaces", "Liste les workspaces (dossiers + nb de conversations).", {}, () => call("GET", "/api/workspaces"));
102
+ addTool("cogitator_create_workspace", "Enregistre un dossier comme workspace.", { dir: z.string().describe("Chemin absolu du dossier (doit exister)"), name: z.string().optional() }, (a) => call("POST", "/api/workspaces", a));
103
+ addTool("cogitator_delete_workspace", "Supprime un workspace (les conversations deviennent libres).", { id: z.string() }, (a) => call("DELETE", `/api/workspaces/${a.id}`));
104
+ // ---------- Conversations ----------
105
+ addTool("cogitator_list_conversations", "Liste les conversations (toutes, ou filtrées par workspace).", { workspace_id: z.string().optional() }, (a) => call("GET", `/api/conversations${a.workspace_id ? `?workspace_id=${a.workspace_id}` : ""}`));
106
+ addTool("cogitator_create_conversation", "Crée une conversation avec un agent (ou provider libre) et un prompt initial optionnel.", {
107
+ agent_id: z.string().optional(),
108
+ provider: z.string().optional(),
109
+ model: z.string().optional(),
110
+ workspace_id: z.string().optional(),
111
+ prompt: z.string().optional(),
112
+ }, (a) => call("POST", "/api/conversations", a));
113
+ // ---------- Registry ----------
114
+ addTool("cogitator_list_providers", "Liste les providers pi (catalogue + statut auth + modèles).", {}, () => call("GET", "/api/providers"));
115
+ addTool("cogitator_list_skills", "Liste les skills disponibles (name, description, path).", {}, () => call("GET", "/api/skills"));
116
+ addTool("cogitator_import_skills", "Importe des skills : repo GitHub (ex: IgnitionAI/skills), dossier local, ou commande CLI (ex: 'npx aiblueprint-cli@latest skills update'). Les dossiers contenant un SKILL.md sont copiés vers ~/.agents/skills/.", {
117
+ source: z.string().describe("URL GitHub (https://github.com/owner/repo) ou chemin absolu d'un dossier local"),
118
+ overwrite: z.boolean().optional().describe("Écrase les skills existants du même nom (défaut: skip)"),
119
+ }, (a) => call("POST", "/api/skills/import", a));
120
+ addTool("cogitator_health", "État du serveur Cogitator (version, pi, sessions, base).", {}, () => call("GET", "/api/health"));
121
+ // ---------- Board kanban (gestion de projet du workspace) ----------
122
+ addTool("cogitator_board_list", "Liste les cartes du board kanban d'un workspace (statut, priorité, labels, assigné, relations).", { workspace_id: z.string() }, (a) => call("GET", `/api/workspaces/${a.workspace_id}/board`));
123
+ addTool("cogitator_board_create_card", "Crée une carte sur le board : titre, description, statut, priorité, labels, assigné (agent id), conversations liées, relations blocks/blocked_by.", {
124
+ workspace_id: z.string(),
125
+ title: z.string(),
126
+ description: z.string().optional(),
127
+ status: z.enum(CARD_STATUSES).optional(),
128
+ priority: z.enum(CARD_PRIORITIES).optional(),
129
+ labels: z.array(z.string()).optional(),
130
+ assignee_agent_id: z.string().nullable().optional(),
131
+ conversation_ids: z.array(z.string()).optional(),
132
+ }, (a) => call("POST", `/api/workspaces/${a.workspace_id}/board/cards`, a));
133
+ addTool("cogitator_board_update_card", "Met à jour une carte (mêmes champs que create ; écrase la config). Relations : blocks/blocked_by (ids de cartes).", {
134
+ workspace_id: z.string(),
135
+ card_id: z.string(),
136
+ title: z.string().optional(),
137
+ description: z.string().optional(),
138
+ status: z.enum(CARD_STATUSES).optional(),
139
+ priority: z.enum(CARD_PRIORITIES).optional(),
140
+ labels: z.array(z.string()).optional(),
141
+ assignee_agent_id: z.string().nullable().optional(),
142
+ conversation_ids: z.array(z.string()).optional(),
143
+ blocks: z.array(z.string()).optional(),
144
+ blocked_by: z.array(z.string()).optional(),
145
+ }, (a) => {
146
+ const { workspace_id, card_id, ...body } = a;
147
+ return call("PUT", `/api/workspaces/${workspace_id}/board/cards/${card_id}`, body);
148
+ });
149
+ addTool("cogitator_board_move", "Déplace une carte vers une colonne (statut).", {
150
+ workspace_id: z.string(),
151
+ card_id: z.string(),
152
+ status: z.enum(CARD_STATUSES),
153
+ }, (a) => call("POST", `/api/workspaces/${a.workspace_id}/board/cards/${a.card_id}/move`, { status: a.status }));
154
+ addTool("cogitator_board_start_work", "Lance l'agent Cogitator assigné sur un ticket : spawn une conversation dans le workspace avec le contenu de la carte, lie la conversation (rollup activité) et passe la carte en in_progress. Nécessite un assignee_agent_id (extra Cogitator) sur la carte.", {
155
+ workspace_id: z.string(),
156
+ card_id: z.string(),
157
+ extra: z.string().optional().describe("Précision complémentaire à ajouter au prompt"),
158
+ }, (a) => call("POST", `/api/workspaces/${a.workspace_id}/board/cards/${a.card_id}/start`, { extra: a.extra }));
159
+ addTool("cogitator_board_comment", "Ajoute un commentaire à une carte (append-only). Auteur par défaut : Majordome.", {
160
+ workspace_id: z.string(),
161
+ card_id: z.string(),
162
+ text: z.string(),
163
+ author: z.string().optional(),
164
+ }, (a) => call("POST", `/api/workspaces/${a.workspace_id}/board/cards/${a.card_id}/comments`, { text: a.text, author: a.author ?? "Majordome" }));
165
+ const transport = new StdioServerTransport();
166
+ await server.connect(transport);
167
+ console.error(`[cogitator-mcp] connecté à ${BASE}`);
@@ -0,0 +1,22 @@
1
+ import { join } from "node:path";
2
+ // Tous overridables par env pour les tests : COGITATOR_HOME, COGITATOR_PI_AGENT_DIR,
3
+ // COGITATOR_AGENTS_DIR, COGITATOR_SKILLS_DIRS (séparés par ":")
4
+ export function getPaths(env = process.env) {
5
+ const home = env.COGITATOR_HOME ?? join(env.HOME ?? "~", ".cogitator");
6
+ const piAgentDir = env.COGITATOR_PI_AGENT_DIR ?? join(env.HOME ?? "~", ".pi", "agent");
7
+ const piAgentsDir = env.COGITATOR_AGENTS_DIR ?? join(piAgentDir, "agents");
8
+ const skillsDirs = (env.COGITATOR_SKILLS_DIRS ?? [
9
+ join(env.HOME ?? "~", ".agents", "skills"),
10
+ join(piAgentDir, "skills"),
11
+ ].join(":")).split(":").filter(Boolean);
12
+ return {
13
+ home,
14
+ db: join(home, "cogitator.db"),
15
+ piAgentDir,
16
+ piModelsJson: join(piAgentDir, "models.json"),
17
+ piAuthJson: join(piAgentDir, "auth.json"),
18
+ piMcpJson: join(piAgentDir, "mcp.json"),
19
+ piAgentsDir,
20
+ skillsDirs,
21
+ };
22
+ }
package/dist/src/pi.js ADDED
@@ -0,0 +1,23 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { createRequire } from "node:module";
3
+ const require = createRequire(import.meta.url);
4
+ export function packageVersion() {
5
+ // dist/src/pi.js → ../../package.json ; en dev tsx (src/pi.ts) → ../package.json
6
+ for (const rel of ["../package.json", "../../package.json"]) {
7
+ try {
8
+ return require(rel).version;
9
+ }
10
+ catch {
11
+ // candidate suivant
12
+ }
13
+ }
14
+ return "0.0.0-dev";
15
+ }
16
+ export function piVersion() {
17
+ try {
18
+ return execFileSync("pi", ["--version"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
19
+ }
20
+ catch {
21
+ return null;
22
+ }
23
+ }
@@ -0,0 +1,183 @@
1
+ /**
2
+ * PiProcessPool — un process `pi --mode rpc` par conversation active (I3 : unique point de spawn).
3
+ * Spawn paresseux, recyclage idle, plafond avec éviction du plus vieux non-streaming.
4
+ */
5
+ export class PoolError extends Error {
6
+ code;
7
+ constructor(message, code) {
8
+ super(message);
9
+ this.code = code;
10
+ }
11
+ }
12
+ /** Bornes par défaut du pool (surchargeables par PoolOptions). */
13
+ const DEFAULT_MAX_PROCESSES = 8;
14
+ const DEFAULT_IDLE_MS = 10 * 60_000;
15
+ const DEFAULT_SETTLE_TIMEOUT_MS = 15 * 60_000;
16
+ export class PiPool {
17
+ opts;
18
+ handles = new Map();
19
+ eventListeners = new Set();
20
+ constructor(opts) {
21
+ this.opts = opts;
22
+ }
23
+ /** Abonnement aux événements pi de toutes les conversations (fan-out SSE côté serveur). */
24
+ onEvent(cb) {
25
+ this.eventListeners.add(cb);
26
+ return () => this.eventListeners.delete(cb);
27
+ }
28
+ get size() {
29
+ return this.handles.size;
30
+ }
31
+ isLive(convId) {
32
+ const h = this.handles.get(convId);
33
+ return Boolean(h && !h.dead);
34
+ }
35
+ async streaming(h) {
36
+ try {
37
+ return (await h.client.getState()).isStreaming === true;
38
+ }
39
+ catch {
40
+ return false; // process mort → considéré non-streaming, évincable
41
+ }
42
+ }
43
+ status(convId, status) {
44
+ this.opts.callbacks?.onStatus?.(convId, status);
45
+ }
46
+ /**
47
+ * Assure qu'un process pi existe pour la conversation (spawn paresseux idempotent).
48
+ * Réutilise un process vivant ; reprend la session `.jsonl` si connue.
49
+ */
50
+ async ensure(convId, spawn) {
51
+ const existing = this.handles.get(convId);
52
+ if (existing && !existing.dead) {
53
+ existing.lastActivityAt = Date.now();
54
+ return {};
55
+ }
56
+ await this.makeRoom();
57
+ const args = spawn.resumeSessionFile ? [...spawn.args, "--session", spawn.resumeSessionFile] : spawn.args;
58
+ const client = this.opts.factory({ cwd: spawn.cwd, args, env: spawn.env });
59
+ const handle = { convId, client, lastActivityAt: Date.now(), dead: false };
60
+ this.handles.set(convId, handle);
61
+ this.status(convId, "spawning");
62
+ try {
63
+ await client.start();
64
+ const state = await client.getState();
65
+ client.onEvent((event) => {
66
+ handle.lastActivityAt = Date.now();
67
+ this.opts.callbacks?.onEvent?.(convId, event);
68
+ for (const l of this.eventListeners)
69
+ l(convId, event);
70
+ });
71
+ this.status(convId, "active");
72
+ return { sessionFile: state.sessionFile };
73
+ }
74
+ catch (err) {
75
+ handle.dead = true;
76
+ this.handles.delete(convId);
77
+ this.status(convId, "dead");
78
+ throw err instanceof Error ? err : new Error(String(err));
79
+ }
80
+ }
81
+ /** Libère une place sous le plafond en évincant le plus vieux process non-streaming. */
82
+ async makeRoom() {
83
+ const max = this.opts.max ?? DEFAULT_MAX_PROCESSES;
84
+ if (this.handles.size < max)
85
+ return;
86
+ const oldestFirst = [...this.handles.values()].sort((a, b) => a.lastActivityAt - b.lastActivityAt);
87
+ for (const h of oldestFirst) {
88
+ if (await this.streaming(h))
89
+ continue; // jamais de kill d'un travail en cours
90
+ await this.evict(h.convId);
91
+ return;
92
+ }
93
+ throw new PoolError("pool plein : toutes les sessions sont actives", "pool_full");
94
+ }
95
+ live(convId) {
96
+ const h = this.handles.get(convId);
97
+ if (!h || h.dead)
98
+ throw new PoolError("session non démarrée (pool)", "not_running");
99
+ h.lastActivityAt = Date.now();
100
+ return h;
101
+ }
102
+ async prompt(convId, text, images) {
103
+ const h = this.live(convId);
104
+ try {
105
+ // followUp : file comme le TUI quand un tour est en cours (sinon pi rejette le prompt)
106
+ return await h.client.prompt(text, images, "followUp");
107
+ }
108
+ catch (err) {
109
+ h.dead = true;
110
+ this.status(convId, "dead");
111
+ throw err;
112
+ }
113
+ }
114
+ async abort(convId) {
115
+ try {
116
+ await this.live(convId).client.abort();
117
+ }
118
+ catch {
119
+ /* process déjà mort : abort est best-effort */
120
+ }
121
+ }
122
+ async setModel(convId, provider, modelId) {
123
+ const h = this.live(convId);
124
+ await h.client.setModel(provider, modelId);
125
+ h.lastActivityAt = Date.now();
126
+ }
127
+ async evict(convId) {
128
+ const h = this.handles.get(convId);
129
+ if (!h)
130
+ return false;
131
+ this.handles.delete(convId);
132
+ try {
133
+ await h.client.stop();
134
+ }
135
+ catch {
136
+ /* stop best-effort */
137
+ }
138
+ this.status(convId, "idle");
139
+ return true;
140
+ }
141
+ /** Recyclage idle : les process sans activité depuis idleMs et non-streaming sont stoppés. */
142
+ async sweep(now = Date.now()) {
143
+ const idleMs = this.opts.idleMs ?? DEFAULT_IDLE_MS;
144
+ for (const h of [...this.handles.values()]) {
145
+ if (now - h.lastActivityAt < idleMs)
146
+ continue;
147
+ if (await this.streaming(h)) {
148
+ h.lastActivityAt = now; // toujours en travail : on reporte
149
+ continue;
150
+ }
151
+ await this.evict(h.convId);
152
+ }
153
+ }
154
+ /** Attend l'événement `agent_settled` d'une conversation (suivi des runs cron). Rejette en timeout. */
155
+ waitForSettled(convId, timeoutMs = DEFAULT_SETTLE_TIMEOUT_MS) {
156
+ return new Promise((resolve, reject) => {
157
+ const timer = setTimeout(() => {
158
+ unsub();
159
+ reject(new PoolError(`timeout d'attente de fin d'agent (${timeoutMs}ms)`, "settle_timeout"));
160
+ }, timeoutMs);
161
+ const unsub = this.onEvent((id, event) => {
162
+ if (id !== convId)
163
+ return;
164
+ const type = event?.type;
165
+ if (type === "agent_settled" || type === "agent_end") {
166
+ clearTimeout(timer);
167
+ unsub();
168
+ resolve();
169
+ }
170
+ });
171
+ });
172
+ }
173
+ /** Test-only : backdate la dernière activité d'une conversation. */
174
+ backdate(convId, at) {
175
+ const h = this.handles.get(convId);
176
+ if (h)
177
+ h.lastActivityAt = at;
178
+ }
179
+ async dispose() {
180
+ for (const id of [...this.handles.keys()])
181
+ await this.evict(id);
182
+ }
183
+ }