mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-26 02:05:31 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6f13cb0333 | ||
|
|
393fed61cb |
+4
-1
@@ -225,7 +225,10 @@ aborts the shared refresh signal at the deadline, and when it stops. Shutdown wa
|
||||
probes to settle before it shuts down provider clients, so a probe cannot start provider work,
|
||||
such as an OpenCode server, after its client has cleaned up. Providers name active catalog operations and
|
||||
finish subprocess, server, or session cleanup before rejecting. Timeout errors list the operations
|
||||
that were still active when the deadline expired.
|
||||
that were still active when the deadline expired. A plugin provider's connection is shared with its
|
||||
running sessions, so the bridge cannot close it at the deadline; it sends `request.cancel` for the
|
||||
abandoned request instead, and the provider stops that request's work
|
||||
([provider guide](../public-docs/plugins/providers.md#stop-a-request-paseo-cancels)).
|
||||
|
||||
Catalogue results stay cached by identity until a refresh or a change to that provider's configuration.
|
||||
Providers change their model lists on the server without a CLI update, so the daemon refreshes
|
||||
|
||||
@@ -63,6 +63,7 @@ const ADAPTER_CAPABILITIES = [
|
||||
"prompt.command",
|
||||
"session.configure",
|
||||
"permission",
|
||||
"request.cancel",
|
||||
] as const;
|
||||
|
||||
interface AcpBoundarySession {
|
||||
@@ -105,6 +106,8 @@ export async function createAcpProviderConnection(
|
||||
const listeners = new Set<(event: ProviderEvent) => void>();
|
||||
const sessions = new Map<string, AcpBoundarySession>();
|
||||
const inFlight = new Set<Promise<void>>();
|
||||
// Catalogue and listing requests each run a probe runtime that cancellation stops.
|
||||
const cancellable = new Map<string, AbortController>();
|
||||
let closed = false;
|
||||
let closePromise: Promise<void> | null = null;
|
||||
const emit = (event: ProviderEvent) => {
|
||||
@@ -128,16 +131,31 @@ export async function createAcpProviderConnection(
|
||||
if (closed) throw new Error("ACP provider connection is closed");
|
||||
input = ProviderInputSchema.parse(input);
|
||||
validateAdmission(input, { capabilities, sessions });
|
||||
if (input.type === "request.cancel") {
|
||||
cancellable.get(input.requestId)?.abort(new Error("Paseo canceled the request"));
|
||||
return;
|
||||
}
|
||||
const admitted = input;
|
||||
const controller = new AbortController();
|
||||
const { signal } = controller;
|
||||
if (admitted.type === "catalog" || admitted.type === "sessions") {
|
||||
cancellable.set(admitted.requestId, controller);
|
||||
}
|
||||
const operation = Promise.resolve().then(async () => {
|
||||
if (closed) return undefined;
|
||||
await dispatch(input, state);
|
||||
await dispatch(admitted, state, signal);
|
||||
return undefined;
|
||||
});
|
||||
const settled = operation.catch((error) => {
|
||||
emitOperationFailure(input, emit, error);
|
||||
if (!signal.aborted) emitOperationFailure(admitted, emit, error);
|
||||
});
|
||||
inFlight.add(settled);
|
||||
void settled.finally(() => inFlight.delete(settled));
|
||||
void settled.finally(() => {
|
||||
inFlight.delete(settled);
|
||||
if ("requestId" in admitted && cancellable.get(admitted.requestId) === controller) {
|
||||
cancellable.delete(admitted.requestId);
|
||||
}
|
||||
});
|
||||
},
|
||||
onEvent(listener) {
|
||||
listeners.add(listener);
|
||||
@@ -147,6 +165,9 @@ export async function createAcpProviderConnection(
|
||||
if (closePromise) return closePromise;
|
||||
closed = true;
|
||||
closePromise = (async () => {
|
||||
for (const controller of cancellable.values()) {
|
||||
controller.abort(new Error("ACP provider connection closed"));
|
||||
}
|
||||
await Promise.all(inFlight);
|
||||
const active = [...sessions.values()];
|
||||
sessions.clear();
|
||||
@@ -209,13 +230,17 @@ function emitOperationFailure(
|
||||
}
|
||||
}
|
||||
|
||||
async function dispatch(input: ProviderInput, state: AcpConnectionState): Promise<void> {
|
||||
async function dispatch(
|
||||
input: Exclude<ProviderInput, { type: "request.cancel" }>,
|
||||
state: AcpConnectionState,
|
||||
signal: AbortSignal,
|
||||
): Promise<void> {
|
||||
switch (input.type) {
|
||||
case "catalog":
|
||||
await discover(input, state);
|
||||
await discover(input, state, signal);
|
||||
return;
|
||||
case "sessions":
|
||||
await listSessions(input, state);
|
||||
await listSessions(input, state, signal);
|
||||
return;
|
||||
case "session.open":
|
||||
await openSession(input, state);
|
||||
@@ -263,58 +288,91 @@ async function dispatch(input: ProviderInput, state: AcpConnectionState): Promis
|
||||
}
|
||||
}
|
||||
|
||||
async function discover(
|
||||
input: Extract<ProviderInput, { type: "catalog" }>,
|
||||
/**
|
||||
* Runs one request in its own short-lived runtime and publishes its result before shutting the
|
||||
* runtime down, so a slow session close cannot delay the reply. Aborting `signal` until shutdown
|
||||
* ends closes the runtime, which terminates its process and fails whatever the request awaits.
|
||||
*/
|
||||
async function withRequestRuntime<Result>(
|
||||
state: AcpConnectionState,
|
||||
request: {
|
||||
boundarySessionId: string;
|
||||
cwd?: string;
|
||||
signal: AbortSignal;
|
||||
run(runtime: AcpRuntime): Promise<Result>;
|
||||
publish(result: Result): void;
|
||||
},
|
||||
): Promise<void> {
|
||||
const { signal } = request;
|
||||
const runtime = await AcpRuntime.start({
|
||||
options: state.options,
|
||||
launch: state.launch,
|
||||
boundarySessionId: "catalog",
|
||||
cwd: input.cwd,
|
||||
boundarySessionId: request.boundarySessionId,
|
||||
cwd: request.cwd,
|
||||
env: {},
|
||||
emit: state.emit,
|
||||
signal,
|
||||
});
|
||||
const closeOnAbort = () => void runtime.close().catch(() => undefined);
|
||||
signal.addEventListener("abort", closeOnAbort, { once: true });
|
||||
try {
|
||||
let catalog = await runtime.discover(input.cwd);
|
||||
const context = runtime.configContext();
|
||||
for (const transformer of state.options.transformers ?? []) {
|
||||
if (transformer.discover) {
|
||||
catalog = await transformer.discover(catalog, context);
|
||||
}
|
||||
}
|
||||
state.emit({ type: "catalog", requestId: input.requestId, catalog });
|
||||
signal.throwIfAborted();
|
||||
const result = await request.run(runtime);
|
||||
signal.throwIfAborted();
|
||||
request.publish(result);
|
||||
} finally {
|
||||
await runtime.closeSession();
|
||||
await (signal.aborted ? runtime.close() : runtime.closeSession());
|
||||
signal.removeEventListener("abort", closeOnAbort);
|
||||
}
|
||||
}
|
||||
|
||||
async function discover(
|
||||
input: Extract<ProviderInput, { type: "catalog" }>,
|
||||
state: AcpConnectionState,
|
||||
signal: AbortSignal,
|
||||
): Promise<void> {
|
||||
await withRequestRuntime(state, {
|
||||
boundarySessionId: "catalog",
|
||||
cwd: input.cwd,
|
||||
signal,
|
||||
async run(runtime) {
|
||||
let catalog = await runtime.discover(input.cwd);
|
||||
const context = runtime.configContext();
|
||||
for (const transformer of state.options.transformers ?? []) {
|
||||
if (transformer.discover) {
|
||||
catalog = await transformer.discover(catalog, context);
|
||||
}
|
||||
}
|
||||
return catalog;
|
||||
},
|
||||
publish(catalog) {
|
||||
state.emit({ type: "catalog", requestId: input.requestId, catalog });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function listSessions(
|
||||
input: Extract<ProviderInput, { type: "sessions" }>,
|
||||
state: AcpConnectionState,
|
||||
signal: AbortSignal,
|
||||
): Promise<void> {
|
||||
const runtime = await AcpRuntime.start({
|
||||
options: state.options,
|
||||
launch: state.launch,
|
||||
await withRequestRuntime(state, {
|
||||
boundarySessionId: "sessions",
|
||||
env: {},
|
||||
emit: state.emit,
|
||||
signal,
|
||||
run: (runtime) => runtime.listSessions({ cwd: input.cwd, limit: input.limit }),
|
||||
publish(selected) {
|
||||
state.emit({
|
||||
type: "sessions",
|
||||
requestId: input.requestId,
|
||||
sessions: selected.map((session) => ({
|
||||
persistence: nativePersistence(session.sessionId),
|
||||
cwd: session.cwd,
|
||||
title: session.title ?? undefined,
|
||||
updatedAt: session.updatedAt ?? undefined,
|
||||
})),
|
||||
});
|
||||
},
|
||||
});
|
||||
try {
|
||||
const selected = await runtime.listSessions({ cwd: input.cwd, limit: input.limit });
|
||||
state.emit({
|
||||
type: "sessions",
|
||||
requestId: input.requestId,
|
||||
sessions: selected.map((session) => ({
|
||||
persistence: nativePersistence(session.sessionId),
|
||||
cwd: session.cwd,
|
||||
title: session.title ?? undefined,
|
||||
updatedAt: session.updatedAt ?? undefined,
|
||||
})),
|
||||
});
|
||||
} finally {
|
||||
await runtime.close();
|
||||
}
|
||||
}
|
||||
|
||||
function retireSession(state: AcpConnectionState, sessionId: string): void {
|
||||
@@ -379,6 +437,8 @@ interface StartRuntimeOptions {
|
||||
cwd?: string;
|
||||
env: Readonly<Record<string, string>>;
|
||||
wrap?: readonly [string, ...string[]];
|
||||
/** Aborting it during startup closes the runtime and rejects with the abort reason. */
|
||||
signal?: AbortSignal;
|
||||
emit(event: ProviderEvent): void;
|
||||
onRetired?: () => void;
|
||||
}
|
||||
@@ -484,6 +544,7 @@ class AcpRuntime {
|
||||
private lastUsage: ProviderUsage = {};
|
||||
|
||||
static async start(options: StartRuntimeOptions): Promise<AcpRuntime> {
|
||||
options.signal?.throwIfAborted();
|
||||
let child: ChildProcessWithoutNullStreams | null = null;
|
||||
let spawnFailure: Promise<never> | null = null;
|
||||
let stream: Stream;
|
||||
@@ -524,6 +585,9 @@ class AcpRuntime {
|
||||
}
|
||||
const runtime = new AcpRuntime(stream, child, closeConnector, whenConnectorClosed, options);
|
||||
onPartialWireRead = () => runtime.notePartialWireRead();
|
||||
// Closing ends the transport, which fails the pending initialize below.
|
||||
const closeOnAbort = () => void runtime.close().catch(() => undefined);
|
||||
options.signal?.addEventListener("abort", closeOnAbort, { once: true });
|
||||
try {
|
||||
const initialize = withTimeout(
|
||||
runtime.call(
|
||||
@@ -539,11 +603,15 @@ class AcpRuntime {
|
||||
const initialized = spawnFailure
|
||||
? await Promise.race([initialize, spawnFailure])
|
||||
: await initialize;
|
||||
options.signal?.throwIfAborted();
|
||||
runtime.agentCapabilities = initialized.agentCapabilities ?? {};
|
||||
return runtime;
|
||||
} catch (error) {
|
||||
await runtime.close();
|
||||
options.signal?.throwIfAborted();
|
||||
throw error;
|
||||
} finally {
|
||||
options.signal?.removeEventListener("abort", closeOnAbort);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { ChildProcess } from "node:child_process";
|
||||
import diagnosticsChannel from "node:diagnostics_channel";
|
||||
import { existsSync } from "node:fs";
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
@@ -2259,6 +2260,150 @@ lines.on("line", (line) => {
|
||||
});
|
||||
});
|
||||
|
||||
async function hangingCatalogAgent(): Promise<{ executable: string; catalogCwd: string }> {
|
||||
const catalogCwd = await mkdtemp(path.join(tmpdir(), "paseo-acp-hanging-catalog-"));
|
||||
temporaryDirectories.push(catalogCwd);
|
||||
// The catalogue probe records its PID and stays resident like an agent that ignores EOF.
|
||||
const executable = await fakeAcp(`const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const readline = require("node:readline");
|
||||
const catalogCwd = ${JSON.stringify(catalogCwd)};
|
||||
const lines = readline.createInterface({ input: process.stdin });
|
||||
const send = (message) => process.stdout.write(JSON.stringify(message) + "\\n");
|
||||
lines.on("line", (line) => {
|
||||
const message = JSON.parse(line);
|
||||
if (message.method === "initialize") send({ jsonrpc: "2.0", id: message.id, result: { protocolVersion: message.params.protocolVersion, agentCapabilities: {} } });
|
||||
else if (message.method === "session/new" && message.params.cwd === catalogCwd) {
|
||||
setInterval(() => undefined, 1_000);
|
||||
fs.writeFileSync(path.join(catalogCwd, "probe.pid"), String(process.pid));
|
||||
}
|
||||
else if (message.method === "session/new") send({ jsonrpc: "2.0", id: message.id, result: { sessionId: "native-1", modes: null, configOptions: [] } });
|
||||
else if (message.method === "session/prompt") send({ jsonrpc: "2.0", id: message.id, result: { stopReason: "end_turn" } });
|
||||
});`);
|
||||
return { executable, catalogCwd };
|
||||
}
|
||||
|
||||
function readIfPresent(file: string): Promise<string> {
|
||||
return readFile(file, "utf8").catch(() => "");
|
||||
}
|
||||
|
||||
async function probePid(catalogCwd: string): Promise<number> {
|
||||
const file = path.join(catalogCwd, "probe.pid");
|
||||
await expect.poll(() => readIfPresent(file), { timeout: 5_000 }).not.toBe("");
|
||||
return Number(await readFile(file, "utf8"));
|
||||
}
|
||||
|
||||
function isRunning(pid: number): boolean {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch (error) {
|
||||
return (error as NodeJS.ErrnoException).code === "EPERM";
|
||||
}
|
||||
}
|
||||
|
||||
describe("runAcpProvider catalogue requests whose session/new never answers", () => {
|
||||
it("offers request cancellation", async () => {
|
||||
const { executable } = await hangingCatalogAgent();
|
||||
const { connection } = await connect(executable, ["prompt.message", "request.cancel"]);
|
||||
try {
|
||||
expect(connection.capabilities).toContain("request.cancel");
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("stops the probe process when Paseo cancels the request and keeps open sessions running", async () => {
|
||||
const { executable, catalogCwd } = await hangingCatalogAgent();
|
||||
const { connection, events } = await connect(executable, ["prompt.message", "request.cancel"]);
|
||||
try {
|
||||
await connection.send(openInput());
|
||||
await waitForEvent(events, (event) => event.type === "session.ready");
|
||||
|
||||
await connection.send({ type: "catalog", requestId: "catalog-1", cwd: catalogCwd });
|
||||
const pid = await probePid(catalogCwd);
|
||||
expect(isRunning(pid)).toBe(true);
|
||||
|
||||
await connection.send({ type: "request.cancel", requestId: "catalog-1" });
|
||||
await expect.poll(() => isRunning(pid), { timeout: 3_000 }).toBe(false);
|
||||
|
||||
await connection.send({
|
||||
type: "session.prompt",
|
||||
sessionId: "session-1",
|
||||
prompt: {
|
||||
clientMessageId: "after-cancel",
|
||||
delivery: "auto",
|
||||
input: { type: "message", content: [{ type: "text", text: "still there?" }] },
|
||||
},
|
||||
});
|
||||
await waitForEvent(
|
||||
events,
|
||||
(event) => event.type === "session.turn" && event.state === "completed",
|
||||
);
|
||||
expect(
|
||||
events.filter((event) => "requestId" in event && event.requestId === "catalog-1"),
|
||||
).toEqual([]);
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("publishes the catalogue before the probe session starts closing", async () => {
|
||||
const closeMarker = path.join(
|
||||
await mkdtemp(path.join(tmpdir(), "paseo-acp-catalog-close-")),
|
||||
"close-started",
|
||||
);
|
||||
temporaryDirectories.push(path.dirname(closeMarker));
|
||||
// session/close never answers, so the probe's shutdown runs into its close timeout.
|
||||
const executable = await fakeAcp(`const fs = require("node:fs");
|
||||
const readline = require("node:readline");
|
||||
const lines = readline.createInterface({ input: process.stdin });
|
||||
const send = (message) => process.stdout.write(JSON.stringify(message) + "\\n");
|
||||
lines.on("line", (line) => {
|
||||
const message = JSON.parse(line);
|
||||
if (message.method === "initialize") send({ jsonrpc: "2.0", id: message.id, result: { protocolVersion: message.params.protocolVersion, agentCapabilities: {} } });
|
||||
else if (message.method === "session/new") send({ jsonrpc: "2.0", id: message.id, result: { sessionId: "catalog-native", modes: null, configOptions: [] } });
|
||||
else if (message.method === "session/close") fs.writeFileSync(${JSON.stringify(closeMarker)}, "started");
|
||||
});`);
|
||||
const { connection, events } = await connect(executable, ["prompt.message", "request.cancel"]);
|
||||
let closingWhenPublished: boolean | undefined;
|
||||
connection.onEvent((event) => {
|
||||
if (event.type === "catalog") closingWhenPublished = existsSync(closeMarker);
|
||||
});
|
||||
try {
|
||||
await connection.send({ type: "catalog", requestId: "catalog-1" });
|
||||
await waitForEvent(events, (event) => event.type === "catalog");
|
||||
expect(closingWhenPublished).toBe(false);
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("ignores cancellation of a request that already finished", async () => {
|
||||
const executable = await fakeAcp(basicAgent);
|
||||
const { connection, events } = await connect(executable, ["prompt.message", "request.cancel"]);
|
||||
try {
|
||||
await connection.send({ type: "catalog", requestId: "catalog-1" });
|
||||
await waitForEvent(events, (event) => event.type === "catalog");
|
||||
await expect(
|
||||
connection.send({ type: "request.cancel", requestId: "catalog-1" }),
|
||||
).resolves.toBeUndefined();
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("stops the probe process when the connection closes", async () => {
|
||||
const { executable, catalogCwd } = await hangingCatalogAgent();
|
||||
const { connection } = await connect(executable, ["prompt.message", "request.cancel"]);
|
||||
await connection.send({ type: "catalog", requestId: "catalog-1", cwd: catalogCwd });
|
||||
const pid = await probePid(catalogCwd);
|
||||
|
||||
await connection.close();
|
||||
expect(isRunning(pid)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("runAcpProvider streamed chunks without messageId (#4699)", () => {
|
||||
interface Chunk {
|
||||
kind: "agent_message_chunk" | "agent_thought_chunk";
|
||||
|
||||
@@ -23,6 +23,7 @@ export const PROVIDER_CAPABILITIES = [
|
||||
"session.unarchive",
|
||||
"permission",
|
||||
"permission.tool_policy",
|
||||
"request.cancel",
|
||||
"timeline.plugin",
|
||||
] as const;
|
||||
|
||||
@@ -387,7 +388,13 @@ export type ProviderInput =
|
||||
| { type: "session.archive"; requestId: string; persistence: ProviderPersistence }
|
||||
| { type: "session.unarchive"; requestId: string; persistence: ProviderPersistence }
|
||||
| { type: "session.can_stop_runtime"; requestId: string; sessionId: string }
|
||||
| { type: "session.close"; requestId: string; sessionId: string };
|
||||
| { type: "session.close"; requestId: string; sessionId: string }
|
||||
/**
|
||||
* Paseo stopped waiting for the request with this `requestId`, such as a catalogue refresh that
|
||||
* passed its deadline. Stop its work and release what it started; Paseo ignores later events for
|
||||
* it. Sent only when the connection offers `request.cancel`.
|
||||
*/
|
||||
| { type: "request.cancel"; requestId: string };
|
||||
|
||||
export interface ProviderThinkingOption {
|
||||
id: string;
|
||||
@@ -803,6 +810,8 @@ export function requiredProviderCapabilities(input: ProviderInput): readonly Pro
|
||||
switch (input.type) {
|
||||
case "session.can_stop_runtime":
|
||||
return ["session.can_stop_runtime"];
|
||||
case "request.cancel":
|
||||
return ["request.cancel"];
|
||||
case "catalog":
|
||||
case "session.interrupt":
|
||||
case "session.close":
|
||||
@@ -1135,6 +1144,7 @@ export const ProviderInputSchema: z.ZodType<ProviderInput> = z.discriminatedUnio
|
||||
})
|
||||
.strict(),
|
||||
z.object({ type: z.literal("session.close"), requestId: idSchema, sessionId: idSchema }).strict(),
|
||||
z.object({ type: z.literal("request.cancel"), requestId: idSchema }).strict(),
|
||||
]);
|
||||
|
||||
const modeSchema = z
|
||||
|
||||
@@ -25,6 +25,7 @@ import { AgentManager } from "./agent-manager.js";
|
||||
import { buildProviderRegistry } from "./provider-registry.js";
|
||||
import { ProviderOverrideSchema } from "@getpaseo/protocol/provider-config";
|
||||
import { PluginAgentClientRegistry } from "./plugin-provider.js";
|
||||
import { runProviderRefreshWithDeadline } from "./provider-refresh-deadline.js";
|
||||
import {
|
||||
isStaleProviderSessionError,
|
||||
StaleProviderSessionError,
|
||||
@@ -2626,6 +2627,140 @@ describe("pending provider responses", () => {
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test.each([
|
||||
{ offered: true, cancels: true },
|
||||
{ offered: false, cancels: false },
|
||||
])(
|
||||
"tells the provider to cancel an abandoned catalogue request: offered $offered",
|
||||
async ({ offered, cancels }) => {
|
||||
const controller = new AbortController();
|
||||
const inputs: ProviderInput[] = [];
|
||||
await withObservedProvider(
|
||||
{
|
||||
capabilities: offered ? [...CAPABILITIES, "request.cancel"] : CAPABILITIES,
|
||||
async handleInput(input) {
|
||||
inputs.push(input);
|
||||
if (input.type === "catalog") setImmediate(() => controller.abort(new Error("Late")));
|
||||
return input.type === "catalog" || input.type === "request.cancel";
|
||||
},
|
||||
},
|
||||
async (client) => {
|
||||
await expect(
|
||||
client.fetchCatalog({ scope: "global" }, { signal: controller.signal }),
|
||||
).rejects.toThrow("Late");
|
||||
await nextTurn();
|
||||
},
|
||||
);
|
||||
const catalog = inputs.find((input) => input.type === "catalog");
|
||||
expect(inputs.filter((input) => input.type === "request.cancel")).toEqual(
|
||||
cancels && catalog && "requestId" in catalog
|
||||
? [{ type: "request.cancel", requestId: catalog.requestId }]
|
||||
: [],
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
function isRunning(pid: number): boolean {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch (error) {
|
||||
return (error as NodeJS.ErrnoException).code === "EPERM";
|
||||
}
|
||||
}
|
||||
|
||||
async function readIfPresent(file: string): Promise<string> {
|
||||
const { readFile } = await import("node:fs/promises");
|
||||
return readFile(file, "utf8").catch(() => "");
|
||||
}
|
||||
|
||||
describe("timed-out plugin catalogue refresh", () => {
|
||||
test("stops the ACP probe stuck in session/new and keeps the provider's running agent", async () => {
|
||||
const logger = createTestLogger();
|
||||
const home = await mkdtemp(join(tmpdir(), "paseo-acp-refresh-timeout-"));
|
||||
const catalogCwd = join(home, "catalog");
|
||||
const storage = new AgentStorage(join(home, "agents"), logger);
|
||||
const script = join(home, "agent.cjs");
|
||||
const { mkdir, readFile, writeFile } = await import("node:fs/promises");
|
||||
await mkdir(catalogCwd);
|
||||
// The catalogue probe records its PID, never answers session/new, and ignores stdin EOF.
|
||||
await writeFile(
|
||||
script,
|
||||
`
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const { createInterface } = require("node:readline");
|
||||
const catalogCwd = ${JSON.stringify(catalogCwd)};
|
||||
const send = (msg) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...msg }) + "\\n");
|
||||
createInterface({ input: process.stdin }).on("line", (line) => {
|
||||
const msg = JSON.parse(line);
|
||||
if (msg.method === "initialize") {
|
||||
send({ id: msg.id, result: { protocolVersion: 1, agentCapabilities: {} } });
|
||||
} else if (msg.method === "session/new" && msg.params.cwd === catalogCwd) {
|
||||
setInterval(() => undefined, 1_000);
|
||||
fs.writeFileSync(path.join(catalogCwd, "probe.pid"), String(process.pid));
|
||||
} else if (msg.method === "session/new") {
|
||||
send({ id: msg.id, result: { sessionId: "live-1", configOptions: [] } });
|
||||
} else if (msg.method === "session/prompt") {
|
||||
send({ method: "session/update", params: { sessionId: "live-1", update: {
|
||||
sessionUpdate: "agent_message_chunk", content: { type: "text", text: "still here" },
|
||||
} } });
|
||||
send({ id: msg.id, result: { stopReason: "end_turn" } });
|
||||
} else if (msg.method === "session/close") {
|
||||
send({ id: msg.id, result: {} });
|
||||
}
|
||||
});
|
||||
`,
|
||||
);
|
||||
const registration = runAcpProvider({
|
||||
id: "hanging-catalog-acp",
|
||||
label: "Hanging Catalog ACP",
|
||||
command: [process.execPath, script],
|
||||
});
|
||||
const plugins = new PluginAgentClientRegistry(logger);
|
||||
plugins.replace([registration]);
|
||||
const manager = new AgentManager({ clients: plugins.clients(), registry: storage, logger });
|
||||
try {
|
||||
const agent = await manager.createAgent({ provider: registration.id, cwd: home }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
const client = plugins.clients()[registration.id]!;
|
||||
|
||||
const refresh = runProviderRefreshWithDeadline({
|
||||
label: registration.label,
|
||||
timeoutMs: 1_000,
|
||||
operation: (context) =>
|
||||
client.fetchCatalog({ scope: "workspace", cwd: catalogCwd }, context),
|
||||
});
|
||||
const pidFile = join(catalogCwd, "probe.pid");
|
||||
await expect.poll(() => readIfPresent(pidFile), { timeout: 5_000 }).not.toBe("");
|
||||
const pid = Number(await readFile(pidFile, "utf8"));
|
||||
await expect(refresh).rejects.toThrow(
|
||||
"Timed out refreshing Hanging Catalog ACP after 1000ms",
|
||||
);
|
||||
await expect.poll(() => isRunning(pid), { timeout: 3_000 }).toBe(false);
|
||||
|
||||
const next = await sendPreparedPromptToAgent({
|
||||
agentManager: manager,
|
||||
agentStorage: storage,
|
||||
agentId: agent.id,
|
||||
prompt: "are you still there?",
|
||||
logger,
|
||||
});
|
||||
expect(next.disposition).toBe("turn_started");
|
||||
if (next.disposition === "turn_started") await next.started;
|
||||
await expect
|
||||
.poll(() => manager.getAgent(agent.id)?.lifecycle, { timeout: 3_000 })
|
||||
.toBe("idle");
|
||||
} finally {
|
||||
await Promise.all(manager.listAgents().map((item) => manager.closeAgent(item.id)));
|
||||
await plugins.shutdown();
|
||||
await storage.flush();
|
||||
await rm(home, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
/** A diagnostic context for a provider that does not report its installation. */
|
||||
|
||||
@@ -447,6 +447,12 @@ class ProviderRuntime {
|
||||
pending.reject(
|
||||
signal?.reason instanceof Error ? signal.reason : new Error("Provider request aborted"),
|
||||
);
|
||||
// Without the cancel, a provider keeps the abandoned work and whatever it spawned (#10734).
|
||||
if (connection.capabilities.includes("request.cancel")) {
|
||||
void connection
|
||||
.send({ type: "request.cancel", requestId: input.requestId })
|
||||
.catch(() => undefined);
|
||||
}
|
||||
};
|
||||
signal?.addEventListener("abort", abort, { once: true });
|
||||
try {
|
||||
|
||||
@@ -892,7 +892,13 @@ const PROVIDER_ID = "shutdown-provider";
|
||||
|
||||
async function createProviderPlugin(
|
||||
root: string,
|
||||
options: { acknowledgeClose: boolean; hooks?: string; reportOpen?: boolean } = {
|
||||
options: {
|
||||
acknowledgeClose: boolean;
|
||||
hooks?: string;
|
||||
reportOpen?: boolean;
|
||||
/** Catalogues for this cwd never answer; their request.cancel writes `marker`. */
|
||||
hangingCatalog?: { cwd: string; marker: string };
|
||||
} = {
|
||||
acknowledgeClose: true,
|
||||
},
|
||||
): Promise<string> {
|
||||
@@ -907,13 +913,16 @@ async function createProviderPlugin(
|
||||
);
|
||||
await writeFile(
|
||||
path.join(directory, "index.server.ts"),
|
||||
`import type {
|
||||
`import { writeFileSync } from "node:fs";
|
||||
import type {
|
||||
ProviderEvent,
|
||||
ProviderInput,
|
||||
ProviderRegistration,
|
||||
} from "@getpaseo/plugin/server/provider";
|
||||
|
||||
const CAPABILITIES = ["prompt.message", "session.persistence"];
|
||||
const CAPABILITIES = ["prompt.message", "session.persistence", "request.cancel"];
|
||||
const HANGING_CATALOG = ${JSON.stringify(options.hangingCatalog ?? null)};
|
||||
const hungRequests = new Set<string>();
|
||||
|
||||
const provider: ProviderRegistration = {
|
||||
id: ${JSON.stringify(PROVIDER_ID)},
|
||||
@@ -926,6 +935,14 @@ const provider: ProviderRegistration = {
|
||||
version: 1,
|
||||
capabilities: CAPABILITIES,
|
||||
async send(input: ProviderInput) {
|
||||
if (input.type === "request.cancel") {
|
||||
if (HANGING_CATALOG && hungRequests.delete(input.requestId)) writeFileSync(HANGING_CATALOG.marker, input.requestId);
|
||||
return;
|
||||
}
|
||||
if (input.type === "catalog" && HANGING_CATALOG && input.cwd === HANGING_CATALOG.cwd) {
|
||||
hungRequests.add(input.requestId);
|
||||
return;
|
||||
}
|
||||
if (input.type === "catalog") {
|
||||
emit({
|
||||
type: "catalog",
|
||||
@@ -1092,6 +1109,53 @@ test("reloading a plugin leaves a completed plugin-provider agent without an err
|
||||
expect((await client.waitForFinish(agent.id, 30_000)).status).toBe("idle");
|
||||
}, 60_000);
|
||||
|
||||
test("a timed-out catalogue refresh cancels its plugin request and keeps the provider's agent running", async () => {
|
||||
const root = await mkdtemp(path.join(tmpdir(), "plugin-provider-refresh-cancel-"));
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }));
|
||||
const workspace = path.join(root, "workspace");
|
||||
const hangingWorkspace = path.join(root, "hanging-workspace");
|
||||
const marker = path.join(root, "canceled-request");
|
||||
await mkdir(workspace, { recursive: true });
|
||||
await mkdir(hangingWorkspace, { recursive: true });
|
||||
const pluginDirectory = await createProviderPlugin(root, {
|
||||
acknowledgeClose: true,
|
||||
hangingCatalog: { cwd: hangingWorkspace, marker },
|
||||
});
|
||||
|
||||
const daemon = await createTestPaseoDaemon({
|
||||
paseoHomeRoot: path.join(root, "daemon"),
|
||||
staticDir: path.join(root, "static"),
|
||||
pluginsEnabled: true,
|
||||
providerCatalogRefreshTimeoutMs: 1_000,
|
||||
plugins: {
|
||||
"shutdown-provider-plugin": { source: "directory", path: pluginDirectory, enabled: true },
|
||||
},
|
||||
});
|
||||
const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws`, appVersion: "0.9.1" });
|
||||
onTestFinished(async () => {
|
||||
await client.close();
|
||||
await daemon.close();
|
||||
});
|
||||
await client.connect();
|
||||
await client.fetchAgents({ subscribe: {} });
|
||||
const agent = await client.createAgent({
|
||||
provider: PROVIDER_ID,
|
||||
model: "shutdown-model",
|
||||
cwd: workspace,
|
||||
title: "Running beside a refresh",
|
||||
});
|
||||
await client.sendMessage(agent.id, "first");
|
||||
await client.waitForFinish(agent.id, 30_000);
|
||||
|
||||
await client.refreshProvidersSnapshot({ cwd: hangingWorkspace, providers: [PROVIDER_ID] });
|
||||
await expect
|
||||
.poll(() => readFile(marker, "utf8").catch(() => ""), { timeout: 10_000 })
|
||||
.not.toBe("");
|
||||
|
||||
await client.sendMessage(agent.id, "second");
|
||||
expect((await client.waitForFinish(agent.id, 30_000)).status).toBe("idle");
|
||||
}, 60_000);
|
||||
|
||||
test("a provider that never acknowledges session.close does not hold the daemon open", async () => {
|
||||
const root = await mkdtemp(path.join(tmpdir(), "plugin-provider-stuck-close-"));
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }));
|
||||
|
||||
@@ -35,6 +35,7 @@ interface TestPaseoDaemonOptions {
|
||||
relayConfigCapability?: boolean;
|
||||
agentClients?: Partial<Record<AgentProvider, AgentClient>>;
|
||||
providerOverrides?: PaseoDaemonConfig["providerOverrides"];
|
||||
providerCatalogRefreshTimeoutMs?: PaseoDaemonConfig["providerCatalogRefreshTimeoutMs"];
|
||||
paseoHomeRoot?: string;
|
||||
staticDir?: string;
|
||||
cleanup?: boolean;
|
||||
@@ -202,6 +203,7 @@ async function prepareTestDaemonConfig(
|
||||
isDev: options.isDev,
|
||||
agentClients: options.agentClients ?? createTestAgentClients(),
|
||||
providerOverrides: options.providerOverrides,
|
||||
providerCatalogRefreshTimeoutMs: options.providerCatalogRefreshTimeoutMs,
|
||||
agentStoragePath: path.join(paseoHome, "agents"),
|
||||
relayEnabled: options.relayEnabled ?? false,
|
||||
relayEndpoint: options.relayEndpoint ?? "relay.paseo.sh:443",
|
||||
|
||||
@@ -160,6 +160,47 @@ Return an empty array for a category the agent does not expose. The selected `mo
|
||||
The catalog describes choices available before a session exists. Session-specific controls come
|
||||
later through `session.config`.
|
||||
|
||||
### Stop a request Paseo cancels
|
||||
|
||||
Paseo gives each catalog refresh a deadline. When it stops waiting for a request, it sends
|
||||
`request.cancel` with that request's `requestId`. Stop the work and release what it started, such
|
||||
as a process you spawned to read the catalog. Paseo ignores any event you emit for that request
|
||||
afterward. Sessions on the same connection keep running.
|
||||
|
||||
Add `request.cancel` to your supported capabilities. Paseo sends the input only to a connection
|
||||
that offers it:
|
||||
|
||||
```ts
|
||||
const pending = new Map<string, AbortController>();
|
||||
|
||||
if (input.type === "catalog") {
|
||||
const controller = new AbortController();
|
||||
pending.set(input.requestId, controller);
|
||||
void readCatalog({ signal: controller.signal })
|
||||
.then(
|
||||
(catalog) => {
|
||||
if (!controller.signal.aborted)
|
||||
emit({ type: "catalog", requestId: input.requestId, catalog });
|
||||
},
|
||||
(error) => {
|
||||
if (!controller.signal.aborted)
|
||||
emit({
|
||||
type: "request.failed",
|
||||
requestId: input.requestId,
|
||||
error: { message: String(error) },
|
||||
});
|
||||
},
|
||||
)
|
||||
.finally(() => pending.delete(input.requestId));
|
||||
}
|
||||
if (input.type === "request.cancel") {
|
||||
pending.get(input.requestId)?.abort();
|
||||
}
|
||||
```
|
||||
|
||||
A cancel can arrive after the request finished. Ignore a `requestId` you no longer track.
|
||||
`runAcpProvider` offers the capability and stops the catalog probe's process.
|
||||
|
||||
## Open a session
|
||||
|
||||
`session.open` contains the complete launch configuration: working directory, environment, system
|
||||
|
||||
@@ -142,6 +142,42 @@ if (input.type === "catalog") {
|
||||
|
||||
目录描述的是会话存在之前可用的选项。会话专属的控件之后通过 `session.config` 提供。
|
||||
|
||||
### 停止 Paseo 取消的请求 {#stop-a-request-paseo-cancels}
|
||||
|
||||
Paseo 为每次目录刷新设置期限。Paseo 不再等待某个请求时,会发送带有该请求 `requestId` 的 `request.cancel`。停止这项工作,并释放它启动的资源,例如为读取目录而启动的进程。之后你为该请求发出的事件都会被 Paseo 忽略。同一连接上的会话继续运行。
|
||||
|
||||
把 `request.cancel` 加入你支持的能力。Paseo 只向提供该能力的连接发送这个输入:
|
||||
|
||||
```ts
|
||||
const pending = new Map<string, AbortController>();
|
||||
|
||||
if (input.type === "catalog") {
|
||||
const controller = new AbortController();
|
||||
pending.set(input.requestId, controller);
|
||||
void readCatalog({ signal: controller.signal })
|
||||
.then(
|
||||
(catalog) => {
|
||||
if (!controller.signal.aborted)
|
||||
emit({ type: "catalog", requestId: input.requestId, catalog });
|
||||
},
|
||||
(error) => {
|
||||
if (!controller.signal.aborted)
|
||||
emit({
|
||||
type: "request.failed",
|
||||
requestId: input.requestId,
|
||||
error: { message: String(error) },
|
||||
});
|
||||
},
|
||||
)
|
||||
.finally(() => pending.delete(input.requestId));
|
||||
}
|
||||
if (input.type === "request.cancel") {
|
||||
pending.get(input.requestId)?.abort();
|
||||
}
|
||||
```
|
||||
|
||||
取消可能在请求完成之后才到达。忽略你已不再跟踪的 `requestId`。`runAcpProvider` 提供这项能力,并会停止目录探测进程。
|
||||
|
||||
## 打开会话 {#open-a-session}
|
||||
|
||||
`session.open` 包含完整的启动配置:工作目录、环境变量、系统提示词、MCP 服务器、工具策略、模型、模式、`providerOptions` 以及持久化偏好。
|
||||
|
||||
Reference in New Issue
Block a user