@ignitionai/cogitator 0.4.1 → 0.5.1
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/README.md +45 -8
- package/dist/extensions/index.js +1 -1
- package/dist/src/classic-configuration.js +153 -0
- package/dist/src/cli.js +2 -3
- package/dist/src/conversations.js +9 -7
- package/dist/src/db.js +52 -3
- package/dist/src/default-agent.js +1 -1
- package/dist/src/durable/admission.js +131 -0
- package/dist/src/durable/approvals.js +171 -0
- package/dist/src/durable/compatibility.js +59 -0
- package/dist/src/durable/effect-gateway.js +68 -0
- package/dist/src/durable/lease.js +48 -0
- package/dist/src/durable/manager.js +167 -0
- package/dist/src/durable/mission-runtime.js +460 -0
- package/dist/src/durable/profile.js +79 -0
- package/dist/src/durable/workers.js +42 -0
- package/dist/src/execution/admission.js +45 -0
- package/dist/src/execution/confinement.js +108 -0
- package/dist/src/execution/container.js +102 -0
- package/dist/src/execution/egress.js +69 -0
- package/dist/src/groups.js +71 -0
- package/dist/src/host-pi.js +61 -0
- package/dist/src/pool.js +193 -72
- package/dist/src/provider-login.js +115 -0
- package/dist/src/registry.js +72 -14
- package/dist/src/runtime.js +92 -0
- package/dist/src/schemas.js +45 -0
- package/dist/src/server.js +423 -23
- package/dist/src/spawner.js +34 -12
- package/dist/src/workspace-files.js +6 -5
- package/dist/src/workspaces.js +19 -6
- package/package.json +8 -1
- package/web/dist/assets/BrandLogo3D-BvZPXohP.js +4035 -0
- package/web/dist/assets/index-7Dyl-4v7.css +1 -0
- package/web/dist/assets/index-CdqzcBU-.js +83 -0
- package/web/dist/index.html +2 -2
- package/web/dist/assets/index-D3Q54zLM.js +0 -83
- package/web/dist/assets/index-Kj5NVQYi.css +0 -1
package/dist/src/server.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
+
import { changeConfiguration, dismissConfiguration, ConfigurationError, recoverConfigurations } from "./classic-configuration.js";
|
|
1
2
|
import { execFile } from "node:child_process";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
2
4
|
import { EventEmitter } from "node:events";
|
|
3
5
|
import { existsSync, statSync, readFileSync, realpathSync } from "node:fs";
|
|
4
6
|
import { dirname, extname, join, normalize, relative, sep } from "node:path";
|
|
@@ -10,18 +12,24 @@ import { protectedRequired } from "./auth-state.js";
|
|
|
10
12
|
import { AuthError, ownerSession, requireApproved, sessionById } from "./native-auth.js";
|
|
11
13
|
import { authFailure, authJson, authRoute, browserHeaders, checkResponse, localCheck, responseChecks, validateBoundary } from "./auth-http.js";
|
|
12
14
|
import { packageVersion, piVersion } from "./pi.js";
|
|
13
|
-
import { API_PROTOCOLS, deleteProvider, listProviders, listSkills, mcpAdapterDetected, readMcp, upsertProvider, validateMcpConfig, writeMcp, } from "./registry.js";
|
|
15
|
+
import { API_PROTOCOLS, authMethodsFor, deleteProvider, listProviders, listSkills, mcpAdapterDetected, readMcp, upsertProvider, validateMcpConfig, writeMcp, } from "./registry.js";
|
|
16
|
+
import { ProviderLogins } from "./provider-login.js";
|
|
14
17
|
import { applyAgent, createAgent, deleteAgent, getAgent, listAgents, unapplyAgent, updateAgent, validateAgent, getDefaultAgentId, setDefaultAgent, } from "./agents.js";
|
|
15
18
|
import { createTask, deleteTask, getTask, listRuns, listTasks, updateTask, } from "./cron.js";
|
|
16
|
-
import { createConversation, deleteConversation, getConversation, listConversations,
|
|
19
|
+
import { createConversation, deleteConversation, getConversation, listConversations, setConversationTitle, } from "./conversations.js";
|
|
20
|
+
import { appendGroupMessage, conversationGroupOwner, deleteGroup, getGroupWithMembers, insertGroup, listGroupMessages, listGroups, matchGroupMention, routeGroupMessage, } from "./groups.js";
|
|
17
21
|
import { makeSpawner } from "./spawner.js";
|
|
22
|
+
import { composeRuntime, runtimeKindOf } from "./runtime.js";
|
|
23
|
+
import { DurableRuntimeManager } from "./durable/manager.js";
|
|
24
|
+
import { assertDurableAdmission, durableToolchainRegistry } from "./durable/compatibility.js";
|
|
18
25
|
import { readHistory, readEntries } from "./history.js";
|
|
19
26
|
import { readFileChanges, readFileEvents, readFileDetail } from "./file-changes.js";
|
|
20
27
|
import { workspaceTree, readWorkspaceFile } from "./workspace-files.js";
|
|
21
28
|
import { listCards, createCardGh, updateCardGh, moveCardGh, addCommentGh, closeCardGh, } from "./board.js";
|
|
22
29
|
import { importSkills } from "./skills-import.js";
|
|
23
|
-
import { agentInputSchema, conversationCreateSchema, messageSchema, modelSwitchSchema, providerUpsertSchema, scheduleCreateSchema, scheduleUpdateSchema, skillImportSchema, workspaceCreateSchema, workspaceUpdateSchema, boardCardSchema, boardCommentSchema, } from "./schemas.js";
|
|
30
|
+
import { agentInputSchema, conversationCreateSchema, groupCreateSchema, messageSchema, modelSwitchSchema, providerLoginReplySchema, providerLoginSchema, providerUpsertSchema, scheduleCreateSchema, scheduleUpdateSchema, skillImportSchema, workspaceCreateSchema, workspaceUpdateSchema, boardCardSchema, boardCommentSchema, approvalDecisionSchema, budgetUpdateSchema, } from "./schemas.js";
|
|
24
31
|
import { spawnConfigFromPreset } from "./spawn.js";
|
|
32
|
+
import { enrollmentPolicyFromEnv } from "./execution/confinement.js";
|
|
25
33
|
import { browseDir, createWorkspace, deleteWorkspace, getWorkspace, listWorkspaces, updateWorkspace, } from "./workspaces.js";
|
|
26
34
|
// ---------- Statique ----------
|
|
27
35
|
/** Localise web/dist en remontant depuis le module (marche en dev src/ comme en prod dist/src/ ou en paquet npm). */
|
|
@@ -245,6 +253,38 @@ function registryRoutes(deps) {
|
|
|
245
253
|
deleteProvider(paths, ctx.params.id);
|
|
246
254
|
sendJson(ctx.res, 200, { ok: true });
|
|
247
255
|
}],
|
|
256
|
+
["POST", "/api/providers/:id/login", (ctx) => {
|
|
257
|
+
const body = parseBody(ctx.res, providerLoginSchema, ctx.body);
|
|
258
|
+
if (!body)
|
|
259
|
+
return;
|
|
260
|
+
const id = ctx.params.id;
|
|
261
|
+
if (authMethodsFor(id).length === 0)
|
|
262
|
+
return sendJson(ctx.res, 404, { error: `Unknown provider: ${id}` });
|
|
263
|
+
sendJson(ctx.res, 202, deps.logins.start(id, body.type));
|
|
264
|
+
}],
|
|
265
|
+
["GET", "/api/provider-logins/:id/events", (ctx) => {
|
|
266
|
+
const id = ctx.params.id;
|
|
267
|
+
if (!deps.logins.has(id))
|
|
268
|
+
return sendJson(ctx.res, 404, { error: "login session not found" });
|
|
269
|
+
const send = openSse(ctx.res);
|
|
270
|
+
const replay = deps.logins.subscribe(id, send) ?? [];
|
|
271
|
+
for (const event of replay)
|
|
272
|
+
send(event);
|
|
273
|
+
ctx.res.once("close", () => deps.logins.unsubscribe(id, send));
|
|
274
|
+
}],
|
|
275
|
+
["POST", "/api/provider-logins/:id/reply", (ctx) => {
|
|
276
|
+
const body = parseBody(ctx.res, providerLoginReplySchema, ctx.body);
|
|
277
|
+
if (!body)
|
|
278
|
+
return;
|
|
279
|
+
if (!deps.logins.reply(ctx.params.id, body.value))
|
|
280
|
+
return sendJson(ctx.res, 409, { error: "no pending prompt" });
|
|
281
|
+
sendJson(ctx.res, 200, { ok: true });
|
|
282
|
+
}],
|
|
283
|
+
["DELETE", "/api/provider-logins/:id", (ctx) => {
|
|
284
|
+
if (!deps.logins.cancel(ctx.params.id))
|
|
285
|
+
return sendJson(ctx.res, 404, { error: "login session not found" });
|
|
286
|
+
sendJson(ctx.res, 200, { ok: true });
|
|
287
|
+
}],
|
|
248
288
|
["GET", "/api/skills", (ctx) => {
|
|
249
289
|
sendJson(ctx.res, 200, { skills: listSkills(paths) });
|
|
250
290
|
}],
|
|
@@ -252,6 +292,11 @@ function registryRoutes(deps) {
|
|
|
252
292
|
const b = parseBody(ctx.res, skillImportSchema, ctx.body);
|
|
253
293
|
if (!b)
|
|
254
294
|
return;
|
|
295
|
+
// Mode distant : les imports par commande hôte (npx/npm) sont désactivés
|
|
296
|
+
// (Plan 0002 §4 : pas d'import npm/npx côté hôte en mode distant).
|
|
297
|
+
if (enrollmentPolicyFromEnv().remote && /^npx\s|^npm\s/.test(b.source.trim())) {
|
|
298
|
+
return sendJson(ctx.res, 400, { error: "import par commande (npx/npm) désactivé en mode distant" });
|
|
299
|
+
}
|
|
255
300
|
const destRoot = paths.skillsDirs[0] ?? join(paths.piAgentDir, "skills");
|
|
256
301
|
const result = await importSkills(b.source, destRoot, b.overwrite === true);
|
|
257
302
|
if (result.error && result.imported.length === 0)
|
|
@@ -272,7 +317,8 @@ function registryRoutes(deps) {
|
|
|
272
317
|
}
|
|
273
318
|
/** Presets d'agents + apply/unapply des définitions herdr. */
|
|
274
319
|
function agentRoutes(deps) {
|
|
275
|
-
const { db, paths } = deps;
|
|
320
|
+
const { db, paths, events } = deps;
|
|
321
|
+
const changed = () => events.emit("event", { type: "agents_changed" });
|
|
276
322
|
return [
|
|
277
323
|
["GET", "/api/agents", (ctx) => {
|
|
278
324
|
sendJson(ctx.res, 200, { agents: listAgents(db) });
|
|
@@ -285,6 +331,7 @@ function agentRoutes(deps) {
|
|
|
285
331
|
return sendJson(ctx.res, 404, { error: "workspace introuvable" });
|
|
286
332
|
}
|
|
287
333
|
const preset = createAgent(db, input);
|
|
334
|
+
changed();
|
|
288
335
|
sendJson(ctx.res, 201, { agent: preset, apply: applyAgent(paths, preset) });
|
|
289
336
|
}],
|
|
290
337
|
["GET", "/api/agents/:id", (ctx) => {
|
|
@@ -303,6 +350,7 @@ function agentRoutes(deps) {
|
|
|
303
350
|
const preset = updateAgent(db, ctx.params.id, input);
|
|
304
351
|
if (!preset)
|
|
305
352
|
return notFound(ctx.res, "agent");
|
|
353
|
+
changed();
|
|
306
354
|
sendJson(ctx.res, 200, { agent: preset, apply: applyAgent(paths, preset) });
|
|
307
355
|
}],
|
|
308
356
|
["DELETE", "/api/agents/:id", (ctx) => {
|
|
@@ -310,6 +358,7 @@ function agentRoutes(deps) {
|
|
|
310
358
|
if (!existing)
|
|
311
359
|
return;
|
|
312
360
|
deleteAgent(db, existing.id);
|
|
361
|
+
changed();
|
|
313
362
|
sendJson(ctx.res, 200, { ok: true, unapplied: unapplyAgent(paths, existing.slug) });
|
|
314
363
|
}],
|
|
315
364
|
["POST", "/api/agents/:id/validate", async (ctx) => {
|
|
@@ -321,6 +370,7 @@ function agentRoutes(deps) {
|
|
|
321
370
|
["POST", "/api/agents/:id/default", (ctx) => {
|
|
322
371
|
if (!setDefaultAgent(db, ctx.params.id))
|
|
323
372
|
return notFound(ctx.res, "agent");
|
|
373
|
+
changed();
|
|
324
374
|
sendJson(ctx.res, 200, { ok: true });
|
|
325
375
|
}],
|
|
326
376
|
];
|
|
@@ -336,7 +386,7 @@ function workspaceRoutes(deps) {
|
|
|
336
386
|
const b = parseBody(ctx.res, workspaceCreateSchema, ctx.body);
|
|
337
387
|
if (!b)
|
|
338
388
|
return;
|
|
339
|
-
const { workspace, error } = createWorkspace(db, b);
|
|
389
|
+
const { workspace, error } = createWorkspace(db, b, enrollmentPolicyFromEnv());
|
|
340
390
|
if (error)
|
|
341
391
|
return sendJson(ctx.res, 400, { error });
|
|
342
392
|
sendJson(ctx.res, 201, { workspace });
|
|
@@ -633,15 +683,28 @@ function conversationRoutes(deps) {
|
|
|
633
683
|
const resolved = resolveSpawnTarget(deps, b);
|
|
634
684
|
if ("error" in resolved)
|
|
635
685
|
return sendJson(ctx.res, resolved.status, { error: resolved.error });
|
|
636
|
-
|
|
686
|
+
const runtimeKind = b.runtime ?? "classic";
|
|
687
|
+
if (runtimeKind === "durable") {
|
|
688
|
+
// Admission fail closed : capacités non classées → refus, aucun travail caché.
|
|
689
|
+
try {
|
|
690
|
+
assertDurableAdmission(durableToolchainRegistry(), resolved.spawn);
|
|
691
|
+
}
|
|
692
|
+
catch (err) {
|
|
693
|
+
return sendJson(ctx.res, 403, { error: err instanceof Error ? err.message : String(err) });
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
let conv = createConversation(db, { workspaceId: resolved.workspaceId, agentId: resolved.agentId, spawn: resolved.spawn, runtimeKind });
|
|
637
697
|
const prompt = b.prompt?.trim();
|
|
638
698
|
if (prompt) {
|
|
639
|
-
|
|
699
|
+
const runtime = deps.compose(conv);
|
|
700
|
+
await runtime.ensure(conv);
|
|
640
701
|
ctx.check();
|
|
641
|
-
await
|
|
702
|
+
const ack = await runtime.prompt(conv, prompt, runtimeKind === "durable" ? randomUUID() : undefined);
|
|
642
703
|
ctx.check();
|
|
643
704
|
setConversationTitle(db, conv.id, prompt);
|
|
644
705
|
conv = getConversation(db, conv.id);
|
|
706
|
+
if (ack.accepted)
|
|
707
|
+
return sendJson(ctx.res, 201, { conversation: conv, accepted: ack.accepted });
|
|
645
708
|
}
|
|
646
709
|
sendJson(ctx.res, 201, { conversation: conv });
|
|
647
710
|
}],
|
|
@@ -649,21 +712,41 @@ function conversationRoutes(deps) {
|
|
|
649
712
|
const conv = requireConversation(deps, ctx);
|
|
650
713
|
if (!conv)
|
|
651
714
|
return;
|
|
652
|
-
|
|
715
|
+
const runtime = deps.compose(conv);
|
|
716
|
+
sendJson(ctx.res, 200, {
|
|
717
|
+
conversation: conv,
|
|
718
|
+
runtime: runtime.kind,
|
|
719
|
+
live: runtime.isLive(conv),
|
|
720
|
+
streaming: runtime.kind === "classic" ? await pool.isStreaming(conv.id) : runtime.isLive(conv),
|
|
721
|
+
});
|
|
653
722
|
}],
|
|
654
723
|
["GET", "/api/conversations/:id/events", async (ctx) => {
|
|
655
724
|
const conv = requireConversation(deps, ctx);
|
|
656
725
|
if (!conv)
|
|
657
726
|
return;
|
|
658
|
-
const
|
|
659
|
-
const
|
|
727
|
+
const runtime = deps.compose(conv);
|
|
728
|
+
const spawned = await runtime.ensure(conv);
|
|
729
|
+
// Mode durable : aucun spawn (la runtime vit dans le contrôleur) ; la lecture
|
|
730
|
+
// d'événements ne crée jamais de mission (Plan 0002 §7).
|
|
731
|
+
const send = openSse(ctx.res, runtime.kind === "durable"
|
|
732
|
+
? { type: "session", runtimeKind: "durable" }
|
|
733
|
+
: { type: "session", sessionFile: spawned.sessionFile ?? conv.session_file });
|
|
660
734
|
const subs = deps.sseSubs.get(conv.id) ?? new Set();
|
|
661
735
|
deps.sseSubs.set(conv.id, subs);
|
|
662
736
|
subs.add(send);
|
|
737
|
+
let detach;
|
|
738
|
+
let detachMission;
|
|
739
|
+
if (runtime.kind === "durable") {
|
|
740
|
+
void runtime.attachEvents(conv, send).then((off) => { detach = off; });
|
|
741
|
+
// États de mission (queued / budget_paused / waiting_approval / …) en direct.
|
|
742
|
+
detachMission = deps.durable.onMissionState(conv.id, (state) => send({ type: "mission_state", mission: state }));
|
|
743
|
+
}
|
|
663
744
|
ctx.res.once("close", () => {
|
|
664
745
|
subs.delete(send);
|
|
665
746
|
if (!subs.size)
|
|
666
747
|
deps.sseSubs.delete(conv.id);
|
|
748
|
+
detach?.();
|
|
749
|
+
detachMission?.();
|
|
667
750
|
});
|
|
668
751
|
}],
|
|
669
752
|
["GET", "/api/conversations/:id/history", (ctx) => {
|
|
@@ -696,42 +779,131 @@ function conversationRoutes(deps) {
|
|
|
696
779
|
if (!b)
|
|
697
780
|
return;
|
|
698
781
|
const text = (b.text ?? "").trim();
|
|
699
|
-
|
|
782
|
+
const runtime = deps.compose(conv);
|
|
783
|
+
if (runtime.kind === "durable" && !b.requestId) {
|
|
784
|
+
return sendJson(ctx.res, 400, { error: "requestId requis pour une conversation durable" });
|
|
785
|
+
}
|
|
786
|
+
await runtime.ensure(conv);
|
|
700
787
|
ctx.check();
|
|
701
|
-
await
|
|
788
|
+
const ack = await runtime.prompt(conv, text, b.requestId, b.images);
|
|
702
789
|
ctx.check();
|
|
703
790
|
if (text)
|
|
704
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 });
|
|
794
|
+
}],
|
|
795
|
+
// ---------- Missions durables : statut, approbations, budget (#16) ----------
|
|
796
|
+
["GET", "/api/conversations/:id/mission", async (ctx) => {
|
|
797
|
+
const conv = requireConversation(deps, ctx);
|
|
798
|
+
if (!conv)
|
|
799
|
+
return;
|
|
800
|
+
if (runtimeKindOf(conv) !== "durable")
|
|
801
|
+
return sendJson(ctx.res, 409, { error: "pas une mission durable" });
|
|
802
|
+
sendJson(ctx.res, 200, { mission: await deps.durable.missionStatus(conv) });
|
|
803
|
+
}],
|
|
804
|
+
["GET", "/api/conversations/:id/approvals", async (ctx) => {
|
|
805
|
+
const conv = requireConversation(deps, ctx);
|
|
806
|
+
if (!conv)
|
|
807
|
+
return;
|
|
808
|
+
if (runtimeKindOf(conv) !== "durable")
|
|
809
|
+
return sendJson(ctx.res, 409, { error: "pas une mission durable" });
|
|
810
|
+
const runtime = await deps.durable.get(conv);
|
|
811
|
+
sendJson(ctx.res, 200, await runtime.approvalsView());
|
|
812
|
+
}],
|
|
813
|
+
// Décision owner sur une action immuable créée côté serveur ; rien d'autre
|
|
814
|
+
// n'est acceptable ici (le client ne fabrique jamais l'action à approuver).
|
|
815
|
+
["POST", "/api/conversations/:id/approvals", async (ctx) => {
|
|
816
|
+
const conv = requireConversation(deps, ctx);
|
|
817
|
+
if (!conv)
|
|
818
|
+
return;
|
|
819
|
+
if (runtimeKindOf(conv) !== "durable")
|
|
820
|
+
return sendJson(ctx.res, 409, { error: "pas une mission durable" });
|
|
821
|
+
const b = parseBody(ctx.res, approvalDecisionSchema, ctx.body);
|
|
822
|
+
if (!b)
|
|
823
|
+
return;
|
|
824
|
+
const runtime = await deps.durable.get(conv);
|
|
825
|
+
const result = await runtime.decideApproval(b.pendingActionId, b.decision, b.denialReason);
|
|
826
|
+
if (result.kind === "error")
|
|
827
|
+
return sendJson(ctx.res, 409, { error: result.reason });
|
|
828
|
+
sendJson(ctx.res, 200, result.grant ? { ok: true, pendingAction: result.pendingAction, grant: result.grant } : { ok: true, pendingAction: result.pendingAction });
|
|
829
|
+
}],
|
|
830
|
+
["POST", "/api/conversations/:id/approvals/:grantId/revoke", async (ctx) => {
|
|
831
|
+
const conv = requireConversation(deps, ctx);
|
|
832
|
+
if (!conv)
|
|
833
|
+
return;
|
|
834
|
+
if (runtimeKindOf(conv) !== "durable")
|
|
835
|
+
return sendJson(ctx.res, 409, { error: "pas une mission durable" });
|
|
836
|
+
const runtime = await deps.durable.get(conv);
|
|
837
|
+
const result = await runtime.revokeGrant(ctx.params.grantId);
|
|
838
|
+
if (!result.ok)
|
|
839
|
+
return sendJson(ctx.res, 404, { error: result.reason });
|
|
705
840
|
sendJson(ctx.res, 200, { ok: true });
|
|
706
841
|
}],
|
|
842
|
+
// Changement EXPLICITE de limite (le seul déliement possible d'une limite de mission).
|
|
843
|
+
["POST", "/api/conversations/:id/budget", async (ctx) => {
|
|
844
|
+
const conv = requireConversation(deps, ctx);
|
|
845
|
+
if (!conv)
|
|
846
|
+
return;
|
|
847
|
+
if (runtimeKindOf(conv) !== "durable")
|
|
848
|
+
return sendJson(ctx.res, 409, { error: "pas une mission durable" });
|
|
849
|
+
const b = parseBody(ctx.res, budgetUpdateSchema, ctx.body);
|
|
850
|
+
if (!b)
|
|
851
|
+
return;
|
|
852
|
+
const runtime = await deps.durable.get(conv);
|
|
853
|
+
await runtime.setBudgetPolicy(b);
|
|
854
|
+
sendJson(ctx.res, 200, { ok: true, mission: await runtime.missionStatus() });
|
|
855
|
+
}],
|
|
707
856
|
["POST", "/api/conversations/:id/stop", async (ctx) => {
|
|
708
857
|
const conv = requireConversation(deps, ctx);
|
|
709
858
|
if (!conv)
|
|
710
859
|
return;
|
|
711
|
-
await
|
|
860
|
+
await deps.compose(conv).abort(conv);
|
|
712
861
|
sendJson(ctx.res, 200, { ok: true });
|
|
713
862
|
}],
|
|
714
863
|
["POST", "/api/conversations/:id/model", async (ctx) => {
|
|
715
864
|
const conv = requireConversation(deps, ctx);
|
|
716
865
|
if (!conv)
|
|
717
866
|
return;
|
|
867
|
+
if (runtimeKindOf(conv) === "durable") {
|
|
868
|
+
// Modèle figé par mission (O6) : pas de bascule à chaud sur une runtime durable.
|
|
869
|
+
return sendJson(ctx.res, 409, { error: "modèle figé pour une mission durable (créer une nouvelle conversation)" });
|
|
870
|
+
}
|
|
718
871
|
const b = parseBody(ctx.res, modelSwitchSchema, ctx.body);
|
|
719
872
|
if (!b)
|
|
720
873
|
return;
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
874
|
+
try {
|
|
875
|
+
const result = await changeConfiguration({ db, pool, paths: deps.paths, ensure: c => deps.spawner.ensure(c), onPresetChanged: () => deps.events.emit("event", { type: "agents_changed" }) }, conv.id, b);
|
|
876
|
+
sendJson(ctx.res, result.status, result.conversation);
|
|
877
|
+
}
|
|
878
|
+
catch (error) {
|
|
879
|
+
if (error instanceof AuthError)
|
|
880
|
+
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) });
|
|
882
|
+
}
|
|
883
|
+
}],
|
|
884
|
+
["DELETE", "/api/conversations/:id/model", async (ctx) => {
|
|
885
|
+
const conv = requireConversation(deps, ctx);
|
|
886
|
+
if (!conv)
|
|
887
|
+
return;
|
|
888
|
+
try {
|
|
889
|
+
sendJson(ctx.res, 200, dismissConfiguration(db, pool, conv.id));
|
|
890
|
+
}
|
|
891
|
+
catch (error) {
|
|
892
|
+
if (!(error instanceof ConfigurationError))
|
|
893
|
+
throw error;
|
|
894
|
+
sendJson(ctx.res, error.status, { error: error.message });
|
|
895
|
+
}
|
|
726
896
|
}],
|
|
727
897
|
["DELETE", "/api/conversations/:id", async (ctx) => {
|
|
728
898
|
const conv = requireConversation(deps, ctx);
|
|
729
899
|
if (!conv)
|
|
730
900
|
return;
|
|
731
|
-
await
|
|
901
|
+
await deps.compose(conv).evict(conv);
|
|
732
902
|
ctx.check();
|
|
733
903
|
deleteConversation(db, conv.id);
|
|
734
|
-
|
|
904
|
+
// L'historique survit sur disque : pi .jsonl en classic (I5), stockage
|
|
905
|
+
// Durable propre en durable (ADR-006 amendé).
|
|
906
|
+
sendJson(ctx.res, 200, { ok: true });
|
|
735
907
|
}],
|
|
736
908
|
];
|
|
737
909
|
}
|
|
@@ -774,6 +946,185 @@ function resolveSpawnTarget(deps, b) {
|
|
|
774
946
|
return { error: "workspace introuvable", status: 404 };
|
|
775
947
|
return { agentId: preset.id, spawn: spawnConfigFromPreset(preset), workspaceId };
|
|
776
948
|
}
|
|
949
|
+
/** Groupes de bots (ADR-011) : création/liste + fil partagé (bus, routage hôte/@, SSE unique). */
|
|
950
|
+
function groupRoutes(deps) {
|
|
951
|
+
const { db, pool } = deps;
|
|
952
|
+
return [
|
|
953
|
+
["GET", "/api/groups", (ctx) => {
|
|
954
|
+
sendJson(ctx.res, 200, { groups: listGroups(db) });
|
|
955
|
+
}],
|
|
956
|
+
["POST", "/api/groups", async (ctx) => {
|
|
957
|
+
const b = parseBody(ctx.res, groupCreateSchema, ctx.body);
|
|
958
|
+
if (!b)
|
|
959
|
+
return;
|
|
960
|
+
const prepared = prepareGroupCreate(deps, b);
|
|
961
|
+
if ("error" in prepared)
|
|
962
|
+
return sendJson(ctx.res, prepared.status, { error: prepared.error });
|
|
963
|
+
// écritures DB atomiques, puis spawn idle des sessions membres (I3 : tout passe par le pool)
|
|
964
|
+
const members = db.transaction(() => {
|
|
965
|
+
const group = insertGroup(db, prepared);
|
|
966
|
+
return prepared.members.map((preset) => ({
|
|
967
|
+
preset,
|
|
968
|
+
conv: createConversation(db, {
|
|
969
|
+
workspaceId: prepared.defaultWorkspaceId ?? prepared.hostPreset.default_workspace_id ?? null,
|
|
970
|
+
agentId: preset.id,
|
|
971
|
+
groupId: group.id,
|
|
972
|
+
spawn: spawnConfigFromPreset(preset),
|
|
973
|
+
}),
|
|
974
|
+
}));
|
|
975
|
+
})();
|
|
976
|
+
try {
|
|
977
|
+
await Promise.all(members.map(({ conv }) => deps.spawner.ensure(conv)));
|
|
978
|
+
}
|
|
979
|
+
catch (err) {
|
|
980
|
+
return sendJson(ctx.res, 502, { error: `spawn membre impossible : ${err instanceof Error ? err.message : String(err)}` });
|
|
981
|
+
}
|
|
982
|
+
ctx.check();
|
|
983
|
+
sendJson(ctx.res, 201, { group: getGroupWithMembers(db, members[0].conv.group_id) });
|
|
984
|
+
}],
|
|
985
|
+
["GET", "/api/groups/:id", (ctx) => {
|
|
986
|
+
const group = getGroupWithMembers(db, ctx.params.id);
|
|
987
|
+
if (!group)
|
|
988
|
+
return notFound(ctx.res, "groupe");
|
|
989
|
+
sendJson(ctx.res, 200, { group });
|
|
990
|
+
}],
|
|
991
|
+
// Bus du fil : rejeu pour le montage de l'UI (le streaming passe par le SSE unique ci-dessous)
|
|
992
|
+
["GET", "/api/groups/:id/messages", (ctx) => {
|
|
993
|
+
if (!getGroupWithMembers(db, ctx.params.id))
|
|
994
|
+
return notFound(ctx.res, "groupe");
|
|
995
|
+
sendJson(ctx.res, 200, { messages: listGroupMessages(db, ctx.params.id) });
|
|
996
|
+
}],
|
|
997
|
+
// Une ligne utilisateur → bus + injection dans la session du seul membre visé (hôte sans @, ADR-011)
|
|
998
|
+
["POST", "/api/groups/:id/messages", async (ctx) => {
|
|
999
|
+
const group = getGroupWithMembers(db, ctx.params.id);
|
|
1000
|
+
if (!group)
|
|
1001
|
+
return notFound(ctx.res, "groupe");
|
|
1002
|
+
const b = parseBody(ctx.res, messageSchema, ctx.body);
|
|
1003
|
+
if (!b)
|
|
1004
|
+
return;
|
|
1005
|
+
const text = (b.text ?? "").trim();
|
|
1006
|
+
const target = routeGroupMessage(group, text);
|
|
1007
|
+
appendGroupMessage(db, { groupId: group.id, role: "user", text });
|
|
1008
|
+
const conv = db
|
|
1009
|
+
.prepare("SELECT * FROM conversation WHERE group_id = ? AND agent_id = ?")
|
|
1010
|
+
.get(group.id, target.agent_id);
|
|
1011
|
+
if (!conv)
|
|
1012
|
+
return sendJson(ctx.res, 500, { error: "session membre introuvable" });
|
|
1013
|
+
await deps.spawner.ensure(conv);
|
|
1014
|
+
ctx.check();
|
|
1015
|
+
await pool.prompt(conv.id, text, b.images);
|
|
1016
|
+
ctx.check();
|
|
1017
|
+
sendJson(ctx.res, 200, { ok: true });
|
|
1018
|
+
}],
|
|
1019
|
+
// Fil du groupe suivi sur UN flux SSE (pas N flux des sessions membres) — événements pi enveloppés group_activity
|
|
1020
|
+
["GET", "/api/groups/:id/events", (ctx) => {
|
|
1021
|
+
if (!getGroupWithMembers(db, ctx.params.id))
|
|
1022
|
+
return notFound(ctx.res, "groupe");
|
|
1023
|
+
// événement initial : flush des en-têtes immédiat (sinon le client attend le premier heartbeat)
|
|
1024
|
+
const send = openSse(ctx.res, { type: "group_ready", groupId: ctx.params.id });
|
|
1025
|
+
const subs = deps.groupSubs.get(ctx.params.id) ?? new Set();
|
|
1026
|
+
deps.groupSubs.set(ctx.params.id, subs);
|
|
1027
|
+
subs.add(send);
|
|
1028
|
+
ctx.res.once("close", () => {
|
|
1029
|
+
subs.delete(send);
|
|
1030
|
+
if (!subs.size)
|
|
1031
|
+
deps.groupSubs.delete(ctx.params.id);
|
|
1032
|
+
});
|
|
1033
|
+
}],
|
|
1034
|
+
["DELETE", "/api/groups/:id", async (ctx) => {
|
|
1035
|
+
const group = getGroupWithMembers(db, ctx.params.id);
|
|
1036
|
+
if (!group)
|
|
1037
|
+
return notFound(ctx.res, "groupe");
|
|
1038
|
+
// Hold member dispatch locks until the cascade: no restart between eviction and deletion.
|
|
1039
|
+
const remove = async (index) => {
|
|
1040
|
+
const member = group.members[index];
|
|
1041
|
+
if (!member) {
|
|
1042
|
+
ctx.check();
|
|
1043
|
+
deleteGroup(db, group.id);
|
|
1044
|
+
return;
|
|
1045
|
+
}
|
|
1046
|
+
await pool.serial(member.conversation_id, async () => {
|
|
1047
|
+
ctx.check();
|
|
1048
|
+
await pool.evict(member.conversation_id);
|
|
1049
|
+
await remove(index + 1);
|
|
1050
|
+
});
|
|
1051
|
+
};
|
|
1052
|
+
await remove(0);
|
|
1053
|
+
sendJson(ctx.res, 200, { ok: true });
|
|
1054
|
+
}],
|
|
1055
|
+
];
|
|
1056
|
+
}
|
|
1057
|
+
/** Valide membres/hôte/workspace ; renvoie l'entrée préparée ou l'erreur HTTP. */
|
|
1058
|
+
function prepareGroupCreate(deps, b) {
|
|
1059
|
+
const { db } = deps;
|
|
1060
|
+
const unique = [...new Set(b.member_agent_ids)];
|
|
1061
|
+
if (unique.length < 2 || unique.length > 6) {
|
|
1062
|
+
return { error: "un groupe contient 2 à 6 bots distincts", status: 400 };
|
|
1063
|
+
}
|
|
1064
|
+
const members = unique.map((id) => getAgent(db, id));
|
|
1065
|
+
if (members.some((m) => !m))
|
|
1066
|
+
return { error: "agent membre introuvable", status: 404 };
|
|
1067
|
+
const hostId = b.host_agent_id ?? unique[0];
|
|
1068
|
+
if (!unique.includes(hostId))
|
|
1069
|
+
return { error: "l'hôte doit être un membre du groupe", status: 400 };
|
|
1070
|
+
const hostPreset = members.find((m) => m.id === hostId);
|
|
1071
|
+
if (b.default_workspace_id && !getWorkspace(db, b.default_workspace_id)) {
|
|
1072
|
+
return { error: "workspace introuvable", status: 404 };
|
|
1073
|
+
}
|
|
1074
|
+
return {
|
|
1075
|
+
name: b.name,
|
|
1076
|
+
memberAgentIds: unique,
|
|
1077
|
+
hostAgentId: hostId,
|
|
1078
|
+
defaultWorkspaceId: b.default_workspace_id ?? null,
|
|
1079
|
+
members: members,
|
|
1080
|
+
hostPreset,
|
|
1081
|
+
};
|
|
1082
|
+
}
|
|
1083
|
+
/** Persiste sur le bus l'activité d'un membre : outils exécutés + réponse finale en fin de tour (ADR-011).
|
|
1084
|
+
* onReply est appelé avec le texte de la réponse dès qu'elle est persistée (handoff #12). */
|
|
1085
|
+
function persistGroupActivity(db, convId, owner, event, onReply) {
|
|
1086
|
+
const ev = event;
|
|
1087
|
+
if (ev.type === "tool_execution_end" && ev.toolCallId) {
|
|
1088
|
+
const result = ev.result?.content
|
|
1089
|
+
?.filter((b) => b.type === "text" && typeof b.text === "string")
|
|
1090
|
+
.map((b) => b.text)
|
|
1091
|
+
.join("\n");
|
|
1092
|
+
appendGroupMessage(db, {
|
|
1093
|
+
groupId: owner.group_id, conversationId: convId, agentId: owner.agent_id,
|
|
1094
|
+
role: "tool", text: ev.toolName ?? "outil",
|
|
1095
|
+
detail: JSON.stringify({ result }), isError: ev.isError === true,
|
|
1096
|
+
});
|
|
1097
|
+
return;
|
|
1098
|
+
}
|
|
1099
|
+
if (ev.type !== "agent_end")
|
|
1100
|
+
return;
|
|
1101
|
+
const append = () => {
|
|
1102
|
+
const lastAssistant = [...readEntries(owner.session_file ?? "")]
|
|
1103
|
+
.reverse()
|
|
1104
|
+
.find((e) => e.type === "assistant" && e.text.trim());
|
|
1105
|
+
if (!lastAssistant || lastAssistant.type !== "assistant")
|
|
1106
|
+
return false; // jsonl pas encore flush : une reprise différée
|
|
1107
|
+
// garde anti-doublon : même conversation + même texte déjà en tête de bus
|
|
1108
|
+
const head = listGroupMessages(db, owner.group_id, 1)[0];
|
|
1109
|
+
if (head?.role === "assistant" && head.conversation_id === convId && head.text === lastAssistant.text)
|
|
1110
|
+
return true;
|
|
1111
|
+
appendGroupMessage(db, {
|
|
1112
|
+
groupId: owner.group_id, conversationId: convId, agentId: owner.agent_id,
|
|
1113
|
+
role: "assistant", text: lastAssistant.text,
|
|
1114
|
+
});
|
|
1115
|
+
onReply?.(lastAssistant.text);
|
|
1116
|
+
return true;
|
|
1117
|
+
};
|
|
1118
|
+
if (!append()) {
|
|
1119
|
+
const retry = setTimeout(() => {
|
|
1120
|
+
try {
|
|
1121
|
+
append();
|
|
1122
|
+
}
|
|
1123
|
+
catch { /* bus best-effort : le rejeu suivant complètera */ }
|
|
1124
|
+
}, 1500);
|
|
1125
|
+
retry.unref();
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
777
1128
|
/** Tâches planifiées (cron) + historique de runs. */
|
|
778
1129
|
function scheduleRoutes(deps) {
|
|
779
1130
|
const { db, cron } = deps;
|
|
@@ -838,11 +1189,52 @@ export function createApp(opts) {
|
|
|
838
1189
|
const { db, paths, pool, cron } = opts;
|
|
839
1190
|
const events = opts.events ?? new EventEmitter();
|
|
840
1191
|
events.setMaxListeners(MAX_SSE_LISTENERS);
|
|
1192
|
+
recoverConfigurations(db);
|
|
1193
|
+
const spawner = makeSpawner({ db, pool, paths });
|
|
1194
|
+
// Runtime Durable : un seul gestionnaire dans le processus contrôleur (bail OS
|
|
1195
|
+
// par conversation). Les tests injectent un modèle contrôlé via opts.durable.
|
|
1196
|
+
const durable = opts.durable ?? new DurableRuntimeManager({ paths, toolchain: durableToolchainRegistry() });
|
|
1197
|
+
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.
|
|
1201
|
+
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
|
+
const group = getGroupWithMembers(db, groupId);
|
|
1205
|
+
if (!group)
|
|
1206
|
+
return;
|
|
1207
|
+
const target = matchGroupMention(group, text);
|
|
1208
|
+
if (!target || target.conversation_id === sourceConvId)
|
|
1209
|
+
return;
|
|
1210
|
+
const conv = db
|
|
1211
|
+
.prepare("SELECT * FROM conversation WHERE id = ?")
|
|
1212
|
+
.get(target.conversation_id);
|
|
1213
|
+
if (!conv)
|
|
1214
|
+
return;
|
|
1215
|
+
handoffTargets.add(target.conversation_id);
|
|
1216
|
+
try {
|
|
1217
|
+
await spawner.ensure(conv);
|
|
1218
|
+
await pool.prompt(conv.id, text);
|
|
1219
|
+
}
|
|
1220
|
+
catch {
|
|
1221
|
+
handoffTargets.delete(target.conversation_id);
|
|
1222
|
+
}
|
|
1223
|
+
}
|
|
841
1224
|
// Fan-out des événements pi vers les abonnés SSE par conversation
|
|
842
1225
|
const sseSubs = new Map();
|
|
1226
|
+
const groupSubs = new Map();
|
|
843
1227
|
const unsubscribePool = pool.onEvent((convId, event) => {
|
|
844
1228
|
for (const send of sseSubs.get(convId) ?? [])
|
|
845
1229
|
send(event);
|
|
1230
|
+
// ADR-011 : activité d'un membre de groupe → persistance bus + relais sur le SSE unique du fil
|
|
1231
|
+
const owner = conversationGroupOwner(db, convId);
|
|
1232
|
+
if (!owner)
|
|
1233
|
+
return;
|
|
1234
|
+
persistGroupActivity(db, convId, owner, event, (text) => void handleHandoff(convId, owner.group_id, text));
|
|
1235
|
+
const envelope = { type: "group_activity", conversationId: convId, agentId: owner.agent_id, name: owner.name, event };
|
|
1236
|
+
for (const send of groupSubs.get(owner.group_id) ?? [])
|
|
1237
|
+
send(envelope);
|
|
846
1238
|
});
|
|
847
1239
|
const deps = {
|
|
848
1240
|
db,
|
|
@@ -853,7 +1245,11 @@ export function createApp(opts) {
|
|
|
853
1245
|
cron,
|
|
854
1246
|
events,
|
|
855
1247
|
sseSubs,
|
|
856
|
-
|
|
1248
|
+
groupSubs,
|
|
1249
|
+
logins: new ProviderLogins(paths),
|
|
1250
|
+
spawner,
|
|
1251
|
+
compose,
|
|
1252
|
+
durable,
|
|
857
1253
|
};
|
|
858
1254
|
const routes = [
|
|
859
1255
|
healthRoute(deps),
|
|
@@ -861,6 +1257,7 @@ export function createApp(opts) {
|
|
|
861
1257
|
...agentRoutes(deps),
|
|
862
1258
|
...workspaceRoutes(deps),
|
|
863
1259
|
...boardRoutes(deps),
|
|
1260
|
+
...groupRoutes(deps),
|
|
864
1261
|
...conversationRoutes(deps),
|
|
865
1262
|
...scheduleRoutes(deps),
|
|
866
1263
|
// Events global (SSE) — les runs cron et les statuts de conversation
|
|
@@ -876,7 +1273,10 @@ export function createApp(opts) {
|
|
|
876
1273
|
app.headersTimeout = 10_000;
|
|
877
1274
|
app.maxHeadersCount = 100;
|
|
878
1275
|
}
|
|
879
|
-
app.once("close",
|
|
1276
|
+
app.once("close", () => {
|
|
1277
|
+
unsubscribePool();
|
|
1278
|
+
void durable.dispose();
|
|
1279
|
+
});
|
|
880
1280
|
app.on("request", async (req, res) => {
|
|
881
1281
|
res.setHeader("content-security-policy", "frame-ancestors 'none'");
|
|
882
1282
|
res.setHeader("x-frame-options", "DENY");
|