@ignitionai/cogitator 0.3.0 → 0.4.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.
@@ -0,0 +1,289 @@
1
+ import { authenticationRequired } from "./config.js";
2
+ import { randomBytes } from "node:crypto";
3
+ import { closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
4
+ import { createServer } from "node:net";
5
+ import { join, resolve } from "node:path";
6
+ import Database from "better-sqlite3";
7
+ import { z } from "zod";
8
+ import { assertOwner, AuthError, createNativeAuth, issueSetupKey, migrateAuth } from "./native-auth.js";
9
+ export const authPaths = (home) => ({ directory: join(home, "auth"), required: join(home, "auth-required"),
10
+ maintenance: join(home, "auth-maintenance"), config: join(home, "auth", "config.json"), db: join(home, "auth", "auth.sqlite"), socket: join(home, "auth", "owner.sock") });
11
+ /** Conservative Unix sun_path limit, including space for its terminating NUL on supported platforms. */
12
+ export function validateOwnerSocketPath(home) {
13
+ if (Buffer.byteLength(authPaths(home).socket, "utf8") > 103)
14
+ throw new Error("Owner socket path exceeds 103 UTF-8 bytes; choose a shorter COGITATOR_HOME.");
15
+ }
16
+ export function protectedRequired(home, explicit) {
17
+ try {
18
+ explicit ??= authenticationRequired();
19
+ }
20
+ catch {
21
+ throw new AuthError("AUTH_UNAVAILABLE", 503);
22
+ }
23
+ const p = authPaths(home);
24
+ return explicit || [p.required, p.directory, p.maintenance].some(path => {
25
+ try {
26
+ lstatSync(path);
27
+ return true;
28
+ }
29
+ catch (err) {
30
+ if (err.code === "ENOENT")
31
+ return false;
32
+ throw err;
33
+ }
34
+ });
35
+ }
36
+ export function checkPrivate(path, directory = false) {
37
+ const s = lstatSync(path);
38
+ if (s.isSymbolicLink() || (directory ? !s.isDirectory() : !s.isFile()) || (s.mode & 0o077) !== 0 ||
39
+ (process.getuid && s.uid !== process.getuid()))
40
+ throw new AuthError("AUTH_UNAVAILABLE", 503);
41
+ }
42
+ function checkHome(home) {
43
+ const s = lstatSync(home);
44
+ if (s.isSymbolicLink() || !s.isDirectory() || (s.mode & 0o022) !== 0 || (process.getuid && s.uid !== process.getuid()))
45
+ throw new AuthError("AUTH_UNAVAILABLE", 503);
46
+ }
47
+ function syncDirectory(path) {
48
+ const fd = openSync(path, "r");
49
+ try {
50
+ fsyncSync(fd);
51
+ }
52
+ finally {
53
+ closeSync(fd);
54
+ }
55
+ }
56
+ export function privateWrite(path, data, exclusive = false) {
57
+ const fd = openSync(path, exclusive ? "wx" : "w", 0o600);
58
+ try {
59
+ writeFileSync(fd, data);
60
+ fsyncSync(fd);
61
+ }
62
+ finally {
63
+ closeSync(fd);
64
+ }
65
+ syncDirectory(resolve(path, ".."));
66
+ }
67
+ export function maintenance(home) {
68
+ const path = authPaths(home).maintenance;
69
+ if (existsSync(path)) {
70
+ checkPrivate(path);
71
+ return;
72
+ }
73
+ privateWrite(path, "Offline administration incomplete. Run auth recover with all servers stopped.\n", true);
74
+ }
75
+ function finishMaintenance(home) {
76
+ privateWrite(authPaths(home).required, "required\n");
77
+ unlinkSync(authPaths(home).maintenance);
78
+ syncDirectory(home);
79
+ }
80
+ export function lockHome(home) {
81
+ mkdirSync(home, { recursive: true, mode: 0o700 });
82
+ checkHome(home);
83
+ const path = join(home, "owner-lock.sqlite");
84
+ if (!existsSync(path)) {
85
+ try {
86
+ privateWrite(path, "", true);
87
+ }
88
+ catch (err) {
89
+ if (!existsSync(path))
90
+ throw err;
91
+ }
92
+ }
93
+ checkPrivate(path);
94
+ const db = new Database(path, { timeout: 0 });
95
+ try {
96
+ db.exec("BEGIN EXCLUSIVE");
97
+ }
98
+ catch {
99
+ db.close();
100
+ throw new Error("Data home is busy; stop all Cogitator instances before offline administration.");
101
+ }
102
+ return () => { db.exec("ROLLBACK"); db.close(); };
103
+ }
104
+ export async function reservePort(port) {
105
+ const server = createServer(socket => socket.destroy());
106
+ await new Promise((done, reject) => { server.once("error", reject); server.listen(port, "127.0.0.1", done); });
107
+ return () => new Promise((done, reject) => server.close(err => err ? reject(err) : done()));
108
+ }
109
+ const configSchema = z.object({ origin: z.string().url(), secret: z.string().min(32), replayKey: z.string().min(32), ownerId: z.string().min(1) }).strict();
110
+ export function validateOrigin(origin) {
111
+ const url = new URL(origin);
112
+ if (url.protocol !== "https:" || url.username || url.password || url.origin !== origin)
113
+ throw new Error("Origin must be an exact HTTPS origin, without a path.");
114
+ return origin;
115
+ }
116
+ export function loadAuth(home, allowMaintenance = false) {
117
+ validateOwnerSocketPath(home);
118
+ if (process.platform === "win32")
119
+ throw new AuthError("AUTH_UNAVAILABLE", 503);
120
+ const p = authPaths(home);
121
+ checkHome(home);
122
+ checkPrivate(p.required);
123
+ checkPrivate(p.directory, true);
124
+ checkPrivate(p.config);
125
+ checkPrivate(p.db);
126
+ if (!allowMaintenance && (readFileSync(p.required, "utf8") !== "required\n" || existsSync(p.maintenance)))
127
+ throw new AuthError("AUTH_UNAVAILABLE", 503);
128
+ for (const name of readdirSync(p.directory)) {
129
+ if (name === "owner.sock")
130
+ continue;
131
+ checkPrivate(join(p.directory, name));
132
+ }
133
+ const config = configSchema.parse(JSON.parse(readFileSync(p.config, "utf8")));
134
+ validateOrigin(config.origin);
135
+ const db = new Database(p.db, { fileMustExist: true });
136
+ try {
137
+ assertOwner(db, config);
138
+ }
139
+ catch (err) {
140
+ if (!allowMaintenance) {
141
+ db.close();
142
+ throw err;
143
+ }
144
+ }
145
+ const { auth } = createNativeAuth(db, config);
146
+ const identities = [p.required, p.directory, p.config, p.db].map(path => ({ path, stat: lstatSync(path) }));
147
+ return { db, config, auth, home, assertAvailable: () => {
148
+ checkPrivate(p.required);
149
+ checkPrivate(p.directory, true);
150
+ checkPrivate(p.db);
151
+ checkPrivate(p.config);
152
+ if (readFileSync(p.required, "utf8") !== "required\n" || existsSync(p.maintenance))
153
+ throw new AuthError("AUTH_UNAVAILABLE", 503);
154
+ for (const { path, stat } of identities) {
155
+ const current = lstatSync(path);
156
+ if (current.ino !== stat.ino || current.dev !== stat.dev)
157
+ throw new AuthError("AUTH_UNAVAILABLE", 503);
158
+ }
159
+ assertOwner(db, config);
160
+ } };
161
+ }
162
+ /** Caller holds the data-home lock and configured port reservation. No application catalog is opened. */
163
+ export async function initializeOwner(home, origin, email, password) {
164
+ validateOwnerSocketPath(home);
165
+ validateOrigin(origin);
166
+ z.email().parse(email);
167
+ if (password.length < 12 || password.length > 128)
168
+ throw new Error("Password must have 12–128 characters.");
169
+ if (process.platform === "win32")
170
+ throw new AuthError("AUTH_UNAVAILABLE", 503);
171
+ const p = authPaths(home);
172
+ const resuming = protectedRequired(home, false);
173
+ if (resuming && !existsSync(p.maintenance) && (!existsSync(p.required) || readFileSync(p.required, "utf8") !== "initializing\n"))
174
+ throw new Error("Protected state already exists; use offline recovery, never reinitialize it.");
175
+ if (!existsSync(p.required))
176
+ privateWrite(p.required, "initializing\n", true);
177
+ else
178
+ checkPrivate(p.required);
179
+ maintenance(home);
180
+ if (!existsSync(p.directory)) {
181
+ mkdirSync(p.directory, { mode: 0o700 });
182
+ syncDirectory(home);
183
+ }
184
+ else
185
+ checkPrivate(p.directory, true);
186
+ let config;
187
+ if (existsSync(p.config)) {
188
+ checkPrivate(p.config);
189
+ config = configSchema.parse(JSON.parse(readFileSync(p.config, "utf8")));
190
+ if (config.ownerId !== "pending")
191
+ throw new Error("Protected state already exists; use offline recovery.");
192
+ if (config.origin !== origin)
193
+ throw new Error("Resume initialization with the original HTTPS origin.");
194
+ }
195
+ else {
196
+ if (existsSync(p.db))
197
+ throw new Error("Missing auth secret; restore the private auth backup, never replace credentials in place.");
198
+ config = { origin, secret: randomBytes(48).toString("base64url"), replayKey: randomBytes(48).toString("base64url"), ownerId: "pending" };
199
+ privateWrite(p.config, JSON.stringify(config), true);
200
+ }
201
+ if (!existsSync(p.db))
202
+ privateWrite(p.db, "", true);
203
+ else
204
+ checkPrivate(p.db);
205
+ const db = new Database(p.db);
206
+ try {
207
+ let resetToken;
208
+ const { auth, options } = createNativeAuth(db, config, true, token => { resetToken = token; });
209
+ await migrateAuth(db, options);
210
+ const owners = db.prepare("SELECT id,email FROM user").all();
211
+ if (owners.length > 1 || (owners[0] && owners[0].email !== email.toLowerCase()))
212
+ throw new AuthError("AUTH_UNAVAILABLE", 503);
213
+ if (owners[0]) {
214
+ config.ownerId = owners[0].id;
215
+ await auth.api.requestPasswordReset({ body: { email: owners[0].email } });
216
+ if (!resetToken)
217
+ throw new AuthError("AUTH_UNAVAILABLE", 503);
218
+ await auth.api.resetPassword({ body: { token: resetToken, newPassword: password } });
219
+ resetToken = undefined;
220
+ }
221
+ else
222
+ config.ownerId = (await auth.api.signUpEmail({ body: { name: "Owner", email, password } })).user.id;
223
+ db.transaction(() => {
224
+ db.prepare("INSERT INTO authPolicy(singleton,ownerId) VALUES(1,?) ON CONFLICT(singleton) DO UPDATE SET ownerId=excluded.ownerId").run(config.ownerId);
225
+ db.exec("DELETE FROM session; DELETE FROM verification;");
226
+ })();
227
+ if (existsSync(`${p.config}.tmp`)) {
228
+ checkPrivate(`${p.config}.tmp`);
229
+ unlinkSync(`${p.config}.tmp`);
230
+ }
231
+ privateWrite(`${p.config}.tmp`, JSON.stringify(config), true);
232
+ renameSync(`${p.config}.tmp`, p.config);
233
+ syncDirectory(p.directory);
234
+ const key = issueSetupKey(db, config);
235
+ assertOwner(db, config);
236
+ finishMaintenance(home);
237
+ return key;
238
+ }
239
+ finally {
240
+ db.close();
241
+ }
242
+ }
243
+ /** Maintenance stays durable on every exception, including a consumed reset token or partial password write. */
244
+ export async function recoverOwner(home, password) {
245
+ validateOwnerSocketPath(home);
246
+ maintenance(home);
247
+ const state = loadAuth(home, true);
248
+ const { db, config } = state;
249
+ let token;
250
+ try {
251
+ const owners = db.prepare("SELECT id,email FROM user").all();
252
+ if (owners.length !== 1 || owners[0]?.id !== config.ownerId)
253
+ throw new AuthError("AUTH_UNAVAILABLE", 503);
254
+ const { auth } = createNativeAuth(db, config, true, value => { token = value; });
255
+ await auth.api.requestPasswordReset({ body: { email: owners[0].email } });
256
+ if (!token)
257
+ throw new AuthError("AUTH_UNAVAILABLE", 503);
258
+ await auth.api.resetPassword({ body: { token, newPassword: password } });
259
+ token = undefined;
260
+ db.transaction(() => {
261
+ db.prepare("UPDATE user SET twoFactorEnabled=0 WHERE id=?").run(config.ownerId);
262
+ db.exec("DELETE FROM twoFactor; DELETE FROM session; DELETE FROM verification;");
263
+ db.prepare("UPDATE authPolicy SET claimId=NULL, claimExpires=0, setupDigest=NULL, setupExpires=0 WHERE singleton=1").run();
264
+ }).immediate();
265
+ const key = issueSetupKey(db, config);
266
+ assertOwner(db, config);
267
+ finishMaintenance(home);
268
+ return key;
269
+ }
270
+ finally {
271
+ token = undefined;
272
+ db.close();
273
+ }
274
+ }
275
+ export function replaceSetupKey(home) {
276
+ const state = loadAuth(home);
277
+ try {
278
+ if (state.db.prepare("SELECT twoFactorEnabled FROM user WHERE id=?").get(state.config.ownerId).twoFactorEnabled)
279
+ throw new Error("Already enrolled; use offline recovery.");
280
+ maintenance(home);
281
+ state.db.exec("DELETE FROM session; DELETE FROM verification; DELETE FROM twoFactor;");
282
+ const key = issueSetupKey(state.db, state.config);
283
+ finishMaintenance(home);
284
+ return key;
285
+ }
286
+ finally {
287
+ state.db.close();
288
+ }
289
+ }
package/dist/src/board.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { checkRequestAuthorization } from "./request-authorization.js";
1
2
  import { execFile } from "node:child_process";
2
3
  import { join } from "node:path";
3
4
  import { readJson, atomicWriteJson } from "./json-files.js";
@@ -21,6 +22,7 @@ const GH_MAX_BUFFER = 8 * 1024 * 1024;
21
22
  const GH_ERROR_MAX = 300;
22
23
  const GH_ISSUE_LIMIT = 200;
23
24
  function gh(wsDir, args, timeoutMs = GH_TIMEOUT_MS) {
25
+ checkRequestAuthorization();
24
26
  return new Promise((resolve) => {
25
27
  execFile("gh", args, { cwd: wsDir, timeout: timeoutMs, maxBuffer: GH_MAX_BUFFER }, (err, stdout, stderr) => {
26
28
  resolve({ ok: !err, stdout: String(stdout), stderr: String(stderr).trim() });
@@ -92,6 +94,7 @@ function readSidecar(wsDir) {
92
94
  return { version: 2, extras: {} }; // v1 ou invalide : on repart sur un sidecar vide (migration gérée par GitHub)
93
95
  }
94
96
  function saveSidecar(wsDir, sidecar) {
97
+ checkRequestAuthorization();
95
98
  atomicWriteJson(boardPath(wsDir), sidecar);
96
99
  }
97
100
  /** Extras Cogitator d'une carte (clé = numéro d'issue). */
package/dist/src/cli.js CHANGED
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  import { EventEmitter } from "node:events";
3
- import { mkdirSync } from "node:fs";
3
+ import { createServer } from "node:http";
4
4
  import { join } from "node:path";
5
5
  import { getPackageDir, RpcClient } from "@earendil-works/pi-coding-agent";
6
- import { HOST, PORT } from "./config.js";
6
+ import { authenticationRequired, HOST, PORT } from "./config.js";
7
7
  import { CronService } from "./cron.js";
8
8
  import { setConversationStatus } from "./conversations.js";
9
9
  import { seedDefaultAgents } from "./default-agent.js";
@@ -11,61 +11,85 @@ import { openDb } from "./db.js";
11
11
  import { getPaths } from "./paths.js";
12
12
  import { PiPool } from "./pool.js";
13
13
  import { createApp } from "./server.js";
14
+ import { authCommand } from "./auth-cli.js";
15
+ import { loadAuth, lockHome, protectedRequired } from "./auth-state.js";
16
+ import { listenOwnerSocket } from "./owner-transport.js";
14
17
  import { makeSpawner } from "./spawner.js";
15
- const paths = getPaths();
16
- mkdirSync(paths.home, { recursive: true });
17
- const { db, version } = openDb(paths.db);
18
- /** Cadences du service (bornes nommées : un chiffre nu ici est une décision, pas un détail). */
18
+ import { mkdirSync } from "node:fs";
19
19
  const SWEEP_INTERVAL_MS = 60_000;
20
20
  const CRON_TICK_MS = 30_000;
21
- // Seed des agents par défaut : Majordome (opérateur) + Chef de Projet (PM)
22
- {
23
- const seeded = seedDefaultAgents(db, paths);
24
- if (seeded.majordome)
25
- console.log("[cogitator] agent par défaut créé : Majordome");
26
- if (seeded.chef)
27
- console.log("[cogitator] agent créé : Chef de Projet");
28
- if (seeded.architecte)
29
- console.log("[cogitator] agent créé : Architecte de Skills");
30
- }
31
- // I3 : tout spawn passe par ce pool (factory RpcClient officiel, cli.js du pi résolu)
32
- const factory = (opts) => new RpcClient({ cliPath: join(getPackageDir(), "dist/cli.js"), cwd: opts.cwd, args: opts.args, env: opts.env });
33
- const pool = new PiPool({
34
- factory,
35
- callbacks: { onStatus: (convId, status) => setConversationStatus(db, convId, status) },
36
- });
37
- const events = new EventEmitter();
38
- const spawner = makeSpawner({ db, pool, paths });
39
- const cron = new CronService({
40
- db, pool, spawner,
41
- notify: (event) => events.emit("event", event),
42
- });
43
- const server = createApp({ db, dbPath: paths.db, dbVersion: version, paths, pool, cron, events });
44
- server.listen(PORT, HOST, () => {
45
- console.log(`[cogitator] http://${HOST}:${PORT}`);
46
- console.log(`[cogitator] data: ${paths.home}`);
47
- console.log(`[cogitator] pi agents: ${paths.piAgentsDir}`);
48
- });
49
- server.on("error", (err) => {
50
- if (err.code === "EADDRINUSE") {
51
- console.error(`[cogitator] port ${PORT} déjà utilisé — Cogitator tourne déjà ? (COGITATOR_PORT pour changer)`);
52
- process.exit(1);
21
+ const paths = getPaths();
22
+ try {
23
+ const required = authenticationRequired();
24
+ const args = process.argv.slice(2);
25
+ if (args[0] === "auth")
26
+ await authCommand(paths.home, PORT, args.slice(1));
27
+ else {
28
+ if (args.length > 1 || args.some(arg => arg !== "--auth-required"))
29
+ throw new Error("Usage: cogitator [--auth-required] | cogitator auth <init|recover|setup-key>");
30
+ await start(required || args.length === 1);
53
31
  }
54
- throw err;
55
- });
56
- // Recyclage idle toutes les minutes
57
- const sweeper = setInterval(() => {
58
- pool.sweep().catch(() => undefined);
59
- }, SWEEP_INTERVAL_MS);
60
- cron.start(CRON_TICK_MS);
61
- async function shutdown() {
62
- clearInterval(sweeper);
63
- cron.stop();
64
- await pool.dispose();
65
- server.close();
66
- db.close();
67
- process.exit(0);
68
32
  }
69
- for (const sig of ["SIGINT", "SIGTERM"]) {
70
- process.on(sig, () => void shutdown());
33
+ catch (err) {
34
+ console.error(`[cogitator] ${err instanceof Error ? err.message : "Startup failed"}`);
35
+ process.exitCode = 1;
36
+ }
37
+ async function start(explicit) {
38
+ mkdirSync(paths.home, { recursive: true });
39
+ const unlock = process.platform === "win32" ? () => { } : lockHome(paths.home);
40
+ let auth;
41
+ let db;
42
+ const server = createServer((_req, res) => { res.writeHead(503, { "content-type": "application/json", "cache-control": "no-store" }); res.end('{"error":"AUTH_UNAVAILABLE"}'); });
43
+ let privateServer;
44
+ try {
45
+ auth = protectedRequired(paths.home, explicit) ? loadAuth(paths.home) : undefined;
46
+ // Detect even an old incompatible binary on the configured port before catalog/seed side effects.
47
+ await new Promise((done, reject) => { server.once("error", reject); server.listen(PORT, HOST, done); });
48
+ privateServer = auth ? await listenOwnerSocket(server, paths.home) : undefined;
49
+ const opened = openDb(paths.db);
50
+ db = opened.db;
51
+ seedDefaultAgents(db, paths);
52
+ const catalog = db;
53
+ const pool = new PiPool({
54
+ factory: (opts) => new RpcClient({ cliPath: join(getPackageDir(), "dist/cli.js"), cwd: opts.cwd, args: opts.args, env: opts.env }),
55
+ callbacks: { onStatus: (convId, status) => setConversationStatus(catalog, convId, status) },
56
+ });
57
+ const events = new EventEmitter();
58
+ const cron = new CronService({ db, pool, spawner: makeSpawner({ db, pool, paths }), notify: event => events.emit("event", event) });
59
+ server.removeAllListeners("request");
60
+ createApp({ db, dbPath: paths.db, dbVersion: opened.version, paths, pool, cron, events, auth, server });
61
+ console.log(`[cogitator] ${auth ? auth.config.origin : `http://${HOST}:${PORT}`}`);
62
+ const sweeper = setInterval(() => { pool.sweep().catch(() => undefined); }, SWEEP_INTERVAL_MS);
63
+ cron.start(CRON_TICK_MS);
64
+ let stopping = false;
65
+ const shutdown = async () => {
66
+ if (stopping)
67
+ return;
68
+ stopping = true;
69
+ clearInterval(sweeper);
70
+ cron.stop();
71
+ privateServer?.closeAllConnections();
72
+ server.closeAllConnections();
73
+ await Promise.all([close(server), ...(privateServer ? [close(privateServer)] : [])]);
74
+ await pool.dispose();
75
+ auth?.db.close();
76
+ catalog.close();
77
+ unlock();
78
+ };
79
+ for (const signal of ["SIGINT", "SIGTERM"])
80
+ process.once(signal, () => { void shutdown().catch(() => { process.exitCode = 1; }); });
81
+ }
82
+ catch (err) {
83
+ privateServer?.closeAllConnections();
84
+ server.closeAllConnections();
85
+ if (privateServer?.listening)
86
+ await close(privateServer);
87
+ if (server.listening)
88
+ await close(server);
89
+ auth?.db.close();
90
+ db?.close();
91
+ unlock();
92
+ throw err;
93
+ }
71
94
  }
95
+ function close(server) { return new Promise((done, reject) => server.close(err => err ? reject(err) : done())); }
@@ -5,3 +5,10 @@ const DEFAULT_PORT = 5320;
5
5
  export const PORT = Number(process.env.COGITATOR_PORT ?? DEFAULT_PORT);
6
6
  /** URL de base du serveur local — COGITATOR_URL l'emporte (ex. autre port/hôte). */
7
7
  export const BASE_URL = process.env.COGITATOR_URL ?? `http://${HOST}:${PORT}`;
8
+ /** Only explicit 0/1 are supported; a typo must never silently select local mode. */
9
+ export function authenticationRequired(env = process.env) {
10
+ const value = env.COGITATOR_AUTH_REQUIRED;
11
+ if (value !== undefined && value !== "0" && value !== "1")
12
+ throw new Error("COGITATOR_AUTH_REQUIRED must be unset, 0, or 1.");
13
+ return value === "1";
14
+ }
@@ -2,15 +2,18 @@ import { randomUUID } from "node:crypto";
2
2
  import { UI_INSTRUCTIONS } from "./generative-ui.js";
3
3
  /** Longueur max du titre dérivé d'un message (contrainte d'affichage de l'UI). */
4
4
  const TITLE_MAX = 80;
5
- export function listConversations(db, workspaceId) {
5
+ export function listConversations(db, workspaceId, agentId) {
6
+ const where = [
7
+ workspaceId ? "c.workspace_id = ?" : "",
8
+ agentId ? "c.agent_id = ?" : "",
9
+ ].filter(Boolean).join(" AND ");
6
10
  const sql = `
7
11
  SELECT c.*, w.dir AS workspace_dir FROM conversation c
8
12
  LEFT JOIN workspace w ON w.id = c.workspace_id
9
- ${workspaceId ? "WHERE c.workspace_id = ?" : ""}
13
+ ${where ? `WHERE ${where}` : ""}
10
14
  ORDER BY c.updated_at DESC`;
11
- return (workspaceId
12
- ? db.prepare(sql).all(workspaceId)
13
- : db.prepare(sql).all());
15
+ const params = [workspaceId, agentId].filter((v) => Boolean(v));
16
+ return (params.length ? db.prepare(sql).all(...params) : db.prepare(sql).all());
14
17
  }
15
18
  export function getConversation(db, id) {
16
19
  const row = db
package/dist/src/db.js CHANGED
@@ -102,6 +102,7 @@ ALTER TABLE conversation_v2 RENAME TO conversation;
102
102
  `;
103
103
  // v2 → v3 : agent par défaut global (le "Majordome")
104
104
  const MIGRATE_V2_TO_V3 = `ALTER TABLE agent_preset ADD COLUMN is_default INTEGER NOT NULL DEFAULT 0;`;
105
+ const MIGRATE_V3_TO_V4 = `ALTER TABLE agent_preset ADD COLUMN default_workspace_id TEXT REFERENCES workspace(id) ON DELETE SET NULL;`;
105
106
  export function openDb(dbPath) {
106
107
  const db = new Database(dbPath);
107
108
  db.pragma("journal_mode = WAL");
@@ -110,8 +111,9 @@ export function openDb(dbPath) {
110
111
  if (version < 1) {
111
112
  db.exec(SCHEMA_V2);
112
113
  db.exec(MIGRATE_V2_TO_V3);
113
- db.pragma("user_version = 3");
114
- return { db, version: 3 };
114
+ db.exec(MIGRATE_V3_TO_V4);
115
+ db.pragma("user_version = 4");
116
+ return { db, version: 4 };
115
117
  }
116
118
  if (version < 2) {
117
119
  // FK OFF pendant la migration (pratique SQLite standard ; les parents peuvent être créés plus tard)
@@ -124,5 +126,9 @@ export function openDb(dbPath) {
124
126
  db.exec(MIGRATE_V2_TO_V3);
125
127
  db.pragma("user_version = 3");
126
128
  }
127
- return { db, version: 3 };
129
+ if (version < 4) {
130
+ db.exec(MIGRATE_V3_TO_V4);
131
+ db.pragma("user_version = 4");
132
+ }
133
+ return { db, version: 4 };
128
134
  }
@@ -9,21 +9,10 @@
9
9
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
10
10
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
11
11
  import { z } from "zod";
12
- import { BASE_URL } from "./config.js";
12
+ import { ownerRequest } from "./owner-transport.js";
13
13
  import { packageVersion } from "./pi.js";
14
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
- }
15
+ const call = ownerRequest;
27
16
  const server = new McpServer({
28
17
  name: "cogitator",
29
18
  version: packageVersion(),
@@ -164,4 +153,4 @@ addTool("cogitator_board_comment", "Ajoute un commentaire à une carte (append-o
164
153
  }, (a) => call("POST", `/api/workspaces/${a.workspace_id}/board/cards/${a.card_id}/comments`, { text: a.text, author: a.author ?? "Majordome" }));
165
154
  const transport = new StdioServerTransport();
166
155
  await server.connect(transport);
167
- console.error(`[cogitator-mcp] connecté à ${BASE}`);
156
+ console.error("[cogitator-mcp] connecté (stdio)");