Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(cli): add lh connect --managed for managed cloud devices (#22275)

Neko679c83e710dd
diff --git a/apps/cli/README.md b/apps/cli/README.md
index 8ce806245a8..296adacfe98 100644
--- a/apps/cli/README.md
+++ b/apps/cli/README.md
@@ -50,6 +50,79 @@ Diagnostics never dump the service's command line or environment. Older connecto
on Linux use a conservative `/proc` lookup; an inaccessible or unsupported entry
is reported as unknown instead of guessed.
+## Managed cloud devices
+
+A managed cloud device is a device that LobeHub creates and runs for you. The
+platform that runs it starts the agent with:
+
+```bash
+lh connect --managed
+```
+
+Managed mode reads everything from the environment. It does not use a stored
+login, a keychain or a browser, and it writes no credentials to disk, so it runs
+headless in a container. `lh connect service install` is not needed: the
+platform supervises the process and restarts it when it exits.
+
+| Variable | Required | Meaning |
+| --------------------------------- | -------- | ----------------------------------------------------------- |
+| `LOBEHUB_MANAGED_DEVICE_ID` | yes | The device id. It replaces the id derived from the machine. |
+| `LOBEHUB_MANAGED_DEVICE_SECRET` | yes | The bootstrap secret. The CLI never prints it. |
+| `LOBEHUB_SERVER` | yes | The LobeHub server URL. |
+| `LOBEHUB_DEVICE_GATEWAY_URL` | yes | The device gateway URL. |
+| `LOBEHUB_DEVICE_ACTIVITY_COMMAND` | no | A JSON array: a command to run while the device does work. |
+
+If a required variable is missing, the CLI names it and exits with status 1.
+`LOBEHUB_SERVER` and `LOBEHUB_DEVICE_GATEWAY_URL` must use `https`; `http` is
+accepted only for `localhost` and the loopback addresses `127.0.0.0/8` and
+`::1`. The URLs must not contain a user name, a password, a query or a fragment.
+A path is kept, so `https://example.com/lobehub` sends the token request to
+`https://example.com/lobehub/api/device/managed/token`. `--managed` cannot be used
+with `--token`, `--gateway`, `--device-id`, `--workspace`, `--public` or
+`--daemon`.
+
+After the CLI reads the secret, it removes it from its own environment, so the
+processes it starts (tool calls, agent runs) do not inherit it. This does not
+hide the secret from the device: other processes of the same user can still
+read the environment the CLI started with (for example `/proc/<pid>/environ`).
+The secret only gets tokens for this device, and it stops working when the
+device is deleted.
+
+**Token.** The CLI sends `POST {LOBEHUB_SERVER}/api/device/managed/token` with
+`{ "deviceId", "secret" }` and gets `{ "token", "expiresAt" }`, where
+`expiresAt` is an RFC 3339 time with `Z` or an offset. The token's
+`workspace_id` claim, when present, makes the device a workspace device;
+otherwise its `sub` is the owning user.
+
+- The CLI gets a new token when 80% of the token's lifetime has passed (at least
+ 5 s after it got the previous one). The open gateway connection stays up:
+ only the next connection uses the new token, so running tool calls, agent
+ runs and tunnels continue.
+- On HTTP 408, 429 or 5xx, a network error or an unreadable response, the CLI
+ tries again after 1 s, then 2 s, 4 s and so on, up to 60 s between attempts
+ (each delay Β±20%). It continues until the server answers.
+- On HTTP 401 (wrong secret, or the device was deleted), 404 (the server has no
+ managed cloud devices) or another 4xx, the CLI exits with status 1.
+- If the gateway rejects a token, the CLI gets a new token and connects again.
+ If the gateway also rejects that token before a connection succeeds, the CLI
+ exits with status 1.
+
+**Activity command.** When `LOBEHUB_DEVICE_ACTIVITY_COMMAND` is set, the CLI runs
+it while the device serves a tool call, an RPC, an agent run or an open tunnel.
+It runs when the work starts and then every 30 s while work continues, never
+more than once in 30 s and never two at a time. The work does not wait for it.
+A run that takes longer than 10 s is stopped. Failures appear only in the debug
+log (`--verbose`).
+
+The value is a JSON array of strings: the program, then its arguments, for
+example `["my-agent","touch"]`. The CLI runs the program directly, without a
+shell, so there is no quoting, `$VAR`, `~` or glob expansion, and `|`, `;`, `&`,
+`>` and `<` are ordinary characters. If the value is not a non-empty JSON array
+of non-empty strings, the CLI exits with status 1 at startup. To use shell
+features, give an explicit shell, for example
+`["sh","-c","my-agent touch >> /var/log/activity"]`. When the CLI stops, it
+also stops a command that is still running.
+
## Publish local artifacts
```bash
diff --git a/apps/cli/package.json b/apps/cli/package.json
index a50da2fb5db..1bda5124fe1 100644
--- a/apps/cli/package.json
+++ b/apps/cli/package.json
@@ -55,6 +55,7 @@
"dayjs": "^1.11.21",
"debug": "^4.4.3",
"diff": "^8.0.4",
+ "es-toolkit": "^1.50.0",
"fast-glob": "^3.3.3",
"ignore": "^7.0.5",
"picocolors": "^1.1.1",
diff --git a/apps/cli/src/commands/connect.managed.test.ts b/apps/cli/src/commands/connect.managed.test.ts
new file mode 100644
index 00000000000..e9bfd50018b
--- /dev/null
+++ b/apps/cli/src/commands/connect.managed.test.ts
@@ -0,0 +1,403 @@
+import type * as DeviceControlModule from '@lobechat/device-control';
+import type * as DeviceGatewayClientModule from '@lobechat/device-gateway-client';
+import { Command } from 'commander';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { resolveToken } from '../auth/resolveToken';
+import { appendLog } from '../daemon/manager';
+import type * as DeviceRegister from '../device/register';
+import type * as SystemInfoModule from '../device/systemInfo';
+import { loadWorkspaceEnrollments, saveDeviceGatewayUrl } from '../settings';
+import { executeToolCall } from '../tools';
+import { log } from '../utils/logger';
+import { registerConnectCommand } from './connect';
+
+vi.mock('../service/status', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ readConnectServices: async () => ({ services: [], unavailableScopes: [] }),
+}));
+
+vi.mock('../device/systemInfo', async (importOriginal) => ({
+ ...(await importOriginal<typeof SystemInfoModule>()),
+ probeNativeRuntimes: vi.fn().mockResolvedValue([]),
+}));
+
+const registerDeviceMock = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
+vi.mock('../device/register', async (importOriginal) => ({
+ ...(await importOriginal<typeof DeviceRegister>()),
+ registerDevice: registerDeviceMock,
+ registerWorkspaceDevice: registerDeviceMock,
+}));
+
+vi.mock('../auth/resolveToken', () => ({ resolveToken: vi.fn() }));
+vi.mock('../settings', () => ({
+ addWorkspaceEnrollment: vi.fn(),
+ loadDeviceGatewayUrl: vi.fn(),
+ loadOrCreateConnectionId: vi.fn().mockReturnValue('test-connection-id'),
+ loadSettings: vi.fn().mockReturnValue(null),
+ loadWorkspaceEnrollments: vi.fn().mockReturnValue(['ws-stale']),
+ normalizeUrl: vi.fn((url?: string) => (url ? url.replace(/\/$/, '') : undefined)),
+ removeWorkspaceEnrollment: vi.fn(),
+ resolveDeviceMetricsBacklogPath: vi.fn((id: string) => `/tmp/device-metrics/${id}.json`),
+ saveDeviceGatewayUrl: vi.fn(),
+ saveSettings: vi.fn(),
+}));
+
+vi.mock('../tools/shell', () => ({
+ cleanupAllProcesses: vi.fn(),
+ getActiveShellCount: vi.fn(() => 0),
+}));
+
+vi.mock('../daemon/manager', () => ({
+ appendLog: vi.fn(),
+ getLogPath: vi.fn().mockReturnValue('/tmp/test-daemon.log'),
+ getRunningDaemonPid: vi.fn().mockReturnValue(null),
+ isProcessAlive: vi.fn(() => false),
+ readStatus: vi.fn(),
+ removePid: vi.fn(),
+ removeStatus: vi.fn(),
+ reportDaemonStartupReady: vi.fn().mockResolvedValue(undefined),
+ spawnDaemon: vi.fn(),
+ stopDaemon: vi.fn(),
+ stopDaemonAndWait: vi.fn(),
+ writeStatus: vi.fn(),
+}));
+
+vi.mock('../tools', () => ({
+ executeToolCall: vi.fn().mockResolvedValue({ content: 'tool result', success: true }),
+}));
+
+const activity = vi.hoisted(() => ({
+ begin: vi.fn(),
+ end: vi.fn(),
+ options: undefined as any,
+ start: vi.fn(),
+ stop: vi.fn(),
+}));
+vi.mock('../device/activityHook', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ ActivityReporter: vi.fn().mockImplementation(function (opts: any) {
+ activity.options = opts;
+ activity.begin.mockImplementation(() => activity.end);
+ return activity;
+ }),
+}));
+
+vi.mock('@lobechat/device-control', async (importOriginal) => ({
+ ...(await importOriginal<typeof DeviceControlModule>()),
+ DeviceMetricsSampler: vi.fn().mockImplementation(function () {
+ return {
+ flush: vi.fn().mockResolvedValue(undefined),
+ start: vi.fn().mockResolvedValue(undefined),
+ stop: vi.fn().mockResolvedValue(undefined),
+ };
+ }),
+}));
+
+let handlers: Record<string, (...args: any[]) => any> = {};
+let clientOptions: any;
+let client: any;
+const GatewayClientMock = vi.hoisted(() => vi.fn());
+vi.mock('@lobechat/device-gateway-client', async (importOriginal) => ({
+ ...(await importOriginal<typeof DeviceGatewayClientModule>()),
+ GatewayClient: GatewayClientMock,
+}));
+
+const jwt = (payload: Record<string, unknown>) =>
+ `h.${Buffer.from(JSON.stringify(payload)).toString('base64url')}.s`;
+const PERSONAL_TOKEN = jwt({ device_id: 'managed-1', purpose: 'managed-device', sub: 'user-1' });
+const WORKSPACE_TOKEN = jwt({
+ device_id: 'managed-1',
+ purpose: 'managed-device',
+ sub: 'ws-1',
+ workspace_id: 'ws-1',
+});
+
+const MANAGED_ENV = {
+ LOBEHUB_DEVICE_GATEWAY_URL: 'https://gateway.example.com',
+ LOBEHUB_MANAGED_DEVICE_ID: 'managed-1',
+ LOBEHUB_MANAGED_DEVICE_SECRET: 'top-secret',
+ LOBEHUB_SERVER: 'https://app.example.com',
+};
+
+const tokenResponse = (token: string, lifetimeMs = 3_600_000) =>
+ Response.json({ expiresAt: new Date(Date.now() + lifetimeMs).toISOString(), token });
+
+describe('connect --managed', () => {
+ let exitSpy: ReturnType<typeof vi.spyOn>;
+ let fetchMock: ReturnType<typeof vi.fn>;
+ let savedEnv: NodeJS.ProcessEnv;
+ let signalListeners: Map<NodeJS.Signals, Set<(...args: unknown[]) => void>>;
+
+ beforeEach(() => {
+ signalListeners = new Map(
+ (['SIGINT', 'SIGTERM'] as const).map((signal) => [
+ signal,
+ new Set(process.listeners(signal)),
+ ]),
+ );
+ savedEnv = { ...process.env };
+ Object.assign(process.env, MANAGED_ENV);
+ delete process.env.LOBEHUB_DEVICE_ACTIVITY_COMMAND;
+ exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {}) as any);
+ vi.spyOn(log, 'error').mockImplementation(() => {});
+ vi.spyOn(log, 'info').mockImplementation(() => {});
+ fetchMock = vi.fn(async () => tokenResponse(PERSONAL_TOKEN));
+ vi.stubGlobal('fetch', fetchMock);
+ clientOptions = undefined;
+ GatewayClientMock.mockImplementation(function (opts: any) {
+ clientOptions = opts;
+ handlers = {};
+ client = {
+ activeTunnelCount: 0,
+ connect: vi.fn().mockResolvedValue(undefined),
+ connectionStatus: 'connecting',
+ currentDeviceId: opts.deviceId,
+ disconnect: vi.fn(),
+ on: vi.fn((event: string, handler: (...args: any[]) => any) => {
+ handlers[event] = handler;
+ }),
+ reconnect: vi.fn().mockResolvedValue(undefined),
+ reportMetrics: vi.fn(),
+ sendAgentRunAck: vi.fn(),
+ sendRpcResponse: vi.fn(),
+ sendSystemInfoResponse: vi.fn(),
+ sendToolCallResponse: vi.fn(),
+ updateToken: vi.fn(),
+ };
+ return client;
+ });
+ });
+
+ afterEach(() => {
+ for (const [signal, existing] of signalListeners) {
+ for (const listener of process.listeners(signal)) {
+ if (!existing.has(listener)) process.removeListener(signal, listener);
+ }
+ }
+ process.env = savedEnv;
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
+ });
+
+ const run = async (...args: string[]) => {
+ const program = new Command();
+ program.exitOverride();
+ registerConnectCommand(program);
+ await program.parseAsync(['node', 'test', 'connect', '--managed', ...args]).catch(() => {});
+ };
+
+ it('connects as the managed device without the stored login', async () => {
+ await run();
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ 'https://app.example.com/api/device/managed/token',
+ expect.objectContaining({
+ body: JSON.stringify({ deviceId: 'managed-1', secret: 'top-secret' }),
+ method: 'POST',
+ }),
+ );
+ expect(clientOptions).toMatchObject({
+ deviceId: 'managed-1',
+ gatewayUrl: 'https://gateway.example.com',
+ serverUrl: 'https://app.example.com',
+ token: PERSONAL_TOKEN,
+ tokenType: 'jwt',
+ userId: 'user-1',
+ workspaceId: undefined,
+ });
+ expect(client.connect).toHaveBeenCalled();
+ expect(resolveToken).not.toHaveBeenCalled();
+ // The platform owns the row; the device never registers or restores shares.
+ expect(registerDeviceMock).not.toHaveBeenCalled();
+ expect(loadWorkspaceEnrollments).not.toHaveBeenCalled();
+ expect(saveDeviceGatewayUrl).not.toHaveBeenCalled();
+ // Child processes (tools, agents) must not inherit the bootstrap secret.
+ expect(process.env.LOBEHUB_MANAGED_DEVICE_SECRET).toBeUndefined();
+ expect(exitSpy).not.toHaveBeenCalled();
+ });
+
+ it('uses the workspace principal when the token carries workspace_id', async () => {
+ fetchMock.mockResolvedValue(tokenResponse(WORKSPACE_TOKEN));
+ await run();
+
+ expect(clientOptions).toMatchObject({ userId: undefined, workspaceId: 'ws-1' });
+ });
+
+ it('fails fast, naming the missing variables but not the secret', async () => {
+ delete process.env.LOBEHUB_DEVICE_GATEWAY_URL;
+ await run();
+
+ expect(exitSpy).toHaveBeenCalledWith(1);
+ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('LOBEHUB_DEVICE_GATEWAY_URL'));
+ expect(JSON.stringify(vi.mocked(log.error).mock.calls)).not.toContain('top-secret');
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(GatewayClientMock).not.toHaveBeenCalled();
+ });
+
+ it.each([['--token', 'x'], ['--workspace', 'ws-1'], ['--device-id', 'd'], ['--daemon']])(
+ 'rejects %s',
+ async (...flag) => {
+ await run(...flag);
+ expect(exitSpy).toHaveBeenCalledWith(1);
+ expect(log.error).toHaveBeenCalledWith(expect.stringContaining(flag[0]));
+ expect(fetchMock).not.toHaveBeenCalled();
+ },
+ );
+
+ it('exits 1 on a 401 so the platform restarts it', async () => {
+ fetchMock.mockResolvedValue(new Response('{}', { status: 401 }));
+ await run();
+
+ expect(exitSpy).toHaveBeenCalledWith(1);
+ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('HTTP 401'));
+ expect(GatewayClientMock).not.toHaveBeenCalled();
+ });
+
+ it('exits 1 on a 404 (the server has no managed cloud devices)', async () => {
+ fetchMock.mockResolvedValue(new Response('{}', { status: 404 }));
+ await run();
+
+ expect(exitSpy).toHaveBeenCalledWith(1);
+ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('HTTP 404'));
+ expect(GatewayClientMock).not.toHaveBeenCalled();
+ });
+
+ it('never hands the gateway token to tools as a server API credential', async () => {
+ await run();
+
+ await handlers.tool_call_request({
+ requestId: 'r1',
+ toolCall: { apiName: 'readLocalFile', arguments: '{}', identifier: 'test' },
+ type: 'tool_call_request',
+ });
+ expect(executeToolCall).toHaveBeenCalledWith('readLocalFile', '{}', undefined, undefined);
+ });
+
+ it('keeps retrying 5xx and network errors before connecting', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+ fetchMock
+ .mockResolvedValueOnce(new Response('{}', { status: 502 }))
+ .mockRejectedValueOnce(new TypeError('fetch failed'))
+ .mockResolvedValueOnce(tokenResponse(PERSONAL_TOKEN));
+
+ const running = run();
+ await vi.advanceTimersByTimeAsync(60_000);
+ await running;
+
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+ expect(exitSpy).not.toHaveBeenCalled();
+ expect(client.connect).toHaveBeenCalled();
+ });
+
+ it('refreshes at 80% of the lifetime without dropping the socket', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] });
+ const refreshed = jwt({ sub: 'user-1', v: 2 });
+ fetchMock
+ .mockResolvedValueOnce(tokenResponse(PERSONAL_TOKEN, 100_000))
+ .mockResolvedValueOnce(tokenResponse(refreshed, 100_000));
+ await run();
+
+ await vi.advanceTimersByTimeAsync(79_999);
+ expect(client.updateToken).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(1);
+ expect(client.updateToken).toHaveBeenCalledWith(refreshed);
+ // The next (re)connection authenticates with it; in-flight work keeps the socket.
+ expect(client.reconnect).not.toHaveBeenCalled();
+ expect(client.disconnect).not.toHaveBeenCalled();
+ });
+
+ it('exits 1 when a scheduled refresh gets a 401', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] });
+ fetchMock
+ .mockResolvedValueOnce(tokenResponse(PERSONAL_TOKEN, 100_000))
+ .mockResolvedValueOnce(new Response('{}', { status: 401 }));
+ await run();
+
+ await vi.advanceTimersByTimeAsync(80_000);
+ expect(exitSpy).toHaveBeenCalledWith(1);
+ expect(client.disconnect).toHaveBeenCalled();
+ });
+
+ it('gets a new token once when the gateway rejects one, then gives up', async () => {
+ const refreshed = jwt({ sub: 'user-1', v: 2 });
+ fetchMock
+ .mockResolvedValueOnce(tokenResponse(PERSONAL_TOKEN))
+ .mockResolvedValueOnce(tokenResponse(refreshed));
+ await run();
+
+ await handlers.auth_failed('token rejected');
+ expect(client.updateToken).toHaveBeenCalledWith(refreshed);
+ expect(client.reconnect).toHaveBeenCalledTimes(1);
+ expect(exitSpy).not.toHaveBeenCalled();
+
+ await handlers.auth_failed('token rejected');
+ expect(exitSpy).toHaveBeenCalledWith(1);
+ });
+
+ it('retries a rejected token again after a successful connection', async () => {
+ await run();
+
+ await handlers.auth_failed('token rejected');
+ handlers.connected();
+ await handlers.auth_failed('token rejected');
+ expect(client.reconnect).toHaveBeenCalledTimes(2);
+ expect(exitSpy).not.toHaveBeenCalled();
+ });
+
+ it('gets a new token and reconnects when the gateway expires the token', async () => {
+ const refreshed = jwt({ sub: 'user-1', v: 2 });
+ fetchMock
+ .mockResolvedValueOnce(tokenResponse(PERSONAL_TOKEN))
+ .mockResolvedValueOnce(tokenResponse(refreshed));
+ await run();
+
+ await handlers.auth_expired();
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(client.updateToken).toHaveBeenCalledWith(refreshed);
+ expect(client.reconnect).toHaveBeenCalledTimes(1);
+ expect(exitSpy).not.toHaveBeenCalled();
+ });
+
+ it('exits 1 when the token exchange refuses the device after the gateway expires the token', async () => {
+ fetchMock
+ .mockResolvedValueOnce(tokenResponse(PERSONAL_TOKEN))
+ .mockResolvedValueOnce(new Response('{}', { status: 401 }));
+ await run();
+
+ await handlers.auth_expired();
+ expect(client.reconnect).not.toHaveBeenCalled();
+ expect(exitSpy).toHaveBeenCalledWith(1);
+ expect(client.disconnect).toHaveBeenCalled();
+ });
+
+ it('reports tool calls, RPCs and agent dispatch through the activity hook', async () => {
+ process.env.LOBEHUB_DEVICE_ACTIVITY_COMMAND = '["my-agent","touch"]';
+ await run();
+
+ expect(activity.options.command).toEqual(['my-agent', 'touch']);
+ expect(activity.start).toHaveBeenCalled();
+
+ await handlers.tool_call_request({
+ requestId: 'r1',
+ toolCall: { apiName: 'readLocalFile', arguments: '{}', identifier: 'test' },
+ type: 'tool_call_request',
+ });
+ await handlers.rpc_request({ method: 'unknownMethod', params: {}, requestId: 'r2' });
+ expect(activity.begin).toHaveBeenCalledTimes(2);
+ expect(activity.end).toHaveBeenCalledTimes(2);
+
+ // Polled work: open tunnels count as busy.
+ expect(activity.options.isBusy()).toBe(false);
+ client.activeTunnelCount = 1;
+ expect(activity.options.isBusy()).toBe(true);
+ });
+
+ it('does not create an activity hook without the variable', async () => {
+ await run();
+ expect(activity.start).not.toHaveBeenCalled();
+ expect(appendLog).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/cli/src/commands/connect/handlers.ts b/apps/cli/src/commands/connect/handlers.ts
new file mode 100644
index 00000000000..3fc39af1058
--- /dev/null
+++ b/apps/cli/src/commands/connect/handlers.ts
@@ -0,0 +1,208 @@
+import { type DeviceControlDeps, executeDeviceRpc } from '@lobechat/device-control';
+import { BROWSER_IDENTIFIER } from '@lobechat/device-control/agent-browser';
+import { COMPUTER_USE_IDENTIFIER } from '@lobechat/device-control/computer-use';
+import type {
+ AgentRunRequestMessage,
+ GatewayClient,
+ RpcRequestMessage,
+ SystemInfoRequestMessage,
+ ToolCallRequestMessage,
+} from '@lobechat/device-gateway-client';
+import type { RuntimeProbeCache } from '@lobechat/heterogeneous-agents/runtimeProbeCache';
+import { executeDeviceOperation } from '@lobechat/local-file-shell/shell';
+
+import type { resolveToken } from '../../auth/resolveToken';
+import type { CliMaintenance } from '../../daemon/maintenance';
+import { appendLog } from '../../daemon/manager';
+import type { ActivityReporter } from '../../device/activityHook';
+import { spawnHeteroAgentRun } from '../../device/agentRun';
+import { collectSystemInfo } from '../../device/systemInfo';
+import { executeToolCall } from '../../tools';
+import { executeBrowserCall, type resolveBrowserDevice } from '../../tools/browser';
+import { executeComputerUseCall, type resolveComputerUseDevice } from '../../tools/computerUse';
+import { log } from '../../utils/logger';
+
+/** Everything a gateway connection's request handlers need from the host process. */
+export interface GatewayHandlerContext {
+ /** Present when `LOBEHUB_DEVICE_ACTIVITY_COMMAND` reports this device's work. */
+ activity?: ActivityReporter;
+ /** Present when an `agent-browser` binary enabled the browser tool on this device. */
+ browser?: Awaited<ReturnType<typeof resolveBrowserDevice>>;
+ /** Present when `--auv` enabled Computer Use on this device. */
+ computerUse?: Awaited<ReturnType<typeof resolveComputerUseDevice>>;
+ deps: DeviceControlDeps;
+ error: (msg: string) => void;
+ /** Read at dispatch time β€” the underlying auth may be refreshed mid-session. */
+ getAuth: () => Awaited<ReturnType<typeof resolveToken>>;
+ /** Credentials tools may use against the server API (e.g. image upload); none when absent. */
+ getToolAuth: () => Awaited<ReturnType<typeof resolveToken>> | undefined;
+ info: (msg: string) => void;
+ isDaemonChild: boolean;
+ maintenance: CliMaintenance;
+ /** Process-wide native runtime probe, shared by every gateway connection. */
+ nativeRuntimes: RuntimeProbeCache;
+ recordRequest: () => void;
+}
+
+/**
+ * Bind the request handlers shared by every gateway connection this process
+ * owns β€” the personal connection and any workspace-share connections opened via
+ * the `enrollWorkspace` RPC β€” so a workspace principal exposes exactly the same
+ * tool / RPC / agent-run surface as the personal one.
+ */
+export function bindGatewayClientHandlers(
+ client: GatewayClient,
+ ctx: GatewayHandlerContext,
+ connectionWorkspaceId?: string,
+) {
+ const {
+ activity,
+ browser,
+ computerUse,
+ deps,
+ error,
+ getAuth,
+ getToolAuth,
+ info,
+ isDaemonChild,
+ maintenance,
+ recordRequest,
+ } = ctx;
+
+ // Handle system info requests
+ client.on('system_info_request', async (request: SystemInfoRequestMessage) => {
+ info(`Received system_info_request: requestId=${request.requestId}`);
+ const systemInfo = await collectSystemInfo(ctx.nativeRuntimes, computerUse, browser);
+ client.sendSystemInfoResponse({
+ requestId: request.requestId,
+ result: { success: true, systemInfo },
+ });
+ });
+
+ // Handle tool call requests
+ client.on('tool_call_request', async (request: ToolCallRequestMessage) => {
+ recordRequest();
+ const endActivity = activity?.begin();
+ const { operationId, requestId, timeout, toolCall } = request;
+ if (isDaemonChild) {
+ appendLog(
+ `[TOOL] ${toolCall.apiName}${operationId ? ` op=${operationId}` : ''} (${requestId})`,
+ );
+ } else {
+ log.toolCall(toolCall.apiName, requestId, toolCall.arguments, operationId);
+ }
+
+ // Timed on the DEVICE's clock. The server can only see the whole dispatch
+ // round trip, so reporting this back is what separates a slow tool from
+ // slow transport.
+ const startedAt = performance.now();
+ const result = await executeDeviceOperation({ apiName: toolCall.apiName, operationId }, () =>
+ maintenance.run(() =>
+ // Computer Use's `runCommand` shares its apiName with the shell tool, and
+ // the browser's apis (`click`, `screenshot`, …) are routed by identifier too.
+ toolCall.identifier === COMPUTER_USE_IDENTIFIER
+ ? executeComputerUseCall(computerUse, toolCall.apiName, toolCall.arguments, timeout)
+ : toolCall.identifier === BROWSER_IDENTIFIER
+ ? executeBrowserCall(browser, toolCall.apiName, toolCall.arguments, timeout)
+ : executeToolCall(toolCall.apiName, toolCall.arguments, timeout, getToolAuth()),
+ ),
+ ).catch((err: Error) => ({
+ content: '',
+ error: err.message,
+ state: undefined,
+ success: false,
+ }));
+ endActivity?.();
+ const executionTimeMs = Math.round(performance.now() - startedAt);
+
+ if (isDaemonChild) {
+ appendLog(
+ `[RESULT] ${result.success ? 'OK' : 'FAIL'} ${executionTimeMs}ms${operationId ? ` op=${operationId}` : ''} (${requestId})`,
+ );
+ } else {
+ log.toolResult(requestId, result.success, result.content, operationId);
+ }
+
+ client.sendToolCallResponse({
+ requestId,
+ result: {
+ content: result.content,
+ error: result.error,
+ executionTimeMs,
+ state: result.state,
+ success: result.success,
+ },
+ });
+ });
+
+ // Handle generic server-internal device RPCs (git / workspace / file ops).
+ // Shares the `@lobechat/device-control` dispatcher with the desktop app so the
+ // CLI exposes the same remote-device control surface.
+ client.on('rpc_request', async (request: RpcRequestMessage) => {
+ const { method, params, requestId } = request;
+ if (isDaemonChild) appendLog(`[RPC] ${method} (${requestId})`);
+ else info(`Received rpc_request: method=${method} (${requestId})`);
+
+ const endActivity = activity?.begin();
+ try {
+ const run = () => executeDeviceRpc(method, params, deps);
+ const isMaintenance = ['getCliUpdateState', 'checkCliUpdate', 'restartCli'].includes(method);
+ const data = await (isMaintenance ? run() : maintenance.run(run));
+ client.sendRpcResponse({ requestId, result: { data, success: true } });
+ if (method === 'restartCli') maintenance.afterResponse();
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ if (isDaemonChild) appendLog(`[RPC ERROR] ${method}: ${message} (${requestId})`);
+ else error(`rpc_request method=${method} failed: ${message}`);
+ client.sendRpcResponse({ requestId, result: { error: message, success: false } });
+ } finally {
+ endActivity?.();
+ }
+ });
+
+ // Handle gateway-dispatched agent runs (heterogeneous agents, e.g. Claude
+ // Code). Mirrors the desktop app: spawn `lh hetero exec`, which owns the full
+ // execution + server-ingest pipeline. Ack with the spawn outcome β€” `accepted`
+ // once the child starts, `rejected` if it fails to spawn (e.g. bad cwd) β€” so
+ // a failed dispatch surfaces as an error instead of a stuck assistant message.
+ client.on('agent_run_request', async (request: AgentRunRequestMessage) => {
+ recordRequest();
+ // Covers the dispatch; the run itself is polled through the task registry.
+ const endActivity = activity?.begin();
+ info(
+ `Received agent_run_request: operationId=${request.operationId} type=${request.agentType}`,
+ );
+ try {
+ const ack = await maintenance.run(() =>
+ spawnHeteroAgentRun(
+ {
+ agentId: request.agentId,
+ agentType: request.agentType,
+ assistantMessageId: request.assistantMessageId,
+ args: request.args,
+ claudeAccountRouting: request.claudeAccountRouting,
+ cwd: request.cwd,
+ imageList: request.imageList,
+ jwt: request.jwt,
+ operationId: request.operationId,
+ prompt: request.prompt,
+ resumeFallbackSystemContext: request.resumeFallbackSystemContext,
+ resumeSessionId: request.resumeSessionId,
+ serverUrl: getAuth().serverUrl,
+ systemContext: request.systemContext,
+ topicId: request.topicId,
+ workspaceId: request.ingestWorkspaceId ?? request.workspaceId ?? connectionWorkspaceId,
+ },
+ { error, info },
+ ),
+ );
+ client.sendAgentRunAck({ operationId: request.operationId, ...ack });
+ } catch (err) {
+ const reason = err instanceof Error ? err.message : String(err);
+ error(`agent_run_request failed: ${reason}`);
+ client.sendAgentRunAck({ operationId: request.operationId, reason, status: 'rejected' });
+ } finally {
+ endActivity?.();
+ }
+ });
+}
diff --git a/apps/cli/src/commands/connect.ts b/apps/cli/src/commands/connect/index.ts
similarity index 77%
rename from apps/cli/src/commands/connect.ts
rename to apps/cli/src/commands/connect/index.ts
index 4d993c46ecb..e3ef6731fbe 100644
--- a/apps/cli/src/commands/connect.ts
+++ b/apps/cli/src/commands/connect/index.ts
@@ -8,33 +8,24 @@ import {
defaultSearchProjectFiles,
type DeviceControlDeps,
DeviceMetricsSampler,
- executeDeviceRpc,
pushMetrics,
} from '@lobechat/device-control';
-import { BROWSER_IDENTIFIER } from '@lobechat/device-control/agent-browser';
-import { COMPUTER_USE_IDENTIFIER } from '@lobechat/device-control/computer-use';
-import type {
- AgentRunRequestMessage,
- RpcRequestMessage,
- SystemInfoRequestMessage,
- ToolCallRequestMessage,
-} from '@lobechat/device-gateway-client';
import { GatewayClient } from '@lobechat/device-gateway-client';
import { listHeterogeneousAgentModels } from '@lobechat/heterogeneous-agents/models';
-import {
- createRuntimeProbeCache,
- type RuntimeProbeCache,
-} from '@lobechat/heterogeneous-agents/runtimeProbeCache';
-import { executeDeviceOperation } from '@lobechat/local-file-shell/shell';
+import { createRuntimeProbeCache } from '@lobechat/heterogeneous-agents/runtimeProbeCache';
import type { Command } from 'commander';
-import { createLambdaClient } from '../api/client';
-import { scheduleProactiveRefresh } from '../auth/proactiveRefresh';
-import { resolveToken } from '../auth/resolveToken';
-import { CLI_API_KEY_ENV } from '../constants/auth';
-import { CLI_CONNECT_SERVICE_NAME, CLI_DISPLAY_NAME, CLI_PRIMARY_BIN } from '../constants/identity';
-import { getCliInstallationPath } from '../daemon/installation';
-import { CliMaintenance } from '../daemon/maintenance';
+import { createLambdaClient } from '../../api/client';
+import { scheduleProactiveRefresh } from '../../auth/proactiveRefresh';
+import { resolveToken } from '../../auth/resolveToken';
+import { CLI_API_KEY_ENV } from '../../constants/auth';
+import {
+ CLI_CONNECT_SERVICE_NAME,
+ CLI_DISPLAY_NAME,
+ CLI_PRIMARY_BIN,
+} from '../../constants/identity';
+import { getCliInstallationPath } from '../../daemon/installation';
+import { CliMaintenance } from '../../daemon/maintenance';
import {
appendLog,
getLogPath,
@@ -47,25 +38,27 @@ import {
stopDaemon,
stopDaemonAndWait,
writeStatus,
-} from '../daemon/manager';
-import { listTasks } from '../daemon/taskRegistry';
-import { spawnHeteroAgentRun } from '../device/agentRun';
+} from '../../daemon/manager';
+import { listTasks } from '../../daemon/taskRegistry';
+import { ActivityReporter } from '../../device/activityHook';
import {
describeDeviceGateway,
describeDeviceGatewayFailure,
rememberGatewayOverride,
resolveCliDeviceGateway,
-} from '../device/gatewayEndpoint';
+} from '../../device/gatewayEndpoint';
+import { MANAGED_GATEWAY_ENV } from '../../device/managed';
import {
mintWorkspaceConnectToken,
registerDevice,
registerWorkspaceDevice,
resolveDeviceIdentity,
resolveWorkspaceDeviceIdentity,
-} from '../device/register';
-import { collectSystemInfo, probeNativeRuntimes } from '../device/systemInfo';
-import { TerminalSessionManager } from '../device/terminal';
-import { cliVersion } from '../pkg';
+} from '../../device/register';
+import { probeNativeRuntimes } from '../../device/systemInfo';
+import { TerminalSessionManager } from '../../device/terminal';
+import { redactUrlCredentials } from '../../doctor/redact';
+import { cliVersion } from '../../pkg';
import {
CONNECT_RETRYABLE_EXIT_CODE,
getWorkspaceFailureExitCode,
@@ -73,23 +66,24 @@ import {
startConnectService,
stopConnectService,
uninstallConnectService,
-} from '../service/connect';
-import { getServiceRestartCommand, readConnectServices } from '../service/status';
+} from '../../service/connect';
+import { getServiceRestartCommand, readConnectServices } from '../../service/status';
import {
addWorkspaceEnrollment,
loadOrCreateConnectionId,
loadWorkspaceEnrollments,
removeWorkspaceEnrollment,
resolveDeviceMetricsBacklogPath,
-} from '../settings';
-import { executeToolCall } from '../tools';
-import { closeBrowserSessions, executeBrowserCall, resolveBrowserDevice } from '../tools/browser';
-import { executeComputerUseCall, resolveComputerUseDevice } from '../tools/computerUse';
-import { cleanupAllProcesses, getActiveShellCount } from '../tools/shell';
-import { log, setVerbose } from '../utils/logger';
-import { sweepLocalTraces } from '../utils/traceMaintenance';
-import { restartConnector } from './connectRestart';
-import { printConnectStatus } from './connectStatus';
+} from '../../settings';
+import { closeBrowserSessions, resolveBrowserDevice } from '../../tools/browser';
+import { resolveComputerUseDevice } from '../../tools/computerUse';
+import { cleanupAllProcesses, getActiveShellCount } from '../../tools/shell';
+import { log, setVerbose } from '../../utils/logger';
+import { sweepLocalTraces } from '../../utils/traceMaintenance';
+import { restartConnector } from '../connectRestart';
+import { printConnectStatus } from '../connectStatus';
+import { bindGatewayClientHandlers, type GatewayHandlerContext } from './handlers';
+import { getManagedFlagConflicts, startManagedDevice } from './managed';
/** Longest a clean stop waits to push pending device health samples. */
const SHUTDOWN_METRICS_FLUSH_MS = 3000;
@@ -104,6 +98,8 @@ interface ConnectOptions {
daemonChild?: boolean;
deviceId?: string;
gateway?: string;
+ /** Run as a managed cloud device; identity and credentials come from the environment. */
+ managed?: boolean;
manager?: string;
/** With --workspace: enroll into the shared pool visible to every member (default: private). */
public?: boolean;
@@ -126,6 +122,10 @@ export function registerConnectCommand(program: Command) {
'--public',
'With --workspace: enroll into the shared pool visible to every member (default: private, visible only to you)',
)
+ .option(
+ '--managed',
+ 'Run as a managed cloud device: read the device id, secret, server and gateway from LOBEHUB_MANAGED_DEVICE_ID, LOBEHUB_MANAGED_DEVICE_SECRET, LOBEHUB_SERVER and LOBEHUB_DEVICE_GATEWAY_URL',
+ )
.option('--auv <binary>', 'Offer Computer Use by running this AUV binary (`auv invoke`)')
.option(
'--agent-browser <binary>',
@@ -138,6 +138,15 @@ export function registerConnectCommand(program: Command) {
.action(async (options: ConnectOptions) => {
if (options.verbose) setVerbose(true);
+ if (options.managed) {
+ const conflicts = getManagedFlagConflicts(options);
+ if (conflicts.length > 0) {
+ log.error(`--managed cannot be combined with ${conflicts.join(', ')}.`);
+ process.exit(1);
+ return;
+ }
+ }
+
// --daemon: spawn detached child and exit
if (options.daemon) {
return handleDaemonStart(options);
@@ -351,6 +360,7 @@ function buildDaemonArgs(options: ConnectOptions): string[] {
if (options.deviceId) args.push('--device-id', options.deviceId);
if (options.workspace) args.push('--workspace', options.workspace);
if (options.public) args.push('--public');
+ if (options.managed) args.push('--managed');
if (options.auv) args.push('--auv', path.resolve(options.auv));
if (options.agentBrowser) args.push('--agent-browser', path.resolve(options.agentBrowser));
if (options.verbose) args.push('--verbose');
@@ -359,9 +369,6 @@ function buildDaemonArgs(options: ConnectOptions): string[] {
}
async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
- const unavailableExitCode = options.workspace ? CONNECT_RETRYABLE_EXIT_CODE : undefined;
- let auth = await resolveToken({ ...options, unavailableExitCode });
-
const info = (msg: string) => {
if (isDaemonChild) appendLog(msg);
else log.info(msg);
@@ -372,20 +379,36 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
else log.error(msg);
};
+ const debug = (msg: string) => {
+ if (!isDaemonChild) log.debug(msg);
+ else if (options.verbose) appendLog(`[DEBUG] ${msg}`);
+ };
+
+ // Managed cloud device: identity, server, gateway and credentials all come
+ // from the environment the platform injected; the stored login is unused.
+ const managed = options.managed ? await startManagedDevice({ debug, error, info }) : undefined;
+
+ const unavailableExitCode = options.workspace ? CONNECT_RETRYABLE_EXIT_CODE : undefined;
+ let auth = managed ? managed.auth : await resolveToken({ ...options, unavailableExitCode });
+
// Resolved once per process, against the server the token belongs to. The
// client's own reconnects and every workspace share connection reuse it.
- const gateway = await resolveCliDeviceGateway({
- override: options.gateway,
- serverUrl: auth.serverUrl,
- });
+ const gateway = managed
+ ? ({ endpoint: { source: 'override', url: managed.config.gatewayUrl }, ok: true } as const)
+ : await resolveCliDeviceGateway({
+ override: options.gateway,
+ serverUrl: auth.serverUrl,
+ });
if (!gateway.ok) {
const { detail, fix } = describeDeviceGatewayFailure(gateway, auth.serverUrl);
// Thrown, so a daemon parent reports it as the startup error too.
throw new Error(`${detail} ${fix}`);
}
const resolvedGatewayUrl = gateway.endpoint.url;
- const gatewayDescription = describeDeviceGateway(gateway.endpoint);
- if (rememberGatewayOverride(auth.serverUrl, gateway.endpoint)) {
+ const gatewayDescription = managed
+ ? `${redactUrlCredentials(resolvedGatewayUrl)} (${MANAGED_GATEWAY_ENV})`
+ : describeDeviceGateway(gateway.endpoint);
+ if (!managed && rememberGatewayOverride(auth.serverUrl, gateway.endpoint)) {
info(
`Saved ${resolvedGatewayUrl} as the device gateway for ${auth.serverUrl}; later runs use it ahead of the server's own address.`,
);
@@ -410,13 +433,20 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
// workspace-derived deviceId. `auth` stays the admin's identity β€” used only to
// (re-)mint the connect token and register the row.
const workspaceId = options.workspace;
+ // The gateway principal of a managed device: its token's workspace, or its owner.
+ const managedWorkspaceId = managed?.principal.workspaceId;
// Resolve a stable device identity. An explicit `--device-id` wins (lets a
// user pin a VM to a fixed identity); otherwise derive from the machine id so
// the same machine maps to one device across reconnects.
- const identity = workspaceId
- ? resolveWorkspaceDeviceIdentity(workspaceId, options.deviceId, loadOrCreateConnectionId())
- : resolveDeviceIdentity(auth.userId, options.deviceId);
+ // A managed device has no derived identity: the platform registered its row
+ // and fixed its id, so it never registers itself.
+ const identity = managed
+ ? undefined
+ : workspaceId
+ ? resolveWorkspaceDeviceIdentity(workspaceId, options.deviceId, loadOrCreateConnectionId())
+ : resolveDeviceIdentity(auth.userId, options.deviceId);
+ const deviceId = managed?.config.deviceId ?? identity?.deviceId ?? options.deviceId;
// The token the gateway socket authenticates with. Re-minted on refresh for
// workspace devices (see `refreshConnectToken`).
@@ -436,6 +466,9 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
// Re-resolve the admin auth and, for workspace mode, re-mint the connect token.
const refreshConnectToken = async (): Promise<string | undefined> => {
+ // `refreshNow` reports the new token through `onToken`, which updates
+ // `auth`, `connectToken` and the client.
+ if (managed) return (await managed.session.refreshNow()).token;
const refreshed = await resolveToken({ unavailableExitCode });
if (!refreshed) return undefined;
auth = refreshed;
@@ -455,23 +488,40 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
const client = new GatewayClient({
channel,
connectionId: loadOrCreateConnectionId(),
- deviceId: identity?.deviceId ?? options.deviceId,
+ deviceId,
gatewayUrl: resolvedGatewayUrl,
logger: isDaemonChild ? createDaemonLogger() : log,
serverUrl: auth.serverUrl,
token: connectToken,
tokenType: connectTokenType,
- userId: workspaceId ? undefined : auth.userId,
- workspaceId,
+ userId: managed ? managed.principal.userId : workspaceId ? undefined : auth.userId,
+ workspaceId: managed ? managedWorkspaceId : workspaceId,
});
+ if (managed) {
+ // Only the next (re)connection authenticates with the token, so a refresh
+ // never closes the socket: tool calls, agent runs and tunnels keep running.
+ managed.events.onToken = (token) => {
+ connectToken = token.token;
+ auth = { ...auth, token: token.token };
+ client.updateToken(token.token);
+ debug('Refreshed the managed device token');
+ };
+ managed.events.onFatal = (err) => exitManaged(err.message);
+ }
+
// Print device info
info(`─── ${CLI_DISPLAY_NAME} ───`);
info(` Device ID : ${client.currentDeviceId}`);
info(` Hostname : ${os.hostname()}`);
info(` Platform : ${process.platform}`);
info(` Gateway : ${gatewayDescription}`);
- info(` Auth : ${auth.tokenType}`);
+ info(` Auth : ${managed ? 'managed device token' : auth.tokenType}`);
+ if (managed) {
+ info(
+ ` Principal : ${managedWorkspaceId ? `workspace ${managedWorkspaceId}` : `user ${managed.principal.userId}`}`,
+ );
+ }
info(` Mode : ${isDaemonChild ? 'daemon' : 'foreground'}`);
info('───────────────────');
@@ -526,9 +576,11 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
// touches it.
const terminals = new TerminalSessionManager({ logger: { warn: (message) => info(message) } });
+ const countActiveTasks = () =>
+ getActiveShellCount() + listTasks().filter((task) => isProcessAlive(task.pid)).length;
+
const maintenance = new CliMaintenance({
- activeTasks: () =>
- getActiveShellCount() + listTasks().filter((task) => isProcessAlive(task.pid)).length,
+ activeTasks: countActiveTasks,
daemon:
!!options.daemonChild && !options.serviceChild && process.env.LOBEHUB_CONNECT_SERVICE !== '1',
restartArgs: buildDaemonArgs(options).slice(1),
@@ -558,13 +610,26 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
// agent dispatch alike, and each probe starts a Codex app-server process.
const nativeRuntimes = createRuntimeProbeCache(probeNativeRuntimes);
+ // Tool calls and RPCs report themselves through `begin()`; agent runs (which
+ // outlive their dispatch), background shells and tunnels are polled.
+ const activity = managed?.config.activityCommand
+ ? new ActivityReporter({
+ command: managed.config.activityCommand,
+ isBusy: () => countActiveTasks() > 0 || client.activeTunnelCount > 0,
+ logger: { debug },
+ })
+ : undefined;
+
const handlerContext: GatewayHandlerContext = {
+ activity,
browser,
computerUse,
deps: deviceControlDeps,
error,
// Read at dispatch time β€” `auth` may be refreshed mid-session.
getAuth: () => auth,
+ // The managed token authenticates with the gateway only, never the server API.
+ getToolAuth: () => (managed ? undefined : auth),
info,
isDaemonChild,
maintenance,
@@ -574,7 +639,23 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
// Request handlers (system info / tool calls / device RPCs / agent runs) β€”
// shared with the workspace-share connections opened via `enrollWorkspace`.
- bindGatewayClientHandlers(client, handlerContext, workspaceId);
+ bindGatewayClientHandlers(client, handlerContext, workspaceId ?? managedWorkspaceId);
+
+ // A scheduled refresh and an auth handler can both reach a final answer from
+ // the one shared token exchange; stop only once.
+ let managedExiting = false;
+ const exitManaged = (message: string) => {
+ if (managedExiting) return;
+ managedExiting = true;
+ error(message);
+ cleanup();
+ process.exit(1);
+ };
+
+ // Managed mode: one token refresh per rejected connection. A token the
+ // gateway rejects right after it was issued will not get better by retrying,
+ // so exit and let the platform restart the agent.
+ let managedAuthRetried = false;
// Machine health (CPU / memory / load) for the device page. Samples go to
// the device gateway over this socket (the gateway is their only store);
@@ -582,11 +663,12 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
// back, so the stretch around a drop is visible afterwards. Each batch is
// mirrored to this machine's workspace-share connections so a shared
// device's workspace row has the same history.
- const metricsSampler = identity
+ const metricsDeviceId = identity?.deviceId ?? managed?.config.deviceId;
+ const metricsSampler = metricsDeviceId
? new DeviceMetricsSampler({
isConnected: () => client.connectionStatus === 'connected',
logger: { warn: (msg) => info(msg) },
- storagePath: resolveDeviceMetricsBacklogPath(identity.deviceId),
+ storagePath: resolveDeviceMetricsBacklogPath(metricsDeviceId),
upload: (samples) =>
pushMetrics(
client,
@@ -597,6 +679,7 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
: undefined;
client.on('connected', () => {
+ managedAuthRetried = false;
updateStatus('connected');
void metricsSampler?.flush();
// A (re)connection reprobes so an upgraded or downgraded Codex is reported, and
@@ -742,7 +825,8 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
}, 500);
return { success: true };
};
- } else {
+ } else if (!managed) {
+ // A managed device belongs to one principal; it is never shared into a workspace.
deviceControlDeps.enrollWorkspace = async ({
identityOnly,
token: wsToken,
@@ -813,26 +897,45 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
// personal device it refreshes the user token. Scheduling watches the actual
// connect token, so the workspace token's shorter life is respected.
const startProactiveRefresh = (): (() => void) | null =>
- scheduleProactiveRefresh(
- connectToken,
- connectTokenType,
- async () => {
- const newToken = await refreshConnectToken();
- if (newToken) {
- client.updateToken(newToken);
- cancelRefreshTimer = startProactiveRefresh();
- }
- return newToken;
- },
- info,
- error,
- );
+ // A managed token session schedules its own refreshes.
+ managed
+ ? null
+ : scheduleProactiveRefresh(
+ connectToken,
+ connectTokenType,
+ async () => {
+ const newToken = await refreshConnectToken();
+ if (newToken) {
+ client.updateToken(newToken);
+ cancelRefreshTimer = startProactiveRefresh();
+ }
+ return newToken;
+ },
+ info,
+ error,
+ );
let cancelRefreshTimer = startProactiveRefresh();
// Handle auth failed β€” attempt token refresh once before giving up
// (e.g., auto-reconnect may send an expired JWT before proactive refresh fires)
let authFailedRefreshAttempted = false;
client.on('auth_failed', async (reason) => {
+ if (managed) {
+ if (managedAuthRetried) {
+ exitManaged(`The gateway rejected the managed device token: ${reason}`);
+ return;
+ }
+ managedAuthRetried = true;
+ info(`Authentication failed (${reason}). Getting a new managed device token...`);
+ try {
+ await managed.session.refreshNow();
+ await client.reconnect();
+ } catch (err) {
+ exitManaged((err as Error).message);
+ }
+ return;
+ }
+
let exitCode = 1;
if (connectTokenType === 'jwt' && !authFailedRefreshAttempted) {
authFailedRefreshAttempted = true;
@@ -886,6 +989,10 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
if (workspaceId) exitCode = getWorkspaceFailureExitCode(err);
}
+ if (managed) {
+ exitManaged('Could not get a new managed device token.');
+ return;
+ }
error("Could not refresh token. Run 'lh login' to re-authenticate.");
cleanup();
process.exit(exitCode);
@@ -911,6 +1018,8 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
const cleanup = () => {
info('Shutting down...');
cancelRefreshTimer?.();
+ managed?.session.stop();
+ activity?.stop();
cleanupAllProcesses();
// Kill every remote-terminal shell this daemon started, so a stopping
// `lh connect` does not leave orphaned PTYs behind on the machine.
@@ -978,183 +1087,14 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
await reportDaemonStartupReady();
await metricsSampler?.start();
+ activity?.start();
// Connect
await client.connect();
// Personal mode: re-open any workspace share connections from a previous run.
// Best-effort after the main connection β€” a failed restore never blocks it.
- if (!workspaceId) void restoreWorkspaceEnrollments();
-}
-
-/** Everything a gateway connection's request handlers need from the host process. */
-interface GatewayHandlerContext {
- /** Present when an `agent-browser` binary enabled the browser tool on this device. */
- browser?: Awaited<ReturnType<typeof resolveBrowserDevice>>;
- /** Present when `--auv` enabled Computer Use on this device. */
- computerUse?: Awaited<ReturnType<typeof resolveComputerUseDevice>>;
- deps: DeviceControlDeps;
- error: (msg: string) => void;
- /** Read at dispatch time β€” the underlying auth may be refreshed mid-session. */
- getAuth: () => Awaited<ReturnType<typeof resolveToken>>;
- info: (msg: string) => void;
- isDaemonChild: boolean;
- maintenance: CliMaintenance;
- /** Process-wide native runtime probe, shared by every gateway connection. */
- nativeRuntimes: RuntimeProbeCache;
- recordRequest: () => void;
-}
-
-/**
- * Bind the request handlers shared by every gateway connection this process
- * owns β€” the personal connection and any workspace-share connections opened via
- * the `enrollWorkspace` RPC β€” so a workspace principal exposes exactly the same
- * tool / RPC / agent-run surface as the personal one.
- */
-function bindGatewayClientHandlers(
- client: GatewayClient,
- ctx: GatewayHandlerContext,
- connectionWorkspaceId?: string,
-) {
- const {
- browser,
- computerUse,
- deps,
- error,
- getAuth,
- info,
- isDaemonChild,
- maintenance,
- recordRequest,
- } = ctx;
-
- // Handle system info requests
- client.on('system_info_request', async (request: SystemInfoRequestMessage) => {
- info(`Received system_info_request: requestId=${request.requestId}`);
- const systemInfo = await collectSystemInfo(ctx.nativeRuntimes, computerUse, browser);
- client.sendSystemInfoResponse({
- requestId: request.requestId,
- result: { success: true, systemInfo },
- });
- });
-
- // Handle tool call requests
- client.on('tool_call_request', async (request: ToolCallRequestMessage) => {
- recordRequest();
- const { operationId, requestId, timeout, toolCall } = request;
- if (isDaemonChild) {
- appendLog(
- `[TOOL] ${toolCall.apiName}${operationId ? ` op=${operationId}` : ''} (${requestId})`,
- );
- } else {
- log.toolCall(toolCall.apiName, requestId, toolCall.arguments, operationId);
- }
-
- // Timed on the DEVICE's clock. The server can only see the whole dispatch
- // round trip, so reporting this back is what separates a slow tool from
- // slow transport.
- const startedAt = performance.now();
- const result = await executeDeviceOperation({ apiName: toolCall.apiName, operationId }, () =>
- maintenance.run(() =>
- // Computer Use's `runCommand` shares its apiName with the shell tool, and
- // the browser's apis (`click`, `screenshot`, …) are routed by identifier too.
- toolCall.identifier === COMPUTER_USE_IDENTIFIER
- ? executeComputerUseCall(computerUse, toolCall.apiName, toolCall.arguments, timeout)
- : toolCall.identifier === BROWSER_IDENTIFIER
- ? executeBrowserCall(browser, toolCall.apiName, toolCall.arguments, timeout)
- : executeToolCall(toolCall.apiName, toolCall.arguments, timeout, getAuth()),
- ),
- ).catch((err: Error) => ({
- content: '',
- error: err.message,
- state: undefined,
- success: false,
- }));
- const executionTimeMs = Math.round(performance.now() - startedAt);
-
- if (isDaemonChild) {
- appendLog(
- `[RESULT] ${result.success ? 'OK' : 'FAIL'} ${executionTimeMs}ms${operationId ? ` op=${operationId}` : ''} (${requestId})`,
- );
- } else {
- log.toolResult(requestId, result.success, result.content, operationId);
- }
-
- client.sendToolCallResponse({
- requestId,
- result: {
- content: result.content,
- error: result.error,
- executionTimeMs,
- state: result.state,
- success: result.success,
- },
- });
- });
-
- // Handle generic server-internal device RPCs (git / workspace / file ops).
- // Shares the `@lobechat/device-control` dispatcher with the desktop app so the
- // CLI exposes the same remote-device control surface.
- client.on('rpc_request', async (request: RpcRequestMessage) => {
- const { method, params, requestId } = request;
- if (isDaemonChild) appendLog(`[RPC] ${method} (${requestId})`);
- else info(`Received rpc_request: method=${method} (${requestId})`);
-
- try {
- const run = () => executeDeviceRpc(method, params, deps);
- const isMaintenance = ['getCliUpdateState', 'checkCliUpdate', 'restartCli'].includes(method);
- const data = await (isMaintenance ? run() : maintenance.run(run));
- client.sendRpcResponse({ requestId, result: { data, success: true } });
- if (method === 'restartCli') maintenance.afterResponse();
- } catch (err) {
- const message = err instanceof Error ? err.message : String(err);
- if (isDaemonChild) appendLog(`[RPC ERROR] ${method}: ${message} (${requestId})`);
- else error(`rpc_request method=${method} failed: ${message}`);
- client.sendRpcResponse({ requestId, result: { error: message, success: false } });
- }
- });
-
- // Handle gateway-dispatched agent runs (heterogeneous agents, e.g. Claude
- // Code). Mirrors the desktop app: spawn `lh hetero exec`, which owns the full
- // execution + server-ingest pipeline. Ack with the spawn outcome β€” `accepted`
- // once the child starts, `rejected` if it fails to spawn (e.g. bad cwd) β€” so
- // a failed dispatch surfaces as an error instead of a stuck assistant message.
- client.on('agent_run_request', async (request: AgentRunRequestMessage) => {
- recordRequest();
- info(
- `Received agent_run_request: operationId=${request.operationId} type=${request.agentType}`,
- );
- try {
- const ack = await maintenance.run(() =>
- spawnHeteroAgentRun(
- {
- agentId: request.agentId,
- agentType: request.agentType,
- assistantMessageId: request.assistantMessageId,
- args: request.args,
- claudeAccountRouting: request.claudeAccountRouting,
- cwd: request.cwd,
- imageList: request.imageList,
- jwt: request.jwt,
- operationId: request.operationId,
- prompt: request.prompt,
- resumeFallbackSystemContext: request.resumeFallbackSystemContext,
- resumeSessionId: request.resumeSessionId,
- serverUrl: getAuth().serverUrl,
- systemContext: request.systemContext,
- topicId: request.topicId,
- workspaceId: request.ingestWorkspaceId ?? request.workspaceId ?? connectionWorkspaceId,
- },
- { error, info },
- ),
- );
- client.sendAgentRunAck({ operationId: request.operationId, ...ack });
- } catch (err) {
- const reason = err instanceof Error ? err.message : String(err);
- error(`agent_run_request failed: ${reason}`);
- client.sendAgentRunAck({ operationId: request.operationId, reason, status: 'rejected' });
- }
- });
+ if (!workspaceId && !managed) void restoreWorkspaceEnrollments();
}
function createDaemonLogger() {
diff --git a/apps/cli/src/commands/connect/managed.ts b/apps/cli/src/commands/connect/managed.ts
new file mode 100644
index 00000000000..a0b8ad7c243
--- /dev/null
+++ b/apps/cli/src/commands/connect/managed.ts
@@ -0,0 +1,109 @@
+import type { resolveToken } from '../../auth/resolveToken';
+import {
+ MANAGED_DEVICE_SECRET_ENV,
+ type ManagedDeviceConfig,
+ type ManagedDeviceToken,
+ type ManagedTokenFatalError,
+ ManagedTokenSession,
+ readManagedDeviceConfig,
+ readManagedTokenPrincipal,
+} from '../../device/managed';
+
+interface ManagedFlagOptions {
+ daemon?: boolean;
+ deviceId?: string;
+ gateway?: string;
+ public?: boolean;
+ token?: string;
+ workspace?: string;
+}
+
+/**
+ * Flags that pick an identity, credential or gateway, which the environment
+ * owns in managed mode, plus `--daemon`: the platform supervises the agent in
+ * the foreground and restarts it when it exits.
+ */
+export function getManagedFlagConflicts(options: ManagedFlagOptions): string[] {
+ return [
+ options.token && '--token',
+ options.gateway && '--gateway',
+ options.deviceId && '--device-id',
+ options.workspace && '--workspace',
+ options.public && '--public',
+ options.daemon && '--daemon',
+ ].filter((flag): flag is string => !!flag);
+}
+
+interface ManagedDeviceEvents {
+ onFatal: (err: ManagedTokenFatalError) => void;
+ onToken: (token: ManagedDeviceToken) => void;
+}
+
+export interface ManagedDeviceStart {
+ auth: Awaited<ReturnType<typeof resolveToken>>;
+ config: ManagedDeviceConfig;
+ /** Assigned once the gateway client exists. */
+ events: ManagedDeviceEvents;
+ principal: ReturnType<typeof readManagedTokenPrincipal>;
+ session: ManagedTokenSession;
+}
+
+/**
+ * Read the managed device environment and get the first gateway token. Exits
+ * with status 1 when the environment is incomplete or the server gives a final
+ * answer (401 bad secret, 404 no managed devices); keeps retrying 5xx and
+ * network failures.
+ */
+export async function startManagedDevice(logger: {
+ debug: (msg: string) => void;
+ error: (msg: string) => void;
+ info: (msg: string) => void;
+}): Promise<ManagedDeviceStart> {
+ const read = readManagedDeviceConfig();
+ if (!read.ok) {
+ logger.error(read.message);
+ process.exit(1);
+ throw new Error('process.exit');
+ }
+ const { config } = read;
+ // Keep the secret out of the environment that tool calls and agent runs
+ // inherit. Processes of the same user can still read the environment this
+ // process started with.
+ delete process.env[MANAGED_DEVICE_SECRET_ENV];
+
+ const events: ManagedDeviceEvents = {
+ onFatal: () => {},
+ onToken: () => {},
+ };
+ const session = new ManagedTokenSession({
+ config,
+ logger: {
+ debug: logger.debug,
+ warn: logger.info,
+ },
+ onFatal: (err) => events.onFatal(err),
+ onToken: (token) => events.onToken(token),
+ });
+
+ try {
+ const token = await session.start();
+ const principal = readManagedTokenPrincipal(token.token);
+ return {
+ auth: {
+ serverUrl: config.serverUrl,
+ token: token.token,
+ tokenType: 'jwt',
+ userId: principal.userId ?? principal.workspaceId,
+ },
+ config,
+ events,
+ principal,
+ session,
+ };
+ } catch (err) {
+ session.stop();
+ logger.error((err as Error).message);
+ process.exit(1);
+ throw new Error('process.exit', { cause: err });
+ }
+}
diff --git a/apps/cli/src/device/activityHook.test.ts b/apps/cli/src/device/activityHook.test.ts
new file mode 100644
index 00000000000..e0082f82bac
--- /dev/null
+++ b/apps/cli/src/device/activityHook.test.ts
@@ -0,0 +1,188 @@
+import { EventEmitter } from 'node:events';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ActivityReporter } from './activityHook';
+
+const spawn = vi.hoisted(() => vi.fn());
+vi.mock('node:child_process', () => ({ spawn }));
+
+class FakeChild extends EventEmitter {
+ kill = vi.fn(() => true);
+ unref = vi.fn();
+}
+
+describe('ActivityReporter', () => {
+ let children: FakeChild[];
+ let debug: ReturnType<typeof vi.fn>;
+ let busy: boolean;
+
+ const createReporter = () =>
+ new ActivityReporter({
+ command: ['report', '--device', 'dev 1'],
+ isBusy: () => busy,
+ logger: { debug },
+ });
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ children = [];
+ busy = false;
+ debug = vi.fn();
+ spawn.mockReset().mockImplementation(() => {
+ const child = new FakeChild();
+ children.push(child);
+ return child;
+ });
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ const finishAll = (code = 0) => {
+ for (const child of children) child.emit('exit', code, null);
+ };
+
+ it('runs the command without a shell when work starts', () => {
+ const reporter = createReporter();
+ reporter.begin();
+ expect(spawn).toHaveBeenCalledWith(
+ 'report',
+ ['--device', 'dev 1'],
+ expect.objectContaining({ shell: false }),
+ );
+ });
+
+ it('runs at most once per 30 s however much work arrives', () => {
+ const reporter = createReporter();
+ reporter.begin()();
+ finishAll();
+ reporter.begin()();
+ vi.advanceTimersByTime(29_999);
+ reporter.begin()();
+ expect(spawn).toHaveBeenCalledTimes(1);
+
+ vi.advanceTimersByTime(1);
+ reporter.begin()();
+ expect(spawn).toHaveBeenCalledTimes(2);
+ });
+
+ it('never runs two at a time', () => {
+ const reporter = createReporter();
+ reporter.begin();
+ vi.advanceTimersByTime(5000);
+ expect(children[0].kill).not.toHaveBeenCalled();
+ // Still running after the interval: skip rather than stack a second one.
+ vi.setSystemTime(Date.now() + 30_000);
+ reporter.begin();
+ expect(spawn).toHaveBeenCalledTimes(1);
+ });
+
+ it('kills a hook that hangs, logging at debug level', () => {
+ const reporter = createReporter();
+ reporter.begin();
+ vi.advanceTimersByTime(10_000);
+ expect(children[0].kill).toHaveBeenCalledWith('SIGKILL');
+ expect(debug).toHaveBeenCalledWith(expect.stringContaining('killed it'));
+ });
+
+ it('re-reports every 30 s while work continues, then goes quiet', () => {
+ const reporter = createReporter();
+ reporter.start();
+ const end = reporter.begin();
+ finishAll();
+
+ vi.advanceTimersByTime(30_000);
+ expect(spawn).toHaveBeenCalledTimes(2);
+ finishAll();
+
+ end();
+ vi.advanceTimersByTime(90_000);
+ expect(spawn).toHaveBeenCalledTimes(2);
+ reporter.stop();
+ });
+
+ it('keeps runs about 30 s apart when work starts between two checks', () => {
+ const reporter = createReporter();
+ reporter.start();
+ vi.advanceTimersByTime(12_000);
+ reporter.begin();
+ finishAll();
+
+ // 30 s after the first run, not at the next 30 s boundary of the ticker.
+ vi.advanceTimersByTime(29_999);
+ expect(spawn).toHaveBeenCalledTimes(1);
+ vi.advanceTimersByTime(5000);
+ expect(spawn).toHaveBeenCalledTimes(2);
+ reporter.stop();
+ });
+
+ it('reports polled work (agent runs, tunnels) on the interval', () => {
+ const reporter = createReporter();
+ reporter.start();
+ vi.advanceTimersByTime(30_000);
+ expect(spawn).not.toHaveBeenCalled();
+
+ busy = true;
+ vi.advanceTimersByTime(30_000);
+ expect(spawn).toHaveBeenCalledTimes(1);
+ reporter.stop();
+ });
+
+ it('logs failures at debug level only and never throws into the work', () => {
+ spawn.mockImplementationOnce(() => {
+ throw new Error('EACCES');
+ });
+ const reporter = createReporter();
+ expect(() => reporter.begin()).not.toThrow();
+ expect(debug).toHaveBeenCalledWith('Activity command could not start: EACCES');
+
+ vi.advanceTimersByTime(30_000);
+ reporter.begin();
+ children[0].emit('error', new Error('spawn report ENOENT'));
+ expect(debug).toHaveBeenCalledWith('Activity command failed: spawn report ENOENT');
+
+ vi.advanceTimersByTime(30_000);
+ reporter.begin();
+ children[1].emit('exit', 3, null);
+ expect(debug).toHaveBeenCalledWith('Activity command exited with 3');
+ });
+
+ it('kills a running hook and clears its kill timer on stop', () => {
+ const reporter = createReporter();
+ reporter.start();
+ reporter.begin();
+ expect(vi.getTimerCount()).toBe(2);
+
+ reporter.stop();
+ expect(children[0].kill).toHaveBeenCalledWith('SIGKILL');
+ expect(vi.getTimerCount()).toBe(0);
+
+ // The killed child settling later is ignored.
+ expect(() => {
+ children[0].emit('exit', null, 'SIGKILL');
+ children[0].emit('error', new Error('late'));
+ }).not.toThrow();
+ expect(debug).not.toHaveBeenCalled();
+ });
+
+ it('runs nothing after stop', () => {
+ const reporter = createReporter();
+ reporter.stop();
+ reporter.start();
+ busy = true;
+ reporter.begin();
+ vi.advanceTimersByTime(60_000);
+ expect(spawn).not.toHaveBeenCalled();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('stops cleanly when no hook is running', () => {
+ const reporter = createReporter();
+ reporter.begin();
+ finishAll();
+ reporter.stop();
+ expect(children[0].kill).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/cli/src/device/activityHook.ts b/apps/cli/src/device/activityHook.ts
new file mode 100644
index 00000000000..4a5d69e8d3d
--- /dev/null
+++ b/apps/cli/src/device/activityHook.ts
@@ -0,0 +1,126 @@
+import { type ChildProcess, spawn } from 'node:child_process';
+
+/** The hook runs at most once per this interval, however much work arrives. */
+const ACTIVITY_REPORT_INTERVAL_MS = 30_000;
+
+/**
+ * How often ongoing work is checked, as a share of the interval. Checking more
+ * often than the interval keeps the gap between two runs close to 30 s instead
+ * of up to twice that when work starts between two checks.
+ */
+const ACTIVITY_CHECKS_PER_INTERVAL = 6;
+
+/** A hook still running after this long is killed so it cannot pile up. */
+const ACTIVITY_COMMAND_TIMEOUT_MS = 10_000;
+
+export interface ActivityReporterOptions {
+ /** The program and its arguments, run without a shell. */
+ command: readonly string[];
+ /** Work the reporter cannot see through `begin()`: agent runs, tunnels, shells. */
+ isBusy?: () => boolean;
+ logger: { debug: (msg: string) => void };
+}
+
+/**
+ * Report "this device is doing work" to the platform by running a configured
+ * command. Runs when work starts, then every interval while work continues;
+ * never more than once per interval, never two at a time, never awaited by the
+ * work itself. Failures are logged at debug level only.
+ */
+export class ActivityReporter {
+ private active = 0;
+ /** The hook run in progress and the timer that kills it if it hangs. */
+ private current: { child: ChildProcess; killTimer: ReturnType<typeof setTimeout> } | undefined;
+ private lastRunAt: number | undefined;
+ private stopped = false;
+ private ticker: ReturnType<typeof setInterval> | undefined;
+
+ constructor(private readonly options: ActivityReporterOptions) {}
+
+ /** Mark one unit of work as started; call the returned function when it ends. */
+ begin(): () => void {
+ this.active++;
+ this.report();
+ return () => {
+ this.active--;
+ };
+ }
+
+ isBusy(): boolean {
+ if (this.active > 0) return true;
+ try {
+ return this.options.isBusy?.() ?? false;
+ } catch {
+ return false;
+ }
+ }
+
+ /** Re-report once per interval while work is still running. */
+ start(): void {
+ if (this.ticker || this.stopped) return;
+ this.ticker = setInterval(() => {
+ if (this.isBusy()) this.report();
+ }, ACTIVITY_REPORT_INTERVAL_MS / ACTIVITY_CHECKS_PER_INTERVAL);
+ this.ticker.unref?.();
+ }
+
+ /** Stop reporting and kill a hook that is still running. */
+ stop(): void {
+ this.stopped = true;
+ if (this.ticker) clearInterval(this.ticker);
+ this.ticker = undefined;
+ const current = this.current;
+ this.current = undefined;
+ if (!current) return;
+ clearTimeout(current.killTimer);
+ try {
+ current.child.kill('SIGKILL');
+ } catch {
+ // Best effort: the hook may already have exited.
+ }
+ }
+
+ private report(): void {
+ const now = Date.now();
+ if (this.stopped || this.current) return;
+ if (this.lastRunAt !== undefined && now - this.lastRunAt < ACTIVITY_REPORT_INTERVAL_MS) return;
+ this.lastRunAt = now;
+
+ const { debug } = this.options.logger;
+ const [file, ...args] = this.options.command;
+ let child: ChildProcess;
+ try {
+ child = spawn(file, args, { shell: false, stdio: 'ignore', windowsHide: true });
+ } catch (err) {
+ debug(`Activity command could not start: ${(err as Error).message}`);
+ return;
+ }
+
+ const killTimer = setTimeout(() => {
+ debug(`Activity command ran longer than ${ACTIVITY_COMMAND_TIMEOUT_MS}ms, killed it`);
+ child.kill('SIGKILL');
+ }, ACTIVITY_COMMAND_TIMEOUT_MS);
+ killTimer.unref?.();
+ const current = { child, killTimer };
+ this.current = current;
+
+ let settled = false;
+ /** True the first time this run ends, unless `stop()` already ended it. */
+ const settle = () => {
+ if (settled) return false;
+ settled = true;
+ clearTimeout(killTimer);
+ if (this.current !== current) return false;
+ this.current = undefined;
+ return true;
+ };
+ child.on('error', (err: Error) => {
+ if (settle()) debug(`Activity command failed: ${err.message}`);
+ });
+ child.on('exit', (code: number | null, signal?: NodeJS.Signals | null) => {
+ if (!settle()) return;
+ if (code !== 0) debug(`Activity command exited with ${code ?? signal ?? 'unknown status'}`);
+ });
+ child.unref();
+ }
+}
diff --git a/apps/cli/src/device/managed.test.ts b/apps/cli/src/device/managed.test.ts
new file mode 100644
index 00000000000..27d1329e401
--- /dev/null
+++ b/apps/cli/src/device/managed.test.ts
@@ -0,0 +1,475 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ exchangeManagedDeviceToken,
+ getManagedTokenRefreshDelay,
+ getManagedTokenRetryDelay,
+ ManagedTokenFatalError,
+ ManagedTokenSession,
+ readManagedDeviceConfig,
+ readManagedTokenPrincipal,
+} from './managed';
+
+const jwt = (payload: Record<string, unknown>) =>
+ `h.${Buffer.from(JSON.stringify(payload)).toString('base64url')}.s`;
+
+const fetchMock = vi.fn<typeof fetch>();
+
+beforeEach(() => {
+ fetchMock.mockReset();
+ vi.stubGlobal('fetch', fetchMock);
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+const NOT_A_SERVICE_URL =
+ 'is not a valid service URL: it must use https (http only for a loopback address) and have no user name, password, query or fragment.';
+
+const FULL_ENV = {
+ LOBEHUB_DEVICE_GATEWAY_URL: 'https://gateway.example.com/',
+ LOBEHUB_MANAGED_DEVICE_ID: 'device-1',
+ LOBEHUB_MANAGED_DEVICE_SECRET: 'top-secret',
+ LOBEHUB_SERVER: 'https://app.example.com/',
+};
+
+describe('readManagedDeviceConfig', () => {
+ it('reads every variable and trims trailing slashes from URLs', () => {
+ expect(
+ readManagedDeviceConfig({
+ ...FULL_ENV,
+ LOBEHUB_DEVICE_ACTIVITY_COMMAND: '["my-agent","touch","--device","a b"]',
+ }),
+ ).toEqual({
+ config: {
+ activityCommand: ['my-agent', 'touch', '--device', 'a b'],
+ deviceId: 'device-1',
+ gatewayUrl: 'https://gateway.example.com',
+ secret: 'top-secret',
+ serverUrl: 'https://app.example.com',
+ },
+ ok: true,
+ });
+ });
+
+ it('names every missing variable', () => {
+ const result = readManagedDeviceConfig({
+ LOBEHUB_MANAGED_DEVICE_ID: 'device-1',
+ LOBEHUB_SERVER: ' ',
+ });
+ expect(result.ok).toBe(false);
+ expect(!result.ok && result.message).toBe(
+ '--managed needs these environment variables, which are not set: LOBEHUB_MANAGED_DEVICE_SECRET, LOBEHUB_SERVER, LOBEHUB_DEVICE_GATEWAY_URL.',
+ );
+ });
+
+ it('rejects a non-http URL without printing any value', () => {
+ const result = readManagedDeviceConfig({ ...FULL_ENV, LOBEHUB_SERVER: 'ftp://top-secret' });
+ expect(result).toEqual({
+ message: `LOBEHUB_SERVER ${NOT_A_SERVICE_URL}`,
+ ok: false,
+ });
+ });
+
+ it('rejects plain http to a remote host', () => {
+ const result = readManagedDeviceConfig({
+ ...FULL_ENV,
+ LOBEHUB_DEVICE_GATEWAY_URL: 'http://gateway.example.com',
+ });
+ expect(result).toEqual({
+ message: `LOBEHUB_DEVICE_GATEWAY_URL ${NOT_A_SERVICE_URL}`,
+ ok: false,
+ });
+ });
+
+ it.each([
+ 'http://localhost:3010',
+ 'http://127.0.0.1:3010',
+ 'http://127.0.0.2:3010',
+ 'http://[::1]:3010',
+ ])('accepts plain http to a loopback address (%s)', (server) => {
+ expect(readManagedDeviceConfig({ ...FULL_ENV, LOBEHUB_SERVER: server })).toMatchObject({
+ config: { serverUrl: server },
+ ok: true,
+ });
+ });
+
+ it.each([
+ 'http://localhost.evil.com',
+ 'http://127.0.0.1.nip.io',
+ 'http://128.0.0.1',
+ 'http://[::2]',
+ ])('rejects plain http to a host that only looks local (%s)', (server) => {
+ expect(readManagedDeviceConfig({ ...FULL_ENV, LOBEHUB_SERVER: server })).toEqual({
+ message: `LOBEHUB_SERVER ${NOT_A_SERVICE_URL}`,
+ ok: false,
+ });
+ });
+
+ it.each([
+ 'https://user:[email protected]',
+ 'https://:[email protected]',
+ 'https://[email protected]',
+ ])('rejects a URL with a user name or password without printing it (%s)', (server) => {
+ const result = readManagedDeviceConfig({ ...FULL_ENV, LOBEHUB_SERVER: server });
+ expect(result).toEqual({
+ message: `LOBEHUB_SERVER ${NOT_A_SERVICE_URL}`,
+ ok: false,
+ });
+ expect(JSON.stringify(result)).not.toContain('hunter2');
+ });
+
+ it.each(['https://app.example.com/?a=1', 'https://app.example.com/#a'])(
+ 'rejects a URL with a query or fragment (%s)',
+ (gateway) => {
+ expect(readManagedDeviceConfig({ ...FULL_ENV, LOBEHUB_DEVICE_GATEWAY_URL: gateway })).toEqual(
+ {
+ message: `LOBEHUB_DEVICE_GATEWAY_URL ${NOT_A_SERVICE_URL}`,
+ ok: false,
+ },
+ );
+ },
+ );
+
+ it('keeps a path prefix and normalizes the URL', () => {
+ expect(
+ readManagedDeviceConfig({
+ ...FULL_ENV,
+ LOBEHUB_DEVICE_GATEWAY_URL: 'https://Gateway.Example.com:443/gw//',
+ LOBEHUB_SERVER: 'https://app.example.com/lobe/',
+ }),
+ ).toMatchObject({
+ config: {
+ gatewayUrl: 'https://gateway.example.com/gw',
+ serverUrl: 'https://app.example.com/lobe',
+ },
+ ok: true,
+ });
+ });
+
+ it.each(['my-agent touch', '[]', '[""]', '["my-agent", 1]', '{"0":"my-agent"}', '"my-agent"'])(
+ 'rejects an activity command that is not a JSON array of strings (%s)',
+ (command) => {
+ const result = readManagedDeviceConfig({
+ ...FULL_ENV,
+ LOBEHUB_DEVICE_ACTIVITY_COMMAND: command,
+ });
+ expect(result).toEqual({
+ message: 'LOBEHUB_DEVICE_ACTIVITY_COMMAND is not a JSON array of non-empty strings.',
+ ok: false,
+ });
+ },
+ );
+
+ it('never puts the secret in a failure message', () => {
+ const result = readManagedDeviceConfig({ ...FULL_ENV, LOBEHUB_DEVICE_GATEWAY_URL: undefined });
+ expect(JSON.stringify(result)).not.toContain('top-secret');
+ });
+});
+
+const CONFIG = {
+ deviceId: 'device-1',
+ secret: 'top-secret',
+ serverUrl: 'https://app.example.com',
+};
+
+describe('exchangeManagedDeviceToken', () => {
+ const call = (response: Response | Error) => {
+ if (response instanceof Error) fetchMock.mockRejectedValueOnce(response);
+ else fetchMock.mockResolvedValueOnce(response);
+ return exchangeManagedDeviceToken(CONFIG);
+ };
+
+ it('posts the device id and secret to the token route', async () => {
+ vi.spyOn(Date, 'now').mockReturnValue(1000);
+ const result = await call(
+ Response.json({ expiresAt: '2030-01-01T00:00:00.000Z', token: 'tok' }),
+ );
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ 'https://app.example.com/api/device/managed/token',
+ expect.objectContaining({
+ body: JSON.stringify({ deviceId: 'device-1', secret: 'top-secret' }),
+ method: 'POST',
+ }),
+ );
+ expect(result).toEqual({
+ expiresAt: Date.parse('2030-01-01T00:00:00.000Z'),
+ issuedAt: 1000,
+ status: 'issued',
+ token: 'tok',
+ });
+ });
+
+ it('keeps the path prefix of the server URL in the token URL', async () => {
+ fetchMock.mockResolvedValueOnce(new Response('{}', { status: 500 }));
+ await exchangeManagedDeviceToken({ ...CONFIG, serverUrl: 'https://app.example.com/lobe' });
+ expect(fetchMock).toHaveBeenCalledWith(
+ 'https://app.example.com/lobe/api/device/managed/token',
+ expect.anything(),
+ );
+ });
+
+ it('measures the lifetime on the server clock when the server sends Date', async () => {
+ const response = Response.json(
+ { expiresAt: '2030-01-01T01:00:00.000Z', token: 'tok' },
+ { headers: { Date: 'Tue, 01 Jan 2030 00:00:00 GMT' } },
+ );
+ const result = await call(response);
+ expect(result).toMatchObject({ issuedAt: Date.parse('2030-01-01T00:00:00.000Z') });
+ // A local clock far ahead of the server still refreshes at 80% of an hour.
+ expect(getManagedTokenRefreshDelay(result as any)).toBe(2_880_000);
+ });
+
+ it.each([
+ [401, { status: 'invalid-credentials' }],
+ [404, { status: 'unavailable' }],
+ [400, { httpStatus: 400, status: 'rejected' }],
+ [413, { httpStatus: 413, status: 'rejected' }],
+ [429, { reason: 'HTTP 429', status: 'retryable' }],
+ [500, { reason: 'HTTP 500', status: 'retryable' }],
+ [503, { reason: 'HTTP 503', status: 'retryable' }],
+ ])('maps HTTP %i', async (status, expected) => {
+ expect(await call(new Response('{}', { status }))).toEqual(expected);
+ });
+
+ it('retries a network error', async () => {
+ expect(await call(new TypeError('fetch failed'))).toEqual({
+ reason: 'fetch failed',
+ status: 'retryable',
+ });
+ });
+
+ it.each([
+ '2030-01-01T00:00:00',
+ '2030-01-01',
+ 'Tue, 01 Jan 2030 00:00:00 GMT',
+ 1_893_456_000_000,
+ ])('retries an expiresAt that is not RFC 3339 with an offset (%s)', async (expiresAt) => {
+ expect(await call(Response.json({ expiresAt, token: 'tok' }))).toEqual({
+ reason: 'the response has no token or expiresAt',
+ status: 'retryable',
+ });
+ });
+
+ it('accepts an expiresAt with a numeric offset', async () => {
+ expect(
+ await call(Response.json({ expiresAt: '2030-01-01T08:00:00+08:00', token: 'tok' })),
+ ).toMatchObject({ expiresAt: Date.parse('2030-01-01T00:00:00.000Z'), status: 'issued' });
+ });
+
+ it.each([
+ ['missing', {}],
+ ['invalid', { Date: 'not a date' }],
+ ])('uses the local clock when the Date header is %s', async (_, headers) => {
+ vi.spyOn(Date, 'now').mockReturnValue(1234);
+ const response = Response.json(
+ { expiresAt: '2030-01-01T00:00:00.000Z', token: 'tok' },
+ { headers },
+ );
+ expect(await call(response)).toMatchObject({ issuedAt: 1234, status: 'issued' });
+ });
+
+ it('retries an unreadable 200 body', async () => {
+ expect(await call(new Response('<html>', { status: 200 }))).toMatchObject({
+ status: 'retryable',
+ });
+ expect(await call(Response.json({ token: 'tok' }))).toMatchObject({ status: 'retryable' });
+ });
+});
+
+describe('readManagedTokenPrincipal', () => {
+ it('uses workspace_id for a workspace device', () => {
+ expect(readManagedTokenPrincipal(jwt({ sub: 'ws-1', workspace_id: 'ws-1' }))).toEqual({
+ workspaceId: 'ws-1',
+ });
+ });
+
+ it('uses sub for a personal device', () => {
+ expect(readManagedTokenPrincipal(jwt({ sub: 'user-1' }))).toEqual({ userId: 'user-1' });
+ });
+
+ it('throws on a token without a principal', () => {
+ expect(() => readManagedTokenPrincipal(jwt({}))).toThrow(/no sub or workspace_id/);
+ expect(() => readManagedTokenPrincipal('not-a-jwt')).toThrow(/not a JWT/);
+ });
+});
+
+describe('refresh and retry delays', () => {
+ it('refreshes at 80% of the lifetime, at least 5 s', () => {
+ expect(getManagedTokenRefreshDelay({ expiresAt: 3_600_000, issuedAt: 0, token: 't' })).toBe(
+ 2_880_000,
+ );
+ expect(getManagedTokenRefreshDelay({ expiresAt: 1000, issuedAt: 0, token: 't' })).toBe(5000);
+ expect(getManagedTokenRefreshDelay({ expiresAt: 0, issuedAt: 1000, token: 't' })).toBe(5000);
+ });
+
+ it('treats a lifetime above 24 h as malformed and refreshes after 5 min', () => {
+ const day = 24 * 60 * 60 * 1000;
+ expect(getManagedTokenRefreshDelay({ expiresAt: day, issuedAt: 0, token: 't' })).toBe(
+ day * 0.8,
+ );
+ expect(getManagedTokenRefreshDelay({ expiresAt: day + 1, issuedAt: 0, token: 't' })).toBe(
+ 300_000,
+ );
+ expect(
+ getManagedTokenRefreshDelay({ expiresAt: Number.MAX_SAFE_INTEGER, issuedAt: 0, token: 't' }),
+ ).toBe(300_000);
+ });
+
+ it('doubles from 1 s to a 60 s cap with Β±20% jitter', () => {
+ const random = vi.spyOn(Math, 'random').mockReturnValue(0.5);
+ expect([1, 2, 3, 6, 7, 20].map((n) => getManagedTokenRetryDelay(n))).toEqual([
+ 1000, 2000, 4000, 32_000, 60_000, 60_000,
+ ]);
+ random.mockReturnValue(0);
+ expect(getManagedTokenRetryDelay(1)).toBe(800);
+ random.mockReturnValue(1);
+ expect(getManagedTokenRetryDelay(1)).toBe(1200);
+ });
+});
+
+describe('ManagedTokenSession', () => {
+ const HOUR = 3_600_000;
+ let onToken: ReturnType<typeof vi.fn>;
+ let onFatal: ReturnType<typeof vi.fn>;
+
+ // The token route's answers, one per call. The token lives one hour from
+ // the moment it is fetched.
+ const issued = (token: string) => async () =>
+ Response.json({ expiresAt: new Date(Date.now() + HOUR).toISOString(), token });
+ const httpStatus = (status: number) => async () => new Response('{}', { status });
+ const networkError = async () => {
+ throw new TypeError('fetch failed');
+ };
+
+ const createSession = () =>
+ new ManagedTokenSession({
+ config: CONFIG,
+ logger: { debug: vi.fn(), warn: vi.fn() },
+ onFatal,
+ onToken,
+ });
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.spyOn(Math, 'random').mockReturnValue(0.5);
+ onToken = vi.fn();
+ onFatal = vi.fn();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('refreshes at 80% of the lifetime and keeps doing so', async () => {
+ fetchMock
+ .mockImplementationOnce(issued('t1'))
+ .mockImplementationOnce(issued('t2'))
+ .mockImplementationOnce(issued('t3'));
+ const session = createSession();
+
+ expect((await session.start()).token).toBe('t1');
+ expect(onToken).not.toHaveBeenCalled();
+
+ await vi.advanceTimersByTimeAsync(0.8 * HOUR - 1);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(onToken).toHaveBeenLastCalledWith(expect.objectContaining({ token: 't2' }));
+
+ await vi.advanceTimersByTimeAsync(0.8 * HOUR);
+ expect(onToken).toHaveBeenLastCalledWith(expect.objectContaining({ token: 't3' }));
+ session.stop();
+ });
+
+ it('retries 5xx and network failures with backoff', async () => {
+ fetchMock
+ .mockImplementationOnce(httpStatus(503))
+ .mockImplementationOnce(networkError)
+ .mockImplementationOnce(issued('t1'));
+ const session = createSession();
+ const started = session.start();
+
+ await vi.advanceTimersByTimeAsync(999);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ await vi.advanceTimersByTimeAsync(1999);
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ // es-toolkit's retry waits one more 0 ms timer between two attempts.
+ await vi.advanceTimersByTimeAsync(2);
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+ expect((await started).token).toBe('t1');
+ session.stop();
+ });
+
+ it('rejects start on a 401 without retrying', async () => {
+ fetchMock.mockImplementation(httpStatus(401));
+ const session = createSession();
+
+ await expect(session.start()).rejects.toBeInstanceOf(ManagedTokenFatalError);
+ await vi.advanceTimersByTimeAsync(HOUR);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('reports a 401 during a scheduled refresh through onFatal', async () => {
+ fetchMock.mockImplementationOnce(issued('t1')).mockImplementation(httpStatus(401));
+ const session = createSession();
+ await session.start();
+
+ await vi.advanceTimersByTimeAsync(0.8 * HOUR);
+ expect(onFatal).toHaveBeenCalledTimes(1);
+ expect(onFatal.mock.calls[0][0].message).toContain('HTTP 401');
+ expect(onToken).not.toHaveBeenCalled();
+ });
+
+ it('keeps retrying a failing scheduled refresh until the server answers', async () => {
+ fetchMock
+ .mockImplementationOnce(issued('t1'))
+ .mockImplementationOnce(httpStatus(500))
+ .mockImplementationOnce(httpStatus(500))
+ .mockImplementationOnce(issued('t2'));
+ const session = createSession();
+ await session.start();
+
+ // Plus a few ms: es-toolkit's retry waits a 0 ms timer between attempts.
+ await vi.advanceTimersByTimeAsync(0.8 * HOUR + 1000 + 2000 + 10);
+ expect(fetchMock).toHaveBeenCalledTimes(4);
+ expect(onToken).toHaveBeenCalledWith(expect.objectContaining({ token: 't2' }));
+ expect(onFatal).not.toHaveBeenCalled();
+ session.stop();
+ });
+
+ it('refreshNow replaces the scheduled refresh and shares one exchange', async () => {
+ fetchMock.mockImplementationOnce(issued('t1')).mockImplementationOnce(issued('t2'));
+ const session = createSession();
+ await session.start();
+
+ const [a, b] = await Promise.all([session.refreshNow(), session.refreshNow()]);
+ expect(a.token).toBe('t2');
+ expect(b.token).toBe('t2');
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+
+ // The old schedule is gone; the next refresh is 80% after t2.
+ fetchMock.mockImplementationOnce(issued('t3'));
+ await vi.advanceTimersByTimeAsync(0.8 * HOUR);
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+ session.stop();
+ });
+
+ it('stops retrying once stopped', async () => {
+ fetchMock.mockImplementation(httpStatus(500));
+ const session = createSession();
+ const started = session.start();
+ await vi.advanceTimersByTimeAsync(0);
+
+ session.stop();
+ // Rejects during the backoff wait, without any timer advancing.
+ await expect(started).rejects.toThrow(/stopped/);
+ expect(vi.getTimerCount()).toBe(0);
+ await vi.advanceTimersByTimeAsync(HOUR);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/cli/src/device/managed.ts b/apps/cli/src/device/managed.ts
new file mode 100644
index 00000000000..e0ca8e9dcdd
--- /dev/null
+++ b/apps/cli/src/device/managed.ts
@@ -0,0 +1,423 @@
+/**
+ * `lh connect --managed`: the agent of a managed cloud device. The platform
+ * that runs the device injects its identity and a bootstrap secret through the
+ * environment; the agent trades the secret for a short-lived gateway token and
+ * keeps that token fresh for as long as it runs. Nothing is read from or
+ * written to the stored login.
+ */
+
+import { BlockList, isIP } from 'node:net';
+
+import dayjs from 'dayjs';
+import { delay, retry } from 'es-toolkit';
+import { z } from 'zod';
+
+const MANAGED_DEVICE_ID_ENV = 'LOBEHUB_MANAGED_DEVICE_ID';
+export const MANAGED_DEVICE_SECRET_ENV = 'LOBEHUB_MANAGED_DEVICE_SECRET';
+const MANAGED_SERVER_ENV = 'LOBEHUB_SERVER';
+export const MANAGED_GATEWAY_ENV = 'LOBEHUB_DEVICE_GATEWAY_URL';
+const DEVICE_ACTIVITY_COMMAND_ENV = 'LOBEHUB_DEVICE_ACTIVITY_COMMAND';
+
+const MANAGED_TOKEN_PATH = 'api/device/managed/token';
+
+/** Refresh when this share of the token's lifetime has passed. */
+const MANAGED_TOKEN_REFRESH_RATIO = 0.8;
+/** Never schedule a refresh sooner than this, even for a nearly expired token. */
+const MANAGED_TOKEN_MIN_REFRESH_DELAY_MS = 5000;
+/** A longer lifetime is malformed; the server issues 1 h tokens. */
+const MANAGED_TOKEN_MAX_LIFETIME_MS = 24 * 60 * 60 * 1000;
+/** Refresh delay used for a token whose lifetime is malformed. */
+const MANAGED_TOKEN_FALLBACK_REFRESH_DELAY_MS = 5 * 60 * 1000;
+const MANAGED_TOKEN_RETRY_INITIAL_DELAY_MS = 1000;
+const MANAGED_TOKEN_RETRY_MAX_DELAY_MS = 60_000;
+const MANAGED_TOKEN_REQUEST_TIMEOUT_MS = 15_000;
+
+export interface ManagedDeviceConfig {
+ /** The program and its arguments, run without a shell. */
+ activityCommand?: string[];
+ deviceId: string;
+ gatewayUrl: string;
+ secret: string;
+ serverUrl: string;
+}
+
+export type ManagedDeviceConfigResult =
+ { config: ManagedDeviceConfig; ok: true } | { message: string; ok: false };
+
+const NOT_A_SERVICE_URL =
+ 'is not a valid service URL: it must use https (http only for a loopback address) and have no user name, password, query or fragment.';
+
+const LOOPBACK_ADDRESSES = new BlockList();
+LOOPBACK_ADDRESSES.addSubnet('127.0.0.0', 8, 'ipv4');
+LOOPBACK_ADDRESSES.addSubnet('::1', 128, 'ipv6');
+
+/** `localhost`, or an IP address in 127.0.0.0/8 or ::1. `hostname` is `URL.hostname`. */
+const isLoopbackHost = (hostname: string): boolean => {
+ if (hostname === 'localhost') return true;
+ const address = hostname.replace(/^\[(.*)]$/, '$1');
+ const family = isIP(address);
+ if (family === 0) return false;
+ return LOOPBACK_ADDRESSES.check(address, family === 4 ? 'ipv4' : 'ipv6');
+};
+
+/**
+ * An https URL, or an http one to a loopback address; the secret and tokens
+ * travel over it. A user name or password is rejected because a request to
+ * such a URL fails with an error that repeats it. Returns the origin plus the
+ * path without a trailing slash, so a path prefix is kept.
+ */
+const parseServiceUrl = (value: string): string | undefined => {
+ let url: URL;
+ try {
+ url = new URL(value);
+ } catch {
+ return undefined;
+ }
+ if (url.username || url.password) return undefined;
+ if (url.search || url.hash) return undefined;
+ const secure =
+ url.protocol === 'https:' || (url.protocol === 'http:' && isLoopbackHost(url.hostname));
+ if (!secure) return undefined;
+ return `${url.origin}${url.pathname.replace(/\/+$/, '')}`;
+};
+
+/** The program and its arguments, for example `["my-agent","touch"]`. */
+const activityCommandSchema = z.array(z.string().min(1)).min(1);
+
+/** A non-empty JSON array of non-empty strings, else `undefined`. */
+const parseActivityCommand = (value: string): string[] | undefined => {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(value);
+ } catch {
+ return undefined;
+ }
+ const result = activityCommandSchema.safeParse(parsed);
+ return result.success ? result.data : undefined;
+};
+
+/**
+ * Read the managed device settings from the environment. The message of a
+ * failure names the variables only β€” never a value, so the secret cannot leak.
+ */
+export function readManagedDeviceConfig(
+ env: NodeJS.ProcessEnv = process.env,
+): ManagedDeviceConfigResult {
+ const read = (name: string) => env[name]?.trim() || undefined;
+
+ const deviceId = read(MANAGED_DEVICE_ID_ENV);
+ const secret = read(MANAGED_DEVICE_SECRET_ENV);
+ const server = read(MANAGED_SERVER_ENV);
+ const gateway = read(MANAGED_GATEWAY_ENV);
+
+ const missing = [
+ !deviceId && MANAGED_DEVICE_ID_ENV,
+ !secret && MANAGED_DEVICE_SECRET_ENV,
+ !server && MANAGED_SERVER_ENV,
+ !gateway && MANAGED_GATEWAY_ENV,
+ ].filter((name): name is string => !!name);
+ if (missing.length > 0) {
+ return {
+ message: `--managed needs these environment variables, which are not set: ${missing.join(', ')}.`,
+ ok: false,
+ };
+ }
+
+ const serverUrl = parseServiceUrl(server!);
+ if (!serverUrl) {
+ return { message: `${MANAGED_SERVER_ENV} ${NOT_A_SERVICE_URL}`, ok: false };
+ }
+ const gatewayUrl = parseServiceUrl(gateway!);
+ if (!gatewayUrl) {
+ return { message: `${MANAGED_GATEWAY_ENV} ${NOT_A_SERVICE_URL}`, ok: false };
+ }
+
+ const rawActivityCommand = read(DEVICE_ACTIVITY_COMMAND_ENV);
+ const activityCommand = rawActivityCommand ? parseActivityCommand(rawActivityCommand) : undefined;
+ if (rawActivityCommand && !activityCommand) {
+ return {
+ message: `${DEVICE_ACTIVITY_COMMAND_ENV} is not a JSON array of non-empty strings.`,
+ ok: false,
+ };
+ }
+
+ return {
+ config: {
+ activityCommand,
+ deviceId: deviceId!,
+ gatewayUrl,
+ secret: secret!,
+ serverUrl,
+ },
+ ok: true,
+ };
+}
+
+export interface ManagedDeviceToken {
+ /** Epoch milliseconds, server clock. */
+ expiresAt: number;
+ /**
+ * Epoch milliseconds at which the server answered, server clock (its `Date`
+ * header, else this machine's clock), so `expiresAt - issuedAt` is the
+ * lifetime even when the two clocks disagree.
+ */
+ issuedAt: number;
+ token: string;
+}
+
+export type ManagedTokenExchangeResult =
+ | ({ status: 'issued' } & ManagedDeviceToken)
+ /** 401: the secret is wrong or the device was deleted. */
+ | { status: 'invalid-credentials' }
+ /** 404: this server has no managed cloud devices. */
+ | { status: 'unavailable' }
+ /** Any other 4xx: the request itself is wrong, so a retry cannot help. */
+ | { httpStatus: number; status: 'rejected' }
+ /** 408, 429, 5xx, a network error or an unreadable body. */
+ | { reason: string; status: 'retryable' };
+
+/** The token route's 200 body. `expiresAt` is RFC 3339 with a `Z` or an offset. */
+const managedTokenResponseSchema = z.object({
+ expiresAt: z.iso.datetime({ offset: true }),
+ token: z.string().min(1),
+});
+
+export async function exchangeManagedDeviceToken({
+ deviceId,
+ secret,
+ serverUrl,
+}: Pick<
+ ManagedDeviceConfig,
+ 'deviceId' | 'secret' | 'serverUrl'
+>): Promise<ManagedTokenExchangeResult> {
+ let response: Response;
+ try {
+ // Relative to the server URL with a trailing slash, so a path prefix is kept.
+ response = await fetch(new URL(MANAGED_TOKEN_PATH, `${serverUrl}/`).href, {
+ body: JSON.stringify({ deviceId, secret }),
+ headers: { 'Content-Type': 'application/json' },
+ method: 'POST',
+ signal: AbortSignal.timeout(MANAGED_TOKEN_REQUEST_TIMEOUT_MS),
+ });
+ } catch (err) {
+ return { reason: (err as Error).message || 'network error', status: 'retryable' };
+ }
+
+ if (response.status === 401) return { status: 'invalid-credentials' };
+ if (response.status === 404) return { status: 'unavailable' };
+ if (response.status === 408 || response.status === 429 || response.status >= 500) {
+ return { reason: `HTTP ${response.status}`, status: 'retryable' };
+ }
+ if (!response.ok) return { httpStatus: response.status, status: 'rejected' };
+
+ let body: unknown;
+ try {
+ body = await response.json();
+ } catch {
+ return { reason: 'the response is not JSON', status: 'retryable' };
+ }
+ const parsed = managedTokenResponseSchema.safeParse(body);
+ if (!parsed.success) {
+ return { reason: 'the response has no token or expiresAt', status: 'retryable' };
+ }
+
+ const dateHeader = response.headers.get('date');
+ const serverDate = dateHeader ? dayjs(dateHeader) : undefined;
+ return {
+ expiresAt: dayjs(parsed.data.expiresAt).valueOf(),
+ issuedAt: serverDate?.isValid() ? serverDate.valueOf() : Date.now(),
+ status: 'issued',
+ token: parsed.data.token,
+ };
+}
+
+/**
+ * Which gateway principal the token belongs to. A workspace device's token
+ * carries `workspace_id`; otherwise `sub` is the owning user.
+ */
+export function readManagedTokenPrincipal(
+ token: string,
+): { userId: string; workspaceId?: undefined } | { userId?: undefined; workspaceId: string } {
+ let payload: { sub?: unknown; workspace_id?: unknown };
+ try {
+ payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString());
+ } catch {
+ throw new Error('The managed device token is not a JWT.');
+ }
+ if (typeof payload.workspace_id === 'string' && payload.workspace_id) {
+ return { workspaceId: payload.workspace_id };
+ }
+ if (typeof payload.sub === 'string' && payload.sub) return { userId: payload.sub };
+ throw new Error('The managed device token has no sub or workspace_id claim.');
+}
+
+/**
+ * Delay before refreshing a token: 80% of its lifetime, at least 5 s. A
+ * lifetime above 24 h is malformed and gets the 5 min fallback, which also
+ * keeps the delay inside the range `setTimeout` accepts.
+ */
+export function getManagedTokenRefreshDelay(token: ManagedDeviceToken): number {
+ const lifetime = token.expiresAt - token.issuedAt;
+ if (lifetime > MANAGED_TOKEN_MAX_LIFETIME_MS) return MANAGED_TOKEN_FALLBACK_REFRESH_DELAY_MS;
+ return Math.max(MANAGED_TOKEN_MIN_REFRESH_DELAY_MS, lifetime * MANAGED_TOKEN_REFRESH_RATIO);
+}
+
+/** Retry delay after `attempt` failures (1-based): 1 s doubling to 60 s, Β±20% jitter. */
+export function getManagedTokenRetryDelay(attempt: number) {
+ const base = Math.min(
+ MANAGED_TOKEN_RETRY_MAX_DELAY_MS,
+ MANAGED_TOKEN_RETRY_INITIAL_DELAY_MS * 2 ** (attempt - 1),
+ );
+ return Math.round(base * (0.8 + 0.4 * Math.random()));
+}
+
+type FatalExchangeResult = Exclude<ManagedTokenExchangeResult, { status: 'issued' | 'retryable' }>;
+
+/** A token exchange answer that retrying cannot change. */
+export class ManagedTokenFatalError extends Error {
+ constructor(result: FatalExchangeResult) {
+ super(describeFatalResult(result));
+ this.name = 'ManagedTokenFatalError';
+ }
+}
+
+/** A token exchange answer that a later attempt may change: 408, 429, 5xx, network. */
+class ManagedTokenRetryableError extends Error {
+ constructor(readonly reason: string) {
+ super(reason);
+ this.name = 'ManagedTokenRetryableError';
+ }
+}
+
+function describeFatalResult(result: FatalExchangeResult): string {
+ switch (result.status) {
+ case 'invalid-credentials': {
+ return `The server rejected ${MANAGED_DEVICE_ID_ENV} / ${MANAGED_DEVICE_SECRET_ENV} (HTTP 401).`;
+ }
+ case 'unavailable': {
+ return 'This server does not offer managed cloud devices (HTTP 404).';
+ }
+ case 'rejected': {
+ return `The server rejected the managed device token request (HTTP ${result.httpStatus}).`;
+ }
+ }
+}
+
+export interface ManagedTokenSessionOptions {
+ config: Pick<ManagedDeviceConfig, 'deviceId' | 'secret' | 'serverUrl'>;
+ logger: { debug: (msg: string) => void; warn: (msg: string) => void };
+ /** A background refresh got an answer that retrying cannot change. */
+ onFatal: (error: ManagedTokenFatalError) => void;
+ /** A new token arrived, from a scheduled refresh or `refreshNow()`. */
+ onToken: (token: ManagedDeviceToken) => void;
+}
+
+/**
+ * Owns the managed device's gateway token: gets the first one, refreshes it
+ * at 80% of its lifetime, and retries 5xx / network failures with backoff
+ * until the server answers. A 401, 404 or other 4xx is final.
+ */
+export class ManagedTokenSession {
+ /** Aborted by `stop()`; ends a pending retry wait at once. */
+ private readonly abort = new AbortController();
+ private inFlight: Promise<ManagedDeviceToken> | undefined;
+ private timer: ReturnType<typeof setTimeout> | undefined;
+
+ constructor(private readonly options: ManagedTokenSessionOptions) {}
+
+ /** Get the first token and schedule its refresh. Rejects only on a final answer. */
+ async start(): Promise<ManagedDeviceToken> {
+ const token = await this.obtain();
+ this.schedule(token);
+ return token;
+ }
+
+ /** Get a new token now (e.g. the gateway rejected the current one). */
+ async refreshNow(): Promise<ManagedDeviceToken> {
+ this.clearTimer();
+ const token = await this.obtain();
+ this.options.onToken(token);
+ this.schedule(token);
+ return token;
+ }
+
+ stop(): void {
+ this.abort.abort();
+ this.clearTimer();
+ }
+
+ private schedule(token: ManagedDeviceToken) {
+ this.clearTimer();
+ if (this.abort.signal.aborted) return;
+ const refreshDelay = getManagedTokenRefreshDelay(token);
+ this.options.logger.debug(
+ `Scheduled managed device token refresh in ${Math.round(refreshDelay / 1000)}s`,
+ );
+ this.timer = setTimeout(() => {
+ this.timer = undefined;
+ this.refreshNow().catch((err) => {
+ if (err instanceof ManagedTokenFatalError) this.options.onFatal(err);
+ });
+ }, refreshDelay);
+ this.timer.unref?.();
+ }
+
+ private clearTimer() {
+ if (this.timer) clearTimeout(this.timer);
+ this.timer = undefined;
+ }
+
+ /** One exchange at a time; concurrent callers share it. */
+ private obtain(): Promise<ManagedDeviceToken> {
+ this.inFlight ??= this.exchangeWithRetry().finally(() => {
+ this.inFlight = undefined;
+ });
+ return this.inFlight;
+ }
+
+ private async exchangeWithRetry(): Promise<ManagedDeviceToken> {
+ const { signal } = this.abort;
+ // es-toolkit's `retry` checks `signal` only before an attempt and does not
+ // pass it to its own wait, so a stop during a 60 s backoff would hang
+ // until the wait ended. The backoff therefore runs at the start of the
+ // next attempt, through `delay`, which rejects as soon as `signal` aborts.
+ let backoff = 0;
+ try {
+ return await retry(
+ async () => {
+ if (backoff > 0) await delay(backoff, { signal });
+ const result = await exchangeManagedDeviceToken(this.options.config);
+ switch (result.status) {
+ case 'issued': {
+ const { expiresAt, issuedAt, token } = result;
+ return { expiresAt, issuedAt, token };
+ }
+ case 'retryable': {
+ throw new ManagedTokenRetryableError(result.reason);
+ }
+ default: {
+ throw new ManagedTokenFatalError(result);
+ }
+ }
+ },
+ {
+ // `attempts` counts from 0, so the first backoff is about 1 s.
+ delay: (attempts, error) => {
+ backoff = getManagedTokenRetryDelay(attempts + 1);
+ this.options.logger.warn(
+ `Could not get a managed device token (${(error as ManagedTokenRetryableError).reason}); retrying in ${Math.round(backoff / 1000)}s`,
+ );
+ return 0;
+ },
+ shouldRetry: (error) => error instanceof ManagedTokenRetryableError,
+ signal,
+ },
+ );
+ } catch (err) {
+ if (signal.aborted) {
+ throw new Error('The managed device token session was stopped.', { cause: err });
+ }
+ throw err;
+ }
+ }
+}
diff --git a/apps/desktop/pnpm-lock.yaml b/apps/desktop/pnpm-lock.yaml
index e053344f145..865d66388d6 100644
--- a/apps/desktop/pnpm-lock.yaml
+++ b/apps/desktop/pnpm-lock.yaml
@@ -882,6 +882,9 @@ importers:
diff:
specifier: ^8.0.4
version: 8.0.4
+ es-toolkit:
+ specifier: ^1.50.0
+ version: 1.52.0
fast-glob:
specifier: ^3.3.3
version: 3.3.3
diff --git a/packages/device-gateway-client/src/client.test.ts b/packages/device-gateway-client/src/client.test.ts
index f6e4aaeafbb..c0cf5b6c7c9 100644
--- a/packages/device-gateway-client/src/client.test.ts
+++ b/packages/device-gateway-client/src/client.test.ts
@@ -639,6 +639,19 @@ describe('GatewayClient', () => {
expect(closeAll).toHaveBeenCalledWith('DEVICE_DISCONNECTED');
});
+ it('reports the tunnel host active count, and 0 when serving is off', () => {
+ vi.spyOn((client as any).tunnelHost, 'activeCount', 'get').mockReturnValue(2);
+ expect(client.activeTunnelCount).toBe(2);
+
+ const offClient = new GatewayClient({
+ autoReconnect: false,
+ gatewayUrl: 'https://gateway.test.com',
+ token: 'tok',
+ tunnel: false,
+ });
+ expect(offClient.activeTunnelCount).toBe(0);
+ });
+
it('answers tunnel_open with TUNNEL_DISABLED when serving is off', async () => {
const offClient = new GatewayClient({
autoReconnect: false,
diff --git a/packages/device-gateway-client/src/client.ts b/packages/device-gateway-client/src/client.ts
index c9a1e58768a..39f94dc2ce2 100644
--- a/packages/device-gateway-client/src/client.ts
+++ b/packages/device-gateway-client/src/client.ts
@@ -181,6 +181,11 @@ export class GatewayClient extends EventEmitter {
return this.deviceId;
}
+ /** Tunnel HTTP requests and WebSockets this device is serving right now. */
+ get activeTunnelCount(): number {
+ return this.tunnelHost?.activeCount ?? 0;
+ }
+
get currentConnectionId(): string {
return this.connectionId;
}