@ignitionai/cogitator 0.5.0 → 0.5.2

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 (63) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/LICENSE +21 -0
  3. package/README.md +83 -44
  4. package/dist/extensions/index.js +66 -29
  5. package/dist/src/app-updates.js +15 -0
  6. package/dist/src/auth-cli.js +18 -8
  7. package/dist/src/auth-http.js +13 -3
  8. package/dist/src/auth-state.js +41 -6
  9. package/dist/src/board.js +3 -1
  10. package/dist/src/browser-http.js +143 -0
  11. package/dist/src/classic-configuration.js +12 -4
  12. package/dist/src/cli.js +30 -4
  13. package/dist/src/config.js +10 -0
  14. package/dist/src/cron.js +91 -15
  15. package/dist/src/db.js +55 -3
  16. package/dist/src/durable/approvals.js +17 -2
  17. package/dist/src/durable/effect-gateway.js +23 -16
  18. package/dist/src/durable/manager.js +15 -6
  19. package/dist/src/durable/mission-runtime.js +204 -46
  20. package/dist/src/durable/recovery.js +37 -0
  21. package/dist/src/durable/workers.js +22 -14
  22. package/dist/src/execution/confinement.js +2 -1
  23. package/dist/src/execution/worker-supervisor.js +222 -0
  24. package/dist/src/git-import.js +187 -0
  25. package/dist/src/github-login.js +101 -0
  26. package/dist/src/history.js +6 -1
  27. package/dist/src/host-pi.js +64 -0
  28. package/dist/src/json-files.js +7 -4
  29. package/dist/src/machine-metrics.js +49 -0
  30. package/dist/src/machine-types.js +1 -0
  31. package/dist/src/mcp-cli.js +63 -0
  32. package/dist/src/mcp-http.js +164 -0
  33. package/dist/src/mcp-oauth.js +502 -0
  34. package/dist/src/mcp-server.js +6 -136
  35. package/dist/src/mcp-tokens.js +104 -0
  36. package/dist/src/mcp-tools.js +264 -0
  37. package/dist/src/native-auth.js +9 -2
  38. package/dist/src/packages.js +190 -0
  39. package/dist/src/paths.js +1 -0
  40. package/dist/src/pi-child.js +180 -0
  41. package/dist/src/pi-rpc-wrap.js +84 -0
  42. package/dist/src/pool.js +58 -7
  43. package/dist/src/project-setup.js +63 -0
  44. package/dist/src/provider-login.js +73 -14
  45. package/dist/src/reap-orphans.js +138 -0
  46. package/dist/src/registry.js +68 -45
  47. package/dist/src/schemas.js +19 -4
  48. package/dist/src/server-compat.js +173 -0
  49. package/dist/src/server-identity.js +69 -0
  50. package/dist/src/server.js +534 -41
  51. package/dist/src/shared-browser.js +357 -0
  52. package/dist/src/skills-import.js +13 -4
  53. package/dist/src/skills-upload.js +68 -0
  54. package/dist/src/spawner.js +20 -4
  55. package/dist/src/subagents.js +242 -0
  56. package/dist/src/team-queue.js +262 -0
  57. package/package.json +13 -4
  58. package/web/dist/assets/BrandLogo3D-CHGXwTbZ.js +4035 -0
  59. package/web/dist/assets/index-DGLkhrE7.css +1 -0
  60. package/web/dist/assets/index-P0WoXBgX.js +84 -0
  61. package/web/dist/index.html +2 -2
  62. package/web/dist/assets/index-C3tRuOTh.js +0 -83
  63. package/web/dist/assets/index-DMQqB0r1.css +0 -1
@@ -5,152 +5,22 @@
5
5
  *
6
6
  * C'est le mécanisme du "Majordome" : un agent pi qui manipule Cogitator
7
7
  * (agents, crons, workspaces, conversations) via des outils MCP natifs.
8
+ * Les outils sont partagés avec le transport Streamable HTTP (`/mcp`, voir mcp-http.ts).
8
9
  */
9
10
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
10
11
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
11
- import { z } from "zod";
12
+ import { registerCogitatorTools } from "./mcp-tools.js";
12
13
  import { ownerRequest } from "./owner-transport.js";
13
14
  import { packageVersion } from "./pi.js";
14
- import { CARD_PRIORITIES, CARD_STATUSES, thinkingSchema } from "./schemas.js";
15
- const call = ownerRequest;
16
15
  const server = new McpServer({
17
16
  name: "cogitator",
18
17
  version: packageVersion(),
19
18
  });
