@ignitionai/cogitator 0.5.2 → 0.7.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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,31 @@
2
2
 
3
3
  User-facing changes to Cogitator. GitHub development updates and npm releases are separate: an entry marked **Unreleased** is not yet available from npm.
4
4
 
5
+ ## [0.7.0] - 2026-11-22
6
+
7
+ **Highlight:** update Cogitator and your pi extensions in one click.
8
+
9
+ ### Added
10
+
11
+ - **One-click updates:** in **Updates**, “Update to X and restart” installs the new Cogitator release with pi, restarts the server and reloads the page. If conversations are still working, Cogitator asks before interrupting them. “Update all” updates every pi extension that has a newer release, then reloads extensions once, without interrupting active conversations. This works for installations managed by pi (`pi install`, server started with `/cogitator`). Source releases and system services (systemd) keep the VPS guide procedure: their code is protected from the server account. Set `COGITATOR_SELF_UPDATE=0` to turn it off.
12
+
13
+ ## [0.6.0] - 2026-11-22
14
+
15
+ **Highlight:** a terminal on your server, in the browser, with an agent at your side.
16
+
17
+ ### Added
18
+
19
+ - **Web terminal:** shells on the server and your Cogitator agents running in pi's interactive interface, in tabs, from your home folder or a workspace. Sessions survive a closed tab or a lost connection (recent output is replayed), up to 8 at once. On phones, a key bar provides Esc, Tab, Ctrl C and the arrow keys. See [Web terminal](https://github.com/IgnitionAI/cogitator/blob/dev/docs/terminal.md).
20
+ - **Terminal assistant:** type `# your request` to get a command written on the line, see live grey suggestions (accept with →), and get an explanation and fix for a failed command. It uses the model of the agent you choose. Commands are never run without you.
21
+
22
+ ### Security
23
+
24
+ - The terminal is a full shell with the server account's rights. It is available only in protected mode to the signed-in owner, never to MCP tokens or OAuth connectors. Its WebSocket checks the exact origin and re-checks the owner session every second, and signing out cuts open terminals. Disable it with `COGITATOR_TERMINAL=0`.
25
+
26
+ ### Requirements
27
+
28
+ - The pseudo-terminal uses the optional `@lydell/node-pty` dependency, with prebuilt binaries for Linux, macOS and Windows (no compilation).
29
+
5
30
  ## [0.5.2] - 2026-11-21
6
31
 
7
32
  **Highlights:** drive Cogitator from Claude, ChatGPT or your own bots over MCP · manage pi extensions from the interface · read what subagents are doing · import GitHub projects from a link · simpler owner login for a VPS.
package/README.md CHANGED
@@ -14,7 +14,7 @@
14
14
 
15
15
  Cogitator is a **pi package and web UI**, not a separate hosted AI service. Connect your model providers, open a bot, and work through conversations, projects, skills and subagents. Your installation keeps its own data and credentials. The interface is available in **English and French**, including on mobile.
16
16
 
