@ignitionai/cogitator 0.5.0 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/LICENSE +21 -0
  3. package/README.md +83 -44
  4. package/dist/extensions/index.js +66 -29
  5. package/dist/src/app-updates.js +15 -0
  6. package/dist/src/auth-cli.js +18 -8
  7. package/dist/src/auth-http.js +13 -3
  8. package/dist/src/auth-state.js +41 -6
  9. package/dist/src/board.js +3 -1
  10. package/dist/src/browser-http.js +143 -0
  11. package/dist/src/classic-configuration.js +12 -4
  12. package/dist/src/cli.js +30 -4
  13. package/dist/src/config.js +10 -0
  14. package/dist/src/cron.js +91 -15
  15. package/dist/src/db.js +55 -3
  16. package/dist/src/durable/approvals.js +17 -2
  17. package/dist/src/durable/effect-gateway.js +23 -16
  18. package/dist/src/durable/manager.js +15 -6
  19. package/dist/src/durable/mission-runtime.js +204 -46
  20. package/dist/src/durable/recovery.js +37 -0
  21. package/dist/src/durable/workers.js +22 -14
  22. package/dist/src/execution/confinement.js +2 -1
  23. package/dist/src/execution/worker-supervisor.js +222 -0
  24. package/dist/src/git-import.js +187 -0
  25. package/dist/src/github-login.js +101 -0
  26. package/dist/src/history.js +6 -1
  27. package/dist/src/host-pi.js +64 -0
  28. package/dist/src/json-files.js +7 -4
  29. package/dist/src/machine-metrics.js +49 -0
  30. package/dist/src/machine-types.js +1 -0
  31. package/dist/src/mcp-cli.js +63 -0
  32. package/dist/src/mcp-http.js +164 -0
  33. package/dist/src/mcp-oauth.js +502 -0
  34. package/dist/src/mcp-server.js +6 -136
  35. package/dist/src/mcp-tokens.js +104 -0
  36. package/dist/src/mcp-tools.js +264 -0
  37. package/dist/src/native-auth.js +9 -2
  38. package/dist/src/packages.js +190 -0
  39. package/dist/src/paths.js +1 -0
  40. package/dist/src/pi-child.js +180 -0
  41. package/dist/src/pi-rpc-wrap.js +84 -0
  42. package/dist/src/pool.js +58 -7
  43. package/dist/src/project-setup.js +63 -0
  44. package/dist/src/provider-login.js +73 -14
  45. package/dist/src/reap-orphans.js +138 -0
  46. package/dist/src/registry.js +68 -45
  47. package/dist/src/schemas.js +19 -4
  48. package/dist/src/server-compat.js +173 -0
  49. package/dist/src/server-identity.js +69 -0
  50. package/dist/src/server.js +534 -41
  51. package/dist/src/shared-browser.js +357 -0
  52. package/dist/src/skills-import.js +13 -4
  53. package/dist/src/skills-upload.js +68 -0
  54. package/dist/src/spawner.js +20 -4
  55. package/dist/src/subagents.js +242 -0
  56. package/dist/src/team-queue.js +262 -0
  57. package/package.json +13 -4
  58. package/web/dist/assets/BrandLogo3D-CHGXwTbZ.js +4035 -0
  59. package/web/dist/assets/index-DGLkhrE7.css +1 -0
  60. package/web/dist/assets/index-P0WoXBgX.js +84 -0
  61. package/web/dist/index.html +2 -2
  62. package/web/dist/assets/index-C3tRuOTh.js +0 -83
  63. package/web/dist/assets/index-DMQqB0r1.css +0 -1
@@ -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,25 @@ 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";
34
49
  // ---------- Statique ----------
35
50
  /** Localise web/dist en remontant depuis le module (marche en dev src/ comme en prod dist/src/ ou en paquet npm). */
