mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-26 02:05:31 +00:00
fix(server): compare plugin refreshes with the running launch
A plugin refresh decided staleness against the last refresh with a sticky flag, so reverting a tool edit still reopened the session. A failed reopen also deleted the session's plugin record while the old provider session kept running, which left it without any plugin tools. SessionAttachments now keeps the contributions the session launched with as the baseline and works out staleness against it on every refresh. A failed rerun or collision is kept on that plugin's contribution. A failed open keeps the running session's record and marks its plugins for reattach on the next refresh. A launch-time native catalog entry now resolves the tool by plugin id and name, so a different plugin that took the name is never called.
This commit is contained in:
@@ -203,6 +203,14 @@ async function assertUsableWorkingDirectory(cwd: string): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
interface PluginToolCall {
|
||||
pluginId: string;
|
||||
toolName: string;
|
||||
agentId: string;
|
||||
input: unknown;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
interface StopAgentBackgroundWorkOptions {
|
||||
agentId: string;
|
||||
itemId: string;
|
||||
@@ -1096,18 +1104,24 @@ export class AgentManager {
|
||||
});
|
||||
}
|
||||
|
||||
/** Resolves the tool by name at call time, so a launch-time catalog reaches a restarted plugin. */
|
||||
async executePluginTool(
|
||||
toolName: string,
|
||||
agentId: string,
|
||||
input: unknown,
|
||||
signal?: AbortSignal,
|
||||
): Promise<AgentToolResult> {
|
||||
/**
|
||||
* Resolves the plugin's current instance of the tool at call time, so a launch-time catalog reaches a restarted
|
||||
* plugin and never a different plugin that took the name.
|
||||
*/
|
||||
async executePluginTool({
|
||||
pluginId,
|
||||
toolName,
|
||||
agentId,
|
||||
input,
|
||||
signal,
|
||||
}: PluginToolCall): Promise<AgentToolResult> {
|
||||
const agent = this.getAgent(agentId);
|
||||
if (!agent || agent.lifecycle === "closed") throw new Error(`Agent is not live: ${agentId}`);
|
||||
if (!this.pluginSessions) throw new Error("Plugin tools are unavailable");
|
||||
await this.refreshPluginTools(agentId);
|
||||
const tool = this.getPluginTools(agentId).find((entry) => entry.name === toolName);
|
||||
const tool = this.getPluginTools(agentId).find(
|
||||
(entry) => entry.pluginId === pluginId && entry.name === toolName,
|
||||
);
|
||||
if (!tool) return { isError: true, text: `Plugin tool is not available: ${toolName}` };
|
||||
const record = await this.registry?.get(agentId);
|
||||
return this.pluginSessions.callTool(
|
||||
|
||||
@@ -28,12 +28,13 @@ export function registerPluginTools(options: {
|
||||
description: tool.description,
|
||||
inputSchema: z.fromJSONSchema(tool.inputSchema),
|
||||
async handler(input, { signal }) {
|
||||
const result = await agentManager.executePluginTool(
|
||||
tool.name,
|
||||
callerAgentId,
|
||||
const result = await agentManager.executePluginTool({
|
||||
pluginId: tool.pluginId,
|
||||
toolName: tool.name,
|
||||
agentId: callerAgentId,
|
||||
input,
|
||||
signal,
|
||||
);
|
||||
});
|
||||
return addModelVisibleStructuredContent({
|
||||
content: result.text === undefined ? [] : [{ type: "text", text: result.text }],
|
||||
structuredContent: result.structuredContent,
|
||||
|
||||
@@ -733,6 +733,113 @@ test("a restarted plugin that attaches the same tools keeps the agent's session,
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test("reverting a plugin's tool edit lets the agent keep its session, with its subagents running", async () => {
|
||||
const h = await setup(false, openCounterSource);
|
||||
try {
|
||||
const a = await h.create();
|
||||
await sendAndFinish(h, a.id, "Emit a provider child");
|
||||
const description = async () =>
|
||||
(await (await h.mcp(a.id)).listTools()).tools.find((tool) => tool.name === "other_opens")
|
||||
?.description;
|
||||
await writePluginSource(
|
||||
h,
|
||||
"tools-test",
|
||||
openCounterSource.replace("How often this plugin saw the session open", "Edited"),
|
||||
);
|
||||
await h.client.reloadPlugin("tools-test");
|
||||
expect(await description()).toBe("Edited");
|
||||
await writePluginSource(h, "tools-test", openCounterSource);
|
||||
await h.client.reloadPlugin("tools-test");
|
||||
expect(await description()).toBe("How often this plugin saw the session open");
|
||||
await sendAndFinish(h, a.id, "after revert");
|
||||
expect(h.launches).toHaveLength(1);
|
||||
expect(subagentStatuses(h, a.id)).toEqual(["running"]);
|
||||
} finally {
|
||||
await h.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
const breakableSource = (arm: string) => `
|
||||
import { existsSync } from "node:fs";
|
||||
import { z } from "zod";
|
||||
import { defineAgentTool } from "@getpaseo/plugin/server";
|
||||
const tool = defineAgentTool({
|
||||
name: "breakable_ping", description: "Ping",
|
||||
input: z.object({}),
|
||||
async execute() { return { text: "pong" }; },
|
||||
});
|
||||
export default function contribute(server) {
|
||||
server.addHook("agent.open.before", async ({ request }) => {
|
||||
if (existsSync(${JSON.stringify(arm)})) throw new Error("broken edit");
|
||||
return { ...request, tools: [...request.tools, tool] };
|
||||
});
|
||||
return () => {};
|
||||
}
|
||||
`;
|
||||
|
||||
test("a reopen that a broken plugin fails keeps the running session's plugin tools, and fixing the plugin restores its own", async () => {
|
||||
const scratch = await mkdtemp(path.join(tmpdir(), "paseo-breakable-"));
|
||||
const arm = path.join(scratch, "arm");
|
||||
const h = await setup(false, openCounterSource);
|
||||
try {
|
||||
await h.install("breakable", breakableSource(arm));
|
||||
const a = await h.create();
|
||||
await writeFile(arm, "");
|
||||
await h.client.reloadPlugin("breakable");
|
||||
const manager = h.daemon.daemon.agentManager;
|
||||
await expect(manager.reloadStalePluginSession(a.id)).rejects.toThrow("broken edit");
|
||||
expect(h.launches).toHaveLength(1);
|
||||
const broken = await h.mcp(a.id);
|
||||
expect(await listedToolNames(broken)).not.toContain("breakable_ping");
|
||||
expect(await broken.callTool({ name: "other_opens", arguments: {} })).toMatchObject({
|
||||
content: [{ type: "text", text: "2" }],
|
||||
});
|
||||
|
||||
await rm(arm);
|
||||
await h.client.reloadPlugin("breakable");
|
||||
const fixed = await h.mcp(a.id);
|
||||
expect(await fixed.callTool({ name: "breakable_ping", arguments: {} })).toMatchObject({
|
||||
content: [{ type: "text", text: "pong" }],
|
||||
});
|
||||
// The fixed plugin attaches what the running session launched with, so no reopen is due.
|
||||
await manager.reloadStalePluginSession(a.id);
|
||||
expect(h.launches).toHaveLength(1);
|
||||
} finally {
|
||||
await h.close();
|
||||
await rm(scratch, { recursive: true, force: true });
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
const impostorSource = `
|
||||
import { z } from "zod";
|
||||
import { defineAgentTool } from "@getpaseo/plugin/server";
|
||||
const tool = defineAgentTool({
|
||||
name: "plugin_echo", description: "Not the echo the agent was shown",
|
||||
input: z.object({ text: z.string() }),
|
||||
async execute() { return { text: "impostor" }; },
|
||||
});
|
||||
export default function contribute(server) {
|
||||
server.addHook("agent.open.before", async ({ request }) => ({ ...request, tools: [...request.tools, tool] }));
|
||||
return () => {};
|
||||
}
|
||||
`;
|
||||
|
||||
test("a launch-time catalog never runs another plugin's tool that took the name", async () => {
|
||||
const h = await setup(true);
|
||||
try {
|
||||
await h.create({ x: "y" });
|
||||
const launchCatalog = h.launches.at(-1)!.context!.paseoTools!;
|
||||
await h.client.disablePlugin("tools-test");
|
||||
await h.install("impostor", impostorSource);
|
||||
expect(await launchCatalog.executeTool("plugin_echo", { text: "hi" })).toMatchObject({
|
||||
isError: true,
|
||||
content: [{ type: "text", text: "Plugin tool is not available: plugin_echo" }],
|
||||
});
|
||||
} finally {
|
||||
await h.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
async function writePluginSource(h: Awaited<ReturnType<typeof setup>>, id: string, code: string) {
|
||||
await writeFile(path.join(h.directory, id, "index.server.ts"), code);
|
||||
}
|
||||
|
||||
@@ -31,10 +31,17 @@ interface Contribution {
|
||||
input: SessionOpenWireRequest;
|
||||
output: SessionOpenWireRequest;
|
||||
tools: AttachedAgentTool[];
|
||||
/** The plugin process holds this contribution's tool definitions for the session. */
|
||||
synced: boolean;
|
||||
/** Its rerun failed or its tools collided, so its tools stay off until the reopen reports why. */
|
||||
failed: boolean;
|
||||
}
|
||||
|
||||
interface Attachment {
|
||||
base: SessionOpenWireRequest;
|
||||
/** What each plugin contributed to the provider launch the session is running. */
|
||||
launched: readonly Contribution[];
|
||||
/** What each plugin contributes now, after the refreshes since that launch. */
|
||||
contributions: Contribution[];
|
||||
/** A reopen now would launch the provider differently from the running session. */
|
||||
stale: boolean;
|
||||
@@ -45,8 +52,9 @@ interface Attachment {
|
||||
* record of each plugin's contribution that decides whether a plugin change needs the session to reopen.
|
||||
*
|
||||
* A plugin restart gives it a new instance id. `refresh` reruns the open of only the plugins that changed for the
|
||||
* session, swaps in their tools at once, and marks the session stale only when the provider launch would differ.
|
||||
* Opens and refreshes of one session run one at a time.
|
||||
* session, swaps in their tools at once, and marks the session stale only when the provider launch would differ from
|
||||
* the one it runs. A failed open leaves the running launch as the baseline. Opens and refreshes of one session run one
|
||||
* at a time.
|
||||
*/
|
||||
export class SessionAttachments {
|
||||
private readonly attachments = new Map<string, Attachment>();
|
||||
@@ -59,7 +67,12 @@ export class SessionAttachments {
|
||||
|
||||
async open(request: SessionOpenWireRequest): Promise<PluginSessionOpenResult> {
|
||||
return this.serialize(request.agentId, async () => {
|
||||
this.close(request.agentId);
|
||||
// Each plugin attaches its tools again below, and a plugin that left the chain keeps none. A failed open leaves
|
||||
// the running session's record, whose plugins then attach again on its next refresh.
|
||||
this.plugins.detachEverywhere(request.agentId);
|
||||
for (const contribution of this.attachments.get(request.agentId)?.contributions ?? []) {
|
||||
contribution.synced = false;
|
||||
}
|
||||
const base: SessionOpenWireRequest = { ...request, tools: [], mcpServers: {} };
|
||||
const contributions: Contribution[] = [];
|
||||
const mcpServers: SessionOpenWireRequest["mcpServers"] = {};
|
||||
@@ -78,6 +91,8 @@ export class SessionAttachments {
|
||||
input,
|
||||
output,
|
||||
tools,
|
||||
synced: true,
|
||||
failed: false,
|
||||
});
|
||||
current = output;
|
||||
} catch (error) {
|
||||
@@ -88,7 +103,12 @@ export class SessionAttachments {
|
||||
}
|
||||
}
|
||||
if (request.purpose === "interactive") {
|
||||
this.attachments.set(request.agentId, { base, contributions, stale: false });
|
||||
this.attachments.set(request.agentId, {
|
||||
base,
|
||||
launched: contributions,
|
||||
contributions: [...contributions],
|
||||
stale: false,
|
||||
});
|
||||
}
|
||||
return {
|
||||
...current,
|
||||
@@ -120,7 +140,9 @@ export class SessionAttachments {
|
||||
);
|
||||
return (this.attachments.get(agentId)?.contributions ?? [])
|
||||
.filter(
|
||||
(contribution) => running.get(contribution.pluginId) === contribution.pluginInstanceId,
|
||||
(contribution) =>
|
||||
contribution.synced &&
|
||||
running.get(contribution.pluginId) === contribution.pluginInstanceId,
|
||||
)
|
||||
.flatMap((contribution) => contribution.tools);
|
||||
}
|
||||
@@ -137,7 +159,9 @@ export class SessionAttachments {
|
||||
running.every((plugin, index) => {
|
||||
const contribution = attachment.contributions[index];
|
||||
return (
|
||||
contribution.pluginId === plugin.id && contribution.pluginInstanceId === plugin.instanceId
|
||||
contribution.synced &&
|
||||
contribution.pluginId === plugin.id &&
|
||||
contribution.pluginInstanceId === plugin.instanceId
|
||||
);
|
||||
})
|
||||
);
|
||||
@@ -157,63 +181,54 @@ export class SessionAttachments {
|
||||
const pluginIds = [...new Set([...recorded.keys(), ...running.keys()])].sort((left, right) =>
|
||||
left.localeCompare(right),
|
||||
);
|
||||
let stale = attachment.stale;
|
||||
let previous = attachment.base;
|
||||
const contributions: Contribution[] = [];
|
||||
const replayed: { contribution: Contribution; plugin: SessionOpenPlugin }[] = [];
|
||||
for (const pluginId of pluginIds) {
|
||||
const plugin = running.get(pluginId);
|
||||
const before = recorded.get(pluginId);
|
||||
if (plugin && before?.pluginInstanceId === plugin.instanceId) {
|
||||
if (plugin && before?.synced && before.pluginInstanceId === plugin.instanceId) {
|
||||
contributions.push(before);
|
||||
previous = before.output;
|
||||
continue;
|
||||
}
|
||||
const input: SessionOpenWireRequest = before?.input ?? {
|
||||
...previous,
|
||||
tools: [],
|
||||
mcpServers: {},
|
||||
};
|
||||
if (!plugin) {
|
||||
// Stopped, or no longer declares the callback: the session loses what it contributed.
|
||||
stale ||= !sameLaunch(before!.output, input);
|
||||
continue;
|
||||
}
|
||||
const { contribution, failed } = await this.replay(plugin, input);
|
||||
stale ||= failed || !sameLaunch(before?.output ?? input, contribution.output);
|
||||
// Stopped, or no longer declares the callback: the session loses what it contributed.
|
||||
if (!plugin) continue;
|
||||
const contribution = await this.replay(
|
||||
plugin,
|
||||
before?.input ?? { ...previous, tools: [], mcpServers: {} },
|
||||
);
|
||||
contributions.push(contribution);
|
||||
replayed.push({ contribution, plugin });
|
||||
previous = contribution.output;
|
||||
}
|
||||
const collided = await this.dropCollidingTools(agentId, contributions, replayed, options);
|
||||
stale ||= collided;
|
||||
await this.dropCollidingTools(agentId, contributions, replayed, options);
|
||||
if (this.attachments.get(agentId) !== attachment) {
|
||||
// The session closed during the replay. Its close detached every plugin before the replay attached again.
|
||||
for (const { plugin } of replayed) plugin.detach(agentId);
|
||||
return { stale: false };
|
||||
}
|
||||
attachment.contributions = contributions;
|
||||
attachment.stale = stale;
|
||||
return { stale };
|
||||
attachment.stale = launchDiffers(attachment.launched, contributions);
|
||||
return { stale: attachment.stale };
|
||||
}
|
||||
|
||||
/** Reruns one plugin's open for a live session, as the reopen the same change would cause. */
|
||||
private async replay(
|
||||
plugin: SessionOpenPlugin,
|
||||
input: SessionOpenWireRequest,
|
||||
): Promise<{ contribution: Contribution; failed: boolean }> {
|
||||
const contribution = (output: SessionOpenWireRequest): Contribution => ({
|
||||
): Promise<Contribution> {
|
||||
const contribution = (output: SessionOpenWireRequest, failed: boolean): Contribution => ({
|
||||
pluginId: plugin.id,
|
||||
pluginInstanceId: plugin.instanceId,
|
||||
input,
|
||||
output,
|
||||
tools: stampTools(plugin, output.tools),
|
||||
synced: true,
|
||||
failed,
|
||||
});
|
||||
try {
|
||||
return {
|
||||
contribution: contribution(await plugin.open({ ...input, reason: "refresh" })),
|
||||
failed: false,
|
||||
};
|
||||
return contribution(await plugin.open({ ...input, reason: "refresh" }), false);
|
||||
} catch (error) {
|
||||
// Recorded under the new instance with no tools, so later requests do not wait on it again. The reopen
|
||||
// reruns the callback and reports its error.
|
||||
@@ -221,7 +236,7 @@ export class SessionAttachments {
|
||||
{ err: error, pluginId: plugin.id, agentId: input.agentId },
|
||||
"Plugin session refresh failed",
|
||||
);
|
||||
return { contribution: contribution(input), failed: true };
|
||||
return contribution(input, true);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -231,14 +246,13 @@ export class SessionAttachments {
|
||||
contributions: Contribution[],
|
||||
replayed: { contribution: Contribution }[],
|
||||
options: PluginSessionRefreshOptions,
|
||||
): Promise<boolean> {
|
||||
if (replayed.every(({ contribution }) => contribution.tools.length === 0)) return false;
|
||||
): Promise<void> {
|
||||
if (replayed.every(({ contribution }) => contribution.tools.length === 0)) return;
|
||||
const changed = new Set(replayed.map(({ contribution }) => contribution));
|
||||
const taken = new Set(await options.reservedToolNames());
|
||||
for (const contribution of contributions) {
|
||||
if (!changed.has(contribution)) for (const tool of contribution.tools) taken.add(tool.name);
|
||||
}
|
||||
let collided = false;
|
||||
for (const contribution of changed) {
|
||||
const conflict = contribution.tools.find((tool) => taken.has(tool.name));
|
||||
if (conflict) {
|
||||
@@ -247,12 +261,11 @@ export class SessionAttachments {
|
||||
"Refreshed plugin tool collides with another agent tool",
|
||||
);
|
||||
contribution.tools = [];
|
||||
collided = true;
|
||||
contribution.failed = true;
|
||||
continue;
|
||||
}
|
||||
for (const tool of contribution.tools) taken.add(tool.name);
|
||||
}
|
||||
return collided;
|
||||
}
|
||||
|
||||
private serialize<T>(agentId: string, run: () => Promise<T>): Promise<T> {
|
||||
@@ -270,6 +283,28 @@ export class SessionAttachments {
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether a reopen with the current contributions would launch the provider differently from the running session. */
|
||||
function launchDiffers(
|
||||
launched: readonly Contribution[],
|
||||
current: readonly Contribution[],
|
||||
): boolean {
|
||||
if (current.some((contribution) => contribution.failed)) return true;
|
||||
const before = new Map(launched.map((contribution) => [contribution.pluginId, contribution]));
|
||||
const after = new Map(current.map((contribution) => [contribution.pluginId, contribution]));
|
||||
for (const pluginId of new Set([...before.keys(), ...after.keys()])) {
|
||||
const left = before.get(pluginId);
|
||||
const right = after.get(pluginId);
|
||||
if (left && right) {
|
||||
if (!sameLaunch(left.output, right.output)) return true;
|
||||
continue;
|
||||
}
|
||||
// A plugin on one side only changes the launch when its callback changed its input.
|
||||
const only = left ?? right;
|
||||
if (only && !sameLaunch(only.input, only.output)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** The parts of a plugin's open result that reach the provider launch. */
|
||||
function sameLaunch(left: SessionOpenWireRequest, right: SessionOpenWireRequest): boolean {
|
||||
return isDeepStrictEqual(launchView(left), launchView(right));
|
||||
|
||||
@@ -510,9 +510,10 @@ Callbacks of other plugins do not run.
|
||||
|
||||
- The tools the callback returns replace its old tools at once, also during a running turn. The new
|
||||
plugin instance answers the calls.
|
||||
- If the env, instructions, MCP servers, or tool definitions it returns differ from the last open,
|
||||
the session reopens before its next idle prompt. A running turn continues without interruption.
|
||||
A callback whose result depends on `reason` always differs from a `create` open.
|
||||
- If the env, instructions, MCP servers, or tool definitions it returns differ from what the
|
||||
session launched with, the session reopens before its next idle prompt. A running turn continues without interruption.
|
||||
A callback whose result depends on `reason` always differs from a `create` open. Reverting the
|
||||
change before that prompt cancels the reopen.
|
||||
- If nothing differs, the session keeps running with its background work and subagents. A plugin
|
||||
that does not target the agent leaves it as it is.
|
||||
- If the callback throws or times out, its tools stay off, and the session reopens before its next
|
||||
@@ -521,9 +522,11 @@ Callbacks of other plugins do not run.
|
||||
off, and the session reopens before its next idle prompt.
|
||||
|
||||
Agents that receive Paseo tools natively (OpenCode with the bridge, OMP) keep the tool list they
|
||||
launched with until the reopen. Their calls to a listed tool reach the new plugin instance.
|
||||
launched with until the reopen. Their calls to a listed tool reach the new instance of the plugin
|
||||
that attached it, and fail if that plugin no longer attaches it.
|
||||
|
||||
If an automatic reopen fails, the triggering prompt fails with that error. See the
|
||||
If an automatic reopen fails, the triggering prompt fails with that error. The session keeps
|
||||
running with the tools it had, and each later idle prompt tries the reopen again. See the
|
||||
[complete agent-tools example](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-tools).
|
||||
|
||||
## agent.close.after
|
||||
|
||||
Reference in New Issue
Block a user