import { join } from 'node:path'; import { setTimeout as delay } from 'node:timers/promises'; import { getWorkspaceDir } from './init-command.js'; import { getRuntimeDir } from './user-data.js'; import { tryAcquireWorkspaceRuntimeLock } from './workspace-runtime-lock.js'; import { readWorkspaceOwnerRecord, workspaceOwnerIdentity } from '../runtime/clawclaw/owner-lock.js'; import { readGameStartRuntime, sendOwnerControlRequestTo } from '../runtime/owner-control.js'; /** Stop locally only: never leave the backend game or claim its control again. */ export async function stopDesktopRuntime(timeoutMs = 10_000): Promise { const workspace = getWorkspaceDir(); const deadline = Date.now() + timeoutMs; let target: string | undefined; let stopSent = false; do { const guard = tryAcquireWorkspaceRuntimeLock(workspace); if (guard) { guard.release(); return; } const owner = readWorkspaceOwnerRecord(workspace); if (owner) { if (owner.workspace_id !== workspaceOwnerIdentity(workspace) || (target !== undefined && target !== owner.instance_id)) { throw new Error('Runtime changed while logging out. Retry from the client.'); } target = owner.instance_id; if (!stopSent) { const pointer = readGameStartRuntime(join(getRuntimeDir(workspace), 'accounts', owner.runtime_account_id)); if (pointer?.instance_id === target && pointer.owner_pid === owner.pid) { const response = await sendOwnerControlRequestTo(pointer, 'stop', { instance_id: target }, Math.max(1, Math.min(1_000, deadline - Date.now()))); stopSent = response?.ok === true; } } } await delay(50); } while (Date.now() < deadline); throw new Error('Runtime did not stop in time. Login binding was retained; retry from the client.'); }