@ignitionai/cogitator 0.5.2 → 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.
- package/CHANGELOG.md +17 -0
- package/README.md +2 -1
- package/dist/src/browser-http.js +3 -0
- package/dist/src/server.js +64 -1
- package/dist/src/terminal-assist.js +96 -0
- package/dist/src/terminal-http.js +167 -0
- package/dist/src/terminal.js +171 -0
- package/package.json +6 -1
- package/web/dist/assets/{BrandLogo3D-CHGXwTbZ.js → BrandLogo3D-4IJEcixt.js} +1 -1
- package/web/dist/assets/addon-fit-DIOBYJe3.js +1 -0
- package/web/dist/assets/index-Bi_Aag-u.js +85 -0
- package/web/dist/assets/index-DQsw9iul.css +1 -0
- package/web/dist/assets/xterm-ScmBfeDI.js +16 -0
- package/web/dist/index.html +2 -2
- package/web/dist/assets/index-DGLkhrE7.css +0 -1
- package/web/dist/assets/index-P0WoXBgX.js +0 -84
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,23 @@
|
|
|
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.6.0] - 2026-11-22
|
|
6
|
+
|
|
7
|
+
**Highlight:** a terminal on your server, in the browser, with an agent at your side.
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
|
|
11
|
+
- **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).
|
|
12
|
+
- **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.
|
|
13
|
+
|
|
14
|
+
### Security
|
|
15
|
+
|
|
16
|
+
- 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`.
|
|
17
|
+
|
|
18
|
+
### Requirements
|
|
19
|
+
|
|
20
|
+
- The pseudo-terminal uses the optional `@lydell/node-pty` dependency, with prebuilt binaries for Linux, macOS and Windows (no compilation).
|
|
21
|
+
|
|
5
22
|
## [0.5.2] - 2026-11-21
|
|
6
23
|
|
|
7
24
|
**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.
|
|
17
|
+
> **Release status:** this README describes the current `dev` build. **0.6.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
|

|
|
20
20
|
|
|
@@ -60,6 +60,7 @@ These are editable agent presets, not separate subscriptions. Select their provi
|
|
|
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
61
|
- **Extensions:** browse the pi catalog, install packages, check their versions, update individually and reload idle conversations. Active parents and background children keep running.
|
|
62
62
|
- **Skills:** import reusable procedures, attach them to agents or invoke `/skill:name` in a message. Ask the Skills Architect to create a missing procedure.
|
|
63
|
+
- **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
64
|
- **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
65
|
- **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
66
|
|
package/dist/src/browser-http.js
CHANGED
|
@@ -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)
|
package/dist/src/server.js
CHANGED
|
@@ -46,6 +46,14 @@ 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 { loadPty, shellLaunch, terminalEnv, TerminalError, TerminalManager } from "./terminal.js";
|
|
50
|
+
import { attachTerminalSocket, terminalRoutes } from "./terminal-http.js";
|
|
51
|
+
import { piComplete } from "./terminal-assist.js";
|
|
52
|
+
import { buildArgs } from "./spawn.js";
|
|
53
|
+
import { runtimeIntegration, currentMcpServers } from "./project-setup.js";
|
|
54
|
+
import { encodeMcpEnv, MCP_ENV_VAR } from "./mcp-env.js";
|
|
55
|
+
import { homedir } from "node:os";
|
|
56
|
+
import { piCliPath } from "./host-pi.js";
|
|
49
57
|
// ---------- Statique ----------
|
|
50
58
|
/** Localise web/dist en remontant depuis le module (marche en dev src/ comme en prod dist/src/ ou en paquet npm). */
|
|
51
59
|
function findWebDist() {
|
|
@@ -1644,8 +1652,33 @@ export function createApp(opts) {
|
|
|
1644
1652
|
oauth,
|
|
1645
1653
|
dispatch: (method, path, body) => dispatchInternal(routes, method, path, body, availability),
|
|
1646
1654
|
});
|
|
1655
|
+
// Terminal web : shells et agents pi interactifs (mode protégé uniquement).
|
|
1656
|
+
const terminals = new TerminalManager(opts.terminalPty === undefined ? loadPty() : opts.terminalPty);
|
|
1657
|
+
routes.push(...terminalRoutes({
|
|
1658
|
+
manager: terminals,
|
|
1659
|
+
protectedMode: !!opts.auth,
|
|
1660
|
+
nonBrowser: (req) => privateRequests.has(req) || syntheticRequests.has(req),
|
|
1661
|
+
send: sendJson,
|
|
1662
|
+
shell: (cwd) => shellLaunch(paths.home, cwd),
|
|
1663
|
+
agent: (agentId, cwd) => agentTerminalLaunch(db, paths, agentId, cwd),
|
|
1664
|
+
workspaceDir: (id) => {
|
|
1665
|
+
const ws = getWorkspace(db, id);
|
|
1666
|
+
if (!ws)
|
|
1667
|
+
throw new TerminalError("TERMINAL_WORKSPACE_NOT_FOUND", 404);
|
|
1668
|
+
return ws.dir;
|
|
1669
|
+
},
|
|
1670
|
+
assistTarget: (agentId) => {
|
|
1671
|
+
const preset = getAgent(db, agentId ?? getDefaultAgentId(db) ?? "");
|
|
1672
|
+
if (!preset)
|
|
1673
|
+
throw new TerminalError("TERMINAL_NO_AGENT", 404);
|
|
1674
|
+
return { provider: preset.provider, model: preset.model };
|
|
1675
|
+
},
|
|
1676
|
+
complete: opts.terminalComplete ?? piComplete(paths),
|
|
1677
|
+
agents: () => listAgents(db).map((a) => ({ id: a.id, name: a.name, provider: a.provider, model: a.model })),
|
|
1678
|
+
}));
|
|
1647
1679
|
const app = opts.server ?? createServer();
|
|
1648
1680
|
attachBrowserView(app, browser, paths.home, opts.auth);
|
|
1681
|
+
attachTerminalSocket(app, terminals, opts.auth);
|
|
1649
1682
|
if (opts.auth) {
|
|
1650
1683
|
app.requestTimeout = 30_000;
|
|
1651
1684
|
app.headersTimeout = 10_000;
|
|
@@ -1793,12 +1826,42 @@ class CaptureResponse extends EventEmitter {
|
|
|
1793
1826
|
flushHeaders() { this.headersSent = true; }
|
|
1794
1827
|
text() { return Buffer.concat(this.chunks).toString("utf8"); }
|
|
1795
1828
|
}
|
|
1796
|
-
/**
|
|
1829
|
+
/** Requêtes synthétiques (dispatch MCP) : jamais privées, jamais navigateur (ex. terminal refusé). */
|
|
1830
|
+
const syntheticRequests = new WeakSet();
|
|
1797
1831
|
function syntheticRequest(method, path) {
|
|
1798
1832
|
const req = new EventEmitter();
|
|
1799
1833
|
Object.assign(req, { method, url: path, headers: { "content-type": "application/json" }, socket: { remoteAddress: "mcp" } });
|
|
1834
|
+
syntheticRequests.add(req);
|
|
1800
1835
|
return req;
|
|
1801
1836
|
}
|
|
1837
|
+
/** Agent Cogitator en mode interactif (TUI pi) : même modèle, prompt, skills et MCP que le preset. */
|
|
1838
|
+
function agentTerminalLaunch(db, paths, agentId, cwd) {
|
|
1839
|
+
const preset = getAgent(db, agentId);
|
|
1840
|
+
if (!preset)
|
|
1841
|
+
throw new TerminalError("TERMINAL_NO_AGENT", 404);
|
|
1842
|
+
let extension;
|
|
1843
|
+
try {
|
|
1844
|
+
extension = runtimeIntegration().extension;
|
|
1845
|
+
}
|
|
1846
|
+
catch {
|
|
1847
|
+
throw new TerminalError("TERMINAL_AGENT_UNAVAILABLE", 503);
|
|
1848
|
+
}
|
|
1849
|
+
const spawn = spawnConfigFromPreset(preset);
|
|
1850
|
+
const id = randomUUID();
|
|
1851
|
+
const mcpEnv = encodeMcpEnv(currentMcpServers(spawn.mcpServers ?? []));
|
|
1852
|
+
const env = terminalEnv({
|
|
1853
|
+
COGITATOR_HOME: paths.home,
|
|
1854
|
+
PI_CODING_AGENT_DIR: paths.piAgentDir,
|
|
1855
|
+
...(mcpEnv ? { [MCP_ENV_VAR]: mcpEnv } : {}),
|
|
1856
|
+
...(githubConfigured(paths) ? { GH_CONFIG_DIR: githubEnv(paths).GH_CONFIG_DIR } : {}),
|
|
1857
|
+
});
|
|
1858
|
+
return {
|
|
1859
|
+
title: preset.name, kind: "agent", agentId: preset.id,
|
|
1860
|
+
file: process.execPath,
|
|
1861
|
+
args: [piCliPath, "--extension", extension, ...buildArgs(spawn, join(paths.home, "tmp"), `terminal-${id}`)],
|
|
1862
|
+
cwd: cwd ?? homedir(), env, shellIntegration: false,
|
|
1863
|
+
};
|
|
1864
|
+
}
|
|
1802
1865
|
/** Exécute une route /api/* en mémoire et renvoie son JSON (erreur si statut ≥ 400). */
|
|
1803
1866
|
async function dispatchInternal(routes, method, path, body, check) {
|
|
1804
1867
|
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
|
+
}
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import { WebSocketServer } from "ws";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { browserHeaders } from "./auth-http.js";
|
|
4
|
+
import { AuthError, ownerSession, requireApproved, sessionById } from "./native-auth.js";
|
|
5
|
+
import { runAssist } from "./terminal-assist.js";
|
|
6
|
+
import { TerminalError } from "./terminal.js";
|
|
7
|
+
export function terminalDisabledReason(protectedMode, env = process.env) {
|
|
8
|
+
if (env.COGITATOR_TERMINAL === "0")
|
|
9
|
+
return "TERMINAL_DISABLED";
|
|
10
|
+
if (!protectedMode)
|
|
11
|
+
return "TERMINAL_PROTECTED_MODE_REQUIRED";
|
|
12
|
+
return null;
|
|
13
|
+
}
|
|
14
|
+
const createSchema = z.object({
|
|
15
|
+
agent_id: z.string().min(1).max(64).optional(),
|
|
16
|
+
workspace_id: z.string().min(1).max(64).optional(),
|
|
17
|
+
cols: z.number().int().optional(),
|
|
18
|
+
rows: z.number().int().optional(),
|
|
19
|
+
}).strict();
|
|
20
|
+
const assistSchema = z.object({
|
|
21
|
+
mode: z.enum(["command", "complete", "explain"]),
|
|
22
|
+
input: z.string().min(1).max(4000),
|
|
23
|
+
output: z.string().max(20_000).optional(),
|
|
24
|
+
cwd: z.string().max(1024).optional(),
|
|
25
|
+
exit_code: z.number().int().optional(),
|
|
26
|
+
agent_id: z.string().min(1).max(64).optional(),
|
|
27
|
+
}).strict();
|
|
28
|
+
export function terminalRoutes(d) {
|
|
29
|
+
const guard = (ctx) => {
|
|
30
|
+
if (d.nonBrowser(ctx.req))
|
|
31
|
+
throw new AuthError("FORBIDDEN", 403);
|
|
32
|
+
const reason = terminalDisabledReason(d.protectedMode);
|
|
33
|
+
if (reason) {
|
|
34
|
+
d.send(ctx.res, 403, { error: reason });
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
ctx.check();
|
|
38
|
+
return true;
|
|
39
|
+
};
|
|
40
|
+
const fail = (ctx, error) => {
|
|
41
|
+
if (error instanceof AuthError)
|
|
42
|
+
throw error;
|
|
43
|
+
if (error instanceof TerminalError)
|
|
44
|
+
return d.send(ctx.res, error.status, { error: error.code });
|
|
45
|
+
if (error instanceof z.ZodError)
|
|
46
|
+
return d.send(ctx.res, 400, { error: "TERMINAL_INVALID_INPUT" });
|
|
47
|
+
d.send(ctx.res, 400, { error: error instanceof Error ? error.message : "TERMINAL_FAILED" });
|
|
48
|
+
};
|
|
49
|
+
return [
|
|
50
|
+
["GET", "/api/terminal", (ctx) => {
|
|
51
|
+
if (d.nonBrowser(ctx.req))
|
|
52
|
+
throw new AuthError("FORBIDDEN", 403);
|
|
53
|
+
const reason = terminalDisabledReason(d.protectedMode) ?? (d.manager.available ? null : "TERMINAL_UNAVAILABLE");
|
|
54
|
+
d.send(ctx.res, 200, { enabled: reason === null, reason, sessions: reason ? [] : d.manager.list(), agents: reason ? [] : d.agents() });
|
|
55
|
+
}],
|
|
56
|
+
["POST", "/api/terminal/sessions", (ctx) => {
|
|
57
|
+
if (!guard(ctx))
|
|
58
|
+
return;
|
|
59
|
+
try {
|
|
60
|
+
const b = createSchema.parse(ctx.body);
|
|
61
|
+
const cwd = b.workspace_id ? d.workspaceDir(b.workspace_id) : undefined;
|
|
62
|
+
const launch = b.agent_id ? d.agent(b.agent_id, cwd) : d.shell(cwd);
|
|
63
|
+
ctx.check();
|
|
64
|
+
const info = d.manager.create(launch, { cols: b.cols ?? 80, rows: b.rows ?? 24 });
|
|
65
|
+
d.send(ctx.res, 201, { session: info, shellIntegration: launch.shellIntegration });
|
|
66
|
+
}
|
|
67
|
+
catch (error) {
|
|
68
|
+
fail(ctx, error);
|
|
69
|
+
}
|
|
70
|
+
}],
|
|
71
|
+
["DELETE", "/api/terminal/sessions/:id", (ctx) => {
|
|
72
|
+
if (!guard(ctx))
|
|
73
|
+
return;
|
|
74
|
+
if (!d.manager.close(ctx.params.id))
|
|
75
|
+
return d.send(ctx.res, 404, { error: "TERMINAL_NOT_FOUND" });
|
|
76
|
+
d.send(ctx.res, 200, { ok: true });
|
|
77
|
+
}],
|
|
78
|
+
["POST", "/api/terminal/assist", async (ctx) => {
|
|
79
|
+
if (!guard(ctx))
|
|
80
|
+
return;
|
|
81
|
+
try {
|
|
82
|
+
const b = assistSchema.parse(ctx.body);
|
|
83
|
+
const target = d.assistTarget(b.agent_id);
|
|
84
|
+
const abort = new AbortController();
|
|
85
|
+
ctx.res.once("close", () => { if (!ctx.res.writableEnded)
|
|
86
|
+
abort.abort(); });
|
|
87
|
+
const result = await runAssist(d.complete, target, { mode: b.mode, input: b.input, output: b.output, cwd: b.cwd, exitCode: b.exit_code }, abort.signal);
|
|
88
|
+
ctx.check();
|
|
89
|
+
d.send(ctx.res, 200, { ...result, model: `${target.provider}/${target.model}` });
|
|
90
|
+
}
|
|
91
|
+
catch (error) {
|
|
92
|
+
fail(ctx, error);
|
|
93
|
+
}
|
|
94
|
+
}],
|
|
95
|
+
];
|
|
96
|
+
}
|
|
97
|
+
const frameSchema = z.discriminatedUnion("t", [
|
|
98
|
+
z.object({ t: z.literal("i"), d: z.string().max(65_536) }),
|
|
99
|
+
z.object({ t: z.literal("r"), c: z.number().int(), r: z.number().int() }),
|
|
100
|
+
]);
|
|
101
|
+
export const TERMINAL_WS_PREFIX = "/api/terminal/ws/";
|
|
102
|
+
/** WebSocket du terminal : session propriétaire exigée et revérifiée chaque seconde. */
|
|
103
|
+
export function attachTerminalSocket(app, manager, state) {
|
|
104
|
+
const wss = new WebSocketServer({ noServer: true, maxPayload: 128 * 1024, perMessageDeflate: false });
|
|
105
|
+
app.once("close", () => { for (const peer of wss.clients)
|
|
106
|
+
peer.terminate(); wss.close(); manager.dispose(); });
|
|
107
|
+
app.on("upgrade", async (req, socket, head) => {
|
|
108
|
+
const url = req.url ?? "";
|
|
109
|
+
if (!url.startsWith(TERMINAL_WS_PREFIX))
|
|
110
|
+
return;
|
|
111
|
+
try {
|
|
112
|
+
const match = /^\/api\/terminal\/ws\/([a-f0-9-]{36})$/.exec(url);
|
|
113
|
+
if (!match || !state || terminalDisabledReason(true))
|
|
114
|
+
throw new Error("route");
|
|
115
|
+
state.assertAvailable();
|
|
116
|
+
if (req.headers.host !== new URL(state.config.origin).host || req.headers.origin !== state.config.origin)
|
|
117
|
+
throw new Error("origin");
|
|
118
|
+
const session = await ownerSession(state.auth, state.db, state.config, browserHeaders(req));
|
|
119
|
+
requireApproved(session, state.config);
|
|
120
|
+
const check = () => { state.assertAvailable(); requireApproved(sessionById(state.db, state.config, session.id), state.config); };
|
|
121
|
+
const id = match[1];
|
|
122
|
+
if (!manager.get(id))
|
|
123
|
+
throw new Error("session");
|
|
124
|
+
wss.handleUpgrade(req, socket, head, (peer) => {
|
|
125
|
+
let detach = () => { };
|
|
126
|
+
const close = () => { detach(); if (peer.readyState === peer.OPEN)
|
|
127
|
+
peer.close(1008); };
|
|
128
|
+
try {
|
|
129
|
+
detach = manager.attach(id, {
|
|
130
|
+
send: (frame) => { if (peer.readyState === peer.OPEN && peer.bufferedAmount < 4 * 1024 * 1024)
|
|
131
|
+
peer.send(frame); },
|
|
132
|
+
close: () => peer.close(1000),
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
catch {
|
|
136
|
+
peer.close(1011);
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
const timer = setInterval(() => { try {
|
|
140
|
+
check();
|
|
141
|
+
}
|
|
142
|
+
catch {
|
|
143
|
+
close();
|
|
144
|
+
} }, 1000);
|
|
145
|
+
peer.on("message", (data) => {
|
|
146
|
+
try {
|
|
147
|
+
check();
|
|
148
|
+
const frame = frameSchema.parse(JSON.parse(data.toString()));
|
|
149
|
+
if (frame.t === "i")
|
|
150
|
+
manager.input(id, frame.d);
|
|
151
|
+
else
|
|
152
|
+
manager.resize(id, frame.c, frame.r);
|
|
153
|
+
}
|
|
154
|
+
catch (error) {
|
|
155
|
+
if (error instanceof AuthError)
|
|
156
|
+
close();
|
|
157
|
+
}
|
|
158
|
+
});
|
|
159
|
+
peer.on("error", () => peer.terminate());
|
|
160
|
+
peer.once("close", () => { clearInterval(timer); detach(); });
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
catch {
|
|
164
|
+
socket.end("HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n");
|
|
165
|
+
}
|
|
166
|
+
});
|
|
167
|
+
}
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Terminal web du serveur : shells et agents pi interactifs dans un pseudo-terminal.
|
|
3
|
+
*
|
|
4
|
+
* Sécurité : un terminal est un shell complet avec les droits du compte serveur.
|
|
5
|
+
* - disponible uniquement en mode protégé (login propriétaire, MFA si activée) ;
|
|
6
|
+
* - jamais pour les jetons MCP ni la socket propriétaire (routes UI uniquement) ;
|
|
7
|
+
* - WebSocket : Origin exacte + session revérifiée chaque seconde (déconnexion = coupure) ;
|
|
8
|
+
* - désactivable par `COGITATOR_TERMINAL=0`.
|
|
9
|
+
* Les sessions survivent à une déconnexion du navigateur (tampon de relecture borné)
|
|
10
|
+
* et sont tuées à l'arrêt du serveur.
|
|
11
|
+
*/
|
|
12
|
+
import { randomUUID } from "node:crypto";
|
|
13
|
+
import { existsSync, mkdirSync, statSync, writeFileSync } from "node:fs";
|
|
14
|
+
import { createRequire } from "node:module";
|
|
15
|
+
import { homedir } from "node:os";
|
|
16
|
+
import { join } from "node:path";
|
|
17
|
+
export const MAX_TERMINALS = 8;
|
|
18
|
+
const REPLAY_BYTES = 256 * 1024;
|
|
19
|
+
const MIN_COLS = 10, MAX_COLS = 500, MIN_ROWS = 4, MAX_ROWS = 200;
|
|
20
|
+
/** node-pty (dépendance optionnelle, binaires précompilés) ; null si indisponible sur cette plateforme. */
|
|
21
|
+
export function loadPty() {
|
|
22
|
+
try {
|
|
23
|
+
const require = createRequire(import.meta.url);
|
|
24
|
+
const mod = require("@lydell/node-pty");
|
|
25
|
+
return (file, args, opts) => mod.spawn(file, args, opts);
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
const clampSize = (cols, rows) => ({
|
|
32
|
+
cols: Math.min(MAX_COLS, Math.max(MIN_COLS, Math.floor(cols) || 80)),
|
|
33
|
+
rows: Math.min(MAX_ROWS, Math.max(MIN_ROWS, Math.floor(rows) || 24)),
|
|
34
|
+
});
|
|
35
|
+
export class TerminalError extends Error {
|
|
36
|
+
code;
|
|
37
|
+
status;
|
|
38
|
+
constructor(code, status = 400) {
|
|
39
|
+
super(code);
|
|
40
|
+
this.code = code;
|
|
41
|
+
this.status = status;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
export class TerminalManager {
|
|
45
|
+
spawnPty;
|
|
46
|
+
sessions = new Map();
|
|
47
|
+
constructor(spawnPty) {
|
|
48
|
+
this.spawnPty = spawnPty;
|
|
49
|
+
}
|
|
50
|
+
get available() { return this.spawnPty !== null; }
|
|
51
|
+
list() {
|
|
52
|
+
return [...this.sessions.values()].map((s) => ({ ...s.info }));
|
|
53
|
+
}
|
|
54
|
+
get(id) {
|
|
55
|
+
const s = this.sessions.get(id);
|
|
56
|
+
return s ? { ...s.info } : undefined;
|
|
57
|
+
}
|
|
58
|
+
create(launch, size) {
|
|
59
|
+
if (!this.spawnPty)
|
|
60
|
+
throw new TerminalError("TERMINAL_UNAVAILABLE", 503);
|
|
61
|
+
if (this.sessions.size >= MAX_TERMINALS)
|
|
62
|
+
throw new TerminalError("TERMINAL_LIMIT", 409);
|
|
63
|
+
if (!existsSync(launch.cwd) || !statSync(launch.cwd).isDirectory())
|
|
64
|
+
throw new TerminalError("TERMINAL_CWD_INVALID");
|
|
65
|
+
const { cols, rows } = clampSize(size.cols, size.rows);
|
|
66
|
+
const pty = this.spawnPty(launch.file, launch.args, { cwd: launch.cwd, env: launch.env, cols, rows, name: "xterm-256color" });
|
|
67
|
+
const info = {
|
|
68
|
+
id: randomUUID(), title: launch.title, kind: launch.kind, cwd: launch.cwd, createdAt: new Date().toISOString(), exited: false,
|
|
69
|
+
...(launch.agentId ? { agentId: launch.agentId } : {}),
|
|
70
|
+
};
|
|
71
|
+
const session = { info, pty, replay: [], replaySize: 0, peers: new Set() };
|
|
72
|
+
this.sessions.set(info.id, session);
|
|
73
|
+
pty.onData((data) => {
|
|
74
|
+
session.replay.push(data);
|
|
75
|
+
session.replaySize += data.length;
|
|
76
|
+
while (session.replaySize > REPLAY_BYTES && session.replay.length > 1)
|
|
77
|
+
session.replaySize -= session.replay.shift().length;
|
|
78
|
+
const frame = JSON.stringify({ t: "o", d: data });
|
|
79
|
+
for (const peer of session.peers)
|
|
80
|
+
peer.send(frame);
|
|
81
|
+
});
|
|
82
|
+
pty.onExit(({ exitCode }) => {
|
|
83
|
+
session.info.exited = true;
|
|
84
|
+
session.info.exitCode = exitCode;
|
|
85
|
+
const frame = JSON.stringify({ t: "x", code: exitCode });
|
|
86
|
+
for (const peer of session.peers)
|
|
87
|
+
peer.send(frame);
|
|
88
|
+
});
|
|
89
|
+
return { ...info };
|
|
90
|
+
}
|
|
91
|
+
/** Branche un client : relecture du tampon puis flux en direct. Renvoie la fonction de détachement. */
|
|
92
|
+
attach(id, peer) {
|
|
93
|
+
const session = this.sessions.get(id);
|
|
94
|
+
if (!session)
|
|
95
|
+
throw new TerminalError("TERMINAL_NOT_FOUND", 404);
|
|
96
|
+
if (session.replay.length)
|
|
97
|
+
peer.send(JSON.stringify({ t: "o", d: session.replay.join("") }));
|
|
98
|
+
if (session.info.exited)
|
|
99
|
+
peer.send(JSON.stringify({ t: "x", code: session.info.exitCode ?? 0 }));
|
|
100
|
+
session.peers.add(peer);
|
|
101
|
+
return () => { session.peers.delete(peer); };
|
|
102
|
+
}
|
|
103
|
+
input(id, data) {
|
|
104
|
+
const session = this.sessions.get(id);
|
|
105
|
+
if (!session || session.info.exited)
|
|
106
|
+
return;
|
|
107
|
+
session.pty.write(data);
|
|
108
|
+
}
|
|
109
|
+
resize(id, cols, rows) {
|
|
110
|
+
const session = this.sessions.get(id);
|
|
111
|
+
if (!session || session.info.exited)
|
|
112
|
+
return;
|
|
113
|
+
const size = clampSize(cols, rows);
|
|
114
|
+
try {
|
|
115
|
+
session.pty.resize(size.cols, size.rows);
|
|
116
|
+
}
|
|
117
|
+
catch { /* processus en sortie */ }
|
|
118
|
+
}
|
|
119
|
+
close(id) {
|
|
120
|
+
const session = this.sessions.get(id);
|
|
121
|
+
if (!session)
|
|
122
|
+
return false;
|
|
123
|
+
this.sessions.delete(id);
|
|
124
|
+
for (const peer of session.peers)
|
|
125
|
+
peer.close();
|
|
126
|
+
if (!session.info.exited) {
|
|
127
|
+
try {
|
|
128
|
+
session.pty.kill("SIGHUP");
|
|
129
|
+
}
|
|
130
|
+
catch { /* déjà sorti */ }
|
|
131
|
+
}
|
|
132
|
+
return true;
|
|
133
|
+
}
|
|
134
|
+
dispose() {
|
|
135
|
+
for (const id of [...this.sessions.keys()])
|
|
136
|
+
this.close(id);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
/** Variables du serveur à ne jamais propager aux shells (identité du processus hôte). */
|
|
140
|
+
const STRIPPED_ENV = /^(COGITATOR_AUTH_REQUIRED|COGITATOR_OWNED_PI|NODE_OPTIONS|NODE_CHANNEL_FD)$/;
|
|
141
|
+
export function terminalEnv(extra = {}) {
|
|
142
|
+
const env = {};
|
|
143
|
+
for (const [k, v] of Object.entries(process.env))
|
|
144
|
+
if (v !== undefined && !STRIPPED_ENV.test(k))
|
|
145
|
+
env[k] = v;
|
|
146
|
+
return { ...env, TERM: "xterm-256color", COLORTERM: "truecolor", COGITATOR_TERMINAL_SESSION: "1", ...extra };
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Shell de connexion. Pour bash, un rcfile charge la configuration habituelle puis
|
|
150
|
+
* émet le code de sortie de chaque commande (OSC 133;D) : l'UI propose alors d'expliquer un échec.
|
|
151
|
+
*/
|
|
152
|
+
export function shellLaunch(home, cwd) {
|
|
153
|
+
const shell = process.env.SHELL && existsSync(process.env.SHELL) ? process.env.SHELL : existsSync("/bin/bash") ? "/bin/bash" : "/bin/sh";
|
|
154
|
+
const dir = cwd ?? homedir();
|
|
155
|
+
if (shell.endsWith("/bash")) {
|
|
156
|
+
const rcDir = join(home, "terminal");
|
|
157
|
+
mkdirSync(rcDir, { recursive: true, mode: 0o700 });
|
|
158
|
+
const rc = join(rcDir, "bashrc");
|
|
159
|
+
writeFileSync(rc, [
|
|
160
|
+
"# Généré par Cogitator : configuration habituelle + statut de sortie pour le terminal web.",
|
|
161
|
+
"if [ -f /etc/profile ]; then . /etc/profile; fi",
|
|
162
|
+
// Comme un shell de connexion : le premier fichier trouvé (il charge d'habitude ~/.bashrc).
|
|
163
|
+
"if [ -f ~/.bash_profile ]; then . ~/.bash_profile; elif [ -f ~/.bash_login ]; then . ~/.bash_login; elif [ -f ~/.profile ]; then . ~/.profile; elif [ -f ~/.bashrc ]; then . ~/.bashrc; fi",
|
|
164
|
+
"__cog_status() { local s=$?; printf '\\033]133;D;%s\\007' \"$s\"; return $s; }",
|
|
165
|
+
"PROMPT_COMMAND=\"__cog_status${PROMPT_COMMAND:+;$PROMPT_COMMAND}\"",
|
|
166
|
+
"",
|
|
167
|
+
].join("\n"), { mode: 0o600 });
|
|
168
|
+
return { title: "bash", kind: "shell", file: shell, args: ["--rcfile", rc, "-i"], cwd: dir, env: terminalEnv(), shellIntegration: true };
|
|
169
|
+
}
|
|
170
|
+
return { title: shell.split("/").pop() ?? "shell", kind: "shell", file: shell, args: ["-l"], cwd: dir, env: terminalEnv(), shellIntegration: false };
|
|
171
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ignitionai/cogitator",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"description": "A web control panel for pi: composable agents, workspaces, interactive conversations, and scheduled tasks. A pi package.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"keywords": [
|
|
@@ -79,10 +79,15 @@
|
|
|
79
79
|
"@types/three": "^0.186.0",
|
|
80
80
|
"@types/ws": "8.18.2",
|
|
81
81
|
"@vitejs/plugin-react": "^6.1.2",
|
|
82
|
+
"@xterm/addon-fit": "^0.11.0",
|
|
83
|
+
"@xterm/xterm": "^6.0.0",
|
|
82
84
|
"react": "^19.3.0",
|
|
83
85
|
"react-dom": "^19.3.0",
|
|
84
86
|
"tsx": "^4.20.0",
|
|
85
87
|
"typescript": "^5.9.0",
|
|
86
88
|
"vite": "^8.3.3"
|
|
89
|
+
},
|
|
90
|
+
"optionalDependencies": {
|
|
91
|
+
"@lydell/node-pty": "1.2.0-beta.18"
|
|
87
92
|
}
|
|
88
93
|
}
|