diff --git a/packages/cli/src/commands/agent/archive.test.ts b/packages/cli/src/commands/agent/archive.test.ts new file mode 100644 index 000000000..de9f6fe68 --- /dev/null +++ b/packages/cli/src/commands/agent/archive.test.ts @@ -0,0 +1,139 @@ +import { describe, expect, it } from "vitest"; +import type { AgentSnapshotPayload } from "@getpaseo/protocol/messages"; +import { archiveAgent, type AgentArchiveClient } from "./archive.js"; +import { reloadAgent, type AgentReloadClient } from "./reload.js"; +import { detachAgent, type AgentDetachClient } from "./detach.js"; + +function makeAgent( + id: string, + overrides: Partial = {}, +): AgentSnapshotPayload { + return { + id, + title: null, + status: "closed", + archivedAt: null, + ...overrides, + } as AgentSnapshotPayload; +} + +class FakeAgentClient implements AgentArchiveClient, AgentReloadClient, AgentDetachClient { + readonly archived: string[] = []; + readonly refreshed: string[] = []; + readonly detached: string[] = []; + readonly fetchAgentCalls: string[] = []; + fetchAgentError: Error | null = null; + closed = false; + + constructor( + private readonly listed: AgentSnapshotPayload[], + private readonly stored: AgentSnapshotPayload[] = listed, + ) {} + + async fetchAgents() { + return { entries: this.listed.map((agent) => ({ agent })), pageInfo: { nextCursor: null } }; + } + + async fetchAgent({ agentId }: { agentId: string }) { + this.fetchAgentCalls.push(agentId); + if (this.fetchAgentError) throw this.fetchAgentError; + const found = + this.stored.find((e) => e.id === agentId) ?? + this.stored.find((e) => e.id.startsWith(agentId)) ?? + this.stored.find((e) => e.title === agentId); + return found ? { agent: found } : null; + } + + async archiveAgent(agentId: string) { + this.archived.push(agentId); + return { archivedAt: "2026-11-15T00:00:00.000Z" }; + } + + async refreshAgent(agentId: string) { + this.refreshed.push(agentId); + return { agentId, timelineSize: 3 }; + } + + async detachAgent(agentId: string) { + this.detached.push(agentId); + } + + async close() { + this.closed = true; + } +} + +describe("unlisted agent resolution", () => { + const unlistedId = "9eac296c-4d60-4189-a0b5-ae71dd9c6ad9"; + const otherId = "c9a97e5d-4a92-4646-a016-53032146d0a1"; + + it("archives an unlisted agent via fetchAgent without title collision", async () => { + const unlisted = makeAgent(unlistedId, { title: "orphaned agent" }); + const other = makeAgent(otherId, { title: `worker ${unlistedId}` }); + const client = new FakeAgentClient([other], [other, unlisted]); + const result = await archiveAgent(unlistedId.toUpperCase(), {}, async () => client); + expect(result.data).toEqual({ + agentId: unlistedId, + status: "archived", + archivedAt: "2026-11-15T00:00:00.000Z", + }); + expect(client.fetchAgentCalls).toEqual([unlistedId]); + expect(client.archived).toEqual([unlistedId]); + expect(client.closed).toBe(true); + }); + + it("enforces archived and running checks on fetched unlisted agents", async () => { + const archivedClient = new FakeAgentClient( + [], + [makeAgent(unlistedId, { archivedAt: "2026-11-14T10:00:00.000Z" })], + ); + await expect(archiveAgent(unlistedId, {}, async () => archivedClient)).rejects.toMatchObject({ + code: "AGENT_ALREADY_ARCHIVED", + }); + const runningClient = new FakeAgentClient([], [makeAgent(unlistedId, { status: "running" })]); + await expect(archiveAgent(unlistedId, {}, async () => runningClient)).rejects.toMatchObject({ + code: "AGENT_RUNNING", + }); + }); + + it("reloads and detaches unlisted agents via fetchAgent fallback", async () => { + const unlisted = makeAgent(unlistedId, { title: "orphaned agent" }); + const reloadClient = new FakeAgentClient([], [unlisted]); + const detachClient = new FakeAgentClient([], [unlisted]); + expect((await reloadAgent(unlistedId, {}, async () => reloadClient)).data).toEqual({ + agentId: unlistedId, + status: "reloaded", + timelineSize: 3, + }); + expect((await detachAgent(unlistedId, {}, async () => detachClient)).data).toEqual({ + agentId: unlistedId, + status: "detached", + }); + }); + + it("does not accept another agent the daemon matched by title for a missing full id", async () => { + const titled = makeAgent(otherId, { title: unlistedId }); + const client = new FakeAgentClient([], [titled]); + await expect(archiveAgent(unlistedId, {}, async () => client)).rejects.toMatchObject({ + code: "AGENT_NOT_FOUND", + }); + expect(client.archived).toEqual([]); + }); + + it("throws AGENT_NOT_FOUND when missing and propagates lookup errors", async () => { + await expect( + archiveAgent(unlistedId, {}, async () => new FakeAgentClient([], [])), + ).rejects.toMatchObject({ + code: "AGENT_NOT_FOUND", + }); + const failingClient = new FakeAgentClient([], []); + failingClient.fetchAgentError = new Error('Agent identifier "9eac" is ambiguous'); + await expect(archiveAgent("9eac", {}, async () => failingClient)).rejects.toMatchObject({ + code: "ARCHIVE_FAILED", + }); + await expect(detachAgent("9eac", {}, async () => failingClient)).rejects.toMatchObject({ + code: "DETACH_FAILED", + message: 'Failed to detach agent: Agent identifier "9eac" is ambiguous', + }); + }); +}); diff --git a/packages/cli/src/commands/agent/archive.ts b/packages/cli/src/commands/agent/archive.ts index 382cd193c..c8e60f503 100644 --- a/packages/cli/src/commands/agent/archive.ts +++ b/packages/cli/src/commands/agent/archive.ts @@ -1,6 +1,6 @@ import { Command } from "commander"; -import { connectToDaemon, resolveAgentId } from "../../utils/client.js"; -import { fetchAllAgents } from "../../utils/agent-directory.js"; +import { connectToDaemon } from "../../utils/client.js"; +import { resolveAgentEntry, type AgentLookupClient } from "../../utils/agent-directory.js"; import type { CommandOptions, SingleResult, @@ -39,10 +39,25 @@ export interface AgentArchiveOptions extends CommandOptions { export type AgentArchiveCommandResult = SingleResult; +export interface AgentArchiveClient extends AgentLookupClient { + archiveAgent(agentId: string): Promise<{ archivedAt: string }>; + close(): Promise; +} + export async function runArchiveCommand( agentIdArg: string, options: AgentArchiveOptions, _command: Command, +): Promise { + return archiveAgent(agentIdArg, options); +} + +export async function archiveAgent( + agentIdArg: string, + options: AgentArchiveOptions, + connect: ( + options: Parameters[0], + ) => Promise = connectToDaemon, ): Promise { // Validate arguments if (!agentIdArg || agentIdArg.trim().length === 0) { @@ -54,12 +69,11 @@ export async function runArchiveCommand( throw error; } - const client = await connectToDaemon({ target: options.daemonTarget }); + const client = await connect({ target: options.daemonTarget }); try { - const agents = await fetchAllAgents(client, { filter: { includeArchived: true } }); - const agentId = resolveAgentId(agentIdArg, agents); - if (!agentId) { + const agent = await resolveAgentEntry(client, agentIdArg); + if (!agent) { const error: CommandError = { code: "AGENT_NOT_FOUND", message: `Agent not found: ${agentIdArg}`, @@ -67,10 +81,7 @@ export async function runArchiveCommand( }; throw error; } - const agent = agents.find((entry) => entry.id === agentId); - if (!agent) { - throw new Error(`Resolved agent missing from fetched agents: ${agentId}`); - } + const agentId = agent.id; // Check if agent is already archived if (agent.archivedAt) { diff --git a/packages/cli/src/commands/agent/detach.ts b/packages/cli/src/commands/agent/detach.ts index 9de223dff..8bf41efd0 100644 --- a/packages/cli/src/commands/agent/detach.ts +++ b/packages/cli/src/commands/agent/detach.ts @@ -1,5 +1,6 @@ import type { Command } from "commander"; -import { connectToDaemon, resolveAgentId } from "../../utils/client.js"; +import { connectToDaemon } from "../../utils/client.js"; +import { resolveAgentEntry, type AgentLookupClient } from "../../utils/agent-directory.js"; import type { CommandError, CommandOptions, @@ -20,27 +21,51 @@ const detachSchema: OutputSchema = { ], }; +export interface AgentDetachClient extends AgentLookupClient { + detachAgent(agentId: string): Promise; + close(): Promise; +} + export async function runDetachCommand( agentIdArg: string, options: CommandOptions, _command: Command, ): Promise> { - const client = await connectToDaemon({ target: options.daemonTarget }); + return detachAgent(agentIdArg, options); +} + +export async function detachAgent( + agentIdArg: string, + options: CommandOptions, + connect: ( + options: Parameters[0], + ) => Promise = connectToDaemon, +): Promise> { + const client = await connect({ target: options.daemonTarget }); try { - const payload = await client.fetchAgents({ filter: { includeArchived: true } }); - const agentId = resolveAgentId( - agentIdArg, - payload.entries.map((entry) => entry.agent), - ); - if (!agentId) { + const agent = await resolveAgentEntry(client, agentIdArg); + if (!agent) { throw { code: "AGENT_NOT_FOUND", message: `Agent not found: ${agentIdArg}`, } satisfies CommandError; } - await client.detachAgent(agentId); - return { type: "single", data: { agentId, status: "detached" }, schema: detachSchema }; + await client.detachAgent(agent.id); + return { + type: "single", + data: { agentId: agent.id, status: "detached" }, + schema: detachSchema, + }; + } catch (err) { + if (err && typeof err === "object" && "code" in err) { + throw err; + } + const message = err instanceof Error ? err.message : String(err); + throw { + code: "DETACH_FAILED", + message: `Failed to detach agent: ${message}`, + } satisfies CommandError; } finally { await client.close().catch(() => undefined); } diff --git a/packages/cli/src/commands/agent/reload.ts b/packages/cli/src/commands/agent/reload.ts index f6cda480e..73b5947a6 100644 --- a/packages/cli/src/commands/agent/reload.ts +++ b/packages/cli/src/commands/agent/reload.ts @@ -1,5 +1,6 @@ import { Command } from "commander"; -import { connectToDaemon, resolveAgentId } from "../../utils/client.js"; +import { connectToDaemon } from "../../utils/client.js"; +import { resolveAgentEntry, type AgentLookupClient } from "../../utils/agent-directory.js"; import type { CommandOptions, SingleResult, @@ -34,10 +35,25 @@ export interface AgentReloadOptions extends CommandOptions { export type AgentReloadCommandResult = SingleResult; +export interface AgentReloadClient extends AgentLookupClient { + refreshAgent(agentId: string): Promise<{ agentId: string; timelineSize?: number }>; + close(): Promise; +} + export async function runReloadCommand( agentIdArg: string, options: AgentReloadOptions, _command: Command, +): Promise { + return reloadAgent(agentIdArg, options); +} + +export async function reloadAgent( + agentIdArg: string, + options: AgentReloadOptions, + connect: ( + options: Parameters[0], + ) => Promise = connectToDaemon, ): Promise { if (!agentIdArg || agentIdArg.trim().length === 0) { const error: CommandError = { @@ -48,13 +64,11 @@ export async function runReloadCommand( throw error; } - const client = await connectToDaemon({ target: options.daemonTarget }); + const client = await connect({ target: options.daemonTarget }); try { - const agentsPayload = await client.fetchAgents({ filter: { includeArchived: true } }); - const agents = agentsPayload.entries.map((entry) => entry.agent); - const agentId = resolveAgentId(agentIdArg, agents); - if (!agentId) { + const agent = await resolveAgentEntry(client, agentIdArg); + if (!agent) { const error: CommandError = { code: "AGENT_NOT_FOUND", message: `Agent not found: ${agentIdArg}`, @@ -63,7 +77,7 @@ export async function runReloadCommand( throw error; } - const result = await client.refreshAgent(agentId); + const result = await client.refreshAgent(agent.id); await client.close(); diff --git a/packages/cli/src/utils/agent-directory.ts b/packages/cli/src/utils/agent-directory.ts index 553121320..106850521 100644 --- a/packages/cli/src/utils/agent-directory.ts +++ b/packages/cli/src/utils/agent-directory.ts @@ -1,17 +1,24 @@ import type { AgentSnapshotPayload } from "@getpaseo/protocol/messages"; -import type { connectToDaemon } from "./client.js"; +import { resolveAgentId, type connectToDaemon } from "./client.js"; -type FetchAgentsOptions = NonNullable< - Parameters>["fetchAgents"]>[0] ->; +type DaemonClient = Awaited>; +type FetchAgentsOptions = NonNullable[0]>; -interface AgentDirectoryClient { +export interface AgentDirectoryClient { fetchAgents(options?: FetchAgentsOptions): Promise<{ entries: { agent: AgentSnapshotPayload }[]; pageInfo: { nextCursor: string | null }; }>; } +export interface AgentLookupClient extends AgentDirectoryClient { + fetchAgent(options: { agentId: string }): Promise<{ + agent: AgentSnapshotPayload; + } | null>; +} + +const FULL_AGENT_UUID_PATTERN = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i; + /** Read the complete directory without agents moving between pages as they update. */ export async function fetchAllAgents( client: AgentDirectoryClient, @@ -31,3 +38,37 @@ export async function fetchAllAgents( } while (cursor); return agents; } + +/** + * Resolve an agent by ID, prefix, or name from the directory, falling back to + * `fetch_agent` for agents omitted from `fetch_agents` (for example after their + * workspace or project was deleted). + */ +export async function resolveAgentEntry( + client: AgentLookupClient, + agentIdArg: string, +): Promise { + const trimmed = agentIdArg.trim(); + if (!trimmed) { + return null; + } + + const agents = await fetchAllAgents(client, { filter: { includeArchived: true } }); + const listedId = resolveAgentId(agentIdArg, agents); + if (listedId) { + const match = agents.find((entry) => entry.id === listedId); + if (match) { + return match; + } + } + + // A complete agent UUID is an exact identity: the daemon falls back to a + // title match, which must not answer for an ID that does not exist. + if (FULL_AGENT_UUID_PATTERN.test(trimmed)) { + const agentId = trimmed.toLowerCase(); + const fetchResult = await client.fetchAgent({ agentId }); + return fetchResult?.agent.id === agentId ? fetchResult.agent : null; + } + const fetchResult = await client.fetchAgent({ agentId: trimmed }); + return fetchResult?.agent ?? null; +} diff --git a/packages/cli/tests/11-agent-archive.test.ts b/packages/cli/tests/11-agent-archive.test.ts index 50df5c326..998ac8ec8 100644 --- a/packages/cli/tests/11-agent-archive.test.ts +++ b/packages/cli/tests/11-agent-archive.test.ts @@ -197,6 +197,16 @@ try { "the agent should be listed before it is archived", ); + const detached = await runPaseoCli(daemon, [ + "agent", + "detach", + TARGET_AGENT_ID, + "--json", + "--host", + host, + ]); + assert.strictEqual(detached.exitCode, 0, detached.stdout + detached.stderr); + const archived = await runPaseoCli(daemon, [ "agent", "archive", @@ -283,6 +293,191 @@ try { await daemon.stop(); } } + // Test 10: archives an agent whose workspace no longer exists (omitted from agent ls) + { + console.log("Test 10: archives an agent whose workspace was deleted"); + const orphanId = "9eac296c-4d60-4189-a0b5-ae71dd9c6ad9"; + const dirs = await createTempDirs(); + await writeFile( + join(dirs.paseoHome, "agents", `${orphanId}.json`), + JSON.stringify( + { + id: orphanId, + provider: "codex", + cwd: dirs.workDir, + workspaceId: "deleted-workspace-id", + createdAt: "2026-09-03T18:29:21.949Z", + updatedAt: "2026-09-03T18:29:21.949Z", + title: "orphaned agent", + labels: {}, + lastStatus: "closed", + }, + null, + 2, + ), + ); + const daemon = await startTestDaemon(dirs); + const host = `127.0.0.1:${daemon.port}`; + try { + const listed = await runPaseoCli(daemon, ["agent", "ls", "-ag", "--json", "--host", host]); + assert.strictEqual(listed.exitCode, 0, listed.stderr); + assert.deepStrictEqual(JSON.parse(listed.stdout), []); + + const inspected = await runPaseoCli(daemon, [ + "agent", + "inspect", + orphanId, + "--json", + "--host", + host, + ]); + assert.strictEqual(inspected.exitCode, 0, inspected.stderr); + assert.strictEqual((JSON.parse(inspected.stdout) as { Archived: boolean }).Archived, false); + + const detached = await runPaseoCli(daemon, [ + "agent", + "detach", + orphanId, + "--json", + "--host", + host, + ]); + assert.strictEqual(detached.exitCode, 0, detached.stdout + detached.stderr); + assert.deepStrictEqual(JSON.parse(detached.stdout), { + agentId: orphanId, + status: "detached", + }); + + const reloaded = await runPaseoCli(daemon, [ + "agent", + "reload", + orphanId, + "--json", + "--host", + host, + ]); + assert.strictEqual(reloaded.exitCode, 1); + assert.strictEqual( + (parseJsonError(reloaded.stderr) as { error: { code: string } }).error.code, + "agent_refresh_failed", + ); + + const archived = await runPaseoCli(daemon, [ + "agent", + "archive", + orphanId, + "--json", + "--host", + host, + ]); + assert.strictEqual(archived.exitCode, 0, archived.stdout + archived.stderr); + const result = JSON.parse(archived.stdout) as { agentId: string; status: string }; + assert.strictEqual(result.agentId, orphanId); + assert.strictEqual(result.status, "archived"); + } finally { + await daemon.stop(); + } + console.log("✓ archives an agent whose workspace was deleted\n"); + } + // Test 11: archives an agent whose provider is not available + { + console.log("Test 11: archives an agent whose provider is not available"); + const agentId = "22222222-2222-4333-8444-555555555555"; + const dirs = await createTempDirs(); + await writeFile( + join(dirs.paseoHome, "agents", `${agentId}.json`), + JSON.stringify( + { + id: agentId, + provider: "not-a-registered-provider", + cwd: dirs.workDir, + createdAt: "2026-09-03T18:29:21.949Z", + updatedAt: "2026-09-03T18:29:21.949Z", + title: "provider gone", + labels: {}, + lastStatus: "closed", + }, + null, + 2, + ), + ); + const daemon = await startTestDaemon(dirs); + const host = `127.0.0.1:${daemon.port}`; + try { + const archived = await runPaseoCli(daemon, [ + "agent", + "archive", + agentId, + "--json", + "--host", + host, + ]); + assert.strictEqual(archived.exitCode, 0, archived.stdout + archived.stderr); + assert.strictEqual((JSON.parse(archived.stdout) as { agentId: string }).agentId, agentId); + } finally { + await daemon.stop(); + } + console.log("✓ archives an agent whose provider is not available\n"); + } + // Test 12: a missing full ID never resolves to an unlisted agent titled with it + { + console.log("Test 12: a missing full ID does not archive an agent titled with it"); + const missingId = "9eac296c-4d60-4189-a0b5-ae71dd9c6ad9"; + const titledId = "c9a97e5d-4a92-4646-a016-53032146d0a1"; + const dirs = await createTempDirs(); + await writeFile( + join(dirs.paseoHome, "agents", `${titledId}.json`), + JSON.stringify( + { + id: titledId, + provider: "codex", + cwd: dirs.workDir, + workspaceId: "deleted-workspace-id", + createdAt: "2026-09-03T18:29:21.949Z", + updatedAt: "2026-09-03T18:29:21.949Z", + title: missingId, + labels: {}, + lastStatus: "closed", + }, + null, + 2, + ), + ); + const daemon = await startTestDaemon(dirs); + const host = `127.0.0.1:${daemon.port}`; + try { + for (const command of ["archive", "detach", "reload"]) { + const result = await runPaseoCli(daemon, [ + "agent", + command, + missingId, + "--json", + "--host", + host, + ]); + assert.strictEqual(result.exitCode, 1, `${command}: ${result.stdout}`); + assert.strictEqual( + (parseJsonError(result.stderr) as { error: { code: string } }).error.code, + "AGENT_NOT_FOUND", + `${command}: ${result.stderr}`, + ); + } + + const titled = await runPaseoCli(daemon, [ + "agent", + "inspect", + titledId, + "--json", + "--host", + host, + ]); + assert.strictEqual(titled.exitCode, 0, titled.stderr); + assert.strictEqual((JSON.parse(titled.stdout) as { Archived: boolean }).Archived, false); + } finally { + await daemon.stop(); + } + console.log("✓ a missing full ID does not archive an agent titled with it\n"); + } } finally { // Clean up temp directory await rm(paseoHome, { recursive: true, force: true });