Files
AgentCompany/AgentCompany-New/tests/integration/autonomous-run.test.ts
T
ZacharyZhang-NY 0575712e02 Run the CEO agent autonomously with a real tool-use loop
The new app reached a real LLM but never ran an agent: the kickoff task_run
sat queued forever and runTask was a single text completion with no tools.

This adds the missing runtime:
- provider-tool-turn: OpenAI Responses + Anthropic Messages tool-use turns
- agent-tools + deliverable-writer: hire_agent, create_task,
  update_task_status, write_deliverable (workspace-scoped, traversal-safe)
- agent-run-loop: real tool-use loop, capped iterations
- task-queue-worker: claims queued runs in a transaction and executes them

task-execution now drives the loop; a background worker auto-runs the
bootstrap CEO run so it hires its team, delegates tasks, and writes the first
deliverable into the bound workspace. Autonomy is gated by AGENTCOMPANY_NEW_AUTORUN
(tests run with it off to stay hermetic).
2026-05-29 21:08:04 -04:00

102 lines
4.8 KiB
TypeScript

import { existsSync, mkdirSync, readFileSync } from "node:fs";
import { randomUUID } from "node:crypto";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, test } from "vitest";
import { DatabaseConnection } from "../../src/main/database/connection";
import { OnboardingService } from "../../src/main/services/onboarding-service";
import { ProviderService } from "../../src/main/services/provider-service";
import { providerAdapters } from "../../src/main/services/provider-adapters";
import { TaskExecutionService } from "../../src/main/services/task-execution-service";
import { SnapshotService } from "../../src/main/services/snapshot-service";
import { claimNextQueuedRun } from "../../src/main/app/task-queue-worker";
import type { AgentTurnResult, ProviderToolTurnInput, ToolCall } from "../../src/main/services/provider-tool-turn";
const testVault = {
encryptSecret: (secret: string) => Buffer.from(secret, "utf8"),
decryptSecret: (ciphertext: Buffer) => ciphertext.toString("utf8"),
};
function call(name: string, args: Record<string, unknown>): ToolCall {
return { id: `call_${randomUUID()}`, name, arguments: args };
}
/** Scripts the CEO: staff two reports, delegate a task, write the plan, then stop. */
function scriptedCeo(): (input: ProviderToolTurnInput) => Promise<AgentTurnResult> {
const script: Array<{ text: string; toolCalls: ToolCall[] }> = [
{ text: "Staffing.", toolCalls: [
call("hire_agent", { name: "Mara Quinn", role: "Growth Marketer", department: "Marketing" }),
call("hire_agent", { name: "Owen Diaz", role: "Operations Lead", department: "Operations" }),
] },
{ text: "Delegating.", toolCalls: [
call("create_task", { title: "Launch the booking site", description: "Ship landing + booking flow.", assignee_agent_name: "Mara Quinn" }),
] },
{ text: "Writing the plan.", toolCalls: [
call("write_deliverable", { path: "plan/operating-plan.md", content: "# OrbitOps Operating Plan\n\n- Validate demand\n- Launch booking site\n" }),
] },
{ text: "Team staffed, work delegated, plan written.", toolCalls: [] },
];
let index = 0;
return async () => {
const turn = script[index] ?? { text: "done", toolCalls: [] };
index += 1;
return { text: turn.text, toolCalls: turn.toolCalls, rawResponseJson: JSON.stringify({ id: `resp_${index}` }) };
};
}
describe("autonomous bootstrap run", () => {
test("the queued kickoff run autonomously hires, delegates, and writes a deliverable", async () => {
const connection = new DatabaseConnection(join(tmpdir(), `ac-auto-${randomUUID()}.db`));
const workspacePath = join(tmpdir(), `ac-auto-ws-${randomUUID()}`);
mkdirSync(workspacePath, { recursive: true });
const providers = new ProviderService(connection.db, providerAdapters, testVault, undefined, scriptedCeo());
const onboarding = new OnboardingService({ db: connection.db, saveProviderCredential: (input) => providers.saveCredential(input) });
const snapshot = new SnapshotService(connection.db);
let orgId = "";
connection.transaction(() => {
const summary = onboarding.bootstrap({
companyName: "OrbitOps AI",
companyDescription: "AI-run operations company.",
employeeName: "Yang",
workspacePath,
executionMode: "ai_ceo",
autoApproveHires: true,
reviewDeliverables: false,
goalTitle: "Stand up a local service business in 30 days.",
goalDescription: "Validate the market and win the first paying customers.",
providerKey: "openai",
providerSecret: "sk-test-key",
providerModel: "gpt-5.4",
});
orgId = summary.orgId;
});
// The bootstrap created exactly one queued run; the worker claims it.
const claimed = claimNextQueuedRun(connection);
expect(claimed?.org_id).toBe(orgId);
expect(claimNextQueuedRun(connection)).toBeNull();
const taskExecution = new TaskExecutionService(connection.db, providers);
await taskExecution.executeRun(claimed!.org_id, claimed!.id);
const state = snapshot.load();
const agentNames = state.agents.filter((a) => a.orgId === orgId).map((a) => a.name).sort();
expect(agentNames).toEqual(["CEO", "Mara Quinn", "Owen Diaz"]);
const delegated = state.tasks.find((t) => t.orgId === orgId && t.title === "Launch the booking site");
expect(delegated).toBeTruthy();
const mara = state.agents.find((a) => a.orgId === orgId && a.name === "Mara Quinn");
expect(delegated?.assigneeAgentId).toBe(mara?.id);
const deliverable = join(workspacePath, "plan", "operating-plan.md");
expect(existsSync(deliverable)).toBe(true);
expect(readFileSync(deliverable, "utf8")).toContain("OrbitOps Operating Plan");
const run = state.taskRuns.find((r) => r.id === claimed!.id);
expect(run?.state).toBe("completed");
connection.close();
});
});