@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
@@ -1,4 +1,4 @@
1
- import { copyFileSync, existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
1
+ import { chmodSync, copyFileSync, existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
2
2
  /** Lit un JSON tolérant (fichier absent → fallback). */
3
3
  export function readJson(path, fallback) {
4
4
  try {
@@ -9,10 +9,13 @@ export function readJson(path, fallback) {
9
9
  }
10
10
  }
11
11
  /** Écriture atomique : tmp + rename, backup `.bak` de l'ancien. */
12
- export function atomicWriteJson(path, value) {
12
+ export function atomicWriteJson(path, value, mode) {
13
13
  const tmp = `${path}.tmp-${process.pid}`;
14
- writeFileSync(tmp, JSON.stringify(value, null, 2) + "\n");
15
- if (existsSync(path))
14
+ writeFileSync(tmp, JSON.stringify(value, null, 2) + "\n", { mode });
15
+ if (existsSync(path)) {
16
16
  copyFileSync(path, `${path}.bak`);
17
+ if (mode !== undefined)
18
+ chmodSync(`${path}.bak`, mode);
19
+ }
17
20
  renameSync(tmp, path);
18
21
  }
@@ -0,0 +1,49 @@
1
+ import { cpus, freemem, totalmem, uptime } from "node:os";
2
+ import { readFile, statfs } from "node:fs/promises";
3
+ export function cpuPercent(before, after) {
4
+ const total = after.total - before.total;
5
+ const idle = after.idle - before.idle;
6
+ return total > 0 && idle >= 0 ? Math.max(0, Math.min(100, (1 - idle / total) * 100)) : null;
7
+ }
8
+ export function availableMemory(meminfo) {
9
+ const value = /^MemAvailable:\s+(\d+)\s+kB$/m.exec(meminfo);
10
+ return value ? Number(value[1]) * 1024 : null;
11
+ }
12
+ function cpuSnapshot() {
13
+ const cores = cpus();
14
+ return { cores: cores.length, idle: cores.reduce((sum, c) => sum + c.times.idle, 0), total: cores.reduce((sum, c) => sum + Object.values(c.times).reduce((a, b) => a + b, 0), 0) };
15
+ }
16
+ /** Host metrics, not a container/service resource quota. No shell or arbitrary path input. */
17
+ export function machineMetrics(home) {
18
+ let previous = cpuSnapshot();
19
+ let lastAt = performance.now();
20
+ let cached;
21
+ let pending;
22
+ return function sample() {
23
+ if (cached && performance.now() - lastAt < 2000)
24
+ return Promise.resolve(cached);
25
+ if (pending)
26
+ return pending;
27
+ pending = (async () => {
28
+ const cpu = cpuSnapshot();
29
+ const elapsed = performance.now() - lastAt;
30
+ const percent = elapsed >= 500 ? cpuPercent(previous, cpu) : null;
31
+ const total = totalmem();
32
+ let available = freemem();
33
+ if (process.platform === "linux") {
34
+ available = await readFile("/proc/meminfo", "utf8").then(s => availableMemory(s) ?? available).catch(() => available);
35
+ }
36
+ const used = Math.max(0, Math.min(total, total - available));
37
+ const disk = await statfs(home).then(s => {
38
+ const total = s.blocks * s.bsize;
39
+ const used = (s.blocks - s.bfree) * s.bsize;
40
+ return { total, used, available: s.bavail * s.bsize, percent: total > 0 ? used / total * 100 : 0 };
41
+ }).catch(() => null);
42
+ previous = cpu;
43
+ lastAt = performance.now();
44
+ cached = { sampledAt: new Date().toISOString(), cpu: { percent, cores: cpu.cores }, memory: { used, total, percent: total > 0 ? used / total * 100 : 0 }, disk, uptimeSeconds: uptime(), processMemoryBytes: process.memoryUsage().rss };
45
+ return cached;
46
+ })().finally(() => { pending = undefined; });
47
+ return pending;
48
+ };
49
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,63 @@
1
+ /** `cogitator mcp …` : gestion des jetons du serveur MCP HTTP (hors ligne, sans serveur). */
2
+ import { createMcpToken, listMcpTokens, mcpTokenPath, revokeMcpToken } from "./mcp-tokens.js";
3
+ import { listOAuthGrants, revokeOAuthGrant } from "./mcp-oauth.js";
4
+ export const MCP_USAGE = "Usage: cogitator mcp token create <name> [--scope read|full] | cogitator mcp token list | cogitator mcp token revoke <id|name>";
5
+ export function mcpCommand(home, port, args, log = console.log) {
6
+ const [group, action, ...rest] = args;
7
+ if (group !== "token")
8
+ throw new Error(MCP_USAGE);
9
+ if (action === "create") {
10
+ let name;
11
+ let scope = "full";
12
+ for (let i = 0; i < rest.length; i++) {
13
+ const arg = rest[i];
14
+ if (arg === "--scope") {
15
+ const value = rest[++i];
16
+ if (value !== "read" && value !== "full")
17
+ throw new Error("--scope attend read ou full");
18
+ scope = value;
19
+ }
20
+ else if (arg.startsWith("--scope=")) {
21
+ const value = arg.slice("--scope=".length);
22
+ if (value !== "read" && value !== "full")
23
+ throw new Error("--scope attend read ou full");
24
+ scope = value;
25
+ }
26
+ else if (!name && !arg.startsWith("--"))
27
+ name = arg;
28
+ else
29
+ throw new Error(MCP_USAGE);
30
+ }
31
+ if (!name)
32
+ throw new Error(MCP_USAGE);
33
+ const { token, info } = createMcpToken(home, { name, scope });
34
+ log(`Jeton MCP créé : ${info.name} (id ${info.id}, scope ${info.scope})`);
35
+ log("");
36
+ log(` ${token}`);
37
+ log("");
38
+ log("Copiez-le maintenant : il ne sera plus affiché.");
39
+ log(`Endpoint : http://127.0.0.1:${port}/mcp (ou https://<votre-origine>/mcp derrière le proxy HTTPS)`);
40
+ log("En-tête : Authorization: Bearer <jeton>");
41
+ return;
42
+ }
43
+ if (action === "list" && rest.length === 0) {
44
+ const tokens = listMcpTokens(home);
45
+ const grants = listOAuthGrants(home);
46
+ if (!tokens.length && !grants.length) {
47
+ log(`Aucun jeton MCP (${mcpTokenPath(home)}).`);
48
+ return;
49
+ }
50
+ for (const t of tokens)
51
+ log(`${t.id} ${t.scope.padEnd(4)} ${t.created_at} ${t.name}`);
52
+ for (const g of grants)
53
+ log(`${g.id} ${g.scope.padEnd(4)} ${g.created_at} ${g.client_name} (OAuth, client ${g.client_id})`);
54
+ return;
55
+ }
56
+ if (action === "revoke" && rest.length === 1) {
57
+ if (!revokeMcpToken(home, rest[0]) && !revokeOAuthGrant(home, rest[0]))
58
+ throw new Error(`Jeton introuvable : ${rest[0]}`);
59
+ log(`Jeton révoqué : ${rest[0]} (sessions ouvertes fermées à la prochaine requête).`);
60
+ return;
61
+ }
62
+ throw new Error(MCP_USAGE);
63
+ }
@@ -0,0 +1,164 @@
1
+ /**
2
+ * Serveur MCP Cogitator en Streamable HTTP (`/mcp`) — pour les agents externes
3
+ * (Claude, GPT, bots…) qui pilotent Cogitator à distance.
4
+ *
5
+ * - Authentification : `Authorization: Bearer cgt_…` (voir mcp-tokens.ts), exigée en
6
+ * mode local comme en mode protégé, revérifiée à chaque requête HTTP et à chaque appel d'outil.
7
+ * - Sessions MCP avec état (en-tête `Mcp-Session-Id`), liées au jeton qui les a ouvertes.
8
+ * - Les outils (mcp-tools.ts) passent par le dispatch interne des routes `/api/*` :
9
+ * mêmes validations, mêmes contrôles de disponibilité que l'UI, sans boucle réseau.
10
+ */
11
+ import { randomUUID } from "node:crypto";
12
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
13
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
14
+ import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
15
+ import { registerCogitatorTools } from "./mcp-tools.js";
16
+ import { bearerToken, McpTokenVerifier } from "./mcp-tokens.js";
17
+ export const MCP_HTTP_PATH = "/mcp";
18
+ const MAX_MCP_BODY_BYTES = 4 * 1024 * 1024;
19
+ const MAX_SESSIONS = 64;
20
+ const SESSION_IDLE_MS = 30 * 60_000;
21
+ const SWEEP_MS = 60_000;
22
+ class McpHttpError extends Error {
23
+ status;
24
+ code;
25
+ constructor(status, code, message) {
26
+ super(message);
27
+ this.status = status;
28
+ this.code = code;
29
+ }
30
+ }
31
+ function jsonRpcError(res, status, code, message, headers = {}) {
32
+ if (res.headersSent) {
33
+ res.end();
34
+ return;
35
+ }
36
+ res.writeHead(status, { "content-type": "application/json", ...headers });
37
+ res.end(JSON.stringify({ jsonrpc: "2.0", error: { code, message }, id: null }));
38
+ }
39
+ function readJsonBody(req) {
40
+ return new Promise((resolve, reject) => {
41
+ let size = 0;
42
+ const chunks = [];
43
+ req.on("data", (c) => {
44
+ size += c.length;
45
+ if (size > MAX_MCP_BODY_BYTES) {
46
+ reject(new McpHttpError(413, -32600, "Requête trop volumineuse"));
47
+ req.destroy();
48
+ return;
49
+ }
50
+ chunks.push(c);
51
+ });
52
+ req.on("end", () => {
53
+ try {
54
+ resolve(JSON.parse(Buffer.concat(chunks).toString("utf8")));
55
+ }
56
+ catch {
57
+ reject(new McpHttpError(400, -32700, "Parse error"));
58
+ }
59
+ });
60
+ req.on("error", reject);
61
+ });
62
+ }
63
+ export class McpHttpEndpoint {
64
+ opts;
65
+ sessions = new Map();
66
+ verifier;
67
+ sweeper;
68
+ constructor(opts) {
69
+ this.opts = opts;
70
+ this.verifier = new McpTokenVerifier(opts.home);
71
+ this.sweeper = setInterval(() => this.sweep(), SWEEP_MS);
72
+ this.sweeper.unref();
73
+ }
74
+ get sessionCount() { return this.sessions.size; }
75
+ verify(token) {
76
+ return this.verifier.verify(token) ?? this.opts.oauth?.verify(token);
77
+ }
78
+ stillValid(token) {
79
+ return this.verifier.stillValid(token.id, token.scope) || (this.opts.oauth?.stillValid(token.id, token.scope) ?? false);
80
+ }
81
+ async handle(req, res) {
82
+ res.setHeader("cache-control", "no-store");
83
+ try {
84
+ const method = req.method ?? "GET";
85
+ if (!["POST", "GET", "DELETE"].includes(method)) {
86
+ return jsonRpcError(res, 405, -32000, "Method not allowed", { allow: "POST, GET, DELETE" });
87
+ }
88
+ const token = this.verify(bearerToken(req.headers.authorization));
89
+ if (!token) {
90
+ const metadata = this.opts.oauth ? `, resource_metadata="${this.opts.oauth.resourceMetadataUrl}"` : "";
91
+ return jsonRpcError(res, 401, -32001, "Jeton MCP manquant ou invalide (Authorization: Bearer cgt_…)", { "www-authenticate": `Bearer realm="cogitator", error="invalid_token"${metadata}` });
92
+ }
93
+ const header = req.headers["mcp-session-id"];
94
+ const sessionId = typeof header === "string" ? header : undefined;
95
+ const body = method === "POST" ? await readJsonBody(req) : undefined;
96
+ if (sessionId) {
97
+ const session = this.sessions.get(sessionId);
98
+ if (!session)
99
+ return jsonRpcError(res, 404, -32001, "Session MCP inconnue ou expirée");
100
+ if (session.token.id !== token.id)
101
+ return jsonRpcError(res, 403, -32001, "Session ouverte par un autre jeton");
102
+ session.lastSeen = Date.now();
103
+ return await session.transport.handleRequest(req, res, body);
104
+ }
105
+ if (method !== "POST" || !isInitializeRequest(body)) {
106
+ return jsonRpcError(res, 400, -32000, "Mcp-Session-Id requis (ou requête initialize)");
107
+ }
108
+ if (this.sessions.size >= MAX_SESSIONS)
109
+ this.evictOldest();
110
+ const transport = this.open(token);
111
+ await transport.handleRequest(req, res, body);
112
+ }
113
+ catch (err) {
114
+ if (err instanceof McpHttpError)
115
+ return jsonRpcError(res, err.status, err.code, err.message);
116
+ jsonRpcError(res, 500, -32603, "Internal error");
117
+ }
118
+ }
119
+ open(token) {
120
+ const server = new McpServer({ name: "cogitator", version: this.opts.version });
121
+ const call = (method, path, body) => {
122
+ if (!this.stillValid(token))
123
+ return Promise.reject(new Error("Jeton MCP révoqué"));
124
+ return this.opts.dispatch(method, path, body);
125
+ };
126
+ registerCogitatorTools(server, { call, scope: token.scope, author: `MCP: ${token.name}` });
127
+ const transport = new StreamableHTTPServerTransport({
128
+ sessionIdGenerator: () => randomUUID(),
129
+ onsessioninitialized: (id) => { this.sessions.set(id, { transport, server, token, lastSeen: Date.now() }); },
130
+ onsessionclosed: (id) => { this.drop(id); },
131
+ });
132
+ transport.onclose = () => { if (transport.sessionId)
133
+ this.sessions.delete(transport.sessionId); };
134
+ void server.connect(transport);
135
+ return transport;
136
+ }
137
+ drop(id) {
138
+ const session = this.sessions.get(id);
139
+ if (!session)
140
+ return;
141
+ this.sessions.delete(id);
142
+ void session.server.close().catch(() => undefined);
143
+ }
144
+ evictOldest() {
145
+ let oldest;
146
+ for (const entry of this.sessions)
147
+ if (!oldest || entry[1].lastSeen < oldest[1].lastSeen)
148
+ oldest = entry;
149
+ if (oldest)
150
+ this.drop(oldest[0]);
151
+ }
152
+ /** Ferme les sessions inactives et celles dont le jeton a été révoqué. */
153
+ sweep(now = Date.now()) {
154
+ for (const [id, s] of this.sessions) {
155
+ if (now - s.lastSeen > SESSION_IDLE_MS || !this.stillValid(s.token))
156
+ this.drop(id);
157
+ }
158
+ }
159
+ async close() {
160
+ clearInterval(this.sweeper);
161
+ for (const id of [...this.sessions.keys()])
162
+ this.drop(id);
163
+ }
164
+ }