Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions extensions/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,11 @@ export default function (pi: ExtensionAPI) {
action: Type.String(), tabId: Type.Optional(Type.String()), url: Type.Optional(Type.String()), selector: Type.Optional(Type.String()), text: Type.Optional(Type.String()), key: Type.Optional(Type.String()), x: Type.Optional(Type.Number()), y: Type.Optional(Type.Number()), delta: Type.Optional(Type.Number()),
})) }),
execute: async (_id, params) => {
const conversationId = process.env.COGITATOR_CONVERSATION_ID;
if (!conversationId) throw new Error("Open this tool from a Cogitator conversation.");
const result = await ownerRequest<{ image?: string; mimeType?: string }>("POST", "/api/browser/agent", {conversationId,...params});
if (!process.env.COGITATOR_CONVERSATION_ID) throw new Error("Open this tool from a Cogitator conversation.");
const result = await ownerRequest<{ image?: string; mimeType?: string }>("POST", "/api/browser/agent", {
profileId: params.profileId,
command: params.command,
});
return result.image ? {content:[{type:"image",data:result.image,mimeType:"image/jpeg"}],details:{}} : {content:[{type:"text",text:JSON.stringify(result)}],details:{}};
},
});
Expand Down
12 changes: 8 additions & 4 deletions src/agents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -248,15 +248,19 @@ function subagentFileName(agentSlug: string, subName: string): string {
return `noo-${agentSlug}-${subName}.md`;
}

function yamlQuote(value: string): string {
return JSON.stringify(value.replace(/\r\n|\r|\n/g, " "));
}

