diff --git a/packages/command-registry/src/flag-definitions-connection.ts b/packages/command-registry/src/flag-definitions-connection.ts index f9c8196bc43..6246a4ddfcf 100644 --- a/packages/command-registry/src/flag-definitions-connection.ts +++ b/packages/command-registry/src/flag-definitions-connection.ts @@ -514,6 +514,16 @@ export const CONNECTION_FLAG_DEFINITIONS: readonly FlagDefinition[] = [ projectConfig: false, recorded: false, }, + { + key: 'form', + names: ['--form'], + type: 'string', + usageLabel: '--form
', + usageDescription: + 'Connect cloud list: show only devices of this form, for example phone or tablet', + projectConfig: false, + recorded: false, + }, { key: 'sessionLock', names: ['--session-lock'], diff --git a/packages/command-surface/src/schema/cli-config.ts b/packages/command-surface/src/schema/cli-config.ts index e90913272b7..6a23fdfddb8 100644 --- a/packages/command-surface/src/schema/cli-config.ts +++ b/packages/command-surface/src/schema/cli-config.ts @@ -28,18 +28,20 @@ export function resolveConfigDefaults(options: { cwd: string; cliFlags: CliFlags; env: EnvMap; -}): ConfigDefaults { - const defaults: ConfigDefaults = { flags: {} }; +}): ConfigDefaults & { configFileFlags: Partial } { + const configFileFlags: Partial = {}; + let devicePin: DevicePin | undefined; for (const entry of resolveConfigPaths(options.cwd, options.cliFlags.config, options.env)) { const parsed = loadSingleConfigFile(entry, options.command); - mergeDefinedFlags(defaults.flags, parsed.flags); - if (parsed.devicePin) defaults.devicePin = parsed.devicePin; + mergeDefinedFlags(configFileFlags, parsed.flags); + if (parsed.devicePin) devicePin = parsed.devicePin; } + const flags = { ...configFileFlags }; if (options.command !== 'help' && !options.cliFlags.help) { - mergeDefinedFlags(defaults.flags, readEnvFlagDefaults(options.env, options.command)); + mergeDefinedFlags(flags, readEnvFlagDefaults(options.env, options.command)); } - if (defaults.devicePin) mergeDefinedFlags(defaults.flags, defaults.devicePin.selector); - return defaults; + if (devicePin) mergeDefinedFlags(flags, devicePin.selector); + return { flags, configFileFlags, ...(devicePin && { devicePin }) }; } type ConfigFileSource = DevicePin['source']['kind']; diff --git a/packages/command-surface/src/schema/command-overrides.ts b/packages/command-surface/src/schema/command-overrides.ts index b29534f6f52..db51b8aa664 100644 --- a/packages/command-surface/src/schema/command-overrides.ts +++ b/packages/command-surface/src/schema/command-overrides.ts @@ -135,12 +135,12 @@ const SCHEMA_ONLY_CLI_COMMAND_SCHEMAS = { 'List cloud offerings or start a hosted session with a CLI login or AGENT_DEVICE_CLOUD_API_KEY. For a custom cloud API, set AGENT_DEVICE_CLOUD_API_KEY_ORIGIN to the same origin as AGENT_DEVICE_CLOUD_BASE_URL. Use AGENT_DEVICE_DAEMON_AUTH_TOKEN for direct remote daemon connections. Direct providers validate credentials and resources before saving state and print any preparation needed before open.', }, usageOverride: - 'connect [cloud] list [--live] [--json] | connect cloud --platform ios|android [--vendor ] [--max-minutes ] [--max-usd ] [--app-url ] [--needs ] [--device ] [--os ] [--show-viewer] | connect [provider] [--target ] [--remote-config ] [--daemon-base-url ] [--tenant ] [--run-id ] [--lease-id ] [--lease-backend ] [--force] [--no-login]', + 'connect [cloud] list [--platform ios|android] [--form ] [--device ] [--os ] [--live] [--json] | connect cloud --platform ios|android [--vendor ] [--max-minutes ] [--max-usd ] [--app-url ] [--needs ] [--device ] [--os ] [--show-viewer] | connect [provider] [--target ] [--remote-config ] [--daemon-base-url ] [--tenant ] [--run-id ] [--lease-id ] [--lease-backend ] [--force] [--no-login]', usageFlags: [], listUsageOverride: 'connect', positionalArgs: ['provider?|list'], allowedFlags: CONNECT_ALLOWED_FLAGS, - supportedFlags: [...CONNECT_SUPPORTED_FLAGS, 'live'], + supportedFlags: [...CONNECT_SUPPORTED_FLAGS, 'live', 'form'], explicitOnlyFlags: ['target'], }, connection: { diff --git a/packages/command-surface/src/schema/option-schema.ts b/packages/command-surface/src/schema/option-schema.ts index e49dd053e9f..633544a889e 100644 --- a/packages/command-surface/src/schema/option-schema.ts +++ b/packages/command-surface/src/schema/option-schema.ts @@ -17,6 +17,7 @@ export type OptionSpec = { const CONFIG_EXCLUDED_FLAG_KEYS = new Set([ 'live', + 'form', 'config', 'remoteConfig', 'help', @@ -28,6 +29,7 @@ const CONFIG_EXCLUDED_FLAG_KEYS = new Set([ const ENV_EXCLUDED_FLAG_KEYS = new Set([ 'live', + 'form', 'appsFilter', 'iosSimulatorDeviceSet', 'textStdin', diff --git a/packages/contracts/src/cli-flags.ts b/packages/contracts/src/cli-flags.ts index f36b3d0983d..4d3031e63f2 100644 --- a/packages/contracts/src/cli-flags.ts +++ b/packages/contracts/src/cli-flags.ts @@ -69,6 +69,7 @@ export type CliFlags = CloudProviderProfileFields & needs?: string; showViewer?: boolean; live?: boolean; + form?: string; kind?: string; perfTemplate?: string; sessionLock?: 'reject' | 'strip'; diff --git a/scripts/integration-progress-model.ts b/scripts/integration-progress-model.ts index 86ca1b712b3..98ff7bd3030 100644 --- a/scripts/integration-progress-model.ts +++ b/scripts/integration-progress-model.ts @@ -275,6 +275,7 @@ function summarizeProviderScenarioFlagExclusions() { 'needs', 'showViewer', 'live', + 'form', ], }, { diff --git a/skills/agent-device/SKILL.md b/skills/agent-device/SKILL.md index ad0f195a776..9e776f78d61 100644 --- a/skills/agent-device/SKILL.md +++ b/skills/agent-device/SKILL.md @@ -25,4 +25,4 @@ Copy refs byte-for-byte: `@e12`, `@e12-s4` — keep the `@` and any `-sN`. Prefe Error output includes corrective hints; follow them instead of re-planning. When your host runs commands in a sandbox and allows `agent-device` by command name, run each call as its own command: do not chain it with `;`, `&&`, or `|`, and do not quote its binary path, or the host's allow rule misses the call and it cannot reach the daemon or the device. If the error is `DEVICE_IN_USE`, another session holds the device: open with `--wait `, or run `agent-device device status --stale` and then `agent-device device release --stale` to clear a reclaimable owner. Never kill daemon processes with `pkill -f agent-device`. Only when the task is specialized (for example gestures, scripting, TV, macOS, remote, or debugging) or a command shape is unclear, run `agent-device help `. `agent-device --help` lists topics, `agent-device help commands` lists commands; neither is a startup step. -To capture network traffic on a Limrun session, see `agent-device help remote` or the Limrun docs. +To pick a cloud device, run `agent-device connect cloud list`. Filter it with `--platform`, `--form`, `--device`, or `--os`. Compare the offers for that device and OS. Book one with `agent-device connect cloud --session `. If those flags omit `--platform`, pass the platform shown for the offer. To capture network traffic on a Limrun session, see `agent-device help remote` or the Limrun docs. diff --git a/src/__tests__/cli-cloud-api-origin.test.ts b/src/__tests__/cli-cloud-api-origin.test.ts index 32eb50df7a8..2cd7aa4a546 100644 --- a/src/__tests__/cli-cloud-api-origin.test.ts +++ b/src/__tests__/cli-cloud-api-origin.test.ts @@ -1,7 +1,7 @@ import { afterEach, expect, test, vi } from 'vitest'; import { readCloudConnection } from '../cli/connection/cloud-connection-record.ts'; import { postCloudAuthJson } from '../cli/cloud-auth-request.ts'; -import { listCloudVendors } from '../cli/connection/cloud-catalog.ts'; +import { fetchCloudCatalogView } from '../cli/connection/cloud-catalog.ts'; import { createCloudSession, readCloudSessionRequest, @@ -196,10 +196,12 @@ test.each([401, 404])('sign-in reports a %i web page as not the cloud API', asyn ).rejects.toMatchObject({ details: { reason, origin: access.cloudBaseUrl, status } }); }); -test('the vendor catalog reports an origin that serves a web page', async () => { +test('the catalog view reports an origin that serves a web page', async () => { vi.stubGlobal('fetch', vi.fn().mockResolvedValueOnce(page(200))); - await expect(listCloudVendors(access.cloudBaseUrl, access.accessToken)).rejects.toMatchObject({ + await expect( + fetchCloudCatalogView(access.cloudBaseUrl, access.accessToken), + ).rejects.toMatchObject({ code: 'COMMAND_FAILED', details: { reason, origin: access.cloudBaseUrl, status: 200, hint: originHint }, }); diff --git a/src/__tests__/cli-cloud-catalog.test.ts b/src/__tests__/cli-cloud-catalog.test.ts index 9c5ef7e10d7..1b4e52d4988 100644 --- a/src/__tests__/cli-cloud-catalog.test.ts +++ b/src/__tests__/cli-cloud-catalog.test.ts @@ -14,6 +14,8 @@ afterEach(() => { vi.unstubAllGlobals(); }); +const emptyView = { version: 1, nodes: [], data: [] }; + test('catalog ignores ambient daemon settings and requires cloud authentication', async () => { const fetchMock = vi.fn(); vi.stubGlobal('fetch', fetchMock); @@ -36,7 +38,7 @@ test.each([DEFAULT_CLOUD_BASE_URL, 'https://issuer.example'])( const fetchMock = vi.fn(async (url: URL, _init: RequestInit) => url.pathname.endsWith('/refresh') ? Response.json({ accessToken: 'catalog-access-key' }) - : Response.json([]), + : Response.json(emptyView), ); vi.stubGlobal('fetch', fetchMock); const result = await runCliCapture(['connect', 'list', '--json'], { @@ -51,7 +53,7 @@ test.each([DEFAULT_CLOUD_BASE_URL, 'https://issuer.example'])( expect(JSON.parse(result.stdout).data).toEqual([]); expect(fetchMock.mock.calls.map(([url]) => url.href)).toEqual([ `${issuer}/api/control-plane/cli-session/refresh`, - `${issuer}/v1/vendors`, + `${issuer}/v1/catalog/view`, ]); const [, refresh] = fetchMock.mock.calls[0]!; expect(JSON.parse(String(refresh.body))).toEqual({ @@ -78,20 +80,11 @@ test.each(['user config', 'configured file', 'explicit config'])( const env: Record = { AGENT_DEVICE_HOME: home }; if (source === 'configured file') env.AGENT_DEVICE_CONFIG = config; if (source === 'explicit config') args.push('--config', config); - const rows = [ - { - vendor: 'test-provider', - platform: 'ios', - usdPerMinute: 0.05, - capabilities: [], - viewer: false, - available: true, - }, - ]; + const rows = [{ device: 'test-device' }]; const fetchMock = vi.fn(async (url: URL, _init: RequestInit) => url.pathname.endsWith('/refresh') ? Response.json({ accessToken: 'catalog-access-key' }) - : Response.json(rows), + : Response.json({ ...emptyView, data: rows }), ); vi.stubGlobal('fetch', fetchMock); @@ -102,7 +95,7 @@ test.each(['user config', 'configured file', 'explicit config'])( expect(result.calls).toEqual([]); expect(fetchMock.mock.calls.map(([url]) => url.href)).toEqual([ `${issuer}/api/control-plane/cli-session/refresh`, - `${issuer}/v1/vendors`, + `${issuer}/v1/catalog/view`, ]); expect(new Headers(fetchMock.mock.calls[1]![1].headers).get('authorization')).toBe( 'Bearer catalog-access-key', @@ -147,30 +140,22 @@ function storeSession(cloudBaseUrl: string): string { return stateDir; } -test('lists authenticated cloud vendors in text and JSON without a named session', async () => { - const rows = [ - { - vendor: 'provider-a', - platform: 'ios', - usdPerMinute: 0.03, - capabilities: ['viewer', 'runtime-preview'], - viewer: true, - available: true, - catalogVersion: 2, - maxMinutes: 115, - }, - { - vendor: 'provider-b', - platform: 'android', - usdPerMinute: 0.05, - capabilities: ['adb'], - viewer: false, - available: false, - catalogVersion: 2, - maxMinutes: 115, - }, - ]; - const fetchMock = vi.fn(async (_url: URL, _init: RequestInit) => Response.json(rows)); +test('renders the cloud catalog view in text, prints its data as JSON and sends the filters', async () => { + const view = { + version: 1, + nodes: [ + { kind: 'heading', text: 'Group A' }, + { + kind: 'group', + title: 'Device one', + columns: ['offer', 'price'], + children: [{ kind: 'row', cells: ['offer-a', '$0.03/min'], book: '--device one' }], + }, + { kind: 'note', text: 'Server note.' }, + ], + data: [{ device: 'one', offer: 'offer-a' }], + }; + const fetchMock = vi.fn(async (_url: URL, _init: RequestInit) => Response.json(view)); vi.stubGlobal('fetch', fetchMock); const env = { AGENT_DEVICE_CLOUD_BASE_URL: 'https://cloud.example', @@ -181,90 +166,97 @@ test('lists authenticated cloud vendors in text and JSON without a named session const human = await runCliCapture(['connect', 'list'], options); expect(human.code, human.stderr || human.stdout).toBeNull(); expect(human.stdout.trim().split('\n')).toEqual([ - 'provider-a ios $0.03/min capabilities: viewer, runtime-preview live view: yes available: yes', - 'provider-b android $0.05/min capabilities: adb live view: no available: no', + 'Group A', + 'Device one', + ' offer price book', + ' offer-a $0.03/min --device one', + 'Note: Server note.', ]); expect(human.calls).toEqual([]); - const json = await runCliCapture(['connect', 'list', '--json'], { - ...options, - env, - }); - expect(json.code).toBeNull(); - expect(JSON.parse(json.stdout).data).toEqual(rows); - expect(fetchMock).toHaveBeenCalledTimes(2); - for (const [url, init] of fetchMock.mock.calls) { - expect(url.href).toBe('https://cloud.example/v1/vendors'); + const json = await runCliCapture( + [ + 'connect', + 'cloud', + 'list', + '--platform', + 'ios', + '--form', + 'phone', + '--device', + 'iphone-17', + '--os', + 'iOS 26', + '--live', + '--json', + ], + options, + ); + expect(json.code, json.stderr || json.stdout).toBeNull(); + expect(JSON.parse(json.stdout).data).toEqual(view.data); + expect(fetchMock.mock.calls.map(([url]) => url.href)).toEqual([ + 'https://cloud.example/v1/catalog/view', + 'https://cloud.example/v1/catalog/view?platform=ios&form=phone&os=iOS+26&device=iphone-17&availability=live', + ]); + for (const [, init] of fetchMock.mock.calls) { expect(init.method).toBe('GET'); expect(new Headers(init.headers).get('authorization')).toBe('Bearer cloud-api-test-key'); } - const invalid = await runCliCapture(['connect', 'list', '--os', '26'], options); + const invalid = await runCliCapture(['connect', 'list', '--vendor', 'any'], options); expect(invalid.code).toBe(1); + for (const flag of [['--live'], ['--form', 'phone']]) { + const refused = await runCliCapture( + ['connect', 'cloud', '--platform', 'ios', ...flag], + options, + ); + expect(refused.code).toBe(1); + expect(refused.stderr).toContain(`${flag[0]} requires a catalog listing`); + } expect(fetchMock).toHaveBeenCalledTimes(2); }); -test('connect list --live asks for fresh availability and renders it with an API key', async () => { - const checkedAt = '2026-11-22T12:00:00.000Z'; - const rows = [ - { - vendor: 'provider-a', - platform: 'ios', - usdPerMinute: 0.1, - capabilities: ['viewer'], - viewer: true, - available: true, - usdMicrosPerMinute: '100000', - minMinutes: 5, - availability: { - state: 'unavailable', - reason: 'sessions_paused', - checkedAt, - scope: 'broker_vendor', - }, - }, - { - vendor: 'provider-b', - platform: 'android', - usdPerMinute: 0.04, - capabilities: ['adb'], - viewer: false, - available: true, - }, - ]; - const fetchMock = vi.fn(async (_url: URL, _init: RequestInit) => Response.json(rows)); +test('catalog applies configured filters and gives explicit CLI filters precedence', async () => { + const config = path.join(mkdtempForTestSync('agent-device-catalog-filters-'), 'config.json'); + fs.writeFileSync( + config, + JSON.stringify({ platform: 'android', device: 'tablet', osVersion: '14' }), + ); + const fetchMock = vi.fn(async (_url: URL) => Response.json(emptyView)); vi.stubGlobal('fetch', fetchMock); - const options = { - env: { - AGENT_DEVICE_CLOUD_BASE_URL: 'https://cloud.example', - AGENT_DEVICE_CLOUD_API_KEY: 'cloud-api-test-key', - AGENT_DEVICE_CLOUD_API_KEY_ORIGIN: 'https://cloud.example', - }, - stateDirPrefix: 'agent-device-cloud-catalog-', + const env = { + AGENT_DEVICE_CONFIG: config, + AGENT_DEVICE_CLOUD_API_KEY: 'catalog-fixture-key', + AGENT_DEVICE_PLATFORM: 'ios', }; - const human = await runCliCapture(['connect', 'list', '--live'], options); - expect(human.code, human.stderr || human.stdout).toBeNull(); - expect(human.stdout.trim().split('\n')).toEqual([ - 'provider-a ios $0.1/min minimum: 5 min capabilities: viewer live view: yes available: yes availability: unavailable (sessions_paused)', - expect.stringMatching( - /^provider-b android {2}\$0\.04\/min {2}capabilities: adb {2}live view: no {2}available: yes {2}availability: unknown \(live_availability_unsupported\)$/, - ), - ]); - const json = await runCliCapture(['connect', 'list', '--live', '--json'], options); - const data = JSON.parse(json.stdout).data; - expect(data[0]).toEqual(rows[0]); - expect(data[1].availability).toMatchObject({ - state: 'unknown', - reason: 'live_availability_unsupported', - scope: 'broker_vendor', - }); - expect(fetchMock).toHaveBeenCalledTimes(2); - for (const [url, init] of fetchMock.mock.calls) { - expect(url.href).toBe('https://cloud.example/v1/vendors?availability=live'); - expect(new Headers(init.headers).get('authorization')).toBe('Bearer cloud-api-test-key'); + + const result = await runCliCapture(['connect', 'cloud', 'list', '--device', 'tv'], { env }); + + expect(result.code, result.stdout + result.stderr).toBeNull(); + expect(fetchMock.mock.calls[0]?.[0].search).toBe('?platform=android&os=14&device=tv'); + expect(result.stdout).toBe('No cloud catalog offers to display.\n'); +}); + +test.each(['environment', 'device pin'])('catalog ignores a selector from %s', async (source) => { + const home = mkdtempForTestSync('agent-device-catalog-selector-'); + const env = { + AGENT_DEVICE_HOME: home, + AGENT_DEVICE_CLOUD_API_KEY: 'catalog-fixture-key', + ...(source === 'environment' && { AGENT_DEVICE_PLATFORM: 'android' }), + }; + if (source === 'device pin') { + fs.writeFileSync( + path.join(home, 'config.json'), + JSON.stringify({ devicePin: { platform: 'android', device: 'tablet' } }), + ); } - const refused = await runCliCapture(['connect', 'cloud', '--platform', 'ios', '--live'], options); - expect(refused.code).toBe(1); - expect(refused.stderr).toContain('--live requires a catalog listing'); - expect(fetchMock).toHaveBeenCalledTimes(2); + const fetchMock = vi.fn(async (_url: URL) => Response.json(emptyView)); + vi.stubGlobal('fetch', fetchMock); + + const all = await runCliCapture(['connect', 'cloud', 'list'], { env }); + const filtered = await runCliCapture(['connect', 'cloud', 'list', '--platform', 'ios'], { env }); + + expect(all.code, all.stderr).toBeNull(); + expect(filtered.code, filtered.stderr).toBeNull(); + expect(fetchMock.mock.calls.map(([url]) => url.search)).toEqual(['', '?platform=ios']); }); test('an ambient self-hosted token does not hide a stored default-cloud login', async () => { @@ -272,7 +264,7 @@ test('an ambient self-hosted token does not hide a stored default-cloud login', const fetchMock = vi.fn(async (url: URL, _init: RequestInit) => url.pathname.endsWith('/refresh') ? Response.json({ accessToken: 'fixture-account-token' }) - : Response.json([]), + : Response.json(emptyView), ); vi.stubGlobal('fetch', fetchMock); const result = await runCliCapture(['connect', 'list', '--json'], { @@ -284,7 +276,7 @@ test('an ambient self-hosted token does not hide a stored default-cloud login', expect(result.code).toBeNull(); expect(fetchMock.mock.calls.map(([url]) => url.pathname)).toEqual([ '/api/control-plane/cli-session/refresh', - '/v1/vendors', + '/v1/catalog/view', ]); expect(new Headers(fetchMock.mock.calls[1]?.[1].headers).get('authorization')).toBe( 'Bearer fixture-account-token', @@ -365,17 +357,11 @@ test.each([ const fetchMock = vi.fn(async (url: URL) => url.pathname.endsWith('/refresh') ? Response.json({ accessToken: 'catalog-access-key' }) - : Response.json([ - { - vendor: 'fixture-vendor', - platform: 'ios', - usdPerMinute: 0, - capabilities: format === 'text' ? [`embedded-${credential}`] : [], - viewer: false, - available: true, - debug: { [`prefix-${credential}`]: 'echo' }, - }, - ]), + : Response.json({ + version: 1, + nodes: [{ kind: 'text', text: format === 'text' ? `embedded-${credential}` : 'text' }], + data: [{ debug: { [`prefix-${credential}`]: 'echo' } }], + }), ); vi.stubGlobal('fetch', fetchMock); const result = await runCliCapture( @@ -392,10 +378,24 @@ test.each([ }, ); expect(result.code).toBe(1); - expect(result.stdout + result.stderr).toContain('invalid vendor list'); + expect(result.stdout + result.stderr).toContain('invalid catalog view'); expect(result.stdout + result.stderr).not.toContain(credential); }); +test('refuses a credential formed when catalog text is sanitized', async () => { + vi.stubGlobal('fetch', async () => + Response.json({ ...emptyView, nodes: [{ kind: 'text', text: 'catalog-\u0000fixture-key' }] }), + ); + const result = await runCliCapture(['connect', 'cloud', 'list'], { + env: { AGENT_DEVICE_CLOUD_API_KEY: 'catalog-fixture-key' }, + }); + + expect(result.code).toBe(1); + expect(result.stdout).toBe(''); + expect(result.stderr).toContain('invalid catalog view'); + expect(result.stderr).not.toContain('catalog-fixture-key'); +}); + test('a provider named list keeps the provider route and ignores ambient live', async () => { const resolve = vi.fn(() => ({ profile: { leaseProvider: 'list', platform: 'ios' } })); const { storePluginCandidates } = await import('@agent-device/plugins/store'); @@ -432,7 +432,7 @@ test('a provider named list keeps the provider route and ignores ambient live', }), }; vi.mocked(storePluginCandidates).mockResolvedValueOnce([candidate]); - const fetchMock = vi.fn(async () => Response.json([])); + const fetchMock = vi.fn(async () => Response.json(emptyView)); vi.stubGlobal('fetch', fetchMock); const env = { AGENT_DEVICE_SESSION: 'fixture-session', AGENT_DEVICE_LIVE: 'true' }; const provider = await runCliCapture(['connect', 'list', '--json'], { env }); diff --git a/src/cli/connect-preflight.ts b/src/cli/connect-preflight.ts index 4de9e502087..38d7284392d 100644 --- a/src/cli/connect-preflight.ts +++ b/src/cli/connect-preflight.ts @@ -36,7 +36,7 @@ async function runCatalogPreflight( if (positionals.length !== (positionals[1] === 'list' ? 2 : 1)) { throw new AppError('INVALID_ARGS', 'A catalog listing accepts no additional arguments.'); } - const allowed = ['config', 'stateDir', 'live', 'json']; + const allowed = ['config', 'stateDir', 'live', 'json', 'platform', 'form', 'osVersion', 'device']; const invalid = providedFlags.find(({ key }) => !allowed.includes(key)); if (invalid) { throw new AppError('INVALID_ARGS', `${invalid.token} is unavailable for a catalog listing.`); @@ -57,6 +57,12 @@ async function runCatalogPreflight( stateDir: paths.baseDir, env: host.env, live: flags.live, + filters: { + platform: flags.platform ?? defaults.configFileFlags.platform, + form: flags.form, + os: flags.osVersion ?? defaults.configFileFlags.osVersion, + device: flags.device ?? defaults.configFileFlags.device, + }, json: flags.json, }); } diff --git a/src/cli/connection/cloud-catalog.test.ts b/src/cli/connection/cloud-catalog.test.ts index eacc0a231c1..64be7de9eea 100644 --- a/src/cli/connection/cloud-catalog.test.ts +++ b/src/cli/connection/cloud-catalog.test.ts @@ -1,127 +1,131 @@ import { afterEach, expect, test, vi } from 'vitest'; -import { formatCloudVendorRow, listCloudVendors } from './cloud-catalog.ts'; +import { fetchCloudCatalogView, renderCloudCatalogView } from './cloud-catalog.ts'; const baseUrl = 'https://cloud.example'; -const legacyRow = { - vendor: 'provider-b', - platform: 'android', - usdPerMinute: 0.04, - capabilities: ['adb'], - viewer: true, - available: true, - catalogVersion: 3, - maxMinutes: 115, +const view = { + version: 1, + nodes: [ + { kind: 'heading', text: 'Group A' }, + { + kind: 'group', + title: 'Device one', + children: [ + { + kind: 'group', + title: 'Version 2', + columns: ['offer', 'price'], + children: [ + { kind: 'row', cells: ['offer-a', '$0.04/min'], book: '--device one --os 2' }, + { kind: 'row', cells: ['offer-long-name', '$0.10/min'], book: '--device one' }, + ], + }, + ], + }, + { kind: 'future-kind', text: 'skipped' }, + { kind: 'text', text: 'Closing text.' }, + { kind: 'note', text: 'A note.' }, + ], + data: [{ any: 'shape' }], }; -const checkedAt = '2026-11-22T12:00:00.000Z'; -const liveAvailability = { - state: 'unavailable', - reason: 'sessions_paused', - checkedAt, - scope: 'broker_vendor', -} as const; + afterEach(() => { vi.unstubAllGlobals(); - vi.useRealTimers(); }); -function stubVendors(body: unknown) { +function stubView(body: unknown) { const fetchMock = vi.fn(async (_url: URL, _init: RequestInit) => Response.json(body)); vi.stubGlobal('fetch', fetchMock); return fetchMock; } -function requestOf(fetchMock: ReturnType) { - const [url, init] = fetchMock.mock.calls.at(-1)!; - return { url, init, headers: new Headers(init.headers) }; -} - -test('a static listing returns older-server rows unchanged and sends the API key', async () => { - const fetchMock = stubVendors([legacyRow]); - expect(await listCloudVendors(baseUrl, 'example-key')).toEqual([legacyRow]); - const { url, init, headers } = requestOf(fetchMock); - expect(url.href).toBe('https://cloud.example/v1/vendors'); - expect(init).toMatchObject({ method: 'GET', redirect: 'manual' }); - expect(headers.get('authorization')).toBe('Bearer example-key'); +test('renders every known node kind, aligns rows under columns and skips unknown kinds', () => { + expect(renderCloudCatalogView(view.nodes).split('\n')).toEqual([ + 'Group A', + 'Device one', + ' Version 2', + ' offer price book', + ' offer-a $0.04/min --device one --os 2', + ' offer-long-name $0.10/min --device one', + 'Closing text.', + 'Note: A note.', + ]); }); -test('a static listing reads the optional price and minimum fields and keeps unknown fields', async () => { - const row = { ...legacyRow, usdMicrosPerMinute: '40000', minMinutes: 5, future: { a: 1 } }; - stubVendors([row]); - expect(await listCloudVendors(baseUrl, 'example-key')).toEqual([row]); -}); - -test('a price in micro-USD may be as wide as the widest --max-usd cap', async () => { - const row = { ...legacyRow, usdMicrosPerMinute: '9999999999999999999' }; - stubVendors([row]); - expect(await listCloudVendors(baseUrl, 'example-key')).toEqual([row]); +test('drops malformed nodes and control characters from server text', () => { + expect( + renderCloudCatalogView([ + null, + { kind: 'row', cells: [1, 2] }, + { kind: 'group', title: 'No children' }, + { kind: 'text', text: 'safe\u001b[31m red' }, + { kind: 'row', cells: ['plain'] }, + ]), + ).toBe('safe[31m red\nplain'); }); -test.each([ - ['a non-array body', { vendors: [] }], - ['a row without a vendor', [{ ...legacyRow, vendor: '' }]], - ['a fractional price in micro-USD', [{ ...legacyRow, usdMicrosPerMinute: '0.04' }]], - ['a numeric price in micro-USD', [{ ...legacyRow, usdMicrosPerMinute: 40000 }]], - ['a signed price in micro-USD', [{ ...legacyRow, usdMicrosPerMinute: '-1' }]], - ['a zero minimum', [{ ...legacyRow, minMinutes: 0 }]], - ['a fractional minimum', [{ ...legacyRow, minMinutes: 2.5 }]], - ['a text minimum', [{ ...legacyRow, minMinutes: '5' }]], -])('rejects %s as an invalid vendor list', async (_name, body) => { - stubVendors(body); - await expect(listCloudVendors(baseUrl, 'example-key')).rejects.toMatchObject({ - code: 'COMMAND_FAILED', - message: 'Cloud session API returned an invalid vendor list.', +test('sends the filters and live flag as query parameters with the API key', async () => { + const fetchMock = stubView(view); + const result = await fetchCloudCatalogView(baseUrl, 'example-key', { + live: true, + filters: { platform: 'ios', form: undefined, os: 'iOS 27', device: 'phone-one' }, }); + expect(result).toEqual(view); + const [url, init] = fetchMock.mock.calls[0]!; + expect(url.href).toBe( + 'https://cloud.example/v1/catalog/view?platform=ios&os=iOS+27&device=phone-one&availability=live', + ); + expect(new Headers(init.headers).get('authorization')).toBe('Bearer example-key'); }); -test('a live listing asks for fresh availability with the API key and returns the signal', async () => { - const fetchMock = stubVendors([{ ...legacyRow, availability: liveAvailability }]); - const rows = await listCloudVendors(baseUrl, 'example-key', { live: true }); - expect(rows).toEqual([{ ...legacyRow, availability: liveAvailability }]); - const { url, init, headers } = requestOf(fetchMock); - expect(url.href).toBe('https://cloud.example/v1/vendors?availability=live'); - expect(init).toMatchObject({ method: 'GET', redirect: 'manual' }); - expect(headers.get('authorization')).toBe('Bearer example-key'); -}); +test.each([[[]], [{ version: 1, nodes: [] }], [{ version: '1', nodes: [], data: [] }]])( + 'rejects a response that is not a catalog view: %j', + async (body) => { + stubView(body); + await expect(fetchCloudCatalogView(baseUrl, 'example-key')).rejects.toMatchObject({ + code: 'COMMAND_FAILED', + message: 'Cloud session API returned an invalid catalog view.', + }); + }, +); -test('a live listing marks rows from a server without the signal as unknown', async () => { - vi.setSystemTime(new Date('2026-11-22T12:30:00.000Z')); - stubVendors([legacyRow, { ...legacyRow, platform: 'ios', availability: liveAvailability }]); - const rows = await listCloudVendors(baseUrl, 'example-key', { live: true }); - expect(rows[0]!.availability).toEqual({ - state: 'unknown', - reason: 'live_availability_unsupported', - checkedAt: '2026-11-22T12:30:00.000Z', - scope: 'broker_vendor', +test('rejects a view that echoes a credential', async () => { + stubView({ ...view, data: [{ leaked: 'example-key' }] }); + await expect(fetchCloudCatalogView(baseUrl, 'example-key')).rejects.toMatchObject({ + code: 'COMMAND_FAILED', }); - expect(rows[1]!.availability).toEqual(liveAvailability); - expect(rows[0]).toMatchObject(legacyRow); }); -test('a static listing leaves a row without availability alone', async () => { - stubVendors([legacyRow]); - const [row] = await listCloudVendors(baseUrl, 'example-key', { live: false }); - expect(row).not.toHaveProperty('availability'); -}); +test.each(['nodes', 'data'])( + 'rejects deeply nested catalog %s before serialization', + async (field) => { + const nested = '['.repeat(10_000) + '0' + ']'.repeat(10_000); + const nodes = field === 'nodes' ? nested : '[]'; + const data = field === 'data' ? nested : '[]'; + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(`{"version":1,"nodes":${nodes},"data":${data}}`)), + ); + await expect(fetchCloudCatalogView(baseUrl, 'example-key')).rejects.toMatchObject({ + code: 'COMMAND_FAILED', + message: 'Cloud session API returned an invalid catalog view.', + }); + }, +); -test.each([ - ['an unknown state', { ...liveAvailability, state: 'busy' }], - ['an unknown reason', { ...liveAvailability, reason: 'on_fire' }], - ['a non-vendor scope', { ...liveAvailability, scope: 'model' }], - ['a missing timestamp', { state: 'available', scope: 'broker_vendor' }], - ['an unparseable timestamp', { ...liveAvailability, checkedAt: 'yesterday' }], - ['a non-object signal', 'available'], -])('a live listing rejects %s', async (_name, availability) => { - stubVendors([{ ...legacyRow, availability }]); - await expect(listCloudVendors(baseUrl, 'example-key', { live: true })).rejects.toMatchObject({ - message: 'Cloud session API returned an invalid vendor list.', +test('rejects an oversized catalog response', async () => { + stubView({ version: 1, nodes: [], data: ['x'.repeat(2 * 1024 * 1024)] }); + await expect(fetchCloudCatalogView(baseUrl, 'example-key')).rejects.toMatchObject({ + code: 'COMMAND_FAILED', + details: { tooLarge: true }, }); }); -test('a live listing keeps an available signal that carries no reason', async () => { - const availability = { state: 'available', checkedAt, scope: 'broker_vendor' } as const; - stubVendors([{ ...legacyRow, availability }]); - const [row] = await listCloudVendors(baseUrl, 'example-key', { live: true }); - expect(row!.availability).toEqual(availability); +test('rejects a table whose column padding would exceed the display limit', () => { + const label = 'x'.repeat(64 * 1024); + const rows = Array.from({ length: 64 }, () => ({ kind: 'row', cells: ['a', 'b'] })); + expect(() => renderCloudCatalogView([{ kind: 'row', cells: [label, 'b'] }, ...rows])).toThrow( + 'Cloud catalog display exceeds the output limit.', + ); }); test('reports a rejected request and an unreachable server without raw response text', async () => { @@ -129,7 +133,7 @@ test('reports a rejected request and an unreachable server without raw response 'fetch', vi.fn(async () => new Response('secret upstream detail', { status: 503 })), ); - const rejected = await listCloudVendors(baseUrl, 'example-key', { live: true }).catch( + const rejected = await fetchCloudCatalogView(baseUrl, 'example-key').catch( (error: Error) => error, ); expect(rejected).toMatchObject({ code: 'COMMAND_FAILED' }); @@ -140,29 +144,7 @@ test('reports a rejected request and an unreachable server without raw response throw new TypeError('connect ECONNREFUSED'); }), ); - await expect(listCloudVendors(baseUrl, 'example-key')).rejects.toMatchObject({ + await expect(fetchCloudCatalogView(baseUrl, 'example-key')).rejects.toMatchObject({ message: 'Could not reach the cloud session API.', }); }); - -test('text rows keep the legacy shape and add the minimum and live availability when present', () => { - expect(formatCloudVendorRow(legacyRow)).toBe( - 'provider-b android $0.04/min capabilities: adb live view: yes available: yes', - ); - expect( - formatCloudVendorRow({ - ...legacyRow, - minMinutes: 5, - available: false, - availability: liveAvailability, - }), - ).toBe( - 'provider-b android $0.04/min minimum: 5 min capabilities: adb live view: yes available: no availability: unavailable (sessions_paused)', - ); - expect( - formatCloudVendorRow({ - ...legacyRow, - availability: { state: 'available', checkedAt, scope: 'broker_vendor' }, - }), - ).toMatch(/ {2}availability: available$/); -}); diff --git a/src/cli/connection/cloud-catalog.ts b/src/cli/connection/cloud-catalog.ts index 771f6e53697..e0057720dab 100644 --- a/src/cli/connection/cloud-catalog.ts +++ b/src/cli/connection/cloud-catalog.ts @@ -4,161 +4,227 @@ import { containsCloudCredential, fetchCloudApi, isCloudText, - isCloudTextArray, readCloudJsonResponse, } from '../cloud-response.ts'; import type { EnvMap } from '@agent-device/kernel/source-value'; import { writeCommandOutput } from '../commands/shared.ts'; import { resolveCloudCatalogAccess } from './cloud-catalog-access.ts'; -import { readMicroUsd } from './cloud-session-api.ts'; - -const AVAILABILITY_STATES = ['available', 'unavailable', 'unknown'] as const; -const AVAILABILITY_REASONS = [ - 'sessions_paused', - 'vendor_disabled', - 'vendor_unconfigured', - 'broker_capacity', - 'capacity_unknown', - 'live_availability_unsupported', -] as const; - -export type CloudVendorAvailability = { - state: (typeof AVAILABILITY_STATES)[number]; - reason?: (typeof AVAILABILITY_REASONS)[number]; - checkedAt: string; - scope: 'broker_vendor'; + +const MAX_CATALOG_RESPONSE_BYTES = 2 * 1024 * 1024; +const MAX_CATALOG_JSON_DEPTH = 32; +const MAX_CATALOG_OUTPUT_LENGTH = 4 * 1024 * 1024; + +/** The catalog filters the cloud service applies. Each one is sent as a query parameter. */ +export type CloudCatalogFilters = { + platform?: string; + form?: string; + os?: string; + device?: string; }; -export type CloudVendorRow = { - vendor: string; - platform: string; - usdPerMinute: number; - capabilities: string[]; - viewer: boolean; - /** Configured and operator-enabled. It says nothing about occupancy or provider stock. */ - available: boolean; - usdMicrosPerMinute?: string; - minMinutes?: number; - /** Present only on a live listing. */ - availability?: CloudVendorAvailability; +/** + * The display tree the cloud service sends for `connect cloud list`. The service decides what + * the nodes say. The CLI renders the known kinds and skips every other kind. + */ +export type CloudCatalogView = { + version: number; + nodes: unknown[]; + data: unknown[]; }; export async function runCloudCatalog(options: { stateDir: string; env: EnvMap; live?: boolean; + filters: CloudCatalogFilters; json: boolean; }): Promise { - const { stateDir, env, live, json } = options; + const { stateDir, env, live, filters, json } = options; const { accessToken, cloudBaseUrl, catalogCredentials } = await resolveCloudCatalogAccess({ stateDir, env, }); - const vendors = await listCloudVendors(cloudBaseUrl, accessToken, { + const view = await fetchCloudCatalogView(cloudBaseUrl, accessToken, { live, + filters, catalogCredentials, }); - await writeCommandOutput({ json }, vendors, () => - vendors.length === 0 - ? 'No cloud vendors listed.' - : vendors.map(formatCloudVendorRow).join('\n'), - ); + await writeCommandOutput({ json }, view.data, () => { + const rendered = renderCloudCatalogView(view.nodes); + if (containsCloudCredential(rendered, [accessToken, ...(catalogCredentials ?? [])])) { + throw invalidCatalogView(); + } + return rendered.trim() ? rendered : 'No cloud catalog offers to display.'; + }); } -/** - * The authenticated vendor catalog. A static listing returns the server's rows as sent. - * A live listing guarantees every row carries - * `availability`: rows from a server that predates the signal get a typed unknown state. - */ -export async function listCloudVendors( +/** The authenticated catalog view for the filters. */ +export async function fetchCloudCatalogView( baseUrl: string, accessToken: string, - options: { live?: boolean; catalogCredentials?: ReadonlySet } = {}, -): Promise { - const url = new URL('/v1/vendors', baseUrl); + options: { + live?: boolean; + filters?: CloudCatalogFilters; + catalogCredentials?: ReadonlySet; + } = {}, +): Promise { + const url = new URL('/v1/catalog/view', baseUrl); + for (const [name, value] of Object.entries(options.filters ?? {})) { + if (value !== undefined) url.searchParams.set(name, value); + } if (options.live) url.searchParams.set('availability', 'live'); const response = await fetchCloudApi(url, { method: 'GET', headers: { authorization: `Bearer ${accessToken}` }, signal: AbortSignal.timeout(30_000), }); - const rows = await readCloudJsonResponse(response, { + const body = await readCloudJsonResponse(response, { origin: url.origin, - rejectedMessage: 'Cloud session API could not list vendors.', + rejectedMessage: 'Cloud session API could not list the catalog.', + maxBytes: MAX_CATALOG_RESPONSE_BYTES, }); + const view = asCloudRecord(body); if ( - !Array.isArray(rows) || - !rows.every(isCloudVendorRow) || - containsCloudCredential(rows, [accessToken, ...(options.catalogCredentials ?? [])]) + !view || + typeof view.version !== 'number' || + !Array.isArray(view.nodes) || + !Array.isArray(view.data) || + !hasCatalogJsonDepth(body, 0) || + containsCloudCredential(body, [accessToken, ...(options.catalogCredentials ?? [])]) ) { - throw new AppError('COMMAND_FAILED', 'Cloud session API returned an invalid vendor list.'); + throw invalidCatalogView(); } - if (!options.live) return rows; - const checkedAt = new Date().toISOString(); - return rows.map((row) => - row.availability ? row : { ...row, availability: unsupportedAvailability(checkedAt) }, - ); + return { version: view.version, nodes: view.nodes, data: view.data }; } -function unsupportedAvailability(checkedAt: string): CloudVendorAvailability { - return { - state: 'unknown', - reason: 'live_availability_unsupported', - checkedAt, - scope: 'broker_vendor', - }; +function invalidCatalogView(): AppError { + return new AppError('COMMAND_FAILED', 'Cloud session API returned an invalid catalog view.'); +} + +function hasCatalogJsonDepth(value: unknown, depth: number): boolean { + if (depth > MAX_CATALOG_JSON_DEPTH) return false; + if (Array.isArray(value)) { + return value.every((item) => hasCatalogJsonDepth(item, depth + 1)); + } + const record = asCloudRecord(value); + return !record || Object.values(record).every((item) => hasCatalogJsonDepth(item, depth + 1)); +} + +const INDENT = ' '; + +type CatalogOutput = { + lines: string[]; + length: number; +}; + +function appendLine(output: CatalogOutput, line: string): void { + output.length += line.length + 1; + if (output.length > MAX_CATALOG_OUTPUT_LENGTH) { + throw new AppError('COMMAND_FAILED', 'Cloud catalog display exceeds the output limit.'); + } + output.lines.push(line); +} + +type CatalogRow = { cells: string[]; book?: string }; + +/** Renders the node kinds `heading`, `group`, `row`, `text` and `note`. Other kinds are skipped. */ +export function renderCloudCatalogView(nodes: readonly unknown[]): string { + const output: CatalogOutput = { lines: [], length: 0 }; + renderNodes(nodes, 0, undefined, output); + return output.lines.join('\n'); } -function isCloudVendorRow(value: unknown): value is CloudVendorRow { - const row = asCloudRecord(value); - return ( - !!row && - isCloudText(row.vendor) && - isCloudText(row.platform) && - typeof row.usdPerMinute === 'number' && - Number.isFinite(row.usdPerMinute) && - isCloudTextArray(row.capabilities) && - typeof row.viewer === 'boolean' && - typeof row.available === 'boolean' && - isOptional(row.usdMicrosPerMinute, isMicros) && - isOptional(row.minMinutes, isPositiveInteger) && - isOptional(row.availability, isAvailability) - ); +/** Server text never reaches the terminal as a control sequence. */ +function printable(text: string): string { + return [...text].filter((char) => !isControl(char.codePointAt(0)!)).join(''); } -function isOptional(value: unknown, valid: (value: unknown) => boolean): boolean { - return value === undefined || valid(value); +function isControl(code: number): boolean { + return code < 0x20 || (code >= 0x7f && code <= 0x9f); } -function isMicros(value: unknown): boolean { - return readMicroUsd(value) !== undefined; +/** The node's text field, when it is non-empty text. */ +function textOf(node: Record, field: string): string | undefined { + const value = node[field]; + return isCloudText(value) ? printable(value) : undefined; } -function isPositiveInteger(value: unknown): boolean { - return typeof value === 'number' && Number.isSafeInteger(value) && value > 0; +function renderNodes( + nodes: readonly unknown[], + depth: number, + columns: string[] | undefined, + output: CatalogOutput, +): void { + const pad = INDENT.repeat(depth); + const rows: CatalogRow[] = []; + const flushRows = () => { + for (const line of table(columns, rows)) appendLine(output, pad + line); + rows.length = 0; + }; + for (const value of nodes) { + const node = asCloudRecord(value); + if (!node) continue; + const row = catalogRow(node); + if (row) { + rows.push(row); + continue; + } + flushRows(); + renderNode(node, depth, output); + } + flushRows(); } -function isAvailability(value: unknown): boolean { - const availability = asCloudRecord(value); - return ( - !!availability && - isMember(AVAILABILITY_STATES, availability.state) && - isOptional(availability.reason, (reason) => isMember(AVAILABILITY_REASONS, reason)) && - typeof availability.checkedAt === 'string' && - Number.isFinite(Date.parse(availability.checkedAt)) && - availability.scope === 'broker_vendor' - ); +function catalogRow(node: Record): CatalogRow | undefined { + if (node.kind !== 'row' || !isTextArray(node.cells)) return undefined; + const book = textOf(node, 'book'); + return { cells: node.cells.map(printable), ...(book !== undefined && { book }) }; } -function isMember(set: readonly string[], value: unknown): boolean { - return typeof value === 'string' && set.includes(value); +function renderNode(node: Record, depth: number, output: CatalogOutput): void { + const pad = INDENT.repeat(depth); + const text = textOf(node, 'text'); + if (node.kind === 'heading' && text !== undefined) { + if (output.lines.length > 0) appendLine(output, ''); + appendLine(output, pad + text); + } else if (node.kind === 'text' && text !== undefined) { + appendLine(output, pad + text); + } else if (node.kind === 'note' && text !== undefined) { + appendLine(output, `${pad}Note: ${text}`); + } else if (node.kind === 'group') { + renderGroup(node, depth, output); + } +} + +function renderGroup(node: Record, depth: number, output: CatalogOutput): void { + const title = textOf(node, 'title'); + if (title === undefined || !Array.isArray(node.children)) return; + appendLine(output, INDENT.repeat(depth) + title); + const columns = isTextArray(node.columns) ? node.columns.map(printable) : undefined; + renderNodes(node.children, depth + 1, columns, output); +} + +/** Left-aligned columns. A row's `book` hint is the last column. */ +function* table(columns: string[] | undefined, rows: readonly CatalogRow[]) { + if (rows.length === 0) return; + const withBook = rows.some((row) => row.book !== undefined); + const header = columns ? [...columns, ...(withBook ? ['book'] : [])] : undefined; + const body = rows.map((row) => [...row.cells, ...(withBook ? [row.book ?? ''] : [])]); + const all = header ? [header, ...body] : body; + const widths: number[] = []; + for (const cells of all) { + cells.forEach((cell, index) => { + widths[index] = Math.max(widths[index] ?? 0, cell.length); + }); + } + for (const cells of all) { + yield cells + .map((cell, index) => (index === cells.length - 1 ? cell : cell.padEnd(widths[index]!))) + .join(' ') + .trimEnd(); + } } -export function formatCloudVendorRow(row: CloudVendorRow): string { - const minimum = row.minMinutes === undefined ? '' : ` minimum: ${row.minMinutes} min`; - const { availability } = row; - const live = availability - ? ` availability: ${availability.state}${availability.reason ? ` (${availability.reason})` : ''}` - : ''; - return `${row.vendor} ${row.platform} $${row.usdPerMinute}/min${minimum} capabilities: ${row.capabilities.join(', ') || 'none'} live view: ${row.viewer ? 'yes' : 'no'} available: ${row.available ? 'yes' : 'no'}${live}`; +function isTextArray(value: unknown): value is string[] { + return Array.isArray(value) && value.every((item) => typeof item === 'string'); } diff --git a/src/cli/connection/provider-admission.ts b/src/cli/connection/provider-admission.ts index 4704cec9979..21822f2cc99 100644 --- a/src/cli/connection/provider-admission.ts +++ b/src/cli/connection/provider-admission.ts @@ -24,10 +24,11 @@ export async function preflightConnect( await primeProviderConnection(provider, host.env); if (!isConnectProviderName(provider, host.env)) return parsed; } - if (parsed.providedFlags.some(({ key }) => key === 'live')) { + const listingOnly = parsed.providedFlags.find(({ key }) => key === 'live' || key === 'form'); + if (listingOnly) { throw new AppError( 'INVALID_ARGS', - '--live requires a catalog listing. Use connect cloud list.', + `${listingOnly.token} requires a catalog listing. Use connect cloud list.`, ); } if ( diff --git a/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index 98282bc428a..1b7436150a6 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -512,7 +512,7 @@ Remote connection providers use the same lifecycle: connect -> install/open -> commands -> close -> disconnect Providers: - Cloud: agent-device connect cloud --platform ios|android starts a hosted session. Use --needs to require capabilities, --vendor to select a vendor, --device and --os to select a configuration, and --max-minutes to request a duration. Use --max-usd to cap the session charge. Use --app-url to preload an app from an HTTPS archive on a supported offering. Use connect cloud list for the catalog. connect cloud succeeds only when the assigned device answers a fresh read of its text size setting (settings text-size, no value), or an unrecorded snapshot when its provider has no text-size read. It takes the lease of a proxy front first and never launches an app, changes a setting, or installs a runner. The next command uses that device and lease without another wait. One budget of 300 s starts after sign-in and covers the lock, allocation, lease, check, and publication for every vendor. Progress goes to stderr; --json prints one result with ready: true and readyElapsedMs. A failure tries to end the lease and hosted session, reports details.cleanup (run disconnect when it is unconfirmed), and names details.reason and details.stage: connect_timeout, connect_cancelled (exit 130 after Ctrl-C), target_mismatch, probe_unsupported, or probe_invalid_reply. Run the same connect again to retry; on a ready session it checks the same device again and reports the same session. Switching a session name between a direct and a hosted connection needs disconnect first (connection_kind_conflict); --force replaces a hosted connection and ends its old allocation first. + Cloud: agent-device connect cloud --platform ios|android starts a hosted session. Use --needs to require capabilities, --vendor to select a vendor, --device and --os to select a configuration, and --max-minutes to request a duration. Use --max-usd to cap the session charge. Use --app-url to preload an app from an HTTPS archive on a supported offering. Pick a device with connect cloud list. Filter offers with --platform, --form, --device and --os. Config file keys platform, device and osVersion set filter defaults. Pass the flags from the book column to connect cloud --session . If those flags omit --platform, pass the platform shown for the offer. --json prints the machine-readable rows. connect cloud succeeds only when the assigned device answers a fresh read of its text size setting (settings text-size, no value), or an unrecorded snapshot when its provider has no text-size read. It takes the lease of a proxy front first and never launches an app, changes a setting, or installs a runner. The next command uses that device and lease without another wait. One budget of 300 s starts after sign-in and covers the lock, allocation, lease, check, and publication for every vendor. Progress goes to stderr; --json prints one result with ready: true and readyElapsedMs. A failure tries to end the lease and hosted session, reports details.cleanup (run disconnect when it is unconfirmed), and names details.reason and details.stage: connect_timeout, connect_cancelled (exit 130 after Ctrl-C), target_mismatch, probe_unsupported, or probe_invalid_reply. Run the same connect again to retry; on a ready session it checks the same device again and reports the same session. Switching a session name between a direct and a hosted connection needs disconnect first (connection_kind_conflict); --force replaces a hosted connection and ends its old allocation first. Remote config: agent-device connect --remote-config ./remote-config.json uses a local profile. Direct proxy: agent-device connect proxy --daemon-base-url stores the shared proxy profile and client identity. Use https or a loopback http URL such as an ssh -L forward. Other plain http URLs fail with insecure_credential_transport unless AGENT_DEVICE_ALLOW_INSECURE_TRANSPORT=1 is set in the client environment. BrowserStack (plugin, install separately): agent-device connect browserstack verifies credentials, the exact device, and a bs:// app reference, then stores a local provider profile. It does not create an App Automate session. diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 70beee718a3..e6afb9b4a2a 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -2697,7 +2697,15 @@ agent-device disconnect --remote-config ./agent-device.remote.json ### Cloud catalog -Use `connect cloud list` for the catalog when a provider owns the name `list`. +Use `connect cloud list` to pick a device. It prints each device, its OS versions, and the offers for each OS. The cloud service decides the groups, labels, and order. Use `connect cloud list` for the catalog when a provider owns the name `list`. + +Each offer row ends with a `book` hint. Pass those flags to `connect cloud` with a session name. If the hint omits `--platform`, also pass the platform shown for the offer. + +```bash +agent-device connect cloud list --platform ios +agent-device connect cloud list --device iphone-17e --os "iOS 27" +agent-device connect cloud --session +``` Authenticate with the selected cloud's CLI login or `AGENT_DEVICE_CLOUD_API_KEY`. A custom origin also requires the key's origin in `AGENT_DEVICE_CLOUD_API_KEY_ORIGIN`. @@ -2705,8 +2713,14 @@ Authenticate with the selected cloud's CLI login or `AGENT_DEVICE_CLOUD_API_KEY` | --- | --- | | `--config ` | Read operator settings, including the state directory, from this config file | | `--state-dir ` | Read the stored CLI login from this state directory | +| `--platform ` | Show only devices of this platform | +| `--form ` | Show only devices of this form, for example `phone` or `tablet` | +| `--device ` | Show only this device | +| `--os ` | Show only this OS version, for example `"iOS 27"` | | `--live` | Request advisory availability | -| `--json` | Print the catalog rows as JSON | +| `--json` | Print the offer rows as JSON | + +You can set default filters with the `platform`, `device`, and `osVersion` config file keys. Command-line filters take precedence. A filter value that matches no device prints an empty catalog with a note. The following option table describes `connect [provider]`. @@ -2715,7 +2729,7 @@ The following option table describes `connect [provider]`. Configure remote or provider state. ```bash -agent-device connect [cloud] list [--live] [--json] | connect cloud --platform ios|android [--vendor ] [--max-minutes ] [--max-usd ] [--app-url ] [--needs ] [--device ] [--os ] [--show-viewer] | connect [provider] [--target ] [--remote-config ] [--daemon-base-url ] [--tenant ] [--run-id ] [--lease-id ] [--lease-backend ] [--force] [--no-login] +agent-device connect [cloud] list [--platform ios|android] [--form ] [--device ] [--os ] [--live] [--json] | connect cloud --platform ios|android [--vendor ] [--max-minutes ] [--max-usd ] [--app-url ] [--needs ] [--device ] [--os ] [--show-viewer] | connect [provider] [--target ] [--remote-config ] [--daemon-base-url ] [--tenant ] [--run-id ] [--lease-id ] [--lease-backend ] [--force] [--no-login] ``` | Option | What it does |