🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(cli): support --workspace in connect service install (#20818)
Rdmclin29b7c8921183e
diff --git a/apps/cli/src/auth/apiKey.test.ts b/apps/cli/src/auth/apiKey.test.tsnew file mode 100644index 00000000000..d67b65f3009--- /dev/null+++ b/apps/cli/src/auth/apiKey.test.ts@@ -0,0 +1,43 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import { getUserIdFromApiKey } from './apiKey';++afterEach(() => vi.restoreAllMocks());++describe('API key validation', () => {+ it.each([+ { status: 503, body: '<html>unavailable</html>', retryable: true },+ { status: 429, body: '{"error":"rate limited"}', retryable: true },+ { status: 401, body: '{"error":"invalid key"}', retryable: false },+ { status: 403, body: '<html>forbidden</html>', retryable: false },+ { status: 200, body: 'invalid JSON', retryable: true },+ { status: 200, body: '{}', retryable: true },+ { status: 200, body: '{"success":false}', retryable: false },+ ])('classifies HTTP $status ($body)', async ({ status, body, retryable }) => {+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(body, { status }));+ await expect(getUserIdFromApiKey('fixture-key', 'http://localhost:1234')).rejects.toMatchObject(+ {+ name: 'ApiKeyValidationError',+ retryable,+ },+ );+ });++ it('classifies a network failure as retryable', async () => {+ vi.spyOn(globalThis, 'fetch').mockRejectedValue(new TypeError('fetch failed'));+ await expect(getUserIdFromApiKey('fixture-key', 'http://localhost:1234')).rejects.toMatchObject(+ {+ name: 'ApiKeyValidationError',+ message: 'fetch failed',+ retryable: true,+ },+ );+ });++ it('returns the current user for a valid API key', async () => {+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(Response.json({ data: { id: 'user-1' } }));+ await expect(getUserIdFromApiKey('fixture-key', 'http://localhost:1234')).resolves.toBe(+ 'user-1',+ );+ });+});diff --git a/apps/cli/src/auth/apiKey.ts b/apps/cli/src/auth/apiKey.tsindex 7b53adb9e7a..6ea344744b1 100644--- a/apps/cli/src/auth/apiKey.ts+++ b/apps/cli/src/auth/apiKey.ts@@ -10,33 +10,51 @@ interface CurrentUserResponse {success?: boolean;}+export class ApiKeyValidationError extends Error {+ constructor(+ message: string,+ readonly retryable: boolean,+ ) {+ super(message);+ this.name = 'ApiKeyValidationError';+ }+}+export async function getUserIdFromApiKey(apiKey: string, serverUrl?: string): Promise<string> {const normalizedServerUrl = normalizeUrl(serverUrl) || resolveServerUrl();- const response = await fetch(`${normalizedServerUrl}/api/v1/users/me?includeCount=0`, {- headers: {- Authorization: `Bearer ${apiKey}`,- },- });+ let response: Response;+ try {+ response = await fetch(`${normalizedServerUrl}/api/v1/users/me?includeCount=0`, {+ headers: {+ Authorization: `Bearer ${apiKey}`,+ },+ });+ } catch (error) {+ throw new ApiKeyValidationError(error instanceof Error ? error.message : String(error), true);+ }+ const retryableStatus = response.status >= 500 || [408, 425, 429].includes(response.status);let body: CurrentUserResponse | undefined;try {body = (await response.json()) as CurrentUserResponse;} catch {- throw new Error(+ throw new ApiKeyValidationError(`Failed to parse response from ${normalizedServerUrl}/api/v1/users/me?includeCount=0.`,+ response.ok || retryableStatus,);}if (!response.ok || body?.success === false) {- throw new Error(+ throw new ApiKeyValidationError(body?.error || body?.message || `Request failed with status ${response.status}.`,+ retryableStatus,);}const userId = body?.data?.id || body?.data?.userId;if (!userId) {- throw new Error('Current user response did not include a user id.');+ throw new ApiKeyValidationError('Current user response did not include a user id.', true);}return userId;diff --git a/apps/cli/src/auth/resolveToken.test.ts b/apps/cli/src/auth/resolveToken.test.tsindex d178058f637..25f8e4820b2 100644--- a/apps/cli/src/auth/resolveToken.test.ts+++ b/apps/cli/src/auth/resolveToken.test.ts@@ -1,12 +1,14 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { log } from '../utils/logger';-import { getUserIdFromApiKey } from './apiKey';+import type * as ApiKeyModule from './apiKey';+import { ApiKeyValidationError, getUserIdFromApiKey } from './apiKey';import type * as RefreshModule from './refresh';import { getValidToken } from './refresh';import { resolveToken } from './resolveToken';-vi.mock('./apiKey', () => ({+vi.mock('./apiKey', async (importOriginal) => ({+ ...(await importOriginal<typeof ApiKeyModule>()),getUserIdFromApiKey: vi.fn(),}));vi.mock('./refresh', async (importOriginal) => ({@@ -99,6 +101,24 @@ describe('resolveToken', () => {});describe('with environment api key', () => {+ it.each([+ { retryable: true, override: 75, expected: 75 },+ { retryable: false, override: 75, expected: 1 },+ { retryable: true, override: undefined, expected: 1 },+ ])(+ 'uses exit $expected with retryable=$retryable and policy=$override',+ async ({ retryable, override, expected }) => {+ process.env.LOBEHUB_CLI_API_KEY = 'fixture-key';+ vi.mocked(getUserIdFromApiKey).mockRejectedValueOnce(+ new ApiKeyValidationError('controlled failure', retryable),+ );+ await expect(resolveToken({ unavailableExitCode: override })).rejects.toThrow(+ 'process.exit',+ );+ expect(exitSpy).toHaveBeenCalledWith(expected);+ },+ );+it('should return API key from environment', async () => {process.env.LOBEHUB_CLI_API_KEY = 'sk-lh-test';vi.mocked(getUserIdFromApiKey).mockResolvedValue('user-789');@@ -130,6 +150,21 @@ describe('resolveToken', () => {});describe('with stored credentials', () => {+ it.each([+ { status: 'unavailable', exitCode: 75 },+ { status: 'spent', exitCode: 1 },+ { status: 'refused', exitCode: 1 },+ { status: 'no-login', exitCode: 1 },+ ] as const)(+ 'uses exit $exitCode for $status with a retry policy',+ async ({ status, exitCode }) => {+ vi.mocked(getValidToken).mockResolvedValue({ detail: 'controlled failure', status });++ await expect(resolveToken({ unavailableExitCode: 75 })).rejects.toThrow('process.exit');+ expect(exitSpy).toHaveBeenCalledWith(exitCode);+ },+ );+it('should return stored credentials token', async () => {const token = makeJwt('stored-user');vi.mocked(getValidToken).mockResolvedValue({diff --git a/apps/cli/src/auth/resolveToken.ts b/apps/cli/src/auth/resolveToken.tsindex 22bcce58962..23f3a95d80f 100644--- a/apps/cli/src/auth/resolveToken.ts+++ b/apps/cli/src/auth/resolveToken.ts@@ -2,13 +2,15 @@ import { CLI_API_KEY_ENV } from '../constants/auth';import { CLI_PRIMARY_BIN } from '../constants/identity';import { resolveServerUrl } from '../settings';import { log } from '../utils/logger';-import { getUserIdFromApiKey } from './apiKey';+import { ApiKeyValidationError, getUserIdFromApiKey } from './apiKey';import { describeTokenLookup, getValidToken } from './refresh';import { pickAuthSource } from './source';interface ResolveTokenOptions {serviceToken?: string;token?: string;+ /** Override the exit status for transient credential validation or refresh failures. */+ unavailableExitCode?: number;userId?: string;}@@ -85,7 +87,11 @@ export async function resolveToken(options: ResolveTokenOptions): Promise<Resolv} catch (error) {const message = error instanceof Error ? error.message : String(error);log.error(`Failed to validate ${source.origin}: ${message}`);- process.exit(1);+ process.exit(+ error instanceof ApiKeyValidationError && error.retryable+ ? (options.unavailableExitCode ?? 1)+ : 1,+ );}}}@@ -112,5 +118,5 @@ export async function resolveToken(options: ResolveTokenOptions): Promise<Resolv? `${report.detail} ${report.fix}`: `No authentication found. Run '${CLI_PRIMARY_BIN} login' first, or set ${CLI_API_KEY_ENV}, or provide --token.`,);- process.exit(1);+ process.exit(result.status === 'unavailable' ? (options.unavailableExitCode ?? 1) : 1);}diff --git a/apps/cli/src/commands/connect.test.ts b/apps/cli/src/commands/connect.test.tsindex 19b73917b0d..8dfd68090de 100644--- a/apps/cli/src/commands/connect.test.ts+++ b/apps/cli/src/commands/connect.test.ts@@ -14,10 +14,17 @@ import { log, setVerbose } from '../utils/logger';import { registerConnectCommand } from './connect';const registerDeviceMock = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));+const mintWorkspaceConnectTokenMock = vi.hoisted(() => vi.fn());+const registerWorkspaceDeviceMock = vi.hoisted(() => vi.fn());vi.mock('../device/register', async (importOriginal) => {const actual = await importOriginal<typeof DeviceRegister>();- return { ...actual, registerDevice: registerDeviceMock };+ return {+ ...actual,+ mintWorkspaceConnectToken: mintWorkspaceConnectTokenMock,+ registerDevice: registerDeviceMock,+ registerWorkspaceDevice: registerWorkspaceDeviceMock,+ };});vi.mock('../auth/refresh', async (importOriginal) => ({@@ -258,6 +265,58 @@ describe('connect command', () => {expect(exitSpy).toHaveBeenCalledWith(1);});+ it('exits with a retryable code when the workspace token mint fails transiently', async () => {+ mintWorkspaceConnectTokenMock.mockRejectedValueOnce(new Error('fetch failed'));++ const program = createProgram();+ await expect(+ program.parseAsync(['node', 'test', 'connect', '--workspace', 'ws_1']),+ ).rejects.toThrow('process.exit');+ expect(exitSpy).toHaveBeenCalledWith(75);+ });++ it('exits without retry when the server refuses the workspace token mint', async () => {+ mintWorkspaceConnectTokenMock.mockRejectedValueOnce(+ Object.assign(new Error('forbidden'), { data: { code: 'FORBIDDEN' } }),+ );++ const program = createProgram();+ await expect(+ program.parseAsync(['node', 'test', 'connect', '--workspace', 'ws_1']),+ ).rejects.toThrow('process.exit');+ expect(exitSpy).toHaveBeenCalledWith(1);+ });++ it.each([+ { error: new Error('fetch failed'), exitCode: 75, reason: 'fails transiently' },+ {+ error: Object.assign(new Error('forbidden'), { data: { code: 'FORBIDDEN' } }),+ exitCode: 1,+ reason: 'is refused by the server',+ },+ ])('exits with $exitCode when workspace registration $reason', async ({ error, exitCode }) => {+ mintWorkspaceConnectTokenMock.mockResolvedValueOnce({ token: 'workspace-token' });+ registerWorkspaceDeviceMock.mockRejectedValueOnce(error);+ exitSpy.mockImplementation(() => {+ throw new Error('process.exit');+ });++ await expect(+ createProgram().parseAsync([+ 'node',+ 'test',+ 'connect',+ '--service-child',+ '--workspace',+ 'ws_1',+ ]),+ ).rejects.toThrow('process.exit');++ expect(registerWorkspaceDeviceMock).toHaveBeenCalledOnce();+ expect(exitSpy).toHaveBeenCalledWith(exitCode);+ expect(connectCalled).toBe(false);+ });+it('should use explicit gateway for custom login server', async () => {vi.mocked(loadSettings).mockReturnValueOnce({ serverUrl: 'https://self-hosted.example.com' });@@ -392,6 +451,38 @@ describe('connect command', () => {expect(exitSpy).not.toHaveBeenCalled();});+ describe.each(['auth_failed', 'auth_expired'] as const)('%s workspace refresh', (event) => {+ it.each([+ { error: new Error('fetch failed'), exitCode: 75, reason: 'a transient outage' },+ {+ error: Object.assign(new Error('forbidden'), { data: { code: 'FORBIDDEN' } }),+ exitCode: 1,+ reason: 'a server refusal',+ },+ ])('exits with $exitCode after $reason', async ({ error, exitCode }) => {+ mintWorkspaceConnectTokenMock.mockResolvedValueOnce({ token: 'workspace-token' });+ registerWorkspaceDeviceMock.mockResolvedValueOnce(undefined);+ await createProgram().parseAsync([+ 'node',+ 'test',+ 'connect',+ '--service-child',+ '--workspace',+ 'ws_1',+ ]);+ expect(connectCalled).toBe(true);+ mintWorkspaceConnectTokenMock.mockRejectedValueOnce(error);++ await clientEventHandlers[event]?.('token expired');++ expect(exitSpy).toHaveBeenCalledWith(exitCode);+ expect(cleanupAllProcesses).toHaveBeenCalledOnce();+ const client = vi.mocked(GatewayClient).mock.results[0].value;+ expect(client.disconnect).toHaveBeenCalledOnce();+ expect(client.reconnect).not.toHaveBeenCalled();+ });+ });+it('should ignore auth_expired for api key auth', async () => {vi.mocked(resolveToken).mockResolvedValueOnce({serverUrl: 'https://self-hosted.example.com',diff --git a/apps/cli/src/commands/connect.ts b/apps/cli/src/commands/connect.tsindex 7359d2074d9..ea1215aff15 100644--- a/apps/cli/src/commands/connect.ts+++ b/apps/cli/src/commands/connect.ts@@ -58,6 +58,8 @@ import {} from '../device/register';import { TerminalSessionManager } from '../device/terminal';import {+ CONNECT_RETRYABLE_EXIT_CODE,+ getWorkspaceFailureExitCode,installConnectService,readConnectServiceStatus,restartConnectService,@@ -94,7 +96,7 @@ interface ConnectOptions {serviceChild?: boolean;token?: string;verbose?: boolean;- /** Enroll this machine as a device of the given workspace (admin only). */+ /** Enroll this machine as a device of the given workspace (workspace members). */workspace?: string;}@@ -105,7 +107,7 @@ export function registerConnectCommand(program: Command) {.option('--token <jwt>', 'JWT access token').option('--gateway <url>', 'Device gateway URL').option('--device-id <id>', 'Device ID (auto-generated if not provided)')- .option('--workspace <id>', 'Enroll as a device of this workspace (admin only)')+ .option('--workspace <id>', 'Enroll as a device of this workspace (workspace members)').option('--public','With --workspace: enroll into the shared pool visible to every member (default: private, visible only to you)',@@ -202,9 +204,18 @@ export function registerConnectCommand(program: Command) {serviceCmd.command('install').description('Install and start the Linux user systemd connect service')- .action(() => {- installConnectService();- log.info(`Installed and started ${CONNECT_SERVICE_NAME}.`);+ .option('--workspace <id>', 'Enroll as a device of this workspace (workspace members)')+ .option(+ '--public',+ 'With --workspace: enroll into the shared pool visible to every member (default: private, visible only to you)',+ )+ .action((options: Pick<ConnectOptions, 'public' | 'workspace'>) => {+ installConnectService({ public: options.public, workspace: options.workspace });+ log.info(+ options.workspace+ ? `Installed and started ${CONNECT_SERVICE_NAME} for workspace ${options.workspace}.`+ : `Installed and started ${CONNECT_SERVICE_NAME}.`,+ );log.info("Run 'lh connect service status' to inspect the service.");});@@ -327,7 +338,8 @@ function buildDaemonArgs(options: ConnectOptions): string[] {}async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {- let auth = await resolveToken(options);+ const unavailableExitCode = options.workspace ? CONNECT_RETRYABLE_EXIT_CODE : undefined;+ let auth = await resolveToken({ ...options, unavailableExitCode });const settings = loadSettings();const gatewayUrl = normalizeUrl(options.gateway) || settings?.gatewayUrl;@@ -364,14 +376,20 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {let connectToken = auth.token;let connectTokenType: 'apiKey' | 'jwt' | 'serviceToken' = auth.tokenType;if (workspaceId) {- const minted = await mintWorkspaceConnectToken(auth, workspaceId);- connectToken = minted.token;+ try {+ const minted = await mintWorkspaceConnectToken(auth, workspaceId);+ connectToken = minted.token;+ } catch (err) {+ log.error(`Workspace connect token mint failed: ${(err as Error).message}`);+ process.exit(getWorkspaceFailureExitCode(err));+ throw new Error('process.exit', { cause: err });+ }connectTokenType = 'jwt';}// Re-resolve the admin auth and, for workspace mode, re-mint the connect token.const refreshConnectToken = async (): Promise<string | undefined> => {- const refreshed = await resolveToken({});+ const refreshed = await resolveToken({ unavailableExitCode });if (!refreshed) return undefined;auth = refreshed;if (workspaceId) {@@ -763,6 +781,7 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {// (e.g., auto-reconnect may send an expired JWT before proactive refresh fires)let authFailedRefreshAttempted = false;client.on('auth_failed', async (reason) => {+ let exitCode = 1;if (connectTokenType === 'jwt' && !authFailedRefreshAttempted) {authFailedRefreshAttempted = true;info(`Authentication failed (${reason}). Attempting token refresh...`);@@ -777,8 +796,9 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {await client.reconnect();return;}- } catch {- // fall through+ } catch (err) {+ error(`Token refresh failed: ${(err as Error).message}`);+ if (workspaceId) exitCode = getWorkspaceFailureExitCode(err);}}@@ -787,7 +807,7 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {`Run '${CLI_PRIMARY_BIN} login', or set ${CLI_API_KEY_ENV} and run '${CLI_PRIMARY_BIN} login --server <url>' to configure API key authentication.`,);cleanup();- process.exit(1);+ process.exit(exitCode);});// Handle auth expired — refresh token and reconnect automatically@@ -798,6 +818,7 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {}info('Authentication expired. Attempting to refresh token...');+ let exitCode = 1;try {const newToken = await refreshConnectToken();@@ -808,13 +829,14 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {await client.reconnect();return;}- } catch {- // refresh failed — fall through+ } catch (err) {+ error(`Token refresh failed: ${(err as Error).message}`);+ if (workspaceId) exitCode = getWorkspaceFailureExitCode(err);}error("Could not refresh token. Run 'lh login' to re-authenticate.");cleanup();- process.exit(1);+ process.exit(exitCode);});// Another `lh connect` of this install (same persisted connection id) took@@ -892,7 +914,7 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {if (workspaceId) {error(`Workspace device registration failed: ${(err as Error).message}`);cleanup();- process.exit(1);+ process.exit(getWorkspaceFailureExitCode(err));}error(`Device registration failed (non-fatal): ${(err as Error).message}`);}diff --git a/apps/cli/src/service/connect.test.ts b/apps/cli/src/service/connect.test.tsindex b81b09e3e98..959106b4872 100644--- a/apps/cli/src/service/connect.test.ts+++ b/apps/cli/src/service/connect.test.ts@@ -4,7 +4,13 @@ import path from 'node:path';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { installConnectService, readConnectServiceStatus, startConnectService } from './connect';+import {+ CONNECT_RETRYABLE_EXIT_CODE,+ getWorkspaceFailureExitCode,+ installConnectService,+ readConnectServiceStatus,+ startConnectService,+} from './connect';const tmpDir = path.join(os.tmpdir(), `lobehub-connect-service-test-${process.pid}`);const unitDir = path.join(tmpDir, 'systemd-user');@@ -107,7 +113,21 @@ describe('connect service', () => {`EnvironmentFile=${path.join(tmpDir, '.lobehub', 'connect-service.env')}`,);expect(systemctlCalls).toContainEqual(['--user', 'daemon-reload']);- expect(systemctlCalls).toContainEqual(['--user', 'enable', '--now', 'lobehub-connect.service']);+ expect(systemctlCalls).toContainEqual(['--user', 'enable', 'lobehub-connect.service']);+ expect(systemctlCalls).toContainEqual(['--user', 'restart', 'lobehub-connect.service']);+ });++ it('passes workspace enrollment flags to the service child', () => {+ installConnectService({ public: true, workspace: 'ws_123' });++ expect(fs.readFileSync(path.join(unitDir, 'lobehub-connect.service'), 'utf8')).toContain(+ `"${process.execPath}" "${fs.realpathSync(entryPath)}" "connect" "--service-child" "--workspace" "ws_123" "--public"`,+ );+ });++ it('rejects --public without --workspace', () => {+ expect(() => installConnectService({ public: true })).toThrow('--public requires --workspace.');+ expect(fs.existsSync(path.join(unitDir, 'lobehub-connect.service'))).toBe(false);});it('does not install when a managed connect daemon is already running', () => {@@ -117,12 +137,7 @@ describe('connect service', () => {'Background connect daemon is already running (PID 12345).',);expect(fs.existsSync(path.join(unitDir, 'lobehub-connect.service'))).toBe(false);- expect(systemctlCalls).not.toContainEqual([- '--user',- 'enable',- '--now',- 'lobehub-connect.service',- ]);+ expect(systemctlCalls).not.toContainEqual(['--user', 'enable', 'lobehub-connect.service']);});it('does not install when no auth is available', () => {@@ -130,12 +145,7 @@ describe('connect service', () => {expect(() => installConnectService()).toThrow("No authentication found. Run 'lh login' first");expect(fs.existsSync(path.join(unitDir, 'lobehub-connect.service'))).toBe(false);- expect(systemctlCalls).not.toContainEqual([- '--user',- 'enable',- '--now',- 'lobehub-connect.service',- ]);+ expect(systemctlCalls).not.toContainEqual(['--user', 'enable', 'lobehub-connect.service']);});it('writes the current environment to a service-scoped env file', () => {@@ -174,4 +184,31 @@ describe('connect service', () => {);expect(systemctlCalls).toContainEqual(['--user', 'start', 'lobehub-connect.service']);});++ describe('getWorkspaceFailureExitCode', () => {+ it('lets systemd retry transient workspace startup failures', () => {+ expect(getWorkspaceFailureExitCode(new Error('fetch failed'))).toBe(+ CONNECT_RETRYABLE_EXIT_CODE,+ );+ expect(getWorkspaceFailureExitCode({ data: { code: 'INTERNAL_SERVER_ERROR' } })).toBe(+ CONNECT_RETRYABLE_EXIT_CODE,+ );+ });++ it('stops on server refusals that a restart cannot fix', () => {+ expect(getWorkspaceFailureExitCode({ data: { code: 'CONFLICT' } })).toBe(1);+ expect(getWorkspaceFailureExitCode({ data: { code: 'FORBIDDEN' } })).toBe(1);+ });++ it('keeps the retryable code outside the unit success exit statuses', () => {+ installConnectService({ workspace: 'ws_123' });+ const unit = fs.readFileSync(path.join(unitDir, 'lobehub-connect.service'), 'utf8');+ const successCodes = unit.match(/^SuccessExitStatus=(.*)$/m)![1].split(' ');+ expect(successCodes).not.toContain(String(CONNECT_RETRYABLE_EXIT_CODE));+ expect(unit).toContain('Restart=on-failure');+ // A start-rate limit would stop the retries after a burst of failures.+ expect(unit).toContain('StartLimitIntervalSec=0');+ expect(unit).not.toContain('StartLimitBurst');+ });+ });});diff --git a/apps/cli/src/service/connect.ts b/apps/cli/src/service/connect.tsindex 9172757e474..f2bbbfc7198 100644--- a/apps/cli/src/service/connect.ts+++ b/apps/cli/src/service/connect.ts@@ -17,6 +17,34 @@ const SERVICE_NAME = CLI_CONNECT_SERVICE_NAME;const ENV_NAME_PATTERN = /^[A-Z_]\w*$/i;const SERVICE_ENV_FILE_NAME = 'connect-service.env';+/**+ * Exit code for workspace failures worth retrying (EX_TEMPFAIL). It sits outside the+ * unit's `SuccessExitStatus`, so `Restart=on-failure` restarts the service child.+ */+export const CONNECT_RETRYABLE_EXIT_CODE = 75;++// Server refusals that a restart cannot fix; retrying them would only loop.+const PERMANENT_TRPC_ERROR_CODES = new Set([+ 'BAD_REQUEST',+ 'CONFLICT',+ 'FORBIDDEN',+ 'NOT_FOUND',+ 'UNAUTHORIZED',+]);++/** Exit code for a failed workspace operation (token mint, refresh, device registration): 1 for refusals, 75 otherwise. */+export function getWorkspaceFailureExitCode(error: unknown): number {+ const code = (error as { data?: { code?: string } } | null)?.data?.code;+ return code && PERMANENT_TRPC_ERROR_CODES.has(code) ? 1 : CONNECT_RETRYABLE_EXIT_CODE;+}++export interface ConnectServiceOptions {+ /** With `workspace`: enroll into the shared pool visible to every member. */+ public?: boolean;+ /** Enroll this machine as a device of the given workspace (workspace members). */+ workspace?: string;+}+export interface ConnectServiceStatus {active: boolean;enabled: boolean;@@ -60,7 +88,14 @@ function getExecErrorMessage(error: unknown): string {return error instanceof Error ? error.message : String(error);}-function renderUnit(): string {+function buildServiceConnectArgs(options: ConnectServiceOptions): string[] {+ const args = ['connect', '--service-child'];+ if (options.workspace) args.push('--workspace', options.workspace);+ if (options.public) args.push('--public');+ return args;+}++function renderUnit(options: ConnectServiceOptions): string {const quoteSystemdValue = (value: string): string =>`"${value.replaceAll('\\', '\\\\').replaceAll('"', '\\"')}"`;const escapeSystemdEnvValue = (value: string): string =>@@ -70,7 +105,7 @@ function renderUnit(): string {const logPath = path.join(cliHomeDir, 'daemon.log');const envFilePath = getServiceEnvFilePath();const scriptPath = fs.realpathSync(process.argv[1]!);- const execStart = [process.execPath, scriptPath, 'connect', '--service-child']+ const execStart = [process.execPath, scriptPath, ...buildServiceConnectArgs(options)].map(quoteSystemdValue).join(' ');@@ -79,8 +114,9 @@ function renderUnit(): string {`Description=${CLI_DISPLAY_NAME} connect service`,'After=network-online.target','Wants=network-online.target',- 'StartLimitIntervalSec=60',- 'StartLimitBurst=10',+ // No start-rate limit: transient workspace startup failures exit 75 and must+ // keep retrying through outages of any length; RestartSec spaces the attempts.+ 'StartLimitIntervalSec=0','','[Service]','Type=simple',@@ -93,7 +129,7 @@ function renderUnit(): string {`StandardError=append:${logPath}`,'Restart=on-failure','SuccessExitStatus=0 1 2',- 'RestartSec=1',+ 'RestartSec=5','TimeoutStopSec=20','','[Install]',@@ -172,17 +208,26 @@ function assertConnectServiceAuthAvailable(): void {);}-export function installConnectService(): void {+export function installConnectService(options: ConnectServiceOptions = {}): void {+ if (options.public && !options.workspace) {+ throw new Error('--public requires --workspace.');+ }+requireLinuxSystemd();assertNoConnectDaemonRunning();assertConnectServiceAuthAvailable();writeServiceEnvironmentFile();fs.mkdirSync(getUserServiceDir(), { mode: 0o700, recursive: true });- fs.writeFileSync(path.join(getUserServiceDir(), SERVICE_NAME), renderUnit(), { mode: 0o644 });+ fs.writeFileSync(path.join(getUserServiceDir(), SERVICE_NAME), renderUnit(options), {+ mode: 0o644,+ });systemctl(['daemon-reload'], 'inherit');- systemctl(['enable', '--now', SERVICE_NAME], 'inherit');+ systemctl(['enable', SERVICE_NAME], 'inherit');+ // `enable --now` leaves an already-active unit on its old ExecStart; restart so+ // a reinstall with different connect args takes effect immediately.+ systemctl(['restart', SERVICE_NAME], 'inherit');}export function uninstallConnectService(): boolean {