diff --git a/packages/remote/src/remote-connection-state.ts b/packages/remote/src/remote-connection-state.ts index f172848e39..f5d842372f 100644 --- a/packages/remote/src/remote-connection-state.ts +++ b/packages/remote/src/remote-connection-state.ts @@ -274,6 +274,18 @@ export function readRemoteConnectionState(options: { stateDir: string; session: string; }): RemoteConnectionState | null { + const observed = observeRemoteConnectionState(options); + return observed.kind === 'valid' ? observed.state : null; +} + +export function observeRemoteConnectionState(options: { + stateDir: string; + session: string; +}): + | { kind: 'absent' } + | { kind: 'invalid' } + | { kind: 'unknown' } + | { kind: 'valid'; state: RemoteConnectionState } { const recordsDir = remoteConnectionRecordsDir(options.stateDir); const canonical = canonicalRemoteConnectionStatePath(recordsDir, options.session); // The older path is read first. A move links the session's own path before it retires the older @@ -295,11 +307,12 @@ export function readRemoteConnectionState(options: { } return observedRemoteConnectionState(options.session, canonical, file.record); } + if (legacyPath !== canonical && legacy.kind === 'unknown') return { kind: 'unknown' }; return legacy.kind === 'owned' && legacy.session === options.session && isMovableLegacyRecord(recordsDir, legacyPath, legacy) ? observedRemoteConnectionState(options.session, legacyPath, legacy.record) - : null; + : { kind: 'absent' }; } /** @@ -372,10 +385,12 @@ function observedRemoteConnectionState( session: string, recordPath: string, record: Record, -): RemoteConnectionState | null { - if (isRemoteConnectionState(record)) return normalizeStoredProvider(record); +): { kind: 'invalid' } | { kind: 'valid'; state: RemoteConnectionState } { + if (isRemoteConnectionState(record)) { + return { kind: 'valid', state: normalizeStoredProvider(record) }; + } warnInvalidRecord(session, recordPath); - return null; + return { kind: 'invalid' }; } function normalizeStoredProvider(record: RemoteConnectionState): RemoteConnectionState { diff --git a/src/__tests__/cli-cloud-limrun-attachment.test.ts b/src/__tests__/cli-cloud-limrun-attachment.test.ts index 38913aaf87..155ae8a2c1 100644 --- a/src/__tests__/cli-cloud-limrun-attachment.test.ts +++ b/src/__tests__/cli-cloud-limrun-attachment.test.ts @@ -302,3 +302,70 @@ test('disconnect preserves recovery when a startup owns the lock before publishi expect((await runCliCapture(['disconnect', '--json'], { env })).code).toBeNull(); expect(mock.mock.calls.filter(([, init]) => init.method === 'DELETE')).toHaveLength(1); }); + +async function bookLimrunWithDaemon() { + const env = limrunEnv('current'); + const location = locationOf(env); + const broker = stubCloudApi(); + broker.mockResolvedValueOnce(Response.json(limrunLease('ios'), { status: 201 })); + expect((await runCliCapture(args('ios'), { env })).code).toBeNull(); + writeHostedDaemonRegistration(location); + return { env, location }; +} + +function writeStaleV1Login(env: ReturnType): void { + const authDir = path.join(env.AGENT_DEVICE_STATE_DIR, 'auth'); + fs.mkdirSync(authDir, { recursive: true, mode: 0o700 }); + fs.writeFileSync( + path.join(authDir, 'cli-session.json'), + JSON.stringify({ + version: 1, + id: 'stale-login', + cloudBaseUrl: env.AGENT_DEVICE_CLOUD_BASE_URL, + refreshCredential: 'stale-refresh-credential', + createdAt: new Date().toISOString(), + }), + { mode: 0o600 }, + ); +} + +test.each(['stale-v1-login', 'unbound'] as const)( + 'local-only sweep of an expired Limrun booking (%s) removes its attachment without stopping its daemon', + async (mode) => { + const { env, location } = await bookLimrunWithDaemon(); + const record = readCloudConnection(location)!; + const { accountBinding: _unbound, ...unbound } = record; + writeCloudConnection(location, { + ...(mode === 'unbound' ? unbound : record), + deadlineAt: new Date(0).toISOString(), + }); + if (mode === 'stale-v1-login') writeStaleV1Login(env); + + await runCliCapture(['connection', 'status', '--session', location.session, '--json'], { + env: mode === 'stale-v1-login' ? { ...env, AGENT_DEVICE_CLOUD_API_KEY: undefined } : env, + }); + + expect(stop).not.toHaveBeenCalled(); + expect(fs.existsSync(cloudAttachmentPath(location))).toBe(false); + }, +); + +test('forget with a stale v1 login clears a paired Limrun booking locally without stopping its daemon', async () => { + const { env, location } = await bookLimrunWithDaemon(); + const daemonDir = hostedPluginDaemonDir(location, readCloudConnection(location)!); + writeStaleV1Login(env); + + const forgotten = await runCliCapture( + ['disconnect', '--forget', '--session', location.session, '--json'], + { env: { ...env, AGENT_DEVICE_CLOUD_API_KEY: undefined } }, + ); + + expect(forgotten.code, forgotten.stdout).toBeNull(); + expect(JSON.parse(forgotten.stdout).data).toMatchObject({ forgotten: true, released: false }); + expect(stop).not.toHaveBeenCalled(); + expect(forgotten.stderr).toContain('local daemon may still be running'); + expect(forgotten.stderr).toContain(daemonDir); + expect(readCloudConnection(location)).toBeNull(); + expect(readRemoteConnectionState(location)).toBeNull(); + expect(fs.existsSync(cloudAttachmentPath(location))).toBe(false); +}); diff --git a/src/__tests__/cli-cloud-record-recovery.test.ts b/src/__tests__/cli-cloud-record-recovery.test.ts index d494643602..a3a22b13a0 100644 --- a/src/__tests__/cli-cloud-record-recovery.test.ts +++ b/src/__tests__/cli-cloud-record-recovery.test.ts @@ -4,6 +4,7 @@ import path from 'node:path'; import { afterEach, expect, test, vi } from 'vitest'; import { writeCliSession } from '../cli/auth-session.ts'; import { + cloudAttachmentPath, cloudConnectionDir, prepareCloudConnection, readCloudConnection, @@ -17,9 +18,11 @@ import { hostedDevice, locationOf, postKey, + proxyFrontDevice, stubCloudApi, timeOutAllocation, timeOutNextCreate, + withLeaseAllocation, } from './cli-cloud-session.fixtures.ts'; afterEach(() => { @@ -286,3 +289,241 @@ test('an inconclusive refusal to end an observed allocation keeps its lease ID', expect((await runCliCapture(['disconnect', '--json'], { env })).code).toBeNull(); expect(fetchMock.mock.calls.at(-1)?.[0].pathname).toBe(`/v1/sessions/${hostedDevice.id}`); }); + +async function bookExpiredUnboundUnfinishedProxyFront(phase: 'pending' | 'closing') { + const env = cloudEnv(); + const location = locationOf(env); + const front = withLeaseAllocation(); + const broker = stubCloudApi(proxyFrontDevice); + const connected = await runCliCapture(connectArgs, { env, sendToDaemon: front }); + expect(connected.code).toBeNull(); + const opened = await runCliCapture( + ['open', 'com.apple.Preferences', '--session', location.session, '--json'], + { env, sendToDaemon: front }, + ); + expect(opened.code).toBeNull(); + const { accountBinding: _unbound, ...record } = readCloudConnection(location)!; + writeCloudConnection(location, { + ...record, + phase, + hostedLeaseId: 'proposed-lease-id', + deadlineAt: new Date(Date.now() - 1000).toISOString(), + }); + broker.mockClear(); + return { env, location, front, broker }; +} + +test.each([ + { phase: 'pending' as const, force: false }, + { phase: 'pending' as const, force: true }, + { phase: 'closing' as const, force: false }, + { phase: 'closing' as const, force: true }, +])( + 'connect (force=$force) on an expired unbound $phase proxy-front booking refuses another account before any lease teardown', + async ({ phase, force }) => { + const { env, location, front, broker } = await bookExpiredUnboundUnfinishedProxyFront(phase); + broker.mockResolvedValueOnce(Response.json({ error: 'not_found' }, { status: 404 })); + + const args = force ? [...connectArgs, '--force'] : connectArgs; + const refused = await runCliCapture(args, { + env: { ...env, AGENT_DEVICE_CLOUD_API_KEY: 'other-account-api-key' }, + sendToDaemon: front, + }); + + expect(refused.code).toBe(1); + expect(JSON.parse(refused.stdout).error.details.reason).toBe( + 'cloud_connection_allocation_unconfirmed', + ); + expect(refused.calls).toEqual([]); + expect(broker.mock.calls.map(([, init]) => init.method)).toEqual(['GET']); + expect(fs.existsSync(cloudAttachmentPath(location))).toBe(true); + expect(readCloudConnection(location)?.phase).toBe(phase); + expect(readCloudConnection(location)?.accountBinding).toBeUndefined(); + }, +); + +test('connect on an expired unbound unfinished proxy-front booking releases its lease once the owner proves allocation and refuses unpaired state', async () => { + const unpaired = await bookExpiredUnboundUnfinishedProxyFront('pending'); + writeCloudConnection(unpaired.location, { + ...readCloudConnection(unpaired.location)!, + generation: 'different-generation', + }); + const blocked = await runCliCapture(connectArgs, { + env: unpaired.env, + sendToDaemon: unpaired.front, + }); + expect(blocked.code).toBe(1); + expect(JSON.parse(blocked.stdout).error.details.reason).toBe('cloud_connection_changed'); + expect(blocked.calls).toEqual([]); + expect(unpaired.broker).not.toHaveBeenCalled(); + + const owned = await bookExpiredUnboundUnfinishedProxyFront('pending'); + owned.broker.mockResolvedValueOnce(Response.json({ id: proxyFrontDevice.id, state: 'settled' })); + const replaced = await runCliCapture(connectArgs, { + env: owned.env, + sendToDaemon: owned.front, + }); + expect(replaced.code, replaced.stdout).toBeNull(); + expect(replaced.calls.map(({ command }) => command)).toContain('lease_release'); + expect(owned.broker.mock.calls.map(([, init]) => init.method)).not.toContain('DELETE'); +}); + +test.each<{ + label: string; + force: boolean; + overrides?: { phase: 'closing'; rollback: true }; +}>([ + { label: 'pending', force: false }, + { label: 'pending', force: true }, + { label: 'closing rollback', force: false, overrides: { phase: 'closing', rollback: true } }, + { label: 'closing rollback', force: true, overrides: { phase: 'closing', rollback: true } }, +])( + 'connect (force=$force) clears an ID-less legacy $label reservation on canonical not_found and continues', + async ({ force, overrides }) => { + const env = cloudEnv(); + const location = locationOf(env); + const reservation = writeLegacyPending(env); + if (overrides) writeCloudConnection(location, { ...reservation, ...overrides }); + const broker = stubCloudApi(); + broker.mockResolvedValueOnce(Response.json({ error: 'not_found' }, { status: 404 })); + + const result = await runCliCapture(force ? [...connectArgs, '--force'] : connectArgs, { env }); + expect(result.code, result.stdout).toBeNull(); + expect(broker.mock.calls.map(([, init]) => init.method)).toEqual(['GET', 'POST']); + const committed = readCloudConnection(location); + expect(committed?.phase).toBe('committed'); + expect(committed?.generation).not.toBe(reservation.generation); + }, +); + +test.each<{ + label: string; + setup?: (location: ReturnType) => void; + response?: () => Response; +}>([ + { label: '500 lookup error', response: () => new Response(null, { status: 500 }) }, + { + label: 'non-canonical 404', + response: () => Response.json({ error: 'other' }, { status: 404 }), + }, + { + label: 'closing record without rollback', + setup: (location) => + writeCloudConnection(location, { ...readCloudConnection(location)!, phase: 'closing' }), + }, + { + label: 'record with allocation ID', + setup: (location) => + writeCloudConnection(location, { ...readCloudConnection(location)!, id: hostedDevice.id }), + }, + { + label: 'record with hostedLeaseId', + setup: (location) => + writeCloudConnection(location, { + ...readCloudConnection(location)!, + hostedLeaseId: 'proposed-lease-id', + }), + }, + { + label: 'reservation with attachment file', + setup: (location) => fs.writeFileSync(cloudAttachmentPath(location), '{}', { mode: 0o600 }), + }, + { + label: 'broker allocation ID mismatch', + setup: (location) => + writeCloudConnection(location, { ...readCloudConnection(location)!, id: hostedDevice.id }), + response: () => Response.json({ id: '00000000-0000-4000-8000-000000000099', state: 'running' }), + }, +])( + 'connect keeps refusing an unbound pending reservation on $label', + async ({ setup, response }) => { + const env = cloudEnv(); + const location = locationOf(env); + const reservation = writeLegacyPending(env); + setup?.(location); + const broker = stubCloudApi(); + broker.mockResolvedValueOnce( + response ? response() : Response.json({ error: 'not_found' }, { status: 404 }), + ); + + const refused = await runCliCapture(connectArgs, { env }); + expect(refused.code).toBe(1); + expect(JSON.parse(refused.stdout).error.details.reason).toBe( + 'cloud_connection_allocation_unconfirmed', + ); + expect(broker.mock.calls.map(([, init]) => init.method)).toEqual(['GET']); + expect(readCloudConnection(location)?.generation).toBe(reservation.generation); + }, +); + +test('connect ends an active broker allocation found for an ID-less legacy pending reservation', async () => { + const env = cloudEnv(); + const location = locationOf(env); + const reservation = writeLegacyPending(env); + const broker = stubCloudApi(); + broker.mockResolvedValueOnce(Response.json({ id: hostedDevice.id, state: 'running' })); + broker.mockResolvedValueOnce(new Response(null, { status: 204 })); + + const result = await runCliCapture(connectArgs, { env }); + expect(result.code, result.stdout).toBeNull(); + expect(broker.mock.calls.map(([, init]) => init.method)).toEqual(['GET', 'DELETE', 'POST']); + expect(readCloudConnection(location)?.generation).not.toBe(reservation.generation); +}); + +test.each([ + { session: 'cloud-qa', force: false }, + { session: 'cloud-qa', force: true }, + { session: 'Cloud-QA', force: false }, +])( + 'connect (session=$session, force=$force) refuses an ID-less pending reservation beside a legacy-transport saved connection', + async ({ session, force }) => { + const env = { ...cloudEnv(), AGENT_DEVICE_SESSION: session }; + const location = locationOf(env); + const reservation = writeLegacyPending(env); + const recordsDir = path.join(location.stateDir, 'remote-connections'); + fs.mkdirSync(recordsDir, { recursive: true, mode: 0o700 }); + const legacyStatePath = path.join(recordsDir, `${session}.json`); + fs.writeFileSync( + legacyStatePath, + JSON.stringify({ + version: 1, + session, + remoteConfigPath: path.join( + location.stateDir, + 'remote-connections', + 'generated', + 'legacy.json', + ), + remoteConfigHash: 'hash', + tenant: 'tenant', + runId: 'run-1', + leaseId: 'legacy-lease-id', + cloudSession: { + id: '00000000-0000-4000-8000-000000000077', + baseUrl: env.AGENT_DEVICE_CLOUD_BASE_URL, + vendor: 'limrun', + transport: 'limrun', + deadlineAt: new Date(Date.now() + 60_000).toISOString(), + generation: 'other-generation', + }, + connectedAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + }), + { mode: 0o600 }, + ); + const broker = stubCloudApi(); + broker.mockResolvedValueOnce(Response.json({ error: 'not_found' }, { status: 404 })); + + const args = force + ? [...connectArgs, '--session', session, '--force'] + : [...connectArgs, '--session', session]; + const refused = await runCliCapture(args, { env }); + expect(refused.code).toBe(1); + expect(JSON.parse(refused.stdout).error.details.reason).toBe( + 'cloud_connection_allocation_unconfirmed', + ); + expect(broker.mock.calls.map(([, init]) => init.method)).toEqual(['GET']); + expect(readCloudConnection(location)?.generation).toBe(reservation.generation); + expect(fs.existsSync(legacyStatePath)).toBe(true); + }, +); diff --git a/src/__tests__/cli-cloud-session-identity.test.ts b/src/__tests__/cli-cloud-session-identity.test.ts index 8242922c8c..519a7366f4 100644 --- a/src/__tests__/cli-cloud-session-identity.test.ts +++ b/src/__tests__/cli-cloud-session-identity.test.ts @@ -666,3 +666,264 @@ test("a direct profile that redirects to another state directory checks identity expect(result.calls).toEqual([]); expect(readCloudConnection(location)?.id).toBe(hostedDevice.id); }); + +function writeRawLogin(stateDir: string, content: string): string { + const authDir = path.join(stateDir, 'auth'); + fs.mkdirSync(authDir, { recursive: true, mode: 0o700 }); + const file = path.join(authDir, 'cli-session.json'); + fs.writeFileSync(file, content, { mode: 0o600 }); + return file; +} + +function writeStaleV1Login(env: Env): string { + return writeRawLogin( + env.AGENT_DEVICE_STATE_DIR, + JSON.stringify({ + version: 1, + id: 'stale-login', + cloudBaseUrl: env.AGENT_DEVICE_CLOUD_BASE_URL, + refreshCredential: 'stale-refresh-credential', + createdAt: new Date().toISOString(), + }), + ); +} + +function expireUnbound( + location: { stateDir: string; session: string }, + extra: Partial>> = {}, +): void { + const { accountBinding: _unbound, ...record } = readCloudConnection(location)!; + writeCloudConnection(location, { + ...record, + ...extra, + deadlineAt: new Date(Date.now() - 1000).toISOString(), + }); +} + +async function assertLocalSweepWithLogin( + session: string, + kind: 'stale-v1' | 'malformed' | 'unreadable', + baseUrl?: string, +): Promise { + const { env, front, location } = await bookProxyFront(session); + expire(location); + const sessionFile = + kind === 'stale-v1' + ? writeStaleV1Login(env) + : writeRawLogin(env.AGENT_DEVICE_STATE_DIR, kind === 'malformed' ? '{' : '{"version":2}'); + if (kind === 'unreadable') fs.chmodSync(sessionFile, 0o000); + try { + const result = await runCliCapture(['connection', 'status', '--session', session, '--json'], { + env: { + ...env, + AGENT_DEVICE_CLOUD_API_KEY: undefined, + ...(baseUrl ? { AGENT_DEVICE_CLOUD_BASE_URL: baseUrl } : {}), + }, + sendToDaemon: front, + }); + expect(JSON.parse(result.stdout).error.details.reason).toBe( + 'cloud_connection_credential_mismatch', + ); + expect(result.calls).toEqual([]); + expect(fs.existsSync(cloudAttachmentPath(location))).toBe(false); + } finally { + if (kind === 'unreadable') fs.chmodSync(sessionFile, 0o600); + } +} + +test.each([ + ...sessions.flatMap((session) => + (['stale-v1', 'malformed'] as const).map((kind) => [session, kind, undefined] as const), + ), + ['cloud-qa', 'stale-v1', 'https://other-cloud.example'] as const, + ['cloud-qa', 'malformed', 'https://other-cloud.example'] as const, +])( + 'an unverifiable (%s / %s / baseUrl=%s) login sweeps expired proxy-front files locally without saved credentials', + async (session, kind, baseUrl) => { + await assertLocalSweepWithLogin(session, kind, baseUrl); + }, +); + +test.skipIf(process.platform === 'win32').each([undefined, 'https://other-cloud.example'])( + 'an unreadable saved login (baseUrl=%s) sweeps expired proxy-front files locally without saved credentials', + async (baseUrl) => { + await assertLocalSweepWithLogin('cloud-qa', 'unreadable', baseUrl); + }, +); + +test('forget with a stale v1 login clears a bound booking locally without saved credentials and refuses with no identity source', async () => { + const { env, front, location } = await bookProxyFront('cloud-qa'); + writeStaleV1Login(env); + + const forgotten = await runCliCapture( + ['disconnect', '--forget', '--session', 'cloud-qa', '--json'], + { env: { ...env, AGENT_DEVICE_CLOUD_API_KEY: undefined }, sendToDaemon: front }, + ); + expect(forgotten.code, forgotten.stdout).toBeNull(); + expect(JSON.parse(forgotten.stdout).data).toMatchObject({ forgotten: true }); + expect(forgotten.calls).toEqual([]); + expect(readCloudConnection(location)).toBeNull(); + + const second = await book('cloud-qa', 'api-key'); + removeRemoteConnectionState(second.location); + writeStaleV1Login(second.env); + fs.writeFileSync(path.join(cloudConnectionDir(second.location), 'record.json'), '{'); + const refused = await runCliCapture( + ['disconnect', '--forget', '--session', 'cloud-qa', '--json'], + { env: { ...second.env, AGENT_DEVICE_CLOUD_API_KEY: undefined } }, + ); + expect(JSON.parse(refused.stdout).error.details.reason).toBe( + 'cloud_connection_credential_mismatch', + ); +}); + +test.each(sessions)( + 'the sweep clears an expired pending or unbound proxy-front booking of session %s without sending saved credentials', + async (session) => { + const pending = await bookProxyFront(session); + removeRemoteConnectionState(pending.location); + expireUnbound(pending.location, { phase: 'pending' }); + const pendingSweep = await runCliCapture(['connection', 'status', '--json'], { + env: pending.env, + sendToDaemon: pending.front, + }); + expect(pendingSweep.calls).toEqual([]); + expect(fs.existsSync(cloudAttachmentPath(pending.location))).toBe(false); + + const { env, front, location } = await bookProxyFront(session); + expireUnbound(location); + const foreignOrigin: Env = { + ...env, + AGENT_DEVICE_CLOUD_BASE_URL: 'https://other-cloud.example', + AGENT_DEVICE_CLOUD_API_KEY_ORIGIN: 'https://other-cloud.example', + }; + const refused = await runCliCapture(['connection', 'status', '--json'], { + env: foreignOrigin, + sendToDaemon: front, + }); + expect(refused.calls).toEqual([]); + expect(fs.existsSync(cloudAttachmentPath(location))).toBe(true); + + const swept = await runCliCapture(['connection', 'status', '--json'], { + env, + sendToDaemon: front, + }); + expect(swept.calls).toEqual([]); + expect(fs.existsSync(cloudAttachmentPath(location))).toBe(false); + }, +); + +test('a verified v2 login with another AGENT_DEVICE_CLOUD_BASE_URL still does not sweep an expired booking', async () => { + const { env, front, location } = await bookProxyFront('cloud-qa'); + expire(location); + storeLogin(env, 'owner-login'); + + await runCliCapture(['connection', 'status', '--session', 'cloud-qa', '--json'], { + env: { + ...env, + AGENT_DEVICE_CLOUD_API_KEY: undefined, + AGENT_DEVICE_CLOUD_BASE_URL: 'https://other-cloud.example', + }, + sendToDaemon: front, + }); + expect(fs.existsSync(cloudAttachmentPath(location))).toBe(true); +}); + +test.each(sessions)( + 'plain disconnect on an expired unbound proxy-front booking of session %s keeps the sidecar so broker-verified teardown releases its lease', + async (session) => { + const { env, front, fetchMock, location } = await bookProxyFront(session); + expireUnbound(location); + fetchMock.mockResolvedValueOnce(Response.json({ id: proxyFrontDevice.id, state: 'settled' })); + + const disconnected = await runCliCapture(['disconnect', '--session', session, '--json'], { + env, + sendToDaemon: front, + }); + expect(disconnected.code, disconnected.stdout).toBeNull(); + expect(disconnected.calls.map(({ command }) => command)).toEqual(['lease_release']); + expect(fs.existsSync(cloudAttachmentPath(location))).toBe(false); + expect(readCloudConnection(location)).toBeNull(); + }, +); + +test('connect cloud --force and unfinished disconnect keep an expired unbound proxy-front sidecar while other sessions sweep locally', async () => { + const forceCase = await bookProxyFront('cloud-qa'); + expireUnbound(forceCase.location); + forceCase.fetchMock.mockResolvedValueOnce( + Response.json({ id: proxyFrontDevice.id, state: 'settled' }), + ); + const replaced = await runCliCapture([...connectArgs, '--session', 'cloud-qa', '--force'], { + env: forceCase.env, + sendToDaemon: forceCase.front, + }); + expect(replaced.code, replaced.stdout).toBeNull(); + expect(replaced.calls.map(({ command }) => command)).toContain('lease_release'); + + const pendingCase = await bookProxyFront('cloud-qa'); + expireUnbound(pendingCase.location, { phase: 'pending' }); + pendingCase.fetchMock.mockResolvedValueOnce( + Response.json({ id: proxyFrontDevice.id, state: 'settled' }), + ); + const refused = await runCliCapture(['disconnect', '--session', 'cloud-qa', '--json'], { + env: pendingCase.env, + sendToDaemon: async (req) => + req.command === 'lease_release' + ? { ok: false, error: { code: 'COMMAND_FAILED', message: 'release denied' } } + : { ok: true, data: {} }, + }); + expect(refused.code).toBe(1); + expect(JSON.parse(refused.stdout).error.details.reason).toBe('cloud_connect_rollback_failed'); + expect(fs.existsSync(cloudAttachmentPath(pendingCase.location))).toBe(true); + + const otherCase = await bookProxyFront('cloud-qa'); + expireUnbound(otherCase.location); + const disconnected = await runCliCapture(['disconnect', '--session', 'other-session', '--json'], { + env: otherCase.env, + sendToDaemon: otherCase.front, + }); + expect(disconnected.code, disconnected.stdout).toBeNull(); + expect(disconnected.calls).toEqual([]); + expect(fs.existsSync(cloudAttachmentPath(otherCase.location))).toBe(false); +}); + +test('forget recovers an orphan attachment with no identity source when cli-session.json is malformed or unreadable', async () => { + for (const unreadable of process.platform === 'win32' ? [false] : [false, true]) { + const { env, location } = await book('cloud-qa', 'api-key'); + removeRemoteConnectionState(location); + const recordFile = path.join(cloudConnectionDir(location), 'record.json'); + fs.writeFileSync(recordFile, '{'); + const sessionFile = writeRawLogin( + env.AGENT_DEVICE_STATE_DIR, + unreadable ? '{"version":2}' : '{', + ); + if (unreadable) fs.chmodSync(sessionFile, 0o000); + try { + const forgotten = await runCliCapture( + ['disconnect', '--forget', '--session', 'cloud-qa', '--json'], + { env: { ...env, AGENT_DEVICE_CLOUD_API_KEY: undefined } }, + ); + expect(forgotten.code, forgotten.stdout).toBeNull(); + expect(JSON.parse(forgotten.stdout).data).toMatchObject({ forgotten: true }); + expect(fs.existsSync(recordFile)).toBe(false); + expect(fs.existsSync(cloudAttachmentPath(location))).toBe(false); + } finally { + if (unreadable) fs.chmodSync(sessionFile, 0o600); + } + } +}); + +test('plain disconnect with a malformed cli-session.json keeps reporting cloud_api_key_required', async () => { + const { env, fetchMock, location } = await book('cloud-qa', 'api-key'); + expire(location); + writeRawLogin(env.AGENT_DEVICE_STATE_DIR, '{'); + + const refused = await runCliCapture(['disconnect', '--session', 'cloud-qa', '--json'], { + env: { ...env, AGENT_DEVICE_CLOUD_API_KEY: undefined }, + }); + expect(refused.code).toBe(1); + expect(JSON.parse(refused.stdout).error.details.reason).toBe('cloud_api_key_required'); + expect(brokerCalls(fetchMock)).toEqual([]); + expect(readCloudConnection(location)?.id).toBe(hostedDevice.id); + expect(fs.existsSync(cloudAttachmentPath(location))).toBe(true); +}); diff --git a/src/cli.ts b/src/cli.ts index 0744b6f880..2edcf364e0 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -454,7 +454,7 @@ async function resolveRunContextOrExit( forget: effectiveFlags.forget, stateDir: daemonPaths.baseDir, host: base.host, - session: effectiveFlags.session ?? flags.session, + session: defaults?.claimed?.session ?? effectiveFlags.session ?? flags.session, binding: cloudSession, remoteConfig: effectiveFlags.remoteConfig, remoteRoute: [ diff --git a/src/cli/commands/connection-hosted.ts b/src/cli/commands/connection-hosted.ts index f923d8c2bd..249acd8e9d 100644 --- a/src/cli/commands/connection-hosted.ts +++ b/src/cli/commands/connection-hosted.ts @@ -48,13 +48,13 @@ import { cloudSessionEnded, readCloudConnection, refuseContendedConnection, + removeCloudConnection, withConnectionLock, writeCloudConnection, type CloudConnectionRecord, type ConnectionLocation, } from '../connection/cloud-connection-record.ts'; import { - assertUncommittedGenerationAccess, sendReceiptWithin, cleanupFailureCodes, closeHostedGeneration, @@ -63,6 +63,7 @@ import { openHostedGeneration, releaseCloudConnection, releaseUncommittedLease, + verifyUncommittedGenerationCleanup, type CloudConnectionRelease, type HostedGenerationClose, type OpenedHostedGeneration, @@ -390,9 +391,18 @@ async function cleanUncommittedGeneration( ): Promise { const record = readCloudConnectionQuietly(location); if (!record || record.phase === 'committed') return; - assertUncommittedGenerationAccess(record, access); - const closed = await timings.measure('cleanup', () => closeWithin(params, location, access)); - if (closed.kind !== 'released') throw leftoverCleanupFailure(closed.cause); + const outcome = await timings.measure('cleanup', async () => { + const plan = await verifyUncommittedGenerationCleanup(location, record, access, params.host); + if (plan.kind === 'clear-reservation') return plan; + return await closeWithin(params, location, access, plan.proven); + }); + if (outcome.kind === 'clear-reservation') { + if (readCloudConnectionQuietly(location)?.generation === record.generation) { + removeCloudConnection(location); + } + return; + } + if (outcome.kind !== 'released') throw leftoverCleanupFailure(outcome.cause); forgetUncommittedGeneration(location, record); } @@ -424,6 +434,7 @@ async function closeWithin( params: ConnectionCommandParams, location: ConnectionLocation, access: HostedCloudAccess, + proven?: { id: string; active: boolean }, ): Promise { const abandoned = new AbortController(); const close = () => @@ -432,6 +443,7 @@ async function closeWithin( access, () => releaseLease(params, location, abandoned.signal), abandoned.signal, + proven, ); const outcome = await settleWithin(close, CLEANUP_TIMEOUT_MS).catch((error: unknown) => ({ kind: 'failed' as const, diff --git a/src/cli/connection/active-connection.ts b/src/cli/connection/active-connection.ts index 7b01dc09b5..422dbe13a3 100644 --- a/src/cli/connection/active-connection.ts +++ b/src/cli/connection/active-connection.ts @@ -8,6 +8,7 @@ import type { HostEnvironment } from '@agent-device/kernel/source-value'; import { type CloudConnectionRecord, type ConnectionLocation, + type ExpiredBookingAdmission, type ProxyFrontAttachment, CLOUD_CONNECTION_REASONS, cleanExpiredCloudAttachments, @@ -42,8 +43,15 @@ export async function resolveCloudAdmission(options: { }) { const { command, usesSessions, stateDir, session, binding } = options; if (!usesSessions || command === 'auth' || (command === 'disconnect' && options.forget)) return; + const teardownSession = + command === 'disconnect' || command === 'connect' ? (session ?? 'default') : undefined; const sweep = () => - sweepAdmittedExpiredBookings(stateDir, options.host, options.releaseProxyFrontLease); + sweepAdmittedExpiredBookings( + stateDir, + options.host, + options.releaseProxyFrontLease, + teardownSession, + ); if (command === 'connect' || command === 'connection' || command === 'disconnect') { await sweep(); return; @@ -82,10 +90,11 @@ async function sweepAdmittedExpiredBookings( stateDir: string, host: HostEnvironment, release: ReleaseProxyFrontLease | undefined, + teardownSession?: string, ): Promise { await cleanExpiredCloudAttachments( stateDir, - (record) => admitsExpiredBooking(stateDir, host.env, record), + (record) => admitsExpiredBooking(stateDir, host.env, record, teardownSession), async (location, generation) => { const { stopHostedPluginDaemon } = await import('./cloud-plugin-attachment.ts'); await stopHostedPluginDaemon(location, generation, host); @@ -112,12 +121,14 @@ function admitsExpiredBooking( stateDir: string, env: HostEnvironment['env'], record: CloudConnectionRecord, -): boolean { + teardownSession?: string, +): ExpiredBookingAdmission | null { try { - admitHostedCaller({ stateDir, env, booking: record }, 'use'); - return true; + const admission = admitHostedCaller({ stateDir, env, booking: record }, 'clear'); + if (record.session === teardownSession && !admission.mayUseSavedCredentials) return null; + return admission; } catch { - return false; + return null; } } diff --git a/src/cli/connection/cloud-access.ts b/src/cli/connection/cloud-access.ts index 4d8e4855ef..c4bbe5f50c 100644 --- a/src/cli/connection/cloud-access.ts +++ b/src/cli/connection/cloud-access.ts @@ -1,4 +1,5 @@ import { createHash } from 'node:crypto'; +import { lstatIfPresent } from '@agent-device/host-kit/file'; import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import type { EnvMap } from '@agent-device/kernel/source-value'; import { @@ -7,6 +8,7 @@ import { loginWithDeviceAuth, readStoredCliSession, resolveCliSessionAccess, + resolveCliSessionPath, } from '../auth-session.ts'; import type { CloudSessionBinding } from '@agent-device/remote/remote-connection-state'; import { containsCloudCredential } from '../cloud-response.ts'; @@ -133,8 +135,12 @@ export function admitHostedCaller( if (purpose === 'use' || presentsCloudCredential(stateDir, env)) throw credentialMismatch(); return { mayUseSavedCredentials: false }; } - const caller = readCloudCaller(stateDir, env, booking.origin); - if (caller) assertCloudConnectionCaller(booking, caller); + const hasApiKey = Boolean(env.AGENT_DEVICE_CLOUD_API_KEY?.trim()); + const login = hasApiKey ? null : readStoredLogin(stateDir); + if (login === 'unverified' && purpose === 'clear') return { mayUseSavedCredentials: false }; + if (hasApiKey || login) { + assertCloudConnectionCaller(booking, readCallerIdentity(env, booking.origin, login)); + } const verifiable = booking.accountBinding !== undefined; if (purpose === 'use' && !verifiable) throw credentialMismatch(); return { mayUseSavedCredentials: verifiable }; @@ -156,6 +162,16 @@ export function admitPairedHostedCaller( admitHostedCaller({ stateDir: location.stateDir, env, booking: record }, 'use'); } +function readStoredLogin(stateDir: string): ReturnType { + const stored = readStoredCliSession(stateDir); + if (stored !== null) return stored; + try { + return lstatIfPresent(resolveCliSessionPath(stateDir)) ? 'unverified' : null; + } catch { + return 'unverified'; + } +} + function presentsCloudCredential(stateDir: string, env: EnvMap): boolean { return Boolean(env.AGENT_DEVICE_CLOUD_API_KEY?.trim() || readStoredCliSession(stateDir)); } diff --git a/src/cli/connection/cloud-connect.ts b/src/cli/connection/cloud-connect.ts index 147170b0db..dae63a829e 100644 --- a/src/cli/connection/cloud-connect.ts +++ b/src/cli/connection/cloud-connect.ts @@ -1,6 +1,7 @@ import type { HostEnvironment } from '@agent-device/kernel/source-value'; import type { AgentDeviceClient } from '@agent-device/command-surface'; import { + observeRemoteConnectionState, readRemoteConnectionState, removeRemoteConnectionState, writeRemoteConnectionState, @@ -9,6 +10,7 @@ import { } from '@agent-device/remote/remote-connection-state'; import { AppError, errorMessage } from '@agent-device/kernel/errors'; import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; +import { lstatIfPresent } from '@agent-device/host-kit/file'; import { settleWithin } from '@agent-device/host-kit/settle-within'; import { createCloudSession, @@ -24,6 +26,7 @@ import type { ReceiptTiming } from './connect-timings.ts'; import { ReadyTarget, type ConnectBudget } from './hosted-readiness.ts'; import { assertCloudRecordSession, + cloudAttachmentPath, samePairedBooking, cloudConnectionUnavailable, CLOUD_CONNECTION_DROP_CREDENTIAL_HINT, @@ -41,7 +44,11 @@ import { type CloudConnectionRecord, type ConnectionLocation, } from './cloud-connection-record.ts'; -import { hostedPluginDaemonDir, stopHostedPluginDaemon } from './cloud-plugin-attachment.ts'; +import { + hasHostedPluginDaemonRegistration, + hostedPluginDaemonDir, + stopHostedPluginDaemon, +} from './cloud-plugin-attachment.ts'; import { isLegacyCloudProfile } from './active-connection.ts'; import { releaseProxyFrontConnectionLease } from '../commands/connection-lease-transaction.ts'; import { @@ -172,9 +179,13 @@ export async function closeHostedGeneration( access: HostedCloudAccess, releaseLease: () => Promise, abandoned: AbortSignal, + proven?: { id: string; active: boolean }, ): Promise { const record = readCloudConnectionQuietly(location); if (!record || record.phase === 'committed') return { kind: 'released' }; + if (record.accountBinding === undefined && !record.brokerReleased && !proven) { + throw cloudConnectionUnavailable(CLOUD_CONNECTION_REASONS.allocationUnconfirmed.reason); + } if (record.phase === 'pending') { // The fence goes up before any cleanup step: no command uses the candidate state after this. writeGeneration(location, 'pending', 'close', { ...record, phase: 'closing', rollback: true }); @@ -184,7 +195,7 @@ export async function closeHostedGeneration( // A confirmed end is saved at once, so a later absence of that booking counts as released. record.brokerReleased ? Promise.resolve() - : endBrokerSession(access, record).then(() => { + : endBrokerSession(access, record, proven).then(() => { // The caller has left the lock: a late confirmation is logged below, never saved. if (abandoned.aborted) return; const current = readCloudConnectionQuietly(location); @@ -240,7 +251,7 @@ const UNBOUND_RELEASED_HINT = `The hosted session has ended, but its record name * lookup proves the owner, so only a record that names its account lets that account release the * lease; an unbound one is left to `disconnect --forget`. */ -export function assertUncommittedGenerationAccess( +function assertUncommittedGenerationAccess( record: CloudConnectionRecord, access: HostedCloudAccess, ): void { @@ -253,6 +264,70 @@ export function assertUncommittedGenerationAccess( assertCloudConnectionCaller(record, access); } +function hasAttachmentEntry(location: ConnectionLocation): boolean { + try { + return lstatIfPresent(cloudAttachmentPath(location)) !== undefined; + } catch { + return true; + } +} + +function isEmptyPendingReservation( + location: ConnectionLocation, + record: CloudConnectionRecord, + stateAbsent: boolean, + host: HostEnvironment, +): boolean { + const uncommitted = + record.phase === 'pending' || (record.phase === 'closing' && record.rollback === true); + return ( + uncommitted && + !record.brokerReleased && + record.id === undefined && + record.hostedLeaseId === undefined && + record.deadlineAt === undefined && + record.assignment === undefined && + record.attachmentRefresh === undefined && + record.target === undefined && + record.receipt === undefined && + stateAbsent && + !hasAttachmentEntry(location) && + !hasHostedPluginDaemonRegistration(location, record.generation, host) + ); +} + +/** Verifies pairing and broker ownership before unfinished teardown; clears empty reservations on `not_found`. */ +export async function verifyUncommittedGenerationCleanup( + location: ConnectionLocation, + record: CloudConnectionRecord, + access: HostedCloudAccess, + host: HostEnvironment, +): Promise< + { kind: 'close'; proven?: { id: string; active: boolean } } | { kind: 'clear-reservation' } +> { + assertUncommittedGenerationAccess(record, access); + const observedState = observeRemoteConnectionState(location); + const state = observedState.kind === 'valid' ? observedState.state : null; + cloudBindingForTeardown(location, state, record); + if (record.accountBinding !== undefined || record.brokerReleased) return { kind: 'close' }; + const found = await lookupCloudSession(access, record.generation).catch(() => { + throw cloudConnectionUnavailable(CLOUD_CONNECTION_REASONS.allocationUnconfirmed.reason); + }); + if ( + !found && + isEmptyPendingReservation(location, record, observedState.kind === 'absent', host) + ) { + return { kind: 'clear-reservation' }; + } + if (!found || (record.id !== undefined && record.id !== found.id)) { + throw cloudConnectionUnavailable(CLOUD_CONNECTION_REASONS.allocationUnconfirmed.reason); + } + record.accountBinding = hostedCloudAccountBinding(access); + record.id = found.id; + writeCloudConnection(location, record); + return { kind: 'close', proven: found }; +} + /** * Removes what an uncommitted generation left locally. The caller holds the connection lock; a * newer generation's files are never touched. @@ -271,8 +346,10 @@ export function forgetUncommittedGeneration( async function endBrokerSession( access: HostedCloudAccess, record: CloudConnectionRecord, + proven?: { id: string; active: boolean }, ): Promise { - const id = record.id ?? (await lookupCloudSession(access, record.generation))?.id; + if (proven && !proven.active) return; + const id = proven?.id ?? record.id ?? (await lookupCloudSession(access, record.generation))?.id; if (id) await deleteCloudSession(access, id); } @@ -701,7 +778,7 @@ export async function forgetCloudConnection(options: { : null; if (!hasFiles && !hostedState) return null; const [daemonStateDir] = await Promise.all([ - stopHostedDaemonForForget(location, binding, host), + stopHostedDaemonForForget(location, binding, record, host, usesSavedCredentials), binding?.transport === 'agent-device-daemon' && usesSavedCredentials ? settleWithin( () => releaseProxyFrontTeardownLease(client, location, hostedState), @@ -721,8 +798,21 @@ export async function forgetCloudConnection(options: { async function stopHostedDaemonForForget( location: ConnectionLocation, binding: CloudSessionBinding | undefined, + record: CloudConnectionRecord | null, host: HostEnvironment, + usesSavedCredentials: boolean, ): Promise { + if (!usesSavedCredentials) { + const candidate = + binding && binding.transport !== 'agent-device-daemon' + ? binding + : record + ? { generation: record.generation } + : undefined; + return candidate && hasHostedPluginDaemonRegistration(location, candidate.generation, host) + ? hostedPluginDaemonDir(location, candidate) + : undefined; + } if (!binding || binding.transport === 'agent-device-daemon') return undefined; const stopped = await settleWithin( () => stopHostedPluginDaemon(location, binding.generation, host), diff --git a/src/cli/connection/cloud-connection-record.test.ts b/src/cli/connection/cloud-connection-record.test.ts index 9db897e74e..2d34f44c44 100644 --- a/src/cli/connection/cloud-connection-record.test.ts +++ b/src/cli/connection/cloud-connection-record.test.ts @@ -111,7 +111,7 @@ test('an expired proxy front is released with its attachment before the attachme const released: unknown[] = []; await cleanExpiredCloudAttachments( location.stateDir, - () => true, + () => ({ mayUseSavedCredentials: true }), async () => { throw new Error('a limrun daemon is not retired for a proxy front'); }, @@ -124,12 +124,68 @@ test('an expired proxy front is released with its attachment before the attachme expect(fs.existsSync(cloudAttachmentPath(location))).toBe(false); }); +test.each(['proxy-front', 'plugin'] as const)( + 'an expired %s attachment is removed without provider callbacks when saved credentials are not admitted', + async (kind) => { + const location = expiredProxyFrontLocation(); + if (kind === 'plugin') { + fs.rmSync(cloudAttachmentPath(location)); + writeCloudAttachment( + location, + { + kind: 'plugin', + plugin: '@agent-device/limrun', + token: 'scoped-plugin-token', + expiresAt: new Date(Date.now() - 1000).toISOString(), + data: { kind: 'limrun-instance' }, + }, + 'generation-1', + ); + } + const callbacks: unknown[] = []; + await cleanExpiredCloudAttachments( + location.stateDir, + () => ({ mayUseSavedCredentials: false }), + async (_location, generation) => { + callbacks.push(generation); + }, + async (_location, attachment) => { + callbacks.push(attachment); + }, + ); + expect(callbacks).toEqual([]); + expect(fs.existsSync(cloudAttachmentPath(location))).toBe(false); + }, +); + +test('the sweep leaves an expired attachment untouched when an invalid legacy saved connection exists for the session', async () => { + const location = expiredProxyFrontLocation(); + const recordsDir = path.join(location.stateDir, 'remote-connections'); + fs.mkdirSync(recordsDir, { recursive: true, mode: 0o700 }); + fs.writeFileSync( + path.join(recordsDir, `${location.session}.json`), + JSON.stringify({ + version: 1, + session: location.session, + cloudSession: { transport: 'limrun', generation: 'other-generation' }, + }), + { mode: 0o600 }, + ); + await cleanExpiredCloudAttachments( + location.stateDir, + () => ({ mayUseSavedCredentials: false }), + async () => undefined, + async () => undefined, + ); + expect(fs.existsSync(cloudAttachmentPath(location))).toBe(true); +}); + test('an expired proxy-front attachment is removed even when its release fails', async () => { const location = expiredProxyFrontLocation(); const attempts: unknown[] = []; await cleanExpiredCloudAttachments( location.stateDir, - () => true, + () => ({ mayUseSavedCredentials: true }), async () => undefined, async (_location, attachment) => { attempts.push(attachment); diff --git a/src/cli/connection/cloud-connection-record.ts b/src/cli/connection/cloud-connection-record.ts index 53147bd677..4065872223 100644 --- a/src/cli/connection/cloud-connection-record.ts +++ b/src/cli/connection/cloud-connection-record.ts @@ -13,6 +13,7 @@ import { import { readCurrentOwnerIdentity } from '@agent-device/host-kit/process'; import { AppError, CLOUD_ATTACHMENT_REASONS, type ReasonTable } from '@agent-device/kernel/errors'; import { + observeRemoteConnectionState, readRemoteConnectionState, type CloudSessionBinding, type RemoteConnectionState, @@ -553,13 +554,15 @@ function isExpired(record: CloudConnectionRecord): boolean { return record.deadlineAt !== undefined && Date.parse(record.deadlineAt) <= Date.now(); } +export type ExpiredBookingAdmission = { mayUseSavedCredentials: boolean }; + /** * Clears what expired bookings left in the state directory. Only a booking that `admits` accepts * is touched, so a caller never tears down a booking that another identity made. */ export async function cleanExpiredCloudAttachments( stateDir: string, - admits: (record: CloudConnectionRecord) => boolean, + admits: (record: CloudConnectionRecord) => ExpiredBookingAdmission | null, retireExpiredDaemon: (location: ConnectionLocation, generation: string) => Promise, releaseExpiredProxyFront: ( location: ConnectionLocation, @@ -581,20 +584,34 @@ export async function cleanExpiredCloudAttachments( if (!location) continue; await tryWithConnectionLock(location, async () => { let current: CloudConnectionRecord | null; + let admission: ExpiredBookingAdmission | null; let kind: unknown; let proxyFront: ProxyFrontAttachment | undefined; try { current = readCloudConnection(location); - if (!current || !isExpired(current) || !admits(current)) return; - // Saved state of another booking is left for the explicit local recovery. - const state = readRemoteConnectionState(location); - if (state && !samePairedBooking(state.cloudSession, current)) return; + if (!current || !isExpired(current)) return; + admission = admits(current); + if (!admission) return; + // Saved state of another or invalid booking is left for explicit local recovery. + const observedState = observeRemoteConnectionState(location); + if ( + observedState.kind === 'invalid' || + observedState.kind === 'unknown' || + (observedState.kind === 'valid' && + !samePairedBooking(observedState.state.cloudSession, current)) + ) { + return; + } kind = readExpiredAttachmentKind(location); proxyFront = kind === 'agent-device-daemon' ? readProxyFrontAttachment(location) : undefined; } catch { return; } + if (!admission.mayUseSavedCredentials) { + removeCloudAttachment(location); + return; + } if (proxyFront && current.phase !== 'pending') { await releaseExpiredProxyFront(location, proxyFront).catch(() => undefined); removeCloudAttachment(location); @@ -613,7 +630,13 @@ export async function cleanExpiredCloudAttachments( function readExpiredAttachmentKind(location: ConnectionLocation): unknown { try { return asCloudRecord(readCloudCredentialJson(cloudAttachmentPath(location)))?.kind; - } catch { + } catch (error) { + if ( + error instanceof AppError && + error.details?.reason === CLOUD_CONNECTION_REASONS.credentialStoreUnsafe.reason + ) { + throw error; + } return undefined; } } diff --git a/src/cli/connection/cloud-plugin-attachment.ts b/src/cli/connection/cloud-plugin-attachment.ts index 8e6f77bd67..f36c84d8e7 100644 --- a/src/cli/connection/cloud-plugin-attachment.ts +++ b/src/cli/connection/cloud-plugin-attachment.ts @@ -4,6 +4,7 @@ import type { AttachmentInput } from '@agent-device/contracts/hosted-attachment' import { resolveDaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution'; import { AppError, cloudPluginRequiredError, type ReasonTable } from '@agent-device/kernel/errors'; import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; +import { lstatIfPresent } from '@agent-device/host-kit/file'; import { pluginInstallCommand } from '@agent-device/contracts/plugin-installation'; import { readVersion } from '@agent-device/host-kit/version'; import type { EnvMap, HostEnvironment } from '@agent-device/kernel/source-value'; @@ -72,6 +73,19 @@ export function hostedPluginDaemonDir( return path.join(cloudConnectionDir(location), 'daemon-' + key.slice(0, 20)); } +export function hasHostedPluginDaemonRegistration( + location: ConnectionLocation, + generation: string, + host: HostEnvironment, +): boolean { + const paths = resolveDaemonPaths(hostedPluginDaemonDir(location, { generation }), host); + try { + return Boolean(lstatIfPresent(paths.infoPath) || lstatIfPresent(paths.lockPath)); + } catch { + return true; + } +} + export async function stopHostedPluginDaemon( location: ConnectionLocation, generation: string | undefined, @@ -85,10 +99,7 @@ export async function stopHostedPluginDaemon( await import('@agent-device/daemon-contracts/daemon-registration'); const expected = { session: location.session, generation }; let identity = readDaemonStopIdentity(paths.infoPath, expected); - if ( - identity.ownership === 'absent' && - (await import('@agent-device/host-kit/file')).lstatIfPresent(paths.lockPath) - ) { + if (identity.ownership === 'absent' && lstatIfPresent(paths.lockPath)) { const { recoverAbandonedDaemonRegistration } = await import('@agent-device/daemon-contracts/daemon-registration-owner'); const retirement = await recoverAbandonedDaemonRegistration({ paths, observed: null });