Compare commits

...
65 changed files with 5731 additions and 169 deletions
@@ -45,6 +45,26 @@ const PROFILE = {
const PROFILE_SUMMARY = "Mock Load Test · One minute stream · Approval test";
// Isolate this suite to the sole mock provider so it tests single-provider picker
// behavior deterministically regardless of which CLIs are installed on the host.
test.use({
e2eDaemonConfig: {
version: 1,
agents: {
providers: {
claude: { enabled: false },
codex: { enabled: false },
copilot: { enabled: false },
opencode: { enabled: false },
pi: { enabled: false },
omp: { enabled: false },
antigravity: { enabled: false },
hoplite: { enabled: false },
},
},
},
});
test.describe("Agent profiles in the model picker", () => {
test("an empty host still exposes agent profile settings from the picker", async ({ page }) => {
const seed = await seedAgentProfiles([]);
@@ -69,8 +89,8 @@ test.describe("Agent profiles in the model picker", () => {
page,
}) => {
const seed = await seedAgentProfiles([PROFILE]);
// A live agent is one provider's process, so the profile has to name that
// same provider or the picker will not offer it at all.
// With only the mock provider enabled on this host, the picker opens
// directly into its models and shows its pinned profile.
const workspace = await seedMockAgentWorkspace({
repoPrefix: "agent-profiles-picker-",
title: "Agent profiles picker",
@@ -0,0 +1,476 @@
import { mkdir } from "node:fs/promises";
import path from "node:path";
import type { Locator } from "@playwright/test";
import { expect, test, type Page } from "../support/fixtures";
import { expectAgentIdle, expectAgentReadyToInterrupt } from "../support/helpers/agent-stream";
import {
drillIntoProvider,
expectComposerMode,
expectComposerModel,
openModelPicker,
selectModelRow,
} from "../support/helpers/agent-profiles";
import { expectWorkspaceAgentConfiguration } from "../support/helpers/command-center-agent-controls";
import {
expectComposerVisible,
expectQueuedMessageButton,
submitMessage,
submitMessageWithButton,
} from "../support/helpers/composer";
import { connectDaemonClient } from "../support/helpers/daemon-client-loader";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import { copyPluginExample } from "../support/helpers/plugin-fixture";
import { userScrollsTimelineToHistoryStart } from "../support/helpers/timeline-pagination";
const DIRECT_PROVIDER = {
id: "direct-example",
label: "Direct provider example",
pluginId: "provider-direct-example",
modelId: "example-1",
modelLabel: "Example 1",
modeLabel: "Build",
} as const;
// Disable external CLIs so the E2E host deterministically exposes only Mock +
// the installed Direct provider plugin on both developer machines and CI.
test.use({
e2eDaemonConfig: {
version: 1,
agents: {
providers: {
claude: { enabled: false },
codex: { enabled: false },
copilot: { enabled: false },
opencode: { enabled: false },
pi: { enabled: false },
omp: { enabled: false },
antigravity: { enabled: false },
hoplite: { enabled: false },
},
},
},
});
interface PluginInstallDaemonClient {
connect(): Promise<void>;
close(): Promise<void>;
getDaemonConfig(): Promise<{ config: { pluginsEnabled?: boolean } }>;
patchDaemonConfig(config: { pluginsEnabled?: boolean }): Promise<unknown>;
installDirectoryPlugin(directory: string): Promise<unknown>;
removePlugin(pluginId: string): Promise<void>;
getProvidersSnapshot(): Promise<{
entries: Array<{ provider: string; available?: boolean }>;
}>;
}
async function hasDirectProvider(client: PluginInstallDaemonClient): Promise<boolean> {
const snapshot = await client.getProvidersSnapshot();
return snapshot.entries.some((entry) => entry.provider === DIRECT_PROVIDER.id);
}
async function expectSwitchMarkerCountAfterScroll(page: Page, expected: number): Promise<void> {
await expect
.poll(
async () => {
await userScrollsTimelineToHistoryStart(page);
return await page.getByTestId("provider-switch-marker").count();
},
{ timeout: 30_000 },
)
.toBe(expected);
}
async function captureQaScreenshot(page: Page, fileName: string): Promise<void> {
const dir = process.env.PASEO_QA_SCREENSHOT_DIR?.trim();
if (!dir) return;
await mkdir(dir, { recursive: true });
await page.screenshot({ path: path.join(dir, fileName), fullPage: false });
}
async function expectNoHorizontalOverflow(page: Page): Promise<void> {
const overflow = await page.evaluate(() => {
const doc = document.documentElement;
return Math.ceil(doc.scrollWidth - doc.clientWidth);
});
expect(overflow).toBeLessThanOrEqual(1);
}
async function completeMockTurn(
page: Page,
agent: Awaited<ReturnType<typeof seedMockAgentWorkspace>>,
prompt: string,
): Promise<Locator> {
await submitMessage(page, prompt);
const userMessage = page.getByTestId("user-message").filter({ hasText: prompt });
await expect(userMessage).toBeVisible({ timeout: 30_000 });
const finish = await agent.client.waitForFinish(agent.agentId, 30_000);
expect(finish.status).toBe("idle");
await expectAgentIdle(page);
await expect(userMessage).toHaveAttribute("aria-busy", "false");
return userMessage;
}
async function completeDirectTurn(
page: Page,
agent: Awaited<ReturnType<typeof seedMockAgentWorkspace>>,
prompt: string,
options?: { useSendButton?: boolean },
): Promise<Locator> {
if (options?.useSendButton) {
await submitMessageWithButton(page, prompt);
} else {
await submitMessage(page, prompt);
}
const userMessage = page.getByTestId("user-message").filter({ hasText: prompt });
await expect(userMessage).toBeVisible({ timeout: 30_000 });
const finish = await agent.client.waitForFinish(agent.agentId, 30_000);
expect(finish.status).toBe("idle");
await expectAgentIdle(page);
await expect(userMessage).toHaveAttribute("aria-busy", "false");
return userMessage;
}
async function stageProviderDesktop(
page: Page,
providerId: string,
modelId: string,
): Promise<void> {
await openModelPicker(page);
const picker = page.getByTestId("combobox-desktop-container");
const backButton = picker.getByTestId("sheet-header-back");
if (await backButton.isVisible()) {
await backButton.click();
}
await drillIntoProvider(page, providerId);
await selectModelRow(page, { provider: providerId, modelId });
await expect(page.getByTestId("staged-provider-switch-banner")).toBeVisible({ timeout: 30_000 });
}
async function stageDirectProviderDesktop(page: Page): Promise<void> {
await stageProviderDesktop(page, DIRECT_PROVIDER.id, DIRECT_PROVIDER.modelId);
}
async function stageDirectProviderCompact(page: Page): Promise<void> {
await page.getByTestId("combined-model-selector").filter({ visible: true }).first().click();
await expect(page.getByTestId("agent-controls-model")).toBeVisible({ timeout: 30_000 });
await page.getByTestId("agent-controls-model").click();
const browserViewport = page.getByTestId("agent-controls-model-browser-viewport");
await expect(browserViewport).toBeVisible({ timeout: 30_000 });
await browserViewport.getByTestId(`model-provider-${DIRECT_PROVIDER.id}`).click();
await browserViewport
.getByTestId(`model-row-${DIRECT_PROVIDER.id}-${DIRECT_PROVIDER.modelId}`)
.click();
await expect(browserViewport).toHaveCount(0, { timeout: 30_000 });
// Dismiss the outer agent-controls sheet so the composer and banner are ready to submit.
await page.getByRole("button", { name: "Close", exact: true }).last().click();
await expect(page.getByTestId("agent-controls-model")).toHaveCount(0, { timeout: 30_000 });
await expect(page.getByTestId("staged-provider-switch-banner")).toBeVisible({ timeout: 30_000 });
}
async function rewindConversation(page: Page, userMessage: Locator, prompt: string): Promise<void> {
await userMessage.getByText(prompt, { exact: true }).hover();
await userMessage.getByRole("button", { name: "Rewind to this message", exact: true }).click();
await page.getByRole("menuitem", { name: "Rewind conversation", exact: true }).click();
}
test.describe.serial("Provider switching in chat", () => {
let pluginClient: PluginInstallDaemonClient;
let pluginFixture: Awaited<ReturnType<typeof copyPluginExample>>;
let previousPluginsEnabled: boolean | undefined;
test.beforeAll(async () => {
pluginClient = await connectDaemonClient<PluginInstallDaemonClient>({
clientIdPrefix: "provider-switching-e2e",
});
pluginFixture = await copyPluginExample("provider-direct");
previousPluginsEnabled = (await pluginClient.getDaemonConfig()).config.pluginsEnabled;
await pluginClient.patchDaemonConfig({ pluginsEnabled: true });
await pluginClient.installDirectoryPlugin(pluginFixture.directory);
await expect.poll(() => hasDirectProvider(pluginClient), { timeout: 30_000 }).toBe(true);
});
test.afterAll(async () => {
await pluginClient?.removePlugin(DIRECT_PROVIDER.pluginId).catch(() => undefined);
await pluginClient
?.patchDaemonConfig({ pluginsEnabled: previousPluginsEnabled })
.catch(() => undefined);
await pluginClient?.close().catch(() => undefined);
await pluginFixture?.cleanup().catch(() => undefined);
});
test("stages, cancels, switches providers, inspects marker, scopes rewind, and survives reload", async ({
page,
}) => {
test.setTimeout(150_000);
await page.setViewportSize({ width: 1280, height: 800 });
const preSwitchPrompt = "First prompt on Mock before switching.";
const postSwitchPrompt = "Follow up on Direct provider after switching.";
const postRewindPrompt = "Continue on Direct provider after rewinding.";
const workspace = await seedMockAgentWorkspace({
repoPrefix: "provider-switch-desktop-",
title: "Provider switch desktop",
model: "e2e-fast-stream",
modeId: "load-test",
});
try {
await openAgentRoute(page, workspace);
await expectComposerVisible(page);
await expectComposerMode(page, "Load test");
const initialUrl = page.url();
await completeMockTurn(page, workspace, preSwitchPrompt);
await test.step("staging updates only draft state and Cancel restores the live provider", async () => {
await stageDirectProviderDesktop(page);
await expectComposerModel(page, DIRECT_PROVIDER.modelLabel);
await expectComposerMode(page, DIRECT_PROVIDER.modeLabel);
await expect(page.getByTestId("staged-provider-switch-banner")).toContainText(
DIRECT_PROVIDER.label,
);
await expectWorkspaceAgentConfiguration(workspace, {
id: workspace.agentId,
provider: "mock",
model: "e2e-fast-stream",
modeId: "load-test",
});
await expectNoHorizontalOverflow(page);
await captureQaScreenshot(page, "desktop-staged-switch.png");
await page.getByTestId("cancel-staged-provider-switch").click();
await expect(page.getByTestId("staged-provider-switch-banner")).toHaveCount(0);
await expectComposerMode(page, "Load test");
});
await test.step("submitting commits the switch in place with clean user display text and inspectable marker", async () => {
await stageDirectProviderDesktop(page);
const switchedMessage = await completeDirectTurn(page, workspace, postSwitchPrompt);
expect(page.url()).toBe(initialUrl);
await expect(page.getByTestId("staged-provider-switch-banner")).toHaveCount(0);
await expectWorkspaceAgentConfiguration(workspace, {
id: workspace.agentId,
provider: DIRECT_PROVIDER.id,
model: DIRECT_PROVIDER.modelId,
modeId: "build",
});
// Clean display text: handoff summary must never leak into the visible user bubble.
await expect(switchedMessage).toContainText(postSwitchPrompt);
await expect(switchedMessage).not.toContainText("<chat-history-summary>");
// Direct provider echoes its prompt, proving bounded pre-switch context was attached.
const directReply = page
.getByTestId("assistant-message")
.filter({ hasText: "Echo:" })
.last();
await expect(directReply).toContainText(preSwitchPrompt);
await expect(directReply).toContainText(postSwitchPrompt);
// Switch marker is visible and expands to show context handoff details.
const marker = page.getByTestId("provider-switch-marker");
await expect(marker).toBeVisible({ timeout: 30_000 });
await marker.scrollIntoViewIfNeeded();
await marker.getByTestId("provider-switch-marker-toggle").click();
const details = marker.getByTestId("provider-switch-marker-details");
await expect(details).toBeVisible();
await expect(details).toContainText("Mock");
await expect(details).toContainText(DIRECT_PROVIDER.label);
await marker.scrollIntoViewIfNeeded();
await expectNoHorizontalOverflow(page);
await captureQaScreenshot(page, "desktop-switched-expanded.png");
await marker.getByTestId("provider-switch-marker-toggle").click();
await expect(details).toHaveCount(0);
});
await test.step("switching back to Mock enforces segment-scoped rewind and preserves pre-switch turns", async () => {
const backToMockPrompt = "Switch back to Mock for segment-scoped rewind.";
await stageProviderDesktop(page, "mock", "ten-second-stream");
await expect(page.getByTestId("staged-provider-switch-banner")).toContainText("Mock");
const backToMockMessage = await completeMockTurn(page, workspace, backToMockPrompt);
await expect(backToMockMessage).not.toContainText("<chat-history-summary>");
await expect(page.getByTestId("provider-switch-marker")).toHaveCount(2, {
timeout: 30_000,
});
await expectWorkspaceAgentConfiguration(workspace, {
id: workspace.agentId,
provider: "mock",
model: "ten-second-stream",
modeId: "load-test",
});
// Pre-switch prompts from earlier segments must not expose rewind even though Mock supports it.
const preSwitchMessage = page
.getByTestId("user-message")
.filter({ hasText: preSwitchPrompt });
await preSwitchMessage.scrollIntoViewIfNeeded();
await preSwitchMessage.getByText(preSwitchPrompt, { exact: true }).hover();
await expect(
preSwitchMessage.getByRole("button", { name: "Rewind to this message", exact: true }),
).toHaveCount(0);
const directMessage = page
.getByTestId("user-message")
.filter({ hasText: postSwitchPrompt });
await directMessage.scrollIntoViewIfNeeded();
await directMessage.getByText(postSwitchPrompt, { exact: true }).hover();
await expect(
directMessage.getByRole("button", { name: "Rewind to this message", exact: true }),
).toHaveCount(0);
// Post-switch prompt on Mock CAN rewind without retiring earlier segments or markers.
await backToMockMessage.scrollIntoViewIfNeeded();
await rewindConversation(page, backToMockMessage, backToMockPrompt);
await expect(
page.getByTestId("user-message").filter({ hasText: backToMockPrompt }),
).toHaveCount(0, { timeout: 30_000 });
await expect(
page.getByTestId("user-message").filter({ hasText: preSwitchPrompt }),
).toBeVisible();
await expect(
page.getByTestId("user-message").filter({ hasText: postSwitchPrompt }),
).toBeVisible();
await expect(page.getByTestId("provider-switch-marker")).toHaveCount(2);
// Continuing in the now-empty active segment completes cleanly.
const retriedMessage = await completeMockTurn(page, workspace, postRewindPrompt);
await expect(retriedMessage).not.toContainText("<chat-history-summary>");
});
await test.step("reload preserves the switched provider, markers, and rewind boundary", async () => {
await page.reload();
await expectComposerVisible(page);
await expectComposerModel(page, "Ten second stream");
await expectSwitchMarkerCountAfterScroll(page, 2);
const reloadedDirect = page
.getByTestId("user-message")
.filter({ hasText: postSwitchPrompt });
await expect(reloadedDirect).toBeVisible();
await expect(
page.getByTestId("user-message").filter({ hasText: postRewindPrompt }),
).toBeVisible();
await reloadedDirect.scrollIntoViewIfNeeded();
await reloadedDirect.getByText(postSwitchPrompt, { exact: true }).hover();
await expect(
reloadedDirect.getByRole("button", { name: "Rewind to this message", exact: true }),
).toHaveCount(0);
});
} finally {
await workspace.cleanup();
}
});
test("stages a switch mid-turn, queues the prompt, and switches cleanly between turns", async ({
page,
}) => {
test.setTimeout(150_000);
await page.setViewportSize({ width: 1280, height: 800 });
const runningPrompt = "Run a ten-second mock turn first.";
const queuedPrompt = "Queued handoff prompt for Direct provider.";
const workspace = await seedMockAgentWorkspace({
repoPrefix: "provider-switch-midturn-",
title: "Provider switch midturn",
model: "ten-second-stream",
modeId: "load-test",
});
try {
await openAgentRoute(page, workspace);
await expectComposerVisible(page);
await submitMessage(page, runningPrompt);
await expectAgentReadyToInterrupt(page);
// Stage Direct provider while Mock is actively streaming.
await stageDirectProviderDesktop(page);
await expectWorkspaceAgentConfiguration(workspace, {
id: workspace.agentId,
provider: "mock",
model: "ten-second-stream",
modeId: "load-test",
});
// Submitting queues the prompt instead of racing the live turn.
await submitMessage(page, queuedPrompt);
await expectQueuedMessageButton(page);
// Once the mock turn completes, the queue drains and commits the switch.
await expect(page.getByTestId("provider-switch-marker")).toBeVisible({ timeout: 45_000 });
await expect(page.getByTestId("staged-provider-switch-banner")).toHaveCount(0, {
timeout: 30_000,
});
await expect(
page.getByTestId("assistant-message").filter({ hasText: queuedPrompt }).last(),
).toBeVisible({ timeout: 30_000 });
await expectAgentIdle(page);
await expectWorkspaceAgentConfiguration(workspace, {
id: workspace.agentId,
provider: DIRECT_PROVIDER.id,
model: DIRECT_PROVIDER.modelId,
modeId: "build",
});
} finally {
await workspace.cleanup();
}
});
test("switches providers cleanly on a compact viewport with zero horizontal overflow", async ({
page,
}) => {
test.setTimeout(150_000);
await page.setViewportSize({ width: 390, height: 844 });
const preSwitchPrompt = "Compact turn on Mock.";
const postSwitchPrompt = "Compact handoff on Direct.";
const workspace = await seedMockAgentWorkspace({
repoPrefix: "provider-switch-compact-",
title: "Provider switch compact",
model: "e2e-fast-stream",
modeId: "load-test",
});
try {
await openAgentRoute(page, workspace);
await expectComposerVisible(page);
await submitMessageWithButton(page, preSwitchPrompt);
await expect(
page.getByTestId("user-message").filter({ hasText: preSwitchPrompt }),
).toBeVisible({ timeout: 30_000 });
const firstFinish = await workspace.client.waitForFinish(workspace.agentId, 30_000);
expect(firstFinish.status).toBe("idle");
await expectAgentIdle(page);
await stageDirectProviderCompact(page);
await expectNoHorizontalOverflow(page);
await captureQaScreenshot(page, "compact-staged-switch.png");
const switchedMessage = await completeDirectTurn(page, workspace, postSwitchPrompt, {
useSendButton: true,
});
await expect(switchedMessage).not.toContainText("<chat-history-summary>");
const marker = page.getByTestId("provider-switch-marker");
await expect(marker).toBeVisible({ timeout: 30_000 });
await marker.scrollIntoViewIfNeeded();
const toggle = marker.getByTestId("provider-switch-marker-toggle");
const toggleBox = await toggle.boundingBox();
expect(toggleBox).not.toBeNull();
expect((toggleBox?.x ?? 0) + (toggleBox?.width ?? 0)).toBeLessThanOrEqual(390);
await toggle.click();
await expect(marker.getByTestId("provider-switch-marker-details")).toBeVisible();
await marker.scrollIntoViewIfNeeded();
await expectNoHorizontalOverflow(page);
await captureQaScreenshot(page, "compact-switched-expanded.png");
} finally {
await workspace.cleanup();
}
});
});
@@ -23,7 +23,14 @@ export interface DraftAgentProfileControls {
}
export type AgentProfileApplyTarget =
| { kind: "agent"; agentId: string; availableModeIds: readonly string[] | null }
| {
kind: "agent";
agentId: string;
availableModeIds: readonly string[] | null;
currentProvider?: string | null;
onApplySameProvider?: () => void;
onStageProviderSwitch?: (profile: MaterializedAgentProfile) => void;
}
| { kind: "draft"; controls: DraftAgentProfileControls };
/** Everything the model picker renders for one profile. It never sees the profile itself. */
@@ -139,6 +146,16 @@ export function useAgentProfilePicker(
return;
}
if (
target.onStageProviderSwitch &&
target.currentProvider &&
resolved.provider !== target.currentProvider
) {
target.onStageProviderSwitch(resolved);
return;
}
target.onApplySameProvider?.();
const reconciled = reconcileMaterializedProfileMode(resolved, target.availableModeIds);
if (!reconciled) {
return;
@@ -101,7 +101,7 @@ function summaryRow(
}
function staysVisibleWhenCollapsed(item: StreamItem): boolean {
return isTurnTrigger(item) || item.kind === "compaction";
return isTurnTrigger(item) || item.kind === "compaction" || item.kind === "provider_switch";
}
function findLastReplyIndex(tail: StreamItem[], start: number, end: number): number {
+30 -2
View File
@@ -37,6 +37,7 @@ import {
ToolCall,
TodoListCard,
CompactionMarker,
ProviderSwitchMarker,
MessageOuterSpacingProvider,
type InlinePathTarget,
} from "@/components/message";
@@ -57,6 +58,7 @@ import { useFileExplorerActions } from "@/hooks/use-file-explorer-actions";
import { useLoadOlderAgentHistory } from "@/hooks/use-load-older-agent-history";
import { resolveContentMaxWidth, useSettings } from "@/hooks/use-settings";
import type { ToastApi } from "@/components/toast-host";
import { isPromptInActiveSegment } from "@/components/rewind/use-rewind-capabilities";
import { returnToTimelineTail } from "./timeline-tail-navigation";
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import { ToolCallDetailsContent } from "@/components/tool-call-details";
@@ -715,8 +717,15 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
const setToolCallGroupExpanded = toolCallExpansion.setGroupExpanded;
const activeSegmentStartSeq = useSessionStore(
(state) =>
state.sessions[resolvedServerId]?.agentTimelineCursor.get(agentId)?.activeSegmentStartSeq ??
0,
);
const renderUserMessageItem = useCallback(
(layoutItem: StreamLayoutItem, item: Extract<StreamItem, { kind: "user_message" }>) => {
const canRewindPrompt = isPromptInActiveSegment(item.timelineCursor, activeSegmentStartSeq);
return (
<UserMessage
itemId={item.id}
@@ -728,7 +737,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
images={item.images}
attachments={item.attachments}
timestamp={item.timestamp.getTime()}
capabilities={context.capabilities}
capabilities={canRewindPrompt ? context.capabilities : undefined}
client={client}
isFirstInGroup={layoutItem.isFirstInUserGroup}
isLastInGroup={layoutItem.isLastInUserGroup}
@@ -739,7 +748,14 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
/>
);
},
[context.capabilities, agentId, client, pendingClientMessageIds, resolvedServerId],
[
activeSegmentStartSeq,
context.capabilities,
agentId,
client,
pendingClientMessageIds,
resolvedServerId,
],
);
const renderAssistantMessageItem = useCallback(
@@ -945,6 +961,18 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
/>
);
case "provider_switch":
return (
<ProviderSwitchMarker
serverId={resolvedServerId}
fromProvider={item.fromProvider}
toProvider={item.toProvider}
fromModel={item.fromModel}
toModel={item.toModel}
context={item.context}
/>
);
case "plugin":
return (
<PluginTimelineItemView agentId={agentId} item={item} serverId={resolvedServerId} />
@@ -75,6 +75,7 @@ export function estimateStreamItemHeight({
case "notification":
return 88;
case "compaction":
case "provider_switch":
return 72;
default:
return 120;
+188
View File
@@ -19,9 +19,11 @@ import {
type RewindMode,
} from "@/components/rewind";
import { TaskListRow } from "@/components/task-list-row";
import { Button } from "@/components/ui/button";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { useIsCompactFormFactor } from "@/constants/layout";
import { isNative, isWeb } from "@/constants/platform";
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
import { useRevealedText, type MarkdownPhase } from "@/hooks/use-revealed-text";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style";
@@ -40,13 +42,17 @@ import type { AgentMessage } from "@getpaseo/protocol/agent-message";
import type {
AgentCapabilityFlags,
AgentMetric,
AgentProvider,
ProviderSwitchContextSummary,
ToolCallDetail,
} from "@getpaseo/protocol/agent-types";
import type { AgentAttachment } from "@getpaseo/protocol/messages";
import MaskedView from "@react-native-masked-view/masked-view";
import {
ArrowRightLeft,
Check,
CheckSquare,
ChevronDown,
ChevronRight,
CircleDot,
Copy,
@@ -1487,6 +1493,188 @@ export const CompactionMarker = memo(function CompactionMarker({
);
});
const StyledSwitchIcon = withUnistyles(ArrowRightLeft, (theme) => ({
color: theme.colors.foregroundMuted,
}));
const StyledChevronDownIcon = withUnistyles(ChevronDown, (theme) => ({
color: theme.colors.foregroundMuted,
}));
const StyledChevronRightIcon = withUnistyles(ChevronRight, (theme) => ({
color: theme.colors.foregroundMuted,
}));
export interface ProviderSwitchMarkerProps {
serverId?: string | null;
fromProvider: AgentProvider;
toProvider: AgentProvider;
fromModel?: string | null;
toModel?: string | null;
context: ProviderSwitchContextSummary;
}
const providerSwitchStylesheet = StyleSheet.create((theme) => ({
wrapper: {
paddingVertical: theme.spacing[2],
paddingHorizontal: theme.spacing[4],
gap: theme.spacing[2],
},
row: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
width: "100%",
},
line: {
flex: 1,
minWidth: 12,
height: 1,
backgroundColor: theme.colors.border,
},
triggerButton: {
flexShrink: 1,
minWidth: 0,
maxWidth: "85%",
},
triggerContent: {
flexDirection: "row",
alignItems: "center",
flexShrink: 1,
minWidth: 0,
maxWidth: "100%",
gap: theme.spacing[1.5],
},
triggerText: {
flexShrink: 1,
minWidth: 0,
fontFamily: theme.fontFamily.ui,
fontSize: 13,
color: theme.colors.foregroundMuted,
},
detailsCard: {
alignSelf: "center",
maxWidth: 480,
width: "100%",
paddingVertical: theme.spacing[2],
paddingHorizontal: theme.spacing[3],
borderRadius: theme.borderRadius.md,
borderWidth: 1,
borderColor: theme.colors.border,
backgroundColor: theme.colors.surface0,
gap: theme.spacing[1],
},
detailRow: {
fontFamily: theme.fontFamily.ui,
fontSize: 12,
color: theme.colors.foregroundMuted,
},
}));
function resolveProviderSwitchLabel(
provider: string,
entries: ReturnType<typeof useProvidersSnapshot>["entries"],
): string {
return entries?.find((entry) => entry.provider === provider)?.label ?? provider;
}
function resolveProviderSwitchModelLabel(
provider: string,
modelId: string | null | undefined,
entries: ReturnType<typeof useProvidersSnapshot>["entries"],
): string | null {
if (!modelId) return null;
const entry = entries?.find((candidate) => candidate.provider === provider);
return entry?.models?.find((model) => model.id === modelId)?.label ?? modelId;
}
function formatProviderSwitchEndpoint(providerLabel: string, modelLabel: string | null): string {
return modelLabel ? `${providerLabel} (${modelLabel})` : providerLabel;
}
export const ProviderSwitchMarker = memo(function ProviderSwitchMarker({
serverId = null,
fromProvider,
toProvider,
fromModel,
toModel,
context,
}: ProviderSwitchMarkerProps) {
const { t } = useTranslation();
const { entries: providerEntries } = useProvidersSnapshot(serverId);
const [expanded, setExpanded] = useState(false);
const handleToggle = useCallback(() => setExpanded((prev) => !prev), []);
const fromLabel = resolveProviderSwitchLabel(fromProvider, providerEntries);
const toLabel = resolveProviderSwitchLabel(toProvider, providerEntries);
const fromModelLabel = resolveProviderSwitchModelLabel(fromProvider, fromModel, providerEntries);
const toModelLabel = resolveProviderSwitchModelLabel(toProvider, toModel, providerEntries);
const title = t("message.providerSwitch.switched", {
from: fromLabel,
to: toLabel,
});
const contextLine = t("message.providerSwitch.contextSummary", {
count: context.includedItems,
chars: context.charCount.toLocaleString(),
budget: context.budgetChars.toLocaleString(),
});
const reasonsLine =
context.truncated && context.omittedReasons?.length
? t("message.providerSwitch.trimmed", {
reasons: context.omittedReasons
.map((reason) => {
if (reason === "tail_window_limit") {
return t("message.providerSwitch.reasonTailWindow");
}
if (reason === "char_budget") {
return t("message.providerSwitch.reasonCharBudget");
}
return reason;
})
.join(", "),
})
: null;
return (
<View style={providerSwitchStylesheet.wrapper} testID="provider-switch-marker">
<View style={providerSwitchStylesheet.row}>
<View style={providerSwitchStylesheet.line} />
<Button
variant="ghost"
size="sm"
style={providerSwitchStylesheet.triggerButton}
onPress={handleToggle}
accessibilityLabel={title}
testID="provider-switch-marker-toggle"
>
<View style={providerSwitchStylesheet.triggerContent}>
<StyledSwitchIcon size={12} />
<Text
style={providerSwitchStylesheet.triggerText}
numberOfLines={1}
ellipsizeMode="tail"
>
{title}
</Text>
{expanded ? <StyledChevronDownIcon size={12} /> : <StyledChevronRightIcon size={12} />}
</View>
</Button>
<View style={providerSwitchStylesheet.line} />
</View>
{expanded ? (
<View style={providerSwitchStylesheet.detailsCard} testID="provider-switch-marker-details">
<Text style={providerSwitchStylesheet.detailRow}>
{`${formatProviderSwitchEndpoint(fromLabel, fromModelLabel)} → ${formatProviderSwitchEndpoint(toLabel, toModelLabel)}`}
</Text>
<Text style={providerSwitchStylesheet.detailRow}>{contextLine}</Text>
{reasonsLine ? (
<Text style={providerSwitchStylesheet.detailRow}>{reasonsLine}</Text>
) : null}
</View>
) : null}
</View>
);
});
interface TodoListCardProps {
items: TodoEntry[];
activity: TaskActivity;
@@ -10,7 +10,11 @@ import { useToast } from "@/contexts/toast-context";
import type { AgentScreenReadySyncState } from "@/hooks/use-agent-screen-state-machine";
import { selectAgentTimelineState, useSessionStore } from "@/stores/session-store";
import { useRewindAgentMutation } from "./use-rewind-agent-mutation";
import { isRewindableMessage, useRewindMenuItems } from "./use-rewind-capabilities";
import {
isPromptInActiveSegment,
isRewindableMessage,
useRewindMenuItems,
} from "./use-rewind-capabilities";
export function RewindCommandCenterRegistration({
serverId,
@@ -42,10 +46,16 @@ export function RewindCommandCenterRegistration({
if (timeline.status !== "synced" || timeline.newer === "available") {
return undefined;
}
return (
const candidate =
session.agentStreamHead.get(agentId)?.findLast((item) => item.kind === "user_message") ??
timeline.items.findLast((item) => item.kind === "user_message")
);
timeline.items.findLast((item) => item.kind === "user_message");
if (
!candidate ||
!isPromptInActiveSegment(candidate.timelineCursor, timeline.range?.activeSegmentStartSeq)
) {
return undefined;
}
return candidate;
});
const { rewindAgent, isPending } = useRewindAgentMutation({
serverId,
@@ -26,6 +26,20 @@ export function isRewindableMessage(messageId: string | undefined, text: string)
return Boolean(messageId) && text.trim().length > 0;
}
/**
* Whether a user prompt belongs to the active provider segment (after the latest provider switch).
* Prompts from earlier provider segments cannot be rewound.
*/
export function isPromptInActiveSegment(
timelineCursor: { anchorSeq?: number; seq?: number } | undefined,
activeSegmentStartSeq: number | undefined,
): boolean {
if (!activeSegmentStartSeq || activeSegmentStartSeq <= 0) return true;
const anchor = timelineCursor?.anchorSeq ?? timelineCursor?.seq;
if (anchor === undefined) return true;
return anchor > activeSegmentStartSeq;
}
export function resolveRewindMenuItems(
capabilities:
| Pick<
+44 -3
View File
@@ -1,7 +1,13 @@
import type { SelectedFile } from "@/attachments/selected-file";
import { FILE_UPLOAD_MAX_BYTES } from "@/attachments/upload-limit";
import type { ForgeSearchItem } from "@getpaseo/protocol/messages";
import type { ActiveTurnBehavior } from "@getpaseo/protocol/messages";
import type { AgentProvider, ProviderOptions } from "@getpaseo/protocol/agent-types";
import type {
ActiveTurnBehavior,
AgentSnapshotPayload,
ForgeSearchItem,
} from "@getpaseo/protocol/messages";
import { AgentProviderSwitchError } from "@getpaseo/client/internal/daemon-client";
import type { StagedProviderSwitch } from "@/composer/provider-switch";
import type {
AttachmentMetadata,
ComposerAttachment,
@@ -56,6 +62,20 @@ export interface ComposerSendClient {
attachments: ReturnType<typeof splitComposerAttachmentsForSubmit>["attachments"];
},
) => Promise<unknown>;
switchAgentProvider?: (
agentId: string,
options: {
provider: AgentProvider;
model?: string | null;
modeId?: string | null;
thinkingOptionId?: string | null;
providerOptions?: ProviderOptions;
text: string;
messageId: string;
images?: Array<{ data: string; mimeType: string }>;
attachments?: ReturnType<typeof splitComposerAttachmentsForSubmit>["attachments"];
},
) => Promise<{ agent?: AgentSnapshotPayload }>;
uploadFile: (input: { fileName: string; mimeType: string; bytes: Uint8Array }) => Promise<{
requestId: string;
file: {
@@ -197,6 +217,8 @@ export interface DispatchComposerAgentMessageInput {
submission: MessageSubmissionWriter;
activeTurnBehavior?: ActiveTurnBehavior;
activeTurnId?: string;
stagedProviderSwitch?: StagedProviderSwitch | null;
onProviderSwitchCommitted?: (agent: AgentSnapshotPayload | undefined) => void;
}
export async function dispatchComposerAgentMessage(
@@ -212,13 +234,29 @@ export async function dispatchComposerAgentMessage(
timestamp: new Date(),
images: wirePayload.images,
attachments: wirePayload.attachments,
...(input.activeTurnBehavior === "steer" && input.activeTurnId
...(input.activeTurnBehavior === "steer" && input.activeTurnId && !input.stagedProviderSwitch
? { turnId: input.activeTurnId }
: {}),
});
input.submission.begin(input.agentId, userMessage);
try {
const imagesData = await input.encodeImages(wirePayload.images);
if (input.stagedProviderSwitch && input.client.switchAgentProvider) {
const result = await input.client.switchAgentProvider(input.agentId, {
provider: input.stagedProviderSwitch.provider,
model: input.stagedProviderSwitch.model,
modeId: input.stagedProviderSwitch.modeId,
thinkingOptionId: input.stagedProviderSwitch.thinkingOptionId,
providerOptions: input.stagedProviderSwitch.providerOptions,
text: input.text,
messageId: clientMessageId,
images: imagesData ?? [],
attachments: wirePayload.attachments,
});
input.onProviderSwitchCommitted?.(result.agent);
input.submission.accept(input.agentId, clientMessageId);
return;
}
await input.client.sendAgentMessage(input.agentId, input.text, {
messageId: clientMessageId,
...(input.activeTurnBehavior ? { activeTurnBehavior: input.activeTurnBehavior } : {}),
@@ -228,6 +266,9 @@ export async function dispatchComposerAgentMessage(
input.submission.accept(input.agentId, clientMessageId);
} catch (error) {
input.submission.reject(input.agentId, clientMessageId);
if (error instanceof AgentProviderSwitchError && error.agent) {
input.onProviderSwitchCommitted?.(error.agent);
}
throw error;
}
}
@@ -16,12 +16,20 @@ import { formatThinkingOptionLabel } from "@/agent-controls/labels";
import { CombinedModelSelector } from "@/components/combined-model-selector";
import {
buildProviderSelectorProviders,
buildSelectableProviderSelectorProviders,
buildSelectorProvider,
type ProviderSelectorProvider,
} from "@/provider-selection/provider-selection";
import { filterSelectableModels } from "@/provider-selection/model-catalog";
import { useSessionStore } from "@/stores/session-store";
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
import { useDraftProviderOptions } from "@/hooks/use-draft-provider-options";
import {
clearStagedProviderSwitch,
type StagedProviderSwitch,
useStagedProviderSwitch,
useStagedProviderSwitchStore,
} from "@/composer/provider-switch";
import { resolveProviderDefinition } from "@/utils/provider-definitions";
import { mergeProviderPreferences, useFormPreferences } from "@/hooks/use-form-preferences";
import {
@@ -102,6 +110,7 @@ import {
type AgentProfilePicker,
type AgentProfileSeed,
type DraftAgentProfileControls,
type MaterializedAgentProfile,
} from "@/agent-profiles";
import { buildSettingsHostSectionRoute } from "@/utils/host-routes";
@@ -1006,6 +1015,148 @@ function useAgentOptionControls(
);
}
function resolveActiveStagedSwitch(
supportsProviderSwitching: boolean,
rawStagedSwitch: StagedProviderSwitch | null,
liveProvider: string | undefined,
): StagedProviderSwitch | null {
if (!supportsProviderSwitching || !rawStagedSwitch || !liveProvider) {
return null;
}
return rawStagedSwitch.provider !== liveProvider ? rawStagedSwitch : null;
}
function resolveDraftTargetModelId(
modelId: string,
preferredModel: string | undefined,
nextModels: AgentModelDefinition[] | null,
): string | null {
if (modelId) return modelId;
if (preferredModel) return preferredModel;
const defaultModel = nextModels?.find((m) => m.isDefault);
return defaultModel?.id ?? nextModels?.[0]?.id ?? null;
}
function resolveDraftThinkingOptionId(
targetModelId: string | null,
targetModel: AgentModelDefinition | undefined,
thinkingByModel: Record<string, string> | undefined,
): string | null {
const preferred = targetModelId ? thinkingByModel?.[targetModelId] : undefined;
if (preferred) return preferred;
return targetModel?.defaultThinkingOptionId ?? targetModel?.thinkingOptions?.[0]?.id ?? null;
}
function resolveDraftModeId(
preferredMode: string | undefined,
nextEntry: ReturnType<typeof resolveProviderSnapshotEntry>,
): string | null {
if (preferredMode) return preferredMode;
return nextEntry?.defaultModeId ?? nextEntry?.modes?.[0]?.id ?? null;
}
function buildStagedProviderSwitchDraft(input: {
nextProvider: string;
modelId: string;
snapshotEntries: ReturnType<typeof useProvidersSnapshot>["entries"];
providerPreferences: ReturnType<typeof useFormPreferences>["preferences"]["providerPreferences"];
}): StagedProviderSwitch {
const { nextProvider, modelId, snapshotEntries, providerPreferences } = input;
const nextEntry = resolveProviderSnapshotEntry(snapshotEntries, nextProvider);
const nextModels = filterSelectableModels(nextEntry?.models ?? null);
const preferred = providerPreferences?.[nextProvider];
const targetModelId = resolveDraftTargetModelId(modelId, preferred?.model, nextModels);
const targetModel = nextModels?.find((m) => m.id === targetModelId);
return {
provider: nextProvider,
model: targetModelId,
thinkingOptionId: resolveDraftThinkingOptionId(
targetModelId,
targetModel,
preferred?.thinkingByModel,
),
modeId: resolveDraftModeId(preferred?.mode, nextEntry),
providerOptions: preferred?.options ? { ...preferred.options } : {},
};
}
function resolveAgentModelSelectionWithStagedSwitch(input: {
models: AgentModelDefinition[] | null;
agent: AgentControlsSlice;
activeStagedSwitch: StagedProviderSwitch | null;
}) {
const { models, agent, activeStagedSwitch } = input;
return resolveAgentModelSelection({
models,
runtimeModelId: activeStagedSwitch ? null : agent?.runtimeModelId,
configuredModelId: activeStagedSwitch ? activeStagedSwitch.model : agent?.model,
runtimeThinkingOptionId: activeStagedSwitch ? null : agent?.runtimeThinkingOptionId,
explicitThinkingOptionId: activeStagedSwitch
? activeStagedSwitch.thinkingOptionId
: agent?.thinkingOptionId,
});
}
function buildStagedDraftOptionsParams(input: {
serverId: string;
agentCwd: string | null | undefined;
activeStagedSwitch: StagedProviderSwitch | null;
getProvider: () => AgentProvider | null;
modelId: string | null;
thinkingOptionId: string | null;
}) {
const { serverId, agentCwd, activeStagedSwitch, getProvider, modelId, thinkingOptionId } = input;
return {
serverId: activeStagedSwitch ? serverId : null,
provider: activeStagedSwitch ? activeStagedSwitch.provider : null,
getProvider,
cwd: agentCwd,
modeId: activeStagedSwitch?.modeId ?? null,
modelId,
thinkingOptionId,
initialOptions: activeStagedSwitch?.providerOptions,
};
}
function resolveAgentOptionControlsForComposer(input: {
activeStagedSwitch: StagedProviderSwitch | null;
stagedControls: ComposerOptionControls | null | undefined;
liveOptionControls: ComposerOptionControls;
onSetOption: (key: string, value: unknown) => void;
}): ComposerOptionControls {
const { activeStagedSwitch, stagedControls, liveOptionControls, onSetOption } = input;
if (!activeStagedSwitch) {
return liveOptionControls;
}
if (stagedControls) {
return { ...stagedControls, onSetOption };
}
return { controls: [], options: activeStagedSwitch.providerOptions, onSetOption };
}
function resolveControlledAgentControlsProps(input: {
effectiveProvider: string | undefined;
liveProvider: string;
selectedModelId: string | null;
selectedThinkingId: string | null;
thinkingOptions: AgentControlOption[];
supportsProviderSwitching: boolean;
handleSelectProviderAndModel: (provider: string, modelId: string) => void;
snapshotIsLoading: boolean;
selectedProviderIsLoading: boolean;
}) {
return {
provider: input.effectiveProvider ?? input.liveProvider,
selectedModelId: input.selectedModelId ?? undefined,
selectedThinkingOptionId: input.selectedThinkingId ?? undefined,
thinkingOptions: input.thinkingOptions.length > 0 ? input.thinkingOptions : undefined,
onSelectProviderAndModel: input.supportsProviderSwitching
? input.handleSelectProviderAndModel
: undefined,
isModelLoading: input.snapshotIsLoading || input.selectedProviderIsLoading,
};
}
export const AgentControls = memo(function AgentControls({
showToolbar,
agentId,
@@ -1013,15 +1164,22 @@ export const AgentControls = memo(function AgentControls({
onDropdownClose,
isCompactLayout,
}: AgentControlsProps) {
const { updatePreferences } = useFormPreferences();
const { preferences, updatePreferences } = useFormPreferences();
const agent = useSessionStore(
useShallow((state) => selectAgentControlsSlice(state, serverId, agentId)),
);
const client = useSessionStore((state) => state.sessions[serverId]?.client ?? null);
const supportsProviderSwitching = useSessionStore(
(state) => state.sessions[serverId]?.serverInfo?.features?.providerSwitching === true,
);
const rawStagedSwitch = useStagedProviderSwitch(serverId, agentId);
const activeStagedSwitch = resolveActiveStagedSwitch(
supportsProviderSwitching,
rawStagedSwitch,
agent?.provider,
);
const toast = useToast();
const modeControl = useLiveAgentModeControl(serverId, agentId);
const commandCenterModes = toCommandCenterModes(modeControl);
const modeProviderDefinitions = getModeProviderDefinitions(modeControl);
const liveModeControl = useLiveAgentModeControl(serverId, agentId);
const {
entries: snapshotEntries,
@@ -1031,24 +1189,34 @@ export const AgentControls = memo(function AgentControls({
refetchIfStale: refetchSnapshotIfStale,
} = useProvidersSnapshot(serverId, { cwd: agent?.cwd });
const effectiveProvider = activeStagedSwitch?.provider ?? agent?.provider;
const effectiveProviderRef = useRef<AgentProvider | null>(effectiveProvider ?? null);
effectiveProviderRef.current = effectiveProvider ?? null;
const snapshotSelectedEntry = useMemo(
() => resolveProviderSnapshotEntry(snapshotEntries, agent?.provider),
[snapshotEntries, agent?.provider],
() => resolveProviderSnapshotEntry(snapshotEntries, effectiveProvider),
[snapshotEntries, effectiveProvider],
);
const models = filterSelectableModels(snapshotSelectedEntry?.models ?? null);
const selectedProviderIsLoading = snapshotSelectedEntry?.status === "loading";
const agentProviderDefinitions = useMemo(
() => buildAgentProviderDefinitions(agent?.provider, snapshotEntries),
[agent?.provider, snapshotEntries],
() => buildAgentProviderDefinitions(effectiveProvider, snapshotEntries),
[effectiveProvider, snapshotEntries],
);
const agentProviderModels = useMemo(
() => buildAgentProviderModels(agent?.provider, models),
[agent?.provider, models],
() => buildAgentProviderModels(effectiveProvider, models),
[effectiveProvider, models],
);
const agentModelSelectorProviders = useMemo(() => {
if (supportsProviderSwitching && snapshotEntries && snapshotEntries.length > 0) {
const selectable = buildSelectableProviderSelectorProviders(snapshotEntries, {
selectedProvider: effectiveProvider ?? null,
});
if (selectable.length > 0) return selectable;
}
if (snapshotSelectedEntry) {
return [buildSelectorProvider(snapshotSelectedEntry)];
}
@@ -1056,14 +1224,19 @@ export const AgentControls = memo(function AgentControls({
providerDefinitions: agentProviderDefinitions,
modelsByProvider: agentProviderModels,
});
}, [agentProviderDefinitions, agentProviderModels, snapshotSelectedEntry]);
}, [
agentProviderDefinitions,
agentProviderModels,
effectiveProvider,
snapshotEntries,
snapshotSelectedEntry,
supportsProviderSwitching,
]);
const modelSelection = resolveAgentModelSelection({
const modelSelection = resolveAgentModelSelectionWithStagedSwitch({
models,
runtimeModelId: agent?.runtimeModelId,
configuredModelId: agent?.model,
runtimeThinkingOptionId: agent?.runtimeThinkingOptionId,
explicitThinkingOptionId: agent?.thinkingOptionId,
agent,
activeStagedSwitch,
});
const modelOptions = useMemo<AgentControlOption[]>(() => {
@@ -1080,8 +1253,87 @@ export const AgentControls = memo(function AgentControls({
const agentProvider = agent?.provider;
const activeModelId = modelSelection.activeModelId;
const stagedModeOptions = useMemo<AgentMode[]>(() => {
if (!activeStagedSwitch || !snapshotSelectedEntry?.modes) return [];
return snapshotSelectedEntry.modes.map((mode) => ({
id: mode.id,
label: mode.label,
description: mode.description ?? "",
}));
}, [activeStagedSwitch, snapshotSelectedEntry?.modes]);
const handleSelectStagedMode = useCallback(
(modeId: string) => {
useStagedProviderSwitchStore.getState().patch(serverId, agentId, (current) => ({
...current,
modeId,
}));
},
[agentId, serverId],
);
const modeControl = useMemo<AgentModeControlValue | null>(() => {
if (!activeStagedSwitch) return liveModeControl;
if (stagedModeOptions.length === 0) return null;
return {
provider: activeStagedSwitch.provider,
providerDefinitions: agentProviderDefinitions,
modeOptions: stagedModeOptions,
selectedModeId:
activeStagedSwitch.modeId ??
snapshotSelectedEntry?.defaultModeId ??
stagedModeOptions[0]?.id ??
null,
onSelectMode: handleSelectStagedMode,
disabled: !client,
};
}, [
activeStagedSwitch,
agentProviderDefinitions,
client,
handleSelectStagedMode,
liveModeControl,
snapshotSelectedEntry?.defaultModeId,
stagedModeOptions,
]);
const commandCenterModes = toCommandCenterModes(modeControl);
const modeProviderDefinitions = getModeProviderDefinitions(modeControl);
const getStagedProvider = useCallback(
() => (activeStagedSwitch ? effectiveProviderRef.current : null),
[activeStagedSwitch],
);
const stagedDraftOptions = useDraftProviderOptions(
buildStagedDraftOptionsParams({
serverId,
agentCwd: agent?.cwd,
activeStagedSwitch,
getProvider: getStagedProvider,
modelId: modelSelection.activeModelId,
thinkingOptionId: modelSelection.selectedThinkingId,
}),
);
const handleSelectModel = useCallback(
async (modelId: string) => {
if (activeStagedSwitch) {
const nextModel = models?.find((candidate) => candidate.id === modelId);
const preferredThinking =
preferences.providerPreferences?.[activeStagedSwitch.provider]?.thinkingByModel?.[
modelId
];
const nextThinking =
preferredThinking ??
nextModel?.defaultThinkingOptionId ??
nextModel?.thinkingOptions?.[0]?.id ??
null;
useStagedProviderSwitchStore.getState().patch(serverId, agentId, (current) => ({
...current,
model: modelId,
thinkingOptionId: nextThinking,
}));
return;
}
if (!client || !agentProvider) {
return;
}
@@ -1099,23 +1351,121 @@ export const AgentControls = memo(function AgentControls({
toast.error(toErrorMessage(error));
}
},
[agentId, agentProvider, client, toast, updatePreferences],
);
const handleSelectCommandCenterModel = useCallback(
(_provider: AgentProvider, modelId: string) => handleSelectModel(modelId),
[handleSelectModel],
[
activeStagedSwitch,
agentId,
agentProvider,
client,
models,
preferences.providerPreferences,
serverId,
toast,
updatePreferences,
],
);
// A running agent is one provider's process, so only that provider's profiles
// can apply to it.
const profileProviders = useMemo(() => (agentProvider ? [agentProvider] : []), [agentProvider]);
const handleSelectProviderAndModel = useCallback(
(nextProvider: string, modelId: string) => {
if (!agentProvider) return;
if (nextProvider === agentProvider) {
clearStagedProviderSwitch(serverId, agentId);
const liveModelId = agent?.runtimeModelId ?? agent?.model ?? null;
if (modelId && modelId !== liveModelId) {
void handleSelectModel(modelId);
}
return;
}
if (!supportsProviderSwitching) return;
useStagedProviderSwitchStore.getState().stage(
serverId,
agentId,
buildStagedProviderSwitchDraft({
nextProvider,
modelId,
snapshotEntries,
providerPreferences: preferences.providerPreferences,
}),
);
},
[
agent?.model,
agent?.runtimeModelId,
agentId,
agentProvider,
handleSelectModel,
preferences.providerPreferences,
serverId,
snapshotEntries,
supportsProviderSwitching,
],
);
const handleSelectCommandCenterModel = useCallback(
(provider: AgentProvider, modelId: string) => {
if (supportsProviderSwitching) {
handleSelectProviderAndModel(provider, modelId);
return;
}
void handleSelectModel(modelId);
},
[handleSelectModel, handleSelectProviderAndModel, supportsProviderSwitching],
);
const handleStageAgentProfileSwitch = useCallback(
(resolved: MaterializedAgentProfile) => {
if (!supportsProviderSwitching) return;
const nextEntry = resolveProviderSnapshotEntry(snapshotEntries, resolved.provider);
const modeIds = resolveSnapshotModeIds(nextEntry);
const validModeId =
resolved.modeId && (!modeIds || modeIds.includes(resolved.modeId))
? resolved.modeId
: (nextEntry?.defaultModeId ?? nextEntry?.modes?.[0]?.id ?? null);
useStagedProviderSwitchStore.getState().stage(serverId, agentId, {
provider: resolved.provider,
model: resolved.modelId ?? null,
modeId: validModeId,
thinkingOptionId: resolved.thinkingOptionId ?? null,
providerOptions: resolved.options ? { ...resolved.options } : {},
});
stagedDraftOptions.applyProfile({
provider: resolved.provider,
options: resolved.options ?? {},
});
},
[agentId, serverId, snapshotEntries, stagedDraftOptions, supportsProviderSwitching],
);
const handleClearStagedSwitchOnProfile = useCallback(() => {
clearStagedProviderSwitch(serverId, agentId);
}, [agentId, serverId]);
const profileProviders = useMemo(() => {
if (supportsProviderSwitching) {
return agentModelSelectorProviders.map((entry) => entry.id);
}
return agentProvider ? [agentProvider] : [];
}, [agentModelSelectorProviders, agentProvider, supportsProviderSwitching]);
const profileModeIds = useMemo(
() => resolveSnapshotModeIds(snapshotSelectedEntry),
[snapshotSelectedEntry],
);
const profileTarget = useMemo<AgentProfileApplyTarget>(
() => ({ kind: "agent", agentId, availableModeIds: profileModeIds }),
[agentId, profileModeIds],
() => ({
kind: "agent",
agentId,
availableModeIds: profileModeIds,
currentProvider: agentProvider,
onApplySameProvider: handleClearStagedSwitchOnProfile,
onStageProviderSwitch: supportsProviderSwitching ? handleStageAgentProfileSwitch : undefined,
}),
[
agentId,
agentProvider,
handleClearStagedSwitchOnProfile,
handleStageAgentProfileSwitch,
profileModeIds,
supportsProviderSwitching,
],
);
const agentProfiles = useAgentProfilePicker({
serverId,
@@ -1128,6 +1478,13 @@ export const AgentControls = memo(function AgentControls({
const handleSelectThinkingOption = useCallback(
(thinkingOptionId: string) => {
if (activeStagedSwitch) {
useStagedProviderSwitchStore.getState().patch(serverId, agentId, (current) => ({
...current,
thinkingOptionId,
}));
return;
}
if (!client || !agentProvider) {
return;
}
@@ -1155,11 +1512,28 @@ export const AgentControls = memo(function AgentControls({
toast.error(toErrorMessage(error));
});
},
[activeModelId, agentId, agentProvider, client, toast, updatePreferences],
[
activeModelId,
activeStagedSwitch,
agentId,
agentProvider,
client,
serverId,
toast,
updatePreferences,
],
);
const handleSetOption = useCallback(
(key: string, value: unknown) => {
if (activeStagedSwitch) {
stagedDraftOptions.setOption(key, value);
useStagedProviderSwitchStore.getState().patch(serverId, agentId, (current) => ({
...current,
providerOptions: { ...current.providerOptions, [key]: value },
}));
return;
}
if (!client || !agentProvider) {
return;
}
@@ -1181,10 +1555,29 @@ export const AgentControls = memo(function AgentControls({
toast.error(toErrorMessage(error));
});
},
[agentId, agentProvider, client, toast, updatePreferences],
[
activeStagedSwitch,
agentId,
agentProvider,
client,
serverId,
stagedDraftOptions,
toast,
updatePreferences,
],
);
const agentOptionControls = useAgentOptionControls(agent, handleSetOption);
const liveOptionControls = useAgentOptionControls(agent, handleSetOption);
const agentOptionControls = useMemo<ComposerOptionControls>(
() =>
resolveAgentOptionControlsForComposer({
activeStagedSwitch,
stagedControls: stagedDraftOptions.optionControls,
liveOptionControls,
onSetOption: handleSetOption,
}),
[activeStagedSwitch, handleSetOption, liveOptionControls, stagedDraftOptions.optionControls],
);
// The agent's composer exists apart from this component; while this is mounted, prompt
// commands go through the input the user is typing in.
@@ -1208,12 +1601,12 @@ export const AgentControls = memo(function AgentControls({
() => ({
serverId,
ownerKey: agentId,
provider: agentProvider,
provider: effectiveProvider,
providerDefinitions: modeProviderDefinitions,
profiles: agentProfiles,
models: {
providers: agentModelSelectorProviders,
selectedProvider: agentProvider,
selectedProvider: effectiveProvider,
selectedModelId: activeModelId,
select: handleSelectCommandCenterModel,
},
@@ -1232,7 +1625,7 @@ export const AgentControls = memo(function AgentControls({
client,
agentId,
agentModelSelectorProviders,
agentProvider,
effectiveProvider,
commandCenterModes,
handleSelectCommandCenterModel,
handleSelectThinkingOption,
@@ -1252,8 +1645,8 @@ export const AgentControls = memo(function AgentControls({
);
const handleModelSelectorOpen = useCallback(() => {
refetchSnapshotIfStale(agentProvider);
}, [agentProvider, refetchSnapshotIfStale]);
refetchSnapshotIfStale(supportsProviderSwitching ? undefined : effectiveProvider);
}, [effectiveProvider, refetchSnapshotIfStale, supportsProviderSwitching]);
const handleRetryModelProvider = useCallback(
(provider: AgentProvider) => {
@@ -1266,6 +1659,18 @@ export const AgentControls = memo(function AgentControls({
return null;
}
const resolvedControlProps = resolveControlledAgentControlsProps({
effectiveProvider,
liveProvider: agent.provider,
selectedModelId: modelSelection.activeModelId,
selectedThinkingId: modelSelection.selectedThinkingId,
thinkingOptions,
supportsProviderSwitching,
handleSelectProviderAndModel,
snapshotIsLoading,
selectedProviderIsLoading,
});
return (
<ComposerModelProvider value={composer}>
{commandCenterRegistration}
@@ -1273,21 +1678,17 @@ export const AgentControls = memo(function AgentControls({
<>
{profileEditor.element}
<ControlledAgentControls
provider={agent.provider}
{...resolvedControlProps}
modelSelectorProviders={agentModelSelectorProviders}
modelOptions={modelOptions}
selectedModelId={modelSelection.activeModelId ?? undefined}
onSelectModel={handleSelectModel}
agentProfiles={agentProfiles}
onApplyAgentProfile={agentProfiles?.applyProfile}
onEditAgentProfiles={handleEditAgentProfiles}
onCreateAgentProfile={profileActions.create}
onEditAgentProfile={profileActions.edit}
thinkingOptions={thinkingOptions.length > 0 ? thinkingOptions : undefined}
selectedThinkingOptionId={modelSelection.selectedThinkingId ?? undefined}
onSelectThinkingOption={handleSelectThinkingOption}
optionControls={agentOptionControls}
isModelLoading={snapshotIsLoading || selectedProviderIsLoading}
onModelSelectorOpen={handleModelSelectorOpen}
onRetryModelProvider={handleRetryModelProvider}
isRetryingModelProvider={snapshotIsRefreshing}
+129 -7
View File
@@ -9,6 +9,15 @@ import { useStore } from "zustand";
import { getHostRuntimeStore } from "@/runtime/host-runtime";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { Alert } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import {
clearStagedProviderSwitch,
getStagedProviderSwitch,
useStagedProviderSwitch,
} from "@/composer/provider-switch";
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
import { normalizeAgentSnapshot } from "@/utils/agent-snapshots";
import { resolveProviderLabel } from "@/utils/provider-definitions";
import {
View,
Pressable,
@@ -48,6 +57,7 @@ import { usePanelStore, type MobilePanelView } from "@/stores/panel-store";
import { usePointerCapabilities } from "@/hooks/pointer-capabilities";
import { useShallow } from "zustand/shallow";
import {
ArrowRightLeft,
ArrowUp,
Square,
Pencil,
@@ -298,16 +308,29 @@ function buildRealtimeVoiceButtonStyle(pressed: boolean, voiceButtonDisabled: bo
const EMPTY_METRICS: AgentMetric[] = [];
const EMPTY_AGENT_STATE = {
provider: null,
status: null,
contextWindowMaxTokens: null,
contextWindowUsedTokens: null,
totalCostUsd: null,
sessionMetrics: EMPTY_METRICS,
model: null,
};
function buildAgentStateSelector(serverId: string, agentId: string) {
return (state: ReturnType<typeof useSessionStore.getState>) => {
const agent = state.sessions[serverId]?.agents?.get(agentId) ?? null;
if (!agent) return EMPTY_AGENT_STATE;
const usage = agent.lastUsage;
return {
status: agent?.status ?? null,
contextWindowMaxTokens: agent?.lastUsage?.contextWindowMaxTokens ?? null,
contextWindowUsedTokens: agent?.lastUsage?.contextWindowUsedTokens ?? null,
totalCostUsd: agent?.lastUsage?.totalCostUsd ?? null,
sessionMetrics: agent?.sessionMetrics ?? EMPTY_METRICS,
model: agent?.model ?? null,
provider: agent.provider ?? null,
status: agent.status ?? null,
contextWindowMaxTokens: usage?.contextWindowMaxTokens ?? null,
contextWindowUsedTokens: usage?.contextWindowUsedTokens ?? null,
totalCostUsd: usage?.totalCostUsd ?? null,
sessionMetrics: agent.sessionMetrics ?? EMPTY_METRICS,
model: agent.model ?? null,
};
};
}
@@ -1351,6 +1374,36 @@ function ComposerContentImpl({
const { settings: appSettings } = useAppSettings();
const agentState = useSessionStore(useShallow(buildAgentStateSelector(serverId, agentId)));
const supportsProviderSwitching = useSessionStore(
(state) => state.sessions[serverId]?.serverInfo?.features?.providerSwitching === true,
);
const rawStagedSwitch = useStagedProviderSwitch(serverId, agentId);
const stagedSwitch =
supportsProviderSwitching &&
rawStagedSwitch &&
agentState.provider &&
rawStagedSwitch.provider !== agentState.provider
? rawStagedSwitch
: null;
const { entries: providerSnapshotEntries } = useProvidersSnapshot(serverId, { cwd });
const stagedProviderLabel = stagedSwitch
? resolveProviderLabel(stagedSwitch.provider, providerSnapshotEntries)
: null;
useEffect(() => {
if (
rawStagedSwitch &&
agentState.provider &&
rawStagedSwitch.provider === agentState.provider
) {
clearStagedProviderSwitch(serverId, agentId);
}
}, [agentId, agentState.provider, rawStagedSwitch, serverId]);
const handleCancelStagedSwitch = useCallback(() => {
clearStagedProviderSwitch(serverId, agentId);
setSendError(null);
}, [agentId, serverId]);
const queuedMessagesRaw = useSessionStore((state) =>
state.sessions[serverId]?.queuedMessages?.get(agentId),
@@ -1709,6 +1762,12 @@ function ComposerContentImpl({
if (!client) {
throw new Error(t("workspace.terminal.hostDisconnected"));
}
const sessionState = useSessionStore.getState().sessions[serverId];
const liveProvider = sessionState?.agents.get(targetAgentId)?.provider;
const canSwitch = sessionState?.serverInfo?.features?.providerSwitching === true;
const pendingSwitch = canSwitch ? getStagedProviderSwitch(serverId, targetAgentId) : null;
const stagedProviderSwitch =
pendingSwitch && pendingSwitch.provider !== liveProvider ? pendingSwitch : null;
await dispatchComposerAgentMessage({
client,
agentId: targetAgentId,
@@ -1719,6 +1778,16 @@ function ComposerContentImpl({
}),
encodeImages,
submission: createMessageSubmissionWriter(serverId),
stagedProviderSwitch,
onProviderSwitchCommitted: (agent) => {
clearStagedProviderSwitch(serverId, targetAgentId);
if (agent) {
getHostRuntimeStore().tryAcceptAgentSnapshot(
serverId,
normalizeAgentSnapshot(agent, serverId),
);
}
},
activeTurnBehavior,
activeTurnId:
activeTurnBehavior === "steer"
@@ -1803,7 +1872,7 @@ function ComposerContentImpl({
attachments: outgoingAttachments,
hasExternalContent,
allowEmptySubmit,
forceSend,
forceSend: stagedSwitch && isAgentRunning ? false : forceSend,
submitBehavior,
isAgentRunning,
// Parent-managed submits are still valid submit paths even when the
@@ -1845,6 +1914,7 @@ function ComposerContentImpl({
queueMessage,
setSelectedAttachments,
replaceUserInput,
stagedSwitch,
submitBehavior,
submitMessage,
t,
@@ -2566,6 +2636,31 @@ function ComposerContentImpl({
? t("composer.github.searching")
: t("composer.github.noResults");
const stagedSwitchBannerNode = useMemo(() => {
if (!stagedSwitch || !stagedProviderLabel) return null;
const message = isAgentRunning
? t("composer.providerSwitch.switchingAfterTurn", { provider: stagedProviderLabel })
: t("composer.providerSwitch.switchingNextMessage", { provider: stagedProviderLabel });
return (
<View style={styles.stagedSwitchBanner} testID="staged-provider-switch-banner">
<View style={styles.stagedSwitchLabelRow}>
<ThemedArrowRightLeft size={ICON_SIZE.sm} uniProps={iconForegroundMutedMapping} />
<Text style={styles.stagedSwitchText} numberOfLines={1}>
{message}
</Text>
</View>
<Button
variant="ghost"
size="sm"
onPress={handleCancelStagedSwitch}
testID="cancel-staged-provider-switch"
>
{t("common.actions.cancel")}
</Button>
</View>
);
}, [handleCancelStagedSwitch, isAgentRunning, stagedProviderLabel, stagedSwitch, t]);
return (
<>
<ComposerKeyboardRegistration
@@ -2591,6 +2686,7 @@ function ComposerContentImpl({
>
<View style={inputAreaContentStyle}>
{isFullscreen ? null : queueList}
{isFullscreen ? null : stagedSwitchBannerNode}
{!isFullscreen && sendErrorNode}
<ComposerAutocompleteBinding
@@ -2846,9 +2942,35 @@ const styles = StyleSheet.create((theme: Theme) => ({
queueSendButton: {
backgroundColor: theme.colors.accent,
},
stagedSwitchBanner: {
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
paddingLeft: theme.spacing[3],
paddingRight: theme.spacing[1.5],
paddingVertical: theme.spacing[1],
backgroundColor: theme.colors.surface1,
borderRadius: theme.borderRadius.md,
borderWidth: theme.borderWidth[1],
borderColor: theme.colors.border,
gap: theme.spacing[2],
},
stagedSwitchLabelRow: {
flex: 1,
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[1.5],
minWidth: 0,
},
stagedSwitchText: {
flex: 1,
fontSize: theme.fontSize.sm,
color: theme.colors.foregroundMuted,
},
})) as unknown as Record<string, object>;
const ThemedAttachmentSpinner = withUnistyles(LoadingSpinner);
const ThemedArrowRightLeft = withUnistyles(ArrowRightLeft);
const ThemedPencil = withUnistyles(Pencil);
const ThemedArrowUp = withUnistyles(ArrowUp);
const ThemedGitPullRequest = withUnistyles(GitPullRequest);
@@ -0,0 +1,7 @@
export {
clearStagedProviderSwitch,
getStagedProviderSwitch,
useStagedProviderSwitch,
useStagedProviderSwitchStore,
type StagedProviderSwitch,
} from "./store";
@@ -0,0 +1,462 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { AgentProviderSwitchError } from "@getpaseo/client/internal/daemon-client";
import type { AgentSnapshotPayload } from "@getpaseo/protocol/messages";
import { dispatchComposerAgentMessage } from "@/composer/actions";
import { isPromptInActiveSegment } from "@/components/rewind/use-rewind-capabilities";
import { collapseTurns } from "@/agent-stream/turn-collapse/model";
import {
processAgentStreamEvent,
processTimelineResponse,
} from "@/timeline/session-stream-reducers";
import { ReplicaCache } from "@/runtime/replica-cache";
import type { ReplicaRow, ReplicaRowStore } from "@/runtime/replica-cache/row-store";
import { HostRuntimeStore } from "@/runtime/host-runtime";
import { useSessionStore } from "@/stores/session-store";
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import type { ProviderSwitchItem, StreamItem, UserMessageItem } from "@/types/stream";
import { getStagedProviderSwitch, useStagedProviderSwitchStore } from "./index";
function createInMemoryRowStore(): ReplicaRowStore {
const rows = new Map<string, ReplicaRow>();
const keyOf = (r: { serverId: string; kind: string; id: string }) =>
`${r.serverId}:${r.kind}:${r.id}`;
return {
async open() {},
async read(serverId, kinds, ids) {
const kindSet = new Set(kinds);
const idSet = ids ? new Set(ids) : null;
return [...rows.values()].filter(
(r) => r.serverId === serverId && kindSet.has(r.kind) && (!idSet || idSet.has(r.id)),
);
},
async readAll() {
const byServer = new Map<string, ReplicaRow[]>();
for (const row of rows.values()) {
const list = byServer.get(row.serverId) ?? [];
list.push(row);
byServer.set(row.serverId, list);
}
return [...byServer.entries()].map(([serverId, list]) => ({ serverId, rows: list }));
},
async apply(changes) {
for (const del of changes.deletes) rows.delete(keyOf(del));
for (const up of changes.upserts) rows.set(keyOf(up), up);
},
async deleteHost(serverId) {
for (const [k, v] of rows) if (v.serverId === serverId) rows.delete(k);
},
async renameHost() {},
async clear() {
rows.clear();
},
};
}
const TS = "2026-11-25T10:00:00.000Z";
function agentSnapshot(provider: string): AgentSnapshotPayload {
return {
id: "agent-1",
provider,
cwd: "/repo",
model: null,
thinkingOptionId: null,
createdAt: TS,
updatedAt: TS,
lastUserMessageAt: null,
status: "idle",
capabilities: {
supportsStreaming: true,
supportsSessionPersistence: true,
supportsDynamicModes: false,
supportsMcpServers: false,
supportsReasoningStream: false,
supportsToolInvocations: true,
supportsRewindConversation: true,
supportsRewindFiles: false,
supportsRewindBoth: false,
},
currentModeId: null,
availableModes: [],
pendingPermissions: [],
persistence: null,
title: null,
labels: {},
};
}
describe("app provider switching integration", () => {
beforeEach(() => {
useStagedProviderSwitchStore.setState({ stagedByKey: new Map() });
});
it("dispatches switchAgentProvider when staged and handles pre-commit vs post-commit failures", async () => {
const committed: Array<AgentSnapshotPayload | undefined> = [];
const sendAgentMessage = vi.fn().mockResolvedValue(undefined);
const switchAgentProvider = vi.fn().mockResolvedValue({ agent: agentSnapshot("codex") });
const submission = {
begin: vi.fn(),
accept: vi.fn(),
reject: vi.fn(),
};
const staged = {
provider: "codex",
model: "gpt-5.4",
thinkingOptionId: "high",
modeId: "auto",
providerOptions: {},
};
// Success path
await dispatchComposerAgentMessage({
client: {
sendAgentMessage,
switchAgentProvider,
uploadFile: vi.fn(),
},
agentId: "agent-1",
text: "Continue with Codex",
attachments: [],
encodeImages: async () => [],
submission,
stagedProviderSwitch: staged,
onProviderSwitchCommitted: (agent) => committed.push(agent),
});
expect(sendAgentMessage).not.toHaveBeenCalled();
expect(switchAgentProvider).toHaveBeenCalledTimes(1);
expect(committed).toEqual([expect.objectContaining({ provider: "codex" })]);
expect(submission.accept).toHaveBeenCalledTimes(1);
// Pre-commit failure: onProviderSwitchCommitted MUST NOT run
committed.length = 0;
switchAgentProvider.mockRejectedValueOnce(new Error("Codex CLI unavailable"));
await expect(
dispatchComposerAgentMessage({
client: { sendAgentMessage, switchAgentProvider, uploadFile: vi.fn() },
agentId: "agent-1",
text: "Retry",
attachments: [],
encodeImages: async () => [],
submission,
stagedProviderSwitch: staged,
onProviderSwitchCommitted: (agent) => committed.push(agent),
}),
).rejects.toThrow("Codex CLI unavailable");
expect(committed).toEqual([]);
// Post-commit start failure (AgentProviderSwitchError with .agent): MUST commit live agent snapshot
switchAgentProvider.mockRejectedValueOnce(
new AgentProviderSwitchError("Rate limited", agentSnapshot("codex")),
);
await expect(
dispatchComposerAgentMessage({
client: { sendAgentMessage, switchAgentProvider, uploadFile: vi.fn() },
agentId: "agent-1",
text: "Retry 2",
attachments: [],
encodeImages: async () => [],
submission,
stagedProviderSwitch: staged,
onProviderSwitchCommitted: (agent) => committed.push(agent),
}),
).rejects.toThrow("Rate limited");
expect(committed).toEqual([expect.objectContaining({ provider: "codex" })]);
});
it("advances activeSegmentStartSeq immediately on live provider_switch events and scopes rewind eligibility", () => {
const preSwitchPrompt: UserMessageItem = {
kind: "user_message",
id: "u1",
messageId: "u1",
text: "Claude prompt",
timestamp: new Date(TS),
timelineCursor: { epoch: "ep-1", seq: 1, anchorSeq: 1 },
};
const liveResult = processAgentStreamEvent({
event: {
type: "timeline",
provider: "codex",
item: {
type: "provider_switch",
fromProvider: "claude",
toProvider: "codex",
fromModel: "sonnet",
toModel: "gpt-5.4",
fromSessionId: "s1",
toSessionId: null,
context: { includedItems: 2, truncated: false, charCount: 100, budgetChars: 100_000 },
},
},
seq: 3,
epoch: "ep-1",
currentTail: [preSwitchPrompt],
currentHead: [],
currentCursor: { epoch: "ep-1", startSeq: 1, endSeq: 2 },
hasAuthoritativeBaseline: true,
timestamp: new Date(TS),
});
expect(liveResult.cursor?.activeSegmentStartSeq).toBe(3);
expect(liveResult.tail.some((item) => item.kind === "provider_switch")).toBe(true);
// Pre-switch prompt (anchor 1 <= 3) is NOT rewindable; post-switch prompt (anchor 4 > 3) IS!
expect(
isPromptInActiveSegment(
preSwitchPrompt.timelineCursor,
liveResult.cursor?.activeSegmentStartSeq,
),
).toBe(false);
expect(
isPromptInActiveSegment({ seq: 4, anchorSeq: 4 }, liveResult.cursor?.activeSegmentStartSeq),
).toBe(true);
// Timeline page response also propagates activeSegmentStartSeq
const pageResult = processTimelineResponse({
payload: {
agentId: "agent-1",
direction: "tail",
projection: "projected",
reset: true,
epoch: "ep-1",
window: { minSeq: 1, maxSeq: 4, nextSeq: 5 },
startCursor: { seq: 1 },
endCursor: { seq: 4 },
hasNewer: false,
hasOlder: false,
activeSegmentStartSeq: 3,
entries: [
{
seqStart: 1,
seqEnd: 1,
provider: "claude",
timestamp: TS,
item: { type: "user_message", text: "Claude prompt", messageId: "u1" },
},
{
seqStart: 3,
seqEnd: 3,
provider: "codex",
timestamp: TS,
item: {
type: "provider_switch",
fromProvider: "claude",
toProvider: "codex",
context: { includedItems: 1, truncated: false, charCount: 50, budgetChars: 100_000 },
},
},
],
error: null,
},
currentTail: [],
currentHead: [],
currentCursor: undefined,
isInitializing: true,
hasActiveInitDeferred: false,
initRequestDirection: "tail",
sendingClientMessageIds: [],
});
expect(pageResult.cursor?.activeSegmentStartSeq).toBe(3);
});
it("persists provider_switch items and activeSegmentStartSeq in ReplicaCache and keeps markers visible when turns collapse", async () => {
const rowStore = createInMemoryRowStore();
const cache = new ReplicaCache(rowStore);
cache.setHosts(["srv-1"]);
const switchItem: ProviderSwitchItem = {
kind: "provider_switch",
id: "provider_switch:ep-1:3",
timestamp: new Date(TS),
timelineCursor: { epoch: "ep-1", seq: 3, anchorSeq: 3 },
fromProvider: "claude",
toProvider: "codex",
fromModel: "sonnet",
toModel: "gpt-5.4",
fromSessionId: "s1",
toSessionId: null,
context: {
includedItems: 2,
truncated: true,
charCount: 150,
budgetChars: 100_000,
omittedReasons: ["tail_window_limit"],
},
};
const items: StreamItem[] = [
{
kind: "user_message",
id: "u1",
messageId: "u1",
text: "Hello",
timestamp: new Date(TS),
timelineCursor: { epoch: "ep-1", seq: 1, anchorSeq: 1 },
},
switchItem,
];
cache.commitTimeline("srv-1", "agent-1", {
agentId: "agent-1",
items,
range: { epoch: "ep-1", startSeq: 1, endSeq: 3, activeSegmentStartSeq: 3 },
hasOlder: false,
});
await cache.flush();
const restored = await cache.readTimeline("srv-1", "agent-1");
expect(restored?.range?.activeSegmentStartSeq).toBe(3);
expect(restored?.items.find((i) => i.kind === "provider_switch")).toMatchObject({
kind: "provider_switch",
fromProvider: "claude",
toProvider: "codex",
context: { truncated: true, omittedReasons: ["tail_window_limit"] },
});
// Turn collapse keeps provider_switch visible
const collapsed = collapseTurns({
tail: [
items[0]!,
{
kind: "tool_call",
id: "tc1",
timestamp: new Date(TS),
payload: {
source: "agent",
data: {
provider: "claude",
callId: "c1",
name: "read",
status: "completed",
error: null,
detail: { type: "read", filePath: "a.ts" },
},
},
},
switchItem,
{
kind: "assistant_message",
id: "a1",
text: "Done",
timestamp: new Date(TS),
},
],
isLatestTurnOpen: false,
expandedHostIds: new Set(),
getGroupedCalls: () => undefined,
previousSummaryRowsByHostId: new Map(),
});
expect(collapsed.tail.some((item) => item.kind === "provider_switch")).toBe(true);
});
it("blocks M2 drain while M1's staged provider switch is in-flight, then sends M2 normally to P2", async () => {
const serverId = "srv_multi_queue_switch";
let resolveSwitch!: (value: { agent: AgentSnapshotPayload }) => void;
const switchPromise = new Promise<{ agent: AgentSnapshotPayload }>((resolve) => {
resolveSwitch = resolve;
});
const switchedCalls: string[] = [];
const sentCalls: string[] = [];
const fakeClient = {
switchAgentProvider: vi.fn(async (_agentId: string, opts: { text: string }) => {
switchedCalls.push(opts.text);
return await switchPromise;
}),
sendAgentMessage: vi.fn(async (_agentId: string, text: string) => {
sentCalls.push(text);
}),
uploadFile: vi.fn(),
} as unknown as DaemonClient;
const runtime = new HostRuntimeStore({
deps: {
createClient: () => fakeClient,
connectToDaemon: async () => ({ client: fakeClient, serverId, hostname: null }),
getClientId: async () => "cid_multi_queue_switch",
},
});
const sessionStore = useSessionStore.getState();
sessionStore.initializeSession(serverId, fakeClient, 1);
useSessionStore.setState((state) => ({
sessions: {
...state.sessions,
[serverId]: {
...state.sessions[serverId]!,
serverInfo: {
serverId,
hostname: "localhost",
version: "0.18.0",
features: { providerSwitching: true },
},
},
},
}));
sessionStore.setAgents(
serverId,
new Map([
[
"agent-1",
{
...agentSnapshot("claude"),
serverId,
parentAgentId: null,
createdAt: new Date(TS),
updatedAt: new Date(TS),
lastUserMessageAt: null,
lastActivityAt: new Date(TS),
attentionTimestamp: null,
archivedAt: null,
turn: { phase: "idle", cancellationRequestId: null },
},
],
]),
);
sessionStore.setQueuedMessages(
serverId,
new Map([
[
"agent-1",
[
{ id: "m1", text: "First queued switch prompt", attachments: [] },
{ id: "m2", text: "Second queued follow-up", attachments: [] },
],
],
]),
);
useStagedProviderSwitchStore.getState().stage(serverId, "agent-1", {
provider: "codex",
model: "gpt-5.4",
thinkingOptionId: null,
modeId: null,
providerOptions: {},
});
// M1 begins switching
runtime.drainQueuedAgentMessage(serverId, "agent-1");
await vi.waitFor(() => {
expect(switchedCalls).toEqual(["First queued switch prompt"]);
});
// Concurrent drain trigger while M1's switch is still in-flight MUST NOT drain M2!
runtime.drainQueuedAgentMessage(serverId, "agent-1");
expect(sentCalls).toEqual([]);
expect(switchedCalls).toHaveLength(1);
expect(useSessionStore.getState().sessions[serverId]?.queuedMessages.get("agent-1")).toEqual([
{ id: "m2", text: "Second queued follow-up", attachments: [] },
]);
// M1 switch completes -> staged switch clears -> M2 drains as a plain sendAgentMessage to Codex!
resolveSwitch({ agent: agentSnapshot("codex") });
await vi.waitFor(() => {
expect(getStagedProviderSwitch(serverId, "agent-1")).toBeNull();
});
runtime.drainQueuedAgentMessage(serverId, "agent-1");
await vi.waitFor(() => {
expect(sentCalls).toEqual(["Second queued follow-up"]);
});
expect(switchedCalls).toHaveLength(1);
sessionStore.clearSession(serverId);
});
});
@@ -0,0 +1,51 @@
import { beforeEach, describe, expect, it } from "vitest";
import {
clearStagedProviderSwitch,
getStagedProviderSwitch,
useStagedProviderSwitchStore,
} from "./index";
describe("staged provider switch store", () => {
beforeEach(() => {
useStagedProviderSwitchStore.setState({ stagedByKey: new Map() });
});
it("stages, patches, and clears per server and agent", () => {
const store = useStagedProviderSwitchStore.getState();
store.stage("srv-1", "agent-1", {
provider: "codex",
model: "gpt-5.4",
thinkingOptionId: "high",
modeId: "auto",
providerOptions: { fast_mode: true },
});
store.stage("srv-1", "agent-2", {
provider: "opencode",
model: null,
thinkingOptionId: null,
modeId: null,
providerOptions: {},
});
expect(getStagedProviderSwitch("srv-1", "agent-1")).toEqual({
provider: "codex",
model: "gpt-5.4",
thinkingOptionId: "high",
modeId: "auto",
providerOptions: { fast_mode: true },
});
store.patch("srv-1", "agent-1", (current) => ({
...current,
thinkingOptionId: "medium",
}));
expect(getStagedProviderSwitch("srv-1", "agent-1")?.thinkingOptionId).toBe("medium");
clearStagedProviderSwitch("srv-1", "agent-1");
expect(getStagedProviderSwitch("srv-1", "agent-1")).toBeNull();
expect(getStagedProviderSwitch("srv-1", "agent-2")?.provider).toBe("opencode");
store.clearForServer("srv-1");
expect(getStagedProviderSwitch("srv-1", "agent-2")).toBeNull();
});
});
@@ -0,0 +1,94 @@
import { create } from "zustand";
import type { AgentProvider, ProviderOptions } from "@getpaseo/protocol/agent-types";
export interface StagedProviderSwitch {
provider: AgentProvider;
model: string | null;
thinkingOptionId: string | null;
modeId: string | null;
providerOptions: ProviderOptions;
}
function stagedKey(serverId: string, agentId: string): string {
return `${serverId}:${agentId}`;
}
interface StagedProviderSwitchState {
stagedByKey: Map<string, StagedProviderSwitch>;
stage: (serverId: string, agentId: string, draft: StagedProviderSwitch) => void;
patch: (
serverId: string,
agentId: string,
updater: (current: StagedProviderSwitch) => StagedProviderSwitch,
) => void;
clear: (serverId: string, agentId: string) => void;
clearForServer: (serverId: string) => void;
}
export const useStagedProviderSwitchStore = create<StagedProviderSwitchState>((set) => ({
stagedByKey: new Map(),
stage: (serverId, agentId, draft) =>
set((state) => {
const next = new Map(state.stagedByKey);
next.set(stagedKey(serverId, agentId), draft);
return { stagedByKey: next };
}),
patch: (serverId, agentId, updater) =>
set((state) => {
const key = stagedKey(serverId, agentId);
const current = state.stagedByKey.get(key);
if (!current) return state;
const updated = updater(current);
if (updated === current) return state;
const next = new Map(state.stagedByKey);
next.set(key, updated);
return { stagedByKey: next };
}),
clear: (serverId, agentId) =>
set((state) => {
const key = stagedKey(serverId, agentId);
if (!state.stagedByKey.has(key)) return state;
const next = new Map(state.stagedByKey);
next.delete(key);
return { stagedByKey: next };
}),
clearForServer: (serverId) =>
set((state) => {
const prefix = `${serverId}:`;
let changed = false;
const next = new Map(state.stagedByKey);
for (const key of next.keys()) {
if (key.startsWith(prefix)) {
next.delete(key);
changed = true;
}
}
return changed ? { stagedByKey: next } : state;
}),
}));
export function getStagedProviderSwitch(
serverId: string,
agentId: string,
): StagedProviderSwitch | null {
return (
useStagedProviderSwitchStore.getState().stagedByKey.get(stagedKey(serverId, agentId)) ?? null
);
}
export function clearStagedProviderSwitch(serverId: string, agentId: string): void {
useStagedProviderSwitchStore.getState().clear(serverId, agentId);
}
export function useStagedProviderSwitch(
serverId: string,
agentId: string,
): StagedProviderSwitch | null {
return useStagedProviderSwitchStore(
(state) => state.stagedByKey.get(stagedKey(serverId, agentId)) ?? null,
);
}
+11
View File
@@ -205,6 +205,10 @@ export const ar: TranslationResources = {
pasteImageFailed: "تعذر لصق الصورة",
fileTooLarge: "{{fileName}} is too large (max {{size}})",
},
providerSwitch: {
switchingNextMessage: "التبديل إلى {{provider}} في الرسالة التالية",
switchingAfterTurn: "سيتم التبديل إلى {{provider}} بعد هذا الدور",
},
clientCommands: {
archiveAgent: "أرشفة الوكيل الحالي",
freshDraft: "أرشفة هذا الوكيل وابدأ مسودة جديدة",
@@ -436,6 +440,13 @@ export const ar: TranslationResources = {
turnFooter: {
workedFor: "عمل لمدة {{duration}}",
},
providerSwitch: {
switched: "تم التبديل من {{from}} إلى {{to}}",
contextSummary: "تم نقل {{count}} عنصر ({{chars}} / {{budget}} حرف)",
trimmed: "تم الاقتطاع: {{reasons}}",
reasonTailWindow: "سجل أقدم خارج النطاق",
reasonCharBudget: "حد الأحرف",
},
compaction: {
loading: "الضغط...",
auto: "يتم ضغط السياق تلقائيًا",
+11
View File
@@ -203,6 +203,10 @@ export const en = {
pasteImageFailed: "Failed to paste image",
fileTooLarge: "{{fileName}} is too large (max {{size}})",
},
providerSwitch: {
switchingNextMessage: "Switching to {{provider}} on next message",
switchingAfterTurn: "Will switch to {{provider}} after this turn",
},
clientCommands: {
archiveAgent: "Archive the current agent",
freshDraft: "Archive this agent and start a fresh draft",
@@ -435,6 +439,13 @@ export const en = {
turnFooter: {
workedFor: "Worked for {{duration}}",
},
providerSwitch: {
switched: "Switched from {{from}} to {{to}}",
contextSummary: "{{count}} items transferred ({{chars}} / {{budget}} chars)",
trimmed: "Trimmed: {{reasons}}",
reasonTailWindow: "older history beyond window",
reasonCharBudget: "character budget",
},
compaction: {
loading: "Compacting...",
auto: "Context automatically compacted",
+11
View File
@@ -207,6 +207,10 @@ export const es: TranslationResources = {
pasteImageFailed: "No se pudo pegar la imagen",
fileTooLarge: "{{fileName}} is too large (max {{size}})",
},
providerSwitch: {
switchingNextMessage: "Cambiando a {{provider}} en el próximo mensaje",
switchingAfterTurn: "Se cambiará a {{provider}} después de este turno",
},
clientCommands: {
archiveAgent: "Archivar el agente actual",
freshDraft: "Archive este agente y comience un nuevo borrador",
@@ -441,6 +445,13 @@ export const es: TranslationResources = {
turnFooter: {
workedFor: "Trabajó durante {{duration}}",
},
providerSwitch: {
switched: "Cambiado de {{from}} a {{to}}",
contextSummary: "{{count}} elementos transferidos ({{chars}} / {{budget}} caracteres)",
trimmed: "Recortado: {{reasons}}",
reasonTailWindow: "historial anterior fuera de la ventana",
reasonCharBudget: "límite de caracteres",
},
compaction: {
loading: "Compactando...",
auto: "Contexto compactado automáticamente",
+11
View File
@@ -208,6 +208,10 @@ export const fr: TranslationResources = {
pasteImageFailed: "Impossible de coller l’image",
fileTooLarge: "{{fileName}} est trop volumineux (maximum {{size}})",
},
providerSwitch: {
switchingNextMessage: "Passage à {{provider}} au prochain message",
switchingAfterTurn: "Passage à {{provider}} après ce tour",
},
clientCommands: {
archiveAgent: "Archiver l’agent actuel",
freshDraft: "Archiver cet agent et démarrer un nouveau brouillon",
@@ -441,6 +445,13 @@ export const fr: TranslationResources = {
turnFooter: {
workedFor: "A travaillé pendant {{duration}}",
},
providerSwitch: {
switched: "Passé de {{from}} à {{to}}",
contextSummary: "{{count}} éléments transférés ({{chars}} / {{budget}} caractères)",
trimmed: "Tronqué : {{reasons}}",
reasonTailWindow: "historique antérieur hors fenêtre",
reasonCharBudget: "limite de caractères",
},
compaction: {
loading: "Compaction…",
auto: "Contexte compacté automatiquement",
+11
View File
@@ -207,6 +207,10 @@ export const ja: TranslationResources = {
pasteImageFailed: "画像を貼り付けられませんでした",
fileTooLarge: "{{fileName}}が大きすぎます(最大{{size}})",
},
providerSwitch: {
switchingNextMessage: "次のメッセージで {{provider}} に切り替えます",
switchingAfterTurn: "このターン終了後に {{provider}} に切り替えます",
},
clientCommands: {
archiveAgent: "現在のエージェントをアーカイブ",
freshDraft: "このエージェントをアーカイブして新しい下書きを開始",
@@ -441,6 +445,13 @@ export const ja: TranslationResources = {
turnFooter: {
workedFor: "作業時間 {{duration}}",
},
providerSwitch: {
switched: "{{from}} から {{to}} に切り替えました",
contextSummary: "{{count}} 件を引き継ぎました ({{chars}} / {{budget}} 文字)",
trimmed: "省略: {{reasons}}",
reasonTailWindow: "ウィンドウ外の古い履歴",
reasonCharBudget: "文字数上限",
},
compaction: {
loading: "コンテキストを圧縮中...",
auto: "コンテキストが自動的に圧縮されました",
+11
View File
@@ -205,6 +205,10 @@ export const ko: TranslationResources = {
pasteImageFailed: "이미지를 붙여넣지 못했습니다.",
fileTooLarge: "{{fileName}}이(가) 너무 큽니다 (최대 {{size}})",
},
providerSwitch: {
switchingNextMessage: "다음 메시지에서 {{provider}}(으)로 전환합니다",
switchingAfterTurn: "이 턴이 끝난 후 {{provider}}(으)로 전환합니다",
},
clientCommands: {
archiveAgent: "현재 에이전트 보관",
freshDraft: "이 에이전트를 보관하고 새 초안을 시작합니다",
@@ -437,6 +441,13 @@ export const ko: TranslationResources = {
turnFooter: {
workedFor: "작업 시간 {{duration}}",
},
providerSwitch: {
switched: "{{from}}에서 {{to}}(으)로 전환됨",
contextSummary: "{{count}}개 항목 전달됨 ({{chars}} / {{budget}}자)",
trimmed: "생략됨: {{reasons}}",
reasonTailWindow: "창 범위를 벗어난 이전 기록",
reasonCharBudget: "문자 수 제한",
},
compaction: {
loading: "압축하는 중...",
auto: "컨텍스트가 자동으로 압축되었습니다",
+11
View File
@@ -206,6 +206,10 @@ export const ptBR: TranslationResources = {
pasteImageFailed: "Falha ao colar a imagem",
fileTooLarge: "{{fileName}} é grande demais (máximo {{size}})",
},
providerSwitch: {
switchingNextMessage: "Trocando para {{provider}} na próxima mensagem",
switchingAfterTurn: "Trocará para {{provider}} após este turno",
},
clientCommands: {
archiveAgent: "Arquivar o agente atual",
freshDraft: "Arquivar este agente e iniciar um novo rascunho",
@@ -440,6 +444,13 @@ export const ptBR: TranslationResources = {
turnFooter: {
workedFor: "Trabalhou por {{duration}}",
},
providerSwitch: {
switched: "Trocado de {{from}} para {{to}}",
contextSummary: "{{count}} itens transferidos ({{chars}} / {{budget}} caracteres)",
trimmed: "Cortado: {{reasons}}",
reasonTailWindow: "histórico anterior além da janela",
reasonCharBudget: "limite de caracteres",
},
compaction: {
loading: "Compactando...",
auto: "Contexto compactado automaticamente",
+11
View File
@@ -207,6 +207,10 @@ export const ru: TranslationResources = {
pasteImageFailed: "Не удалось вставить изображение",
fileTooLarge: "Файл {{fileName}} слишком большой (максимальный размер: {{size}})",
},
providerSwitch: {
switchingNextMessage: "Переключение на {{provider}} в следующем сообщении",
switchingAfterTurn: "Переключение на {{provider}} после этого хода",
},
clientCommands: {
archiveAgent: "Архивировать текущего агента",
freshDraft: "Архивировать этого агента и создать новый черновик",
@@ -440,6 +444,13 @@ export const ru: TranslationResources = {
turnFooter: {
workedFor: "Время работы: {{duration}}",
},
providerSwitch: {
switched: "Переключено с {{from}} на {{to}}",
contextSummary: "Передано элементов: {{count}} ({{chars}} / {{budget}} симв.)",
trimmed: "Сокращено: {{reasons}}",
reasonTailWindow: "более ранняя история вне окна",
reasonCharBudget: "лимит символов",
},
compaction: {
loading: "Сжатие контекста...",
auto: "Контекст сжат автоматически",
+11
View File
@@ -205,6 +205,10 @@ export const zhCN: TranslationResources = {
pasteImageFailed: "无法粘贴图片",
fileTooLarge: "{{fileName}} is too large (max {{size}})",
},
providerSwitch: {
switchingNextMessage: "下一条消息将切换到 {{provider}}",
switchingAfterTurn: "本轮结束后将切换到 {{provider}}",
},
clientCommands: {
archiveAgent: "归档当前 Agent",
freshDraft: "归档此 Agent 并开始新的草稿",
@@ -436,6 +440,13 @@ export const zhCN: TranslationResources = {
turnFooter: {
workedFor: "工作了 {{duration}}",
},
providerSwitch: {
switched: "已从 {{from}} 切换到 {{to}}",
contextSummary: "已传递 {{count}} 项上下文({{chars}} / {{budget}} 字符)",
trimmed: "已裁剪:{{reasons}}",
reasonTailWindow: "超出窗口的早期历史",
reasonCharBudget: "字符预算限制",
},
compaction: {
loading: "正在压缩...",
auto: "上下文已自动压缩",
@@ -65,6 +65,7 @@ function sourceTimelineItem(item: StreamItem): AgentTimelineItem | null {
...(item.preTokens !== undefined ? { preTokens: item.preTokens } : {}),
};
case "plugin":
case "provider_switch":
case "turn_summary":
return null;
}
+23 -2
View File
@@ -83,8 +83,10 @@ import {
} from "@/desktop/browser/automation/handler";
import { schedulesQueryBaseKey } from "@/schedules/aggregated-schedules";
import { dispatchComposerAgentMessage, sendQueuedComposerMessageNow } from "@/composer/actions";
import { clearStagedProviderSwitch, getStagedProviderSwitch } from "@/composer/provider-switch";
import { createMessageSubmissionWriter } from "@/composer/submission/writer";
import { resolveComposerAttachmentSubmitFormat } from "@/composer/attachments/submit";
import { normalizeAgentSnapshot } from "@/utils/agent-snapshots";
import { encodeImages } from "@/utils/encode-images";
import { DirectorySync, type RefreshAgentDirectoryResult } from "@/runtime/directory-sync";
import { ReplicaCache } from "@/runtime/replica-cache";
@@ -2903,8 +2905,16 @@ export class HostRuntimeStore {
write: (update) => useSessionStore.getState().setQueuedMessages(serverId, update),
},
submitMessage: async ({ text, attachments }) => {
const supportsForgeAttachments =
useSessionStore.getState().sessions[serverId]?.serverInfo?.features?.forgeSearch === true;
const currentSession = useSessionStore.getState().sessions[serverId];
const supportsForgeAttachments = currentSession?.serverInfo?.features?.forgeSearch === true;
const supportsProviderSwitching =
currentSession?.serverInfo?.features?.providerSwitching === true;
const liveProvider = currentSession?.agents.get(agentId)?.provider;
const rawStagedSwitch = supportsProviderSwitching
? getStagedProviderSwitch(serverId, agentId)
: null;
const stagedProviderSwitch =
rawStagedSwitch && rawStagedSwitch.provider !== liveProvider ? rawStagedSwitch : null;
await dispatchComposerAgentMessage({
client,
agentId,
@@ -2915,6 +2925,13 @@ export class HostRuntimeStore {
}),
encodeImages,
submission: createMessageSubmissionWriter(serverId),
stagedProviderSwitch,
onProviderSwitchCommitted: (agent) => {
clearStagedProviderSwitch(serverId, agentId);
if (agent) {
this.tryAcceptAgentSnapshot(serverId, normalizeAgentSnapshot(agent, serverId));
}
},
// The queue drains when the agent goes idle, but the agent can start a turn of its own
// in that same moment (a wake-up after background work). Steering folds the message
// into that turn instead of interrupting it; with no turn running, the daemon starts
@@ -2960,6 +2977,10 @@ export class HostRuntimeStore {
return this.requireDirectory(serverId).acceptAgent(agent);
}
tryAcceptAgentSnapshot(serverId: string, agent: Agent): Agent | null {
return this.directorySyncByServer.get(serverId)?.acceptAgent(agent) ?? null;
}
archiveAgentSnapshot(serverId: string, agentId: string, archivedAt: string): void {
this.requireDirectory(serverId).archiveAgent(agentId, archivedAt);
}
@@ -170,6 +170,23 @@ const StoredTimelineItemSchema = z.discriminatedUnion("kind", [
trigger: z.enum(["auto", "manual"]).optional(),
preTokens: z.number().nonnegative().optional(),
}),
z.strictObject({
...TimelineItemBaseShape,
kind: z.literal("provider_switch"),
fromProvider: AgentProviderSchema,
toProvider: AgentProviderSchema,
fromModel: z.string().nullable().optional(),
toModel: z.string().nullable().optional(),
fromSessionId: z.string().nullable().optional(),
toSessionId: z.string().nullable().optional(),
context: z.strictObject({
includedItems: z.number().int().nonnegative(),
truncated: z.boolean(),
charCount: z.number().int().nonnegative(),
budgetChars: z.number().int().positive(),
omittedReasons: z.array(z.string()).optional(),
}),
}),
z.strictObject({
...TimelineItemBaseShape,
kind: z.literal("tool_call"),
@@ -371,6 +388,7 @@ const StoredTimelineSchema = z.strictObject({
epoch: z.string(),
startSeq: z.number().int().nonnegative(),
endSeq: z.number().int().nonnegative(),
activeSegmentStartSeq: z.number().int().nonnegative().optional(),
})
.nullable(),
hasOlder: z.boolean(),
@@ -482,6 +500,23 @@ function serializeAgentToolCall(data: AgentToolCallData): StoredToolCall {
}
}
function serializeProviderSwitchItem(
base: ReturnType<typeof timelineBase>,
item: Extract<StreamItem, { kind: "provider_switch" }>,
): StoredTimelineItem {
return {
...base,
kind: item.kind,
fromProvider: item.fromProvider,
toProvider: item.toProvider,
...(item.fromModel !== undefined ? { fromModel: item.fromModel } : {}),
...(item.toModel !== undefined ? { toModel: item.toModel } : {}),
...(item.fromSessionId !== undefined ? { fromSessionId: item.fromSessionId } : {}),
...(item.toSessionId !== undefined ? { toSessionId: item.toSessionId } : {}),
context: item.context,
};
}
function serializeTimelineItem(item: StreamItem): StoredTimelineItem | null {
const base = timelineBase(item);
switch (item.kind) {
@@ -527,6 +562,8 @@ function serializeTimelineItem(item: StreamItem): StoredTimelineItem | null {
...(item.trigger ? { trigger: item.trigger } : {}),
...(item.preTokens !== undefined ? { preTokens: item.preTokens } : {}),
};
case "provider_switch":
return serializeProviderSwitchItem(base, item);
case "tool_call":
if (item.payload.source !== "agent") return null;
return {
@@ -579,6 +616,23 @@ function deserializeTimelineItem(item: StoredTimelineItem): StreamItem {
return deserializeBuiltinTimelineItem(item);
}
function deserializeProviderSwitchItem(
base: { id: string; timelineCursor?: TimelinePosition; turnId?: string; timestamp: Date },
item: Extract<StoredTimelineItem, { kind: "provider_switch" }>,
): StreamItem {
return {
...base,
kind: item.kind,
fromProvider: item.fromProvider,
toProvider: item.toProvider,
...(item.fromModel !== undefined ? { fromModel: item.fromModel } : {}),
...(item.toModel !== undefined ? { toModel: item.toModel } : {}),
...(item.fromSessionId !== undefined ? { fromSessionId: item.fromSessionId } : {}),
...(item.toSessionId !== undefined ? { toSessionId: item.toSessionId } : {}),
context: item.context,
};
}
function deserializeBuiltinTimelineItem(
item: Exclude<StoredTimelineItem, { kind: "plugin" }>,
): StreamItem {
@@ -631,6 +685,8 @@ function deserializeBuiltinTimelineItem(
...(item.trigger ? { trigger: item.trigger } : {}),
...(item.preTokens !== undefined ? { preTokens: item.preTokens } : {}),
};
case "provider_switch":
return deserializeProviderSwitchItem(base, item);
case "tool_call": {
const tool = item.item;
if (tool.type !== "tool_call") {
@@ -862,7 +918,14 @@ function serializeTimeline(timeline: CachedTimeline): StoredTimeline | null {
agentId: timeline.agentId,
items,
range: canPersistCoverage
? { epoch: range.epoch, startSeq: range.startSeq, endSeq: range.endSeq }
? {
epoch: range.epoch,
startSeq: range.startSeq,
endSeq: range.endSeq,
...(range.activeSegmentStartSeq !== undefined
? { activeSegmentStartSeq: range.activeSegmentStartSeq }
: {}),
}
: null,
hasOlder: canPersistCoverage ? timeline.hasOlder : false,
...(timeline.unsettledTurn
+1
View File
@@ -317,6 +317,7 @@ export interface AgentTimelineCursorState {
epoch: string;
startSeq: number;
endSeq: number;
activeSegmentStartSeq?: number;
retainedRanges?: Array<{
startSeq: number;
endSeq: number;
@@ -40,6 +40,7 @@ export interface TimelineCursor {
epoch: string;
startSeq: number;
endSeq: number;
activeSegmentStartSeq?: number;
retainedRanges?: TimelineLoadedRange[];
}
@@ -164,6 +165,9 @@ function mergeTimelineCoverage(
epoch: current.epoch,
startSeq: contiguous.startSeq,
endSeq: contiguous.endSeq,
...(current.activeSegmentStartSeq !== undefined
? { activeSegmentStartSeq: current.activeSegmentStartSeq }
: {}),
...(retainedRanges.length > 0 ? { retainedRanges } : {}),
};
}
@@ -172,7 +176,8 @@ function timelineCursorEquals(left: TimelineCursor, right: TimelineCursor): bool
if (
left.epoch !== right.epoch ||
left.startSeq !== right.startSeq ||
left.endSeq !== right.endSeq
left.endSeq !== right.endSeq ||
(left.activeSegmentStartSeq ?? 0) !== (right.activeSegmentStartSeq ?? 0)
) {
return false;
}
@@ -217,6 +222,7 @@ export interface ProcessTimelineResponseInput {
hasOlder: boolean;
mergeWindow?: boolean;
retirements?: TimelineRetirement[];
activeSegmentStartSeq?: number;
};
currentTail: StreamItem[];
currentHead: StreamItem[];
@@ -1304,6 +1310,57 @@ function applyTimelineIncrementalPath(args: {
};
}
function mergeResponseActiveSegmentCursor(
cursor: TimelineCursor | null | undefined,
cursorChanged: boolean,
currentCursor: TimelineCursor | undefined,
incomingActiveSegmentStartSeq: number | undefined,
): { cursor: TimelineCursor | null | undefined; cursorChanged: boolean } {
if (!cursor) {
return { cursor, cursorChanged };
}
const prevSegment =
currentCursor?.epoch === cursor.epoch ? (currentCursor.activeSegmentStartSeq ?? 0) : 0;
const incomingSegment = incomingActiveSegmentStartSeq ?? cursor.activeSegmentStartSeq ?? 0;
const mergedSegment = Math.max(prevSegment, incomingSegment);
if (mergedSegment > 0 && cursor.activeSegmentStartSeq !== mergedSegment) {
return { cursor: { ...cursor, activeSegmentStartSeq: mergedSegment }, cursorChanged: true };
}
return { cursor, cursorChanged };
}
function advanceLiveActiveSegmentCursor(input: {
shouldApply: boolean;
event: AgentStreamEventPayload;
seq: number | undefined;
epoch: string | undefined;
nextCursor: TimelineCursor | null;
cursorChanged: boolean;
currentCursor: TimelineCursor | undefined;
}): { cursor: TimelineCursor | null; cursorChanged: boolean } {
const { shouldApply, event, seq, epoch, nextCursor, cursorChanged, currentCursor } = input;
if (
!shouldApply ||
event.type !== "timeline" ||
event.item.type !== "provider_switch" ||
typeof seq !== "number" ||
typeof epoch !== "string"
) {
return { cursor: nextCursor, cursorChanged };
}
const baseCursor =
nextCursor ??
(currentCursor?.epoch === epoch ? currentCursor : { epoch, startSeq: seq, endSeq: seq });
const nextActiveSegment = Math.max(baseCursor.activeSegmentStartSeq ?? 0, seq);
if (baseCursor.activeSegmentStartSeq !== nextActiveSegment || nextCursor === null) {
return {
cursor: { ...baseCursor, activeSegmentStartSeq: nextActiveSegment },
cursorChanged: true,
};
}
return { cursor: nextCursor, cursorChanged };
}
export function processTimelineResponse(
input: ProcessTimelineResponseInput,
): ProcessTimelineResponseOutput {
@@ -1459,8 +1516,12 @@ export function processTimelineResponse(
const nextTail = stampTimelineTurnMetrics(timelineResult.tail, payload.epoch, pageEntries);
const nextHead = stampTimelineTurnMetrics(timelineResult.head, payload.epoch, pageEntries);
const nextCursor = timelineResult.cursor;
const cursorChanged = timelineResult.cursorChanged;
const { cursor: nextCursor, cursorChanged } = mergeResponseActiveSegmentCursor(
timelineResult.cursor,
timelineResult.cursorChanged,
currentCursor,
payload.activeSegmentStartSeq,
);
sideEffects.push(...timelineResult.sideEffects);
// ------------------------------------------------------------------
@@ -1779,14 +1840,23 @@ export function processAgentStreamEvent(
});
}
const { tail, head, changedTail, changedHead } = streamResult;
const { cursor: nextTimelineCursor, cursorChanged } = advanceLiveActiveSegmentCursor({
shouldApply: sequencing.shouldApplyStreamEvent,
event,
seq,
epoch,
nextCursor: sequencing.nextTimelineCursor,
cursorChanged: sequencing.cursorChanged,
currentCursor,
});
return {
tail,
head,
changedTail,
changedHead,
cursor: sequencing.nextTimelineCursor,
cursorChanged: sequencing.cursorChanged,
cursor: nextTimelineCursor,
cursorChanged,
acknowledgedClientMessageIds: streamResult.acknowledgedClientMessageIds ?? [],
...(sequencing.shouldApplyStreamEvent && event.type === "timeline" && event.item.type === "todo"
? { taskSnapshot: event.item.items }
+53
View File
@@ -4,6 +4,7 @@ import type {
AgentProvider,
AgentTimelineItem,
JsonValue,
ProviderSwitchContextSummary,
ToolCallDetail,
} from "@getpaseo/protocol/agent-types";
import { timelineItemIdentity } from "@getpaseo/protocol/timeline-identity";
@@ -89,9 +90,25 @@ export type StreamItem =
| TodoListItem
| NotificationItem
| CompactionItem
| ProviderSwitchItem
| PluginTimelineStreamItem
| TurnSummaryItem;
export interface ProviderSwitchItem {
kind: "provider_switch";
id: string;
timelineCursor?: TimelinePosition;
turnId?: string;
timestamp: Date;
fromProvider: AgentProvider;
toProvider: AgentProvider;
fromModel?: string | null;
toModel?: string | null;
fromSessionId?: string | null;
toSessionId?: string | null;
context: ProviderSwitchContextSummary;
}
export type UserMessageImageAttachment = AttachmentMetadata;
export interface UserMessageItem {
@@ -1580,6 +1597,40 @@ function reduceTimelineCompaction(
return [...state, compaction];
}
function reduceTimelineProviderSwitch(
state: StreamItem[],
item: Extract<AgentTimelineItem, { type: "provider_switch" }>,
timestamp: Date,
timelineCursor?: TimelinePosition,
): StreamItem[] {
const switchId =
timelineCursor !== undefined
? `provider_switch:${timelineCursor.epoch}:${timelineCursor.anchorSeq}`
: createUniqueTimelineId(
state,
"provider_switch",
`${item.fromProvider}->${item.toProvider}`,
timestamp,
);
if (state.some((existing) => existing.kind === "provider_switch" && existing.id === switchId)) {
return state;
}
const marker: ProviderSwitchItem = {
kind: "provider_switch",
id: switchId,
...(timelineCursor ? { timelineCursor } : {}),
timestamp,
fromProvider: item.fromProvider,
toProvider: item.toProvider,
...(item.fromModel !== undefined ? { fromModel: item.fromModel } : {}),
...(item.toModel !== undefined ? { toModel: item.toModel } : {}),
...(item.fromSessionId !== undefined ? { fromSessionId: item.fromSessionId } : {}),
...(item.toSessionId !== undefined ? { toSessionId: item.toSessionId } : {}),
context: item.context,
};
return [...state, marker];
}
function reduceTimelineEvent(
state: StreamItem[],
event: Extract<AgentStreamEventPayload, { type: "timeline" }>,
@@ -1651,6 +1702,8 @@ function reduceTimelineEvent(
}
case "compaction":
return reduceTimelineCompaction(state, item, timestamp, timelineCursor);
case "provider_switch":
return reduceTimelineProviderSwitch(state, item, timestamp, timelineCursor);
case "plugin":
return appendPluginTimelineItem(state, item, timestamp, timelineCursor);
default:
+1
View File
@@ -144,6 +144,7 @@ export const DEFAULT_CLIENT_CAPABILITIES = {
[CLIENT_CAPS.timelineRewindOperations]: true,
[CLIENT_CAPS.timelineNotifications]: true,
[CLIENT_CAPS.pluginTimelineItems]: true,
[CLIENT_CAPS.timelineProviderSwitches]: true,
[CLIENT_CAPS.workspaceSetupBlocked]: true,
[CLIENT_CAPS.workspaceSetupObservation]: true,
[CLIENT_CAPS.pluginBinaryPayloads]: true,
@@ -1146,6 +1146,7 @@ test("advertises client capabilities in hello", async () => {
terminal_reflowable_snapshot: true,
terminal_chunked_replay: true,
timeline_notifications: true,
timeline_provider_switches: true,
plugin_timeline_items: true,
plugin_binary_payloads: true,
workspace_setup_blocked: true,
+74
View File
@@ -127,6 +127,8 @@ import type {
DaemonConfigReloadResponse,
DiagnosticsResponse,
AgentRewindResponseMessage,
AgentProviderSwitchRequest,
AgentProviderSwitchResponseMessage,
ListTerminalsResponse,
CreateTerminalResponse,
SubscribeTerminalResponse,
@@ -509,6 +511,28 @@ export interface SendMessageOptions {
attachments?: SendAgentMessageRequest["attachments"];
}
export interface SwitchAgentProviderOptions {
provider: AgentProvider;
model?: string | null;
modeId?: string | null;
thinkingOptionId?: string | null;
providerOptions?: Record<string, unknown>;
text: string;
messageId?: string;
images?: Array<{ data: string; mimeType: string }>;
attachments?: AgentProviderSwitchRequest["attachments"];
}
export class AgentProviderSwitchError extends Error {
constructor(
message: string,
readonly agent?: AgentSnapshotPayload,
) {
super(message);
this.name = "AgentProviderSwitchError";
}
}
export interface AgentAttentionRequiredNotification {
agentId: string;
reason: "finished" | "error" | "permission";
@@ -4339,6 +4363,56 @@ export class DaemonClient {
};
}
async switchAgentProvider(
agentId: string,
options: SwitchAgentProviderOptions,
): Promise<{ agent?: AgentSnapshotPayload }> {
if (this.lastServerInfoMessage?.features?.providerSwitching !== true) {
throw new Error("Update the Paseo host to switch providers in an existing chat.");
}
const requestId = this.createRequestId();
const messageId = options.messageId ?? crypto.randomUUID();
const message = SessionInboundMessageSchema.parse({
type: "agent.provider.switch.request",
requestId,
agentId,
provider: options.provider,
...(options.model !== undefined ? { model: options.model } : {}),
...(options.modeId !== undefined ? { modeId: options.modeId } : {}),
...(options.thinkingOptionId !== undefined
? { thinkingOptionId: options.thinkingOptionId }
: {}),
...(options.providerOptions !== undefined
? { providerOptions: options.providerOptions }
: {}),
text: options.text,
messageId,
images: options.images,
attachments: options.attachments,
});
const payload: AgentProviderSwitchResponseMessage["payload"] = await this.sendRequest({
requestId,
message,
options: { skipQueue: true },
select: (msg) => {
if (msg.type !== "agent.provider.switch.response") {
return null;
}
if (msg.payload.requestId !== requestId) {
return null;
}
return msg.payload;
},
});
if (!payload.accepted) {
throw new AgentProviderSwitchError(
payload.error ?? "switchAgentProvider rejected",
payload.agent,
);
}
return payload.agent ? { agent: payload.agent } : {};
}
/** The behavior to put on the wire for this host. */
private activeTurnBehaviorForHost(
options: SendMessageOptions,
+21 -1
View File
@@ -399,6 +399,25 @@ export interface PluginTimelineItem {
data: JsonValue;
}
export interface ProviderSwitchContextSummary {
includedItems: number;
truncated: boolean;
charCount: number;
budgetChars: number;
omittedReasons?: string[];
}
export interface ProviderSwitchTimelineItem {
type: "provider_switch";
fromProvider: AgentProvider;
toProvider: AgentProvider;
fromModel?: string | null;
toModel?: string | null;
fromSessionId?: string | null;
toSessionId?: string | null;
context: ProviderSwitchContextSummary;
}
export interface AgentTaskItem {
text: string;
completed: boolean;
@@ -420,7 +439,8 @@ export type AgentTimelineItem =
message: string;
}
| CompactionTimelineItem
| PluginTimelineItem;
| PluginTimelineItem
| ProviderSwitchTimelineItem;
export type AgentStreamEvent =
| { type: "thread_started"; sessionId: string; provider: AgentProvider }
@@ -48,6 +48,9 @@ export const CLIENT_CAPS = {
timelineNotifications: "timeline_notifications",
// COMPAT(pluginTimelineItems): added in v0.8.0, remove after 2027-03-07 once client floor >= v0.8.0.
pluginTimelineItems: "plugin_timeline_items",
// COMPAT(timelineProviderSwitches): added in v0.18.0, remove after 2027-05-25 once client floor >= v0.18.0.
// The daemon omits provider_switch timeline items for older clients whose strict union rejects them.
timelineProviderSwitches: "timeline_provider_switches",
workspaceSetupObservation: "workspace_setup_observation",
// COMPAT(pluginBinaryPayloads): added in v0.15.0, remove after 2027-05-02 once client floor >= v0.15.0.
// The daemon sends plugin RPC outputs as binary opcode 0x21 only to clients that decode it.
@@ -0,0 +1,168 @@
import { describe, expect, it } from "vitest";
import { CLIENT_CAPS } from "./client-capabilities.js";
import {
AgentProviderSwitchRequestSchema,
AgentProviderSwitchResponseMessageSchema,
AgentTimelineItemPayloadSchema,
FetchAgentTimelineResponseMessageSchema,
ServerInfoStatusPayloadSchema,
SessionInboundMessageSchema,
SessionOutboundMessageSchema,
WSHelloMessageSchema,
} from "./messages.js";
import { isTimelineTurnTrigger } from "./timeline-turn.js";
describe("provider switching protocol", () => {
it("parses agent.provider.switch.request and response including agent snapshot on rejection", () => {
const request = SessionInboundMessageSchema.parse({
type: "agent.provider.switch.request",
requestId: "req-switch-1",
agentId: "agent-1",
provider: "codex",
model: "gpt-5.4",
modeId: "auto",
thinkingOptionId: "high",
providerOptions: { fast_mode: true },
text: "Continue in Codex",
messageId: "msg-switch-1",
attachments: [
{
type: "text",
mimeType: "text/plain",
text: "extra context",
},
],
});
expect(request).toEqual(AgentProviderSwitchRequestSchema.parse(request));
const acceptedResponse = SessionOutboundMessageSchema.parse({
type: "agent.provider.switch.response",
payload: {
requestId: "req-switch-1",
agentId: "agent-1",
accepted: true,
error: null,
},
});
expect(acceptedResponse).toEqual(
AgentProviderSwitchResponseMessageSchema.parse(acceptedResponse),
);
const postCommitError = AgentProviderSwitchResponseMessageSchema.parse({
type: "agent.provider.switch.response",
payload: {
requestId: "req-switch-1",
agentId: "agent-1",
accepted: false,
agent: {
id: "agent-1",
provider: "codex",
cwd: "/repo",
model: "gpt-5.4",
createdAt: "2026-11-25T10:00:00.000Z",
updatedAt: "2026-11-25T10:01:00.000Z",
lastUserMessageAt: null,
status: "error",
capabilities: {
supportsStreaming: true,
supportsSessionPersistence: true,
supportsDynamicModes: true,
supportsMcpServers: true,
supportsReasoningStream: true,
supportsToolInvocations: true,
},
currentModeId: "auto",
availableModes: [],
pendingPermissions: [],
persistence: null,
title: "Chat",
labels: {},
},
error: "Rate limit exceeded",
},
});
expect(postCommitError.payload.accepted).toBe(false);
expect(postCommitError.payload.agent?.provider).toBe("codex");
});
it("parses provider_switch timeline items including null toSessionId and marks them turn triggers", () => {
const item = AgentTimelineItemPayloadSchema.parse({
type: "provider_switch",
fromProvider: "claude",
toProvider: "codex",
fromModel: "claude-sonnet-4-6",
toModel: "gpt-5.4",
fromSessionId: "claude-sess-1",
toSessionId: null,
context: {
includedItems: 12,
truncated: true,
omittedOlderItems: true,
truncatedText: false,
charCount: 14_200,
budgetChars: 100_000,
},
});
expect(item.type).toBe("provider_switch");
expect(isTimelineTurnTrigger(item)).toBe(true);
});
it("supports optional activeSegmentStartSeq on fetch_agent_timeline_response", () => {
const base = {
type: "fetch_agent_timeline_response" as const,
payload: {
requestId: "req-1",
agentId: "agent-1",
agent: null,
direction: "tail" as const,
projection: "projected" as const,
epoch: "ep-1",
reset: false,
staleCursor: false,
gap: false,
window: { minSeq: 1, maxSeq: 12, nextSeq: 13 },
startCursor: { epoch: "ep-1", seq: 1 },
endCursor: { epoch: "ep-1", seq: 12 },
hasOlder: false,
hasNewer: false,
entries: [],
error: null,
},
};
const withoutBoundary = FetchAgentTimelineResponseMessageSchema.parse(base);
expect(withoutBoundary.payload.activeSegmentStartSeq).toBeUndefined();
const withBoundary = FetchAgentTimelineResponseMessageSchema.parse({
...base,
payload: { ...base.payload, activeSegmentStartSeq: 9 },
});
expect(withBoundary.payload.activeSegmentStartSeq).toBe(9);
});
it("supports features.providerSwitching and CLIENT_CAPS.timelineProviderSwitches", () => {
const info = ServerInfoStatusPayloadSchema.parse({
status: "server_info",
serverId: "srv-1",
features: { providerSwitching: true },
});
expect(info.features?.providerSwitching).toBe(true);
const legacyInfo = ServerInfoStatusPayloadSchema.parse({
status: "server_info",
serverId: "srv-1",
features: {},
});
expect(legacyInfo.features?.providerSwitching).toBeUndefined();
const hello = WSHelloMessageSchema.parse({
type: "hello",
clientId: "client-1",
clientType: "browser",
protocolVersion: 1,
capabilities: {
[CLIENT_CAPS.timelineProviderSwitches]: true,
},
});
expect(hello.capabilities?.[CLIENT_CAPS.timelineProviderSwitches]).toBe(true);
});
});
+54
View File
@@ -817,6 +817,22 @@ export const AgentTimelineItemPayloadSchema: z.ZodType<AgentTimelineItem, unknow
version: z.number(),
data: JsonWireValueSchema,
}),
z.object({
type: z.literal("provider_switch"),
fromProvider: AgentProviderSchema,
toProvider: AgentProviderSchema,
fromModel: z.string().nullable().optional(),
toModel: z.string().nullable().optional(),
fromSessionId: z.string().nullable().optional(),
toSessionId: z.string().nullable().optional(),
context: z.object({
includedItems: z.number().int().nonnegative(),
truncated: z.boolean(),
charCount: z.number().int().nonnegative(),
budgetChars: z.number().int().nonnegative(),
omittedReasons: z.array(z.string()).optional(),
}),
}),
]);
export const AgentStreamEventPayloadSchema = z.discriminatedUnion("type", [
@@ -2299,6 +2315,21 @@ export const AgentRewindResponseMessageSchema = z.object({
}),
});
export const AgentProviderSwitchRequestSchema = z.object({
type: z.literal("agent.provider.switch.request"),
requestId: z.string(),
agentId: z.string(),
provider: AgentProviderSchema,
model: z.string().nullable().optional(),
modeId: z.string().nullable().optional(),
thinkingOptionId: z.string().nullable().optional(),
providerOptions: z.record(z.string(), z.unknown()).optional(),
text: z.string(),
messageId: z.string().min(1),
images: z.array(ImageAttachmentSchema).optional(),
attachments: AgentAttachmentsSchema,
});
export const UpdateAgentResponseMessageSchema = z.object({
type: z.literal("update_agent_response"),
payload: AgentActionResponsePayloadSchema,
@@ -3620,6 +3651,7 @@ export const SessionInboundMessageSchema = z.discriminatedUnion("type", [
WorkspaceArchiveUndoRequestSchema,
SetVoiceModeMessageSchema,
SendAgentMessageRequestSchema,
AgentProviderSwitchRequestSchema,
WaitForFinishRequestSchema,
DaemonGetStatusRequestSchema,
DaemonGetPairingOfferRequestSchema,
@@ -4095,6 +4127,8 @@ export const ServerInfoStatusPayloadSchema = z
// COMPAT(timelineRewindOperations): added in v0.14.1, remove gate after 2027-05-10.
// A conversation rewind arrives as `agent.timeline.rewind`, not a replacement.
timelineRewindOperations: z.boolean().optional(),
// COMPAT(providerSwitching): added in v0.18.0, remove gate after 2027-05-25.
providerSwitching: z.boolean().optional(),
// COMPAT(agentTimelinePromptIndex): added in v0.2.X, drop the gate when floor >= v0.2.X.
agentTimelinePromptIndex: z.boolean().optional(),
// COMPAT(agentHistorySearch): added in v0.3.0, remove gate after 2027-02-07.
@@ -5192,6 +5226,8 @@ export const FetchAgentTimelineResponseMessageSchema = z.object({
// COMPAT(timelineRewindOperations): added in v0.14.1. Retirements whose seq lies in the page's
// span; apply them before the entries. Sent only to clients with the capability.
retirements: z.array(AgentTimelineRetirementSchema).optional(),
/** Seq of the latest active provider_switch marker, or 0 if never switched. */
activeSegmentStartSeq: z.number().int().nonnegative().optional(),
error: z.string().nullable(),
}),
});
@@ -5582,6 +5618,17 @@ export const SendAgentMessageResponseMessageSchema = z.object({
}),
});
export const AgentProviderSwitchResponseMessageSchema = z.object({
type: z.literal("agent.provider.switch.response"),
payload: z.object({
requestId: z.string(),
agentId: z.string(),
accepted: z.boolean(),
agent: AgentSnapshotPayloadSchema.optional(),
error: z.string().nullable(),
}),
});
export const WaitForFinishResponseMessageSchema = z.object({
type: z.literal("wait_for_finish_response"),
payload: z.object({
@@ -7827,6 +7874,7 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [
WorkspaceClearAttentionResponseSchema,
WorkspaceMarkUnreadResponseSchema,
SendAgentMessageResponseMessageSchema,
AgentProviderSwitchResponseMessageSchema,
SetVoiceModeResponseMessageSchema,
DaemonGetStatusResponseSchema,
DaemonGetPairingOfferResponseSchema,
@@ -8056,6 +8104,9 @@ export type AgentTimelineListPromptsResponseMessage = z.infer<
export type AgentForkContextResponseMessage = z.infer<typeof AgentForkContextResponseMessageSchema>;
export type CancelAgentResponseMessage = z.infer<typeof CancelAgentResponseMessageSchema>;
export type SendAgentMessageResponseMessage = z.infer<typeof SendAgentMessageResponseMessageSchema>;
export type AgentProviderSwitchResponseMessage = z.infer<
typeof AgentProviderSwitchResponseMessageSchema
>;
export type SetVoiceModeResponseMessage = z.infer<typeof SetVoiceModeResponseMessageSchema>;
export type SetAgentModeResponseMessage = z.infer<typeof SetAgentModeResponseMessageSchema>;
export type SetAgentModelResponseMessage = z.infer<typeof SetAgentModelResponseMessageSchema>;
@@ -8191,6 +8242,7 @@ export type ProjectSuggestionsResponse = z.infer<typeof ProjectSuggestionsRespon
export type FetchAgentRequestMessage = z.infer<typeof FetchAgentRequestMessageSchema>;
export type AgentForkContextRequestMessage = z.infer<typeof AgentForkContextRequestMessageSchema>;
export type SendAgentMessageRequest = z.infer<typeof SendAgentMessageRequestSchema>;
export type AgentProviderSwitchRequest = z.infer<typeof AgentProviderSwitchRequestSchema>;
export type WaitForFinishRequest = z.infer<typeof WaitForFinishRequestSchema>;
export type DictationStreamStartMessage = z.infer<typeof DictationStreamStartMessageSchema>;
export type DictationStreamChunkMessage = z.infer<typeof DictationStreamChunkMessageSchema>;
@@ -8512,6 +8564,8 @@ export const WSHelloMessageSchema = z.object({
[CLIENT_CAPS.timelineReplacementInvalidation]: z.boolean().optional(),
[CLIENT_CAPS.timelineRewindOperations]: z.boolean().optional(),
[CLIENT_CAPS.timelineNotifications]: z.boolean().optional(),
[CLIENT_CAPS.pluginTimelineItems]: z.boolean().optional(),
[CLIENT_CAPS.timelineProviderSwitches]: z.boolean().optional(),
[CLIENT_CAPS.backgroundAgents]: z.boolean().optional(),
[CLIENT_CAPS.browserHost]: BrowserAutomationHostCapabilitySchema.optional(),
})
+1
View File
@@ -19,6 +19,7 @@ export function isTimelineTurnTrigger(item: {
}): boolean {
return (
item.type === "user_message" ||
item.type === "provider_switch" ||
(item.type === "tool_call" && (item.agentMessage !== undefined || item.name === "heartbeat"))
);
}
@@ -10,7 +10,7 @@ import { projectTimelineRows, selectItemsByProjectedLimit } from "./timeline-pro
const DEFAULT_MAX_ITEMS = 0;
const MAX_TOOL_INPUT_CHARS = 400;
const MAX_TOOL_SUMMARY_CHARS = 200;
const MAX_FORK_CONTEXT_CHARS = 100_000;
export const MAX_FORK_CONTEXT_CHARS = 100_000;
const MAX_FORK_METADATA_CHARS = 1_000;
const FORK_HISTORY_OMITTED = "[Earlier chat history omitted]\n";
// A fork copies only these kinds.
@@ -27,7 +27,7 @@ interface ActivityCuratorOptions {
includeExternalToolInput?: boolean;
}
interface ActivityEntry {
export interface ActivityEntry {
text: string;
}
@@ -138,7 +138,7 @@ function appendAgentMessageEntries(entries: ActivityEntry[], message: AgentMessa
if (body) entries.push(activityEntry(body));
}
function curateProjectedActivityEntries(
export function curateProjectedActivityEntries(
items: readonly AgentTimelineItem[],
options?: ActivityCuratorOptions,
): ActivityEntry[] {
@@ -186,6 +186,11 @@ function curateProjectedActivityEntries(
case "compaction":
entries.push(activityEntry("[Compacted]"));
break;
case "provider_switch":
entries.push(
activityEntry(`[Switched provider: ${item.fromProvider} -> ${item.toProvider}]`),
);
break;
}
}
@@ -24,7 +24,7 @@ export type AgentLoaderManager = Pick<
AgentManager,
"createAgentFromRecord" | "getAgent" | "getRegisteredProviderIds" | "resumeAgentFromPersistence"
> &
Partial<Pick<AgentManager, "waitForAgentClose">>;
Partial<Pick<AgentManager, "waitForAgentClose" | "reconcilePendingProviderSwitch">>;
export interface EnsureAgentLoadedDeps {
agentManager: AgentLoaderManager;
@@ -55,6 +55,7 @@ export async function loadAgentHistory(
): Promise<AgentHistorySource> {
const live = deps.agentManager.getAgent(agentId);
if (live) return { kind: "live", agent: live };
await deps.agentManager.reconcilePendingProviderSwitch?.(agentId);
const record = await deps.agentStorage.get(agentId);
if (!record) throw new AgentNotFoundError(agentId);
if (await deps.agentManager.hasStoredHistory(agentId)) {
@@ -128,6 +129,7 @@ export async function ensureAgentLoaded(
}
const initPromise = (async () => {
await deps.agentManager.reconcilePendingProviderSwitch?.(agentId);
const record = await requireLoadableRecord(agentId, deps);
const validProviders = deps.validProviders ?? deps.agentManager.getRegisteredProviderIds();
const handle = toAgentPersistenceHandle(validProviders, record.persistence);
+689 -27
View File
@@ -3,7 +3,7 @@ import { ProviderOptionsValidationError } from "./provider-options.js";
import type { AgentToolResult } from "@getpaseo/plugin/server";
import type { RuntimeCleanupCandidate } from "./idle-runtime-cleanup/index.js";
import { AgentNotFoundError, ensureAgentLoaded } from "./agent-loading.js";
import { AgentTurnChangedError } from "./agent-prompt.js";
import { AgentTurnBusyError, AgentTurnChangedError } from "./agent-prompt.js";
import { lastAssistantMessageText, TimelineProjection } from "./timeline-projection.js";
import type { PluginLifecycle } from "../plugins/lifecycle/index.js";
import { describeHookAgent, publishAgentStream } from "../plugins/lifecycle/index.js";
@@ -64,6 +64,8 @@ import {
type ImportedTimelineEntry,
type ImportableProviderSession,
type ListImportableSessionsOptions,
type ProviderSwitchContextSummary,
type ProviderSwitchTimelineItem,
RewindAppliedError,
RewindNotAppliedError,
} from "./agent-sdk-types.js";
@@ -81,7 +83,19 @@ import {
foldHookFeatureValues,
type ProviderOptionsPatch,
} from "./option-controls.js";
import type { StoredAgentRecord, AgentStorage } from "./agent-storage.js";
import {
appendUniquePreviousSession,
type SerializableAgentConfig,
type StoredAgentRecord,
type AgentStorage,
} from "./agent-storage.js";
import {
buildProviderSwitchHandoff,
HANDOFF_TAIL_LIMIT,
prependHandoffAttachment,
promptHasChatHistoryAttachment,
renderProviderPromptText,
} from "./provider-switch/index.js";
import type { AgentOwner } from "./agent-owner.js";
import type {
AgentTimelineFetchOptions,
@@ -96,6 +110,7 @@ import {
type TimelinePrompts,
type TimelineEntry,
type TimelineIngestResult,
type TimelineProviderSwitchIntent,
type TimelineRetirementCommit,
type TimelineRewindIntent,
type TimelineScope,
@@ -171,6 +186,22 @@ function submittedPromptText(prompt: AgentPromptInput): string {
.trim();
}
function toSerializableAgentConfig(config: AgentSessionConfig): SerializableAgentConfig {
return {
...(config.modeId ? { modeId: config.modeId } : {}),
...(config.model ? { model: config.model } : {}),
...(config.thinkingOptionId ? { thinkingOptionId: config.thinkingOptionId } : {}),
...(config.providerOptions !== undefined ? { providerOptions: config.providerOptions } : {}),
...(config.toolPolicy
? {
toolPolicy: { preapproved: config.toolPolicy.preapproved.map((grant) => ({ ...grant })) },
}
: {}),
...(config.systemPrompt ? { systemPrompt: config.systemPrompt } : {}),
...(config.mcpServers ? { mcpServers: config.mcpServers } : {}),
};
}
export class AgentManagerShuttingDownError extends Error {
constructor() {
super("Agent manager is shutting down");
@@ -178,6 +209,38 @@ export class AgentManagerShuttingDownError extends Error {
}
}
/**
* Thrown when a provider switch committed (the live agent is now on the target provider)
* but starting the first turn on the new provider failed.
*/
export class AgentProviderSwitchStartError extends Error {
constructor(
readonly agent: ManagedAgent,
cause: unknown,
) {
super(cause instanceof Error ? cause.message : String(cause), { cause });
this.name = "AgentProviderSwitchStartError";
}
}
export interface SwitchAgentProviderInput {
toProvider: AgentProvider;
model?: string | null;
modeId?: string | null;
thinkingOptionId?: string | null;
providerOptions?: ProviderOptions | null;
prompt: AgentPromptInput;
messageId: string;
beforeDispatch?: () => Promise<void>;
}
export interface SwitchAgentProviderResult {
agent: ManagedAgent;
handoffPrompt: AgentPromptInput;
markerSeq: number;
context: ProviderSwitchContextSummary;
}
type RunCancellationCause = "reload" | "replace" | "rewind" | "stop";
export class AgentRunCancellationError extends Error {
@@ -921,6 +984,127 @@ export interface RetiredInternalAgent {
lastMessage: string | null;
}
function toPersistenceHandle(
stored: NonNullable<StoredAgentRecord["persistence"]>,
): AgentPersistenceHandle {
return {
provider: stored.provider,
sessionId: stored.sessionId,
...(stored.nativeHandle !== undefined ? { nativeHandle: stored.nativeHandle } : {}),
...(stored.metadata ? { metadata: stored.metadata } : {}),
};
}
function toResumeConfigFromStored(storedRecord: StoredAgentRecord): AgentSessionConfig {
return {
provider: storedRecord.provider,
cwd: storedRecord.cwd,
modeId: storedRecord.lastModeId ?? storedRecord.config?.modeId ?? undefined,
model: storedRecord.config?.model ?? undefined,
thinkingOptionId: storedRecord.config?.thinkingOptionId ?? undefined,
providerOptions: storedRecord.config?.providerOptions ?? undefined,
toolPolicy: storedRecord.config?.toolPolicy ?? undefined,
systemPrompt: storedRecord.config?.systemPrompt ?? undefined,
mcpServers: storedRecord.config?.mcpServers ?? undefined,
};
}
function toResumeOptionsFromStored(storedRecord: StoredAgentRecord) {
return {
createdAt: new Date(storedRecord.createdAt),
updatedAt: new Date(storedRecord.updatedAt),
lastUserMessageAt: storedRecord.lastUserMessageAt
? new Date(storedRecord.lastUserMessageAt)
: null,
labels: storedRecord.labels,
metadata: storedRecord.metadata,
workspaceId: storedRecord.workspaceId,
owner: storedRecord.owner,
background: storedRecord.background,
attention: extractAttention(storedRecord),
};
}
function buildSwitchTargetSessionConfig(
input: SwitchAgentProviderInput,
source: {
cwd: string;
baseConfig: Partial<AgentSessionConfig> | StoredAgentRecord["config"] | undefined;
internal: boolean;
persistedTitle: string | null;
},
): AgentSessionConfig {
return stripInternalPaseoMcpServer({
provider: input.toProvider,
cwd: source.cwd,
...(input.model ? { model: input.model } : {}),
...(input.modeId ? { modeId: input.modeId } : {}),
...(input.thinkingOptionId ? { thinkingOptionId: input.thinkingOptionId } : {}),
...(input.providerOptions ? { providerOptions: input.providerOptions } : {}),
...(source.baseConfig?.toolPolicy ? { toolPolicy: source.baseConfig.toolPolicy } : {}),
...(source.baseConfig?.systemPrompt ? { systemPrompt: source.baseConfig.systemPrompt } : {}),
...(source.baseConfig?.mcpServers ? { mcpServers: source.baseConfig.mcpServers } : {}),
...(source.internal ? { internal: true } : {}),
...(source.persistedTitle ? { title: source.persistedTitle } : {}),
});
}
function buildInitialRegisterPersistOptions(
title: string | null,
previousSessions: AgentPersistenceHandle[] | undefined,
): { title: string | null; previousSessions?: AgentPersistenceHandle[] } {
return previousSessions !== undefined ? { title, previousSessions } : { title };
}
function extractSwitchSourceFromLive(
live: ActiveManagedAgent,
storedRecord: StoredAgentRecord | null,
) {
return {
fromProvider: live.provider,
fromPersistence: live.persistence ?? null,
fromModel: live.runtimeInfo?.model ?? live.config.model ?? null,
cwd: live.cwd,
workspaceId: live.workspaceId,
labels: live.labels,
metadata: live.metadata,
owner: live.owner,
background: live.background,
launchEnv: live.launchEnv,
createdAt: live.createdAt,
lastUserMessageAt: live.lastUserMessageAt,
baseConfig: live.config as Partial<AgentSessionConfig>,
internal: Boolean(live.internal || storedRecord?.internal),
titleCandidate: live.config.title ?? storedRecord?.title ?? undefined,
storedTitle: storedRecord?.title ?? null,
};
}
function extractSwitchSourceFromStored(storedRecord: StoredAgentRecord) {
return {
fromProvider: storedRecord.provider,
fromPersistence: storedRecord.persistence
? toPersistenceHandle(storedRecord.persistence)
: null,
fromModel: storedRecord.runtimeInfo?.model ?? storedRecord.config?.model ?? null,
cwd: storedRecord.cwd,
workspaceId: storedRecord.workspaceId,
labels: storedRecord.labels ?? {},
metadata: storedRecord.metadata ?? {},
owner: storedRecord.owner,
background: storedRecord.background ?? false,
launchEnv: storedRecord.launchEnv,
createdAt: new Date(storedRecord.createdAt),
lastUserMessageAt: storedRecord.lastUserMessageAt
? new Date(storedRecord.lastUserMessageAt)
: null,
baseConfig: storedRecord.config ?? undefined,
internal: Boolean(storedRecord.internal),
titleCandidate: storedRecord.title ?? undefined,
storedTitle: storedRecord.title ?? null,
};
}
export class AgentManager {
private readonly pluginLifecycle: PluginLifecycle | undefined;
private readonly retiredInternalAgents = new Map<
@@ -963,6 +1147,10 @@ export class AgentManager {
private readonly collectingRuntimes = new Set<string>();
private readonly lifecycleMutationTails = new Map<string, Promise<void>>();
private readonly pendingCancellations = new Map<string, Promise<unknown>>();
private readonly pendingSubmittedPrompts = new Map<
string,
{ displayText: string; providerPromptText: string }
>();
private readonly agentStreamCoalescer: AgentStreamCoalescer;
private mcpBaseUrl: string | null;
private readonly mcpAuthToken: string | null;
@@ -2012,11 +2200,360 @@ export class AgentManager {
): Promise<ManagedAgent> {
return this.trackAgentRegistrationOperation(
this.runLifecycleMutation(agentId, async () => {
await this.reconcilePendingProviderSwitchUnlocked(agentId);
return (await this.reloadSession(agentId, overrides)).agent;
}),
);
}
/**
* Reconciles any open durable provider-switch intent left behind by a crash or partial failure.
* Safe to call before loading a stored agent or inspecting its history.
*/
async reconcilePendingProviderSwitch(agentId: string): Promise<void> {
const scope: TimelineScope = { agentId };
const head = await this.timeline.describe(scope);
if (!head?.providerSwitch) return;
await this.runLifecycleMutation(agentId, () =>
this.reconcilePendingProviderSwitchUnlocked(agentId),
);
}
private async reconcilePendingProviderSwitchUnlocked(agentId: string): Promise<void> {
const scope: TimelineScope = { agentId };
const head = await this.timeline.describe(scope);
const intent = head?.providerSwitch;
if (!intent) return;
if (intent.phase === "preparing") {
await this.timeline.abandonProviderSwitch(scope, intent.id);
return;
}
if (this.registry) {
const record = await this.registry.get(agentId);
if (record) {
const previousSessions = appendUniquePreviousSession(
record.previousSessions,
intent.fromPersistence,
);
const repaired: StoredAgentRecord = {
...record,
provider: intent.toProvider,
config: intent.toConfig ?? null,
lastModeId: intent.toConfig?.modeId ?? null,
persistence: intent.targetPersistence ?? null,
...(previousSessions ? { previousSessions } : {}),
controls: undefined,
runtimeInfo: undefined,
sessionMetrics: undefined,
lastStatus: "closed",
updatedAt: new Date().toISOString(),
};
await this.registry.upsert(repaired);
}
}
await this.timeline.completeProviderSwitch(scope, intent.id);
}
/**
* Switches an existing Paseo agent to a fresh session on a different provider under the same
* `agentId`, preserving visible history, recording a durable `provider_switch` marker, and
* returning the handoff-enriched prompt for turn 1 on the new provider.
*/
switchAgentProvider(
agentId: string,
input: SwitchAgentProviderInput,
): Promise<SwitchAgentProviderResult> {
const resolvedAgentId = validateAgentId(agentId, "switchAgentProvider");
return this.trackAgentRegistrationOperation(
this.runLifecycleMutation(resolvedAgentId, () =>
this.switchAgentProviderUnlocked(resolvedAgentId, input),
),
);
}
private async ensureSourceAgentReadyForSwitch(
agentId: string,
scope: TimelineScope,
storedRecord: StoredAgentRecord | null,
): Promise<ActiveManagedAgent | null> {
if (storedRecord?.archivedAt) {
throw new Error(`Agent is archived: ${agentId}`);
}
const existingLive = this.agents.get(agentId) ?? null;
if (existingLive) {
if (this.hasInFlightRun(agentId) || existingLive.activeForegroundTurnId) {
throw new AgentTurnBusyError(`Cannot switch provider while agent ${agentId} is running`);
}
if (existingLive.pendingPermissions.size > 0) {
throw new Error(
`Cannot switch provider while agent ${agentId} has pending permission requests`,
);
}
await this.settleOpenRewind(existingLive, { judge: false });
return existingLive;
}
if (!storedRecord) {
throw new AgentNotFoundError(agentId);
}
return await this.prepareDormantAgentForSwitch(agentId, scope, storedRecord);
}
private async prepareDormantAgentForSwitch(
agentId: string,
scope: TimelineScope,
storedRecord: StoredAgentRecord,
): Promise<ActiveManagedAgent | null> {
const existingHead = await this.timeline.describe(scope);
if (existingHead?.rewind) {
if (!existingHead.rewind.cut) {
throw new RewindOutcomeUnknownError();
}
const completion = await this.timeline.completeRewind(scope, existingHead.rewind.id, {
publish: (commit) => this.publishRetirement(agentId, commit),
});
if (completion.kind === "unpublished") {
this.logger.error(
{ err: completion.error, agentId },
"Failed to publish committed rewind before provider switch",
);
}
return null;
}
if (existingHead) {
return null;
}
if (!storedRecord.persistence) {
await this.timeline.open(scope);
return null;
}
const handle = toPersistenceHandle(storedRecord.persistence);
await this.resumeAgentFromPersistenceInternal(
handle,
toResumeConfigFromStored(storedRecord),
agentId,
toResumeOptionsFromStored(storedRecord),
);
return this.requireSessionAgent(agentId);
}
private async extractSwitchSourceContext(
agentId: string,
existingLive: ActiveManagedAgent | null,
storedRecord: StoredAgentRecord | null,
) {
const raw = existingLive
? extractSwitchSourceFromLive(existingLive, storedRecord)
: extractSwitchSourceFromStored(storedRecord!);
const persistedTitle = await this.resolveInitialPersistedTitle(
agentId,
{
provider: raw.fromProvider,
cwd: raw.cwd,
title: raw.titleCandidate,
},
raw.storedTitle,
);
return {
...raw,
persistedTitle,
};
}
private async closeLiveSessionForSwitch(
existingLive: ActiveManagedAgent | null,
agentId: string,
): Promise<void> {
if (!existingLive) return;
await this.closeReloadedSession(existingLive.session, agentId);
await this.drainSessionEvents(agentId);
await this.cancelRunningProviderSubagents(agentId);
this.clearProviderBackgroundWork(agentId);
await this.prepareAgentForClosure(existingLive, "provider switched");
}
private async switchAgentProviderUnlocked(
agentId: string,
input: SwitchAgentProviderInput,
): Promise<SwitchAgentProviderResult> {
this.assertAcceptingAgentRegistrations();
await this.reconcilePendingProviderSwitchUnlocked(agentId);
const scope: TimelineScope = { agentId };
const storedRecord = this.registry ? await this.registry.get(agentId) : null;
const existingLive = await this.ensureSourceAgentReadyForSwitch(agentId, scope, storedRecord);
const source = await this.extractSwitchSourceContext(agentId, existingLive, storedRecord);
if (input.toProvider === source.fromProvider) {
throw new Error(`Agent ${agentId} is already using provider '${input.toProvider}'`);
}
this.requireEnabledProvider(input.toProvider);
const targetClient = await this.requireAvailableClient({ provider: input.toProvider });
const tail = await this.timeline.fetch(scope, {
direction: "tail",
limit: HANDOFF_TAIL_LIMIT,
wholeTurns: true,
});
const handoff = buildProviderSwitchHandoff({
rows: tail.rows,
hasOlder: tail.hasOlder,
fromProvider: source.fromProvider,
toProvider: input.toProvider,
agentTitle: source.persistedTitle,
cwd: source.cwd,
});
const targetConfig = buildSwitchTargetSessionConfig(input, source);
const hadPreviousPaseoToolPolicy = this.paseoToolPolicies.has(agentId);
const previousPaseoToolPolicy = this.paseoToolPolicies.get(agentId);
const { storedConfig, launchConfig, paseoToolPolicy } = await this.prepareSessionConfig(
targetConfig,
agentId,
{ env: source.launchEnv },
);
let targetSession: AgentSession | undefined;
let intent: TimelineProviderSwitchIntent | null = null;
let committed = false;
let handedToRegistration = false;
try {
this.paseoToolPolicies.set(agentId, paseoToolPolicy);
const launchContext = await this.buildLaunchContext(
agentId,
targetClient,
storedConfig.cwd,
paseoToolPolicy,
source.launchEnv,
{
reason: "create",
purpose: "interactive",
workspaceId: source.workspaceId ?? null,
title: source.persistedTitle,
background: source.background,
labels: source.labels,
metadata: source.metadata,
},
);
const providerLaunchConfig = this.resolveProviderLaunchConfig(launchConfig, launchContext);
const launchedOptions = this.launchOptionsFor({
client: targetClient,
own: storedConfig.providerOptions,
});
targetSession = await targetClient.createSession(providerLaunchConfig, launchContext);
await this.requireExternalMcpSupport(targetSession, providerLaunchConfig, launchContext);
const targetRuntimeInfo = await targetSession.getRuntimeInfo().catch(() => undefined);
const targetPersistence = normalizePersistenceForConfig(
targetSession.describePersistence(),
storedConfig,
);
intent = await this.timeline.beginProviderSwitch(scope, {
messageId: input.messageId,
fromProvider: source.fromProvider,
fromPersistence: source.fromPersistence,
fromModel: source.fromModel,
toProvider: input.toProvider,
toConfig: toSerializableAgentConfig(storedConfig),
targetPersistence,
context: handoff.summary,
});
await this.closeLiveSessionForSwitch(existingLive, agentId);
this.assertAcceptingAgentRegistrations();
await input.beforeDispatch?.();
const markerItem: ProviderSwitchTimelineItem = {
type: "provider_switch",
fromProvider: source.fromProvider,
toProvider: input.toProvider,
fromModel: source.fromModel,
toModel: targetRuntimeInfo?.model ?? storedConfig.model ?? null,
fromSessionId: source.fromPersistence?.sessionId ?? null,
toSessionId: targetPersistence?.sessionId ?? null,
context: handoff.summary,
};
const commitResult = await this.timeline.commitProviderSwitch(scope, intent.id, {
markerEntry: { provider: input.toProvider, item: markerItem },
targetPersistence,
publish: (commit) =>
this.publishTimelineEvent(
agentId,
{ type: "timeline", item: markerItem, provider: input.toProvider },
commit,
),
});
if (commitResult.kind === "absent") {
throw new Error(`Provider switch intent '${intent.id}' disappeared before commit`);
}
if (commitResult.kind === "unpublished") {
this.logger.error(
{ err: commitResult.error, agentId },
"Failed to publish committed provider switch marker",
);
}
committed = true;
const previousSessions = appendUniquePreviousSession(
storedRecord?.previousSessions,
source.fromPersistence,
);
handedToRegistration = true;
const switchedAgent = await this.registerSession(targetSession, storedConfig, agentId, {
launchedOptions,
labels: source.labels,
metadata: source.metadata,
workspaceId: source.workspaceId,
owner: source.owner,
background: source.background,
launchEnv: source.launchEnv,
createdAt: source.createdAt,
updatedAt: new Date(),
lastUserMessageAt: source.lastUserMessageAt,
initialTitle: source.persistedTitle,
previousSessions,
restoring: true,
});
await this.timeline.completeProviderSwitch(scope, intent.id);
return {
agent: switchedAgent,
handoffPrompt: prependHandoffAttachment(input.prompt, handoff.attachment),
markerSeq: commitResult.row.seq,
context: handoff.summary,
};
} catch (error) {
if (!committed && intent) {
await this.timeline.abandonProviderSwitch(scope, intent.id).catch(() => undefined);
}
throw error;
} finally {
if (!handedToRegistration) {
this.restoreToolPolicyOnSwitchFailure(
agentId,
hadPreviousPaseoToolPolicy,
previousPaseoToolPolicy,
);
if (targetSession) {
await this.closeUnregisteredSession(targetSession);
}
}
}
}
private restoreToolPolicyOnSwitchFailure(
agentId: string,
hadPrevious: boolean,
previous: ProviderPaseoToolsPolicy | undefined,
): void {
if (hadPrevious) {
this.paseoToolPolicies.set(agentId, previous);
} else {
this.paseoToolPolicies.delete(agentId);
}
}
private async reloadSession(
agentId: string,
overrides?: Partial<AgentSessionConfig>,
@@ -3374,6 +3911,65 @@ export class AgentManager {
});
}
private async maybeAttachEmptySegmentHandoff(
agent: ActiveManagedAgent,
prompt: AgentPromptInput,
): Promise<AgentPromptInput> {
if (promptHasChatHistoryAttachment(prompt)) return prompt;
const scope: TimelineScope = { agentId: agent.id };
const head = await this.timeline.describe(scope);
if (!head || head.activeSegmentStartSeq <= 0) return prompt;
const { rows: promptRows } = await this.timeline.readPrompts(scope);
const hasAcceptedSegmentPrompt = promptRows.some(
(row) =>
row.seqStart > head.activeSegmentStartSeq &&
(!row.rejected || row.providerMessageId !== undefined),
);
if (hasAcceptedSegmentPrompt) return prompt;
const beforePage = await this.timeline.fetch(scope, {
direction: "before",
cursor: { epoch: head.epoch, seq: head.activeSegmentStartSeq },
limit: HANDOFF_TAIL_LIMIT,
wholeTurns: true,
});
const markerPage = await this.timeline.fetch(scope, {
direction: "before",
cursor: { epoch: head.epoch, seq: head.activeSegmentStartSeq + 1 },
limit: 1,
});
const markerRow = markerPage.rows.find((r) => r.seqStart === head.activeSegmentStartSeq);
const fromProvider =
markerRow?.item.type === "provider_switch" ? markerRow.item.fromProvider : agent.provider;
const stored = this.registry ? await this.registry.get(agent.id) : null;
const handoff = buildProviderSwitchHandoff({
rows: beforePage.rows,
hasOlder: beforePage.hasOlder,
fromProvider,
toProvider: agent.provider,
agentTitle: stored?.title ?? agent.config.title ?? null,
cwd: agent.cwd,
});
return prependHandoffAttachment(prompt, handoff.attachment);
}
private trackPendingSubmittedPrompt(
options: AgentRunOptions | undefined,
effectivePrompt: AgentPromptInput,
): void {
if (!options?.clientMessageId) return;
this.pendingSubmittedPrompts.set(options.clientMessageId, {
displayText: submittedPromptText(effectivePrompt),
providerPromptText: renderProviderPromptText(effectivePrompt),
});
}
private clearPendingSubmittedPrompt(options: AgentRunOptions | undefined): void {
if (options?.clientMessageId) {
this.pendingSubmittedPrompts.delete(options.clientMessageId);
}
}
private async startPendingForegroundTurn(params: {
agent: ActiveManagedAgent;
agentId: string;
@@ -3381,27 +3977,38 @@ export class AgentManager {
prompt: AgentPromptInput;
options?: AgentRunOptions;
promptStart?: ForegroundPromptStart;
}): Promise<string | null> {
}): Promise<{ turnId: string; effectivePrompt: AgentPromptInput } | null> {
const { agent, agentId, pendingRun, prompt, options, promptStart } = params;
if (promptStart?.admit?.() === false) {
this.runs.settleForegroundRun(agentId, pendingRun.token);
return null;
}
let effectivePrompt = prompt;
try {
// A rewind still open from an earlier failure must settle before the conversation moves on.
await this.settleOpenRewind(agent, { judge: false });
const result = await agent.session.startTurn(prompt, options);
effectivePrompt = await this.maybeAttachEmptySegmentHandoff(agent, prompt);
this.trackPendingSubmittedPrompt(options, effectivePrompt);
const result = await agent.session.startTurn(effectivePrompt, options);
if (pendingRun.settled) {
this.clearPendingSubmittedPrompt(options);
throw new Error(`Agent ${agentId} run was canceled before its turn started`);
}
return result.turnId;
return { turnId: result.turnId, effectivePrompt };
} catch (error) {
this.clearPendingSubmittedPrompt(options);
if (error instanceof AgentTurnStartCanceledError) {
if (!pendingRun.settled) {
if (options?.clientMessageId) {
await this.recordSubmittedPrompt(agent, prompt, options.clientMessageId, "rejected", {
messageId: options.clientMessageId,
});
await this.recordSubmittedPrompt(
agent,
effectivePrompt,
options.clientMessageId,
"rejected",
{
messageId: options.clientMessageId,
},
);
}
await this.handleStreamEvent(agent, {
type: "turn_canceled",
@@ -3433,9 +4040,15 @@ export class AgentManager {
try {
// A terminal rejection belongs after the submitted prompt even though no provider turn exists.
if (options?.clientMessageId) {
await this.recordSubmittedPrompt(agent, prompt, options.clientMessageId, "rejected", {
messageId: options.clientMessageId,
});
await this.recordSubmittedPrompt(
agent,
effectivePrompt,
options.clientMessageId,
"rejected",
{
messageId: options.clientMessageId,
},
);
}
await this.handleStreamEvent(agent, {
type: "turn_failed",
@@ -3583,9 +4196,8 @@ export class AgentManager {
promptStart?.bind(pendingRun);
const streamForwarder = async function* streamForwarder(this: AgentManager) {
let turnId: string | null;
let turnStream: ReturnType<AgentRunState["createTurnStream"]> | null = null;
turnId = await this.startPendingForegroundTurn({
const startedTurn = await this.startPendingForegroundTurn({
agent,
agentId,
pendingRun,
@@ -3593,7 +4205,7 @@ export class AgentManager {
options,
promptStart,
});
if (turnId === null) {
if (startedTurn === null) {
const canceledEvent: AgentStreamEvent = {
type: "turn_canceled",
provider: agent.provider,
@@ -3602,6 +4214,7 @@ export class AgentManager {
yield canceledEvent;
return;
}
const { turnId, effectivePrompt } = startedTurn;
if (isReplacement) {
agent.pendingReplacement = false;
@@ -3633,20 +4246,27 @@ export class AgentManager {
// Not awaited: the start is already settled, so awaiting would let live provider events
// run ahead of the staged ones below. The timeline commits writes in call order, and
// stream handling waits for it before publishing anything else.
const clientMessageId = options.clientMessageId;
const write = this.recordSubmittedPrompt(
agent,
prompt,
options.clientMessageId,
effectivePrompt,
clientMessageId,
"accepted",
{
messageId: options.clientMessageId,
messageId: clientMessageId,
turnId,
providerMessageId:
stagedSubmittedPromptEcho?.item.type === "user_message"
? stagedSubmittedPromptEcho.item.messageId
: undefined,
providerPromptText:
stagedSubmittedPromptEcho?.item.type === "user_message"
? stagedSubmittedPromptEcho.item.text
: renderProviderPromptText(effectivePrompt),
},
);
).finally(() => {
this.pendingSubmittedPrompts.delete(clientMessageId);
});
this.trackTimelineWrite(agent.id, write);
}
for (const stagedEvent of pendingRun.stagedEvents.splice(0)) {
@@ -4322,6 +4942,7 @@ export class AgentManager {
}
async rewind(agentId: string, messageId: string, mode: RewindMode): Promise<void> {
await this.reconcilePendingProviderSwitch(agentId);
let agent = this.requireSessionAgent(agentId);
if (this.historySessions.has(agent.session)) {
agent = await this.ensureInteractiveSession(agentId);
@@ -4791,6 +5412,7 @@ export class AgentManager {
launchedOptions: ProviderOptions;
restoring?: boolean;
initialTitle?: string | null;
previousSessions?: AgentPersistenceHandle[];
publishWhenReady?: boolean;
workspaceId?: string;
owner?: AgentOwner;
@@ -4866,9 +5488,10 @@ export class AgentManager {
}
await this.refreshRuntimeInfo(managed, { emit: false });
this.assertAgentRegistrationActive(managed);
await this.persistSnapshot(managed, {
title: initialPersistedTitle,
});
await this.persistSnapshot(
managed,
buildInitialRegisterPersistOptions(initialPersistedTitle, options?.previousSessions),
);
this.assertAgentRegistrationActive(managed);
if (!options?.publishWhenReady) {
this.emitState(managed, { persist: false });
@@ -5337,7 +5960,11 @@ export class AgentManager {
private async persistSnapshot(
agent: ManagedAgent,
options?: { title?: string | null; internal?: boolean },
options?: {
title?: string | null;
internal?: boolean;
previousSessions?: AgentPersistenceHandle[];
},
): Promise<void> {
if (!this.registry) {
return;
@@ -5983,6 +6610,8 @@ export class AgentManager {
turnId?: string,
options?: {
providerMessageId?: string;
providerPromptText?: string;
rejected?: boolean;
notifyWaiters?: boolean;
onRecorded?: () => void;
},
@@ -6000,6 +6629,10 @@ export class AgentManager {
provider,
...(turnId !== undefined ? { turnId } : {}),
...(options?.providerMessageId ? { providerMessageId: options.providerMessageId } : {}),
...(options?.providerPromptText !== undefined
? { providerPromptText: options.providerPromptText }
: {}),
...(options?.rejected ? { rejected: true } : {}),
},
{
publish: (commit) => {
@@ -6115,7 +6748,12 @@ export class AgentManager {
prompt: AgentPromptInput,
clientMessageId: string,
outcome: "accepted" | "rejected",
options?: { messageId?: string; providerMessageId?: string; turnId?: string },
options?: {
messageId?: string;
providerMessageId?: string;
providerPromptText?: string;
turnId?: string;
},
): Promise<void> {
const items = projectAgentMessages({
type: "user_message",
@@ -6123,11 +6761,18 @@ export class AgentManager {
clientMessageId,
...(options?.messageId ? { messageId: options.messageId } : {}),
});
const providerPromptText = options?.providerPromptText ?? renderProviderPromptText(prompt);
const writes: Promise<void>[] = [];
for (const item of items) {
// Human attempts stay in history on rejection; delivery notifications require acceptance.
if (outcome === "rejected" && item.type !== "user_message") continue;
writes.push(this.recordSubmittedPromptItem(agent, item, options));
writes.push(
this.recordSubmittedPromptItem(agent, item, {
...options,
...(item.type === "user_message" ? { providerPromptText } : {}),
...(outcome === "rejected" ? { rejected: true } : {}),
}),
);
}
await Promise.all(writes);
}
@@ -6136,10 +6781,19 @@ export class AgentManager {
private recordSubmittedPromptItem(
agent: ActiveManagedAgent,
item: AgentTimelineItem,
options?: { providerMessageId?: string; turnId?: string },
options?: {
providerMessageId?: string;
providerPromptText?: string;
rejected?: boolean;
turnId?: string;
},
): Promise<void> {
return this.recordAndDispatchTimelineItem(agent.id, item, agent.provider, options?.turnId, {
...(options?.providerMessageId ? { providerMessageId: options.providerMessageId } : {}),
...(options?.providerPromptText !== undefined
? { providerPromptText: options.providerPromptText }
: {}),
...(options?.rejected ? { rejected: true } : {}),
onRecorded: () => {
this.touchUpdatedAt(agent);
if (item.type === "user_message") agent.lastUserMessageAt = new Date();
@@ -6158,11 +6812,17 @@ export class AgentManager {
const scope: TimelineScope = { agentId: agent.id };
const existing = await this.timeline.findSubmittedPrompt(scope, clientMessageId);
if (!existing) {
const pending = this.pendingSubmittedPrompts.get(clientMessageId);
await this.recordSubmittedPromptItem(
agent,
{ ...item, messageId: clientMessageId },
{
...item,
text: pending ? pending.displayText : item.text,
messageId: clientMessageId,
},
{
...(messageId ? { providerMessageId: messageId } : {}),
providerPromptText: item.text,
...(turnId ? { turnId } : {}),
},
);
@@ -6170,7 +6830,9 @@ export class AgentManager {
}
if (existing.item.type !== "user_message") return false;
if (messageId) {
await this.timeline.attachProviderMessageId(scope, clientMessageId, messageId);
await this.timeline.attachProviderMessageId(scope, clientMessageId, messageId, {
providerPromptText: item.text,
});
}
return true;
}
@@ -7,6 +7,8 @@ import type {
AgentTaskItem,
JsonValue,
ProviderOptions,
ProviderSwitchContextSummary,
ProviderSwitchTimelineItem,
ToolPolicy,
} from "@getpaseo/protocol/agent-types";
import type { AgentMessage } from "@getpaseo/protocol/agent-message";
@@ -26,6 +28,8 @@ export type {
AgentOptionToggleControl,
AgentProviderNotice,
AgentTaskItem,
ProviderSwitchContextSummary,
ProviderSwitchTimelineItem,
};
export type AgentProvider = string;
@@ -420,7 +424,8 @@ export type AgentTimelineItem =
message: string;
}
| CompactionTimelineItem
| PluginTimelineItem;
| PluginTimelineItem
| ProviderSwitchTimelineItem;
export type AgentStreamEvent =
| { type: "thread_started"; sessionId: string; provider: AgentProvider }
@@ -41,15 +41,14 @@ const SERIALIZABLE_CONFIG_SCHEMA = z
.nullable()
.optional();
const PERSISTENCE_HANDLE_SCHEMA = z
.object({
provider: z.string(),
sessionId: z.string(),
nativeHandle: z.any().optional(),
metadata: z.record(z.string(), z.any()).optional(),
})
.nullable()
.optional();
const PERSISTENCE_HANDLE_OBJECT_SCHEMA = z.object({
provider: z.string(),
sessionId: z.string(),
nativeHandle: z.any().optional(),
metadata: z.record(z.string(), z.any()).optional(),
});
const PERSISTENCE_HANDLE_SCHEMA = PERSISTENCE_HANDLE_OBJECT_SCHEMA.nullable().optional();
const RAW_STORED_AGENT_SCHEMA = z.object({
id: z.string(),
@@ -82,6 +81,7 @@ const RAW_STORED_AGENT_SCHEMA = z.object({
// COMPAT(featureValues): added in v0.15.0, remove after 2027-05-01. Read-only; becomes controls.
features: z.array(AgentFeatureSchema).optional(),
persistence: PERSISTENCE_HANDLE_SCHEMA,
previousSessions: z.array(PERSISTENCE_HANDLE_OBJECT_SCHEMA).optional(),
sessionMetrics: z.array(AgentMetricSchema).optional(),
lastError: z.string().nullable().optional(),
requiresAttention: z.boolean().optional(),
@@ -128,6 +128,75 @@ export function parseStoredAgentRecord(value: unknown): StoredAgentRecord {
return STORED_AGENT_SCHEMA.parse(value);
}
type StoredPersistenceHandle = z.infer<typeof PERSISTENCE_HANDLE_OBJECT_SCHEMA>;
/** Appends a prior persistence handle to `previousSessions`, deduplicating by provider + id. */
export function appendUniquePreviousSession(
previousSessions: readonly StoredPersistenceHandle[] | undefined,
handle: StoredPersistenceHandle | null | undefined,
): StoredPersistenceHandle[] | undefined {
const existing = previousSessions ? [...previousSessions] : [];
if (!handle) return existing.length > 0 ? existing : undefined;
const alreadyPresent = existing.some(
(entry) =>
entry.provider === handle.provider &&
entry.sessionId === handle.sessionId &&
entry.nativeHandle === handle.nativeHandle,
);
if (!alreadyPresent) existing.push(handle);
return existing;
}
function resolveSnapshotFields(
agent: ManagedAgent,
existing: StoredAgentRecord | null | undefined,
overrides: {
hasTitleOverride: boolean;
hasInternalOverride: boolean;
options?: { title?: string | null; internal?: boolean };
},
) {
const title = overrides.hasTitleOverride
? (overrides.options?.title ?? null)
: (existing?.title ?? null);
const internal = overrides.hasInternalOverride
? overrides.options?.internal
: (agent.internal ?? existing?.internal);
return { title, createdAt: existing?.createdAt, internal };
}
function mergeStoredAgentSnapshot(
agent: ManagedAgent,
existing: StoredAgentRecord | null | undefined,
overrides: {
hasTitleOverride: boolean;
hasInternalOverride: boolean;
hasPreviousSessionsOverride: boolean;
options?: {
title?: string | null;
internal?: boolean;
previousSessions?: StoredPersistenceHandle[];
};
},
): StoredAgentRecord {
const record = toStoredAgentRecord(agent, resolveSnapshotFields(agent, existing, overrides));
if (existing && existing.archivedAt !== undefined) {
record.archivedAt = existing.archivedAt;
}
if (existing?.background) {
record.background = true;
}
const previousSessions = overrides.hasPreviousSessionsOverride
? overrides.options?.previousSessions
: existing?.previousSessions;
if (previousSessions && previousSessions.length > 0) {
record.previousSessions = previousSessions;
}
record.resumeOnStartup =
Boolean(existing?.resumeOnStartup) && agent.lifecycle !== "idle" && agent.lifecycle !== "error";
return record;
}
export class AgentStorage {
private cache: Map<string, StoredAgentRecord> = new Map();
private pathById: Map<string, string> = new Map();
@@ -278,11 +347,13 @@ export class AgentStorage {
providerHandleId: string,
): Promise<StoredAgentRecord[]> {
await this.load();
const matchesHandle = (handle: StoredPersistenceHandle | null | undefined) =>
handle?.provider === provider &&
(handle.sessionId === providerHandleId || handle.nativeHandle === providerHandleId);
return Array.from(this.cache.values()).filter(
(record) =>
record.persistence?.provider === provider &&
(record.persistence.sessionId === providerHandleId ||
record.persistence.nativeHandle === providerHandleId),
matchesHandle(record.persistence) ||
(record.previousSessions?.some(matchesHandle) ?? false),
);
}
@@ -406,32 +477,27 @@ export class AgentStorage {
async applySnapshot(
agent: ManagedAgent,
options?: { title?: string | null; internal?: boolean },
options?: {
title?: string | null;
internal?: boolean;
previousSessions?: StoredPersistenceHandle[];
},
): Promise<void> {
await this.load();
const hasTitleOverride =
options !== undefined && Object.prototype.hasOwnProperty.call(options, "title");
const hasInternalOverride =
options !== undefined && Object.prototype.hasOwnProperty.call(options, "internal");
await this.queueRecordMutation(agent.id, (existing) => {
const record = toStoredAgentRecord(agent, {
title: hasTitleOverride ? (options?.title ?? null) : (existing?.title ?? null),
createdAt: existing?.createdAt,
internal: hasInternalOverride ? options?.internal : (agent.internal ?? existing?.internal),
});
// Preserve soft-delete/archive status across snapshot flushes. The
// projection runs inside the per-agent write queue so it cannot commit a
// stale pre-archive record after the archive mutation.
if (existing && existing.archivedAt !== undefined) {
record.archivedAt = existing.archivedAt;
}
// Background is fixed at creation; a runtime opened without it cannot clear it.
if (existing?.background) record.background = true;
record.resumeOnStartup =
existing?.resumeOnStartup && agent.lifecycle !== "idle" && agent.lifecycle !== "error";
return record;
});
const hasPreviousSessionsOverride =
options !== undefined && Object.prototype.hasOwnProperty.call(options, "previousSessions");
await this.queueRecordMutation(agent.id, (existing) =>
mergeStoredAgentSnapshot(agent, existing, {
hasTitleOverride,
hasInternalOverride,
hasPreviousSessionsOverride,
options,
}),
);
}
async setTitle(agentId: string, title: string): Promise<void> {
@@ -9,6 +9,13 @@ export interface AgentTimelineRow {
readonly provider?: AgentProvider;
readonly turnId?: string;
readonly providerMessageId?: string;
/**
* Daemon-internal provider-facing prompt text (e.g. including rendered attachments/handoff).
* Used for reload reconciliation; never emitted over the wire.
*/
readonly providerPromptText?: string;
/** True when a submitted prompt was rejected before the provider accepted any turn; never emitted over the wire. */
readonly rejected?: boolean;
/** Metrics of the turn this row carries the footer for. */
readonly turnMetrics?: AgentMetric[];
}
@@ -59,4 +66,6 @@ export interface AgentTimelineFetchResult {
retirements: TimelineRetirement[];
/** Retirements of this history so far. */
retirementCount: number;
/** Seq of the latest active provider_switch marker, or 0 if never switched. */
activeSegmentStartSeq: number;
}
@@ -0,0 +1,133 @@
import { describe, expect, it } from "vitest";
import type { ProjectedTimelineRow } from "../timeline-projection.js";
import {
buildProviderSwitchHandoff,
prependHandoffAttachment,
renderProviderPromptText,
} from "./index.js";
const TS = "2026-11-25T10:00:00.000Z";
function row(
seq: number,
item: ProjectedTimelineRow["item"],
provider = "claude",
): ProjectedTimelineRow {
return {
seq,
seqStart: seq,
seqEnd: seq,
sourceSeqRanges: [[seq, seq]],
timestamp: TS,
provider,
item,
collapsed: [],
};
}
describe("buildProviderSwitchHandoff", () => {
it("returns a null attachment and zero summary when there is no prior active history", () => {
const handoff = buildProviderSwitchHandoff({
rows: [],
hasOlder: false,
fromProvider: "claude",
toProvider: "codex",
agentTitle: "Refactor auth",
cwd: "/repo",
});
expect(handoff.attachment).toBeNull();
expect(handoff.summary).toEqual({
includedItems: 0,
truncated: false,
charCount: 0,
budgetChars: 100_000,
});
});
it("curates user messages, assistant messages, tool calls, and prior provider switches while omitting reasoning and errors", () => {
const handoff = buildProviderSwitchHandoff({
rows: [
row(1, { type: "user_message", text: "Fix the bug", messageId: "m1" }),
row(2, { type: "reasoning", text: "Internal chain of thought" }),
row(3, {
type: "tool_call",
callId: "c1",
name: "read_file",
status: "completed",
error: null,
detail: { type: "read", filePath: "src/app.ts" },
}),
row(4, { type: "assistant_message", text: "I found the issue in src/app.ts." }),
row(5, { type: "error", message: "Transient warning" }),
row(6, {
type: "provider_switch",
fromProvider: "claude",
toProvider: "opencode",
fromModel: "sonnet",
toModel: "gemini",
fromSessionId: "s1",
toSessionId: "s2",
context: { includedItems: 2, truncated: false, charCount: 100, budgetChars: 100_000 },
}),
],
hasOlder: false,
fromProvider: "opencode",
toProvider: "codex",
agentTitle: "Bug fix",
cwd: "/repo",
});
expect(handoff.attachment).not.toBeNull();
expect(handoff.attachment?.type).toBe("text");
expect(handoff.attachment?.mimeType).toBe("text/plain");
expect(handoff.attachment?.contextKind).toBe("chat_history");
expect(handoff.attachment?.text).toContain("<chat-history-summary>");
expect(handoff.attachment?.text).toContain("[User] Fix the bug");
expect(handoff.attachment?.text).toContain("[Assistant] I found the issue in src/app.ts.");
expect(handoff.attachment?.text).toContain("[Switched provider: claude -> opencode]");
expect(handoff.attachment?.text).not.toContain("Internal chain of thought");
expect(handoff.attachment?.text).not.toContain("Transient warning");
expect(handoff.summary.includedItems).toBe(4);
expect(handoff.summary.truncated).toBe(false);
expect(handoff.summary.omittedReasons).toBeUndefined();
expect(handoff.summary.charCount).toBe(handoff.attachment?.text.length);
});
it("marks tail_window_limit when hasOlder is true and char_budget when history exceeds budgetChars", () => {
const bigReply = "x".repeat(500);
const handoff = buildProviderSwitchHandoff({
rows: [
row(10, { type: "user_message", text: "First prompt in window", messageId: "m1" }),
row(11, { type: "assistant_message", text: bigReply }),
row(12, { type: "user_message", text: "Most recent prompt", messageId: "m2" }),
],
hasOlder: true,
fromProvider: "claude",
toProvider: "codex",
budgetChars: 350,
});
expect(handoff.attachment).not.toBeNull();
expect(handoff.attachment!.text.length).toBeLessThanOrEqual(350);
expect(handoff.attachment!.text).toContain("[Earlier chat history omitted]");
expect(handoff.attachment!.text).toContain("[User] Most recent prompt");
expect(handoff.summary.truncated).toBe(true);
expect(handoff.summary.omittedReasons).toEqual(["tail_window_limit", "char_budget"]);
expect(handoff.summary.includedItems).toBe(1);
});
it("prepends handoff attachment and renders providerPromptText including attachments", () => {
const attachment = {
type: "text" as const,
mimeType: "text/plain",
contextKind: "chat_history" as const,
title: "Chat history",
text: "<chat-history-summary>\n[User] hi\n</chat-history-summary>",
};
const combined = prependHandoffAttachment("Continue here", attachment);
expect(Array.isArray(combined)).toBe(true);
expect(renderProviderPromptText(combined)).toContain("<chat-history-summary>");
expect(renderProviderPromptText(combined)).toContain("Continue here");
});
});
@@ -0,0 +1,200 @@
import type { AgentAttachment } from "@getpaseo/protocol/messages";
import type {
AgentPromptInput,
AgentProvider,
AgentTimelineItem,
ProviderSwitchContextSummary,
} from "../agent-sdk-types.js";
import type { ProjectedTimelineRow } from "../timeline-projection.js";
import {
curateProjectedActivityEntries,
MAX_FORK_CONTEXT_CHARS,
type ActivityEntry,
} from "../activity-curator.js";
export const HANDOFF_TAIL_LIMIT = 80;
export const MAX_HANDOFF_CONTEXT_CHARS = MAX_FORK_CONTEXT_CHARS;
const MAX_HANDOFF_METADATA_CHARS = 1_000;
const HANDOFF_OMITTED_MARKER = "[Earlier chat history omitted]\n";
const HANDOFF_CONTEXT_KINDS: readonly AgentTimelineItem["type"][] = [
"user_message",
"assistant_message",
"tool_call",
"provider_switch",
];
type TextAgentAttachment = Extract<AgentAttachment, { type: "text" }>;
export interface ProviderSwitchHandoffResult {
attachment: TextAgentAttachment | null;
summary: ProviderSwitchContextSummary;
}
function trimMetadata(value: string | null | undefined): string | null {
const trimmed = value?.trim();
return trimmed ? trimmed.slice(0, MAX_HANDOFF_METADATA_CHARS) : null;
}
function wrapHandoffContextText(input: {
body: string;
fromProvider: AgentProvider;
toProvider: AgentProvider;
agentTitle?: string | null;
cwd?: string | null;
}): string {
const header = [
`Chat history from this Paseo conversation before switching from ${input.fromProvider} to ${input.toProvider}.`,
];
const agentTitle = trimMetadata(input.agentTitle);
const cwd = trimMetadata(input.cwd);
if (agentTitle) header.push(`Conversation: ${agentTitle}`);
if (cwd) header.push(`Directory: ${cwd}`);
return `<chat-history-summary>\n${header.join("\n")}\n\n${input.body}\n</chat-history-summary>`;
}
function fitHandoffEntries(
entries: readonly ActivityEntry[],
budget: number,
alreadyHasOlder: boolean,
): { body: string; includedItems: number; charBudgetTruncated: boolean } {
const prefix = alreadyHasOlder ? HANDOFF_OMITTED_MARKER : "";
const fullJoined = entries.map((entry) => entry.text).join("\n");
if (prefix.length + fullJoined.length <= budget) {
return {
body: prefix + fullJoined,
includedItems: entries.length,
charBudgetTruncated: false,
};
}
const selected: string[] = [];
let remaining = Math.max(0, budget - HANDOFF_OMITTED_MARKER.length);
for (let index = entries.length - 1; index >= 0; index--) {
const text = entries[index]!.text;
const size = text.length + (selected.length > 0 ? 1 : 0);
if (size > remaining) {
if (selected.length === 0 && remaining > 0) {
const marker = "\n[Message truncated]\n";
if (remaining > marker.length + 2) {
const available = remaining - marker.length;
const head = Math.ceil(available / 2);
selected.push(text.slice(0, head) + marker + text.slice(-(available - head)));
} else {
selected.push(text.slice(0, remaining));
}
}
break;
}
selected.push(text);
remaining -= size;
}
return {
body: HANDOFF_OMITTED_MARKER + selected.toReversed().join("\n"),
includedItems: selected.length,
charBudgetTruncated: true,
};
}
export function buildProviderSwitchHandoff(input: {
rows: readonly ProjectedTimelineRow[];
hasOlder: boolean;
fromProvider: AgentProvider;
toProvider: AgentProvider;
agentTitle?: string | null;
cwd?: string | null;
budgetChars?: number;
}): ProviderSwitchHandoffResult {
const budgetChars = input.budgetChars ?? MAX_HANDOFF_CONTEXT_CHARS;
const entries = curateProjectedActivityEntries(
input.rows.map((row) => row.item),
{
maxItems: 0,
labelAssistantMessages: true,
includeKinds: HANDOFF_CONTEXT_KINDS,
includeExternalToolInput: false,
},
);
if (entries.length === 0 && !input.hasOlder) {
return {
attachment: null,
summary: {
includedItems: 0,
truncated: false,
charCount: 0,
budgetChars,
},
};
}
const wrapperOverhead = wrapHandoffContextText({
body: "",
fromProvider: input.fromProvider,
toProvider: input.toProvider,
agentTitle: input.agentTitle,
cwd: input.cwd,
}).length;
const bodyBudget = Math.max(0, budgetChars - wrapperOverhead);
const fitted =
entries.length > 0
? fitHandoffEntries(entries, bodyBudget, input.hasOlder)
: { body: HANDOFF_OMITTED_MARKER.trimEnd(), includedItems: 0, charBudgetTruncated: false };
const omittedReasons: string[] = [];
if (input.hasOlder) omittedReasons.push("tail_window_limit");
if (fitted.charBudgetTruncated) omittedReasons.push("char_budget");
const text = wrapHandoffContextText({
body: fitted.body,
fromProvider: input.fromProvider,
toProvider: input.toProvider,
agentTitle: input.agentTitle,
cwd: input.cwd,
});
return {
attachment: {
type: "text",
mimeType: "text/plain",
contextKind: "chat_history",
title: "Chat history",
text,
},
summary: {
includedItems: fitted.includedItems,
truncated: omittedReasons.length > 0,
charCount: text.length,
budgetChars,
...(omittedReasons.length > 0 ? { omittedReasons } : {}),
},
};
}
export function promptHasChatHistoryAttachment(prompt: AgentPromptInput): boolean {
if (typeof prompt === "string") return false;
return prompt.some(
(block) =>
block.type === "text" && "contextKind" in block && block.contextKind === "chat_history",
);
}
export function prependHandoffAttachment(
prompt: AgentPromptInput,
attachment: TextAgentAttachment | null,
): AgentPromptInput {
if (!attachment) return prompt;
if (typeof prompt === "string") {
return [attachment, { type: "text", text: prompt }];
}
return [attachment, ...prompt];
}
export function renderProviderPromptText(prompt: AgentPromptInput): string {
if (typeof prompt === "string") return prompt;
return prompt
.flatMap((block) => (block.type === "text" ? [block.text] : []))
.join("\n\n")
.trim();
}
@@ -0,0 +1,9 @@
export {
buildProviderSwitchHandoff,
HANDOFF_TAIL_LIMIT,
MAX_HANDOFF_CONTEXT_CHARS,
prependHandoffAttachment,
promptHasChatHistoryAttachment,
renderProviderPromptText,
type ProviderSwitchHandoffResult,
} from "./handoff-context.js";
@@ -0,0 +1,548 @@
import { randomUUID } from "node:crypto";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, it, onTestFinished } from "vitest";
import { createTestLogger } from "../../../test-utils/test-logger.js";
import { AgentManager, AgentProviderSwitchStartError } from "../agent-manager.js";
import { AgentStorage } from "../agent-storage.js";
import { ensureAgentLoaded } from "../agent-loading.js";
import { startAgentRun } from "../agent-prompt.js";
import { createStoredAgentTimeline } from "../timeline/index.js";
import { openTestTimelineDatabase } from "../timeline/testing.js";
import type {
AgentClient,
AgentPersistenceHandle,
AgentPromptInput,
AgentProvider,
AgentRunOptions,
AgentRunResult,
AgentSession,
AgentSessionConfig,
AgentStreamEvent,
ConversationRewindResult,
} from "../agent-sdk-types.js";
import { renderProviderPromptText } from "./index.js";
const BASE_CAPABILITIES = {
supportsStreaming: true,
supportsSessionPersistence: true,
supportsDynamicModes: false,
supportsMcpServers: true,
supportsReasoningStream: false,
supportsToolInvocations: true,
supportsRewindConversation: true,
supportsRewindFiles: false,
supportsRewindBoth: false,
} as const;
class FakeSession implements AgentSession {
readonly id: string;
readonly provider: AgentProvider;
readonly capabilities = BASE_CAPABILITIES;
readonly receivedPrompts: Array<{ prompt: AgentPromptInput; options?: AgentRunOptions }> = [];
closed = false;
private listeners = new Set<(event: AgentStreamEvent) => void>();
private persistence: AgentPersistenceHandle | null;
private turnCount = 0;
private readonly onStartTurn?: (
session: FakeSession,
prompt: AgentPromptInput,
options?: AgentRunOptions,
) => Promise<void> | void;
private readonly persistAfterFirstTurn: boolean;
private readonly echoBeforeStartResolves: boolean;
constructor(params: {
id: string;
provider: AgentProvider;
initialPersistence: AgentPersistenceHandle | null;
persistAfterFirstTurn?: boolean;
echoBeforeStartResolves?: boolean;
onStartTurn?: (
session: FakeSession,
prompt: AgentPromptInput,
options?: AgentRunOptions,
) => Promise<void> | void;
}) {
this.id = params.id;
this.provider = params.provider;
this.persistence = params.initialPersistence;
this.persistAfterFirstTurn = params.persistAfterFirstTurn ?? false;
this.echoBeforeStartResolves = params.echoBeforeStartResolves ?? false;
this.onStartTurn = params.onStartTurn;
}
emit(event: AgentStreamEvent): void {
for (const listener of this.listeners) listener(event);
}
subscribe(listener: (event: AgentStreamEvent) => void): () => void {
this.listeners.add(listener);
return () => this.listeners.delete(listener);
}
async startTurn(
prompt: AgentPromptInput,
options?: AgentRunOptions,
): Promise<{ turnId: string }> {
this.receivedPrompts.push({ prompt, options });
if (this.onStartTurn) {
await this.onStartTurn(this, prompt, options);
}
this.turnCount += 1;
const turnId = `${this.provider}-turn-${this.turnCount}`;
const providerMessageId = `${this.provider}-msg-${this.turnCount}`;
if (this.persistAfterFirstTurn && !this.persistence) {
this.persistence = { provider: this.provider, sessionId: `${this.provider}-late-${this.id}` };
}
const rendered = renderProviderPromptText(prompt);
const emitTurn = () => {
if (options?.clientMessageId) {
this.emit({
type: "timeline",
provider: this.provider,
turnId,
item: {
type: "user_message",
text: rendered,
messageId: providerMessageId,
clientMessageId: options.clientMessageId,
},
});
}
this.emit({
type: "timeline",
provider: this.provider,
turnId,
item: {
type: "assistant_message",
text: `${this.provider} reply ${this.turnCount}`,
},
});
this.emit({
type: "turn_completed",
provider: this.provider,
turnId,
});
};
if (this.echoBeforeStartResolves) {
emitTurn();
} else {
queueMicrotask(emitTurn);
}
return { turnId };
}
async run(prompt: AgentPromptInput, options?: AgentRunOptions): Promise<AgentRunResult> {
await this.startTurn(prompt, options);
return { sessionId: this.id, finalText: "", timeline: [] };
}
async *stream(): AsyncGenerator<AgentStreamEvent> {}
async *streamHistory(): AsyncGenerator<AgentStreamEvent> {}
async revertConversation(): Promise<ConversationRewindResult> {
return { kind: "after", retainedMessageId: null };
}
async interrupt(): Promise<void> {}
async getAvailableModes() {
return [];
}
async getCurrentMode() {
return null;
}
async setMode() {}
async getRuntimeInfo() {
return {
provider: this.provider,
sessionId: this.persistence?.sessionId ?? null,
model: `${this.provider}-model`,
};
}
describePersistence(): AgentPersistenceHandle | null {
return this.persistence;
}
async close(): Promise<void> {
this.closed = true;
}
}
class FakeClient implements AgentClient {
readonly capabilities = BASE_CAPABILITIES;
readonly createdSessions: FakeSession[] = [];
resumeCalls = 0;
available = true;
failNextCreate: Error | null = null;
initialPersistenceNull = false;
persistAfterFirstTurn = false;
echoBeforeStartResolves = false;
onStartTurn?: (
session: FakeSession,
prompt: AgentPromptInput,
options?: AgentRunOptions,
) => Promise<void> | void;
constructor(readonly provider: AgentProvider) {}
async isAvailable(): Promise<boolean> {
return this.available;
}
async createSession(_config: AgentSessionConfig): Promise<AgentSession> {
if (this.failNextCreate) {
const error = this.failNextCreate;
this.failNextCreate = null;
throw error;
}
const id = `${this.provider}-sess-${this.createdSessions.length + 1}`;
const session = new FakeSession({
id,
provider: this.provider,
initialPersistence: this.initialPersistenceNull
? null
: { provider: this.provider, sessionId: id },
persistAfterFirstTurn: this.persistAfterFirstTurn,
echoBeforeStartResolves: this.echoBeforeStartResolves,
onStartTurn: this.onStartTurn,
});
this.createdSessions.push(session);
return session;
}
async resumeSession(handle: AgentPersistenceHandle): Promise<AgentSession> {
this.resumeCalls += 1;
const session = new FakeSession({
id: handle.sessionId,
provider: this.provider,
initialPersistence: handle,
onStartTurn: this.onStartTurn,
});
this.createdSessions.push(session);
return session;
}
}
function createHarness() {
const dir = mkdtempSync(join(tmpdir(), "paseo-switch-test-"));
onTestFinished(() => rmSync(dir, { recursive: true, force: true }));
const cwd = mkdtempSync(join(tmpdir(), "paseo-switch-cwd-"));
onTestFinished(() => rmSync(cwd, { recursive: true, force: true }));
const logger = createTestLogger();
const db = openTestTimelineDatabase();
const timeline = createStoredAgentTimeline(db);
const storage = new AgentStorage(dir, logger);
const claude = new FakeClient("claude");
const codex = new FakeClient("codex");
const manager = new AgentManager({
logger,
registry: storage,
timeline,
clients: { claude, codex },
});
onTestFinished(async () => {
await manager.flush().catch(() => undefined);
await timeline.close().catch(() => undefined);
});
return { dir, cwd, logger, db, timeline, storage, claude, codex, manager };
}
async function runAndWaitIdle(
manager: AgentManager,
agentId: string,
prompt: AgentPromptInput,
clientMessageId: string,
): Promise<void> {
const logger = createTestLogger();
const idle = new Promise<void>((resolve) => {
const unsub = manager.subscribe(
(event) => {
if (event.type === "agent_state" && event.agent.lifecycle === "idle") {
unsub();
resolve();
}
},
{ agentId, replayState: false },
);
});
const dispatch = await startAgentRun(manager, agentId, prompt, logger, {
runOptions: { clientMessageId },
});
if (dispatch.disposition === "turn_started") {
await dispatch.started;
}
await idle;
await manager.flush();
}
describe("AgentManager provider switching", () => {
it("switches a live agent to a provider with null initial persistence, preserves history, keeps <chat-history-summary> out of item.text, and tracks previousSessions", async () => {
const { cwd, manager, storage, timeline, claude, codex } = createHarness();
// Simulate Codex/Claude returning persistence: null until turn 1 runs
codex.initialPersistenceNull = true;
codex.persistAfterFirstTurn = true;
const agentId = randomUUID();
const created = await manager.createAgent(
{ provider: "claude", cwd, title: "Auth refactor" },
agentId,
{ workspaceId: "ws-1", labels: { team: "core" }, metadata: { ticket: "P-1" } },
);
await runAndWaitIdle(manager, created.id, "Analyze auth.ts", "msg-c1");
const switched = await manager.switchAgentProvider(created.id, {
toProvider: "codex",
model: "gpt-5.4",
prompt: "Now rewrite it cleanly",
messageId: "msg-sw1",
});
expect(switched.agent.id).toBe(agentId);
expect(switched.agent.provider).toBe("codex");
expect(switched.agent.workspaceId).toBe("ws-1");
expect(switched.agent.labels).toEqual({ team: "core" });
expect(switched.agent.metadata).toEqual({ ticket: "P-1" });
expect(claude.createdSessions[0]!.closed).toBe(true);
// Marker persisted with toSessionId: null (since codex had null persistence before turn 1)
const rowsBeforeTurn1 = await timeline.readRows({ agentId });
const marker = rowsBeforeTurn1.find((r) => r.item.type === "provider_switch");
expect(marker?.item).toMatchObject({
type: "provider_switch",
fromProvider: "claude",
toProvider: "codex",
fromSessionId: "claude-sess-1",
toSessionId: null,
});
// Run turn 1 on Codex with the handoffPrompt
await runAndWaitIdle(manager, agentId, switched.handoffPrompt, "msg-sw1");
// Codex received the handoff attachment + user prompt
const codexPrompt1 = codex.createdSessions[0]!.receivedPrompts[0]!.prompt;
expect(renderProviderPromptText(codexPrompt1)).toContain("<chat-history-summary>");
expect(renderProviderPromptText(codexPrompt1)).toContain("Analyze auth.ts");
// Stored timeline rows: earlier rows keep provider "claude", switch prompt keeps clean item.text!
const allRows = await timeline.readRows({ agentId });
const claudePrompt = allRows.find(
(r) => r.item.type === "user_message" && r.item.messageId === "msg-c1",
);
const codexPrompt = allRows.find(
(r) => r.item.type === "user_message" && r.item.messageId === "msg-sw1",
);
expect(claudePrompt?.provider).toBe("claude");
expect(codexPrompt?.provider).toBe("codex");
expect(codexPrompt?.item).toMatchObject({
type: "user_message",
text: "Now rewrite it cleanly",
});
expect(codexPrompt?.item.type === "user_message" ? codexPrompt.item.text : "").not.toContain(
"<chat-history-summary>",
);
expect(codexPrompt?.providerPromptText).toContain("<chat-history-summary>");
// previousSessions tracks Claude's handle and listByProviderSession finds the agent
const stored = await storage.get(agentId);
expect(stored?.provider).toBe("codex");
expect(stored?.previousSessions).toEqual([
expect.objectContaining({ provider: "claude", sessionId: "claude-sess-1" }),
]);
const foundByOldSession = await storage.listByProviderSession("claude", "claude-sess-1");
expect(foundByOldSession.map((r) => r.id)).toEqual([agentId]);
});
it("keeps the original session live and leaves no switch marker when target creation fails", async () => {
const { cwd, manager, timeline, claude, codex } = createHarness();
const created = await manager.createAgent({ provider: "claude", cwd }, randomUUID(), {});
await runAndWaitIdle(manager, created.id, "Hello", "msg-1");
codex.failNextCreate = new Error("codex CLI failed to start");
await expect(
manager.switchAgentProvider(created.id, {
toProvider: "codex",
prompt: "Switch now",
messageId: "msg-2",
}),
).rejects.toThrow("codex CLI failed to start");
// Claude session is still live and usable, and no marker or open switch intent exists
expect(manager.getAgent(created.id)?.provider).toBe("claude");
expect(claude.createdSessions[0]!.closed).toBe(false);
expect((await timeline.describe({ agentId: created.id }))?.providerSwitch).toBeNull();
expect((await timeline.describe({ agentId: created.id }))?.activeSegmentStartSeq).toBe(0);
await runAndWaitIdle(manager, created.id, "Still on Claude", "msg-3");
expect(claude.createdSessions[0]!.receivedPrompts).toHaveLength(2);
});
it("switches a closed agent directly from SQLite history without booting the old provider", async () => {
const { cwd, manager, claude, codex } = createHarness();
const created = await manager.createAgent({ provider: "claude", cwd }, randomUUID(), {});
await runAndWaitIdle(manager, created.id, "Stored turn", "msg-1");
await manager.closeAgent(created.id);
expect(manager.getAgent(created.id)).toBeNull();
const switched = await manager.switchAgentProvider(created.id, {
toProvider: "codex",
prompt: "Continue on Codex",
messageId: "msg-2",
});
expect(switched.agent.provider).toBe("codex");
expect(claude.resumeCalls).toBe(0);
expect(renderProviderPromptText(switched.handoffPrompt)).toContain("Stored turn");
expect(codex.createdSessions).toHaveLength(1);
});
it("heals crash recovery for marker_committed with null targetPersistence through ensureAgentLoaded and re-injects context on turn 1", async () => {
const { cwd, manager, storage, timeline, logger, codex } = createHarness();
codex.initialPersistenceNull = true;
const created = await manager.createAgent({ provider: "claude", cwd }, randomUUID(), {});
await runAndWaitIdle(manager, created.id, "Before crash", "msg-1");
await manager.closeAgent(created.id);
// Simulate a crash right after commitProviderSwitch (marker_committed) before StoredAgentRecord updated!
const intent = await timeline.beginProviderSwitch(
{ agentId: created.id },
{
messageId: "msg-crash-sw",
fromProvider: "claude",
fromPersistence: { provider: "claude", sessionId: "claude-sess-1" },
fromModel: "claude-model",
toProvider: "codex",
toConfig: { model: "gpt-5.4", modeId: "auto" },
targetPersistence: null,
context: { includedItems: 2, truncated: false, charCount: 80, budgetChars: 100_000 },
},
);
await timeline.commitProviderSwitch({ agentId: created.id }, intent.id, {
markerEntry: {
provider: "codex",
item: {
type: "provider_switch",
fromProvider: "claude",
toProvider: "codex",
fromModel: "claude-model",
toModel: "gpt-5.4",
fromSessionId: "claude-sess-1",
toSessionId: null,
context: { includedItems: 2, truncated: false, charCount: 80, budgetChars: 100_000 },
},
},
targetPersistence: null,
});
// StoredAgentRecord on disk is still stale (points to claude with claude persistence & runtimeInfo)
const staleRecord = await storage.get(created.id);
expect(staleRecord?.provider).toBe("claude");
// ensureAgentLoaded reconciles the committed switch and opens Codex cleanly via createAgentFromRecord
const loaded = await ensureAgentLoaded(created.id, {
agentManager: manager,
agentStorage: storage,
logger,
});
expect(loaded.provider).toBe("codex");
expect((await timeline.describe({ agentId: created.id }))?.providerSwitch).toBeNull();
const repairedRecord = await storage.get(created.id);
expect(repairedRecord?.provider).toBe("codex");
expect(repairedRecord?.previousSessions).toEqual([
expect.objectContaining({ provider: "claude", sessionId: "claude-sess-1" }),
]);
// First prompt sent after crash recovery automatically receives fresh pre-switch context!
await runAndWaitIdle(manager, created.id, "First prompt after recovery", "msg-after-crash");
const delivered = renderProviderPromptText(
codex.createdSessions[0]!.receivedPrompts[0]!.prompt,
);
expect(delivered).toContain("<chat-history-summary>");
expect(delivered).toContain("Before crash");
expect(delivered).toContain("First prompt after recovery");
// Second prompt in the same segment does NOT double-inject context
await runAndWaitIdle(manager, created.id, "Second prompt", "msg-after-crash-2");
const delivered2 = renderProviderPromptText(
codex.createdSessions[0]!.receivedPrompts[1]!.prompt,
);
expect(delivered2).not.toContain("<chat-history-summary>");
});
it("re-injects fresh pre-switch context after rewinding turn 1 and after a rejected turn 1, and prevents <chat-history-summary> leak on early echo race", async () => {
const { cwd, manager, timeline, codex } = createHarness();
// Simulate early echo race (provider echoes user_message before startTurn resolves!)
codex.echoBeforeStartResolves = true;
const created = await manager.createAgent({ provider: "claude", cwd }, randomUUID(), {});
await runAndWaitIdle(manager, created.id, "Claude context turn", "msg-c1");
let failFirstCodexTurn = true;
codex.onStartTurn = () => {
if (failFirstCodexTurn) {
failFirstCodexTurn = false;
throw new Error("Transient Codex start error");
}
};
const switched = await manager.switchAgentProvider(created.id, {
toProvider: "codex",
prompt: "Attempt 1",
messageId: "msg-sw1",
});
// Turn 1 rejects before Codex accepts -> rejected user_message recorded
const logger = createTestLogger();
await expect(
(async () => {
const dispatch = await startAgentRun(manager, created.id, switched.handoffPrompt, logger, {
runOptions: { clientMessageId: "msg-sw1" },
});
if (dispatch.disposition === "turn_started") await dispatch.started;
})(),
).rejects.toThrow("Transient Codex start error");
await manager.flush();
// Retry with a fresh messageId (no attachment passed by caller) -> auto-reinjects fresh context!
await runAndWaitIdle(manager, created.id, "Attempt 2 succeeds", "msg-sw2");
const retryDelivered = renderProviderPromptText(
codex.createdSessions[0]!.receivedPrompts[1]!.prompt,
);
expect(retryDelivered).toContain("<chat-history-summary>");
expect(retryDelivered).toContain("Claude context turn");
// Early echo race MUST NOT leak <chat-history-summary> into item.text!
const rowsAfterRetry = await timeline.readRows({ agentId: created.id });
const retryRow = rowsAfterRetry.find(
(r) => r.item.type === "user_message" && r.item.messageId === "msg-sw2",
);
expect(retryRow?.item).toMatchObject({ type: "user_message", text: "Attempt 2 succeeds" });
expect(retryRow?.item.type === "user_message" ? retryRow.item.text : "").not.toContain(
"<chat-history-summary>",
);
expect(retryRow?.providerPromptText).toContain("<chat-history-summary>");
// Now rewind Attempt 2 (first accepted post-switch turn) -> pre-switch history & marker stay!
await manager.rewind(created.id, "msg-sw2", "conversation");
const rowsAfterRewind = await timeline.readRows({ agentId: created.id });
expect(rowsAfterRewind.some((r) => r.item.type === "provider_switch")).toBe(true);
expect(
rowsAfterRewind.some((r) => r.item.type === "user_message" && r.item.messageId === "msg-c1"),
).toBe(true);
// Sending a fresh prompt after rewinding turn 1 re-injects bounded pre-switch context!
await runAndWaitIdle(manager, created.id, "After rewind prompt", "msg-sw3");
const afterRewindDelivered = renderProviderPromptText(
codex.createdSessions[0]!.receivedPrompts[2]!.prompt,
);
expect(afterRewindDelivered).toContain("<chat-history-summary>");
expect(afterRewindDelivered).toContain("Claude context turn");
expect(afterRewindDelivered).toContain("After rewind prompt");
});
});
// Touch AgentProviderSwitchStartError to verify export
void AgentProviderSwitchStartError;
@@ -28,6 +28,8 @@ export interface TimelineProjectionEntry {
provider?: AgentProvider;
turnId?: string;
providerMessageId?: string;
providerPromptText?: string;
rejected?: boolean;
turnMetrics?: AgentMetric[];
timestamp: string;
seqStart: number;
@@ -144,6 +146,10 @@ function makeCanonicalEntries(rows: readonly AgentTimelineRow[]): WorkingEntry[]
...(row.provider ? { provider: row.provider } : {}),
...(row.turnId ? { turnId: row.turnId } : {}),
...(row.providerMessageId ? { providerMessageId: row.providerMessageId } : {}),
...(row.providerPromptText !== undefined
? { providerPromptText: row.providerPromptText }
: {}),
...(row.rejected ? { rejected: true } : {}),
...(row.turnMetrics ? { turnMetrics: row.turnMetrics } : {}),
seqStart: row.seq,
seqEnd: row.seq,
@@ -416,6 +422,7 @@ export class TimelineProjection {
private readonly retirements: TimelineRetirement[] = [];
private readonly retiredIdentities = new Set<string>();
private readonly retiredTurnIds = new Set<string>();
private activeSegmentStartSeq = 0;
constructor(rows: readonly AgentTimelineRow[] = []) {
for (const row of rows) this.appendProjected(row);
@@ -455,6 +462,9 @@ export class TimelineProjection {
return this.rows.length - 1;
}
const entry = fold.row;
if (entry.item.type === "provider_switch") {
this.resetProviderSegment(entry.seqStart);
}
if (identity !== null) this.identities.set(identity, this.rows.length);
this.rows.push(entry);
const last = this.spans.at(-1);
@@ -505,6 +515,25 @@ export class TimelineProjection {
return this.retiredIdentities.has(identity);
}
/**
* Starts a fresh provider segment at `markerSeq`. Tool-call live identities and retired keys from
* the closed previous provider session are cleared so IDs in the new session cannot collide.
*/
private resetProviderSegment(markerSeq: number): void {
this.activeSegmentStartSeq = markerSeq;
for (const [identity, rowIndex] of this.identities) {
if (this.rows[rowIndex]?.item.type === "tool_call") {
this.identities.delete(identity);
}
}
this.retiredIdentities.clear();
this.retiredTurnIds.clear();
}
getActiveSegmentStartSeq(): number {
return this.activeSegmentStartSeq;
}
/**
* Retires the active rows anchored at or after `retireFromSeq`. Rows are in anchor order, so they
* form the display suffix. Their source seqs and the retirement's own seq stay covered.
@@ -512,7 +541,9 @@ export class TimelineProjection {
retire(retirement: TimelineRetirement): ProjectedTimelineRow[] {
const cut = this.firstRowAnchoredAtOrAfter(retirement.retireFromSeq);
const retired = this.rows.splice(cut);
const activeTurnIds = new Set(this.rows.map((row) => row.turnId));
const activeTurnIds = new Set(
this.rows.filter((row) => row.seqStart > this.activeSegmentStartSeq).map((row) => row.turnId),
);
for (const row of retired) {
if (row.item.type === "tool_call") {
const identity = timelineItemIdentity(row.item);
@@ -782,12 +813,19 @@ export class TimelineProjection {
enrichSubmittedUserMessage(
clientMessageId: string,
providerMessageId: string,
options?: { providerPromptText?: string },
): ProjectedTimelineRow | null {
const index = this.rows.findIndex(
(row) => row.item.type === "user_message" && row.item.clientMessageId === clientMessageId,
);
if (index < 0) return null;
this.rows[index] = { ...this.rows[index], providerMessageId };
this.rows[index] = {
...this.rows[index],
providerMessageId,
...(options?.providerPromptText !== undefined
? { providerPromptText: options.providerPromptText }
: {}),
};
return { ...this.rows[index] };
}
@@ -818,11 +856,16 @@ export class TimelineProjection {
const tail = this.rows.length - 1;
if (tail < 0) return null;
if (turnId === undefined) return tail;
const index = this.rows.findLastIndex((row) => row.turnId === turnId);
const index = this.rows.findLastIndex(
(row) => row.seqStart > this.activeSegmentStartSeq && row.turnId === turnId,
);
if (index >= 0) return index;
// Rows replayed from provider history carry no turn id, so the turn is the
// trailing one. A tail owned by another turn means this turn wrote no rows.
return this.rows[tail].turnId === undefined ? tail : null;
return this.rows[tail].seqStart > this.activeSegmentStartSeq &&
this.rows[tail].turnId === undefined
? tail
: null;
}
}
@@ -229,7 +229,9 @@ describe.each(
seq: 1,
size: 1,
retirementCount: 0,
activeSegmentStartSeq: 0,
rewind: null,
providerSwitch: null,
});
await expect(timeline.readRows(child)).rejects.toBeInstanceOf(UnknownTimelineError);
});
@@ -5,8 +5,10 @@ import { SqliteTimelineBackend } from "./internal/sqlite-backend.js";
export {
AgentTimeline,
TimelineClosedError,
TimelineProviderSwitchPendingError,
TimelineRewindBoundaryError,
TimelineRewindPendingError,
TimelineRewindSegmentBoundaryError,
TimelineRewindTargetError,
type TimelineAppendResult,
type TimelineChild,
@@ -16,6 +18,8 @@ export {
type TimelineImportResult,
type TimelinePrompts,
type TimelineIngestResult,
type TimelineProviderSwitchCommit,
type TimelineProviderSwitchIntent,
type TimelineReconcileResult,
type TimelineRetirement,
type TimelineRetirementCommit,
@@ -1,6 +1,7 @@
import { randomUUID } from "node:crypto";
import type {
AgentMetric,
AgentPersistenceHandle,
AgentTimelineItem,
ConversationRewindCut,
} from "../../agent-sdk-types.js";
@@ -18,6 +19,7 @@ import type {
TimelineEntry,
TimelineHead,
TimelinePrompt,
TimelineProviderSwitchIntent,
TimelineRewindIntent,
TimelineScope,
TimelineSeed,
@@ -30,6 +32,7 @@ export type {
TimelineChild,
TimelineEntry,
TimelineHead,
TimelineProviderSwitchIntent,
TimelineRewindIntent,
TimelineScope,
TimelineSeed,
@@ -65,6 +68,13 @@ export type TimelineRewindCompletion =
/** No rewind with this id is open: it completed or was abandoned. Nothing changed. */
| { kind: "absent" };
export type TimelineProviderSwitchCommit =
| ({ kind: "committed"; activeSegmentStartSeq: number } & TimelineCommit)
/** Committed, but `publish` threw; see `TimelineIngestResult`. */
| ({ kind: "unpublished"; activeSegmentStartSeq: number; error: unknown } & TimelineCommit)
/** No switch with this id is open: it completed or was abandoned. Nothing changed. */
| { kind: "absent" };
/**
* What the provider's own history says about an open rewind, judged against the active prompts.
* `unknown` carries the reason the evidence does not decide it.
@@ -92,6 +102,13 @@ export class TimelineRewindPendingError extends Error {
}
}
export class TimelineProviderSwitchPendingError extends Error {
constructor(readonly intent: TimelineProviderSwitchIntent) {
super("Another provider switch of this conversation has not settled");
this.name = "TimelineProviderSwitchPendingError";
}
}
/** The rewind target is not an active prompt: it never existed or a rewind already retired it. */
export class TimelineRewindTargetError extends Error {
constructor(readonly messageId: string) {
@@ -100,6 +117,14 @@ export class TimelineRewindTargetError extends Error {
}
}
/** The rewind target belongs to a provider segment before the latest provider switch. */
export class TimelineRewindSegmentBoundaryError extends Error {
constructor(readonly messageId: string) {
super("Cannot rewind to a message from a previous provider segment");
this.name = "TimelineRewindSegmentBoundaryError";
}
}
/** The provider's cut does not resolve to a prompt at or before the target. */
export class TimelineRewindBoundaryError extends Error {
constructor(readonly intent: TimelineRewindIntent) {
@@ -140,7 +165,9 @@ export type TimelineReconcileResult =
/** The provider's history disagrees with the owned history, which is kept unchanged. */
| { kind: "diverged"; reason: string }
/** A rewind is open; it settles first. Nothing changed. */
| { kind: "rewind_open" };
| { kind: "rewind_open" }
/** A provider switch is open; it settles first. Nothing changed. */
| { kind: "provider_switch_open" };
export interface TimelineIngestOptions {
/**
@@ -242,10 +269,12 @@ export class AgentTimeline {
return this.run(scope, async () => {
const head = await this.requireHead(scope);
if (head.rewind) return { kind: "rewind_open" };
if (head.providerSwitch) return { kind: "provider_switch_open" };
const plan = planProviderHistory({
rows: await this.backendFor(scope).readRows(scope),
prompts: await this.prompts(scope),
provider: entries.map(providerHistoryEntry),
activeSegmentStartSeq: head.activeSegmentStartSeq,
});
if (plan.kind !== "append") return plan;
const commits = await this.commit(scope, plan.entries);
@@ -364,9 +393,15 @@ export class AgentTimeline {
scope: TimelineScope,
clientMessageId: string,
providerMessageId: string,
options?: { providerPromptText?: string },
): Promise<AgentTimelineRow | null> {
return this.run(scope, () =>
this.backendFor(scope).attachProviderMessageId(scope, clientMessageId, providerMessageId),
this.backendFor(scope).attachProviderMessageId(
scope,
clientMessageId,
providerMessageId,
options,
),
);
}
@@ -420,6 +455,97 @@ export class AgentTimeline {
return this.run(scope, () => this.backendFor(scope).lastAssistantMessage(scope));
}
/**
* Opens a durable provider-switch intent. Refused while a rewind or another switch is open.
*/
beginProviderSwitch(
scope: TimelineScope,
input: Omit<TimelineProviderSwitchIntent, "id" | "phase" | "markerSeq">,
): Promise<TimelineProviderSwitchIntent> {
return this.run(scope, async () => {
const head = await this.requireHead(scope);
if (head.rewind) throw new TimelineRewindPendingError(head.rewind);
if (head.providerSwitch) throw new TimelineProviderSwitchPendingError(head.providerSwitch);
const intent: TimelineProviderSwitchIntent = {
...input,
id: randomUUID(),
phase: "preparing",
};
await this.backendFor(scope).setProviderSwitch(scope, intent);
return intent;
});
}
/**
* Atomically appends the `provider_switch` marker, advances `activeSegmentStartSeq`, clears
* live tool-call identities and retired keys, and moves the intent to `marker_committed`.
*/
commitProviderSwitch(
scope: TimelineScope,
intentId: string,
options: {
markerEntry: TimelineEntry;
targetPersistence?: AgentPersistenceHandle | null;
publish?: (commit: TimelineCommit) => void;
},
): Promise<TimelineProviderSwitchCommit> {
return this.run(scope, async () => {
const head = await this.requireHead(scope);
const intent = head.providerSwitch;
if (intent?.id !== intentId) return { kind: "absent" };
const nextIntent: TimelineProviderSwitchIntent = {
...intent,
phase: "marker_committed",
...(options.targetPersistence !== undefined
? { targetPersistence: options.targetPersistence }
: {}),
};
const result = await this.backendFor(scope).commitProviderSwitch(scope, {
markerEntry: boundEntry(options.markerEntry),
nextIntent,
});
this.track(scope, result.head);
const commit: TimelineCommit = {
row: result.row,
epoch: result.head.epoch,
retirementCount: result.head.retirementCount,
};
const failure = publishCommitted(options.publish, commit);
return failure
? {
kind: "unpublished",
error: failure.error,
activeSegmentStartSeq: result.head.activeSegmentStartSeq,
...commit,
}
: {
kind: "committed",
activeSegmentStartSeq: result.head.activeSegmentStartSeq,
...commit,
};
});
}
/** Closes a committed provider switch once `StoredAgentRecord` has been updated. */
completeProviderSwitch(scope: TimelineScope, intentId: string): Promise<void> {
return this.run(scope, async () => {
const head = await this.requireHead(scope);
if (head.providerSwitch?.id === intentId) {
await this.backendFor(scope).setProviderSwitch(scope, null);
}
});
}
/** Closes an uncommitted (`preparing`) provider switch. History is unchanged. */
abandonProviderSwitch(scope: TimelineScope, intentId: string): Promise<void> {
return this.run(scope, async () => {
const head = await this.requireHead(scope);
if (head.providerSwitch?.id === intentId && head.providerSwitch.phase === "preparing") {
await this.backendFor(scope).setProviderSwitch(scope, null);
}
});
}
/**
* Opens a rewind to before the active prompt `messageId`. While it is open, `describe` reports it,
* and a second rewind is refused until this one completes or is abandoned.
@@ -428,8 +554,12 @@ export class AgentTimeline {
return this.run(scope, async () => {
const head = await this.requireHead(scope);
if (head.rewind) throw new TimelineRewindPendingError(head.rewind);
if (head.providerSwitch) throw new TimelineProviderSwitchPendingError(head.providerSwitch);
const target = (await this.prompts(scope)).find((prompt) => prompt.messageId === messageId);
if (!target) throw new TimelineRewindTargetError(messageId);
if (target.seqStart <= head.activeSegmentStartSeq) {
throw new TimelineRewindSegmentBoundaryError(messageId);
}
const intent: TimelineRewindIntent = {
id: randomUUID(),
messageId,
@@ -473,9 +603,14 @@ export class AgentTimeline {
providerPromptIds: readonly string[],
): Promise<TimelineRewindVerdict> {
return this.run(scope, async () => {
const intent = (await this.requireHead(scope)).rewind;
const head = await this.requireHead(scope);
const intent = head.rewind;
if (intent?.id !== intentId) return { kind: "absent" };
return judgeRewindEvidence(intent, await this.prompts(scope), providerPromptIds);
const segmentPrompts = activeSegmentPrompts(
await this.prompts(scope),
head.activeSegmentStartSeq,
);
return judgeRewindEvidence(intent, segmentPrompts, providerPromptIds);
});
}
@@ -493,8 +628,14 @@ export class AgentTimeline {
const intent = head.rewind;
if (intent?.id !== intentId) return { kind: "absent" };
if (!intent.cut) throw new Error("Cannot complete a rewind before its provider outcome");
const retireFromSeq = resolveRetireFromSeq(intent, await this.prompts(scope));
if (retireFromSeq === null) throw new TimelineRewindBoundaryError(intent);
const segmentPrompts = activeSegmentPrompts(
await this.prompts(scope),
head.activeSegmentStartSeq,
);
const retireFromSeq = resolveRetireFromSeq(intent, segmentPrompts);
if (retireFromSeq === null || retireFromSeq <= head.activeSegmentStartSeq) {
throw new TimelineRewindBoundaryError(intent);
}
const result = await this.backendFor(scope).retire(scope, {
retireFromSeq,
selectChildren: childrenSpawnedBy,
@@ -677,20 +818,41 @@ function judgeRewindEvidence(
};
}
/** The active prompts belonging to the current provider segment. */
function activeSegmentPrompts(
prompts: readonly TimelinePrompt[],
activeSegmentStartSeq: number,
): TimelinePrompt[] {
return activeSegmentStartSeq > 0
? prompts.filter((prompt) => prompt.seqStart > activeSegmentStartSeq)
: [...prompts];
}
/** The listed children that retired tool calls spawned, and their descendants. */
function childrenSpawnedBy(
retiredRows: readonly ProjectedTimelineRow[],
children: readonly TimelineChild[],
): string[] {
const toolCallIds = new Set(
retiredRows.flatMap((row) => (row.item.type === "tool_call" ? [row.item.callId] : [])),
);
const retiredToolCalls: Array<{ callId: string; provider: string | undefined }> = [];
for (const row of retiredRows) {
if (row.item.type === "tool_call") {
retiredToolCalls.push({ callId: row.item.callId, provider: row.provider });
}
}
const listed = children.flatMap((child) =>
!child.retired && child.descriptor ? [child.descriptor] : [],
);
const retired = new Set(
listed
.filter((child) => child.toolCallId !== null && toolCallIds.has(child.toolCallId))
.filter(
(child) =>
child.toolCallId !== null &&
retiredToolCalls.some(
(call) =>
call.callId === child.toolCallId &&
(call.provider === undefined || call.provider === child.provider),
),
)
.map((child) => child.id),
);
let grew = retired.size > 0;
@@ -1,9 +1,12 @@
import type {
AgentMetric,
AgentPersistenceHandle,
AgentProvider,
AgentTimelineItem,
ConversationRewindCut,
ProviderSwitchContextSummary,
} from "../../agent-sdk-types.js";
import type { SerializableAgentConfig } from "../../agent-storage.js";
import type {
AgentTimelineFetchOptions,
AgentTimelineFetchResult,
@@ -25,6 +28,8 @@ export interface TimelineEntry {
timestamp?: string;
turnId?: string;
providerMessageId?: string;
providerPromptText?: string;
rejected?: boolean;
turnMetrics?: AgentMetric[];
}
@@ -45,8 +50,33 @@ export interface TimelineHead {
size: number;
/** Rewinds applied since the history was created. */
retirementCount: number;
/** Seq of the latest active provider_switch marker, or 0 if never switched. */
activeSegmentStartSeq: number;
/** The rewind in progress, or one whose provider outcome is not settled yet. */
rewind: TimelineRewindIntent | null;
/** The provider switch in progress, or one whose record update is not settled yet. */
providerSwitch: TimelineProviderSwitchIntent | null;
}
/**
* A provider switch between its preparation start and final settlement.
* - `preparing`: target session is being swapped in; no marker is committed yet.
* - `marker_committed`: the `provider_switch` marker is committed in SQLite and `StoredAgentRecord`
* must reflect the target provider/config/persistence before the intent closes.
*/
export interface TimelineProviderSwitchIntent {
id: string;
/** The clientMessageId of the prompt that triggered this switch. */
messageId: string;
fromProvider: AgentProvider;
fromPersistence: AgentPersistenceHandle | null;
fromModel?: string | null;
toProvider: AgentProvider;
toConfig: SerializableAgentConfig;
targetPersistence?: AgentPersistenceHandle | null;
context: ProviderSwitchContextSummary;
phase: "preparing" | "marker_committed";
markerSeq?: number;
}
/**
@@ -103,6 +133,11 @@ export interface TimelineBackendRetireResult {
head: TimelineHead;
}
export interface TimelineBackendCommitProviderSwitchResult {
row: AgentTimelineRow;
head: TimelineHead;
}
export type MaybePromise<T> = T | Promise<T>;
/**
@@ -126,6 +161,21 @@ export interface AgentTimelineBackend {
/** Active user prompt rows in display order, read without the rest of the history. */
promptRows(scope: TimelineScope): MaybePromise<ProjectedTimelineRow[]>;
setRewind(scope: TimelineScope, rewind: TimelineRewindIntent | null): MaybePromise<TimelineHead>;
setProviderSwitch(
scope: TimelineScope,
providerSwitch: TimelineProviderSwitchIntent | null,
): MaybePromise<TimelineHead>;
/**
* Atomically appends the `provider_switch` marker, advances `activeSegmentStartSeq`, clears
* live tool-call identities and retired keys for the scope, and updates the switch intent.
*/
commitProviderSwitch(
scope: TimelineScope,
input: {
markerEntry: TimelineEntry;
nextIntent: TimelineProviderSwitchIntent | null;
},
): MaybePromise<TimelineBackendCommitProviderSwitchResult>;
/**
* Allocates the next sequence number for a retirement of the active rows anchored at or after
* `retireFromSeq`, marks the children `selectChildren` picks retired, and clears the rewind
@@ -145,6 +195,7 @@ export interface AgentTimelineBackend {
scope: TimelineScope,
clientMessageId: string,
providerMessageId: string,
options?: { providerPromptText?: string },
): MaybePromise<AgentTimelineRow | null>;
/** Records a completed turn's metrics on its footer row. Null when the turn has none. */
stampTurnMetrics(
@@ -16,6 +16,7 @@ export interface TimelinePageHistory {
minSeq: number;
nextSeq: number;
retirementCount: number;
activeSegmentStartSeq: number;
}
/**
@@ -74,5 +75,6 @@ export function fetchTimelinePage(input: {
),
retirements: page.retirements,
retirementCount: history.retirementCount,
activeSegmentStartSeq: history.activeSegmentStartSeq,
};
}
@@ -10,11 +10,13 @@ import type { ProviderSubagentDescriptor } from "../../provider-subagents/store.
import type {
AgentTimelineBackend,
TimelineBackendAppendResult,
TimelineBackendCommitProviderSwitchResult,
RetiredChildSelector,
TimelineBackendRetireResult,
TimelineChild,
TimelineEntry,
TimelineHead,
TimelineProviderSwitchIntent,
TimelineRewindIntent,
TimelineScope,
TimelineSeed,
@@ -32,6 +34,7 @@ interface MemoryTimelineState {
retired: ProjectedTimelineRow[];
retirementCount: number;
rewind: TimelineRewindIntent | null;
providerSwitch: TimelineProviderSwitchIntent | null;
/** Child scopes only. */
descriptor: ProviderSubagentDescriptor | null;
childRetired: boolean;
@@ -73,6 +76,7 @@ export class MemoryTimelineBackend implements AgentTimelineBackend {
retired: [],
retirementCount: 0,
rewind: null,
providerSwitch: null,
descriptor: null,
childRetired: false,
};
@@ -154,6 +158,34 @@ export class MemoryTimelineBackend implements AgentTimelineBackend {
return this.describe(state);
}
setProviderSwitch(
scope: TimelineScope,
providerSwitch: TimelineProviderSwitchIntent | null,
): TimelineHead {
const state = this.requireState(scope);
state.providerSwitch = providerSwitch ? structuredClone(providerSwitch) : null;
return this.describe(state);
}
commitProviderSwitch(
scope: TimelineScope,
input: {
markerEntry: TimelineEntry;
nextIntent: TimelineProviderSwitchIntent | null;
},
): TimelineBackendCommitProviderSwitchResult {
const state = this.requireState(scope);
const timestamp = new Date().toISOString();
const row = buildSourceRow(input.markerEntry, state.nextSeq, timestamp);
state.projection.append(row);
state.nextSeq = row.seq + 1;
if (state.minSeq === 0) state.minSeq = row.seq;
state.providerSwitch = input.nextIntent
? structuredClone({ ...input.nextIntent, markerSeq: row.seq })
: null;
return { row: cloneRow(row), head: this.describe(state) };
}
retire(
scope: TimelineScope,
input: { retireFromSeq: number; selectChildren: RetiredChildSelector },
@@ -188,10 +220,12 @@ export class MemoryTimelineBackend implements AgentTimelineBackend {
scope: TimelineScope,
clientMessageId: string,
providerMessageId: string,
options?: { providerPromptText?: string },
): AgentTimelineRow | null {
return this.requireState(scope).projection.enrichSubmittedUserMessage(
clientMessageId,
providerMessageId,
options,
);
}
@@ -218,7 +252,13 @@ export class MemoryTimelineBackend implements AgentTimelineBackend {
fetch(scope: TimelineScope, options: AgentTimelineFetchOptions): AgentTimelineFetchResult {
const state = this.requireState(scope);
return fetchTimelinePage({
history: state,
history: {
epoch: state.epoch,
minSeq: state.minSeq,
nextSeq: state.nextSeq,
retirementCount: state.retirementCount,
activeSegmentStartSeq: state.projection.getActiveSegmentStartSeq(),
},
options,
selectPage: (page) => state.projection.selectPage(page),
});
@@ -243,7 +283,9 @@ export class MemoryTimelineBackend implements AgentTimelineBackend {
seq: state.nextSeq - 1,
size: state.projection.size,
retirementCount: state.retirementCount,
activeSegmentStartSeq: state.projection.getActiveSegmentStartSeq(),
rewind: state.rewind ? { ...state.rewind } : null,
providerSwitch: state.providerSwitch ? structuredClone(state.providerSwitch) : null,
};
}
@@ -24,8 +24,16 @@ export function planProviderHistory(input: {
rows: readonly ProjectedTimelineRow[];
prompts: readonly TimelinePrompt[];
provider: readonly TimelineEntry[];
activeSegmentStartSeq?: number;
}): ProviderHistoryPlan {
const owned = ownedPrompts(input.rows, input.prompts);
const segmentStart = input.activeSegmentStartSeq ?? 0;
const segmentRows =
segmentStart > 0 ? input.rows.filter((row) => row.seqStart > segmentStart) : input.rows;
const segmentPrompts =
segmentStart > 0
? input.prompts.filter((prompt) => prompt.seqStart > segmentStart)
: input.prompts;
const owned = ownedPrompts(segmentRows, segmentPrompts);
const provider = providerPrompts(input.provider);
if ([...owned.prompts, ...provider].some((prompt) => prompt.id === undefined)) {
return { kind: "diverged", reason: "A prompt has no provider id" };
@@ -61,7 +69,10 @@ function ownedPrompts(
if (!prompt) continue;
trailingUndeliveredPrompt = prompt.submitted && !prompt.providerMessageId;
if (!trailingUndeliveredPrompt) {
acknowledged.push({ id: prompt.providerMessageId ?? prompt.messageId, text: row.item.text });
acknowledged.push({
id: prompt.providerMessageId ?? prompt.messageId,
text: row.providerPromptText ?? row.item.text,
});
}
}
return { prompts: acknowledged, trailingUndeliveredPrompt };
@@ -14,6 +14,10 @@ export function buildSourceRow(
...(entry.provider ? { provider: entry.provider } : {}),
...(entry.turnId ? { turnId: entry.turnId } : {}),
...(entry.providerMessageId ? { providerMessageId: entry.providerMessageId } : {}),
...(entry.providerPromptText !== undefined
? { providerPromptText: entry.providerPromptText }
: {}),
...(entry.rejected ? { rejected: true } : {}),
...(entry.turnMetrics ? { turnMetrics: entry.turnMetrics } : {}),
};
}
@@ -25,10 +25,12 @@ import type {
AgentTimelineBackend,
RetiredChildSelector,
TimelineBackendAppendResult,
TimelineBackendCommitProviderSwitchResult,
TimelineBackendRetireResult,
TimelineChild,
TimelineEntry,
TimelineHead,
TimelineProviderSwitchIntent,
TimelineRewindIntent,
TimelineScope,
TimelineSeed,
@@ -127,10 +129,18 @@ CREATE TABLE timeline_retired_keys (
);
`;
const SCHEMA_V2 = `
ALTER TABLE timeline_scopes ADD COLUMN provider_switch TEXT;
ALTER TABLE timeline_scopes ADD COLUMN active_segment_start_seq INTEGER NOT NULL DEFAULT 0;
`;
/** The timeline store's schema in the daemon database. */
export const timelineSchema: SchemaModule = {
name: "timeline",
migrations: [{ up: (sql) => sql.exec(SCHEMA_V1) }],
migrations: [
{ up: (sql) => sql.exec(SCHEMA_V1) },
{ breaking: true, up: (sql) => sql.exec(SCHEMA_V2) },
],
};
interface ScopeRecord {
@@ -142,6 +152,8 @@ interface ScopeRecord {
active_max_seq_end: number;
retirement_count: number;
rewind: string | null;
provider_switch: string | null;
active_segment_start_seq: number;
descriptor: string | null;
child_retired: number;
}
@@ -173,7 +185,7 @@ interface RetirementRecord {
const SCOPE_COLUMNS =
"id, epoch, next_seq, min_seq, active_count, active_max_seq_end, retirement_count, rewind, " +
"descriptor, child_retired";
"provider_switch, active_segment_start_seq, descriptor, child_retired";
const SHAPE_COLUMNS = "seq_start, turn_id, turn_trigger, item_type";
const ACTIVE = "scope_id = ? AND retired_by IS NULL";
@@ -262,6 +274,49 @@ export class SqliteTimelineBackend implements AgentTimelineBackend {
});
}
setProviderSwitch(
scope: TimelineScope,
providerSwitch: TimelineProviderSwitchIntent | null,
): TimelineHead {
return this.database.write((sql) => {
const record = requireScope(sql, scope);
record.provider_switch = providerSwitch ? JSON.stringify(providerSwitch) : null;
sql.run(
"UPDATE timeline_scopes SET provider_switch = ? WHERE id = ?",
record.provider_switch,
record.id,
);
return describe(record);
});
}
commitProviderSwitch(
scope: TimelineScope,
input: {
markerEntry: TimelineEntry;
nextIntent: TimelineProviderSwitchIntent | null;
},
): TimelineBackendCommitProviderSwitchResult {
return this.database.write((sql) => {
const record = requireScope(sql, scope);
const timestamp = new Date().toISOString();
const row = buildSourceRow(input.markerEntry, record.next_seq, timestamp);
foldSourceRow(sql, record, row);
record.next_seq = row.seq + 1;
if (record.min_seq === 0) record.min_seq = row.seq;
record.provider_switch = input.nextIntent
? JSON.stringify({ ...input.nextIntent, markerSeq: row.seq })
: null;
saveScopeCounters(sql, record);
sql.run(
"UPDATE timeline_scopes SET provider_switch = ? WHERE id = ?",
record.provider_switch,
record.id,
);
return { row, head: describe(record) };
});
}
retire(
scope: TimelineScope,
input: { retireFromSeq: number; selectChildren: RetiredChildSelector },
@@ -284,7 +339,10 @@ export class SqliteTimelineBackend implements AgentTimelineBackend {
if (row.item.type === "tool_call") {
addRetiredKey(sql, record.id, "identity", row.item.callId);
}
if (row.turnId !== undefined && !hasActiveTurn(sql, record.id, row.turnId)) {
if (
row.turnId !== undefined &&
!hasActiveTurn(sql, record.id, row.turnId, record.active_segment_start_seq)
) {
addRetiredKey(sql, record.id, "turn", row.turnId);
}
}
@@ -359,12 +417,19 @@ export class SqliteTimelineBackend implements AgentTimelineBackend {
scope: TimelineScope,
clientMessageId: string,
providerMessageId: string,
options?: { providerPromptText?: string },
): AgentTimelineRow | null {
return this.database.write((sql) => {
const { id } = requireScope(sql, scope);
const record = findSubmittedPromptRecord(sql, id, clientMessageId);
if (!record) return null;
const row = { ...parseRow(record), providerMessageId };
const row = {
...parseRow(record),
providerMessageId,
...(options?.providerPromptText !== undefined
? { providerPromptText: options.providerPromptText }
: {}),
};
saveRow(sql, id, row);
return row;
});
@@ -376,8 +441,8 @@ export class SqliteTimelineBackend implements AgentTimelineBackend {
options?: { turnId?: string },
): ProjectedTimelineRow | null {
return this.database.write((sql) => {
const { id } = requireScope(sql, scope);
const footer = turnFooterSeq(sql, id, options?.turnId);
const { id, active_segment_start_seq } = requireScope(sql, scope);
const footer = turnFooterSeq(sql, id, options?.turnId, active_segment_start_seq);
if (footer === null) return null;
const record = sql.get<RowRecord>(
"SELECT seq_start, item_type, row FROM timeline_rows WHERE scope_id = ? AND seq_start = ?",
@@ -407,6 +472,7 @@ export class SqliteTimelineBackend implements AgentTimelineBackend {
minSeq: record.min_seq,
nextSeq: record.next_seq,
retirementCount: record.retirement_count,
activeSegmentStartSeq: record.active_segment_start_seq,
},
options,
selectPage: (page) => new StoredPageSelection(sql, record).select(page),
@@ -475,7 +541,11 @@ function describe(record: ScopeRecord): TimelineHead {
seq: record.next_seq - 1,
size: record.active_count,
retirementCount: record.retirement_count,
activeSegmentStartSeq: record.active_segment_start_seq,
rewind: record.rewind ? (JSON.parse(record.rewind) as TimelineRewindIntent) : null,
providerSwitch: record.provider_switch
? (JSON.parse(record.provider_switch) as TimelineProviderSwitchIntent)
: null,
};
}
@@ -531,7 +601,9 @@ function createScope(sql: WriteSql, scope: TimelineScope, seed: TimelineSeed): S
);
const nextSeq = sourceRows.reduce((next, row) => Math.max(next, row.seq + 1), startSeq);
// A seed is already in memory; projecting it there reuses the projection's seeding rules.
const rows = new TimelineProjection(sourceRows).getRows();
const projection = new TimelineProjection(sourceRows);
const rows = projection.getRows();
const activeSegmentStartSeq = projection.getActiveSegmentStartSeq();
const record: ScopeRecord = {
id: 0,
epoch: seed.epoch ?? randomUUID(),
@@ -541,24 +613,30 @@ function createScope(sql: WriteSql, scope: TimelineScope, seed: TimelineSeed): S
active_max_seq_end: 0,
retirement_count: 0,
rewind: null,
provider_switch: null,
active_segment_start_seq: activeSegmentStartSeq,
descriptor: null,
child_retired: 0,
};
record.id = sql.get<{ id: number }>(
"INSERT INTO timeline_scopes (agent_id, subagent_id, epoch, next_seq, min_seq, " +
"active_count, active_max_seq_end, retirement_count) VALUES (?, ?, ?, ?, ?, ?, 0, 0) " +
"RETURNING id",
"active_count, active_max_seq_end, retirement_count, active_segment_start_seq) " +
"VALUES (?, ?, ?, ?, ?, ?, 0, 0, ?) RETURNING id",
scope.agentId,
scope.subagentId ?? null,
record.epoch,
record.next_seq,
record.min_seq,
record.active_count,
record.active_segment_start_seq,
)!.id;
const liveIdentityAt = new Map<string, number>();
for (const row of rows) {
const identity = timelineItemIdentity(row.item);
if (identity !== null) liveIdentityAt.set(identity, row.seqStart);
if (identity !== null) {
if (row.item.type === "tool_call" && row.seqStart <= activeSegmentStartSeq) continue;
liveIdentityAt.set(identity, row.seqStart);
}
}
const ranges: (TimelineSeqRange & { rowSeqStart: number })[] = [];
for (const row of rows) {
@@ -612,6 +690,15 @@ function foldSourceRow(sql: WriteSql, record: ScopeRecord, row: AgentTimelineRow
coverSourceSeq(sql, record, row.seq, fold.row);
return;
}
if (fold.row.item.type === "provider_switch") {
record.active_segment_start_seq = fold.row.seqStart;
sql.run(
"UPDATE timeline_rows SET identity_live = 0 " +
"WHERE scope_id = ? AND identity_live = 1 AND item_type = 'tool_call'",
record.id,
);
sql.run("DELETE FROM timeline_retired_keys WHERE scope_id = ?", record.id);
}
if (identity !== null) {
sql.run(
"UPDATE timeline_rows SET identity_live = 0 " +
@@ -680,12 +767,13 @@ function insertSourceRange(
function saveScopeCounters(sql: WriteSql, record: ScopeRecord): void {
sql.run(
"UPDATE timeline_scopes SET next_seq = ?, min_seq = ?, active_count = ?, " +
"active_max_seq_end = ?, retirement_count = ? WHERE id = ?",
"active_max_seq_end = ?, retirement_count = ?, active_segment_start_seq = ? WHERE id = ?",
record.next_seq,
record.min_seq,
record.active_count,
record.active_max_seq_end,
record.retirement_count,
record.active_segment_start_seq,
record.id,
);
}
@@ -847,11 +935,17 @@ function findSubmittedPromptRecord(
);
}
function hasActiveTurn(sql: ReadSql, scopeId: number, turnId: string): boolean {
function hasActiveTurn(
sql: ReadSql,
scopeId: number,
turnId: string,
activeSegmentStartSeq: number,
): boolean {
return (
sql.get(
`SELECT 1 FROM timeline_rows WHERE ${ACTIVE} AND turn_id = ? LIMIT 1`,
`SELECT 1 FROM timeline_rows WHERE ${ACTIVE} AND seq_start > ? AND turn_id = ? LIMIT 1`,
scopeId,
activeSegmentStartSeq,
turnId,
) !== undefined
);
@@ -889,7 +983,12 @@ function continuesShape(previous: RowShape, next: RowShape): boolean {
* The row a completed turn's metrics go on: the turn's last assistant message, else its last row
* when that row is a tool call. Mirrors `TimelineProjection.stampTurnMetrics`.
*/
function turnFooterSeq(sql: ReadSql, scopeId: number, turnId: string | undefined): number | null {
function turnFooterSeq(
sql: ReadSql,
scopeId: number,
turnId: string | undefined,
activeSegmentStartSeq: number,
): number | null {
const tail = sql.get<RowShape>(
`SELECT ${SHAPE_COLUMNS} FROM timeline_rows WHERE ${ACTIVE} ORDER BY seq_start DESC LIMIT 1`,
scopeId,
@@ -899,11 +998,12 @@ function turnFooterSeq(sql: ReadSql, scopeId: number, turnId: string | undefined
if (turnId !== undefined) {
last =
sql.get<RowShape>(
`SELECT ${SHAPE_COLUMNS} FROM timeline_rows WHERE ${ACTIVE} AND turn_id = ? ` +
`SELECT ${SHAPE_COLUMNS} FROM timeline_rows WHERE ${ACTIVE} AND seq_start > ? AND turn_id = ? ` +
"ORDER BY seq_start DESC LIMIT 1",
scopeId,
activeSegmentStartSeq,
turnId,
) ?? (tail.turn_id === null ? tail : undefined);
) ?? (tail.seq_start > activeSegmentStartSeq && tail.turn_id === null ? tail : undefined);
}
if (!last) return null;
let next: RowShape | undefined;
@@ -0,0 +1,486 @@
import { describe, expect, it } from "vitest";
import type { AgentTimelineItem, ProviderSwitchTimelineItem } from "../agent-sdk-types.js";
import type { ProviderSubagentDescriptor } from "../provider-subagents/store.js";
import {
DatabaseSchemaTooNewError,
openDaemonDatabase,
type DaemonDatabase,
type SchemaModule,
} from "../../database/index.js";
import { createTestLogger } from "../../../test-utils/test-logger.js";
import { nextTestDatabasePath } from "../../test-utils/test-database-path.js";
import {
AgentTimeline,
TimelineProviderSwitchPendingError,
TimelineRewindPendingError,
TimelineRewindSegmentBoundaryError,
createStoredAgentTimeline,
timelineSchema,
type TimelineEntry,
type TimelineProviderSwitchIntent,
type TimelineScope,
} from "./index.js";
import { SqliteTimelineBackend } from "./internal/sqlite-backend.js";
import { openTestTimelineDatabase, TIMELINE_CONTRACT_BACKENDS } from "./testing.js";
const scope: TimelineScope = { agentId: "agent-switch" };
const TS = "2026-11-25T10:00:00.000Z";
function switchMarker(fromProvider = "claude", toProvider = "codex"): ProviderSwitchTimelineItem {
return {
type: "provider_switch",
fromProvider,
toProvider,
fromModel: "claude-sonnet-4-6",
toModel: "gpt-5.4",
fromSessionId: "claude-sess-1",
toSessionId: null,
context: {
includedItems: 2,
truncated: false,
charCount: 120,
budgetChars: 100_000,
},
};
}
function switchIntent(
overrides: Partial<TimelineProviderSwitchIntent> = {},
): Omit<TimelineProviderSwitchIntent, "id" | "phase"> {
return {
messageId: "msg-switch-1",
fromProvider: "claude",
fromPersistence: { provider: "claude", sessionId: "claude-sess-1" },
fromModel: "claude-sonnet-4-6",
toProvider: "codex",
toConfig: { model: "gpt-5.4", modeId: "auto" },
targetPersistence: null,
context: {
includedItems: 2,
truncated: false,
charCount: 120,
budgetChars: 100_000,
},
...overrides,
};
}
function tool(callId: string, status: "running" | "completed", label = callId): AgentTimelineItem {
return {
type: "tool_call",
callId,
name: "shell",
status,
error: null,
detail: { type: "plain_text", label },
};
}
function childDescriptor(
id: string,
provider: string,
toolCallId: string,
): ProviderSubagentDescriptor {
return {
id,
parentAgentId: scope.agentId,
parentSubagentId: null,
provider,
title: id,
description: null,
status: "completed",
createdAt: TS,
updatedAt: TS,
toolCallId,
cwd: null,
subtitle: null,
};
}
function dumpTables(database: DaemonDatabase): Record<string, unknown[]> {
return database.read((sql) => {
const tables = sql
.all<{ name: string }>(
"SELECT name FROM sqlite_master WHERE type = 'table' AND name LIKE 'timeline_%' ORDER BY name",
)
.map((table) => table.name);
return Object.fromEntries(tables.map((table) => [table, sql.all(`SELECT * FROM ${table}`)]));
});
}
describe.each(TIMELINE_CONTRACT_BACKENDS)(
"provider switching timeline contract ($name)",
({ create }) => {
it("commits switch marker, scopes rewind to active segment, and protects pre-switch history on null retainedMessageId", async () => {
const timeline = new AgentTimeline(create());
await timeline.create(scope, { epoch: "ep-1" });
// Segment 1 (Claude)
await timeline.ingest(scope, {
provider: "claude",
turnId: "t1",
item: {
type: "user_message",
text: "First Claude prompt",
messageId: "c1",
clientMessageId: "c1",
},
});
await timeline.attachProviderMessageId(scope, "c1", "claude-p1");
await timeline.ingest(scope, {
provider: "claude",
turnId: "t1",
item: { type: "assistant_message", text: "Claude answer" },
});
const intent = await timeline.beginProviderSwitch(scope, switchIntent());
expect((await timeline.describe(scope))?.providerSwitch?.phase).toBe("preparing");
// Rewind refused while switch intent is open
await expect(timeline.beginRewind(scope, "c1")).rejects.toThrow(
TimelineProviderSwitchPendingError,
);
const committed = await timeline.commitProviderSwitch(scope, intent.id, {
markerEntry: { provider: "codex", item: switchMarker("claude", "codex") },
});
expect(committed.kind).toBe("committed");
if (committed.kind !== "committed") return;
const markerSeq = committed.row.seq;
const headAfterCommit = await timeline.describe(scope);
expect(headAfterCommit?.activeSegmentStartSeq).toBe(markerSeq);
expect(headAfterCommit?.providerSwitch?.phase).toBe("marker_committed");
expect(headAfterCommit?.providerSwitch?.markerSeq).toBe(markerSeq);
await timeline.completeProviderSwitch(scope, intent.id);
expect((await timeline.describe(scope))?.providerSwitch).toBeNull();
// Segment 2 (Codex)
await timeline.ingest(scope, {
provider: "codex",
turnId: "t1",
providerPromptText:
"<chat-history-summary>...</chat-history-summary>\n\nFirst Codex prompt",
item: {
type: "user_message",
text: "First Codex prompt",
messageId: "c2",
clientMessageId: "c2",
},
});
await timeline.attachProviderMessageId(scope, "c2", "codex-p1", {
providerPromptText:
"<chat-history-summary>...</chat-history-summary>\n\nFirst Codex prompt",
});
await timeline.ingest(scope, {
provider: "codex",
turnId: "t1",
item: { type: "assistant_message", text: "Codex answer" },
});
const page = await timeline.fetch(scope, { direction: "tail", limit: 20 });
expect(page.activeSegmentStartSeq).toBe(markerSeq);
// Rewinding pre-switch prompt is refused
await expect(timeline.beginRewind(scope, "c1")).rejects.toThrow(
TimelineRewindSegmentBoundaryError,
);
// Rewinding first post-switch prompt with retainedMessageId: null retires ONLY segment 2
const rewind = await timeline.beginRewind(scope, "c2");
await timeline.recordRewindCut(scope, rewind.id, { kind: "after", retainedMessageId: null });
const completion = await timeline.completeRewind(scope, rewind.id);
expect(completion.kind).toBe("retired");
if (completion.kind !== "retired") return;
expect(completion.retirement.retireFromSeq).toBeGreaterThan(markerSeq);
const remaining = await timeline.readRows(scope);
expect(remaining.map((r) => r.item.type)).toEqual([
"user_message",
"assistant_message",
"provider_switch",
]);
});
it("judges open rewind and reconciles provider history strictly within the active segment using providerPromptText", async () => {
const timeline = new AgentTimeline(create());
await timeline.create(scope, { epoch: "ep-1" });
// Segment 1 (Claude)
await timeline.ingest(scope, {
provider: "claude",
item: {
type: "user_message",
text: "Claude prompt",
messageId: "c1",
clientMessageId: "c1",
},
});
await timeline.attachProviderMessageId(scope, "c1", "claude-p1");
const intent = await timeline.beginProviderSwitch(scope, switchIntent());
await timeline.commitProviderSwitch(scope, intent.id, {
markerEntry: { provider: "codex", item: switchMarker("claude", "codex") },
});
await timeline.completeProviderSwitch(scope, intent.id);
// Segment 2 (Codex) with attachment-bearing handoff prompt + second prompt
const handoffRendered =
"<chat-history-summary>\nctx\n</chat-history-summary>\n\nSwitch prompt";
await timeline.ingest(scope, {
provider: "codex",
providerPromptText: handoffRendered,
item: {
type: "user_message",
text: "Switch prompt",
messageId: "c2",
clientMessageId: "c2",
},
});
await timeline.attachProviderMessageId(scope, "c2", "codex-p1", {
providerPromptText: handoffRendered,
});
await timeline.ingest(scope, {
provider: "codex",
item: { type: "assistant_message", text: "Codex reply 1" },
});
await timeline.ingest(scope, {
provider: "codex",
item: { type: "user_message", text: "Follow up", messageId: "c3", clientMessageId: "c3" },
});
await timeline.attachProviderMessageId(scope, "c3", "codex-p2");
// Reconcile against Codex native replay (which only has codex-p1 and codex-p2, plus a new turn)
const providerReplay: TimelineEntry[] = [
{
provider: "codex",
item: { type: "user_message", text: handoffRendered, messageId: "codex-p1" },
},
{ provider: "codex", item: { type: "assistant_message", text: "Codex reply 1" } },
{
provider: "codex",
item: { type: "user_message", text: "Follow up", messageId: "codex-p2" },
},
{
provider: "codex",
item: { type: "user_message", text: "External turn", messageId: "codex-p3" },
},
{ provider: "codex", item: { type: "assistant_message", text: "External reply" } },
];
const reconciled = await timeline.reconcileProviderHistory(scope, providerReplay);
expect(reconciled.kind).toBe("appended");
// Judge open rewind on codex-p2 using only Codex's native prompt IDs
const rw = await timeline.beginRewind(scope, "c3");
const unchanged = await timeline.judgeRewind(scope, rw.id, [
"codex-p1",
"codex-p2",
"codex-p3",
]);
expect(unchanged).toEqual({ kind: "unchanged" });
const applied = await timeline.judgeRewind(scope, rw.id, ["codex-p1"]);
expect(applied).toEqual({
kind: "applied",
cut: { kind: "after", retainedMessageId: "codex-p1" },
});
// Opening a provider switch while rewind is open is refused
await expect(
timeline.beginProviderSwitch(scope, switchIntent({ messageId: "msg-2" })),
).rejects.toThrow(TimelineRewindPendingError);
});
it("isolates tool call identities, retired keys, turn metrics, and provider children across segments", async () => {
const timeline = new AgentTimeline(create());
await timeline.create(scope, { epoch: "ep-1" });
// Segment 1 (Claude) with tool call_1 (active) and turn t1 + tool call_2 (retired)
await timeline.ingest(scope, {
provider: "claude",
turnId: "t1",
item: { type: "user_message", text: "Claude 1", messageId: "c1", clientMessageId: "c1" },
});
await timeline.attachProviderMessageId(scope, "c1", "claude-p1");
await timeline.ingest(scope, {
provider: "claude",
turnId: "t1",
item: tool("call_shared", "completed", "claude tool"),
});
await timeline.recordChild({ agentId: scope.agentId, subagentId: "claude-child-1" }, () =>
childDescriptor("claude-child-1", "claude", "call_shared"),
);
await timeline.ingest(scope, {
provider: "claude",
turnId: "t1",
item: { type: "assistant_message", text: "Claude 1 reply" },
});
await timeline.ingest(scope, {
provider: "claude",
turnId: "t_retired",
item: { type: "user_message", text: "Claude 2", messageId: "c2", clientMessageId: "c2" },
});
await timeline.attachProviderMessageId(scope, "c2", "claude-p2");
await timeline.ingest(scope, {
provider: "claude",
turnId: "t_retired",
item: tool("call_retired", "completed"),
});
// Retire Claude 2 so call_retired and t_retired are in retired keys
const rw1 = await timeline.beginRewind(scope, "c2");
await timeline.recordRewindCut(scope, rw1.id, { kind: "at_target" });
await timeline.completeRewind(scope, rw1.id);
// Switch to Codex
const intent = await timeline.beginProviderSwitch(scope, switchIntent());
await timeline.commitProviderSwitch(scope, intent.id, {
markerEntry: { provider: "codex", item: switchMarker("claude", "codex") },
});
await timeline.completeProviderSwitch(scope, intent.id);
// Segment 2 (Codex) reuses turnId "t_retired", callId "call_retired", and callId "call_shared"
await timeline.ingest(scope, {
provider: "codex",
turnId: "t_retired",
item: { type: "user_message", text: "Codex 1", messageId: "c3", clientMessageId: "c3" },
});
await timeline.attachProviderMessageId(scope, "c3", "codex-p1");
const reusedRetired = await timeline.ingest(scope, {
provider: "codex",
turnId: "t_retired",
item: tool("call_retired", "completed", "codex reused retired"),
});
expect(reusedRetired.kind).toBe("recorded");
const reusedActive = await timeline.ingest(scope, {
provider: "codex",
turnId: "t1",
item: tool("call_shared", "completed", "codex tool"),
});
expect(reusedActive.kind).toBe("recorded");
await timeline.ingest(scope, {
provider: "codex",
turnId: "t1",
item: { type: "assistant_message", text: "Codex reply" },
});
// Stamping turnMetrics for turnId "t1" stamps Codex's assistant reply, not Claude's
const stamped = await timeline.stampTurnMetrics(scope, [{ label: "Tokens", value: "42" }], {
turnId: "t1",
});
expect(stamped?.item).toEqual({ type: "assistant_message", text: "Codex reply" });
// Both Claude's and Codex's call_shared rows exist separately
const rows = await timeline.readRows(scope);
const sharedTools = rows.filter(
(row) => row.item.type === "tool_call" && row.item.callId === "call_shared",
);
expect(sharedTools).toHaveLength(2);
// Rewinding Codex's turn with call_shared does NOT retire Claude's historical provider child
const rw2 = await timeline.beginRewind(scope, "c3");
await timeline.recordRewindCut(scope, rw2.id, { kind: "at_target" });
await timeline.completeRewind(scope, rw2.id);
const children = await timeline.listChildren(scope.agentId);
expect(children).toEqual([
expect.objectContaining({ subagentId: "claude-child-1", retired: false }),
]);
});
},
);
describe("SQLite timeline migration v2 and durability", () => {
it("migrates a v1 database in place and refuses downgrade to a v1 reader", async () => {
const file = nextTestDatabasePath();
const v1Schema: SchemaModule = {
name: "timeline",
migrations: [timelineSchema.migrations[0]!],
};
const dbV1 = openDaemonDatabase({
path: file,
modules: [v1Schema],
logger: createTestLogger(),
});
// Seed a v1 scope row directly
dbV1.write((sql) => {
sql.run(
"INSERT INTO timeline_scopes (agent_id, subagent_id, epoch, next_seq, min_seq, active_count, active_max_seq_end, retirement_count) VALUES (?, NULL, 'ep-v1', 1, 0, 0, 0, 0)",
scope.agentId,
);
});
dbV1.close();
// Open with v2 schema — upgrades cleanly
const dbV2 = openDaemonDatabase({
path: file,
modules: [timelineSchema],
logger: createTestLogger(),
});
const timeline = createStoredAgentTimeline(dbV2);
const head = await timeline.describe(scope);
expect(head).toMatchObject({
epoch: "ep-v1",
activeSegmentStartSeq: 0,
providerSwitch: null,
});
const intent = await timeline.beginProviderSwitch(scope, switchIntent());
await timeline.commitProviderSwitch(scope, intent.id, {
markerEntry: { provider: "codex", item: switchMarker() },
});
await timeline.close();
dbV2.close();
// Reopening with v2 preserves open intent + activeSegmentStartSeq
const dbV2Reopen = openDaemonDatabase({
path: file,
modules: [timelineSchema],
logger: createTestLogger(),
});
const reopened = createStoredAgentTimeline(dbV2Reopen);
const reopenedHead = await reopened.describe(scope);
expect(reopenedHead?.activeSegmentStartSeq).toBe(1);
expect(reopenedHead?.providerSwitch?.phase).toBe("marker_committed");
await reopened.close();
dbV2Reopen.close();
// Reopening with v1 reader refuses with DatabaseSchemaTooNewError
expect(() =>
openDaemonDatabase({ path: file, modules: [v1Schema], logger: createTestLogger() }),
).toThrow(DatabaseSchemaTooNewError);
});
it("rolls back commitProviderSwitch atomically if a statement fails mid-transaction", () => {
const database = openTestTimelineDatabase();
const backend = new SqliteTimelineBackend(database);
backend.create(scope, { epoch: "ep-rollback" });
backend.append(scope, [
{
provider: "claude",
item: { type: "user_message", text: "hi", messageId: "m1" },
timestamp: TS,
},
]);
const intent: TimelineProviderSwitchIntent = {
id: "sw-1",
phase: "preparing",
...switchIntent(),
};
backend.setProviderSwitch(scope, intent);
const before = dumpTables(database);
database.write((sql) => {
sql.exec(
"CREATE TRIGGER fail_switch BEFORE INSERT ON timeline_source_ranges " +
"BEGIN SELECT RAISE(ABORT, 'disk full'); END;",
);
});
expect(() =>
backend.commitProviderSwitch(scope, {
markerEntry: { provider: "codex", item: switchMarker(), timestamp: TS },
nextIntent: { ...intent, phase: "marker_committed", markerSeq: 2 },
}),
).toThrow(/disk full/);
expect(dumpTables(database)).toEqual(before);
database.close();
});
});
@@ -16,10 +16,12 @@ import type {
MaybePromise,
RetiredChildSelector,
TimelineBackendAppendResult,
TimelineBackendCommitProviderSwitchResult,
TimelineBackendRetireResult,
TimelineChild,
TimelineEntry,
TimelineHead,
TimelineProviderSwitchIntent,
TimelineRewindIntent,
TimelineScope,
TimelineSeed,
@@ -114,6 +116,21 @@ export class DeferredTimelineBackend implements AgentTimelineBackend {
setRewind(scope: TimelineScope, rewind: TimelineRewindIntent | null): Promise<TimelineHead> {
return this.defer(() => this.inner.setRewind(scope, rewind));
}
setProviderSwitch(
scope: TimelineScope,
providerSwitch: TimelineProviderSwitchIntent | null,
): Promise<TimelineHead> {
return this.defer(() => this.inner.setProviderSwitch(scope, providerSwitch));
}
commitProviderSwitch(
scope: TimelineScope,
input: {
markerEntry: TimelineEntry;
nextIntent: TimelineProviderSwitchIntent | null;
},
): Promise<TimelineBackendCommitProviderSwitchResult> {
return this.defer(() => this.inner.commitProviderSwitch(scope, input));
}
children(agentId: string): Promise<TimelineChild[]> {
return this.defer(() => this.inner.children(agentId));
}
@@ -143,9 +160,10 @@ export class DeferredTimelineBackend implements AgentTimelineBackend {
scope: TimelineScope,
clientMessageId: string,
providerMessageId: string,
options?: { providerPromptText?: string },
): Promise<AgentTimelineRow | null> {
return this.defer(() =>
this.inner.attachProviderMessageId(scope, clientMessageId, providerMessageId),
this.inner.attachProviderMessageId(scope, clientMessageId, providerMessageId, options),
);
}
stampTurnMetrics(
@@ -23,6 +23,7 @@ const INBOUND_PERMISSION = {
"agent.background_work.list.request": "workspace.read",
"agent.background_work.stop.request": ["workspace.write", "hub.execute"],
"agent.provider_subagents.timeline.get.request": "workspace.read",
"agent.provider.switch.request": "workspace.write",
"agent.rewind.request": "workspace.write",
"agent.skills.get_status.request": "daemon.read",
"agent.skills.import_legacy_selection.request": "daemon.manage",
@@ -270,6 +271,7 @@ const OUTBOUND_PERMISSION = {
"agent.background_work.list.response": "workspace.read",
"agent.background_work.stop.response": ["workspace.write", "hub.execute"],
"agent.background_work.update": "workspace.read",
"agent.provider.switch.response": "workspace.write",
"agent.rewind.response": "workspace.write",
"agent.skills.get_status.response": "daemon.read",
"agent.skills.import_legacy_selection.response": "daemon.manage",
@@ -0,0 +1,289 @@
import { randomUUID } from "node:crypto";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it, onTestFinished } from "vitest";
import { CLIENT_CAPS } from "@getpaseo/protocol/client-capabilities";
import type { SessionOutboundMessage } from "@getpaseo/protocol/messages";
import {
AgentProviderSwitchError,
DaemonClient,
type WebSocketLike,
} from "@getpaseo/client/internal/daemon-client";
import { WebSocket } from "ws";
import { createTestPaseoDaemon, type TestPaseoDaemon } from "./test-utils/paseo-daemon.js";
import type {
AgentClient,
AgentPersistenceHandle,
AgentPromptInput,
AgentProvider,
AgentRunOptions,
AgentRunResult,
AgentSession,
AgentSessionConfig,
AgentStreamEvent,
} from "./agent/agent-sdk-types.js";
import { renderProviderPromptText } from "./agent/provider-switch/index.js";
const CAPS = {
supportsStreaming: true,
supportsSessionPersistence: true,
supportsDynamicModes: false,
supportsMcpServers: true,
supportsReasoningStream: false,
supportsToolInvocations: true,
supportsRewindConversation: true,
supportsRewindFiles: false,
supportsRewindBoth: false,
} as const;
class E2EFakeSession implements AgentSession {
readonly capabilities = CAPS;
readonly receivedPrompts: AgentPromptInput[] = [];
private listeners = new Set<(event: AgentStreamEvent) => void>();
private turnCount = 0;
constructor(
readonly id: string,
readonly provider: AgentProvider,
private persistence: AgentPersistenceHandle | null,
private readonly onStartTurn?: () => void,
) {}
subscribe(listener: (event: AgentStreamEvent) => void): () => void {
this.listeners.add(listener);
return () => this.listeners.delete(listener);
}
async startTurn(
prompt: AgentPromptInput,
options?: AgentRunOptions,
): Promise<{ turnId: string }> {
this.receivedPrompts.push(prompt);
this.onStartTurn?.();
this.turnCount += 1;
const turnId = `${this.provider}-t${this.turnCount}`;
const msgId = `${this.provider}-m${this.turnCount}`;
const rendered = renderProviderPromptText(prompt);
queueMicrotask(() => {
for (const listener of this.listeners) {
if (options?.clientMessageId) {
listener({
type: "timeline",
provider: this.provider,
turnId,
item: {
type: "user_message",
text: rendered,
messageId: msgId,
clientMessageId: options.clientMessageId,
},
});
}
listener({
type: "timeline",
provider: this.provider,
turnId,
item: {
type: "assistant_message",
text: `${this.provider} reply ${this.turnCount}`,
},
});
listener({ type: "turn_completed", provider: this.provider, turnId });
}
});
return { turnId };
}
async run(prompt: AgentPromptInput, options?: AgentRunOptions): Promise<AgentRunResult> {
await this.startTurn(prompt, options);
return { sessionId: this.id, finalText: "", timeline: [] };
}
async *stream(): AsyncGenerator<AgentStreamEvent> {}
async *streamHistory(): AsyncGenerator<AgentStreamEvent> {}
async interrupt(): Promise<void> {}
async getAvailableModes() {
return [];
}
async getCurrentMode() {
return null;
}
async setMode() {}
async getRuntimeInfo() {
return { provider: this.provider, sessionId: this.persistence?.sessionId ?? null };
}
describePersistence(): AgentPersistenceHandle | null {
return this.persistence;
}
async close(): Promise<void> {}
}
class E2EFakeClient implements AgentClient {
readonly capabilities = CAPS;
readonly sessions: E2EFakeSession[] = [];
failNextTurn: Error | null = null;
constructor(
readonly provider: AgentProvider,
private readonly initialPersistenceNull = false,
) {}
async isAvailable(): Promise<boolean> {
return true;
}
async fetchCatalog() {
return { models: [], modes: [] };
}
async createSession(_config: AgentSessionConfig): Promise<AgentSession> {
const id = `${this.provider}-s${this.sessions.length + 1}`;
const session = new E2EFakeSession(
id,
this.provider,
this.initialPersistenceNull ? null : { provider: this.provider, sessionId: id },
() => {
if (this.failNextTurn) {
const err = this.failNextTurn;
this.failNextTurn = null;
throw err;
}
},
);
this.sessions.push(session);
return session;
}
async resumeSession(handle: AgentPersistenceHandle): Promise<AgentSession> {
const session = new E2EFakeSession(handle.sessionId, this.provider, handle);
this.sessions.push(session);
return session;
}
}
async function connectClient(
url: string,
capabilities?: Record<string, boolean>,
): Promise<{ client: DaemonClient; messages: SessionOutboundMessage[] }> {
const messages: SessionOutboundMessage[] = [];
const client = new DaemonClient({
url,
clientId: randomUUID(),
webSocketFactory: (wsUrl) => new WebSocket(wsUrl) as unknown as WebSocketLike,
reconnect: { enabled: false },
...(capabilities ? { capabilities } : {}),
});
client.subscribeRawMessages((msg) => {
messages.push(msg);
});
await client.connect();
onTestFinished(async () => {
await client.close().catch(() => undefined);
});
return { client, messages };
}
describe("Provider switching WebSocket RPC, receipts, and capability gating", () => {
let daemon: TestPaseoDaemon | null = null;
afterEach(async () => {
await daemon?.close();
daemon = null;
});
it("handles switch RPC, idempotent retry, post-commit start failure, and gates provider_switch items for legacy clients", async () => {
const cwd = mkdtempSync(join(tmpdir(), "paseo-e2e-switch-"));
onTestFinished(() => rmSync(cwd, { recursive: true, force: true }));
const claude = new E2EFakeClient("claude");
const codex = new E2EFakeClient("codex", true);
daemon = await createTestPaseoDaemon({
agentClients: { claude, codex },
});
const wsUrl = `ws://127.0.0.1:${daemon.port}/ws`;
const modern = await connectClient(wsUrl);
const legacy = await connectClient(wsUrl, {
[CLIENT_CAPS.timelineProviderSwitches]: false,
[CLIENT_CAPS.timelineRewindOperations]: true,
[CLIENT_CAPS.selectiveAgentTimeline]: true,
});
// Server advertises providerSwitching feature
const serverInfoMsg = modern.messages.find(
(m) => m.type === "status" && m.payload.status === "server_info",
);
expect(
serverInfoMsg &&
serverInfoMsg.type === "status" &&
serverInfoMsg.payload.status === "server_info"
? serverInfoMsg.payload.features?.providerSwitching
: undefined,
).toBe(true);
const agent = await modern.client.createAgent({ provider: "claude", cwd });
await modern.client.sendMessage(agent.id, "First message on Claude", undefined, {
messageId: "msg-c1",
});
// Wait briefly for turn 1 to settle
await new Promise((resolve) => setTimeout(resolve, 100));
// Switch from Claude to Codex via RPC
const switched = await modern.client.switchAgentProvider(agent.id, {
provider: "codex",
text: "Continue on Codex",
messageId: "msg-sw-1",
});
expect(switched.agent?.provider).toBe("codex");
expect(switched.agent?.id).toBe(agent.id);
// Wait for Codex turn 1 to settle
await new Promise((resolve) => setTimeout(resolve, 100));
// Idempotent retry with same messageId + same payload succeeds and returns current agent without creating a 2nd session
const retried = await modern.client.switchAgentProvider(agent.id, {
provider: "codex",
text: "Continue on Codex",
messageId: "msg-sw-1",
});
expect(retried.agent?.provider).toBe("codex");
expect(codex.sessions).toHaveLength(1);
// Modern client sees provider_switch item + activeSegmentStartSeq > 0
const modernPage = await modern.client.fetchAgentTimeline(agent.id, {
direction: "tail",
limit: 50,
});
expect(modernPage.activeSegmentStartSeq).toBeGreaterThan(0);
expect(modernPage.entries.some((e) => e.item.type === "provider_switch")).toBe(true);
// Ensure providerPromptText is NEVER leaked on wire entries
for (const entry of modernPage.entries) {
expect("providerPromptText" in entry).toBe(false);
}
// Legacy client WITHOUT timeline_provider_switches NEVER receives provider_switch items!
const legacyPage = await legacy.client.fetchAgentTimeline(agent.id, {
direction: "tail",
limit: 50,
});
expect(legacyPage.entries.some((e) => e.item.type === "provider_switch")).toBe(false);
expect(legacyPage.entries.filter((e) => e.item.type === "user_message")).toHaveLength(2);
// Post-commit start failure: switch back to Claude, but fail turn 1 startTurn
claude.failNextTurn = new Error("Claude rate limited on turn 1");
let caught: unknown;
try {
await modern.client.switchAgentProvider(agent.id, {
provider: "claude",
text: "Back to Claude",
messageId: "msg-sw-2",
});
} catch (error) {
caught = error;
}
expect(caught).toBeInstanceOf(AgentProviderSwitchError);
const switchErr = caught as AgentProviderSwitchError;
expect(switchErr.message).toContain("Claude rate limited on turn 1");
// Response MUST include committed Claude agent snapshot so UI updates live provider and lets user retry normally!
expect(switchErr.agent?.provider).toBe("claude");
expect(switchErr.agent?.id).toBe(agent.id);
});
});
+146 -3
View File
@@ -89,6 +89,7 @@ import {
} from "./agent/agent-loading.js";
import {
sendPromptToAgent,
startAgentRun,
waitForAgentRunStartWithTimeout,
unarchiveAgentState,
} from "./agent/agent-prompt.js";
@@ -130,7 +131,11 @@ import {
type WorkspaceLabelService,
} from "./workspace-labels/index.js";
import { AgentManager, AgentRunCancellationError } from "./agent/agent-manager.js";
import {
AgentManager,
AgentProviderSwitchStartError,
AgentRunCancellationError,
} from "./agent/agent-manager.js";
import { buildTimelinePromptIndex } from "./agent/timeline-prompt-index.js";
import { ProviderSnapshotManager } from "./agent/provider-snapshot-manager.js";
import type {
@@ -1567,12 +1572,13 @@ export class Session {
return owner;
}
// COMPAT(timelineItemCapabilities): plugin items added in v0.8.0, notifications in v0.7.2.
// Remove after 2027-03-07 once the supported client floor is >= v0.8.0.
// COMPAT(timelineItemCapabilities): plugin items added in v0.8.0, notifications in v0.7.2,
// provider switches in v0.18.0. Remove each gate after its client floor advances.
private supportsTimelineItem(item: { type: string }, source?: object): boolean {
let capability: ClientCapability;
if (item.type === "notification") capability = CLIENT_CAPS.timelineNotifications;
else if (item.type === "plugin") capability = CLIENT_CAPS.pluginTimelineItems;
else if (item.type === "provider_switch") capability = CLIENT_CAPS.timelineProviderSwitches;
else return true;
return source ? this.supportsForSource(capability, source) : this.supports(capability);
}
@@ -3261,6 +3267,8 @@ export class Session {
switch (msg.type) {
case "agent.rewind.request":
return this.handleAgentRewindRequest(msg, source);
case "agent.provider.switch.request":
return this.handleAgentProviderSwitchRequest(msg, source);
default:
return undefined;
}
@@ -8773,6 +8781,7 @@ export class Session {
...(this.appliesRewinds(source)
? { retirements: fetchedControlTimeline.retirements }
: {}),
activeSegmentStartSeq: fetchedControlTimeline.activeSegmentStartSeq,
entries: entries.map((entry) => {
const payloadEntry = {
// A row keeps the provider that wrote it; older rows have none.
@@ -9242,6 +9251,140 @@ export class Session {
return requested ?? "queue";
}
private async handleAgentProviderSwitchRequest(
msg: Extract<SessionInboundMessage, { type: "agent.provider.switch.request" }>,
source?: object,
): Promise<void> {
const resolved = await this.resolveAgentIdentifier(msg.agentId);
if (!resolved.ok) {
this.emitForSource(
{
type: "agent.provider.switch.response",
payload: {
requestId: msg.requestId,
agentId: msg.agentId,
accepted: false,
error: resolved.error,
},
},
source,
);
return;
}
const agentId = resolved.agentId;
try {
const prompt = buildAgentPrompt(msg.text, msg.images, msg.attachments);
const send = async (beforeDispatch: () => Promise<void>) => {
const switched = await this.agentManager.switchAgentProvider(agentId, {
toProvider: msg.provider,
model: msg.model,
modeId: msg.modeId,
thinkingOptionId: msg.thinkingOptionId,
providerOptions: msg.providerOptions,
prompt,
messageId: msg.messageId,
beforeDispatch,
});
const stored = await this.agentStorage.get(agentId);
if (stored && !stored.title && !stored.lastUserMessageAt) {
const { provisionalTitle } = resolveCreateAgentTitles({ initialPrompt: msg.text });
if (provisionalTitle) await this.agentManager.setTitle(agentId, provisionalTitle);
}
try {
const dispatchResult = await startAgentRun(
this.agentManager,
agentId,
switched.handoffPrompt,
this.sessionLogger,
{
idleOnly: true,
runOptions: { clientMessageId: msg.messageId },
},
);
if (dispatchResult.disposition === "turn_started") {
await waitForAgentRunStartWithTimeout(
this.agentManager,
agentId,
dispatchResult.started,
this.delivery.requestSignal,
);
}
} catch (startError) {
const liveAgent = this.agentManager.getAgent(agentId) ?? switched.agent;
throw new AgentProviderSwitchStartError(liveAgent, startError);
}
};
await this.messageReceipts.send({
agentId,
messageId: msg.messageId,
request: {
kind: "provider_switch",
provider: msg.provider,
model: msg.model ?? null,
modeId: msg.modeId ?? null,
thinkingOptionId: msg.thinkingOptionId ?? null,
providerOptions: msg.providerOptions ?? null,
prompt,
},
send,
});
const agentPayload = await this.getAgentPayloadById(agentId);
this.emitForSource(
{
type: "agent.provider.switch.response",
payload: {
requestId: msg.requestId,
agentId,
accepted: true,
...(agentPayload ? { agent: agentPayload } : {}),
error: null,
},
},
source,
);
} catch (error) {
if (this.delivery.requestSignal.aborted) return;
if (error instanceof AgentProviderSwitchStartError) {
this.handleAgentRunError(
agentId,
error.cause ?? error,
"Failed to start turn after provider switch",
);
const agentPayload =
(await this.getAgentPayloadById(agentId)) ?? toAgentPayload(error.agent);
this.emitForSource(
{
type: "agent.provider.switch.response",
payload: {
requestId: msg.requestId,
agentId,
accepted: false,
agent: agentPayload,
error: errorToFriendlyMessage(error),
},
},
source,
);
return;
}
this.emitForSource(
{
type: "agent.provider.switch.response",
payload: {
requestId: msg.requestId,
agentId,
accepted: false,
error: errorToFriendlyMessage(error),
},
},
source,
);
}
}
private async handleSendAgentMessageRequest(
msg: Extract<SessionInboundMessage, { type: "send_agent_message_request" }>,
): Promise<void> {
@@ -2178,6 +2178,8 @@ export class VoiceAssistantWebSocketServer {
rewind: true,
// COMPAT(timelineRewindOperations): added in v0.14.1, remove gate after 2027-05-10.
timelineRewindOperations: true,
// COMPAT(providerSwitching): added in v0.18.0, remove gate after 2027-11-25.
providerSwitching: true,
// COMPAT(agentTimelinePromptIndex): added in v0.2.X, drop the gate when floor >= v0.2.X.
agentTimelinePromptIndex: true,
// COMPAT(agentHistorySearch): added in v0.3.0, remove gate after 2027-02-07.