Archive, detach and reload agents that agent ls leaves out (#9726)

* fix(cli): fall back to fetchAgent in archive, reload, and detach (#9696)

* fix(cli): keep a full agent id exact when archive falls back to the daemon

The fallback added for agents missing from the listing asks the daemon
with fetch_agent, which tries the id, then an id prefix, then an exact
title. A full id that matches no agent could therefore resolve to a
different agent titled with that id, and archive, detach, or reload
acted on it. Accept the daemon's answer for a full id only when it is
that id, as the listing lookup already does since #9680.

Co-authored-by: xunWhale <2338923971@qq.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(cli): cover detach past the listing page and archive with a missing provider

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(cli): report a failed detach lookup as DETACH_FAILED

detach now asks the daemon when the listing has no match, and the
daemon rejects an ambiguous prefix. Wrap that failure in DETACH_FAILED
as archive and reload already do, instead of letting it out raw.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: xunWhale <2338923971@qq.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
authored and GitHub committed 2026-11-15 01:54:43 +00:00
1 parent 7286d3ef81
commit ed8aa9ada8
6 files changed
+457 -32

No files matched your search

@@ -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> = {},
): 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',
});
});
});
+21 -10
View File
@@ -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<AgentArchiveResult>;
export interface AgentArchiveClient extends AgentLookupClient {
archiveAgent(agentId: string): Promise<{ archivedAt: string }>;
close(): Promise<void>;
}
export async function runArchiveCommand(
agentIdArg: string,
options: AgentArchiveOptions,
_command: Command,
): Promise<AgentArchiveCommandResult> {
return archiveAgent(agentIdArg, options);
}
export async function archiveAgent(
agentIdArg: string,
options: AgentArchiveOptions,
connect: (
options: Parameters<typeof connectToDaemon>[0],
) => Promise<AgentArchiveClient> = connectToDaemon,
): Promise<AgentArchiveCommandResult> {
// 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) {
+35 -10
View File
@@ -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<AgentDetachResult> = {
],
};
export interface AgentDetachClient extends AgentLookupClient {
detachAgent(agentId: string): Promise<unknown>;
close(): Promise<void>;
}
export async function runDetachCommand(
agentIdArg: string,
options: CommandOptions,
_command: Command,
): Promise<SingleResult<AgentDetachResult>> {
const client = await connectToDaemon({ target: options.daemonTarget });
return detachAgent(agentIdArg, options);
}
export async function detachAgent(
agentIdArg: string,
options: CommandOptions,
connect: (
options: Parameters<typeof connectToDaemon>[0],
) => Promise<AgentDetachClient> = connectToDaemon,
): Promise<SingleResult<AgentDetachResult>> {
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);
}
+21 -7
View File
@@ -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<AgentReloadResult>;
export interface AgentReloadClient extends AgentLookupClient {
refreshAgent(agentId: string): Promise<{ agentId: string; timelineSize?: number }>;
close(): Promise<void>;
}
export async function runReloadCommand(
agentIdArg: string,
options: AgentReloadOptions,
_command: Command,
): Promise<AgentReloadCommandResult> {
return reloadAgent(agentIdArg, options);
}
export async function reloadAgent(
agentIdArg: string,
options: AgentReloadOptions,
connect: (
options: Parameters<typeof connectToDaemon>[0],
) => Promise<AgentReloadClient> = connectToDaemon,
): Promise<AgentReloadCommandResult> {
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();
+46 -5
View File
@@ -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<Awaited<ReturnType<typeof connectToDaemon>>["fetchAgents"]>[0]
>;
type DaemonClient = Awaited<ReturnType<typeof connectToDaemon>>;
type FetchAgentsOptions = NonNullable<Parameters<DaemonClient["fetchAgents"]>[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<AgentSnapshotPayload | null> {
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;
}
+195
View File
@@ -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 });