@ignitionai/cogitator 0.2.1 → 0.4.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/README.md +13 -2
- package/dist/extensions/index.js +21 -3
- package/dist/src/agents.js +5 -4
- package/dist/src/auth-cli.js +113 -0
- package/dist/src/auth-http.js +203 -0
- package/dist/src/auth-state.js +289 -0
- package/dist/src/board.js +3 -0
- package/dist/src/cli.js +78 -54
- package/dist/src/config.js +7 -0
- package/dist/src/conversations.js +8 -5
- package/dist/src/db.js +9 -3
- package/dist/src/file-changes.js +1 -1
- package/dist/src/history.js +3 -3
- package/dist/src/mcp-server.js +3 -14
- package/dist/src/native-auth.js +277 -0
- package/dist/src/owner-transport.js +127 -0
- package/dist/src/pool.js +4 -4
- package/dist/src/request-authorization.js +4 -0
- package/dist/src/schemas.js +1 -0
- package/dist/src/server.js +164 -39
- package/dist/src/skills-import.js +8 -0
- package/dist/src/spawner.js +3 -1
- package/package.json +5 -2
- package/web/dist/assets/index-D3Q54zLM.js +83 -0
- package/web/dist/assets/index-Kj5NVQYi.css +1 -0
- package/web/dist/index.html +2 -2
- package/web/dist/assets/index-2i_5DnXg.js +0 -80
- package/web/dist/assets/index-BjIxsyOx.css +0 -1
package/dist/src/server.js
CHANGED
|
@@ -1,10 +1,14 @@
|
|
|
1
1
|
import { execFile } from "node:child_process";
|
|
2
2
|
import { EventEmitter } from "node:events";
|
|
3
|
-
import { existsSync, statSync, readFileSync } from "node:fs";
|
|
4
|
-
import { dirname, extname, join, normalize } from "node:path";
|
|
3
|
+
import { existsSync, statSync, readFileSync, realpathSync } from "node:fs";
|
|
4
|
+
import { dirname, extname, join, normalize, relative, sep } from "node:path";
|
|
5
5
|
import { fileURLToPath } from "node:url";
|
|
6
6
|
import { createServer } from "node:http";
|
|
7
7
|
import { HOST } from "./config.js";
|
|
8
|
+
import { requestAuthorization } from "./request-authorization.js";
|
|
9
|
+
import { protectedRequired } from "./auth-state.js";
|
|
10
|
+
import { AuthError, ownerSession, requireApproved, sessionById } from "./native-auth.js";
|
|
11
|
+
import { authFailure, authJson, authRoute, browserHeaders, checkResponse, localCheck, responseChecks, validateBoundary } from "./auth-http.js";
|
|
8
12
|
import { packageVersion, piVersion } from "./pi.js";
|
|
9
13
|
import { API_PROTOCOLS, deleteProvider, listProviders, listSkills, mcpAdapterDetected, readMcp, upsertProvider, validateMcpConfig, writeMcp, } from "./registry.js";
|
|
10
14
|
import { applyAgent, createAgent, deleteAgent, getAgent, listAgents, unapplyAgent, updateAgent, validateAgent, getDefaultAgentId, setDefaultAgent, } from "./agents.js";
|
|
@@ -46,22 +50,38 @@ const CONTENT_TYPES = {
|
|
|
46
50
|
};
|
|
47
51
|
/** Sert le build statique de l'UI ; SPA fallback vers index.html.
|
|
48
52
|
* Le dossier est résolu à chaque requête : un build web peut être (re)généré après le démarrage. */
|
|
49
|
-
function serveStatic(res, pathname) {
|
|
53
|
+
function serveStatic(res, pathname, publicOnly = false) {
|
|
50
54
|
const root = findWebDist();
|
|
51
55
|
if (!root)
|
|
52
56
|
return false;
|
|
53
|
-
const
|
|
54
|
-
|
|
55
|
-
if (!file.startsWith(root))
|
|
56
|
-
return false; // pas de traversal
|
|
57
|
-
const target = existsSync(file) && statSync(file).isFile() ? file : join(root, "index.html");
|
|
58
|
-
if (!existsSync(target))
|
|
57
|
+
const target = resolveStaticFile(root, pathname, publicOnly);
|
|
58
|
+
if (!target)
|
|
59
59
|
return false;
|
|
60
|
+
checkResponse(res);
|
|
60
61
|
res.writeHead(200, { "content-type": CONTENT_TYPES[extname(target)] ?? "application/octet-stream" });
|
|
61
62
|
res.end(readFileSync(target));
|
|
62
63
|
return true;
|
|
63
64
|
}
|
|
65
|
+
/** Resolve symlinks before serving: lexical prefix checks alone are not containment. */
|
|
66
|
+
export function resolveStaticFile(root, pathname, publicOnly = false) {
|
|
67
|
+
const rel = pathname === "/" ? "index.html" : pathname;
|
|
68
|
+
const file = normalize(join(root, rel));
|
|
69
|
+
if (relative(root, file).startsWith(`..${sep}`))
|
|
70
|
+
return null;
|
|
71
|
+
if (publicOnly && pathname !== "/" && pathname !== "/index.html" && !/^\/assets\/[A-Za-z0-9_-]+\.(?:js|css|woff2)$/.test(pathname))
|
|
72
|
+
return null;
|
|
73
|
+
if (publicOnly && !existsSync(file))
|
|
74
|
+
return null;
|
|
75
|
+
const target = existsSync(file) && statSync(file).isFile() ? file : join(root, "index.html");
|
|
76
|
+
if (!existsSync(target))
|
|
77
|
+
return null;
|
|
78
|
+
const contained = relative(realpathSync(root), realpathSync(target));
|
|
79
|
+
if (contained.startsWith(`..${sep}`) || contained === "..")
|
|
80
|
+
return null;
|
|
81
|
+
return target;
|
|
82
|
+
}
|
|
64
83
|
function sendJson(res, status, body) {
|
|
84
|
+
checkResponse(res);
|
|
65
85
|
res.writeHead(status, { "content-type": "application/json" });
|
|
66
86
|
res.end(JSON.stringify(body));
|
|
67
87
|
}
|
|
@@ -94,7 +114,8 @@ function matchRoute(routes, method, pathname) {
|
|
|
94
114
|
}
|
|
95
115
|
return null;
|
|
96
116
|
}
|
|
97
|
-
|
|
117
|
+
// Doit rester cohérent avec messageSchema : 8 images × 15 Mo base64 + texte (~121 Mo).
|
|
118
|
+
const MAX_BODY_BYTES = 130_000_000;
|
|
98
119
|
function readBody(req) {
|
|
99
120
|
return new Promise((resolve, reject) => {
|
|
100
121
|
let size = 0;
|
|
@@ -102,8 +123,7 @@ function readBody(req) {
|
|
|
102
123
|
req.on("data", (c) => {
|
|
103
124
|
size += c.length;
|
|
104
125
|
if (size > MAX_BODY_BYTES) {
|
|
105
|
-
reject(new
|
|
106
|
-
req.destroy();
|
|
126
|
+
reject(new AuthError("INVALID_INPUT", 413));
|
|
107
127
|
return;
|
|
108
128
|
}
|
|
109
129
|
chunks.push(c);
|
|
@@ -115,7 +135,7 @@ function readBody(req) {
|
|
|
115
135
|
resolve(JSON.parse(Buffer.concat(chunks).toString("utf8")));
|
|
116
136
|
}
|
|
117
137
|
catch {
|
|
118
|
-
reject(new
|
|
138
|
+
reject(new AuthError("INVALID_INPUT", 400));
|
|
119
139
|
}
|
|
120
140
|
});
|
|
121
141
|
req.on("error", reject);
|
|
@@ -135,15 +155,34 @@ function parseBody(res, schema, body) {
|
|
|
135
155
|
}
|
|
136
156
|
const SSE_HEADERS = {
|
|
137
157
|
"content-type": "text/event-stream",
|
|
138
|
-
"cache-control": "no-
|
|
158
|
+
"cache-control": "no-store",
|
|
139
159
|
connection: "keep-alive",
|
|
140
160
|
};
|
|
141
161
|
/** Ouvre un flux SSE et renvoie l'émetteur (`initial` = premier événement, ex. session_file). */
|
|
142
162
|
function openSse(res, initial) {
|
|
163
|
+
checkResponse(res);
|
|
143
164
|
res.writeHead(200, SSE_HEADERS);
|
|
144
165
|
const send = (event) => {
|
|
145
|
-
|
|
166
|
+
try {
|
|
167
|
+
checkResponse(res);
|
|
168
|
+
if (!res.destroyed && !res.writableEnded)
|
|
169
|
+
res.write(`data: ${JSON.stringify(event)}\n\n`);
|
|
170
|
+
}
|
|
171
|
+
catch {
|
|
172
|
+
res.end();
|
|
173
|
+
}
|
|
146
174
|
};
|
|
175
|
+
const heartbeat = setInterval(() => {
|
|
176
|
+
try {
|
|
177
|
+
checkResponse(res);
|
|
178
|
+
res.write(": heartbeat\n\n");
|
|
179
|
+
}
|
|
180
|
+
catch {
|
|
181
|
+
res.end();
|
|
182
|
+
}
|
|
183
|
+
}, 15_000);
|
|
184
|
+
heartbeat.unref();
|
|
185
|
+
res.once("close", () => clearInterval(heartbeat));
|
|
147
186
|
if (initial !== undefined)
|
|
148
187
|
send(initial);
|
|
149
188
|
return send;
|
|
@@ -242,6 +281,9 @@ function agentRoutes(deps) {
|
|
|
242
281
|
const input = parseBody(ctx.res, agentInputSchema, ctx.body);
|
|
243
282
|
if (!input)
|
|
244
283
|
return;
|
|
284
|
+
if (input.default_workspace_id && !getWorkspace(db, input.default_workspace_id)) {
|
|
285
|
+
return sendJson(ctx.res, 404, { error: "workspace introuvable" });
|
|
286
|
+
}
|
|
245
287
|
const preset = createAgent(db, input);
|
|
246
288
|
sendJson(ctx.res, 201, { agent: preset, apply: applyAgent(paths, preset) });
|
|
247
289
|
}],
|
|
@@ -255,6 +297,9 @@ function agentRoutes(deps) {
|
|
|
255
297
|
const input = parseBody(ctx.res, agentInputSchema, ctx.body);
|
|
256
298
|
if (!input)
|
|
257
299
|
return;
|
|
300
|
+
if (input.default_workspace_id && !getWorkspace(db, input.default_workspace_id)) {
|
|
301
|
+
return sendJson(ctx.res, 404, { error: "workspace introuvable" });
|
|
302
|
+
}
|
|
258
303
|
const preset = updateAgent(db, ctx.params.id, input);
|
|
259
304
|
if (!preset)
|
|
260
305
|
return notFound(ctx.res, "agent");
|
|
@@ -467,7 +512,7 @@ function boardRoutes(deps) {
|
|
|
467
512
|
const ws = requireWorkspace(deps, ctx);
|
|
468
513
|
if (!ws)
|
|
469
514
|
return;
|
|
470
|
-
const started = await startCardWork(deps, ws, cardNumber(ctx), (ctx.body ?? {}).extra);
|
|
515
|
+
const started = await startCardWork(deps, ws, cardNumber(ctx), (ctx.body ?? {}).extra, ctx.check);
|
|
471
516
|
if ("error" in started)
|
|
472
517
|
return sendJson(ctx.res, started.status, { error: started.error });
|
|
473
518
|
sendJson(ctx.res, 201, started);
|
|
@@ -531,8 +576,9 @@ async function findCard(wsDir, number) {
|
|
|
531
576
|
return card ? { card } : { error: "carte introuvable", status: 404 };
|
|
532
577
|
}
|
|
533
578
|
/** Ticket → conversation pilotée par l'agent assigné, puis carte déplacée en in_progress. */
|
|
534
|
-
async function startCardWork(deps, ws, number, extra) {
|
|
579
|
+
async function startCardWork(deps, ws, number, extra, check = () => { }) {
|
|
535
580
|
const found = await findCard(ws.dir, number);
|
|
581
|
+
check();
|
|
536
582
|
if ("error" in found)
|
|
537
583
|
return found;
|
|
538
584
|
const { card } = found;
|
|
@@ -549,10 +595,13 @@ async function startCardWork(deps, ws, number, extra) {
|
|
|
549
595
|
setConversationTitle(deps.db, conv.id, `#${card.number} ${card.title}`);
|
|
550
596
|
const titled = getConversation(deps.db, conv.id);
|
|
551
597
|
await deps.spawner.ensure(titled);
|
|
598
|
+
check();
|
|
552
599
|
await deps.pool.prompt(titled.id, ticketPrompt(card, extra));
|
|
600
|
+
check();
|
|
553
601
|
const moved = await moveCardGh(ws.dir, card.number, "in_progress");
|
|
554
602
|
if ("error" in moved)
|
|
555
603
|
return { conversation: titled, card };
|
|
604
|
+
check();
|
|
556
605
|
const linked = await updateCardGh(ws.dir, card.number, {
|
|
557
606
|
title: moved.card.title,
|
|
558
607
|
conversation_ids: [...new Set([...card.conversation_ids, conv.id])],
|
|
@@ -573,8 +622,9 @@ function conversationRoutes(deps) {
|
|
|
573
622
|
const { db, pool } = deps;
|
|
574
623
|
return [
|
|
575
624
|
["GET", "/api/conversations", (ctx) => {
|
|
576
|
-
const workspaceId = ctx.query.get("workspace_id");
|
|
577
|
-
|
|
625
|
+
const workspaceId = ctx.query.get("workspace_id") ?? undefined;
|
|
626
|
+
const agentId = ctx.query.get("agent_id") ?? undefined;
|
|
627
|
+
sendJson(ctx.res, 200, { conversations: listConversations(db, workspaceId, agentId) });
|
|
578
628
|
}],
|
|
579
629
|
["POST", "/api/conversations", async (ctx) => {
|
|
580
630
|
const b = parseBody(ctx.res, conversationCreateSchema, ctx.body);
|
|
@@ -583,11 +633,13 @@ function conversationRoutes(deps) {
|
|
|
583
633
|
const resolved = resolveSpawnTarget(deps, b);
|
|
584
634
|
if ("error" in resolved)
|
|
585
635
|
return sendJson(ctx.res, resolved.status, { error: resolved.error });
|
|
586
|
-
let conv = createConversation(db, { workspaceId:
|
|
636
|
+
let conv = createConversation(db, { workspaceId: resolved.workspaceId, agentId: resolved.agentId, spawn: resolved.spawn });
|
|
587
637
|
const prompt = b.prompt?.trim();
|
|
588
638
|
if (prompt) {
|
|
589
639
|
await deps.spawner.ensure(conv);
|
|
640
|
+
ctx.check();
|
|
590
641
|
await pool.prompt(conv.id, prompt);
|
|
642
|
+
ctx.check();
|
|
591
643
|
setConversationTitle(db, conv.id, prompt);
|
|
592
644
|
conv = getConversation(db, conv.id);
|
|
593
645
|
}
|
|
@@ -608,8 +660,10 @@ function conversationRoutes(deps) {
|
|
|
608
660
|
const subs = deps.sseSubs.get(conv.id) ?? new Set();
|
|
609
661
|
deps.sseSubs.set(conv.id, subs);
|
|
610
662
|
subs.add(send);
|
|
611
|
-
ctx.
|
|
663
|
+
ctx.res.once("close", () => {
|
|
612
664
|
subs.delete(send);
|
|
665
|
+
if (!subs.size)
|
|
666
|
+
deps.sseSubs.delete(conv.id);
|
|
613
667
|
});
|
|
614
668
|
}],
|
|
615
669
|
["GET", "/api/conversations/:id/history", (ctx) => {
|
|
@@ -643,7 +697,9 @@ function conversationRoutes(deps) {
|
|
|
643
697
|
return;
|
|
644
698
|
const text = (b.text ?? "").trim();
|
|
645
699
|
await deps.spawner.ensure(conv);
|
|
700
|
+
ctx.check();
|
|
646
701
|
await pool.prompt(conv.id, text, b.images);
|
|
702
|
+
ctx.check();
|
|
647
703
|
if (text)
|
|
648
704
|
setConversationTitle(db, conv.id, text);
|
|
649
705
|
sendJson(ctx.res, 200, { ok: true });
|
|
@@ -663,6 +719,7 @@ function conversationRoutes(deps) {
|
|
|
663
719
|
if (!b)
|
|
664
720
|
return;
|
|
665
721
|
await pool.setModel(conv.id, b.provider, b.id);
|
|
722
|
+
ctx.check();
|
|
666
723
|
const spawn = { ...JSON.parse(conv.spawn_args || "{}"), provider: b.provider, model: b.id };
|
|
667
724
|
setConversationModel(db, conv.id, b.provider, b.id, spawn);
|
|
668
725
|
sendJson(ctx.res, 200, { ok: true });
|
|
@@ -672,6 +729,7 @@ function conversationRoutes(deps) {
|
|
|
672
729
|
if (!conv)
|
|
673
730
|
return;
|
|
674
731
|
await pool.evict(conv.id);
|
|
732
|
+
ctx.check();
|
|
675
733
|
deleteConversation(db, conv.id);
|
|
676
734
|
sendJson(ctx.res, 200, { ok: true }); // le .jsonl pi survit sur disque (I5)
|
|
677
735
|
}],
|
|
@@ -689,11 +747,15 @@ function resolveSpawnTarget(deps, b) {
|
|
|
689
747
|
const preset = getAgent(db, agentId);
|
|
690
748
|
if (!preset)
|
|
691
749
|
return { error: "agent introuvable", status: 404 };
|
|
692
|
-
|
|
750
|
+
const workspaceId = b.workspace_id ?? preset.default_workspace_id ?? null;
|
|
751
|
+
if (workspaceId && !getWorkspace(db, workspaceId))
|
|
752
|
+
return { error: "workspace introuvable", status: 404 };
|
|
753
|
+
return { agentId: preset.id, spawn: spawnConfigFromPreset(preset), workspaceId };
|
|
693
754
|
}
|
|
694
755
|
if (b.provider && b.model) {
|
|
695
756
|
return {
|
|
696
757
|
agentId: null,
|
|
758
|
+
workspaceId: b.workspace_id ?? null,
|
|
697
759
|
spawn: {
|
|
698
760
|
provider: b.provider, model: b.model, thinking: b.thinking ?? null,
|
|
699
761
|
systemPrompt: b.system_prompt, skills: b.skills, tools: b.tools, mcpServers: b.mcp_servers,
|
|
@@ -707,7 +769,10 @@ function resolveSpawnTarget(deps, b) {
|
|
|
707
769
|
const preset = getAgent(db, fallbackId);
|
|
708
770
|
if (!preset)
|
|
709
771
|
return { error: "agent introuvable", status: 404 };
|
|
710
|
-
|
|
772
|
+
const workspaceId = b.workspace_id ?? preset.default_workspace_id ?? null;
|
|
773
|
+
if (workspaceId && !getWorkspace(db, workspaceId))
|
|
774
|
+
return { error: "workspace introuvable", status: 404 };
|
|
775
|
+
return { agentId: preset.id, spawn: spawnConfigFromPreset(preset), workspaceId };
|
|
711
776
|
}
|
|
712
777
|
/** Tâches planifiées (cron) + historique de runs. */
|
|
713
778
|
function scheduleRoutes(deps) {
|
|
@@ -746,7 +811,7 @@ function scheduleRoutes(deps) {
|
|
|
746
811
|
if (!task)
|
|
747
812
|
return notFound(ctx.res, "schedule");
|
|
748
813
|
// fire-and-forget : le run est tracé et observable via /runs + /events
|
|
749
|
-
void cron.fireNow(task.id).catch(() => undefined);
|
|
814
|
+
requestAuthorization.exit(() => { void cron.fireNow(task.id).catch(() => undefined); });
|
|
750
815
|
sendJson(ctx.res, 202, { ok: true });
|
|
751
816
|
}],
|
|
752
817
|
["GET", "/api/schedules/:id/runs", (ctx) => {
|
|
@@ -775,7 +840,7 @@ export function createApp(opts) {
|
|
|
775
840
|
events.setMaxListeners(MAX_SSE_LISTENERS);
|
|
776
841
|
// Fan-out des événements pi vers les abonnés SSE par conversation
|
|
777
842
|
const sseSubs = new Map();
|
|
778
|
-
pool.onEvent((convId, event) => {
|
|
843
|
+
const unsubscribePool = pool.onEvent((convId, event) => {
|
|
779
844
|
for (const send of sseSubs.get(convId) ?? [])
|
|
780
845
|
send(event);
|
|
781
846
|
});
|
|
@@ -802,28 +867,88 @@ export function createApp(opts) {
|
|
|
802
867
|
["GET", "/api/events", (ctx) => {
|
|
803
868
|
const send = openSse(ctx.res);
|
|
804
869
|
events.on("event", send);
|
|
805
|
-
ctx.
|
|
870
|
+
ctx.res.once("close", () => events.off("event", send));
|
|
806
871
|
}],
|
|
807
872
|
];
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
873
|
+
const app = opts.server ?? createServer();
|
|
874
|
+
if (opts.auth) {
|
|
875
|
+
app.requestTimeout = 30_000;
|
|
876
|
+
app.headersTimeout = 10_000;
|
|
877
|
+
app.maxHeadersCount = 100;
|
|
878
|
+
}
|
|
879
|
+
app.once("close", unsubscribePool);
|
|
880
|
+
app.on("request", async (req, res) => {
|
|
881
|
+
res.setHeader("content-security-policy", "frame-ancestors 'none'");
|
|
882
|
+
res.setHeader("x-frame-options", "DENY");
|
|
883
|
+
res.setHeader("referrer-policy", "no-referrer");
|
|
884
|
+
res.setHeader("x-content-type-options", "nosniff");
|
|
817
885
|
try {
|
|
818
|
-
const
|
|
886
|
+
const privateRequest = privateRequests.has(req);
|
|
887
|
+
const state = opts.auth;
|
|
888
|
+
if (privateRequest && ("origin" in req.headers || Object.keys(req.headers).some(h => h.startsWith("sec-fetch-"))))
|
|
889
|
+
throw new AuthError("FORBIDDEN", 403);
|
|
890
|
+
if (state) {
|
|
891
|
+
state.assertAvailable();
|
|
892
|
+
if (!privateRequest)
|
|
893
|
+
validateBoundary(req, state);
|
|
894
|
+
}
|
|
895
|
+
else
|
|
896
|
+
localCheck(paths.home);
|
|
897
|
+
const url = new URL(req.url ?? "/", `http://${HOST}`);
|
|
898
|
+
if (req.url === "/api/status" && req.method === "GET")
|
|
899
|
+
return authJson(res, 200, { service: "cogitator", authentication: state ? "required" : "local" });
|
|
900
|
+
if (url.pathname.startsWith("/api/auth")) {
|
|
901
|
+
if (privateRequest)
|
|
902
|
+
throw new AuthError("FORBIDDEN", 403);
|
|
903
|
+
if (state)
|
|
904
|
+
return await authRoute(req, res, state);
|
|
905
|
+
if (req.url === "/api/auth/status" && req.method === "GET")
|
|
906
|
+
return authJson(res, 200, { mode: "local" });
|
|
907
|
+
throw new AuthError("NOT_FOUND", 404);
|
|
908
|
+
}
|
|
909
|
+
// Only the build login shell and its JS/CSS/font assets are public, never an SPA fallback.
|
|
910
|
+
if (state && !url.pathname.startsWith("/api/") && req.method === "GET" && serveStatic(res, url.pathname, true))
|
|
911
|
+
return;
|
|
912
|
+
let check = () => localCheck(paths.home);
|
|
913
|
+
if (state) {
|
|
914
|
+
if (privateRequest)
|
|
915
|
+
check = () => state.assertAvailable();
|
|
916
|
+
else {
|
|
917
|
+
const session = await ownerSession(state.auth, state.db, state.config, browserHeaders(req));
|
|
918
|
+
requireApproved(session);
|
|
919
|
+
check = () => { state.assertAvailable(); requireApproved(sessionById(state.db, state.config, session.id)); };
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
check();
|
|
923
|
+
responseChecks.set(res, check);
|
|
924
|
+
if (state)
|
|
925
|
+
res.setHeader("cache-control", "no-store");
|
|
926
|
+
if (!url.pathname.startsWith("/api/")) {
|
|
927
|
+
if (serveStatic(res, url.pathname))
|
|
928
|
+
return;
|
|
929
|
+
return sendJson(res, 404, { error: "NOT_FOUND" });
|
|
930
|
+
}
|
|
931
|
+
const body = req.method === "POST" || req.method === "PUT" || req.method === "DELETE" ? await readBody(req) : {};
|
|
932
|
+
check();
|
|
819
933
|
const found = matchRoute(routes, req.method ?? "GET", url.pathname);
|
|
820
934
|
if (!found)
|
|
821
|
-
return sendJson(res, 404, { error: `not found: ${url.pathname}` });
|
|
822
|
-
await found.handler({ params: found.params, query: url.searchParams, body, req, res });
|
|
935
|
+
return sendJson(res, 404, { error: state ? "NOT_FOUND" : `not found: ${url.pathname}` });
|
|
936
|
+
await requestAuthorization.run(check, () => found.handler({ params: found.params, query: url.searchParams, body, req, res, check }));
|
|
823
937
|
}
|
|
824
938
|
catch (err) {
|
|
825
|
-
|
|
939
|
+
if (err instanceof AuthError || opts.auth || protectedRequired(paths.home))
|
|
940
|
+
authFailure(res, err);
|
|
941
|
+
else if (!res.headersSent)
|
|
942
|
+
sendJson(res, 500, { error: err instanceof Error ? err.message : String(err) });
|
|
943
|
+
else
|
|
944
|
+
res.end();
|
|
826
945
|
}
|
|
827
946
|
});
|
|
947
|
+
return app;
|
|
948
|
+
}
|
|
949
|
+
// Server-owned identity only: no HTTP header can confer the local OS-owner capability.
|
|
950
|
+
const privateRequests = new WeakSet();
|
|
951
|
+
export function createPrivateServer(app) {
|
|
952
|
+
return createServer((req, res) => { privateRequests.add(req); app.emit("request", req, res); });
|
|
828
953
|
}
|
|
829
954
|
export { sendJson, API_PROTOCOLS };
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { checkRequestAuthorization } from "./request-authorization.js";
|
|
2
|
+
import { AuthError } from "./native-auth.js";
|
|
1
3
|
import { execFile } from "node:child_process";
|
|
2
4
|
import { cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
3
5
|
import { tmpdir } from "node:os";
|
|
@@ -41,6 +43,7 @@ export function scanSkillDirs(root, depth = 0, found = []) {
|
|
|
41
43
|
}
|
|
42
44
|
/** Copie les skills trouvés sous srcDir vers destRoot (~/.agents/skills). */
|
|
43
45
|
export function importFromDir(srcDir, destRoot, overwrite = false) {
|
|
46
|
+
checkRequestAuthorization();
|
|
44
47
|
const result = { imported: [], skipped: [] };
|
|
45
48
|
const skills = scanSkillDirs(srcDir);
|
|
46
49
|
mkdirSync(destRoot, { recursive: true });
|
|
@@ -104,6 +107,8 @@ export async function importFromGitHub(source, destRoot, overwrite = false) {
|
|
|
104
107
|
return importFromDir(join(extractDir, roots[0]), destRoot, overwrite);
|
|
105
108
|
}
|
|
106
109
|
catch (err) {
|
|
110
|
+
if (err instanceof AuthError)
|
|
111
|
+
throw err;
|
|
107
112
|
return { imported: [], skipped: [], error: err instanceof Error ? err.message : String(err) };
|
|
108
113
|
}
|
|
109
114
|
finally {
|
|
@@ -129,6 +134,7 @@ export function importSkills(source, destRoot, overwrite = false) {
|
|
|
129
134
|
* (pas de quotes — limitation assumée, ponytail: découper avec un vrai shell-quote si besoin).
|
|
130
135
|
*/
|
|
131
136
|
export async function runSkillCommand(cmd, destRoots, timeoutMs = CLI_TIMEOUT_MS) {
|
|
137
|
+
checkRequestAuthorization();
|
|
132
138
|
const tokens = cmd.split(/\s+/).filter(Boolean);
|
|
133
139
|
const bin = tokens[0];
|
|
134
140
|
if (bin !== "npx" && bin !== "npm") {
|
|
@@ -162,6 +168,8 @@ export async function runSkillCommand(cmd, destRoots, timeoutMs = CLI_TIMEOUT_MS
|
|
|
162
168
|
return result;
|
|
163
169
|
}
|
|
164
170
|
catch (err) {
|
|
171
|
+
if (err instanceof AuthError)
|
|
172
|
+
throw err;
|
|
165
173
|
return { imported: [], skipped: [], error: err instanceof Error ? err.message : String(err) };
|
|
166
174
|
}
|
|
167
175
|
}
|
package/dist/src/spawner.js
CHANGED
|
@@ -5,6 +5,8 @@ import { setConversationSession } from "./conversations.js";
|
|
|
5
5
|
import { UI_INSTRUCTIONS, UI_PRESENTATION_POLICY } from "./generative-ui.js";
|
|
6
6
|
import { MCP_ENV_VAR, encodeMcpEnv } from "./mcp-env.js";
|
|
7
7
|
import { buildArgs } from "./spawn.js";
|
|
8
|
+
/** Identité d'environnement : l'agent sait qu'il tourne dans le web UI, pas dans le TUI pi. */
|
|
9
|
+
const ENVIRONMENT_NOTICE = "Environnement : tu t'exécutes dans Cogitator, un panneau de contrôle web pour pi. L'utilisateur interagit depuis un navigateur : ne lui demande jamais de changer de mode, d'appuyer sur une touche ou d'utiliser le TUI pi — tu as déjà accès complet aux outils, agis directement.";
|
|
8
10
|
/** Fabrique unique du mécanisme de spawn, partagé par le serveur HTTP et le CronService. */
|
|
9
11
|
export function makeSpawner(opts) {
|
|
10
12
|
const { db, pool, paths } = opts;
|
|
@@ -18,7 +20,7 @@ export function makeSpawner(opts) {
|
|
|
18
20
|
const result = await pool.ensure(conv.id, {
|
|
19
21
|
cwd: conv.workspace_dir ?? homedir(),
|
|
20
22
|
// Host presentation capability: also available to legacy sessions, without rewriting their snapshot.
|
|
21
|
-
args: buildArgs({ ...spawn, uiInstructions: `${spawn.uiInstructions ?? UI_INSTRUCTIONS}\n\n${UI_PRESENTATION_POLICY}` }, tmpDir, conv.id),
|
|
23
|
+
args: buildArgs({ ...spawn, uiInstructions: `${spawn.uiInstructions ?? UI_INSTRUCTIONS}\n\n${UI_PRESENTATION_POLICY}\n\n${ENVIRONMENT_NOTICE}` }, tmpDir, conv.id),
|
|
22
24
|
resumeSessionFile: conv.session_file,
|
|
23
25
|
env: mcpEnv ? { [MCP_ENV_VAR]: mcpEnv } : undefined,
|
|
24
26
|
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ignitionai/cogitator",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "A web control panel for pi: composable agents, workspaces, interactive conversations, and scheduled tasks. A pi package.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"keywords": [
|
|
@@ -39,7 +39,8 @@
|
|
|
39
39
|
"dev:web": "vite web",
|
|
40
40
|
"test": "tsx --test test/*.test.ts",
|
|
41
41
|
"prepublishOnly": "npm run build && npm test",
|
|
42
|
-
"typecheck": "tsc --noEmit && tsc --noEmit -p web"
|
|
42
|
+
"typecheck": "tsc --noEmit && tsc --noEmit -p web",
|
|
43
|
+
"durable:spike": "npm --prefix scripts/durable-spike run check"
|
|
43
44
|
},
|
|
44
45
|
"pi": {
|
|
45
46
|
"extensions": [
|
|
@@ -53,11 +54,13 @@
|
|
|
53
54
|
"dependencies": {
|
|
54
55
|
"@fontsource/inter": "^5.3.0",
|
|
55
56
|
"@modelcontextprotocol/sdk": "^1.32.1",
|
|
57
|
+
"better-auth": "1.7.7",
|
|
56
58
|
"better-sqlite3": "^12.11.1",
|
|
57
59
|
"cron-parser": "^5.10.1",
|
|
58
60
|
"zod": "^4.6.5"
|
|
59
61
|
},
|
|
60
62
|
"devDependencies": {
|
|
63
|
+
"@better-auth/utils": "0.4.2",
|
|
61
64
|
"@earendil-works/pi-coding-agent": "^1.0.4",
|
|
62
65
|
"@types/better-sqlite3": "^9.6.0",
|
|
63
66
|
"@types/node": "^24.0.0",
|