function renderSubagent(sub: SubagentInput & { id: string }, agentSlug: string): { file: string; content: string } {
const lines = [
"---",
`name: noo-${agentSlug}-${sub.name}`,
`description: ${(sub.description ?? "").replace(/\n/g, " ")}`,
`name: ${yamlQuote(`noo-${agentSlug}-${sub.name}`)}`,
`description: ${yamlQuote(sub.description ?? "")}`,
"kind: pi",
`model: ${sub.provider}/${sub.model}`,
`model: ${yamlQuote(`${sub.provider}/${sub.model}`)}`,
];
if (sub.thinking) lines.push(`thinking: ${sub.thinking}`);
if (sub.thinking) lines.push(`thinking: ${yamlQuote(sub.thinking)}`);
if (sub.skills?.length) lines.push(`skills: ${JSON.stringify(sub.skills)}`);
lines.push("---", "", sub.system_prompt ?? "");
return { file: subagentFileName(agentSlug, sub.name), content: lines.join("\n") + "\n" };
Expand Down
10 changes: 8 additions & 2 deletions src/browser-http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ import type { AuthState } from './auth-state.js';
import { AuthError, ownerSession, requireApproved, sessionById } from './native-auth.js';
import { browserHeaders, validateBoundary, localCheck } from './auth-http.js';
import { requestAuthorization } from './request-authorization.js';
import { CONVERSATION_ID_HEADER } from './config.js';

function headerValue(raw: string | string[] | undefined): string | undefined {
return Array.isArray(raw) ? raw[0] : raw;
}

type Ctx = { params: Record<string,string>; body: unknown; req: IncomingMessage; res: ServerResponse; check: () => void };
type Route = [string, string, (ctx: Ctx) => Promise<void> | void];
Expand All @@ -27,8 +32,9 @@ export function browserRoutes(browser: SharedBrowser, privateRequest: (req: Inco
// Agent identity is attached by the bundled extension, not accepted on the public HTTP surface.
if (!privateRequest(ctx.req) && protectedMode) throw new AuthError('FORBIDDEN',403);
try {
const b = z.object({conversationId:z.string().uuid(),profileId:z.string().uuid().optional(),command:z.unknown().optional()}).strict().parse(ctx.body);
ctx.check(); const result = b.profileId ? await browser.act(b.profileId,b.command,b.conversationId) : {profiles:browser.agentProfiles(b.conversationId)};
const b = z.object({conversationId:z.string().uuid().optional(),profileId:z.string().uuid().optional(),command:z.unknown().optional()}).strict().parse(ctx.body);
const conversationId = z.string().uuid().parse(headerValue(ctx.req.headers[CONVERSATION_ID_HEADER]));
ctx.check(); const result = b.profileId ? await browser.act(b.profileId,b.command,conversationId) : {profiles:browser.agentProfiles(conversationId)};
ctx.check(); send(ctx.res,200,result);
} catch(error) { if(error instanceof BrowserProblem || error instanceof z.ZodError) send(ctx.res,400,{error:error instanceof BrowserProblem ? error.message : 'BROWSER_INVALID_INPUT'}); else if (error instanceof AuthError) throw error; else send(ctx.res,400,{error:'BROWSER_ACTION_FAILED'}); }
}],
Expand Down
3 changes: 3 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ export const PORT = Number(process.env.COGITATOR_PORT ?? DEFAULT_PORT);
/** URL de base du serveur local — COGITATOR_URL l'emporte (ex. autre port/hôte). */
export const BASE_URL = process.env.COGITATOR_URL ?? `http://${HOST}:${PORT}`;

/** Identité de conversation du process agent, jamais lue depuis le corps HTTP. */
export const CONVERSATION_ID_HEADER = "x-cogitator-conversation-id";

/** Only explicit 0/1 are supported; a typo must never silently select local mode. */
export function authenticationRequired(env: NodeJS.ProcessEnv = process.env): boolean {
const value = env.COGITATOR_AUTH_REQUIRED;
Expand Down
2 changes: 1 addition & 1 deletion src/default-agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ Tes responsabilités :
4bis. Lancer les agents sur leurs tickets : assigne la carte (assignee_agent_id) puis cogitator_board_start_work — la conversation spawnée est automatiquement liée (activité cumulée).
4ter. Créer les moyens manquants — TOUJOURS VÉRIFIER L'EXISTANT D'ABORD, jamais de doublon :
- Agent : d'abord cogitator_list_agents — un preset existant couvre-t-il la tâche ? Si oui, réutilise-le (cogitator_update_agent si besoin). Si non, cogitator_create_agent (provider, modèle, thinking, prompt de scope, skills, MCP), puis cogitator_validate_agent.
- Skill : d'abord cogitator_list_skills — un skill existant couvre-t-il le besoin ? SI ET SEULEMENT SI aucun ne convient : déléguer à l'Architecte de Skills, OU importer via cogitator_import_skills (GitHub/npx).
- Skill : d'abord cogitator_list_skills — un skill existant couvre-t-il le besoin ? SI ET SEULEMENT SI aucun ne convient : déléguer à l'Architecte de Skills, OU importer via cogitator_import_skills (GitHub ou dossier local ; jamais une commande npm/npx).
5. Proposer des priorités — ne jamais décider seul d'annuler une carte sans confirmation explicite.
6. Fournir des bilans : "où on en est", "qu'est-ce qui bloque", "prochaines étapes" — courts et factuels.

Expand Down
8 changes: 6 additions & 2 deletions src/mcp-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { z } from "zod";
import { ownerRequest } from "./owner-transport.js";
import { packageVersion } from "./pi.js";
import { CARD_PRIORITIES, CARD_STATUSES, thinkingSchema } from "./schemas.js";
import { COMMAND_IMPORT_HUMAN_ONLY, skillCommandSource } from "./skills-import.js";

const call = ownerRequest;

Expand Down Expand Up @@ -178,12 +179,15 @@ addTool("cogitator_list_providers", "Liste les providers pi (catalogue + statut

addTool("cogitator_list_skills", "Liste les skills disponibles (name, description, path).", {}, () => call("GET", "/api/skills"));

addTool("cogitator_import_skills", "Importe des skills : repo GitHub (ex: IgnitionAI/skills), dossier local, ou commande CLI (ex: 'npx aiblueprint-cli@latest skills update'). Les dossiers contenant un SKILL.md sont copiés vers ~/.agents/skills/.",
addTool("cogitator_import_skills", "Importe des skills depuis un repo GitHub (ex: IgnitionAI/skills) ou un dossier local. Les dossiers contenant un SKILL.md sont copiés vers le répertoire de skills. L'import par commande npm/npx n'est pas disponible ici.",
{
source: z.string().describe("URL GitHub (https://github.com/owner/repo) ou chemin absolu d'un dossier local"),
overwrite: z.boolean().optional().describe("Écrase les skills existants du même nom (défaut: skip)"),
},
(a) => call("POST", "/api/skills/import", a));
(a) => {
if (skillCommandSource(String(a.source ?? ""))) throw new Error(COMMAND_IMPORT_HUMAN_ONLY);
return call("POST", "/api/skills/import", a);
});

addTool("cogitator_health", "État du serveur Cogitator (version, pi, sessions, base).", {}, () => call("GET", "/api/health"));

Expand Down
14 changes: 11 additions & 3 deletions src/owner-transport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { chmodSync, closeSync, existsSync, fstatSync, fsyncSync, lstatSync, open
import { request, type Server } from "node:http";
import { connect } from "node:net";
import { authPaths, checkPrivate, protectedRequired, validateOwnerSocketPath } from "./auth-state.js";
import { authenticationRequired, BASE_URL } from "./config.js";
import { authenticationRequired, BASE_URL, CONVERSATION_ID_HEADER } from "./config.js";
import { getPaths } from "./paths.js";
import { createPrivateServer } from "./server.js";

Expand Down Expand Up @@ -64,12 +64,20 @@ function removeOwnedFile(path: string, own: Stats | undefined): void {
}

/** Explicit URLs, including loopback overrides, always retain ordinary HTTP semantics. */
function ownerHeaders(env: NodeJS.ProcessEnv, withJson: boolean): Record<string, string> {
const headers: Record<string, string> = {};
if (withJson) headers["content-type"] = "application/json";
const conversationId = env.COGITATOR_CONVERSATION_ID;
if (conversationId) headers[CONVERSATION_ID_HEADER] = conversationId;
return headers;
}

export async function ownerRequest<T>(method: string, path: string, body?: unknown, env: NodeJS.ProcessEnv = process.env): Promise<T> {
const home = getPaths(env).home;
const required = authenticationRequired(env);
if (env.COGITATOR_URL !== undefined || !protectedRequired(home, required)) {
const response = await fetch(`${env.COGITATOR_URL ?? BASE_URL}${path}`, { method,
...(body !== undefined ? { headers: { "content-type": "application/json" }, body: JSON.stringify(body) } : {}) });
...(body !== undefined ? { headers: ownerHeaders(env, true), body: JSON.stringify(body) } : { headers: ownerHeaders(env, false) }) });
const data = await response.json() as Record<string, unknown>;
if (!response.ok) throw new Error(typeof data.error === "string" ? data.error : `HTTP ${response.status}`);
return data as T;
Expand All @@ -80,7 +88,7 @@ export async function ownerRequest<T>(method: string, path: string, body?: unkno
const s = lstatSync(socket);
if (!s.isSocket() || (s.mode & 0o077) || (process.getuid && s.uid !== process.getuid())) throw new Error("Unsafe owner socket");
return new Promise<T>((done, reject) => {
const req = request({ socketPath: socket, method, path, headers: { "content-type": "application/json" }, timeout: 30_000 }, res => {
const req = request({ socketPath: socket, method, path, headers: ownerHeaders(env, true), timeout: 30_000 }, res => {
const chunks: Buffer[] = [];
res.on("data", chunk => chunks.push(Buffer.from(chunk)));
res.on("error", reject);
Expand Down
22 changes: 19 additions & 3 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ import {
listCards, createCardGh, updateCardGh, moveCardGh, addCommentGh, closeCardGh,
type BoardCard, type CardWrite,
} from "./board.js";
import { importSkills } from "./skills-import.js";
import { COMMAND_IMPORT_HUMAN_ONLY, importSkills, skillCommandSource } from "./skills-import.js";
import {
agentInputSchema, conversationCreateSchema, groupCreateSchema, messageSchema, modelSwitchSchema,
providerLoginReplySchema, providerLoginSchema, providerUpsertSchema, scheduleCreateSchema, scheduleUpdateSchema, skillImportSchema,
Expand Down Expand Up @@ -155,6 +155,19 @@ function sendJson(res: ServerResponse, status: number, body: unknown): void {
res.end(JSON.stringify(body));
}

/** Commande npm/npx : uniquement une requête navigateur (Origin = Host), jamais le canal agent. */
function isHumanUiRequest(req: IncomingMessage): boolean {
if (privateRequests.has(req)) return false;
const origin = req.headers.origin;
const host = req.headers.host;
if (typeof origin !== "string" || !origin || typeof host !== "string") return false;
try {
return new URL(origin).host === host;
} catch {
return false;
}
}

/** Répond 404 et renvoie null — garde d'existence commune à toutes les routes paramétrées. */
function notFound(res: ServerResponse, what: string): null {
sendJson(res, 404, { error: `${what} introuvable` });
Expand Down Expand Up @@ -456,13 +469,16 @@ function registryRoutes(deps: Deps): Route[] {
["POST", "/api/skills/import", async (ctx) => {
const b = parseBody(ctx.res, skillImportSchema, ctx.body);
if (!b) return;
const command = skillCommandSource(b.source);
// Mode distant : les imports par commande hôte (npx/npm) sont désactivés
// (Plan 0002 §4 : pas d'import npm/npx côté hôte en mode distant).
if (enrollmentPolicyFromEnv().remote && /^npx\s|^npm\s/.test(b.source.trim())) {
if (command && enrollmentPolicyFromEnv().remote) {
return sendJson(ctx.res, 400, { error: "import par commande (npx/npm) désactivé en mode distant" });
}
const allowCommand = command && isHumanUiRequest(ctx.req);
if (command && !allowCommand) return sendJson(ctx.res, 400, { error: COMMAND_IMPORT_HUMAN_ONLY });
const destRoot = paths.skillsDirs[0] ?? join(paths.piAgentDir, "skills");
const result = await importSkills(b.source, destRoot, b.overwrite === true);
const result = await importSkills(b.source, destRoot, b.overwrite === true, allowCommand);
if (result.error && result.imported.length === 0) return sendJson(ctx.res, 400, { error: result.error });
sendJson(ctx.res, 200, { ...result, dest: destRoot, skills: listSkills(paths) });
}],
Expand Down
42 changes: 37 additions & 5 deletions src/skills-import.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { checkRequestAuthorization } from "./request-authorization.js";
import { AuthError } from "./native-auth.js";
import { execFile } from "node:child_process";
import { cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, statSync, writeFileSync, realpathSync, renameSync } from "node:fs";
import { cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, rmSync, statSync, writeFileSync, realpathSync, renameSync } from "node:fs";
import { tmpdir } from "node:os";
import { basename, join, resolve, sep } from "node:path";

Expand All @@ -19,6 +19,31 @@ const CLI_MAX_BUFFER = 5 * 1024 * 1024;
const CLI_TIMEOUT_MS = 180_000;
const CLI_OUTPUT_TAIL_LINES = 3;

export const COMMAND_IMPORT_HUMAN_ONLY =
"import par commande réservé à une action humaine dans l'interface";

/** True si la source est une commande npm/npx (pas un chemin ni un dépôt). */
export function skillCommandSource(source: string): boolean {
return /^npx\s|^npm\s/.test(source.trim());
}

function assertNoSymlinks(root: string): void {
const stack = [root];
while (stack.length) {
const dir = stack.pop()!;
for (const name of readdirSync(dir)) {
const path = join(dir, name);
const st = lstatSync(path);
if (st.isSymbolicLink()) throw new Error("lien symbolique refusé à l'extraction");
if (st.isDirectory()) stack.push(path);
}
}
}

function cliArgsWithoutScriptToggle(tokens: string[]): string[] {
return tokens.filter((token) => token !== "--ignore-scripts" && !token.startsWith("--ignore-scripts="));
}

/** Nom de dossier sûr pour un skill (kebab-case, pas de traversal). */
export function sanitizeSkillName(name: string): string {
const clean = basename(name).replace(/[^a-zA-Z0-9-_]+/g, "-").replace(/^-+|-+$/g, "");
Expand Down Expand Up @@ -63,8 +88,10 @@ export function importFromDir(srcDir: string, destRoot: string, overwrite = fals
result.skipped.push(name);
continue;
}
assertNoSymlinks(dir);
const stage = mkdtempSync(join(destRoot, ".import-"));
cpSync(dir, stage, { recursive: true });
assertNoSymlinks(stage);
if (existsSync(target)) renameSync(target, `${stage}.previous-${name}`);
renameSync(stage, target);
result.imported.push(name);
Expand Down Expand Up @@ -111,6 +138,7 @@ export async function importFromGitHub(source: string, destRoot: string, overwri
await new Promise<void>((resolve, reject) => {
execFile("tar", ["-xzf", tgz, "-C", extractDir], (err) => (err ? reject(err) : resolve()));
});
assertNoSymlinks(extractDir);
const roots = readdirSync(extractDir).filter((e) => statSync(join(extractDir, e)).isDirectory());
if (roots.length === 0) return { imported: [], skipped: [], error: "tarball vide" };
return importFromDir(join(extractDir, roots[0]!), destRoot, overwrite);
Expand All @@ -122,9 +150,10 @@ export async function importFromGitHub(source: string, destRoot: string, overwri
}
}

/** Point d'entrée unique : URL GitHub, chemin local, ou commande npx/npm. */
export function importSkills(source: string, destRoot: string, overwrite = false): Promise<ImportResult> {
if (/^npx\s|^npm\s/.test(source.trim())) {
/** Point d'entrée unique : URL GitHub, chemin local, ou commande npx/npm (si allowCommand). */
export function importSkills(source: string, destRoot: string, overwrite = false, allowCommand = false): Promise<ImportResult> {
if (skillCommandSource(source)) {
if (!allowCommand) return Promise.resolve({ imported: [], skipped: [], error: COMMAND_IMPORT_HUMAN_ONLY });
return runSkillCommand(source.trim(), [destRoot]);
}
if (/^(https?:\/\/github\.com\/|git@github\.com:|[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+?$)/.test(source.trim()) && !existsSync(source)) {
Expand All @@ -148,6 +177,7 @@ export async function runSkillCommand(cmd: string, destRoots: string[], timeoutM
if (bin !== "npx" && bin !== "npm") {
return { imported: [], skipped: [], error: "seuls npx et npm sont autorisés comme commande d'import" };
}
const args = [...cliArgsWithoutScriptToggle(tokens.slice(1)), "--ignore-scripts"];
const snapshot = new Set<string>();
for (const root of destRoots) {
for (const dir of scanSkillDirs(root)) snapshot.add(sanitizeSkillName(basename(dir)));
Expand All @@ -156,7 +186,9 @@ export async function runSkillCommand(cmd: string, destRoots: string[], timeoutM
try {
const { stdout, stderr } = await new Promise<{ stdout: string; stderr: string }>((resolve) => {
// certains CLI renvoient un code non nul tout en ayant installé : on garde la sortie
execFile(bin, tokens.slice(1), { timeout: timeoutMs, maxBuffer: CLI_MAX_BUFFER }, (_err, out, serr) => {
const cwd = destRoots[0];
if (cwd) mkdirSync(cwd, { recursive: true });
execFile(bin, args, { timeout: timeoutMs, maxBuffer: CLI_MAX_BUFFER, cwd, env: { ...process.env, npm_config_ignore_scripts: "true" } }, (_err, out, serr) => {
resolve({ stdout: String(out), stderr: String(serr) });
});
});
Expand Down
5 changes: 3 additions & 2 deletions src/spawn.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { mkdirSync, writeFileSync } from "node:fs";
import { chmodSync, mkdirSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import type { McpServerEntry } from "./mcp-env.js";

Expand Down Expand Up @@ -52,7 +52,8 @@ export function buildArgs(c: SpawnConfig, tmpDir: string, convId: string): strin
const systemPrompt = [c.systemPrompt, c.uiInstructions].filter(Boolean).join("\n\n");
if (systemPrompt) {
const file = join(tmpDir, `${convId}.prompt.md`);
writeFileSync(file, systemPrompt);
writeFileSync(file, systemPrompt, { mode: 0o600 });
chmodSync(file, 0o600);
args.push("--append-system-prompt", file);
}
if (c.skills?.length) {
Expand Down
Loading