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
perf(console): bring a host's watchers up in a couple of round trips each (#609)
Louis Amaudruz97ce7118353c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e1299949f..6c9e6bcbf 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1358,6 +1358,15 @@ version of their own to them without also giving them a release of their own.### [Unreleased]#### Changed+- **Updating the sidecars on a host with many agents takes a fraction of the+ SSH round trips.** Each agent's bring-up used to check the host's shared+ bundle for itself — half a dozen commands asking the same question — and+ then stop an old sidecar, write its flags, stage its configuration and+ launch it in as many more. The bundle is now checked, and uploaded if+ needed, once per host, and each agent is brought up in one command after+ its configuration is staged: about two round trips instead of thirteen.+ Agents are still brought up one after another, so their reconnects to+ Switch stay spread out.- **Every agent starts a session when it is addressed; the "Auto-create asession on notify" setting is gone.** Its switch is removed from the agentpage and the create form, and new agents register as `auto_session`.diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/host-bundle.test.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/host-bundle.test.tsnew file mode 100644index 000000000..2ef5ae788--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/host-bundle.test.ts@@ -0,0 +1,134 @@+import { execFile } from 'node:child_process';+import { createHash } from 'node:crypto';+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readdirSync,+ rmSync,+ utimesSync,+ writeFileSync,+} from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { promisify } from 'node:util';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({ exec: vi.fn(), copy: vi.fn(), bundle: '' }));+vi.mock('@main/core/agent-runtime/impl/resolve-sidecar-bundle', () => ({+ resolveSharedHostBundlePath: () => mocks.bundle,+}));+vi.mock('@main/core/ssh/connect/connect-agent-ssh', () => ({+ ensureSshConnected: vi.fn(async () => ({})),+}));+vi.mock('@main/core/execution-context/ssh-execution-context', () => ({+ SshExecutionContext: class {+ exec = mocks.exec;+ },+}));+vi.mock('@main/core/fs/impl/ssh-fs', () => ({+ SshFileSystem: class {+ copyLocalFile = mocks.copy;+ close() {}+ },+}));++const { clearHostBundles, ensureHostBundle, forgetHostBundle, HOST_PREPARE } =+ await import('./host-bundle');++let home: string;+beforeEach(() => {+ home = mkdtempSync(join(tmpdir(), 'host-bundle-'));+ mocks.bundle = join(home, 'local-bundle.mjs');+ writeFileSync(mocks.bundle, 'export {}');+ clearHostBundles();+ vi.clearAllMocks();+});+afterEach(() => rmSync(home, { recursive: true, force: true }));++const transport = { kind: 'ssh', connectionId: 'conn-1', host: 'builder', dir: '/work' } as const;+const hash = () => createHash('sha256').update('export {}').digest('hex');++async function prepare(env: Record<string, string> = {}) {+ const name = `shared-host-${hash()}.mjs`;+ const { stdout } = await promisify(execFile)(+ process.execPath,+ ['-e', HOST_PREPARE, name, hash(), String(60 * 60 * 1000)],+ { env: { ...process.env, HOME: home, ...env } }+ );+ return JSON.parse(stdout.trim()) as { directory: string; staging: string; present: boolean };+}++it('readies a host in one command: finds the bundle, prunes old ones, clears stale staging', async () => {+ const state = join(home, '.local/state/switch');+ const hostDir = join(state, 'sdk-host');+ mkdirSync(hostDir, { recursive: true });+ writeFileSync(join(hostDir, `shared-host-${hash()}.mjs`), 'export {}');+ writeFileSync(join(hostDir, `shared-host-${'b'.repeat(64)}.mjs`), 'old build');+ const stale = join(state, 'sdk-launch/launch-old');+ const fresh = join(state, 'sdk-launch/launch-new');+ const legacy = join(state, 'sdk-watchers/.launch-old');+ for (const dir of [stale, fresh, legacy]) mkdirSync(dir, { recursive: true });+ const old = new Date(Date.now() - 2 * 60 * 60 * 1000);+ utimesSync(stale, old, old);+ utimesSync(legacy, old, old);++ expect(await prepare()).toEqual({+ directory: hostDir,+ staging: join(state, 'sdk-launch'),+ present: true,+ });+ expect(readdirSync(hostDir)).toEqual([`shared-host-${hash()}.mjs`]);+ expect(existsSync(stale)).toBe(false);+ expect(existsSync(legacy)).toBe(false);+ expect(existsSync(fresh)).toBe(true);+});++it('says when this build’s bundle is not on the host, or is not what it should be', async () => {+ expect((await prepare()).present).toBe(false);+ writeFileSync(+ join(home, '.local/state/switch/sdk-host', `shared-host-${hash()}.mjs`),+ 'truncated'+ );+ expect((await prepare()).present).toBe(false);+});++it('checks a host once for all its agents, and uploads only a bundle that is missing', async () => {+ mocks.exec.mockImplementation(async (_command: string, args: string[]) =>+ args[1] === HOST_PREPARE+ ? {+ stdout: JSON.stringify({+ directory: '/h/sdk-host',+ staging: '/h/sdk-launch',+ present: false,+ }),+ }+ : { stdout: '' }+ );++ const all = await Promise.all([1, 2, 3].map(() => ensureHostBundle(transport)));++ expect(all).toEqual(+ Array(3).fill({ entrypoint: `/h/sdk-host/shared-host-${hash()}.mjs`, staging: '/h/sdk-launch' })+ );+ expect(mocks.exec.mock.calls.filter(([, args]) => args[1] === HOST_PREPARE)).toHaveLength(1);+ expect(mocks.copy).toHaveBeenCalledOnce();++ await ensureHostBundle(transport);+ expect(mocks.exec.mock.calls.filter(([, args]) => args[1] === HOST_PREPARE)).toHaveLength(1);++ // A launch that failed makes the next one look again.+ forgetHostBundle('conn-1');+ await ensureHostBundle(transport);+ expect(mocks.exec.mock.calls.filter(([, args]) => args[1] === HOST_PREPARE)).toHaveLength(2);+});++it('does not remember a check that failed', async () => {+ mocks.exec.mockRejectedValueOnce(new Error('SSH exec channel open timed out'));+ await expect(ensureHostBundle(transport)).rejects.toThrow('timed out');+ mocks.exec.mockResolvedValue({+ stdout: JSON.stringify({ directory: '/h/sdk-host', staging: '/h/sdk-launch', present: true }),+ });+ await expect(ensureHostBundle(transport)).resolves.toMatchObject({ staging: '/h/sdk-launch' });+ expect(mocks.copy).not.toHaveBeenCalled();+});diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/host-bundle.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/host-bundle.tsnew file mode 100644index 000000000..e5b5e9d86--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/host-bundle.ts@@ -0,0 +1,155 @@+import { createHash, randomUUID } from 'node:crypto';+import { readFile } from 'node:fs/promises';+import { resolveSharedHostBundlePath } from '@main/core/agent-runtime/impl/resolve-sidecar-bundle';+import { SshExecutionContext } from '@main/core/execution-context/ssh-execution-context';+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 { STALE_LAUNCH_MS } from './state-roots';++/**+ * Readies a host for this build's shared host, and prints what the caller+ * needs as JSON: the bundle's directory, whether this build's bundle is+ * already there, and where launches stage their configuration.+ *+ * Everything a host needs once rather than once per agent, in one command:+ * the directories exist, bundles no running process names are removed (every+ * deployment leaves one named after its own hash, so an upgraded host would+ * otherwise keep one per build it ever ran), and staged configurations older+ * than `STALE_LAUNCH_MS` are removed, since each holds an agent's credentials+ * and a launch whose connection dropped leaves its own behind.+ *+ * Arguments: this build's bundle file name, its SHA-256, and the staleness+ * threshold in milliseconds.+ */+export const HOST_PREPARE = String.raw`+const fs = require('node:fs'), path = require('node:path'), crypto = require('node:crypto');+const [wanted, hash, staleArg] = process.argv.slice(1);+const state = path.join(require('node:os').homedir(), '.local', 'state', 'switch');+const directory = path.join(state, 'sdk-host');+const staging = path.join(state, 'sdk-launch');+fs.mkdirSync(directory, { recursive: true, mode: 0o700 });+fs.mkdirSync(staging, { recursive: true, mode: 0o700 });+let present = false;+try {+ present = crypto.createHash('sha256').update(fs.readFileSync(path.join(directory, wanted))).digest('hex') === hash;+} catch (e) { if (e.code !== 'ENOENT') throw e; }+const running = require('node:child_process').execFileSync('ps', ['-eo', 'args='], { encoding: 'utf8' });+for (const name of fs.readdirSync(directory)) {+ if (name === wanted || running.includes(name)) continue;+ if (/^shared-host-[a-f0-9]{64}\.mjs$/.test(name) || /^shared-host-[a-f0-9]{64}\.[0-9a-f-]+\.tmp$/.test(name))+ fs.rmSync(path.join(directory, name), { force: true });+}+const cutoff = Date.now() - Number(staleArg);+const sweep = (dir, abandoned) => {+ let names;+ try { names = fs.readdirSync(dir); } catch (e) { if (e.code === 'ENOENT') return; throw e; }+ for (const name of names) {+ if (!abandoned(name)) continue;+ const entry = path.join(dir, name);+ let stat;+ try { stat = fs.statSync(entry); } catch (e) { if (e.code === 'ENOENT') continue; throw e; }+ if (stat.mtimeMs < cutoff) fs.rmSync(entry, { recursive: true, force: true });+ }+};+sweep(staging, () => true);+for (const kind of ['sdk-watchers', 'sdk-sessions'])+ sweep(path.join(state, kind), (name) => name.startsWith('.launch-') || name.startsWith('launch-'));+console.log(JSON.stringify({ directory, staging, present }));+`;++export type HostBundle = {+ /** This build's shared host entrypoint on the host. */+ entrypoint: string;+ /** Where a launch stages its configuration on the host. */+ staging: string;+};++/**+ * How long a host is taken to still have this build's bundle once checked.+ * Another Console on the same account, on another build, prunes bundles no+ * running process names, so the answer does not hold for ever.+ */+export const HOST_BUNDLE_TTL_MS = 10 * 60 * 1000;++const prepared = new Map<string, { at: number; hash: string; bundle: Promise<HostBundle> }>();++/** Forget what was learned about a host, so the next launch checks it again. */+export function forgetHostBundle(connectionId: string): void {+ prepared.delete(connectionId);+}++/** Forget every host. For tests. */+export function clearHostBundles(): void {+ prepared.clear();+}++/**+ * This build's shared host bundle on an SSH host, uploaded if it is not there.+ *+ * Once per host, not once per agent: every agent on a host runs the same+ * file, so checking it for each of twenty agents asked the same question+ * twenty times, at half a dozen round trips each. Callers on the same host+ * share one check — the one in flight, or its answer for+ * `HOST_BUNDLE_TTL_MS` — and a launch that fails forgets it+ * (`forgetHostBundle`), since a missing bundle is one reason it might.+ */+export async function ensureHostBundle(+ transport: Extract<LocationTransport, { kind: 'ssh' }>+): Promise<HostBundle> {+ const local = resolveSharedHostBundlePath();+ const hash = createHash('sha256')+ .update(await readFile(local))+ .digest('hex');+ const cached = prepared.get(transport.connectionId);+ if (cached && cached.hash === hash && Date.now() - cached.at < HOST_BUNDLE_TTL_MS)+ return cached.bundle;+ const bundle = prepare(transport, local, hash);+ prepared.set(transport.connectionId, { at: Date.now(), hash, bundle });+ bundle.catch(() => {+ if (prepared.get(transport.connectionId)?.bundle === bundle)+ prepared.delete(transport.connectionId);+ });+ return bundle;+}++async function prepare(+ transport: Extract<LocationTransport, { kind: 'ssh' }>,+ local: string,+ hash: string+): Promise<HostBundle> {+ const proxy = await ensureSshConnected(transport.connectionId, transport.host);+ const ctx = new SshExecutionContext(proxy, { root: transport.dir });+ const name = `shared-host-${hash}.mjs`;+ const { stdout } = await ctx.exec('node', [+ '-e',+ HOST_PREPARE,+ name,+ hash,+ String(STALE_LAUNCH_MS),+ ]);+ const host = JSON.parse(stdout.trim()) as {+ directory: string;+ staging: string;+ present: boolean;+ };+ const entrypoint = `${host.directory}/${name}`;+ if (!host.present) {+ // Uploaded under a temporary name and renamed into place, so a process+ // starting from it never reads half a file.+ const temporary = `shared-host-${hash}.${randomUUID()}.tmp`;+ const fs = new SshFileSystem(proxy, host.directory);+ try {+ await fs.copyLocalFile(local, temporary);+ } finally {+ fs.close();+ }+ await ctx.exec('node', [+ '-e',+ "require('node:fs').renameSync(process.argv[1],process.argv[2])",+ `${host.directory}/${temporary}`,+ entrypoint,+ ]);+ }+ return { entrypoint, staging: host.staging };+}diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/legacy-sidecar.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/legacy-sidecar.tsindex 4ed40d3be..a60de5b6a 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/legacy-sidecar.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/legacy-sidecar.ts@@ -19,11 +19,11 @@ import { log } from '@main/lib/logger';* credentials recorded itself under `default` and names no owner; those are* left for a deliberate sweep rather than guessed at.*/-const STOP_LEGACY_SIDECAR = `+export const STOP_LEGACY_SIDECAR_FN = `+function stopLegacySidecar(repoDir, slug) {const fs = require('node:fs');const path = require('node:path');const cp = require('node:child_process');-const [repoDir, slug] = process.argv.slice(1);const directory = path.join(repoDir, '.switchdash', 'agents', slug);const read = (name) => {try {@@ -72,16 +72,28 @@ if (Number.isSafeInteger(pid) && pid > 0 && alive(pid)) {if (alive(pid)) throw new Error('Superseded sidecar ' + pid + ' would not stop.');stopped.push('sidecar:' + pid);}-console.log(JSON.stringify(stopped));+return stopped;+}+`;++const STOP_LEGACY_SIDECAR = `${STOP_LEGACY_SIDECAR_FN}+const [repoDir, slug] = process.argv.slice(1);+console.log(JSON.stringify(stopLegacySidecar(repoDir, slug)));`;+/** The name an earlier sidecar deployment recorded this agent under. */+export function legacySidecarSlug(credentialsPath: string): string {+ const slug = posix.basename(credentialsPath, '.json');+ if (!slug) throw new Error('Cannot identify the agent whose superseded sidecar should stop.');+ return slug;+}+export async function stopLegacySidecar(ctx: IExecutionContext,repoDir: string,credentialsPath: string): Promise<void> {- const slug = posix.basename(credentialsPath, '.json');- if (!slug) throw new Error('Cannot identify the agent whose superseded sidecar should stop.');+ const slug = legacySidecarSlug(credentialsPath);const { stdout } = await ctx.exec('node', ['-e', STOP_LEGACY_SIDECAR, repoDir, slug]);const stopped: string[] = JSON.parse(stdout.trim() || '[]');if (stopped.length)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 c8d0d1477..26c50b90f 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,4 +1,4 @@-import { createHash, randomUUID } from 'node:crypto';+import { createHash } from 'node:crypto';import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';import { tmpdir } from 'node:os';import { join } from 'node:path';@@ -9,17 +9,9 @@ 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 { MAKE_LAUNCH_DIR, RESOLVE_STATE_ROOT, STALE_LAUNCH_MS } from './state-roots';-/**- * Every deployment leaves a bundle named after its own hash, so without this- * an upgraded host accumulates one file per build it has ever run. A bundle a- * process still names on its command line is kept: it belongs to a host this- * deployment has not replaced yet.- */-const PRUNE_SUPERSEDED_BUNDLES =- "const fs=require('node:fs');const [dir,keep]=process.argv.slice(1);const running=require('node:child_process').execFileSync('ps',['-eo','args='],{encoding:'utf8'});for(const name of fs.readdirSync(dir)){if(name===keep||!/^shared-host-[a-f0-9]{64}\\.mjs$/.test(name)||running.includes(name))continue;fs.rmSync(dir+'/'+name,{force:true})}";-/*** Prints the path of a shared host bundle already on the host: this build's* when it is there, otherwise the newest one an earlier deployment left, and@@ -72,53 +64,13 @@ export async function deploySharedHost(watcher: boolean) {let ctx: IExecutionContext;- const bundle = resolveSharedHostBundlePath();- const hash = createHash('sha256')- .update(await readFile(bundle))- .digest('hex');const key = createHash('sha256').update(identity).digest('hex');- let entrypoint = bundle;+ let entrypoint = resolveSharedHostBundlePath();if (transport.kind === 'ssh') {+ // Checked, and uploaded if missing, once per host rather than per agent.+ entrypoint = (await ensureHostBundle(transport)).entrypoint;const proxy = await ensureSshConnected(transport.connectionId, transport.host);ctx = new SshExecutionContext(proxy, { root: sessionPath });- const { stdout } = await ctx.exec('node', [- '-e',- "console.log(require('node:path').join(require('node:os').homedir(),'.local','state','switch','sdk-host'))",- ]);- const directory = stdout.trim();- await ctx.exec('node', [- '-e',- "require('node:fs').mkdirSync(process.argv[1],{recursive:true,mode:0o700})",- directory,- ]);- const fs = new SshFileSystem(proxy, directory);- entrypoint = `${directory}/shared-host-${hash}.mjs`;- const existing = await ctx.exec('node', [- '-e',- "const fs=require('node:fs');try{console.log(require('node:crypto').createHash('sha256').update(fs.readFileSync(process.argv[1])).digest('hex')===process.argv[2])}catch(e){if(e.code!=='ENOENT')throw e;console.log(false)}",- entrypoint,- hash,- ]);- const temporary = `shared-host-${hash}.${randomUUID()}.tmp`;- try {- if (existing.stdout.trim() !== 'true') {- await fs.copyLocalFile(bundle, temporary);- await ctx.exec('node', [- '-e',- "require('node:fs').renameSync(process.argv[1],process.argv[2])",- `${directory}/${temporary}`,- entrypoint,- ]);- }- } finally {- fs.close();- await ctx.exec('node', [- '-e',- "require('node:fs').rmSync(process.argv[1],{force:true})",- `${directory}/${temporary}`,- ]);- }- await ctx.exec('node', ['-e', PRUNE_SUPERSEDED_BUNDLES, directory, `shared-host-${hash}.mjs`]);} else ctx = new LocalExecutionContext();const { stdout } = await ctx.exec('node', ['-e',diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-watcher.auto-approve.test.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-watcher.auto-approve.test.tsindex e48653d0b..17d1ac99b 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-watcher.auto-approve.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-watcher.auto-approve.test.ts@@ -18,6 +18,7 @@ const mocks = vi.hoisted(() => ({runCommand: vi.fn(),updateAgent: vi.fn(),stopLegacySidecar: vi.fn(),+ bringUp: vi.fn(),}));vi.mock('@main/core/agents/getAgentById', () => ({ getAgentById: mocks.agent }));@@ -63,7 +64,11 @@ vi.mock('./shared-host-deployment', () => ({runSharedHostCommand: mocks.runCommand,}));vi.mock('./legacy-sidecar', () => ({ stopLegacySidecar: mocks.stopLegacySidecar }));-vi.mock('./watcher-inspection', () => ({ waitForWatcherStop: 'process.exit(0)' }));+vi.mock('./watcher-inspection', () => ({}));+vi.mock('./watcher-bring-up', () => ({+ AUTO_APPROVE_CHOICE_FILE: 'auto-approve.json',+ bringUpRemoteWatcher: mocks.bringUp,+}));vi.mock('./adopt-subagent', () => ({ adoptSubagent: vi.fn() }));vi.mock('./local-host', () => ({ startLocalWatcher: vi.fn(), stopLocalWatcher: vi.fn() }));vi.mock('@main/lib/logger', () => ({ log: { info: vi.fn(), warn: vi.fn() } }));@@ -97,11 +102,6 @@ function savedSpec(runtimeMode: string) {);}-/** A person's choice, kept beside the watcher by a sharing-aware Console. */-function chosen(runtimeMode: string) {- writeFileSync(join(root, 'auto-approve.json'), JSON.stringify({ runtimeMode, at: 'then' }));-}-function readChoice(): { runtimeMode: string } {return JSON.parse(readFileSync(join(root, 'auto-approve.json'), 'utf8'));}@@ -110,13 +110,9 @@ function readSpec(): { start: { input: { runtimeMode: string } } } {return JSON.parse(readFileSync(join(root, 'config.json'), 'utf8'));}-function writtenMode(): string {- const [, , config] = mocks.runCommand.mock.calls.at(-1) as [- unknown,- unknown,- { start: { input: { runtimeMode: string } } },- ];- return config.start.input.runtimeMode;+/** Whether the bring-up was asked to take the host's choice into the watcher. */+function adopted(): boolean {+ return (mocks.bringUp.mock.calls.at(-1)![0] as { adoptAutoApprove: boolean }).adoptAutoApprove;}beforeEach(() => {@@ -129,71 +125,50 @@ beforeEach(() => {connectionId: 'connection-1',});mocks.deploy.mockImplementation(async () => ({ ctx, root, entrypoint: 'shared-host.mjs' }));+ mocks.bringUp.mockResolvedValue({ root, runtimeMode: null, legacyStopped: [] });});afterEach(() => {rmSync(root, { recursive: true, force: true });});+// What the host's choice does to the watcher's spec is the bring-up script's,+// tested against real files in watcher-bring-up.test.ts. Here: when this+// Console asks for it, and what it does with the answer.+it('takes auto-approve from the host when another Console changed it', async () => {mocks.agent.mockResolvedValue(agent(false));- savedSpec('full-access');- chosen('full-access');+ mocks.bringUp.mockResolvedValue({ root, runtimeMode: 'full-access', legacyStopped: [] });await configureSharedWatcher('agent-1', { connected: true, spawning: true }, 'explicit');- expect(writtenMode()).toBe('full-access');+ expect(adopted()).toBe(true);expect(mocks.updateAgent).toHaveBeenCalledWith({ agentId: 'agent-1', autoApprove: true });});it('leaves the row alone when it already agrees with the host', async () => {mocks.agent.mockResolvedValue(agent(true));- savedSpec('full-access');- chosen('full-access');-- await configureSharedWatcher('agent-1', { connected: true, spawning: true }, 'explicit');-- expect(writtenMode()).toBe('full-access');- expect(mocks.updateAgent).not.toHaveBeenCalled();-});--it('does not take a saved spec for a choice when nobody made one', async () => {- // An older Console wrote this spec from its own row and kept no choice.- mocks.agent.mockResolvedValue(agent(true));- savedSpec('approval-required');-- await configureSharedWatcher('agent-1', { connected: true, spawning: true }, 'explicit');-- expect(writtenMode()).toBe('full-access');- expect(mocks.updateAgent).not.toHaveBeenCalled();-});--it('writes the first watcher from the row, with no spec on the host yet', async () => {- mocks.agent.mockResolvedValue(agent(true));await configureSharedWatcher('agent-1', { connected: true, spawning: true }, 'explicit');- expect(writtenMode()).toBe('full-access');+ expect(adopted()).toBe(true);expect(mocks.updateAgent).not.toHaveBeenCalled();});it('writes this Console’s value when the person using it has just changed it', async () => {mocks.agent.mockResolvedValue(agent(true));- savedSpec('approval-required');await configureSharedWatcherFor('agent-1', { connected: true, spawning: true }, 'explicit', {name: undefined,autoApprove: 'this-console',});- expect(writtenMode()).toBe('full-access');+ expect(adopted()).toBe(false);expect(mocks.updateAgent).not.toHaveBeenCalled();});it('does not take a subagent watcher’s setting for its parent’s', async () => {mocks.agent.mockResolvedValue(agent(false));- savedSpec('full-access');- chosen('full-access');// A subagent watcher reads its Switch id from the credentials file.const readId = vi.spyOn(ctx, 'exec');readId.mockImplementation(async (command: string, args: string[]) => {@@ -209,11 +184,19 @@ it('does not take a subagent watcher’s setting for its parent’s', async () ='helper');- expect(writtenMode()).toBe('approval-required');+ expect(adopted()).toBe(false);expect(mocks.updateAgent).not.toHaveBeenCalled();readId.mockRestore();});+it('asks nothing of the host’s choice for a watcher being stopped', async () => {+ mocks.agent.mockResolvedValue(agent(true));++ await configureSharedWatcher('agent-1', { connected: false, spawning: false }, 'explicit');++ expect(adopted()).toBe(false);+});+it('keeps a changed setting on the host for a watcher that starts no sessions', async () => {mocks.agent.mockResolvedValue(agent(false));savedSpec('approval-required');diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-watcher.locality.test.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-watcher.locality.test.tsindex 894f521fc..e30aaa747 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-watcher.locality.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-watcher.locality.test.ts@@ -13,6 +13,7 @@ const mocks = vi.hoisted(() => ({ssh: vi.fn(),ready: vi.fn(),server: vi.fn(),+ bringUp: vi.fn(),}));vi.mock('@main/core/managed-switch-server/session-readiness', () => ({@@ -52,9 +53,12 @@ vi.mock('./shared-host-deployment', () => ({runSharedHostCommand: mocks.runCommand,}));vi.mock('./watcher-inspection', () => ({- waitForWatcherStop: 'wait',removeWatcherRoots: 'fs.rmSync(root)',}));+vi.mock('./watcher-bring-up', () => ({+ AUTO_APPROVE_CHOICE_FILE: 'auto-approve.json',+ bringUpRemoteWatcher: mocks.bringUp,+}));vi.mock('./adopt-subagent', () => ({ adoptSubagent: vi.fn() }));vi.mock('./local-host', () => ({startLocalWatcher: mocks.startLocal,@@ -74,6 +78,7 @@ beforeEach(() => {entrypoint: 'shared-host.mjs',});mocks.exec.mockResolvedValue({ stdout: '' });+ mocks.bringUp.mockResolvedValue({ root: '/state/watcher', runtimeMode: null, legacyStopped: [] });mocks.stopped.mockResolvedValue([]);mocks.agentById.mockResolvedValue({id: 'agent-1',@@ -112,7 +117,7 @@ it('stops a local agent through Console rather than a deployed host', async () =expect(mocks.deploy).not.toHaveBeenCalled();});-it('still deploys the shared host for an agent on an SSH host', async () => {+it('brings a watcher on an SSH host up in one command there', async () => {mocks.location.mockResolvedValue({id: 'remote',dir: '/work',@@ -120,14 +125,20 @@ it('still deploys the shared host for an agent on an SSH host', async () => {connectionId: 'connection-1',});await configureSharedWatcher('agent-1', { connected: true, spawning: true }, 'explicit');- expect(mocks.deploy).toHaveBeenCalled();- expect(mocks.runCommand).toHaveBeenCalledWith(- expect.objectContaining({ kind: 'ssh' }),- expect.anything(),- expect.anything(),- '--ensure-watch',- false- );+ expect(mocks.bringUp).toHaveBeenCalledOnce();+ expect(mocks.bringUp.mock.calls[0][0]).toMatchObject({+ transport: expect.objectContaining({ kind: 'ssh' }),+ repoDir: '/work',+ identity: 'switch-agent-1',+ credentialsPath: '/work/.switch/agents/scout.json',+ state: { connected: true, spawning: true },+ config: expect.objectContaining({+ session: expect.objectContaining({ agentId: 'switch-agent-1' }),+ }),+ });+ // Not the per-agent deploy and launch it replaces.+ expect(mocks.deploy).not.toHaveBeenCalled();+ expect(mocks.runCommand).not.toHaveBeenCalled();expect(mocks.startLocal).not.toHaveBeenCalled();});@@ -143,21 +154,20 @@ it.each([async (intent, connected, clear) => {mocks.location.mockResolvedValue({ id: 'remote', dir: '/work', sshHost: 'builder' });await configureSharedWatcher('agent-1', { connected, spawning: connected }, intent);- const write = mocks.exec.mock.calls.find((call) => call[1][1].includes('taken-over.json'));- expect(write?.[1].slice(2)).toEqual([- '/state/watcher',- String(connected),- String(connected),- clear,- ]);+ expect(mocks.bringUp.mock.calls[0][0]).toMatchObject({+ state: { connected, spawning: connected },+ clear: clear === 'true',+ });});it('tells an SSH host to connect without spawning when auto-start is off', async () => {mocks.location.mockResolvedValue({ id: 'remote', dir: '/work', sshHost: 'builder' });await configureSharedWatcher('agent-1', { connected: true, spawning: false }, 'explicit');- const write = mocks.exec.mock.calls.find((call) => call[1][1].includes('taken-over.json'));- expect(write?.[1].slice(2)).toEqual(['/state/watcher', 'true', 'false', 'true']);+ expect(mocks.bringUp.mock.calls[0][0]).toMatchObject({+ state: { connected: true, spawning: false },+ clear: true,+ });});it('passes the spawn decision to a local watcher', async () => {@@ -241,7 +251,7 @@ it('never connects to a server whose update failed', async () => {await expect(configureSharedWatcher('agent-1', { connected: true, spawning: true }, 'restore')).rejects.toThrow('failed');- expect(mocks.deploy).not.toHaveBeenCalled();+ expect(mocks.bringUp).not.toHaveBeenCalled();expect(mocks.startLocal).not.toHaveBeenCalled();});diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-watcher.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-watcher.tsindex 12cfdeff3..d51a88510 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-watcher.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-watcher.ts@@ -1,5 +1,4 @@import { readFile } from 'node:fs/promises';-import type { SharedHostConfig } from '@switch-console/agent-providers';import { getAgentLocation } from '@main/core/agents/agent-location';import { getAgentById } from '@main/core/agents/getAgentById';import { updateAgent } from '@main/core/agents/updateAgent';@@ -14,7 +13,6 @@ import { controllerConnectionId } from '@main/core/switch-rooms/session-connectiimport { getServer } from '@main/core/switch-servers/servers-store';import { log } from '@main/lib/logger';import { adoptSubagent } from './adopt-subagent';-import { stopLegacySidecar } from './legacy-sidecar';import {removeLocalWatcherRoots,startLocalWatcher,@@ -22,12 +20,9 @@ import {type WatcherIntent,} from './local-host';import { buildSharedHostConfig } from './shared-agent-runtime';-import {- deploySharedHost,- resolveWatcherRoot,- runSharedHostCommand,-} from './shared-host-deployment';-import { removeWatcherRoots, waitForWatcherStop } from './watcher-inspection';+import { deploySharedHost, resolveWatcherRoot } from './shared-host-deployment';+import { AUTO_APPROVE_CHOICE_FILE, bringUpRemoteWatcher } from './watcher-bring-up';+import { removeWatcherRoots } from './watcher-inspection';const READ_SWITCH_AGENT_ID ="console.log(JSON.parse(require('node:fs').readFileSync(process.argv[1],'utf8')).env.SWITCH_AGENT_ID)";@@ -60,11 +55,6 @@ export type AutoApproveSource = 'host' | 'this-console';type ConsoleRuntimeMode = 'full-access' | 'approval-required';-const AUTO_APPROVE_CHOICE_FILE = 'auto-approve.json';--/** Prints the auto-approve choice kept beside a watcher, or nothing. */-const READ_AUTO_APPROVE_CHOICE = `const fs=require('node:fs');try{const c=JSON.parse(fs.readFileSync(require('node:path').join(process.argv[1],'${AUTO_APPROVE_CHOICE_FILE}'),'utf8'));console.log(c?.runtimeMode??'')}catch(e){if(e.code!=='ENOENT')throw e}`;-/*** Atomically keeps an auto-approve choice beside a watcher and, with a third* argument `spec`, in its saved spec too. A missing root is a no-op: the first@@ -76,37 +66,6 @@ function runtimeModeFor(autoApprove: boolean): ConsoleRuntimeMode {return autoApprove ? 'full-access' : 'approval-required';}-type HostContext = Awaited<ReturnType<typeof deploySharedHost>>['ctx'];--async function readAutoApproveChoice(- ctx: HostContext,- root: string-): Promise<ConsoleRuntimeMode | null> {- const { stdout } = await ctx.exec('node', ['-e', READ_AUTO_APPROVE_CHOICE, root]);- const mode = stdout.trim();- return mode === 'full-access' || mode === 'approval-required' ? mode : null;-}--/**- * Take the choice on the host for a watcher about to be written, and bring- * this Console's row in line so its toggle shows what the agent runs with.- */-async function adoptHostAutoApprove(- agentId: string,- ctx: HostContext,- root: string,- config: SharedHostConfig-): Promise<void> {- const chosen = await readAutoApproveChoice(ctx, root);- if (chosen === null || chosen === config.start.input.runtimeMode) return;- log.info('shared-watcher: taking auto-approve from the host, where another Console set it', {- agentId,- runtimeMode: chosen,- });- config.start.input.runtimeMode = chosen;- await updateAgent({ agentId, autoApprove: chosen === 'full-access' });-}-async function writeAutoApproveChoice(agentId: string,autoApprove: boolean,@@ -272,33 +231,32 @@ export async function configureSharedWatcherFor(else await stopLocalWatcher(config.session.agentId);return;}- const { ctx, root, entrypoint } = await deploySharedHost(- transport,- location.dir,- config.session.agentId,- true- );- await stopLegacySidecar(ctx, location.dir, config.execution!.credentialsPath);- // `clear` removes the stood-down marker on the same hop that writes the- // enable flag: an explicit start, or any stop. A restore leaves it, so a- // watcher that was displaced stays displaced across a Console restart.- await ctx.exec('node', [- '-e',- "const fs=require('node:fs');const path=require('node:path');const [root,enabled,spawn,clear]=process.argv.slice(1);fs.mkdirSync(root,{recursive:true,mode:0o700});if(clear==='true')try{fs.unlinkSync(path.join(root,'taken-over.json'))}catch(e){if(e.code!=='ENOENT')throw e}const dest=path.join(root,'watch.json');const tmp=dest+'.'+require('node:crypto').randomUUID();const fd=fs.openSync(tmp,'wx',0o600);try{fs.writeFileSync(fd,JSON.stringify({enabled:enabled==='true',spawn:spawn==='true'}));fs.fsyncSync(fd)}finally{fs.closeSync(fd)}fs.renameSync(tmp,dest)",- root,- String(state.connected),- String(state.spawning),- String(!state.connected || intent === 'explicit'),- ]);- if (!state.connected) {- await ctx.exec('node', ['-e', waitForWatcherStop, root]);- return;- }// A subagent's watcher runs with its parent's setting, which the parent's// own watcher has already taken from the host.const ownWatcher = !name || name === agent.name;- if (ownWatcher && autoApprove === 'host') {- await adoptHostAutoApprove(agentId, ctx, root, config);+ // `clear` removes the stood-down marker on the same hop that writes the+ // enable flag: an explicit start, or any stop. A restore leaves it, so a+ // watcher that was displaced stays displaced across a Console restart.+ const brought = await bringUpRemoteWatcher({+ transport,+ repoDir: location.dir,+ identity: config.session.agentId,+ credentialsPath: config.execution!.credentialsPath,+ state,+ clear: !state.connected || intent === 'explicit',+ adoptAutoApprove: state.connected && ownWatcher && autoApprove === 'host',+ config,+ });+ if (brought.legacyStopped.length)+ log.warn('Stopped a superseded sidecar deployment for this agent', {+ agentId,+ stopped: brought.legacyStopped,+ });+ if (brought.runtimeMode !== null) {+ log.info('shared-watcher: taking auto-approve from the host, where another Console set it', {+ agentId,+ runtimeMode: brought.runtimeMode,+ });+ await updateAgent({ agentId, autoApprove: brought.runtimeMode === 'full-access' });}- await runSharedHostCommand(transport, { ctx, root, entrypoint }, config, '--ensure-watch', false);}diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/watcher-bring-up.test.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/watcher-bring-up.test.tsnew file mode 100644index 000000000..dcd3aed8e--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/watcher-bring-up.test.ts@@ -0,0 +1,161 @@+import { execFile } from 'node:child_process';+import { createHash } from 'node:crypto';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { promisify } from 'node:util';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import type { BringUpOptions } from './watcher-bring-up';++// Only the script is run here; the transport around it is never reached.+vi.mock('@main/core/ssh/connect/connect-agent-ssh', () => ({ ensureSshConnected: vi.fn() }));+vi.mock('@main/core/execution-context/ssh-execution-context', () => ({+ SshExecutionContext: vi.fn(),+}));+vi.mock('@main/core/fs/impl/ssh-fs', () => ({ SshFileSystem: vi.fn() }));+vi.mock('./host-bundle', () => ({ ensureHostBundle: vi.fn(), forgetHostBundle: vi.fn() }));++const { BRING_UP_SCRIPT } = await import('./watcher-bring-up');++/**+ * The bring-up script run for real, with `node`, against a home directory+ * standing in for the agent's host, and a stand-in launcher that records what+ * it was started with and what configuration it read.+ */++let home: string;+let root: string;+let staging: string;+let launcher: string;+let launches: string;++beforeEach(() => {+ home = mkdtempSync(join(tmpdir(), 'bring-up-'));+ const watchers = join(home, '.local/state/switch/sdk-watchers');+ root = join(watchers, createHash('sha256').update('switch-agent-1').digest('hex'));+ staging = join(home, '.local/state/switch/sdk-launch/launch-1');+ launches = join(home, 'launches.jsonl');+ launcher = join(home, 'launcher.cjs');+ writeFileSync(+ launcher,+ `const fs = require('node:fs');+const [root, config, mode, resuming] = process.argv.slice(2);+if (process.env.FAIL_LAUNCH) { console.error('provider not signed in'); process.exit(3); }+fs.appendFileSync(${JSON.stringify(launches)}, JSON.stringify({ root, mode, resuming,+ config: JSON.parse(fs.readFileSync(config, 'utf8')) }) + '\\n');+console.log('{"created":false}');`+ );+});++afterEach(() => {+ rmSync(home, { recursive: true, force: true });+});++function stage(runtimeMode: string) {+ mkdirSync(staging, { recursive: true });+ writeFileSync(+ join(staging, 'config.json'),+ JSON.stringify({ session: { agentId: 'switch-agent-1' }, start: { input: { runtimeMode } } })+ );+}++function options(overrides: Partial<BringUpOptions> = {}): BringUpOptions {+ return {+ identity: 'switch-agent-1',+ repoDir: join(home, 'work'),+ slug: 'scout',+ enabled: true,+ spawn: true,+ clear: false,+ adoptAutoApprove: true,+ entrypoint: launcher,+ staging,+ ...overrides,+ };+}++async function bringUp(overrides: Partial<BringUpOptions> = {}, env: Record<string, string> = {}) {+ const { stdout } = await promisify(execFile)(+ process.execPath,+ ['-e', BRING_UP_SCRIPT, JSON.stringify(options(overrides))],+ { env: { ...process.env, HOME: home, ...env } }+ );+ return JSON.parse(stdout.trim()) as { root: string; runtimeMode: string | null };+}++function launched(): { root: string; mode: string; resuming: string; config: any }[] {+ return existsSync(launches)+ ? readFileSync(launches, 'utf8')+ .trim()+ .split('\n')+ .map((line) => JSON.parse(line))+ : [];+}++const watchFlags = () => JSON.parse(readFileSync(join(root, 'watch.json'), 'utf8'));++it('writes the flags and launches the watcher from its staged configuration, in one go', async () => {+ stage('approval-required');++ const result = await bringUp();++ expect(result).toEqual({ root, runtimeMode: null, legacyStopped: [] });+ expect(watchFlags()).toEqual({ enabled: true, spawn: true });+ expect(launched()).toEqual([+ {+ root,+ mode: '--ensure-watch',+ resuming: 'false',+ config: expect.objectContaining({ session: { agentId: 'switch-agent-1' } }),+ },+ ]);+ // It holds the agent's credentials, so it does not outlive the launch.+ expect(existsSync(staging)).toBe(false);+});++it('takes auto-approve from the host when another Console chose differently', async () => {+ stage('approval-required');+ mkdirSync(root, { recursive: true });+ writeFileSync(join(root, 'auto-approve.json'), JSON.stringify({ runtimeMode: 'full-access' }));++ const result = await bringUp();++ expect(result.runtimeMode).toBe('full-access');+ expect(launched()[0]!.config.start.input.runtimeMode).toBe('full-access');+});++it('keeps this Console’s value when nobody chose on the host, or when told to', async () => {+ stage('full-access');+ expect((await bringUp()).runtimeMode).toBeNull();+ expect(launched()[0]!.config.start.input.runtimeMode).toBe('full-access');++ stage('full-access');+ writeFileSync(+ join(root, 'auto-approve.json'),+ JSON.stringify({ runtimeMode: 'approval-required' })+ );+ expect((await bringUp({ adoptAutoApprove: false })).runtimeMode).toBeNull();+ expect(launched()[1]!.config.start.input.runtimeMode).toBe('full-access');+});++it('stops a watcher without launching anything, clearing a takeover only when asked', async () => {+ mkdirSync(root, { recursive: true });+ writeFileSync(join(root, 'taken-over.json'), JSON.stringify({ reason: 'another client' }));++ await bringUp({ enabled: false, spawn: false, staging: null, clear: false });+ expect(watchFlags()).toEqual({ enabled: false, spawn: false });+ expect(existsSync(join(root, 'taken-over.json'))).toBe(true);++ await bringUp({ enabled: false, spawn: false, staging: null, clear: true });+ expect(existsSync(join(root, 'taken-over.json'))).toBe(false);+ expect(launched()).toEqual([]);+});++it('says why the launcher failed, and removes the staged configuration anyway', async () => {+ stage('full-access');++ await expect(bringUp({}, { FAIL_LAUNCH: '1' })).rejects.toThrow(+ /launcher failed \(exit 3\): provider not signed in/+ );+ expect(existsSync(staging)).toBe(false);+});diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/watcher-bring-up.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/watcher-bring-up.tsnew file mode 100644index 000000000..528ef777e--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/watcher-bring-up.ts@@ -0,0 +1,166 @@+import { randomUUID } from 'node:crypto';+import { mkdtemp, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { z } from 'zod';+import { SshExecutionContext } from '@main/core/execution-context/ssh-execution-context';+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, forgetHostBundle } from './host-bundle';+import { legacySidecarSlug, STOP_LEGACY_SIDECAR_FN } from './legacy-sidecar';+import { WATCHER_ROOT } from './state-roots';+import { WAIT_FOR_WATCHER_STOP_FN } from './watcher-inspection';++/** Where the auto-approve choice a Console made is kept, beside the watcher. */+export const AUTO_APPROVE_CHOICE_FILE = 'auto-approve.json';++/**+ * Brings one agent's watcher on its host to the state asked for, in one+ * command. Takes one argument, the JSON of `BringUpOptions`, and prints the+ * JSON of `BringUpResult`.+ *+ * In order: find the watcher's state root; stop a sidecar an earlier Console+ * deployed for the agent, if one is still there; write the watch flags,+ * clearing a takeover marker when asked; then either wait for a watcher that+ * is being stopped to go, or launch it from the configuration staged for it —+ * taking the auto-approve choice kept on the host first, when asked, since+ * another Console on the account may have set it. The staged configuration is+ * removed whatever happens, since it holds the agent's credentials.+ *+ * These used to be eight separate SSH commands, each its own round trip and+ * its own chance to be cut off halfway. They are all small operations in one+ * directory tree on one machine, so they are one.+ */+export const BRING_UP_SCRIPT = String.raw`${WATCHER_ROOT}${STOP_LEGACY_SIDECAR_FN}${WAIT_FOR_WATCHER_STOP_FN}+const fs = require('node:fs'), path = require('node:path'), crypto = require('node:crypto');+const cp = require('node:child_process');+const o = JSON.parse(process.argv[1]);+const put = (file, data) => {+ const tmp = file + '.' + crypto.randomUUID();+ const fd = fs.openSync(tmp, 'wx', 0o600);+ try { fs.writeFileSync(fd, JSON.stringify(data)); fs.fsyncSync(fd); } finally { fs.closeSync(fd); }+ fs.renameSync(tmp, file);+};+const out = { root: null, runtimeMode: null, legacyStopped: [] };+try {+ const base = path.join(require('node:os').homedir(), '.local', 'state', 'switch', 'sdk-watchers');+ const root = watcherRoot(base, o.identity);+ out.root = root;+ out.legacyStopped = stopLegacySidecar(o.repoDir, o.slug);+ fs.mkdirSync(root, { recursive: true, mode: 0o700 });+ if (o.clear)+ try { fs.unlinkSync(path.join(root, 'taken-over.json')); } catch (e) { if (e.code !== 'ENOENT') throw e; }+ put(path.join(root, 'watch.json'), { enabled: o.enabled, spawn: o.spawn });+ if (!o.enabled) waitForWatcherStop(root);+ else {+ const configPath = path.join(o.staging, 'config.json');+ fs.chmodSync(configPath, 0o600);+ if (o.adoptAutoApprove) {+ let chosen = null;+ try {+ chosen = JSON.parse(fs.readFileSync(path.join(root, '${AUTO_APPROVE_CHOICE_FILE}'), 'utf8'))?.runtimeMode ?? null;+ } catch (e) { if (e.code !== 'ENOENT') throw e; }+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));+ if ((chosen === 'full-access' || chosen === 'approval-required') && chosen !== config.start.input.runtimeMode) {+ config.start.input.runtimeMode = chosen;+ put(configPath, config);+ out.runtimeMode = chosen;+ }+ }+ const launched = cp.spawnSync(+ process.execPath,+ [o.entrypoint, root, configPath, '--ensure-watch', 'false'],+ { encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 }+ );+ if (launched.error) throw launched.error;+ if (launched.status !== 0)+ throw new Error('The shared host launcher failed (exit ' + launched.status + '): ' ++ String(launched.stderr || launched.stdout || '').trim().slice(-2000));+ }+} finally {+ if (o.staging) fs.rmSync(o.staging, { recursive: true, force: true });+}+console.log(JSON.stringify(out));+`;++export type BringUpOptions = {+ /** The Switch agent id the watcher runs as. */+ identity: string;+ /** The agent's working directory, and its name there, for an earlier sidecar. */+ repoDir: string;+ slug: string;+ enabled: boolean;+ spawn: boolean;+ /** Remove a takeover marker: an explicit start, or any stop. */+ clear: boolean;+ /** Take the auto-approve choice kept on the host into the staged configuration. */+ adoptAutoApprove: boolean;+ entrypoint: string;+ /** The directory the configuration is staged in, or null when stopping. */+ staging: string | null;+};++const resultSchema = z.object({+ root: z.string(),+ runtimeMode: z.enum(['full-access', 'approval-required']).nullable(),+ legacyStopped: z.array(z.string()),+});++export type BringUpResult = z.infer<typeof resultSchema>;++/**+ * Bring an agent's watcher on an SSH host to `state`, in two round trips at+ * most: the configuration staged over SFTP (only when connecting), then+ * `BRING_UP_SCRIPT`. The host's bundle is checked once per host, not here+ * (`ensureHostBundle`); a bring-up that fails forgets that check, since a+ * bundle that has gone is one reason it might.+ */+export async function bringUpRemoteWatcher(input: {+ transport: Extract<LocationTransport, { kind: 'ssh' }>;+ repoDir: string;+ identity: string;+ credentialsPath: string;+ state: { connected: boolean; spawning: boolean };+ clear: boolean;+ adoptAutoApprove: boolean;+ config: unknown;+}): Promise<BringUpResult> {+ const { transport } = input;+ try {+ const bundle = await ensureHostBundle(transport);+ const proxy = await ensureSshConnected(transport.connectionId, transport.host);+ let staging: string | null = null;+ if (input.state.connected) {+ const name = `launch-${randomUUID()}`;+ const local = await mkdtemp(join(tmpdir(), 'switch-sdk-launch-'));+ const fs = new SshFileSystem(proxy, bundle.staging);+ try {+ await writeFile(join(local, 'config.json'), JSON.stringify(input.config), { mode: 0o600 });+ await fs.mkdir(name);+ await fs.copyLocalFile(join(local, 'config.json'), `${name}/config.json`);+ } finally {+ fs.close();+ await rm(local, { recursive: true, force: true });+ }+ staging = `${bundle.staging}/${name}`;+ }+ const options: BringUpOptions = {+ identity: input.identity,+ repoDir: input.repoDir,+ slug: legacySidecarSlug(input.credentialsPath),+ enabled: input.state.connected,+ spawn: input.state.spawning,+ clear: input.clear,+ adoptAutoApprove: input.adoptAutoApprove,+ entrypoint: bundle.entrypoint,+ staging,+ };+ const ctx = new SshExecutionContext(proxy, { root: input.repoDir });+ const { stdout } = await ctx.exec('node', ['-e', BRING_UP_SCRIPT, JSON.stringify(options)]);+ return resultSchema.parse(JSON.parse(stdout.trim()));+ } catch (error) {+ forgetHostBundle(transport.connectionId);+ throw error;+ }+}diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/watcher-inspection.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/watcher-inspection.tsindex 9eb64de46..43609bea9 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/watcher-inspection.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/watcher-inspection.ts@@ -50,4 +50,34 @@ console.log(JSON.stringify(process.argv[2]==='logs'?logs.join('\n\n'):result));*/export const removeWatcherRoots = String.raw`${IS_STATE_ROOT}const fs=require('node:fs'),path=require('node:path');const identity=process.argv[1];const base=path.join(require('node:os').homedir(),'.local','state','switch','sdk-watchers');const roots=new Set([path.join(base,require('node:crypto').createHash('sha256').update(identity).digest('hex'))]);if(fs.existsSync(base))for(const name of fs.readdirSync(base).filter(isStateRoot)){try{if(JSON.parse(fs.readFileSync(path.join(base,name,'config.json'),'utf8')).session.agentId===identity)roots.add(path.join(base,name))}catch(e){if(e.code!=='ENOENT')throw e}}for(const root of roots)fs.rmSync(root,{recursive:true,force:true})`;-export const waitForWatcherStop = String.raw`const fs=require('node:fs'),path=require('node:path');const files=['shared-owner.lock','supervisor/owner.json'];const alive=file=>{try{const pid=JSON.parse(fs.readFileSync(path.join(process.argv[1],file),'utf8')).pid;if(!Number.isSafeInteger(pid)||pid<=0)throw new Error('Invalid watcher PID');process.kill(pid,0);return true}catch(e){if(['ENOENT','ESRCH'].includes(e.code))return false;throw e}};(async()=>{for(let i=0;i<100;i++){if(!files.some(alive))return;await new Promise(r=>setTimeout(r,200))}throw new Error('The shared watcher has not stopped; retry after checking its log.')})().catch(e=>{console.error(e.message);process.exitCode=1})`;+/**+ * `waitForWatcherStop(root)` for scripts run with `node -e`: returns once+ * neither the watcher nor its supervisor at `root` is alive, and throws if+ * they are still up after 20 s.+ */+export const WAIT_FOR_WATCHER_STOP_FN = String.raw`+function waitForWatcherStop(root) {+ const fs = require('node:fs'), path = require('node:path');+ const files = ['shared-owner.lock', 'supervisor/owner.json'];+ const alive = (file) => {+ try {+ const pid = JSON.parse(fs.readFileSync(path.join(root, file), 'utf8')).pid;+ if (!Number.isSafeInteger(pid) || pid <= 0) throw new Error('Invalid watcher PID');+ process.kill(pid, 0);+ return true;+ } catch (e) {+ if (['ENOENT', 'ESRCH'].includes(e.code)) return false;+ throw e;+ }+ };+ for (let i = 0; i < 100; i++) {+ if (!files.some(alive)) return;+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 200);+ }+ throw new Error('The shared watcher has not stopped; retry after checking its log.');+}+`;++export const waitForWatcherStop = String.raw`${WAIT_FOR_WATCHER_STOP_FN}+try { waitForWatcherStop(process.argv[1]); } catch (e) { console.error(e.message); process.exitCode = 1; }+`;