@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.
- package/CHANGELOG.md +86 -0
- package/LICENSE +21 -0
- package/README.md +81 -56
- package/dist/extensions/index.js +66 -29
- package/dist/src/app-updates.js +15 -0
- package/dist/src/auth-cli.js +18 -8
- package/dist/src/auth-http.js +13 -3
- package/dist/src/auth-state.js +41 -6
- package/dist/src/board.js +3 -1
- package/dist/src/browser-http.js +146 -0
- package/dist/src/classic-configuration.js +12 -4
- package/dist/src/cli.js +29 -2
- package/dist/src/config.js +10 -0
- package/dist/src/cron.js +91 -15
- package/dist/src/db.js +55 -3
- package/dist/src/durable/approvals.js +17 -2
- package/dist/src/durable/effect-gateway.js +23 -16
- package/dist/src/durable/manager.js +13 -4
- package/dist/src/durable/mission-runtime.js +204 -46
- package/dist/src/durable/recovery.js +37 -0
- package/dist/src/durable/workers.js +22 -14
- package/dist/src/execution/confinement.js +2 -1
- package/dist/src/execution/worker-supervisor.js +222 -0
- package/dist/src/git-import.js +187 -0
- package/dist/src/github-login.js +101 -0
- package/dist/src/history.js +6 -1
- package/dist/src/host-pi.js +9 -6
- package/dist/src/json-files.js +7 -4
- package/dist/src/machine-metrics.js +49 -0
- package/dist/src/machine-types.js +1 -0
- package/dist/src/mcp-cli.js +63 -0
- package/dist/src/mcp-http.js +164 -0
- package/dist/src/mcp-oauth.js +502 -0
- package/dist/src/mcp-server.js +6 -136
- package/dist/src/mcp-tokens.js +104 -0
- package/dist/src/mcp-tools.js +264 -0
- package/dist/src/native-auth.js +9 -2
- package/dist/src/packages.js +190 -0
- package/dist/src/paths.js +1 -0
- package/dist/src/pi-child.js +180 -0
- package/dist/src/pi-rpc-wrap.js +84 -0
- package/dist/src/pool.js +58 -7
- package/dist/src/project-setup.js +63 -0
- package/dist/src/provider-login.js +72 -13
- package/dist/src/reap-orphans.js +138 -0
- package/dist/src/registry.js +66 -43
- package/dist/src/schemas.js +19 -4
- package/dist/src/server-compat.js +173 -0
- package/dist/src/server-identity.js +69 -0
- package/dist/src/server.js +597 -41
- package/dist/src/shared-browser.js +357 -0
- package/dist/src/skills-import.js +13 -4
- package/dist/src/skills-upload.js +68 -0
- package/dist/src/spawner.js +20 -4
- package/dist/src/subagents.js +242 -0
- package/dist/src/team-queue.js +262 -0
- 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 +13 -3
- package/web/dist/assets/{BrandLogo3D-BvZPXohP.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-7Dyl-4v7.css +0 -1
- package/web/dist/assets/index-CdqzcBU-.js +0 -83
package/dist/src/server.js
CHANGED
|
@@ -1,9 +1,17 @@
|
|
|
1
|
+
import { machineMetrics } from "./machine-metrics.js";
|
|
2
|
+
import { SharedBrowser } from "./shared-browser.js";
|
|
3
|
+
import { browserRoutes, attachBrowserView } from "./browser-http.js";
|
|
4
|
+
import { resourceInventory, probeCogitatorTools } from "./project-setup.js";
|
|
5
|
+
import { importSkillUpload } from "./skills-upload.js";
|
|
6
|
+
import { appUpdateStatus } from "./app-updates.js";
|
|
7
|
+
import { GitHubLogin, githubEnv, githubConfigured } from "./github-login.js";
|
|
8
|
+
import { catalog, installedPackages, packageUpdates, PackageManager } from "./packages.js";
|
|
1
9
|
import { changeConfiguration, dismissConfiguration, ConfigurationError, recoverConfigurations } from "./classic-configuration.js";
|
|
2
10
|
import { execFile } from "node:child_process";
|
|
3
11
|
import { randomUUID } from "node:crypto";
|
|
4
12
|
import { EventEmitter } from "node:events";
|
|
5
|
-
import { existsSync, statSync, readFileSync, realpathSync } from "node:fs";
|
|
6
|
-
import { dirname, extname, join, normalize, relative, sep } from "node:path";
|
|
13
|
+
import { existsSync, rmSync, statSync, readFileSync, realpathSync } from "node:fs";
|
|
14
|
+
import { basename, dirname, extname, join, normalize, relative, resolve, sep } from "node:path";
|
|
7
15
|
import { fileURLToPath } from "node:url";
|
|
8
16
|
import { createServer } from "node:http";
|
|
9
17
|
import { HOST } from "./config.js";
|
|
@@ -19,18 +27,33 @@ import { createTask, deleteTask, getTask, listRuns, listTasks, updateTask, } fro
|
|
|
19
27
|
import { createConversation, deleteConversation, getConversation, listConversations, setConversationTitle, } from "./conversations.js";
|
|
20
28
|
import { appendGroupMessage, conversationGroupOwner, deleteGroup, getGroupWithMembers, insertGroup, listGroupMessages, listGroups, matchGroupMention, routeGroupMessage, } from "./groups.js";
|
|
21
29
|
import { makeSpawner } from "./spawner.js";
|
|
30
|
+
import { hopContext, kickQueuedLanes, LaneDispatcher, originHop, QueueError, recoverInterrupted, submitToLane, } from "./team-queue.js";
|
|
31
|
+
import { reapOrphanOwnedPi, startPeriodicReap } from "./reap-orphans.js";
|
|
22
32
|
import { composeRuntime, runtimeKindOf } from "./runtime.js";
|
|
23
33
|
import { DurableRuntimeManager } from "./durable/manager.js";
|
|
34
|
+
import { NeedsAttentionError } from "./durable/mission-runtime.js";
|
|
24
35
|
import { assertDurableAdmission, durableToolchainRegistry } from "./durable/compatibility.js";
|
|
25
36
|
import { readHistory, readEntries } from "./history.js";
|
|
26
37
|
import { readFileChanges, readFileEvents, readFileDetail } from "./file-changes.js";
|
|
27
38
|
import { workspaceTree, readWorkspaceFile } from "./workspace-files.js";
|
|
28
39
|
import { listCards, createCardGh, updateCardGh, moveCardGh, addCommentGh, closeCardGh, } from "./board.js";
|
|
29
40
|
import { importSkills } from "./skills-import.js";
|
|
30
|
-
import { agentInputSchema, conversationCreateSchema, groupCreateSchema, messageSchema, modelSwitchSchema, providerLoginReplySchema, providerLoginSchema, providerUpsertSchema, scheduleCreateSchema, scheduleUpdateSchema, skillImportSchema, workspaceCreateSchema, workspaceUpdateSchema, boardCardSchema, boardCommentSchema, approvalDecisionSchema, budgetUpdateSchema, } from "./schemas.js";
|
|
41
|
+
import { agentInputSchema, conversationCreateSchema, groupCreateSchema, messageSchema, modelSwitchSchema, providerLoginReplySchema, providerLoginSchema, providerUpsertSchema, scheduleCreateSchema, scheduleUpdateSchema, skillImportSchema, workspaceCreateSchema, workspaceUpdateSchema, boardCardSchema, boardCommentSchema, approvalDecisionSchema, budgetUpdateSchema, teamSendSchema, } from "./schemas.js";
|
|
31
42
|
import { spawnConfigFromPreset } from "./spawn.js";
|
|
32
43
|
import { enrollmentPolicyFromEnv } from "./execution/confinement.js";
|
|
33
|
-
import { browseDir, createWorkspace, deleteWorkspace, getWorkspace, listWorkspaces, updateWorkspace, } from "./workspaces.js";
|
|
44
|
+
import { browseDir, createWorkspace, deleteWorkspace, getWorkspace, getWorkspaceByDir, listWorkspaces, updateWorkspace, } from "./workspaces.js";
|
|
45
|
+
import { cloneRepo, isInsideDir, localDirFor } from "./git-import.js";
|
|
46
|
+
import { listSubagents, readSubagentTranscript } from "./subagents.js";
|
|
47
|
+
import { MCP_HTTP_PATH, McpHttpEndpoint } from "./mcp-http.js";
|
|
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";
|
|
34
57
|
// ---------- Statique ----------
|
|
35
58
|
/** Localise web/dist en remontant depuis le module (marche en dev src/ comme en prod dist/src/ ou en paquet npm). */
|
|
36
59
|
function findWebDist() {
|
|
@@ -218,6 +241,29 @@ function requireWorkspace(deps, ctx) {
|
|
|
218
241
|
function requireConversation(deps, ctx) {
|
|
219
242
|
return getConversation(deps.db, ctx.params.id) ?? notFound(ctx.res, "conversation");
|
|
220
243
|
}
|
|
244
|
+
function queueHttpStatus(code) {
|
|
245
|
+
switch (code) {
|
|
246
|
+
case "hop_limit":
|
|
247
|
+
case "conflict":
|
|
248
|
+
return 409;
|
|
249
|
+
case "not_found":
|
|
250
|
+
return 404;
|
|
251
|
+
default: {
|
|
252
|
+
const _exhaustive = code;
|
|
253
|
+
return _exhaustive;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
async function deliverClassic(deps, conv, text, images, extra) {
|
|
258
|
+
return submitToLane(deps.db, deps.team, {
|
|
259
|
+
conversationId: conv.id,
|
|
260
|
+
body: text || "(image)",
|
|
261
|
+
fromAgentId: extra?.fromAgentId ?? null,
|
|
262
|
+
chainId: extra?.chainId,
|
|
263
|
+
hop: extra?.hop,
|
|
264
|
+
idempotencyKey: extra?.idempotencyKey,
|
|
265
|
+
}, images);
|
|
266
|
+
}
|
|
221
267
|
function requireAgent(deps, ctx) {
|
|
222
268
|
return getAgent(deps.db, ctx.params.id) ?? notFound(ctx.res, "agent");
|
|
223
269
|
}
|
|
@@ -225,7 +271,70 @@ function requireAgent(deps, ctx) {
|
|
|
225
271
|
/** Registry pi : providers, skills, MCP user-level. */
|
|
226
272
|
function registryRoutes(deps) {
|
|
227
273
|
const { paths } = deps;
|
|
274
|
+
const packages = new PackageManager(paths, () => deps.pool.refreshExtensions());
|
|
275
|
+
const sampleMachine = machineMetrics(paths.home);
|
|
228
276
|
return [
|
|
277
|
+
["GET", "/api/machine", async (ctx) => {
|
|
278
|
+
const metrics = await sampleMachine();
|
|
279
|
+
ctx.check();
|
|
280
|
+
sendJson(ctx.res, 200, metrics);
|
|
281
|
+
}],
|
|
282
|
+
["GET", "/api/github/connection", async (ctx) => {
|
|
283
|
+
sendJson(ctx.res, 200, await deps.githubLogin.state());
|
|
284
|
+
}],
|
|
285
|
+
["POST", "/api/github/connection", (ctx) => {
|
|
286
|
+
ctx.check();
|
|
287
|
+
sendJson(ctx.res, 202, deps.githubLogin.start());
|
|
288
|
+
}],
|
|
289
|
+
["DELETE", "/api/github/connection", (ctx) => {
|
|
290
|
+
ctx.check();
|
|
291
|
+
deps.githubLogin.cancel();
|
|
292
|
+
sendJson(ctx.res, 200, { ok: true });
|
|
293
|
+
}],
|
|
294
|
+
["GET", "/api/app-updates", async (ctx) => {
|
|
295
|
+
try {
|
|
296
|
+
sendJson(ctx.res, 200, await appUpdateStatus());
|
|
297
|
+
}
|
|
298
|
+
catch {
|
|
299
|
+
sendJson(ctx.res, 502, { error: "Release check unavailable" });
|
|
300
|
+
}
|
|
301
|
+
}],
|
|
302
|
+
["GET", "/api/packages", (ctx) => {
|
|
303
|
+
sendJson(ctx.res, 200, { installed: installedPackages(paths), operation: packages.operation });
|
|
304
|
+
}],
|
|
305
|
+
["GET", "/api/packages/catalog", async (ctx) => {
|
|
306
|
+
const page = Math.max(1, Math.min(1000, Number(ctx.query.get("page")) || 1));
|
|
307
|
+
try {
|
|
308
|
+
sendJson(ctx.res, 200, await catalog(ctx.query.get("q") ?? "", ctx.query.get("type") ?? "extension", Math.floor(page)));
|
|
309
|
+
}
|
|
310
|
+
catch (error) {
|
|
311
|
+
sendJson(ctx.res, 502, { error: error.message });
|
|
312
|
+
}
|
|
313
|
+
}],
|
|
314
|
+
["POST", "/api/packages", (ctx) => {
|
|
315
|
+
const body = ctx.body;
|
|
316
|
+
if (!body || typeof body.name !== "string" || !["install", "remove", "update"].includes(String(body.action)))
|
|
317
|
+
return sendJson(ctx.res, 400, { error: "Package et action requis." });
|
|
318
|
+
try {
|
|
319
|
+
ctx.check();
|
|
320
|
+
sendJson(ctx.res, 202, packages.start(body.name, body.action));
|
|
321
|
+
}
|
|
322
|
+
catch (error) {
|
|
323
|
+
sendJson(ctx.res, 409, { error: error.message });
|
|
324
|
+
}
|
|
325
|
+
}],
|
|
326
|
+
["GET", "/api/packages/updates", async (ctx) => {
|
|
327
|
+
sendJson(ctx.res, 200, { updates: await packageUpdates(paths) });
|
|
328
|
+
}],
|
|
329
|
+
["POST", "/api/packages/reload", async (ctx) => {
|
|
330
|
+
ctx.check();
|
|
331
|
+
if (packages.operation?.status === "running")
|
|
332
|
+
return sendJson(ctx.res, 409, { error: "Une installation est déjà en cours." });
|
|
333
|
+
const deferred = await deps.pool.refreshExtensions();
|
|
334
|
+
if (packages.operation)
|
|
335
|
+
packages.operation.deferred = deferred;
|
|
336
|
+
sendJson(ctx.res, 200, { deferred });
|
|
337
|
+
}],
|
|
229
338
|
["GET", "/api/providers", async (ctx) => {
|
|
230
339
|
sendJson(ctx.res, 200, { providers: await listProviders(paths) });
|
|
231
340
|
}],
|
|
@@ -258,8 +367,11 @@ function registryRoutes(deps) {
|
|
|
258
367
|
if (!body)
|
|
259
368
|
return;
|
|
260
369
|
const id = ctx.params.id;
|
|
261
|
-
|
|
370
|
+
const methods = authMethodsFor(id);
|
|
371
|
+
if (methods.length === 0)
|
|
262
372
|
return sendJson(ctx.res, 404, { error: `Unknown provider: ${id}` });
|
|
373
|
+
if (!methods.some(method => method.type === body.type))
|
|
374
|
+
return sendJson(ctx.res, 400, { error: "Unsupported authentication method" });
|
|
263
375
|
sendJson(ctx.res, 202, deps.logins.start(id, body.type));
|
|
264
376
|
}],
|
|
265
377
|
["GET", "/api/provider-logins/:id/events", (ctx) => {
|
|
@@ -285,9 +397,33 @@ function registryRoutes(deps) {
|
|
|
285
397
|
return sendJson(ctx.res, 404, { error: "login session not found" });
|
|
286
398
|
sendJson(ctx.res, 200, { ok: true });
|
|
287
399
|
}],
|
|
400
|
+
["GET", "/api/setup-context", async (ctx) => {
|
|
401
|
+
const workspaceId = ctx.query.get("workspace_id");
|
|
402
|
+
const workspace = workspaceId ? getWorkspace(deps.db, workspaceId) : null;
|
|
403
|
+
if (workspaceId && !workspace)
|
|
404
|
+
return sendJson(ctx.res, 404, { error: "Workspace introuvable" });
|
|
405
|
+
const inventory = resourceInventory(deps.db, paths, workspace?.dir ?? paths.home);
|
|
406
|
+
try {
|
|
407
|
+
sendJson(ctx.res, 200, { ...inventory, tools: await probeCogitatorTools(paths), ready: true });
|
|
408
|
+
}
|
|
409
|
+
catch (error) {
|
|
410
|
+
sendJson(ctx.res, 200, { ...inventory, tools: [], ready: false, error: error.message });
|
|
411
|
+
}
|
|
412
|
+
}],
|
|
288
413
|
["GET", "/api/skills", (ctx) => {
|
|
289
414
|
sendJson(ctx.res, 200, { skills: listSkills(paths) });
|
|
290
415
|
}],
|
|
416
|
+
["POST", "/api/skills/upload", (ctx) => {
|
|
417
|
+
ctx.check();
|
|
418
|
+
const dest = paths.skillsDirs[0] ?? join(paths.piAgentDir, "skills");
|
|
419
|
+
try {
|
|
420
|
+
const result = importSkillUpload(ctx.body?.files, dest);
|
|
421
|
+
sendJson(ctx.res, 200, { ...result, dest });
|
|
422
|
+
}
|
|
423
|
+
catch (error) {
|
|
424
|
+
sendJson(ctx.res, 400, { error: error.message });
|
|
425
|
+
}
|
|
426
|
+
}],
|
|
291
427
|
["POST", "/api/skills/import", async (ctx) => {
|
|
292
428
|
const b = parseBody(ctx.res, skillImportSchema, ctx.body);
|
|
293
429
|
if (!b)
|
|
@@ -382,11 +518,96 @@ function workspaceRoutes(deps) {
|
|
|
382
518
|
["GET", "/api/workspaces", (ctx) => {
|
|
383
519
|
sendJson(ctx.res, 200, { workspaces: listWorkspaces(db) });
|
|
384
520
|
}],
|
|
385
|
-
["POST", "/api/workspaces", (ctx) => {
|
|
521
|
+
["POST", "/api/workspaces", async (ctx) => {
|
|
386
522
|
const b = parseBody(ctx.res, workspaceCreateSchema, ctx.body);
|
|
387
523
|
if (!b)
|
|
388
524
|
return;
|
|
389
|
-
const
|
|
525
|
+
const policy = enrollmentPolicyFromEnv();
|
|
526
|
+
if (b.git_url) {
|
|
527
|
+
const root = deps.paths.projectsDir;
|
|
528
|
+
const target = localDirFor(b.git_url, root);
|
|
529
|
+
if ("error" in target)
|
|
530
|
+
return sendJson(ctx.res, 400, { error: target.error });
|
|
531
|
+
// B1/L2 : en mode distant, refuser AVANT toute écriture si la destination
|
|
532
|
+
// canonique n'est sous aucune racine enrôlée. Les deux côtés sont canonicalisés :
|
|
533
|
+
// un <root> ou <root>/<owner> déjà présent en symlink ferait sinon écrire hors
|
|
534
|
+
// racine (le clone suit les liens, la garde lexicale non).
|
|
535
|
+
if (policy.remote) {
|
|
536
|
+
// Canonicalise le plus long préfixe existant puis résout le reste lexicalement
|
|
537
|
+
// (cf. resolveConfined) : appliqué à la destination ET aux racines, sinon deux
|
|
538
|
+
// représentations du même chemin (/tmp vs /private/tmp) ne matchent jamais.
|
|
539
|
+
const canonical = (p) => {
|
|
540
|
+
let existing = resolve(p);
|
|
541
|
+
const tail = [];
|
|
542
|
+
while (!existsSync(existing)) {
|
|
543
|
+
const parent = dirname(existing);
|
|
544
|
+
if (parent === existing)
|
|
545
|
+
break;
|
|
546
|
+
tail.unshift(basename(existing));
|
|
547
|
+
existing = parent;
|
|
548
|
+
}
|
|
549
|
+
try {
|
|
550
|
+
return join(realpathSync(existing), ...tail);
|
|
551
|
+
}
|
|
552
|
+
catch {
|
|
553
|
+
return resolve(p);
|
|
554
|
+
}
|
|
555
|
+
};
|
|
556
|
+
const destCanon = canonical(target.dest);
|
|
557
|
+
if (!policy.enrolledRoots.some((enrolled) => isInsideDir(destCanon, canonical(enrolled)))) {
|
|
558
|
+
return sendJson(ctx.res, 400, { error: `racine de clone hors des racines enrôlées: ${root}` });
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
const result = await cloneRepo(target.source, target.dest, githubConfigured(deps.paths) ? githubEnv(deps.paths) : undefined);
|
|
562
|
+
if ("error" in result)
|
|
563
|
+
return sendJson(ctx.res, 400, { error: result.error });
|
|
564
|
+
// D4 : tout échec après le clone (autorisation révoquée pendant les 25 s, ou refus
|
|
565
|
+
// d'enrôlement) doit laisser le disque propre — sans jamais supprimer un dossier
|
|
566
|
+
// qu'un workspace référence déjà (import concurrent gagnant) ni un dossier vide
|
|
567
|
+
// préexistant que Cogitator n'a pas créé (S3 : `created` le distingue). La
|
|
568
|
+
// comparaison se fait en forme canonicalisée, comme les lignes DB écrites par
|
|
569
|
+
// createWorkspace : une comparaison lexicale rendrait la garde inerte sur toute
|
|
570
|
+
// racine symlinkée (/tmp sur macOS — M1).
|
|
571
|
+
const discardClone = () => {
|
|
572
|
+
if (!result.cloned || !result.created)
|
|
573
|
+
return;
|
|
574
|
+
let cloned;
|
|
575
|
+
try {
|
|
576
|
+
cloned = realpathSync(result.dir); // le dossier existe : on vient de le cloner
|
|
577
|
+
}
|
|
578
|
+
catch {
|
|
579
|
+
return; // déjà parti
|
|
580
|
+
}
|
|
581
|
+
if (getWorkspaceByDir(db, cloned))
|
|
582
|
+
return;
|
|
583
|
+
// Nettoyage best-effort : un EBUSY/EPERM ne doit pas masquer l'erreur d'origine
|
|
584
|
+
// (S2) — ici on est dans le catch de la requête ou sur un refus 400.
|
|
585
|
+
try {
|
|
586
|
+
rmSync(cloned, { recursive: true, force: true });
|
|
587
|
+
}
|
|
588
|
+
catch {
|
|
589
|
+
/* dossier résiduel possible, signalé par l'erreur d'origine */
|
|
590
|
+
}
|
|
591
|
+
};
|
|
592
|
+
let created;
|
|
593
|
+
try {
|
|
594
|
+
ctx.check(); // autorisation à revérifier après l'await long (le clone)
|
|
595
|
+
created = (deps.createWorkspaceImpl ?? createWorkspace)(db, { dir: result.dir, name: b.name, default_agent_id: b.default_agent_id }, policy);
|
|
596
|
+
}
|
|
597
|
+
catch (err) {
|
|
598
|
+
discardClone();
|
|
599
|
+
throw err;
|
|
600
|
+
}
|
|
601
|
+
if (created.error) {
|
|
602
|
+
discardClone();
|
|
603
|
+
return sendJson(ctx.res, 400, { error: created.error });
|
|
604
|
+
}
|
|
605
|
+
return sendJson(ctx.res, 201, { workspace: created.workspace });
|
|
606
|
+
}
|
|
607
|
+
// Le refine du schéma garantit dir ici ; la garde sert de resserrement de type.
|
|
608
|
+
if (!b.dir)
|
|
609
|
+
return sendJson(ctx.res, 400, { error: "dir ou git_url requis" });
|
|
610
|
+
const { workspace, error } = createWorkspace(db, { dir: b.dir, name: b.name, default_agent_id: b.default_agent_id }, policy);
|
|
390
611
|
if (error)
|
|
391
612
|
return sendJson(ctx.res, 400, { error });
|
|
392
613
|
sendJson(ctx.res, 201, { workspace });
|
|
@@ -644,9 +865,8 @@ async function startCardWork(deps, ws, number, extra, check = () => { }) {
|
|
|
644
865
|
});
|
|
645
866
|
setConversationTitle(deps.db, conv.id, `#${card.number} ${card.title}`);
|
|
646
867
|
const titled = getConversation(deps.db, conv.id);
|
|
647
|
-
await deps.spawner.ensure(titled);
|
|
648
868
|
check();
|
|
649
|
-
await deps
|
|
869
|
+
await deliverClassic(deps, titled, ticketPrompt(card, extra));
|
|
650
870
|
check();
|
|
651
871
|
const moved = await moveCardGh(ws.dir, card.number, "in_progress");
|
|
652
872
|
if ("error" in moved)
|
|
@@ -671,10 +891,15 @@ function ticketPrompt(card, extra) {
|
|
|
671
891
|
function conversationRoutes(deps) {
|
|
672
892
|
const { db, pool } = deps;
|
|
673
893
|
return [
|
|
674
|
-
["GET", "/api/conversations", (ctx) => {
|
|
894
|
+
["GET", "/api/conversations", async (ctx) => {
|
|
675
895
|
const workspaceId = ctx.query.get("workspace_id") ?? undefined;
|
|
676
896
|
const agentId = ctx.query.get("agent_id") ?? undefined;
|
|
677
|
-
|
|
897
|
+
const conversations = await Promise.all(listConversations(db, workspaceId, agentId).map(async (conv) => {
|
|
898
|
+
const runtime = deps.compose(conv);
|
|
899
|
+
return { ...conv, streaming: runtime.kind === "classic" ? await pool.isStreaming(conv.id) : runtime.isLive(conv) };
|
|
900
|
+
}));
|
|
901
|
+
ctx.check();
|
|
902
|
+
sendJson(ctx.res, 200, { conversations });
|
|
678
903
|
}],
|
|
679
904
|
["POST", "/api/conversations", async (ctx) => {
|
|
680
905
|
const b = parseBody(ctx.res, conversationCreateSchema, ctx.body);
|
|
@@ -697,14 +922,30 @@ function conversationRoutes(deps) {
|
|
|
697
922
|
const prompt = b.prompt?.trim();
|
|
698
923
|
if (prompt) {
|
|
699
924
|
const runtime = deps.compose(conv);
|
|
700
|
-
await runtime.ensure(conv);
|
|
701
|
-
ctx.check();
|
|
702
|
-
const ack = await runtime.prompt(conv, prompt, runtimeKind === "durable" ? randomUUID() : undefined);
|
|
703
925
|
ctx.check();
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
926
|
+
if (runtime.kind === "durable") {
|
|
927
|
+
await runtime.ensure(conv);
|
|
928
|
+
ctx.check();
|
|
929
|
+
const ack = await runtime.prompt(conv, prompt, randomUUID());
|
|
930
|
+
ctx.check();
|
|
931
|
+
setConversationTitle(db, conv.id, prompt);
|
|
932
|
+
conv = getConversation(db, conv.id);
|
|
933
|
+
if (ack.accepted)
|
|
934
|
+
return sendJson(ctx.res, 201, { conversation: conv, accepted: ack.accepted });
|
|
935
|
+
}
|
|
936
|
+
else {
|
|
937
|
+
try {
|
|
938
|
+
await deliverClassic(deps, conv, prompt);
|
|
939
|
+
}
|
|
940
|
+
catch (err) {
|
|
941
|
+
if (err instanceof QueueError)
|
|
942
|
+
return sendJson(ctx.res, queueHttpStatus(err.code), { error: err.message, code: err.code });
|
|
943
|
+
throw err;
|
|
944
|
+
}
|
|
945
|
+
ctx.check();
|
|
946
|
+
setConversationTitle(db, conv.id, prompt);
|
|
947
|
+
conv = getConversation(db, conv.id);
|
|
948
|
+
}
|
|
708
949
|
}
|
|
709
950
|
sendJson(ctx.res, 201, { conversation: conv });
|
|
710
951
|
}],
|
|
@@ -725,7 +966,21 @@ function conversationRoutes(deps) {
|
|
|
725
966
|
if (!conv)
|
|
726
967
|
return;
|
|
727
968
|
const runtime = deps.compose(conv);
|
|
728
|
-
|
|
969
|
+
let spawned;
|
|
970
|
+
try {
|
|
971
|
+
spawned = await runtime.ensure(conv);
|
|
972
|
+
}
|
|
973
|
+
catch (error) {
|
|
974
|
+
if (error instanceof AuthError)
|
|
975
|
+
throw error;
|
|
976
|
+
ctx.check();
|
|
977
|
+
const send = openSse(ctx.res);
|
|
978
|
+
send({ type: "session_error", code: error instanceof ConfigurationError ? error.code : "SESSION_START_FAILED",
|
|
979
|
+
provider: error instanceof ConfigurationError ? error.provider : conv.provider,
|
|
980
|
+
error: error instanceof Error ? error.message : "Session startup failed" });
|
|
981
|
+
ctx.res.end();
|
|
982
|
+
return;
|
|
983
|
+
}
|
|
729
984
|
// Mode durable : aucun spawn (la runtime vit dans le contrôleur) ; la lecture
|
|
730
985
|
// d'événements ne crée jamais de mission (Plan 0002 §7).
|
|
731
986
|
const send = openSse(ctx.res, runtime.kind === "durable"
|
|
@@ -762,6 +1017,22 @@ function conversationRoutes(deps) {
|
|
|
762
1017
|
return;
|
|
763
1018
|
sendJson(ctx.res, 200, { files: readFileChanges(conv.session_file ?? "") });
|
|
764
1019
|
}],
|
|
1020
|
+
// Subagents herdr live de cette conversation (ADR-012) : lecture seule, jamais de 5xx herdr.
|
|
1021
|
+
["GET", "/api/conversations/:id/subagents", async (ctx) => {
|
|
1022
|
+
const conv = requireConversation(deps, ctx);
|
|
1023
|
+
if (!conv)
|
|
1024
|
+
return;
|
|
1025
|
+
sendJson(ctx.res, 200, listSubagents(conv.session_file));
|
|
1026
|
+
}],
|
|
1027
|
+
["GET", "/api/conversations/:id/subagents/:subagentId", (ctx) => {
|
|
1028
|
+
const conv = requireConversation(deps, ctx);
|
|
1029
|
+
if (!conv)
|
|
1030
|
+
return;
|
|
1031
|
+
const transcript = readSubagentTranscript(conv.session_file, ctx.params.subagentId);
|
|
1032
|
+
if (!transcript)
|
|
1033
|
+
return sendJson(ctx.res, 404, { error: "Subagent transcript unavailable" });
|
|
1034
|
+
sendJson(ctx.res, 200, transcript);
|
|
1035
|
+
}],
|
|
765
1036
|
["GET", "/api/conversations/:id/file", (ctx) => {
|
|
766
1037
|
const conv = requireConversation(deps, ctx);
|
|
767
1038
|
if (!conv)
|
|
@@ -783,14 +1054,37 @@ function conversationRoutes(deps) {
|
|
|
783
1054
|
if (runtime.kind === "durable" && !b.requestId) {
|
|
784
1055
|
return sendJson(ctx.res, 400, { error: "requestId requis pour une conversation durable" });
|
|
785
1056
|
}
|
|
786
|
-
await runtime.ensure(conv);
|
|
787
|
-
ctx.check();
|
|
788
|
-
const ack = await runtime.prompt(conv, text, b.requestId, b.images);
|
|
789
1057
|
ctx.check();
|
|
790
|
-
if (
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
1058
|
+
if (runtime.kind === "durable") {
|
|
1059
|
+
try {
|
|
1060
|
+
await runtime.ensure(conv);
|
|
1061
|
+
ctx.check();
|
|
1062
|
+
const ack = await runtime.prompt(conv, text, b.requestId, b.images);
|
|
1063
|
+
ctx.check();
|
|
1064
|
+
if (text)
|
|
1065
|
+
setConversationTitle(db, conv.id, text);
|
|
1066
|
+
sendJson(ctx.res, 200, ack.accepted ? { ok: true, accepted: ack.accepted } : { ok: true });
|
|
1067
|
+
}
|
|
1068
|
+
catch (err) {
|
|
1069
|
+
if (!(err instanceof NeedsAttentionError))
|
|
1070
|
+
throw err;
|
|
1071
|
+
ctx.check();
|
|
1072
|
+
sendJson(ctx.res, 409, { error: err.message, code: "needs_attention" });
|
|
1073
|
+
}
|
|
1074
|
+
return;
|
|
1075
|
+
}
|
|
1076
|
+
try {
|
|
1077
|
+
await deliverClassic(deps, conv, text, b.images);
|
|
1078
|
+
ctx.check();
|
|
1079
|
+
if (text)
|
|
1080
|
+
setConversationTitle(db, conv.id, text);
|
|
1081
|
+
sendJson(ctx.res, 200, { ok: true });
|
|
1082
|
+
}
|
|
1083
|
+
catch (err) {
|
|
1084
|
+
if (err instanceof QueueError)
|
|
1085
|
+
return sendJson(ctx.res, queueHttpStatus(err.code), { error: err.message, code: err.code });
|
|
1086
|
+
throw err;
|
|
1087
|
+
}
|
|
794
1088
|
}],
|
|
795
1089
|
// ---------- Missions durables : statut, approbations, budget (#16) ----------
|
|
796
1090
|
["GET", "/api/conversations/:id/mission", async (ctx) => {
|
|
@@ -878,7 +1172,7 @@ function conversationRoutes(deps) {
|
|
|
878
1172
|
catch (error) {
|
|
879
1173
|
if (error instanceof AuthError)
|
|
880
1174
|
throw error;
|
|
881
|
-
sendJson(ctx.res, error instanceof ConfigurationError ? error.status : error.code === "pool_full" ? 503 : 502, { error: error instanceof Error ? error.message : String(error) });
|
|
1175
|
+
sendJson(ctx.res, error instanceof ConfigurationError ? error.status : error.code === "pool_full" ? 503 : 502, { error: error instanceof Error ? error.message : String(error), ...(error instanceof ConfigurationError ? { code: error.code, provider: error.provider } : {}) });
|
|
882
1176
|
}
|
|
883
1177
|
}],
|
|
884
1178
|
["DELETE", "/api/conversations/:id/model", async (ctx) => {
|
|
@@ -1010,9 +1304,15 @@ function groupRoutes(deps) {
|
|
|
1010
1304
|
.get(group.id, target.agent_id);
|
|
1011
1305
|
if (!conv)
|
|
1012
1306
|
return sendJson(ctx.res, 500, { error: "session membre introuvable" });
|
|
1013
|
-
await deps.spawner.ensure(conv);
|
|
1014
1307
|
ctx.check();
|
|
1015
|
-
|
|
1308
|
+
try {
|
|
1309
|
+
await deliverClassic(deps, conv, text, b.images);
|
|
1310
|
+
}
|
|
1311
|
+
catch (err) {
|
|
1312
|
+
if (err instanceof QueueError)
|
|
1313
|
+
return sendJson(ctx.res, queueHttpStatus(err.code), { error: err.message, code: err.code });
|
|
1314
|
+
throw err;
|
|
1315
|
+
}
|
|
1016
1316
|
ctx.check();
|
|
1017
1317
|
sendJson(ctx.res, 200, { ok: true });
|
|
1018
1318
|
}],
|
|
@@ -1171,6 +1471,50 @@ function scheduleRoutes(deps) {
|
|
|
1171
1471
|
}],
|
|
1172
1472
|
];
|
|
1173
1473
|
}
|
|
1474
|
+
function teamRoutes(deps) {
|
|
1475
|
+
const { db } = deps;
|
|
1476
|
+
return [
|
|
1477
|
+
["POST", "/api/team/send", async (ctx) => {
|
|
1478
|
+
const b = parseBody(ctx.res, teamSendSchema, ctx.body);
|
|
1479
|
+
if (!b)
|
|
1480
|
+
return;
|
|
1481
|
+
const conv = getConversation(db, b.conversation_id);
|
|
1482
|
+
if (!conv) {
|
|
1483
|
+
notFound(ctx.res, "conversation");
|
|
1484
|
+
return;
|
|
1485
|
+
}
|
|
1486
|
+
if (runtimeKindOf(conv) === "durable")
|
|
1487
|
+
return sendJson(ctx.res, 409, { error: "file durable : conversation durable refusée", code: "conflict" });
|
|
1488
|
+
if (!b.from_conversation_id)
|
|
1489
|
+
return sendJson(ctx.res, 400, { error: "émetteur requis (COGITATOR_CONVERSATION_ID)" });
|
|
1490
|
+
const sender = getConversation(db, b.from_conversation_id);
|
|
1491
|
+
if (!sender)
|
|
1492
|
+
return sendJson(ctx.res, 400, { error: "conversation émetteur inconnue" });
|
|
1493
|
+
if (!sender.group_id || sender.group_id !== conv.group_id)
|
|
1494
|
+
return sendJson(ctx.res, 403, { error: "team_send : groupe commun requis" });
|
|
1495
|
+
const fromAgentId = sender.agent_id;
|
|
1496
|
+
if (fromAgentId && !getAgent(db, fromAgentId))
|
|
1497
|
+
return sendJson(ctx.res, 400, { error: "agent émetteur inconnu" });
|
|
1498
|
+
if (b.from_agent_id && !getAgent(db, b.from_agent_id))
|
|
1499
|
+
return sendJson(ctx.res, 400, { error: "agent émetteur inconnu" });
|
|
1500
|
+
const inherited = hopContext(deps.team, sender.id);
|
|
1501
|
+
try {
|
|
1502
|
+
const queued = await deliverClassic(deps, conv, b.body, undefined, {
|
|
1503
|
+
fromAgentId,
|
|
1504
|
+
chainId: inherited.chainId ?? b.chain_id ?? null,
|
|
1505
|
+
hop: Math.max(inherited.hop, b.hop ?? 0),
|
|
1506
|
+
idempotencyKey: b.idempotency_key,
|
|
1507
|
+
});
|
|
1508
|
+
sendJson(ctx.res, 200, { ok: true, queue_item_id: queued.id, lane_id: queued.laneId, created: queued.created });
|
|
1509
|
+
}
|
|
1510
|
+
catch (err) {
|
|
1511
|
+
if (err instanceof QueueError)
|
|
1512
|
+
return sendJson(ctx.res, queueHttpStatus(err.code), { error: err.message, code: err.code });
|
|
1513
|
+
throw err;
|
|
1514
|
+
}
|
|
1515
|
+
}],
|
|
1516
|
+
];
|
|
1517
|
+
}
|
|
1174
1518
|
const DEFAULT_RUNS_LIMIT = 50;
|
|
1175
1519
|
function healthRoute(deps) {
|
|
1176
1520
|
const { dbPath, dbVersion, paths, pool } = deps;
|
|
@@ -1190,17 +1534,31 @@ export function createApp(opts) {
|
|
|
1190
1534
|
const events = opts.events ?? new EventEmitter();
|
|
1191
1535
|
events.setMaxListeners(MAX_SSE_LISTENERS);
|
|
1192
1536
|
recoverConfigurations(db);
|
|
1537
|
+
recoverInterrupted(db);
|
|
1538
|
+
reapOrphanOwnedPi(paths.home);
|
|
1539
|
+
const stopReap = startPeriodicReap(paths.home);
|
|
1193
1540
|
const spawner = makeSpawner({ db, pool, paths });
|
|
1541
|
+
const team = new LaneDispatcher({
|
|
1542
|
+
db,
|
|
1543
|
+
pool,
|
|
1544
|
+
ensure: async (conversationId) => {
|
|
1545
|
+
const conv = getConversation(db, conversationId);
|
|
1546
|
+
if (!conv)
|
|
1547
|
+
throw new QueueError("conversation introuvable", "not_found");
|
|
1548
|
+
if (runtimeKindOf(conv) === "durable")
|
|
1549
|
+
throw new QueueError("file durable : conversation durable refusée", "conflict");
|
|
1550
|
+
return spawner.ensure(conv);
|
|
1551
|
+
},
|
|
1552
|
+
});
|
|
1553
|
+
cron?.attachTeam(team);
|
|
1554
|
+
kickQueuedLanes(db, team);
|
|
1194
1555
|
// Runtime Durable : un seul gestionnaire dans le processus contrôleur (bail OS
|
|
1195
1556
|
// par conversation). Les tests injectent un modèle contrôlé via opts.durable.
|
|
1196
1557
|
const durable = opts.durable ?? new DurableRuntimeManager({ paths, toolchain: durableToolchainRegistry() });
|
|
1197
1558
|
const compose = composeRuntime({ pool, spawner, durable });
|
|
1198
|
-
//
|
|
1199
|
-
|
|
1200
|
-
// Handoff ADR-011 (#12) : une réponse de membre qui @ un autre membre est injectée dans sa session.
|
|
1559
|
+
// Handoff ADR-011 (#12) : une réponse qui @ un autre membre est injectée dans sa session.
|
|
1560
|
+
// Le hop du message d'origine est hérité (#30) : la limite de sauts coupe A↔B, plus de garde one-shot.
|
|
1201
1561
|
async function handleHandoff(sourceConvId, groupId, text) {
|
|
1202
|
-
if (handoffTargets.delete(sourceConvId))
|
|
1203
|
-
return; // réponse d'un tour déclenché par handoff : pas de cascade
|
|
1204
1562
|
const group = getGroupWithMembers(db, groupId);
|
|
1205
1563
|
if (!group)
|
|
1206
1564
|
return;
|
|
@@ -1212,13 +1570,20 @@ export function createApp(opts) {
|
|
|
1212
1570
|
.get(target.conversation_id);
|
|
1213
1571
|
if (!conv)
|
|
1214
1572
|
return;
|
|
1215
|
-
|
|
1573
|
+
const source = getConversation(db, sourceConvId);
|
|
1574
|
+
const inherited = originHop(db, sourceConvId);
|
|
1216
1575
|
try {
|
|
1217
|
-
await
|
|
1218
|
-
|
|
1576
|
+
await submitToLane(db, team, {
|
|
1577
|
+
conversationId: conv.id,
|
|
1578
|
+
body: text,
|
|
1579
|
+
fromAgentId: source?.agent_id ?? null,
|
|
1580
|
+
chainId: inherited.chainId,
|
|
1581
|
+
hop: inherited.hop,
|
|
1582
|
+
});
|
|
1219
1583
|
}
|
|
1220
|
-
catch {
|
|
1221
|
-
|
|
1584
|
+
catch (err) {
|
|
1585
|
+
if (err instanceof QueueError && err.code === "hop_limit")
|
|
1586
|
+
return;
|
|
1222
1587
|
}
|
|
1223
1588
|
}
|
|
1224
1589
|
// Fan-out des événements pi vers les abonnés SSE par conversation
|
|
@@ -1247,11 +1612,16 @@ export function createApp(opts) {
|
|
|
1247
1612
|
sseSubs,
|
|
1248
1613
|
groupSubs,
|
|
1249
1614
|
logins: new ProviderLogins(paths),
|
|
1615
|
+
githubLogin: new GitHubLogin(paths, () => pool.refreshExtensions()),
|
|
1250
1616
|
spawner,
|
|
1251
1617
|
compose,
|
|
1252
1618
|
durable,
|
|
1619
|
+
createWorkspaceImpl: opts.createWorkspaceImpl,
|
|
1620
|
+
team,
|
|
1253
1621
|
};
|
|
1622
|
+
const browser = new SharedBrowser(paths.home, db, opts.auth?.config.origin);
|
|
1254
1623
|
const routes = [
|
|
1624
|
+
...browserRoutes(browser, req => privateRequests.has(req), sendJson, !!opts.auth),
|
|
1255
1625
|
healthRoute(deps),
|
|
1256
1626
|
...registryRoutes(deps),
|
|
1257
1627
|
...agentRoutes(deps),
|
|
@@ -1260,6 +1630,7 @@ export function createApp(opts) {
|
|
|
1260
1630
|
...groupRoutes(deps),
|
|
1261
1631
|
...conversationRoutes(deps),
|
|
1262
1632
|
...scheduleRoutes(deps),
|
|
1633
|
+
...teamRoutes(deps),
|
|
1263
1634
|
// Events global (SSE) — les runs cron et les statuts de conversation
|
|
1264
1635
|
["GET", "/api/events", (ctx) => {
|
|
1265
1636
|
const send = openSse(ctx.res);
|
|
@@ -1267,14 +1638,58 @@ export function createApp(opts) {
|
|
|
1267
1638
|
ctx.res.once("close", () => events.off("event", send));
|
|
1268
1639
|
}],
|
|
1269
1640
|
];
|
|
1641
|
+
// Dispatch interne des routes /api/* pour le serveur MCP HTTP : mêmes handlers,
|
|
1642
|
+
// mêmes validations et contrôles de disponibilité que l'UI, sans boucle réseau.
|
|
1643
|
+
const availability = () => { if (opts.auth)
|
|
1644
|
+
opts.auth.assertAvailable();
|
|
1645
|
+
else
|
|
1646
|
+
localCheck(paths.home); };
|
|
1647
|
+
// OAuth 2.1 (connecteurs web ChatGPT / Claude.ai) : seulement avec une origine HTTPS et un login propriétaire.
|
|
1648
|
+
const oauth = opts.auth ? new McpOAuth(paths.home, opts.auth) : undefined;
|
|
1649
|
+
const mcp = new McpHttpEndpoint({
|
|
1650
|
+
home: paths.home,
|
|
1651
|
+
version: packageVersion(),
|
|
1652
|
+
oauth,
|
|
1653
|
+
dispatch: (method, path, body) => dispatchInternal(routes, method, path, body, availability),
|
|
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
|
+
}));
|
|
1270
1679
|
const app = opts.server ?? createServer();
|
|
1680
|
+
attachBrowserView(app, browser, paths.home, opts.auth);
|
|
1681
|
+
attachTerminalSocket(app, terminals, opts.auth);
|
|
1271
1682
|
if (opts.auth) {
|
|
1272
1683
|
app.requestTimeout = 30_000;
|
|
1273
1684
|
app.headersTimeout = 10_000;
|
|
1274
1685
|
app.maxHeadersCount = 100;
|
|
1275
1686
|
}
|
|
1276
1687
|
app.once("close", () => {
|
|
1688
|
+
deps.logins.dispose();
|
|
1689
|
+
deps.githubLogin.cancel();
|
|
1690
|
+
stopReap.stop();
|
|
1277
1691
|
unsubscribePool();
|
|
1692
|
+
void mcp.close();
|
|
1278
1693
|
void durable.dispose();
|
|
1279
1694
|
});
|
|
1280
1695
|
app.on("request", async (req, res) => {
|
|
@@ -1287,6 +1702,35 @@ export function createApp(opts) {
|
|
|
1287
1702
|
const state = opts.auth;
|
|
1288
1703
|
if (privateRequest && ("origin" in req.headers || Object.keys(req.headers).some(h => h.startsWith("sec-fetch-"))))
|
|
1289
1704
|
throw new AuthError("FORBIDDEN", 403);
|
|
1705
|
+
// MCP Streamable HTTP : authentifié par jeton Bearer (jamais par cookie de session),
|
|
1706
|
+
// donc hors de la frontière navigateur ; l'hôte et une Origin éventuelle restent contrôlés.
|
|
1707
|
+
if ((req.url ?? "").split("?")[0] === MCP_HTTP_PATH) {
|
|
1708
|
+
if (privateRequest)
|
|
1709
|
+
throw new AuthError("FORBIDDEN", 403);
|
|
1710
|
+
if (state) {
|
|
1711
|
+
state.assertAvailable();
|
|
1712
|
+
if (req.headers.host !== new URL(state.config.origin).host)
|
|
1713
|
+
throw new AuthError("FORBIDDEN", 403);
|
|
1714
|
+
if (req.headers.origin !== undefined && req.headers.origin !== state.config.origin)
|
|
1715
|
+
throw new AuthError("FORBIDDEN", 403);
|
|
1716
|
+
}
|
|
1717
|
+
else
|
|
1718
|
+
localCheck(paths.home);
|
|
1719
|
+
return await mcp.handle(req, res);
|
|
1720
|
+
}
|
|
1721
|
+
// OAuth : métadonnées, enregistrement, jeton (appelés de serveur à serveur) et page de
|
|
1722
|
+
// consentement (navigation intersite depuis l'application). Contrôles propres au module.
|
|
1723
|
+
if (oauth && McpOAuth.handles((req.url ?? "").split("?")[0] ?? "")) {
|
|
1724
|
+
if (privateRequest || !state)
|
|
1725
|
+
throw new AuthError("FORBIDDEN", 403);
|
|
1726
|
+
state.assertAvailable();
|
|
1727
|
+
if (req.headers.host !== new URL(state.config.origin).host)
|
|
1728
|
+
throw new AuthError("FORBIDDEN", 403);
|
|
1729
|
+
return await oauth.handle(req, res, new URL(req.url ?? "/", state.config.origin));
|
|
1730
|
+
}
|
|
1731
|
+
// Sans OAuth (mode local), la découverte doit échouer proprement, jamais via le fallback SPA.
|
|
1732
|
+
if ((req.url ?? "").startsWith("/.well-known/") || (req.url ?? "").startsWith("/oauth/"))
|
|
1733
|
+
return sendJson(res, 404, { error: "NOT_FOUND" });
|
|
1290
1734
|
if (state) {
|
|
1291
1735
|
state.assertAvailable();
|
|
1292
1736
|
if (!privateRequest)
|
|
@@ -1315,8 +1759,8 @@ export function createApp(opts) {
|
|
|
1315
1759
|
check = () => state.assertAvailable();
|
|
1316
1760
|
else {
|
|
1317
1761
|
const session = await ownerSession(state.auth, state.db, state.config, browserHeaders(req));
|
|
1318
|
-
requireApproved(session);
|
|
1319
|
-
check = () => { state.assertAvailable(); requireApproved(sessionById(state.db, state.config, session.id)); };
|
|
1762
|
+
requireApproved(session, state.config);
|
|
1763
|
+
check = () => { state.assertAvailable(); requireApproved(sessionById(state.db, state.config, session.id), state.config); };
|
|
1320
1764
|
}
|
|
1321
1765
|
}
|
|
1322
1766
|
check();
|
|
@@ -1346,6 +1790,118 @@ export function createApp(opts) {
|
|
|
1346
1790
|
});
|
|
1347
1791
|
return app;
|
|
1348
1792
|
}
|
|
1793
|
+
/** Réponse en mémoire pour le dispatch interne (routes JSON uniquement, pas de SSE). */
|
|
1794
|
+
class CaptureResponse extends EventEmitter {
|
|
1795
|
+
statusCode = 200;
|
|
1796
|
+
headersSent = false;
|
|
1797
|
+
destroyed = false;
|
|
1798
|
+
writableEnded = false;
|
|
1799
|
+
chunks = [];
|
|
1800
|
+
headers = new Map();
|
|
1801
|
+
setHeader(name, value) { this.headers.set(name.toLowerCase(), value); return this; }
|
|
1802
|
+
getHeader(name) { return this.headers.get(name.toLowerCase()); }
|
|
1803
|
+
removeHeader(name) { this.headers.delete(name.toLowerCase()); }
|
|
1804
|
+
writeHead(status, headers) {
|
|
1805
|
+
this.statusCode = status;
|
|
1806
|
+
for (const [k, v] of Object.entries(headers ?? {}))
|
|
1807
|
+
this.setHeader(k, v);
|
|
1808
|
+
this.headersSent = true;
|
|
1809
|
+
return this;
|
|
1810
|
+
}
|
|
1811
|
+
write(chunk) {
|
|
1812
|
+
this.headersSent = true;
|
|
1813
|
+
if (chunk !== undefined && chunk !== null)
|
|
1814
|
+
this.chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));
|
|
1815
|
+
return true;
|
|
1816
|
+
}
|
|
1817
|
+
end(chunk) {
|
|
1818
|
+
if (typeof chunk !== "function")
|
|
1819
|
+
this.write(chunk);
|
|
1820
|
+
this.headersSent = true;
|
|
1821
|
+
this.writableEnded = true;
|
|
1822
|
+
this.emit("finish");
|
|
1823
|
+
this.emit("close");
|
|
1824
|
+
return this;
|
|
1825
|
+
}
|
|
1826
|
+
flushHeaders() { this.headersSent = true; }
|
|
1827
|
+
text() { return Buffer.concat(this.chunks).toString("utf8"); }
|
|
1828
|
+
}
|
|
1829
|
+
/** Requêtes synthétiques (dispatch MCP) : jamais privées, jamais navigateur (ex. terminal refusé). */
|
|
1830
|
+
const syntheticRequests = new WeakSet();
|
|
1831
|
+
function syntheticRequest(method, path) {
|
|
1832
|
+
const req = new EventEmitter();
|
|
1833
|
+
Object.assign(req, { method, url: path, headers: { "content-type": "application/json" }, socket: { remoteAddress: "mcp" } });
|
|
1834
|
+
syntheticRequests.add(req);
|
|
1835
|
+
return req;
|
|
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
|
+
}
|
|
1865
|
+
/** Exécute une route /api/* en mémoire et renvoie son JSON (erreur si statut ≥ 400). */
|
|
1866
|
+
async function dispatchInternal(routes, method, path, body, check) {
|
|
1867
|
+
const url = new URL(path, `http://${HOST}`);
|
|
1868
|
+
if (!url.pathname.startsWith("/api/"))
|
|
1869
|
+
throw new Error(`not found: ${url.pathname}`);
|
|
1870
|
+
const found = matchRoute(routes, method, url.pathname);
|
|
1871
|
+
if (!found)
|
|
1872
|
+
throw new Error(`not found: ${url.pathname}`);
|
|
1873
|
+
const capture = new CaptureResponse();
|
|
1874
|
+
const res = capture;
|
|
1875
|
+
responseChecks.set(res, check);
|
|
1876
|
+
check();
|
|
1877
|
+
// Aller-retour JSON : le handler voit exactement ce qu'un client HTTP aurait envoyé.
|
|
1878
|
+
const parsed = body === undefined ? {} : JSON.parse(JSON.stringify(body));
|
|
1879
|
+
try {
|
|
1880
|
+
await requestAuthorization.run(check, () => found.handler({
|
|
1881
|
+
params: found.params, query: url.searchParams, body: parsed, req: syntheticRequest(method, path), res, check,
|
|
1882
|
+
}));
|
|
1883
|
+
}
|
|
1884
|
+
catch (err) {
|
|
1885
|
+
if (err instanceof AuthError)
|
|
1886
|
+
throw new Error(err.code);
|
|
1887
|
+
throw err;
|
|
1888
|
+
}
|
|
1889
|
+
if (!capture.writableEnded)
|
|
1890
|
+
throw new Error(`route sans réponse JSON : ${method} ${url.pathname}`);
|
|
1891
|
+
const text = capture.text();
|
|
1892
|
+
let data;
|
|
1893
|
+
try {
|
|
1894
|
+
data = text ? JSON.parse(text) : {};
|
|
1895
|
+
}
|
|
1896
|
+
catch {
|
|
1897
|
+
throw new Error(`réponse non JSON : ${method} ${url.pathname}`);
|
|
1898
|
+
}
|
|
1899
|
+
if (capture.statusCode >= 400) {
|
|
1900
|
+
const error = data && typeof data === "object" && "error" in data ? data.error : undefined;
|
|
1901
|
+
throw new Error(typeof error === "string" ? error : `HTTP ${capture.statusCode}`);
|
|
1902
|
+
}
|
|
1903
|
+
return data;
|
|
1904
|
+
}
|
|
1349
1905
|
// Server-owned identity only: no HTTP header can confer the local OS-owner capability.
|
|
1350
1906
|
const privateRequests = new WeakSet();
|
|
1351
1907
|
export function createPrivateServer(app) {
|