36
51
  function findWebDist() {
@@ -218,6 +233,29 @@ function requireWorkspace(deps, ctx) {
218
233
  function requireConversation(deps, ctx) {
219
234
  return getConversation(deps.db, ctx.params.id) ?? notFound(ctx.res, "conversation");
220
235
  }
236
+ function queueHttpStatus(code) {
237
+ switch (code) {
238
+ case "hop_limit":
239
+ case "conflict":
240
+ return 409;
241
+ case "not_found":
242
+ return 404;
243
+ default: {
244
+ const _exhaustive = code;
245
+ return _exhaustive;
246
+ }
247
+ }
248
+ }
249
+ async function deliverClassic(deps, conv, text, images, extra) {
250
+ return submitToLane(deps.db, deps.team, {
251
+ conversationId: conv.id,
252
+ body: text || "(image)",
253
+ fromAgentId: extra?.fromAgentId ?? null,
254
+ chainId: extra?.chainId,
255
+ hop: extra?.hop,
256
+ idempotencyKey: extra?.idempotencyKey,
257
+ }, images);
258
+ }
221
259
  function requireAgent(deps, ctx) {
222
260
  return getAgent(deps.db, ctx.params.id) ?? notFound(ctx.res, "agent");
223
261
  }
@@ -225,7 +263,70 @@ function requireAgent(deps, ctx) {
225
263
  /** Registry pi : providers, skills, MCP user-level. */
226
264
  function registryRoutes(deps) {
227
265
  const { paths } = deps;
266
+ const packages = new PackageManager(paths, () => deps.pool.refreshExtensions());
267
+ const sampleMachine = machineMetrics(paths.home);
228
268
  return [
269
+ ["GET", "/api/machine", async (ctx) => {
270
+ const metrics = await sampleMachine();
271
+ ctx.check();
272
+ sendJson(ctx.res, 200, metrics);
273
+ }],
274
+ ["GET", "/api/github/connection", async (ctx) => {
275
+ sendJson(ctx.res, 200, await deps.githubLogin.state());
276
+ }],
277
+ ["POST", "/api/github/connection", (ctx) => {
278
+ ctx.check();
279
+ sendJson(ctx.res, 202, deps.githubLogin.start());
280
+ }],
281
+ ["DELETE", "/api/github/connection", (ctx) => {
282
+ ctx.check();
283
+ deps.githubLogin.cancel();
284
+ sendJson(ctx.res, 200, { ok: true });
285
+ }],
286
+ ["GET", "/api/app-updates", async (ctx) => {
287
+ try {
288
+ sendJson(ctx.res, 200, await appUpdateStatus());
289
+ }
290
+ catch {
291
+ sendJson(ctx.res, 502, { error: "Release check unavailable" });
292
+ }
293
+ }],
294
+ ["GET", "/api/packages", (ctx) => {
295
+ sendJson(ctx.res, 200, { installed: installedPackages(paths), operation: packages.operation });
296
+ }],
297
+ ["GET", "/api/packages/catalog", async (ctx) => {
298
+ const page = Math.max(1, Math.min(1000, Number(ctx.query.get("page")) || 1));
299
+ try {
300
+ sendJson(ctx.res, 200, await catalog(ctx.query.get("q") ?? "", ctx.query.get("type") ?? "extension", Math.floor(page)));
301
+ }
302
+ catch (error) {
303
+ sendJson(ctx.res, 502, { error: error.message });
304
+ }
305
+ }],
306
+ ["POST", "/api/packages", (ctx) => {
307
+ const body = ctx.body;
308
+ if (!body || typeof body.name !== "string" || !["install", "remove", "update"].includes(String(body.action)))
309
+ return sendJson(ctx.res, 400, { error: "Package et action requis." });
310
+ try {
311
+ ctx.check();
312
+ sendJson(ctx.res, 202, packages.start(body.name, body.action));
313
+ }
314
+ catch (error) {
315
+ sendJson(ctx.res, 409, { error: error.message });
316
+ }
317
+ }],
318
+ ["GET", "/api/packages/updates", async (ctx) => {
319
+ sendJson(ctx.res, 200, { updates: await packageUpdates(paths) });
320
+ }],
321
+ ["POST", "/api/packages/reload", 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 deferred = await deps.pool.refreshExtensions();
326
+ if (packages.operation)
327
+ packages.operation.deferred = deferred;
328
+ sendJson(ctx.res, 200, { deferred });
329
+ }],
229
330
  ["GET", "/api/providers", async (ctx) => {
230
331
  sendJson(ctx.res, 200, { providers: await listProviders(paths) });
231
332
  }],
@@ -258,8 +359,11 @@ function registryRoutes(deps) {
258
359
  if (!body)
259
360
  return;
260
361
  const id = ctx.params.id;
261
- if (authMethodsFor(id).length === 0)
362
+ const methods = authMethodsFor(id);
363
+ if (methods.length === 0)
262
364
  return sendJson(ctx.res, 404, { error: `Unknown provider: ${id}` });
365
+ if (!methods.some(method => method.type === body.type))
366
+ return sendJson(ctx.res, 400, { error: "Unsupported authentication method" });
263
367
  sendJson(ctx.res, 202, deps.logins.start(id, body.type));
264
368
  }],
265
369
  ["GET", "/api/provider-logins/:id/events", (ctx) => {
@@ -285,9 +389,33 @@ function registryRoutes(deps) {
285
389
  return sendJson(ctx.res, 404, { error: "login session not found" });
286
390
  sendJson(ctx.res, 200, { ok: true });
287
391
  }],
392
+ ["GET", "/api/setup-context", async (ctx) => {
393
+ const workspaceId = ctx.query.get("workspace_id");
394
+ const workspace = workspaceId ? getWorkspace(deps.db, workspaceId) : null;
395
+ if (workspaceId && !workspace)
396
+ return sendJson(ctx.res, 404, { error: "Workspace introuvable" });
397
+ const inventory = resourceInventory(deps.db, paths, workspace?.dir ?? paths.home);
398
+ try {
399
+ sendJson(ctx.res, 200, { ...inventory, tools: await probeCogitatorTools(paths), ready: true });
400
+ }
401
+ catch (error) {
402
+ sendJson(ctx.res, 200, { ...inventory, tools: [], ready: false, error: error.message });
403
+ }
404
+ }],
288
405
  ["GET", "/api/skills", (ctx) => {
289
406
  sendJson(ctx.res, 200, { skills: listSkills(paths) });
290
407
  }],
408
+ ["POST", "/api/skills/upload", (ctx) => {
409
+ ctx.check();
410
+ const dest = paths.skillsDirs[0] ?? join(paths.piAgentDir, "skills");
411
+ try {
412
+ const result = importSkillUpload(ctx.body?.files, dest);
413
+ sendJson(ctx.res, 200, { ...result, dest });
414
+ }
415
+ catch (error) {
416
+ sendJson(ctx.res, 400, { error: error.message });
417
+ }
418
+ }],
291
419
  ["POST", "/api/skills/import", async (ctx) => {
292
420
  const b = parseBody(ctx.res, skillImportSchema, ctx.body);
293
421
  if (!b)
@@ -382,11 +510,96 @@ function workspaceRoutes(deps) {
382
510
  ["GET", "/api/workspaces", (ctx) => {
383
511
  sendJson(ctx.res, 200, { workspaces: listWorkspaces(db) });
384
512
  }],
385
- ["POST", "/api/workspaces", (ctx) => {
513
+ ["POST", "/api/workspaces", async (ctx) => {
386
514
  const b = parseBody(ctx.res, workspaceCreateSchema, ctx.body);
387
515
  if (!b)
388
516
  return;
389
- const { workspace, error } = createWorkspace(db, b, enrollmentPolicyFromEnv());
517
+ const policy = enrollmentPolicyFromEnv();
518
+ if (b.git_url) {
519
+ const root = deps.paths.projectsDir;
520
+ const target = localDirFor(b.git_url, root);
521
+ if ("error" in target)
522
+ return sendJson(ctx.res, 400, { error: target.error });
523
+ // B1/L2 : en mode distant, refuser AVANT toute écriture si la destination
524
+ // canonique n'est sous aucune racine enrôlée. Les deux côtés sont canonicalisés :
525
+ // un <root> ou <root>/<owner> déjà présent en symlink ferait sinon écrire hors
526
+ // racine (le clone suit les liens, la garde lexicale non).
527
+ if (policy.remote) {
528
+ // Canonicalise le plus long préfixe existant puis résout le reste lexicalement
529
+ // (cf. resolveConfined) : appliqué à la destination ET aux racines, sinon deux
530
+ // représentations du même chemin (/tmp vs /private/tmp) ne matchent jamais.
531
+ const canonical = (p) => {
532
+ let existing = resolve(p);
533
+ const tail = [];
534
+ while (!existsSync(existing)) {
535
+ const parent = dirname(existing);
536
+ if (parent === existing)
537
+ break;
538
+ tail.unshift(basename(existing));
539
+ existing = parent;
540
+ }
541
+ try {
542
+ return join(realpathSync(existing), ...tail);
543
+ }
544
+ catch {
545
+ return resolve(p);
546
+ }
547
+ };
548
+ const destCanon = canonical(target.dest);
549
+ if (!policy.enrolledRoots.some((enrolled) => isInsideDir(destCanon, canonical(enrolled)))) {
550
+ return sendJson(ctx.res, 400, { error: `racine de clone hors des racines enrôlées: ${root}` });
551
+ }
552
+ }
553
+ const result = await cloneRepo(target.source, target.dest, githubConfigured(deps.paths) ? githubEnv(deps.paths) : undefined);
554
+ if ("error" in result)
555
+ return sendJson(ctx.res, 400, { error: result.error });
556
+ // D4 : tout échec après le clone (autorisation révoquée pendant les 25 s, ou refus
557
+ // d'enrôlement) doit laisser le disque propre — sans jamais supprimer un dossier
558
+ // qu'un workspace référence déjà (import concurrent gagnant) ni un dossier vide
559
+ // préexistant que Cogitator n'a pas créé (S3 : `created` le distingue). La
560
+ // comparaison se fait en forme canonicalisée, comme les lignes DB écrites par
561
+ // createWorkspace : une comparaison lexicale rendrait la garde inerte sur toute
562
+ // racine symlinkée (/tmp sur macOS — M1).
563
+ const discardClone = () => {
564
+ if (!result.cloned || !result.created)
565
+ return;
566
+ let cloned;
567
+ try {
568
+ cloned = realpathSync(result.dir); // le dossier existe : on vient de le cloner
569
+ }
570
+ catch {
571
+ return; // déjà parti
572
+ }
573
+ if (getWorkspaceByDir(db, cloned))
574
+ return;
575
+ // Nettoyage best-effort : un EBUSY/EPERM ne doit pas masquer l'erreur d'origine
576
+ // (S2) — ici on est dans le catch de la requête ou sur un refus 400.
577
+ try {
578
+ rmSync(cloned, { recursive: true, force: true });
579
+ }
580
+ catch {
581
+ /* dossier résiduel possible, signalé par l'erreur d'origine */
582
+ }
583
+ };
584
+ let created;
585
+ try {
586
+ ctx.check(); // autorisation à revérifier après l'await long (le clone)
587
+ created = (deps.createWorkspaceImpl ?? createWorkspace)(db, { dir: result.dir, name: b.name, default_agent_id: b.default_agent_id }, policy);
588
+ }
589
+ catch (err) {
590
+ discardClone();
591
+ throw err;
592
+ }
593
+ if (created.error) {
594
+ discardClone();
595
+ return sendJson(ctx.res, 400, { error: created.error });
596
+ }
597
+ return sendJson(ctx.res, 201, { workspace: created.workspace });
598
+ }
599
+ // Le refine du schéma garantit dir ici ; la garde sert de resserrement de type.
600
+ if (!b.dir)
601
+ return sendJson(ctx.res, 400, { error: "dir ou git_url requis" });
602
+ const { workspace, error } = createWorkspace(db, { dir: b.dir, name: b.name, default_agent_id: b.default_agent_id }, policy);
390
603
  if (error)
391
604
  return sendJson(ctx.res, 400, { error });
392
605
  sendJson(ctx.res, 201, { workspace });
@@ -644,9 +857,8 @@ async function startCardWork(deps, ws, number, extra, check = () => { }) {
644
857
  });
645
858
  setConversationTitle(deps.db, conv.id, `#${card.number} ${card.title}`);
646
859
  const titled = getConversation(deps.db, conv.id);
647
- await deps.spawner.ensure(titled);
648
860
  check();
649
- await deps.pool.prompt(titled.id, ticketPrompt(card, extra));
861
+ await deliverClassic(deps, titled, ticketPrompt(card, extra));
650
862
  check();
651
863
  const moved = await moveCardGh(ws.dir, card.number, "in_progress");
652
864
  if ("error" in moved)
@@ -671,10 +883,15 @@ function ticketPrompt(card, extra) {
671
883
  function conversationRoutes(deps) {
672
884
  const { db, pool } = deps;
673
885
  return [
674
- ["GET", "/api/conversations", (ctx) => {
886
+ ["GET", "/api/conversations", async (ctx) => {
675
887
  const workspaceId = ctx.query.get("workspace_id") ?? undefined;
676
888
  const agentId = ctx.query.get("agent_id") ?? undefined;
677
- sendJson(ctx.res, 200, { conversations: listConversations(db, workspaceId, agentId) });
889
+ const conversations = await Promise.all(listConversations(db, workspaceId, agentId).map(async (conv) => {
890
+ const runtime = deps.compose(conv);
891
+ return { ...conv, streaming: runtime.kind === "classic" ? await pool.isStreaming(conv.id) : runtime.isLive(conv) };
892
+ }));
893
+ ctx.check();
894
+ sendJson(ctx.res, 200, { conversations });
678
895
  }],
679
896
  ["POST", "/api/conversations", async (ctx) => {
680
897
  const b = parseBody(ctx.res, conversationCreateSchema, ctx.body);
@@ -697,14 +914,30 @@ function conversationRoutes(deps) {
697
914
  const prompt = b.prompt?.trim();
698
915
  if (prompt) {
699
916
  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
917
  ctx.check();
704
- setConversationTitle(db, conv.id, prompt);
705
- conv = getConversation(db, conv.id);
706
- if (ack.accepted)
707
- return sendJson(ctx.res, 201, { conversation: conv, accepted: ack.accepted });
918
+ if (runtime.kind === "durable") {
919
+ await runtime.ensure(conv);
920
+ ctx.check();
921
+ const ack = await runtime.prompt(conv, prompt, randomUUID());
922
+ ctx.check();
923
+ setConversationTitle(db, conv.id, prompt);
924
+ conv = getConversation(db, conv.id);
925
+ if (ack.accepted)
926
+ return sendJson(ctx.res, 201, { conversation: conv, accepted: ack.accepted });
927
+ }
928
+ else {
929
+ try {
930
+ await deliverClassic(deps, conv, prompt);
931
+ }
932
+ catch (err) {
933
+ if (err instanceof QueueError)
934
+ return sendJson(ctx.res, queueHttpStatus(err.code), { error: err.message, code: err.code });
935
+ throw err;
936
+ }
937
+ ctx.check();
938
+ setConversationTitle(db, conv.id, prompt);
939
+ conv = getConversation(db, conv.id);
940
+ }
708
941
  }
709
942
  sendJson(ctx.res, 201, { conversation: conv });
710
943
  }],
@@ -725,7 +958,21 @@ function conversationRoutes(deps) {
725
958
  if (!conv)
726
959
  return;
727
960
  const runtime = deps.compose(conv);
728
- const spawned = await runtime.ensure(conv);
961
+ let spawned;
962
+ try {
963
+ spawned = await runtime.ensure(conv);
964
+ }
965
+ catch (error) {
966
+ if (error instanceof AuthError)
967
+ throw error;
968
+ ctx.check();
969
+ const send = openSse(ctx.res);
970
+ send({ type: "session_error", code: error instanceof ConfigurationError ? error.code : "SESSION_START_FAILED",
971
+ provider: error instanceof ConfigurationError ? error.provider : conv.provider,
972
+ error: error instanceof Error ? error.message : "Session startup failed" });
973
+ ctx.res.end();
974
+ return;
975
+ }
729
976
  // Mode durable : aucun spawn (la runtime vit dans le contrôleur) ; la lecture
730
977
  // d'événements ne crée jamais de mission (Plan 0002 §7).
731
978
  const send = openSse(ctx.res, runtime.kind === "durable"
@@ -762,6 +1009,22 @@ function conversationRoutes(deps) {
762
1009
  return;
763
1010
  sendJson(ctx.res, 200, { files: readFileChanges(conv.session_file ?? "") });
764
1011
  }],
1012
+ // Subagents herdr live de cette conversation (ADR-012) : lecture seule, jamais de 5xx herdr.
1013
+ ["GET", "/api/conversations/:id/subagents", async (ctx) => {
1014
+ const conv = requireConversation(deps, ctx);
1015
+ if (!conv)
1016
+ return;
1017
+ sendJson(ctx.res, 200, listSubagents(conv.session_file));
1018
+ }],
1019
+ ["GET", "/api/conversations/:id/subagents/:subagentId", (ctx) => {
1020
+ const conv = requireConversation(deps, ctx);
1021
+ if (!conv)
1022
+ return;
1023
+ const transcript = readSubagentTranscript(conv.session_file, ctx.params.subagentId);
1024
+ if (!transcript)
1025
+ return sendJson(ctx.res, 404, { error: "Subagent transcript unavailable" });
1026
+ sendJson(ctx.res, 200, transcript);
1027
+ }],
765
1028
  ["GET", "/api/conversations/:id/file", (ctx) => {
766
1029
  const conv = requireConversation(deps, ctx);
767
1030
  if (!conv)
@@ -783,14 +1046,37 @@ function conversationRoutes(deps) {
783
1046
  if (runtime.kind === "durable" && !b.requestId) {
784
1047
  return sendJson(ctx.res, 400, { error: "requestId requis pour une conversation durable" });
785
1048
  }
786
- await runtime.ensure(conv);
787
- ctx.check();
788
- const ack = await runtime.prompt(conv, text, b.requestId, b.images);
789
1049
  ctx.check();
790
- if (text)
791
- setConversationTitle(db, conv.id, text);
792
- // Durable : accusé renvoyé après acceptation durable, avec l'identité acceptée.
793
- sendJson(ctx.res, 200, ack.accepted ? { ok: true, accepted: ack.accepted } : { ok: true });
1050
+ if (runtime.kind === "durable") {
1051
+ try {
1052
+ await runtime.ensure(conv);
1053
+ ctx.check();
1054
+ const ack = await runtime.prompt(conv, text, b.requestId, b.images);
1055
+ ctx.check();
1056
+ if (text)
1057
+ setConversationTitle(db, conv.id, text);
1058
+ sendJson(ctx.res, 200, ack.accepted ? { ok: true, accepted: ack.accepted } : { ok: true });
1059
+ }
1060
+ catch (err) {
1061
+ if (!(err instanceof NeedsAttentionError))
1062
+ throw err;
1063
+ ctx.check();
1064
+ sendJson(ctx.res, 409, { error: err.message, code: "needs_attention" });
1065
+ }
1066
+ return;
1067
+ }
1068
+ try {
1069
+ await deliverClassic(deps, conv, text, b.images);
1070
+ ctx.check();
1071
+ if (text)
1072
+ setConversationTitle(db, conv.id, text);
1073
+ sendJson(ctx.res, 200, { ok: true });
1074
+ }
1075
+ catch (err) {
1076
+ if (err instanceof QueueError)
1077
+ return sendJson(ctx.res, queueHttpStatus(err.code), { error: err.message, code: err.code });
1078
+ throw err;
1079
+ }
794
1080
  }],
795
1081
  // ---------- Missions durables : statut, approbations, budget (#16) ----------
796
1082
  ["GET", "/api/conversations/:id/mission", async (ctx) => {
@@ -878,7 +1164,7 @@ function conversationRoutes(deps) {
878
1164
  catch (error) {
879
1165
  if (error instanceof AuthError)
880
1166
  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) });
1167
+ 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
1168
  }
883
1169
  }],
884
1170
  ["DELETE", "/api/conversations/:id/model", async (ctx) => {
@@ -1010,9 +1296,15 @@ function groupRoutes(deps) {
1010
1296
  .get(group.id, target.agent_id);
1011
1297
  if (!conv)
1012
1298
  return sendJson(ctx.res, 500, { error: "session membre introuvable" });
1013
- await deps.spawner.ensure(conv);
1014
1299
  ctx.check();
1015
- await pool.prompt(conv.id, text, b.images);
1300
+ try {
1301
+ await deliverClassic(deps, conv, text, b.images);
1302
+ }
1303
+ catch (err) {
1304
+ if (err instanceof QueueError)
1305
+ return sendJson(ctx.res, queueHttpStatus(err.code), { error: err.message, code: err.code });
1306
+ throw err;
1307
+ }
1016
1308
  ctx.check();
1017
1309
  sendJson(ctx.res, 200, { ok: true });
1018
1310
  }],
@@ -1171,6 +1463,50 @@ function scheduleRoutes(deps) {
1171
1463
  }],
1172
1464
  ];
1173
1465
  }
1466
+ function teamRoutes(deps) {
1467
+ const { db } = deps;
1468
+ return [
1469
+ ["POST", "/api/team/send", async (ctx) => {
1470
+ const b = parseBody(ctx.res, teamSendSchema, ctx.body);
1471
+ if (!b)
1472
+ return;
1473
+ const conv = getConversation(db, b.conversation_id);
1474
+ if (!conv) {
1475
+ notFound(ctx.res, "conversation");
1476
+ return;
1477
+ }
1478
+ if (runtimeKindOf(conv) === "durable")
1479
+ return sendJson(ctx.res, 409, { error: "file durable : conversation durable refusée", code: "conflict" });
1480
+ if (!b.from_conversation_id)
1481
+ return sendJson(ctx.res, 400, { error: "émetteur requis (COGITATOR_CONVERSATION_ID)" });
1482
+ const sender = getConversation(db, b.from_conversation_id);
1483
+ if (!sender)
1484
+ return sendJson(ctx.res, 400, { error: "conversation émetteur inconnue" });
1485
+ if (!sender.group_id || sender.group_id !== conv.group_id)
1486
+ return sendJson(ctx.res, 403, { error: "team_send : groupe commun requis" });
1487
+ const fromAgentId = sender.agent_id;
1488
+ if (fromAgentId && !getAgent(db, fromAgentId))
1489
+ return sendJson(ctx.res, 400, { error: "agent émetteur inconnu" });
1490
+ if (b.from_agent_id && !getAgent(db, b.from_agent_id))
1491
+ return sendJson(ctx.res, 400, { error: "agent émetteur inconnu" });
1492
+ const inherited = hopContext(deps.team, sender.id);
1493
+ try {
1494
+ const queued = await deliverClassic(deps, conv, b.body, undefined, {
1495
+ fromAgentId,
1496
+ chainId: inherited.chainId ?? b.chain_id ?? null,
1497
+ hop: Math.max(inherited.hop, b.hop ?? 0),
1498
+ idempotencyKey: b.idempotency_key,
1499
+ });
1500
+ sendJson(ctx.res, 200, { ok: true, queue_item_id: queued.id, lane_id: queued.laneId, created: queued.created });
1501
+ }
1502
+ catch (err) {
1503
+ if (err instanceof QueueError)
1504
+ return sendJson(ctx.res, queueHttpStatus(err.code), { error: err.message, code: err.code });
1505
+ throw err;
1506
+ }
1507
+ }],
1508
+ ];
1509
+ }
1174
1510
  const DEFAULT_RUNS_LIMIT = 50;
1175
1511
  function healthRoute(deps) {
1176
1512
  const { dbPath, dbVersion, paths, pool } = deps;
@@ -1190,17 +1526,31 @@ export function createApp(opts) {
1190
1526
  const events = opts.events ?? new EventEmitter();
1191
1527
  events.setMaxListeners(MAX_SSE_LISTENERS);
1192
1528
  recoverConfigurations(db);
1529
+ recoverInterrupted(db);
1530
+ reapOrphanOwnedPi(paths.home);
1531
+ const stopReap = startPeriodicReap(paths.home);
1193
1532
  const spawner = makeSpawner({ db, pool, paths });
1533
+ const team = new LaneDispatcher({
1534
+ db,
1535
+ pool,
1536
+ ensure: async (conversationId) => {
1537
+ const conv = getConversation(db, conversationId);
1538
+ if (!conv)
1539
+ throw new QueueError("conversation introuvable", "not_found");
1540
+ if (runtimeKindOf(conv) === "durable")
1541
+ throw new QueueError("file durable : conversation durable refusée", "conflict");
1542
+ return spawner.ensure(conv);
1543
+ },
1544
+ });
1545
+ cron?.attachTeam(team);
1546
+ kickQueuedLanes(db, team);
1194
1547
  // Runtime Durable : un seul gestionnaire dans le processus contrôleur (bail OS
1195
1548
  // par conversation). Les tests injectent un modèle contrôlé via opts.durable.
1196
1549
  const durable = opts.durable ?? new DurableRuntimeManager({ paths, toolchain: durableToolchainRegistry() });
1197
1550
  const compose = composeRuntime({ pool, spawner, durable });
1198
- // Tours déclenchés par un handoff : leur réponse ne re-handoffe pas (garde anti-boucle A↔B, #12)
1199
- const handoffTargets = new Set();
1200
- // Handoff ADR-011 (#12) : une réponse de membre qui @ un autre membre est injectée dans sa session.
1551
+ // Handoff ADR-011 (#12) : une réponse qui @ un autre membre est injectée dans sa session.
1552
+ // Le hop du message d'origine est hérité (#30) : la limite de sauts coupe A↔B, plus de garde one-shot.
1201
1553
  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
1554
  const group = getGroupWithMembers(db, groupId);
1205
1555
  if (!group)
1206
1556
  return;
@@ -1212,13 +1562,20 @@ export function createApp(opts) {
1212
1562
  .get(target.conversation_id);
1213
1563
  if (!conv)
1214
1564
  return;
1215
- handoffTargets.add(target.conversation_id);
1565
+ const source = getConversation(db, sourceConvId);
1566
+ const inherited = originHop(db, sourceConvId);
1216
1567
  try {
1217
- await spawner.ensure(conv);
1218
- await pool.prompt(conv.id, text);
1568
+ await submitToLane(db, team, {
1569
+ conversationId: conv.id,
1570
+ body: text,
1571
+ fromAgentId: source?.agent_id ?? null,
1572
+ chainId: inherited.chainId,
1573
+ hop: inherited.hop,
1574
+ });
1219
1575
  }
1220
- catch {
1221
- handoffTargets.delete(target.conversation_id);
1576
+ catch (err) {
1577
+ if (err instanceof QueueError && err.code === "hop_limit")
1578
+ return;
1222
1579
  }
1223
1580
  }
1224
1581
  // Fan-out des événements pi vers les abonnés SSE par conversation
@@ -1247,11 +1604,16 @@ export function createApp(opts) {
1247
1604
  sseSubs,
1248
1605
  groupSubs,
1249
1606
  logins: new ProviderLogins(paths),
1607
+ githubLogin: new GitHubLogin(paths, () => pool.refreshExtensions()),
1250
1608
  spawner,
1251
1609
  compose,
1252
1610
  durable,
1611
+ createWorkspaceImpl: opts.createWorkspaceImpl,
1612
+ team,
1253
1613
  };
1614
+ const browser = new SharedBrowser(paths.home, db, opts.auth?.config.origin);
1254
1615
  const routes = [
1616
+ ...browserRoutes(browser, req => privateRequests.has(req), sendJson, !!opts.auth),
1255
1617
  healthRoute(deps),
1256
1618
  ...registryRoutes(deps),
1257
1619
  ...agentRoutes(deps),
@@ -1260,6 +1622,7 @@ export function createApp(opts) {
1260
1622
  ...groupRoutes(deps),
1261
1623
  ...conversationRoutes(deps),
1262
1624
  ...scheduleRoutes(deps),
1625
+ ...teamRoutes(deps),
1263
1626
  // Events global (SSE) — les runs cron et les statuts de conversation
1264
1627
  ["GET", "/api/events", (ctx) => {
1265
1628
  const send = openSse(ctx.res);
@@ -1267,14 +1630,33 @@ export function createApp(opts) {
1267
1630
  ctx.res.once("close", () => events.off("event", send));
1268
1631
  }],
1269
1632
  ];
1633
+ // Dispatch interne des routes /api/* pour le serveur MCP HTTP : mêmes handlers,
1634
+ // mêmes validations et contrôles de disponibilité que l'UI, sans boucle réseau.
1635
+ const availability = () => { if (opts.auth)
1636
+ opts.auth.assertAvailable();
1637
+ else
1638
+ localCheck(paths.home); };
1639
+ // OAuth 2.1 (connecteurs web ChatGPT / Claude.ai) : seulement avec une origine HTTPS et un login propriétaire.
1640
+ const oauth = opts.auth ? new McpOAuth(paths.home, opts.auth) : undefined;
1641
+ const mcp = new McpHttpEndpoint({
1642
+ home: paths.home,
1643
+ version: packageVersion(),
1644
+ oauth,
1645
+ dispatch: (method, path, body) => dispatchInternal(routes, method, path, body, availability),
1646
+ });
1270
1647
  const app = opts.server ?? createServer();
1648
+ attachBrowserView(app, browser, paths.home, opts.auth);
1271
1649
  if (opts.auth) {
1272
1650
  app.requestTimeout = 30_000;
1273
1651
  app.headersTimeout = 10_000;
1274
1652
  app.maxHeadersCount = 100;
1275
1653
  }
1276
1654
  app.once("close", () => {
1655
+ deps.logins.dispose();
1656
+ deps.githubLogin.cancel();
1657
+ stopReap.stop();
1277
1658
  unsubscribePool();
1659
+ void mcp.close();
1278
1660
  void durable.dispose();
1279
1661
  });
1280
1662
  app.on("request", async (req, res) => {
@@ -1287,6 +1669,35 @@ export function createApp(opts) {
1287
1669
  const state = opts.auth;
1288
1670
  if (privateRequest && ("origin" in req.headers || Object.keys(req.headers).some(h => h.startsWith("sec-fetch-"))))
1289
1671
  throw new AuthError("FORBIDDEN", 403);
1672
+ // MCP Streamable HTTP : authentifié par jeton Bearer (jamais par cookie de session),
1673
+ // donc hors de la frontière navigateur ; l'hôte et une Origin éventuelle restent contrôlés.
1674
+ if ((req.url ?? "").split("?")[0] === MCP_HTTP_PATH) {
1675
+ if (privateRequest)
1676
+ throw new AuthError("FORBIDDEN", 403);
1677
+ if (state) {
1678
+ state.assertAvailable();
1679
+ if (req.headers.host !== new URL(state.config.origin).host)
1680
+ throw new AuthError("FORBIDDEN", 403);
1681
+ if (req.headers.origin !== undefined && req.headers.origin !== state.config.origin)
1682
+ throw new AuthError("FORBIDDEN", 403);
1683
+ }
1684
+ else
1685
+ localCheck(paths.home);
1686
+ return await mcp.handle(req, res);
1687
+ }
1688
+ // OAuth : métadonnées, enregistrement, jeton (appelés de serveur à serveur) et page de
1689
+ // consentement (navigation intersite depuis l'application). Contrôles propres au module.
1690
+ if (oauth && McpOAuth.handles((req.url ?? "").split("?")[0] ?? "")) {
1691
+ if (privateRequest || !state)
1692
+ throw new AuthError("FORBIDDEN", 403);
1693
+ state.assertAvailable();
1694
+ if (req.headers.host !== new URL(state.config.origin).host)
1695
+ throw new AuthError("FORBIDDEN", 403);
1696
+ return await oauth.handle(req, res, new URL(req.url ?? "/", state.config.origin));
1697
+ }
1698
+ // Sans OAuth (mode local), la découverte doit échouer proprement, jamais via le fallback SPA.
1699
+ if ((req.url ?? "").startsWith("/.well-known/") || (req.url ?? "").startsWith("/oauth/"))
1700
+ return sendJson(res, 404, { error: "NOT_FOUND" });
1290
1701
  if (state) {
1291
1702
  state.assertAvailable();
1292
1703
  if (!privateRequest)
@@ -1315,8 +1726,8 @@ export function createApp(opts) {
1315
1726
  check = () => state.assertAvailable();
1316
1727
  else {
1317
1728
  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)); };
1729
+ requireApproved(session, state.config);
1730
+ check = () => { state.assertAvailable(); requireApproved(sessionById(state.db, state.config, session.id), state.config); };
1320
1731
  }
1321
1732
  }
1322
1733
  check();
@@ -1346,6 +1757,88 @@ export function createApp(opts) {
1346
1757
  });
1347
1758
  return app;
1348
1759
  }
1760
+ /** Réponse en mémoire pour le dispatch interne (routes JSON uniquement, pas de SSE). */
1761
+ class CaptureResponse extends EventEmitter {
1762
+ statusCode = 200;
1763
+ headersSent = false;
1764
+ destroyed = false;
1765
+ writableEnded = false;
1766
+ chunks = [];
1767
+ headers = new Map();
1768
+ setHeader(name, value) { this.headers.set(name.toLowerCase(), value); return this; }
1769
+ getHeader(name) { return this.headers.get(name.toLowerCase()); }
1770
+ removeHeader(name) { this.headers.delete(name.toLowerCase()); }
1771
+ writeHead(status, headers) {
1772
+ this.statusCode = status;
1773
+ for (const [k, v] of Object.entries(headers ?? {}))
1774
+ this.setHeader(k, v);
1775
+ this.headersSent = true;
1776
+ return this;
1777
+ }
1778
+ write(chunk) {
1779
+ this.headersSent = true;
1780
+ if (chunk !== undefined && chunk !== null)
1781
+ this.chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));
1782
+ return true;
1783
+ }
1784
+ end(chunk) {
1785
+ if (typeof chunk !== "function")
1786
+ this.write(chunk);
1787
+ this.headersSent = true;
1788
+ this.writableEnded = true;
1789
+ this.emit("finish");
1790
+ this.emit("close");
1791
+ return this;
1792
+ }
1793
+ flushHeaders() { this.headersSent = true; }
1794
+ text() { return Buffer.concat(this.chunks).toString("utf8"); }
1795
+ }
1796
+ /** Requête synthétique : jamais privée (pas de capacité propriétaire OS), jamais navigateur. */
1797
+ function syntheticRequest(method, path) {
1798
+ const req = new EventEmitter();
1799
+ Object.assign(req, { method, url: path, headers: { "content-type": "application/json" }, socket: { remoteAddress: "mcp" } });
1800
+ return req;
1801
+ }
1802
+ /** Exécute une route /api/* en mémoire et renvoie son JSON (erreur si statut ≥ 400). */
1803
+ async function dispatchInternal(routes, method, path, body, check) {
1804
+ const url = new URL(path, `http://${HOST}`);
1805
+ if (!url.pathname.startsWith("/api/"))
1806
+ throw new Error(`not found: ${url.pathname}`);
1807
+ const found = matchRoute(routes, method, url.pathname);
1808
+ if (!found)
1809
+ throw new Error(`not found: ${url.pathname}`);
1810
+ const capture = new CaptureResponse();
1811
+ const res = capture;
1812
+ responseChecks.set(res, check);
1813
+ check();
1814
+ // Aller-retour JSON : le handler voit exactement ce qu'un client HTTP aurait envoyé.
1815
+ const parsed = body === undefined ? {} : JSON.parse(JSON.stringify(body));
1816
+ try {
1817
+ await requestAuthorization.run(check, () => found.handler({
1818
+ params: found.params, query: url.searchParams, body: parsed, req: syntheticRequest(method, path), res, check,
1819
+ }));
1820
+ }
1821
+ catch (err) {
1822
+ if (err instanceof AuthError)
1823
+ throw new Error(err.code);
1824
+ throw err;
1825
+ }
1826
+ if (!capture.writableEnded)
1827
+ throw new Error(`route sans réponse JSON : ${method} ${url.pathname}`);
1828
+ const text = capture.text();
1829
+ let data;
1830
+ try {
1831
+ data = text ? JSON.parse(text) : {};
1832
+ }
1833
+ catch {
1834
+ throw new Error(`réponse non JSON : ${method} ${url.pathname}`);
1835
+ }
1836
+ if (capture.statusCode >= 400) {
1837
+ const error = data && typeof data === "object" && "error" in data ? data.error : undefined;
1838
+ throw new Error(typeof error === "string" ? error : `HTTP ${capture.statusCode}`);
1839
+ }
1840
+ return data;
1841
+ }
1349
1842
  // Server-owned identity only: no HTTP header can confer the local OS-owner capability.
1350
1843
  const privateRequests = new WeakSet();
1351
1844
  export function createPrivateServer(app) {