feat(FN-1190): add agent export for Agent Companies packages
- Add a core exporter that generates COMPANY.md, per-agent AGENTS.md files, and optional SKILL.md stubs with stable slug/link handling - Export new Agent Companies exporter APIs from @fusion/core and extend manifest kinds to include skill entries - Add fn agent export with project-aware agent loading, optional company metadata flags, and export summary/error output - Add POST /api/agents/export route with request validation, agent ID filtering, custom/default output directory support, and exporter integration - Add focused tests for core exporter behavior, CLI export command, and dashboard route handling
This commit is contained in:
152
packages/dashboard/src/__tests__/routes-agent-export.test.ts
Normal file
152
packages/dashboard/src/__tests__/routes-agent-export.test.ts
Normal file
@@ -0,0 +1,152 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import { EventEmitter } from "node:events";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
|
||||
import { request } from "../test-request.js";
|
||||
|
||||
const mockInit = vi.fn().mockResolvedValue(undefined);
|
||||
const mockListAgents = vi.fn().mockResolvedValue([]);
|
||||
const mockExportAgentsToDirectory = vi.fn();
|
||||
|
||||
vi.mock("@fusion/core", () => {
|
||||
return {
|
||||
AgentStore: class MockAgentStore {
|
||||
init = mockInit;
|
||||
listAgents = mockListAgents;
|
||||
},
|
||||
exportAgentsToDirectory: (...args: unknown[]) => mockExportAgentsToDirectory(...args),
|
||||
};
|
||||
});
|
||||
|
||||
class MockStore extends EventEmitter {
|
||||
getRootDir(): string {
|
||||
return "/tmp/fn-1190-test";
|
||||
}
|
||||
|
||||
getFusionDir(): string {
|
||||
return "/tmp/fn-1190-test/.fusion";
|
||||
}
|
||||
|
||||
getDatabase() {
|
||||
return {
|
||||
exec: vi.fn(),
|
||||
prepare: vi.fn().mockReturnValue({
|
||||
run: vi.fn().mockReturnValue({ changes: 0 }),
|
||||
get: vi.fn(),
|
||||
all: vi.fn().mockReturnValue([]),
|
||||
}),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async function postExport(app: Parameters<typeof request>[0], body: unknown) {
|
||||
return request(app, "POST", "/api/agents/export", JSON.stringify(body), {
|
||||
"content-type": "application/json",
|
||||
});
|
||||
}
|
||||
|
||||
describe("POST /api/agents/export", () => {
|
||||
let store: MockStore;
|
||||
let app: ReturnType<typeof import("../server.js").createServer>;
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
testDir = mkdtempSync(join(tmpdir(), "kb-agent-export-route-"));
|
||||
|
||||
mockInit.mockResolvedValue(undefined);
|
||||
mockListAgents.mockResolvedValue([
|
||||
{
|
||||
id: "agent-1",
|
||||
name: "CEO",
|
||||
role: "executor",
|
||||
state: "idle",
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
metadata: {},
|
||||
},
|
||||
{
|
||||
id: "agent-2",
|
||||
name: "Reviewer",
|
||||
role: "reviewer",
|
||||
state: "idle",
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
metadata: {},
|
||||
},
|
||||
]);
|
||||
|
||||
mockExportAgentsToDirectory.mockResolvedValue({
|
||||
outputDir: join(testDir, "export"),
|
||||
agentsExported: 2,
|
||||
skillsExported: 1,
|
||||
filesWritten: [join(testDir, "export", "COMPANY.md")],
|
||||
errors: [],
|
||||
});
|
||||
|
||||
store = new MockStore();
|
||||
const { createServer } = await import("../server.js");
|
||||
app = createServer(store as any);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
rmSync(testDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("exports all agents when agentIds is omitted", async () => {
|
||||
const response = await postExport(app, {});
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(mockExportAgentsToDirectory).toHaveBeenCalledTimes(1);
|
||||
const [agentsArg, outputDirArg] = mockExportAgentsToDirectory.mock.calls[0] ?? [];
|
||||
expect(agentsArg).toHaveLength(2);
|
||||
expect(typeof outputDirArg).toBe("string");
|
||||
|
||||
const body = response.body as any;
|
||||
expect(body.agentsExported).toBe(2);
|
||||
expect(body.skillsExported).toBe(1);
|
||||
});
|
||||
|
||||
it("exports only requested agent IDs", async () => {
|
||||
const response = await postExport(app, { agentIds: ["agent-2"] });
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
const [agentsArg] = mockExportAgentsToDirectory.mock.calls[0] ?? [];
|
||||
expect(agentsArg).toHaveLength(1);
|
||||
expect(agentsArg[0]?.id).toBe("agent-2");
|
||||
});
|
||||
|
||||
it("passes custom company options and output directory", async () => {
|
||||
const customOutputDir = join(testDir, "custom-output");
|
||||
|
||||
const response = await postExport(app, {
|
||||
companyName: "Acme AI",
|
||||
companySlug: "acme-ai",
|
||||
outputDir: customOutputDir,
|
||||
});
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
const [, outputDirArg, optionsArg] = mockExportAgentsToDirectory.mock.calls[0] ?? [];
|
||||
expect(outputDirArg).toBe(customOutputDir);
|
||||
expect(optionsArg).toEqual({ companyName: "Acme AI", companySlug: "acme-ai" });
|
||||
});
|
||||
|
||||
it("returns 400 when no agents are available", async () => {
|
||||
mockListAgents.mockResolvedValue([]);
|
||||
|
||||
const response = await postExport(app, {});
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect((response.body as any).error).toContain("No agents found to export");
|
||||
});
|
||||
|
||||
it("returns 400 for invalid outputDir type", async () => {
|
||||
const response = await postExport(app, { outputDir: 123 });
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect((response.body as any).error).toContain("outputDir must be a string");
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,10 @@
|
||||
import { Router, type Request, type Response, type NextFunction } from "express";
|
||||
import multer from "multer";
|
||||
import { createReadStream, existsSync } from "node:fs";
|
||||
import { mkdtemp } from "node:fs/promises";
|
||||
import { execSync } from "node:child_process";
|
||||
import { resolve, sep, join } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
import * as nodeFs from "node:fs";
|
||||
import * as nodeChildProcess from "node:child_process";
|
||||
import type { TaskStore, Column, MergeResult, ScheduleType, ActivityEventType, ModelPreset, AutomationStep, MessageType, ParticipantType, MessageCreateInput } from "@fusion/core";
|
||||
@@ -7527,6 +7529,75 @@ Output ONLY the prompt text (no markdown, no explanations).`;
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /api/agents/export
|
||||
* Export agents to an Agent Companies package directory.
|
||||
*
|
||||
* Body:
|
||||
* - { agentIds?: string[]; companyName?: string; companySlug?: string; outputDir?: string }
|
||||
*/
|
||||
router.post("/agents/export", async (req, res) => {
|
||||
try {
|
||||
const { agentIds, companyName, companySlug, outputDir } = req.body ?? {};
|
||||
|
||||
if (agentIds !== undefined) {
|
||||
if (!Array.isArray(agentIds)) {
|
||||
throw badRequest("agentIds must be an array of strings");
|
||||
}
|
||||
if (agentIds.some((id: unknown) => typeof id !== "string" || id.trim().length === 0)) {
|
||||
throw badRequest("agentIds must contain non-empty strings");
|
||||
}
|
||||
}
|
||||
|
||||
if (companyName !== undefined && typeof companyName !== "string") {
|
||||
throw badRequest("companyName must be a string");
|
||||
}
|
||||
if (companySlug !== undefined && typeof companySlug !== "string") {
|
||||
throw badRequest("companySlug must be a string");
|
||||
}
|
||||
if (outputDir !== undefined && typeof outputDir !== "string") {
|
||||
throw badRequest("outputDir must be a string");
|
||||
}
|
||||
|
||||
const scopedStore = await getScopedStore(req);
|
||||
const { AgentStore, exportAgentsToDirectory } = await import("@fusion/core");
|
||||
|
||||
const agentStore = new AgentStore({ rootDir: scopedStore.getFusionDir() });
|
||||
await agentStore.init();
|
||||
|
||||
const allAgents = await agentStore.listAgents();
|
||||
const requestedIds = Array.isArray(agentIds) ? [...new Set(agentIds.map((id) => id.trim()))] : [];
|
||||
const agentsToExport = requestedIds.length > 0
|
||||
? allAgents.filter((agent: any) => requestedIds.includes(agent.id))
|
||||
: allAgents;
|
||||
|
||||
if (agentsToExport.length === 0) {
|
||||
throw badRequest("No agents found to export");
|
||||
}
|
||||
|
||||
let resolvedOutputDir: string;
|
||||
if (typeof outputDir === "string" && outputDir.trim().length > 0) {
|
||||
resolvedOutputDir = resolve(outputDir.trim());
|
||||
} else if (typeof outputDir === "string") {
|
||||
throw badRequest("outputDir cannot be empty");
|
||||
} else {
|
||||
resolvedOutputDir = await mkdtemp(join(tmpdir(), "fusion-agent-export-"));
|
||||
}
|
||||
|
||||
const result = await exportAgentsToDirectory(agentsToExport, resolvedOutputDir, {
|
||||
companyName: typeof companyName === "string" ? companyName : undefined,
|
||||
companySlug: typeof companySlug === "string" ? companySlug : undefined,
|
||||
});
|
||||
|
||||
res.json(result);
|
||||
} catch (err: any) {
|
||||
if (err instanceof ApiError) {
|
||||
throw err;
|
||||
}
|
||||
rethrowAsApiError(err);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /api/agents/import
|
||||
* Import agents from Agent Companies sources.
|
||||
|
||||
Reference in New Issue
Block a user