fix(server): reopen only sessions a plugin change affects

A plugin reload bumped one global session-open generation, so every live
agent reopened at its next idle prompt. The reopen closes the provider
session, cancels its subagents and clears background work, even for agents
the plugin never touched.

SessionAttachments now owns what each agent.open.before plugin contributed
to each live session. A refresh reruns only the plugins whose instance
changed, swaps their tools in place, and marks the session stale only when
its launch would differ. This replaces the AgentManager maps, the runtime's
failed-replay record, and the global generation. Native-tool providers
resolve plugin tools by name at call time, so their calls reach the new
instance.
This commit is contained in:
Mohamed Boudra
2026-11-25 12:07:59 +01:00
parent fb8ee48859
commit a1f408dcc4
12 changed files with 577 additions and 361 deletions
+4
View File
@@ -464,6 +464,10 @@ registry property, independent of position. The [hooks reference](../public-docs
owns payloads, ordering, failure behavior, and examples. `agent.create.before` edits saved
configuration; `agent.open.before` contributes launch-only `env`, `tools`, and `mcpServers` on
every open. Executable tool definitions stay in the plugin process; only metadata crosses the boundary.
`packages/server/src/server/plugins/session-attachments.ts` records what each plugin contributed to
each live session. A plugin start, stop, or reload reruns only that plugin's callback per session,
swaps its tools in place, and reopens a session only when its launch would differ. A reopen closes
the provider process, so a reload must not reopen agents the plugin does not change.
Worktree placement is resolved before Git source planning, so a hook can change the branch and base
without undoing fetched refs. Restores use the recorded destination and bypass creation hooks.
@@ -1,3 +1,4 @@
import type { PluginSessionsRuntime } from "../plugins/agent-tools.js";
import { createIdleRuntimeCleanup } from "./idle-runtime-cleanup/index.js";
import {
prepareAgentMessage,
@@ -679,6 +680,22 @@ async function startAndSteerThroughManager(
return { manager, agentId: agent.id, workdir };
}
/** Plugin sessions whose only plugin appends the given instructions to every open. */
function instructionPluginSessions(instructions: () => string[]): PluginSessionsRuntime {
return {
openSession: async (request) => ({
...request,
appendSystemPrompt: instructions(),
tools: [],
mcpServerOwners: {},
}),
refreshSession: async () => ({ stale: false }),
sessionTools: () => [],
closeSession: () => {},
callTool: async () => ({ isError: true, text: "No plugin tools" }),
};
}
test("OpenCode persistence excludes launch-only instructions from storage and clients", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-plugin-persistence-"));
const harness = new V2Harness();
@@ -690,13 +707,7 @@ test("OpenCode persistence excludes launch-only instructions from storage and cl
registry: storage,
logger,
appendSystemPrompt: "Daemon instruction",
pluginLifecycle: {
emit: () => {},
before: async (name, request) =>
name === "agent.open.before"
? { ...request, appendSystemPrompt: ["Plugin instruction"] }
: request,
},
pluginSessions: instructionPluginSessions(() => ["Plugin instruction"]),
});
const agent = await manager.createAgent({ provider: "opencode", cwd: workdir }, undefined, {
workspaceId: undefined,
@@ -16144,11 +16155,7 @@ test("plugin instructions are recomputed for each launch without changing saved
registry: storage,
logger,
appendSystemPrompt: "Daemon",
pluginLifecycle: {
emit: () => {},
before: async (name, request) =>
name === "agent.open.before" ? { ...request, appendSystemPrompt: additions } : request,
},
pluginSessions: instructionPluginSessions(() => additions),
});
const snapshot = await manager.createAgent(
{ provider: "codex", cwd: workdir, systemPrompt: "Saved" },
+44 -153
View File
@@ -1,9 +1,4 @@
import type {
AttachedAgentTool,
PluginAgentToolsRuntime,
ReattachedAgentTools,
SessionOpenWireRequest,
} from "../plugins/agent-tools.js";
import type { AttachedAgentTool, PluginSessionsRuntime } 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";
@@ -208,13 +203,6 @@ async function assertUsableWorkingDirectory(cwd: string): Promise<void> {
}
}
interface PluginToolReattach {
runtime: PluginAgentToolsRuntime;
agentId: string;
request: SessionOpenWireRequest;
stale: readonly string[];
}
interface StopAgentBackgroundWorkOptions {
agentId: string;
itemId: string;
@@ -411,7 +399,7 @@ export interface AgentManagerOptions {
terminalManager?: TerminalManager | null;
mcpBaseUrl?: string;
mcpAuthToken?: string;
pluginAgentTools?: PluginAgentToolsRuntime;
pluginSessions?: PluginSessionsRuntime;
paseoToolsEnabled?: boolean;
paseoToolCatalogFactory?: PaseoToolCatalogFactory;
resolvePaseoToolPolicy?: (provider: AgentProvider) => ProviderPaseoToolsPolicy | undefined;
@@ -949,12 +937,7 @@ export class AgentManager {
private readonly agentStreamCoalescer: AgentStreamCoalescer;
private mcpBaseUrl: string | null;
private readonly mcpAuthToken: string | null;
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 readonly pluginSessions: PluginSessionsRuntime | undefined;
private paseoToolsEnabled = true;
private paseoToolCatalogFactory: PaseoToolCatalogFactory | null = null;
private readonly paseoToolPolicies = new Map<string, ProviderPaseoToolsPolicy | undefined>();
@@ -972,7 +955,7 @@ export class AgentManager {
constructor(options: AgentManagerOptions) {
this.pluginLifecycle = options.pluginLifecycle;
this.pluginAgentTools = options.pluginAgentTools;
this.pluginSessions = options.pluginSessions;
this.timelineStore = options.timelineStore ?? new InMemoryAgentTimelineStore();
this.idFactory = options.idFactory ?? (() => randomUUID());
this.registry = options?.registry;
@@ -1077,47 +1060,57 @@ export class AgentManager {
this.paseoToolCatalogFactory = factory;
}
invalidatePluginSessions(): void {
this.sessionOpenGeneration++;
}
/**
* Reopens an idle agent whose plugin attachment changed in a way the running provider session cannot pick up:
* env, instructions, MCP servers, or tool definitions. A plugin change that leaves the agent's launch as it was
* keeps the session, with its background work and subagents.
*/
async reloadStalePluginSession(agentId: string): Promise<void> {
if (!this.needsPluginSessionReload(agentId)) return;
if (!(await this.needsPluginSessionReload(agentId))) return;
await this.trackAgentRegistrationOperation(
this.runLifecycleMutation(agentId, async () => {
if (!this.needsPluginSessionReload(agentId)) return;
if (!(await this.needsPluginSessionReload(agentId))) return;
await this.reloadAgentSessionInternal(agentId);
}),
);
}
private needsPluginSessionReload(agentId: string): boolean {
private async needsPluginSessionReload(agentId: string): Promise<boolean> {
const agent = this.getAgent(agentId);
return (
agent !== null &&
agent.lifecycle !== "closed" &&
this.sessionOpenGenerations.get(agentId) !== this.sessionOpenGeneration &&
!this.hasInFlightRun(agentId)
);
if (!agent || agent.lifecycle === "closed" || this.hasInFlightRun(agentId)) return false;
return (await this.refreshPluginTools(agentId)).stale;
}
getPluginTools(agentId: string): readonly AttachedAgentTool[] {
return (this.attachedPluginTools.get(agentId) ?? []).filter((tool) =>
this.pluginAgentTools?.isToolPluginAvailable(tool.pluginId, tool.pluginInstanceId),
);
return this.pluginSessions?.sessionTools(agentId) ?? [];
}
/**
* Brings a live session's plugin tools up to date with the running plugins. A plugin restart gives it a new
* instance; only that plugin's open is rerun for the session, without reopening it or interrupting its turn.
*/
async refreshPluginTools(agentId: string): Promise<{ stale: boolean }> {
if (!this.pluginSessions) return { stale: false };
return this.pluginSessions.refreshSession(agentId, {
reservedToolNames: () => this.reservedAgentToolNames(agentId),
});
}
/** Resolves the tool by name at call time, so a launch-time catalog reaches a restarted plugin. */
async executePluginTool(
tool: AttachedAgentTool,
toolName: string,
agentId: string,
input: unknown,
signal?: AbortSignal,
): Promise<AgentToolResult> {
const agent = this.getAgent(agentId);
if (!agent || agent.lifecycle === "closed") throw new Error(`Agent is not live: ${agentId}`);
if (!this.pluginAgentTools) throw new Error("Plugin tools are unavailable");
if (!this.pluginSessions) throw new Error("Plugin tools are unavailable");
await this.refreshPluginTools(agentId);
const tool = this.getPluginTools(agentId).find((entry) => entry.name === toolName);
if (!tool) return { isError: true, text: `Plugin tool is not available: ${toolName}` };
const record = await this.registry?.get(agentId);
return this.pluginAgentTools.callTool(
return this.pluginSessions.callTool(
tool.pluginId,
tool.pluginInstanceId,
describeHookAgent({ ...agent, title: record?.title ?? agent.config.title }),
@@ -1127,100 +1120,18 @@ 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;
/** Paseo's own tool names, including the ones the agent's provider disables, and its running plugin tools. */
private async reservedAgentToolNames(agentId: string): Promise<ReadonlySet<string>> {
if (!this.paseoToolCatalogFactory) return new Set();
const catalog = await this.paseoToolCatalogFactory({
callerAgentId: agentId,
paseoToolPolicy: {},
});
return new Set(catalog.tools.keys());
}
private detachPluginTools(agentId: string): void {
this.attachedPluginTools.delete(agentId);
this.pluginOpenRequests.delete(agentId);
this.sessionOpenGenerations.delete(agentId);
this.pluginAgentTools?.detachTools(agentId);
this.pluginSessions?.closeSession(agentId);
}
getPaseoToolPolicy(agentId: string): ProviderPaseoToolsPolicy | undefined {
@@ -6617,22 +6528,10 @@ 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);
let appendSystemPrompt: string[] | undefined;
let mcpServers: AgentSessionConfig["mcpServers"];
let mcpServerOwners: Record<string, string> | undefined;
if (this.pluginLifecycle) {
if (this.pluginSessions) {
const request = {
agentId,
provider: client.provider,
@@ -6647,17 +6546,10 @@ export class AgentManager {
tools: [],
mcpServers: {},
};
const transformed = await this.pluginLifecycle.before("agent.open.before", request);
const transformed = await this.pluginSessions.openSession(request);
env = transformed.env;
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;
}
@@ -6691,7 +6583,6 @@ export class AgentManager {
throw error;
}
}
this.sessionOpenGenerations.set(agentId, generation);
return context;
}
@@ -28,7 +28,12 @@ export function registerPluginTools(options: {
description: tool.description,
inputSchema: z.fromJSONSchema(tool.inputSchema),
async handler(input, { signal }) {
const result = await agentManager.executePluginTool(tool, callerAgentId, input, signal);
const result = await agentManager.executePluginTool(
tool.name,
callerAgentId,
input,
signal,
);
return addModelVisibleStructuredContent({
content: result.text === undefined ? [] : [{ type: "text", text: result.text }],
structuredContent: result.structuredContent,
+1 -7
View File
@@ -1047,7 +1047,7 @@ export async function createPaseoDaemon(
const initialAgentManagerState = providerSnapshotManager.getAgentManagerProviderState();
const agentManager = new AgentManager({
pluginLifecycle: pluginRuntime,
pluginAgentTools: pluginRuntime,
pluginSessions: pluginRuntime,
clients: initialAgentManagerState.clients,
providerDefinitions: initialAgentManagerState.providerDefinitions,
registry: agentStorage,
@@ -1068,10 +1068,6 @@ export async function createPaseoDaemon(
const unsubscribePluginProviders =
pluginRuntime.subscribeProviderRegistrations(syncPluginProviders);
const unsubscribePluginSessionChanges = pluginRuntime.subscribeSessionOpenChanges(() => {
agentManager.invalidatePluginSessions();
});
const detachAgentStoragePersistence = attachAgentStoragePersistence(
logger,
agentManager,
@@ -2046,7 +2042,6 @@ export async function createPaseoDaemon(
localCredential = null;
await deleteLocalCredential(config.paseoHome);
unsubscribePluginProviders();
unsubscribePluginSessionChanges();
await pluginRuntime.stopAllPlugins().catch(() => undefined);
await serviceProxy.stopStandalone().catch(() => undefined);
await agentProviderRuntime.shutdown().catch(() => undefined);
@@ -2068,7 +2063,6 @@ export async function createPaseoDaemon(
// that is still open. Plugins themselves are stopped once every session
// they serve has been closed, further down.
unsubscribePluginProviders();
unsubscribePluginSessionChanges();
await hubRelationships.stop();
workspaceReconciliation.dispose();
scriptHealthMonitor.stop();
@@ -477,18 +477,25 @@ test("structured tool results get model-visible text when text is omitted", asyn
}
}, 60_000);
test("reloading a plugin retires its old attachments, and the agent MCP reattaches them from the new instance", async () => {
test("reloading a plugin retires its old attachments, and both the agent MCP and the launch-time catalog reach the new instance", async () => {
const h = await setup(true);
try {
const a = await h.create({ x: "y" });
const mcp = await h.mcp(a.id);
const oldCatalog = h.launches.at(-1)!.context!.paseoTools!;
const launchCatalog = h.launches.at(-1)!.context!.paseoTools!;
expect((await mcp.listTools()).tools.map((tool) => tool.name)).toContain("plugin_echo");
expect((await launchCatalog.executeTool("plugin_echo", { text: "before" })).isError).not.toBe(
true,
);
await h.client.reloadPlugin("tools-test");
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") }],
// A native provider keeps the catalog it launched with. Its call reaches the restarted plugin, whose own call
// count starts again.
const result = await launchCatalog.executeTool("plugin_echo", { text: "after restart" });
expect(result.isError).not.toBe(true);
expect(JSON.parse((result.content as { text: string }[])[0].text)).toMatchObject({
input: { text: "after restart" },
calls: 1,
});
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([
@@ -673,7 +680,8 @@ test("a busy agent's MCP lists and calls a restarted plugin's tools without reop
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.
// The plugin's env records the open reason, and the replay's `refresh` differs from the create, so the session
// reopens at its next idle prompt to apply it.
release();
await expect.poll(() => h.daemon.daemon.agentManager.hasInFlightRun(a.id)).toBe(false);
await sendAndFinish(h, a.id, "idle prompt");
@@ -684,6 +692,47 @@ test("a busy agent's MCP lists and calls a restarted plugin's tools without reop
}
}, 60_000);
function subagentStatuses(h: Awaited<ReturnType<typeof setup>>, agentId: string) {
return h.daemon.daemon.agentManager
.listProviderSubagentActivity()
.filter((subagent) => subagent.parentAgentId === agentId)
.map((subagent) => subagent.status);
}
test("reloading a plugin keeps an agent it does not target on its provider session, with its subagents running", async () => {
const h = await setup();
try {
const b = await h.create();
await sendAndFinish(h, b.id, "Emit a provider child");
expect(subagentStatuses(h, b.id)).toEqual(["running"]);
await h.client.reloadPlugin("tools-test");
await sendAndFinish(h, b.id, "after reload");
expect(h.launches).toHaveLength(1);
expect(subagentStatuses(h, b.id)).toEqual(["running"]);
} finally {
await h.close();
}
}, 60_000);
test("a restarted plugin that attaches the same tools keeps the agent's session, and the new instance answers", async () => {
const h = await setup(false, openCounterSource);
try {
const a = await h.create();
await sendAndFinish(h, a.id, "Emit a provider child");
await h.client.reloadPlugin("tools-test");
await sendAndFinish(h, a.id, "after reload");
expect(h.launches).toHaveLength(1);
expect(subagentStatuses(h, a.id)).toEqual(["running"]);
// The restarted instance counts the one replayed open.
const mcp = await h.mcp(a.id);
expect(await mcp.callTool({ name: "other_opens", arguments: {} })).toMatchObject({
content: [{ type: "text", text: "1" }],
});
} 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);
}
@@ -744,7 +793,8 @@ test("a reopen during a tool replay keeps the reopen's tool definitions in the p
// 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");
// The restarted plugin attaches the same definition, so only an explicit reload reopens the session here.
const reopening = h.daemon.daemon.agentManager.reloadAgentSession(a.id);
// 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, "");
@@ -1118,7 +1168,7 @@ test("installing and disabling an MCP plugin reopens idle sessions before their
}
}, 60_000);
test("installing and disabling an MCP plugin never interrupts a running turn", async () => {
test("installing and disabling an MCP plugin during a running turn neither interrupts it nor reopens the session", async () => {
let release!: () => void;
const blocked = new Promise<void>((resolve) => {
release = resolve;
@@ -1144,8 +1194,9 @@ test("installing and disabling an MCP plugin never interrupts a running turn", a
expect(h.events.interrupts).toBe(0);
release();
await expect.poll(() => manager.hasInFlightRun(a.id)).toBe(false);
// The plugin came and went before the session saw it, so the launch is unchanged.
await sendAndFinish(h, a.id, "idle");
expect(h.launches).toHaveLength(2);
expect(h.launches).toHaveLength(1);
expect(h.launches.at(-1)!.config.mcpServers?.company).toBeUndefined();
} finally {
release();
@@ -27,23 +27,31 @@ export type SessionOpenWireRequest = Omit<PluginSessionOpenRequest, "tools"> & {
tools: AgentToolMetadata[];
};
export interface ReattachedAgentTools {
pluginId: string;
export type PluginSessionOpenResult = SessionOpenWireRequest & {
tools: AttachedAgentTool[];
mcpServerOwners: Record<string, string>;
};
export interface PluginSessionRefreshOptions {
/** Tool names a refreshed plugin tool must not take, beyond the tools other plugins attached. */
reservedToolNames(): Promise<ReadonlySet<string>>;
}
export interface PluginAgentToolsRuntime {
isToolPluginAvailable(pluginId: string, pluginInstanceId: string): boolean;
/** What the agent manager asks of plugins about a session: its open, its attached tools, and their calls. */
export interface PluginSessionsRuntime {
/** Runs every `agent.open.before` callback for a session open and records what each plugin attached. */
openSession(request: SessionOpenWireRequest): Promise<PluginSessionOpenResult>;
/**
* 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.
* Reruns the open of only the plugins that changed since the session opened, swaps in their tools, and reports
* whether the session must reopen to apply the rest.
*/
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;
refreshSession(
agentId: string,
options: PluginSessionRefreshOptions,
): Promise<{ stale: boolean }>;
/** The session's tools from running plugin instances. */
sessionTools(agentId: string): readonly AttachedAgentTool[];
closeSession(agentId: string): void;
callTool(
pluginId: string,
pluginInstanceId: string,
+15 -19
View File
@@ -1,4 +1,4 @@
import type { PluginAgentToolsRuntime } from "./agent-tools.js";
import type { PluginSessionsRuntime } from "./agent-tools.js";
import type { PluginLifecycle } from "./lifecycle/index.js";
import path from "node:path";
import { stat, rm } from "node:fs/promises";
@@ -42,11 +42,9 @@ import type { PluginUsageSourceMetadata } from "./plugin-process-protocol.js";
const BUILTIN_PROVIDER_ID_SET: ReadonlySet<string> = new Set(BUILTIN_PROVIDER_IDS);
interface PluginRuntimePort {
subscribeSessionOpenChanges?: PluginRuntime["subscribeSessionOpenChanges"];
sessionAttachments?: PluginRuntime["sessionAttachments"];
isToolPluginAvailable?: PluginRuntime["isToolPluginAvailable"];
reattachTools?: PluginRuntime["reattachTools"];
callTool?: PluginRuntime["callTool"];
detachTools?: PluginRuntime["detachTools"];
emit?: PluginLifecycle["emit"];
drainEvents?: PluginRuntime["drainEvents"];
before?: PluginLifecycle["before"];
@@ -154,26 +152,24 @@ export class PluginService {
this.runtime.emit?.(name, event);
};
subscribeSessionOpenChanges(listener: () => void): () => void {
return this.runtime.subscribeSessionOpenChanges?.(listener) ?? (() => {});
}
readonly isToolPluginAvailable: PluginAgentToolsRuntime["isToolPluginAvailable"] = (
pluginId,
pluginInstanceId,
) => {
return this.runtime.isToolPluginAvailable?.(pluginId, pluginInstanceId) ?? false;
readonly openSession: PluginSessionsRuntime["openSession"] = async (request) => {
if (this.runtime.sessionAttachments) return this.runtime.sessionAttachments.open(request);
return { ...request, tools: [], mcpServers: {}, mcpServerOwners: {} };
};
readonly reattachTools: PluginAgentToolsRuntime["reattachTools"] = async (request, pluginIds) => {
return (await this.runtime.reattachTools?.(request, pluginIds)) ?? [];
readonly refreshSession: PluginSessionsRuntime["refreshSession"] = async (agentId, options) => {
return (await this.runtime.sessionAttachments?.refresh(agentId, options)) ?? { stale: false };
};
readonly detachTools: PluginAgentToolsRuntime["detachTools"] = (agentId, pluginIds) => {
this.runtime.detachTools?.(agentId, pluginIds);
readonly sessionTools: PluginSessionsRuntime["sessionTools"] = (agentId) => {
return this.runtime.sessionAttachments?.tools(agentId) ?? [];
};
readonly callTool: PluginAgentToolsRuntime["callTool"] = async (
readonly closeSession: PluginSessionsRuntime["closeSession"] = (agentId) => {
this.runtime.sessionAttachments?.close(agentId);
};
readonly callTool: PluginSessionsRuntime["callTool"] = async (
pluginId,
pluginInstanceId,
agent,
@@ -181,7 +177,7 @@ export class PluginService {
input,
signal,
) => {
if (!this.isToolPluginAvailable(pluginId, pluginInstanceId) || !this.runtime.callTool)
if (!this.runtime.isToolPluginAvailable?.(pluginId, pluginInstanceId) || !this.runtime.callTool)
return { isError: true, text: `Plugin is not available: ${pluginId}` };
return this.runtime.callTool(pluginId, pluginInstanceId, agent, name, input, signal);
};
@@ -34,10 +34,11 @@ export type PluginWireBeforeRequests = Omit<PluginHookRequests, "agent.open.befo
"agent.open.before": SessionOpenWireRequest;
};
/** Daemon-only results; ownership never crosses the plugin process boundary. */
export type PluginBeforeResults = PluginWireBeforeRequests & {
"agent.open.before": SessionOpenWireRequest & { mcpServerOwners?: Record<string, string> };
};
/** Session opens run through the plugin runtime's session attachments, which record each plugin's contribution. */
export type PluginLifecycleBeforeName = Exclude<
keyof PluginWireBeforeRequests,
"agent.open.before"
>;
const worktreeRequestFields = {
repoRoot: z.string(),
@@ -144,10 +145,10 @@ export interface PluginLifecycle {
payload: PluginHookPayload<"worktree.create.after">,
): Promise<void>;
emit<Name extends keyof PluginHookEvents>(name: Name, event: PluginHookEvents[Name]): void;
before<Name extends keyof PluginWireBeforeRequests>(
before<Name extends PluginLifecycleBeforeName>(
name: Name,
request: PluginWireBeforeRequests[Name],
): Promise<PluginBeforeResults[Name]>;
): Promise<PluginWireBeforeRequests[Name]>;
}
export function validateBeforeRequest<Name extends keyof PluginWireBeforeRequests>(
+36 -136
View File
@@ -1,11 +1,7 @@
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,
ReattachedAgentTools,
} from "./agent-tools.js";
import type { PluginLifecycleBeforeName, PluginWireBeforeRequests } from "./lifecycle/index.js";
import { SessionAttachments, type SessionOpenPlugin } from "./session-attachments.js";
import type { UsageScope } from "@getpaseo/plugin/server/usage";
import {
ProviderInspectionSchema,
@@ -372,15 +368,14 @@ 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;
private readonly spawnChild: () => PluginChild;
private sessionHost: PluginPaseoSessionHost | null;
private readonly listeners = new Set<(pluginId: string, error?: string) => void>();
private readonly sessionOpenListeners = new Set<() => void>();
/** What `agent.open.before` plugins attached to each live session. */
readonly sessionAttachments: SessionAttachments;
constructor(
logger: pino.Logger,
@@ -390,6 +385,13 @@ export class PluginRuntime {
this.logger = logger.child({ module: "plugins" });
this.spawnChild = dependencies.spawnChild ?? spawnPluginChild;
this.sessionHost = dependencies.sessionHost ?? null;
this.sessionAttachments = new SessionAttachments(
{
sessionOpenPlugins: () => this.sessionOpenPlugins(),
detachEverywhere: (agentId) => this.detachTools(agentId),
},
this.logger,
);
}
bindPaseoSessionHost(sessionHost: PluginPaseoSessionHost): void {
@@ -403,16 +405,6 @@ export class PluginRuntime {
return () => this.listeners.delete(listener);
}
subscribeSessionOpenChanges(listener: () => void): () => void {
this.sessionOpenListeners.add(listener);
return () => this.sessionOpenListeners.delete(listener);
}
private notifySessionOpenChange(loaded: LoadedPlugin): void {
if (!loaded.hooks.includes("agent.open.before")) return;
for (const listener of this.sessionOpenListeners) listener();
}
async startPlugin(
pluginId: string,
configuredPath: string,
@@ -435,7 +427,6 @@ export class PluginRuntime {
throw new Error(`Plugin start cancelled: ${pluginId}`);
}
this.plugins.set(pluginId, loaded);
this.notifySessionOpenChange(loaded);
this.appendLog(pluginId, "stdout", "[paseo] Plugin ready");
}
@@ -455,7 +446,6 @@ export class PluginRuntime {
clientBundle: bundles.clientBundle ?? "",
});
this.plugins.set(input.id, loaded);
this.notifySessionOpenChange(loaded);
this.appendLog(input.id, "stdout", "[paseo] Plugin ready");
}
@@ -467,7 +457,6 @@ export class PluginRuntime {
const loaded = this.plugins.get(pluginId);
if (!loaded) return false;
this.plugins.delete(pluginId);
this.notifySessionOpenChange(loaded);
this.rejectPending(loaded, `Plugin stopped: ${pluginId}`);
await this.stopPlugin(loaded);
return true;
@@ -758,17 +747,14 @@ export class PluginRuntime {
}
}
async before<Name extends keyof PluginWireBeforeRequests>(
async before<Name extends PluginLifecycleBeforeName>(
name: Name,
input: PluginWireBeforeRequests[Name],
): Promise<PluginBeforeResults[Name]> {
): Promise<PluginWireBeforeRequests[Name]> {
let request = validateBeforeRequest(name, input);
const plugins = [...this.plugins.values()].sort((left, right) => {
return left.id.localeCompare(right.id);
});
const attached: AttachedAgentTool[] = [];
const mcpServers: SessionOpenWireRequest["mcpServers"] = {};
const mcpServerOwners: Record<string, string> = {};
for (const loaded of plugins) {
if (!loaded.hooks.includes(name)) {
continue;
@@ -778,7 +764,7 @@ export class PluginRuntime {
type: "hook",
requestId: randomUUID(),
name,
input: name === "agent.open.before" ? { ...request, tools: [], mcpServers: {} } : request,
input: request,
});
request = await validateBeforeResult(name, request, output);
if (name === "worktree.create.before") {
@@ -788,27 +774,12 @@ export class PluginRuntime {
repoPath: worktree.repoRoot,
});
}
if (name === "agent.open.before") {
const opened = request as SessionOpenWireRequest;
this.collectMcpServers(mcpServers, mcpServerOwners, loaded, opened.mcpServers);
this.collectAgentTools(attached, loaded, opened.tools);
}
} catch (error) {
if (name === "agent.open.before")
this.detachTools((request as SessionOpenWireRequest).agentId);
throw new Error(`Plugin ${loaded.id} ${name} failed: ${describeError(error)}`, {
cause: error,
});
}
}
if (name === "agent.open.before") {
return {
...request,
tools: attached,
mcpServers,
mcpServerOwners,
} as PluginBeforeResults[Name];
}
return request;
}
@@ -933,97 +904,35 @@ export class PluginRuntime {
return output;
}
private collectMcpServers(
servers: SessionOpenWireRequest["mcpServers"],
owners: Record<string, string>,
loaded: LoadedPlugin,
contributions: SessionOpenWireRequest["mcpServers"],
): void {
for (const [name, server] of Object.entries(contributions)) {
if (Object.hasOwn(servers, name)) {
throw new Error(
`MCP server ${name} from plugin ${loaded.id} collides with plugin ${owners[name]}`,
);
}
servers[name] = server;
owners[name] = loaded.id;
}
}
private collectAgentTools(
attached: AttachedAgentTool[],
loaded: LoadedPlugin,
tools: SessionOpenWireRequest["tools"],
): void {
for (const tool of tools) {
const collision = attached.find((entry) => entry.name === tool.name);
if (collision)
throw new Error(
`Agent tool ${tool.name} from plugin ${loaded.id} collides with plugin ${collision.pluginId}`,
);
attached.push({ ...tool, pluginId: loaded.id, pluginInstanceId: loaded.instanceId });
}
}
isToolPluginAvailable(pluginId: string, pluginInstanceId: string): boolean {
return this.plugins.get(pluginId)?.instanceId === pluginInstanceId;
}
// 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;
private sessionOpenPlugins(): SessionOpenPlugin[] {
return [...this.plugins.values()]
.filter((loaded) => loaded.child && loaded.hooks.includes("agent.open.before"))
.sort((left, right) => left.id.localeCompare(right.id))
.map((loaded) => ({
id: loaded.id,
instanceId: loaded.instanceId,
open: async (input) => {
const output = await this.request(loaded, {
type: "hook",
requestId: randomUUID(),
name: "agent.open.before",
input,
});
return validateBeforeResult("agent.open.before", input, output);
},
detach: (agentId) => {
if (loaded.child)
void send(loaded.child, { type: "tools.detach", agentId }).catch(() => {});
},
}));
}
/** 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);
private detachTools(agentId: string): void {
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(() => {});
}
}
@@ -1128,7 +1037,6 @@ export class PluginRuntime {
const loaded = [...this.plugins.values()];
this.plugins.clear();
for (const plugin of loaded) {
this.notifySessionOpenChange(plugin);
this.rejectPending(plugin, `Plugin stopped: ${plugin.id}`);
}
await Promise.all(loaded.map((plugin) => this.stopPlugin(plugin)));
@@ -1369,14 +1277,7 @@ export class PluginRuntime {
private handleChildMessage(loaded: LoadedPlugin, message: PluginProcessMessage): void {
if (message.type === "hooks.changed") {
const hadSessionOpen = loaded.hooks.includes("agent.open.before");
loaded.hooks = message.hooks;
if (
this.plugins.get(loaded.id) === loaded &&
hadSessionOpen !== loaded.hooks.includes("agent.open.before")
) {
for (const listener of this.sessionOpenListeners) listener();
}
return;
}
if (message.type === "worktree_manager.changed") {
@@ -1708,7 +1609,6 @@ export class PluginRuntime {
const wasPublished = this.plugins.get(loaded.id) === loaded;
if (wasPublished) {
this.plugins.delete(loaded.id);
this.notifySessionOpenChange(loaded);
}
this.rejectPending(loaded, `Plugin process exited: ${loaded.id}`);
for (const state of loaded.providerConnections.values()) {
@@ -0,0 +1,339 @@
import { isDeepStrictEqual } from "node:util";
import type pino from "pino";
import type {
AttachedAgentTool,
PluginSessionOpenResult,
PluginSessionRefreshOptions,
SessionOpenWireRequest,
} from "./agent-tools.js";
/** A running plugin that declares `agent.open.before`. */
export interface SessionOpenPlugin {
id: string;
instanceId: string;
/** Runs this plugin's `agent.open.before` callback and returns its validated result. */
open(input: SessionOpenWireRequest): Promise<SessionOpenWireRequest>;
/** Drops the agent's tool definitions inside this plugin's process. */
detach(agentId: string): void;
}
export interface SessionAttachmentPlugins {
/** The running plugins that declare `agent.open.before`, in the order a session open runs them. */
sessionOpenPlugins(): SessionOpenPlugin[];
/** Every running plugin process, so a closed session leaves no tool definitions behind. */
detachEverywhere(agentId: string): void;
}
/** What one plugin's `agent.open.before` callback was handed and returned for a session. */
interface Contribution {
pluginId: string;
pluginInstanceId: string;
input: SessionOpenWireRequest;
output: SessionOpenWireRequest;
tools: AttachedAgentTool[];
}
interface Attachment {
base: SessionOpenWireRequest;
contributions: Contribution[];
/** A reopen now would launch the provider differently from the running session. */
stale: boolean;
}
/**
* Owns what `agent.open.before` plugins attached to each live session: the tools Paseo serves to the agent, and the
* 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.
*/
export class SessionAttachments {
private readonly attachments = new Map<string, Attachment>();
private readonly tails = new Map<string, Promise<unknown>>();
constructor(
private readonly plugins: SessionAttachmentPlugins,
private readonly logger: pino.Logger,
) {}
async open(request: SessionOpenWireRequest): Promise<PluginSessionOpenResult> {
return this.serialize(request.agentId, async () => {
this.close(request.agentId);
const base: SessionOpenWireRequest = { ...request, tools: [], mcpServers: {} };
const contributions: Contribution[] = [];
const mcpServers: SessionOpenWireRequest["mcpServers"] = {};
const mcpServerOwners: Record<string, string> = {};
let current = base;
for (const plugin of this.plugins.sessionOpenPlugins()) {
const input: SessionOpenWireRequest = { ...current, tools: [], mcpServers: {} };
try {
const output = await plugin.open(input);
collectMcpServers(mcpServers, mcpServerOwners, plugin.id, output.mcpServers);
const tools = stampTools(plugin, output.tools);
assertNoToolCollision(contributions, plugin.id, tools);
contributions.push({
pluginId: plugin.id,
pluginInstanceId: plugin.instanceId,
input,
output,
tools,
});
current = output;
} catch (error) {
this.plugins.detachEverywhere(request.agentId);
throw new Error(`Plugin ${plugin.id} agent.open.before failed: ${describeError(error)}`, {
cause: error,
});
}
}
if (request.purpose === "interactive") {
this.attachments.set(request.agentId, { base, contributions, stale: false });
}
return {
...current,
tools: contributions.flatMap((contribution) => contribution.tools),
mcpServers,
mcpServerOwners,
};
});
}
/**
* Brings a live session's tools up to date with the running plugins and reports whether the session must reopen
* to apply the rest. Plugins that did not change since the session opened are not called.
*/
async refresh(
agentId: string,
options: PluginSessionRefreshOptions,
): Promise<{ stale: boolean }> {
const attachment = this.attachments.get(agentId);
if (!attachment) return { stale: false };
if (this.isCurrent(attachment)) return { stale: attachment.stale };
return this.serialize(agentId, () => this.reconcile(agentId, options));
}
/** The session's tools from running plugin instances. */
tools(agentId: string): AttachedAgentTool[] {
const running = new Map(
this.plugins.sessionOpenPlugins().map((plugin) => [plugin.id, plugin.instanceId]),
);
return (this.attachments.get(agentId)?.contributions ?? [])
.filter(
(contribution) => running.get(contribution.pluginId) === contribution.pluginInstanceId,
)
.flatMap((contribution) => contribution.tools);
}
close(agentId: string): void {
this.attachments.delete(agentId);
this.plugins.detachEverywhere(agentId);
}
private isCurrent(attachment: Attachment): boolean {
const running = this.plugins.sessionOpenPlugins();
return (
running.length === attachment.contributions.length &&
running.every((plugin, index) => {
const contribution = attachment.contributions[index];
return (
contribution.pluginId === plugin.id && contribution.pluginInstanceId === plugin.instanceId
);
})
);
}
private async reconcile(
agentId: string,
options: PluginSessionRefreshOptions,
): Promise<{ stale: boolean }> {
const attachment = this.attachments.get(agentId);
if (!attachment) return { stale: false };
if (this.isCurrent(attachment)) return { stale: attachment.stale };
const running = new Map(this.plugins.sessionOpenPlugins().map((plugin) => [plugin.id, plugin]));
const recorded = new Map(
attachment.contributions.map((contribution) => [contribution.pluginId, contribution]),
);
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) {
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);
contributions.push(contribution);
replayed.push({ contribution, plugin });
previous = contribution.output;
}
const collided = await this.dropCollidingTools(agentId, contributions, replayed, options);
stale ||= collided;
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 };
}
/** 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 => ({
pluginId: plugin.id,
pluginInstanceId: plugin.instanceId,
input,
output,
tools: stampTools(plugin, output.tools),
});
try {
return {
contribution: contribution(await plugin.open({ ...input, reason: "refresh" })),
failed: 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.
this.logger.warn(
{ err: error, pluginId: plugin.id, agentId: input.agentId },
"Plugin session refresh failed",
);
return { contribution: contribution(input), failed: true };
}
}
/** A replayed plugin whose tool takes a name already in use keeps no tools; the reopen reports the collision. */
private async dropCollidingTools(
agentId: string,
contributions: Contribution[],
replayed: { contribution: Contribution }[],
options: PluginSessionRefreshOptions,
): Promise<boolean> {
if (replayed.every(({ contribution }) => contribution.tools.length === 0)) return false;
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) {
this.logger.warn(
{ agentId, pluginId: contribution.pluginId, tool: conflict.name },
"Refreshed plugin tool collides with another agent tool",
);
contribution.tools = [];
collided = true;
continue;
}
for (const tool of contribution.tools) taken.add(tool.name);
}
return collided;
}
private serialize<T>(agentId: string, run: () => Promise<T>): Promise<T> {
const previous = this.tails.get(agentId) ?? Promise.resolve();
const next = previous.then(run, run);
const settled = next.then(
() => undefined,
() => undefined,
);
this.tails.set(agentId, settled);
void settled.finally(() => {
if (this.tails.get(agentId) === settled) this.tails.delete(agentId);
});
return next;
}
}
/** 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));
}
function launchView(request: SessionOpenWireRequest) {
return {
env: request.env,
appendSystemPrompt: request.appendSystemPrompt ?? [],
mcpServers: request.mcpServers,
tools: request.tools.map(({ name, title, description, inputSchema }) => ({
name,
title,
description,
inputSchema,
})),
};
}
function stampTools(
plugin: SessionOpenPlugin,
tools: SessionOpenWireRequest["tools"],
): AttachedAgentTool[] {
return tools.map((tool) => ({
...tool,
pluginId: plugin.id,
pluginInstanceId: plugin.instanceId,
}));
}
function assertNoToolCollision(
contributions: readonly Contribution[],
pluginId: string,
tools: readonly AttachedAgentTool[],
): void {
for (const tool of tools) {
const owner = contributions.find((contribution) =>
contribution.tools.some((entry) => entry.name === tool.name),
);
if (owner) {
throw new Error(
`Agent tool ${tool.name} from plugin ${pluginId} collides with plugin ${owner.pluginId}`,
);
}
}
}
function collectMcpServers(
servers: SessionOpenWireRequest["mcpServers"],
owners: Record<string, string>,
pluginId: string,
contributions: SessionOpenWireRequest["mcpServers"],
): void {
for (const [name, server] of Object.entries(contributions)) {
if (Object.hasOwn(servers, name)) {
throw new Error(
`MCP server ${name} from plugin ${pluginId} collides with plugin ${owners[name]}`,
);
}
servers[name] = server;
owners[name] = pluginId;
}
}
function describeError(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
+26 -6
View File
@@ -496,12 +496,32 @@ 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. 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. |
| Change | When the agent receives it |
| ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Start, stop, or reload a plugin declaring `agent.open.before` | Before the session's next agent tool call or prompt, as described below. |
| 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. |
When a plugin declaring `agent.open.before` starts, stops, or reloads, Paseo reruns only that
plugin's callback for each open session. The callback gets the request it saw at the session's last
open, with `reason: "refresh"`. This happens before the session's next agent tool call or prompt.
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 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
idle prompt. Paseo does not rerun it for the same plugin instance.
- If a returned tool collides with a Paseo tool or another plugin's tool, that plugin's tools stay
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.
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).