mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-26 02:05:31 +00:00
fix(server): replay the plugin chain in order, hold refreshes over a plugin restart, and roll back every failed launch's plugin open
- A cached plugin contribution is reused only when its instance and the env and instructions it received still match; otherwise the plugin reruns in open order and the composed launch is compared with the running one. - A plugin reload or source update publishes one settled change: a session refresh waits for the restart instead of reading the stop as removal. - Create, resume, import, and reopen share one launch boundary: the pending plugin open commits when registerSession admits the agent and is discarded when the launch throws before that.
This commit is contained in:
@@ -207,6 +207,18 @@ 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;
|
||||
@@ -1682,7 +1694,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,
|
||||
@@ -1803,7 +1825,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,
|
||||
@@ -1909,18 +1943,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 });
|
||||
@@ -2016,7 +2055,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 },
|
||||
@@ -2132,8 +2193,8 @@ export class AgentManager {
|
||||
throw error;
|
||||
} finally {
|
||||
if (!handedToRegistration) {
|
||||
// The closed agent drops its plugin record; a launch that never closed it leaves the rollback to launchAgent.
|
||||
if (closedExisting) this.detachPluginTools(agentId);
|
||||
else this.pluginLaunchFailed(agentId);
|
||||
if (hadPreviousPaseoToolPolicy) {
|
||||
this.paseoToolPolicies.set(agentId, previousPaseoToolPolicy);
|
||||
} else {
|
||||
@@ -2146,34 +2207,21 @@ export class AgentManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates a reload's launch before it closes the running session. A rejected launch never takes over, so the
|
||||
* running session keeps its plugin tools.
|
||||
*/
|
||||
/** Validates a reload's launch before it closes the running session. */
|
||||
private resolveReloadLaunchConfig(
|
||||
existing: ActiveManagedAgent,
|
||||
launchConfig: AgentSessionConfig,
|
||||
launchContext: AgentLaunchContext,
|
||||
): AgentSessionConfig {
|
||||
try {
|
||||
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;
|
||||
} catch (error) {
|
||||
this.pluginLaunchFailed(existing.id);
|
||||
throw error;
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/** The plugin open for a launch that never took over; the session still running keeps its plugin tools. */
|
||||
private pluginLaunchFailed(agentId: string): void {
|
||||
this.pluginSessions?.sessionLaunchFailed(agentId);
|
||||
return providerLaunchConfig;
|
||||
}
|
||||
|
||||
private async closeReloadedSession(session: AgentSession, agentId: string): Promise<void> {
|
||||
@@ -4645,8 +4693,6 @@ export class AgentManager {
|
||||
launchEnv?: Record<string, string>;
|
||||
},
|
||||
): Promise<ManagedAgent> {
|
||||
// The provider session launched and passed validation, so its plugin open now describes the running session.
|
||||
this.pluginSessions?.sessionLaunched(agentId);
|
||||
let registered = false;
|
||||
try {
|
||||
this.assertAcceptingAgentRegistrations();
|
||||
@@ -4695,6 +4741,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) {
|
||||
@@ -6633,16 +6681,12 @@ 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.pluginLaunchFailed(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;
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
@@ -901,6 +901,85 @@ test("a plugin reload reruns its callback with the agent's current metadata", as
|
||||
}
|
||||
}, 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);
|
||||
|
||||
// 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";
|
||||
@@ -1481,6 +1560,25 @@ 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("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 {
|
||||
|
||||
@@ -101,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;
|
||||
@@ -166,6 +171,7 @@ export class PluginService {
|
||||
};
|
||||
|
||||
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 };
|
||||
};
|
||||
|
||||
@@ -522,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);
|
||||
});
|
||||
@@ -866,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(
|
||||
@@ -906,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) {
|
||||
|
||||
@@ -148,7 +148,8 @@ export class SessionAttachments {
|
||||
|
||||
/** The last open's result never launched. The session that is still running keeps its record. */
|
||||
launchFailed(agentId: string): void {
|
||||
this.pending.delete(agentId);
|
||||
// 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);
|
||||
}
|
||||
|
||||
@@ -195,31 +196,28 @@ export class SessionAttachments {
|
||||
const attachment = this.attachments.get(agentId);
|
||||
if (!attachment || this.pending.has(agentId)) return { stale: false };
|
||||
if (this.isCurrent(attachment)) return { stale: attachment.stale };
|
||||
const running = new Map(this.plugins.sessionOpenPlugins().map((plugin) => [plugin.id, plugin]));
|
||||
const recorded = new Map(
|
||||
attachment.contributions.map((contribution) => [contribution.pluginId, contribution]),
|
||||
);
|
||||
const pluginIds = [...new Set([...recorded.keys(), ...running.keys()])].sort((left, right) =>
|
||||
left.localeCompare(right),
|
||||
);
|
||||
// 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 pluginId of pluginIds) {
|
||||
const plugin = running.get(pluginId);
|
||||
const before = recorded.get(pluginId);
|
||||
if (plugin && before?.synced && before.pluginInstanceId === plugin.instanceId) {
|
||||
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;
|
||||
}
|
||||
// Stopped, or no longer declares the callback: the session loses what it contributed.
|
||||
if (!plugin) continue;
|
||||
facts ??= await options.agentFacts();
|
||||
const contribution = await this.replay(plugin, {
|
||||
...(before?.input ?? { ...previous, tools: [], mcpServers: {} }),
|
||||
...previous,
|
||||
...facts,
|
||||
tools: [],
|
||||
mcpServers: {},
|
||||
});
|
||||
contributions.push(contribution);
|
||||
replayed.push({ contribution, plugin });
|
||||
@@ -238,7 +236,12 @@ export class SessionAttachments {
|
||||
return { stale: false };
|
||||
}
|
||||
attachment.contributions = contributions;
|
||||
attachment.stale = launchDiffers(attachment.launched, contributions);
|
||||
attachment.stale =
|
||||
contributions.some((contribution) => contribution.failed) ||
|
||||
!isDeepStrictEqual(
|
||||
composedLaunch(attachment.base, attachment.launched),
|
||||
composedLaunch(attachment.base, contributions),
|
||||
);
|
||||
return { stale: attachment.stale };
|
||||
}
|
||||
|
||||
@@ -343,44 +346,43 @@ function toolOwners(contributions: readonly Contribution[]): Map<string, string>
|
||||
);
|
||||
}
|
||||
|
||||
/** Whether a reopen with the current contributions would launch the provider differently from the running session. */
|
||||
function launchDiffers(
|
||||
launched: readonly Contribution[],
|
||||
current: readonly Contribution[],
|
||||
/**
|
||||
* 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 {
|
||||
if (current.some((contribution) => contribution.failed)) return true;
|
||||
const before = new Map(launched.map((contribution) => [contribution.pluginId, contribution]));
|
||||
const after = new Map(current.map((contribution) => [contribution.pluginId, contribution]));
|
||||
for (const pluginId of new Set([...before.keys(), ...after.keys()])) {
|
||||
const left = before.get(pluginId);
|
||||
const right = after.get(pluginId);
|
||||
if (left && right) {
|
||||
if (!sameLaunch(left.output, right.output)) return true;
|
||||
continue;
|
||||
}
|
||||
// A plugin on one side only changes the launch when its callback changed its input.
|
||||
const only = left ?? right;
|
||||
if (only && !sameLaunch(only.input, only.output)) return true;
|
||||
}
|
||||
return false;
|
||||
return (
|
||||
contribution.synced &&
|
||||
contribution.pluginInstanceId === plugin.instanceId &&
|
||||
isDeepStrictEqual(chainedFields(contribution.input), chainedFields(incoming))
|
||||
);
|
||||
}
|
||||
|
||||
/** The parts of a plugin's open result that reach the provider launch. */
|
||||
function sameLaunch(left: SessionOpenWireRequest, right: SessionOpenWireRequest): boolean {
|
||||
return isDeepStrictEqual(launchView(left), launchView(right));
|
||||
/** 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 ?? [] };
|
||||
}
|
||||
|
||||
function launchView(request: SessionOpenWireRequest) {
|
||||
/** What the provider launches with when the session opens with these contributions, in open order. */
|
||||
function composedLaunch(base: SessionOpenWireRequest, contributions: readonly Contribution[]) {
|
||||
return {
|
||||
env: request.env,
|
||||
appendSystemPrompt: request.appendSystemPrompt ?? [],
|
||||
mcpServers: request.mcpServers,
|
||||
tools: request.tools.map(({ name, title, description, inputSchema }) => ({
|
||||
name,
|
||||
title,
|
||||
description,
|
||||
inputSchema,
|
||||
})),
|
||||
...chainedFields(contributions.at(-1)?.output ?? base),
|
||||
mcpServers: Object.assign(
|
||||
{},
|
||||
...contributions.map((contribution) => contribution.output.mcpServers),
|
||||
) as SessionOpenWireRequest["mcpServers"],
|
||||
tools: contributions.flatMap((contribution) =>
|
||||
contribution.tools.map(({ name, title, description, inputSchema }) => ({
|
||||
name,
|
||||
title,
|
||||
description,
|
||||
inputSchema,
|
||||
})),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -503,10 +503,15 @@ target are unaffected.
|
||||
| Apply immediately | Call `await paseo.agents.ref(id).reload({ requestId: "reload-notes" })`. `requestId` is optional. This reopens the provider session, reruns hooks with `reason: "refresh"`, and interrupts a running turn. |
|
||||
| Read the current snapshot | Call `await paseo.agents.ref(id).refresh()`. This reads state without reopening the session. |
|
||||
|
||||
When a plugin declaring `agent.open.before` starts, stops, or reloads, Paseo reruns only that
|
||||
plugin's callback for each open session. The callback gets the request it saw at the session's last
|
||||
open, with `reason: "refresh"` and the agent's current title, workspace, labels, and metadata. This happens before the session's next agent tool call or prompt.
|
||||
Callbacks of other plugins do not run.
|
||||
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.
|
||||
|
||||
Reference in New Issue
Block a user