mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-26 02:05:31 +00:00
Compare commits
21
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
39d203248f | ||
|
|
6c18d7ecf1 | ||
|
|
8747a78457 | ||
|
|
033255a333 | ||
|
|
89d0fb7f8a | ||
|
|
8afcdb6cbe | ||
|
|
59b3ec8aad | ||
|
|
3a521cd866 | ||
|
|
43f961e25c | ||
|
|
9599936139 | ||
|
|
0912eabb97 | ||
|
|
a1f408dcc4 | ||
|
|
fb8ee48859 | ||
|
|
ded9ae9f60 | ||
|
|
1f00a8115b | ||
|
|
b3eb076539 | ||
|
|
0228ae14da | ||
|
|
62db1c7fb0 | ||
|
|
78ca2a7765 | ||
|
|
84a61f0e46 | ||
|
|
d3ebb3f02f |
@@ -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,24 @@ 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: {},
|
||||
}),
|
||||
sessionLaunched: () => {},
|
||||
sessionLaunchFailed: () => {},
|
||||
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 +709,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 +16157,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" },
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import type { AttachedAgentTool, PluginAgentToolsRuntime } from "../plugins/agent-tools.js";
|
||||
import type {
|
||||
AttachedAgentTool,
|
||||
PluginSessionsRuntime,
|
||||
SessionOpenAgentFacts,
|
||||
} 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";
|
||||
@@ -203,6 +207,26 @@ async function assertUsableWorkingDirectory(cwd: string): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
interface ResumeAgentOptions {
|
||||
createdAt?: Date;
|
||||
updatedAt?: Date;
|
||||
lastUserMessageAt?: Date | null;
|
||||
labels?: Record<string, string>;
|
||||
metadata?: AgentMetadata;
|
||||
workspaceId?: string;
|
||||
owner?: AgentOwner;
|
||||
background?: boolean;
|
||||
attention?: AttentionState;
|
||||
}
|
||||
|
||||
interface PluginToolCall {
|
||||
pluginId: string;
|
||||
toolName: string;
|
||||
agentId: string;
|
||||
input: unknown;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
interface StopAgentBackgroundWorkOptions {
|
||||
agentId: string;
|
||||
itemId: string;
|
||||
@@ -399,7 +423,7 @@ export interface AgentManagerOptions {
|
||||
terminalManager?: TerminalManager | null;
|
||||
mcpBaseUrl?: string;
|
||||
mcpAuthToken?: string;
|
||||
pluginAgentTools?: PluginAgentToolsRuntime;
|
||||
pluginSessions?: PluginSessionsRuntime;
|
||||
paseoToolsEnabled?: boolean;
|
||||
paseoToolCatalogFactory?: PaseoToolCatalogFactory;
|
||||
resolvePaseoToolPolicy?: (provider: AgentProvider) => ProviderPaseoToolsPolicy | undefined;
|
||||
@@ -937,10 +961,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 pluginAgentTools: PluginAgentToolsRuntime | undefined;
|
||||
private readonly pluginSessions: PluginSessionsRuntime | undefined;
|
||||
private paseoToolsEnabled = true;
|
||||
private paseoToolCatalogFactory: PaseoToolCatalogFactory | null = null;
|
||||
private readonly paseoToolPolicies = new Map<string, ProviderPaseoToolsPolicy | undefined>();
|
||||
@@ -958,7 +979,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;
|
||||
@@ -1063,47 +1084,75 @@ 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) ?? [];
|
||||
}
|
||||
|
||||
async executePluginTool(
|
||||
tool: AttachedAgentTool,
|
||||
agentId: string,
|
||||
input: unknown,
|
||||
signal?: AbortSignal,
|
||||
): Promise<AgentToolResult> {
|
||||
/**
|
||||
* 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),
|
||||
agentFacts: () => this.pluginOpenAgentFacts(agentId),
|
||||
});
|
||||
}
|
||||
|
||||
/** The agent fields a reopen would put in its plugin open request. */
|
||||
private async pluginOpenAgentFacts(agentId: string): Promise<SessionOpenAgentFacts> {
|
||||
const agent = this.requireAgent(agentId);
|
||||
return {
|
||||
workspaceId: agent.workspaceId ?? null,
|
||||
title: await this.resolveInitialPersistedTitle(agentId, agent.config, null),
|
||||
background: agent.background === true,
|
||||
...agentEntityData(agent),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.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.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.pluginAgentTools.callTool(
|
||||
return this.pluginSessions.callTool(
|
||||
tool.pluginId,
|
||||
tool.pluginInstanceId,
|
||||
describeHookAgent({ ...agent, title: record?.title ?? agent.config.title }),
|
||||
@@ -1113,10 +1162,22 @@ export class AgentManager {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Paseo's own tool names for the agent, including the ones its provider disables. The catalog also lists the
|
||||
* agent's plugin tools; the plugin session owner settles those names between plugins itself.
|
||||
*/
|
||||
private async reservedAgentToolNames(agentId: string): Promise<ReadonlySet<string>> {
|
||||
if (!this.paseoToolCatalogFactory) return new Set();
|
||||
const pluginToolNames = new Set(this.getPluginTools(agentId).map((tool) => tool.name));
|
||||
const catalog = await this.paseoToolCatalogFactory({
|
||||
callerAgentId: agentId,
|
||||
paseoToolPolicy: {},
|
||||
});
|
||||
return new Set([...catalog.tools.keys()].filter((name) => !pluginToolNames.has(name)));
|
||||
}
|
||||
|
||||
private detachPluginTools(agentId: string): void {
|
||||
this.attachedPluginTools.delete(agentId);
|
||||
this.sessionOpenGenerations.delete(agentId);
|
||||
this.pluginAgentTools?.detachTools(agentId);
|
||||
this.pluginSessions?.closeSession(agentId);
|
||||
}
|
||||
|
||||
getPaseoToolPolicy(agentId: string): ProviderPaseoToolsPolicy | undefined {
|
||||
@@ -1637,7 +1698,17 @@ export class AgentManager {
|
||||
);
|
||||
}
|
||||
|
||||
private async createAgentInternal(
|
||||
private createAgentInternal(
|
||||
config: AgentSessionConfig,
|
||||
resolvedAgentId: string,
|
||||
options: CreateAgentOptions,
|
||||
): Promise<ManagedAgent> {
|
||||
return this.launchAgent(resolvedAgentId, () =>
|
||||
this.createAgentSession(config, resolvedAgentId, options),
|
||||
);
|
||||
}
|
||||
|
||||
private async createAgentSession(
|
||||
config: AgentSessionConfig,
|
||||
resolvedAgentId: string,
|
||||
options: CreateAgentOptions,
|
||||
@@ -1758,7 +1829,19 @@ export class AgentManager {
|
||||
);
|
||||
}
|
||||
|
||||
private async resumeAgentFromPersistenceInternal(
|
||||
private resumeAgentFromPersistenceInternal(
|
||||
handle: AgentPersistenceHandle,
|
||||
overrides: Partial<AgentSessionConfig> | undefined,
|
||||
agentId: string,
|
||||
options?: ResumeAgentOptions,
|
||||
resumeOptions?: AgentResumeSessionOptions,
|
||||
): Promise<ManagedAgent> {
|
||||
return this.launchAgent(agentId, () =>
|
||||
this.resumeAgentSession(handle, overrides, agentId, options, resumeOptions),
|
||||
);
|
||||
}
|
||||
|
||||
private async resumeAgentSession(
|
||||
handle: AgentPersistenceHandle,
|
||||
overrides?: Partial<AgentSessionConfig>,
|
||||
agentId?: string,
|
||||
@@ -1864,18 +1947,23 @@ export class AgentManager {
|
||||
workspaceId: string;
|
||||
labels?: Record<string, string>;
|
||||
}): Promise<ManagedAgent> {
|
||||
return this.trackAgentRegistrationOperation(this.importProviderSessionInternal(input));
|
||||
const resolvedAgentId = validateAgentId(this.idFactory(), "importProviderSession");
|
||||
return this.trackAgentRegistrationOperation(
|
||||
this.launchAgent(resolvedAgentId, () => this.importAgentSession(input, resolvedAgentId)),
|
||||
);
|
||||
}
|
||||
|
||||
private async importProviderSessionInternal(input: {
|
||||
provider: AgentProvider;
|
||||
providerHandleId: string;
|
||||
cwd: string;
|
||||
workspaceId: string;
|
||||
labels?: Record<string, string>;
|
||||
}): Promise<ManagedAgent> {
|
||||
private async importAgentSession(
|
||||
input: {
|
||||
provider: AgentProvider;
|
||||
providerHandleId: string;
|
||||
cwd: string;
|
||||
workspaceId: string;
|
||||
labels?: Record<string, string>;
|
||||
},
|
||||
resolvedAgentId: string,
|
||||
): Promise<ManagedAgent> {
|
||||
this.assertAcceptingAgentRegistrations();
|
||||
const resolvedAgentId = validateAgentId(this.idFactory(), "importProviderSession");
|
||||
this.requireEnabledProvider(input.provider);
|
||||
|
||||
const client = await this.requireAvailableClient({ provider: input.provider });
|
||||
@@ -1971,7 +2059,29 @@ export class AgentManager {
|
||||
);
|
||||
}
|
||||
|
||||
private async reloadAgentSessionInternal(
|
||||
private reloadAgentSessionInternal(
|
||||
agentId: string,
|
||||
overrides?: Partial<AgentSessionConfig>,
|
||||
options?: { rehydrateFromDisk?: boolean },
|
||||
): Promise<ManagedAgent> {
|
||||
return this.launchAgent(agentId, () => this.reopenAgentSession(agentId, overrides, options));
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs one provider launch: create, resume, import, or reopen. Its plugin open takes over the session once
|
||||
* `registerSession` admits the agent. A launch that fails before then discards that open, so a session still
|
||||
* running keeps its plugin tools.
|
||||
*/
|
||||
private async launchAgent<T>(agentId: string, launch: () => Promise<T>): Promise<T> {
|
||||
try {
|
||||
return await launch();
|
||||
} catch (error) {
|
||||
this.pluginSessions?.sessionLaunchFailed(agentId);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private async reopenAgentSession(
|
||||
agentId: string,
|
||||
overrides?: Partial<AgentSessionConfig>,
|
||||
options?: { rehydrateFromDisk?: boolean },
|
||||
@@ -2019,13 +2129,11 @@ export class AgentManager {
|
||||
metadata: existing.metadata,
|
||||
},
|
||||
);
|
||||
const providerLaunchConfig = this.resolveProviderLaunchConfig(launchConfig, launchContext);
|
||||
if (
|
||||
Object.keys(stripInternalPaseoMcpServer(providerLaunchConfig).mcpServers ?? {}).length > 0 &&
|
||||
existing.session.capabilities.supportsMcpServers !== true
|
||||
) {
|
||||
throw this.unsupportedMcpError(providerLaunchConfig, launchContext);
|
||||
}
|
||||
const providerLaunchConfig = this.resolveReloadLaunchConfig(
|
||||
existing,
|
||||
launchConfig,
|
||||
launchContext,
|
||||
);
|
||||
|
||||
let session: AgentSession | undefined;
|
||||
let closedExisting: ManagedAgentClosed | undefined;
|
||||
@@ -2089,7 +2197,8 @@ export class AgentManager {
|
||||
throw error;
|
||||
} finally {
|
||||
if (!handedToRegistration) {
|
||||
this.detachPluginTools(agentId);
|
||||
// The closed agent drops its plugin record; a launch that never closed it leaves the rollback to launchAgent.
|
||||
if (closedExisting) this.detachPluginTools(agentId);
|
||||
if (hadPreviousPaseoToolPolicy) {
|
||||
this.paseoToolPolicies.set(agentId, previousPaseoToolPolicy);
|
||||
} else {
|
||||
@@ -2102,6 +2211,23 @@ export class AgentManager {
|
||||
}
|
||||
}
|
||||
|
||||
/** Validates a reload's launch before it closes the running session. */
|
||||
private resolveReloadLaunchConfig(
|
||||
existing: ActiveManagedAgent,
|
||||
launchConfig: AgentSessionConfig,
|
||||
launchContext: AgentLaunchContext,
|
||||
): AgentSessionConfig {
|
||||
const providerLaunchConfig = this.resolveProviderLaunchConfig(launchConfig, launchContext);
|
||||
const mcpServers = stripInternalPaseoMcpServer(providerLaunchConfig).mcpServers ?? {};
|
||||
if (
|
||||
Object.keys(mcpServers).length > 0 &&
|
||||
existing.session.capabilities.supportsMcpServers !== true
|
||||
) {
|
||||
throw this.unsupportedMcpError(providerLaunchConfig, launchContext);
|
||||
}
|
||||
return providerLaunchConfig;
|
||||
}
|
||||
|
||||
private async closeReloadedSession(session: AgentSession, agentId: string): Promise<void> {
|
||||
let operation = this.reloadedSessionCloses.get(session);
|
||||
if (!operation) {
|
||||
@@ -4619,6 +4745,8 @@ export class AgentManager {
|
||||
this.runtimeCleanupIdentities.set(session, Object.freeze({ openedAt: Date.now() }));
|
||||
this.agents.set(resolvedAgentId, managed);
|
||||
registered = true;
|
||||
// The agent now runs this launch, so its plugin open describes the running session.
|
||||
this.pluginSessions?.sessionLaunched(resolvedAgentId);
|
||||
// Initialize previousStatus to track transitions
|
||||
this.previousStatuses.set(resolvedAgentId, managed.lifecycle);
|
||||
if (session.initialTimeline?.length) {
|
||||
@@ -6513,13 +6641,10 @@ export class AgentManager {
|
||||
metadata?: AgentMetadata;
|
||||
},
|
||||
): Promise<AgentLaunchContext> {
|
||||
// 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,
|
||||
@@ -6534,10 +6659,9 @@ 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;
|
||||
mcpServers = transformed.mcpServers;
|
||||
mcpServerOwners = transformed.mcpServerOwners;
|
||||
@@ -6561,18 +6685,13 @@ export class AgentManager {
|
||||
this.paseoToolCatalogFactory &&
|
||||
(useNativeTools || this.getPluginTools(agentId).length > 0)
|
||||
) {
|
||||
try {
|
||||
const catalog = await this.paseoToolCatalogFactory({
|
||||
callerAgentId: agentId,
|
||||
paseoToolPolicy,
|
||||
});
|
||||
if (useNativeTools) context.paseoTools = catalog;
|
||||
} catch (error) {
|
||||
this.detachPluginTools(agentId);
|
||||
throw error;
|
||||
}
|
||||
// Building the catalog checks the plugin tools against Paseo's own names.
|
||||
const catalog = await this.paseoToolCatalogFactory({
|
||||
callerAgentId: agentId,
|
||||
paseoToolPolicy,
|
||||
});
|
||||
if (useNativeTools) context.paseoTools = catalog;
|
||||
}
|
||||
this.sessionOpenGenerations.set(agentId, generation);
|
||||
return context;
|
||||
}
|
||||
|
||||
|
||||
@@ -28,7 +28,13 @@ 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({
|
||||
pluginId: tool.pluginId,
|
||||
toolName: tool.name,
|
||||
agentId: callerAgentId,
|
||||
input,
|
||||
signal,
|
||||
});
|
||||
return addModelVisibleStructuredContent({
|
||||
content: result.text === undefined ? [] : [{ type: "text", text: result.text }],
|
||||
structuredContent: result.structuredContent,
|
||||
|
||||
@@ -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,
|
||||
@@ -1700,6 +1696,7 @@ export async function createPaseoDaemon(
|
||||
// state is retained between requests, matching the previous
|
||||
// `sessionIdGenerator: undefined` transport.
|
||||
const createAgentMcpSession = async (callerAgentId?: string) => {
|
||||
if (callerAgentId) await agentManager.refreshPluginTools(callerAgentId);
|
||||
const agentMcpServer = await createAgentMcpServer(
|
||||
createAgentToolHostDependencies({
|
||||
callerAgentId,
|
||||
@@ -2045,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);
|
||||
@@ -2067,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();
|
||||
|
||||
@@ -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,20 +477,31 @@ 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 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((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") }],
|
||||
// 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([
|
||||
"plugin_echo",
|
||||
]);
|
||||
expect(h.launches).toHaveLength(1);
|
||||
} finally {
|
||||
await h.close();
|
||||
}
|
||||
@@ -611,6 +623,673 @@ 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 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");
|
||||
expect(h.launches).toHaveLength(2);
|
||||
} finally {
|
||||
release();
|
||||
await h.close();
|
||||
}
|
||||
}, 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);
|
||||
|
||||
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 paseoNameClashSource = openCounterSource.replace(
|
||||
"tools: [...request.tools, tool]",
|
||||
'tools: [...request.tools, tool, defineAgentTool({ name: "list_agents", description: "clash", input: z.object({}), async execute() { return { text: "clash" }; } })]',
|
||||
);
|
||||
|
||||
test("a reopen that a plugin's Paseo tool name fails is retried, keeps the running session's plugin tools, and fixing the plugin restores its own", async () => {
|
||||
const h = await setup(false, openCounterSource);
|
||||
try {
|
||||
await h.install("unrelated", breakableSource(path.join(h.directory, "never-armed")));
|
||||
const a = await h.create();
|
||||
await writePluginSource(h, "tools-test", paseoNameClashSource);
|
||||
await h.client.reloadPlugin("tools-test");
|
||||
const manager = h.daemon.daemon.agentManager;
|
||||
const collision = /list_agents from plugin tools-test collides with Paseo tool/;
|
||||
await expect(manager.reloadStalePluginSession(a.id)).rejects.toThrow(collision);
|
||||
await expect(manager.reloadStalePluginSession(a.id)).rejects.toThrow(collision);
|
||||
expect(h.launches).toHaveLength(1);
|
||||
const broken = await h.mcp(a.id);
|
||||
expect(await listedToolNames(broken)).not.toContain("other_opens");
|
||||
expect(await broken.callTool({ name: "breakable_ping", arguments: {} })).toMatchObject({
|
||||
content: [{ type: "text", text: "pong" }],
|
||||
});
|
||||
|
||||
await writePluginSource(h, "tools-test", openCounterSource);
|
||||
await h.client.reloadPlugin("tools-test");
|
||||
expect(
|
||||
await (await h.mcp(a.id)).callTool({ name: "other_opens", arguments: {} }),
|
||||
).toMatchObject({ content: [{ type: "text", text: "1" }] });
|
||||
await manager.reloadStalePluginSession(a.id);
|
||||
expect(h.launches).toHaveLength(1);
|
||||
} finally {
|
||||
await h.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
const claimsOtherOpensSource = `
|
||||
import { z } from "zod";
|
||||
import { defineAgentTool } from "@getpaseo/plugin/server";
|
||||
const tool = defineAgentTool({
|
||||
name: "other_opens", description: "clash",
|
||||
input: z.object({}),
|
||||
async execute() { return { text: "clash" }; },
|
||||
});
|
||||
export default function contribute(server) {
|
||||
server.addHook("agent.open.before", async ({ request }) => ({ ...request, tools: [...request.tools, tool] }));
|
||||
return () => {};
|
||||
}
|
||||
`;
|
||||
|
||||
test("after a rejected reopen, a tool name stays with the plugin that had it, even when the claimant sorts first", async () => {
|
||||
const h = await setup(false, openCounterSource);
|
||||
try {
|
||||
await h.install("a-claimant", breakableSource(path.join(h.directory, "never-armed")));
|
||||
const a = await h.create();
|
||||
await writePluginSource(h, "a-claimant", claimsOtherOpensSource);
|
||||
await h.client.reloadPlugin("a-claimant");
|
||||
const manager = h.daemon.daemon.agentManager;
|
||||
await expect(manager.reloadStalePluginSession(a.id)).rejects.toThrow(
|
||||
/other_opens from plugin tools-test collides with plugin a-claimant/,
|
||||
);
|
||||
expect(h.launches).toHaveLength(1);
|
||||
const result = await (await h.mcp(a.id)).callTool({ name: "other_opens", arguments: {} });
|
||||
expect(result.content).not.toEqual([{ type: "text", text: "clash" }]);
|
||||
expect(manager.getPluginTools(a.id).map((tool) => tool.pluginId)).toEqual(["tools-test"]);
|
||||
} finally {
|
||||
await h.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
const metadataGatedSource = openCounterSource.replace(
|
||||
"opens++;",
|
||||
'opens++;\n if (request.metadata.tools !== "on") return;',
|
||||
);
|
||||
|
||||
test("a plugin reload reruns its callback with the agent's current metadata", async () => {
|
||||
const h = await setup(false, metadataGatedSource);
|
||||
try {
|
||||
const manager = h.daemon.daemon.agentManager;
|
||||
const a = await h.create();
|
||||
expect(await listedToolNames(await h.mcp(a.id))).not.toContain("other_opens");
|
||||
await manager.setMetadata(a.id, { tools: "on" });
|
||||
await h.client.reloadPlugin("tools-test");
|
||||
expect(await listedToolNames(await h.mcp(a.id))).toContain("other_opens");
|
||||
// The session launched without the tool, so it reopens at the next idle prompt.
|
||||
await sendAndFinish(h, a.id, "after metadata");
|
||||
expect(h.launches).toHaveLength(2);
|
||||
} finally {
|
||||
await h.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
const setsXSource = `
|
||||
export default function contribute(server) {
|
||||
server.addHook("agent.open.before", async ({ request }) => ({ ...request, env: { ...request.env, X: "yes" } }));
|
||||
return () => {};
|
||||
}
|
||||
`;
|
||||
|
||||
const needsXSource = `
|
||||
export default function contribute(server) {
|
||||
server.addHook("agent.open.before", async ({ request }) => {
|
||||
if (request.env.X !== "yes") return;
|
||||
return { ...request, env: { ...request.env, Y: "yes" } };
|
||||
});
|
||||
return () => {};
|
||||
}
|
||||
`;
|
||||
|
||||
test("a plugin reruns when an earlier plugin changes what it receives, and the session reopens with the composed launch", async () => {
|
||||
const h = await setup(false, openCounterSource);
|
||||
try {
|
||||
await h.install("a-sets-x", setsXSource);
|
||||
const a = await h.create();
|
||||
expect(h.launches.at(-1)!.context!.env).toMatchObject({ X: "yes" });
|
||||
await h.client.disablePlugin("a-sets-x");
|
||||
await h.install("b-needs-x", needsXSource);
|
||||
await listedToolNames(await h.mcp(a.id));
|
||||
await h.client.enablePlugin("a-sets-x");
|
||||
await listedToolNames(await h.mcp(a.id));
|
||||
// b-needs-x now sees X and adds Y, which the running session never launched with.
|
||||
await sendAndFinish(h, a.id, "after re-enable");
|
||||
expect(h.launches).toHaveLength(2);
|
||||
expect(h.launches.at(-1)!.context!.env).toMatchObject({ X: "yes", Y: "yes" });
|
||||
} finally {
|
||||
await h.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
const hintSource = (hint: string) => `
|
||||
export default function contribute(server) {
|
||||
server.addHook("agent.open.before", async ({ request }) => ({ ...request, env: { ...request.env, HINT: ${JSON.stringify(hint)} } }));
|
||||
return () => {};
|
||||
}
|
||||
`;
|
||||
|
||||
const hintReaderSource = `
|
||||
import { z } from "zod";
|
||||
import { defineAgentTool } from "@getpaseo/plugin/server";
|
||||
export default function contribute(server) {
|
||||
server.addHook("agent.open.before", async ({ request }) => {
|
||||
const { HINT: hint, ...env } = request.env;
|
||||
const tool = defineAgentTool({
|
||||
name: "read_tool_hint", description: "The hint from the plugin before",
|
||||
input: z.object({}),
|
||||
async execute() { return { text: String(hint) }; },
|
||||
});
|
||||
return { ...request, env, tools: [...request.tools, tool] };
|
||||
});
|
||||
return () => {};
|
||||
}
|
||||
`;
|
||||
|
||||
test("a later plugin rerun by an earlier plugin's edit keeps its own tool, and the session keeps running", async () => {
|
||||
const h = await setup(false, openCounterSource);
|
||||
try {
|
||||
await h.install("a-hint", hintSource("red"));
|
||||
await h.install("b-hint-reader", hintReaderSource);
|
||||
const a = await h.create();
|
||||
await writePluginSource(h, "a-hint", hintSource("green"));
|
||||
await h.client.reloadPlugin("a-hint");
|
||||
expect(
|
||||
await (await h.mcp(a.id)).callTool({ name: "read_tool_hint", arguments: {} }),
|
||||
).toMatchObject({ content: [{ type: "text", text: "green" }] });
|
||||
// b-hint-reader removes the hint, so the launch is unchanged.
|
||||
await sendAndFinish(h, a.id, "after hint change");
|
||||
expect(h.launches).toHaveLength(1);
|
||||
} finally {
|
||||
await h.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
// The tool waits for the gate file while it answers the first hint.
|
||||
const slowHintReaderSource = (entered: string, gate: string) => `
|
||||
import { existsSync, writeFileSync } from "node:fs";
|
||||
import { z } from "zod";
|
||||
import { defineAgentTool } from "@getpaseo/plugin/server";
|
||||
export default function contribute(server) {
|
||||
server.addHook("agent.open.before", async ({ request }) => {
|
||||
const { HINT: hint, ...env } = request.env;
|
||||
const tool = defineAgentTool({
|
||||
name: "read_tool_hint", description: "The hint from the plugin before",
|
||||
input: z.object({}),
|
||||
async execute() {
|
||||
if (hint === "red") {
|
||||
writeFileSync(${JSON.stringify(entered)}, "");
|
||||
while (!existsSync(${JSON.stringify(gate)})) await new Promise((r) => setTimeout(r, 20));
|
||||
}
|
||||
return { text: String(hint) };
|
||||
},
|
||||
});
|
||||
return { ...request, env, tools: [...request.tools, tool] };
|
||||
});
|
||||
return () => {};
|
||||
}
|
||||
`;
|
||||
|
||||
test("a refresh that reruns a plugin lets that plugin's running tool call finish", async () => {
|
||||
const scratch = await mkdtemp(path.join(tmpdir(), "paseo-running-call-"));
|
||||
const entered = path.join(scratch, "entered");
|
||||
const gate = path.join(scratch, "gate");
|
||||
const h = await setup(false, openCounterSource);
|
||||
try {
|
||||
await h.install("a-hint", hintSource("red"));
|
||||
await h.install("b-hint-reader", slowHintReaderSource(entered, gate));
|
||||
const a = await h.create();
|
||||
const running = (await h.mcp(a.id)).callTool({ name: "read_tool_hint", arguments: {} });
|
||||
await expect.poll(() => existsSync(entered)).toBe(true);
|
||||
await writePluginSource(h, "a-hint", hintSource("green"));
|
||||
await h.client.reloadPlugin("a-hint");
|
||||
expect(
|
||||
await (await h.mcp(a.id)).callTool({ name: "read_tool_hint", arguments: {} }),
|
||||
).toMatchObject({ content: [{ type: "text", text: "green" }] });
|
||||
await writeFile(gate, "");
|
||||
expect(await running).toMatchObject({ content: [{ type: "text", text: "red" }] });
|
||||
} finally {
|
||||
await h.close();
|
||||
await rm(scratch, { recursive: true, force: true });
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
// Once armed, the module waits for the gate file before it loads, which holds a restart between stop and start.
|
||||
const gatedStartSource = (arm: string, entered: string, gate: string) =>
|
||||
openCounterSource.replace(
|
||||
'import { z } from "zod";',
|
||||
`import { existsSync, writeFileSync } from "node:fs";
|
||||
import { z } from "zod";
|
||||
if (existsSync(${JSON.stringify(arm)})) {
|
||||
writeFileSync(${JSON.stringify(entered)}, "");
|
||||
const pause = new Int32Array(new SharedArrayBuffer(4));
|
||||
while (!existsSync(${JSON.stringify(gate)})) Atomics.wait(pause, 0, 0, 20);
|
||||
}`,
|
||||
);
|
||||
|
||||
test("an idle prompt during a plugin restart keeps the agent's session, with its subagents running", async () => {
|
||||
const scratch = await mkdtemp(path.join(tmpdir(), "paseo-restart-gap-"));
|
||||
const arm = path.join(scratch, "arm");
|
||||
const entered = path.join(scratch, "entered");
|
||||
const gate = path.join(scratch, "gate");
|
||||
const h = await setup(false, gatedStartSource(arm, entered, gate));
|
||||
try {
|
||||
const a = await h.create();
|
||||
await sendAndFinish(h, a.id, "Emit a provider child");
|
||||
await writeFile(arm, "");
|
||||
const reloading = h.client.reloadPlugin("tools-test");
|
||||
await expect.poll(() => existsSync(entered)).toBe(true);
|
||||
const prompting = sendAndFinish(h, a.id, "during restart");
|
||||
// Room for a prompt that does not wait for the restart to reopen the session first.
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
await writeFile(gate, "");
|
||||
await reloading;
|
||||
await prompting;
|
||||
expect(h.launches).toHaveLength(1);
|
||||
expect(subagentStatuses(h, a.id)).toEqual(["running"]);
|
||||
expect(
|
||||
await (await h.mcp(a.id)).callTool({ name: "other_opens", arguments: {} }),
|
||||
).toMatchObject({ content: [{ type: "text", text: "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);
|
||||
}
|
||||
|
||||
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);
|
||||
// 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, "");
|
||||
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(
|
||||
@@ -858,7 +1537,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;
|
||||
@@ -884,8 +1563,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();
|
||||
@@ -972,6 +1652,118 @@ test("session-open MCP servers fail on unsupported providers and leave saved con
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
const mcpWithToolSource = openCounterSource.replace(
|
||||
"return { ...request, tools: [...request.tools, tool] };",
|
||||
`return { ...request, tools: [...request.tools, tool], mcpServers: { ...request.mcpServers, company: ${JSON.stringify(companyServer)} } };`,
|
||||
);
|
||||
|
||||
test("a create that fails the MCP check leaves no plugin tools behind for its agent id", async () => {
|
||||
const h = await setup(false, mcpWithToolSource, undefined, { supportsMcpServers: false });
|
||||
try {
|
||||
const manager = h.daemon.daemon.agentManager;
|
||||
const agentId = "00000000-0000-4000-8000-000000009493";
|
||||
await expect(
|
||||
manager.createAgent({ provider: "codex", cwd: h.directory }, agentId, {}),
|
||||
).rejects.toThrow(/does not support MCP servers.*plugin tools-test/);
|
||||
expect(manager.getPluginTools(agentId)).toEqual([]);
|
||||
} finally {
|
||||
await h.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test("switching a native tool to an equivalent plugin under another id reopens the session, so its catalog reaches the replacement", async () => {
|
||||
const h = await setup(true, openCounterSource);
|
||||
try {
|
||||
const a = await h.create();
|
||||
await h.client.disablePlugin("tools-test");
|
||||
await h.install("replacement", openCounterSource);
|
||||
await sendAndFinish(h, a.id, "after replacement");
|
||||
expect(h.launches).toHaveLength(2);
|
||||
// The replacement answers: it saw the refresh and the reopen.
|
||||
expect(
|
||||
await h.launches.at(-1)!.context!.paseoTools!.executeTool("other_opens", {}),
|
||||
).toMatchObject({ content: [{ type: "text", text: "2" }] });
|
||||
} finally {
|
||||
await h.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
const mcpOnlySource = `
|
||||
export default function contribute(server) {
|
||||
server.addHook("agent.open.before", async ({ request }) => ({ ...request, mcpServers: { ...request.mcpServers, company: ${JSON.stringify(companyServer)} } }));
|
||||
return () => {};
|
||||
}
|
||||
`;
|
||||
|
||||
test("a plugin that adds an MCP server name another plugin already uses makes the reopen report the collision", async () => {
|
||||
const h = await setup(false, mcpOnlySource);
|
||||
try {
|
||||
const a = await h.create();
|
||||
await h.install("duplicate-mcp", mcpOnlySource);
|
||||
await expect(h.daemon.daemon.agentManager.reloadStalePluginSession(a.id)).rejects.toThrow(
|
||||
/MCP server company from plugin tools-test collides with plugin duplicate-mcp/,
|
||||
);
|
||||
expect(h.launches).toHaveLength(1);
|
||||
} finally {
|
||||
await h.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test("a reopen that fails the MCP check is retried, and the running session keeps its plugin tools", async () => {
|
||||
const h = await setup(false, mcpSource, undefined, { supportsMcpServers: false });
|
||||
try {
|
||||
await h.client.disablePlugin("tools-test");
|
||||
await h.install("unrelated", breakableSource(path.join(h.directory, "never-armed")));
|
||||
const a = await h.create();
|
||||
await h.client.enablePlugin("tools-test");
|
||||
const manager = h.daemon.daemon.agentManager;
|
||||
await expect(manager.reloadStalePluginSession(a.id)).rejects.toThrow(/does not support MCP/);
|
||||
await expect(manager.reloadStalePluginSession(a.id)).rejects.toThrow(/does not support MCP/);
|
||||
expect(h.launches).toHaveLength(1);
|
||||
expect(
|
||||
await (await h.mcp(a.id)).callTool({ name: "breakable_ping", arguments: {} }),
|
||||
).toMatchObject({ content: [{ type: "text", text: "pong" }] });
|
||||
} finally {
|
||||
await h.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test("a reopen whose plugin MCP server takes a saved server name is retried, and reverting the plugin restores its tools", async () => {
|
||||
const h = await setup(false, openCounterSource);
|
||||
try {
|
||||
const manager = h.daemon.daemon.agentManager;
|
||||
const a = await manager.createAgent(
|
||||
{
|
||||
provider: "codex",
|
||||
cwd: h.directory,
|
||||
mcpServers: { company: companyServer },
|
||||
},
|
||||
undefined,
|
||||
{},
|
||||
);
|
||||
await writePluginSource(
|
||||
h,
|
||||
"tools-test",
|
||||
openCounterSource.replace(
|
||||
"return { ...request, tools: [...request.tools, tool] };",
|
||||
`return { ...request, tools: [...request.tools, tool], mcpServers: { company: ${JSON.stringify(companyServer)} } };`,
|
||||
),
|
||||
);
|
||||
await h.client.reloadPlugin("tools-test");
|
||||
const collision = /MCP server 'company' from plugin tools-test collides with agent saved/;
|
||||
await expect(manager.reloadStalePluginSession(a.id)).rejects.toThrow(collision);
|
||||
await expect(manager.reloadStalePluginSession(a.id)).rejects.toThrow(collision);
|
||||
|
||||
await writePluginSource(h, "tools-test", openCounterSource);
|
||||
await h.client.reloadPlugin("tools-test");
|
||||
expect(await listedToolNames(await h.mcp(a.id))).toContain("other_opens");
|
||||
await manager.reloadStalePluginSession(a.id);
|
||||
expect(h.launches).toHaveLength(1);
|
||||
} finally {
|
||||
await h.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test("history opens ignore session-open MCP servers", async () => {
|
||||
const h = await setup(true, mcpSource);
|
||||
try {
|
||||
|
||||
@@ -27,9 +27,46 @@ export type SessionOpenWireRequest = Omit<PluginSessionOpenRequest, "tools"> & {
|
||||
tools: AgentToolMetadata[];
|
||||
};
|
||||
|
||||
export interface PluginAgentToolsRuntime {
|
||||
isToolPluginAvailable(pluginId: string, pluginInstanceId: string): boolean;
|
||||
detachTools(agentId: string): void;
|
||||
export type PluginSessionOpenResult = SessionOpenWireRequest & {
|
||||
tools: AttachedAgentTool[];
|
||||
mcpServerOwners: Record<string, string>;
|
||||
};
|
||||
|
||||
/** What an open request says about the agent that can change while its session runs. Plugins cannot change it. */
|
||||
export type SessionOpenAgentFacts = Pick<
|
||||
SessionOpenWireRequest,
|
||||
"workspaceId" | "title" | "background" | "labels" | "metadata"
|
||||
>;
|
||||
|
||||
export interface PluginSessionRefreshOptions {
|
||||
/** Tool names a refreshed plugin tool must not take, beyond the tools other plugins attached. */
|
||||
reservedToolNames(): Promise<ReadonlySet<string>>;
|
||||
/** The agent as it is now, so a rerun callback sees what a reopen would show it. */
|
||||
agentFacts(): Promise<SessionOpenAgentFacts>;
|
||||
}
|
||||
|
||||
/** 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. The result
|
||||
* replaces the running session's record once `sessionLaunched` reports that its provider launch took over.
|
||||
*/
|
||||
openSession(request: SessionOpenWireRequest): Promise<PluginSessionOpenResult>;
|
||||
/** The provider session launched with the last open's result. */
|
||||
sessionLaunched(agentId: string): void;
|
||||
/** The last open's result did not launch; the session still running keeps its tools. */
|
||||
sessionLaunchFailed(agentId: string): void;
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
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,
|
||||
|
||||
@@ -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,10 +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"];
|
||||
callTool?: PluginRuntime["callTool"];
|
||||
detachTools?: PluginRuntime["detachTools"];
|
||||
emit?: PluginLifecycle["emit"];
|
||||
drainEvents?: PluginRuntime["drainEvents"];
|
||||
before?: PluginLifecycle["before"];
|
||||
@@ -102,6 +101,11 @@ export class PluginService {
|
||||
private readonly builtinPlugins: BuiltinPluginLoader;
|
||||
private readonly logger: pino.Logger;
|
||||
private readonly errors = new Map<string, string>();
|
||||
/**
|
||||
* Restarts in progress. A restart stops the plugin before its replacement starts; a session refresh waits for it,
|
||||
* so the gap never reads as the plugin's removal. A restart that fails to start reads as one.
|
||||
*/
|
||||
private readonly restarts = new Set<Promise<void>>();
|
||||
private readonly listeners = new Set<(pluginId: string) => void>();
|
||||
private readonly providers = new Map<string, ProviderRegistration>();
|
||||
private readonly usageSources: UsageSourceRegistry;
|
||||
@@ -153,22 +157,33 @@ 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 detachTools: PluginAgentToolsRuntime["detachTools"] = (agentId) => {
|
||||
this.runtime.detachTools?.(agentId);
|
||||
readonly sessionLaunched: PluginSessionsRuntime["sessionLaunched"] = (agentId) => {
|
||||
this.runtime.sessionAttachments?.launched(agentId);
|
||||
};
|
||||
|
||||
readonly callTool: PluginAgentToolsRuntime["callTool"] = async (
|
||||
readonly sessionLaunchFailed: PluginSessionsRuntime["sessionLaunchFailed"] = (agentId) => {
|
||||
this.runtime.sessionAttachments?.launchFailed(agentId);
|
||||
};
|
||||
|
||||
readonly refreshSession: PluginSessionsRuntime["refreshSession"] = async (agentId, options) => {
|
||||
while (this.restarts.size > 0) await Promise.all(this.restarts);
|
||||
return (await this.runtime.sessionAttachments?.refresh(agentId, options)) ?? { stale: false };
|
||||
};
|
||||
|
||||
readonly sessionTools: PluginSessionsRuntime["sessionTools"] = (agentId) => {
|
||||
return this.runtime.sessionAttachments?.tools(agentId) ?? [];
|
||||
};
|
||||
|
||||
readonly closeSession: PluginSessionsRuntime["closeSession"] = (agentId) => {
|
||||
this.runtime.sessionAttachments?.close(agentId);
|
||||
};
|
||||
|
||||
readonly callTool: PluginSessionsRuntime["callTool"] = async (
|
||||
pluginId,
|
||||
pluginInstanceId,
|
||||
agent,
|
||||
@@ -176,7 +191,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);
|
||||
};
|
||||
@@ -513,8 +528,10 @@ export class PluginService {
|
||||
throw new Error("Plugins are globally disabled");
|
||||
}
|
||||
this.errors.delete(pluginId);
|
||||
await this.stopPlugin(pluginId);
|
||||
await this.startExplicit(pluginId, source.path);
|
||||
await this.restart(async () => {
|
||||
await this.stopPlugin(pluginId);
|
||||
await this.startExplicit(pluginId, source.path);
|
||||
});
|
||||
this.notify(pluginId);
|
||||
return this.requireItem(pluginId);
|
||||
});
|
||||
@@ -857,6 +874,17 @@ export class PluginService {
|
||||
for (const listener of this.providerListeners) listener();
|
||||
}
|
||||
|
||||
private async restart(run: () => Promise<void>): Promise<void> {
|
||||
const restart = run();
|
||||
const settled = restart.catch(() => {});
|
||||
this.restarts.add(settled);
|
||||
try {
|
||||
await restart;
|
||||
} finally {
|
||||
this.restarts.delete(settled);
|
||||
}
|
||||
}
|
||||
|
||||
private enqueue<T>(operation: () => Promise<T>): Promise<T> {
|
||||
const result = this.lifecycle.then(operation, operation);
|
||||
this.lifecycle = result.then(
|
||||
@@ -897,28 +925,30 @@ export class PluginService {
|
||||
const shouldActivate =
|
||||
current.enabled !== false && this.configStore.get().pluginsEnabled === true;
|
||||
if (shouldActivate) {
|
||||
if (isRunning) await this.stopPlugin(pluginId);
|
||||
try {
|
||||
await this.startExplicit(pluginId, candidate.directory);
|
||||
} catch (error) {
|
||||
let recoveryError: unknown;
|
||||
await this.restart(async () => {
|
||||
if (isRunning) await this.stopPlugin(pluginId);
|
||||
try {
|
||||
this.errors.delete(pluginId);
|
||||
if (isRunning && this.canPublish(pluginId))
|
||||
await this.startExplicit(pluginId, source.path);
|
||||
} catch (restoreError) {
|
||||
recoveryError = restoreError;
|
||||
} finally {
|
||||
await managedSources.discard(candidate);
|
||||
this.notify(pluginId);
|
||||
await this.startExplicit(pluginId, candidate.directory);
|
||||
} catch (error) {
|
||||
let recoveryError: unknown;
|
||||
try {
|
||||
this.errors.delete(pluginId);
|
||||
if (isRunning && this.canPublish(pluginId))
|
||||
await this.startExplicit(pluginId, source.path);
|
||||
} catch (restoreError) {
|
||||
recoveryError = restoreError;
|
||||
} finally {
|
||||
await managedSources.discard(candidate);
|
||||
this.notify(pluginId);
|
||||
}
|
||||
if (recoveryError)
|
||||
throw new Error(
|
||||
`Update failed: ${error instanceof Error ? error.message : String(error)}; restoring previous plugin also failed: ${recoveryError instanceof Error ? recoveryError.message : String(recoveryError)}`,
|
||||
{ cause: error },
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
if (recoveryError)
|
||||
throw new Error(
|
||||
`Update failed: ${error instanceof Error ? error.message : String(error)}; restoring previous plugin also failed: ${recoveryError instanceof Error ? recoveryError.message : String(recoveryError)}`,
|
||||
{ cause: error },
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
const activatedSource = this.configStore.get().plugins?.[pluginId];
|
||||
if (!activatedSource) {
|
||||
|
||||
@@ -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>(
|
||||
@@ -390,7 +391,8 @@ export class PluginHookHandlers implements PluginLifecycleRegistration {
|
||||
context: PluginHookContext,
|
||||
): Promise<SessionOpenWireRequest> {
|
||||
let request = validateBeforeRequest("agent.open.before", input);
|
||||
this.agentTools?.detach(request.agentId);
|
||||
// Attaching replaces the session's definitions for later calls; calls already running finish. The daemon detaches
|
||||
// the session before an open that replaces the provider session.
|
||||
let tools: AgentToolDefinition[] = [];
|
||||
for (const handler of this.handlers.get("agent.open.before") ?? []) {
|
||||
context.signal.throwIfAborted();
|
||||
|
||||
@@ -1,7 +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 } 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,
|
||||
@@ -374,7 +374,8 @@ export class PluginRuntime {
|
||||
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,
|
||||
@@ -384,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 {
|
||||
@@ -397,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,
|
||||
@@ -429,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");
|
||||
}
|
||||
|
||||
@@ -449,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");
|
||||
}
|
||||
|
||||
@@ -461,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;
|
||||
@@ -752,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;
|
||||
@@ -772,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") {
|
||||
@@ -782,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;
|
||||
}
|
||||
|
||||
@@ -927,43 +904,34 @@ 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;
|
||||
}
|
||||
|
||||
detachTools(agentId: string): void {
|
||||
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(() => {});
|
||||
},
|
||||
}));
|
||||
}
|
||||
|
||||
private detachTools(agentId: string): void {
|
||||
for (const loaded of this.plugins.values()) {
|
||||
if (loaded.child) void send(loaded.child, { type: "tools.detach", agentId }).catch(() => {});
|
||||
}
|
||||
@@ -1069,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)));
|
||||
@@ -1310,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") {
|
||||
@@ -1649,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,472 @@
|
||||
import { isDeepStrictEqual } from "node:util";
|
||||
import type pino from "pino";
|
||||
import type {
|
||||
AttachedAgentTool,
|
||||
PluginSessionOpenResult,
|
||||
PluginSessionRefreshOptions,
|
||||
SessionOpenAgentFacts,
|
||||
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[];
|
||||
/** 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 from
|
||||
* the one it runs. An open becomes the baseline only once its provider launch takes over the session, so a failed open
|
||||
* or launch 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>();
|
||||
/** Interactive opens whose provider launch has not taken over the session yet. */
|
||||
private readonly pending = 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 () => {
|
||||
// Each plugin attaches its tools again below, and a plugin that left the chain keeps none. Until the launch
|
||||
// takes over, the running session's record stays, and its plugins attach again on its next refresh if the
|
||||
// launch fails.
|
||||
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[] = [];
|
||||
let current = base;
|
||||
for (const plugin of this.plugins.sessionOpenPlugins()) {
|
||||
const input: SessionOpenWireRequest = { ...current, tools: [], mcpServers: {} };
|
||||
try {
|
||||
const output = await plugin.open(input);
|
||||
const tools = stampTools(plugin, output.tools);
|
||||
assertNoToolCollision(contributions, plugin.id, tools);
|
||||
contributions.push({
|
||||
pluginId: plugin.id,
|
||||
pluginInstanceId: plugin.instanceId,
|
||||
input,
|
||||
output,
|
||||
tools,
|
||||
synced: true,
|
||||
failed: false,
|
||||
});
|
||||
current = output;
|
||||
} catch (error) {
|
||||
this.plugins.detachEverywhere(request.agentId);
|
||||
throw new Error(`Plugin ${plugin.id} agent.open.before failed: ${describeError(error)}`, {
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
let launch: PluginSessionOpenResult;
|
||||
try {
|
||||
launch = composeLaunch(base, contributions);
|
||||
} catch (error) {
|
||||
this.plugins.detachEverywhere(request.agentId);
|
||||
throw error;
|
||||
}
|
||||
if (request.purpose === "interactive") {
|
||||
this.pending.set(request.agentId, {
|
||||
base,
|
||||
launched: contributions,
|
||||
contributions: [...contributions],
|
||||
stale: false,
|
||||
});
|
||||
}
|
||||
return launch;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
// A launch in progress attaches its own tools and takes over once it succeeds.
|
||||
if (!attachment || this.pending.has(agentId)) return { stale: false };
|
||||
if (this.isCurrent(attachment)) return { stale: attachment.stale };
|
||||
return this.serialize(agentId, () => this.reconcile(agentId, options));
|
||||
}
|
||||
|
||||
/** The provider session launched with the last open's result and now runs it. */
|
||||
launched(agentId: string): void {
|
||||
const opened = this.pending.get(agentId);
|
||||
if (!opened) return;
|
||||
this.pending.delete(agentId);
|
||||
this.attachments.set(agentId, opened);
|
||||
}
|
||||
|
||||
/** The last open's result never launched. The session that is still running keeps its record. */
|
||||
launchFailed(agentId: string): void {
|
||||
// Nothing is pending once a launch took over; its later failures close the session instead.
|
||||
if (!this.pending.delete(agentId)) return;
|
||||
this.plugins.detachEverywhere(agentId);
|
||||
}
|
||||
|
||||
/** 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]),
|
||||
);
|
||||
const attachment = this.pending.get(agentId) ?? this.attachments.get(agentId);
|
||||
return (attachment?.contributions ?? [])
|
||||
.filter(
|
||||
(contribution) =>
|
||||
contribution.synced &&
|
||||
running.get(contribution.pluginId) === contribution.pluginInstanceId,
|
||||
)
|
||||
.flatMap((contribution) => contribution.tools);
|
||||
}
|
||||
|
||||
close(agentId: string): void {
|
||||
this.pending.delete(agentId);
|
||||
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.synced &&
|
||||
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 || this.pending.has(agentId)) return { stale: false };
|
||||
if (this.isCurrent(attachment)) return { stale: attachment.stale };
|
||||
const recorded = new Map(
|
||||
attachment.contributions.map((contribution) => [contribution.pluginId, contribution]),
|
||||
);
|
||||
// The running plugins in open order, as a reopen would run them. A stopped plugin, or one that no longer declares
|
||||
// the callback, drops out, and the plugins after it see the chain without it.
|
||||
let previous = attachment.base;
|
||||
const contributions: Contribution[] = [];
|
||||
const replayed: { contribution: Contribution; plugin: SessionOpenPlugin }[] = [];
|
||||
let facts: SessionOpenAgentFacts | undefined;
|
||||
for (const plugin of this.plugins.sessionOpenPlugins()) {
|
||||
const before = recorded.get(plugin.id);
|
||||
if (before && isReusable(before, plugin, previous)) {
|
||||
contributions.push(before);
|
||||
previous = before.output;
|
||||
continue;
|
||||
}
|
||||
facts ??= await options.agentFacts();
|
||||
const contribution = await this.replay(plugin, {
|
||||
...previous,
|
||||
...facts,
|
||||
tools: [],
|
||||
mcpServers: {},
|
||||
});
|
||||
contributions.push(contribution);
|
||||
replayed.push({ contribution, plugin });
|
||||
previous = contribution.output;
|
||||
}
|
||||
await this.dropCollidingTools({
|
||||
agentId,
|
||||
owners: toolOwners(attachment.contributions),
|
||||
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 =
|
||||
contributions.some((contribution) => contribution.failed) ||
|
||||
!launchesMatch(attachment.base, 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> {
|
||||
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(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.
|
||||
this.logger.warn(
|
||||
{ err: error, pluginId: plugin.id, agentId: input.agentId },
|
||||
"Plugin session refresh failed",
|
||||
);
|
||||
return contribution(input, true);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A replayed plugin whose tool takes a name already in use keeps no tools; the reopen reports the collision. A name
|
||||
* stays with the plugin that has it in the session's record, whatever the plugin order.
|
||||
*/
|
||||
private async dropCollidingTools({
|
||||
agentId,
|
||||
owners,
|
||||
contributions,
|
||||
replayed,
|
||||
options,
|
||||
}: CollisionCheck): 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);
|
||||
}
|
||||
// The previous owner keeps a name only while it still returns that tool.
|
||||
const ownedElsewhere = (contribution: Contribution, name: string) => {
|
||||
const owner = owners.get(name);
|
||||
if (owner === undefined || owner === contribution.pluginId) return false;
|
||||
return contributions.some(
|
||||
(other) => other.pluginId === owner && other.tools.some((tool) => tool.name === name),
|
||||
);
|
||||
};
|
||||
for (const contribution of changed) {
|
||||
const conflict = contribution.tools.find(
|
||||
(tool) => taken.has(tool.name) || ownedElsewhere(contribution, tool.name),
|
||||
);
|
||||
if (conflict) {
|
||||
this.logger.warn(
|
||||
{ agentId, pluginId: contribution.pluginId, tool: conflict.name },
|
||||
"Refreshed plugin tool collides with another agent tool",
|
||||
);
|
||||
contribution.tools = [];
|
||||
contribution.failed = true;
|
||||
continue;
|
||||
}
|
||||
for (const tool of contribution.tools) taken.add(tool.name);
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
interface CollisionCheck {
|
||||
agentId: string;
|
||||
/** Which plugin has each tool name in the session's record before this refresh. */
|
||||
owners: ReadonlyMap<string, string>;
|
||||
contributions: Contribution[];
|
||||
replayed: { contribution: Contribution }[];
|
||||
options: PluginSessionRefreshOptions;
|
||||
}
|
||||
|
||||
function toolOwners(contributions: readonly Contribution[]): Map<string, string> {
|
||||
return new Map(
|
||||
contributions.flatMap((contribution) =>
|
||||
contribution.tools.map((tool) => [tool.name, contribution.pluginId] as const),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A recorded contribution stands for the plugin's callback in a reopen while the plugin runs the same instance, holds
|
||||
* the tools in its process, and would receive the same env and instructions from the plugins before it.
|
||||
*/
|
||||
function isReusable(
|
||||
contribution: Contribution,
|
||||
plugin: SessionOpenPlugin,
|
||||
incoming: SessionOpenWireRequest,
|
||||
): boolean {
|
||||
return (
|
||||
contribution.synced &&
|
||||
contribution.pluginInstanceId === plugin.instanceId &&
|
||||
isDeepStrictEqual(chainedFields(contribution.input), chainedFields(incoming))
|
||||
);
|
||||
}
|
||||
|
||||
/** The fields one plugin's callback passes on to the next. Tools and MCP servers are collected per plugin instead. */
|
||||
function chainedFields(request: SessionOpenWireRequest) {
|
||||
return { env: request.env, appendSystemPrompt: request.appendSystemPrompt ?? [] };
|
||||
}
|
||||
|
||||
/**
|
||||
* What the provider launches with when the session opens with these contributions, in open order. Throws when two
|
||||
* plugins return the same MCP server name.
|
||||
*/
|
||||
function composeLaunch(
|
||||
base: SessionOpenWireRequest,
|
||||
contributions: readonly Contribution[],
|
||||
): PluginSessionOpenResult {
|
||||
const mcpServers: SessionOpenWireRequest["mcpServers"] = {};
|
||||
const mcpServerOwners: Record<string, string> = {};
|
||||
for (const contribution of contributions) {
|
||||
collectMcpServers(
|
||||
mcpServers,
|
||||
mcpServerOwners,
|
||||
contribution.pluginId,
|
||||
contribution.output.mcpServers,
|
||||
);
|
||||
}
|
||||
return {
|
||||
...(contributions.at(-1)?.output ?? base),
|
||||
tools: contributions.flatMap((contribution) => contribution.tools),
|
||||
mcpServers,
|
||||
mcpServerOwners,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the proposed contributions launch the session as it runs now. A tool's plugin counts, since native-tool
|
||||
* catalogs dispatch to it; its instance does not. A launch the open would reject never matches, so the reopen
|
||||
* reports it.
|
||||
*/
|
||||
function launchesMatch(
|
||||
base: SessionOpenWireRequest,
|
||||
launched: readonly Contribution[],
|
||||
proposed: readonly Contribution[],
|
||||
): boolean {
|
||||
let next: PluginSessionOpenResult;
|
||||
try {
|
||||
next = composeLaunch(base, proposed);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
return isDeepStrictEqual(launchContract(composeLaunch(base, launched)), launchContract(next));
|
||||
}
|
||||
|
||||
function launchContract(launch: PluginSessionOpenResult) {
|
||||
return {
|
||||
...chainedFields(launch),
|
||||
mcpServers: launch.mcpServers,
|
||||
tools: launch.tools.map(({ pluginId, name, title, description, inputSchema }) => ({
|
||||
pluginId,
|
||||
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(
|
||||
`Plugin ${pluginId} agent.open.before failed: 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);
|
||||
}
|
||||
@@ -498,12 +498,42 @@ 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. |
|
||||
| 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. |
|
||||
|
||||
If an automatic reopen fails, the triggering prompt fails with that error. See the
|
||||
When a plugin declaring `agent.open.before` starts, stops, or reloads, Paseo reruns that plugin's
|
||||
callback for each open session, before the session's next agent tool call or prompt. The callback
|
||||
gets the request it saw at the session's last open, with `reason: "refresh"` and the agent's current
|
||||
title, workspace, labels, and metadata. A later plugin in the chain also reruns when the env or
|
||||
instructions it receives change. Other callbacks do not run.
|
||||
|
||||
A reload counts as one change. A tool call or prompt during the reload waits for the plugin to
|
||||
start, so the session does not lose the plugin's tools in between. If the plugin fails to start,
|
||||
the session continues as if the plugin stopped.
|
||||
|
||||
- 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, tool definitions, or the plugin that provides a tool
|
||||
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
|
||||
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.
|
||||
- If two plugins return the same MCP server name, both plugins keep their agent tools, but the reopen
|
||||
before the next idle prompt fails with the collision error.
|
||||
|
||||
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 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. 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