import assert from "node:assert/strict"; import { test } from "node:test"; import { listAgents, openHostedAgents, resolveAgent } from "../agents.ts"; import { failure } from "../models.ts"; import type { Policy } from "../policy.ts"; import { d1, migrated } from "./d1.ts"; const KEY = "sk-ant-api03-secret-value-1234"; const admin = { actor: { kind: "human", person: { id: "u1", name: "Aman", email: "a@x" }, via: "session" }, person: { id: "u1", name: "Aman", email: "a@x" } } as unknown as Policy; const input = { handle: "security", description: "Finds security holes.", instructions: "Look for injection.", provider: "", model: "", key: "" }; function setup(status = 200) { const sqlite = migrated(); sqlite.exec(`INSERT INTO namespaces (id, slug, name, kind, created_at) VALUES ('ns', 'refs', 'refs', 'org', 0); INSERT INTO users (id, email, name, password_hash, created_at) VALUES ('u1', 'a@x', 'Aman', '', 0); INSERT INTO repos (id, namespace_id, name, artifacts_name, default_branch, visibility, description, created_at, creator_id) VALUES ('r1', 'ns', 'source', 'a', 'main', 'private', '', 0, 'u1')`); const sent: { provider: string; headers: Record; query: Record }[] = []; const AI = { gateway: () => ({ run: async (request: (typeof sent)[number]) => { sent.push(request); return new Response(status === 200 ? JSON.stringify({ choices: [{ message: { content: "OK" } }] }) : JSON.stringify({ error: { message: `Incorrect API key provided: ${KEY}` } }), { status }); }, }), }; const env = { DB: d1(sqlite), AI, CI_SECRETS_KEY: btoa(String.fromCharCode(...new Uint8Array(32).fill(7))) } as unknown as Env; return { env, sqlite, sent }; } test("a repository agent replaces the shared and built-in agent of the same handle", async () => { const { env } = setup(); assert.equal((await openHostedAgents(env, admin, "ns", null, true).save({ ...input, handle: "reviewer", instructions: "Shared review rules." })).ok, true); assert.equal((await openHostedAgents(env, admin, "ns", "r1", true).save({ ...input, handle: "reviewer", instructions: "Repo review rules." })).ok, true); const list = (await listAgents(env.DB, "ns", "r1")).filter((agent) => agent.handle === "reviewer"); assert.deepEqual(list.map((agent) => [agent.scope, agent.handle, agent.replaced]), [["repo", "reviewer", false], ["namespace", "reviewer", true], ["builtin", "reviewer", true]]); assert.equal((await resolveAgent(env, "ns", "r1", "reviewer"))?.instructions, "Repo review rules."); assert.equal((await resolveAgent(env, "ns", "other", "reviewer"))?.instructions, "Shared review rules."); assert.equal(await resolveAgent(env, "ns", "r1", "nobody"), null); }); test("a working key is tested, sealed, kept on a later edit, and opened for runs", async () => { const { env, sqlite, sent } = setup(); const agents = openHostedAgents(env, admin, "ns", "r1", true); assert.equal((await agents.save({ ...input, provider: "anthropic", model: " claude-sonnet-5-5 ", key: KEY })).ok, true); assert.equal(sent[0].headers.authorization, `Bearer ${KEY}`); assert.ok(!JSON.stringify(sqlite.prepare("SELECT * FROM hosted_agents").all()).includes(KEY)); assert.equal((await agents.save({ ...input, description: "Changed.", provider: "anthropic", model: "claude-opus-5-5", key: "" })).ok, true); assert.deepEqual((await resolveAgent(env, "ns", "r1", "security"))?.choice, { provider: "anthropic", model: "claude-opus-5-5", key: KEY }); assert.deepEqual((await listAgents(env.DB, "ns", "r1"))[0].model, { provider: "anthropic", model: "claude-opus-5-5", keyHint: "1234" }); }); test("a rejected key is not stored and the error never shows the key", async () => { const { env, sqlite } = setup(400); const outcome = await openHostedAgents(env, admin, "ns", "r1", true).save({ ...input, provider: "openai", model: "gpt-5.5", key: KEY }); assert.ok(!outcome.ok && !outcome.problem.message.includes(KEY)); assert.equal(sqlite.prepare("SELECT count(*) AS n FROM hosted_agents").get()!.n, 0); }); test("only a person with edit rights changes agents, and bad input is refused before any request", async () => { const { env, sent } = setup(); assert.equal((await openHostedAgents(env, admin, "ns", "r1", false).save(input)).ok, false); const agent = { ...admin, actor: { kind: "agent" } } as unknown as Policy; assert.equal((await openHostedAgents(env, agent, "ns", "r1", true).save(input)).ok, false); const agents = openHostedAgents(env, admin, "ns", "r1", true); for (const bad of [{ handle: "Bad Name" }, { handle: "all" }, { instructions: " " }, { provider: "mistral", model: "x", key: KEY }, { provider: "openai", model: "has space", key: KEY }, { provider: "openai", model: "gpt-5.5", key: "" }]) { assert.equal((await agents.save({ ...input, ...bad })).ok, false, JSON.stringify(bad)); } assert.equal(sent.length, 0); }); test("provider errors name the problem without the key", () => { const choice = { provider: "openai", model: "gpt-5.5", key: KEY } as const; assert.equal(failure(choice, 401, KEY), "OpenAI rejected the API key."); assert.equal(failure(choice, 404, JSON.stringify({ error: { message: `model not found for ${KEY} and sk-proj-otherkey99` } })), "OpenAI returned 404: model not found for … and …"); });