mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-18 14:25:25 +00:00
Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ded9ae9f60 | ||
|
|
1f00a8115b | ||
|
|
b3eb076539 | ||
|
|
0228ae14da | ||
|
|
62db1c7fb0 | ||
|
|
78ca2a7765 | ||
|
|
84a61f0e46 | ||
|
|
d3ebb3f02f |
@@ -1,4 +1,9 @@
|
||||
import type { AttachedAgentTool, PluginAgentToolsRuntime } from "../plugins/agent-tools.js";
|
||||
import type {
|
||||
AttachedAgentTool,
|
||||
PluginAgentToolsRuntime,
|
||||
ReattachedAgentTools,
|
||||
SessionOpenWireRequest,
|
||||
} from "../plugins/agent-tools.js";
|
||||
import { ProviderOptionsValidationError } from "./provider-options.js";
|
||||
import type { AgentToolResult } from "@getpaseo/plugin/server";
|
||||
import type { RuntimeCleanupCandidate } from "./idle-runtime-cleanup/index.js";
|
||||
@@ -192,6 +197,13 @@ async function assertUsableWorkingDirectory(cwd: string): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
interface PluginToolReattach {
|
||||
runtime: PluginAgentToolsRuntime;
|
||||
agentId: string;
|
||||
request: SessionOpenWireRequest;
|
||||
stale: readonly string[];
|
||||
}
|
||||
|
||||
interface StopAgentBackgroundWorkOptions {
|
||||
agentId: string;
|
||||
itemId: string;
|
||||
@@ -881,6 +893,8 @@ export class AgentManager {
|
||||
private sessionOpenGeneration = 0;
|
||||
private readonly sessionOpenGenerations = new Map<string, number>();
|
||||
private readonly attachedPluginTools = new Map<string, AttachedAgentTool[]>();
|
||||
private readonly pluginOpenRequests = new Map<string, SessionOpenWireRequest>();
|
||||
private readonly pluginToolRefreshes = new Map<string, Promise<void>>();
|
||||
private readonly pluginAgentTools: PluginAgentToolsRuntime | undefined;
|
||||
private paseoToolsEnabled = true;
|
||||
private paseoToolCatalogFactory: PaseoToolCatalogFactory | null = null;
|
||||
@@ -1054,8 +1068,98 @@ export class AgentManager {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reattaches a live session's tools from plugins that restarted since it opened. A restart gives the plugin a
|
||||
* new instance id, which `getPluginTools` filters out, and the session would otherwise wait for a reopen that only
|
||||
* happens before a prompt to an idle agent. The agent MCP calls this before it builds a request's catalog.
|
||||
*/
|
||||
async refreshPluginTools(agentId: string): Promise<void> {
|
||||
const runtime = this.pluginAgentTools;
|
||||
const request = this.pluginOpenRequests.get(agentId);
|
||||
const agent = this.getAgent(agentId);
|
||||
if (!runtime || !request || !agent || agent.lifecycle === "closed") return;
|
||||
const pending = this.pluginToolRefreshes.get(agentId);
|
||||
if (pending) return pending;
|
||||
const stale = [
|
||||
...new Set(
|
||||
(this.attachedPluginTools.get(agentId) ?? [])
|
||||
.filter((tool) => !runtime.isToolPluginAvailable(tool.pluginId, tool.pluginInstanceId))
|
||||
.map((tool) => tool.pluginId),
|
||||
),
|
||||
];
|
||||
if (stale.length === 0) return;
|
||||
const refresh = this.reattachPluginTools({ runtime, agentId, request, stale }).finally(() =>
|
||||
this.pluginToolRefreshes.delete(agentId),
|
||||
);
|
||||
this.pluginToolRefreshes.set(agentId, refresh);
|
||||
return refresh;
|
||||
}
|
||||
|
||||
private async reattachPluginTools({
|
||||
runtime,
|
||||
agentId,
|
||||
request,
|
||||
stale,
|
||||
}: PluginToolReattach): Promise<void> {
|
||||
let replayed: ReattachedAgentTools[];
|
||||
let taken: Set<string>;
|
||||
try {
|
||||
replayed = await runtime.reattachTools(request, stale);
|
||||
if (replayed.length === 0) return;
|
||||
taken = await this.takenAgentToolNames(agentId);
|
||||
} catch (err) {
|
||||
this.logger.warn({ err, agentId, plugins: stale }, "Plugin tool reattach failed");
|
||||
return;
|
||||
}
|
||||
if (this.pluginOpenRequests.get(agentId) !== request) {
|
||||
// The session closed during the replay, after its detach went out. A reopen waits for every pending refresh
|
||||
// before it detaches, so dropping what the replay attached inside the replayed plugins cannot touch a newer
|
||||
// open's tools.
|
||||
runtime.detachTools(
|
||||
agentId,
|
||||
replayed.map((entry) => entry.pluginId),
|
||||
);
|
||||
return;
|
||||
}
|
||||
const replayedIds = new Set(replayed.map((entry) => entry.pluginId));
|
||||
const kept = (this.attachedPluginTools.get(agentId) ?? []).filter(
|
||||
(tool) => !replayedIds.has(tool.pluginId),
|
||||
);
|
||||
const accepted: AttachedAgentTool[] = [];
|
||||
for (const { pluginId, tools } of replayed) {
|
||||
const conflict = tools.find((tool) => taken.has(tool.name));
|
||||
if (conflict) {
|
||||
// An open with this catalog would fail. Leave the session's other tools working; the reopen reports it.
|
||||
this.logger.warn(
|
||||
{ agentId, pluginId, tool: conflict.name },
|
||||
"Reattached plugin tool collides with another agent tool",
|
||||
);
|
||||
continue;
|
||||
}
|
||||
for (const tool of tools) taken.add(tool.name);
|
||||
accepted.push(...tools);
|
||||
}
|
||||
this.attachedPluginTools.set(agentId, [...kept, ...accepted]);
|
||||
}
|
||||
|
||||
/** Names a refreshed plugin tool must not take: Paseo's own tools and the tools still attached from running plugins. */
|
||||
private async takenAgentToolNames(agentId: string): Promise<Set<string>> {
|
||||
const names = new Set(this.getPluginTools(agentId).map((tool) => tool.name));
|
||||
if (this.paseoToolCatalogFactory) {
|
||||
// An all-enabled policy, so the catalog lists every Paseo tool the plugin check reserves, including the ones
|
||||
// the agent's provider disables. Without a policy the factory falls back to the agent's own.
|
||||
const catalog = await this.paseoToolCatalogFactory({
|
||||
callerAgentId: agentId,
|
||||
paseoToolPolicy: {},
|
||||
});
|
||||
for (const name of catalog.tools.keys()) names.add(name);
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
private detachPluginTools(agentId: string): void {
|
||||
this.attachedPluginTools.delete(agentId);
|
||||
this.pluginOpenRequests.delete(agentId);
|
||||
this.sessionOpenGenerations.delete(agentId);
|
||||
this.pluginAgentTools?.detachTools(agentId);
|
||||
}
|
||||
@@ -6253,6 +6357,15 @@ export class AgentManager {
|
||||
metadata?: AgentMetadata;
|
||||
},
|
||||
): Promise<AgentLaunchContext> {
|
||||
// A tool replay still in flight would otherwise attach its definitions inside the plugin after this open's.
|
||||
// The check and the detach below run in one tick, so no replay can start between them.
|
||||
for (
|
||||
let pending = this.pluginToolRefreshes.get(agentId);
|
||||
pending;
|
||||
pending = this.pluginToolRefreshes.get(agentId)
|
||||
) {
|
||||
await pending;
|
||||
}
|
||||
// A plugin changing during this open must still make the resulting session stale.
|
||||
const generation = this.sessionOpenGeneration;
|
||||
this.detachPluginTools(agentId);
|
||||
@@ -6279,6 +6392,12 @@ export class AgentManager {
|
||||
if (request.purpose === "interactive") {
|
||||
this.attachedPluginTools.set(agentId, transformed.tools as AttachedAgentTool[]);
|
||||
appendSystemPrompt = transformed.appendSystemPrompt;
|
||||
const {
|
||||
mcpServerOwners: _owners,
|
||||
appendSystemPrompt: _instructions,
|
||||
...opened
|
||||
} = transformed;
|
||||
this.pluginOpenRequests.set(agentId, { ...opened, tools: [], mcpServers: {} });
|
||||
mcpServers = transformed.mcpServers;
|
||||
mcpServerOwners = transformed.mcpServerOwners;
|
||||
}
|
||||
|
||||
@@ -1625,6 +1625,7 @@ export async function createPaseoDaemon(
|
||||
const agentMcpRoute = "/mcp/agents";
|
||||
|
||||
const createAgentMcpSession = async (callerAgentId?: string) => {
|
||||
if (callerAgentId) await agentManager.refreshPluginTools(callerAgentId);
|
||||
const agentMcpServer = await createAgentMcpServer(
|
||||
createAgentToolHostDependencies({
|
||||
callerAgentId,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { existsSync } from "node:fs";
|
||||
import { mkdtemp, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
@@ -476,7 +477,7 @@ test("structured tool results get model-visible text when text is omitted", asyn
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test("reloading a plugin retires its old attachments before an agent reopens", async () => {
|
||||
test("reloading a plugin retires its old attachments, and the agent MCP reattaches them from the new instance", async () => {
|
||||
const h = await setup(true);
|
||||
try {
|
||||
const a = await h.create({ x: "y" });
|
||||
@@ -484,12 +485,16 @@ test("reloading a plugin retires its old attachments before an agent reopens", a
|
||||
const oldCatalog = h.launches.at(-1)!.context!.paseoTools!;
|
||||
expect((await mcp.listTools()).tools.map((tool) => tool.name)).toContain("plugin_echo");
|
||||
await h.client.reloadPlugin("tools-test");
|
||||
expect((await mcp.listTools()).tools.map((tool) => tool.name)).not.toContain("plugin_echo");
|
||||
expect(h.daemon.daemon.agentManager.getPluginTools(a.id)).toEqual([]);
|
||||
expect(await oldCatalog.executeTool("plugin_echo", { text: "retired" })).toMatchObject({
|
||||
isError: true,
|
||||
content: [{ type: "text", text: expect.stringContaining("not available") }],
|
||||
});
|
||||
expect((await mcp.listTools()).tools.map((tool) => tool.name)).toContain("plugin_echo");
|
||||
expect(h.daemon.daemon.agentManager.getPluginTools(a.id).map((tool) => tool.name)).toEqual([
|
||||
"plugin_echo",
|
||||
]);
|
||||
expect(h.launches).toHaveLength(1);
|
||||
} finally {
|
||||
await h.close();
|
||||
}
|
||||
@@ -611,6 +616,261 @@ test("a busy agent is steered after plugin reload and reopens only at its next i
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
const openCounterSource = `
|
||||
import { z } from "zod";
|
||||
import { defineAgentTool } from "@getpaseo/plugin/server";
|
||||
let opens = 0;
|
||||
const tool = defineAgentTool({
|
||||
name: "other_opens", description: "How often this plugin saw the session open",
|
||||
input: z.object({}),
|
||||
async execute() { return { text: String(opens) }; },
|
||||
});
|
||||
export default function contribute(server) {
|
||||
server.addHook("agent.open.before", async ({ request }) => {
|
||||
opens++;
|
||||
return { ...request, tools: [...request.tools, tool] };
|
||||
});
|
||||
return () => {};
|
||||
}
|
||||
`;
|
||||
|
||||
test("a busy agent's MCP lists and calls a restarted plugin's tools without reopening", async () => {
|
||||
let release!: () => void;
|
||||
const blocked = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
const h = await setup(false, pluginSource, undefined, {
|
||||
beforeTurnComplete: async () => blocked,
|
||||
});
|
||||
try {
|
||||
await h.install("other-hook", openCounterSource);
|
||||
const a = await h.create({ x: "y" });
|
||||
await h.client.sendMessage(a.id, "busy prompt", { activeTurnBehavior: "steer" });
|
||||
await expect.poll(() => h.daemon.daemon.agentManager.hasInFlightRun(a.id)).toBe(true);
|
||||
await h.client.reloadPlugin("tools-test");
|
||||
await h.client.sendMessage(a.id, "message while busy", { activeTurnBehavior: "steer" });
|
||||
expect(h.daemon.daemon.agentManager.hasInFlightRun(a.id)).toBe(true);
|
||||
|
||||
const mcp = await h.mcp(a.id);
|
||||
const names = (await mcp.listTools()).tools.map((tool) => tool.name);
|
||||
expect(names).toContain("plugin_echo");
|
||||
expect(names).toContain("other_opens");
|
||||
const result = await mcp.callTool({
|
||||
name: "plugin_echo",
|
||||
arguments: { text: "after restart" },
|
||||
});
|
||||
expect(result.isError).not.toBe(true);
|
||||
// The restarted plugin answers: its own call count starts again.
|
||||
expect(JSON.parse((result.content as { text: string }[])[0].text)).toMatchObject({
|
||||
agent: { id: a.id },
|
||||
input: { text: "after restart" },
|
||||
calls: 1,
|
||||
});
|
||||
// Only the restarted plugin saw the replayed open.
|
||||
expect(await mcp.callTool({ name: "other_opens", arguments: {} })).toMatchObject({
|
||||
content: [{ type: "text", text: "1" }],
|
||||
});
|
||||
expect(h.launches).toHaveLength(1);
|
||||
expect(h.events.interrupts).toBe(0);
|
||||
|
||||
// The session still reopens at its next idle prompt, for env and MCP servers.
|
||||
release();
|
||||
await expect.poll(() => h.daemon.daemon.agentManager.hasInFlightRun(a.id)).toBe(false);
|
||||
await sendAndFinish(h, a.id, "idle prompt");
|
||||
expect(h.launches).toHaveLength(2);
|
||||
} finally {
|
||||
release();
|
||||
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);
|
||||
}
|
||||
|
||||
async function listedToolNames(mcp: Client) {
|
||||
return (await mcp.listTools()).tools.map((tool) => tool.name);
|
||||
}
|
||||
|
||||
test("an agent MCP request while a plugin is stopped keeps its tools eligible for the restart", async () => {
|
||||
const h = await setup();
|
||||
try {
|
||||
const a = await h.create({ x: "y" });
|
||||
await h.client.disablePlugin("tools-test");
|
||||
expect(await listedToolNames(await h.mcp(a.id))).not.toContain("plugin_echo");
|
||||
await h.client.enablePlugin("tools-test");
|
||||
expect(await listedToolNames(await h.mcp(a.id))).toContain("plugin_echo");
|
||||
expect(h.launches).toHaveLength(1);
|
||||
} finally {
|
||||
await h.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
// Each open names its tool after its count. Once armed, a process's first open marks that it started and waits
|
||||
// for the gate file.
|
||||
const gatedOpenSource = (arm: string, entered: string, gate: string) => `
|
||||
import { existsSync, writeFileSync } from "node:fs";
|
||||
import { z } from "zod";
|
||||
import { defineAgentTool } from "@getpaseo/plugin/server";
|
||||
let opens = 0;
|
||||
export default function contribute(server) {
|
||||
server.addHook("agent.open.before", async ({ request }) => {
|
||||
const open = ++opens;
|
||||
if (open === 1 && existsSync(${JSON.stringify(arm)})) {
|
||||
writeFileSync(${JSON.stringify(entered)}, "");
|
||||
while (!existsSync(${JSON.stringify(gate)})) await new Promise((r) => setTimeout(r, 20));
|
||||
}
|
||||
const tool = defineAgentTool({
|
||||
name: "which_open", description: "open " + open,
|
||||
input: z.object({}),
|
||||
async execute() { return { text: "open " + open }; },
|
||||
});
|
||||
return { ...request, tools: [...request.tools, tool] };
|
||||
});
|
||||
return () => {};
|
||||
}
|
||||
`;
|
||||
|
||||
test("a reopen during a tool replay keeps the reopen's tool definitions in the plugin", async () => {
|
||||
const h = await setup();
|
||||
const arm = path.join(h.directory, "replay-arm");
|
||||
const entered = path.join(h.directory, "replay-entered");
|
||||
const gate = path.join(h.directory, "replay-gate");
|
||||
try {
|
||||
await h.install("gated", gatedOpenSource(arm, entered, gate));
|
||||
const a = await h.create();
|
||||
await writeFile(arm, "");
|
||||
await h.client.reloadPlugin("gated");
|
||||
// The restarted process counts from zero, so its first open is the replay. Hold it at the gate.
|
||||
const replaying = h.mcp(a.id);
|
||||
await expect.poll(() => existsSync(entered)).toBe(true);
|
||||
const reopening = sendAndFinish(h, a.id, "idle prompt");
|
||||
// Room for an unguarded reopen to reach the plugin first. A guarded one waits, so this cannot change the result.
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
await writeFile(gate, "");
|
||||
const mcp = await replaying;
|
||||
await reopening;
|
||||
expect(h.launches).toHaveLength(2);
|
||||
const mcpAfter = await h.mcp(a.id);
|
||||
expect((await mcpAfter.listTools()).tools.find((t) => t.name === "which_open")).toMatchObject({
|
||||
description: "open 2",
|
||||
});
|
||||
expect(await mcpAfter.callTool({ name: "which_open", arguments: {} })).toMatchObject({
|
||||
content: [{ type: "text", text: "open 2" }],
|
||||
});
|
||||
await mcp.close();
|
||||
} finally {
|
||||
await h.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
const failingReplaySource = (arm: string, opens: string) =>
|
||||
pluginSource
|
||||
.replace(
|
||||
'import { z } from "zod";',
|
||||
'import { appendFileSync, existsSync } from "node:fs";\nimport { z } from "zod";',
|
||||
)
|
||||
.replace(
|
||||
'if (request.labels.x !== "y") return;',
|
||||
`if (request.labels.x !== "y") return;
|
||||
appendFileSync(${JSON.stringify(opens)}, "o");
|
||||
if (existsSync(${JSON.stringify(arm)})) throw new Error("replay failed");`,
|
||||
);
|
||||
|
||||
test("a failed tool replay is not repeated for the same plugin instance, and the next restart replays again", async () => {
|
||||
const scratch = await mkdtemp(path.join(tmpdir(), "paseo-replay-arm-"));
|
||||
const arm = path.join(scratch, "arm");
|
||||
const opens = path.join(scratch, "opens");
|
||||
const openCount = async () => (await readFile(opens, "utf8")).length;
|
||||
const h = await setup(false, failingReplaySource(arm, opens));
|
||||
try {
|
||||
const a = await h.create({ x: "y" });
|
||||
expect(await openCount()).toBe(1);
|
||||
await writeFile(arm, "");
|
||||
await h.client.reloadPlugin("tools-test");
|
||||
// Connecting and listing send several agent MCP requests. Only the first one replays the open.
|
||||
const mcp = await h.mcp(a.id);
|
||||
expect(await listedToolNames(mcp)).toContain("list_agents");
|
||||
expect(await listedToolNames(mcp)).not.toContain("plugin_echo");
|
||||
expect(await openCount()).toBe(2);
|
||||
await mcp.close();
|
||||
|
||||
await rm(arm);
|
||||
await h.client.reloadPlugin("tools-test");
|
||||
expect(await listedToolNames(await h.mcp(a.id))).toContain("plugin_echo");
|
||||
expect(await openCount()).toBe(3);
|
||||
expect(h.launches).toHaveLength(1);
|
||||
} finally {
|
||||
await h.close();
|
||||
await rm(scratch, { recursive: true, force: true });
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
const openReasonSource = `
|
||||
import { z } from "zod";
|
||||
import { defineAgentTool } from "@getpaseo/plugin/server";
|
||||
export default function contribute(server) {
|
||||
server.addHook("agent.open.before", async ({ request }) => ({
|
||||
...request,
|
||||
tools: [...request.tools, defineAgentTool({ name: "open_reason", description: request.reason, input: z.object({}), async execute() { return { text: request.reason }; } })],
|
||||
}));
|
||||
return () => {};
|
||||
}
|
||||
`;
|
||||
|
||||
test("a tool replay reaches the restarted plugin with reason refresh", async () => {
|
||||
const h = await setup(false, openReasonSource);
|
||||
try {
|
||||
const a = await h.create();
|
||||
await h.client.reloadPlugin("tools-test");
|
||||
const mcp = await h.mcp(a.id);
|
||||
expect((await mcp.listTools()).tools.find((t) => t.name === "open_reason")).toMatchObject({
|
||||
description: "refresh",
|
||||
});
|
||||
expect(h.launches).toHaveLength(1);
|
||||
} finally {
|
||||
await h.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
const nameClashSource = (name: string) =>
|
||||
pluginSource.replace(
|
||||
"tools: [...request.tools, tool]",
|
||||
`tools: [...request.tools, tool, defineAgentTool({ name: ${JSON.stringify(name)}, description: "clash", input: z.object({}), async execute() { return { text: "clash" }; } })]`,
|
||||
);
|
||||
|
||||
test.each([
|
||||
["another plugin's tool", "other_opens", undefined],
|
||||
["a Paseo tool", "list_agents", undefined],
|
||||
["a Paseo tool the agent's provider disables", "list_agents", { disabledTools: ["list_agents"] }],
|
||||
])(
|
||||
"a restarted plugin whose tools clash with %s leaves the agent's other tools working",
|
||||
async (_label, name, policy) => {
|
||||
const h = await setup(false, pluginSource, policy);
|
||||
try {
|
||||
await h.install("other-hook", openCounterSource);
|
||||
const a = await h.create({ x: "y" });
|
||||
await writePluginSource(h, "tools-test", nameClashSource(name));
|
||||
await h.client.reloadPlugin("tools-test");
|
||||
const mcp = await h.mcp(a.id);
|
||||
const names = await listedToolNames(mcp);
|
||||
expect(names).toContain("other_opens");
|
||||
expect(names.includes("list_agents")).toBe(policy === undefined);
|
||||
expect(names).toContain("get_agent_status");
|
||||
expect(names).not.toContain("plugin_echo");
|
||||
expect(await mcp.callTool({ name: "other_opens", arguments: {} })).toMatchObject({
|
||||
content: [{ type: "text", text: "1" }],
|
||||
});
|
||||
expect(h.daemon.daemon.agentManager.getPluginTools(a.id).map((t) => t.pluginId)).toEqual([
|
||||
"other-hook",
|
||||
]);
|
||||
} finally {
|
||||
await h.close();
|
||||
}
|
||||
},
|
||||
60_000,
|
||||
);
|
||||
|
||||
const reloadRpcSource = pluginSource
|
||||
.replace("import { z }", 'import { defineRpc } from "@getpaseo/plugin";\nimport { z }')
|
||||
.replace(
|
||||
|
||||
@@ -27,9 +27,23 @@ export type SessionOpenWireRequest = Omit<PluginSessionOpenRequest, "tools"> & {
|
||||
tools: AgentToolMetadata[];
|
||||
};
|
||||
|
||||
export interface ReattachedAgentTools {
|
||||
pluginId: string;
|
||||
tools: AttachedAgentTool[];
|
||||
}
|
||||
|
||||
export interface PluginAgentToolsRuntime {
|
||||
isToolPluginAvailable(pluginId: string, pluginInstanceId: string): boolean;
|
||||
detachTools(agentId: string): void;
|
||||
/**
|
||||
* Replays a live session's open to the named plugins and returns their tools, stamped with the running instance.
|
||||
* Plugins that are not running or fail the replay are left out.
|
||||
*/
|
||||
reattachTools(
|
||||
request: SessionOpenWireRequest,
|
||||
pluginIds: readonly string[],
|
||||
): Promise<ReattachedAgentTools[]>;
|
||||
/** Drops an agent's tools inside the named plugins, or inside every plugin when none are named. */
|
||||
detachTools(agentId: string, pluginIds?: readonly string[]): void;
|
||||
callTool(
|
||||
pluginId: string,
|
||||
pluginInstanceId: string,
|
||||
|
||||
@@ -41,6 +41,7 @@ const BUILTIN_PROVIDER_ID_SET: ReadonlySet<string> = new Set(BUILTIN_PROVIDER_ID
|
||||
interface PluginRuntimePort {
|
||||
subscribeSessionOpenChanges?: PluginRuntime["subscribeSessionOpenChanges"];
|
||||
isToolPluginAvailable?: PluginRuntime["isToolPluginAvailable"];
|
||||
reattachTools?: PluginRuntime["reattachTools"];
|
||||
callTool?: PluginRuntime["callTool"];
|
||||
detachTools?: PluginRuntime["detachTools"];
|
||||
emit?: PluginLifecycle["emit"];
|
||||
@@ -154,8 +155,12 @@ export class PluginService {
|
||||
return this.runtime.isToolPluginAvailable?.(pluginId, pluginInstanceId) ?? false;
|
||||
};
|
||||
|
||||
readonly detachTools: PluginAgentToolsRuntime["detachTools"] = (agentId) => {
|
||||
this.runtime.detachTools?.(agentId);
|
||||
readonly reattachTools: PluginAgentToolsRuntime["reattachTools"] = async (request, pluginIds) => {
|
||||
return (await this.runtime.reattachTools?.(request, pluginIds)) ?? [];
|
||||
};
|
||||
|
||||
readonly detachTools: PluginAgentToolsRuntime["detachTools"] = (agentId, pluginIds) => {
|
||||
this.runtime.detachTools?.(agentId, pluginIds);
|
||||
};
|
||||
|
||||
readonly callTool: PluginAgentToolsRuntime["callTool"] = async (
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import { validateWorktreePath } from "../../utils/worktree-path.js";
|
||||
import type { PluginHookPayload } from "@getpaseo/plugin/server";
|
||||
import type { PluginWireBeforeRequests, PluginBeforeResults } from "./lifecycle/index.js";
|
||||
import type { SessionOpenWireRequest, AttachedAgentTool } from "./agent-tools.js";
|
||||
import type {
|
||||
SessionOpenWireRequest,
|
||||
AttachedAgentTool,
|
||||
ReattachedAgentTools,
|
||||
} from "./agent-tools.js";
|
||||
import type { UsageScope } from "@getpaseo/plugin/server/usage";
|
||||
import {
|
||||
ProviderStatusSchema,
|
||||
@@ -281,6 +285,8 @@ function send(child: PluginChild, message: PluginProcessRequest): Promise<void>
|
||||
|
||||
export class PluginRuntime {
|
||||
private readonly plugins = new Map<string, LoadedPlugin>();
|
||||
/** Per agent, the plugin instance whose tool replay failed. That instance is not replayed again for the agent. */
|
||||
private readonly failedToolReplays = new Map<string, Map<string, string>>();
|
||||
private readonly pendingEvents = new Set<Promise<void>>();
|
||||
private readonly logTails = new Map<string, PluginLogTail>();
|
||||
private readonly logger: pino.Logger;
|
||||
@@ -710,8 +716,61 @@ export class PluginRuntime {
|
||||
return this.plugins.get(pluginId)?.instanceId === pluginInstanceId;
|
||||
}
|
||||
|
||||
detachTools(agentId: string): void {
|
||||
// A restarted plugin has a new instance id, so a live session's tools from it are stranded until the session
|
||||
// reopens. Only the named plugins see the replayed open, so no other plugin's hook runs twice for one session.
|
||||
// Env and MCP server changes are dropped: those belong to the provider process and still need a reopen.
|
||||
// The replay arrives as `refresh`, like the reopen the same restart causes for an idle agent.
|
||||
// A plugin that is stopped, mid-restart, or fails the replay is left out of the result, so the caller keeps it
|
||||
// eligible. A failed replay is not repeated for the same plugin instance: the next restart gets a new try.
|
||||
async reattachTools(
|
||||
request: SessionOpenWireRequest,
|
||||
pluginIds: readonly string[],
|
||||
): Promise<ReattachedAgentTools[]> {
|
||||
const input: SessionOpenWireRequest = {
|
||||
...request,
|
||||
reason: "refresh",
|
||||
tools: [],
|
||||
mcpServers: {},
|
||||
};
|
||||
// Detaching the agent drops this record, so a replay that fails after its agent closed records nothing.
|
||||
const failed = this.failedToolReplays.get(request.agentId) ?? new Map<string, string>();
|
||||
this.failedToolReplays.set(request.agentId, failed);
|
||||
const replayed: ReattachedAgentTools[] = [];
|
||||
for (const pluginId of pluginIds) {
|
||||
const loaded = this.plugins.get(pluginId);
|
||||
if (!loaded || failed.get(pluginId) === loaded.instanceId) continue;
|
||||
if (!loaded.child || !loaded.hooks.includes("agent.open.before")) {
|
||||
replayed.push({ pluginId, tools: [] });
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
const output = await this.request(loaded, {
|
||||
type: "hook",
|
||||
requestId: randomUUID(),
|
||||
name: "agent.open.before",
|
||||
input,
|
||||
});
|
||||
const opened = await validateBeforeResult("agent.open.before", input, output);
|
||||
const tools: AttachedAgentTool[] = [];
|
||||
this.collectAgentTools(tools, loaded, opened.tools);
|
||||
replayed.push({ pluginId, tools });
|
||||
} catch (error) {
|
||||
// Left out like a stopped plugin. The next instance of this plugin is replayed again.
|
||||
failed.set(pluginId, loaded.instanceId);
|
||||
this.logger.warn(
|
||||
{ err: error, pluginId, agentId: request.agentId },
|
||||
"Plugin tool reattach failed",
|
||||
);
|
||||
}
|
||||
}
|
||||
return replayed;
|
||||
}
|
||||
|
||||
/** Drops an agent's tools inside the named plugins, or inside every plugin when none are named. */
|
||||
detachTools(agentId: string, pluginIds?: readonly string[]): void {
|
||||
if (!pluginIds) this.failedToolReplays.delete(agentId);
|
||||
for (const loaded of this.plugins.values()) {
|
||||
if (pluginIds && !pluginIds.includes(loaded.id)) continue;
|
||||
if (loaded.child) void send(loaded.child, { type: "tools.detach", agentId }).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -496,12 +496,12 @@ tool or another plugin's tool on the same agent fails the session open and names
|
||||
A duplicate name within one plugin also fails the session open. Agents the callback does not
|
||||
target are unaffected.
|
||||
|
||||
| Change | When the agent receives it |
|
||||
| ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Start, stop, or reload a plugin declaring `agent.open.before` | Open sessions become stale. Each reopens before its next idle prompt; a running turn continues without interruption. The next prompt after that reopen reuses the session. |
|
||||
| Change which agents the callback targets | Run `paseo plugin reload agent-tools` after editing this example, then send the agent a prompt when it is idle. |
|
||||
| Apply immediately | Call `await paseo.agents.ref(id).reload({ requestId: "reload-notes" })`. `requestId` is optional. This reopens the provider session, reruns hooks with `reason: "refresh"`, and interrupts a running turn. |
|
||||
| Read the current snapshot | Call `await paseo.agents.ref(id).refresh()`. This reads state without reopening the session. |
|
||||
| Change | When the agent receives it |
|
||||
| ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Start, stop, or reload a plugin declaring `agent.open.before` | Open sessions become stale. Each reopens before its next idle prompt; a running turn continues without interruption. The next prompt after that reopen reuses the session. Until then, a restarted plugin's tools stay available over the agent's MCP: Paseo reruns only that plugin's callback with the session's open request, with `reason: "refresh"`, and keeps the tools it returns. If that callback throws or times out, Paseo does not rerun it for the same plugin instance; the next restart tries again. Agents that receive Paseo tools natively (OpenCode with the bridge, OMP) keep their launch-time tools until the reopen, so a restarted plugin's tools fail for them until then. If one of those tools collides with a Paseo tool or another plugin's tool, that plugin's tools stay off until the reopen, which fails with the collision. |
|
||||
| Change which agents the callback targets | Run `paseo plugin reload agent-tools` after editing this example, then send the agent a prompt when it is idle. |
|
||||
| Apply immediately | Call `await paseo.agents.ref(id).reload({ requestId: "reload-notes" })`. `requestId` is optional. This reopens the provider session, reruns hooks with `reason: "refresh"`, and interrupts a running turn. |
|
||||
| Read the current snapshot | Call `await paseo.agents.ref(id).refresh()`. This reads state without reopening the session. |
|
||||
|
||||
If an automatic reopen fails, the triggering prompt fails with that error. See the
|
||||
[complete agent-tools example](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-tools).
|
||||
|
||||
Reference in New Issue
Block a user