Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
Continue a Claude Code CLI conversation in a Console session (CHOO-3835) (#1082)
Christian McDermotta9dea3715097
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4b1c83042..b36d750d2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2476,6 +2476,12 @@ version of their own to them without also giving them a release of their own.that still has a working login of its own, such as one it copied while themachine had an `auth.json`, starts as before; a copy that no longer works isremoved.+- **A Claude Code agent's session can continue a conversation started in the+ Claude Code CLI.** The new-session dialog lists the conversations started in+ the agent's folder, on this computer or its SSH host. The session continues a+ copy of the one picked, so the terminal's own is never written to, and its+ transcript starts with what was said in it. A conversation still open in a+ terminal can't be picked. No earlier prompt is sent again.#### Changed- **Usage data follows an install to a working agent.** Three newdiff --git a/console/apps/switch-console-desktop/package.json b/console/apps/switch-console-desktop/package.jsonindex 776b14f4e..043d9ae26 100644--- a/console/apps/switch-console-desktop/package.json+++ b/console/apps/switch-console-desktop/package.json@@ -76,7 +76,7 @@"smol-toml": "^1.8.0","ssh2": "^1.17.0","tldts": "^7.4.2",- "zod": "^4.3.6"+ "zod": "^4.6.7"},"devDependencies": {"@base-ui/react": "^1.3.0",diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/host-watchers.test.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/host-watchers.test.tsindex 35824b3ba..81373985b 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/host-watchers.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/host-watchers.test.ts@@ -17,10 +17,11 @@ import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';import { tmpdir } from 'node:os';import { join } from 'node:path';import { promisify } from 'node:util';-import { expect, it, vi } from 'vitest';+import { describe, expect, it, vi } from 'vitest';import {listHostWatchers,watcherIsCurrent,+ watcherRunsBundle,WATCHER_STATUS_SCRIPT,type HostWatcherStatus,} from './host-watchers';@@ -156,3 +157,51 @@ it('reports each watcher’s process, what it wrote about itself, and why it stoawait rm(base, { recursive: true, force: true });}});++describe('which bundle a watcher runs', () => {+ const bundle = { identity: 'abc123', file: BUNDLE_FILE };+ const health = (extra: object) => ({+ state: 'connected',+ detail: null,+ since: '2026-11-01T00:00:00.000Z',+ placements: {},+ pid: 101,+ updatedAt: '2026-11-01T00:00:00.000Z',+ ...extra,+ });++ it('takes the word of the watcher process alive now', () => {+ expect(watcherRunsBundle(status({ health: health({ bundle: 'abc123' }) }), bundle)).toBe(true);+ expect(watcherRunsBundle(status({ health: health({ bundle: 'older' }) }), bundle)).toBe(false);+ });++ it('takes a watcher whose own record names no bundle to run another build', () => {+ expect(watcherRunsBundle(status({ health: health({}) }), bundle)).toBe(false);+ });++ it.each([+ ['written nothing yet', status({ health: null })],+ ['written a record it cannot read', status({ health: { pid: 101 } })],+ ['only the file a previous process left', status({ health: health({ pid: 99 }) })],+ [+ 'only the file a previous process on another build left',+ status({ health: health({ bundle: 'older', pid: 99 }) }),+ ],+ ])('has no answer for a watcher process that has %s', (_label, watcher) => {+ expect(watcherRunsBundle(watcher, bundle)).toBeNull();+ });++ it('asks the supervisor while the watcher process is down', () => {+ const down = { workerAlive: false, health: health({ bundle: 'abc123' }) };+ expect(watcherRunsBundle(status(down), bundle)).toBe(true);+ expect(watcherRunsBundle(status({ ...down, build: '/…/shared-host-old.mjs' }), bundle)).toBe(+ false+ );+ expect(watcherRunsBundle(status({ ...down, build: null }), bundle)).toBeNull();+ });++ it('has no answer when no watcher is running', () => {+ expect(watcherRunsBundle(undefined, bundle)).toBeNull();+ expect(watcherRunsBundle(status({ running: false, workerAlive: false }), bundle)).toBeNull();+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/host-watchers.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/host-watchers.tsindex b1124e4ed..5aeca12e9 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/host-watchers.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/host-watchers.ts@@ -1,3 +1,4 @@+import { watcherHealthFileSchema } from '@switch-console/agent-providers';import { z } from 'zod';import type { IExecutionContext } from '@main/core/execution-context/types';import { READ_JSON } from './remote-json';@@ -138,3 +139,31 @@ export function watcherIsCurrent(if (!status.build || status.build.split('/').pop() !== want.bundleFile) return false;return status.enabled === want.enabled && status.spawn === want.spawn;}++/**+ * Whether a watcher runs the shared-host bundle `bundle` names, so the session+ * configurations it is handed are read by that build. Its own process says+ * which bundle it loaded, in its health file, taken only from the process+ * alive now; a record from that process that names none comes from a build+ * too old to say, which is some other build. While that process is down, its+ * supervisor, which starts it again from the same file, says which file that+ * is.+ *+ * Null when no watcher is running, and when which bundle it runs cannot be+ * told: its process has written no record of its own yet (one just started,+ * or the file is its predecessor's), or its supervisor did not say which file+ * it starts. Only a watcher that says it runs another build is false.+ */+export function watcherRunsBundle(+ status: HostWatcherStatus | undefined,+ bundle: { identity: string; file: string }+): boolean | null {+ if (!status || (!status.workerAlive && !status.running)) return null;+ if (status.workerAlive) {+ const written = watcherHealthFileSchema.safeParse(status.health);+ if (!written.success || written.data.pid !== status.workerPid) return null;+ return written.data.bundle === bundle.identity;+ }+ const file = status.build?.split('/').pop();+ return file ? file === bundle.file : null;+}diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.initial-prompt.test.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.initial-prompt.test.tsindex 6d6643db4..ff826d22a 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.initial-prompt.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.initial-prompt.test.ts@@ -20,6 +20,7 @@ const mocks = vi.hoisted(() => ({behavior: {} as Record<string, unknown>,ready: vi.fn(),sidecarEnsure: vi.fn(),+ watchers: vi.fn(),}));// Console runs every agent here; none was moved to a managed machine.@@ -66,6 +67,11 @@ vi.mock('./shared-host-deployment', () => ({entrypoint: 'run.mjs',})),runSharedHostCommand: vi.fn(),+ sharedHostBundle: async () => ({ identity: 'this-build', file: 'shared-host-this-build.mjs' }),+}));+vi.mock('./host-watchers', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ listHostWatchers: mocks.watchers,}));vi.mock('./local-host', () => ({startLocalSession: mocks.runHost,@@ -102,6 +108,7 @@ vi.mock('@main/core/providers/plugin-registry', () => ({vi.mock('@main/lib/logger', () => ({ log: { warn: vi.fn(), error: vi.fn() } }));const { SharedAgentRuntime, buildSharedHostConfig } = await import('./shared-agent-runtime');+const { trackCliConversationFork } = await import('@main/core/sessions/cli-conversation-forks');const session = {id: 'session-1',@@ -169,6 +176,163 @@ it('delivers the initial prompt on a relaunch that did not create the host', asyexpect(mocks.persist.mock.calls.map((call) => call[1].state)).toEqual(['pending', 'submitted']);});+it('delivers the initial prompt of a session whose transcript holds only a continued conversation’s history', async () => {+ mocks.snapshot.mockResolvedValue({+ session: { epoch: 'epoch-2', connectivity: 'online', status: 'ready' },+ turns: [{ type: 'turn.upsert', turnId: 'imported:u1', status: 'completed', commandId: null }],+ items: [{ itemId: 'imported:u1', turnId: 'imported:u1', kind: 'user-message' }],+ });++ await runtime().start(session, false, 'Say hello');++ expect(mocks.submit).toHaveBeenCalledTimes(1);+ expect(mocks.submit.mock.calls[0][1]).toMatchObject({+ body: { type: 'message.send', text: 'Say hello' },+ });+});++it('refuses to start a continued session whose copy was never made', async () => {+ await expect(+ buildSharedHostConfig(+ { ...session, cliConversation: { nativeSessionId: 'cli-1', title: 'Fix the build' } },+ { sessionPath: '/work', sessionEnvVars: {} },+ { kind: 'local' } as LocationTransport+ )+ ).rejects.toThrow('its copy was never made');+});++it('starts a continued session with the copy its row recorded after the session was read', async () => {+ mocks.loadSession.mockResolvedValue({+ row: { config: { providerSessionId: 'copy-1' } },+ providerId: 'claude',+ name: 'scout',+ });+ await expect(+ buildSharedHostConfig(+ { ...session, cliConversation: { nativeSessionId: 'cli-1', title: 'Fix the build' } },+ { sessionPath: '/work', sessionEnvVars: {} },+ { kind: 'local' } as LocationTransport+ )+ ).resolves.toMatchObject({+ start: { input: { resume: { nativeSessionId: 'copy-1' } } },+ importHistory: true,+ });+ expect(mocks.loadSession).toHaveBeenCalledWith('session-1');+});++it('starts a session whose copy is still being made with that copy, once it is made', async () => {+ let made!: (id: string) => void;+ void trackCliConversationFork(+ 'session-1',+ new Promise<string>((resolve) => {+ made = resolve;+ })+ );+ const config = buildSharedHostConfig(+ { ...session, cliConversation: { nativeSessionId: 'cli-1', title: 'Fix the build' } },+ { sessionPath: '/work', sessionEnvVars: {} },+ { kind: 'local' } as LocationTransport+ );+ made('copy-1');+ await expect(config).resolves.toMatchObject({+ start: { input: { resume: { nativeSessionId: 'copy-1' } } },+ importHistory: true,+ });+});++/** A watcher on the host, with what its process says it runs, in a record of its own or not. */+function watcherRunning(bundle: string | undefined, recordedBy = 41) {+ return new Map([+ [+ 'remote-agent',+ {+ agentId: 'remote-agent',+ root: '/state/watcher',+ running: true,+ build: `/state/sdk-host/shared-host-${bundle ?? 'unknown'}.mjs`,+ enabled: true,+ spawn: true,+ stoodDown: false,+ supervisorPid: 40,+ workerPid: 41,+ workerAlive: true,+ health: {+ state: 'connected',+ detail: null,+ since: '2026-11-01T00:00:00.000Z',+ placements: {},+ pid: recordedBy,+ updatedAt: '2026-11-01T00:00:00.000Z',+ ...(bundle ? { bundle } : {}),+ },+ failure: null,+ takenOver: null,+ },+ ],+ ]);+}++const continued = {+ ...session,+ providerSessionId: 'copy-1',+ cliConversation: { nativeSessionId: 'cli-1', title: 'Fix the build' },+};++it.each([+ ['an older build', 'older-build'],+ ['a build too old to say', undefined],+])(+ 'refuses a continued session before handing it to a Room watcher on %s',+ async (_label, bundle) => {+ const agent = new SharedAgentRuntime(+ { kind: 'ssh', connectionId: 'host-1', host: 'build-box' } as LocationTransport,+ { sessionId: session.id, sessionPath: '/work', sessionEnvVars: {} }+ );+ mocks.watchers.mockResolvedValue(watcherRunning(bundle));++ await expect(agent.start(continued, false, undefined, 'user')).rejects.toThrow(+ "The Room watcher on build-box does not run this version of Switch Console's host"+ );+ expect(mocks.sidecarEnsure).not.toHaveBeenCalled();+ }+);++it.each([+ ['this build', watcherRunning('this-build')],+ ['a build it cannot tell yet', watcherRunning('older-build', 40)],+ ['no watcher', new Map()],+])('hands a continued session to a host with a Room watcher on %s', async (_label, watchers) => {+ const agent = new SharedAgentRuntime(+ { kind: 'ssh', connectionId: 'host-1', host: 'build-box' } as LocationTransport,+ { sessionId: session.id, sessionPath: '/work', sessionEnvVars: {} }+ );+ mocks.watchers.mockResolvedValue(watchers);++ await agent.start(continued, false, undefined, 'user');++ expect(mocks.sidecarEnsure).toHaveBeenCalledWith(+ expect.objectContaining({ config: expect.objectContaining({ importHistory: true }) })+ );+});++it('relaunches a continued session without asking which build its Room watcher runs', async () => {+ const agent = new SharedAgentRuntime(+ { kind: 'ssh', connectionId: 'host-1', host: 'build-box' } as LocationTransport,+ { sessionId: session.id, sessionPath: '/work', sessionEnvVars: {} }+ );+ mocks.watchers.mockResolvedValue(watcherRunning('older-build'));++ await agent.start(continued, true);++ expect(mocks.watchers).not.toHaveBeenCalled();+ expect(mocks.sidecarEnsure).toHaveBeenCalledWith(+ expect.objectContaining({+ resuming: true,+ config: expect.objectContaining({ importHistory: true }),+ })+ );+});+it('hands the host how a new session started, so it can tell Switch', async () => {await runtime().start(session, false, 'Say hello', 'user');@@ -311,6 +475,26 @@ it('reads updated model, effort and instructions for each launch', async () => {expect(second.execution?.context).not.toContain('First instructions');});+it('resumes the copy a CLI conversation was continued from, starting its transcript with it', async () => {+ const config = await buildSharedHostConfig(+ {+ ...session,+ providerSessionId: 'copy-1',+ cliConversation: { nativeSessionId: 'cli-1', title: 'Fix the build' },+ },+ { sessionPath: '/work', sessionEnvVars: {} },+ { kind: 'local' } as LocationTransport+ );+ expect(config.start.input.resume).toEqual({ nativeSessionId: 'copy-1' });+ expect(config.importHistory).toBe(true);+ const ordinary = await buildSharedHostConfig(+ session,+ { sessionPath: '/work', sessionEnvVars: {} },+ { kind: 'local' } as LocationTransport+ );+ expect(ordinary.importHistory).toBeUndefined();+});+it('runs a session as the agent definition built from its config file', async () => {mocks.definition.mockResolvedValue({ description: 'Reviews diffs', prompt: 'Be careful.' });const config = await buildSharedHostConfig(diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.tsindex 8bb6fa00e..77694a948 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.ts@@ -11,6 +11,7 @@ import { stopLegacySidecar } from './legacy-sidecar';import { readLocalHostFailure, startLocalSession } from './local-host';import { deploySharedHost } from './shared-host-deployment';import { withSidecar } from './sidecar-control';+import { ensureWatcherCanContinueCliConversation } from './watcher-bundle-check';export { deploySharedHost } from './shared-host-deployment';import { randomUUID } from 'node:crypto';import { join, posix } from 'node:path';@@ -27,7 +28,11 @@ import {type SharedHostConfig,} from '@switch-console/agent-providers';import { sessionLaunchFrom } from '@switch-console/plugins/agents';-import { commandStatusSchema, type Snapshot } from '@switch-console/shared/session-v1';+import {+ commandStatusSchema,+ hasOwnActivity,+ type Snapshot,+} from '@switch-console/shared/session-v1';import {AgentManagedByControllerError,managedRecordFor,@@ -41,6 +46,7 @@ import { hostDependencyStore } from '@main/core/dependencies/host-dependency-stoimport type { LocationTransport } from '@main/core/locations/location-transport';import { ensureServerSessionReady } from '@main/core/managed-switch-server/session-readiness';import { getPlugin } from '@main/core/providers/plugin-registry';+import { cliConversationForkInFlight } from '@main/core/sessions/cli-conversation-forks';import { setInitialPromptDelivery } from '@main/core/sessions/operations/set-initial-prompt-delivery';import { loadSessionWithAgent } from '@main/core/sessions/session-join';import { getPersistedRoomConnection } from '@main/core/switch-rooms/session-room-store';@@ -195,6 +201,14 @@ export class SharedAgentRuntime implements AgentRuntimeProvider {]);return JSON.parse(result.stdout);};+ // Checked only before the first start, the one that imports the+ // conversation: a relaunch goes ahead as any other session's does.+ if (config.importHistory && !isResuming)+ await ensureWatcherCanContinueCliConversation(+ deployed.ctx,+ this.transport.host,+ agent.switchAgentId+ );// Started by the agent's sidecar, which is then its parent: it talks to// the session over IPC, and Console reaches it through the sidecar.await withSidecar(session.agentId, (client) =>@@ -298,7 +312,9 @@ export class SharedAgentRuntime implements AgentRuntimeProvider {epoch,record: saved?.initialPromptDelivery,legacyCommandId: `initial-${session.id}`,- hasPriorActivity: snapshot.turns.length > 0 || snapshot.items.length > 0,+ // History copied in from a CLI conversation is not this session having+ // run: its first prompt is still owed.+ hasPriorActivity: hasOwnActivity(snapshot),lookup: async (commandId) => {try {const status = await sessionCommandStatus(session.agentId, session.id, commandId);@@ -396,10 +412,14 @@ export class SharedAgentRuntime implements AgentRuntimeProvider {}export async function buildSharedHostConfig(- session: Pick<Session, 'id' | 'agentId' | 'providerId' | 'agentName' | 'providerSessionId'>,+ session: Pick<+ Session,+ 'id' | 'agentId' | 'providerId' | 'agentName' | 'providerSessionId' | 'cliConversation'+ >,params: { sessionPath: string; sessionEnvVars: Record<string, string>; shellSetup?: string },transport: LocationTransport): Promise<SharedHostConfig> {+ const providerSessionId = session.providerSessionId ?? (await copyBeingMade(session));const agent = await getAgentById(session.agentId);if (!agent?.switchAgentId) throw new Error('Link the agent to Switch before launching its host.');const launch = await agentLaunchConfig(session.agentId);@@ -467,9 +487,7 @@ export async function buildSharedHostConfig(runtimeMode: runtimeModeFor(agent),env: params.sessionEnvVars,mcpServers: {},- ...(session.providerSessionId- ? { resume: { nativeSessionId: session.providerSessionId } }- : {}),+ ...(providerSessionId ? { resume: { nativeSessionId: providerSessionId } } : {}),...(sessionLaunch.agent? {agentName: sessionLaunch.agent.name,@@ -479,6 +497,7 @@ export async function buildSharedHostConfig(...(sessionLaunch.model ? { model: sessionLaunch.model } : {}),},},+ ...(session.cliConversation ? { importHistory: true } : {}),// Every session of an agent is reached over that agent's one connection,// held by its controller, so the identity is derived rather than minted:// a session that restarts binds to the same one it did before.@@ -510,6 +529,30 @@ export async function buildSharedHostConfig(return config;}+/**+ * The copy a session that continues a CLI conversation resumes, when the+ * session as it was read does not hold one: the session is saved before its+ * copy is made, so one started meanwhile waits for the copy, and one read+ * before the copy was recorded finds it in its row now. With neither, Console+ * stopped while copying, and the session refuses to start rather than open a+ * new conversation in place of the one it was made to continue. Undefined for+ * every other session.+ */+async function copyBeingMade(+ session: Pick<Session, 'id' | 'cliConversation'>+): Promise<string | undefined> {+ if (!session.cliConversation) return undefined;+ const inFlight = cliConversationForkInFlight(session.id);+ if (inFlight) return inFlight;+ const recorded = (await loadSessionWithAgent(session.id))?.row.config?.providerSessionId;+ if (recorded) return recorded;+ const started = cliConversationForkInFlight(session.id);+ if (started) return started;+ throw new Error(+ `This session was to continue the Claude Code conversation “${session.cliConversation.title}”, but its copy was never made. Delete it and start a new session from that conversation.`+ );+}+/** The generation a session's host last recorded, or null if it has recorded none. */async function journalEpoch(agentId: string, sessionId: string): Promise<string | null> {try {diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-host-deployment.host-request.test.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-host-deployment.host-request.test.tsnew file mode 100644index 000000000..485222d7e--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-host-deployment.host-request.test.ts@@ -0,0 +1,331 @@+/**+ * `runHostRequest`: a one-off command of this build's shared host, with its+ * request staged as a private file rather than put on a command line. Here+ * and on an SSH host the file is readable only by the user and gone+ * afterwards; reading a host never deploys to it, and a host without this+ * build's bundle is refused rather than asked with another build's. A launch+ * (`runSharedHostCommand`) stages its configuration the same way.+ */+import { createHash } from 'node:crypto';+import { mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises';+import type * as FsPromises from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import { afterAll, beforeAll, beforeEach, expect, it, onTestFinished, vi } from 'vitest';+import { MAKE_LAUNCH_DIR } from './state-roots';++const mocks = vi.hoisted(() => ({+ bundlePath: '',+ ensureSshConnected: vi.fn(async () => ({ proxy: true })),+ sshExec: vi.fn(),+ localExec: vi.fn(),+ /** What each SFTP copy found in the local file it copied, and where it put it. */+ copied: [] as { root: string; dest: string; content: string; mode: number }[],+ ensureHostBundle: vi.fn(),+ forgetHostBundle: vi.fn(),+ warn: vi.fn(),+ rm: vi.fn(),+}));++vi.mock('node:fs/promises', async (importOriginal) => {+ const actual = await importOriginal<typeof FsPromises>();+ mocks.rm.mockImplementation(actual.rm);+ return { ...actual, rm: mocks.rm };+});++vi.mock('@main/core/agent-runtime/impl/resolve-sidecar-bundle', () => ({+ resolveSharedHostBundlePath: () => mocks.bundlePath,+}));+vi.mock('@main/core/ssh/connect/connect-agent-ssh', () => ({+ ensureSshConnected: mocks.ensureSshConnected,+}));+vi.mock('@main/core/execution-context/ssh-execution-context', () => ({+ SshExecutionContext: class {+ exec = mocks.sshExec;+ dispose() {}+ },+}));+vi.mock('@main/core/execution-context/local-execution-context', () => ({+ LocalExecutionContext: class {+ exec = mocks.localExec;+ dispose() {}+ },+}));+vi.mock('@main/core/fs/impl/ssh-fs', () => ({+ SshFileSystem: class {+ constructor(+ _proxy: unknown,+ private readonly root: string+ ) {}+ async copyLocalFile(local: string, dest: string) {+ mocks.copied.push({+ root: this.root,+ dest,+ content: await readFile(local, 'utf8'),+ mode: (await stat(local)).mode & 0o777,+ });+ }+ close() {}+ },+}));+vi.mock('./host-bundle', () => ({+ ensureHostBundle: mocks.ensureHostBundle,+ forgetHostBundle: mocks.forgetHostBundle,+}));+vi.mock('@main/lib/logger', () => ({ log: { warn: mocks.warn } }));++const { LOCATE_BUNDLE, runHostRequest, runSharedHostCommand } =+ await import('./shared-host-deployment');++const STATE = '/home/someone/.local/state/switch';+const STAGED = `${STATE}/sdk-sessions/cli-conversations/launch-1`;+const SECRET = `shell-setup-${'q'.repeat(14)}`;+const REQUEST = { provider: 'claude', dir: '/work', shellSetup: `export SETTING=${SECRET}` };+const ssh = { kind: 'ssh', connectionId: 'conn-1', host: 'build-box', dir: '/work' } as never;++let scratch = '';+let entrypoint = '';+beforeAll(async () => {+ scratch = await mkdtemp(join(tmpdir(), 'host-request-'));+ mocks.bundlePath = join(scratch, 'shared-host.mjs');+ await writeFile(mocks.bundlePath, 'export {};\n');+ const hash = createHash('sha256').update('export {};\n').digest('hex');+ entrypoint = `${STATE}/sdk-host/shared-host-${hash}.mjs`;+});+afterAll(async () => {+ await rm(scratch, { recursive: true, force: true });+});++/**+ * An SSH host that has `bundle` (or none), stages requests in `STAGED`, and+ * answers the command with `answer`.+ */+function host(bundle: string | null, answer: () => Promise<unknown>) {+ mocks.sshExec.mockImplementation(async (_command: string, args: string[]) => {+ if (args[0] !== '-e') return answer();+ const script = args[1];+ if (script === LOCATE_BUNDLE) return { stdout: `${bundle ?? ''}\n`, stderr: '' };+ if (script === MAKE_LAUNCH_DIR) return { stdout: `${STAGED}\n`, stderr: '' };+ return { stdout: '', stderr: '' };+ });+}++const CHMOD = "require('node:fs').chmodSync(process.argv[1],0o600)";+const REMOVE = "require('node:fs').rmSync(process.argv[1],{recursive:true,force:true})";++/** The arguments of each time `script` ran on the host with `node -e`. */+function scripts(script: string): string[][] {+ return mocks.sshExec.mock.calls+ .map((call) => call[1] as string[])+ .filter((args) => args[0] === '-e' && args[1] === script)+ .map((args) => args.slice(2));+}++beforeEach(() => {+ vi.clearAllMocks();+ mocks.copied = [];+});++it.each([false, true])(+ 'stages the request here as a private file, off the command line, and removes it (failing: %s)',+ async (fail) => {+ let path = '';+ mocks.localExec.mockImplementation(async (_command: string, args: string[]) => {+ expect(JSON.stringify(args)).not.toContain(SECRET);+ path = args[2]!;+ expect(args.slice(0, 2)).toEqual([mocks.bundlePath, '--cli-conversations']);+ expect((await stat(path)).mode & 0o777).toBe(0o600);+ expect(JSON.parse(await readFile(path, 'utf8'))).toEqual(REQUEST);+ if (fail) throw new Error('Command failed');+ return { stdout: '{}', stderr: '' };+ });+ const answered = runHostRequest({ kind: 'local' }, '--cli-conversations', REQUEST, {+ deploy: false,+ timeout: 1_000,+ });+ if (fail) await expect(answered).rejects.toThrow('Command failed');+ else await expect(answered).resolves.toEqual({ stdout: '{}', stderr: '' });+ await expect(stat(dirname(path))).rejects.toMatchObject({ code: 'ENOENT' });+ expect(mocks.ensureSshConnected).not.toHaveBeenCalled();+ }+);++it('reads an SSH host with this build’s bundle without deploying, staging the request privately and removing it', async () => {+ host(entrypoint, async () => ({ stdout: '{"ownershipKnown":true}', stderr: '' }));++ await expect(+ runHostRequest(ssh, '--cli-conversations', REQUEST, { deploy: false, timeout: 1_000 })+ ).resolves.toMatchObject({ stdout: '{"ownershipKnown":true}' });++ expect(mocks.ensureHostBundle).not.toHaveBeenCalled();+ // Staged beside a launch's configuration, as a file only the user can read.+ expect(scripts(MAKE_LAUNCH_DIR)).toEqual([+ [`${STATE}/sdk-sessions/cli-conversations`, String(60 * 60 * 1000)],+ ]);+ expect(mocks.copied).toEqual([+ { root: STAGED, dest: 'request.json', content: JSON.stringify(REQUEST), mode: 0o600 },+ ]);+ expect(scripts(CHMOD)).toEqual([[`${STAGED}/request.json`]]);+ const run = mocks.sshExec.mock.calls.find((call) => (call[1] as string[])[0] !== '-e')!;+ expect(run[1]).toEqual([entrypoint, '--cli-conversations', `${STAGED}/request.json`]);+ expect(run[2]).toEqual({ timeout: 1_000 });+ expect(JSON.stringify(mocks.sshExec.mock.calls)).not.toContain(SECRET);+ expect(scripts(REMOVE)).toEqual([[STAGED]]);+});++it.each([+ ['another build’s bundle', `${STATE}/sdk-host/shared-host-${'b'.repeat(64)}.mjs`],+ ['no bundle', null],+])('refuses to read an SSH host that has %s, rather than deploy to it', async (_label, bundle) => {+ host(bundle, async () => ({ stdout: '{}', stderr: '' }));++ await expect(+ runHostRequest(ssh, '--cli-conversations', REQUEST, { deploy: false, timeout: 1_000 })+ ).rejects.toThrow("build-box does not have this version of Switch Console's host yet");++ expect(mocks.ensureHostBundle).not.toHaveBeenCalled();+ expect(scripts(MAKE_LAUNCH_DIR)).toEqual([]);+ expect(mocks.copied).toEqual([]);+});++it('deploys for a launch, and on a failure that names the bundle forgets the host and still removes the request', async () => {+ mocks.ensureHostBundle.mockResolvedValue({ entrypoint, staging: `${STATE}/sdk-launch` });+ host(null, async () =>+ Promise.reject(+ Object.assign(new Error('Command failed'), {+ stderr: `Cannot find module '${entrypoint}'`,+ })+ )+ );++ await expect(+ runHostRequest(ssh, '--fork-cli-conversation', REQUEST, { deploy: true, timeout: 1_000 })+ ).rejects.toThrow('Command failed');++ expect(mocks.ensureHostBundle).toHaveBeenCalledWith(ssh);+ expect(scripts(LOCATE_BUNDLE)).toEqual([]);+ expect(mocks.forgetHostBundle).toHaveBeenCalledWith('conn-1');+ expect(scripts(REMOVE)).toEqual([[STAGED]]);+});++/** Makes removing what was staged on the SSH host fail, after `host()` set it up. */+function removalFails() {+ const exec = mocks.sshExec.getMockImplementation()!;+ mocks.sshExec.mockImplementation(async (command: string, args: string[]) => {+ if (args[0] === '-e' && args[1] === REMOVE) throw new Error('Permission denied');+ return exec(command, args);+ });+}++it('keeps the command’s own failure when the staged request cannot be removed', async () => {+ host(entrypoint, async () => Promise.reject(new Error('Command failed')));+ removalFails();++ await expect(+ runHostRequest(ssh, '--cli-conversations', REQUEST, { deploy: false, timeout: 1_000 })+ ).rejects.toThrow('Command failed');+ expect(mocks.warn).toHaveBeenCalledWith(+ 'Could not remove a file staged for the shared host',+ expect.objectContaining({+ event: 'sdk_host.staged_file_cleanup',+ stage: 'request-finished',+ host: 'build-box',+ error: 'Error: Permission denied',+ })+ );+});++it('keeps the command’s own failure here when the staged request cannot be removed', async () => {+ let path = '';+ mocks.localExec.mockImplementation(async (_command: string, args: string[]) => {+ path = args[2]!;+ throw new Error('Command failed');+ });+ mocks.rm.mockRejectedValueOnce(new Error('Device busy'));+ onTestFinished(() => rm(dirname(path), { recursive: true, force: true }));++ await expect(+ runHostRequest({ kind: 'local' }, '--cli-conversations', REQUEST, {+ deploy: false,+ timeout: 1_000,+ })+ ).rejects.toThrow('Command failed');+ expect(mocks.warn).toHaveBeenCalledWith(+ 'Could not remove a file staged for the shared host',+ expect.objectContaining({ event: 'sdk_host.staged_file_cleanup', stage: 'request-finished' })+ );+});++it('keeps why staging failed when what it had made cannot be removed', async () => {+ host(entrypoint, async () => ({ stdout: '{}', stderr: '' }));+ const exec = mocks.sshExec.getMockImplementation()!;+ mocks.sshExec.mockImplementation(async (command: string, args: string[]) => {+ if (args[0] === '-e' && args[1] === CHMOD) throw new Error('Read-only file system');+ if (args[0] === '-e' && args[1] === REMOVE) throw new Error('Permission denied');+ return exec(command, args);+ });++ await expect(+ runHostRequest(ssh, '--cli-conversations', REQUEST, { deploy: false, timeout: 1_000 })+ ).rejects.toThrow('Read-only file system');+ expect(mocks.warn).toHaveBeenCalledWith(+ 'Could not remove a file staged for the shared host',+ expect.objectContaining({+ event: 'sdk_host.staged_file_cleanup',+ stage: 'staging-failed',+ host: 'build-box',+ })+ );+});++it('keeps a launch command’s own failure when its staged configuration cannot be removed', async () => {+ const root = `${STATE}/sdk-sessions/abc`;+ host(entrypoint, async () => Promise.reject(new Error('Command failed')));+ removalFails();+ const ctx = { exec: mocks.sshExec } as never;++ await expect(+ runSharedHostCommand(ssh, { ctx, root, entrypoint }, {}, '--ensure', false)+ ).rejects.toThrow('Command failed');+ expect(mocks.warn).toHaveBeenCalledWith(+ 'Could not remove a file staged for the shared host',+ expect.objectContaining({+ event: 'sdk_host.staged_file_cleanup',+ stage: 'command-failed',+ host: 'build-box',+ })+ );+});++it('fails a launch that ran when its staged configuration cannot be removed', async () => {+ const root = `${STATE}/sdk-sessions/abc`;+ host(entrypoint, async () => ({ stdout: '{"created":true}', stderr: '' }));+ removalFails();+ const ctx = { exec: mocks.sshExec } as never;++ await expect(+ runSharedHostCommand(ssh, { ctx, root, entrypoint }, {}, '--ensure', false)+ ).rejects.toThrow('Permission denied');+ expect(mocks.warn).not.toHaveBeenCalled();+});++it('stages a launch’s configuration on an SSH host in its state root, privately, and removes it', async () => {+ const config = { environment: { PRIVATE_TEST_VALUE: SECRET } };+ const root = `${STATE}/sdk-sessions/abc`;+ host(entrypoint, async () => ({ stdout: '{"created":true}', stderr: '' }));+ const ctx = { exec: mocks.sshExec } as never;++ await expect(+ runSharedHostCommand(ssh, { ctx, root, entrypoint }, config, '--ensure', true)+ ).resolves.toMatchObject({ stdout: '{"created":true}' });++ expect(scripts(MAKE_LAUNCH_DIR)).toEqual([[root, String(60 * 60 * 1000)]]);+ expect(mocks.copied).toEqual([+ { root: STAGED, dest: 'config.json', content: JSON.stringify(config), mode: 0o600 },+ ]);+ expect(scripts(CHMOD)).toEqual([[`${STAGED}/config.json`]]);+ const run = mocks.sshExec.mock.calls.find((call) => (call[1] as string[])[0] !== '-e')!;+ expect(run[1]).toEqual([entrypoint, root, `${STAGED}/config.json`, '--ensure', 'true']);+ expect(JSON.stringify(mocks.sshExec.mock.calls)).not.toContain(SECRET);+ expect(scripts(REMOVE)).toEqual([[STAGED]]);+});diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-host-deployment.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-host-deployment.tsindex 26c50b90f..b75f3f879 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-host-deployment.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-host-deployment.ts@@ -1,7 +1,7 @@import { createHash } from 'node:crypto';-import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';+import { mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises';import { tmpdir } from 'node:os';-import { join } from 'node:path';+import { join, posix } from 'node:path';import { resolveSharedHostBundlePath } from '@main/core/agent-runtime/impl/resolve-sidecar-bundle';import { LocalExecutionContext } from '@main/core/execution-context/local-execution-context';import { SshExecutionContext } from '@main/core/execution-context/ssh-execution-context';@@ -9,7 +9,8 @@ import type { IExecutionContext } from '@main/core/execution-context/types';import { SshFileSystem } from '@main/core/fs/impl/ssh-fs';import type { LocationTransport } from '@main/core/locations/location-transport';import { ensureSshConnected } from '@main/core/ssh/connect/connect-agent-ssh';-import { ensureHostBundle } from './host-bundle';+import { log } from '@main/lib/logger';+import { ensureHostBundle, forgetHostBundle, type HostBundle } from './host-bundle';import { MAKE_LAUNCH_DIR, RESOLVE_STATE_ROOT, STALE_LAUNCH_MS } from './state-roots';/**@@ -45,18 +46,227 @@ export async function locateSharedHost(): Promise<{ ctx: IExecutionContext; entrypoint: string } | null> {const bundle = resolveSharedHostBundlePath();if (transport.kind !== 'ssh') return { ctx: new LocalExecutionContext(), entrypoint: bundle };- const hash = createHash('sha256')- .update(await readFile(bundle))+ return locateBundle(transport, dir, (await sharedHostBundle()).file);+}++type SshTransport = Extract<LocationTransport, { kind: 'ssh' }>;++/** The last bundle hashed, so a file that has not changed is not read again. */+let hashed: {+ path: string;+ mtimeMs: number;+ size: number;+ bundle: { identity: string; file: string };+} | null = null;++/**+ * This build's shared-host bundle as a host knows it: its SHA-256, which is+ * what a watcher records as the `bundleIdentity` it runs, and the file name it+ * is deployed under, which is named after it.+ */+export async function sharedHostBundle(): Promise<{ identity: string; file: string }> {+ const path = resolveSharedHostBundlePath();+ const { mtimeMs, size } = await stat(path);+ if (hashed?.path === path && hashed.mtimeMs === mtimeMs && hashed.size === size)+ return hashed.bundle;+ const identity = createHash('sha256')+ .update(await readFile(path)).digest('hex');+ hashed = { path, mtimeMs, size, bundle: { identity, file: `shared-host-${identity}.mjs` } };+ return hashed.bundle;+}++async function locateBundle(+ transport: SshTransport,+ dir: string,+ name: string+): Promise<{ ctx: IExecutionContext; entrypoint: string } | null> {const proxy = await ensureSshConnected(transport.connectionId, transport.host);const ctx = new SshExecutionContext(proxy, { root: dir });- const { stdout } = await ctx.exec('node', ['-e', LOCATE_BUNDLE, `shared-host-${hash}.mjs`]);+ const { stdout } = await ctx.exec('node', ['-e', LOCATE_BUNDLE, name]);const entrypoint = stdout.trim();if (entrypoint) return { ctx, entrypoint };ctx.dispose();return null;}+/** How much a one-off command may print here before Node stops reading it. */+const REQUEST_MAX_BUFFER = 64 * 1024 * 1024;++/** A private file staged for one of the shared host's commands, and how to take it away. */+type StagedFile = { path: string; remove: () => Promise<void> };++/**+ * When a staged file could not be removed: while staging it failed part way,+ * after a one-off request (whatever its outcome), or after a launch command+ * failed.+ */+type StagedFileStage = 'staging-failed' | 'request-finished' | 'command-failed';++/**+ * Records that a staged file could not be removed, in place of throwing: the+ * failure must not hide how the command it was staged for went, and what is+ * left is swept with abandoned launches (`HOST_PREPARE`).+ */+function stagedFileLeft(stage: StagedFileStage, host: string | null, error: unknown): void {+ log.warn('Could not remove a file staged for the shared host', {+ event: 'sdk_host.staged_file_cleanup',+ stage,+ host,+ error: String(error),+ });+}++/**+ * Stages `content` as a file named `name` that only the user can read, for one+ * of the shared host's commands to read rather than take on its command line,+ * where `ps` would show it to everyone. It is written here first, mode 0600,+ * in a directory of its own. For an SSH host it is then copied over SFTP into+ * a new private directory under the state root `root`, made as a launch's is+ * (`MAKE_LAUNCH_DIR`), and made 0600 there as well. `remove()` takes away both+ * copies; a staging that fails part way removes what it had made, and throws+ * why it failed even when that removal fails too.+ */+async function stagePrivateFile(+ name: string,+ content: string,+ remote: { transport: SshTransport; ctx: IExecutionContext; root: string } | null+): Promise<StagedFile> {+ const local = await mkdtemp(join(tmpdir(), 'switch-sdk-launch-'));+ const localFile = join(local, name);+ let remoteDir: string | null = null;+ const remove = async () => {+ try {+ if (remote && remoteDir)+ await remote.ctx.exec('node', [+ '-e',+ "require('node:fs').rmSync(process.argv[1],{recursive:true,force:true})",+ remoteDir,+ ]);+ } finally {+ await rm(local, { recursive: true, force: true });+ }+ };+ try {+ await writeFile(localFile, content, { mode: 0o600 });+ if (!remote) return { path: localFile, remove };+ const proxy = await ensureSshConnected(remote.transport.connectionId, remote.transport.host);+ remoteDir = (+ await remote.ctx.exec('node', ['-e', MAKE_LAUNCH_DIR, remote.root, String(STALE_LAUNCH_MS)])+ ).stdout.trim();+ const fs = new SshFileSystem(proxy, remoteDir);+ try {+ await fs.copyLocalFile(localFile, name);+ } finally {+ fs.close();+ }+ const path = `${remoteDir}/${name}`;+ await remote.ctx.exec('node', [+ '-e',+ "require('node:fs').chmodSync(process.argv[1],0o600)",+ path,+ ]);+ return { path, remove };+ } catch (error) {+ await remove().catch((removal: unknown) =>+ stagedFileLeft('staging-failed', remote?.transport.host ?? null, removal)+ );+ throw error;+ }+}++/**+ * Answers a request with one of this build's shared host's one-off commands.+ * The request is staged as a private file (`stagePrivateFile`) beside a+ * launch's configuration and removed afterwards, since it can carry a shell+ * setup a command line would show to `ps`. Here it runs on Console's own+ * runtime, as local sessions do; on an SSH host it runs on the host's `node`.+ *+ * `deploy` uploads this build's bundle to an SSH host first when it is not+ * there, which only a launch may do. Without it the command runs only where+ * this build's bundle already is: reading a host must not change what is+ * installed there, and an earlier build's bundle may not know the command.+ */+export async function runHostRequest(+ transport: LocationTransport,+ mode: string,+ request: unknown,+ options: { deploy: boolean; timeout: number }+): Promise<{ stdout: string; stderr: string }> {+ if (transport.kind !== 'ssh') {+ const staged = await stagePrivateFile('request.json', JSON.stringify(request), null);+ const ctx = new LocalExecutionContext();+ try {+ return await ctx.exec(process.execPath, [resolveSharedHostBundlePath(), mode, staged.path], {+ env: { ELECTRON_RUN_AS_NODE: '1' },+ timeout: options.timeout,+ maxBuffer: REQUEST_MAX_BUFFER,+ });+ } finally {+ ctx.dispose();+ await staged+ .remove()+ .catch((error: unknown) => stagedFileLeft('request-finished', null, error));+ }+ }+ const bundle = options.deploy+ ? await ensureHostBundle(transport)+ : await thisBuildsBundle(transport);+ if (!bundle)+ throw new Error(+ `${transport.host} does not have this version of Switch Console's host yet. Start a session for an agent there, or press Update on its Room watcher, then try again.`+ );+ const proxy = await ensureSshConnected(transport.connectionId, transport.host);+ const ctx = new SshExecutionContext(proxy, { root: transport.dir });+ let staged: StagedFile | null = null;+ try {+ // Staged as a launch is, and swept with what abandoned launches left: the+ // script takes a state root, and finds `sdk-launch` beside its kind.+ staged = await stagePrivateFile('request.json', JSON.stringify(request), {+ transport,+ ctx,+ root: posix.join(posix.dirname(bundle.staging), 'sdk-sessions', 'cli-conversations'),+ });+ return await ctx.exec('node', [bundle.entrypoint, mode, staged.path], {+ timeout: options.timeout,+ });+ } catch (error) {+ // A bundle that has gone is one reason a launch fails; the next checks+ // again. A command that ran and refused says nothing about the bundle.+ const stderr = (error as { stderr?: unknown }).stderr;+ if (+ options.deploy &&+ typeof stderr === 'string' &&+ stderr.includes(posix.basename(bundle.entrypoint))+ )+ forgetHostBundle(transport.connectionId);+ throw error;+ } finally {+ if (staged)+ await staged+ .remove()+ .catch((error: unknown) => stagedFileLeft('request-finished', transport.host, error));+ ctx.dispose();+ }+}++/**+ * This build's bundle on an SSH host, found without deploying it, or null when+ * the host has another build's or none. Its staging directory sits beside the+ * bundle's, where `HOST_PREPARE` made both.+ */+async function thisBuildsBundle(transport: SshTransport): Promise<HostBundle | null> {+ const name = (await sharedHostBundle()).file;+ const located = await locateBundle(transport, transport.dir, name);+ if (!located) return null;+ located.ctx.dispose();+ if (posix.basename(located.entrypoint) !== name) return null;+ return {+ entrypoint: located.entrypoint,+ staging: posix.join(posix.dirname(posix.dirname(located.entrypoint)), 'sdk-launch'),+ };+}+export async function deploySharedHost(transport: LocationTransport,sessionPath: string,@@ -86,7 +296,7 @@ export async function deploySharedHost(/** The state root of `identity`'s watcher on an SSH host, and a context to act* in it, without deploying the host bundle. */export async function resolveWatcherRoot(- transport: Extract<LocationTransport, { kind: 'ssh' }>,+ transport: SshTransport,sessionPath: string,identity: string): Promise<{ ctx: IExecutionContext; root: string }> {@@ -110,51 +320,25 @@ export async function runSharedHostCommand(mode: '--ensure' | '--ensure-watch' | '--restart',resuming: boolean) {- const local = await mkdtemp(join(tmpdir(), 'switch-sdk-launch-'));- const localFile = join(local, 'config.json');- let remote: string | null = null;- try {- await writeFile(localFile, JSON.stringify(config), { mode: 0o600 });- let configPath = localFile;- if (transport.kind === 'ssh') {- const proxy = await ensureSshConnected(transport.connectionId, transport.host);- const result = await deployed.ctx.exec('node', [- '-e',- MAKE_LAUNCH_DIR,- deployed.root,- String(STALE_LAUNCH_MS),- ]);- remote = result.stdout.trim();- const fs = new SshFileSystem(proxy, remote);- try {- await fs.copyLocalFile(localFile, 'config.json');- } finally {- fs.close();- }- configPath = `${remote}/config.json`;- await deployed.ctx.exec('node', [- '-e',- "require('node:fs').chmodSync(process.argv[1],0o600)",- configPath,- ]);- }- return await deployed.ctx.exec('node', [- deployed.entrypoint,- deployed.root,- configPath,- mode,- String(resuming),- ]);- } finally {- try {- if (remote)- await deployed.ctx.exec('node', [- '-e',- "require('node:fs').rmSync(process.argv[1],{recursive:true,force:true})",- remote,- ]);- } finally {- await rm(local, { recursive: true, force: true });- }- }+ const staged = await stagePrivateFile(+ 'config.json',+ JSON.stringify(config),+ transport.kind === 'ssh' ? { transport, ctx: deployed.ctx, root: deployed.root } : null+ );+ const result = await deployed.ctx+ .exec('node', [deployed.entrypoint, deployed.root, staged.path, mode, String(resuming)])+ .catch(async (error: unknown) => {+ await staged+ .remove()+ .catch((removal: unknown) =>+ stagedFileLeft(+ 'command-failed',+ transport.kind === 'ssh' ? transport.host : null,+ removal+ )+ );+ throw error;+ });+ await staged.remove();+ return result;}diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/watcher-bundle-check.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/watcher-bundle-check.tsnew file mode 100644index 000000000..ebb51f25d--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/watcher-bundle-check.ts@@ -0,0 +1,26 @@+import type { IExecutionContext } from '@main/core/execution-context/types';+import { listHostWatchers, watcherRunsBundle } from './host-watchers';+import { sharedHostBundle } from './shared-host-deployment';++/**+ * Refuses a session that is to continue a CLI conversation when the agent's+ * Room watcher on `host` says it runs another build of Switch Console's host.+ * That watcher reads the session's configuration with its own schema: an+ * older one refuses the key and could not import the history anyway. One+ * whose build cannot be told, or no watcher at all, is not refused: handing+ * the session over says what is wrong, if anything is.+ *+ * Asked before such a session's conversation is copied, and again before its+ * first start, which imports the conversation.+ */+export async function ensureWatcherCanContinueCliConversation(+ ctx: IExecutionContext,+ host: string,+ switchAgentId: string+): Promise<void> {+ const watcher = (await listHostWatchers(ctx)).get(switchAgentId);+ if (watcherRunsBundle(watcher, await sharedHostBundle()) === false)+ throw new Error(+ `The Room watcher on ${host} does not run this version of Switch Console's host, so it cannot continue a CLI conversation. Press Update on its Room watcher, then try again.`+ );+}diff --git a/console/apps/switch-console-desktop/src/main/core/sessions/cli-conversation-forks.ts b/console/apps/switch-console-desktop/src/main/core/sessions/cli-conversation-forks.tsnew file mode 100644index 000000000..5b44d9a73--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/sessions/cli-conversation-forks.ts@@ -0,0 +1,29 @@+/**+ * The copies of CLI conversations being made for new sessions right now, by+ * session id, each settling with the copy's id once the session's row holds+ * it. A session's row is saved before its copy is made, so something can+ * start the session in between; it waits here for the copy rather than take+ * the missing id for a copy that was never made.+ *+ * In memory only: a copy in flight belongs to this run of Console, and one+ * that a restart cut short was never recorded.+ */+const inFlight = new Map<string, Promise<string>>();++/** Records `copy` as the copy being made for `sessionId` until it settles, and returns it. */+export function trackCliConversationFork(+ sessionId: string,+ copy: Promise<string>+): Promise<string> {+ inFlight.set(sessionId, copy);+ const settled = () => {+ if (inFlight.get(sessionId) === copy) inFlight.delete(sessionId);+ };+ copy.then(settled, settled);+ return copy;+}++/** The copy being made for this session, or undefined when none is. */+export function cliConversationForkInFlight(sessionId: string): Promise<string> | undefined {+ return inFlight.get(sessionId);+}diff --git a/console/apps/switch-console-desktop/src/main/core/sessions/cli-conversations.test.ts b/console/apps/switch-console-desktop/src/main/core/sessions/cli-conversations.test.tsnew file mode 100644index 000000000..abde84071--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/sessions/cli-conversations.test.ts@@ -0,0 +1,434 @@+import { MAX_SESSIONS_PER_REQUEST } from '@switch-console/agent-providers';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import {+ discardCliConversationCopies,+ forkCliConversation,+ HostRefusedError,+ listCliConversations,+} from './cli-conversations';++const mocks = vi.hoisted(() => ({+ getAgentById: vi.fn(),+ getLocation: vi.fn(),+ runHostRequest: vi.fn(),+ resolveSessionEnv: vi.fn(),+ warn: vi.fn(),+}));++vi.mock('@main/core/agents/getAgentById', () => ({ getAgentById: mocks.getAgentById }));+vi.mock('@main/core/locations/location-manager', () => ({+ locationManager: { getLocation: mocks.getLocation },+}));+vi.mock('@main/core/locations/location-runtime-factory', () => ({+ resolveSessionEnv: mocks.resolveSessionEnv,+}));+vi.mock('@main/core/sdk-host/shared-host-deployment', () => ({+ runHostRequest: mocks.runHostRequest,+}));+vi.mock('@main/lib/logger', () => ({ log: { info: vi.fn(), warn: mocks.warn } }));++let locations = 0;+/** An open location of its own, so what one test leaves to retry stays there. */+function newLocation() {+ locations += 1;+ return {+ locationId: `loc-${locations}`,+ dir: '/work',+ transport: { kind: 'local' },+ fs: {},+ settings: {},+ };+}+let location = newLocation();++function conversation(nativeSessionId: string) {+ return {+ nativeSessionId,+ title: nativeSessionId,+ lastActivityAt: 1,+ gitBranch: null,+ openIn: null,+ };+}++/** The requests the host was asked, in order: each command and the sessions it named. */+function asked(): [string, string | string[] | undefined][] {+ return mocks.runHostRequest.mock.calls.map(([, mode, request]) => {+ const { consoleSessionId, consoleSessionIds } = request as {+ consoleSessionId?: string;+ consoleSessionIds?: string[];+ };+ return [mode, consoleSessionIds ?? consoleSessionId];+ });+}++/**+ * Answers each host command with `answers[mode]`: a value is printed, an Error+ * is thrown, and a promise is waited for first.+ */+function hostAnswers(answers: Record<string, unknown>) {+ mocks.runHostRequest.mockImplementation(async (_transport, mode: string) => {+ const answer = await answers[mode];+ if (answer instanceof Error) throw answer;+ return { stdout: `${JSON.stringify(answer)}\n`, stderr: '' };+ });+}++/**+ * Answers a list with no conversations, and a removal with one copy found for+ * each session it names, but fails a removal that names `failing`.+ */+function hostRemovesCopies(failing: string | null) {+ mocks.runHostRequest.mockImplementation(+ async (_transport, mode: string, request: { consoleSessionIds?: string[] }) => {+ if (mode === '--cli-conversations')+ return { stdout: '{"ownershipKnown":true,"conversations":[]}\n', stderr: '' };+ const sessionIds = request.consoleSessionIds ?? [];+ if (failing !== null && sessionIds.includes(failing))+ throw new Error('ssh: connection reset');+ const deleted = Object.fromEntries(sessionIds.map((id) => [id, 1]));+ return { stdout: `${JSON.stringify({ deleted })}\n`, stderr: '' };+ }+ );+}++/** Ids for `count` sessions, in order. */+function sessionIds(count: number): string[] {+ return Array.from({ length: count }, (_, index) => `session-${index + 1}`);+}++/** What the host prints for a copy it refused to make. */+function refusal(error: string) {+ return Object.assign(new Error('Command failed'), {+ stdout: `${JSON.stringify({ error })}\n`,+ });+}++/** Lets the removals a list or copy started in the background finish. */+function removalsSettle(): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, 0));+}++afterEach(() => {+ vi.useRealTimers();+});++beforeEach(() => {+ vi.clearAllMocks();+ location = newLocation();+ mocks.getAgentById.mockResolvedValue({+ id: 'agent',+ locationId: location.locationId,+ providerId: 'claude',+ });+ mocks.getLocation.mockReturnValue(location);+ mocks.resolveSessionEnv.mockResolvedValue({+ sessionEnvVars: { SWITCHDASH_SESSION_ID: 'session-1' },+ shellSetup: 'export CLAUDE_CONFIG_DIR="$HOME/.claude-work"',+ });+});++it('lists the folder’s CLI conversations on its host without deploying, as the host gives them', async () => {+ mocks.runHostRequest.mockResolvedValue({+ stdout: `${JSON.stringify({ ownershipKnown: true, conversations: [conversation('cli-1')] })}\n`,+ stderr: '',+ });++ const result = await listCliConversations('agent');++ expect(mocks.runHostRequest).toHaveBeenCalledWith(+ location.transport,+ '--cli-conversations',+ expect.objectContaining({+ provider: 'claude',+ dir: '/work',+ shellSetup: 'export CLAUDE_CONFIG_DIR="$HOME/.claude-work"',+ inheritEnv: expect.arrayContaining(['CLAUDE_CONFIG_DIR', 'HOME']),+ }),+ { deploy: false, timeout: 60_000 }+ );+ expect(result).toEqual({+ success: true,+ data: { ownershipKnown: true, conversations: [conversation('cli-1')] },+ });+});++it('offers nothing for an agent that is not Claude Code', async () => {+ mocks.getAgentById.mockResolvedValue({ id: 'agent', locationId: 'loc', providerId: 'codex' });+ const result = await listCliConversations('agent');+ expect(result).toEqual({+ success: false,+ error: { message: 'Only Claude Code agents can continue a conversation started in its CLI.' },+ });+ expect(mocks.runHostRequest).not.toHaveBeenCalled();+});++it('copies with the session’s own environment, for the session to tag it with, deploying the host as a launch does', async () => {+ mocks.runHostRequest.mockResolvedValue({ stdout: '{"nativeSessionId":"copy-2"}\n', stderr: '' });+ await expect(+ forkCliConversation(location as never, { id: 'session-1', title: 'Fix' }, 'cli-1', true)+ ).resolves.toBe('copy-2');+ expect(mocks.resolveSessionEnv).toHaveBeenCalledWith(+ { id: 'session-1', title: 'Fix' },+ { path: '/work', fs: location.fs },+ location.settings+ );+ expect(mocks.runHostRequest).toHaveBeenCalledWith(+ location.transport,+ '--fork-cli-conversation',+ expect.objectContaining({+ env: { SWITCHDASH_SESSION_ID: 'session-1' },+ nativeSessionId: 'cli-1',+ consoleSessionId: 'session-1',+ confirmedClosed: true,+ }),+ { deploy: true, timeout: 120_000 }+ );+});++it('throws the reason the host gave for refusing a copy, not that its command failed', async () => {+ mocks.runHostRequest.mockRejectedValue(+ refusal(+ 'This conversation is open in Claude Code (process 41). Close it there, then try again.'+ )+ );+ const copied = forkCliConversation(+ location as never,+ { id: 'session-1', title: 'Fix' },+ 'cli-1',+ true+ );+ await expect(copied).rejects.toThrow('This conversation is open in Claude Code (process 41)');+ await expect(copied).rejects.toBeInstanceOf(HostRefusedError);+});++it('passes on a failure the host did not explain', async () => {+ const failure = new Error('ssh: connection refused');+ mocks.runHostRequest.mockRejectedValue(failure);+ await expect(+ forkCliConversation(location as never, { id: 'session-1', title: 'Fix' }, 'cli-1', true)+ ).rejects.toBe(failure);+});++it('removes the copies tagged as a session’s, reading the host without deploying', async () => {+ hostAnswers({ '--delete-cli-conversation-copies': { deleted: { 'session-1': 1 } } });+ await discardCliConversationCopies(location as never, 'session-1');+ expect(mocks.runHostRequest).toHaveBeenCalledWith(+ location.transport,+ '--delete-cli-conversation-copies',+ expect.objectContaining({ provider: 'claude', dir: '/work', consoleSessionIds: ['session-1'] }),+ { deploy: false, timeout: 60_000 }+ );+ mocks.runHostRequest.mockClear();+ hostAnswers({ '--cli-conversations': { ownershipKnown: true, conversations: [] } });+ await listCliConversations('agent');+ await removalsSettle();+ expect(asked()).toEqual([['--cli-conversations', undefined]]);+});++it('does not try again for a copy the host refused to make', async () => {+ hostAnswers({+ '--fork-cli-conversation': refusal('This conversation is open in Claude Code (process 41).'),+ '--delete-cli-conversation-copies': { deleted: { 'session-1': 0 } },+ '--cli-conversations': { ownershipKnown: true, conversations: [] },+ });+ await expect(+ forkCliConversation(location as never, { id: 'session-1', title: 'Fix' }, 'cli-1', true)+ ).rejects.toThrow('open in Claude Code');+ mocks.runHostRequest.mockClear();+ await listCliConversations('agent');+ await removalsSettle();+ expect(asked()).toEqual([['--cli-conversations', undefined]]);+});++it('keeps trying, with each list, to remove a copy whose outcome is unknown until a removal finds it', async () => {+ hostAnswers({+ '--fork-cli-conversation': new Error('Timed out after 120000ms'),+ '--delete-cli-conversation-copies': { deleted: { 'session-1': 0 } },+ '--cli-conversations': { ownershipKnown: true, conversations: [] },+ });+ await expect(+ forkCliConversation(location as never, { id: 'session-1', title: 'Fix' }, 'cli-1', true)+ ).rejects.toThrow('Timed out');+ // Found nothing: the copy may still be being made on the host.+ await discardCliConversationCopies(location as never, 'session-1');+ mocks.runHostRequest.mockClear();+ await listCliConversations('agent');+ await removalsSettle();+ expect(asked()).toContainEqual(['--delete-cli-conversation-copies', ['session-1']]);+ hostAnswers({+ '--delete-cli-conversation-copies': { deleted: { 'session-1': 1 } },+ '--cli-conversations': { ownershipKnown: true, conversations: [] },+ });+ mocks.runHostRequest.mockClear();+ await listCliConversations('agent');+ await removalsSettle();+ expect(asked()).toContainEqual(['--delete-cli-conversation-copies', ['session-1']]);+ mocks.runHostRequest.mockClear();+ await listCliConversations('agent');+ await removalsSettle();+ expect(asked()).toEqual([['--cli-conversations', undefined]]);+});++it('stops looking for a copy no removal found, long after its outcome became unknown, and says so', async () => {+ vi.useFakeTimers({ toFake: ['Date'] });+ vi.setSystemTime(new Date('2026-11-04T10:00:00.000Z'));+ hostAnswers({+ '--fork-cli-conversation': new Error('Timed out after 120000ms'),+ '--delete-cli-conversation-copies': { deleted: { 'session-1': 0 } },+ '--cli-conversations': { ownershipKnown: true, conversations: [] },+ });+ await expect(+ forkCliConversation(location as never, { id: 'session-1', title: 'Fix' }, 'cli-1', true)+ ).rejects.toThrow('Timed out');+ vi.setSystemTime(new Date('2026-11-04T10:14:00.000Z'));+ await listCliConversations('agent');+ await removalsSettle();+ expect(mocks.warn).not.toHaveBeenCalled();+ vi.setSystemTime(new Date('2026-11-04T10:15:00.000Z'));+ mocks.runHostRequest.mockClear();+ await listCliConversations('agent');+ await removalsSettle();+ expect(asked()).toContainEqual(['--delete-cli-conversation-copies', ['session-1']]);+ expect(mocks.warn).toHaveBeenCalledWith(+ expect.any(String),+ expect.objectContaining({+ event: 'cli_conversation.copy_cleanup',+ stage: 'abandoned',+ sessionId: 'session-1',+ recordedAt: '2026-11-04T10:00:00.000Z',+ })+ );+ mocks.runHostRequest.mockClear();+ await listCliConversations('agent');+ await removalsSettle();+ expect(asked()).toEqual([['--cli-conversations', undefined]]);+});++it('keeps trying, however long it takes, while removing a copy fails', async () => {+ vi.useFakeTimers({ toFake: ['Date'] });+ vi.setSystemTime(new Date('2026-11-04T10:00:00.000Z'));+ hostAnswers({ '--delete-cli-conversation-copies': new Error('ssh: connection reset') });+ await discardCliConversationCopies(location as never, 'session-1');+ expect(mocks.warn).toHaveBeenCalledWith(+ expect.any(String),+ expect.objectContaining({+ event: 'cli_conversation.copy_cleanup',+ stage: 'failed',+ sessionIds: ['session-1'],+ })+ );+ vi.setSystemTime(new Date('2026-11-04T11:00:00.000Z'));+ hostAnswers({+ '--delete-cli-conversation-copies': { deleted: { 'session-1': 1 } },+ '--fork-cli-conversation': { nativeSessionId: 'copy-2' },+ });+ mocks.runHostRequest.mockClear();+ await expect(+ forkCliConversation(location as never, { id: 'session-2', title: 'Fix' }, 'cli-1', true)+ ).resolves.toBe('copy-2');+ await removalsSettle();+ expect(asked()).toContainEqual(['--delete-cli-conversation-copies', ['session-1']]);+ // Another location's copies are its own.+ const elsewhere = newLocation();+ hostAnswers({ '--delete-cli-conversation-copies': new Error('ssh: connection reset') });+ await discardCliConversationCopies(elsewhere as never, 'session-3');+ hostAnswers({ '--cli-conversations': { ownershipKnown: true, conversations: [] } });+ mocks.runHostRequest.mockClear();+ await listCliConversations('agent');+ await removalsSettle();+ expect(asked()).toEqual([['--cli-conversations', undefined]]);+});++it('asks the host once for every session whose copies it is removing', async () => {+ hostAnswers({+ '--fork-cli-conversation': new Error('Timed out after 120000ms'),+ '--delete-cli-conversation-copies': new Error('ssh: connection reset'),+ });+ for (const id of ['session-1', 'session-2'])+ await expect(+ forkCliConversation(location as never, { id, title: 'Fix' }, 'cli-1', true)+ ).rejects.toThrow('Timed out');+ await removalsSettle();+ hostAnswers({+ '--delete-cli-conversation-copies': { deleted: { 'session-1': 1, 'session-2': 0 } },+ '--cli-conversations': { ownershipKnown: true, conversations: [] },+ });+ mocks.runHostRequest.mockClear();+ await listCliConversations('agent');+ await removalsSettle();+ expect(asked()).toEqual([+ ['--cli-conversations', undefined],+ ['--delete-cli-conversation-copies', ['session-1', 'session-2']],+ ]);+ mocks.runHostRequest.mockClear();+ await listCliConversations('agent');+ await removalsSettle();+ expect(asked()).toContainEqual(['--delete-cli-conversation-copies', ['session-2']]);+});++it('removes the copies of more sessions than one request may name in several requests', async () => {+ const ids = sessionIds(MAX_SESSIONS_PER_REQUEST + 1);+ hostRemovesCopies(null);+ await Promise.all(ids.map((id) => discardCliConversationCopies(location as never, id)));+ expect(asked()).toEqual([+ ['--delete-cli-conversation-copies', ids.slice(0, MAX_SESSIONS_PER_REQUEST)],+ ['--delete-cli-conversation-copies', ids.slice(MAX_SESSIONS_PER_REQUEST)],+ ]);+ mocks.runHostRequest.mockClear();+ await listCliConversations('agent');+ await removalsSettle();+ expect(asked()).toEqual([['--cli-conversations', undefined]]);+});++it('still asks about the other sessions when one request of a removal fails, and tries again only those it named', async () => {+ const ids = sessionIds(MAX_SESSIONS_PER_REQUEST + 1);+ const firstRequest = ids.slice(0, MAX_SESSIONS_PER_REQUEST);+ hostAnswers({ '--delete-cli-conversation-copies': new Error('ssh: connection reset') });+ await Promise.all(ids.map((id) => discardCliConversationCopies(location as never, id)));+ hostRemovesCopies('session-1');+ mocks.runHostRequest.mockClear();+ mocks.warn.mockClear();+ await listCliConversations('agent');+ await removalsSettle();+ expect(asked()).toEqual([+ ['--cli-conversations', undefined],+ ['--delete-cli-conversation-copies', firstRequest],+ ['--delete-cli-conversation-copies', ids.slice(MAX_SESSIONS_PER_REQUEST)],+ ]);+ expect(mocks.warn).toHaveBeenCalledTimes(1);+ expect(mocks.warn).toHaveBeenCalledWith(+ expect.any(String),+ expect.objectContaining({ stage: 'failed', sessionIds: firstRequest })+ );+ mocks.runHostRequest.mockClear();+ await listCliConversations('agent');+ await removalsSettle();+ expect(asked()).toEqual([+ ['--cli-conversations', undefined],+ ['--delete-cli-conversation-copies', firstRequest],+ ]);+});++it('does not hold up a list or a copy for the removals it starts', async () => {+ hostAnswers({+ '--fork-cli-conversation': new Error('Timed out after 120000ms'),+ '--delete-cli-conversation-copies': new Error('ssh: connection reset'),+ });+ await expect(+ forkCliConversation(location as never, { id: 'session-1', title: 'Fix' }, 'cli-1', true)+ ).rejects.toThrow('Timed out');+ await removalsSettle();+ hostAnswers({+ '--delete-cli-conversation-copies': new Promise(() => {}),+ '--cli-conversations': { ownershipKnown: true, conversations: [conversation('cli-1')] },+ '--fork-cli-conversation': { nativeSessionId: 'copy-2' },+ });+ await expect(listCliConversations('agent')).resolves.toEqual({+ success: true,+ data: { ownershipKnown: true, conversations: [conversation('cli-1')] },+ });+ await expect(+ forkCliConversation(location as never, { id: 'session-2', title: 'Fix' }, 'cli-1', true)+ ).resolves.toBe('copy-2');+});diff --git a/console/apps/switch-console-desktop/src/main/core/sessions/cli-conversations.ts b/console/apps/switch-console-desktop/src/main/core/sessions/cli-conversations.tsnew file mode 100644index 000000000..c142e731a--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/sessions/cli-conversations.ts@@ -0,0 +1,319 @@+import {+ type CliConversationMode,+ type CliConversationRequest,+ cliConversationFailureSchema,+ cliConversationListSchema,+ deletedCliConversationCopiesSchema,+ EXECUTION_INHERIT_ENV,+ forkedCliConversationSchema,+ MAX_SESSIONS_PER_REQUEST,+} from '@switch-console/agent-providers';+import { err, ok, type Result } from '@switch-console/shared';+import type { z } from 'zod';+import { getAgentById } from '@main/core/agents/getAgentById';+import { locationManager } from '@main/core/locations/location-manager';+import type { LocationProvider } from '@main/core/locations/location-provider';+import { resolveSessionEnv } from '@main/core/locations/location-runtime-factory';+import { runHostRequest } from '@main/core/sdk-host/shared-host-deployment';+import { log } from '@main/lib/logger';+import type { CliConversationList } from '@shared/core/sessions/cli-conversations';++/** How long listing may take on the host, its shell setup included. */+const LIST_TIMEOUT_MS = 60_000;+/** How long copying may take on the host: a long conversation is a large file. */+const FORK_TIMEOUT_MS = 120_000;+/** How long removing sessions' copies may take on the host. */+const DELETE_TIMEOUT_MS = 60_000;+/**+ * How long after a copy's outcome became unknown a removal that finds no copy+ * is taken at its word. Until then the copy may still be being made: a copy+ * Console stopped waiting for can finish on the host well after that.+ */+const UNSETTLED_COPY_WINDOW_MS = 15 * 60_000;++/**+ * What a request that is not one session's resolves the session's environment+ * with: it only says where the session's Claude Code would look.+ */+const NO_SESSION = { id: 'new-session', title: 'Session' };++/** The host ran the command and said why it failed, so its outcome is known. */+export class HostRefusedError extends Error {}++/**+ * Sessions whose copy may still be on a location's host, by location id, each+ * with when that was last found to be so: the copy was asked for and no+ * answer came back (a timeout, a dropped connection), so it may be made after+ * Console stopped waiting; or its session will not run, and the copy has yet+ * to be removed. Each list or copy in the location tries removing them again,+ * in the background. A session is forgotten once a removal finds its copy, or+ * once one finds none {@link UNSETTLED_COPY_WINDOW_MS} after it was recorded; a+ * removal that fails says nothing, and is tried again. In memory only, so a+ * copy whose session is forgotten across a restart stays; it is still tagged+ * as a copy and hidden from the dialog.+ */+const unsettledCopies = new Map<string, Map<string, number>>();++/** The removal running in each location, by location id, which the next one there follows. */+const removals = new Map<string, Promise<void>>();++/**+ * The conversations started in Claude Code's own CLI in an agent's folder that+ * a new session could continue, read on the machine the agent's sessions run+ * on. Copies Console made, its sessions' own among them, are left out by the+ * host.+ *+ * Only reads the host: on an SSH host without this build's bundle it says so+ * rather than deploying one.+ */+export async function listCliConversations(+ agentId: string+): Promise<Result<CliConversationList, { message: string }>> {+ try {+ const agent = await getAgentById(agentId);+ if (!agent) throw new Error('This agent no longer exists.');+ if (agent.providerId !== 'claude')+ throw new Error('Only Claude Code agents can continue a conversation started in its CLI.');+ const location = locationManager.getLocation(agent.locationId);+ if (!location) throw new Error('Open the agent’s folder in Console first.');+ const request = await conversationRequest(location, NO_SESSION);+ void removeUnsettledCopies(location);+ return ok(+ await runConversationRequest(+ location,+ '--cli-conversations',+ request,+ { deploy: false, timeout: LIST_TIMEOUT_MS },+ cliConversationListSchema+ )+ );+ } catch (error) {+ return err({ message: error instanceof Error ? error.message : String(error) });+ }+}++/**+ * Copies a conversation started in Claude Code's CLI for `session` to continue,+ * and returns the copy's id. The copy is tagged with the session, so a copy+ * whose session never starts can be removed ({@link discardCliConversationCopies}).+ * Refused while a Claude Code process has the conversation open, or, where+ * Claude Code cannot say, unless the person said it is closed. A copy the host+ * refused, a {@link HostRefusedError}, leaves none tagged as the session's.+ * Part of starting the session, so it deploys this build's bundle to an SSH+ * host that lacks it.+ */+export async function forkCliConversation(+ location: LocationProvider,+ session: { id: string; title: string },+ nativeSessionId: string,+ confirmedClosed: boolean+): Promise<string> {+ const request = await conversationRequest(location, session);+ void removeUnsettledCopies(location);+ const fork = await runConversationRequest(+ location,+ '--fork-cli-conversation',+ { ...request, nativeSessionId, consoleSessionId: session.id, confirmedClosed },+ { deploy: true, timeout: FORK_TIMEOUT_MS },+ forkedCliConversationSchema+ ).catch((error: unknown) => {+ if (!(error instanceof HostRefusedError)) rememberUnsettledCopy(location, session.id);+ throw error;+ });+ return fork.nativeSessionId;+}++/**+ * Removes the copies made for a session that will not run: its copy's+ * outcome is unknown, or it finished after the session's row was deleted.+ * Only conversations tagged as this session's are removed, and the session is+ * tried again with the location's next list or copy until its copy is found+ * or long enough has passed ({@link unsettledCopies}). Nothing needs to wait+ * for it: the returned promise settles once this attempt is over and never+ * rejects, so it cannot hide why the session did not start.+ */+export function discardCliConversationCopies(+ location: LocationProvider,+ sessionId: string+): Promise<void> {+ rememberUnsettledCopy(location, sessionId);+ return removeUnsettledCopies(location);+}++function rememberUnsettledCopy(location: LocationProvider, sessionId: string): void {+ const sessions = unsettledCopies.get(location.locationId) ?? new Map<string, number>();+ sessions.set(sessionId, Date.now());+ unsettledCopies.set(location.locationId, sessions);+}++/**+ * Tries again to remove the copies {@link unsettledCopies} holds for this+ * location, once the removal already running there is over, and settles when+ * it is. Never rejects.+ */+function removeUnsettledCopies(location: LocationProvider): Promise<void> {+ const next = (removals.get(location.locationId) ?? Promise.resolve()).then(() =>+ removeCopiesOnce(location)+ );+ removals.set(location.locationId, next);+ void next.then(() => {+ if (removals.get(location.locationId) === next) removals.delete(location.locationId);+ });+ return next;+}++/**+ * One attempt at {@link removeUnsettledCopies}, with one request to the host+ * for each {@link MAX_SESSIONS_PER_REQUEST} sessions, each made whether or not+ * the one before it failed. Never throws.+ */+async function removeCopiesOnce(location: LocationProvider): Promise<void> {+ const sessions = unsettledCopies.get(location.locationId);+ if (!sessions?.size) return;+ const sessionIds = [...sessions.keys()];+ for (let start = 0; start < sessionIds.length; start += MAX_SESSIONS_PER_REQUEST)+ await removeSomeCopies(+ location,+ sessions,+ sessionIds.slice(start, start + MAX_SESSIONS_PER_REQUEST)+ );+ if (sessions.size === 0 && unsettledCopies.get(location.locationId) === sessions)+ unsettledCopies.delete(location.locationId);+}++/**+ * One request of {@link removeCopiesOnce}: removes these sessions' copies and+ * forgets each session whose copy was found, or was looked for long enough. A+ * request that fails forgets none of them. Never throws.+ */+async function removeSomeCopies(+ location: LocationProvider,+ sessions: Map<string, number>,+ sessionIds: string[]+): Promise<void> {+ let deleted: Record<string, number>;+ try {+ deleted = await deleteCopies(location, sessionIds);+ } catch (error) {+ log.warn(+ 'Could not remove the copies of CLI conversations made for sessions that did not start',+ {+ event: 'cli_conversation.copy_cleanup',+ stage: 'failed',+ sessionIds,+ error: String(error),+ }+ );+ return;+ }+ const now = Date.now();+ for (const sessionId of sessionIds) {+ const recordedAt = sessions.get(sessionId);+ if (recordedAt === undefined) continue;+ const count = deleted[sessionId] ?? 0;+ if (count > 0) {+ sessions.delete(sessionId);+ log.info('Removed the copy of a CLI conversation made for a session that did not start', {+ event: 'cli_conversation.copy_cleanup',+ stage: 'removed',+ sessionId,+ deleted: count,+ });+ } else if (now - recordedAt >= UNSETTLED_COPY_WINDOW_MS) {+ sessions.delete(sessionId);+ log.warn(+ 'Stopped looking for the copy of a CLI conversation made for a session that did not start: none was found long after it was asked for',+ {+ event: 'cli_conversation.copy_cleanup',+ stage: 'abandoned',+ sessionId,+ recordedAt: new Date(recordedAt).toISOString(),+ }+ );+ }+ }+}++/**+ * Removes the copies tagged as these sessions', at most+ * {@link MAX_SESSIONS_PER_REQUEST} of them, in one request, and says how many+ * each had.+ */+async function deleteCopies(+ location: LocationProvider,+ sessionIds: string[]+): Promise<Record<string, number>> {+ const request = await conversationRequest(location, NO_SESSION);+ const { deleted } = await runConversationRequest(+ location,+ '--delete-cli-conversation-copies',+ { ...request, consoleSessionIds: sessionIds },+ { deploy: false, timeout: DELETE_TIMEOUT_MS },+ deletedCliConversationCopiesSchema+ );+ return deleted;+}++/**+ * What the host needs to look for conversations where the session's Claude+ * Code will: the variables, shell setup and inherited names its host starts+ * the provider with (`buildSharedHostConfig`).+ */+async function conversationRequest(+ location: LocationProvider,+ session: { id: string; title: string }+): Promise<CliConversationRequest> {+ const { sessionEnvVars, shellSetup } = await resolveSessionEnv(+ session,+ { path: location.dir, fs: location.fs },+ location.settings+ );+ return {+ provider: 'claude',+ dir: location.dir,+ env: sessionEnvVars,+ ...(shellSetup ? { shellSetup } : {}),+ inheritEnv: [...EXECUTION_INHERIT_ENV],+ };+}++/**+ * Runs one of the shared host's conversation commands where the location's+ * sessions run. A command that fails prints why on stdout; that reason is what+ * is thrown, as a {@link HostRefusedError}, rather than that the command+ * exited 1.+ */+async function runConversationRequest<T>(+ location: LocationProvider,+ mode: CliConversationMode,+ request: CliConversationRequest,+ options: { deploy: boolean; timeout: number },+ schema: z.ZodType<T>+): Promise<T> {+ let stdout: string;+ try {+ ({ stdout } = await runHostRequest(location.transport, mode, request, options));+ } catch (error) {+ const failure = cliConversationFailureSchema.safeParse(lastJsonLine(error));+ if (failure.success) throw new HostRefusedError(failure.data.error);+ throw error;+ }+ const answer = schema.safeParse(lastJsonLine({ stdout }));+ if (!answer.success)+ throw new Error(+ `Could not read what the agent's host answered: ${stdout.trim().slice(0, 200) || 'it printed nothing'}`+ );+ return answer.data;+}++function lastJsonLine(output: unknown): unknown {+ const stdout = (output as { stdout?: unknown } | null)?.stdout;+ if (typeof stdout !== 'string') return undefined;+ const line = stdout.trim().split('\n').at(-1);+ if (!line) return undefined;+ try {+ return JSON.parse(line);+ } catch {+ return undefined;+ }+}diff --git a/console/apps/switch-console-desktop/src/main/core/sessions/controller.ts b/console/apps/switch-console-desktop/src/main/core/sessions/controller.tsindex ff748b658..ead360fec 100644--- a/console/apps/switch-console-desktop/src/main/core/sessions/controller.ts+++ b/console/apps/switch-console-desktop/src/main/core/sessions/controller.ts@@ -2,6 +2,7 @@ import { provisionTriggerOf } from '@main/core/telemetry/narrow';import type { CreateSessionParams, SessionLifecycleStatus } from '@shared/core/sessions/sessions';import type { SessionProvisionTrigger } from '@shared/core/telemetry/reporting';import { createRPCController } from '@shared/lib/ipc/rpc';+import { listCliConversations } from './cli-conversations';import { dehydrateSession } from './operations/dehydrateSession';import { getSession } from './operations/getSession';import { hydrateSession } from './operations/hydrateSession';@@ -17,6 +18,8 @@ export const sessionController = createRPCController({async createSession(params: CreateSessionParams) {return sessionService.createSession(params);},+ /** The conversations started in Claude Code's CLI in an agent's folder that a session could continue. */+ listCliConversations,async getSessions(locationId?: string) {return sessionService.getSessions(locationId);},diff --git a/console/apps/switch-console-desktop/src/main/core/sessions/operations/createSession.test.ts b/console/apps/switch-console-desktop/src/main/core/sessions/operations/createSession.test.tsindex 443c4ef9c..d2ebc7347 100644--- a/console/apps/switch-console-desktop/src/main/core/sessions/operations/createSession.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/sessions/operations/createSession.test.ts@@ -1,5 +1,7 @@import { beforeEach, describe, expect, it, vi } from 'vitest';import type { SessionRow } from '@main/db/schema';+import { cliConversationForkInFlight } from '../cli-conversation-forks';+import { HostRefusedError } from '../cli-conversations';import { createSession } from './createSession';const mocks = vi.hoisted(() => ({@@ -12,6 +14,27 @@ const mocks = vi.hoisted(() => ({provisionSessionRuntime: vi.fn(),registerSession: vi.fn(),startSession: vi.fn(),+ forkCliConversation: vi.fn(),+ discardCliConversationCopies: vi.fn(),+ setProviderSessionId: vi.fn(),+ watcherCheck: vi.fn(),+ logError: vi.fn(),+}));++vi.mock('@main/core/sdk-host/watcher-bundle-check', () => ({+ ensureWatcherCanContinueCliConversation: mocks.watcherCheck,+}));++vi.mock('@main/lib/logger', () => ({ log: { error: mocks.logError } }));++vi.mock('./set-provider-session-id', () => ({+ setProviderSessionId: mocks.setProviderSessionId,+}));++vi.mock('../cli-conversations', () => ({+ forkCliConversation: mocks.forkCliConversation,+ discardCliConversationCopies: mocks.discardCliConversationCopies,+ HostRefusedError: class HostRefusedError extends Error {},}));vi.mock('@main/core/agents/getAgentById', () => ({@@ -84,7 +107,13 @@ describe('createSession', () => {locationId: 'loc-1',providerId: 'claude',});- mocks.getLocation.mockReturnValue({ locationId: 'loc-1', dir: '/repo', ctx: {} });+ mocks.getLocation.mockReturnValue({+ locationId: 'loc-1',+ dir: '/repo',+ ctx: {},+ transport: { kind: 'local' },+ });+ mocks.watcherCheck.mockResolvedValue(undefined);mocks.provisionSessionRuntime.mockResolvedValue({path: '/repo',locationId: 'loc-1',@@ -102,6 +131,225 @@ describe('createSession', () => {expect(mocks.insert).not.toHaveBeenCalled();});+ it('continues a copy of a CLI conversation, recording which one it continues', async () => {+ mocks.forkCliConversation.mockResolvedValue('copy-1');+ mocks.setProviderSessionId.mockResolvedValue(true);+ const cliConversation = { nativeSessionId: 'cli-1', title: 'Fix the build' };+ const result = await createSession({+ ...baseParams,+ cliConversation: { ...cliConversation, confirmedClosed: true },+ });+ expect(result.success).toBe(true);+ if (!result.success) throw new Error('Expected session creation to succeed');+ expect(mocks.forkCliConversation).toHaveBeenCalledWith(+ expect.objectContaining({ dir: '/repo' }),+ { id: 'session-1', title: 'Test Session' },+ 'cli-1',+ true+ );+ // The row exists before the copy is made, so the copy always has an owner.+ expect(mocks.insert.mock.invocationCallOrder[0]).toBeLessThan(+ mocks.forkCliConversation.mock.invocationCallOrder[0]!+ );+ expect(mocks.setProviderSessionId).toHaveBeenCalledWith('session-1', 'copy-1');+ expect(result.data.session.providerSessionId).toBe('copy-1');+ expect(result.data.session.cliConversation).toEqual(cliConversation);+ expect(mocks.discardCliConversationCopies).not.toHaveBeenCalled();+ expect(mocks.startSession).toHaveBeenCalledWith(+ expect.objectContaining({ providerSessionId: 'copy-1' }),+ false,+ undefined,+ null+ );+ });++ it('does not start a session deleted while its conversation was being copied, and removes the copy', async () => {+ mocks.forkCliConversation.mockResolvedValue('copy-1');+ mocks.setProviderSessionId.mockResolvedValue(false);+ const result = await createSession({+ ...baseParams,+ cliConversation: { nativeSessionId: 'cli-1', title: 'Fix the build', confirmedClosed: false },+ });+ expect(result).toEqual({+ success: false,+ error: {+ type: 'spawn-failed',+ message: 'This session was deleted while its conversation was being copied.',+ },+ });+ expect(mocks.discardCliConversationCopies).toHaveBeenCalledWith(+ expect.objectContaining({ dir: '/repo' }),+ 'session-1'+ );+ expect(mocks.provisionSessionRuntime).not.toHaveBeenCalled();+ expect(mocks.startSession).not.toHaveBeenCalled();+ });++ it('lets anything that starts the session while its copy is made wait for the copy', async () => {+ let made!: (id: string) => void;+ mocks.forkCliConversation.mockReturnValue(+ new Promise<string>((resolve) => {+ made = resolve;+ })+ );+ mocks.setProviderSessionId.mockResolvedValue(true);+ const created = createSession({+ ...baseParams,+ cliConversation: { nativeSessionId: 'cli-1', title: 'Fix the build', confirmedClosed: true },+ });+ await vi.waitFor(() => expect(mocks.forkCliConversation).toHaveBeenCalled());+ const waiting = cliConversationForkInFlight('session-1');+ expect(waiting).toBeDefined();+ made('copy-1');+ // Settled once the row holds the copy, not merely once the copy exists.+ await expect(waiting).resolves.toBe('copy-1');+ expect(mocks.setProviderSessionId).toHaveBeenCalledWith('session-1', 'copy-1');+ await created;+ expect(cliConversationForkInFlight('session-1')).toBeUndefined();+ });++ it('takes the session away again when the host refuses to copy the CLI conversation, with no copy to remove', async () => {+ mocks.forkCliConversation.mockRejectedValue(+ new HostRefusedError(+ 'This conversation is open in Claude Code (process 41). Close it there, then try again.'+ )+ );+ const result = await createSession({+ ...baseParams,+ cliConversation: { nativeSessionId: 'cli-1', title: 'Fix the build', confirmedClosed: false },+ });+ expect(result).toEqual({+ success: false,+ error: {+ type: 'spawn-failed',+ message:+ 'This conversation is open in Claude Code (process 41). Close it there, then try again.',+ },+ });+ expect(mocks.deleteFn).toHaveBeenCalledTimes(1);+ expect(mocks.discardCliConversationCopies).not.toHaveBeenCalled();+ expect(mocks.startSession).not.toHaveBeenCalled();+ });++ it('takes the session away again and removes any copy when copying gave no answer', async () => {+ mocks.forkCliConversation.mockRejectedValue(new Error('Timed out after 120000ms'));+ const result = await createSession({+ ...baseParams,+ cliConversation: { nativeSessionId: 'cli-1', title: 'Fix the build', confirmedClosed: true },+ });+ expect(result).toEqual({+ success: false,+ error: { type: 'spawn-failed', message: 'Timed out after 120000ms' },+ });+ expect(mocks.deleteFn).toHaveBeenCalledTimes(1);+ expect(mocks.discardCliConversationCopies).toHaveBeenCalledWith(+ expect.objectContaining({ dir: '/repo' }),+ 'session-1'+ );+ expect(mocks.startSession).not.toHaveBeenCalled();+ });++ it('still says why the copy failed when the session cannot be taken away again', async () => {+ mocks.forkCliConversation.mockRejectedValue(new Error('Timed out after 120000ms'));+ mocks.deleteFn.mockReturnValue({+ where: () => Promise.reject(new Error('SQLITE_BUSY: database is locked')),+ });+ const result = await createSession({+ ...baseParams,+ cliConversation: { nativeSessionId: 'cli-1', title: 'Fix the build', confirmedClosed: true },+ });+ expect(result).toEqual({+ success: false,+ error: { type: 'spawn-failed', message: 'Timed out after 120000ms' },+ });+ expect(mocks.discardCliConversationCopies).toHaveBeenCalledWith(+ expect.objectContaining({ dir: '/repo' }),+ 'session-1'+ );+ expect(mocks.logError).toHaveBeenCalledWith(+ expect.any(String),+ expect.objectContaining({+ event: 'cli_conversation.session_rollback',+ stage: 'delete-failed',+ sessionId: 'session-1',+ error: 'Error: SQLITE_BUSY: database is locked',+ })+ );+ });++ it('asks an SSH host’s Room watcher whether it can continue a CLI conversation before anything is recorded or copied', async () => {+ const ctx = { exec: vi.fn() };+ mocks.getAgentById.mockResolvedValue({+ id: 'agent-1',+ locationId: 'loc-1',+ providerId: 'claude',+ switchAgentId: 'switch-agent-1',+ });+ mocks.getLocation.mockReturnValue({+ locationId: 'loc-1',+ dir: '/repo',+ ctx,+ transport: { kind: 'ssh', host: 'build-box', dir: '/repo', connectionId: 'conn-1' },+ });+ mocks.watcherCheck.mockRejectedValue(+ new Error("The Room watcher on build-box does not run this version of Switch Console's host")+ );+ const result = await createSession({+ ...baseParams,+ cliConversation: { nativeSessionId: 'cli-1', title: 'Fix the build', confirmedClosed: true },+ });+ expect(result).toEqual({+ success: false,+ error: {+ type: 'spawn-failed',+ message: "The Room watcher on build-box does not run this version of Switch Console's host",+ },+ });+ expect(mocks.watcherCheck).toHaveBeenCalledWith(ctx, 'build-box', 'switch-agent-1');+ expect(mocks.insert).not.toHaveBeenCalled();+ expect(mocks.forkCliConversation).not.toHaveBeenCalled();+ expect(mocks.setProviderSessionId).not.toHaveBeenCalled();++ mocks.watcherCheck.mockResolvedValue(undefined);+ mocks.forkCliConversation.mockResolvedValue('copy-1');+ mocks.setProviderSessionId.mockResolvedValue(true);+ const continued = await createSession({+ ...baseParams,+ cliConversation: { nativeSessionId: 'cli-1', title: 'Fix the build', confirmedClosed: true },+ });+ expect(continued.success).toBe(true);+ expect(mocks.watcherCheck.mock.invocationCallOrder.at(-1)).toBeLessThan(+ mocks.insert.mock.invocationCallOrder[0]!+ );+ });++ it('does not ask a Room watcher about a session that continues no CLI conversation', async () => {+ mocks.getLocation.mockReturnValue({+ locationId: 'loc-1',+ dir: '/repo',+ ctx: {},+ transport: { kind: 'ssh', host: 'build-box', dir: '/repo', connectionId: 'conn-1' },+ });+ const result = await createSession(baseParams);+ expect(result.success).toBe(true);+ expect(mocks.watcherCheck).not.toHaveBeenCalled();+ });++ it('refuses to continue a CLI conversation for an agent that is not Claude Code', async () => {+ mocks.getAgentById.mockResolvedValue({+ id: 'agent-1',+ locationId: 'loc-1',+ providerId: 'codex',+ });+ const result = await createSession({+ ...baseParams,+ cliConversation: { nativeSessionId: 'cli-1', title: 'Fix the build', confirmedClosed: false },+ });+ expect(result.success).toBe(false);+ expect(mocks.forkCliConversation).not.toHaveBeenCalled();+ expect(mocks.insert).not.toHaveBeenCalled();+ });+it('inserts the session and provisions the runtime', async () => {const result = await createSession(baseParams);expect(result.success).toBe(true);diff --git a/console/apps/switch-console-desktop/src/main/core/sessions/operations/createSession.ts b/console/apps/switch-console-desktop/src/main/core/sessions/operations/createSession.tsindex 237ff3806..0950da20f 100644--- a/console/apps/switch-console-desktop/src/main/core/sessions/operations/createSession.ts+++ b/console/apps/switch-console-desktop/src/main/core/sessions/operations/createSession.ts@@ -4,8 +4,10 @@ import { eq, sql } from 'drizzle-orm';import { providerAdapterRegistry } from '@main/core/agent-runtime/impl/provider-adapter-registry';import { getAgentById } from '@main/core/agents/getAgentById';import { locationManager } from '@main/core/locations/location-manager';+import { ensureWatcherCanContinueCliConversation } from '@main/core/sdk-host/watcher-bundle-check';import { db } from '@main/db/client';import { sessions } from '@main/db/schema';+import { log } from '@main/lib/logger';import { providerNamesSentence } from '@shared/core/providers/agent-provider-registry';import type { SessionConfig } from '@shared/core/sessions/session-config';import type {@@ -14,9 +16,16 @@ import type {CreateSessionParams,} from '@shared/core/sessions/sessions';import type { SessionStartSource } from '@shared/core/telemetry/reporting';+import { trackCliConversationFork } from '../cli-conversation-forks';+import {+ discardCliConversationCopies,+ forkCliConversation,+ HostRefusedError,+} from '../cli-conversations';import { provisionSessionRuntime } from '../session-builder';import { sessionRuntimeManager } from '../session-runtime-manager';import { mapSessionRowToSession } from '../utils/utils';+import { setProviderSessionId } from './set-provider-session-id';/*** What the session's host tells Switch about how it started. `adopted` never@@ -52,6 +61,30 @@ export async function createSession(const configObj: SessionConfig = {};if (params.initialPrompt?.trim()) configObj.initialPrompt = params.initialPrompt.trim();+ if (params.cliConversation) {+ if (!location) return err({ type: 'agent-not-found' });+ if (agent.providerId !== 'claude')+ return err({+ type: 'spawn-failed',+ message: 'Only Claude Code agents can continue a conversation started in its CLI.',+ });+ // Asked before anything is recorded or copied, so a session its Room+ // watcher could not start is never left holding a copy.+ if (location.transport.kind === 'ssh' && agent.switchAgentId)+ try {+ await ensureWatcherCanContinueCliConversation(+ location.ctx,+ location.transport.host,+ agent.switchAgentId+ );+ } catch (e) {+ return err({ type: 'spawn-failed', message: e instanceof Error ? e.message : String(e) });+ }+ configObj.cliConversation = {+ nativeSessionId: params.cliConversation.nativeSessionId,+ title: params.cliConversation.title,+ };+ }// The session's launch identity is not stored — it is read live from the// owning agent's `name` (see mapSessionRowToSession). How that name spawns is// the provider's business (Claude Code → `--agent <name>`) (CHOO-1440).@@ -78,10 +111,51 @@ export async function createSession(// as a Result instead of a raw UNIQUE-constraint throw.if (!row) return err({ type: 'already-exists' });- const session = mapSessionRowToSession(row, agent.providerId, agent.name);+ let session = mapSessionRowToSession(row, agent.providerId, agent.name);if (adopted) return ok({ session });if (!location) return err({ type: 'agent-not-found' });+ if (params.cliConversation) {+ // Copied once the session's row holds its id, tagged with it, so a copy+ // always names a session to own it. One that cannot be made (open in a+ // terminal, say) takes the row away again, and whatever copy was made is+ // removed; one the host refused left none. The copy is what the session+ // resumes; the CLI's own conversation is never written to. Anything that+ // starts the session while the copy is made waits for it+ // (`trackCliConversationFork`).+ const { nativeSessionId, confirmedClosed } = params.cliConversation;+ const owner = { id: session.id, title: session.title };+ try {+ const providerSessionId = await trackCliConversationFork(+ session.id,+ (async () => {+ const copy = await forkCliConversation(location, owner, nativeSessionId, confirmedClosed);+ // Into the row as it stands after the copy, which can take a while.+ if (!(await setProviderSessionId(owner.id, copy)))+ throw new Error('This session was deleted while its conversation was being copied.');+ return copy;+ })()+ );+ session = { ...session, providerSessionId };+ } catch (e) {+ // Not waited for: it never throws, and the reason the session did not+ // start is what the person is waiting to hear.+ if (!(e instanceof HostRefusedError)) void discardCliConversationCopies(location, session.id);+ try {+ await db.delete(sessions).where(eq(sessions.id, session.id));+ } catch (removal) {+ // The reason the copy failed is still the one to give. The row left+ // behind refuses to start, saying its copy was never made.+ log.error('Could not remove a session whose CLI conversation was not copied', {+ event: 'cli_conversation.session_rollback',+ stage: 'delete-failed',+ sessionId: session.id,+ error: String(removal),+ });+ }+ return err({ type: 'spawn-failed', message: e instanceof Error ? e.message : String(e) });+ }+ }try {const built = await provisionSessionRuntime(session, location);await sessionRuntimeManager.registerSession(session.id, built, location.ctx);diff --git a/console/apps/switch-console-desktop/src/main/core/sessions/utils/utils.ts b/console/apps/switch-console-desktop/src/main/core/sessions/utils/utils.tsindex ecb009d55..312b4dc8a 100644--- a/console/apps/switch-console-desktop/src/main/core/sessions/utils/utils.ts+++ b/console/apps/switch-console-desktop/src/main/core/sessions/utils/utils.ts@@ -39,6 +39,7 @@ export function mapSessionRowToSession(autoApprove: config.autoApprove,autoMode: config.autoMode,providerSessionId: config.providerSessionId,+ cliConversation: config.cliConversation,initialPromptDelivery: config.initialPromptDelivery,agentName,createdAt: row.createdAt,diff --git a/console/apps/switch-console-desktop/src/renderer/features/sessions/create-session-modal/cli-conversation-field.tsx b/console/apps/switch-console-desktop/src/renderer/features/sessions/create-session-modal/cli-conversation-field.tsxnew file mode 100644index 000000000..6f54de425--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/sessions/create-session-modal/cli-conversation-field.tsx@@ -0,0 +1,194 @@+import { useQuery } from '@tanstack/react-query';+import { ChevronDown } from 'lucide-react';+import { useState } from 'react';+import { failureText } from '@renderer/lib/errors/describe-failure';+import { rpc } from '@renderer/lib/ipc';+import { Checkbox } from '@renderer/lib/ui/checkbox';+import {+ Combobox,+ ComboboxContent,+ ComboboxEmpty,+ ComboboxInput,+ ComboboxItem,+ ComboboxList,+ ComboboxTrigger,+} from '@renderer/lib/ui/combobox';+import { Field, FieldLabel } from '@renderer/lib/ui/field';+import { RelativeTime } from '@renderer/lib/ui/relative-time';+import { cn } from '@renderer/utils/utils';+import type { CliConversation, CliConversationList } from '@shared/core/sessions/cli-conversations';++/**+ * The conversations started in Claude Code's own CLI in an agent's folder, read+ * on the machine its sessions run on. Asked for only once `request` is called,+ * when the person opens the picker: each read runs on the agent's host, and+ * most sessions start a new conversation. A listing that failed is asked for+ * again the next time the picker opens; one that succeeded is kept. Never+ * asked for when `agentId` is null.+ */+export function useCliConversations(agentId: string | null): {+ list: CliConversationList | null;+ loading: boolean;+ error: string | null;+ request: () => void;+} {+ const [requestedFor, setRequestedFor] = useState<string | null>(null);+ const query = useQuery({+ queryKey: ['cliConversations', agentId],+ queryFn: () => rpc.sessions.listCliConversations(agentId!),+ enabled: agentId !== null && requestedFor === agentId,+ // Read afresh each time the dialog is opened and the picker with it, since+ // whether a terminal has one open changes from minute to minute; kept for+ // the rest of that dialog, and not read again on every return to the+ // window. The copy checks again.+ staleTime: 0,+ gcTime: 0,+ refetchOnWindowFocus: false,+ });+ const result = query.data;+ const error = query.error+ ? failureText(query.error, 'Could not list the agent’s Claude Code conversations.')+ : result && !result.success+ ? result.error.message+ : null;+ const retrying = error !== null && query.isFetching;+ return {+ request: () => {+ if (requestedFor !== agentId) setRequestedFor(agentId);+ else if (error !== null && !query.isFetching) void query.refetch();+ },+ list: result?.success ? result.data : null,+ loading: query.isLoading || retrying,+ error: retrying ? null : error,+ };+}++const TRIGGER =+ 'flex h-9 w-full min-w-0 items-center gap-2 rounded-md border border-border bg-transparent px-2.5 py-1 text-sm outline-none';++function openInLabel(openIn: NonNullable<CliConversation['openIn']>): string {+ const where = openIn.entrypoint === 'claude-vscode' ? 'VS Code' : 'Claude Code';+ return `Open in ${where} (process ${openIn.pid})`;+}++/**+ * Where a Claude Code agent's session starts: a new conversation, or one+ * started in Claude Code's CLI, which the session continues from a copy so the+ * terminal's own is never written to. One a terminal has open cannot be+ * picked; where Claude Code does not record which are open, picking one asks+ * the person to say it is closed. The conversations are read when the picker+ * first opens, and again when it reopens after a listing failed.+ */+export function CliConversationField({+ conversations,+ value,+ onChange,+ confirmedClosed,+ onConfirmedClosedChange,+}: {+ conversations: ReturnType<typeof useCliConversations>;+ value: CliConversation | null;+ onChange: (next: CliConversation | null) => void;+ confirmedClosed: boolean;+ onConfirmedClosedChange: (next: boolean) => void;+}) {+ const { list, loading, error, request } = conversations;+ const items = list?.conversations ?? [];+ return (+ <Field>+ <FieldLabel>Conversation</FieldLabel>+ <Combobox+ items={items}+ value={value}+ onValueChange={(next: CliConversation | null) => {+ onChange(next);+ onConfirmedClosedChange(false);+ }}+ isItemEqualToValue={(a: CliConversation, b: CliConversation) =>+ a.nativeSessionId === b.nativeSessionId+ }+ itemToStringLabel={(item: CliConversation) => item.title}+ filter={(item: CliConversation, query) =>+ item.title.toLowerCase().includes(query.toLowerCase())+ }+ onOpenChange={(open: boolean) => {+ if (open) request();+ }}+ autoHighlight+ >+ <ComboboxTrigger className={TRIGGER}>+ <span className={cn('flex-1 truncate text-left', !value && 'text-foreground-muted')}>+ {value ? value.title : 'New conversation'}+ </span>+ <ChevronDown className="size-3.5 shrink-0 text-foreground-muted" />+ </ComboboxTrigger>+ <ComboboxContent className="min-w-(--anchor-width)">+ <ComboboxInput showTrigger={false} placeholder="Search conversations…" />+ <ComboboxList>+ {(item: CliConversation) => (+ <ComboboxItem key={item.nativeSessionId} value={item} disabled={item.openIn !== null}>+ <span className="flex min-w-0 flex-1 flex-col">+ <span className="truncate">{item.title}</span>+ <span className="truncate text-xs text-foreground-muted">+ {item.openIn ? (+ openInLabel(item.openIn)+ ) : (+ <>+ <RelativeTime value={item.lastActivityAt} />+ {item.gitBranch && ` · ${item.gitBranch}`}+ </>+ )}+ </span>+ </span>+ </ComboboxItem>+ )}+ </ComboboxList>+ <ComboboxEmpty>+ {loading+ ? 'Looking for CLI conversations…'+ : error+ ? 'Could not list the conversations.'+ : 'No conversations found'}+ </ComboboxEmpty>+ </ComboboxContent>+ </Combobox>+ {value && (+ <button+ type="button"+ className="mt-1 self-start text-xs text-foreground-muted underline-offset-2 hover:underline"+ onClick={() => {+ onChange(null);+ onConfirmedClosedChange(false);+ }}+ >+ Start a new conversation instead+ </button>+ )}+ <p className="mt-1 text-xs text-foreground-muted">+ {error+ ? error+ : value+ ? 'The session continues a copy of this conversation and shows what was said in it. The original in Claude Code stays as it was.'+ : list && items.length === 0+ ? 'No conversations started in the Claude Code CLI in this agent’s folder.'+ : 'Or continue a conversation started in the Claude Code CLI in this agent’s folder.'}+ </p>+ {value && list && !list.ownershipKnown && (+ <label className="group/field mt-2 flex cursor-pointer items-start gap-2.5">+ <Checkbox+ checked={confirmedClosed}+ onCheckedChange={(checked) => onConfirmedClosedChange(checked === true)}+ className="mt-0.5"+ />+ <span className="flex flex-col gap-0.5">+ <span className="text-sm font-medium">It isn’t open in a terminal</span>+ <span className="text-xs text-foreground-muted">+ This version of Claude Code doesn’t record which conversations are open, so Console+ can’t check. Close it in the terminal first.+ </span>+ </span>+ </label>+ )}+ </Field>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/sessions/create-session-modal/create-session-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/sessions/create-session-modal/create-session-modal.tsxindex 161812877..c36398edb 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sessions/create-session-modal/create-session-modal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sessions/create-session-modal/create-session-modal.tsx@@ -40,9 +40,12 @@ import { Textarea } from '@renderer/lib/ui/textarea';import { log } from '@renderer/utils/logger';import { cn } from '@renderer/utils/utils';import type { Agent } from '@shared/core/agents/agents';+import type { CliConversation } from '@shared/core/sessions/cli-conversations';+import { MAX_SESSION_TITLE_LENGTH } from '@shared/core/sessions/sessions';import type { RemoteAgentRoom } from '@shared/core/switch-servers/switch-servers';import type { UiEntryPoint } from '@shared/core/telemetry/reporting';import { buildConnectPrompt } from './build-connect-prompt';+import { CliConversationField, useCliConversations } from './cli-conversation-field';// In Switch Console a "session" is a *session*: a `claude` process spawned in the agent's// own directory. The directory is fixed (the agent), the provider is fixed (claude),@@ -159,6 +162,8 @@ export const CreateSessionModal = observer(function CreateSessionModal({const [room, setRoom] = useState<RemoteAgentRoom | null>(null);const [roleName, setRoleName] = useState<string>(NO_ROLE);const [pickedAgent, setPickedAgent] = useState<Agent | null>(null);+ const [cliConversation, setCliConversation] = useState<CliConversation | null>(null);+ const [confirmedClosed, setConfirmedClosed] = useState(false);// Room-first mode: the room is fixed and the agent is the open question —// unless the caller already answered it (a "+" on an agent row listed under@@ -260,7 +265,33 @@ export const CreateSessionModal = observer(function CreateSessionModal({});const roles = rolesQuery.data ?? [];- const canCreate = !!selectedLocationId;+ // The agent row the session will be owned by. Only a Claude Code agent can+ // continue a conversation started in its CLI.+ const sessionAgent = effectiveAgentName ? subagent : agent;+ const continuable = sessionAgent?.providerId === 'claude';+ const cliConversations = useCliConversations(continuable ? sessionAgent.id : null);+ useEffect(() => {+ setCliConversation(null);+ setConfirmedClosed(false);+ }, [sessionAgent?.id]);+ // The picked conversation as the latest listing has it. One that has gone,+ // or that a terminal has opened since, can no longer be continued.+ const listed = cliConversation+ ? cliConversations.list?.conversations.find(+ (c) => c.nativeSessionId === cliConversation.nativeSessionId+ )+ : undefined;+ useEffect(() => {+ if (cliConversation && cliConversations.list && (!listed || listed.openIn))+ setCliConversation(null);+ }, [cliConversation, cliConversations.list, listed]);+ // Without a listing (it failed) nothing says the conversation is closed, so+ // it cannot be continued until it is listed again or a new one is chosen.+ const awaitingConfirmation =+ cliConversation !== null &&+ (cliConversations.list === null || (!cliConversations.list.ownershipKnown && !confirmedClosed));++ const canCreate = !!selectedLocationId && !awaitingConfirmation;const handleSpawn = () => {if (!selectedLocationId) return;@@ -304,9 +335,22 @@ export const CreateSessionModal = observer(function CreateSessionModal({const created = sessionManager.createSession({id,agentId: resolvedAgent.id,- title: trimmedName || (activeRoom ? `Session for ${activeRoom.roomName}` : 'Session'),+ title:+ trimmedName ||+ (cliConversation &&+ Array.from(cliConversation.title).slice(0, MAX_SESSION_TITLE_LENGTH).join('')) ||+ (activeRoom ? `Session for ${activeRoom.roomName}` : 'Session'),initialPrompt,agentName: effectiveAgentName || undefined,+ ...(continuable && cliConversation+ ? {+ cliConversation: {+ nativeSessionId: cliConversation.nativeSessionId,+ title: cliConversation.title,+ confirmedClosed,+ },+ }+ : {}),entryPoint,// Whether a room was asked for, never which one. Declared here because// the record `noteIntendedRoom` just wrote is consumed while this@@ -441,6 +485,15 @@ export const CreateSessionModal = observer(function CreateSessionModal({)}</Field>)}+ {continuable && (+ <CliConversationField+ conversations={cliConversations}+ value={cliConversation}+ onChange={setCliConversation}+ confirmedClosed={confirmedClosed}+ onConfirmedClosedChange={setConfirmedClosed}+ />+ )}<Field><FieldLabel>Name</FieldLabel><Inputdiff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/cli-conversation-field.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/cli-conversation-field.test.tsxnew file mode 100644index 000000000..6336a8d8c--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/cli-conversation-field.test.tsx@@ -0,0 +1,183 @@+/**+ * The new-session dialog's Conversation field offers the Claude Code CLI+ * conversations in the agent's folder, read when its picker opens and again+ * when it reopens after a listing failed, will not take one a terminal has+ * open, and asks for confirmation where Claude Code cannot say which are open.+ */+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { act, useState } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, expect, it, vi } from 'vitest';+import { page, userEvent } from 'vitest/browser';+import type { CliConversation, CliConversationList } from '@shared/core/sessions/cli-conversations';++const listCliConversations = vi.hoisted(() => vi.fn());++vi.hoisted(() => {+ window.electronAPI ??= {+ invoke: () => Promise.resolve(undefined),+ eventOn: () => () => {},+ eventSend: () => {},+ } as unknown as typeof window.electronAPI;+});++vi.mock('@renderer/lib/ipc', () => ({+ events: { on: vi.fn() },+ rpc: { sessions: { listCliConversations } },+}));++import {+ CliConversationField,+ useCliConversations,+} from '@renderer/features/sessions/create-session-modal/cli-conversation-field';+import { Dialog, DialogContent } from '@renderer/lib/ui/dialog';+import '@renderer/index.css';++let container: HTMLDivElement | null = null;+let root: Root | null = null;+const picked: { current: CliConversation | null } = { current: null };++afterEach(async () => {+ if (root) await act(async () => root!.unmount());+ container?.remove();+ container = null;+ root = null;+ picked.current = null;+ listCliConversations.mockReset();+});++const OPEN: CliConversation = {+ nativeSessionId: 'open-1',+ title: 'Refactor the session host',+ lastActivityAt: Date.now() - 60_000,+ gitBranch: 'main',+ openIn: { pid: 41, entrypoint: 'cli' },+};+const CLOSED: CliConversation = {+ nativeSessionId: 'closed-1',+ title: 'Fix the flaky build',+ lastActivityAt: Date.now() - 3 * 60 * 60_000,+ gitBranch: 'fix/build',+ openIn: null,+};++function Harness() {+ const conversations = useCliConversations('agent-1');+ const [value, setValue] = useState<CliConversation | null>(null);+ const [confirmed, setConfirmed] = useState(false);+ picked.current = value;+ return (+ <CliConversationField+ conversations={conversations}+ value={value}+ onChange={setValue}+ confirmedClosed={confirmed}+ onConfirmedClosedChange={setConfirmed}+ />+ );+}++async function render(list: CliConversationList) {+ listCliConversations.mockResolvedValue({ success: true, data: list });+ await mount();+}++async function mount() {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ await act(async () =>+ root!.render(+ <QueryClientProvider client={client}>+ <Dialog open>+ <DialogContent>+ <Harness />+ </DialogContent>+ </Dialog>+ </QueryClientProvider>+ )+ );+}++it('lists the conversations only once the picker opens, and says it is looking meanwhile', async () => {+ let answer!: (value: unknown) => void;+ listCliConversations.mockReturnValue(+ new Promise((resolve) => {+ answer = resolve;+ })+ );+ await mount();+ await expect.element(page.getByText('New conversation')).toBeVisible();+ expect(listCliConversations).not.toHaveBeenCalled();+ await page.getByText('New conversation').click();+ await expect.element(page.getByText('Looking for CLI conversations…')).toBeVisible();+ expect(listCliConversations).toHaveBeenCalledWith('agent-1');+ await act(async () =>+ answer({ success: true, data: { ownershipKnown: true, conversations: [CLOSED] } })+ );+ await expect.element(page.getByRole('option', { name: /Fix the flaky build/ })).toBeVisible();+ await expect.element(page.getByText('Looking for CLI conversations…')).not.toBeInTheDocument();+});++it('offers a closed conversation and not one a terminal has open', async () => {+ await render({ ownershipKnown: true, conversations: [OPEN, CLOSED] });+ await expect.element(page.getByText('New conversation')).toBeVisible();+ await page.getByText('New conversation').click();+ expect(listCliConversations).toHaveBeenCalledWith('agent-1');+ await expect.element(page.getByText('Open in Claude Code (process 41)')).toBeVisible();+ await expect+ .element(page.getByRole('option', { name: /Refactor the session host/ }))+ .toHaveAttribute('aria-disabled', 'true');+ await page.getByRole('option', { name: /Fix the flaky build/ }).click();+ expect(picked.current?.nativeSessionId).toBe('closed-1');+ await expect.element(page.getByText(/continues a copy of this conversation/)).toBeVisible();+ await expect.element(page.getByText('It isn’t open in a terminal')).not.toBeInTheDocument();+ await page.getByText('Start a new conversation instead').click();+ expect(picked.current).toBeNull();+});++it('asks whether the conversation is closed when Claude Code cannot say', async () => {+ await render({ ownershipKnown: false, conversations: [CLOSED] });+ await page.getByText('New conversation').click();+ await page.getByRole('option', { name: /Fix the flaky build/ }).click();+ await expect.element(page.getByText('It isn’t open in a terminal')).toBeVisible();+});++it('says why nothing is offered', async () => {+ listCliConversations.mockResolvedValue({+ success: false,+ error: { message: 'Open the agent’s folder in Console first.' },+ });+ await mount();+ await page.getByText('New conversation').click();+ await expect.element(page.getByText('Open the agent’s folder in Console first.')).toBeVisible();+ await expect.element(page.getByText('Could not list the conversations.')).toBeVisible();+});++it('lists again when the picker reopens after a listing failed, and keeps one that succeeded', async () => {+ listCliConversations+ .mockResolvedValueOnce({+ success: false,+ error: { message: 'build-box does not answer.' },+ })+ .mockResolvedValue({ success: true, data: { ownershipKnown: true, conversations: [CLOSED] } });+ await mount();+ await page.getByText('New conversation').click();+ await expect.element(page.getByText('build-box does not answer.')).toBeVisible();+ await userEvent.keyboard('{Escape}');+ await expect.element(page.getByText('Could not list the conversations.')).not.toBeInTheDocument();++ await page.getByText('New conversation').click();+ await expect.element(page.getByRole('option', { name: /Fix the flaky build/ })).toBeVisible();+ expect(listCliConversations).toHaveBeenCalledTimes(2);+ await expect.element(page.getByText('build-box does not answer.')).not.toBeInTheDocument();+ await userEvent.keyboard('{Escape}');+ await expect+ .element(page.getByRole('option', { name: /Fix the flaky build/ }))+ .not.toBeInTheDocument();++ await page.getByText('New conversation').click();+ await expect.element(page.getByRole('option', { name: /Fix the flaky build/ })).toBeVisible();+ expect(listCliConversations).toHaveBeenCalledTimes(2);+});diff --git a/console/apps/switch-console-desktop/src/shared/core/sessions/cli-conversations.ts b/console/apps/switch-console-desktop/src/shared/core/sessions/cli-conversations.tsnew file mode 100644index 000000000..d1ed008eb--- /dev/null+++ b/console/apps/switch-console-desktop/src/shared/core/sessions/cli-conversations.ts@@ -0,0 +1,23 @@+// The renderer's view of `cliConversationListSchema` (agent-providers). The main+// process parses the host's answer with that schema and returns it as this type,+// so the two cannot drift apart without that failing to compile.++/** A conversation started in Claude Code's own CLI, as the new-session dialog offers it. */+export type CliConversation = {+ nativeSessionId: string;+ title: string;+ /** Epoch milliseconds. */+ lastActivityAt: number;+ gitBranch: string | null;+ /** The running Claude Code process that has it open, or null for none. */+ openIn: { pid: number; entrypoint: string | null } | null;+};++export type CliConversationList = {+ /**+ * Whether the agent's Claude Code records which conversations its running+ * processes have open. When it does not, an open one looks closed.+ */+ ownershipKnown: boolean;+ conversations: CliConversation[];+};diff --git a/console/apps/switch-console-desktop/src/shared/core/sessions/session-config.ts b/console/apps/switch-console-desktop/src/shared/core/sessions/session-config.tsindex 9f75e8884..0ba744d01 100644--- a/console/apps/switch-console-desktop/src/shared/core/sessions/session-config.ts+++ b/console/apps/switch-console-desktop/src/shared/core/sessions/session-config.ts@@ -20,6 +20,10 @@ const initialPromptDeliverySchema = z.object({export type InitialPromptDelivery = z.infer<typeof initialPromptDeliverySchema>;+const cliConversationSchema = z.object({ nativeSessionId: z.string(), title: z.string() });++export type ContinuedCliConversation = z.infer<typeof cliConversationSchema>;+const sessionConfigV0Schema = z.object({autoApprove: z.boolean().optional(),autoMode: z.boolean().optional(),@@ -30,6 +34,9 @@ const sessionConfigV0Schema = z.object({/** Delivery state of `initialPrompt`, so a relaunch can tell "never submitted"* from "already delivered" instead of guessing from the launch result. */initialPromptDelivery: initialPromptDeliverySchema.optional(),+ /** The conversation started in Claude Code's own CLI that this session continues;+ * `providerSessionId` is the copy of it the session runs. */+ cliConversation: cliConversationSchema.optional(),});export const sessionConfig = defineVersionedSchema().unversioned(sessionConfigV0Schema).build();diff --git a/console/apps/switch-console-desktop/src/shared/core/sessions/sessions.ts b/console/apps/switch-console-desktop/src/shared/core/sessions/sessions.tsindex 78cf2ff5b..97c2cae28 100644--- a/console/apps/switch-console-desktop/src/shared/core/sessions/sessions.ts+++ b/console/apps/switch-console-desktop/src/shared/core/sessions/sessions.ts@@ -2,7 +2,7 @@ import z from 'zod';import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';import type { AgentStatus } from '@shared/core/providers/agentEvents';import type { SessionStartSource, UiEntryPoint } from '@shared/core/telemetry/reporting';-import type { InitialPromptDelivery } from './session-config';+import type { ContinuedCliConversation, InitialPromptDelivery } from './session-config';export const MAX_SESSION_TITLE_LENGTH = 100;@@ -34,6 +34,8 @@ export type Session = {statusChangedAt: string;/** Native conversation imported from an earlier session, when available. */providerSessionId?: string;+ /** The conversation started in Claude Code's CLI that this session continues. */+ cliConversation?: ContinuedCliConversation;initialPromptDelivery?: InitialPromptDelivery;agentStatus?: AgentStatus | null;agentStatusSeen?: boolean;@@ -70,6 +72,13 @@ export type CreateSessionParams = {agentName?: string;/** Attach to an existing SDK session without starting a fresh conversation. */attach?: boolean;+ /**+ * Continue this conversation, started in Claude Code's own CLI in the agent's+ * folder. The session runs a copy of it, so the CLI's own is left alone.+ * `confirmedClosed`: the person said it is closed, which a copy needs where+ * Claude Code cannot say which conversations are open.+ */+ cliConversation?: ContinuedCliConversation & { confirmedClosed: boolean };/*** Which control the user started the session from, for reporting. Omitted by* callers with no user behind them, which report as `unknown`.diff --git a/console/docs/sdk-sessions.md b/console/docs/sdk-sessions.mdindex b328e28ad..3b643fa69 100644--- a/console/docs/sdk-sessions.md+++ b/console/docs/sdk-sessions.md@@ -111,6 +111,106 @@ Adopted sessions do not launch providers. Open their location and select the sesto load its transcript. Existing older Console binaries need an update to receivethese discovery fixes.+## Continuing a Claude Code CLI conversation++A Claude Code agent's session can continue a conversation that was started in+Claude Code's own terminal or IDE clients in the agent's folder. Pick it under+**Conversation** in the new-session dialog. The list is read when that picker+first opens, not with the dialog, on the session's execution host, local or+SSH, with the Agent SDK's `listSessions`. Conversations a program started+through the SDK are left out, Switch's own sessions included, and so are the+copies Console made (below). Only Claude Code conversations can be continued;+Codex runs each session in a private `CODEX_HOME` and records no running+conversations to check against.++Conversations are looked for where the session's Claude Code will look: the+host applies the agent's shell setup and inherited variables, as it does before+starting the provider, so a `CLAUDE_CONFIG_DIR` set there is honoured. Console+sends that request as a private file, in a directory only the user can read+beside a launch's configuration, not on a command line. Listing only reads the+host. On an SSH host that does not yet have this Console's host bundle the+dialog says so instead of deploying it; starting a session, which copies the+conversation, deploys it as any launch does. A Room watcher that does not run+this Console's host bundle cannot start such a session. Before the+conversation is copied, and again before the session's first start, Console+asks which bundle the agent's watcher runs (its `health.json`, written by the+process alive now, or while that process is down its supervisor's record of+the file it starts) and, when it names another build, refuses and says to+update the watcher. A session that cannot start this way never gets a copy. A+watcher whose bundle cannot be told yet (its process has written no record of+its own, or its supervisor names no file) is not refused, nor is a host with+no watcher; a relaunch of a session that has started is not asked about.++The session never writes to the CLI's conversation. Starting the session copies+it under a new id (the SDK's `forkSession`), and the session resumes the copy.+The source is read with `getSessionInfo`, and a copy Console made is refused as+one. Each copy is tagged `switch-console:<session id>` (`tagSession`) as soon as+it is made; a copy that cannot be tagged is removed at once. The session is+recorded before the copy is made. Something that starts it while the copy is+being made waits for the copy. If the copy fails, or the session's row was+deleted while it was made, the session is removed again and Console removes the+conversations in the folder tagged with that session's id, and nothing else; a+copy the host refused, saying why, leaves nothing tagged to remove. When the+copy's outcome is unknown (a timeout or a dropped connection, so it may be made+after Console stopped waiting), or removing it fails, Console tries again in the+background with each list or copy in that location, never holding either up, and+asks the host about every such session in one request. A session is tried until+a removal finds its copy, or until one finds none 15 minutes after it was+recorded, by when a copy still being made would have finished; a removal that+fails does not count. A session read before its copy was recorded finds the copy+in its row. One whose copy was never recorded (Console stopped while copying)+refuses to start rather than open a new conversation. The copy is titled+`… (continued in Switch Console)`, so Claude Code's own `/resume` list shows it+is taken. The dialog never offers a copy, by its tag (a renamed one included)+or by that title (one made before copies were tagged), whether or not its+session still exists. The original stays the terminal's. Continuing it there+afterwards starts a separate branch that does not include what happened in+Console.++A conversation that a running Claude Code process has open cannot be picked, and+the copy is refused if one has opened it since. Claude Code records each running+process under its config directory's `sessions/<pid>.json`, rewriting it as the+process goes busy or idle; a record read half-written is read again. A record+counts while its process is alive and is Claude Code, whatever its recorded start+time says, since a stepped clock moves that. A live process that is something+else no longer holds the conversation unless it started at the recorded time+(`ps -o lstart=` in UTC). A live process `ps` cannot describe is taken to hold+its conversation. When a live Claude Code process's record cannot be read, or+this Claude Code keeps no records, the dialog asks for confirmation that the+conversation is closed. The check runs again when the copy is made: without+that confirmation, a Claude Code that keeps no records refuses the copy and+asks for it, and a record that cannot be read just then refuses it and asks to+try again.++No earlier prompt is sent again. Before the provider starts, the session's+transcript is filled with the copy's earlier turns, up to the last 500 items:+prompts, slash and `!` commands as they were typed (a prompt that quotes Claude+Code's command tags among other text is shown as typed), Claude's replies, and+the tools it ran, with a failed tool marked as failed. Reasoning, subagents' own+messages, the entries Claude Code marks as hidden (a loaded skill's+instructions, say), the context it adds on its own (in its own tags; markup a+person pasted stays) and its notes that a turn was stopped are left out, as they+are from a live transcript. Imported turns carry ids starting `imported:`+(`isImportedTurn` in `@switch-console/shared/session-v1`), and nothing that asks+whether a session has run anything counts them: its initial prompt is still+delivered, its first room message still opens the conversation, and its agent+instructions are not announced as changed. Where the conversation was compacted,+an item marks it instead of showing the summary as a prompt. Text is scrubbed of+service tokens before it is cut into parts, and an item the conversation repeats+is shown once. A notice after those turns says how many items were not shown,+and settles the import: the host reads it back from its event journal on+restart. Items are recorded in batches bounded in count and bytes. An import cut+short by a crash runs again and publishes only what it had not. A saved+transcript is read whole or not at all: only a last line cut short by a write in+progress is left out. If the conversation cannot be read, or its turns cannot be+recorded, a warning says so once and the session goes on to resume it, which+decides whether it is there. Because the session continues a conversation that+already had answers, a copy that cannot be resumed is never quietly replaced+with a new conversation. Console asks for the explicit fresh start instead. Once+the person has taken it, a restart before the fresh conversation has run a turn+starts another without asking, since that one was never the copy and never+answered.+## Context, models and attachmentsReset starts a fresh native conversation under a new server-issued epoch. Thediff --git a/console/packages/agent-controller/package.json b/console/packages/agent-controller/package.jsonindex 47737befe..f2a297cd6 100644--- a/console/packages/agent-controller/package.json+++ b/console/packages/agent-controller/package.json@@ -28,7 +28,7 @@"@switch-console/agent-providers": "workspace:*","@switch-console/plugins": "workspace:*","ws": "^8.21.3",- "zod": "^4.4.3"+ "zod": "^4.6.7"},"devDependencies": {"@sandboxaq/switch-agent-runtime": "workspace:*",diff --git a/console/packages/agent-providers/package.json b/console/packages/agent-providers/package.jsonindex 56f7c5634..4d6a63a0a 100644--- a/console/packages/agent-providers/package.json+++ b/console/packages/agent-providers/package.json@@ -42,7 +42,7 @@"@switch-console/shared": "workspace:*","jsonc-parser": "3.3.1","smol-toml": "^1.8.0",- "zod": "^4.4.3"+ "zod": "^4.6.7"},"devDependencies": {"@types/node": "^24.13.3",diff --git a/console/packages/agent-providers/src/adapter.ts b/console/packages/agent-providers/src/adapter.tsindex 3a3c2ac0c..c2992be71 100644--- a/console/packages/agent-providers/src/adapter.ts+++ b/console/packages/agent-providers/src/adapter.ts@@ -147,6 +147,21 @@ export interface ProviderTurnStartResult {steeredInto?: string;}+/** One turn of a saved native conversation, as a transcript that starts with it shows it. */+export interface ConversationHistoryTurn {+ /** The same every time the same conversation is read, so reading it twice adds nothing. */+ turnId: string;+ items: ConversationHistoryItem[];+}++export interface ConversationHistoryItem {+ itemId: string;+ kind: 'user-message' | 'assistant-message' | 'tool-activity';+ status: 'completed' | 'failed';+ title: string;+ text: string;+}+export interface ProviderCapabilities {/** The adapter can switch models on a live session, not only at start. */modelSwitchInSession: boolean;@@ -195,6 +210,17 @@ export interface ProviderAdapter {* has no such channel; a caller says it in the next user message instead.*/addDeveloperMessage?(sessionId: string, text: string): Promise<void>;+ /**+ * The turns of a saved native conversation, oldest first: what a session+ * that continues a conversation started outside Switch shows before its own.+ * Read without starting the session, from where a session with `env` would+ * find it. Absent means the provider cannot read its saved conversations.+ */+ conversationHistory?(+ nativeSessionId: string,+ cwd: string,+ env: Record<string, string>+ ): Promise<ConversationHistoryTurn[]>;stopSession(sessionId: string): Promise<void>;stopAll(): Promise<void>;hasSession(sessionId: string): boolean;diff --git a/console/packages/agent-providers/src/claude/claude-adapter.ts b/console/packages/agent-providers/src/claude/claude-adapter.tsindex fcd1773a7..67e525517 100644--- a/console/packages/agent-providers/src/claude/claude-adapter.ts+++ b/console/packages/agent-providers/src/claude/claude-adapter.ts@@ -1,9 +1,8 @@import { randomUUID } from 'node:crypto';import { accessSync, constants, existsSync } from 'node:fs';-import { access, readdir, readFile } from 'node:fs/promises';-import { homedir } from 'node:os';+import { readFile } from 'node:fs/promises';import { delimiter, join } from 'node:path';-import { query as sdkQuery } from '@anthropic-ai/claude-agent-sdk';+import { getSessionMessages, query as sdkQuery } from '@anthropic-ai/claude-agent-sdk';import type {CanUseTool,EffortLevel,@@ -24,6 +23,7 @@ import {resolveWindowsCommandPath,} from '@switch-console/shared/windows-spawn';import type {+ ConversationHistoryTurn,ModelSelection,ProviderAdapter,ProviderCapabilities,@@ -50,6 +50,7 @@ import type {} from '../events';import { spawnProvider, stopProvider } from '../provider-process';import { CumulativeUsage, mergeUsage } from '../usage';+import { historyFromClaudeMessages } from './claude-history';import {approvalContent,isRecord,@@ -65,6 +66,7 @@ import {toolTitle,truncate,} from './claude-mapping';+import { claudeConfigDir, configDirSessionStore, savedConversationPath } from './cli-conversations';const PROVIDER = 'claude';const ASK_USER_QUESTION = 'AskUserQuestion';@@ -141,6 +143,8 @@ export interface ClaudeAdapterOptions {nativeSessionId: string,env: Record<string, string>) => Promise<boolean>;+ /** Test seam: the SDK's reader of a saved conversation. */+ sessionMessages?: typeof getSessionMessages;}/**@@ -153,24 +157,7 @@ async function claudeConversationSaved(nativeSessionId: string,env: Record<string, string>): Promise<boolean> {- const configDir = env.CLAUDE_CONFIG_DIR || join(env.HOME || homedir(), '.claude');- let projects: string[];- try {- projects = await readdir(join(configDir, 'projects'));- } catch (error) {- if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false;- throw error;- }- for (const project of projects) {- try {- await access(join(configDir, 'projects', project, `${nativeSessionId}.jsonl`));- return true;- } catch (error) {- const code = (error as NodeJS.ErrnoException).code;- if (code !== 'ENOENT' && code !== 'ENOTDIR') throw error;- }- }- return false;+ return (await savedConversationPath(claudeConfigDir(env), nativeSessionId)) !== null;}type EventBody<T extends ProviderRuntimeEvent = ProviderRuntimeEvent> =@@ -428,12 +415,14 @@ export class ClaudeAdapter implements ProviderAdapter {private readonly savedConversationExists: NonNullable<ClaudeAdapterOptions['savedConversationExists']>;+ private readonly sessionMessages: typeof getSessionMessages;constructor(options: ClaudeAdapterOptions = {}) {this.executablePath = options.claudeExecutablePath;this.logger = options.logger;this.queryFn = options.query ?? sdkQuery;this.savedConversationExists = options.savedConversationExists ?? claudeConversationSaved;+ this.sessionMessages = options.sessionMessages ?? getSessionMessages;}subscribe(listener: (event: ProviderRuntimeEvent) => void): () => void {@@ -612,6 +601,28 @@ export class ClaudeAdapter implements ProviderAdapter {return { turnId: input.turnId, ...(steeredInto ? { steeredInto } : {}) };}+ /**+ * Read from Claude Code's saved transcript, the way its own `/resume` reads+ * it, in the config directory `env` gives Claude Code: through a store over+ * that directory, so this process's own environment, which the host's other+ * work shares, is left alone. A conversation with nothing in it is an error+ * rather than an empty history: it is either not there or not one a person+ * had.+ */+ async conversationHistory(+ nativeSessionId: string,+ cwd: string,+ env: Record<string, string>+ ): Promise<ConversationHistoryTurn[]> {+ const messages = await this.sessionMessages(nativeSessionId, {+ dir: cwd,+ sessionStore: configDirSessionStore(claudeConfigDir(env)),+ });+ if (messages.length === 0)+ throw new Error(`Claude Code has no saved conversation ${nativeSessionId} to show.`);+ return historyFromClaudeMessages(messages);+ }+async interruptTurn(sessionId: string): Promise<void> {const session = this.requireSession(sessionId);try {diff --git a/console/packages/agent-providers/src/claude/claude-history.store.test.ts b/console/packages/agent-providers/src/claude/claude-history.store.test.tsnew file mode 100644index 000000000..cb5b167bb--- /dev/null+++ b/console/packages/agent-providers/src/claude/claude-history.store.test.ts@@ -0,0 +1,112 @@+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, expect, it } from 'vitest';+import { ClaudeAdapter } from './claude-adapter';+import { configDirSessionStore } from './cli-conversations';++const roots: string[] = [];+afterEach(async () => {+ for (const root of roots.splice(0)) await rm(root, { recursive: true, force: true });+});++const ID = '11111111-2222-4333-8444-555555555555';+const U1 = 'aaaaaaaa-0000-4000-8000-000000000001';+const A1 = 'aaaaaaaa-0000-4000-8000-000000000002';+const M1 = 'aaaaaaaa-0000-4000-8000-000000000003';+const U2 = 'aaaaaaaa-0000-4000-8000-000000000004';+const A2 = 'aaaaaaaa-0000-4000-8000-000000000005';++function line(+ type: string,+ uuid: string,+ parentUuid: string | null,+ content: unknown,+ extra: object = {}+): string {+ const role = type === 'user' ? 'user' : 'assistant';+ return JSON.stringify({+ type,+ uuid,+ parentUuid,+ sessionId: ID,+ isSidechain: false,+ timestamp: '2026-10-28T12:00:00.000Z',+ message: { role, content },+ ...extra,+ });+}++async function savedConversation(+ lines: string[] = [+ line('user', U1, null, 'Fix the build'),+ line('assistant', A1, U1, [{ type: 'text', text: 'Done.' }]),+ '{"type":"assistant","uuid":"cut sho',+ ]+): Promise<string> {+ const dir = await mkdtemp(join(tmpdir(), 'claude-config-'));+ roots.push(dir);+ await mkdir(join(dir, 'projects', '-work'), { recursive: true });+ await writeFile(join(dir, 'projects', '-work', `${ID}.jsonl`), lines.join('\n'));+ return dir;+}++it('finds a saved conversation by its id in any project, leaving out a line cut short', async () => {+ const dir = await savedConversation();+ const store = configDirSessionStore(dir);+ const entries = await store.load({ projectKey: 'anything', sessionId: ID });+ expect(entries?.map((e) => e.uuid)).toEqual([U1, A1]);+ expect(await store.load({ projectKey: 'anything', sessionId: 'missing' })).toBeNull();+ expect(+ await configDirSessionStore(join(dir, 'none')).load({ projectKey: 'x', sessionId: ID })+ ).toBeNull();+});++it('reads a conversation from the session’s config directory without touching this process’s environment', async () => {+ const dir = await savedConversation();+ const before = process.env.CLAUDE_CONFIG_DIR;+ const turns = await new ClaudeAdapter().conversationHistory(ID, '/work', {+ CLAUDE_CONFIG_DIR: dir,+ });+ expect(turns.map((turn) => turn.items.map((item) => item.text))).toEqual([+ ['Fix the build', 'Done.'],+ ]);+ expect(process.env.CLAUDE_CONFIG_DIR).toBe(before);+});++it('refuses a conversation with a line that is not JSON before its last', async () => {+ const dir = await savedConversation([+ line('user', U1, null, 'Fix the build'),+ '{"type":"assistant","uuid":"cut sho',+ line('assistant', A1, U1, [{ type: 'text', text: 'Done.' }]),+ '',+ ]);+ await expect(+ configDirSessionStore(dir).load({ projectKey: 'anything', sessionId: ID })+ ).rejects.toThrow(/Line 2 of Claude Code's saved conversation .* is not JSON/);+});++it('leaves out what Claude Code adds as a hidden user entry, keeping the turns around it whole', async () => {+ // Loading a skill records its instructions as a user entry marked `isMeta`,+ // in the chain between the prompt and the reply.+ const dir = await savedConversation([+ line('user', U1, null, 'Use the release skill'),+ line(+ 'user',+ M1,+ U1,+ [{ type: 'text', text: 'Base directory for this skill: /work/.claude/skills/release' }],+ { isMeta: true }+ ),+ line('assistant', A1, M1, [{ type: 'text', text: 'Releasing.' }]),+ line('user', U2, A1, 'Thanks'),+ line('assistant', A2, U2, [{ type: 'text', text: 'Any time.' }]),+ ]);+ const turns = await new ClaudeAdapter().conversationHistory(ID, '/work', {+ CLAUDE_CONFIG_DIR: dir,+ });+ expect(turns.map((turn) => turn.items.map((item) => item.text))).toEqual([+ ['Use the release skill', 'Releasing.'],+ ['Thanks', 'Any time.'],+ ]);+});diff --git a/console/packages/agent-providers/src/claude/claude-history.test.ts b/console/packages/agent-providers/src/claude/claude-history.test.tsnew file mode 100644index 000000000..fd75a1269--- /dev/null+++ b/console/packages/agent-providers/src/claude/claude-history.test.ts@@ -0,0 +1,189 @@+import type { SessionMessage } from '@anthropic-ai/claude-agent-sdk';+import { expect, it } from 'vitest';+import { historyFromClaudeMessages } from './claude-history';++function entry(+ type: SessionMessage['type'],+ uuid: string,+ content: unknown,+ parentToolUseId: string | null = null+): SessionMessage {+ return {+ type,+ uuid,+ session_id: 'conversation',+ message: { role: type, content },+ parent_tool_use_id: parentToolUseId,+ parent_agent_id: null,+ };+}++it('turns a Claude Code transcript into turns that start at each prompt someone typed', () => {+ const turns = historyFromClaudeMessages([+ entry('user', 'u1', 'Why does the build fail?'),+ entry('assistant', 'a1', [+ { type: 'thinking', thinking: 'Let me look.' },+ { type: 'text', text: 'Checking the build.' },+ { type: 'tool_use', id: 'tool-1', name: 'Bash', input: { command: 'pnpm build' } },+ ]),+ entry('user', 'r1', [{ type: 'tool_result', tool_use_id: 'tool-1', is_error: true }]),+ entry('assistant', 'a2', [{ type: 'text', text: 'A type error in main.ts.' }]),+ entry('user', 'u2', [+ { type: 'text', text: '<ide_opened_file>main.ts</ide_opened_file>' },+ { type: 'text', text: 'Fix it' },+ { type: 'image', source: {} },+ ]),+ entry('assistant', 'a3', [+ { type: 'tool_use', id: 'tool-2', name: 'Edit', input: { file_path: 'main.ts' } },+ ]),+ entry('user', 'r2', [{ type: 'tool_result', tool_use_id: 'tool-2', content: 'ok' }]),+ ]);++ expect(turns).toEqual([+ {+ turnId: 'u1',+ items: [+ {+ itemId: 'u1',+ kind: 'user-message',+ status: 'completed',+ title: '',+ text: 'Why does the build fail?',+ },+ {+ itemId: 'a1:1',+ kind: 'assistant-message',+ status: 'completed',+ title: '',+ text: 'Checking the build.',+ },+ {+ itemId: 'a1:2',+ kind: 'tool-activity',+ status: 'failed',+ title: 'pnpm build',+ text: '',+ },+ {+ itemId: 'a2:0',+ kind: 'assistant-message',+ status: 'completed',+ title: '',+ text: 'A type error in main.ts.',+ },+ ],+ },+ {+ turnId: 'u2',+ items: [+ {+ itemId: 'u2',+ kind: 'user-message',+ status: 'completed',+ title: '',+ text: 'Fix it\n\n[image]',+ },+ {+ itemId: 'a3:0',+ kind: 'tool-activity',+ status: 'completed',+ title: 'Edit main.ts',+ text: '',+ },+ ],+ },+ ]);+});++it('shows a slash command as typed and leaves out what Claude Code added on its own', () => {+ const turns = historyFromClaudeMessages([+ entry(+ 'user',+ 'c1',+ '<command-name>/review</command-name>\n<command-message>review</command-message>\n<command-args>main.ts</command-args>'+ ),+ entry('user', 'c2', '<local-command-stdout>Reviewed.</local-command-stdout>'),+ entry('user', 'n1', '<task-notification>\nThe build finished.\n</task-notification>'),+ ]);++ expect(turns.map((turn) => turn.items.map((item) => item.text))).toEqual([['/review main.ts']]);+});++it('leaves out a stopped turn’s note and command output, and shows a ! command as typed', () => {+ const turns = historyFromClaudeMessages([+ entry('user', 'u1', 'Run the tests'),+ entry('user', 'i1', [{ type: 'text', text: '[Request interrupted by user for tool use]' }]),+ entry(+ 'user',+ 'c1',+ '<command-message>review</command-message>\n<command-name>/review</command-name>'+ ),+ entry('user', 'b1', '<bash-input>git status</bash-input>'),+ entry('user', 'b2', '<bash-stdout>clean</bash-stdout><bash-stderr></bash-stderr>'),+ entry('user', 'p1', '<div> is not centred, why?'),+ entry('user', 'p2', '<config><key>v</key></config>'),+ ]);++ expect(turns.map((turn) => turn.items.map((item) => item.text))).toEqual([+ ['Run the tests'],+ ['/review'],+ ['! git status'],+ ['<div> is not centred, why?'],+ ['<config><key>v</key></config>'],+ ]);+});++it('shows a prompt that quotes Claude Code’s command tags as it was typed', () => {+ const pastedCommand =+ 'Why does this show up in my transcript? <command-name>/review</command-name><command-args>main.ts</command-args>';+ const pastedShell = 'What does <bash-input>git status</bash-input> mean here?';+ const trailing = '<command-name>/review</command-name> and then what?';+ const turns = historyFromClaudeMessages([+ entry('user', 'p1', pastedCommand),+ entry('user', 'p2', pastedShell),+ entry('user', 'p3', trailing),+ entry('user', 'c1', '<command-name>/review</command-name>\n<command-args>a < b</command-args>'),+ ]);++ expect(turns.map((turn) => turn.items.map((item) => item.text))).toEqual([+ [pastedCommand],+ [pastedShell],+ [trailing],+ ['/review a < b'],+ ]);+});++it('marks where a conversation was compacted instead of showing its summary as a prompt', () => {+ const turns = historyFromClaudeMessages([+ entry(+ 'user',+ 's1',+ 'This session is being continued from a previous conversation that ran out of context. The conversation is summarized below: …'+ ),+ entry('user', 'u1', 'Carry on'),+ ]);++ expect(+ turns.map((turn) => turn.items.map((item) => [item.kind, item.title || item.text]))+ ).toEqual([+ [['tool-activity', 'Conversation compacted: the turns before this were summarized']],+ [['user-message', 'Carry on']],+ ]);+});++it('leaves out what a subagent said, which its own tool call stands for', () => {+ const turns = historyFromClaudeMessages([+ entry('user', 'u1', 'Explore the repo'),+ entry('assistant', 'a1', [+ { type: 'tool_use', id: 'task-1', name: 'Agent', input: { description: 'Survey the code' } },+ ]),+ entry('user', 's1', 'Survey the code', 'task-1'),+ entry('assistant', 's2', [{ type: 'text', text: 'Found three packages.' }], 'task-1'),+ ]);++ expect(turns).toHaveLength(1);+ expect(turns[0]!.items.map((item) => item.title || item.text)).toEqual([+ 'Explore the repo',+ 'Survey the code',+ ]);+});diff --git a/console/packages/agent-providers/src/claude/claude-history.ts b/console/packages/agent-providers/src/claude/claude-history.tsnew file mode 100644index 000000000..11e9fd87b--- /dev/null+++ b/console/packages/agent-providers/src/claude/claude-history.ts@@ -0,0 +1,176 @@+import type { SessionMessage } from '@anthropic-ai/claude-agent-sdk';+import type { ConversationHistoryItem, ConversationHistoryTurn } from '../adapter';+import { isRecord, toolTitle } from './claude-mapping';++/** Claude Code's note that someone stopped a turn: not a prompt. */+const INTERRUPTED = /^\[Request interrupted by user[^\]]*\]$/;+/**+ * How Claude Code's summary of a compacted conversation opens. It is recorded+ * as a user entry, and the SDK's reader does not say which entry it is.+ */+const COMPACTION_SUMMARY = /^This session is being continued from a previous conversation/;+const OPENING_TAG = /^<([a-z][\w-]*)(?:\s[^>]*)?>/;+/**+ * The tags Claude Code wraps around what it records on its own: the context it+ * adds, and how it records a slash command someone ran+ * (`<command-name>/mcp</command-name>…`) or a shell command run with `!`+ * (`<bash-input>…</bash-input>`). Only text made of nothing but these is read+ * as Claude Code's: a person who pastes `<div>…</div>`, or a prompt that+ * quotes one of these tags, still sees what they typed.+ */+const ADDED_CONTEXT_TAGS = new Set([+ 'bash-input',+ 'bash-stderr',+ 'bash-stdout',+ 'command-args',+ 'command-message',+ 'command-name',+ 'ide_diagnostics',+ 'ide_opened_file',+ 'ide_selection',+ 'local-command-caveat',+ 'local-command-stderr',+ 'local-command-stdout',+ 'system-reminder',+ 'task-notification',+ 'user-prompt-submit-hook',+]);++/**+ * A Claude Code conversation as transcript turns: each prompt someone typed+ * starts a turn, and what Claude said and the tools it ran follow it.+ *+ * Reasoning is left out, as it is from a live transcript, and so are a+ * subagent's own messages: the tool call that started the subagent stands for+ * it. A tool whose result was an error is shown as failed.+ */+export function historyFromClaudeMessages(messages: SessionMessage[]): ConversationHistoryTurn[] {+ const turns: ConversationHistoryTurn[] = [];+ const tools = new Map<string, ConversationHistoryItem>();+ let turn: ConversationHistoryTurn | null = null;+ const add = (uuid: string, item: ConversationHistoryItem) => {+ if (!turn) {+ turn = { turnId: uuid, items: [] };+ turns.push(turn);+ }+ turn.items.push(item);+ };+ for (const message of messages) {+ if (message.parent_tool_use_id !== null) continue;+ const content = isRecord(message.message) ? message.message.content : undefined;+ const blocks =+ typeof content === 'string'+ ? [{ type: 'text', text: content }]+ : Array.isArray(content)+ ? content.filter(isRecord)+ : [];+ if (message.type === 'user') {+ for (const block of blocks)+ if (block.type === 'tool_result' && block.is_error === true) {+ const tool = typeof block.tool_use_id === 'string' && tools.get(block.tool_use_id);+ if (tool) tool.status = 'failed';+ }+ const texts = blocks.flatMap((block) =>+ block.type === 'text' && typeof block.text === 'string' ? [block.text.trim()] : []+ );+ if (texts.some((text) => COMPACTION_SUMMARY.test(text))) {+ turn = { turnId: message.uuid, items: [] };+ turns.push(turn);+ add(message.uuid, {+ itemId: message.uuid,+ kind: 'tool-activity',+ status: 'completed',+ title: 'Conversation compacted: the turns before this were summarized',+ text: '',+ });+ continue;+ }+ const prompt = blocks+ .map((block) =>+ block.type === 'text' && typeof block.text === 'string'+ ? promptText(block.text)+ : block.type === 'image'+ ? '[image]'+ : ''+ )+ .filter(Boolean)+ .join('\n\n');+ if (!prompt) continue;+ turn = { turnId: message.uuid, items: [] };+ turns.push(turn);+ add(message.uuid, {+ itemId: message.uuid,+ kind: 'user-message',+ status: 'completed',+ title: '',+ text: prompt,+ });+ } else if (message.type === 'assistant') {+ blocks.forEach((block, index) => {+ const itemId = `${message.uuid}:${index}`;+ if (block.type === 'text' && typeof block.text === 'string' && block.text.trim())+ add(message.uuid, {+ itemId,+ kind: 'assistant-message',+ status: 'completed',+ title: '',+ text: block.text,+ });+ else if (block.type === 'tool_use' && typeof block.name === 'string') {+ const tool: ConversationHistoryItem = {+ itemId,+ kind: 'tool-activity',+ status: 'completed',+ title: toolTitle(block.name, isRecord(block.input) ? block.input : {}),+ text: '',+ };+ add(message.uuid, tool);+ if (typeof block.id === 'string') tools.set(block.id, tool);+ }+ });+ }+ }+ return turns;+}++/**+ * What a person typed in one text block: a slash command or `!` command as they+ * typed it; nothing for what Claude Code added on its own, or its note that a+ * turn was stopped; and anything else as it was typed.+ */+function promptText(text: string): string {+ const trimmed = text.trim();+ if (INTERRUPTED.test(trimmed)) return '';+ const blocks = addedContextBlocks(trimmed);+ if (!blocks) return trimmed;+ const command = blocks.get('command-name');+ if (command !== undefined)+ return [command.trim(), blocks.get('command-args')?.trim()].filter(Boolean).join(' ');+ const shell = blocks.get('bash-input');+ if (shell !== undefined) return `! ${shell.trim()}`;+ return '';+}++/**+ * The contents of each of Claude Code's own tags in a text made of their+ * blocks and nothing else, such as `<task-notification>…</task-notification>`+ * or a command's `<bash-stdout>…</bash-stdout><bash-stderr>…</bash-stderr>`,+ * by tag, the first of each; null for any other text, which a person typed.+ * Walked rather than matched with one pattern, which would backtrack on a long+ * paste.+ */+function addedContextBlocks(text: string): Map<string, string> | null {+ const blocks = new Map<string, string>();+ let rest = text;+ if (!rest) return null;+ while (rest) {+ const open = OPENING_TAG.exec(rest);+ if (!open || !ADDED_CONTEXT_TAGS.has(open[1]!)) return null;+ const closing = `</${open[1]}>`;+ const end = rest.indexOf(closing, open[0].length);+ if (end < 0) return null;+ if (!blocks.has(open[1]!)) blocks.set(open[1]!, rest.slice(open[0].length, end));+ rest = rest.slice(end + closing.length).trimStart();+ }+ return blocks;+}diff --git a/console/packages/agent-providers/src/claude/cli-conversations.test.ts b/console/packages/agent-providers/src/claude/cli-conversations.test.tsnew file mode 100644index 000000000..933c4eccc--- /dev/null+++ b/console/packages/agent-providers/src/claude/cli-conversations.test.ts@@ -0,0 +1,432 @@+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { SDKSessionInfo } from '@anthropic-ai/claude-agent-sdk';+import { afterEach, expect, it, vi } from 'vitest';+import {+ type CliConversationDeps,+ deleteClaudeCliConversationCopies,+ forkClaudeCliConversation,+ listClaudeCliConversations,+ type ProcessInfo,+ withClaudeConfigDir,+} from './cli-conversations';++const roots: string[] = [];+afterEach(async () => {+ for (const root of roots.splice(0)) await rm(root, { recursive: true, force: true });+});++const STARTED = 'Mon Oct 26 18:02:59 2026';+const STARTED_AT = Date.parse(`${STARTED} UTC`);+const CLAUDE: ProcessInfo = { startedAt: STARTED_AT, command: '/usr/local/bin/claude --resume' };++const SESSIONS: SDKSessionInfo[] = [+ { sessionId: 'older', summary: 'Tidy the README', lastModified: 1_000, gitBranch: 'main' },+ { sessionId: 'newer', summary: 'Build fix', customTitle: 'Build fix', lastModified: 2_000 },+];++/** A Claude Code config directory, with each of `records` written as `sessions/<name>`. */+async function configDir(records: Record<string, string | object> | null): Promise<string> {+ const dir = await mkdtemp(join(tmpdir(), 'claude-config-'));+ roots.push(dir);+ if (records) {+ await mkdir(join(dir, 'sessions'));+ for (const [name, record] of Object.entries(records))+ await writeFile(+ join(dir, 'sessions', name),+ typeof record === 'string' ? record : JSON.stringify(record)+ );+ }+ return dir;+}++function holding(sessionId: string, extra: object = {}) {+ return { sessionId, procStart: STARTED, entrypoint: 'cli', status: 'idle', ...extra };+}++/** A copy of `nativeSessionId` asked for by the Console session `session-1`. */+function fork(nativeSessionId: string, confirmedClosed: boolean) {+ return { dir: '/work', nativeSessionId, consoleSessionId: 'session-1', confirmedClosed };+}++function deps(+ described: Record<number, ProcessInfo> | null = {},+ overrides: Partial<CliConversationDeps> = {}+): CliConversationDeps {+ return {+ listSessions: vi.fn(async () => structuredClone(SESSIONS)),+ getSessionInfo: vi.fn(async (id: string) =>+ structuredClone(SESSIONS.find((session) => session.sessionId === id))+ ),+ forkSession: vi.fn(async () => ({ sessionId: 'copy' })),+ tagSession: vi.fn(async () => {}),+ deleteSession: vi.fn(async () => {}),+ processExists: () => true,+ processes: vi.fn(async () =>+ described === null ? null : new Map(Object.entries(described).map(([k, v]) => [Number(k), v]))+ ),+ ...overrides,+ };+}++it('lists the conversations started from Claude Code’s own clients, newest first, with what holds each', async () => {+ const dir = await configDir({ '41.json': holding('newer'), '41.abc.key': 'not a record' });+ const run = deps({ 41: CLAUDE });+ const list = await listClaudeCliConversations('/work', { CLAUDE_CONFIG_DIR: dir }, run);++ expect(run.listSessions).toHaveBeenCalledWith({+ dir: '/work',+ includeProgrammatic: false,+ includeWorktrees: false,+ });+ expect(list).toEqual({+ ownershipKnown: true,+ conversations: [+ {+ nativeSessionId: 'newer',+ title: 'Build fix',+ lastActivityAt: 2_000,+ gitBranch: null,+ openIn: { pid: 41, entrypoint: 'cli' },+ },+ {+ nativeSessionId: 'older',+ title: 'Tidy the README',+ lastActivityAt: 1_000,+ gitBranch: 'main',+ openIn: null,+ },+ ],+ });+});++it('reads conversations from the config directory the session’s environment names', async () => {+ const dir = await configDir({});+ const seen: (string | undefined)[] = [];+ const before = process.env.CLAUDE_CONFIG_DIR;+ await listClaudeCliConversations(+ '/work',+ { CLAUDE_CONFIG_DIR: dir },+ deps(+ {},+ {+ listSessions: vi.fn(async () => {+ seen.push(process.env.CLAUDE_CONFIG_DIR);+ return [];+ }),+ }+ )+ );+ expect(seen).toEqual([dir]);+ expect(process.env.CLAUDE_CONFIG_DIR).toBe(before);+});++it('keeps a live Claude Code process holding its conversation when the clock has moved its start', async () => {+ const dir = await configDir({ '41.json': holding('newer') });+ const list = await listClaudeCliConversations(+ '/work',+ { CLAUDE_CONFIG_DIR: dir },+ deps({ 41: { ...CLAUDE, startedAt: STARTED_AT + 3_600_000 } })+ );+ expect(list.conversations[0]!.openIn?.pid).toBe(41);+});++it('does not count a record whose process has gone, or whose process id now names something else', async () => {+ const dir = await configDir({ '41.json': holding('newer'), '42.json': holding('older') });+ const run = deps(+ { 42: { startedAt: STARTED_AT + 86_400_000, command: '/bin/zsh -c cat ~/.claude/notes' } },+ { processExists: (pid) => pid === 42 }+ );+ const list = await listClaudeCliConversations('/work', { CLAUDE_CONFIG_DIR: dir }, run);+ expect(list.conversations.map((c) => c.openIn)).toEqual([null, null]);+ expect(list.ownershipKnown).toBe(true);+});++it('asks `ps` about every live process at once, and takes one it cannot describe to hold its conversation', async () => {+ const dir = await configDir({ '41.json': holding('newer'), '42.json': holding('older') });+ const run = deps(null);+ const list = await listClaudeCliConversations('/work', { CLAUDE_CONFIG_DIR: dir }, run);+ expect(run.processes).toHaveBeenCalledOnce();+ expect([...vi.mocked(run.processes).mock.calls[0]![0]].sort((a, b) => a - b)).toEqual([41, 42]);+ expect(list.conversations.map((c) => c.openIn?.pid)).toEqual([41, 42]);+});++it('says ownership is unknown when a live Claude Code process’s record cannot be read', async () => {+ const dir = await configDir({ '41.json': '{"sessionId": "new', '42.json': holding('older') });+ const list = await listClaudeCliConversations(+ '/work',+ { CLAUDE_CONFIG_DIR: dir },+ deps({ 41: CLAUDE, 42: CLAUDE })+ );+ expect(list.ownershipKnown).toBe(false);+ expect(list.conversations.map((c) => c.openIn?.pid ?? null)).toEqual([null, 42]);+});++it('reads a record in a shape it does not fully know, as long as it names the conversation', async () => {+ const dir = await configDir({+ '41.json': { sessionId: 'newer', procStart: 7, entrypoint: null },+ });+ const list = await listClaudeCliConversations(+ '/work',+ { CLAUDE_CONFIG_DIR: dir },+ deps({ 41: CLAUDE })+ );+ expect(list.ownershipKnown).toBe(true);+ expect(list.conversations[0]!.openIn).toEqual({ pid: 41, entrypoint: null });+});++it('says when this Claude Code keeps no record of what its processes hold', async () => {+ const dir = await configDir(null);+ const list = await listClaudeCliConversations('/work', { CLAUDE_CONFIG_DIR: dir }, deps());+ expect(list.ownershipKnown).toBe(false);+ expect(list.conversations.every((c) => c.openIn === null)).toBe(true);+});++it('copies a closed conversation under a new id, titled so Claude Code’s own list shows it is taken and tagged with its session', async () => {+ const dir = await configDir({});+ const seen: (string | undefined)[] = [];+ const run = deps(+ {},+ {+ forkSession: vi.fn(async () => {+ seen.push(process.env.CLAUDE_CONFIG_DIR);+ return { sessionId: 'copy' };+ }),+ }+ );+ await expect(+ forkClaudeCliConversation(fork('newer', false), { CLAUDE_CONFIG_DIR: dir }, run)+ ).resolves.toEqual({ nativeSessionId: 'copy' });+ // The one conversation is read, not the folder's whole list.+ expect(run.getSessionInfo).toHaveBeenCalledWith('newer', { dir: '/work' });+ expect(run.listSessions).not.toHaveBeenCalled();+ expect(run.forkSession).toHaveBeenCalledWith('newer', {+ dir: '/work',+ title: 'Build fix (continued in Switch Console)',+ });+ expect(run.tagSession).toHaveBeenCalledWith('copy', 'switch-console:session-1', {+ dir: '/work',+ });+ expect(vi.mocked(run.forkSession).mock.invocationCallOrder[0]).toBeLessThan(+ vi.mocked(run.tagSession).mock.invocationCallOrder[0]!+ );+ expect(run.deleteSession).not.toHaveBeenCalled();+ expect(seen).toEqual([dir]);+});++it('removes a copy it could not tag, since nothing could find it to remove later', async () => {+ const dir = await configDir({});+ const run = deps({}, { tagSession: vi.fn(async () => Promise.reject(new Error('disk full'))) });+ await expect(+ forkClaudeCliConversation(fork('newer', true), { CLAUDE_CONFIG_DIR: dir }, run)+ ).rejects.toThrow(+ "Could not mark the copy of this conversation as Switch Console's, so it was removed"+ );+ expect(run.deleteSession).toHaveBeenCalledWith('copy', { dir: '/work' });+});++it('says so when a copy it could not tag could not be removed either', async () => {+ const dir = await configDir({});+ const run = deps(+ {},+ {+ tagSession: vi.fn(async () => Promise.reject(new Error('disk full'))),+ deleteSession: vi.fn(async () => Promise.reject(new Error('permission denied'))),+ }+ );+ await expect(+ forkClaudeCliConversation(fork('newer', true), { CLAUDE_CONFIG_DIR: dir }, run)+ ).rejects.toThrow(/copy copy .*disk full.*nor remove it.*permission denied/);+});++it.each([+ { label: 'tagged', info: { tag: 'switch-console:session-0', summary: 'Build fix' } },+ { label: 'titled', info: { summary: 'Build fix (continued in Switch Console)' } },+])('refuses to copy a copy Switch made ($label)', async ({ info }) => {+ const dir = await configDir({});+ const run = deps(+ {},+ {+ getSessionInfo: vi.fn(async () => ({ sessionId: 'newer', lastModified: 2_000, ...info })),+ }+ );+ await expect(+ forkClaudeCliConversation(fork('newer', true), { CLAUDE_CONFIG_DIR: dir }, run)+ ).rejects.toThrow('This conversation is a copy Switch Console made');+ expect(run.forkSession).not.toHaveBeenCalled();+});++it('refuses to copy a conversation that is open in Claude Code', async () => {+ const dir = await configDir({ '41.json': holding('newer') });+ const run = deps({ 41: CLAUDE });+ await expect(+ forkClaudeCliConversation(fork('newer', false), { CLAUDE_CONFIG_DIR: dir }, run)+ ).rejects.toThrow('This conversation is open in Claude Code (process 41)');+ expect(run.forkSession).not.toHaveBeenCalled();+});++it('refuses a conversation that is not one of the folder’s own', async () => {+ const dir = await configDir({});+ const run = deps();+ await expect(+ forkClaudeCliConversation(fork('elsewhere', false), { CLAUDE_CONFIG_DIR: dir }, run)+ ).rejects.toThrow('Claude Code has no conversation elsewhere in /work to continue.');+ expect(run.forkSession).not.toHaveBeenCalled();+});++it('leaves out the copies Switch made, a renamed one and one no session owns included', async () => {+ const dir = await configDir({});+ const list = await listClaudeCliConversations(+ '/work',+ { CLAUDE_CONFIG_DIR: dir },+ deps(+ {},+ {+ listSessions: vi.fn(async () => [+ ...structuredClone(SESSIONS),+ {+ sessionId: 'copy',+ summary: 'Build fix (continued in Switch Console)',+ lastModified: 3_000,+ },+ {+ sessionId: 'renamed-copy',+ summary: 'Renamed in the terminal',+ customTitle: 'Renamed in the terminal',+ tag: 'switch-console:session-1',+ lastModified: 4_000,+ },+ {+ sessionId: 'tagged-by-someone',+ summary: 'Tagged by the person',+ tag: 'mine',+ lastModified: 5_000,+ },+ ]),+ }+ )+ );+ expect(list.conversations.map((c) => c.nativeSessionId)).toEqual([+ 'tagged-by-someone',+ 'newer',+ 'older',+ ]);+});++it('cuts a long title by character, never between the halves of one', async () => {+ const dir = await configDir({});+ const summary = `${'a'.repeat(199)}😀 and more`;+ const run = deps(+ {},+ {+ getSessionInfo: vi.fn(async () => ({ sessionId: 'newer', summary, lastModified: 2_000 })),+ }+ );+ await forkClaudeCliConversation(fork('newer', true), { CLAUDE_CONFIG_DIR: dir }, run);+ expect(run.forkSession).toHaveBeenCalledWith('newer', {+ dir: '/work',+ title: `${'a'.repeat(199)}😀 (continued in Switch Console)`,+ });+});++it('removes only the copies tagged as the given sessions’, wherever they came from', async () => {+ const dir = await configDir({});+ const seen: (string | undefined)[] = [];+ const run = deps(+ {},+ {+ listSessions: vi.fn(async () => {+ seen.push(process.env.CLAUDE_CONFIG_DIR);+ return [+ ...structuredClone(SESSIONS),+ {+ sessionId: 'mine',+ summary: 'Build fix',+ tag: 'switch-console:session-1',+ lastModified: 3,+ },+ {+ sessionId: 'another-session',+ summary: 'Build fix',+ tag: 'switch-console:session-10',+ lastModified: 4,+ },+ {+ sessionId: 'theirs',+ summary: 'Tidy the README',+ tag: 'switch-console:session-2',+ lastModified: 6,+ },+ {+ sessionId: 'untagged-copy',+ summary: 'Build fix (continued in Switch Console)',+ lastModified: 5,+ },+ ];+ }),+ }+ );+ await expect(+ deleteClaudeCliConversationCopies(+ '/work',+ ['session-1', 'session-2', 'session-3'],+ { CLAUDE_CONFIG_DIR: dir },+ run+ )+ ).resolves.toEqual({ deleted: { 'session-1': 1, 'session-2': 1, 'session-3': 0 } });+ // A copy is a programmatic conversation once its session has run in it.+ expect(run.listSessions).toHaveBeenCalledOnce();+ expect(run.listSessions).toHaveBeenCalledWith({+ dir: '/work',+ includeProgrammatic: true,+ includeWorktrees: false,+ });+ expect(vi.mocked(run.deleteSession).mock.calls).toEqual([+ ['mine', { dir: '/work' }],+ ['theirs', { dir: '/work' }],+ ]);+ expect(seen).toEqual([dir]);+});++it('copies only on the person’s word where Claude Code keeps no record of what is open', async () => {+ const dir = await configDir(null);+ const run = deps();+ await expect(+ forkClaudeCliConversation(fork('newer', false), { CLAUDE_CONFIG_DIR: dir }, run)+ ).rejects.toThrow('confirm it is closed');+ expect(run.forkSession).not.toHaveBeenCalled();+ await expect(+ forkClaudeCliConversation(fork('newer', true), { CLAUDE_CONFIG_DIR: dir }, run)+ ).resolves.toEqual({ nativeSessionId: 'copy' });+});++it('asks to try again, not to confirm, when a live Claude Code process’s record cannot be read just now', async () => {+ const dir = await configDir({ '41.json': '{"sessionId": "new' });+ const run = deps({ 41: CLAUDE });+ const refused = forkClaudeCliConversation(fork('newer', false), { CLAUDE_CONFIG_DIR: dir }, run);+ await expect(refused).rejects.toThrow(+ 'Console could not read which conversations Claude Code has open right now. Try again in a moment.'+ );+ expect(run.forkSession).not.toHaveBeenCalled();+});++it('takes turns with the process-wide config directory, so overlapping reads each see their own', async () => {+ const before = process.env.CLAUDE_CONFIG_DIR;+ let release!: () => void;+ const held = new Promise<void>((resolve) => {+ release = resolve;+ });+ const seen: (string | undefined)[] = [];+ const first = withClaudeConfigDir({ CLAUDE_CONFIG_DIR: '/a' }, async () => {+ await held;+ seen.push(process.env.CLAUDE_CONFIG_DIR);+ });+ const second = withClaudeConfigDir({ CLAUDE_CONFIG_DIR: '/b' }, async () => {+ seen.push(process.env.CLAUDE_CONFIG_DIR);+ });+ release();+ await Promise.all([first, second]);+ expect(seen).toEqual(['/a', '/b']);+ expect(process.env.CLAUDE_CONFIG_DIR).toBe(before);+});diff --git a/console/packages/agent-providers/src/claude/cli-conversations.ts b/console/packages/agent-providers/src/claude/cli-conversations.tsnew file mode 100644index 000000000..3045a676a--- /dev/null+++ b/console/packages/agent-providers/src/claude/cli-conversations.ts@@ -0,0 +1,499 @@+import { execFile } from 'node:child_process';+import { access, readFile, readdir } from 'node:fs/promises';+import { homedir } from 'node:os';+import { join } from 'node:path';+import { setTimeout as delay } from 'node:timers/promises';+import { promisify } from 'node:util';+import {+ deleteSession as sdkDeleteSession,+ forkSession as sdkForkSession,+ getSessionInfo as sdkGetSessionInfo,+ listSessions as sdkListSessions,+ type SDKSessionInfo,+ type SessionStore,+ type SessionStoreEntry,+ tagSession as sdkTagSession,+} from '@anthropic-ai/claude-agent-sdk';+import { z } from 'zod';++/** The Claude Code conversations started in a folder outside Switch, newest first. */+export const cliConversationListSchema = z.object({+ /**+ * Whether every running Claude Code process said which conversation it has+ * open. False when this Claude Code keeps no such records, or a live+ * process's record could not be read: an open conversation can then look+ * like a closed one.+ */+ ownershipKnown: z.boolean(),+ conversations: z.array(+ z.object({+ nativeSessionId: z.string(),+ title: z.string(),+ lastActivityAt: z.number(),+ gitBranch: z.string().nullable(),+ /** The running Claude Code process that has the conversation open, or null for none. */+ openIn: z.object({ pid: z.number(), entrypoint: z.string().nullable() }).nullable(),+ })+ ),+});+export type CliConversationList = z.infer<typeof cliConversationListSchema>;++export const forkedCliConversationSchema = z.object({ nativeSessionId: z.string() });++/** How many copies `--delete-cli-conversation-copies` removed, for each Console session it named. */+export const deletedCliConversationCopiesSchema = z.object({+ deleted: z.record(z.string(), z.number().int().min(0)),+});++/** What a fork is titled in Claude Code's own `/resume` list, so it reads as taken. */+const FORK_TITLE_SUFFIX = ' (continued in Switch Console)';++/**+ * How every copy Switch makes is tagged: with this and the id of the Console+ * session that owns it. The tag is what a copy left by a session that never+ * started is found and removed by, and it survives a rename where the title+ * would not.+ */+const COPY_TAG_PREFIX = 'switch-console:';++/** The tag of the copy a Console session continues. */+export function cliConversationCopyTag(consoleSessionId: string): string {+ return `${COPY_TAG_PREFIX}${consoleSessionId}`;+}++/**+ * Whether a conversation is a copy Switch made to continue another, by its+ * tag or, for a copy made before copies were tagged, its title.+ */+function isSwitchCopy(session: Pick<SDKSessionInfo, 'tag' | 'summary'>): boolean {+ return (+ session.tag?.startsWith(COPY_TAG_PREFIX) === true || session.summary.endsWith(FORK_TITLE_SUFFIX)+ );+}++/**+ * One running Claude Code process's own record, `sessions/<pid>.json` under its+ * config directory. Only the conversation it names is required; the rest is+ * read where it is in a shape this knows.+ */+const holderRecordSchema = z.object({+ sessionId: z.string().min(1),+ procStart: z.unknown().optional(),+ entrypoint: z.unknown().optional(),+});++/**+ * A command line that runs Claude Code: its `claude` executable, or the npm or+ * SDK package's script. Not any mention of the word, which a shell running a+ * script about `~/.claude` would make.+ */+const CLAUDE_COMMAND =+ /(?:^|[/\\\s])claude(?:\.exe)?(?:\s|$)|@anthropic-ai\/claude-(?:code|agent-sdk)\//;++/** How far apart a record's start time and its process's may be and still be the same process. */+const START_TOLERANCE_MS = 5_000;++type Holder = { pid: number; entrypoint: string | null };+type HolderRecord = z.infer<typeof holderRecordSchema>;++/** A running process as `ps` describes it. */+export type ProcessInfo = { startedAt: number | null; command: string };++export interface CliConversationDeps {+ listSessions: typeof sdkListSessions;+ getSessionInfo: typeof sdkGetSessionInfo;+ forkSession: typeof sdkForkSession;+ tagSession: typeof sdkTagSession;+ deleteSession: typeof sdkDeleteSession;+ processExists: (pid: number) => boolean;+ /** What `ps` says about these processes, in one call; null when it cannot be asked. */+ processes: (pids: number[]) => Promise<Map<number, ProcessInfo> | null>;+}++const defaultDeps: CliConversationDeps = {+ listSessions: sdkListSessions,+ getSessionInfo: sdkGetSessionInfo,+ forkSession: sdkForkSession,+ tagSession: sdkTagSession,+ deleteSession: sdkDeleteSession,+ processExists,+ processes,+};++/**+ * The conversations started in `dir` from Claude Code's own terminal or IDE+ * clients, with the process that has each one open. Conversations a program+ * started through the SDK, Switch's own sessions among them, are left out, and+ * so are the copies Switch made to continue, renamed or not: one whose session+ * went away, or whose copy finished after Console stopped waiting, is not a+ * CLI conversation.+ *+ * `env` is the session's execution environment, so the conversations are+ * looked for in the config directory the session's Claude Code will use.+ */+export async function listClaudeCliConversations(+ dir: string,+ env: Record<string, string | undefined>,+ deps: CliConversationDeps = defaultDeps+): Promise<CliConversationList> {+ const [sessions, ownership] = await Promise.all([+ withClaudeConfigDir(env, () =>+ deps.listSessions({ dir, includeProgrammatic: false, includeWorktrees: false })+ ),+ claudeHolders(claudeConfigDir(env), deps),+ ]);+ return {+ ownershipKnown: ownership !== null && ownership.complete,+ conversations: sessions+ .filter((session) => !isSwitchCopy(session))+ .sort((a, b) => b.lastModified - a.lastModified)+ .map((session) => ({+ nativeSessionId: session.sessionId,+ title: session.summary,+ lastActivityAt: session.lastModified,+ gitBranch: session.gitBranch ?? null,+ openIn: ownership?.holders.get(session.sessionId) ?? null,+ })),+ };+}++/**+ * A copy of a Claude Code conversation under a new id, for a Switch session to+ * continue: the original stays the terminal's, and nothing Switch does is+ * written to it. Refused while a running Claude Code process has it open, so+ * the copy is never taken from the middle of a turn; and, where Claude Code+ * cannot say which conversations are open, unless the person said this one+ * is closed (`confirmedClosed`). A copy Switch made is not copied again.+ *+ * The copy is tagged with the Console session that owns it+ * ({@link cliConversationCopyTag}), so one whose session never started can be+ * found and removed ({@link deleteClaudeCliConversationCopies}). A copy that+ * cannot be tagged is removed at once, since nothing could find it later.+ */+export async function forkClaudeCliConversation(+ request: {+ dir: string;+ nativeSessionId: string;+ consoleSessionId: string;+ confirmedClosed: boolean;+ },+ env: Record<string, string | undefined>,+ deps: CliConversationDeps = defaultDeps+): Promise<{ nativeSessionId: string }> {+ const { dir, nativeSessionId } = request;+ const ownership = await claudeHolders(claudeConfigDir(env), deps);+ const holder = ownership?.holders.get(nativeSessionId);+ if (holder)+ throw new Error(+ `This conversation is open in Claude Code (process ${holder.pid}). Close it there, then try again.`+ );+ if (!request.confirmedClosed) {+ if (ownership === null)+ throw new Error(+ 'Console cannot tell whether this conversation is open in Claude Code right now. Choose it again and confirm it is closed.'+ );+ if (!ownership.complete)+ throw new Error(+ 'Console could not read which conversations Claude Code has open right now. Try again in a moment.'+ );+ }+ return withClaudeConfigDir(env, async () => {+ const source = await deps.getSessionInfo(nativeSessionId, { dir });+ if (!source)+ throw new Error(`Claude Code has no conversation ${nativeSessionId} in ${dir} to continue.`);+ if (isSwitchCopy(source))+ throw new Error(+ 'This conversation is a copy Switch Console made to continue another one. Choose the conversation it was copied from.'+ );+ const fork = await deps.forkSession(nativeSessionId, {+ dir,+ // Cut by code point, so a character outside the BMP is never split in two.+ title: `${Array.from(source.summary).slice(0, 200).join('')}${FORK_TITLE_SUFFIX}`,+ });+ try {+ await deps.tagSession(fork.sessionId, cliConversationCopyTag(request.consoleSessionId), {+ dir,+ });+ } catch (error) {+ try {+ await deps.deleteSession(fork.sessionId, { dir });+ } catch (removal) {+ throw new Error(+ `Could not mark the copy ${fork.sessionId} of this conversation as Switch Console's (${String(error)}), nor remove it (${String(removal)}).`,+ { cause: error }+ );+ }+ throw new Error(+ `Could not mark the copy of this conversation as Switch Console's, so it was removed: ${String(error)}`,+ { cause: error }+ );+ }+ return { nativeSessionId: fork.sessionId };+ });+}++/**+ * Removes the copies in `dir` tagged as any of the given Console sessions',+ * and says how many each had: what is left when a session's copy was made but+ * the session never started. Only a conversation carrying exactly one of those+ * sessions' tags is removed. The folder is listed once for all of them.+ */+export async function deleteClaudeCliConversationCopies(+ dir: string,+ consoleSessionIds: string[],+ env: Record<string, string | undefined>,+ deps: CliConversationDeps = defaultDeps+): Promise<{ deleted: Record<string, number> }> {+ const owners = new Map(consoleSessionIds.map((id) => [cliConversationCopyTag(id), id]));+ return withClaudeConfigDir(env, async () => {+ const deleted: Record<string, number> = Object.fromEntries(+ consoleSessionIds.map((id) => [id, 0])+ );+ const sessions = await deps.listSessions({+ dir,+ includeProgrammatic: true,+ includeWorktrees: false,+ });+ for (const session of sessions) {+ const owner = session.tag === undefined ? undefined : owners.get(session.tag);+ if (owner === undefined) continue;+ await deps.deleteSession(session.sessionId, { dir });+ deleted[owner] = (deleted[owner] ?? 0) + 1;+ }+ return { deleted };+ });+}++/**+ * The saved conversations under one Claude Code config directory, as the SDK's+ * readers take a store: for reading a conversation from the directory a+ * session uses without changing this process's environment, which a host+ * running other work cannot afford. Read only; a conversation is found by its+ * id under any project, as Claude Code's own resume finds it.+ *+ * Only a last line that is not JSON is left out: a write Claude Code has not+ * finished. Anywhere else such a line is a transcript this cannot read whole,+ * and reading it is refused rather than shown with a gap.+ */+export function configDirSessionStore(configDir: string): SessionStore {+ return {+ append: async () => {+ throw new Error('This store only reads saved conversations.');+ },+ load: async ({ sessionId, subpath }) => {+ if (subpath !== undefined) return null;+ const path = await savedConversationPath(configDir, sessionId);+ if (path === null) return null;+ const lines = (await readFile(path, 'utf8')).split('\n');+ let last = lines.length - 1;+ while (last >= 0 && !lines[last]!.trim()) last--;+ return lines.flatMap((line, index): SessionStoreEntry[] => {+ if (!line.trim()) return [];+ try {+ return [JSON.parse(line) as SessionStoreEntry];+ } catch (error) {+ if (index === last) return [];+ throw new Error(+ `Line ${index + 1} of Claude Code's saved conversation ${path} is not JSON: ${String(error)}`,+ { cause: error }+ );+ }+ });+ },+ };+}++/**+ * Where Claude Code saved the conversation with this id under a config+ * directory, `projects/<directory>/<id>.jsonl` in whichever project it was+ * started in; null when it saved none.+ */+export async function savedConversationPath(+ configDir: string,+ sessionId: string+): Promise<string | null> {+ const projects = join(configDir, 'projects');+ let names: string[];+ try {+ names = await readdir(projects);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;+ throw error;+ }+ for (const name of names) {+ const path = join(projects, name, `${sessionId}.jsonl`);+ try {+ await access(path);+ return path;+ } catch (error) {+ const code = (error as NodeJS.ErrnoException).code;+ if (code !== 'ENOENT' && code !== 'ENOTDIR') throw error;+ }+ }+ return null;+}++/** Where Claude Code keeps its conversations for a process with this environment. */+export function claudeConfigDir(env: Record<string, string | undefined>): string {+ return env.CLAUDE_CONFIG_DIR || join(env.HOME || homedir(), '.claude');+}++/** The last `withClaudeConfigDir` call to settle; each waits for the one before. */+let configDirTurn: Promise<unknown> = Promise.resolve();++/**+ * Runs `work` with this process's `CLAUDE_CONFIG_DIR` naming the directory+ * `env` gives Claude Code. Listing and copying use the SDK's own file access,+ * which takes the directory from this process's environment and remembers it+ * per value of the variable, so setting it is enough. For the host's one-off+ * commands, each its own short-lived process; a long-lived host reads through+ * {@link configDirSessionStore} instead. Calls take turns all the same, and+ * are not to be nested: an inner call would wait for the outer one for ever.+ */+export function withClaudeConfigDir<T>(+ env: Record<string, string | undefined>,+ work: () => Promise<T>+): Promise<T> {+ const run = configDirTurn.then(async () => {+ const previous = process.env.CLAUDE_CONFIG_DIR;+ process.env.CLAUDE_CONFIG_DIR = claudeConfigDir(env);+ try {+ return await work();+ } finally {+ if (previous === undefined) delete process.env.CLAUDE_CONFIG_DIR;+ else process.env.CLAUDE_CONFIG_DIR = previous;+ }+ });+ configDirTurn = run.catch(() => {});+ return run;+}++/**+ * The conversations Claude Code's running processes have open, by+ * conversation id, from the record each process keeps. Null when there are no+ * records at all: a Claude Code too old to keep them.+ *+ * Wrong in the safe direction where it has to be. A record whose process has+ * gone holds nothing, and neither does one whose process id now names+ * something other than Claude Code that started at another time. A live+ * process that is Claude Code holds its conversation whatever its start time+ * says, since a clock that was stepped moves that; so does one `ps` cannot+ * describe. A live process whose record cannot be read leaves `complete` false.+ */+async function claudeHolders(+ dir: string,+ deps: CliConversationDeps+): Promise<{ holders: Map<string, Holder>; complete: boolean } | null> {+ let names: string[];+ try {+ names = await readdir(join(dir, 'sessions'));+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;+ throw error;+ }+ const records: { pid: number; record: HolderRecord | null }[] = [];+ for (const name of names) {+ const pid = Number(/^(\d+)\.json$/.exec(name)?.[1]);+ if (!Number.isSafeInteger(pid) || pid <= 0 || !deps.processExists(pid)) continue;+ const record = await readHolderRecord(join(dir, 'sessions', name));+ if (record !== 'gone') records.push({ pid, record });+ }+ const described = records.length ? await deps.processes(records.map((r) => r.pid)) : null;+ const holders = new Map<string, Holder>();+ let complete = true;+ for (const { pid, record } of records) {+ const info = described?.get(pid);+ if (info && !CLAUDE_COMMAND.test(info.command)) {+ const recorded = recordedStart(record?.procStart);+ if (+ recorded === null ||+ info.startedAt === null ||+ Math.abs(info.startedAt - recorded) > START_TOLERANCE_MS+ )+ continue;+ }+ if (!record) {+ complete = false;+ continue;+ }+ holders.set(record.sessionId, {+ pid,+ entrypoint: typeof record.entrypoint === 'string' ? record.entrypoint : null,+ });+ }+ return { holders, complete };+}++/**+ * A process record, read twice before giving up: its process rewrites it each+ * time it goes busy or idle, so one read can meet it half written. Null when it+ * cannot be read; `gone` when its process removed it, which it does on exit.+ */+async function readHolderRecord(path: string): Promise<HolderRecord | null | 'gone'> {+ for (let attempt = 0; ; attempt++) {+ try {+ return holderRecordSchema.parse(JSON.parse(await readFile(path, 'utf8')));+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return 'gone';+ if (attempt > 0) {+ console.warn(`Could not read Claude Code's process record ${path}: ${String(error)}`);+ return null;+ }+ await delay(100);+ }+ }+}++/** A record's `procStart`, which Claude Code writes as `ps -o lstart=` prints it in UTC. */+function recordedStart(value: unknown): number | null {+ if (typeof value !== 'string') return null;+ const parsed = Date.parse(`${value.trim()} UTC`);+ return Number.isNaN(parsed) ? null : parsed;+}++function processExists(pid: number): boolean {+ try {+ process.kill(pid, 0);+ return true;+ } catch (error) {+ // EPERM: it exists, as another user's.+ return (error as NodeJS.ErrnoException).code !== 'ESRCH';+ }+}++/**+ * `ps -o pid=,lstart=,args=` for these processes, in UTC and the C locale so its+ * start time reads as Claude Code's records write it. A process that has gone+ * is not in the answer; `ps` then exits 1 if none is left.+ */+async function processes(pids: number[]): Promise<Map<number, ProcessInfo> | null> {+ if (process.platform === 'win32') return null;+ let stdout: string;+ try {+ ({ stdout } = await promisify(execFile)(+ 'ps',+ ['-o', 'pid=,lstart=,args=', '-p', pids.join(',')],+ { encoding: 'utf8', env: { ...process.env, TZ: 'UTC', LC_ALL: 'C' } }+ ));+ } catch (error) {+ const output = (error as { stdout?: unknown }).stdout;+ if ((error as { code?: unknown }).code !== 1 || typeof output !== 'string') {+ console.warn(+ `Could not ask ps about Claude Code's processes, so each live one is taken to hold its conversation: ${String(error)}`+ );+ return null;+ }+ stdout = output;+ }+ const described = new Map<number, ProcessInfo>();+ for (const line of stdout.split('\n')) {+ const [pid, weekday, month, day, time, year, ...command] = line.trim().split(/\s+/);+ if (!pid || !year) continue;+ const startedAt = Date.parse(`${weekday} ${month} ${day} ${time} ${year} UTC`);+ described.set(Number(pid), {+ startedAt: Number.isNaN(startedAt) ? null : startedAt,+ command: command.join(' '),+ });+ }+ return described;+}diff --git a/console/packages/agent-providers/src/host/cli-conversations.test.ts b/console/packages/agent-providers/src/host/cli-conversations.test.tsnew file mode 100644index 000000000..19db50d91--- /dev/null+++ b/console/packages/agent-providers/src/host/cli-conversations.test.ts@@ -0,0 +1,50 @@+import { describe, expect, it } from 'vitest';+import { EXECUTION_INHERIT_ENV } from './agent-env';+import {+ cliConversationRequestSchema,+ MAX_INHERITED_NAMES,+ MAX_SESSIONS_PER_REQUEST,+} from './cli-conversations';++/** A removal request as Console stages it, naming `consoleSessionIds`. */+function removal(inheritEnv: string[], consoleSessionIds: string[]) {+ return {+ provider: 'claude',+ dir: '/work',+ env: {},+ inheritEnv,+ consoleSessionIds,+ };+}++function names(prefix: string, count: number): string[] {+ return Array.from({ length: count }, (_, index) => `${prefix}_${index}`);+}++/** Where and why a request was refused, or null when it was accepted. */+function refusal(request: unknown) {+ const result = cliConversationRequestSchema.safeParse(request);+ return result.success+ ? null+ : result.error.issues.map(({ path, code }) => ({ path: path.join('.'), code }));+}++describe('cliConversationRequestSchema', () => {+ it('accepts the names Console inherits and as many sessions as one request may name', () => {+ expect(+ refusal(removal([...EXECUTION_INHERIT_ENV], names('session', MAX_SESSIONS_PER_REQUEST)))+ ).toBeNull();+ });++ it('refuses more inherited names than a request may carry', () => {+ expect(refusal(removal(names('NAME', MAX_INHERITED_NAMES + 1), ['session-1']))).toEqual([+ { path: 'inheritEnv', code: 'too_big' },+ ]);+ });++ it('refuses more sessions than one removal may name', () => {+ expect(refusal(removal(['PATH'], names('session', MAX_SESSIONS_PER_REQUEST + 1)))).toEqual([+ { path: 'consoleSessionIds', code: 'too_big' },+ ]);+ });+});diff --git a/console/packages/agent-providers/src/host/cli-conversations.ts b/console/packages/agent-providers/src/host/cli-conversations.tsnew file mode 100644index 000000000..ff0c755ec--- /dev/null+++ b/console/packages/agent-providers/src/host/cli-conversations.ts@@ -0,0 +1,105 @@+import { readFile } from 'node:fs/promises';+import { z } from 'zod';+import {+ type CliConversationList,+ deleteClaudeCliConversationCopies,+ forkClaudeCliConversation,+ listClaudeCliConversations,+} from '../claude/cli-conversations';+import { executionEnvironment } from './shared-config';++/**+ * What the host's one-off conversation commands print instead of their answer+ * when they fail, so Console can say why: the conversation is open in the+ * terminal, say, rather than that a command exited 1.+ */+export const cliConversationFailureSchema = z.object({ error: z.string() });++/** The host's one-off conversation commands. */+export const CLI_CONVERSATION_MODES = [+ '--cli-conversations',+ '--fork-cli-conversation',+ '--delete-cli-conversation-copies',+] as const;+export type CliConversationMode = (typeof CLI_CONVERSATION_MODES)[number];++/**+ * The most inherited names a request may carry, so a request is refused+ * before an unbounded list is read. Console sends `EXECUTION_INHERIT_ENV`,+ * well under this, with room for it to grow.+ */+export const MAX_INHERITED_NAMES = 512;++/**+ * The most Console sessions one `--delete-cli-conversation-copies` request may+ * name, so a request is refused before an unbounded list is read. Console asks+ * about more in several requests.+ */+export const MAX_SESSIONS_PER_REQUEST = 200;++/**+ * What Console asks a conversation command, staged as a private file because+ * a shell setup may hold secrets a command line would show to `ps`. The+ * session's variables, shell setup and inherited names are what its host would+ * start the provider with, so Claude Code is looked for where the session's+ * Claude Code will look.+ */+export const cliConversationRequestSchema = z.strictObject({+ provider: z.string(),+ dir: z.string().min(1),+ env: z.record(z.string(), z.string()),+ shellSetup: z.string().optional(),+ inheritEnv: z.array(z.string()).max(MAX_INHERITED_NAMES),+ /** The conversation to copy, for `--fork-cli-conversation`. */+ nativeSessionId: z.string().min(1).optional(),+ /** The Console session a copy is for, for `--fork-cli-conversation`, which tags the copy with it. */+ consoleSessionId: z.string().min(1).optional(),+ /**+ * The Console sessions whose copies `--delete-cli-conversation-copies`+ * removes: the conversations tagged with exactly one of them.+ */+ consoleSessionIds: z.array(z.string().min(1)).min(1).max(MAX_SESSIONS_PER_REQUEST).optional(),+ /**+ * The person said the conversation is closed, for a copy where Claude Code+ * cannot say which conversations are open. Absent means they did not.+ */+ confirmedClosed: z.boolean().optional(),+});+export type CliConversationRequest = z.infer<typeof cliConversationRequestSchema>;++/** Answers one of the {@link CLI_CONVERSATION_MODES} for the request at `path`. */+export async function answerCliConversationRequest(+ mode: CliConversationMode,+ path: string+): Promise<+ CliConversationList | { nativeSessionId: string } | { deleted: Record<string, number> }+> {+ const request = cliConversationRequestSchema.parse(JSON.parse(await readFile(path, 'utf8')));+ if (request.provider !== 'claude')+ throw new Error(+ `Switch continues conversations started in Claude Code, not ones started in ${request.provider}.`+ );+ const env = await executionEnvironment(+ request.dir,+ request.env,+ request.shellSetup,+ request.inheritEnv+ );+ if (mode === '--cli-conversations') return listClaudeCliConversations(request.dir, env);+ if (mode === '--delete-cli-conversation-copies') {+ if (!request.consoleSessionIds)+ throw new Error('Name the Console sessions whose copies to remove.');+ return deleteClaudeCliConversationCopies(request.dir, request.consoleSessionIds, env);+ }+ if (!request.consoleSessionId) throw new Error('Name the Console session the copy is for.');+ if (!request.nativeSessionId) throw new Error('Name the conversation to copy.');+ return forkClaudeCliConversation(+ {+ dir: request.dir,+ nativeSessionId: request.nativeSessionId,+ consoleSessionId: request.consoleSessionId,+ confirmedClosed: request.confirmedClosed === true,+ },+ env+ );+}diff --git a/console/packages/agent-providers/src/host/journal.ts b/console/packages/agent-providers/src/host/journal.tsindex a1c168daf..17cf23fa3 100644--- a/console/packages/agent-providers/src/host/journal.ts+++ b/console/packages/agent-providers/src/host/journal.ts@@ -36,14 +36,19 @@ export class Journal<T> {}append(value: T): Promise<void> {- const copy = structuredClone(value);+ return this.appendAll([value]);+ }++ /** Appends several entries with one write and one flush to disk. */+ appendAll(values: T[]): Promise<void> {+ const copies = structuredClone(values);const pending = this.tail.then(async () => {if (this.poisoned) throw new Error('Journal write failed; reload before continuing.');const file = await open(this.path, 'a', 0o600);try {- await file.writeFile(`${JSON.stringify(copy)}\n`);+ await file.writeFile(copies.map((copy) => `${JSON.stringify(copy)}\n`).join(''));await file.sync();- this.records.push(copy);+ this.records.push(...copies);} catch (error) {this.poisoned = true;throw error;diff --git a/console/packages/agent-providers/src/host/session-host.test.ts b/console/packages/agent-providers/src/host/session-host.test.tsindex 2fa386655..1df0d4394 100644--- a/console/packages/agent-providers/src/host/session-host.test.ts+++ b/console/packages/agent-providers/src/host/session-host.test.ts@@ -1,14 +1,19 @@import { randomUUID } from 'node:crypto';-import { appendFile, mkdtemp, readFile, rm } from 'node:fs/promises';+import { appendFile, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';import { tmpdir } from 'node:os';import { join } from 'node:path';import type { Command, Session } from '@switch-console/shared/session-v1';import { afterEach, describe, expect, it, vi } from 'vitest';-import { ProviderConversationUnavailableError, type ProviderAdapter } from '../adapter';+import {+ type ConversationHistoryTurn,+ ProviderConversationUnavailableError,+ type ProviderAdapter,+} from '../adapter';import type { ProviderRuntimeEvent } from '../events';import { abandonWaits, announcing, changed, until } from '../testing/until';+import { Redactions } from './redaction';import { CONNECTOR_APPROVAL_NOTICE, ServiceNotices } from './service-notices';-import { HostedSession, type RoomReply, unpostedReply } from './session-host';+import { HostedSession, recentTurns, type RoomReply, unpostedReply } from './session-host';// Every step here is a journal write flushed to disk, and Windows runners take// many times longer over that. The waits have no deadline of their own (see@@ -572,6 +577,387 @@ it('starts a new conversation on its own when the saved one is gone and never an);});+/** A session started to continue a conversation begun outside Switch, as Console configures one. */+function continuing(+ provider: Session['provider'],+ history: () => Promise<ConversationHistoryTurn[]>+) {+ const fixture = setup(provider);+ fixture.adapter.conversationHistory = vi.fn(history);+ return {+ ...fixture,+ config: {+ ...fixture.config,+ importHistory: true,+ input: { ...fixture.config.input, resume: { nativeSessionId: 'cli-copy' } },+ },+ };+}++const CLI_TURNS: ConversationHistoryTurn[] = [+ {+ turnId: 'cli:prompt-1',+ items: [+ {+ itemId: 'cli:prompt-1',+ kind: 'user-message',+ status: 'completed',+ title: '',+ text: 'Fix the build',+ },+ {+ itemId: 'cli:answer-1:0',+ kind: 'tool-activity',+ status: 'failed',+ title: 'pnpm build',+ text: '',+ },+ {+ itemId: 'cli:answer-1:1',+ kind: 'assistant-message',+ status: 'completed',+ title: '',+ text: 'x'.repeat(5000),+ },+ ],+ },+];++it('starts a continued conversation’s transcript with its earlier turns, before the provider and once', async () => {+ const root = await mkdtemp(join(tmpdir(), 'sdk-history-test-'));+ roots.push(root);+ const fixture = continuing('claude', async () => structuredClone(CLI_TURNS));+ const host = await startHost(root, fixture.config, fixture.adapter);+ hosts.push(host);+ await until(() => expect(host.snapshot().session.status).toBe('ready'));+ expect(fixture.adapter.conversationHistory).toHaveBeenCalledWith('cli-copy', tmpdir(), {});+ expect(fixture.adapter.startSession).toHaveBeenCalledWith(+ expect.objectContaining({ resume: { nativeSessionId: 'cli-copy' } })+ );+ expect(vi.mocked(fixture.adapter.conversationHistory!).mock.invocationCallOrder[0]).toBeLessThan(+ vi.mocked(fixture.adapter.startSession).mock.invocationCallOrder[0]!+ );+ const snapshot = host.snapshot();+ expect(snapshot.turns).toEqual([+ { type: 'turn.upsert', turnId: 'imported:cli:prompt-1', status: 'completed', commandId: null },+ ]);+ expect(+ snapshot.items.map((item) => [item.itemId, item.kind, item.status, item.text.length])+ ).toEqual([+ ['imported:cli:prompt-1', 'user-message', 'completed', 13],+ ['imported:cli:answer-1:0', 'tool-activity', 'failed', 0],+ ['imported:cli:answer-1:1', 'assistant-message', 'completed', 4096],+ ['imported:cli:answer-1:1:part:1', 'assistant-message', 'completed', 904],+ ]);+ expect(snapshot.items.every((item) => item.origin === null && item.revision === 1)).toBe(true);+ expect(snapshot.notices.map((notice) => notice.code)).toContain('HISTORY_IMPORTED');++ await host.shutdown();+ const next = continuing('claude', async () => structuredClone(CLI_TURNS));+ const restarted = await startHost(root, next.config, next.adapter);+ hosts.push(restarted);+ await until(() => expect(restarted.snapshot().session.status).toBe('ready'));+ expect(next.adapter.conversationHistory).not.toHaveBeenCalled();+ expect(next.adapter.startSession).toHaveBeenCalledWith(+ expect.objectContaining({ resume: { nativeSessionId: 'native' } })+ );+ expect(restarted.snapshot().items).toHaveLength(4);+});++it('resumes the conversation it continues after a start that failed once its import was done', async () => {+ const root = await mkdtemp(join(tmpdir(), 'sdk-history-test-'));+ roots.push(root);+ const fixture = continuing('claude', async () => structuredClone(CLI_TURNS));+ vi.mocked(fixture.adapter.startSession).mockRejectedValueOnce(new Error('Authentication failed'));+ await expect(startHost(root, fixture.config, fixture.adapter)).rejects.toThrow(+ 'Authentication failed'+ );+ const next = continuing('claude', async () => structuredClone(CLI_TURNS));+ const restarted = await startHost(root, next.config, next.adapter);+ hosts.push(restarted);+ await until(() => expect(restarted.snapshot().session.status).toBe('ready'));+ expect(next.adapter.conversationHistory).not.toHaveBeenCalled();+ expect(next.adapter.startSession).toHaveBeenCalledWith(+ expect.objectContaining({ resume: { nativeSessionId: 'cli-copy' } })+ );+});++it('asks before replacing a continued conversation it cannot resume, and says why its history is missing', async () => {+ const root = await mkdtemp(join(tmpdir(), 'sdk-history-test-'));+ roots.push(root);+ const fixture = continuing('claude', async () => {+ throw new Error('Claude Code has no saved conversation cli-copy to show.');+ });+ vi.mocked(fixture.adapter.startSession).mockRejectedValueOnce(+ new ProviderConversationUnavailableError('claude', 'session', 'No saved conversation')+ );+ const host = await startHost(root, fixture.config, fixture.adapter);+ hosts.push(host);+ expect(host.resetDecisionPending).toBe(true);+ expect(fixture.adapter.startSession).toHaveBeenCalledTimes(1);+ expect(host.snapshot().notices).toContainEqual(+ expect.objectContaining({+ code: 'HISTORY_UNAVAILABLE',+ message: expect.stringContaining('no saved conversation cli-copy'),+ })+ );+ expect(host.snapshot().notices.map((notice) => notice.code)).not.toContain(+ 'CONVERSATION_STARTED_FRESH'+ );++ // Said once: a later start does not try the history again.+ await host.shutdown();+ const next = continuing('claude', async () => structuredClone(CLI_TURNS));+ const restarted = await startHost(root, next.config, next.adapter);+ hosts.push(restarted);+ expect(next.adapter.conversationHistory).not.toHaveBeenCalled();+});++it('scrubs a token from a continued conversation’s history before cutting long text into parts', async () => {+ const root = await mkdtemp(join(tmpdir(), 'sdk-history-test-'));+ roots.push(root);+ const token = `redact-me-${'q'.repeat(14)}`;+ const text = `${'x'.repeat(4090)}${token} and more`;+ const fixture = continuing('claude', async () => [+ {+ turnId: 'cli:prompt-1',+ items: [{ itemId: 'cli:a', kind: 'assistant-message', status: 'completed', title: '', text }],+ },+ ]);+ const redactions = new Redactions();+ redactions.add(token);+ const host = await startHost(root, { ...fixture.config, redactions }, fixture.adapter);+ hosts.push(host);+ await until(() => expect(host.snapshot().session.status).toBe('ready'));+ const published = host+ .snapshot()+ .items.map((item) => item.text)+ .join('');+ expect(published).not.toContain(token.slice(0, 6));+ expect(published).not.toContain(token.slice(-6));+});++it('says how much of a continued conversation it left out, a long latest turn included', async () => {+ const root = await mkdtemp(join(tmpdir(), 'sdk-history-test-'));+ roots.push(root);+ const fixture = continuing('claude', async () => [+ {+ turnId: 'cli:long',+ items: Array.from({ length: 600 }, (_, index) => ({+ itemId: `cli:long:${index}`,+ kind: 'tool-activity' as const,+ status: 'completed' as const,+ title: `step ${index}`,+ text: '',+ })),+ },+ ]);+ const host = await startHost(root, fixture.config, fixture.adapter);+ hosts.push(host);+ await until(() => expect(host.snapshot().session.status).toBe('ready'));+ expect(host.snapshot().items).toHaveLength(500);+ expect(host.snapshot().notices).toContainEqual(+ expect.objectContaining({+ code: 'HISTORY_IMPORTED',+ message: expect.stringContaining('the last 500 of the 600 messages and tool calls'),+ })+ );+});++it('starts afresh without asking again once the person chose a fresh start over a copy it could not resume', async () => {+ const root = await mkdtemp(join(tmpdir(), 'sdk-history-test-'));+ roots.push(root);+ const fixture = continuing('claude', async () => structuredClone(CLI_TURNS));+ vi.mocked(fixture.adapter.startSession).mockRejectedValueOnce(+ new ProviderConversationUnavailableError('claude', 'session', 'No saved conversation')+ );+ const host = await startHost(root, fixture.config, fixture.adapter);+ hosts.push(host);+ expect(host.resetDecisionPending).toBe(true);+ const reset: Command = { ...message('fresh-start'), body: { type: 'session.reset' } };+ expect((await host.command(reset)).status).toBe('applied');+ await until(() => expect(host.snapshot().session.status).toBe('ready'));+ expect(vi.mocked(fixture.adapter.startSession).mock.calls[1]![0].resume).toBeUndefined();+ await host.shutdown();++ // Claude Code saves a conversation only once a turn has run in it, so the+ // fresh one cannot be resumed either. It was never answered, and it is not+ // the copy the session was made to continue: nothing is lost by starting+ // another.+ const next = continuing('claude', async () => structuredClone(CLI_TURNS));+ vi.mocked(next.adapter.startSession).mockRejectedValueOnce(+ new ProviderConversationUnavailableError('claude', 'session', 'No saved conversation')+ );+ const restarted = await startHost(root, next.config, next.adapter);+ hosts.push(restarted);+ expect(restarted.resetDecisionPending).toBe(false);+ expect(next.adapter.startSession).toHaveBeenCalledTimes(2);+ expect(vi.mocked(next.adapter.startSession).mock.calls[0]![0].resume).toEqual({+ nativeSessionId: 'native',+ });+ expect(vi.mocked(next.adapter.startSession).mock.calls[1]![0].resume).toBeUndefined();+ await until(() =>+ expect(restarted.replay(0).events.map((e) => e.body)).toContainEqual(+ expect.objectContaining({ code: 'CONVERSATION_STARTED_FRESH' })+ )+ );+});++it('starts a continued session with a warning when its earlier turns cannot be recorded', async () => {+ const root = await mkdtemp(join(tmpdir(), 'sdk-history-test-'));+ roots.push(root);+ const fixture = continuing('claude', async () => [+ {+ turnId: 'cli:prompt-1',+ items: [+ {+ itemId: 'cli:prompt-1',+ // Not a kind the transcript records, so the event is refused.+ kind: 'reasoning' as never,+ status: 'completed',+ title: '',+ text: 'Fix the build',+ },+ ],+ },+ ]);+ const host = await startHost(root, fixture.config, fixture.adapter);+ hosts.push(host);+ await until(() => expect(host.snapshot().session.status).toBe('ready'));+ expect(fixture.adapter.startSession).toHaveBeenCalledWith(+ expect.objectContaining({ resume: { nativeSessionId: 'cli-copy' } })+ );+ const codes = host.snapshot().notices.map((notice) => notice.code);+ expect(codes).toContain('HISTORY_UNAVAILABLE');+ expect(codes).not.toContain('HISTORY_IMPORTED');+ expect(host.snapshot().items).toEqual([]);++ // Settled by the warning: a later start does not try again.+ await host.shutdown();+ const next = continuing('claude', async () => structuredClone(CLI_TURNS));+ const restarted = await startHost(root, next.config, next.adapter);+ hosts.push(restarted);+ await until(() => expect(restarted.snapshot().session.status).toBe('ready'));+ expect(next.adapter.conversationHistory).not.toHaveBeenCalled();+});++it('publishes an item a continued conversation repeats once, as it first appears', async () => {+ const root = await mkdtemp(join(tmpdir(), 'sdk-history-test-'));+ roots.push(root);+ const item = (text: string) => ({+ itemId: 'cli:answer-1:0',+ kind: 'assistant-message' as const,+ status: 'completed' as const,+ title: '',+ text,+ });+ const fixture = continuing('claude', async () => [+ { turnId: 'cli:prompt-1', items: [item('First')] },+ { turnId: 'cli:prompt-1', items: [item('Second')] },+ ]);+ const host = await startHost(root, fixture.config, fixture.adapter);+ hosts.push(host);+ await until(() => expect(host.snapshot().session.status).toBe('ready'));+ expect(host.snapshot().turns.map((turn) => turn.turnId)).toEqual(['imported:cli:prompt-1']);+ expect(host.snapshot().items.map((i) => [i.itemId, i.text])).toEqual([+ ['imported:cli:answer-1:0', 'First'],+ ]);+ expect(host.snapshot().notices.map((notice) => notice.code)).toContain('HISTORY_IMPORTED');+});++it('refuses to start a continued session that has no copy to resume, rather than start afresh', async () => {+ const root = await mkdtemp(join(tmpdir(), 'sdk-history-test-'));+ roots.push(root);+ const fixture = continuing('claude', async () => structuredClone(CLI_TURNS));+ const { resume: _resume, ...input } = fixture.config.input;+ await expect(startHost(root, { ...fixture.config, input }, fixture.adapter)).rejects.toThrow(+ 'no copy of it was recorded to resume'+ );+ expect(fixture.adapter.startSession).not.toHaveBeenCalled();+});++it('finishes an import a crash cut short without republishing what it had published', async () => {+ const root = await mkdtemp(join(tmpdir(), 'sdk-history-test-'));+ roots.push(root);+ const fixture = continuing('claude', async () => structuredClone(CLI_TURNS));+ const host = await startHost(root, fixture.config, fixture.adapter);+ hosts.push(host);+ await until(() => expect(host.snapshot().session.status).toBe('ready'));+ await host.shutdown();+ hosts.splice(hosts.indexOf(host), 1);+ // As if the host died after the history but before the notice that settles it.+ const journal = join(root, 'events.jsonl');+ const lines = (await readFile(journal, 'utf8')).split('\n').filter(Boolean);+ const settled = lines.findIndex((line) => line.includes('HISTORY_IMPORTED'));+ await writeFile(journal, `${lines.slice(0, settled).join('\n')}\n`);+ const before = (await readFile(journal, 'utf8')).split('\n').filter(Boolean).length;+ // A token issued since would make republished text differ from what is there.+ const redactions = new Redactions();+ redactions.add('x'.repeat(40));+ const next = continuing('claude', async () => structuredClone(CLI_TURNS));+ const restarted = await startHost(root, { ...next.config, redactions }, next.adapter);+ hosts.push(restarted);+ await until(() => expect(restarted.snapshot().session.status).toBe('ready'));+ expect(next.adapter.conversationHistory).toHaveBeenCalledOnce();+ const events = (await readFile(journal, 'utf8')).split('\n').filter(Boolean).slice(before);+ expect(events.filter((line) => line.includes('"item.upsert"'))).toEqual([]);+ expect(restarted.snapshot().notices.map((notice) => notice.code)).toContain('HISTORY_IMPORTED');+});++it('publishes the prompt and later parts a crash kept from being recorded, though their turn and first part were', async () => {+ const root = await mkdtemp(join(tmpdir(), 'sdk-history-test-'));+ roots.push(root);+ const fixture = continuing('claude', async () => structuredClone(CLI_TURNS));+ const host = await startHost(root, fixture.config, fixture.adapter);+ hosts.push(host);+ await until(() => expect(host.snapshot().session.status).toBe('ready'));+ await host.shutdown();+ hosts.splice(hosts.indexOf(host), 1);+ // The turn shares its id with its prompt, and the reply's first part is in;+ // the prompt itself, the reply's second part and the settling notice are not.+ const journal = join(root, 'events.jsonl');+ const lines = (await readFile(journal, 'utf8')).split('\n').filter(Boolean);+ const settled = lines.findIndex((line) => line.includes('HISTORY_IMPORTED'));+ const kept = lines+ .slice(0, settled)+ .filter(+ (line) => !line.includes('"itemId":"imported:cli:prompt-1"') && !line.includes(':part:1"')+ );+ await writeFile(journal, `${kept.join('\n')}\n`);+ const next = continuing('claude', async () => structuredClone(CLI_TURNS));+ const restarted = await startHost(root, next.config, next.adapter);+ hosts.push(restarted);+ await until(() => expect(restarted.snapshot().session.status).toBe('ready'));+ expect(restarted.snapshot().items.map((item) => item.itemId)).toEqual(+ expect.arrayContaining(['imported:cli:prompt-1', 'imported:cli:answer-1:1:part:1'])+ );+ expect(+ restarted.snapshot().items.filter((item) => item.turnId.startsWith('imported:'))+ ).toHaveLength(4);+});++it('keeps the most recent whole turns of a long conversation', () => {+ const turn = (id: string, count: number): ConversationHistoryTurn => ({+ turnId: id,+ items: Array.from({ length: count }, (_, index) => ({+ itemId: `${id}:${index}`,+ kind: 'assistant-message' as const,+ status: 'completed' as const,+ title: '',+ text: '',+ })),+ });+ const turns = [turn('a', 3), turn('b', 2), turn('c', 2)];+ expect(recentTurns(turns, 5).map((t) => t.turnId)).toEqual(['b', 'c']);+ expect(recentTurns(turns, 7).map((t) => t.turnId)).toEqual(['a', 'b', 'c']);+ expect(recentTurns([turn('big', 9)], 4)[0]!.items.map((item) => item.itemId)).toEqual([+ 'big:5',+ 'big:6',+ 'big:7',+ 'big:8',+ ]);+});+it('validates native model choices and persists a confirmed choice across restart', async () => {const root = await mkdtemp(join(tmpdir(), 'sdk-model-test-'));roots.push(root);diff --git a/console/packages/agent-providers/src/host/session-host.ts b/console/packages/agent-providers/src/host/session-host.tsindex 003d394fa..161fee673 100644--- a/console/packages/agent-providers/src/host/session-host.ts+++ b/console/packages/agent-providers/src/host/session-host.ts@@ -2,9 +2,11 @@ import { randomUUID } from 'node:crypto';import { join } from 'node:path';import { isDeepStrictEqual } from 'node:util';import {+ IMPORTED_TURN_PREFIX,SessionReplica,commandSchema,eventBytes,+ hasOwnActivity,serverEventSchema,} from '@switch-console/shared/session-v1';import type {@@ -20,10 +22,15 @@ import type {} from '@switch-console/shared/session-v1';import { z } from 'zod';import { ProviderConversationUnavailableError } from '../adapter';-import type { ProviderAdapter, ProviderSessionStartInput, TurnAttachment } from '../adapter';+import type {+ ConversationHistoryTurn,+ ProviderAdapter,+ ProviderSessionStartInput,+ TurnAttachment,+} from '../adapter';import type { TokenUsage, TurnOutcome, UserInputAnswers } from '../events';import type { ProviderRuntimeEvent } from '../events';-import { ChatProjector } from '../session-v1/chat-projector';+import { ChatProjector, ITEM_PART_CHARACTERS, itemParts } from '../session-v1/chat-projector';import { ATTACHMENT_MIME_TYPES } from './attachments';import { Journal } from './journal';import { fitModelCatalog } from './model-catalog';@@ -59,6 +66,12 @@ export const hostInboxRecordSchema = z.discriminatedUnion('type', [/** The host posts this turn's reply to its room itself: decided once, before posting. */z.object({ type: z.literal('room-reply'), commandId: z.string() }),]);+/**+ * The notices that end a continued conversation's import, either way. Read+ * back from the event journal rather than recorded in the inbox, whose+ * records an older host could not read.+ */+const HISTORY_SETTLED = new Set(['HISTORY_IMPORTED', 'HISTORY_UNAVAILABLE']);type RecordEntry = z.infer<typeof hostInboxRecordSchema>;export type HostSessionStart = {session: Session;@@ -75,6 +88,12 @@ export type HostSessionStart = {replyToRoom?: (reply: RoomReply) => Promise<void>;/** Service tokens to scrub from every event before it is recorded; none when absent. */redactions?: Redactions;+ /**+ * The session continues a native conversation started outside Switch, so+ * its transcript starts with that conversation's turns, and a conversation+ * that cannot be resumed is never quietly replaced by a new one.+ */+ importHistory?: boolean;/*** Told each time the provider asks to run a connector's tool, before the* request is published, so a notice it raises comes ahead of the card.@@ -106,6 +125,7 @@ export class HostedSession {private readonly dispatched = new Set<string>();private readonly finished = new Set<string>();private readonly roomReplies = new Set<string>();+ private historyImported = false;private readonly postedTurns = new Set<string>();/** Turns whose posts to the room were refused, with the last refusal. */private readonly failedPosts = new Map<string, string>();@@ -168,6 +188,8 @@ export class HostedSession {this.replica = new SessionReplica(prior);}this.replica.apply(event);+ if (event.body.type === 'notice' && HISTORY_SETTLED.has(event.body.code))+ this.historyImported = true;}for (const record of inbox.records) {if (record.type === 'accepted') this.commands.set(record.command.commandId, record.command);@@ -290,7 +312,8 @@ export class HostedSession {return host;}// A session whose provider never opened a conversation (its first- // start failed) has nothing to resume: it starts one below.+ // start failed) has nothing to resume: it starts one below. One that+ // continues a conversation resumes the copy it was started with.if (!host.nativeId && host.providerAnswered())throw new Error('Cannot recover a session without its native provider ID.');if (config.epochAuthority !== 'server') config.session.epoch = randomUUID();@@ -301,6 +324,16 @@ export class HostedSession {host.replica = new SessionReplica(next);}await host.publish({ type: 'session.upsert', session: structuredClone(config.session) });+ if (config.importHistory) {+ // Without the copy to resume, starting would open a new conversation+ // in place of the one this session was made to continue.+ const continued = config.input.resume?.nativeSessionId;+ if (!continued)+ throw new Error(+ 'This session continues a conversation started outside Switch, but no copy of it was recorded to resume.'+ );+ if (!host.historyImported) await host.importHistory(continued);+ }const native = await host.startProvider({...config.input,...(host.nativeId ? { resume: { nativeSessionId: host.nativeId } } : {}),@@ -329,8 +362,12 @@ export class HostedSession {await host.eventSerial;// Nothing the provider said is lost when it never answered (a session// whose turns all failed while its CLI was signed out, say): start a- // new conversation rather than ask.- if (!host.providerAnswered()) {+ // new conversation rather than ask. The copy of a conversation this+ // session was started to continue was answered before Switch had it;+ // a fresh one it started since was not.+ const resuming = host.nativeId ?? config.input.resume?.nativeSessionId;+ const copy = config.importHistory ? config.input.resume?.nativeSessionId : undefined;+ if (!host.providerAnswered() && (copy === undefined || resuming !== copy)) {try {await host.startFresh();return host;@@ -349,13 +386,16 @@ export class HostedSession {}}- /** Whether the provider has ever answered in this session. */+ /**+ * Whether the provider has ever answered in this session. Turns copied in+ * from a conversation this session continues are not its own answers.+ */private providerAnswered(): boolean {const snapshot = this.replica.snapshot();- return (- snapshot.items.some((item) => item.kind === 'assistant-message') ||- snapshot.turns.some((turn) => turn.status === 'completed')- );+ return hasOwnActivity({+ items: snapshot.items.filter((item) => item.kind === 'assistant-message'),+ turns: snapshot.turns.filter((turn) => turn.status === 'completed'),+ });}/** Start a new provider conversation in place of one that cannot be resumed. */@@ -385,6 +425,135 @@ export class HostedSession {});}+ /**+ * Publishes the earlier turns of the native conversation this session+ * continues, ahead of any of its own: the most recent ones, up to+ * {@link HISTORY_ITEM_LIMIT} items, a batch to a journal write, under ids+ * marked as imported (`IMPORTED_TURN_PREFIX`). Settled by the notice that+ * ends it. An import a crash cut short runs again on the next start and+ * publishes only what it had not; an item the conversation itself repeats+ * is published once.+ *+ * A conversation that cannot be read, or whose turns cannot be recorded, is+ * said in the transcript, once, and does not stop the session: resuming is+ * what decides whether the conversation is there, and asks before replacing+ * it.+ */+ private async importHistory(nativeSessionId: string): Promise<void> {+ let turns: ConversationHistoryTurn[];+ try {+ if (!this.adapter.conversationHistory)+ throw new Error(`${this.config.session.provider} cannot read its saved conversations.`);+ turns = await this.adapter.conversationHistory(+ nativeSessionId,+ this.config.input.cwd,+ this.config.input.env+ );+ } catch (error) {+ await this.historyUnavailable(error);+ return;+ }+ const shown = recentTurns(turns, HISTORY_ITEM_LIMIT);+ // What an import a crash cut short already published stays as it was, and+ // an id the conversation repeats is published the first time only:+ // published again it could differ (a token scrubbed since, or another+ // entry's text), and two versions of one revision are a conflict the+ // transcript refuses.+ const present = this.replica.snapshot();+ const publishedTurns = new Set(present.turns.map((turn) => turn.turnId));+ const publishedItems = new Set(present.items.map((item) => item.itemId));+ const bodies: HostBody[] = [];+ let shortened = false;+ for (const turn of shown) {+ const turnId = `${IMPORTED_TURN_PREFIX}${turn.turnId}`;+ if (!publishedTurns.has(turnId)) {+ publishedTurns.add(turnId);+ bodies.push({ type: 'turn.upsert', turnId, status: 'completed', commandId: null });+ }+ for (const item of turn.items) {+ // Scrubbed whole before it is cut, as the chat projector does, so no+ // part carries a token in pieces that the scrub of each part would miss.+ const scrubbed = this.config.redactions+ ? this.config.redactions.text(item.text)+ : item.text;+ const characters = Array.from(scrubbed);+ if (characters.length > HISTORY_TEXT_LIMIT) shortened = true;+ const text =+ characters.length > HISTORY_TEXT_LIMIT+ ? `${characters.slice(0, HISTORY_TEXT_LIMIT - 1).join('')}…`+ : scrubbed;+ const title = this.config.redactions ? this.config.redactions.text(item.title) : item.title;+ const parts = itemParts(+ {+ itemId: `${IMPORTED_TURN_PREFIX}${item.itemId}`,+ turnId,+ revision: 1,+ kind: item.kind,+ status: item.status,+ title: Array.from(title).slice(0, ITEM_PART_CHARACTERS).join(''),+ text: '',+ attachments: [],+ origin: null,+ },+ text,+ 1+ );+ for (const part of parts) {+ if (publishedItems.has(part.itemId)) continue;+ publishedItems.add(part.itemId);+ bodies.push({ type: 'item.upsert', item: part });+ }+ }+ }+ const total = turns.reduce((count, turn) => count + turn.items.length, 0);+ const kept = shown.reduce((count, turn) => count + turn.items.length, 0);+ try {+ // Batched to spare a flush to disk per event, and bounded in bytes too,+ // so no one write is larger than a single event could already make it.+ let batch: HostBody[] = [];+ let batchBytes = 0;+ for (const body of bodies) {+ const bytes = Buffer.byteLength(JSON.stringify(body));+ if (+ batch.length &&+ (batch.length >= HISTORY_BATCH || batchBytes + bytes > HISTORY_BATCH_BYTES)+ ) {+ await this.publishBatch(batch);+ batch = [];+ batchBytes = 0;+ }+ batch.push(body);+ batchBytes += bytes;+ }+ if (batch.length) await this.publishBatch(batch);+ await this.publish({+ type: 'notice',+ level: 'info',+ code: 'HISTORY_IMPORTED',+ message: `${kept < total ? `Above are the last ${kept} of the ${total} messages and tool calls in the conversation this session continues; the earlier ones are not shown here.` : 'Above is the conversation this session continues.'} It was copied when the session started, and the agent has all of it. The original is unchanged.${shortened ? ' Long messages are cut short here.' : ''}`,+ });+ } catch (error) {+ await this.historyUnavailable(error);+ return;+ }+ this.historyImported = true;+ }++ /**+ * Says in the transcript why the earlier turns of the conversation this+ * session continues are not shown, or not all of them, and settles the+ * import so it is said once.+ */+ private async historyUnavailable(error: unknown): Promise<void> {+ await this.publish({+ type: 'notice',+ level: 'warning',+ code: 'HISTORY_UNAVAILABLE',+ message: `Could not show the earlier turns of the conversation this session continues: ${error instanceof Error ? error.message : String(error)}`,+ });+ this.historyImported = true;+ }+private async startProvider(input: ProviderSessionStartInput) {const [authentication, provider] = await Promise.allSettled([Promise.resolve().then(() => this.config.authenticate?.()),@@ -1323,23 +1492,33 @@ export class HostedSession {return bodies.reduce((tail, body) => tail.then(() => this.publish(body)), Promise.resolve());}private publish(body: ServerEvent['body']): Promise<void> {+ return this.publishBatch([body]);+ }+ /** Publishes events in order, recorded with one write to the journal. */+ private publishBatch(bodies: ServerEvent['body'][]): Promise<void> {const pending = this.publishing.then(async () => {- const event: ServerEvent = {- contractVersion: 1,- eventId: randomUUID(),- sessionId: this.config.session.sessionId,- sequence: this.events.records.length + 1,- occurredAt: new Date().toISOString(),- // Scrubbed here, once: the journal, Console's view and the activity- // rows Switch shows on the bridges are all made from what is recorded.- body: this.config.redactions ? this.config.redactions.value(body) : body,- };- if (eventBytes(event) > 64 * 1024)- throw new Error('PAYLOAD_TOO_LARGE: event exceeds 64 KiB.');- serverEventSchema.parse(event);- await this.events.append(event);- this.replica.apply(event);- for (const listener of this.listeners) listener(event);+ const occurredAt = new Date().toISOString();+ const events = bodies.map((body, index) => {+ const event: ServerEvent = {+ contractVersion: 1,+ eventId: randomUUID(),+ sessionId: this.config.session.sessionId,+ sequence: this.events.records.length + 1 + index,+ occurredAt,+ // Scrubbed here, once: the journal, Console's view and the activity+ // rows Switch shows on the bridges are all made from what is recorded.+ body: this.config.redactions ? this.config.redactions.value(body) : body,+ };+ if (eventBytes(event) > 64 * 1024)+ throw new Error('PAYLOAD_TOO_LARGE: event exceeds 64 KiB.');+ serverEventSchema.parse(event);+ return event;+ });+ await this.events.appendAll(events);+ for (const event of events) {+ this.replica.apply(event);+ for (const listener of this.listeners) listener(event);+ }});this.publishing = pending.catch(() => {});return pending;@@ -1385,6 +1564,37 @@ export class HostedSession {}}+/** How many items of a continued conversation's earlier turns a transcript starts with. */+const HISTORY_ITEM_LIMIT = 500;+/** How much of one imported item's text is shown; the agent still has all of it. */+const HISTORY_TEXT_LIMIT = 4 * ITEM_PART_CHARACTERS;+/** How many of a continued conversation's events are recorded with one journal write. */+const HISTORY_BATCH = 100;+/** And how much: no larger than one event may be, so no write is larger than one could be already. */+const HISTORY_BATCH_BYTES = 64 * 1024;++/**+ * The most recent turns that together hold no more than `limit` items, oldest+ * first. A latest turn larger than that on its own keeps its last `limit`.+ */+export function recentTurns(+ turns: ConversationHistoryTurn[],+ limit: number+): ConversationHistoryTurn[] {+ const kept: ConversationHistoryTurn[] = [];+ let items = 0;+ for (let index = turns.length - 1; index >= 0; index--) {+ const turn = turns[index]!;+ if (items + turn.items.length > limit) {+ if (kept.length === 0) kept.push({ ...turn, items: turn.items.slice(-limit) });+ break;+ }+ kept.push(turn);+ items += turn.items.length;+ }+ return kept.reverse();+}+/*** What the host posts for a room turn that ended without the agent posting:* only that it failed, and why, so a crash is not silent. A turn thatdiff --git a/console/packages/agent-providers/src/host/shared-config.ts b/console/packages/agent-providers/src/host/shared-config.tsindex c8d03fc92..4d57e5a1c 100644--- a/console/packages/agent-providers/src/host/shared-config.ts+++ b/console/packages/agent-providers/src/host/shared-config.ts@@ -41,6 +41,12 @@ export const sharedConfigSchema = z.strictObject({* addressed a room message to.*/grant: z.strictObject({ roomId: z.string().min(1), messageId: z.string().min(1) }).optional(),+ /**+ * The session continues a native conversation started outside Switch+ * (`start.input.resume`), and its transcript starts with that conversation.+ * Absent from every other session, and from configurations written before it.+ */+ importHistory: z.boolean().optional(),execution: z.strictObject({credentialsPath: z.string().min(1),diff --git a/console/packages/agent-providers/src/host/shared-daemon.ts b/console/packages/agent-providers/src/host/shared-daemon.tsindex dfc5f8725..e02944b89 100644--- a/console/packages/agent-providers/src/host/shared-daemon.ts+++ b/console/packages/agent-providers/src/host/shared-daemon.ts@@ -4,6 +4,11 @@ import { mkdir, readFile } from 'node:fs/promises';import { join, resolve } from 'node:path';import { openSwitchStream, runAgentHost } from './agent-host';import { AttachmentTransfers } from './attachment-transfers';+import {+ answerCliConversationRequest,+ CLI_CONVERSATION_MODES,+ type CliConversationMode,+} from './cli-conversations';import { type ControlContext, ensureSessions, serveControl } from './control';import { dirMode } from './host-permissions';import { materializeHostedProvider } from './hosted-provider';@@ -78,6 +83,18 @@ async function main(): Promise<void> {}return;}+ if (isCliConversationMode(root)) {+ // Answered on stdout either way, so Console can say why one failed.+ try {+ console.log(JSON.stringify(await answerCliConversationRequest(root, configPath)));+ } catch (error) {+ console.log(+ JSON.stringify({ error: error instanceof Error ? error.message : String(error) })+ );+ process.exitCode = 1;+ }+ return;+ }if (root === '--probe') {console.log(JSON.stringify(@@ -294,6 +311,10 @@ async function helper(): Promise<void> {}}+function isCliConversationMode(value: string): value is CliConversationMode {+ return (CLI_CONVERSATION_MODES as readonly string[]).includes(value);+}+if (root === '--git-credential' || root === '--github-cli') await helper();elsetry {@@ -303,6 +324,7 @@ elseroot !== undefined &&root !== '--probe' &&root !== '--models' &&+ !isCliConversationMode(root) &&mode !== '--supervise' &&mode !== '--watch-supervise') {diff --git a/console/packages/agent-providers/src/host/shared-host.test.ts b/console/packages/agent-providers/src/host/shared-host.test.tsindex 09d6a5167..3b562f384 100644--- a/console/packages/agent-providers/src/host/shared-host.test.ts+++ b/console/packages/agent-providers/src/host/shared-host.test.ts@@ -6,6 +6,7 @@ import { join } from 'node:path';import type { Command, Session, Snapshot } from '@switch-console/shared/session-v1';import { afterEach, expect, it, vi } from 'vitest';import {+ type ConversationHistoryTurn,ProviderConversationUnavailableError,type ProviderAdapter,type TurnAttachment,@@ -160,6 +161,8 @@ async function start(instructions?: string | null;/** The provider takes developer messages mid-conversation; each one is recorded here. */developerMessages?: string[];+ /** The session continues a conversation started outside Switch, which had these turns. */+ continuing?: ConversationHistoryTurn[];} = {}): Promise<Harness> {const parent = fakeParent();@@ -270,6 +273,8 @@ async function start(};},};+ const continuing = opts.continuing;+ if (continuing) adapter.conversationHistory = vi.fn(async () => structuredClone(continuing));if (opts.conversationLost)vi.mocked(adapter.startSession).mockRejectedValueOnce(new ProviderConversationUnavailableError(@@ -311,8 +316,10 @@ async function start(env: {},mcpServers: {},connectorMcpServers: [],+ ...(continuing ? { resume: { nativeSessionId: 'cli-copy' } } : {}),},...(opts.rooms ? { roomConnection: { connectionId: 'controller' } } : {}),+ importHistory: continuing !== undefined,parent: channel,parkAfterMs: opts.parkAfterMs ?? null,instructions: opts.instructions ?? null,@@ -465,6 +472,36 @@ it('turns a room message it was handed into a fenced prompt, once', async () =>}});+it('starts a continued conversation as new here: its instructions are not news, and its first room message opens it', async () => {+ const host = await start({+ rooms: true,+ instructions: '',+ continuing: [+ {+ turnId: 'prompt-1',+ items: [+ {+ itemId: 'prompt-1',+ kind: 'user-message',+ status: 'completed',+ title: '',+ text: 'Fix the build',+ },+ ],+ },+ ],+ });+ try {+ expect(await host.parent.ask({ type: 'room', handoff: roomMessage(1, 'hi') })).toMatchObject({+ ok: true,+ });+ await until(() => expect(host.turns).toHaveLength(1));+ expect(host.turns[0]!.text).not.toContain('instructions were');+ } finally {+ expect(await host.stop()).toBeNull();+ }+});+it('tells a running conversation once that its instructions changed, across restarts', async () => {// Each host is its own process, whose exit frees its ownership for the next.const restart = async (host: Harness, instructions: string): Promise<Harness> => {diff --git a/console/packages/agent-providers/src/host/shared-host.ts b/console/packages/agent-providers/src/host/shared-host.tsindex 69c8a1c01..b89aa431f 100644--- a/console/packages/agent-providers/src/host/shared-host.ts+++ b/console/packages/agent-providers/src/host/shared-host.ts@@ -1,7 +1,7 @@import { createHash } from 'node:crypto';import { join, resolve } from 'node:path';import { setTimeout as delay } from 'node:timers/promises';-import { commandSchema } from '@switch-console/shared/session-v1';+import { commandSchema, hasOwnActivity } from '@switch-console/shared/session-v1';import type { Command, CommandStatus, Session, Snapshot } from '@switch-console/shared/session-v1';import { z } from 'zod';import type { ProviderAdapter, ProviderSessionStartInput } from '../adapter';@@ -98,6 +98,8 @@ export type SharedHostOptions = {input: ProviderSessionStartInput;roomConnection?: z.infer<typeof roomConnectionSchema>;grant?: { roomId: string; messageId: string };+ /** The session continues a native conversation started outside Switch. */+ importHistory: boolean;/** The IPC channel to the process that started this host, or null if none did. */parent: ParentChannel | null;/** How long the host waits with nothing to do before parking; null never parks. */@@ -409,6 +411,7 @@ export async function runSharedHost(: {}),session: options.session,input: options.input,+ importHistory: options.importHistory,resumeOperationId: options.resumeOperationId,authenticate: options.authenticate,redactions: options.redactions,@@ -659,12 +662,14 @@ export async function runSharedHost(// A conversation that has not started yet is given the current ones as it// starts. One that has, and was told others, gets a note with the next// room message: its provider would otherwise keep the old ones.+ // Turns copied in from a conversation started outside Switch are not this+ // conversation having started here: it resumes under Switch's context.+ const startedHere = () => hasOwnActivity(host!.snapshot());const instructions = options.instructions;let instructionsNote: string | null = null;if (instructions !== null) {const told = await readToldInstructions(options.root);- if (host.snapshot().turns.length === 0)- await recordToldInstructions(options.root, instructions);+ if (!startedHere()) await recordToldInstructions(options.root, instructions);else if (told !== instructions) instructionsNote = instructionsChangedNote(instructions);}const instructionsTold = async (): Promise<void> => {@@ -699,7 +704,7 @@ export async function runSharedHost(roomId: string): Promise<{ note: string | null; instructions: string | null }> => {if (!parentChannel || !options.roomConnection) return { note: null, instructions: null };- if (host!.snapshot().turns.length === 0) toldRooms = {};+ if (!startedHere()) toldRooms = {};try {const { instructions } = roomInstructionsAnswerSchema.parse(await parentChannel.ask({ type: 'room-instructions', roomId })@@ -842,7 +847,7 @@ export async function runSharedHost(surface: 'switch-web',attachments,preface: preface.length ? preface.join('\n\n') : null,- firstOfConversation: host!.snapshot().turns.length === 0,+ firstOfConversation: !startedHere(),});// Taken by the host before the delivery is acknowledged: the host's// inbox is durable, so a crash between the two runs the message once@@ -1188,6 +1193,7 @@ export async function hostSessionProcess(input: {input: prepared.input,roomConnection: config.roomConnection,grant: config.grant,+ importHistory: config.importHistory ?? false,parent,parkAfterMs: parkAfterMs(),instructions: config.execution?.instructions ?? null,diff --git a/console/packages/agent-providers/src/index.ts b/console/packages/agent-providers/src/index.tsindex 96b75b09d..47ca2a7a7 100644--- a/console/packages/agent-providers/src/index.ts+++ b/console/packages/agent-providers/src/index.ts@@ -1,5 +1,7 @@export type {AgentLaunchDefinition,+ ConversationHistoryItem,+ ConversationHistoryTurn,HttpMcpServerSpec,McpServerSpec,ModelSelection,@@ -177,6 +179,18 @@ export { readSharedCredentials, sharedConfigSchema } from './host/shared-config'export type { SharedHostConfig } from './host/shared-config';export { providerReadinessSchema } from './readiness';+export {+ cliConversationListSchema,+ deletedCliConversationCopiesSchema,+ forkedCliConversationSchema,+ type CliConversationList,+} from './claude/cli-conversations';+export {+ cliConversationFailureSchema,+ type CliConversationMode,+ type CliConversationRequest,+ MAX_SESSIONS_PER_REQUEST,+} from './host/cli-conversations';export { verifyClaudeSignIn } from './claude/sign-in';export type { ProviderReadiness, SignInCheckInput } from './readiness';export {diff --git a/console/packages/agent-providers/src/session-v1/chat-projector.ts b/console/packages/agent-providers/src/session-v1/chat-projector.tsindex bffa4f074..59e4e26ca 100644--- a/console/packages/agent-providers/src/session-v1/chat-projector.ts+++ b/console/packages/agent-providers/src/session-v1/chat-projector.ts@@ -3,6 +3,27 @@ import type { ProviderRuntimeEvent } from '../events';import type { Redactions } from '../host/redaction';type TurnContext = { commandId: string | null; origin: Origin | null };++/** As much text as one published item carries; longer text goes in `:part:` items after it. */+export const ITEM_PART_CHARACTERS = 4096;++/**+ * `item` with `text`, as the items it is published as: the first under the+ * item's own id, and each further {@link ITEM_PART_CHARACTERS} of text under+ * `<id>:part:<n>`. At least `minimum` of them, so an item whose text has grown+ * shorter still updates every part it was published in before.+ */+export function itemParts(item: Item, text: string, minimum: number): Item[] {+ const characters = Array.from(text);+ const count = Math.max(1, Math.ceil(characters.length / ITEM_PART_CHARACTERS), minimum);+ return Array.from({ length: count }, (_, index) => ({+ ...structuredClone(item),+ itemId: index === 0 ? item.itemId : `${item.itemId}:part:${index}`,+ text: characters+ .slice(index * ITEM_PART_CHARACTERS, (index + 1) * ITEM_PART_CHARACTERS)+ .join(''),+ }));+}type BufferedItem = { item: Item; emittedAt: number; dirty: boolean; parts: number };/** Projects chat and tool summaries only. The host owns sequencing and durable publication. */@@ -82,7 +103,7 @@ export class ChatProjector {revision: previous?.item.revision ?? 0,kind,status: event.item.status === 'in_progress' ? 'in-progress' : event.item.status,- title: event.item.title.slice(0, 4096),+ title: event.item.title.slice(0, ITEM_PART_CHARACTERS),text: kind === 'tool-activity' ? '' : (event.item.text ?? previous?.item.text ?? ''),attachments: [],origin: kind === 'user-message' ? context.origin : null,@@ -123,17 +144,9 @@ export class ChatProjector {buffer.item.revision += 1;buffer.emittedAt = now;buffer.dirty = false;- const characters = Array.from(this.visible(buffer.item.text, final));- const count = Math.max(1, Math.ceil(characters.length / 4096), buffer.parts);- buffer.parts = count;- return Array.from({ length: count }, (_, index) => ({- type: 'item.upsert' as const,- item: {- ...structuredClone(buffer.item),- itemId: index === 0 ? buffer.item.itemId : `${buffer.item.itemId}:part:${index}`,- text: characters.slice(index * 4096, (index + 1) * 4096).join(''),- },- }));+ const parts = itemParts(buffer.item, this.visible(buffer.item.text, final), buffer.parts);+ buffer.parts = parts.length;+ return parts.map((item) => ({ type: 'item.upsert' as const, item }));}private visible(text: string, final: boolean): string {diff --git a/console/packages/core/package.json b/console/packages/core/package.jsonindex 3a8a29b2e..470029db5 100644--- a/console/packages/core/package.json+++ b/console/packages/core/package.json@@ -56,7 +56,7 @@"@switch-console/shared": "workspace:*","semver": "^7.8.4","smol-toml": "^1.8.0",- "zod": "^4.4.3"+ "zod": "^4.6.7"},"devDependencies": {"@types/node": "^24.13.3",diff --git a/console/packages/plugins/package.json b/console/packages/plugins/package.jsonindex e97887db6..0d24e3248 100644--- a/console/packages/plugins/package.json+++ b/console/packages/plugins/package.json@@ -33,7 +33,7 @@"dependencies": {"@switch-console/core": "workspace:*","smol-toml": "^1.8.0",- "zod": "^4.4.3"+ "zod": "^4.6.7"},"devDependencies": {"@typescript/native-preview": "7.0.0-dev.20260609.1",diff --git a/console/packages/shared/package.json b/console/packages/shared/package.jsonindex c6ac8eec6..7cd24a465 100644--- a/console/packages/shared/package.json+++ b/console/packages/shared/package.json@@ -36,7 +36,7 @@"typecheck": "tsgo --noEmit -p tsconfig.json"},"dependencies": {- "zod": "^4.4.3"+ "zod": "^4.6.7"},"devDependencies": {"@types/node": "^24.13.3",diff --git a/console/packages/shared/src/session-v1/imported.ts b/console/packages/shared/src/session-v1/imported.tsnew file mode 100644index 000000000..07aac6358--- /dev/null+++ b/console/packages/shared/src/session-v1/imported.ts@@ -0,0 +1,21 @@+import type { Snapshot } from './contract';++/**+ * What a turn's id starts with when the host copied the turn into the+ * transcript from a conversation that began outside Switch, rather than ran+ * it. Such turns are history: they say nothing about whether this session has+ * done anything yet.+ */+export const IMPORTED_TURN_PREFIX = 'imported:';++export function isImportedTurn(turnId: string): boolean {+ return turnId.startsWith(IMPORTED_TURN_PREFIX);+}++/** Whether the session has run anything itself, leaving imported history aside. */+export function hasOwnActivity(snapshot: Pick<Snapshot, 'turns' | 'items'>): boolean {+ return (+ snapshot.turns.some((turn) => !isImportedTurn(turn.turnId)) ||+ snapshot.items.some((item) => !isImportedTurn(item.turnId))+ );+}diff --git a/console/packages/shared/src/session-v1/index.ts b/console/packages/shared/src/session-v1/index.tsindex 50790513a..a7dae037d 100644--- a/console/packages/shared/src/session-v1/index.ts+++ b/console/packages/shared/src/session-v1/index.ts@@ -1,5 +1,6 @@export type * from './contract';export { SessionReplica } from './replica';+export { hasOwnActivity, IMPORTED_TURN_PREFIX, isImportedTurn } from './imported';export {attachmentSchema,commandSchema,diff --git a/console/pnpm-lock.yaml b/console/pnpm-lock.yamlindex 79d52f725..d11f4b494 100644--- a/console/pnpm-lock.yaml+++ b/console/pnpm-lock.yaml@@ -83,8 +83,8 @@ importers:specifier: ^7.4.2version: 7.4.2zod:- specifier: ^4.3.6- version: 4.4.3+ specifier: ^4.6.7+ version: 4.6.7devDependencies:'@base-ui/react':specifier: ^1.3.0@@ -315,8 +315,8 @@ importers:specifier: ^8.21.3version: 8.21.3zod:- specifier: ^4.4.3- version: 4.4.3+ specifier: ^4.6.7+ version: 4.6.7devDependencies:'@sandboxaq/switch-agent-runtime':specifier: workspace:*@@ -344,10 +344,10 @@ importers:dependencies:'@anthropic-ai/claude-agent-sdk':specifier: ^0.3.260- version: 0.3.260(@anthropic-ai/[email protected]([email protected]))(@modelcontextprotocol/[email protected]([email protected]))([email protected])+ version: 0.3.260(@anthropic-ai/[email protected]([email protected]))(@modelcontextprotocol/[email protected]([email protected]))([email protected])'@modelcontextprotocol/sdk':specifier: ^1.30.0- version: 1.30.0([email protected])+ version: 1.30.0([email protected])'@opencode-ai/sdk':specifier: ^1.18.27version: 1.18.27@@ -364,8 +364,8 @@ importers:specifier: ^1.8.0version: 1.8.0zod:- specifier: ^4.4.3- version: 4.4.3+ specifier: ^4.6.7+ version: 4.6.7devDependencies:'@types/node':specifier: ^24.13.3@@ -395,8 +395,8 @@ importers:specifier: ^1.8.0version: 1.8.0zod:- specifier: ^4.4.3- version: 4.4.3+ specifier: ^4.6.7+ version: 4.6.7devDependencies:'@types/node':specifier: ^24.13.3@@ -423,8 +423,8 @@ importers:specifier: ^1.8.0version: 1.8.0zod:- specifier: ^4.4.3- version: 4.4.3+ specifier: ^4.6.7+ version: 4.6.7devDependencies:'@typescript/native-preview':specifier: 7.0.0-dev.20260609.1@@ -445,8 +445,8 @@ importers:packages/shared:dependencies:zod:- specifier: ^4.4.3- version: 4.4.3+ specifier: ^4.6.7+ version: 4.6.7devDependencies:'@types/node':specifier: ^24.13.3@@ -465,7 +465,7 @@ importers:dependencies:'@modelcontextprotocol/sdk':specifier: ^1.0.0- version: 1.30.0([email protected])+ version: 1.30.0([email protected])devDependencies:'@types/node':specifier: ^24.13.3@@ -5812,8 +5812,8 @@ packages:peerDependencies:zod: ^3.25.28 || ^4- resolution: {integrity: sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==}+ resolution: {integrity: sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==}resolution: {integrity: sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==}@@ -5849,11 +5849,11 @@ snapshots:'@anthropic-ai/[email protected]':optional: true- '@anthropic-ai/[email protected](@anthropic-ai/[email protected]([email protected]))(@modelcontextprotocol/[email protected]([email protected]))([email protected])':+ '@anthropic-ai/[email protected](@anthropic-ai/[email protected]([email protected]))(@modelcontextprotocol/[email protected]([email protected]))([email protected])':dependencies:- '@anthropic-ai/sdk': 0.123.0([email protected])- '@modelcontextprotocol/sdk': 1.30.0([email protected])- zod: 4.4.3+ '@anthropic-ai/sdk': 0.123.0([email protected])+ '@modelcontextprotocol/sdk': 1.30.0([email protected])+ zod: 4.6.7optionalDependencies:'@anthropic-ai/claude-agent-sdk-darwin-arm64': 0.3.260'@anthropic-ai/claude-agent-sdk-darwin-x64': 0.3.260@@ -5864,12 +5864,12 @@ snapshots:'@anthropic-ai/claude-agent-sdk-win32-arm64': 0.3.260'@anthropic-ai/claude-agent-sdk-win32-x64': 0.3.260- '@anthropic-ai/[email protected]([email protected])':+ '@anthropic-ai/[email protected]([email protected])':dependencies:json-schema-to-ts: 3.1.1standardwebhooks: 1.1.1optionalDependencies:- zod: 4.4.3+ zod: 4.6.7'@antithesishq/[email protected]': {}@@ -6536,7 +6536,7 @@ snapshots:dependencies:'@chevrotain/types': 11.1.2- '@modelcontextprotocol/[email protected]([email protected])':+ '@modelcontextprotocol/[email protected]([email protected])':dependencies:'@hono/node-server': 2.0.12([email protected])ajv: 8.20.0@@ -6553,8 +6553,8 @@ snapshots:json-schema-typed: 8.0.2pkce-challenge: 5.0.1raw-body: 3.0.2- zod: 4.4.3- zod-to-json-schema: 3.25.2([email protected])+ zod: 4.6.7+ zod-to-json-schema: 3.25.2([email protected])transitivePeerDependencies:- supports-color@@ -11107,10 +11107,10 @@ snapshots:dependencies:- zod: 4.4.3+ zod: 4.6.7- [email protected]: {}+ [email protected]: {}