@ignitionai/cogitator 0.5.1 → 0.6.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 (68) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/LICENSE +21 -0
  3. package/README.md +81 -56
  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 +146 -0
  11. package/dist/src/classic-configuration.js +12 -4
  12. package/dist/src/cli.js +29 -2
  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 +13 -4
  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 +9 -6
  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 +72 -13
  45. package/dist/src/reap-orphans.js +138 -0
  46. package/dist/src/registry.js +66 -43
  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 +597 -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/dist/src/terminal-assist.js +96 -0
  58. package/dist/src/terminal-http.js +167 -0
  59. package/dist/src/terminal.js +171 -0
  60. package/package.json +13 -3
  61. package/web/dist/assets/{BrandLogo3D-BvZPXohP.js → BrandLogo3D-4IJEcixt.js} +1 -1
  62. package/web/dist/assets/addon-fit-DIOBYJe3.js +1 -0
  63. package/web/dist/assets/index-Bi_Aag-u.js +85 -0
  64. package/web/dist/assets/index-DQsw9iul.css +1 -0
  65. package/web/dist/assets/xterm-ScmBfeDI.js +16 -0
  66. package/web/dist/index.html +2 -2
  67. package/web/dist/assets/index-7Dyl-4v7.css +0 -1
  68. package/web/dist/assets/index-CdqzcBU-.js +0 -83