20
- /** Enveloppe un outil : résultat JSON en texte, erreur remontée à l'agent (jamais d'exception brute). */
21
- function addTool(name, description, inputSchema, fn) {
22
- server.registerTool(name, { description, inputSchema }, async (args) => {
23
- try {
24
- return { content: [{ type: "text", text: JSON.stringify(await fn(args), null, 2) }] };
25
- }
26
- catch (err) {
27
- return { content: [{ type: "text", text: `Erreur: ${err instanceof Error ? err.message : String(err)}` }], isError: true };
28
- }
29
- });
30
- }
31
- // ---------- Agents ----------
32
- addTool("cogitator_list_agents", "Liste les presets d'agents Cogitator (sans prompts).", {}, () => call("GET", "/api/agents"));
33
- addTool("cogitator_get_agent", "Détail complet d'un agent (prompt, skills, MCP, subagents).", { id: z.string() }, (a) => call("GET", `/api/agents/${a.id}`));
34
- 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.", {
35
- name: z.string().describe("Nom d'affichage"),
36
- provider: z.string().describe("ex: openai, deepseek, kimi-coding"),
37
- model: z.string().describe("id du modèle dans le provider"),
38
- description: z.string().optional(),
39
- thinking: thinkingSchema.optional(),
40
- system_prompt: z.string().optional().describe("Prompt de scope de l'agent"),
41
- skills: z.array(z.string()).optional().describe("Chemins absolus de skills"),
42
- tools: z.array(z.string()).optional().describe("Allowlist d'outils (absent = tous)"),
43
- }, (a) => call("POST", "/api/agents", a));
44
- addTool("cogitator_update_agent", "Modifie un agent existant (mêmes champs que create, écrase la config).", {
45
- id: z.string(),
46
- name: z.string(),
47
- provider: z.string(),
48
- model: z.string(),
49
- description: z.string().optional(),
50
- thinking: thinkingSchema.nullable().optional(),
51
- system_prompt: z.string().optional(),
52
- skills: z.array(z.string()).optional(),
53
- tools: z.array(z.string()).nullable().optional(),
54
- }, (a) => {
55
- const { id, ...body } = a;
56
- return call("PUT", `/api/agents/${id}`, body);
19
+ registerCogitatorTools(server, {
20
+ call: (method, path, body) => ownerRequest(method, path, body),
21
+ scope: "full",
22
+ fromConversationId: process.env.COGITATOR_CONVERSATION_ID,
57
23
  });
58
- addTool("cogitator_delete_agent", "Supprime un agent et ses définitions herdr noo-*.", { id: z.string() }, (a) => call("DELETE", `/api/agents/${a.id}`));
59
- 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`));
60
- 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`));
61
- // ---------- Schedules (cron) ----------
62
- addTool("cogitator_list_schedules", "Liste les tâches cron (avec prochain run calculé).", {}, () => call("GET", "/api/schedules"));
63
- addTool("cogitator_create_schedule", "Crée une tâche cron : un prompt tiré contre un agent à heure fixe.", {
64
- name: z.string(),
65
- cron_expr: z.string().describe("5 champs: min heure jour mois jour-sem — ex: '0 9 * * 1-5'"),
66
- prompt: z.string(),
67
- agent_id: z.string(),
68
- workspace_id: z.string(),
69
- output_policy: z.enum(["append_session", "new_session"]).optional(),
70
- busy_policy: z.enum(["skip", "queue", "kill"]).optional(),
71
- catchup: z.boolean().optional(),
72
- }, (a) => call("POST", "/api/schedules", a));
73
- addTool("cogitator_update_schedule", "Modifie une tâche cron (champs partiels, enabled inclus).", {
74
- id: z.string(),
75
- name: z.string().optional(),
76
- cron_expr: z.string().optional(),
77
- prompt: z.string().optional(),
78
- output_policy: z.enum(["append_session", "new_session"]).optional(),
79
- busy_policy: z.enum(["skip", "queue", "kill"]).optional(),
80
- catchup: z.boolean().optional(),
81
- enabled: z.boolean().optional(),
82
- }, (a) => {
83
- const { id, ...body } = a;
84
- return call("PUT", `/api/schedules/${id}`, body);
85
- });
86
- 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}`));
87
- addTool("cogitator_fire_schedule", "Déclenche immédiatement une tâche cron.", { id: z.string() }, (a) => call("POST", `/api/schedules/${a.id}/run`));
88
- 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`));
89
- // ---------- Workspaces ----------
90
- addTool("cogitator_list_workspaces", "Liste les workspaces (dossiers + nb de conversations).", {}, () => call("GET", "/api/workspaces"));
91
- 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));
92
- addTool("cogitator_delete_workspace", "Supprime un workspace (les conversations deviennent libres).", { id: z.string() }, (a) => call("DELETE", `/api/workspaces/${a.id}`));
93
- // ---------- Conversations ----------
94
- 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}` : ""}`));
95
- addTool("cogitator_create_conversation", "Crée une conversation avec un agent (ou provider libre) et un prompt initial optionnel.", {
96
- agent_id: z.string().optional(),
97
- provider: z.string().optional(),
98
- model: z.string().optional(),
99
- workspace_id: z.string().optional(),
100
- prompt: z.string().optional(),
101
- }, (a) => call("POST", "/api/conversations", a));
102
- // ---------- Registry ----------
103
- addTool("cogitator_list_providers", "Liste les providers pi (catalogue + statut auth + modèles).", {}, () => call("GET", "/api/providers"));
104
- addTool("cogitator_list_skills", "Liste les skills disponibles (name, description, path).", {}, () => call("GET", "/api/skills"));
105
- 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/.", {
106
- source: z.string().describe("URL GitHub (https://github.com/owner/repo) ou chemin absolu d'un dossier local"),
107
- overwrite: z.boolean().optional().describe("Écrase les skills existants du même nom (défaut: skip)"),
108
- }, (a) => call("POST", "/api/skills/import", a));
109
- addTool("cogitator_health", "État du serveur Cogitator (version, pi, sessions, base).", {}, () => call("GET", "/api/health"));
110
- // ---------- Board kanban (gestion de projet du workspace) ----------
111
- 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`));
112
- 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.", {
113
- workspace_id: z.string(),
114
- title: z.string(),
115
- description: z.string().optional(),
116
- status: z.enum(CARD_STATUSES).optional(),
117
- priority: z.enum(CARD_PRIORITIES).optional(),
118
- labels: z.array(z.string()).optional(),
119
- assignee_agent_id: z.string().nullable().optional(),
120
- conversation_ids: z.array(z.string()).optional(),
121
- }, (a) => call("POST", `/api/workspaces/${a.workspace_id}/board/cards`, a));
122
- addTool("cogitator_board_update_card", "Met à jour une carte (mêmes champs que create ; écrase la config). Relations : blocks/blocked_by (ids de cartes).", {
123
- workspace_id: z.string(),
124
- card_id: z.string(),
125
- title: z.string().optional(),
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
- blocks: z.array(z.string()).optional(),
133
- blocked_by: z.array(z.string()).optional(),
134
- }, (a) => {
135
- const { workspace_id, card_id, ...body } = a;
136
- return call("PUT", `/api/workspaces/${workspace_id}/board/cards/${card_id}`, body);
137
- });
138
- addTool("cogitator_board_move", "Déplace une carte vers une colonne (statut).", {
139
- workspace_id: z.string(),
140
- card_id: z.string(),
141
- status: z.enum(CARD_STATUSES),
142
- }, (a) => call("POST", `/api/workspaces/${a.workspace_id}/board/cards/${a.card_id}/move`, { status: a.status }));
143
- 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.", {
144
- workspace_id: z.string(),
145
- card_id: z.string(),
146
- extra: z.string().optional().describe("Précision complémentaire à ajouter au prompt"),
147
- }, (a) => call("POST", `/api/workspaces/${a.workspace_id}/board/cards/${a.card_id}/start`, { extra: a.extra }));
148
- addTool("cogitator_board_comment", "Ajoute un commentaire à une carte (append-only). Auteur par défaut : Majordome.", {
149
- workspace_id: z.string(),
150
- card_id: z.string(),
151
- text: z.string(),
152
- author: z.string().optional(),
153
- }, (a) => call("POST", `/api/workspaces/${a.workspace_id}/board/cards/${a.card_id}/comments`, { text: a.text, author: a.author ?? "Majordome" }));
154
24
  const transport = new StdioServerTransport();
155
25
  await server.connect(transport);
156
26
  console.error("[cogitator-mcp] connecté (stdio)");
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Jetons d'accès du serveur MCP HTTP (`/mcp`).
3
+ *
4
+ * Un jeton est un secret aléatoire de 256 bits, montré une seule fois à la création.
5
+ * Seul son SHA-256 est stocké (`<home>/mcp-tokens.json`, mode 0600). Le fichier est
6
+ * relu dès qu'il change : une révocation par la CLI prend effet sur le serveur en cours,
7
+ * y compris pour les sessions MCP déjà ouvertes (vérification à chaque requête et appel).
8
+ */
9
+ import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
10
+ import { chmodSync, existsSync, mkdirSync, statSync } from "node:fs";
11
+ import { join } from "node:path";
12
+ import { atomicWriteJson, readJson } from "./json-files.js";
13
+ import { MCP_SCOPES } from "./mcp-tools.js";
14
+ export const MCP_TOKEN_PREFIX = "cgt_";
15
+ const TOKEN_FILE = "mcp-tokens.json";
16
+ const NAME_MAX = 64;
17
+ export function mcpTokenPath(home) {
18
+ return join(home, TOKEN_FILE);
19
+ }
20
+ const digest = (token) => createHash("sha256").update(token, "utf8").digest("hex");
21
+ function readFile(home) {
22
+ const data = readJson(mcpTokenPath(home), { version: 1, tokens: [] });
23
+ const tokens = Array.isArray(data.tokens) ? data.tokens.filter(isRecord) : [];
24
+ return { version: 1, tokens };
25
+ }
26
+ function isRecord(value) {
27
+ if (!value || typeof value !== "object")
28
+ return false;
29
+ const r = value;
30
+ return typeof r.id === "string" && typeof r.name === "string" && typeof r.hash === "string"
31
+ && /^[0-9a-f]{64}$/.test(r.hash) && MCP_SCOPES.includes(r.scope) && typeof r.created_at === "string";
32
+ }
33
+ function writeFile(home, file) {
34
+ mkdirSync(home, { recursive: true });
35
+ atomicWriteJson(mcpTokenPath(home), file, 0o600);
36
+ chmodSync(mcpTokenPath(home), 0o600);
37
+ }
38
+ const info = ({ hash: _hash, ...rest }) => rest;
39
+ export function createMcpToken(home, input) {
40
+ const name = input.name.trim();
41
+ if (!name || name.length > NAME_MAX)
42
+ throw new Error(`Nom de jeton requis (1-${NAME_MAX} caractères)`);
43
+ const scope = input.scope ?? "full";
44
+ if (!MCP_SCOPES.includes(scope))
45
+ throw new Error(`Scope invalide : ${scope} (read | full)`);
46
+ const token = MCP_TOKEN_PREFIX + randomBytes(32).toString("base64url");
47
+ const record = { id: randomUUID().slice(0, 8), name, scope, hash: digest(token), created_at: new Date().toISOString() };
48
+ const file = readFile(home);
49
+ file.tokens.push(record);
50
+ writeFile(home, file);
51
+ return { token, info: info(record) };
52
+ }
53
+ export function listMcpTokens(home) {
54
+ return readFile(home).tokens.map(info);
55
+ }
56
+ export function revokeMcpToken(home, idOrName) {
57
+ const file = readFile(home);
58
+ const kept = file.tokens.filter((t) => t.id !== idOrName && t.name !== idOrName);
59
+ if (kept.length === file.tokens.length)
60
+ return false;
61
+ writeFile(home, { version: 1, tokens: kept });
62
+ return true;
63
+ }
64
+ /** Vérificateur avec cache invalidé sur mtime/taille du fichier. */
65
+ export class McpTokenVerifier {
66
+ home;
67
+ cache;
68
+ constructor(home) {
69
+ this.home = home;
70
+ }
71
+ tokens() {
72
+ const path = mcpTokenPath(this.home);
73
+ if (!existsSync(path))
74
+ return [];
75
+ const s = statSync(path);
76
+ const key = `${s.mtimeMs}:${s.size}:${s.ino}`;
77
+ if (this.cache?.key !== key)
78
+ this.cache = { key, tokens: readFile(this.home).tokens };
79
+ return this.cache.tokens;
80
+ }
81
+ /** Jeton présenté → enregistrement, ou undefined (absent, inconnu, révoqué). */
82
+ verify(token) {
83
+ if (!token || !token.startsWith(MCP_TOKEN_PREFIX) || token.length > 128)
84
+ return undefined;
85
+ const presented = Buffer.from(digest(token), "hex");
86
+ let found;
87
+ for (const record of this.tokens()) {
88
+ if (timingSafeEqual(presented, Buffer.from(record.hash, "hex")))
89
+ found = record;
90
+ }
91
+ return found ? info(found) : undefined;
92
+ }
93
+ /** Le jeton `id` est-il toujours valide avec ce scope ? (révocation en cours de session) */
94
+ stillValid(id, scope) {
95
+ return this.tokens().some((t) => t.id === id && t.scope === scope);
96
+ }
97
+ }
98
+ /** Extrait le jeton d'un en-tête `Authorization: Bearer …`. */
99
+ export function bearerToken(header) {
100
+ if (typeof header !== "string")
101
+ return undefined;
102
+ const match = /^Bearer\s+(\S+)\s*$/i.exec(header);
103
+ return match?.[1];
104
+ }
@@ -0,0 +1,264 @@
1
+ /**
2
+ * Outils MCP Cogitator — source unique partagée par les deux transports :
3
+ * - stdio (`mcp-server.ts`, le Majordome lancé par pi) ;
4
+ * - Streamable HTTP (`mcp-http.ts`, agents externes : Claude, GPT, bots…).
5
+ *
6
+ * Chaque outil appelle l'API Cogitator via `call(method, path, body)`. Le transport
7
+ * fournit `call` : requête propriétaire (stdio) ou dispatch interne autorisé (HTTP).
8
+ * Le scope `read` n'enregistre que les outils en lecture ; `call` le refait respecter.
9
+ */
10
+ import { randomUUID } from "node:crypto";
11
+ import { z } from "zod";
12
+ import { CARD_PRIORITIES, CARD_STATUSES, thinkingSchema } from "./schemas.js";
13
+ export const MCP_SCOPES = ["read", "full"];
14
+ /** Segment d'URL sûr : un id ne peut jamais viser une autre route. */
15
+ const enc = (value) => encodeURIComponent(String(value));
16
+ const DEFAULT_WAIT_S = 120;
17
+ const MAX_WAIT_S = 900;
18
+ const DEFAULT_POLL_MS = 1000;
19
+ const DEFAULT_READ_LIMIT = 50;
20
+ const MAX_READ_LIMIT = 300;
21
+ export function registerCogitatorTools(server, opts) {
22
+ const scope = opts.scope ?? "full";
23
+ const pollMs = opts.pollMs ?? DEFAULT_POLL_MS;
24
+ const call = (method, path, body) => {
25
+ if (scope === "read" && method !== "GET")
26
+ return Promise.reject(new Error("Scope read : écriture refusée"));
27
+ return opts.call(method, path, body);
28
+ };
29
+ const names = [];
30
+ function addTool(name, description, inputSchema, readOnly, fn, destructive = false) {
31
+ if (scope === "read" && !readOnly)
32
+ return;
33
+ names.push(name);
34
+ server.registerTool(name, {
35
+ description,
36
+ inputSchema,
37
+ annotations: { readOnlyHint: readOnly, destructiveHint: !readOnly && destructive, openWorldHint: false },
38
+ }, async (args, extra) => {
39
+ try {
40
+ return { content: [{ type: "text", text: JSON.stringify(await fn(args, extra), null, 2) }] };
41
+ }
42
+ catch (err) {
43
+ return { content: [{ type: "text", text: `Erreur: ${err instanceof Error ? err.message : String(err)}` }], isError: true };
44
+ }
45
+ });
46
+ }
47
+ const read = (name, description, inputSchema, fn) => addTool(name, description, inputSchema, true, fn);
48
+ const write = (name, description, inputSchema, fn) => addTool(name, description, inputSchema, false, fn);
49
+ const destroy = (name, description, inputSchema, fn) => addTool(name, description, inputSchema, false, fn, true);
50
+ // ---------- Agents ----------
51
+ read("cogitator_list_agents", "Liste les presets d'agents Cogitator (sans prompts).", {}, () => call("GET", "/api/agents"));
52
+ read("cogitator_get_agent", "Détail complet d'un agent (prompt, skills, MCP, subagents).", { id: z.string() }, (a) => call("GET", `/api/agents/${enc(a.id)}`));
53
+ write("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.", {
54
+ name: z.string().describe("Nom d'affichage"),
55
+ provider: z.string().describe("ex: openai, deepseek, kimi-coding"),
56
+ model: z.string().describe("id du modèle dans le provider"),
57
+ description: z.string().optional(),
58
+ thinking: thinkingSchema.optional(),
59
+ system_prompt: z.string().optional().describe("Prompt de scope de l'agent"),
60
+ skills: z.array(z.string()).optional().describe("Chemins absolus de skills"),
61
+ tools: z.array(z.string()).optional().describe("Allowlist d'outils (absent = tous)"),
62
+ }, (a) => call("POST", "/api/agents", a));
63
+ write("cogitator_update_agent", "Modifie un agent existant (mêmes champs que create, écrase la config).", {
64
+ id: z.string(),
65
+ name: z.string(),
66
+ provider: z.string(),
67
+ model: z.string(),
68
+ description: z.string().optional(),
69
+ thinking: thinkingSchema.nullable().optional(),
70
+ system_prompt: z.string().optional(),
71
+ skills: z.array(z.string()).optional(),
72
+ tools: z.array(z.string()).nullable().optional(),
73
+ }, (a) => {
74
+ const { id, ...body } = a;
75
+ return call("PUT", `/api/agents/${enc(id)}`, body);
76
+ });
77
+ destroy("cogitator_delete_agent", "Supprime un agent et ses définitions herdr noo-*.", { id: z.string() }, (a) => call("DELETE", `/api/agents/${enc(a.id)}`));
78
+ write("cogitator_validate_agent", "Valide un agent (provider/modèle du catalogue, skills, MCP, auth).", { id: z.string() }, (a) => call("POST", `/api/agents/${enc(a.id)}/validate`));
79
+ write("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/${enc(a.id)}/default`));
80
+ // ---------- Schedules (cron) ----------
81
+ read("cogitator_list_schedules", "Liste les tâches cron (avec prochain run calculé).", {}, () => call("GET", "/api/schedules"));
82
+ write("cogitator_create_schedule", "Crée une tâche cron : un prompt tiré contre un agent à heure fixe.", {
83
+ name: z.string(),
84
+ cron_expr: z.string().describe("5 champs: min heure jour mois jour-sem — ex: '0 9 * * 1-5'"),
85
+ prompt: z.string(),
86
+ agent_id: z.string(),
87
+ workspace_id: z.string(),
88
+ output_policy: z.enum(["append_session", "new_session"]).optional(),
89
+ busy_policy: z.enum(["skip", "queue", "kill"]).optional(),
90
+ catchup: z.boolean().optional(),
91
+ }, (a) => call("POST", "/api/schedules", a));
92
+ write("cogitator_update_schedule", "Modifie une tâche cron (champs partiels, enabled inclus).", {
93
+ id: z.string(),
94
+ name: z.string().optional(),
95
+ cron_expr: z.string().optional(),
96
+ prompt: z.string().optional(),
97
+ output_policy: z.enum(["append_session", "new_session"]).optional(),
98
+ busy_policy: z.enum(["skip", "queue", "kill"]).optional(),
99
+ catchup: z.boolean().optional(),
100
+ enabled: z.boolean().optional(),
101
+ }, (a) => {
102
+ const { id, ...body } = a;
103
+ return call("PUT", `/api/schedules/${enc(id)}`, body);
104
+ });
105
+ destroy("cogitator_delete_schedule", "Supprime une tâche cron et l'historique de ses runs.", { id: z.string() }, (a) => call("DELETE", `/api/schedules/${enc(a.id)}`));
106
+ write("cogitator_fire_schedule", "Déclenche immédiatement une tâche cron.", { id: z.string() }, (a) => call("POST", `/api/schedules/${enc(a.id)}/run`));
107
+ read("cogitator_list_runs", "Historique des runs d'une tâche cron (status, session, erreur).", { id: z.string() }, (a) => call("GET", `/api/schedules/${enc(a.id)}/runs`));
108
+ // ---------- Workspaces ----------
109
+ read("cogitator_list_workspaces", "Liste les workspaces (dossiers + nb de conversations).", {}, () => call("GET", "/api/workspaces"));
110
+ write("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));
111
+ destroy("cogitator_delete_workspace", "Supprime un workspace (les conversations deviennent libres).", { id: z.string() }, (a) => call("DELETE", `/api/workspaces/${enc(a.id)}`));
112
+ // ---------- Conversations ----------
113
+ read("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=${enc(a.workspace_id)}` : ""}`));
114
+ read("cogitator_get_conversation", "État d'une conversation : agent, modèle, workspace, runtime, live/streaming (tour en cours).", { conversation_id: z.string() }, (a) => call("GET", `/api/conversations/${enc(a.conversation_id)}`));
115
+ read("cogitator_read_conversation", "Lit le transcript d'une conversation : messages user/assistant, et optionnellement réflexion et appels d'outils (résultats tronqués).", {
116
+ conversation_id: z.string(),
117
+ limit: z.number().int().min(1).max(MAX_READ_LIMIT).optional().describe(`Nombre d'entrées les plus récentes (défaut ${DEFAULT_READ_LIMIT})`),
118
+ include_tools: z.boolean().optional().describe("Inclut les appels d'outils et la réflexion (défaut false)"),
119
+ }, async (a) => {
120
+ const limit = typeof a.limit === "number" ? a.limit : DEFAULT_READ_LIMIT;
121
+ const entries = await historyEntries(call, String(a.conversation_id));
122
+ const filtered = a.include_tools ? entries : entries.filter((e) => e.type === "user" || e.type === "assistant");
123
+ return { entries: filtered.slice(-limit) };
124
+ });
125
+ write("cogitator_create_conversation", "Crée une conversation avec un agent (ou provider libre) et un prompt initial optionnel. Utilise cogitator_send_message avec wait=true pour obtenir une réponse.", {
126
+ agent_id: z.string().optional(),
127
+ provider: z.string().optional(),
128
+ model: z.string().optional(),
129
+ workspace_id: z.string().optional(),
130
+ prompt: z.string().optional(),
131
+ }, (a) => call("POST", "/api/conversations", a));
132
+ write("cogitator_send_message", "Envoie un message utilisateur à une conversation. Avec wait=true (défaut), attend la fin du tour de l'agent en émettant des notifications de progression, puis renvoie sa réponse.", {
133
+ conversation_id: z.string(),
134
+ text: z.string().min(1),
135
+ wait: z.boolean().optional().describe("Attendre la réponse de l'agent (défaut true)"),
136
+ timeout_seconds: z.number().int().min(1).max(MAX_WAIT_S).optional().describe(`Attente maximale (défaut ${DEFAULT_WAIT_S} s). Au-delà : status=running, relire avec cogitator_read_conversation.`),
137
+ }, async (a, extra) => {
138
+ const id = String(a.conversation_id);
139
+ const before = a.wait === false ? [] : await historyEntries(call, id);
140
+ await call("POST", `/api/conversations/${enc(id)}/messages`, { text: a.text, requestId: randomUUID() });
141
+ if (a.wait === false)
142
+ return { ok: true, status: "sent" };
143
+ const timeoutMs = (typeof a.timeout_seconds === "number" ? a.timeout_seconds : DEFAULT_WAIT_S) * 1000;
144
+ return waitForTurn(call, id, before, timeoutMs, pollMs, extra);
145
+ });
146
+ write("cogitator_stop_conversation", "Interrompt le tour en cours d'une conversation.", { conversation_id: z.string() }, (a) => call("POST", `/api/conversations/${enc(a.conversation_id)}/stop`));
147
+ write("team_send", "Envoie un message durable à une conversation (file lane/queue_item, limite de sauts, idempotence).", {
148
+ conversation_id: z.string().describe("Conversation destinataire"),
149
+ body: z.string(),
150
+ idempotency_key: z.string().optional(),
151
+ }, (a) => call("POST", "/api/team/send", {
152
+ conversation_id: a.conversation_id,
153
+ body: a.body,
154
+ idempotency_key: a.idempotency_key,
155
+ from_conversation_id: opts.fromConversationId,
156
+ }));
157
+ // ---------- Registry ----------
158
+ read("cogitator_list_providers", "Liste les providers pi (catalogue + statut auth + modèles).", {}, () => call("GET", "/api/providers"));
159
+ read("cogitator_list_skills", "Liste les skills disponibles (name, description, path).", {}, () => call("GET", "/api/skills"));
160
+ write("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/.", {
161
+ source: z.string().describe("URL GitHub (https://github.com/owner/repo) ou chemin absolu d'un dossier local"),
162
+ overwrite: z.boolean().optional().describe("Écrase les skills existants du même nom (défaut: skip)"),
163
+ }, (a) => call("POST", "/api/skills/import", a));
164
+ read("cogitator_health", "État du serveur Cogitator (version, pi, sessions, base).", {}, () => call("GET", "/api/health"));
165
+ // ---------- Board kanban (gestion de projet du workspace) ----------
166
+ read("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/${enc(a.workspace_id)}/board`));
167
+ write("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.", {
168
+ workspace_id: z.string(),
169
+ title: z.string(),
170
+ description: z.string().optional(),
171
+ status: z.enum(CARD_STATUSES).optional(),
172
+ priority: z.enum(CARD_PRIORITIES).optional(),
173
+ labels: z.array(z.string()).optional(),
174
+ assignee_agent_id: z.string().nullable().optional(),
175
+ conversation_ids: z.array(z.string()).optional(),
176
+ }, (a) => call("POST", `/api/workspaces/${enc(a.workspace_id)}/board/cards`, a));
177
+ write("cogitator_board_update_card", "Met à jour une carte (mêmes champs que create ; écrase la config). Relations : blocks/blocked_by (ids de cartes).", {
178
+ workspace_id: z.string(),
179
+ card_id: z.string(),
180
+ title: z.string().optional(),
181
+ description: z.string().optional(),
182
+ status: z.enum(CARD_STATUSES).optional(),
183
+ priority: z.enum(CARD_PRIORITIES).optional(),
184
+ labels: z.array(z.string()).optional(),
185
+ assignee_agent_id: z.string().nullable().optional(),
186
+ conversation_ids: z.array(z.string()).optional(),
187
+ blocks: z.array(z.string()).optional(),
188
+ blocked_by: z.array(z.string()).optional(),
189
+ }, (a) => {
190
+ const { workspace_id, card_id, ...body } = a;
191
+ return call("PUT", `/api/workspaces/${enc(workspace_id)}/board/cards/${enc(card_id)}`, body);
192
+ });
193
+ write("cogitator_board_move", "Déplace une carte vers une colonne (statut).", {
194
+ workspace_id: z.string(),
195
+ card_id: z.string(),
196
+ status: z.enum(CARD_STATUSES),
197
+ }, (a) => call("POST", `/api/workspaces/${enc(a.workspace_id)}/board/cards/${enc(a.card_id)}/move`, { status: a.status }));
198
+ write("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.", {
199
+ workspace_id: z.string(),
200
+ card_id: z.string(),
201
+ extra: z.string().optional().describe("Précision complémentaire à ajouter au prompt"),
202
+ }, (a) => call("POST", `/api/workspaces/${enc(a.workspace_id)}/board/cards/${enc(a.card_id)}/start`, { extra: a.extra }));
203
+ write("cogitator_board_comment", `Ajoute un commentaire à une carte (append-only). Auteur par défaut : ${opts.author ?? "Majordome"}.`, {
204
+ workspace_id: z.string(),
205
+ card_id: z.string(),
206
+ text: z.string(),
207
+ author: z.string().optional(),
208
+ }, (a) => call("POST", `/api/workspaces/${enc(a.workspace_id)}/board/cards/${enc(a.card_id)}/comments`, { text: a.text, author: a.author ?? opts.author ?? "Majordome" }));
209
+ return names;
210
+ }
211
+ async function historyEntries(call, conversationId) {
212
+ const data = await call("GET", `/api/conversations/${enc(conversationId)}/history`);
213
+ return Array.isArray(data.entries) ? data.entries : [];
214
+ }
215
+ async function isStreaming(call, conversationId) {
216
+ const data = await call("GET", `/api/conversations/${enc(conversationId)}`);
217
+ return data.streaming === true;
218
+ }
219
+ const sleep = (ms, signal) => new Promise((done, reject) => {
220
+ if (signal.aborted)
221
+ return reject(new Error("Annulé"));
222
+ const timer = setTimeout(() => { signal.removeEventListener("abort", onAbort); done(); }, ms);
223
+ const onAbort = () => { clearTimeout(timer); reject(new Error("Annulé")); };
224
+ signal.addEventListener("abort", onAbort, { once: true });
225
+ });
226
+ /**
227
+ * Attend la fin du tour : le transcript a grandi et la conversation ne streame plus.
228
+ * Le transcript est fenêtré (dernières entrées) : on compare aussi le dernier élément.
229
+ */
230
+ async function waitForTurn(call, id, before, timeoutMs, pollMs, extra) {
231
+ const started = Date.now();
232
+ const token = extra._meta?.progressToken;
233
+ let tick = 0;
234
+ let sawStreaming = false;
235
+ for (;;) {
236
+ await sleep(pollMs, extra.signal);
237
+ tick++;
238
+ const streaming = await isStreaming(call, id);
239
+ sawStreaming ||= streaming;
240
+ const entries = await historyEntries(call, id);
241
+ const last = entries[entries.length - 1];
242
+ const previous = before[before.length - 1];
243
+ const grown = sawStreaming || entries.length > before.length || JSON.stringify(last) !== JSON.stringify(previous);
244
+ if (!streaming && grown && last?.type === "assistant") {
245
+ const lastUser = entries.map((e) => e.type).lastIndexOf("user");
246
+ const turn = entries.slice(lastUser + 1);
247
+ return {
248
+ status: "completed",
249
+ reply: turn.filter((e) => e.type === "assistant").map((e) => e.text ?? "").join("\n"),
250
+ tools_used: turn.filter((e) => e.type === "tool").map((e) => ({ name: e.name, isError: e.isError === true })),
251
+ elapsed_ms: Date.now() - started,
252
+ };
253
+ }
254
+ if (token !== undefined) {
255
+ await extra.sendNotification({ method: "notifications/progress", params: {
256
+ progressToken: token, progress: tick,
257
+ message: streaming ? `agent en cours (${Math.round((Date.now() - started) / 1000)} s)` : "en attente du démarrage du tour",
258
+ } }).catch(() => undefined);
259
+ }
260
+ if (Date.now() - started >= timeoutMs) {
261
+ return { status: "running", hint: "Le tour continue : relire avec cogitator_read_conversation ou rappeler plus tard.", elapsed_ms: Date.now() - started };
262
+ }
263
+ }
264
+ }
@@ -118,6 +118,8 @@ export class AuthError extends Error {
118
118
  this.retryAt = retryAt;
119
119
  }
120
120
  }
121
+ /** Older configurations retain their explicitly reviewed MFA boundary. */
122
+ export const requiresMfa = (config) => config.authentication !== "password";
121
123
  export function createNativeAuth(db, config, offline = false, captureReset) {
122
124
  installFactorMutationGuard(db);
123
125
  const options = {
@@ -165,6 +167,7 @@ export function createNativeAuth(db, config, offline = false, captureReset) {
165
167
  databaseHooks: { session: { create: { before: async (session, ctx) => {
166
168
  const eligible = session.userId === config.ownerId && !ctx?.context.session &&
167
169
  (ctx?.path === "/two-factor/verify-totp" || ctx?.path === "/two-factor/verify-backup-code");
170
+ const passwordLogin = !requiresMfa(config) && session.userId === config.ownerId && ctx?.path === "/sign-in/email";
168
171
  if (eligible) {
169
172
  const factor = db.prepare('SELECT verified FROM twoFactor WHERE userId = ?').get(config.ownerId);
170
173
  if (factor?.verified !== 1)
@@ -182,7 +185,7 @@ export function createNativeAuth(db, config, offline = false, captureReset) {
182
185
  }
183
186
  }
184
187
  return { data: { ...session, mfaApproved: eligible,
185
- ...(!eligible ? { expiresAt: new Date(Math.min(new Date(session.expiresAt).getTime(), Date.now() + ENROLLMENT_MS)) } : {}) } };
188
+ ...(!eligible && !passwordLogin ? { expiresAt: new Date(Math.min(new Date(session.expiresAt).getTime(), Date.now() + ENROLLMENT_MS)) } : {}) } };
186
189
  } } } },
187
190
  };
188
191
  const auth = betterAuth(options);
@@ -219,6 +222,8 @@ export function assertOwner(db, config) {
219
222
  if (factors.length > 1 || factors.some(f => f.userId !== config.ownerId) ||
220
223
  Boolean(owners[0].twoFactorEnabled) !== Boolean(factors[0]?.verified))
221
224
  throw new AuthError("AUTH_UNAVAILABLE", 503);
225
+ if (!requiresMfa(config) && (owners[0].twoFactorEnabled || factors.length))
226
+ throw new AuthError("AUTH_UNAVAILABLE", 503);
222
227
  }
223
228
  export function sessionById(db, config, id) {
224
229
  assertOwner(db, config);
@@ -235,9 +240,11 @@ export async function ownerSession(auth, db, config, headers) {
235
240
  const result = await auth.api.getSession({ headers, query: { disableCookieCache: true } });
236
241
  return result ? sessionById(db, config, result.session.id) : null;
237
242
  }
238
- export function requireApproved(session) {
243
+ export function requireApproved(session, config) {
239
244
  if (!session)
240
245
  throw new AuthError("AUTH_REQUIRED", 401);
246
+ if (config && !requiresMfa(config))
247
+ return;
241
248
  if (!session.approved || !session.enrolled)
242
249
  throw new AuthError("MFA_REQUIRED", 403);
243
250
  }