17
- > **Release status:** this README describes the current `dev` build. **0.5.2** is published on npm, and the badge above shows the latest published version. Any later entry marked **Unreleased** in the [changelog](https://github.com/IgnitionAI/cogitator/blob/dev/CHANGELOG.md) requires a source build until it is published.
17
+ > **Release status:** this README describes the current `dev` build. **0.7.0** is published on npm, and the badge above shows the latest published version. Any later entry marked **Unreleased** in the [changelog](https://github.com/IgnitionAI/cogitator/blob/dev/CHANGELOG.md) requires a source build until it is published.
18
18
 
19
19
  ![Cogitator bots: Majordome, Project Manager and Skills Architect](https://raw.githubusercontent.com/IgnitionAI/cogitator/dev/docs/images/bots.jpg)
20
20
 
@@ -58,8 +58,10 @@ These are editable agent presets, not separate subscriptions. Select their provi
58
58
  - **Conversations:** streaming responses, tool results, code, images, files and diffs. Change the model without discarding history once the current turn finishes.
59
59
  - **Projects:** import GitHub repositories, connect a private GitHub account, inspect project files, use a GitHub Issues board and start agent work from a ticket.
60
60
  - **Subagents:** install `@gotgenes/pi-subagents` from Extensions to enable delegation. Click a child in the Subagents panel to read its conversation in a large dialog, with live progress and expandable tools. The parent keeps working.
61
+ - **Updates:** update Cogitator and every pi extension in one click from **Updates**; Cogitator restarts and the page reloads (pi-managed installations).
61
62
  - **Extensions:** browse the pi catalog, install packages, check their versions, update individually and reload idle conversations. Active parents and background children keep running.
62
63
  - **Skills:** import reusable procedures, attach them to agents or invoke `/skill:name` in a message. Ask the Skills Architect to create a missing procedure.
64
+ - **Terminal:** a shell on your server in the browser (protected mode), your agents running interactively in pi, and an assistant that turns `# a request` into a command, suggests the rest of what you type and explains errors. Nothing runs without you. See [Web terminal](https://github.com/IgnitionAI/cogitator/blob/dev/docs/terminal.md).
63
65
  - **Schedules:** repeat a task with cron, inspect run history and review its outcome. The server must remain running; model usage is billed by your provider.
64
66
  - **MCP:** the bundled stdio MCP server lets agents operate Cogitator. External agents (Claude Code, the Claude/OpenAI APIs, your own bots) can use the same tools over **Streamable HTTP** at `/mcp`, with a revocable Bearer token (`cogitator mcp token create`), or via OAuth for ChatGPT/Claude.ai custom connectors on a protected VPS. See [Remote MCP](https://github.com/IgnitionAI/cogitator/blob/dev/docs/mcp-http.md). Agent presets can also use other MCP servers; **Settings** exposes global MCP configuration.
65
67
 
@@ -62,6 +62,9 @@ export function attachBrowserView(app, browser, home, state) {
62
62
  cleanup.set(app, dispose);
63
63
  app.once('close', () => { void dispose(); });
64
64
  app.on('upgrade', async (req, socket, head) => {
65
+ // The terminal registers its own upgrade handler for this prefix.
66
+ if ((req.url ?? '').startsWith('/api/terminal/ws/'))
67
+ return;
65
68
  try {
66
69
  const match = /^\/api\/browser\/view\/([a-f0-9-]{36})\/([a-f0-9-]{36})$/.exec(req.url ?? '');
67
70
  if (!match)
@@ -108,6 +108,42 @@ export class PackageManager {
108
108
  void this.perform(operation);
109
109
  return operation;
110
110
  }
111
+ /** Met à jour toutes les extensions qui ont une version plus récente, puis recharge une seule fois. */
112
+ startAll(exclude = []) {
113
+ if (this.operation?.status === "running")
114
+ throw new Error("Une installation est déjà en cours.");
115
+ const operation = { name: "*", action: "update-all", status: "running", updated: [], failed: [] };
116
+ this.operation = operation;
117
+ void this.performAll(operation, new Set(exclude));
118
+ return operation;
119
+ }
120
+ async performAll(operation, exclude) {
121
+ try {
122
+ const updates = (await packageUpdates(this.paths)).filter(u => u.available && u.latest && !exclude.has(u.name));
123
+ operation.total = updates.length;
124
+ for (const update of updates) {
125
+ try {
126
+ const meta = JSON.parse(await fetchText(`https://registry.npmjs.org/${encodeURIComponent(update.name)}/latest`));
127
+ if (meta.name !== update.name || !meta.keywords?.includes("pi-package") || !/^\d+\.\d+\.\d+$/.test(meta.version))
128
+ throw new Error("Ce package n’est pas un package pi valide.");
129
+ await this.run("install", `npm:${update.name}@${meta.version}`, this.paths);
130
+ operation.updated.push(update.name);
131
+ }
132
+ catch (error) {
133
+ operation.failed.push({ name: update.name, error: error instanceof Error ? error.message : "Mise à jour échouée." });
134
+ }
135
+ }
136
+ if (operation.updated.length)
137
+ operation.deferred = await this.refresh();
138
+ operation.status = operation.failed.length && !operation.updated.length ? "error" : "done";
139
+ if (operation.status === "error")
140
+ operation.error = operation.failed.map(f => `${f.name} : ${f.error}`).join("\n");
141
+ }
142
+ catch (error) {
143
+ operation.status = "error";
144
+ operation.error = error instanceof Error ? error.message : "Mise à jour échouée.";
145
+ }
146
+ }
111
147
  async perform(operation) {
112
148
  try {
113
149
  let source;
@@ -142,7 +178,7 @@ export class PackageManager {
142
178
  }
143
179
  }
144
180
  }
145
- function runPi(action, source, paths) {
181
+ export function runPi(action, source, paths) {
146
182
  return new Promise((resolve, reject) => {
147
183
  // Arguments, never shell text. Same executable environment and profile as chat RPC.
148
184
  const child = spawn("pi", [action, source], { cwd: paths.home, env: { ...process.env, PI_CODING_AGENT_DIR: paths.piAgentDir }, stdio: "ignore", detached: process.platform !== "win32" });
package/dist/src/pool.js CHANGED
@@ -142,6 +142,14 @@ export class PiPool {
142
142
  await this.evictIdle(handle);
143
143
  return this.handles.size;
144
144
  }
145
+ /** Conversations au travail (tour en cours, compaction ou sous-agent vivant). */
146
+ async busyCount() {
147
+ let busy = 0;
148
+ for (const handle of [...this.handles.values()])
149
+ if (!handle.dead && await this.streaming(handle))
150
+ busy++;
151
+ return busy;
152
+ }
145
153
  isLive(convId) {
146
154
  const h = this.handles.get(convId);
147
155
  return Boolean(h && !h.dead);
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Mise à jour de Cogitator en un clic, pour une installation gérée par pi
3
+ * (`pi install npm:@ignitionai/cogitator`, serveur lancé par `/cogitator`).
4
+ *
5
+ * 1. `pi install npm:@ignitionai/cogitator@<dernière>` : remplace le paquet sur place ;
6
+ * 2. un relanceur détaché attend la fin de ce processus puis relance la même commande ;
7
+ * 3. le serveur s'arrête proprement (SIGTERM → arrêt habituel de cli.ts).
8
+ *
9
+ * Refusé pour une release source ou un service systemd : leur code n'appartient pas au
10
+ * compte du serveur (protection voulue) ; l'UI affiche alors la procédure du guide VPS.
11
+ */
12
+ import { spawn } from "node:child_process";
13
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
14
+ import { join, sep } from "node:path";
15
+ import { findPackageRoot } from "./default-agent.js";
16
+ export const PACKAGE = "@ignitionai/cogitator";
17
+ export function selfUpdateSupport(paths, root = findPackageRoot(), env = process.env) {
18
+ if (!root)
19
+ return { supported: false, reason: "SOURCE_BUILD" };
20
+ const piModules = join(paths.piAgentDir, "npm", "node_modules");
21
+ let real, base;
22
+ try {
23
+ real = realpathSync(root);
24
+ base = realpathSync(piModules);
25
+ }
26
+ catch {
27
+ return { supported: false, reason: "NOT_PI_MANAGED" };
28
+ }
29
+ if (!real.startsWith(base + sep))
30
+ return { supported: false, reason: "NOT_PI_MANAGED" };
31
+ // Un service (systemd) gère lui-même le cycle de vie : pas de relance concurrente.
32
+ if (env.INVOCATION_ID || env.COGITATOR_SELF_UPDATE === "0")
33
+ return { supported: false, reason: "SERVICE_MANAGED" };
34
+ return { supported: true };
35
+ }
36
+ export class SelfUpdateError extends Error {
37
+ code;
38
+ status;
39
+ detail;
40
+ constructor(code, status = 409, detail) {
41
+ super(code);
42
+ this.code = code;
43
+ this.status = status;
44
+ this.detail = detail;
45
+ }
46
+ }
47
+ export class SelfUpdater {
48
+ deps;
49
+ state = { status: "idle" };
50
+ constructor(deps) {
51
+ this.deps = deps;
52
+ }
53
+ /** Lance la mise à jour ; l'installation se poursuit en tâche de fond (suivie par `state`). */
54
+ async start(force = false) {
55
+ if (this.state.status === "installing" || this.state.status === "restarting")
56
+ throw new SelfUpdateError("SELF_UPDATE_RUNNING");
57
+ const support = this.deps.support();
58
+ if (!support.supported)
59
+ throw new SelfUpdateError(`SELF_UPDATE_${support.reason}`, 400);
60
+ const release = await this.deps.release();
61
+ if (release.status !== "available")
62
+ throw new SelfUpdateError("SELF_UPDATE_NOT_AVAILABLE", 409, { current: release.current, latest: release.latest });
63
+ const busy = await this.deps.busy();
64
+ if (busy > 0 && !force)
65
+ throw new SelfUpdateError("SELF_UPDATE_BUSY", 409, { busy });
66
+ const target = release.latest;
67
+ this.state = { status: "installing", target };
68
+ void this.run(target);
69
+ return { ...this.state };
70
+ }
71
+ async run(target) {
72
+ try {
73
+ await this.deps.install(`npm:${PACKAGE}@${target}`);
74
+ const installed = this.deps.installedVersion();
75
+ if (installed !== target)
76
+ throw new Error(`Version installée inattendue : ${installed ?? "inconnue"}`);
77
+ this.state = { status: "restarting", target };
78
+ this.deps.relaunch();
79
+ // Laisse le temps à l'UI de lire l'état « restarting » avant l'arrêt.
80
+ setTimeout(() => this.deps.shutdown(), 500).unref();
81
+ }
82
+ catch (error) {
83
+ this.state = { status: "error", target, error: error instanceof Error ? error.message : String(error) };
84
+ }
85
+ }
86
+ }
87
+ export function installedPackageVersion(root = findPackageRoot()) {
88
+ if (!root)
89
+ return null;
90
+ const file = join(root, "package.json");
91
+ if (!existsSync(file))
92
+ return null;
93
+ try {
94
+ const v = JSON.parse(readFileSync(file, "utf8")).version;
95
+ return typeof v === "string" ? v : null;
96
+ }
97
+ catch {
98
+ return null;
99
+ }
100
+ }
101
+ /**
102
+ * Relanceur détaché : attend la sortie de ce processus (60 s max), puis relance
103
+ * exactement la même commande (`node …/cli.js [--auth-required]`) avec le même environnement.
104
+ */
105
+ export function spawnRelauncher(pid = process.pid, exec = process.execPath, args = process.argv.slice(1), env = process.env) {
106
+ const script = [
107
+ "const { spawn } = require('node:child_process');",
108
+ "const [pid, exec, ...args] = process.argv.slice(1);",
109
+ "const deadline = Date.now() + 60000;",
110
+ "const alive = () => { try { process.kill(Number(pid), 0); return true; } catch { return false; } };",
111
+ "(function wait() {",
112
+ " if (alive() && Date.now() < deadline) return setTimeout(wait, 200);",
113
+ " spawn(exec, args, { detached: true, stdio: 'ignore' }).unref();",
114
+ "})();",
115
+ ].join("\n");
116
+ spawn(process.execPath, ["-e", script, String(pid), exec, ...args], { detached: true, stdio: "ignore", env }).unref();
117
+ }
@@ -5,7 +5,7 @@ import { resourceInventory, probeCogitatorTools } from "./project-setup.js";
5
5
  import { importSkillUpload } from "./skills-upload.js";
6
6
  import { appUpdateStatus } from "./app-updates.js";
7
7
  import { GitHubLogin, githubEnv, githubConfigured } from "./github-login.js";
8
- import { catalog, installedPackages, packageUpdates, PackageManager } from "./packages.js";
8
+ import { catalog, installedPackages, packageUpdates, PackageManager, runPi } from "./packages.js";
9
9
  import { changeConfiguration, dismissConfiguration, ConfigurationError, recoverConfigurations } from "./classic-configuration.js";
10
10
  import { execFile } from "node:child_process";
11
11
  import { randomUUID } from "node:crypto";
@@ -46,6 +46,15 @@ import { cloneRepo, isInsideDir, localDirFor } from "./git-import.js";
46
46
  import { listSubagents, readSubagentTranscript } from "./subagents.js";
47
47
  import { MCP_HTTP_PATH, McpHttpEndpoint } from "./mcp-http.js";
48
48
  import { McpOAuth } from "./mcp-oauth.js";
49
+ import { installedPackageVersion, PACKAGE as SELF_PACKAGE, SelfUpdateError, SelfUpdater, selfUpdateSupport, spawnRelauncher } from "./self-update.js";
50
+ import { loadPty, shellLaunch, terminalEnv, TerminalError, TerminalManager } from "./terminal.js";
51
+ import { attachTerminalSocket, terminalRoutes } from "./terminal-http.js";
52
+ import { piComplete } from "./terminal-assist.js";
53
+ import { buildArgs } from "./spawn.js";
54
+ import { runtimeIntegration, currentMcpServers } from "./project-setup.js";
55
+ import { encodeMcpEnv, MCP_ENV_VAR } from "./mcp-env.js";
56
+ import { homedir } from "node:os";
57
+ import { piCliPath } from "./host-pi.js";
49
58
  // ---------- Statique ----------
50
59
  /** Localise web/dist en remontant depuis le module (marche en dev src/ comme en prod dist/src/ ou en paquet npm). */
51
60
  function findWebDist() {
@@ -264,6 +273,20 @@ function requireAgent(deps, ctx) {
264
273
  function registryRoutes(deps) {
265
274
  const { paths } = deps;
266
275
  const packages = new PackageManager(paths, () => deps.pool.refreshExtensions());
276
+ const selfUpdater = new SelfUpdater({
277
+ support: () => selfUpdateSupport(paths),
278
+ release: () => appUpdateStatus(),
279
+ busy: () => deps.pool.busyCount(),
280
+ install: (source) => runPi("install", source, paths),
281
+ installedVersion: () => installedPackageVersion(),
282
+ relaunch: () => spawnRelauncher(),
283
+ shutdown: () => {
284
+ // Arrêt habituel (cli.ts) ; filet de sécurité si une poignée retient le processus.
285
+ setTimeout(() => process.exit(0), 15_000).unref();
286
+ process.kill(process.pid, "SIGTERM");
287
+ },
288
+ ...deps.selfUpdate,
289
+ });
267
290
  const sampleMachine = machineMetrics(paths.home);
268
291
  return [
269
292
  ["GET", "/api/machine", async (ctx) => {
@@ -284,11 +307,40 @@ function registryRoutes(deps) {
284
307
  sendJson(ctx.res, 200, { ok: true });
285
308
  }],
286
309
  ["GET", "/api/app-updates", async (ctx) => {
310
+ const selfUpdate = { ...selfUpdateSupport(paths), state: selfUpdater.state };
287
311
  try {
288
- sendJson(ctx.res, 200, await appUpdateStatus());
312
+ sendJson(ctx.res, 200, { ...await appUpdateStatus(), selfUpdate });
289
313
  }
290
314
  catch {
291
- sendJson(ctx.res, 502, { error: "Release check unavailable" });
315
+ sendJson(ctx.res, 502, { error: "Release check unavailable", selfUpdate });
316
+ }
317
+ }],
318
+ ["GET", "/api/app-updates/state", (ctx) => {
319
+ sendJson(ctx.res, 200, { ...selfUpdateSupport(paths), state: selfUpdater.state, version: packageVersion() });
320
+ }],
321
+ ["POST", "/api/app-updates/apply", async (ctx) => {
322
+ ctx.check();
323
+ if (packages.operation?.status === "running")
324
+ return sendJson(ctx.res, 409, { error: "Une installation est déjà en cours." });
325
+ const force = ctx.body?.force === true;
326
+ try {
327
+ sendJson(ctx.res, 202, await selfUpdater.start(force));
328
+ }
329
+ catch (error) {
330
+ if (error instanceof SelfUpdateError)
331
+ return sendJson(ctx.res, error.status, { error: error.code, ...error.detail });
332
+ sendJson(ctx.res, 502, { error: error instanceof Error ? error.message : "Release check unavailable" });
333
+ }
334
+ }],
335
+ ["POST", "/api/packages/update-all", (ctx) => {
336
+ ctx.check();
337
+ if (selfUpdater.state.status === "installing")
338
+ return sendJson(ctx.res, 409, { error: "Une installation est déjà en cours." });
339
+ try {
340
+ sendJson(ctx.res, 202, packages.startAll([SELF_PACKAGE]));
341
+ }
342
+ catch (error) {
343
+ sendJson(ctx.res, 409, { error: error.message });
292
344
  }
293
345
  }],
294
346
  ["GET", "/api/packages", (ctx) => {
@@ -1610,6 +1662,7 @@ export function createApp(opts) {
1610
1662
  durable,
1611
1663
  createWorkspaceImpl: opts.createWorkspaceImpl,
1612
1664
  team,
1665
+ selfUpdate: opts.selfUpdate,
1613
1666
  };
1614
1667
  const browser = new SharedBrowser(paths.home, db, opts.auth?.config.origin);
1615
1668
  const routes = [
@@ -1644,8 +1697,33 @@ export function createApp(opts) {
1644
1697
  oauth,
1645
1698
  dispatch: (method, path, body) => dispatchInternal(routes, method, path, body, availability),
1646
1699
  });
1700
+ // Terminal web : shells et agents pi interactifs (mode protégé uniquement).
1701
+ const terminals = new TerminalManager(opts.terminalPty === undefined ? loadPty() : opts.terminalPty);
1702
+ routes.push(...terminalRoutes({
1703
+ manager: terminals,
1704
+ protectedMode: !!opts.auth,
1705
+ nonBrowser: (req) => privateRequests.has(req) || syntheticRequests.has(req),
1706
+ send: sendJson,
1707
+ shell: (cwd) => shellLaunch(paths.home, cwd),
1708
+ agent: (agentId, cwd) => agentTerminalLaunch(db, paths, agentId, cwd),
1709
+ workspaceDir: (id) => {
1710
+ const ws = getWorkspace(db, id);
1711
+ if (!ws)
1712
+ throw new TerminalError("TERMINAL_WORKSPACE_NOT_FOUND", 404);
1713
+ return ws.dir;
1714
+ },
1715
+ assistTarget: (agentId) => {
1716
+ const preset = getAgent(db, agentId ?? getDefaultAgentId(db) ?? "");
1717
+ if (!preset)
1718
+ throw new TerminalError("TERMINAL_NO_AGENT", 404);
1719
+ return { provider: preset.provider, model: preset.model };
1720
+ },
1721
+ complete: opts.terminalComplete ?? piComplete(paths),
1722
+ agents: () => listAgents(db).map((a) => ({ id: a.id, name: a.name, provider: a.provider, model: a.model })),
1723
+ }));
1647
1724
  const app = opts.server ?? createServer();
1648
1725
  attachBrowserView(app, browser, paths.home, opts.auth);
1726
+ attachTerminalSocket(app, terminals, opts.auth);
1649
1727
  if (opts.auth) {
1650
1728
  app.requestTimeout = 30_000;
1651
1729
  app.headersTimeout = 10_000;
@@ -1793,12 +1871,42 @@ class CaptureResponse extends EventEmitter {
1793
1871
  flushHeaders() { this.headersSent = true; }
1794
1872
  text() { return Buffer.concat(this.chunks).toString("utf8"); }
1795
1873
  }
1796
- /** Requête synthétique : jamais privée (pas de capacité propriétaire OS), jamais navigateur. */
1874
+ /** Requêtes synthétiques (dispatch MCP) : jamais privées, jamais navigateur (ex. terminal refusé). */
1875
+ const syntheticRequests = new WeakSet();
1797
1876
  function syntheticRequest(method, path) {
1798
1877
  const req = new EventEmitter();
1799
1878
  Object.assign(req, { method, url: path, headers: { "content-type": "application/json" }, socket: { remoteAddress: "mcp" } });
1879
+ syntheticRequests.add(req);
1800
1880
  return req;
1801
1881
  }
1882
+ /** Agent Cogitator en mode interactif (TUI pi) : même modèle, prompt, skills et MCP que le preset. */
1883
+ function agentTerminalLaunch(db, paths, agentId, cwd) {
1884
+ const preset = getAgent(db, agentId);
1885
+ if (!preset)
1886
+ throw new TerminalError("TERMINAL_NO_AGENT", 404);
1887
+ let extension;
1888
+ try {
1889
+ extension = runtimeIntegration().extension;
1890
+ }
1891
+ catch {
1892
+ throw new TerminalError("TERMINAL_AGENT_UNAVAILABLE", 503);
1893
+ }
1894
+ const spawn = spawnConfigFromPreset(preset);
1895
+ const id = randomUUID();
1896
+ const mcpEnv = encodeMcpEnv(currentMcpServers(spawn.mcpServers ?? []));
1897
+ const env = terminalEnv({
1898
+ COGITATOR_HOME: paths.home,
1899
+ PI_CODING_AGENT_DIR: paths.piAgentDir,
1900
+ ...(mcpEnv ? { [MCP_ENV_VAR]: mcpEnv } : {}),
1901
+ ...(githubConfigured(paths) ? { GH_CONFIG_DIR: githubEnv(paths).GH_CONFIG_DIR } : {}),
1902
+ });
1903
+ return {
1904
+ title: preset.name, kind: "agent", agentId: preset.id,
1905
+ file: process.execPath,
1906
+ args: [piCliPath, "--extension", extension, ...buildArgs(spawn, join(paths.home, "tmp"), `terminal-${id}`)],
1907
+ cwd: cwd ?? homedir(), env, shellIntegration: false,
1908
+ };
1909
+ }
1802
1910
  /** Exécute une route /api/* en mémoire et renvoie son JSON (erreur si statut ≥ 400). */
1803
1911
  async function dispatchInternal(routes, method, path, body, check) {
1804
1912
  const url = new URL(path, `http://${HOST}`);
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Assistant du terminal web : trois aides courtes, jamais d'exécution.
3
+ * - `command` : langage naturel → une commande shell (insérée, pas lancée) ;
4
+ * - `complete` : suite probable de la commande en cours (texte fantôme) ;
5
+ * - `explain` : explication d'un échec + correctif proposé.
6
+ *
7
+ * Le modèle est celui d'un agent Cogitator (défaut : l'agent par défaut), appelé en une
8
+ * passe avec les identifiants du fournisseur déjà configurés pour pi (auth.json / models.json).
9
+ */
10
+ import { join } from "node:path";
11
+ import { pathToFileURL } from "node:url";
12
+ import { piAiRoot, piCodingAgent } from "./host-pi.js";
13
+ import { fileCredentialStore } from "./provider-login.js";
14
+ const OUTPUT_CAP = 4000;
15
+ const INPUT_CAP = 2000;
16
+ const LIMITS = {
17
+ command: { maxTokens: 300, timeoutMs: 30_000 },
18
+ complete: { maxTokens: 80, timeoutMs: 8_000 },
19
+ explain: { maxTokens: 600, timeoutMs: 45_000 },
20
+ };
21
+ const SYSTEM = {
22
+ command: "You turn requests into shell commands for a Linux server. Reply with exactly one shell command on a single line (use && or pipes if needed). No explanation, no markdown, no code fences. Prefer safe, non-destructive commands; never add sudo unless the request requires it.",
23
+ complete: "You autocomplete shell commands. Given the partial command line, reply with ONLY the characters to append to complete it (no repetition of the existing text, no explanation, no markdown). Reply with an empty answer if unsure.",
24
+ explain: "You are a concise Linux expert. Explain in 1-3 short sentences why the command failed, in the user's language when it is evident from the output, otherwise in English. If a corrected command exists, add a last line exactly in the form `FIX: <command>`. No markdown headings, no code fences.",
25
+ };
26
+ function tail(text, cap) {
27
+ if (!text)
28
+ return "";
29
+ return text.length > cap ? text.slice(-cap) : text;
30
+ }
31
+ export function buildPrompt(req) {
32
+ const context = [
33
+ `Shell: ${req.shell ?? "bash"}`,
34
+ req.cwd ? `Working directory: ${req.cwd}` : "",
35
+ req.exitCode !== undefined ? `Exit code: ${req.exitCode}` : "",
36
+ ].filter(Boolean).join("\n");
37
+ const output = tail(req.output, OUTPUT_CAP);
38
+ const input = tail(req.input, INPUT_CAP);
39
+ const label = req.mode === "command" ? "Request" : req.mode === "complete" ? "Partial command line" : "Failed command";
40
+ return `${context}\n${output ? `\nRecent terminal output:\n${output}\n` : ""}\n${label}: ${input}`;
41
+ }
42
+ /** Retire clôtures markdown, préfixes de prompt et lignes superflues. */
43
+ export function cleanCommand(raw) {
44
+ let text = raw.trim().replace(/^```[a-z]*\n?/i, "").replace(/\n?```$/, "").trim();
45
+ text = text.split("\n").map((l) => l.trim()).find((l) => l.length > 0) ?? "";
46
+ return text.replace(/^\$\s+/, "").replace(/^`(.*)`$/, "$1").trim();
47
+ }
48
+ export function parseExplain(raw) {
49
+ const lines = raw.trim().replace(/```[a-z]*\n?|```/gi, "").split("\n");
50
+ const fixIndex = lines.findIndex((l) => /^\s*FIX:\s*/i.test(l));
51
+ const fix = fixIndex >= 0 ? cleanCommand(lines[fixIndex].replace(/^\s*FIX:\s*/i, "")) : undefined;
52
+ const text = lines.filter((_, i) => i !== fixIndex).join("\n").trim();
53
+ return { text, ...(fix ? { fix } : {}) };
54
+ }
55
+ export async function runAssist(complete, target, req, signal) {
56
+ const limit = LIMITS[req.mode];
57
+ const timeout = AbortSignal.timeout(limit.timeoutMs);
58
+ const combined = signal ? AbortSignal.any([signal, timeout]) : timeout;
59
+ const raw = await complete(target, SYSTEM[req.mode], buildPrompt(req), { maxTokens: limit.maxTokens, signal: combined });
60
+ if (req.mode === "explain")
61
+ return parseExplain(raw);
62
+ if (req.mode === "command")
63
+ return { text: cleanCommand(raw) };
64
+ // complete : la suite seule ; si le modèle a répété la ligne, on retire le préfixe.
65
+ let suffix = raw.replace(/```[a-z]*\n?|```/gi, "").split("\n")[0] ?? "";
66
+ if (suffix.trimStart().startsWith(req.input.trim()) && req.input.trim())
67
+ suffix = suffix.trimStart().slice(req.input.trim().length);
68
+ return { text: suffix.replace(/\s+$/, "") };
69
+ }
70
+ let compat;
71
+ /** Appel réel : ModelRuntime de pi (mêmes fichiers que les sessions), puis completeSimple. */
72
+ export function piComplete(paths) {
73
+ return async (target, system, user, opts) => {
74
+ compat ??= import(pathToFileURL(join(piAiRoot, "dist/compat.js")).href);
75
+ const { completeSimple } = await compat;
76
+ const runtime = await piCodingAgent.ModelRuntime.create({
77
+ credentials: fileCredentialStore(paths.piAuthJson),
78
+ modelsPath: paths.piModelsJson,
79
+ allowModelNetwork: false,
80
+ });
81
+ const model = runtime.getModel(target.provider, target.model);
82
+ if (!model)
83
+ throw new Error(`Modèle introuvable : ${target.provider}/${target.model}`);
84
+ const resolved = await runtime.getAuth(model, { signal: opts.signal });
85
+ if (!resolved || (!resolved.auth.apiKey && !resolved.auth.headers))
86
+ throw new Error(`Fournisseur non connecté : ${target.provider}`);
87
+ const requestModel = resolved.auth.baseUrl ? { ...model, baseUrl: resolved.auth.baseUrl } : model;
88
+ const message = await completeSimple(requestModel, {
89
+ systemPrompt: system,
90
+ messages: [{ role: "user", content: user, timestamp: Date.now() }],
91
+ }, { apiKey: resolved.auth.apiKey, headers: resolved.auth.headers, env: resolved.env, maxTokens: opts.maxTokens, signal: opts.signal });
92
+ if (message.stopReason === "error" || message.stopReason === "aborted")
93
+ throw new Error(message.errorMessage || "Échec de l'appel au modèle");
94
+ return message.content.filter((c) => c.type === "text").map((c) => c.text ?? "").join("");
95
+ };
96
+ }