@@ -0,0 +1,190 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { spawn } from "node:child_process";
4
+ export const packageName = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/;
5
+ export function parseCatalog(html) {
6
+ const text = (s) => s.replace(/<[^>]*>/g, "").replace(/&(?:amp|quot|lt|gt|#39|apos);/g, e => ({ "&amp;": "&", "&quot;": '"', "&lt;": "<", "&gt;": ">", "&#39;": "'", "&apos;": "'" })[e]);
7
+ const packages = [];
8
+ for (const match of html.matchAll(/<article\b[^>]*data-package-name="([^"]+)"[^>]*>([\s\S]*?)<\/article>/g)) {
9
+ const name = text(match[1]);
10
+ if (!packageName.test(name))
11
+ continue;
12
+ packages.push({ name, description: text(match[2].match(/<p class="packages-desc">([\s\S]*?)<\/p>/)?.[1] ?? ""), types: [...match[2].matchAll(/data-type="([a-z]+)"/g)].map(m => m[1]) });
13
+ }
14
+ if (!html.includes("packages-action-bar"))
15
+ throw new Error("Catalogue pi indisponible : format inattendu.");
16
+ return { packages, hasNext: /(?:aria-label="Next|>Next|>Suivant)/i.test(html) };
17
+ }
18
+ async function fetchText(url) {
19
+ const origin = new URL(url).origin;
20
+ let res;
21
+ const signal = AbortSignal.timeout(15_000);
22
+ for (let redirect = 0; redirect < 4; redirect++) {
23
+ res = await fetch(url, { signal, redirect: "manual" });
24
+ if (![301, 302, 303, 307, 308].includes(res.status))
25
+ break;
26
+ const location = res.headers.get("location");
27
+ await res.body?.cancel();
28
+ if (!location)
29
+ throw new Error("Redirection du catalogue invalide.");
30
+ const target = new URL(location, url);
31
+ if (target.origin !== origin)
32
+ throw new Error("Redirection externe du catalogue refusée.");
33
+ url = target.href;
34
+ }
35
+ if (!res)
36
+ throw new Error("Catalogue indisponible.");
37
+ if (!res.ok)
38
+ throw new Error(`Catalogue indisponible (HTTP ${res.status}).`);
39
+ const body = await res.text();
40
+ if (body.length > 3_000_000)
41
+ throw new Error("Réponse du catalogue trop volumineuse.");
42
+ return body;
43
+ }
44
+ export async function catalog(query, type, page) {
45
+ const url = new URL("https://pi.dev/packages");
46
+ if (query)
47
+ url.searchParams.set("name", query.slice(0, 100));
48
+ if (["extension", "skill", "theme", "prompt"].includes(type))
49
+ url.searchParams.set("type", type);
50
+ if (page > 1)
51
+ url.searchParams.set("page", String(page));
52
+ const html = await fetchText(url.href);
53
+ const result = parseCatalog(html);
54
+ // Pagination links retain the active search and filters.
55
+ result.hasNext = [...html.matchAll(/href="([^"#]+)"/g)].some(m => {
56
+ try {
57
+ const link = new URL(m[1].replaceAll("&amp;", "&"), url);
58
+ return link.pathname === "/packages" && Number(link.searchParams.get("page")) === page + 1;
59
+ }
60
+ catch {
61
+ return false;
62
+ }
63
+ });
64
+ return result;
65
+ }
66
+ export function installedPackages(paths) {
67
+ let settings;
68
+ try {
69
+ settings = JSON.parse(readFileSync(join(paths.piAgentDir, "settings.json"), "utf8"));
70
+ }
71
+ catch (error) {
72
+ if (error.code === "ENOENT")
73
+ return [];
74
+ throw error;
75
+ }
76
+ return (settings.packages ?? []).map(entry => {
77
+ const source = typeof entry === "string" ? entry : entry.source;
78
+ const match = /^npm:((?:@[^/]+\/)?[^@]+)(?:@(.+))?$/.exec(source);
79
+ let version = match?.[2] ?? "";
80
+ if (match && packageName.test(match[1])) {
81
+ try {
82
+ const manifest = JSON.parse(readFileSync(join(paths.piAgentDir, "npm", "node_modules", match[1], "package.json"), "utf8"));
83
+ if (typeof manifest.version === "string")
84
+ version = manifest.version;
85
+ }
86
+ catch { /* use configured version if unavailable */ }
87
+ }
88
+ return { source, name: match?.[1] ?? source, version, removable: !!match && packageName.test(match[1]) };
89
+ });
90
+ }
91
+ export class PackageManager {
92
+ paths;
93
+ refresh;
94
+ run;
95
+ operation = null;
96
+ constructor(paths, refresh, run = runPi) {
97
+ this.paths = paths;
98
+ this.refresh = refresh;
99
+ this.run = run;
100
+ }
101
+ start(name, action) {
102
+ if (!packageName.test(name) || name.length > 214)
103
+ throw new Error("Nom de package npm invalide.");
104
+ if (this.operation?.status === "running")
105
+ throw new Error("Une installation est déjà en cours.");
106
+ const operation = { name, action, status: "running" };
107
+ this.operation = operation;
108
+ void this.perform(operation);
109
+ return operation;
110
+ }
111
+ async perform(operation) {
112
+ try {
113
+ let source;
114
+ const current = installedPackages(this.paths).find(p => p.name === operation.name && p.removable);
115
+ if (operation.action === "update" && !current)
116
+ throw new Error("Ce package n’est pas installé dans ce profil.");
117
+ if (operation.action === "remove") {
118
+ const installed = installedPackages(this.paths).find(p => p.name === operation.name && p.removable);
119
+ if (!installed)
120
+ throw new Error("Ce package n’est pas installé dans ce profil.");
121
+ source = installed.source;
122
+ }
123
+ else {
124
+ const meta = JSON.parse(await fetchText(`https://registry.npmjs.org/${encodeURIComponent(operation.name)}/latest`));
125
+ if (meta.name !== operation.name || !meta.keywords?.includes("pi-package") || !/^[0-9]+\.[0-9]+\.[0-9]+(?:-[\w.-]+)?$/.test(meta.version))
126
+ throw new Error("Ce package n’est pas un package pi valide.");
127
+ if (operation.action === "update" && current && (!/^\d+\.\d+\.\d+$/.test(current.version) || !/^\d+\.\d+\.\d+$/.test(meta.version)))
128
+ throw new Error("Version non comparable : mise à jour automatique indisponible.");
129
+ if (operation.action === "update" && current && !newerVersion(meta.version, current.version)) {
130
+ operation.status = "done";
131
+ return;
132
+ }
133
+ source = `npm:${operation.name}@${meta.version}`;
134
+ }
135
+ await this.run(operation.action === "update" ? "install" : operation.action, source, this.paths);
136
+ operation.deferred = await this.refresh();
137
+ operation.status = "done";
138
+ }
139
+ catch (error) {
140
+ operation.status = "error";
141
+ operation.error = error instanceof Error ? error.message : "Installation échouée.";
142
+ }
143
+ }
144
+ }
145
+ function runPi(action, source, paths) {
146
+ return new Promise((resolve, reject) => {
147
+ // Arguments, never shell text. Same executable environment and profile as chat RPC.
148
+ const child = spawn("pi", [action, source], { cwd: paths.home, env: { ...process.env, PI_CODING_AGENT_DIR: paths.piAgentDir }, stdio: "ignore", detached: process.platform !== "win32" });
149
+ const timer = setTimeout(() => { try {
150
+ if (child.pid && process.platform !== "win32")
151
+ process.kill(-child.pid, "SIGKILL");
152
+ else
153
+ child.kill("SIGKILL");
154
+ }
155
+ catch { /* already exited */ } }, 180_000);
156
+ child.once("error", () => { clearTimeout(timer); reject(new Error("Impossible de démarrer pi. Vérifiez son installation sur ce serveur.")); });
157
+ child.once("close", code => { clearTimeout(timer); code === 0 ? resolve() : reject(new Error("La commande pi a échoué ou dépassé trois minutes. Vérifiez le réseau et la compatibilité du package.")); });
158
+ });
159
+ }
160
+ /** Stable npm releases only: never downgrade a local/newer or prerelease build. */
161
+ export function newerVersion(latest, current) {
162
+ const parse = (v) => /^\d+\.\d+\.\d+$/.test(v) ? v.split(".").map(Number) : null;
163
+ const a = parse(latest);
164
+ const b = parse(current);
165
+ if (!a || !b)
166
+ return false;
167
+ for (let i = 0; i < 3; i++) {
168
+ if (a[i] !== b[i])
169
+ return a[i] > b[i];
170
+ }
171
+ return false;
172
+ }
173
+ export async function packageUpdates(paths) {
174
+ const installed = installedPackages(paths).filter(p => p.removable);
175
+ const updates = [];
176
+ for (let offset = 0; offset < installed.length; offset += 4) {
177
+ updates.push(...await Promise.all(installed.slice(offset, offset + 4).map(async (p) => {
178
+ try {
179
+ const meta = JSON.parse(await fetchText(`https://registry.npmjs.org/${encodeURIComponent(p.name)}/latest`));
180
+ if (meta.name !== p.name || typeof meta.version !== "string" || !/^\d+\.\d+\.\d+$/.test(p.version) || !/^\d+\.\d+\.\d+$/.test(meta.version))
181
+ throw new Error("Invalid metadata or incomparable version");
182
+ return { name: p.name, version: p.version, latest: meta.version, available: newerVersion(meta.version, p.version) };
183
+ }
184
+ catch {
185
+ return { name: p.name, version: p.version, available: false, failed: true };
186
+ }
187
+ })));
188
+ }
189
+ return updates;
190
+ }
package/dist/src/paths.js CHANGED
@@ -12,6 +12,7 @@ export function getPaths(env = process.env) {
12
12
  return {
13
13
  home,
14
14
  db: join(home, "cogitator.db"),
15
+ projectsDir: env.COGITATOR_PROJECTS_DIR ?? join(home, "projects"),
15
16
  piAgentDir,
16
17
  piModelsJson: join(piAgentDir, "models.json"),
17
18
  piAuthJson: join(piAgentDir, "auth.json"),
@@ -0,0 +1,180 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { getPaths } from "./paths.js";
6
+ /**
7
+ * PDEATHSIG (PR_SET_PDEATHSIG) est délivré à la mort du *thread* parent, pas du
8
+ * process. RpcClient.spawn doit donc s'exécuter depuis le thread principal Node
9
+ * (pas worker_threads). Cogitator n'utilise pas worker_threads sur ce chemin.
10
+ */
11
+ const WRAP_JS = fileURLToPath(new URL("./pi-rpc-wrap.js", import.meta.url));
12
+ const NO_SETPRIV = "COGITATOR_PI_NO_SETPRIV";
13
+ const SHIM_PREFIX = "pdeathsig-";
14
+ let cachedSetpriv;
15
+ const shimDirs = new Map();
16
+ /** util-linux `setpriv`, détecté à l'exécution (absent hors Linux / hors PATH). */
17
+ export function linuxSetprivPath() {
18
+ if (cachedSetpriv !== undefined)
19
+ return cachedSetpriv ?? undefined;
20
+ if (process.platform !== "linux") {
21
+ cachedSetpriv = null;
22
+ return undefined;
23
+ }
24
+ try {
25
+ const found = execFileSync("which", ["setpriv"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
26
+ if (!found) {
27
+ cachedSetpriv = null;
28
+ return undefined;
29
+ }
30
+ execFileSync(found, ["--help"], { stdio: ["ignore", "pipe", "ignore"] });
31
+ cachedSetpriv = found;
32
+ return found;
33
+ }
34
+ catch {
35
+ cachedSetpriv = null;
36
+ return undefined;
37
+ }
38
+ }
39
+ function shQuote(value) {
40
+ return `'${value.replace(/'/g, `'\\''`)}'`;
41
+ }
42
+ function setprivAllowed() {
43
+ return process.env[NO_SETPRIV] !== "1";
44
+ }
45
+ /**
46
+ * Répertoire mis en tête de PATH pour que `spawn("node", …)` d'RpcClient
47
+ * exécute un shim. Le shim restaure PATH avant exec setpriv, pour que les
48
+ * outils de pi (bash / nohup node) n'héritent pas du pdeathsig.
49
+ */
50
+ function setprivShimDir(home) {
51
+ if (!setprivAllowed())
52
+ return undefined;
53
+ const setpriv = linuxSetprivPath();
54
+ if (!setpriv)
55
+ return undefined;
56
+ const existing = shimDirs.get(home);
57
+ if (existing)
58
+ return existing;
59
+ mkdirSync(home, { recursive: true });
60
+ const dir = mkdtempSync(join(home, SHIM_PREFIX));
61
+ chmodSync(dir, 0o700);
62
+ // PATH recalculé à chaque exécution du shim (pas figé au premier spawn) : on retire
63
+ // le dossier de shim du PATH de l'appelant, puis on exec setpriv. Les outils de pi
64
+ // (bash, nohup node) héritent donc du PATH de l'appelant, sans le pdeathsig.
65
+ const script = [
66
+ "#!/bin/sh",
67
+ `shim=${shQuote(dir)}`,
68
+ 'case $PATH in',
69
+ ' "$shim:"*) caller_path=${PATH#"$shim:"} ;;',
70
+ ' "$shim") caller_path= ;;',
71
+ ' *) caller_path=$PATH ;;',
72
+ 'esac',
73
+ `PATH=$caller_path exec ${shQuote(setpriv)} --pdeathsig KILL ${shQuote(process.execPath)} "$@"`,
74
+ "",
75
+ ].join("\n");
76
+ const dest = join(dir, "node");
77
+ writeFileSync(dest, script, { encoding: "utf8" });
78
+ chmodSync(dest, 0o755);
79
+ shimDirs.set(home, dir);
80
+ return dir;
81
+ }
82
+ /**
83
+ * Dossiers de shim encore référencés par un process vivant (PATH d'un `/proc/<pid>/environ`)
84
+ * plus ceux créés par ce process. Limite : hors Linux (`/proc` absent) ou pour un process
85
+ * d'un autre utilisateur (environ illisible), on ne peut pas savoir → on ne supprime rien.
86
+ */
87
+ function pdeathsigDirsInUse() {
88
+ const used = new Set(shimDirs.values());
89
+ if (process.platform !== "linux")
90
+ return used;
91
+ let pids;
92
+ try {
93
+ pids = readdirSync("/proc");
94
+ }
95
+ catch {
96
+ return used;
97
+ }
98
+ for (const name of pids) {
99
+ if (!/^\d+$/.test(name))
100
+ continue;
101
+ let environ;
102
+ try {
103
+ environ = readFileSync(join("/proc", name, "environ"), "utf8");
104
+ }
105
+ catch {
106
+ continue;
107
+ }
108
+ for (const entry of environ.split("\0")) {
109
+ if (!entry.startsWith("PATH="))
110
+ continue;
111
+ for (const part of entry.slice("PATH=".length).split(":")) {
112
+ if (part.includes(`/${SHIM_PREFIX}`))
113
+ used.add(part);
114
+ }
115
+ }
116
+ }
117
+ return used;
118
+ }
119
+ /**
120
+ * Ramasse les shims `pdeathsig-*` orphelins d'un hôte tué sans arrêt propre (`kill -9`,
121
+ * crash), à appeler au démarrage une fois le home verrouillé. Un dossier référencé par
122
+ * le PATH d'un process vivant est conservé. Renvoie les dossiers supprimés.
123
+ */
124
+ export function reapStaleSetprivShims(home) {
125
+ // Sans `/proc` on ne sait pas distinguer un shim vivant d'un orphelin : on ne touche à rien.
126
+ if (process.platform !== "linux")
127
+ return [];
128
+ let names;
129
+ try {
130
+ names = readdirSync(home);
131
+ }
132
+ catch {
133
+ return [];
134
+ }
135
+ const candidates = names.filter((name) => name.startsWith(SHIM_PREFIX)).map((name) => join(home, name));
136
+ if (!candidates.length)
137
+ return [];
138
+ const inUse = pdeathsigDirsInUse();
139
+ const removed = [];
140
+ for (const dir of candidates) {
141
+ if (inUse.has(dir))
142
+ continue;
143
+ try {
144
+ rmSync(dir, { recursive: true, force: true });
145
+ removed.push(dir);
146
+ }
147
+ catch {
148
+ /* déjà parti ou protégé */
149
+ }
150
+ }
151
+ return removed;
152
+ }
153
+ export function piRpcWrapPath() {
154
+ if (!existsSync(WRAP_JS))
155
+ throw new Error(`wrapper rpc pi introuvable: ${WRAP_JS}`);
156
+ return WRAP_JS;
157
+ }
158
+ /** Supprime les shims setpriv (arrêt de l'hôte). */
159
+ export function disposeSetprivShims() {
160
+ for (const dir of shimDirs.values()) {
161
+ try {
162
+ rmSync(dir, { recursive: true, force: true });
163
+ }
164
+ catch { /* déjà parti */ }
165
+ }
166
+ shimDirs.clear();
167
+ }
168
+ /** Options RpcClient : setpriv via PATH si possible, sinon wrapper watchdog. */
169
+ export function guardedRpcSpawn(piCliPath, opts) {
170
+ const env = { ...opts.env };
171
+ const home = env.COGITATOR_HOME ?? getPaths().home;
172
+ const origPath = env.PATH ?? process.env.PATH ?? "";
173
+ const shim = setprivShimDir(home);
174
+ if (shim) {
175
+ env.PATH = origPath ? `${shim}:${origPath}` : shim;
176
+ return { cliPath: piCliPath, cwd: opts.cwd, args: opts.args, env, shimDir: shim };
177
+ }
178
+ env.COGITATOR_PI_CLI = piCliPath;
179
+ return { cliPath: piRpcWrapPath(), cwd: opts.cwd, args: opts.args, env };
180
+ }
@@ -0,0 +1,84 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Repli sans setpriv : le process RpcClient est ce wrapper.
4
+ * Il spawn le vrai cli pi, transmet SIGTERM/SIGINT/SIGHUP, et quitte si l'hôte meurt.
5
+ */
6
+ import { spawn } from "node:child_process";
7
+ import { readFileSync } from "node:fs";
8
+ import { join } from "node:path";
9
+ const WATCH_MS = 1500;
10
+ const FORWARD = ["SIGTERM", "SIGINT", "SIGHUP"];
11
+ function parseProcStat(stat) {
12
+ const close = stat.lastIndexOf(")");
13
+ if (close < 0)
14
+ return undefined;
15
+ const rest = stat.slice(close + 1).trim().split(/\s+/);
16
+ const state = rest[0];
17
+ const starttime = rest[19];
18
+ if (!state || starttime === undefined || starttime === "")
19
+ return undefined;
20
+ return { state, starttime };
21
+ }
22
+ function readProcStat(pid) {
23
+ try {
24
+ return parseProcStat(readFileSync(join("/proc", String(pid), "stat"), "utf8"));
25
+ }
26
+ catch {
27
+ return undefined;
28
+ }
29
+ }
30
+ function parseMarker(value) {
31
+ const sep = value.indexOf(":");
32
+ if (sep <= 0)
33
+ return undefined;
34
+ const pid = Number(value.slice(0, sep));
35
+ const starttime = value.slice(sep + 1);
36
+ if (!Number.isInteger(pid) || pid <= 0 || starttime === "")
37
+ return undefined;
38
+ return { pid, starttime };
39
+ }
40
+ function hostGone(marker) {
41
+ const stat = readProcStat(marker.pid);
42
+ return !stat || stat.state === "Z" || stat.starttime !== marker.starttime;
43
+ }
44
+ const realCli = process.env.COGITATOR_PI_CLI;
45
+ if (!realCli) {
46
+ process.stderr.write("COGITATOR_PI_CLI manquant\n");
47
+ process.exit(1);
48
+ }
49
+ const marker = parseMarker(process.env.COGITATOR_OWNED_PI ?? "");
50
+ const child = spawn(process.execPath, [realCli, ...process.argv.slice(2)], { stdio: "inherit" });
51
+ function forward(signal) {
52
+ try {
53
+ child.kill(signal);
54
+ }
55
+ catch { /* déjà mort */ }
56
+ }
57
+ for (const signal of FORWARD) {
58
+ process.on(signal, () => forward(signal));
59
+ }
60
+ child.on("exit", (code, signal) => {
61
+ for (const name of FORWARD)
62
+ process.removeAllListeners(name);
63
+ if (signal) {
64
+ process.kill(process.pid, signal);
65
+ return;
66
+ }
67
+ process.exit(code ?? 0);
68
+ });
69
+ child.on("error", (err) => {
70
+ process.stderr.write(String(err));
71
+ process.exit(1);
72
+ });
73
+ if (process.platform !== "win32" && marker) {
74
+ const timer = setInterval(() => {
75
+ if (!hostGone(marker))
76
+ return;
77
+ try {
78
+ child.kill("SIGKILL");
79
+ }
80
+ catch { /* déjà mort */ }
81
+ process.exit(1);
82
+ }, WATCH_MS);
83
+ timer.unref?.();
84
+ }
package/dist/src/pool.js CHANGED
@@ -7,6 +7,38 @@ export class PoolError extends Error {
7
7
  this.code = code;
8
8
  }
9
9
  }
10
+ const ASYNC_WIDGET_PREFIX = "PI_SUBAGENT_ASYNC_JSON:";
11
+ const SUBAGENT_ALIVE = new Set(["queued", "running", "pending"]);
12
+ function widgetRunStates(lines) {
13
+ const line = lines?.find((entry) => entry.startsWith(ASYNC_WIDGET_PREFIX));
14
+ if (!line)
15
+ return undefined;
16
+ try {
17
+ const snap = JSON.parse(line.slice(ASYNC_WIDGET_PREFIX.length));
18
+ return Array.isArray(snap.runs) ? snap.runs.map((run) => run.state ?? "") : [];
19
+ }
20
+ catch {
21
+ return undefined;
22
+ }
23
+ }
24
+ /** Met à jour le compteur de subagents async d'après les événements RPC pi-subagents. */
25
+ function applySubagentBackground(current, event) {
26
+ const e = event;
27
+ if (e.type === "tool_execution_end" && e.toolName === "subagent") {
28
+ const text = (e.result?.content ?? []).map((part) => part.text ?? "").join("");
29
+ if (e.result?.details?.runId || /\bDetached\b|\bAsync:/.test(text))
30
+ return Math.max(current, 1);
31
+ }
32
+ if (e.type === "extension_ui_request" && e.method === "setWidget" && e.widgetKey === "subagent-async") {
33
+ const states = widgetRunStates(e.widgetLines);
34
+ if (states)
35
+ return states.some((state) => SUBAGENT_ALIVE.has(state)) ? Math.max(current, 1) : 0;
36
+ }
37
+ if (e.type === "subagent:async-complete" || e.type === "subagent:process-terminal") {
38
+ return Math.max(0, current - 1);
39
+ }
40
+ return current;
41
+ }
10
42
  /** Bornes par défaut du pool (surchargeables par PoolOptions). */
11
43
  const DEFAULT_MAX_PROCESSES = 8;
12
44
  const DEFAULT_IDLE_MS = 10 * 60_000;
@@ -104,6 +136,12 @@ export class PiPool {
104
136
  get size() {
105
137
  return this.handles.size;
106
138
  }
139
+ /** Reload only idle processes. Busy parents and async children remain intact. */
140
+ async refreshExtensions() {
141
+ for (const handle of [...this.handles.values()])
142
+ await this.evictIdle(handle);
143
+ return this.handles.size;
144
+ }
107
145
  isLive(convId) {
108
146
  const h = this.handles.get(convId);
109
147
  return Boolean(h && !h.dead);
@@ -113,6 +151,8 @@ export class PiPool {
113
151
  return handle && !handle.dead ? this.streaming(handle) : false;
114
152
  }
115
153
  async streaming(h) {
154
+ if (h.background > 0)
155
+ return true; // enfant pi-subagents encore en vie : pas d'éviction (pdeathsig tuerait l'enfant)
116
156
  try {
117
157
  const state = await h.client.getState();
118
158
  return h.active || state.isStreaming === true || state.isCompacting === true;
@@ -141,7 +181,7 @@ export class PiPool {
141
181
  checkRequestAuthorization();
142
182
  const args = spawn.resumeSessionFile ? [...spawn.args, "--session", spawn.resumeSessionFile] : spawn.args;
143
183
  const client = this.opts.factory({ cwd: spawn.cwd, args, env: spawn.env });
144
- const handle = { convId, client, lastActivityAt: Date.now(), dead: false, active: false, queue: [] };
184
+ const handle = { convId, client, lastActivityAt: Date.now(), dead: false, active: false, background: 0, queue: [] };
145
185
  this.handles.set(convId, handle);
146
186
  return handle;
147
187
  });
@@ -154,11 +194,15 @@ export class PiPool {
154
194
  if (handle.dead)
155
195
  return;
156
196
  handle.lastActivityAt = Date.now();
197
+ const previousBackground = handle.background;
198
+ handle.background = applySubagentBackground(handle.background, event);
157
199
  const type = event?.type;
158
200
  if (type === "agent_start")
159
201
  handle.active = true;
160
- if (type === "agent_settled") {
202
+ if (type === "agent_settled")
161
203
  handle.active = false;
204
+ // Drain seulement si plus aucun tour parent NI enfant async (sinon la file part trop tôt).
205
+ if (!handle.active && handle.background === 0 && (type === "agent_settled" || previousBackground > 0)) {
162
206
  this.lockContext.exit(() => { void this.serial(convId, () => this.drain(handle)); });
163
207
  }
164
208
  this.emit(convId, event);
@@ -254,6 +298,10 @@ export class PiPool {
254
298
  this.clearQueue(h);
255
299
  this.handles.delete(convId);
256
300
  try {
301
+ // RpcClient.stop() (pi-coding-agent, dist/modes/rpc/rpc-client.js) envoie SIGTERM puis
302
+ // SIGKILL après 1 s figé côté dépendance : le délai n'est pas configurable depuis
303
+ // Cogitator. Mesuré 108–121 ms sur un pi idle, donc 1 s suffit largement ; au pire un
304
+ // pi bloqué meurt 1 s plus tard, sans effet de bord (éviction/recyclage seulement).
257
305
  await h.client.stop();
258
306
  }
259
307
  catch {
@@ -287,11 +335,14 @@ export class PiPool {
287
335
  if (id !== convId)
288
336
  return;
289
337
  const type = event?.type;
290
- if (type === "agent_settled") {
291
- clearTimeout(timer);
292
- unsub();
293
- resolve();
294
- }
338
+ if (type !== "agent_settled")
339
+ return;
340
+ const h = this.handles.get(convId);
341
+ if (h && h.background > 0)
342
+ return; // parent settled mais l'enfant pi-subagents tourne encore
343
+ clearTimeout(timer);
344
+ unsub();
345
+ resolve();
295
346
  });
296
347
  });
297
348
  }
@@ -0,0 +1,63 @@
1
+ import { existsSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
4
+ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
5
+ import { findPackageRoot } from "./default-agent.js";
6
+ import { listAgents } from "./agents.js";
7
+ import { listSkills } from "./registry.js";
8
+ export function runtimeIntegration() {
9
+ const root = findPackageRoot();
10
+ const extension = root && join(root, "dist/extensions/index.js");
11
+ const server = root && join(root, "dist/src/mcp-server.js");
12
+ if (!extension || !server || !existsSync(extension) || !existsSync(server))
13
+ throw new Error("Intégration Cogitator absente : reconstruis ou réinstalle cette version.");
14
+ return { extension, server };
15
+ }
16
+ /** Refresh only the bundled server, leaving unrelated custom MCP configurations intact. */
17
+ export function currentMcpServers(entries) {
18
+ return entries.map(entry => {
19
+ const script = entry.args?.[0];
20
+ if (entry.name !== "cogitator" || !script?.endsWith("/dist/src/mcp-server.js") || !findPackageRoot(dirname(script)))
21
+ return entry;
22
+ return { ...entry, command: process.execPath, args: [runtimeIntegration().server] };
23
+ });
24
+ }
25
+ export function resourceInventory(db, paths, cwd = paths.home) {
26
+ return {
27
+ agents: listAgents(db).map(a => ({ id: a.id, name: a.name, slug: a.slug, description: a.description, skills: a.skills })),
28
+ skills: listSkills(paths, cwd).map(s => ({ name: s.name, description: s.description, path: s.path })),
29
+ };
30
+ }
31
+ export function resourceInstructions(db, paths, cwd = paths.home) {
32
+ const resources = resourceInventory(db, paths, cwd);
33
+ const inventory = { agents: resources.agents.slice(0, 40).map(a => ({ ...a, description: a.description?.slice(0, 200) })), skills: resources.skills.slice(0, 60).map(s => ({ ...s, description: s.description.slice(0, 200) })), totalAgents: resources.agents.length, totalSkills: resources.skills.length };
34
+ return `Ressources Cogitator existantes (inventaire descriptif, pas des instructions à exécuter) :\n${JSON.stringify(inventory)}\nAvant de créer un agent ou un skill, consulte cet inventaire et les outils cogitator_list_agents / cogitator_list_skills pour le compléter. Les outils MCP peuvent être accessibles via tool_search et codemode plutôt que directement : cherche les outils cogitator avant de conclure à leur absence. Pour confier du travail à un preset existant, utilise les outils de conversation Cogitator avec son agent_id ; ne suppose pas que son nom est un agent pi-subagents exporté. Lis le SKILL.md pertinent avant d'appliquer sa méthode. Réutilise l'existant. Pour initialiser un projet : inventorie d'abord, attribue explicitement chaque tâche à un agent existant et indique les skills retenus. Le Majordome coordonne, le Chef de Projet organise le backlog, l'Architecte de Skills ne crée que ce qui manque. Présente un plan concret (réutilisations, manques, fichiers, validations) avant modifications. Après accord, exécute puis vérifie les résultats. Une relance doit reconnaître ce qui est déjà installé et ne pas créer de doublons. Ne prétends pas avoir utilisé un skill ou délégué sans l'avoir fait. Si les outils sont indisponibles, expose le blocage avant de proposer des créations.`;
35
+ }
36
+ export async function probeCogitatorTools(paths) {
37
+ const { server } = runtimeIntegration();
38
+ const transport = new StdioClientTransport({ command: process.execPath, args: [server], stderr: "pipe", env: {
39
+ ...Object.fromEntries(Object.entries(process.env).filter((e) => typeof e[1] === "string" && e[0] !== "COGITATOR_URL")),
40
+ COGITATOR_HOME: paths.home, COGITATOR_PI_AGENT_DIR: paths.piAgentDir,
41
+ } });
42
+ const client = new Client({ name: "cogitator-preflight", version: "1.0.0" });
43
+ let timer;
44
+ try {
45
+ return await Promise.race([
46
+ (async () => {
47
+ await client.connect(transport);
48
+ const tools = (await client.listTools()).tools.map(t => t.name);
49
+ if (!["cogitator_list_agents", "cogitator_list_skills"].every(name => tools.includes(name)))
50
+ throw new Error("Outils Cogitator incomplets.");
51
+ const result = await client.callTool({ name: "cogitator_list_agents", arguments: {} });
52
+ if (result.isError)
53
+ throw new Error("Le MCP ne peut pas joindre Cogitator.");
54
+ return tools;
55
+ })(),
56
+ new Promise((_, reject) => { timer = setTimeout(() => reject(new Error("Le MCP Cogitator ne répond pas.")), 10000); }),
57
+ ]);
58
+ }
59
+ finally {
60
+ clearTimeout(timer);
61
+ await client.close();
62
+ }
63
+ }