|
| 1 | +import { SystemError } from '@expo/eas-build-job'; |
| 2 | +import { |
| 3 | + BuildFunction, |
| 4 | + BuildRuntimePlatform, |
| 5 | + BuildStepInput, |
| 6 | + BuildStepInputValueTypeName, |
| 7 | +} from '@expo/steps'; |
| 8 | +import spawn from '@expo/turtle-spawn'; |
| 9 | +import fs from 'node:fs'; |
| 10 | +import os from 'node:os'; |
| 11 | +import path from 'node:path'; |
| 12 | +import { z } from 'zod'; |
| 13 | + |
| 14 | +import { CustomBuildContext } from '../../customBuildContext'; |
| 15 | +import { |
| 16 | + ensureCloudflaredInstalledAsync, |
| 17 | + getDeviceRunSessionIdOrThrow, |
| 18 | + spawnDetached, |
| 19 | + startServeSimWithTunnelAsync, |
| 20 | + uploadRemoteSessionConfigAsync, |
| 21 | + waitForFileAsync, |
| 22 | + waitForMatchInOutputAsync, |
| 23 | +} from '../utils/remoteDeviceRunSession'; |
| 24 | + |
| 25 | +const ARGENT_PACKAGE_NAME = '@swmansion/argent'; |
| 26 | +const ARGENT_STATE_FILE = path.join(os.homedir(), '.argent', 'tool-server.json'); |
| 27 | +const XCODE_DEVELOPER_DIR = '/Applications/Xcode.app/Contents/Developer'; |
| 28 | +const STARTUP_TIMEOUT_MS = 60_000; |
| 29 | + |
| 30 | +const ArgentToolServerStateSchema = z.object({ port: z.number() }); |
| 31 | + |
| 32 | +export function createStartArgentRemoteSessionBuildFunction( |
| 33 | + ctx: CustomBuildContext |
| 34 | +): BuildFunction { |
| 35 | + return new BuildFunction({ |
| 36 | + namespace: 'eas', |
| 37 | + id: 'start_argent_remote_session', |
| 38 | + name: 'Start argent remote session', |
| 39 | + __metricsId: 'eas/start_argent_remote_session', |
| 40 | + inputProviders: [ |
| 41 | + BuildStepInput.createProvider({ |
| 42 | + id: 'package_version', |
| 43 | + required: false, |
| 44 | + allowedValueTypeName: BuildStepInputValueTypeName.STRING, |
| 45 | + }), |
| 46 | + ], |
| 47 | + fn: async ({ logger, global }, { inputs, env }) => { |
| 48 | + // Fail fast before any expensive setup if the orchestrator-injected |
| 49 | + // DEVICE_RUN_SESSION_ID env var is missing — without it we cannot |
| 50 | + // report the remote config back to the API server. |
| 51 | + const deviceRunSessionId = getDeviceRunSessionIdOrThrow(env); |
| 52 | + |
| 53 | + const packageVersion = inputs.package_version.value as string | undefined; |
| 54 | + const versionSpec = packageVersion ?? 'latest'; |
| 55 | + const { runtimePlatform } = global; |
| 56 | + logger.info( |
| 57 | + `Starting argent remote session (version: ${versionSpec}, runtime: ${runtimePlatform}).` |
| 58 | + ); |
| 59 | + |
| 60 | + if (runtimePlatform === BuildRuntimePlatform.DARWIN) { |
| 61 | + logger.info(`Selecting Xcode developer directory: ${XCODE_DEVELOPER_DIR}.`); |
| 62 | + await spawn('sudo', ['xcode-select', '-s', XCODE_DEVELOPER_DIR], { env, logger }); |
| 63 | + } |
| 64 | + |
| 65 | + logger.info('Ensuring cloudflared is installed.'); |
| 66 | + const cloudflaredCommand = await ensureCloudflaredInstalledAsync({ |
| 67 | + runtimePlatform, |
| 68 | + env, |
| 69 | + logger, |
| 70 | + }); |
| 71 | + |
| 72 | + // Stale state from a previous run would mask the new server's port. |
| 73 | + await fs.promises.rm(ARGENT_STATE_FILE, { force: true }); |
| 74 | + |
| 75 | + logger.info(`Launching ${ARGENT_PACKAGE_NAME}@${versionSpec} via bunx.`); |
| 76 | + // `argent mcp` is the public entry that triggers @argent/tools-client |
| 77 | + // to spawn the tool-server detached + unref'd, so the tool-server |
| 78 | + // outlives this MCP process. ARGENT_IDLE_TIMEOUT_MINUTES=0 disables the |
| 79 | + // 30-min idle shutdown that would otherwise tear the tunnel down. |
| 80 | + spawnDetached({ |
| 81 | + command: 'bunx', |
| 82 | + args: [`${ARGENT_PACKAGE_NAME}@${versionSpec}`, 'mcp'], |
| 83 | + env: { ...env, ARGENT_IDLE_TIMEOUT_MINUTES: '0' }, |
| 84 | + }); |
| 85 | + |
| 86 | + logger.info(`Waiting for argent tool-server state at ${ARGENT_STATE_FILE}.`); |
| 87 | + const { port: toolServerPort } = await waitForFileAsync({ |
| 88 | + filePath: ARGENT_STATE_FILE, |
| 89 | + timeoutMs: STARTUP_TIMEOUT_MS, |
| 90 | + description: 'argent tool-server state', |
| 91 | + parse: parseArgentToolServerState, |
| 92 | + }); |
| 93 | + logger.info(`Argent tool-server is listening on port ${toolServerPort}.`); |
| 94 | + |
| 95 | + logger.info(`Starting cloudflared tunnel to http://localhost:${toolServerPort}.`); |
| 96 | + const cloudflared = spawnDetached({ |
| 97 | + command: cloudflaredCommand, |
| 98 | + args: ['tunnel', '--url', `http://localhost:${toolServerPort}`], |
| 99 | + env, |
| 100 | + }); |
| 101 | + |
| 102 | + logger.info('Waiting for a public tunnel URL.'); |
| 103 | + const toolsUrl = await waitForMatchInOutputAsync({ |
| 104 | + process: cloudflared, |
| 105 | + pattern: /https:\/\/[a-z0-9-]+\.trycloudflare\.com/, |
| 106 | + timeoutMs: STARTUP_TIMEOUT_MS, |
| 107 | + description: 'cloudflared tunnel', |
| 108 | + }); |
| 109 | + logger.info(`Tunnel is ready at ${toolsUrl}.`); |
| 110 | + |
| 111 | + // serve-sim is iOS-only — Android sessions go without a preview URL. |
| 112 | + let webPreviewUrl: string | undefined; |
| 113 | + if (runtimePlatform === BuildRuntimePlatform.DARWIN) { |
| 114 | + const serveSim = await startServeSimWithTunnelAsync({ |
| 115 | + env, |
| 116 | + logger, |
| 117 | + timeoutMs: STARTUP_TIMEOUT_MS, |
| 118 | + }); |
| 119 | + webPreviewUrl = serveSim.previewUrl; |
| 120 | + logger.info(`Web preview URL: ${webPreviewUrl}`); |
| 121 | + } |
| 122 | + |
| 123 | + await uploadRemoteSessionConfigAsync({ |
| 124 | + ctx, |
| 125 | + deviceRunSessionId, |
| 126 | + remoteConfig: { |
| 127 | + toolsUrl, |
| 128 | + ...(webPreviewUrl ? { webPreviewUrl } : {}), |
| 129 | + }, |
| 130 | + logger, |
| 131 | + }); |
| 132 | + |
| 133 | + logger.info('Remote session is live. Keeping the job alive until the session is stopped.'); |
| 134 | + // Keep the turtle job alive so the tool-server and tunnel stay reachable |
| 135 | + // until stopDeviceRunSession cancels the run. |
| 136 | + await new Promise<never>(() => {}); |
| 137 | + }, |
| 138 | + }); |
| 139 | +} |
| 140 | + |
| 141 | +function parseArgentToolServerState(raw: string): { port: number } { |
| 142 | + const result = ArgentToolServerStateSchema.safeParse(JSON.parse(raw)); |
| 143 | + if (!result.success) { |
| 144 | + throw new SystemError( |
| 145 | + `Expected tool-server state to contain { "port": <number>, ... }: ${result.error.message}` |
| 146 | + ); |
| 147 | + } |
| 148 | + return result.data; |
| 149 | +} |
0 commit comments