From 99a7b6fa1261a0385601175fd3d2fbddc3bc8388 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 20 Nov 2026 08:21:55 +0100 Subject: [PATCH 1/7] feat(plugins): add the platform contribution kind --- packages/contracts/package.json | 4 + packages/contracts/src/plugin-inventory.ts | 8 +- packages/contracts/src/web-provider.ts | 68 ++++++ .../request-router-replay-plugin.test.ts | 2 +- .../daemon/src/server/http/daemon-runtime.ts | 1 + .../daemon/src/server/http/server-shutdown.ts | 25 ++- .../daemon/src/sessions/handlers/lease.ts | 1 + packages/maestro/src/plugin.test.ts | 3 +- packages/platform-web/src/provider.ts | 80 +------ packages/plugins/src/contract.ts | 4 + packages/plugins/src/discovery.ts | 6 +- packages/plugins/src/platform.test.ts | 203 ++++++++++++++++++ packages/plugins/src/platform.ts | 83 +++++++ packages/plugins/src/registry.ts | 136 +++++++++--- packages/plugins/src/store.ts | 39 +++- packages/plugins/src/validate.ts | 167 +++++++++----- packages/replay/src/plugin.test.ts | 3 +- .../install-workspace-replay-plugins.test.ts | 10 +- .../layering/contracts-exports.snapshot.json | 3 +- src/cli/commands/daemon.ts | 2 +- src/cli/commands/plugins.ts | 2 +- src/provider-device-runtimes.ts | 2 +- src/sdk/plugins.ts | 3 + 23 files changed, 668 insertions(+), 187 deletions(-) create mode 100644 packages/contracts/src/web-provider.ts create mode 100644 packages/plugins/src/platform.test.ts create mode 100644 packages/plugins/src/platform.ts diff --git a/packages/contracts/package.json b/packages/contracts/package.json index 219268bc02..8bd39bc066 100644 --- a/packages/contracts/package.json +++ b/packages/contracts/package.json @@ -312,6 +312,10 @@ "types": "./src/logs-runtime-plan.ts", "default": "./src/logs-runtime-plan.ts" }, + "./web-provider": { + "types": "./src/web-provider.ts", + "default": "./src/web-provider.ts" + }, "./managed-web-backend": { "types": "./src/managed-web-backend.ts", "default": "./src/managed-web-backend.ts" diff --git a/packages/contracts/src/plugin-inventory.ts b/packages/contracts/src/plugin-inventory.ts index 4a697c4515..a340df132e 100644 --- a/packages/contracts/src/plugin-inventory.ts +++ b/packages/contracts/src/plugin-inventory.ts @@ -17,6 +17,7 @@ export type PluginInventoryCredentials = Readonly<{ type PluginInventoryIdentity = Readonly<{ provider?: string; backend?: string; + platform?: string; source: PluginSource; package?: string; version?: string; @@ -38,7 +39,11 @@ export type PluginCleanupStep = * dispose, which reads as `ok`. */ export type PluginCleanupOutcome = Readonly< - ({ provider: string; backend?: never } | { backend: string; provider?: never }) & { + ( + | { provider: string; backend?: never; platform?: never } + | { backend: string; provider?: never; platform?: never } + | { platform: string; provider?: never; backend?: never } + ) & { source: PluginSource; shutdown: PluginCleanupStep; dispose: PluginCleanupStep; @@ -82,6 +87,7 @@ function readEntry(value: unknown): PluginInventoryEntry | undefined { const identity = { ...(typeof value.provider === 'string' ? { provider: value.provider } : {}), ...(typeof value.backend === 'string' ? { backend: value.backend } : {}), + ...(typeof value.platform === 'string' ? { platform: value.platform } : {}), source: value.source, ...(typeof value.package === 'string' ? { package: value.package } : {}), ...(typeof value.version === 'string' ? { version: value.version } : {}), diff --git a/packages/contracts/src/web-provider.ts b/packages/contracts/src/web-provider.ts new file mode 100644 index 0000000000..6536762600 --- /dev/null +++ b/packages/contracts/src/web-provider.ts @@ -0,0 +1,68 @@ +import type { ScrollDirection } from './scroll-gesture.ts'; +import type { SessionSurface } from './session-surface.ts'; +import type { RawSnapshotNode } from '@agent-device/kernel/snapshot'; +import type { BackendDumpNetworkOptions, BackendDumpNetworkResult } from './backend-diagnostics.ts'; +import type { AudioProbeResult } from './audio-probe-result.ts'; + +export type WebOpenOptions = { + url?: string; +}; + +export type WebScreenshotOptions = { + fullscreen?: boolean; + stabilize?: boolean; + surface?: SessionSurface; +}; + +export type WebSnapshotOptions = { + interactiveOnly?: boolean; + depth?: number; + scope?: string; + includeRects?: boolean; + surface?: SessionSurface; + signal?: AbortSignal; +}; + +export type WebSnapshotResult = { + nodes: RawSnapshotNode[]; + truncated?: boolean; +}; + +export type WebAudioProbeAction = 'start' | 'status' | 'stop'; + +export type WebAudioProbeOptions = { + action: WebAudioProbeAction; + durationMs?: number; + bucketMs?: number; +}; + +export type WebAudioProbeResult = AudioProbeResult & { + source: 'media-elements'; + mediaElementCount: number; +}; + +export type WebProvider = { + open(target: string, options?: WebOpenOptions): Promise; + close(target?: string): Promise; + startRecording?(outPath: string): Promise; + stopRecording?(): Promise; + snapshot(options?: WebSnapshotOptions): Promise; + screenshot(outPath: string, options?: WebScreenshotOptions): Promise; + setViewport(width: number, height: number): Promise; + click(x: number, y: number): Promise; + clickRef?(ref: string): Promise; + /** Move the pointer to a point without pressing, raising the page's hover state. */ + hover?(x: number, y: number): Promise; + /** Hover a snapshot ref through the provider's own element handle. */ + hoverRef?(ref: string): Promise; + fill(x: number, y: number, text: string, options?: { delayMs?: number }): Promise; + fillRef?(ref: string, text: string, options?: { delayMs?: number }): Promise; + typeText(text: string, options?: { delayMs?: number }): Promise; + scroll( + direction: ScrollDirection, + options?: { amount?: number; pixels?: number; durationMs?: number }, + ): Promise | void>; + readText?(x: number, y: number): Promise; + dumpNetwork?(options?: BackendDumpNetworkOptions): Promise; + probeAudio?(options: WebAudioProbeOptions): Promise; +}; diff --git a/packages/daemon/src/server/__tests__/request-router-replay-plugin.test.ts b/packages/daemon/src/server/__tests__/request-router-replay-plugin.test.ts index 1ad1e35dab..bce9e74ffa 100644 --- a/packages/daemon/src/server/__tests__/request-router-replay-plugin.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-replay-plugin.test.ts @@ -21,7 +21,7 @@ async function fixture(storeEnv?: NodeJS.ProcessEnv) { await resolveProviderPlugins([]), { env: {}, cwd: '/' }, { - assertReplaySelectionCurrent: storeEnv ? createPluginSelectionGuard([], storeEnv) : undefined, + assertSelectionCurrent: storeEnv ? createPluginSelectionGuard([], storeEnv) : undefined, adaptWebDriver: async () => { throw new Error('no provider'); }, diff --git a/packages/daemon/src/server/http/daemon-runtime.ts b/packages/daemon/src/server/http/daemon-runtime.ts index 0c34e07593..8ada67cf48 100644 --- a/packages/daemon/src/server/http/daemon-runtime.ts +++ b/packages/daemon/src/server/http/daemon-runtime.ts @@ -668,6 +668,7 @@ async function startDaemonRuntimeOnHost( for (const plugin of deps.pluginInventory.filter(({ state }) => state === 'failed')) { await emitDaemonDiagnostic(logPath, 'provider_plugin_failed', { provider: plugin.provider, + platform: plugin.platform, package: plugin.package, source: plugin.source, code: plugin.error?.code, diff --git a/packages/daemon/src/server/http/server-shutdown.ts b/packages/daemon/src/server/http/server-shutdown.ts index d269471eaa..d30bdf7b64 100644 --- a/packages/daemon/src/server/http/server-shutdown.ts +++ b/packages/daemon/src/server/http/server-shutdown.ts @@ -71,6 +71,7 @@ export type ShutdownReport = { failed: { provider?: string; backend?: string; + platform?: string; source?: PluginCleanupOutcome['source']; step: 'shutdown' | 'dispose'; error: NormalizedError; @@ -162,7 +163,9 @@ export function createPluginClose(params: { }): PluginClose { let closing: Promise | undefined; const cleanupOwners = params.inventory.flatMap((entry) => - entry.state === 'active' ? [{ provider: entry.provider, backend: entry.backend }] : [], + entry.state === 'active' + ? [{ provider: entry.provider, backend: entry.backend, platform: entry.platform }] + : [], ); return { close: () => @@ -175,9 +178,7 @@ export function createPluginClose(params: { return { disposed: [], failed: [], - pending: cleanupOwners.map( - ({ provider, backend }) => provider ?? `replay-backend:${backend}`, - ), + pending: cleanupOwners.map(pluginCleanupName), }; } if (outcome.kind === 'rejected') { @@ -227,8 +228,7 @@ function reportCleanupOutcomes( outcomes: readonly PluginCleanupOutcome[], ): ShutdownReport['plugins'] { const report: ShutdownReport['plugins'] = { disposed: [], failed: [], pending: [] }; - for (const { provider, backend, source, shutdown, dispose } of outcomes) { - const identity = provider === undefined ? { backend } : { provider }; + for (const { source, shutdown, dispose, ...identity } of outcomes) { for (const [step, result] of [ ['shutdown', shutdown], ['dispose', dispose], @@ -243,11 +243,22 @@ function reportCleanupOutcomes( }); } if (shutdown.status === 'ok' && dispose.status === 'ok') - report.disposed.push(provider ?? `replay-backend:${backend}`); + report.disposed.push(pluginCleanupName(identity)); } return report; } +function pluginCleanupName(identity: { + provider?: string; + backend?: string; + platform?: string; +}): string { + return ( + identity.provider ?? + (identity.platform ? `platform:${identity.platform}` : `replay-backend:${identity.backend}`) + ); +} + /** Undoes startup work in reverse order; a step that throws never stops the ones before it. */ export type StartupRollback = Readonly<{ onRollback(step: () => Promise | void): void; diff --git a/packages/daemon/src/sessions/handlers/lease.ts b/packages/daemon/src/sessions/handlers/lease.ts index bd3186db08..eeb9491790 100644 --- a/packages/daemon/src/sessions/handlers/lease.ts +++ b/packages/daemon/src/sessions/handlers/lease.ts @@ -439,6 +439,7 @@ function assertProviderRuntimeRegistered( const failures = failedPlugins.flatMap((plugin) => plugin.state === 'failed' && plugin.backend === undefined && + plugin.platform === undefined && (plugin.provider === provider || plugin.provider === undefined) ? [ { diff --git a/packages/maestro/src/plugin.test.ts b/packages/maestro/src/plugin.test.ts index e3e0996adc..08d914bf8f 100644 --- a/packages/maestro/src/plugin.test.ts +++ b/packages/maestro/src/plugin.test.ts @@ -12,7 +12,8 @@ function contributionOf( plugin: AgentDevicePlugin, ): ReplayBackendContribution | ReplayExecutionContribution { const [contribution] = plugin.contributes; - if (contribution.kind === 'provider') throw new Error('expected a replay contribution'); + if (contribution.kind !== 'replay-backend' && contribution.kind !== 'replay-execution') + throw new Error('expected a replay contribution'); return contribution; } diff --git a/packages/platform-web/src/provider.ts b/packages/platform-web/src/provider.ts index f13fb6d080..360e559f7f 100644 --- a/packages/platform-web/src/provider.ts +++ b/packages/platform-web/src/provider.ts @@ -1,76 +1,14 @@ -import type { ScrollDirection } from '@agent-device/contracts/scroll-gesture'; -import type { SessionSurface } from '@agent-device/contracts/session'; import { AppError } from '@agent-device/kernel/errors'; import { createScopedProvider } from '@agent-device/kernel/scoped-provider'; -import type { RawSnapshotNode } from '@agent-device/kernel/snapshot'; -import type { - BackendDumpNetworkOptions, - BackendDumpNetworkResult, -} from '@agent-device/contracts/backend-diagnostics'; -import type { AudioProbeResult } from '@agent-device/contracts/audio-probe-result'; - -export type WebOpenOptions = { - url?: string; -}; - -export type WebScreenshotOptions = { - fullscreen?: boolean; - stabilize?: boolean; - surface?: SessionSurface; -}; - -export type WebSnapshotOptions = { - interactiveOnly?: boolean; - depth?: number; - scope?: string; - includeRects?: boolean; - surface?: SessionSurface; - signal?: AbortSignal; -}; - -export type WebSnapshotResult = { - nodes: RawSnapshotNode[]; - truncated?: boolean; -}; - -export type WebAudioProbeAction = 'start' | 'status' | 'stop'; - -export type WebAudioProbeOptions = { - action: WebAudioProbeAction; - durationMs?: number; - bucketMs?: number; -}; - -export type WebAudioProbeResult = AudioProbeResult & { - source: 'media-elements'; - mediaElementCount: number; -}; - -export type WebProvider = { - open(target: string, options?: WebOpenOptions): Promise; - close(target?: string): Promise; - startRecording?(outPath: string): Promise; - stopRecording?(): Promise; - snapshot(options?: WebSnapshotOptions): Promise; - screenshot(outPath: string, options?: WebScreenshotOptions): Promise; - setViewport(width: number, height: number): Promise; - click(x: number, y: number): Promise; - clickRef?(ref: string): Promise; - /** Move the pointer to a point without pressing, raising the page's hover state. */ - hover?(x: number, y: number): Promise; - /** Hover a snapshot ref through the provider's own element handle. */ - hoverRef?(ref: string): Promise; - fill(x: number, y: number, text: string, options?: { delayMs?: number }): Promise; - fillRef?(ref: string, text: string, options?: { delayMs?: number }): Promise; - typeText(text: string, options?: { delayMs?: number }): Promise; - scroll( - direction: ScrollDirection, - options?: { amount?: number; pixels?: number; durationMs?: number }, - ): Promise | void>; - readText?(x: number, y: number): Promise; - dumpNetwork?(options?: BackendDumpNetworkOptions): Promise; - probeAudio?(options: WebAudioProbeOptions): Promise; -}; +import type { WebProvider } from '@agent-device/contracts/web-provider'; + +export type { + WebSnapshotOptions, + WebSnapshotResult, + WebAudioProbeOptions, + WebAudioProbeResult, + WebProvider, +} from '@agent-device/contracts/web-provider'; /** * The un-composed fallback: a request that reaches a web device without a composed provider is a diff --git a/packages/plugins/src/contract.ts b/packages/plugins/src/contract.ts index 37f0ec3b0e..c58a3b15b7 100644 --- a/packages/plugins/src/contract.ts +++ b/packages/plugins/src/contract.ts @@ -4,6 +4,7 @@ import type { ProviderConnectionVerification, RemoteConfigProfile, } from '@agent-device/contracts/remote'; +import type { PlatformContribution } from './platform.ts'; import type { ProviderPluginHost } from './host.ts'; import type { ReplayBackendContribution, ReplayExecutionContribution } from './replay-backend.ts'; @@ -104,9 +105,12 @@ export type ProviderContribution> | PluginSetupResult; }>; +export type { PlatformContribution, PlatformHost, PlatformSetup } from './platform.ts'; + /** One independently activated claim a plugin declares. New kinds need an explicit decision. */ export type Contribution = | ProviderContribution + | PlatformContribution | ReplayBackendContribution | ReplayExecutionContribution; diff --git a/packages/plugins/src/discovery.ts b/packages/plugins/src/discovery.ts index 09edb54a08..5625829a9a 100644 --- a/packages/plugins/src/discovery.ts +++ b/packages/plugins/src/discovery.ts @@ -10,8 +10,10 @@ import { readPluginPackageClaims, type PluggedClaim } from './validate.ts'; * order. Read before any import: the apiVersion must be the supported one, and every declared claim * must be unreserved. After the factory runs, its returned claims must equal these, in any order. */ -export function readAgentDeviceClaims(manifest: Record): readonly PluggedClaim[] { - return readPluginPackageClaims(manifest['agent-device']); +export async function readAgentDeviceClaims( + manifest: Record, +): Promise { + return await readPluginPackageClaims(manifest['agent-device']); } /** diff --git a/packages/plugins/src/platform.test.ts b/packages/plugins/src/platform.test.ts new file mode 100644 index 0000000000..e26a2bcbf6 --- /dev/null +++ b/packages/plugins/src/platform.test.ts @@ -0,0 +1,203 @@ +import { expect, test } from 'vitest'; +import { pluginHome, selectPlugin } from '@agent-device/test-kit'; +import { missingOptionalPlatformError } from '@agent-device/contracts/platform-module'; +import type { HostEnvironment } from '@agent-device/kernel/source-value'; +import { createPluginSelectionGuard, storePluginCandidates } from './store.ts'; +import { resolveProviderPlugins, startProviderRegistry } from './registry.ts'; + +const WEB_PACKAGE = '@agent-device/web'; +const stateDir = '/fixture-state'; +const reportAbsent = (family: Parameters[0]) => + missingOptionalPlatformError(family, '0.22.0'); + +const platformClaim = `{ + kind: 'platform', + family: 'web', + setup: host => ({ + family: 'web', + inventoryModule: { family: 'web', loadInventory: async () => ({ + discover: async () => [{ id: host.stateDir, platform: 'web', kind: 'device' }], + }) }, + runtimeModule: { family: 'web', loadRuntime() { throw new Error('must stay lazy'); } }, + createInteractor() { throw new Error('must stay lazy'); }, + withRequestProvider: async (_, task) => task(), + operations: { + setup() {}, + doctor() {}, + cleanupOrphans() { throw new Error('startup operation is not a disposer'); }, + browserLifecycleCheck() {}, + createProvider() {}, + resolveRequestProvider() {}, + }, + }), +}`; + +function selectWeb(home: string, opts: Parameters[3] = {}) { + selectPlugin( + home, + WEB_PACKAGE, + `export default () => ({ apiVersion: 3, contributes: [${platformClaim}] });`, + { claims: { apiVersion: 3, platform: 'web' }, ...opts }, + ); +} + +async function startStore(env: HostEnvironment['env']) { + const candidates = await storePluginCandidates(env); + const host = { env, cwd: '/' }; + const resolved = await resolveProviderPlugins(candidates); + return await startProviderRegistry(resolved, host, { + platformHost: { + ...host, + stateDir, + runCommand: async () => { + throw new Error('setup must not start a process'); + }, + emitDiagnostic: () => {}, + withDiagnosticTimer: async (_phase, run) => await run(), + }, + assertSelectionCurrent: createPluginSelectionGuard(candidates, env), + adaptWebDriver: async () => { + throw new Error('unexpected WebDriver'); + }, + }); +} + +test('a managed platform registers its inventory against the supplied state directory and closes once', async () => { + const { home, env } = pluginHome(); + selectWeb(home); + const registry = await startStore(env); + expect(registry.inventory).toEqual([ + { + source: 'store', + package: WEB_PACKAGE, + version: '2.0.0', + platform: 'web', + state: 'active', + credentials: { variables: [], byBackend: {} }, + }, + ]); + const platform = registry.resolvePlatform('web', reportAbsent, WEB_PACKAGE); + if (platform.family !== 'web') throw new Error('expected web'); + const inventory = await platform.inventoryModule.loadInventory(); + expect( + await inventory.discover( + {}, + { + signal: new AbortController().signal, + diagnostics: { emit() {} }, + progress: { report() {} }, + }, + ), + ).toEqual([{ id: stateDir, platform: 'web', kind: 'device' }]); + const closing = registry.close(); + expect(registry.close()).toBe(closing); + await expect(closing).resolves.toEqual([ + { platform: 'web', source: 'store', shutdown: { status: 'ok' }, dispose: { status: 'ok' } }, + ]); + expect(() => registry.resolvePlatform('web', reportAbsent, WEB_PACKAGE)).toThrow( + expect.objectContaining({ details: { reason: 'plugin-registry-closed' } }), + ); +}); + +test('a missing platform has an install hint, and adding it to a running set requires restart', async () => { + const { home, env } = pluginHome(); + const registry = await startStore(env); + expect(() => registry.resolvePlatform('web', reportAbsent, WEB_PACKAGE)).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ + reason: 'plugin-not-installed', + installCommand: 'agent-device plugins add @agent-device/web', + }), + }), + ); + selectWeb(home); + expect(() => registry.resolvePlatform('web', reportAbsent, WEB_PACKAGE)).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'daemon-plugin-set-stale', package: WEB_PACKAGE }), + }), + ); + await registry.close(); +}); + +test.each([ + [ + 'required family', + 'apple', + platformClaim.replace("family: 'web'", "family: 'apple'"), + 'reserved_platform', + ], + ['unknown family', 'example', platformClaim, 'invalid_plugin'], + ['factory mismatch', 'linux', platformClaim, 'invalid_plugin'], + [ + 'wrong runtime family', + 'web', + platformClaim.replace("runtimeModule: { family: 'web'", "runtimeModule: { family: 'linux'"), + 'invalid_plugin', + ], + ['missing operation', 'web', platformClaim.replace('doctor() {},', ''), 'invalid_plugin'], +])('rejects a platform claim with %s', async (_description, family, claim, reason) => { + const { home, env } = pluginHome(); + selectPlugin( + home, + WEB_PACKAGE, + `export default () => ({ apiVersion: 3, contributes: [${claim}] });`, + { + claims: { apiVersion: 3, platform: family }, + }, + ); + const registry = await startStore(env); + expect(registry.platforms).toEqual([]); + expect(registry.inventory).toMatchObject([{ state: 'failed', error: { reason } }]); + await registry.close(); +}); + +test('a below-floor package retains its platform claim without importing its entry', async () => { + const { home, env } = pluginHome(); + selectPlugin(home, WEB_PACKAGE, "throw new Error('must never import');", { + claims: { apiVersion: 3, platform: 'web' }, + manifest: { engines: { node: '>=999' } }, + }); + selectPlugin( + home, + 'later-plugin', + `export default () => ({ apiVersion: 3, contributes: [${platformClaim}] });`, + { + claims: { apiVersion: 3, platform: 'web' }, + }, + ); + const registry = await startStore(env); + expect(registry.inventory).toMatchObject([ + { platform: 'web', state: 'failed', error: { reason: 'node-below-floor' } }, + { platform: 'web', state: 'failed', error: { reason: 'duplicate_platform' } }, + ]); + expect(() => registry.resolvePlatform('web', reportAbsent, WEB_PACKAGE)).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'node-below-floor', package: WEB_PACKAGE }), + }), + ); + await registry.close(); +}); + +test('platform and replay claims in one package activate independently', async () => { + const { home, env } = pluginHome(); + selectPlugin( + home, + WEB_PACKAGE, + `export default () => ({ + apiVersion: 3, + contributes: [${platformClaim}, { + kind: 'replay-backend', + backend: 'fixture', + setup() { throw new Error('replay setup failed'); }, + }], + });`, + { claims: { apiVersion: 3, platform: 'web', replayBackend: 'fixture' } }, + ); + const registry = await startStore(env); + expect(registry.inventory).toMatchObject([ + { platform: 'web', state: 'active' }, + { backend: 'fixture', state: 'failed', error: { reason: 'plugin_setup_failed' } }, + ]); + expect(registry.resolvePlatform('web', reportAbsent, WEB_PACKAGE).family).toBe('web'); + await registry.close(); +}); diff --git a/packages/plugins/src/platform.ts b/packages/plugins/src/platform.ts new file mode 100644 index 0000000000..d402404277 --- /dev/null +++ b/packages/plugins/src/platform.ts @@ -0,0 +1,83 @@ +import type { ManagedWebBackend } from '@agent-device/contracts/managed-web-backend'; +import type { DoctorCheck } from '@agent-device/contracts/observability'; +import type { + InventoryPlatformModule, + OptionalPlatform, +} from '@agent-device/contracts/platform-module'; +import type { PlatformPlugin } from '@agent-device/contracts/platform-plugin'; +import type { PlatformRuntimeModule } from '@agent-device/contracts/platform-runtime-operations'; +import type { WebProvider } from '@agent-device/contracts/web-provider'; +import type { DiagnosticEventInput, withDiagnosticTimer } from '@agent-device/host-kit/diagnostics'; +import type { OwnedProcessRecordStore } from '@agent-device/host-kit/process'; +import type { HostEnvironment } from '@agent-device/kernel/source-value'; + +/** Authority shared by web setup and daemon-owned web sessions. */ +export type PlatformHost = HostEnvironment & + Readonly<{ + stateDir: string; + openWebSessionNames?(): readonly string[]; + ownedProcessRecords?: OwnedProcessRecordStore; + runCommand( + executable: string, + args: string[], + options: { + env?: HostEnvironment['env']; + allowFailure?: boolean; + timeoutMs?: number; + signal?: AbortSignal; + stdin?: string; + }, + ): Promise<{ stdout: string; stderr: string; exitCode: number }>; + emitDiagnostic(event: DiagnosticEventInput): void; + withDiagnosticTimer: typeof withDiagnosticTimer; + }>; + +export type WebPlatformOperations = ManagedWebBackend & + Readonly<{ + cleanupOrphans(openWebSessionNames: readonly string[]): Promise; + browserLifecycleCheck(stateDir: string): Promise; + createProvider(session: string): Promise; + resolveRequestProvider(): Promise; + }>; + +export type PlatformSetup = + Family extends OptionalPlatform + ? Readonly<{ + family: Family; + inventoryModule: Readonly<{ + family: Family; + loadInventory(...args: never[]): Promise; + }>; + runtimeModule: Readonly<{ + family: Family; + loadRuntime(...args: never[]): Promise; + }>; + createInteractor(...args: never[]): Promise; + }> & + (Family extends 'web' + ? Readonly<{ + withRequestProvider(provider: WebProvider, task: () => Promise): Promise; + operations: WebPlatformOperations; + }> + : unknown) + : never; + +/** Full module types used after the composing registry validates the declared family and loaders. */ +export type RegisteredPlatformSetup = + Family extends OptionalPlatform + ? Omit, 'inventoryModule' | 'runtimeModule' | 'createInteractor'> & + Readonly<{ + createInteractor: PlatformPlugin['createInteractor']; + inventoryModule: InventoryPlatformModule; + runtimeModule: PlatformRuntimeModule & { readonly family: Family }; + }> + : never; + +export type PlatformContribution = { + [Family in OptionalPlatform]: Readonly<{ + kind: 'platform'; + family: Family; + /** Registers modules and operations. Setup itself does not start or install the backend. */ + setup(host: PlatformHost): PlatformSetup | Promise>; + }>; +}[OptionalPlatform]; diff --git a/packages/plugins/src/registry.ts b/packages/plugins/src/registry.ts index 42f5860832..c41be34194 100644 --- a/packages/plugins/src/registry.ts +++ b/packages/plugins/src/registry.ts @@ -1,5 +1,6 @@ +import type { OptionalPlatform } from '@agent-device/contracts/platform-module'; +import type { PlatformHost, RegisteredPlatformSetup } from './platform.ts'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; -import { NATIVE_REPLAY_BACKEND } from '@agent-device/contracts/replay-execution'; import type { ReplayExecution, ReplayExecutionResolver, @@ -15,7 +16,6 @@ import { isRecord } from '@agent-device/kernel/record'; import type { ProviderDeviceRuntime } from '@agent-device/contracts/device'; import type { PlatformRuntimeProviderModule } from '@agent-device/contracts/platform-runtime-operations'; import type { - AgentDevicePlugin, Contribution, PluginConnection, PluginSetupResult, @@ -36,7 +36,6 @@ import { describePluginFailure } from './inventory.ts'; import { assertProviderRuntime, claimKeyOf, - claimOfContribution, duplicateClaimError, identityOfClaim, invalidPlugin, @@ -88,7 +87,8 @@ export function claimProviderIds(providers: readonly string[]): PluginCandidate[ * plugin's `{ webDriver }` descriptor becomes a runtime. */ export type PluginRegistryPolicy = Readonly<{ - assertReplaySelectionCurrent?(packageName: string): void; + platformHost?: PlatformHost; + assertSelectionCurrent?(packageName: string): void; adaptWebDriver( descriptor: WebDriverDescriptor, context: Readonly<{ clientVersion: string }>, @@ -116,6 +116,7 @@ type Claim = PluggedClaim & { contribution?: Contribution; failure?: unknown; registration?: ProviderRegistration; + platformSetup?: RegisteredPlatformSetup; replaySetup?: ReplayBackendSetup | ReplayExecutionSetup; replayLoading?: Promise; executionLoading?: Promise; @@ -125,7 +126,6 @@ type Claim = PluggedClaim & { /** A candidate, its load outcome, and the claims it holds. */ type Slot = { candidate: PluginCandidate; - plugin?: AgentDevicePlugin; /** Why this slot cannot answer its claims; each unclaimed entry reports it. */ failure?: unknown; claims: Claim[]; @@ -168,6 +168,12 @@ export type ResolvedProviderPlugins = Readonly<{ export type ProviderRegistry = Readonly<{ registrations: readonly ProviderRegistration[]; + platforms: readonly RegisteredPlatformSetup[]; + resolvePlatform( + family: OptionalPlatform, + reportAbsent: (family: OptionalPlatform) => AppError, + packageName?: string, + ): RegisteredPlatformSetup; resolveReplayBackend: ReplayBackendResolver; resolveReplayExecution: ReplayExecutionResolver; claimedProviders: readonly string[]; @@ -193,7 +199,7 @@ export async function resolveProviderPlugins( for (const candidate of candidates) { const slot: Slot = { candidate, claims: [] }; slots.push(slot); - reserveDeclaredClaims(slot, claimed, !candidate.dormant); + await reserveDeclaredClaims(slot, claimed, !candidate.dormant); if (!candidate.dormant) await loadSlot(slot, claimed); } @@ -226,9 +232,13 @@ export async function resolveProviderPlugins( * of a kind and id wins; a later one is recorded as failed against its own slot, and so is a claim of * an id the host reserves. A dormant slot holds its claims without listing them. */ -function reserveDeclaredClaims(slot: Slot, claimed: ClaimedClaims, list: boolean): void { +async function reserveDeclaredClaims( + slot: Slot, + claimed: ClaimedClaims, + list: boolean, +): Promise { for (const claim of slot.candidate.declaredClaims ?? []) { - const obstacle = claimObstacle(claimed, claim); + const obstacle = await claimObstacle(claimed, claim); if (obstacle !== undefined) { if (list) slot.claims.push({ ...claim, slot, failure: obstacle }); continue; @@ -241,8 +251,11 @@ function reserveDeclaredClaims(slot: Slot, claimed: ClaimedClaims, list: boolean * Why this claim cannot be held: its id belongs to the host, or its space already names it. Nothing * is reserved when there is an obstacle. */ -function claimObstacle(claimed: ClaimedClaims, claim: PluggedClaim): AppError | undefined { - const reserved = reservedClaimError(claim); +async function claimObstacle( + claimed: ClaimedClaims, + claim: PluggedClaim, +): Promise { + const reserved = await reservedClaimError(claim); if (reserved !== undefined) return reserved; return reserveClaim(claimed, claim) ? undefined : duplicateClaimError(claim); } @@ -265,11 +278,9 @@ async function loadSlot(slot: Slot, claimed: ClaimedClaims): Promise { let raw: unknown; try { raw = await slot.candidate.load(); - const plugin = validateAgentDevicePlugin(raw); - assertDeclaredClaims(slot.candidate, plugin); - slot.plugin = plugin; - for (const contribution of plugin.contributes) { - const claim = claimOfContribution(contribution); + const returnedClaims = await validateAgentDevicePlugin(raw); + assertDeclaredClaims(slot.candidate, returnedClaims); + for (const { contribution, ...claim } of returnedClaims) { const reserved = slot.claims.find( (entry) => entry.contribution === undefined && claimKeyOf(entry) === claimKeyOf(claim), ); @@ -277,7 +288,7 @@ async function loadSlot(slot: Slot, claimed: ClaimedClaims): Promise { reserved.contribution = contribution; continue; } - const obstacle = claimObstacle(claimed, claim); + const obstacle = reserveClaim(claimed, claim) ? undefined : duplicateClaimError(claim); slot.claims.push({ ...claim, slot, @@ -291,7 +302,7 @@ async function loadSlot(slot: Slot, claimed: ClaimedClaims): Promise { // A reservation reason (a duplicate or reserved id) is the actionable one; keep it. if (claim.contribution === undefined) claim.failure ??= slot.failure; } - nameFailedClaims(slot, claimed, raw); + await nameFailedClaims(slot, claimed, raw); } } @@ -302,23 +313,20 @@ async function loadSlot(slot: Slot, claimed: ClaimedClaims): Promise { * before the load and is left alone. Each claim carries the slot's own reason, which is the one the * author can act on. */ -function nameFailedClaims(slot: Slot, claimed: ClaimedClaims, raw: unknown): void { +async function nameFailedClaims(slot: Slot, claimed: ClaimedClaims, raw: unknown): Promise { if (slot.candidate.declaredClaims !== undefined || slot.claims.length > 0) return; - for (const claim of readableClaimsOfValue(raw)) { + for (const claim of await readableClaimsOfValue(raw)) { reserveClaim(claimed, claim); slot.claims.push({ ...claim, slot, failure: slot.failure }); } } /** After the factory runs, declared and returned claims must be exactly equal, unordered. */ -function assertDeclaredClaims(candidate: PluginCandidate, plugin: AgentDevicePlugin): void { +function assertDeclaredClaims(candidate: PluginCandidate, returned: readonly PluggedClaim[]): void { const declared = candidate.declaredClaims; if (declared === undefined) return; - const returned = plugin.contributes.map((contribution) => - claimKeyOf(claimOfContribution(contribution)), - ); - const sortedDeclared = declared.map((claim) => claimKeyOf(claim)).sort(); - const sortedReturned = [...returned].sort(); + const sortedDeclared = declared.map(claimKeyOf).sort(); + const sortedReturned = returned.map(claimKeyOf).sort(); if ( sortedDeclared.length !== sortedReturned.length || sortedDeclared.some((key, index) => key !== sortedReturned[index]) @@ -335,6 +343,8 @@ function assertDeclaredClaims(candidate: PluginCandidate, plugin: AgentDevicePlu } } +type RegistryScope = 'all' | 'replay-backends' | 'platforms'; + /** * Sets up every loaded claim in order. A claim whose setup throws, or returns a result the registry * refuses, is cleaned up and recorded as failed; the remaining claims still activate, so a broken @@ -345,7 +355,7 @@ export async function startProviderRegistry( resolved: ResolvedProviderPlugins, host: HostEnvironment, policy: PluginRegistryPolicy, - scope: 'all' | 'replay-backends' = 'all', + scope: RegistryScope = 'all', ): Promise { await setUpClaims(resolved.slots, host, policy, scope); const registrations = resolved.slots.flatMap(({ claims }) => @@ -356,6 +366,29 @@ export async function startProviderRegistry( const refreshInventory = () => inventory.splice(0, inventory.length, ...resolved.inventory()); return Object.freeze({ registrations, + platforms: Object.freeze( + resolved.slots.flatMap(({ claims }) => + claims.flatMap(({ platformSetup }) => (platformSetup ? [platformSetup] : [])), + ), + ), + resolvePlatform: (family, reportAbsent, packageName) => { + if (closed) + throw new AppError('COMMAND_FAILED', 'Plugin registry is closed', { + reason: 'plugin-registry-closed', + }); + const claim = findClaim( + resolved, + { kind: 'platform', id: family }, + packageName, + policy.assertSelectionCurrent, + ); + if (!claim) throw reportAbsent(family); + if (claim.failure !== undefined) { + throw platformClaimError(claim); + } + if (!claim.platformSetup) throw invalidPlugin(`Platform was not set up: ${family}`); + return claim.platformSetup; + }, claimedProviders: resolved.claimedProviders, inventory, resolveReplayBackend: async (id, host, packageName) => { @@ -367,11 +400,12 @@ export async function startProviderRegistry( resolved, { kind: 'replay-backend', id }, packageName, - policy.assertReplaySelectionCurrent, + policy.assertSelectionCurrent, ); return await resolveRegisteredReplayBackend(claim, refreshInventory, host); }, resolveReplayExecution: async (packageName) => { + const { NATIVE_REPLAY_BACKEND } = await import('@agent-device/contracts/replay-execution'); if (closed) throw new AppError('COMMAND_FAILED', 'Plugin registry is closed', { reason: 'plugin-registry-closed', @@ -380,7 +414,7 @@ export async function startProviderRegistry( resolved, { kind: 'replay-execution', id: NATIVE_REPLAY_BACKEND }, packageName, - policy.assertReplaySelectionCurrent, + policy.assertSelectionCurrent, ); return await resolveRegisteredReplayExecution(claim, refreshInventory); }, @@ -391,7 +425,10 @@ export async function startProviderRegistry( closed = true; const activated = resolved.slots.flatMap(({ claims }) => claims.filter( - (claim) => claim.registration !== undefined || claim.replaySetup !== undefined, + (claim) => + claim.registration !== undefined || + claim.replaySetup !== undefined || + claim.platformSetup !== undefined, ), ); return await Promise.all([...activated].reverse().map((claim) => cleanUpClaim(claim))); @@ -407,7 +444,7 @@ async function setUpClaims( slots: readonly Slot[], host: HostEnvironment, policy: PluginRegistryPolicy, - scope: 'all' | 'replay-backends', + scope: RegistryScope, ): Promise { for (const slot of slots) { for (const claim of slot.claims) { @@ -418,6 +455,7 @@ async function setUpClaims( claim.failure = asPluginFailure(error, 'plugin_setup_failed'); claim.registration = undefined; claim.replaySetup = undefined; + claim.platformSetup = undefined; } } } @@ -427,7 +465,7 @@ async function setUpClaim( claim: Claim, host: HostEnvironment, policy: PluginRegistryPolicy, - scope: 'all' | 'replay-backends', + scope: RegistryScope, ): Promise { const contribution = claim.contribution; if (contribution === undefined) { @@ -437,6 +475,15 @@ async function setUpClaim( if (scope === 'all') await setUpProviderClaim(claim, contribution, host, policy); return; } + if (contribution.kind === 'platform') { + if (scope === 'replay-backends') return; + if (!policy.platformHost) throw invalidPlugin('Platform setup requires a platform host'); + const result = await contribution.setup(policy.platformHost); + validateClaimSetup(claim, result); + claim.platformSetup = Object.freeze(result as RegisteredPlatformSetup); + return; + } + if (scope === 'platforms') return; const result = await contribution.setup(createReplaySetupHost()); try { validateClaimSetup(claim, result); @@ -502,17 +549,17 @@ function assertStoreSelectionCurrent( } /** - * The claim a replay resolution answers, in candidate order, so the first candidate that named it + * The claim a resolution answers, in candidate order, so the first candidate that named it * owns what a resolution surfaces. A candidate that failed before its claims were readable still * answers for the selection that named it, so a chosen plugin keeps its own reason instead of * reporting absence. */ -function requireReplayClaim( +function findClaim( resolved: ResolvedProviderPlugins, claim: PluggedClaim, packageName: string | undefined, assertSelectionCurrent?: (packageName: string) => void, -): Claim { +): Claim | undefined { const wanted = claimKeyOf(claim); for (const slot of resolved.slots) { const held = slot.claims.find((entry) => claimKeyOf(entry) === wanted); @@ -534,12 +581,33 @@ function requireReplayClaim( return { ...claim, slot: failedSlot, failure: failedSlot.failure }; } if (packageName) assertSelectionCurrent?.(packageName); + return undefined; +} + +function requireReplayClaim( + resolved: ResolvedProviderPlugins, + claim: PluggedClaim, + packageName: string | undefined, + assertSelectionCurrent?: (packageName: string) => void, +): Claim { + const found = findClaim(resolved, claim, packageName, assertSelectionCurrent); + if (found) return found; throw new AppError('INVALID_ARGS', `Replay backend is not installed: ${claim.id}`, { reason: 'plugin-not-installed', backend: claim.id, }); } +function platformClaimError(claim: Claim): AppError { + const error = asPluginFailure(claim.failure, 'plugin_load_failed'); + return new AppError( + error.code, + error.message, + { ...error.details, ...identityOfClaim(claim), package: claim.slot.candidate.package }, + error, + ); +} + function replayClaimError(claim: Claim): AppError { const error = asPluginFailure(claim.failure ?? claim.replayFailure, 'plugin_load_failed'); const packageName = claim.slot.candidate.package; diff --git a/packages/plugins/src/store.ts b/packages/plugins/src/store.ts index 54bc932245..66866ad7f7 100644 --- a/packages/plugins/src/store.ts +++ b/packages/plugins/src/store.ts @@ -81,7 +81,7 @@ export function createPluginSelectionGuard( } catch (error) { throw new AppError( 'INVALID_ARGS', - 'Cannot read the selected replay plugin configuration', + 'Cannot read the selected plugin configuration', { reason: 'invalid_plugin', package: packageName, @@ -133,6 +133,7 @@ type StoreInstallation = { directory: string; selection: PluginSelection; entry: string; + assertCompatibleHost(): void; declaredClaims: readonly PluggedClaim[]; }; @@ -161,12 +162,19 @@ async function describeInstallation( throw new AppError('INVALID_ARGS', `Invalid artifact plugin metadata: ${name}`, { reason: 'invalid_plugin', }); - const entry = discoverPluginEntry(directory); // Before any import: the supported contract version, the Node floor, and the static claims. The // claims the factory returns must equal these once it runs with its options. - const declaredClaims = readAgentDeviceClaims(packageJson); - assertNodeFloor(packageJson); - return { name, version, directory, selection, entry, declaredClaims }; + const entry = discoverPluginEntry(directory); + const declaredClaims = await readAgentDeviceClaims(packageJson); + return { + name, + version, + directory, + selection, + declaredClaims, + entry, + assertCompatibleHost: () => assertNodeFloor(packageJson), + }; } async function readInstallation(home: string, name: string, selection: PluginSelection) { @@ -178,7 +186,13 @@ async function readInstallation(home: string, name: string, selection: PluginSel ); } -async function loadInstallation({ name, entry, selection }: StoreInstallation) { +async function loadInstallation({ + name, + entry, + assertCompatibleHost, + selection, +}: StoreInstallation) { + assertCompatibleHost(); const module = await import(pathToFileURL(entry).href); if (typeof module.default !== 'function') throw new AppError('INVALID_ARGS', `Plugin must export a default factory: ${name}`, { @@ -273,6 +287,7 @@ export async function listPlugins(env: NodeJS.ProcessEnv, builtinProviders: read ...(entry.version !== undefined ? { version: entry.version } : {}), ...(entry.provider !== undefined ? { provider: entry.provider } : {}), ...(entry.backend !== undefined ? { backend: entry.backend } : {}), + ...(entry.platform !== undefined ? { platform: entry.platform } : {}), compatible: entry.state === 'active', ...(entry.error ? { error: entry.error } : {}), })); @@ -390,9 +405,12 @@ async function stagePlugin( JSON.stringify({ private: true, dependencies: { [name]: version ?? 'latest' } }), ); await installInProject(stage.project, env); - await describeInstallation(name, installationDirectory(stage.home, name, stage.installation), { - installation: stage.installation, - }); + const installation = await describeInstallation( + name, + installationDirectory(stage.home, name, stage.installation), + { installation: stage.installation }, + ); + installation.assertCompatibleHost(); } /** @@ -492,7 +510,8 @@ export async function addPluginArtifact( installation, artifact: { integrity, version: manifest.version }, }; - await describeInstallation(name, directory, selection); + const described = await describeInstallation(name, directory, selection); + described.assertCompatibleHost(); if (Object.hasOwn(selections, name)) throw new AppError('INVALID_ARGS', `Plugin is already installed: ${name}`, { reason: 'plugin_already_installed', diff --git a/packages/plugins/src/validate.ts b/packages/plugins/src/validate.ts index 4032e33a29..6917f8b935 100644 --- a/packages/plugins/src/validate.ts +++ b/packages/plugins/src/validate.ts @@ -1,4 +1,3 @@ -import { NATIVE_REPLAY_BACKEND } from '@agent-device/contracts/replay-execution'; import type { ReplayExecution } from '@agent-device/contracts/replay-execution'; import type { ReplayBackend } from '@agent-device/contracts/replay-backend'; import type { ReplayBackendSetup, ReplayExecutionSetup } from './replay-backend.ts'; @@ -7,11 +6,7 @@ import { isRecord } from '@agent-device/kernel/record'; import type { ConnectionProviderCapabilities } from '@agent-device/contracts/remote'; import type { ProviderDeviceRuntime } from '@agent-device/contracts/device'; import type { PlatformRuntimeProviderModule } from '@agent-device/contracts/platform-runtime-operations'; -import { - PLUGIN_API_VERSION, - ROUTING_PROVIDER_IDENTITIES, - type AgentDevicePlugin, -} from './contract.ts'; +import { PLUGIN_API_VERSION, ROUTING_PROVIDER_IDENTITIES, type Contribution } from './contract.ts'; const ENVIRONMENT_VARIABLE = /^[A-Z_][A-Z0-9_]*$/; @@ -19,30 +14,77 @@ const ENVIRONMENT_VARIABLE = /^[A-Z_][A-Z0-9_]*$/; const CLAIM_ID = /^[a-z][a-z0-9-]*$/; /** The claim space one contribution kind owns. */ -export type ClaimKind = 'provider' | 'replay-backend' | 'replay-execution'; +export type ClaimKind = 'provider' | 'platform' | 'replay-backend' | 'replay-execution'; /** One claim: its kind's space and the id this plugin holds in it. */ export type PluggedClaim = Readonly<{ kind: ClaimKind; id: string }>; /** How a claim's space names it in the inventory and in a cleanup outcome. */ -export type ClaimIdentity = Readonly<{ provider: string } | { backend: string }>; +export type ClaimIdentity = Readonly< + { provider: string } | { backend: string } | { platform: string } +>; /** Deterministic order for reading a package's static claims and for claim spaces. */ const CLAIM_KINDS: Readonly> = { provider: { metadataField: 'provider', contributionIdField: 'provider', - reservedIds: ROUTING_PROVIDER_IDENTITIES, + reservedError: (id) => + ROUTING_PROVIDER_IDENTITIES.includes(id) + ? new AppError('INVALID_ARGS', `Provider id is reserved for routing: ${id}`, { + reason: 'reserved_provider', + provider: id, + }) + : undefined, duplicateReason: 'duplicate_provider', identityFor: (id) => ({ provider: id }), readMetadata: (value) => readableClaimId(value, 'provider'), readContribution: (value) => ({ kind: 'provider', id: readProviderContribution(value) }), validateSetup: () => {}, }, + platform: { + metadataField: 'platform', + contributionIdField: 'family', + reservedError: async (id) => { + const [{ isPlatform }, { isOptionalPlatform }] = await Promise.all([ + import('@agent-device/kernel/device'), + import('@agent-device/contracts/platform-module'), + ]); + if (!isPlatform(id)) return invalidPlugin(`Unknown platform family: ${id}`); + if (isOptionalPlatform(id)) return undefined; + return new AppError('INVALID_ARGS', `Platform family is reserved for core: ${id}`, { + reason: 'reserved_platform', + platform: id, + }); + }, + duplicateReason: 'duplicate_platform', + identityFor: (id) => ({ platform: id }), + readMetadata: (value) => readableClaimId(value, 'platform'), + readContribution: (value) => { + const id = readableClaimId(value.family, 'family'); + if (typeof value.setup !== 'function') { + throw invalidPlugin('A platform contribution must provide setup(host)'); + } + return { kind: 'platform', id }; + }, + validateSetup: validatePlatformSetup, + }, 'replay-backend': { metadataField: 'replayBackend', contributionIdField: 'backend', - reservedIds: [NATIVE_REPLAY_BACKEND], + reservedError: async (id) => { + const { NATIVE_REPLAY_BACKEND } = await import('@agent-device/contracts/replay-execution'); + return id === NATIVE_REPLAY_BACKEND + ? new AppError( + 'INVALID_ARGS', + `Replay backend id is reserved for native execution: ${id}`, + { + reason: 'reserved_replay_backend', + backend: id, + }, + ) + : undefined; + }, duplicateReason: 'duplicate_replay_backend', identityFor: (id) => ({ backend: id }), readMetadata: (value) => readableClaimId(value, 'replayBackend'), @@ -62,15 +104,15 @@ const CLAIM_KINDS: Readonly> = { 'replay-execution': { metadataField: 'replayExecution', contributionIdField: 'id', - reservedIds: [], duplicateReason: 'duplicate_replay_execution', identityFor: (id) => ({ backend: id }), - readMetadata: (value) => { + readMetadata: async (value) => { // One spelling for this claim: the id itself belongs to the kind, not to the package. if (value !== true) throw invalidPlugin('Plugin metadata replayExecution must be true'); - return NATIVE_REPLAY_BACKEND; + return (await import('@agent-device/contracts/replay-execution')).NATIVE_REPLAY_BACKEND; }, - readContribution: (value) => { + readContribution: async (value) => { + const { NATIVE_REPLAY_BACKEND } = await import('@agent-device/contracts/replay-execution'); if (value.id !== NATIVE_REPLAY_BACKEND) { throw invalidPlugin( `A replay-execution contribution must declare id ${NATIVE_REPLAY_BACKEND}`, @@ -98,17 +140,17 @@ type ClaimKindSpec = Readonly<{ /** The contribution field that spells this kind's id. */ contributionIdField: string; /** Ids no plugin may claim in this space. */ - reservedIds: readonly string[]; + reservedError?(id: string): AppError | undefined | Promise; /** What a claim that loses this space's duplicate race reports. */ duplicateReason: string; /** How this space names the claim in the inventory and in cleanup outcomes. */ identityFor(id: string): ClaimIdentity; /** Reads the id out of the `agent-device` field. */ - readMetadata(value: unknown): string; + readMetadata(value: unknown): string | Promise; /** Validates one contribution of this kind and answers its claim. */ - readContribution(value: Record): PluggedClaim; + readContribution(value: Record): PluggedClaim | Promise; /** Checks what setup returned before the registry keeps the claim. */ - validateSetup(value: unknown): void; + validateSetup(value: unknown, id: string): void; }>; /** The claim spaces, in the order a package's static claims are read and compared. */ @@ -118,31 +160,35 @@ const CLAIM_KIND_ORDER = Object.keys(CLAIM_KINDS) as readonly ClaimKind[]; * The one validation of what a plugin factory returned, whichever source produced it: the whole * declaration is validated before any of its claims is published. */ -export function validateAgentDevicePlugin(value: unknown): AgentDevicePlugin { +export async function validateAgentDevicePlugin( + value: unknown, +): Promise { if (!isRecord(value)) throw invalidPlugin('Plugin factory must return a plugin object'); if (value.apiVersion !== PLUGIN_API_VERSION) throw incompatiblePluginApi(value.apiVersion); if (!Array.isArray(value.contributes) || value.contributes.length === 0) { throw invalidPlugin('Plugin must declare a nonempty contributes list'); } const keys = new Set(); - for (const contribution of value.contributes) { - const claim = claimOfContribution(contribution); - assertClaimAvailable(claim); + const claims = []; + for (const contribution of value.contributes as readonly unknown[]) { + const claim = await claimOfContribution(contribution); + await assertClaimAvailable(claim); const key = claimKeyOf(claim); if (keys.has(key)) { throw invalidPlugin(`Plugin declares the same claim twice: ${key}`); } keys.add(key); + claims.push({ ...claim, contribution: contribution as Contribution }); } - return value as AgentDevicePlugin; + return claims; } /** The claim a contribution names, after validating the contribution's own shape. */ -export function claimOfContribution(value: unknown): PluggedClaim { +async function claimOfContribution(value: unknown): Promise { if (!isRecord(value)) throw invalidPlugin('Each contribution must be an object'); const spec = claimKindSpecOf(value.kind); if (spec === undefined) throw invalidPlugin(`Unknown contribution kind: ${String(value.kind)}`); - return spec.readContribution(value); + return await spec.readContribution(value); } /** One claim as the store's declared claims and the registry compare them: `kind:id`. */ @@ -151,26 +197,13 @@ export function claimKeyOf(claim: PluggedClaim): string { } /** Why a claim cannot be held at all: a reserved id belongs to the host, not to a package. */ -export function reservedClaimError(claim: PluggedClaim): AppError | undefined { - if (!CLAIM_KINDS[claim.kind].reservedIds.includes(claim.id)) return undefined; - return claim.kind === 'provider' - ? new AppError('INVALID_ARGS', `Provider id is reserved for routing: ${claim.id}`, { - reason: 'reserved_provider', - provider: claim.id, - }) - : new AppError( - 'INVALID_ARGS', - `Replay backend id is reserved for native execution: ${claim.id}`, - { - reason: 'reserved_replay_backend', - backend: claim.id, - }, - ); +export async function reservedClaimError(claim: PluggedClaim): Promise { + return await CLAIM_KINDS[claim.kind].reservedError?.(claim.id); } /** Whether anything may still claim this id: a reserved id belongs to the host, not to a package. */ -function assertClaimAvailable(claim: PluggedClaim): void { - const reserved = reservedClaimError(claim); +async function assertClaimAvailable(claim: PluggedClaim): Promise { + const reserved = await reservedClaimError(claim); if (reserved !== undefined) throw reserved; } @@ -179,12 +212,12 @@ function assertClaimAvailable(claim: PluggedClaim): void { * a slot that failed before its claims were readable uses this, so the inventory and the plugin that * selected it can still say what it was meant to provide. */ -export function readableClaimsOfValue(value: unknown): readonly PluggedClaim[] { +export async function readableClaimsOfValue(value: unknown): Promise { if (!isRecord(value)) return []; const claims: PluggedClaim[] = [...versionTwoReplayClaims(value)]; for (const kind of CLAIM_KIND_ORDER) { const spec = CLAIM_KINDS[kind]; - const declared = claimIdSpelledBy(kind, value[spec.metadataField]); + const declared = await claimIdSpelledBy(kind, value[spec.metadataField]); if (declared !== undefined) { claims.push({ kind, id: declared }); continue; @@ -192,7 +225,7 @@ export function readableClaimsOfValue(value: unknown): readonly PluggedClaim[] { if (!Array.isArray(value.contributes)) continue; for (const contribution of value.contributes) { if (!isRecord(contribution) || contribution.kind !== kind) continue; - const named = claimIdSpelledBy(kind, contribution[spec.contributionIdField]); + const named = await claimIdSpelledBy(kind, contribution[spec.contributionIdField]); if (named !== undefined) claims.push({ kind, id: named }); } } @@ -213,9 +246,11 @@ function versionTwoReplayClaims(value: Record): readonly Plugge } /** The id this value spells for a kind, or nothing when it does not spell one. */ -function claimIdSpelledBy(kind: ClaimKind, value: unknown): string | undefined { +async function claimIdSpelledBy(kind: ClaimKind, value: unknown): Promise { // The native claim's id belongs to the kind, so its metadata spells it as `true`. - if (kind === 'replay-execution' && value === true) return NATIVE_REPLAY_BACKEND; + if (kind === 'replay-execution' && value === true) { + return (await import('@agent-device/contracts/replay-execution')).NATIVE_REPLAY_BACKEND; + } return isClaimId(value) ? value : undefined; } @@ -235,7 +270,7 @@ export function identityOfClaim(claim: PluggedClaim): ClaimIdentity { /** Checks a setup result against the kind that asked for it. */ export function validateClaimSetup(claim: PluggedClaim, value: unknown): void { - CLAIM_KINDS[claim.kind].validateSetup(value); + CLAIM_KINDS[claim.kind].validateSetup(value, claim.id); } /** @@ -243,7 +278,7 @@ export function validateClaimSetup(claim: PluggedClaim, value: unknown): void { * plus each static claim id, read through its own kind. Read before any import; after the factory * runs, its returned claims must equal these, in any order. */ -export function readPluginPackageClaims(field: unknown): readonly PluggedClaim[] { +export async function readPluginPackageClaims(field: unknown): Promise { if (!isRecord(field) || field.apiVersion !== PLUGIN_API_VERSION) { throw incompatiblePackageApi(field); } @@ -252,13 +287,43 @@ export function readPluginPackageClaims(field: unknown): readonly PluggedClaim[] const spec = CLAIM_KINDS[kind]; const declared = field[spec.metadataField]; if (declared === undefined) continue; - const id = spec.readMetadata(declared); - assertClaimAvailable({ kind, id }); + const id = await spec.readMetadata(declared); + await assertClaimAvailable({ kind, id }); claims.push({ kind, id }); } return claims; } +function validatePlatformSetup(value: unknown, family: string): void { + if ( + !isRecord(value) || + value.family !== family || + !isRecord(value.inventoryModule) || + value.inventoryModule.family !== family || + typeof value.inventoryModule.loadInventory !== 'function' || + !isRecord(value.runtimeModule) || + value.runtimeModule.family !== family || + typeof value.runtimeModule.loadRuntime !== 'function' || + typeof value.createInteractor !== 'function' + ) { + throw invalidPlugin(`Platform setup must supply matching family modules: ${family}`); + } + if (family !== 'web') return; + const operations = value.operations; + if ( + typeof value.withRequestProvider !== 'function' || + !isRecord(operations) || + typeof operations.setup !== 'function' || + typeof operations.doctor !== 'function' || + typeof operations.cleanupOrphans !== 'function' || + typeof operations.browserLifecycleCheck !== 'function' || + typeof operations.createProvider !== 'function' || + typeof operations.resolveRequestProvider !== 'function' + ) { + throw invalidPlugin('Web platform setup must supply request scoping and web operations'); + } +} + function isClaimId(value: unknown): value is string { return typeof value === 'string' && CLAIM_ID.test(value); } diff --git a/packages/replay/src/plugin.test.ts b/packages/replay/src/plugin.test.ts index d336f403ae..adc0782d23 100644 --- a/packages/replay/src/plugin.test.ts +++ b/packages/replay/src/plugin.test.ts @@ -15,7 +15,8 @@ function contributionOf( plugin: AgentDevicePlugin, ): ReplayBackendContribution | ReplayExecutionContribution { const [contribution] = plugin.contributes; - if (contribution.kind === 'provider') throw new Error('expected a replay contribution'); + if (contribution.kind !== 'replay-backend' && contribution.kind !== 'replay-execution') + throw new Error('expected a replay contribution'); return contribution; } diff --git a/scripts/__tests__/install-workspace-replay-plugins.test.ts b/scripts/__tests__/install-workspace-replay-plugins.test.ts index 9131c4ae1e..da8027bc3c 100644 --- a/scripts/__tests__/install-workspace-replay-plugins.test.ts +++ b/scripts/__tests__/install-workspace-replay-plugins.test.ts @@ -58,10 +58,12 @@ test('a non-source workspace install keeps the manifest fields the store reads b // The written manifest is what the store validates before it imports anything: the typed claims of // the `agent-device` field, and the `engines.node` floor. const claims = Object.fromEntries( - (['maestro', 'replay'] as const).map((packageId) => [ - packageId, - readPluginPackageClaims(installedManifest(home, packageId)['agent-device']), - ]), + await Promise.all( + (['maestro', 'replay'] as const).map(async (packageId) => [ + packageId, + await readPluginPackageClaims(installedManifest(home, packageId)['agent-device']), + ]), + ), ); assert.deepEqual(claims, { maestro: [{ kind: 'replay-backend', id: 'maestro' }], diff --git a/scripts/layering/contracts-exports.snapshot.json b/scripts/layering/contracts-exports.snapshot.json index 6257e13d59..8da152a7db 100644 --- a/scripts/layering/contracts-exports.snapshot.json +++ b/scripts/layering/contracts-exports.snapshot.json @@ -139,5 +139,6 @@ "@agent-device/contracts/type-text-runtime", "@agent-device/contracts/unsupported-interactor", "@agent-device/contracts/viewport-runtime", - "@agent-device/contracts/wait" + "@agent-device/contracts/wait", + "@agent-device/contracts/web-provider" ] diff --git a/src/cli/commands/daemon.ts b/src/cli/commands/daemon.ts index 3dbbf37c67..4c4492c415 100644 --- a/src/cli/commands/daemon.ts +++ b/src/cli/commands/daemon.ts @@ -135,7 +135,7 @@ function renderDaemonStatus( plugin.state === 'active' ? 'active' : `failed: ${plugin.error?.message ?? 'unknown'}`; - return ` ${plugin.provider ?? (plugin.backend ? `replay backend ${plugin.backend}` : '(unknown plugin)')} [${plugin.source}] ${origin} - ${outcome}`; + return ` ${plugin.provider ?? plugin.platform ?? (plugin.backend ? `replay backend ${plugin.backend}` : '(unknown plugin)')} [${plugin.source}] ${origin} - ${outcome}`; }), ]), ].join('\n'); diff --git a/src/cli/commands/plugins.ts b/src/cli/commands/plugins.ts index e3ee13d323..6244967b1e 100644 --- a/src/cli/commands/plugins.ts +++ b/src/cli/commands/plugins.ts @@ -50,7 +50,7 @@ export const pluginsCommand: ClientCommandHandler = async ({ host, positionals, ] : plugins.map((plugin) => plugin.compatible - ? `${plugin.name}@${plugin.version} (${plugin.provider ?? plugin.backend})` + ? `${plugin.name}@${plugin.version} (${plugin.provider ?? plugin.platform ?? plugin.backend})` : plugin.name === undefined ? `Plugin config unavailable: ${plugin.error?.message}` : `${plugin.name}: unavailable; run plugins update ${plugin.name} or plugins remove ${plugin.name}`, diff --git a/src/provider-device-runtimes.ts b/src/provider-device-runtimes.ts index 7bc8e5c990..00623ada19 100644 --- a/src/provider-device-runtimes.ts +++ b/src/provider-device-runtimes.ts @@ -32,7 +32,7 @@ export async function createDaemonProviderRuntimeComposition( const candidates = await storePluginCandidates(host.env); return await composeProviderRuntime(host, candidates, { ...PROVIDER_PLUGIN_POLICY, - assertReplaySelectionCurrent: createPluginSelectionGuard(candidates, host.env), + assertSelectionCurrent: createPluginSelectionGuard(candidates, host.env), }); } diff --git a/src/sdk/plugins.ts b/src/sdk/plugins.ts index 3fd5ed515b..ee93baacd7 100644 --- a/src/sdk/plugins.ts +++ b/src/sdk/plugins.ts @@ -15,6 +15,9 @@ export type { } from '@agent-device/plugins/host'; export type { Contribution, + PlatformContribution, + PlatformHost, + PlatformSetup, PluginConnection, PluginConnectionContext, PluginConnectionResolution, From b81911e38ad3090b3aa47b58c25ebe3010b4a9c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 20 Nov 2026 10:18:51 +0100 Subject: [PATCH 2/7] refactor(web): ship web as the first platform plugin --- docs/agents/web-backend.md | 5 +- package.json | 3 +- packages/contracts/package.json | 4 + packages/contracts/src/managed-web-backend.ts | 3 + .../contracts/src/platform-module.test.ts | 25 +-- packages/contracts/src/platform-module.ts | 151 ++---------------- packages/contracts/src/platform-plugin.ts | 27 ++++ packages/contracts/src/plugin-installation.ts | 149 +++++++++++++++++ packages/daemon/package.json | 1 - .../__tests__/session-teardown-budget.test.ts | 2 +- packages/daemon/tsconfig.json | 3 - .../composed-inventory-gateways.test.ts | 9 +- .../src/composed-inventory-gateways.ts | 3 +- .../src/inventory-gateways.fixtures.ts | 3 +- packages/platform-web/build.mjs | 14 ++ packages/platform-web/package.json | 58 +++++-- .../platform-web/src/agent-browser-install.ts | 4 +- .../src/agent-browser-lifecycle.ts | 5 +- .../src/agent-browser-provider.ts | 11 +- .../platform-web/src/agent-browser-tool.ts | 30 ++-- .../src/index-startup-cleanup.test.ts | 68 ++++++++ packages/platform-web/src/index.ts | 141 +++++++++------- .../platform-web/src/interactor-facade.ts | 11 -- packages/platform-web/src/interactor.test.ts | 2 +- packages/platform-web/src/interactor.ts | 12 +- packages/platform-web/src/resolve-provider.ts | 3 +- packages/platform-web/test/package-smoke.mjs | 90 +++++++++++ packages/platform-web/tsconfig.json | 4 +- packages/plugins/src/platform.test.ts | 2 +- packages/plugins/src/platform.ts | 30 ++-- packages/plugins/src/registry.ts | 2 + pnpm-lock.yaml | 15 +- scripts/capability-matrix/collect.ts | 4 +- scripts/capability-matrix/seams.ts | 23 +-- .../contracts/platform-plugin-parity.test.ts | 26 +-- .../test-utils/absent-platform-registry.ts | 8 + src/cli/connection/provider-policy.ts | 7 +- src/commands/provider-plugin-catalog.ts | 5 +- src/commands/schema/cli-help.ts | 3 + src/core/interactors.ts | 11 +- src/core/interactors/register-builtins.ts | 25 ++- src/core/platform-plugin-absence.ts | 2 +- ...rm-plugin-registry-optional-family.test.ts | 6 +- ...m-plugin-registry-provider-routing.test.ts | 16 +- src/core/platform-plugin-registry.ts | 43 ++--- src/daemon-composition-credentials.test.ts | 5 +- src/daemon-composition-web-cleanup.test.ts | 77 ++------- src/daemon-composition.test.ts | 5 +- src/daemon-composition.ts | 45 +++--- src/daemon-runtime-limrun-public-http.test.ts | 18 ++- src/host.test.ts | 2 + ...atform-runtime-android-adb-binding.test.ts | 3 - ...rm-runtime-apple-close-composition.test.ts | 2 - src/platform-runtime-audio-probe-host.test.ts | 12 +- src/platform-runtime-audio-probe-host.ts | 5 +- src/platform-runtime-claim-recovery.ts | 6 +- src/platform-runtime-daemon-lifecycle.test.ts | 10 +- src/platform-runtime-daemon-lifecycle.ts | 9 +- src/platform-runtime-device-inventory.test.ts | 9 +- ...-runtime-gateway-gesture-admission.test.ts | 4 +- ...platform-runtime-gateway-recording.test.ts | 2 - src/platform-runtime-gateway.fixtures.ts | 4 +- src/platform-runtime-host-diagnostics.ts | 10 +- src/platform-runtime-host.test.ts | 12 +- ...m-runtime-local-application-interactors.ts | 4 +- src/platform-runtime-managed-web-backend.ts | 64 ++++++-- ...form-runtime-network-web-transport.test.ts | 11 +- src/platform-runtime-network-web-transport.ts | 9 +- src/platform-runtime-operation-host.ts | 13 +- src/platform-runtime-perf-host.test.ts | 2 - src/platform-runtime-provider-scope.test.ts | 8 +- src/platform-runtime-resource-cleanup.test.ts | 7 +- src/platform-runtime-resource-cleanup.ts | 56 +------ src/platform-runtime-screen-recording-host.ts | 4 +- ...-runtime-screen-recording-web-host.test.ts | 22 ++- ...tform-runtime-screen-recording-web-host.ts | 5 +- src/platform-runtime-web-provider.fixtures.ts | 31 +++- src/platform-runtime.test.ts | 8 +- src/platform-runtime.ts | 46 +++--- src/platform-runtime/plugin-host.ts | 21 +++ src/platform-runtime/request-providers.ts | 60 +++---- src/provider-device-runtimes.ts | 47 +++++- .../integration/provider-scenarios/harness.ts | 15 +- .../help-conformance-error-routes.ts | 2 +- .../provider-scenarios/web-provider.test.ts | 9 +- .../provider-scenarios/web-world.ts | 2 +- .../smoke-tvos-platform-coverage.test.ts | 2 - test/integration/smoke-web-platform.test.ts | 85 ++++++---- test/integration/web-e2e/fill-scenario.ts | 11 +- .../web-e2e/web-plugin-artifact.ts | 32 ++++ test/output-economy/daemon-route-fixtures.ts | 2 +- website/docs/docs/agent-setup.md | 2 +- website/docs/docs/client-api.md | 4 +- website/docs/docs/commands.md | 3 +- 94 files changed, 1150 insertions(+), 746 deletions(-) create mode 100644 packages/contracts/src/plugin-installation.ts create mode 100644 packages/platform-web/build.mjs create mode 100644 packages/platform-web/src/index-startup-cleanup.test.ts delete mode 100644 packages/platform-web/src/interactor-facade.ts create mode 100644 packages/platform-web/test/package-smoke.mjs create mode 100644 src/__tests__/test-utils/absent-platform-registry.ts create mode 100644 src/platform-runtime/plugin-host.ts create mode 100644 test/integration/web-e2e/web-plugin-artifact.ts diff --git a/docs/agents/web-backend.md b/docs/agents/web-backend.md index def61c1857..e805ac95d6 100644 --- a/docs/agents/web-backend.md +++ b/docs/agents/web-backend.md @@ -1,11 +1,12 @@ # Web Backend -Web automation uses a managed `agent-browser` backend as an implementation detail. +The `@agent-device/web` plugin provides web automation through a managed `agent-browser` backend. - Runtime web commands resolve the backend only from the state-dir managed install at `tools/agent-browser/`. - Normal `--platform web` commands do not install the managed backend on first use. If the backend is missing, they fail with a setup hint. -- Before first web automation or in CI/sandbox bootstrap steps, use `agent-device web setup`. +- Before first web automation, install the plugin with `agent-device plugins add @agent-device/web`. +- After you install the plugin, run `agent-device web setup` for the state directory you will use. - To run the backend health check, use `agent-device web doctor`. - Each backend call spawns the package's declared `bin` entry with the current Node runtime. It never spawns the `node_modules/.bin` console shim. diff --git a/package.json b/package.json index c35c2dbb4b..04486cfc47 100644 --- a/package.json +++ b/package.json @@ -165,7 +165,7 @@ "depgraph:test": "node --experimental-strip-types scripts/node-test-tmpdir.ts --experimental-strip-types --test scripts/depgraph/model.test.ts scripts/depgraph/entries.test.ts scripts/depgraph/import-graph.test.ts scripts/depgraph/affected.test.ts scripts/depgraph/structure-summary.test.ts tools/depgraph-view/*.test.mjs", "check:production-exports": "fallow dead-code --config fallow-production-exports.json --production --unused-exports --fail-on-issues", "check:bundle-owner-files": "node --experimental-strip-types scripts/check-bundle-owner-files.ts", - "check:package": "node --experimental-strip-types scripts/node-test-tmpdir.ts --experimental-strip-types --test packages/maestro/test/package-artifact.test.mjs packages/maestro/test/package-smoke.mjs packages/replay/test/package-smoke.mjs && node --experimental-strip-types scripts/check-package.ts", + "check:package": "node --experimental-strip-types scripts/node-test-tmpdir.ts --experimental-strip-types --test packages/maestro/test/package-artifact.test.mjs packages/maestro/test/package-smoke.mjs packages/replay/test/package-smoke.mjs packages/platform-web/test/package-smoke.mjs && node --experimental-strip-types scripts/check-package.ts", "check:provider-plugin": "node scripts/check-provider-plugin.mjs", "check:command-docs": "vitest run --project unit-core test/repo-guards/command-doc-coverage.test.ts", "check:adr-citations": "vitest run --project unit-core test/repo-guards/adr-citations.test.ts", @@ -326,7 +326,6 @@ "@agent-device/platform-harmonyos": "workspace:*", "@agent-device/platform-linux": "workspace:*", "@agent-device/platform-vega": "workspace:*", - "@agent-device/platform-web": "workspace:*", "@agent-device/plugins": "workspace:*", "@agent-device/provider-limrun": "workspace:*", "@agent-device/provider-webdriver": "workspace:*", diff --git a/packages/contracts/package.json b/packages/contracts/package.json index 8bd39bc066..46375c4ec6 100644 --- a/packages/contracts/package.json +++ b/packages/contracts/package.json @@ -300,6 +300,10 @@ "types": "./src/lease-scope.ts", "default": "./src/lease-scope.ts" }, + "./plugin-installation": { + "types": "./src/plugin-installation.ts", + "default": "./src/plugin-installation.ts" + }, "./plugin-inventory": { "types": "./src/plugin-inventory.ts", "default": "./src/plugin-inventory.ts" diff --git a/packages/contracts/src/managed-web-backend.ts b/packages/contracts/src/managed-web-backend.ts index 34e38226f5..4279d3207e 100644 --- a/packages/contracts/src/managed-web-backend.ts +++ b/packages/contracts/src/managed-web-backend.ts @@ -1,3 +1,6 @@ +/** Deadline that web session teardown must leave for the managed browser. */ +export const AGENT_BROWSER_TIMEOUT_MS = 30_000; + export type ManagedWebBackendStatus = Readonly<{ version: string; stateDir: string; diff --git a/packages/contracts/src/platform-module.test.ts b/packages/contracts/src/platform-module.test.ts index f8052369e7..2a41e55b76 100644 --- a/packages/contracts/src/platform-module.test.ts +++ b/packages/contracts/src/platform-module.test.ts @@ -4,25 +4,28 @@ import { PLATFORMS, type Platform } from '@agent-device/kernel/device'; import { AppError } from '@agent-device/kernel/errors'; import { createPlatformModuleRegistry, - getOptionalPlatformPluginDeclaration, isOptionalPlatform, - missingOptionalPlatformError, OPTIONAL_PLATFORMS, - pluginInstallCommand, - pluginPackageSelector, - pluginRepairCommand, REQUIRED_PLATFORMS, type PlatformModuleMetadata, type PlatformPartitionIsCanonical, } from './platform-module.ts'; +import { + getOptionalPlatformPluginDeclaration, + missingOptionalPlatformError, + pluginInstallCommand, + pluginPackageSelector, + pluginRepairCommand, +} from './plugin-installation.ts'; const CORE_VERSION = '0.22.0'; +const reportAbsent = (family: Platform) => missingOptionalPlatformError(family, CORE_VERSION); test('platform metadata registry is canonical, ordered, and immutable', () => { const registrations = [...PLATFORMS] .reverse() .map((family) => ({ family, marker: family.toUpperCase() })); - const registry = createPlatformModuleRegistry(registrations, CORE_VERSION); + const registry = createPlatformModuleRegistry(registrations, reportAbsent); assert.deepEqual(registry.families, PLATFORMS); assert.deepEqual( @@ -40,13 +43,13 @@ test('platform metadata registry rejects missing required and duplicate family o // Only the required families are completeness-checked, so dropping one optional family is not // a missing registration — this drops `apple`. const missing = PLATFORMS.filter((family) => family !== 'apple').map((family) => ({ family })); - assert.throws(() => createPlatformModuleRegistry(missing, CORE_VERSION), /Missing.*apple/); + assert.throws(() => createPlatformModuleRegistry(missing, reportAbsent), /Missing.*apple/); const duplicate: PlatformModuleMetadata[] = [ ...PLATFORMS.map((family) => ({ family })), { family: 'apple' }, ]; - assert.throws(() => createPlatformModuleRegistry(duplicate, CORE_VERSION), /Duplicate.*apple/); + assert.throws(() => createPlatformModuleRegistry(duplicate, reportAbsent), /Duplicate.*apple/); }); test('platform metadata registry rejects an unknown runtime family value', () => { @@ -55,7 +58,7 @@ test('platform metadata registry rejects an unknown runtime family value', () => { family: 'unknown' as Platform }, ]; assert.throws( - () => createPlatformModuleRegistry(registrations, CORE_VERSION), + () => createPlatformModuleRegistry(registrations, reportAbsent), /Unknown.*unknown/, ); }); @@ -141,7 +144,7 @@ test('missingOptionalPlatformError returns plugin-not-installed with the family test('optional families may be absent: the registry keeps only what is registered', () => { const registrations = REQUIRED_PLATFORMS.map((family) => ({ family, marker: family })); - const registry = createPlatformModuleRegistry(registrations, CORE_VERSION); + const registry = createPlatformModuleRegistry(registrations, reportAbsent); assert.deepEqual(registry.families, [...REQUIRED_PLATFORMS]); assert.deepEqual( @@ -154,7 +157,7 @@ test('optional families may be absent: the registry keeps only what is registere test('get on an absent optional family throws the typed plugin-not-installed outcome', () => { const registry = createPlatformModuleRegistry( REQUIRED_PLATFORMS.map((family) => ({ family })), - CORE_VERSION, + reportAbsent, ); for (const family of OPTIONAL_PLATFORMS) { diff --git a/packages/contracts/src/platform-module.ts b/packages/contracts/src/platform-module.ts index b89466a9c1..fe0c69bac0 100644 --- a/packages/contracts/src/platform-module.ts +++ b/packages/contracts/src/platform-module.ts @@ -36,141 +36,6 @@ export type PlatformPartitionIsCanonical = AssertTrue< : false >; -/** - * Which release of a plugin package the running core can install (#4694). The release workflow - * stamps the core and its public plugins with the same nightly version, so an installation hint must - * name that release: the bare package name on a nightly core resolves to the staged `latest` - * placeholder rather than to the build that core works with. Every catalog that tells a user to - * install a plugin — the provider catalog and the optional platform families ADR 0034 makes - * installable — builds its selector here, so one channel rule cannot be fixed in one catalog and - * missed in another. The caller supplies `coreVersion`: contracts owns vocabulary, and reading the - * installed version is host mechanics. - */ -export type PluginReleaseDeclaration = Readonly<{ - package: string; - // A 0.22.x-dev version carries no source branch, so the 0.22 branch's nightly tag is the shared - // default for development builds, including main checkouts. - nightlyTag?: 'nightly-0.22'; -}>; - -// The release workflow stamps the core and its public plugins with the same nightly version. -const NIGHTLY_0_22_VERSION = /^0\.22\.\d+-nightly(?:-0-22)?\.\d{8}\.[1-9]\d*$/; -const DEVELOPMENT_0_22_VERSION = /^0\.22\.\d+-dev$/; - -/** The package selector a core of `coreVersion` installs: its own release, else the branch tag. */ -export function pluginPackageSelector( - declaration: PluginReleaseDeclaration, - coreVersion: string, -): string { - if (declaration.nightlyTag === undefined) return declaration.package; - const version = coreVersion.trim(); - if (NIGHTLY_0_22_VERSION.test(version)) return `${declaration.package}@${version}`; - if (DEVELOPMENT_0_22_VERSION.test(version)) { - return `${declaration.package}@${declaration.nightlyTag}`; - } - return declaration.package; -} - -/** The `plugins add` line that installs `declaration` for a core of `coreVersion`. */ -export function pluginInstallCommand( - declaration: PluginReleaseDeclaration, - coreVersion: string, -): string { - return `agent-device plugins add ${pluginPackageSelector(declaration, coreVersion)}`; -} - -/** - * The `plugins` line that repairs an installed `declaration`: `update` keeps a selector the user - * chose, while a pinned nightly release must be added again. - */ -export function pluginRepairCommand( - declaration: PluginReleaseDeclaration, - coreVersion: string, -): string { - const selector = pluginPackageSelector(declaration, coreVersion); - const action = selector === declaration.package ? 'update' : 'add'; - return `agent-device plugins ${action} ${selector}`; -} - -/** - * Engine-free install-hint catalog for the optional platform families (ADR 0034): each family - * maps to its package in the maintainer-controlled `@agent-device/*` scope. It is vetted - * declaration data only — it never probes whether an engine is installed or working, and an - * unknown family has no row and yields no inferred package. The record is total over - * `OptionalPlatform`, so a newly optional family cannot ship without its installation row, and each - * row uses the release-channel rule above, as the provider catalog does. - */ -export type OptionalPlatformPluginDeclaration = PluginReleaseDeclaration & - Readonly<{ - family: OptionalPlatform; - label: string; - }>; - -const OPTIONAL_PLATFORM_PLUGIN_CATALOG: Readonly< - Record -> = Object.freeze({ - harmonyos: Object.freeze({ - family: 'harmonyos', - package: '@agent-device/harmonyos', - label: 'HarmonyOS', - nightlyTag: 'nightly-0.22', - }), - vega: Object.freeze({ - family: 'vega', - package: '@agent-device/vega', - label: 'Vega', - nightlyTag: 'nightly-0.22', - }), - linux: Object.freeze({ - family: 'linux', - package: '@agent-device/linux', - label: 'Linux desktop', - nightlyTag: 'nightly-0.22', - }), - web: Object.freeze({ - family: 'web', - package: '@agent-device/web', - label: 'Web', - nightlyTag: 'nightly-0.22', - }), -} as const satisfies Record); - -/** - * The vetted declaration for an optional family, or `undefined` for any other family: the - * required families and unknown names produce no inferred package. - */ -export function getOptionalPlatformPluginDeclaration( - family: Platform, -): OptionalPlatformPluginDeclaration | undefined { - return isOptionalPlatform(family) ? OPTIONAL_PLATFORM_PLUGIN_CATALOG[family] : undefined; -} - -/** - * The typed outcome for a platform family a composition does not have (ADR 0034). An optional family - * reports `plugin-not-installed` with the package that provides it and its installation command, - * before any device binding. The required families and unknown names have no catalog row, so they - * keep the plain unsupported-platform outcome with no package inferred: absence of a required family - * is a broken composition, not something a user can install. - */ -export function missingOptionalPlatformError(family: Platform, coreVersion: string): AppError { - const declaration = getOptionalPlatformPluginDeclaration(family); - if (!declaration) { - return new AppError('UNSUPPORTED_PLATFORM', `Unsupported platform: ${family}`); - } - const installCommand = pluginInstallCommand(declaration, coreVersion); - return new AppError( - 'UNSUPPORTED_PLATFORM', - `${declaration.label} platform requires the ${declaration.package} plugin.`, - { - reason: 'plugin-not-installed', - family, - package: declaration.package, - installCommand, - hint: `Install:\n ${installCommand}\nThen retry the original command. If a local daemon is already running, close its sessions and run agent-device daemon stop with the same --state-dir before retrying.`, - }, - ); -} - /** Cheap family identity which may be evaluated during root composition. */ export type PlatformModuleMetadata = Readonly<{ family: Platform; @@ -192,18 +57,18 @@ export type PlatformModuleRegistry = Read families: readonly Platform[]; modules: readonly Module[]; get(family: Platform): Module; + tryGet(family: Platform): Module | undefined; }>; /** * Composes `registrations` into the presence authority for platform families. * - * `coreVersion` is the running core's version, which the typed absence outcome needs to name the - * plugin release that core can install. The caller supplies it: reading the installed version is - * host mechanics, which contracts does not own. + * The caller supplies the absence reporter for this composition. */ export function createPlatformModuleRegistry( registrations: readonly Module[], - coreVersion: string, + reportAbsent = unsupportedPlatform, + assertSelectionCurrent?: (family: Platform) => void, ): PlatformModuleRegistry { const byFamily = new Map(); for (const registration of registrations) { @@ -227,17 +92,23 @@ export function createPlatformModuleRegistry byFamily.get(family), get: (family: Platform) => { + assertSelectionCurrent?.(family); const registration = byFamily.get(family); if (registration) return registration; // An explicitly requested family with no registration is a missing plugin, reported as the // typed outcome rather than a contract violation. Absence of a required family cannot reach // here: the completeness check above rejects that composition. - throw missingOptionalPlatformError(family, coreVersion); + throw reportAbsent(family); }, }); } +function unsupportedPlatform(family: Platform): AppError { + return new AppError('UNSUPPORTED_PLATFORM', `Unsupported platform: ${family}`); +} + function freezeRegistration(registration: Module): Module { return Object.freeze({ ...registration }) as Module; } diff --git a/packages/contracts/src/platform-plugin.ts b/packages/contracts/src/platform-plugin.ts index 8417b565b5..27d45309ce 100644 --- a/packages/contracts/src/platform-plugin.ts +++ b/packages/contracts/src/platform-plugin.ts @@ -1,3 +1,8 @@ +import type { ManagedWebBackend } from './managed-web-backend.ts'; +import type { DoctorCheck } from './doctor.ts'; +import type { InventoryPlatformModule } from './platform-module.ts'; +import type { PlatformRuntimeModule } from './platform-runtime-operations.ts'; +import type { WebProvider } from './web-provider.ts'; import type { DeviceInfo, Platform, PlatformSelector } from '@agent-device/kernel/device'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; import type { PlatformGatedProviderResolverKey } from './platform-providers.ts'; @@ -63,3 +68,25 @@ export type PlatformPlugin = { readonly platformGatedResolvers: readonly PlatformGatedProviderResolverKey[]; }; }; + +export type WebPlatformOperations = ManagedWebBackend & + Readonly<{ + cleanupOrphans(openWebSessionNames: readonly string[]): Promise; + browserLifecycleCheck(stateDir: string): Promise; + createProvider(session: string): Promise; + resolveRequestProvider(): Promise; + }>; + +export type WebPlatformRegistration = Readonly<{ + family: 'web'; + inventoryModule: InventoryPlatformModule<'web'>; + runtimeModule: PlatformRuntimeModule & { readonly family: 'web' }; + createInteractor: PlatformPlugin['createInteractor']; + withRequestProvider(provider: WebProvider, task: () => Promise): Promise; + operations: WebPlatformOperations; +}>; + +export type WebPlatformSelection = Readonly<{ + active?: WebPlatformRegistration; + get(): WebPlatformRegistration; +}>; diff --git a/packages/contracts/src/plugin-installation.ts b/packages/contracts/src/plugin-installation.ts new file mode 100644 index 0000000000..94350cd564 --- /dev/null +++ b/packages/contracts/src/plugin-installation.ts @@ -0,0 +1,149 @@ +import { AppError } from '@agent-device/kernel/errors'; +import type { Platform } from '@agent-device/kernel/device'; +import type { OptionalPlatform } from './platform-module.ts'; + +/** + * Which release of a plugin package the running core can install (#4694). The release workflow + * stamps the core and its public plugins with the same nightly version, so an installation hint must + * name that release: the bare package name on a nightly core resolves to the staged `latest` + * placeholder rather than to the build that core works with. Every catalog that tells a user to + * install a plugin — the provider catalog and the optional platform families ADR 0034 makes + * installable — builds its selector here, so one channel rule cannot be fixed in one catalog and + * missed in another. The caller supplies `coreVersion`: contracts owns vocabulary, and reading the + * installed version is host mechanics. + */ +export type PluginReleaseDeclaration = Readonly<{ + package: string; + // A 0.22.x-dev version carries no source branch, so the 0.22 branch's nightly tag is the shared + // default for development builds, including main checkouts. + nightlyTag?: 'nightly-0.22'; +}>; + +// The release workflow stamps the core and its public plugins with the same nightly version. +const NIGHTLY_0_22_VERSION = /^0\.22\.\d+-nightly(?:-0-22)?\.\d{8}\.[1-9]\d*$/; +const DEVELOPMENT_0_22_VERSION = /^0\.22\.\d+-dev$/; + +/** The package selector a core of `coreVersion` installs: its own release, else the branch tag. */ +export function pluginPackageSelector( + declaration: PluginReleaseDeclaration, + coreVersion: string, +): string { + if (declaration.nightlyTag === undefined) return declaration.package; + const version = coreVersion.trim(); + if (NIGHTLY_0_22_VERSION.test(version)) return `${declaration.package}@${version}`; + if (DEVELOPMENT_0_22_VERSION.test(version)) { + return `${declaration.package}@${declaration.nightlyTag}`; + } + return declaration.package; +} + +/** The `plugins add` line that installs `declaration` for a core of `coreVersion`. */ +export function pluginInstallCommand( + declaration: PluginReleaseDeclaration, + coreVersion: string, +): string { + return `agent-device plugins add ${pluginPackageSelector(declaration, coreVersion)}`; +} + +/** + * The `plugins` line that repairs an installed `declaration`: `update` keeps a selector the user + * chose, while a pinned nightly release must be added again. + */ +export function pluginRepairCommand( + declaration: PluginReleaseDeclaration, + coreVersion: string, +): string { + const selector = pluginPackageSelector(declaration, coreVersion); + const action = selector === declaration.package ? 'update' : 'add'; + return `agent-device plugins ${action} ${selector}`; +} + +/** Installs the selected release and applies it to the next daemon. */ +export function pluginInstallationHint( + declaration: PluginReleaseDeclaration, + coreVersion: string, +): { installCommand: string; hint: string } { + const installCommand = pluginInstallCommand(declaration, coreVersion); + return { + installCommand, + hint: `Install:\n ${installCommand}\nThen retry the original command. If a local daemon is already running, close its sessions and run agent-device daemon stop with the same --state-dir before retrying.`, + }; +} +/** + * Engine-free install-hint catalog for the optional platform families (ADR 0034): each family + * maps to its package in the maintainer-controlled `@agent-device/*` scope. It is vetted + * declaration data only — it never probes whether an engine is installed or working, and an + * unknown family has no row and yields no inferred package. The record is total over + * `OptionalPlatform`, so a newly optional family cannot ship without its installation row, and each + * row uses the release-channel rule above, as the provider catalog does. + */ +export type OptionalPlatformPluginDeclaration = PluginReleaseDeclaration & + Readonly<{ + family: OptionalPlatform; + label: string; + }>; + +const OPTIONAL_PLATFORM_PLUGIN_CATALOG: Readonly< + Record +> = Object.freeze({ + harmonyos: Object.freeze({ + family: 'harmonyos', + package: '@agent-device/harmonyos', + label: 'HarmonyOS', + nightlyTag: 'nightly-0.22', + }), + vega: Object.freeze({ + family: 'vega', + package: '@agent-device/vega', + label: 'Vega', + nightlyTag: 'nightly-0.22', + }), + linux: Object.freeze({ + family: 'linux', + package: '@agent-device/linux', + label: 'Linux desktop', + nightlyTag: 'nightly-0.22', + }), + web: Object.freeze({ + family: 'web', + package: '@agent-device/web', + label: 'Web', + nightlyTag: 'nightly-0.22', + }), +} as const satisfies Record); + +/** + * The vetted declaration for an optional family, or `undefined` for any other family: the + * required families and unknown names produce no inferred package. + */ +export function getOptionalPlatformPluginDeclaration( + family: Platform, +): OptionalPlatformPluginDeclaration | undefined { + return Object.hasOwn(OPTIONAL_PLATFORM_PLUGIN_CATALOG, family) + ? OPTIONAL_PLATFORM_PLUGIN_CATALOG[family as OptionalPlatform] + : undefined; +} + +/** + * The typed outcome for a platform family a composition does not have (ADR 0034). An optional family + * reports `plugin-not-installed` with the package that provides it and its installation command, + * before any device binding. The required families and unknown names have no catalog row, so they + * keep the plain unsupported-platform outcome with no package inferred: absence of a required family + * is a broken composition, not something a user can install. + */ +export function missingOptionalPlatformError(family: Platform, coreVersion: string): AppError { + const declaration = getOptionalPlatformPluginDeclaration(family); + if (!declaration) { + return new AppError('UNSUPPORTED_PLATFORM', `Unsupported platform: ${family}`); + } + return new AppError( + 'UNSUPPORTED_PLATFORM', + `${declaration.label} platform requires the ${declaration.package} plugin.`, + { + reason: 'plugin-not-installed', + family, + package: declaration.package, + ...pluginInstallationHint(declaration, coreVersion), + }, + ); +} diff --git a/packages/daemon/package.json b/packages/daemon/package.json index 2694d82ed7..c5efb7c798 100644 --- a/packages/daemon/package.json +++ b/packages/daemon/package.json @@ -15,7 +15,6 @@ "@agent-device/kernel": "workspace:*", "@agent-device/platform-android": "workspace:*", "@agent-device/platform-apple": "workspace:*", - "@agent-device/platform-web": "workspace:*", "@agent-device/replay-port": "workspace:*", "@agent-device/selectors": "workspace:*", "@agent-device/session-journal": "workspace:*" diff --git a/packages/daemon/src/sessions/__tests__/session-teardown-budget.test.ts b/packages/daemon/src/sessions/__tests__/session-teardown-budget.test.ts index 6d17d8c686..66810b11cd 100644 --- a/packages/daemon/src/sessions/__tests__/session-teardown-budget.test.ts +++ b/packages/daemon/src/sessions/__tests__/session-teardown-budget.test.ts @@ -1,6 +1,6 @@ import path from 'node:path'; import { expect, test } from 'vitest'; -import { AGENT_BROWSER_TIMEOUT_MS } from '@agent-device/platform-web'; +import { AGENT_BROWSER_TIMEOUT_MS } from '@agent-device/contracts/managed-web-backend'; import { createLiveTestHostEnvironment, mkdtempForTestSync } from '@agent-device/test-kit'; import { makeAndroidSession } from '../../__tests__/support/session-factories.ts'; import { SessionStore } from '../../core/session-store.ts'; diff --git a/packages/daemon/tsconfig.json b/packages/daemon/tsconfig.json index fb3d123454..7c9ea611a2 100644 --- a/packages/daemon/tsconfig.json +++ b/packages/daemon/tsconfig.json @@ -53,9 +53,6 @@ { "path": "../platform-apple" }, - { - "path": "../platform-web" - }, { "path": "../proxy" }, diff --git a/packages/device-selection/src/__tests__/composed-inventory-gateways.test.ts b/packages/device-selection/src/__tests__/composed-inventory-gateways.test.ts index 921effbf8b..be622bd417 100644 --- a/packages/device-selection/src/__tests__/composed-inventory-gateways.test.ts +++ b/packages/device-selection/src/__tests__/composed-inventory-gateways.test.ts @@ -7,6 +7,7 @@ import { type InventoryPlatformModule, createPlatformModuleRegistry, } from '@agent-device/contracts/platform-module'; +import { missingOptionalPlatformError } from '@agent-device/contracts/plugin-installation'; import type { DeviceInventoryHost, PlatformRequestScope, @@ -256,7 +257,9 @@ describe('composed device inventory gateway', () => { }, }), ); - const registry = createPlatformModuleRegistry(modules, CORE_VERSION); + const registry = createPlatformModuleRegistry(modules, (family) => + missingOptionalPlatformError(family, CORE_VERSION), + ); const gateways = createComposedDeviceInventoryGateways({ registry, loadHost: async () => host, @@ -361,7 +364,9 @@ function inventoryWorld( }, })); return { - registry: createPlatformModuleRegistry(modules, CORE_VERSION), + registry: createPlatformModuleRegistry(modules, (family) => + missingOptionalPlatformError(family, CORE_VERSION), + ), loadHost: async () => { hosts += 1; return host; diff --git a/packages/device-selection/src/composed-inventory-gateways.ts b/packages/device-selection/src/composed-inventory-gateways.ts index 949f2f162e..8f3df1a618 100644 --- a/packages/device-selection/src/composed-inventory-gateways.ts +++ b/packages/device-selection/src/composed-inventory-gateways.ts @@ -100,9 +100,10 @@ function createLocalDeviceInventoryGateway( }; const sourceLoads = new Map>(); const loadSource = async (family: Platform): Promise => { + const module = registry.get(family); const existing = sourceLoads.get(family); if (existing) return await existing; - const pending = loadFamilyInventory(registry.get(family), requiredHost); + const pending = loadFamilyInventory(module, requiredHost); sourceLoads.set(family, pending); try { return await pending; diff --git a/packages/device-selection/src/inventory-gateways.fixtures.ts b/packages/device-selection/src/inventory-gateways.fixtures.ts index 4088b65fec..2ec0c1b12a 100644 --- a/packages/device-selection/src/inventory-gateways.fixtures.ts +++ b/packages/device-selection/src/inventory-gateways.fixtures.ts @@ -11,6 +11,7 @@ import { type InventoryPlatformModule, createPlatformModuleRegistry, } from '@agent-device/contracts/platform-module'; +import { missingOptionalPlatformError } from '@agent-device/contracts/plugin-installation'; import type { DeviceInventoryHost, PlatformRequestScope, @@ -80,7 +81,7 @@ export function createTestDeviceInventoryGateways( return createComposedDeviceInventoryGateways({ registry: createPlatformModuleRegistry( testInventoryModules(options.local ?? (async () => [] as readonly DeviceInfo[])), - TEST_CORE_VERSION, + (family) => missingOptionalPlatformError(family, TEST_CORE_VERSION), ), loadHost: async () => testInventoryHost, provider: options.provider, diff --git a/packages/platform-web/build.mjs b/packages/platform-web/build.mjs new file mode 100644 index 0000000000..0374440887 --- /dev/null +++ b/packages/platform-web/build.mjs @@ -0,0 +1,14 @@ +import { build } from 'tsdown'; +import { providerPluginBuildConfig } from '@agent-device/build-config'; + +await build({ + ...providerPluginBuildConfig, + config: false, + dts: true, + tsconfig: '../../tsconfig.lib.json', + entry: { 'agent-device': 'src/index.ts' }, + deps: { + ...providerPluginBuildConfig.deps, + neverBundle: ['agent-device/plugins'], + }, +}); diff --git a/packages/platform-web/package.json b/packages/platform-web/package.json index d1ff4ac9d3..51dd68a25a 100644 --- a/packages/platform-web/package.json +++ b/packages/platform-web/package.json @@ -1,27 +1,53 @@ { - "name": "@agent-device/platform-web", - "version": "0.0.0", + "name": "@agent-device/web", + "version": "0.22.0-dev", "private": true, "type": "module", - "description": "Web-family platform runtime metadata and implementations for agent-device.", - "dependencies": { + "description": "Managed web platform plugin for agent-device.", + "exports": { + "./agent-device": { + "types": "./src/index.ts", + "default": "./src/index.ts" + } + }, + "devDependencies": { + "@agent-device/test-kit": "workspace:*", "@agent-device/capture-kit": "workspace:*", "@agent-device/contracts": "workspace:*", "@agent-device/host-kit": "workspace:*", "@agent-device/kernel": "workspace:*", - "@agent-device/selectors": "workspace:*" + "@agent-device/selectors": "workspace:*", + "@agent-device/build-config": "workspace:*", + "agent-device": "workspace:*" }, - "exports": { - ".": { - "types": "./src/index.ts", - "default": "./src/index.ts" + "engines": { + "node": ">=24" + }, + "files": [ + "dist" + ], + "license": "MIT", + "agent-device": { + "apiVersion": 3, + "platform": "web" + }, + "scripts": { + "build": "node --experimental-strip-types build.mjs", + "prepack": "pnpm build" + }, + "publishConfig": { + "exports": { + "./agent-device": { + "types": "./dist/agent-device.d.mts", + "import": "./dist/agent-device.mjs" + } }, - "./interactor": { - "types": "./src/interactor-facade.ts", - "default": "./src/interactor-facade.ts" - } + "access": "public" }, - "devDependencies": { - "@agent-device/test-kit": "workspace:*" - } + "repository": { + "type": "git", + "url": "git+https://github.com/callstack/agent-device.git", + "directory": "packages/platform-web" + }, + "homepage": "https://agent-device.dev/docs/commands#web" } diff --git a/packages/platform-web/src/agent-browser-install.ts b/packages/platform-web/src/agent-browser-install.ts index dd5d443a39..bfd3e77e66 100644 --- a/packages/platform-web/src/agent-browser-install.ts +++ b/packages/platform-web/src/agent-browser-install.ts @@ -1,6 +1,7 @@ import path from 'node:path'; import { AppError } from '@agent-device/kernel/errors'; import { runCmd } from '@agent-device/host-kit/command'; +import type { PlatformHost } from 'agent-device/plugins'; import type { EnvMap } from '@agent-device/kernel/source-value'; import { ensureHostDirectorySync, @@ -22,6 +23,7 @@ export async function installManagedAgentBrowserPackage(params: { packageSpec: string; timeoutMs: number; env: Readonly; + runCommand?: PlatformHost['runCommand']; }): Promise { ensureHostDirectorySync(params.packageRoot); // `--no-global` keeps an ambient `npm_config_global` from redirecting the @@ -36,7 +38,7 @@ export async function installManagedAgentBrowserPackage(params: { '--no-save', params.packageSpec, ]); - await runCmd(npm.command, npm.args, { + await (params.runCommand ?? runCmd)(npm.command, npm.args, { env: params.env, timeoutMs: params.timeoutMs, }); diff --git a/packages/platform-web/src/agent-browser-lifecycle.ts b/packages/platform-web/src/agent-browser-lifecycle.ts index 5a1da161a2..1338a4a7b2 100644 --- a/packages/platform-web/src/agent-browser-lifecycle.ts +++ b/packages/platform-web/src/agent-browser-lifecycle.ts @@ -1,7 +1,7 @@ import path from 'node:path'; import type { EnvMap } from '@agent-device/kernel/source-value'; import { uniqueStrings } from '@agent-device/kernel/collections'; -import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; +import { emitDiagnostic, type DiagnosticEventInput } from '@agent-device/host-kit/diagnostics'; import { hostFileStatSync, readHostDirectorySync } from '@agent-device/host-kit/host-file'; import { type OwnedProcessRecordStore, @@ -45,6 +45,7 @@ export type AgentBrowserCleanupOptions = { env: Readonly; openWebSessionNames?: readonly string[]; ownedProcessRecords?: OwnedProcessRecordStore; + emitDiagnostic?(event: DiagnosticEventInput): void; /** The fleet session whose open runs this cleanup: it has spawned nothing yet, so it never blocks the reap. */ startingSession?: string; }; @@ -95,7 +96,7 @@ export async function cleanupManagedAgentBrowserOrphans( }); const signalPids = [...reaped.terminatedPids]; if (reaped.inspected > 0) { - emitDiagnostic({ + (options.emitDiagnostic ?? emitDiagnostic)({ level: 'warn', phase: 'web_agent_browser_orphan_cleanup', data: { diff --git a/packages/platform-web/src/agent-browser-provider.ts b/packages/platform-web/src/agent-browser-provider.ts index 6f619f4a37..d83e3934dc 100644 --- a/packages/platform-web/src/agent-browser-provider.ts +++ b/packages/platform-web/src/agent-browser-provider.ts @@ -1,3 +1,4 @@ +import { AGENT_BROWSER_TIMEOUT_MS } from '@agent-device/contracts/managed-web-backend'; import { execFailureDetails } from '@agent-device/host-kit/command'; import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; import type { OwnedProcessRecordStore } from '@agent-device/host-kit/process'; @@ -9,7 +10,6 @@ import { } from '@agent-device/kernel/errors'; import type { Rect } from '@agent-device/kernel/snapshot'; -import type { HostEnvironment } from '@agent-device/kernel/source-value'; import { buildSelectFocusedContentEvalScript, readSelectFocusedContentOutcome, @@ -32,6 +32,7 @@ import { getManagedAgentBrowserStatus, mapManagedAgentBrowserError, runManagedAgentBrowser, + type ManagedBrowserHost, } from './agent-browser-tool.ts'; import { agentBrowserFleetOf, type AgentBrowserFleet } from './agent-browser-fleet.ts'; import { cleanupManagedAgentBrowserOrphansForProviderStartup } from './agent-browser-lifecycle.ts'; @@ -43,13 +44,12 @@ import { uniqueStrings } from '@agent-device/kernel/collections'; import { DEFAULT_SCROLL_AMOUNT } from '@agent-device/contracts/scroll-gesture'; const AGENT_BROWSER = 'agent-browser'; -const AGENT_BROWSER_TIMEOUT_MS = 30_000; const AGENT_BROWSER_DOCTOR_HINT = 'Run `agent-device web setup` to install the managed web backend.'; type AgentBrowserProviderOptions = { /** The composing runtime's host; every backend spawn and status read uses it. */ - host: HostEnvironment; + host: ManagedBrowserHost; /** The backend session key, read from the session device id; omitted for no session. */ session?: string; stateDir?: string; @@ -686,7 +686,7 @@ async function finalizeAgentBrowserProcessRecord(params: { await recordManagedAgentBrowserProcesses(params.status, store, params.options.host); } } catch (error) { - emitDiagnostic({ + (params.options.host.emitDiagnostic ?? emitDiagnostic)({ level: 'warn', phase: 'web_agent_browser_process_record_failed', data: { error: error instanceof Error ? error.message : String(error) }, @@ -784,6 +784,7 @@ async function cleanupProviderStartupOrphans( try { await cleanupManagedAgentBrowserOrphansForProviderStartup(status, { env: options.host.env, + ...(options.host.emitDiagnostic ? { emitDiagnostic: options.host.emitDiagnostic } : {}), openWebSessionNames: options.openWebSessionNames(), ...(startingSession === undefined ? {} : { startingSession }), ...(options.ownedProcessRecords === undefined @@ -791,7 +792,7 @@ async function cleanupProviderStartupOrphans( : { ownedProcessRecords: options.ownedProcessRecords }), }); } catch (error) { - emitDiagnostic({ + (options.host.emitDiagnostic ?? emitDiagnostic)({ level: 'warn', phase: 'web_agent_browser_provider_orphan_cleanup_failed', data: { error: error instanceof Error ? error.message : String(error) }, diff --git a/packages/platform-web/src/agent-browser-tool.ts b/packages/platform-web/src/agent-browser-tool.ts index 8ab9c70f79..c4c6bb234c 100644 --- a/packages/platform-web/src/agent-browser-tool.ts +++ b/packages/platform-web/src/agent-browser-tool.ts @@ -1,3 +1,4 @@ +import type { PlatformHost } from 'agent-device/plugins'; import path from 'node:path'; import { runCmd, type ExecResult } from '@agent-device/host-kit/command'; import { acquireProcessLock, withProcessLock } from '@agent-device/host-kit/file'; @@ -39,10 +40,12 @@ const SETUP_TIMEOUT_MS = 5 * 60_000; const DOCTOR_TIMEOUT_MS = 60_000; export type AgentBrowserToolStatus = ManagedWebBackendStatus; +export type ManagedBrowserHost = HostEnvironment & + Partial>; export type ManagedAgentBrowserRunOptions = { /** The caller's host: its environment selects the state dir and seeds the backend env. */ - host: HostEnvironment; + host: ManagedBrowserHost; stateDir?: string; timeoutMs: number; allowFailure?: boolean; @@ -66,7 +69,7 @@ export async function runManagedAgentBrowser( } export async function setupManagedAgentBrowser(options: { - host: HostEnvironment; + host: ManagedBrowserHost; stateDir?: string; }): Promise { const status = getManagedAgentBrowserStatus(options); @@ -94,6 +97,7 @@ export async function setupManagedAgentBrowser(options: { packageSpec: `${AGENT_BROWSER}@${MANAGED_AGENT_BROWSER_VERSION}`, timeoutMs: SETUP_TIMEOUT_MS, env: options.host.env, + runCommand: options.host.runCommand, }); // The backend entry only exists once npm has written the package. const installedStatus = getManagedAgentBrowserStatus(options); @@ -117,7 +121,7 @@ export async function setupManagedAgentBrowser(options: { } export async function doctorManagedAgentBrowser(options: { - host: HostEnvironment; + host: ManagedBrowserHost; stateDir?: string; }): Promise<{ status: AgentBrowserToolStatus; stdout: string; stderr: string; exitCode: number }> { const status = getManagedAgentBrowserStatus(options); @@ -133,7 +137,7 @@ export async function doctorManagedAgentBrowser(options: { } export function getManagedAgentBrowserStatus(options: { - host: HostEnvironment; + host: ManagedBrowserHost; stateDir?: string; }): AgentBrowserToolStatus { const stateDir = @@ -171,13 +175,17 @@ async function spawnManagedAgentBrowser( options: Omit, ): Promise { if (!status.entryScript) throw missingManagedToolError(status); - return await runCmd(hostNodeExecutablePath(), [status.entryScript, ...args], { - allowFailure: options.allowFailure, - env: managedAgentBrowserEnv(status, options.host.env), - timeoutMs: options.timeoutMs, - signal: options.signal, - stdin: options.stdin, - }); + return await (options.host.runCommand ?? runCmd)( + hostNodeExecutablePath(), + [status.entryScript, ...args], + { + allowFailure: options.allowFailure, + env: managedAgentBrowserEnv(status, options.host.env), + timeoutMs: options.timeoutMs, + signal: options.signal, + stdin: options.stdin, + }, + ); } function managedAgentBrowserEnv( diff --git a/packages/platform-web/src/index-startup-cleanup.test.ts b/packages/platform-web/src/index-startup-cleanup.test.ts new file mode 100644 index 0000000000..13f5175bef --- /dev/null +++ b/packages/platform-web/src/index-startup-cleanup.test.ts @@ -0,0 +1,68 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import { beforeEach, expect, test, vi } from 'vitest'; +import { + createLiveTestHostEnvironment, + installFakeManagedAgentBrowser, + mkdtempForTestSync, +} from '@agent-device/test-kit'; + +const { cleanupManagedAgentBrowserOrphansMock } = vi.hoisted(() => ({ + cleanupManagedAgentBrowserOrphansMock: vi.fn(), +})); + +vi.mock('./agent-browser-lifecycle.ts', async (importOriginal) => ({ + ...(await importOriginal()), + cleanupManagedAgentBrowserOrphans: cleanupManagedAgentBrowserOrphansMock, +})); + +import webPlatformPlugin from './index.ts'; +import { emitDiagnostic, withDiagnosticTimer } from '@agent-device/host-kit/diagnostics'; +import { runCmd } from '@agent-device/host-kit/command'; + +function cleanupWebBrowserOrphansForDaemonStartup(stateDir: string) { + const host = { + ...createLiveTestHostEnvironment(), + stateDir, + runCommand: runCmd, + emitDiagnostic, + withDiagnosticTimer, + }; + return webPlatformPlugin().contributes[0].setup(host).operations.cleanupOrphans; +} + +const mockCleanupManagedAgentBrowserOrphans = vi.mocked(cleanupManagedAgentBrowserOrphansMock); + +beforeEach(() => { + mockCleanupManagedAgentBrowserOrphans.mockReset(); +}); + +test('daemon-startup web cleanup passes open web sessions to the reaper', async () => { + const stateDir = mkdtempForTestSync('agent-device-web-daemon-cleanup-'); + try { + await installFakeManagedAgentBrowser(stateDir); + await cleanupWebBrowserOrphansForDaemonStartup(stateDir)(['web-session']); + + assert.equal(mockCleanupManagedAgentBrowserOrphans.mock.calls.length, 1); + assert.equal(mockCleanupManagedAgentBrowserOrphans.mock.calls[0]?.[1], 'daemon-startup'); + expect(mockCleanupManagedAgentBrowserOrphans.mock.calls[0]?.[2]).toEqual({ + env: process.env, + ownedProcessRecords: undefined, + emitDiagnostic: expect.any(Function), + openWebSessionNames: ['web-session'], + }); + } finally { + fs.rmSync(stateDir, { recursive: true, force: true }); + } +}); + +test('daemon-startup web cleanup does not run when the managed backend is absent', async () => { + const stateDir = mkdtempForTestSync('agent-device-web-daemon-cleanup-'); + try { + await cleanupWebBrowserOrphansForDaemonStartup(stateDir)([]); + + assert.equal(mockCleanupManagedAgentBrowserOrphans.mock.calls.length, 0); + } finally { + fs.rmSync(stateDir, { recursive: true, force: true }); + } +}); diff --git a/packages/platform-web/src/index.ts b/packages/platform-web/src/index.ts index c507b24b97..a335feb46c 100644 --- a/packages/platform-web/src/index.ts +++ b/packages/platform-web/src/index.ts @@ -1,27 +1,15 @@ +import type { PlatformContribution, PlatformSetup } from 'agent-device/plugins'; import type { InventoryPlatformModule, PlatformModuleMetadata, } from '@agent-device/contracts/platform-module'; import type { PlatformRuntimeModule } from '@agent-device/contracts/platform-runtime-operations'; -// fallow-ignore-next-line code-duplication -type DeferredFunction = (...args: never[]) => unknown; -type Deferred = ( - ...args: Parameters -) => Promise>>; - -function deferred(load: () => Promise): Deferred { - return (async (...args: Parameters) => - await ( - await load() - )(...args)) as unknown as Deferred; -} - const metadata = Object.freeze({ family: 'web', } satisfies PlatformModuleMetadata); -export const runtimeModule = Object.freeze({ +const runtimeModule = Object.freeze({ ...metadata, loadRuntime: async (host) => { const { createWebPlatformRuntime } = await import('./runtime.ts'); @@ -29,7 +17,7 @@ export const runtimeModule = Object.freeze({ }, } satisfies PlatformRuntimeModule); -export const inventoryModule: InventoryPlatformModule<'web'> = Object.freeze({ +const inventoryModule: InventoryPlatformModule<'web'> = Object.freeze({ ...metadata, loadInventory: async () => { const { createWebInventory } = await import('./inventory.ts'); @@ -37,51 +25,80 @@ export const inventoryModule: InventoryPlatformModule<'web'> = Object.freeze({ }, }); -export const AGENT_BROWSER_TIMEOUT_MS = 30_000; - -export type { WebProvider } from './provider.ts'; -export type { AgentBrowserProcessSummary } from './agent-browser-process-record.ts'; -export type { AgentBrowserToolStatus } from './agent-browser-tool.ts'; - -export const createAgentBrowserWebProvider = deferred< - (typeof import('./agent-browser-provider.ts'))['createAgentBrowserWebProvider'] ->(async () => (await import('./agent-browser-provider.ts')).createAgentBrowserWebProvider); -export const getManagedAgentBrowserStatus = deferred< - (typeof import('./agent-browser-tool.ts'))['getManagedAgentBrowserStatus'] ->(async () => (await import('./agent-browser-tool.ts')).getManagedAgentBrowserStatus); -export const setupManagedAgentBrowser = deferred< - (typeof import('./agent-browser-tool.ts'))['setupManagedAgentBrowser'] ->(async () => (await import('./agent-browser-tool.ts')).setupManagedAgentBrowser); -export const doctorManagedAgentBrowser = deferred< - (typeof import('./agent-browser-tool.ts'))['doctorManagedAgentBrowser'] ->(async () => (await import('./agent-browser-tool.ts')).doctorManagedAgentBrowser); -export const inspectManagedAgentBrowserProcesses = deferred< - (typeof import('./agent-browser-process-record.ts'))['inspectManagedAgentBrowserProcesses'] ->( - async () => - (await import('./agent-browser-process-record.ts')).inspectManagedAgentBrowserProcesses, -); -export const summarizeAgentBrowserProcesses = deferred< - (typeof import('./agent-browser-process-record.ts'))['summarizeAgentBrowserProcesses'] ->(async () => (await import('./agent-browser-process-record.ts')).summarizeAgentBrowserProcesses); -export const cleanupManagedAgentBrowserOrphans = deferred< - (typeof import('./agent-browser-lifecycle.ts'))['cleanupManagedAgentBrowserOrphans'] ->(async () => (await import('./agent-browser-lifecycle.ts')).cleanupManagedAgentBrowserOrphans); -export const webBrowserLifecycleCheck = deferred< - (typeof import('./doctor.ts'))['webBrowserLifecycleCheck'] ->(async () => (await import('./doctor.ts')).webBrowserLifecycleCheck); - -export const resolveRequestScopedWebProvider = deferred< - (typeof import('./resolve-provider.ts'))['resolveRequestScopedWebProvider'] ->(async () => (await import('./resolve-provider.ts')).resolveRequestScopedWebProvider); -export const resolveWebProviderForHost = deferred< - (typeof import('./resolve-provider.ts'))['resolveWebProviderForHost'] ->(async () => (await import('./resolve-provider.ts')).resolveWebProviderForHost); - -export async function withWebProvider( - provider: import('./provider.ts').WebProvider | undefined, - fn: () => Promise, -): Promise { - const { withWebProvider: implementation } = await import('./provider.ts'); - return await implementation(provider, fn); +function webPlatformPlugin() { + return { + apiVersion: 3, + contributes: [ + { + kind: 'platform', + family: 'web', + setup(host): PlatformSetup<'web'> { + const { stateDir, openWebSessionNames, ownedProcessRecords } = host; + return { + family: 'web', + inventoryModule, + runtimeModule, + createInteractor: async () => { + const { createWebInteractor } = await import('./interactor.ts'); + return await createWebInteractor(host, undefined, stateDir); + }, + withRequestProvider: async (provider, task) => { + const { withWebProvider } = await import('./provider.ts'); + return await withWebProvider(provider, task); + }, + operations: { + setup: async (options) => { + const { setupManagedAgentBrowser } = await import('./agent-browser-tool.ts'); + return await setupManagedAgentBrowser({ + stateDir: options.stateDir ?? stateDir, + host, + }); + }, + doctor: async (options) => { + const { doctorManagedAgentBrowser } = await import('./agent-browser-tool.ts'); + return await doctorManagedAgentBrowser({ + stateDir: options.stateDir ?? stateDir, + host, + }); + }, + browserLifecycleCheck: async (dir) => { + const { webBrowserLifecycleCheck } = await import('./doctor.ts'); + return await webBrowserLifecycleCheck(dir, host); + }, + cleanupOrphans: async (openSessions) => { + const { getManagedAgentBrowserStatus } = await import('./agent-browser-tool.ts'); + const status = getManagedAgentBrowserStatus({ stateDir, host }); + if (!status.installed) return; + const { cleanupManagedAgentBrowserOrphans } = + await import('./agent-browser-lifecycle.ts'); + await cleanupManagedAgentBrowserOrphans(status, 'daemon-startup', { + env: host.env, + openWebSessionNames: openSessions, + ownedProcessRecords, + emitDiagnostic: host.emitDiagnostic, + }); + }, + createProvider: async (session) => { + const { createAgentBrowserWebProvider } = + await import('./agent-browser-provider.ts'); + return await createAgentBrowserWebProvider({ + host, + stateDir, + session, + openWebSessionNames, + ownedProcessRecords, + }); + }, + resolveRequestProvider: async () => { + const { resolveRequestScopedWebProvider } = await import('./resolve-provider.ts'); + return await resolveRequestScopedWebProvider(); + }, + }, + }; + }, + }, + ], + } satisfies { apiVersion: 3; contributes: [Extract] }; } + +export { webPlatformPlugin as default }; diff --git a/packages/platform-web/src/interactor-facade.ts b/packages/platform-web/src/interactor-facade.ts deleted file mode 100644 index 9e5da0998e..0000000000 --- a/packages/platform-web/src/interactor-facade.ts +++ /dev/null @@ -1,11 +0,0 @@ -import type { Interactor } from '@agent-device/contracts/interactor-types'; -import type { HostEnvironment } from '@agent-device/kernel/source-value'; -import type { WebProvider } from './provider.ts'; - -export async function createWebInteractor( - host: HostEnvironment, - provider?: WebProvider, -): Promise { - const { createWebInteractor: create } = await import('./interactor.ts'); - return await create(host, provider); -} diff --git a/packages/platform-web/src/interactor.test.ts b/packages/platform-web/src/interactor.test.ts index d631fa2aac..d03b4dcd93 100644 --- a/packages/platform-web/src/interactor.test.ts +++ b/packages/platform-web/src/interactor.test.ts @@ -2,7 +2,7 @@ import assert from 'node:assert/strict'; import { test } from 'vitest'; import { createWebInteractor } from './interactor.ts'; import { AppError } from '@agent-device/kernel/errors'; -import { withWebProvider } from './index.ts'; +import { withWebProvider } from './provider.ts'; import { makeWebProvider } from './__tests__/test-utils.ts'; test('web interactor delegates first-slice operations to the scoped provider', async () => { diff --git a/packages/platform-web/src/interactor.ts b/packages/platform-web/src/interactor.ts index e612d2b479..6e5bbe017e 100644 --- a/packages/platform-web/src/interactor.ts +++ b/packages/platform-web/src/interactor.ts @@ -4,16 +4,18 @@ import { createUnsupportedInteractor } from '@agent-device/contracts/unsupported import { AppError } from '@agent-device/kernel/errors'; import { stripAtPrefix } from '@agent-device/selectors/interaction-positionals'; import { withDiagnosticTimer } from '@agent-device/host-kit/diagnostics'; -import { resolveWebProviderForHost, type WebProvider } from './index.ts'; -import type { HostEnvironment } from '@agent-device/kernel/source-value'; +import { resolveWebProviderForHost } from './resolve-provider.ts'; +import type { WebProvider } from '@agent-device/contracts/web-provider'; +import type { ManagedBrowserHost } from './agent-browser-tool.ts'; export async function createWebInteractor( - host: HostEnvironment, + host: ManagedBrowserHost, provider?: WebProvider, + stateDir?: string, ): Promise { // A request's scoped provider wins; an out-of-request local path binds the composing root's // host into its own default provider instead of reading an ambient one (#3794). - const resolvedProvider = await resolveWebProviderForHost(host, provider); + const resolvedProvider = await resolveWebProviderForHost(host, provider, stateDir); const clickRef = resolvedProvider.clickRef; const hover = resolvedProvider.hover; const hoverRef = resolvedProvider.hoverRef; @@ -56,7 +58,7 @@ export async function createWebInteractor( screenshot: (outPath, options) => resolvedProvider.screenshot(outPath, options), setViewport: (width, height) => resolvedProvider.setViewport(width, height), snapshot: async (options) => { - const result = await withDiagnosticTimer( + const result = await (host.withDiagnosticTimer ?? withDiagnosticTimer)( 'snapshot_capture', async () => await resolvedProvider.snapshot(options), { backend: 'web' }, diff --git a/packages/platform-web/src/resolve-provider.ts b/packages/platform-web/src/resolve-provider.ts index b332903f0c..cf5e05e12d 100644 --- a/packages/platform-web/src/resolve-provider.ts +++ b/packages/platform-web/src/resolve-provider.ts @@ -21,10 +21,11 @@ export async function resolveRequestScopedWebProvider(): Promise { if (provider) return provider; const scoped = await resolveRequestScopedWebProvider(); if (scoped) return scoped; const { createAgentBrowserWebProvider } = await import('./agent-browser-provider.ts'); - return await createAgentBrowserWebProvider({ host }); + return await createAgentBrowserWebProvider({ host, stateDir }); } diff --git a/packages/platform-web/test/package-smoke.mjs b/packages/platform-web/test/package-smoke.mjs new file mode 100644 index 0000000000..0ee58ac60d --- /dev/null +++ b/packages/platform-web/test/package-smoke.mjs @@ -0,0 +1,90 @@ +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { test } from 'node:test'; +import { installFakeManagedAgentBrowser } from '@agent-device/test-kit'; + +const repo = path.resolve(import.meta.dirname, '../../..'); + +test('packed core discovers web only after the managed platform is installed', () => { + const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-device-web-pack-')); + const env = { + ...Object.fromEntries( + Object.entries(process.env).filter(([name]) => !name.startsWith('AGENT_DEVICE_')), + ), + AGENT_DEVICE_HOME: path.join(scratch, 'home'), + AGENT_DEVICE_STATE_DIR: path.join(scratch, 'state'), + AGENT_DEVICE_CLAIMS_DIR: path.join(scratch, 'claims'), + AGENT_DEVICE_NO_UPDATE_NOTIFIER: '1', + }; + const exec = (command, args, cwd = scratch) => + execFileSync(command, args, { cwd, env, encoding: 'utf8', timeout: 120_000 }); + const cli = (...args) => + exec(process.execPath, ['node_modules/agent-device/bin/agent-device.mjs', ...args]); + const runCli = (expectedExit, ...args) => { + try { + const reply = JSON.parse(cli(...args, '--json')); + assert.equal(expectedExit, 0); + return reply; + } catch (error) { + if (expectedExit !== 0 && error.status === expectedExit) return JSON.parse(error.stdout); + throw error; + } + }; + try { + const [packed] = JSON.parse( + exec('npm', ['pack', '--ignore-scripts', '--json', '--pack-destination', scratch], repo), + ); + assert.ok(!packed.files.some(({ path }) => path.includes('/agent-browser-provider.'))); + exec( + 'pnpm', + ['pack', '--out', path.join(scratch, 'web.tgz')], + path.join(repo, 'packages/platform-web'), + ); + fs.writeFileSync(path.join(scratch, 'package.json'), '{"private":true}'); + exec('npm', [ + 'install', + '--ignore-scripts', + '--no-audit', + '--no-fund', + path.join(scratch, packed.filename), + ]); + assert.match(cli('help', 'web'), /agent-device plugins add @agent-device\/web/); + + for (const args of [ + ['web', 'setup'], + ['web', 'doctor'], + ['devices', '--platform', 'web'], + ]) { + const { error } = runCli(1, ...args); + assert.equal(error.details.reason, 'plugin-not-installed'); + assert.match(error.hint, /agent-device plugins add @agent-device\/web/); + } + runCli(0, 'daemon', 'stop'); + if (Number(process.versions.node.split('.')[0]) < 24) { + assert.equal( + runCli(1, 'plugins', 'add', './web.tgz').error.details.reason, + 'node-below-floor', + ); + return; + } + runCli(0, 'plugins', 'add', './web.tgz'); + assert.match( + JSON.stringify(runCli(0, 'devices', '--platform', 'web').data), + /agent-browser-chrome/, + ); + const plugins = runCli(0, 'daemon', 'status').data.plugins; + assert.ok(plugins.some((plugin) => plugin.platform === 'web' && plugin.state === 'active')); + installFakeManagedAgentBrowser(env.AGENT_DEVICE_STATE_DIR); + assert.equal(runCli(0, 'web', 'doctor').data.status.installed, true); + } finally { + try { + if (fs.existsSync(path.join(scratch, 'node_modules/agent-device'))) + runCli(0, 'daemon', 'stop'); + } finally { + fs.rmSync(scratch, { recursive: true, force: true }); + } + } +}); diff --git a/packages/platform-web/tsconfig.json b/packages/platform-web/tsconfig.json index 59e004380a..f7f9b272a3 100644 --- a/packages/platform-web/tsconfig.json +++ b/packages/platform-web/tsconfig.json @@ -6,11 +6,13 @@ "emitDeclarationOnly": true, "declaration": true, "declarationDir": "./dist-types", - "rootDir": "./src", + "rootDir": ".", + "paths": { "agent-device/plugins": ["./node_modules/agent-device/src/sdk/plugins.ts"] }, "tsBuildInfoFile": "./dist-types/index.tsbuildinfo" }, "include": ["src"], "references": [ + { "path": "../build-config" }, { "path": "../capture-kit" }, { "path": "../contracts" }, { "path": "../host-kit" }, diff --git a/packages/plugins/src/platform.test.ts b/packages/plugins/src/platform.test.ts index e26a2bcbf6..f52b53ab14 100644 --- a/packages/plugins/src/platform.test.ts +++ b/packages/plugins/src/platform.test.ts @@ -1,6 +1,6 @@ import { expect, test } from 'vitest'; import { pluginHome, selectPlugin } from '@agent-device/test-kit'; -import { missingOptionalPlatformError } from '@agent-device/contracts/platform-module'; +import { missingOptionalPlatformError } from '@agent-device/contracts/plugin-installation'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; import { createPluginSelectionGuard, storePluginCandidates } from './store.ts'; import { resolveProviderPlugins, startProviderRegistry } from './registry.ts'; diff --git a/packages/plugins/src/platform.ts b/packages/plugins/src/platform.ts index d402404277..ed51d0d3e8 100644 --- a/packages/plugins/src/platform.ts +++ b/packages/plugins/src/platform.ts @@ -1,10 +1,12 @@ -import type { ManagedWebBackend } from '@agent-device/contracts/managed-web-backend'; -import type { DoctorCheck } from '@agent-device/contracts/observability'; import type { InventoryPlatformModule, OptionalPlatform, } from '@agent-device/contracts/platform-module'; -import type { PlatformPlugin } from '@agent-device/contracts/platform-plugin'; +import type { + PlatformPlugin, + WebPlatformOperations, + WebPlatformRegistration, +} from '@agent-device/contracts/platform-plugin'; import type { PlatformRuntimeModule } from '@agent-device/contracts/platform-runtime-operations'; import type { WebProvider } from '@agent-device/contracts/web-provider'; import type { DiagnosticEventInput, withDiagnosticTimer } from '@agent-device/host-kit/diagnostics'; @@ -32,14 +34,6 @@ export type PlatformHost = HostEnvironment & withDiagnosticTimer: typeof withDiagnosticTimer; }>; -export type WebPlatformOperations = ManagedWebBackend & - Readonly<{ - cleanupOrphans(openWebSessionNames: readonly string[]): Promise; - browserLifecycleCheck(stateDir: string): Promise; - createProvider(session: string): Promise; - resolveRequestProvider(): Promise; - }>; - export type PlatformSetup = Family extends OptionalPlatform ? Readonly<{ @@ -65,12 +59,14 @@ export type PlatformSetup = /** Full module types used after the composing registry validates the declared family and loaders. */ export type RegisteredPlatformSetup = Family extends OptionalPlatform - ? Omit, 'inventoryModule' | 'runtimeModule' | 'createInteractor'> & - Readonly<{ - createInteractor: PlatformPlugin['createInteractor']; - inventoryModule: InventoryPlatformModule; - runtimeModule: PlatformRuntimeModule & { readonly family: Family }; - }> + ? Family extends 'web' + ? WebPlatformRegistration + : Omit, 'inventoryModule' | 'runtimeModule' | 'createInteractor'> & + Readonly<{ + createInteractor: PlatformPlugin['createInteractor']; + inventoryModule: InventoryPlatformModule; + runtimeModule: PlatformRuntimeModule & { readonly family: Family }; + }> : never; export type PlatformContribution = { diff --git a/packages/plugins/src/registry.ts b/packages/plugins/src/registry.ts index c41be34194..1bc15e8bf5 100644 --- a/packages/plugins/src/registry.ts +++ b/packages/plugins/src/registry.ts @@ -841,3 +841,5 @@ function once(run: () => Promise): () => Promise { let started: Promise | undefined; return () => (started ??= run()); } + +export type { RegisteredPlatformSetup } from './platform.ts'; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 7dcd6b4cce..580cf679df 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -92,9 +92,6 @@ importers: '@agent-device/platform-vega': specifier: workspace:* version: link:packages/platform-vega - '@agent-device/platform-web': - specifier: workspace:* - version: link:packages/platform-web '@agent-device/plugins': specifier: workspace:* version: link:packages/plugins @@ -526,9 +523,6 @@ importers: '@agent-device/platform-apple': specifier: workspace:* version: link:../platform-apple - '@agent-device/platform-web': - specifier: workspace:* - version: link:../platform-web '@agent-device/replay-port': specifier: workspace:* version: link:../replay-port @@ -840,7 +834,10 @@ importers: version: link:../provision-kit packages/platform-web: - dependencies: + devDependencies: + '@agent-device/build-config': + specifier: workspace:* + version: link:../build-config '@agent-device/capture-kit': specifier: workspace:* version: link:../capture-kit @@ -856,10 +853,12 @@ importers: '@agent-device/selectors': specifier: workspace:* version: link:../selectors - devDependencies: '@agent-device/test-kit': specifier: workspace:* version: link:../test-kit + agent-device: + specifier: workspace:* + version: link:../.. packages/plugins: dependencies: diff --git a/scripts/capability-matrix/collect.ts b/scripts/capability-matrix/collect.ts index d7cfb959b3..c5bafd765c 100644 --- a/scripts/capability-matrix/collect.ts +++ b/scripts/capability-matrix/collect.ts @@ -12,7 +12,7 @@ import { listRuntimeFactCommands } from '@agent-device/command-registry/registry import { commandIsAvailableFromFacts } from '@agent-device/command-registry/planned-operations'; import { runtimeModule as appleRuntimeModule } from '@agent-device/platform-apple'; import { createAndroidRuntimeModule } from '@agent-device/platform-android'; -import { runtimeModule as webRuntimeModule } from '@agent-device/platform-web'; +import { webSelectionFixture } from '../../src/platform-runtime-web-provider.fixtures.ts'; import { runtimeModule as vegaRuntimeModule } from '@agent-device/platform-vega'; import { runtimeModule as harmonyosRuntimeModule } from '@agent-device/platform-harmonyos'; import { runtimeModule as linuxRuntimeModule } from '@agent-device/platform-linux'; @@ -31,6 +31,8 @@ import type { DeviceInfo } from '@agent-device/kernel/device'; import { createProviderWire, PROVIDER_ENV, stubLimrunSdk, type ProviderWire } from './seams.ts'; import { TARGETS, type Target } from './targets.ts'; +const webRuntimeModule = webSelectionFixture().get().runtimeModule; + export type CommandSupport = Readonly<{ /** Public commands the registry derives from runtime facts, in registry order. */ commands: readonly string[]; diff --git a/scripts/capability-matrix/seams.ts b/scripts/capability-matrix/seams.ts index 4a10951e34..21a0d2b379 100644 --- a/scripts/capability-matrix/seams.ts +++ b/scripts/capability-matrix/seams.ts @@ -6,8 +6,7 @@ // no daemon, no credentials, and no network. Nothing here talks to a provider. import moduleHooks from 'node:module'; -import { createAgentBrowserWebProvider, withWebProvider } from '@agent-device/platform-web'; -import { createWebInteractor } from '@agent-device/platform-web/interactor'; +import { webSelectionFixture } from '../../src/platform-runtime-web-provider.fixtures.ts'; import type { RunHostCommand } from '@agent-device/plugins/host'; import type { PlatformRuntimeHost } from '@agent-device/contracts/platform-runtime-operations'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; @@ -43,11 +42,9 @@ function inert(pathname: string): unknown { // The daemon answers web facts through the agent-browser provider it composes // into every web request (src/platform-runtime/request-providers.ts); the seam // builds the same provider, so the provider's own surface decides each cell. -async function matrixWebProvider() { - return await createAgentBrowserWebProvider({ host: HOST_ENVIRONMENT }); -} - -const HOST_ENVIRONMENT: HostEnvironment = { env: {} } as unknown as HostEnvironment; +const HOST_ENVIRONMENT: HostEnvironment = { env: {}, cwd: process.cwd() }; +const web = webSelectionFixture(HOST_ENVIRONMENT); +const webRegistration = web.get(); const localProcessTransport = Object.freeze({ mode: 'local' as const, @@ -78,7 +75,10 @@ export function createStubHost(): PlatformRuntimeHost { // daemon's default provider is scoped, and the production resolver reads // that scope to choose its mode, so the fact must be collected the same way. resolve: async (device: Parameters[0]) => - await withWebProvider(await matrixWebProvider(), () => resolveWebNetworkTransport(device)), + await webRegistration.withRequestProvider( + await webRegistration.operations.createProvider('default'), + () => resolveWebNetworkTransport(device, web), + ), }, screenRecording: { apple: { @@ -90,15 +90,16 @@ export function createStubHost(): PlatformRuntimeHost { // Inside a web request the daemon scopes its default provider, so the // matrix scopes it the same way before asking the production resolver. resolve: async (device: Parameters[0]) => - await withWebProvider(await matrixWebProvider(), () => - resolveWebScreenRecordingTransport(device), + await webRegistration.withRequestProvider( + await webRegistration.operations.createProvider('default'), + () => resolveWebScreenRecordingTransport(device, web), ), }, }, localInteractors: { // The production web plugin path: the factory composes the default // agent-browser provider from this host when none is scoped. - resolve: async () => await createWebInteractor(HOST_ENVIRONMENT), + resolve: webRegistration.createInteractor, }, }; return new Proxy(real, { diff --git a/src/__tests__/contracts/platform-plugin-parity.test.ts b/src/__tests__/contracts/platform-plugin-parity.test.ts index 2c27904e92..0341d204a3 100644 --- a/src/__tests__/contracts/platform-plugin-parity.test.ts +++ b/src/__tests__/contracts/platform-plugin-parity.test.ts @@ -1,7 +1,10 @@ +import { + createPlatformModuleRegistry, + REQUIRED_PLATFORMS, +} from '@agent-device/contracts/platform-module'; import assert from 'node:assert/strict'; import { test } from 'vitest'; -import { PLATFORMS, type Platform } from '@agent-device/kernel/device'; -import { REQUIRED_PLATFORMS } from '@agent-device/contracts/platform-module'; +import type { Platform } from '@agent-device/kernel/device'; import { AppError } from '@agent-device/kernel/errors'; import { getPlugin, @@ -17,7 +20,7 @@ import { import { missingPlatformPlugin } from '../../core/platform-plugin-absence.ts'; // Idempotently populate the root-owned registry for this test module. -registerBuiltinPlatformPlugins(missingPlatformPlugin); +registerBuiltinPlatformPlugins(missingPlatformPlugin, createPlatformModuleRegistry); // Independent copy of the internal platform accept-set. The CLI `--platform` // enum derives separately from `PLATFORM_SELECTORS`; this oracle keeps registry @@ -33,11 +36,11 @@ function parsePlatformByHand(value: unknown): Platform | undefined { : undefined; } -test('registeredPlatforms() equals the canonical PLATFORMS tuple, in order', () => { +test('built-in platforms follow the canonical family order', () => { // Byte-for-byte allow-list parity: the registry derives exactly PLATFORMS, // in the same order. (Left as a parity assertion — PLATFORMS stays the // hand-authored source of truth; nothing is derived FROM the registry yet.) - assert.deepEqual(registeredPlatforms(), [...PLATFORMS]); + assert.deepEqual(registeredPlatforms(), ['apple', 'android', 'harmonyos', 'vega', 'linux']); }); test('every required family is covered by a builtin plugin; optional families may be absent', () => { @@ -75,7 +78,7 @@ test('registry coverage is byte-for-byte equal to the parsePlatform hand allow-l ]; for (const candidate of candidates) { const registered = tryGetPlugin(candidate as Platform) !== undefined; - const parses = parsePlatformByHand(candidate) !== undefined; + const parses = parsePlatformByHand(candidate) !== undefined && candidate !== 'web'; assert.equal(registered, parses, `coverage parity for ${JSON.stringify(candidate)}`); } }); @@ -91,7 +94,7 @@ test('a family plugin resolves to the SAME instance for every leaf it owns', () }); test('each registered platform resolves to a plugin that owns it', () => { - for (const platform of PLATFORMS) { + for (const platform of registeredPlatforms()) { const plugin = getPlugin(platform); assert.ok( plugin.platforms.includes(platform), @@ -116,7 +119,12 @@ test('getPlugin throws UNSUPPORTED_PLATFORM (verbatim) for an unregistered platf test('registering a duplicate platform is a hard error', () => { assert.throws( - () => registerPlatformPluginSet([BUILTIN_PLATFORM_PLUGINS[0]], missingPlatformPlugin), - /already registered for platform/, + () => + registerPlatformPluginSet( + [BUILTIN_PLATFORM_PLUGINS[0]], + missingPlatformPlugin, + createPlatformModuleRegistry, + ), + /Duplicate platform family registration/, ); }); diff --git a/src/__tests__/test-utils/absent-platform-registry.ts b/src/__tests__/test-utils/absent-platform-registry.ts new file mode 100644 index 0000000000..7f44444274 --- /dev/null +++ b/src/__tests__/test-utils/absent-platform-registry.ts @@ -0,0 +1,8 @@ +import type { ProviderRegistry } from '@agent-device/plugins/registry'; + +export const absentPlatformRegistry: Pick = { + platforms: [], + resolvePlatform: (family, reportAbsent) => { + throw reportAbsent(family); + }, +}; diff --git a/src/cli/connection/provider-policy.ts b/src/cli/connection/provider-policy.ts index 1d38a4e408..9e2aeb4028 100644 --- a/src/cli/connection/provider-policy.ts +++ b/src/cli/connection/provider-policy.ts @@ -6,10 +6,11 @@ import { pluginConnectionNames, primePluginConnections, } from '@agent-device/plugins/connection'; +import { pluginInstallationHint } from '@agent-device/contracts/plugin-installation'; +import { readVersion } from '@agent-device/host-kit/version'; import { AppError } from '@agent-device/kernel/errors'; import { getProviderPluginDeclaration, - providerPluginInstallCommand, providerPluginRepairCommand, } from '../../commands/provider-plugin-catalog.ts'; import { @@ -94,7 +95,6 @@ export function unavailableConnectPluginError( hint: `Run agent-device plugins list --json to inspect the plugin, fix its configuration or run ${providerPluginRepairCommand(declaration)}, then retry your original command.`, }); } - const installCommand = providerPluginInstallCommand(declaration); return new AppError( 'UNSUPPORTED_OPERATION', `${declaration.label} requires the ${declaration.package} plugin.`, @@ -102,8 +102,7 @@ export function unavailableConnectPluginError( reason: 'plugin-not-installed', provider, package: declaration.package, - installCommand, - hint: `Install:\n ${installCommand}\nThen retry your original command. If a local daemon is already running, close its sessions and run agent-device daemon stop with the same --state-dir before retrying.`, + ...pluginInstallationHint(declaration, readVersion()), }, ); } diff --git a/src/commands/provider-plugin-catalog.ts b/src/commands/provider-plugin-catalog.ts index d019f2c321..1be956f0a9 100644 --- a/src/commands/provider-plugin-catalog.ts +++ b/src/commands/provider-plugin-catalog.ts @@ -4,7 +4,7 @@ import { pluginInstallCommand, pluginPackageSelector, pluginRepairCommand, -} from '@agent-device/contracts/platform-module'; +} from '@agent-device/contracts/plugin-installation'; type ProviderPluginDeclaration = PluginReleaseDeclaration & Readonly<{ @@ -41,9 +41,6 @@ export function getProviderPluginDeclaration( return PROVIDER_PLUGIN_CATALOG.find((plugin) => plugin.provider === provider); } -// The release-channel rule lives in @agent-device/contracts/platform-module, shared with the -// optional platform families, so the two catalogs cannot drift apart on the nightly selector. - export function providerPluginInstallCommand( declaration: ProviderPluginDeclaration, coreVersion: string = readVersion(), diff --git a/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index 53f255ac5f..311b389d6a 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -98,6 +98,7 @@ Command shape: Bootstrap: open --foreground -> snapshot. Selection: explicit --device/--udid/--serial, then session, booted/bootable local, or provider; --platform/--target only filter. Ambiguous/empty fails with bounded retry selectors; no provider fallback. + An absent optional platform returns details.reason plugin-not-installed with its install command. Install arguments are app/package id then artifact path: agent-device install com.example.app ./dist/app.apk --platform android, then open --relaunch for fresh state. Use reinstall only when explicitly requested. Unknown app id: devices, then apps, then open . Never open artifact paths or invent package ids; ask if lookup misses the target. Apple CI: prepare ios-runner after boot/install, before replay/test (help prepare). Remote/cloud: connect -> open -> commands -> close -> disconnect (help remote). Reusable scripts, secret-safe fills, replay repair: help scripting. @@ -685,6 +686,7 @@ Dependency: Browser mechanics come from a managed, pinned agent-browser backend. agent-device owns command/session/replay integration, selectors/refs at the command surface, and artifact routing; agent-browser owns browser launch, page control, screenshots, and browser-specific behavior. Use --platform web when a browser step belongs inside an agent-device session, replay, batch, MCP, or typed-client flow. Use agent-browser directly for standalone web automation. Before first use, set up and verify the managed backend: + agent-device plugins add @agent-device/web agent-device web setup agent-device web doctor Web automation requires Node 24+. @@ -694,6 +696,7 @@ Planning rule: First-slice loop: Audio probe start uses duration seconds first, then bucket milliseconds. + agent-device plugins add @agent-device/web agent-device web setup agent-device web doctor agent-device open https://example.com --platform web diff --git a/src/core/interactors.ts b/src/core/interactors.ts index 0976e33c68..3381077172 100644 --- a/src/core/interactors.ts +++ b/src/core/interactors.ts @@ -1,3 +1,5 @@ +import { createPlatformModuleRegistry } from '@agent-device/contracts/platform-module'; +import type { WebPlatformSelection } from '@agent-device/contracts/platform-plugin'; import { publicPlatformString, type DeviceInfo } from '@agent-device/kernel/device'; import { AppError } from '@agent-device/kernel/errors'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; @@ -9,12 +11,13 @@ import { registerBuiltinPlatformPlugins } from './interactors/register-builtins. // Populate the platform-plugin registry once, at module load (only registers // lazy closures — no leaf code is imported here, so CLI cold-start is unaffected). -registerBuiltinPlatformPlugins(missingPlatformPlugin); +registerBuiltinPlatformPlugins(missingPlatformPlugin, createPlatformModuleRegistry); export async function getInteractor( device: DeviceInfo, runnerContext: RunnerContext, host: HostEnvironment, + web?: WebPlatformSelection, ): Promise { if (isActiveProviderDevice(device)) { const providerInteractor = getProviderDeviceInteractor(device, runnerContext); @@ -26,7 +29,7 @@ export async function getInteractor( ); } - return await getLocalInteractor(device, runnerContext, host); + return await getLocalInteractor(device, runnerContext, host, web); } /** @@ -39,7 +42,11 @@ export async function getLocalInteractor( device: DeviceInfo, runnerContext: RunnerContext, host: HostEnvironment, + web?: WebPlatformSelection, ): Promise { + if (device.platform === 'web' && web) { + return await web.get().createInteractor(device, runnerContext, host); + } // Byte-identical replacement for the former per-platform switch: each plugin's // `createInteractor` is the SAME lazy dynamic import + factory call the switch // arm performed, and `getPlugin` throws the SAME `UNSUPPORTED_PLATFORM` AppError diff --git a/src/core/interactors/register-builtins.ts b/src/core/interactors/register-builtins.ts index ccbe8b6562..667edde7c5 100644 --- a/src/core/interactors/register-builtins.ts +++ b/src/core/interactors/register-builtins.ts @@ -1,6 +1,9 @@ import type { RunnerContext } from '@agent-device/contracts/interactor-types'; import type { PlatformPlugin } from '@agent-device/contracts/platform-plugin'; -import type { RequiredPlatform } from '@agent-device/contracts/platform-module'; +import type { + RequiredPlatform, + createPlatformModuleRegistry, +} from '@agent-device/contracts/platform-module'; import { registerPlatformPluginSet, type PlatformPluginAbsence, @@ -42,18 +45,6 @@ const linuxPlugin = { }, } as const satisfies PlatformPlugin; -const webPlugin = { - id: 'web', - platforms: ['web'], - // Declares the platform-gated request provider resolver the web family owns (the web - // provider, formerly gated by `device.platform === 'web'`). - providers: { platformGatedResolvers: ['webProvider'] }, - createInteractor: async (_device, _runner, host) => { - const { createWebInteractor } = await import('@agent-device/platform-web/interactor'); - return await createWebInteractor(host); - }, -} as const satisfies PlatformPlugin; - /** * The builtin plugins, in `PLATFORMS` order so `registeredPlatforms()` derives * the canonical tuple's order (asserted by the parity test). @@ -64,7 +55,6 @@ export const BUILTIN_PLATFORM_PLUGINS = [ harmonyosPlugin, vegaPlugin, linuxPlugin, - webPlugin, ] as const satisfies readonly PlatformPlugin[]; // The leaf platforms covered by at least one builtin plugin, recovered from the @@ -94,8 +84,11 @@ let registered = false; * decides which core's plugin release an installation hint names (ADR 0034). It belongs to the set — * not to a plugin — so no plugin can swap this process's absence policy. */ -export function registerBuiltinPlatformPlugins(reportAbsent: PlatformPluginAbsence): void { +export function registerBuiltinPlatformPlugins( + reportAbsent: PlatformPluginAbsence, + createRegistry: typeof createPlatformModuleRegistry, +): void { if (registered) return; - registerPlatformPluginSet(BUILTIN_PLATFORM_PLUGINS, reportAbsent); + registerPlatformPluginSet(BUILTIN_PLATFORM_PLUGINS, reportAbsent, createRegistry); registered = true; } diff --git a/src/core/platform-plugin-absence.ts b/src/core/platform-plugin-absence.ts index add88b6fbc..2268c853bc 100644 --- a/src/core/platform-plugin-absence.ts +++ b/src/core/platform-plugin-absence.ts @@ -1,6 +1,6 @@ import type { Platform } from '@agent-device/kernel/device'; import type { AppError } from '@agent-device/kernel/errors'; -import { missingOptionalPlatformError } from '@agent-device/contracts/platform-module'; +import { missingOptionalPlatformError } from '@agent-device/contracts/plugin-installation'; import { readVersion } from '@agent-device/host-kit/version'; /** diff --git a/src/core/platform-plugin-registry-optional-family.test.ts b/src/core/platform-plugin-registry-optional-family.test.ts index 5390ee28db..a4e3b5ed63 100644 --- a/src/core/platform-plugin-registry-optional-family.test.ts +++ b/src/core/platform-plugin-registry-optional-family.test.ts @@ -1,3 +1,4 @@ +import { createPlatformModuleRegistry } from '@agent-device/contracts/platform-module'; import type { PlatformProviderRequestContext } from '@agent-device/contracts/platform-providers'; import type { PlatformPlugin } from '@agent-device/contracts/platform-plugin'; import assert from 'node:assert/strict'; @@ -18,6 +19,7 @@ vi.mock('./interactors/register-builtins.ts', async (importOriginal) => { registerPlatformPluginSet( original.BUILTIN_PLATFORM_PLUGINS.filter((plugin) => plugin.id !== 'vega'), reportAbsent, + createPlatformModuleRegistry, ); }, }; @@ -104,6 +106,7 @@ test('a duplicate plugin set is rejected before it replaces the composed set or registry.registerPlatformPluginSet( [pluginOwning('apple', ['apple']), pluginOwning('android', ['android'])], composedAbsence, + createPlatformModuleRegistry, ); assert.equal(registry.getPlugin('apple').id, 'apple'); assert.throws( @@ -120,8 +123,9 @@ test('a duplicate plugin set is rejected before it replaces the composed set or registry.registerPlatformPluginSet( [pluginOwning('web-and-apple', ['web', 'apple'])], rejectedAbsence, + createPlatformModuleRegistry, ), - /already registered for platform "apple"/, + /Duplicate platform family registration: apple/, ); // Neither the duplicate's platform nor its absence policy reached the registry. diff --git a/src/core/platform-plugin-registry-provider-routing.test.ts b/src/core/platform-plugin-registry-provider-routing.test.ts index 800a0b3657..ff9937ed8d 100644 --- a/src/core/platform-plugin-registry-provider-routing.test.ts +++ b/src/core/platform-plugin-registry-provider-routing.test.ts @@ -1,8 +1,11 @@ +import { + createPlatformModuleRegistry, + REQUIRED_PLATFORMS, +} from '@agent-device/contracts/platform-module'; import type { PlatformGatedProviderResolverKey, PlatformProviderRequestContext, } from '@agent-device/contracts/platform-providers'; -import { REQUIRED_PLATFORMS } from '@agent-device/contracts/platform-module'; import assert from 'node:assert/strict'; import { test } from 'vitest'; import { @@ -33,7 +36,7 @@ import { type PlatformProviderResolvers, } from '../platform-runtime.ts'; -registerBuiltinPlatformPlugins(missingPlatformPlugin); +registerBuiltinPlatformPlugins(missingPlatformPlugin, createPlatformModuleRegistry); const GATED_KEYS: PlatformGatedProviderResolverKey[] = [ 'androidAdbProvider', @@ -97,13 +100,17 @@ const SAMPLE_DEVICES: DeviceInfo[] = [ ...buildDeviceMatrix(), ]; -test('providers.platformGatedResolvers facet is byte-identical to the former hand gate', () => { +test('built-in provider facets retain the former routing', () => { for (const device of SAMPLE_DEVICES) { const facet = tryGetPlugin(device.platform)?.providers; const expected = gatedResolversByHand(device); for (const key of GATED_KEYS) { const applies = facet?.platformGatedResolvers.includes(key) ?? false; - assert.equal(applies, expected.has(key), `gate for ${key} on ${device.id}`); + assert.equal( + applies, + key !== 'webProvider' && expected.has(key), + `gate for ${key} on ${device.id}`, + ); } } }); @@ -122,7 +129,6 @@ test('every family carries the providers facet with the resolvers it owns', () = [...getPlugin('linux').providers!.platformGatedResolvers], ['linuxToolProvider'], ); - assert.deepEqual([...getPlugin('web').providers!.platformGatedResolvers], ['webProvider']); }); test('root provider composition invokes exactly the resolvers the former gate did', async () => { diff --git a/src/core/platform-plugin-registry.ts b/src/core/platform-plugin-registry.ts index 3049883e5a..44b094424a 100644 --- a/src/core/platform-plugin-registry.ts +++ b/src/core/platform-plugin-registry.ts @@ -1,5 +1,9 @@ import type { Platform } from '@agent-device/kernel/device'; import { AppError } from '@agent-device/kernel/errors'; +import type { + createPlatformModuleRegistry, + PlatformModuleRegistry, +} from '@agent-device/contracts/platform-module'; import type { PlatformPlugin } from '@agent-device/contracts/platform-plugin'; /** @@ -12,17 +16,9 @@ import type { PlatformPlugin } from '@agent-device/contracts/platform-plugin'; */ export type PlatformPluginAbsence = (family: Platform) => AppError; -const registry = new Map(); -let reportAbsence: PlatformPluginAbsence = unsupportedPlatform; +type InteractorRegistration = { family: Platform; plugin: PlatformPlugin }; -/** - * What an absent family is before a composition has registered a plugin set and named its absence - * outcome: unsupported, with no package inferred. A family with no installation row keeps this - * outcome after registration too. - */ -function unsupportedPlatform(family: Platform): AppError { - return new AppError('UNSUPPORTED_PLATFORM', `Unsupported platform: ${family}`); -} +let registry: PlatformModuleRegistry | undefined; /** * Composes `plugins` as this process's platform-plugin set and takes, once for the whole set, the @@ -38,20 +34,12 @@ function unsupportedPlatform(family: Platform): AppError { export function registerPlatformPluginSet( plugins: readonly PlatformPlugin[], reportAbsent: PlatformPluginAbsence, + createRegistry: typeof createPlatformModuleRegistry, ): void { - const claimed = new Map(); - for (const plugin of plugins) { - for (const platform of plugin.platforms) { - if (registry.has(platform) || claimed.has(platform)) { - throw new Error(`PlatformPlugin already registered for platform "${platform}"`); - } - claimed.set(platform, plugin); - } - } - reportAbsence = reportAbsent; - for (const [platform, plugin] of claimed) { - registry.set(platform, plugin); - } + const registrations = plugins.flatMap((plugin) => + plugin.platforms.map((family) => ({ family, plugin })), + ); + registry = createRegistry([...(registry?.modules ?? []), ...registrations], reportAbsent); } /** @@ -62,16 +50,15 @@ export function registerPlatformPluginSet( * outcome with no package inferred. */ export function getPlugin(platform: Platform): PlatformPlugin { - const plugin = registry.get(platform); - if (plugin) return plugin; - throw reportAbsence(platform); + if (!registry) throw new AppError('UNSUPPORTED_PLATFORM', `Unsupported platform: ${platform}`); + return registry.get(platform).plugin; } export function tryGetPlugin(platform: Platform): PlatformPlugin | undefined { - return registry.get(platform); + return registry?.tryGet(platform)?.plugin; } /** @internal Registered leaf platforms in insertion order, for parity gates. */ export function registeredPlatforms(): Platform[] { - return [...registry.keys()]; + return [...(registry?.families ?? [])]; } diff --git a/src/daemon-composition-credentials.test.ts b/src/daemon-composition-credentials.test.ts index f8156f903a..212093dc13 100644 --- a/src/daemon-composition-credentials.test.ts +++ b/src/daemon-composition-credentials.test.ts @@ -1,3 +1,4 @@ +import { absentPlatformRegistry } from './__tests__/test-utils/absent-platform-registry.ts'; import fs from 'node:fs'; import { expect, test, vi } from 'vitest'; import { startDaemonRuntime } from '@agent-device/daemon'; @@ -30,7 +31,8 @@ vi.mock('./platform-runtime.ts', () => ({ createPlatformDeviceInventoryGateways: () => ({}), })); -vi.mock('./provider-device-runtimes.ts', async () => ({ +vi.mock('./provider-device-runtimes.ts', async (importOriginal) => ({ + ...(await importOriginal()), createDaemonProviderRuntimeComposition: async () => ({ runtimes: [ { @@ -43,6 +45,7 @@ vi.mock('./provider-device-runtimes.ts', async () => ({ }, ], platformModules: [], + platformRegistry: absentPlatformRegistry, shutdown: async () => [], inventory: [ ...(await ( diff --git a/src/daemon-composition-web-cleanup.test.ts b/src/daemon-composition-web-cleanup.test.ts index aef948fda9..c23fb36a70 100644 --- a/src/daemon-composition-web-cleanup.test.ts +++ b/src/daemon-composition-web-cleanup.test.ts @@ -1,66 +1,15 @@ -import assert from 'node:assert/strict'; -import fs from 'node:fs'; -import { beforeEach, test, vi } from 'vitest'; -import { - createLiveTestHostEnvironment, - installFakeManagedAgentBrowser, - mkdtempForTestSync, -} from '@agent-device/test-kit'; - -const { cleanupManagedAgentBrowserOrphansMock } = vi.hoisted(() => ({ - cleanupManagedAgentBrowserOrphansMock: vi.fn(), -})); - -vi.mock('@agent-device/platform-web', async (importOriginal) => { - const actual = await importOriginal(); - return { - ...actual, - cleanupManagedAgentBrowserOrphans: cleanupManagedAgentBrowserOrphansMock, - }; -}); - +import { expect, test, vi } from 'vitest'; import { createDaemonStartupWebOrphanCleanup } from './daemon-composition.ts'; - -const cleanupWebBrowserOrphansForDaemonStartup = createDaemonStartupWebOrphanCleanup( - createLiveTestHostEnvironment(), -); - -const mockCleanupManagedAgentBrowserOrphans = vi.mocked(cleanupManagedAgentBrowserOrphansMock); - -beforeEach(() => { - mockCleanupManagedAgentBrowserOrphans.mockReset(); -}); - -test('daemon-startup web cleanup passes open web sessions to the reaper', async () => { - const stateDir = mkdtempForTestSync('agent-device-web-daemon-cleanup-'); - try { - await installFakeManagedAgentBrowser(stateDir); - await cleanupWebBrowserOrphansForDaemonStartup({ - stateDir, - openWebSessionNames: ['web-session'], - }); - - assert.equal(mockCleanupManagedAgentBrowserOrphans.mock.calls.length, 1); - assert.equal(mockCleanupManagedAgentBrowserOrphans.mock.calls[0]?.[1], 'daemon-startup'); - assert.deepEqual(mockCleanupManagedAgentBrowserOrphans.mock.calls[0]?.[2], { - env: process.env, - openWebSessionNames: ['web-session'], - }); - } finally { - fs.rmSync(stateDir, { recursive: true, force: true }); - } -}); - -test('daemon-startup web cleanup does not run when the managed backend is absent', async () => { - const stateDir = mkdtempForTestSync('agent-device-web-daemon-cleanup-'); - try { - await cleanupWebBrowserOrphansForDaemonStartup({ - stateDir, - openWebSessionNames: [], - }); - - assert.equal(mockCleanupManagedAgentBrowserOrphans.mock.calls.length, 0); - } finally { - fs.rmSync(stateDir, { recursive: true, force: true }); - } +import { webSelectionFixture } from './platform-runtime-web-provider.fixtures.ts'; + +test('daemon startup passes open web sessions to the selected platform cleanup', async () => { + const active = webSelectionFixture().get(); + const cleanupOrphans = vi.fn(async (_sessions: readonly string[]) => {}); + const registration = { ...active, operations: { ...active.operations, cleanupOrphans } }; + const cleanup = createDaemonStartupWebOrphanCleanup({ + active: registration, + get: () => registration, + }); + await cleanup({ stateDir: '/fixture-state', openWebSessionNames: ['web-session'] }); + expect(cleanupOrphans).toHaveBeenCalledExactlyOnceWith(['web-session']); }); diff --git a/src/daemon-composition.test.ts b/src/daemon-composition.test.ts index 9f66551bf0..9fb0592877 100644 --- a/src/daemon-composition.test.ts +++ b/src/daemon-composition.test.ts @@ -1,3 +1,4 @@ +import { absentPlatformRegistry } from './__tests__/test-utils/absent-platform-registry.ts'; import { afterEach, expect, test, vi } from 'vitest'; import type { DeviceInfo } from '@agent-device/kernel/device'; import type { ProviderDeviceRuntime } from '@agent-device/contracts/device'; @@ -41,10 +42,12 @@ vi.mock('./platform-runtime.ts', () => ({ createPlatformDeviceInventoryGateways: ports.inventoryGateways, })); -vi.mock('./provider-device-runtimes.ts', () => ({ +vi.mock('./provider-device-runtimes.ts', async (importOriginal) => ({ + ...(await importOriginal()), createDaemonProviderRuntimeComposition: async () => ({ runtimes: [], platformModules: [], + platformRegistry: absentPlatformRegistry, shutdown: ports.shutdownProviders, inventory: [], resolveReplayBackend: async () => { diff --git a/src/daemon-composition.ts b/src/daemon-composition.ts index 69130c6e94..fee0a8613f 100644 --- a/src/daemon-composition.ts +++ b/src/daemon-composition.ts @@ -1,3 +1,4 @@ +import { missingPlatformPlugin } from './core/platform-plugin-absence.ts'; // The daemon runtime's dependency construction, extracted from `packages/daemon/src/server/http/daemon-runtime.ts` // so the operational server owns sequencing and this module owns naming runtimes (ADR 0019). // Everything here that names a platform runtime, a provider runtime, an interactor, host @@ -20,9 +21,11 @@ import { import { createDaemonProviderRuntimeComposition, createEmbeddedProviderRuntimeComposition, + selectWebPlatform, } from './provider-device-runtimes.ts'; import { readDaemonProviderCredentials } from './provider-credential-fingerprint.ts'; -import { readVersion } from '@agent-device/host-kit/version'; +import { createPlatformPluginHost } from './platform-runtime/plugin-host.ts'; +import type { WebPlatformSelection } from '@agent-device/contracts/platform-plugin'; import { getInteractor } from './core/interactors.ts'; import { androidObservation, @@ -41,7 +44,6 @@ import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; import type { AgentDeviceRuntimeConfig } from '@agent-device/contracts/runtime-contract'; import type { PluginCandidate } from '@agent-device/plugins/registry'; import type { DeviceInfo } from '@agent-device/kernel/device'; -import type { HostEnvironment } from '@agent-device/kernel/source-value'; import type { RunnerContext } from '@agent-device/contracts/interactor-types'; import type { ComposeDaemonRuntimeDeps, DaemonRuntimeDeps } from '@agent-device/daemon'; @@ -51,7 +53,7 @@ import type { ComposeDaemonRuntimeDeps, DaemonRuntimeDeps } from '@agent-device/ * refuses is a diagnostic, not a reason to keep the next daemon from serving. */ export function createDaemonStartupWebOrphanCleanup( - host: HostEnvironment, + web?: WebPlatformSelection, ): (params: { stateDir: string; openWebSessionNames: readonly string[]; @@ -59,7 +61,7 @@ export function createDaemonStartupWebOrphanCleanup( }) => Promise { return async (params) => { try { - await createPlatformDaemonLifecycleOwners(host).cleanupManagedWebOrphans(params); + await createPlatformDaemonLifecycleOwners(web).cleanupManagedWebOrphans(params); } catch (error) { emitDiagnostic({ level: 'warn', @@ -112,11 +114,14 @@ export async function composeDaemonRuntimeDeps( sessionsDir, resolveSessionDir, }); - const hostDiagnostics = createHostDiagnostics(host); + const platformHost = createPlatformPluginHost(host, baseDir, { + ownedProcessRecords, + openWebSessionNames, + }); const providerComposition = providerCandidates === undefined - ? await createDaemonProviderRuntimeComposition(host) - : await createEmbeddedProviderRuntimeComposition(host, providerCandidates); + ? await createDaemonProviderRuntimeComposition(host, platformHost) + : await createEmbeddedProviderRuntimeComposition(host, providerCandidates, platformHost); // The registry has set up every plugin. Until this function returns, nothing else owns its // cleanup, so any later failure closes it here; success transfers ownership to the daemon. try { @@ -127,12 +132,12 @@ export async function composeDaemonRuntimeDeps( providerComposition.resolveReplayExecution, ); const providerDeviceRuntimes = [...providerComposition.runtimes]; - // The typed absent-family outcome names the plugin release this core can install, so the - // composition that knows its own version passes it to the registries it composes. - const coreVersion = readVersion(); + const web = selectWebPlatform(providerComposition.platformRegistry); + const hostDiagnostics = createHostDiagnostics(host, web); const deviceRuntimeGateway = createPlatformRuntimeGateway({ host, - coreVersion, + web, + reportAbsent: missingPlatformPlugin, assertShutdownAllowed, providerRuntimes: providerDeviceRuntimes, providerModules: providerComposition.platformModules, @@ -148,17 +153,13 @@ export async function composeDaemonRuntimeDeps( appleRunnerScreenRecordingTransport: providerRuntimeProviders.appleRunnerScreenRecordingTransport, }, - defaultWebProvider: { - host, - stateDir: baseDir, - openWebSessionNames, - ownedProcessRecords, - }, + web, }); const deviceInventoryGateways = await createPlatformDeviceInventoryGateways( host, - coreVersion, providerRuntimeProviders.deviceInventorySource, + web, + missingPlatformPlugin, ); // Root composition of the platform-services port and the owner-scoped claim-recovery gateway. // platform-runtime.ts is already static in this module, so the deferred imports keep these thin @@ -176,7 +177,7 @@ export async function composeDaemonRuntimeDeps( return Object.freeze({ ownedProcessRecords, hostDiagnostics, - ownerLifecycle: createPlatformDaemonLifecycleOwners(host), + ownerLifecycle: createPlatformDaemonLifecycleOwners(web), shutdownProviderRuntimes: providerComposition.shutdown, pluginInventory: providerComposition.inventory, resolveReplayBackend: providerComposition.resolveReplayBackend, @@ -186,16 +187,16 @@ export async function composeDaemonRuntimeDeps( recoverExpiredLease: providerRuntimeProviders.recoverExpiredLease, recoverableProviderIds: providerRuntimeProviders.recoverableProviderIds, deviceRuntimeGateway, - platformResourceCleanup: createPlatformResourceCleanup(host, ownedProcessRecords), + platformResourceCleanup: createPlatformResourceCleanup(host, web), claimRecoveryGateway: createClaimRecoveryGatewayFor(host), interactorResolution: Object.freeze({ resolve: async (device: DeviceInfo, runnerContext: RunnerContext) => - await getInteractor(device, runnerContext, host), + await getInteractor(device, runnerContext, host, web), }), providerDeviceAdmission: Object.freeze({ isActive: (device: DeviceInfo) => isActiveProviderDevice(device), }), - cleanupManagedWebOrphans: createDaemonStartupWebOrphanCleanup(host), + cleanupManagedWebOrphans: createDaemonStartupWebOrphanCleanup(web), requestRouter: Object.freeze({ requestPlatformProviders, deviceInventoryGateways, diff --git a/src/daemon-runtime-limrun-public-http.test.ts b/src/daemon-runtime-limrun-public-http.test.ts index b0f75306f7..f93daa51c1 100644 --- a/src/daemon-runtime-limrun-public-http.test.ts +++ b/src/daemon-runtime-limrun-public-http.test.ts @@ -1,3 +1,4 @@ +import { absentPlatformRegistry } from './__tests__/test-utils/absent-platform-registry.ts'; import fs from 'node:fs'; import assert from 'node:assert/strict'; import { test, vi } from 'vitest'; @@ -11,6 +12,7 @@ import { } from '@agent-device/contracts/daemon-http'; import { createDaemonRuntimeDeps } from './daemon-composition.ts'; import { limrunTestDependencies } from './platform-runtime-gateway.fixtures.ts'; +import type { ProviderRuntimeComposition } from './provider-device-runtimes.ts'; const limrunIo = vi.hoisted(() => ({ listAssets: vi.fn(), @@ -23,12 +25,15 @@ const rootPorts = vi.hoisted(() => { finalizeDaemonShutdown: vi.fn(async () => []), }; return { - providerComposition: vi.fn(async () => ({ - runtimes: [] as unknown[], - platformModules: [] as unknown[], - inventory: [] as unknown[], - shutdown: async () => [], - })), + providerComposition: + vi.fn< + () => Promise< + Pick< + ProviderRuntimeComposition, + 'runtimes' | 'platformModules' | 'platformRegistry' | 'inventory' | 'shutdown' + > + > + >(), createPlatformRuntimeGateway: vi.fn(() => ({ applicationLifecycle, inspectFacts: async () => { @@ -84,6 +89,7 @@ test('public HTTP rejects Limrun uploaded-app listing and allocation before prov rootPorts.providerComposition.mockResolvedValue({ runtimes: [limrun], platformModules: [], + platformRegistry: absentPlatformRegistry, inventory: [], shutdown: async () => { await limrun.shutdown(); diff --git a/src/host.test.ts b/src/host.test.ts index 4d37cd354a..ec6e7c3d4c 100644 --- a/src/host.test.ts +++ b/src/host.test.ts @@ -12,6 +12,7 @@ import { readProcessStartTime } from '@agent-device/host-kit/process'; import { createTestHostEnvironment, mkdtempForTestSync } from '@agent-device/test-kit'; import type { PluginCandidate } from '@agent-device/plugins/registry'; import type { AgentDevicePlugin } from './sdk/plugins.ts'; +import { absentPlatformRegistry } from './__tests__/test-utils/absent-platform-registry.ts'; import { builtinPluginInventory } from './__tests__/test-utils/builtin-plugin-inventory.ts'; import { stopRecordedDaemon } from '@agent-device/daemon-client'; import { startAgentDevice } from './host.ts'; @@ -78,6 +79,7 @@ vi.mock('./provider-device-runtimes.ts', async (importOriginal) => { return { runtimes: [], platformModules: [], + platformRegistry: absentPlatformRegistry, shutdown: async () => [], inventory: [ ...(await ( diff --git a/src/platform-runtime-android-adb-binding.test.ts b/src/platform-runtime-android-adb-binding.test.ts index 55efa081f7..7e57cb1772 100644 --- a/src/platform-runtime-android-adb-binding.test.ts +++ b/src/platform-runtime-android-adb-binding.test.ts @@ -1,4 +1,3 @@ -import { readVersion } from '@agent-device/host-kit/version'; import type { DeviceInfo } from '@agent-device/kernel/device'; import { expect, test, vi } from 'vitest'; @@ -54,7 +53,6 @@ const device: DeviceInfo = { test('the composed gateway lists Android apps from inside the platform package', async () => { const gateway = createPlatformRuntimeGateway({ - coreVersion: readVersion(), host: createLiveTestHostEnvironment(), ...sessionArtifacts, }); @@ -83,7 +81,6 @@ test('the composed gateway lists Android apps from inside the platform package', test('the composed gateway reads Android app state from inside the platform package', async () => { const gateway = createPlatformRuntimeGateway({ - coreVersion: readVersion(), host: createLiveTestHostEnvironment(), ...sessionArtifacts, }); diff --git a/src/platform-runtime-apple-close-composition.test.ts b/src/platform-runtime-apple-close-composition.test.ts index c6dc3e5ec9..531d26f9b2 100644 --- a/src/platform-runtime-apple-close-composition.test.ts +++ b/src/platform-runtime-apple-close-composition.test.ts @@ -1,4 +1,3 @@ -import { readVersion } from '@agent-device/host-kit/version'; import { expect, test, vi } from 'vitest'; import { bindTestCommandHost, @@ -50,7 +49,6 @@ test('the composed close awaits the real runner release before dismissing alerts booted: true, }; const gateway = createPlatformRuntimeGateway({ - coreVersion: readVersion(), host, sessionsDir: root, resolveSessionArtifacts: (sessionId) => ({ diff --git a/src/platform-runtime-audio-probe-host.test.ts b/src/platform-runtime-audio-probe-host.test.ts index 18852a6a3f..c1a23c2d5c 100644 --- a/src/platform-runtime-audio-probe-host.test.ts +++ b/src/platform-runtime-audio-probe-host.test.ts @@ -1,10 +1,9 @@ import { expect, test } from 'vitest'; -import { withWebProvider } from '@agent-device/platform-web'; import { createTestHostEnvironment } from '@agent-device/test-kit'; import { emptyAudioProbeResult } from '@agent-device/contracts/audio-probe-result'; import type { AudioProbeQueryInput } from '@agent-device/contracts/audio-probe-runtime'; import { createAudioProbeRuntimeHost } from './platform-runtime-audio-probe-host.ts'; -import { makeWebProvider } from './platform-runtime-web-provider.fixtures.ts'; +import { makeWebProvider, webSelectionFixture } from './platform-runtime-web-provider.fixtures.ts'; const web = { platform: 'web' as const, @@ -15,13 +14,18 @@ const web = { booted: true, }; +const webPlugin = webSelectionFixture(); + test('never falls back to the default browser session for a web audio probe', async () => { - const { web: webAudio } = createAudioProbeRuntimeHost({ host: createTestHostEnvironment() }); + const { web: webAudio } = createAudioProbeRuntimeHost({ + host: createTestHostEnvironment(), + web: webPlugin, + }); expect(await webAudio.resolve(web)).toBeUndefined(); const actions: string[] = []; const query: AudioProbeQueryInput = { action: 'status', durationMs: 1000, bucketMs: 100 }; - await withWebProvider( + await webPlugin.get().withRequestProvider( makeWebProvider({ probeAudio: async (options) => { actions.push(options.action); diff --git a/src/platform-runtime-audio-probe-host.ts b/src/platform-runtime-audio-probe-host.ts index a5670f74d2..0b53e69ba3 100644 --- a/src/platform-runtime-audio-probe-host.ts +++ b/src/platform-runtime-audio-probe-host.ts @@ -1,3 +1,4 @@ +import type { WebPlatformSelection } from '@agent-device/contracts/platform-plugin'; import { isIosFamily, type DeviceInfo } from '@agent-device/kernel/device'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; import type { @@ -23,6 +24,7 @@ import { export function createAudioProbeRuntimeHost(options: { ownedProcesses?: OwnedProcessRecordWriter; host: HostEnvironment; + web?: WebPlatformSelection; }): AudioProbeRuntimeHost { const host = options.host; const ownedProcesses: OwnedProcessRecordWriter = @@ -63,8 +65,7 @@ export function createAudioProbeRuntimeHost(options: { web: Object.freeze({ resolve: async (device: DeviceInfo): Promise => { if (device.platform !== 'web') return undefined; - const { resolveRequestScopedWebProvider } = await import('@agent-device/platform-web'); - const provider = await resolveRequestScopedWebProvider(); + const provider = await options.web?.get().operations.resolveRequestProvider(); const probeAudio = provider?.probeAudio?.bind(provider); if (!probeAudio) return undefined; return Object.freeze({ diff --git a/src/platform-runtime-claim-recovery.ts b/src/platform-runtime-claim-recovery.ts index 3d9329bb05..055c4556a5 100644 --- a/src/platform-runtime-claim-recovery.ts +++ b/src/platform-runtime-claim-recovery.ts @@ -1,3 +1,4 @@ +import { missingPlatformPlugin } from './core/platform-plugin-absence.ts'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; import { createOwnerScopedDeviceClaimReconciler, @@ -11,7 +12,6 @@ import { type DeviceClaimSelectors, type DeviceClaimStaleReleaseOutcome, } from '@agent-device/daemon-contracts/device-claims'; -import { readVersion } from '@agent-device/host-kit/version'; import { createPlatformRuntimeGateway } from './platform-runtime.ts'; /** @@ -27,9 +27,7 @@ export const createClaimRecoveryGatewayFor = (input) => createPlatformRuntimeGateway({ host, - // This composition names its own core version so an absent family's install hint points at - // the release this process runs (ADR 0034). - coreVersion: readVersion(), + reportAbsent: missingPlatformPlugin, sessionsDir: input.sessionsDir, ownedProcesses: input.ownedProcesses, resolveSessionArtifacts: input.resolveSessionArtifacts, diff --git a/src/platform-runtime-daemon-lifecycle.test.ts b/src/platform-runtime-daemon-lifecycle.test.ts index c79564be15..e016d5444c 100644 --- a/src/platform-runtime-daemon-lifecycle.test.ts +++ b/src/platform-runtime-daemon-lifecycle.test.ts @@ -2,11 +2,7 @@ import fs from 'node:fs'; import path from 'node:path'; import { afterEach, expect, test, vi } from 'vitest'; import type { ResourceDiagnostic } from '@agent-device/host-kit/diagnostics'; -import { - createLiveTestHostEnvironment, - mkdtempForTestSync, - withMockedPlatform, -} from '@agent-device/test-kit'; +import { mkdtempForTestSync, withMockedPlatform } from '@agent-device/test-kit'; const legacyRedirect = vi.hoisted(() => ({ xctestDeviceSetPath: '' })); @@ -26,9 +22,7 @@ vi.mock('@agent-device/platform-apple/runner-owner', async (importOriginal) => { import { createPlatformDaemonLifecycleOwners } from './platform-runtime-daemon-lifecycle.ts'; -const platformDaemonLifecycleOwners = createPlatformDaemonLifecycleOwners( - createLiveTestHostEnvironment(), -); +const platformDaemonLifecycleOwners = createPlatformDaemonLifecycleOwners(); const roots: string[] = []; diff --git a/src/platform-runtime-daemon-lifecycle.ts b/src/platform-runtime-daemon-lifecycle.ts index acd18ecc1b..fb34b23ebb 100644 --- a/src/platform-runtime-daemon-lifecycle.ts +++ b/src/platform-runtime-daemon-lifecycle.ts @@ -1,11 +1,10 @@ -import type { HostEnvironment } from '@agent-device/kernel/source-value'; +import type { WebPlatformSelection } from '@agent-device/contracts/platform-plugin'; import type { PlatformOwnerLifecycle } from '@agent-device/daemon'; import { configureAppleRunnerDeviceClaimAuthorityProbe, configureAppleRunnerLeaseOwnerStateDir, } from './platform-runtime-apple-runner-owner.ts'; import { - cleanupManagedWebRuntimeOrphans, resetAndroidSnapshotHelperRuntime, restoreLegacyXctestDeviceSetRedirectRuntime, } from './platform-runtime-resource-cleanup.ts'; @@ -16,7 +15,9 @@ import { * snapshot-helper and Web orphan cleanups, legacy app-log marker recovery, and the legacy * `XCTestDevices` restore); the daemon holds only the typed `PlatformOwnerLifecycle` contract. */ -export function createPlatformDaemonLifecycleOwners(host: HostEnvironment): PlatformOwnerLifecycle { +export function createPlatformDaemonLifecycleOwners( + web?: WebPlatformSelection, +): PlatformOwnerLifecycle { return Object.freeze({ configureForDaemonLock: async (input) => { await configureAppleRunnerLeaseOwnerStateDir(input.stateDir); @@ -33,7 +34,7 @@ export function createPlatformDaemonLifecycleOwners(host: HostEnvironment): Plat return await recoverLegacyAppLogMarkersAfterDaemonLock(sessionsDir); }, cleanupManagedWebOrphans: async (params) => { - await cleanupManagedWebRuntimeOrphans(params, host); + await web?.active?.operations.cleanupOrphans(params.openWebSessionNames); }, resetAndroidSnapshotHelper: async () => { await resetAndroidSnapshotHelperRuntime(); diff --git a/src/platform-runtime-device-inventory.test.ts b/src/platform-runtime-device-inventory.test.ts index 4823749f9a..238c08d2af 100644 --- a/src/platform-runtime-device-inventory.test.ts +++ b/src/platform-runtime-device-inventory.test.ts @@ -3,6 +3,7 @@ import { type InventoryPlatformModule, createPlatformModuleRegistry, } from '@agent-device/contracts/platform-module'; +import { missingOptionalPlatformError } from '@agent-device/contracts/plugin-installation'; import { testInventoryHost, testRequestScope, @@ -54,7 +55,9 @@ describe('production device inventory composition', () => { source(family === 'apple' ? [simulator('sim-a'), simulator('sim-b')] : []), })); const gateways = await attachAppleSelectionProbes({ - registry: createPlatformModuleRegistry(modules, CORE_VERSION), + registry: createPlatformModuleRegistry(modules, (family) => + missingOptionalPlatformError(family, CORE_VERSION), + ), loadHost: async () => testInventoryHost, env: {}, }); @@ -114,7 +117,9 @@ describe('production device inventory composition', () => { loadInventory: async () => source(family === 'apple' ? [mac] : []), })); const gateways = await attachAppleSelectionProbes({ - registry: createPlatformModuleRegistry(modules, CORE_VERSION), + registry: createPlatformModuleRegistry(modules, (family) => + missingOptionalPlatformError(family, CORE_VERSION), + ), loadHost: async () => testInventoryHost, env: { AGENT_DEVICE_MACOS_APP_BACKEND: backend }, }); diff --git a/src/platform-runtime-gateway-gesture-admission.test.ts b/src/platform-runtime-gateway-gesture-admission.test.ts index d35358b81f..707710c5fd 100644 --- a/src/platform-runtime-gateway-gesture-admission.test.ts +++ b/src/platform-runtime-gateway-gesture-admission.test.ts @@ -1,4 +1,4 @@ -import { readVersion } from '@agent-device/host-kit/version'; +import { webSelectionFixture } from './platform-runtime-web-provider.fixtures.ts'; import type { DeviceInfo } from '@agent-device/kernel/device'; import { expect, test } from 'vitest'; import { bindTestCommandHost, createLiveTestHostEnvironment } from '@agent-device/test-kit'; @@ -7,7 +7,7 @@ import { createPlatformRuntimeGateway } from './platform-runtime.ts'; bindTestCommandHost(); const gateway = createPlatformRuntimeGateway({ - coreVersion: readVersion(), + web: webSelectionFixture(), host: createLiveTestHostEnvironment(), resolveSessionArtifacts: () => ({ outputPath: '/sessions/gesture-admission/app.log', diff --git a/src/platform-runtime-gateway-recording.test.ts b/src/platform-runtime-gateway-recording.test.ts index 211d5f592a..3e4f612476 100644 --- a/src/platform-runtime-gateway-recording.test.ts +++ b/src/platform-runtime-gateway-recording.test.ts @@ -1,4 +1,3 @@ -import { readVersion } from '@agent-device/host-kit/version'; import path from 'node:path'; import { expect, test } from 'vitest'; import type { DeviceInfo } from '@agent-device/kernel/device'; @@ -21,7 +20,6 @@ test.each(unsupportedRecordingDevices)( async (device) => { const sessionsDir = mkdtempForTestSync('platform-runtime-recording-'); const gateway = createPlatformRuntimeGateway({ - coreVersion: readVersion(), host: createLiveTestHostEnvironment(), sessionsDir, resolveSessionArtifacts: (sessionId) => ({ diff --git a/src/platform-runtime-gateway.fixtures.ts b/src/platform-runtime-gateway.fixtures.ts index 2ddb0e6fca..3c3763c3ce 100644 --- a/src/platform-runtime-gateway.fixtures.ts +++ b/src/platform-runtime-gateway.fixtures.ts @@ -24,7 +24,7 @@ import { createUnavailableRuntimeFactsForTest, unavailableDeploymentSnapshotAndShutdownOperationFacts, } from '@agent-device/test-kit'; -import { readVersion } from '@agent-device/host-kit/version'; +import { missingPlatformPlugin } from './core/platform-plugin-absence.ts'; import { createComposedPlatformRuntimeGateway, type PlatformRuntimeProviderRegistration, @@ -52,7 +52,7 @@ export function runtimeModuleRegistryFixture(modules: readonly PlatformRuntimeMo }) as PlatformRuntimeModule, ), ], - readVersion(), + missingPlatformPlugin, ); } diff --git a/src/platform-runtime-host-diagnostics.ts b/src/platform-runtime-host-diagnostics.ts index 60426029f8..516844929f 100644 --- a/src/platform-runtime-host-diagnostics.ts +++ b/src/platform-runtime-host-diagnostics.ts @@ -1,3 +1,4 @@ +import type { WebPlatformSelection } from '@agent-device/contracts/platform-plugin'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; import type { DeviceInfo, PlatformSelector } from '@agent-device/kernel/device'; import type { DoctorCheck } from '@agent-device/contracts/observability'; @@ -12,7 +13,10 @@ import { loadAndroidMechanics } from './platform-runtime-android-mechanics.ts'; * execution). Families load lazily: a probe module is imported only when its family's method * actually runs, matching the platform registry's implementation-laziness. */ -export function createHostDiagnostics(host: HostEnvironment): HostDiagnostics { +export function createHostDiagnostics( + host: HostEnvironment, + web?: WebPlatformSelection, +): HostDiagnostics { const { env } = host; return Object.freeze({ toolchainCheck: async ( @@ -46,8 +50,8 @@ export function createHostDiagnostics(host: HostEnvironment): HostDiagnostics { return await androidDeviceChecks(device, context); }, ambientChecks: async (context: HostDiagnosticsContext): Promise => { - const { webBrowserLifecycleCheck } = await import('@agent-device/platform-web'); - return [await webBrowserLifecycleCheck(context.stateDir, host)]; + if (!web?.active) return []; + return [await web.active.operations.browserLifecycleCheck(context.stateDir)]; }, warmupCheck: async ( device: DeviceInfo, diff --git a/src/platform-runtime-host.test.ts b/src/platform-runtime-host.test.ts index 56ae089a15..e6226121eb 100644 --- a/src/platform-runtime-host.test.ts +++ b/src/platform-runtime-host.test.ts @@ -1,4 +1,3 @@ -import { readVersion } from '@agent-device/host-kit/version'; import { expect, test, vi } from 'vitest'; import { chmodSync, mkdirSync, writeFileSync } from 'node:fs'; import path from 'node:path'; @@ -116,13 +115,10 @@ test('a host env with no home still inventories every family through the gateway // the gateways load the one host for all of them. Reverting the refusal makes both assertions // below red: the Apple host-Mac route fails with COMMAND_FAILED, and Vega fails with // COMMAND_FAILED instead of the honest TOOL_MISSING its PATH-only answer yields. - const gateways = await createPlatformDeviceInventoryGateways( - { - env: {}, - cwd: process.cwd(), - }, - readVersion(), - ); + const gateways = await createPlatformDeviceInventoryGateways({ + env: {}, + cwd: process.cwd(), + }); const scope: PlatformRequestScope = Object.freeze({ signal: new AbortController().signal, diagnostics: Object.freeze({ emit: () => {} }), diff --git a/src/platform-runtime-local-application-interactors.ts b/src/platform-runtime-local-application-interactors.ts index 46c56c718f..b58e1ef994 100644 --- a/src/platform-runtime-local-application-interactors.ts +++ b/src/platform-runtime-local-application-interactors.ts @@ -1,3 +1,4 @@ +import type { WebPlatformSelection } from '@agent-device/contracts/platform-plugin'; import type { LocalApplicationInteractorHost } from '@agent-device/contracts/application-lifecycle-runtime'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; import type { DeviceInfo } from '@agent-device/kernel/device'; @@ -6,11 +7,12 @@ import type { RunnerContext } from '@agent-device/contracts/interactor-types'; /** Lazy local interactor construction; package bindings decide when it is needed. */ export function createLocalApplicationInteractorHost( host: HostEnvironment, + web?: WebPlatformSelection, ): LocalApplicationInteractorHost { return Object.freeze({ resolve: async (device: DeviceInfo, runner: RunnerContext) => { const { getLocalInteractor } = await import('./core/interactors.ts'); - return await getLocalInteractor(device, runner, host); + return await getLocalInteractor(device, runner, host, web); }, }); } diff --git a/src/platform-runtime-managed-web-backend.ts b/src/platform-runtime-managed-web-backend.ts index ab4bf31af5..7b71c32b6e 100644 --- a/src/platform-runtime-managed-web-backend.ts +++ b/src/platform-runtime-managed-web-backend.ts @@ -1,16 +1,62 @@ import type { ManagedWebBackend } from '@agent-device/contracts/managed-web-backend'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; +import type { PlatformSetup } from '@agent-device/plugins/contract'; -/** Root composition for the managed browser host tool used by the CLI web command. */ export function createManagedWebBackend(host: HostEnvironment): ManagedWebBackend { return Object.freeze({ - setup: async (options) => { - const { setupManagedAgentBrowser } = await import('@agent-device/platform-web'); - return await setupManagedAgentBrowser({ ...options, host }); - }, - doctor: async (options) => { - const { doctorManagedAgentBrowser } = await import('@agent-device/platform-web'); - return await doctorManagedAgentBrowser({ ...options, host }); - }, + setup: (options) => + withWebPlatform(host, options.stateDir, (web) => web.operations.setup(options)), + doctor: (options) => + withWebPlatform(host, options.stateDir, (web) => web.operations.doctor(options)), }); } + +async function withWebPlatform( + host: HostEnvironment, + stateDir: string | undefined, + run: (web: PlatformSetup<'web'>) => Promise, +): Promise { + const [ + { resolveProviderPlugins, startProviderRegistry }, + { storePluginCandidates, createPluginSelectionGuard }, + { getOptionalPlatformPluginDeclaration }, + { createPlatformPluginHost }, + { resolveDaemonPaths }, + { selectWebPlatform }, + { PROVIDER_PLUGIN_POLICY }, + ] = await Promise.all([ + import('@agent-device/plugins/registry'), + import('@agent-device/plugins/store'), + import('@agent-device/contracts/plugin-installation'), + import('./platform-runtime/plugin-host.ts'), + import('@agent-device/daemon-contracts/daemon-resolution'), + import('./provider-device-runtimes.ts'), + import('./provider-plugin-policy.ts'), + ]); + const packageName = getOptionalPlatformPluginDeclaration('web')?.package; + const installed = await storePluginCandidates(host.env); + const candidates = installed.filter( + (candidate) => + candidate.package === packageName || + candidate.declaredClaims?.some(({ kind, id }) => kind === 'platform' && id === 'web'), + ); + const resolved = await resolveProviderPlugins(candidates); + const registry = await startProviderRegistry( + resolved, + host, + { + ...PROVIDER_PLUGIN_POLICY, + assertSelectionCurrent: createPluginSelectionGuard(installed, host.env), + platformHost: createPlatformPluginHost( + host, + resolveDaemonPaths(stateDir, { env: host.env, cwd: host.cwd }).baseDir, + ), + }, + 'platforms', + ); + try { + return await run(selectWebPlatform(registry).get()); + } finally { + await registry.close(); + } +} diff --git a/src/platform-runtime-network-web-transport.test.ts b/src/platform-runtime-network-web-transport.test.ts index dcdd730337..3211bcbbde 100644 --- a/src/platform-runtime-network-web-transport.test.ts +++ b/src/platform-runtime-network-web-transport.test.ts @@ -1,8 +1,7 @@ import { expect, test } from 'vitest'; -import { withWebProvider } from '@agent-device/platform-web'; import type { NetworkProviderDump } from '@agent-device/contracts/network-runtime'; import { resolveWebNetworkTransport } from './platform-runtime-network-web-transport.ts'; -import { makeWebProvider } from './platform-runtime-web-provider.fixtures.ts'; +import { makeWebProvider, webSelectionFixture } from './platform-runtime-web-provider.fixtures.ts'; const web = { platform: 'web' as const, @@ -13,14 +12,16 @@ const web = { booted: true, }; +const webPlugin = webSelectionFixture(); + test('never falls back to the default browser session for a network dump', async () => { - const unscoped = await resolveWebNetworkTransport(web); + const unscoped = await resolveWebNetworkTransport(web, webPlugin); expect(unscoped.mode).toBe('local'); expect('dump' in unscoped && unscoped.dump).toBeFalsy(); const limits: Array = []; const dumpInput: Parameters[0] = { maxEntries: 7, include: 'summary' }; - await withWebProvider( + await webPlugin.get().withRequestProvider( makeWebProvider({ dumpNetwork: async (options) => { limits.push(options?.limit); @@ -28,7 +29,7 @@ test('never falls back to the default browser session for a network dump', async }, }), async () => { - const scoped = await resolveWebNetworkTransport(web); + const scoped = await resolveWebNetworkTransport(web, webPlugin); if (scoped.mode !== 'transport-composed' || !scoped.dump) { throw new Error('missing scoped web network transport'); } diff --git a/src/platform-runtime-network-web-transport.ts b/src/platform-runtime-network-web-transport.ts index d685dd36d1..d6fd026e55 100644 --- a/src/platform-runtime-network-web-transport.ts +++ b/src/platform-runtime-network-web-transport.ts @@ -1,10 +1,13 @@ +import type { WebPlatformSelection } from '@agent-device/contracts/platform-plugin'; import type { NetworkTransport } from '@agent-device/contracts/network-runtime'; import type { DeviceInfo } from '@agent-device/kernel/device'; -export async function resolveWebNetworkTransport(device: DeviceInfo): Promise { +export async function resolveWebNetworkTransport( + device: DeviceInfo, + web?: WebPlatformSelection, +): Promise { if (device.platform !== 'web') return Object.freeze({ mode: 'local' }); - const { resolveRequestScopedWebProvider } = await import('@agent-device/platform-web'); - const provider = await resolveRequestScopedWebProvider(); + const provider = await web?.get().operations.resolveRequestProvider(); if (!provider) return Object.freeze({ mode: 'local' }); const dumpNetwork = provider.dumpNetwork; if (!dumpNetwork) return Object.freeze({ mode: 'transport-composed' }); diff --git a/src/platform-runtime-operation-host.ts b/src/platform-runtime-operation-host.ts index cd8a0adb88..cb5b1e4f6f 100644 --- a/src/platform-runtime-operation-host.ts +++ b/src/platform-runtime-operation-host.ts @@ -1,3 +1,4 @@ +import type { WebPlatformSelection } from '@agent-device/contracts/platform-plugin'; import type { EnvMap, HostEnvironment } from '@agent-device/kernel/source-value'; import type { AppLogSessionArtifacts } from '@agent-device/contracts/app-log-runtime'; import type { DeviceShutdownRuntimeLoaders } from '@agent-device/contracts/device-shutdown-runtime'; @@ -52,6 +53,7 @@ export async function loadMacOsSurfaceSnapshot( export function createPlatformRuntimeHost(options: { host: HostEnvironment; + web?: WebPlatformSelection; sessionsDir: string; resolveSessionArtifacts(sessionId: string): AppLogSessionArtifacts; shutdownLoaders: DeviceShutdownRuntimeLoaders; @@ -72,7 +74,7 @@ export function createPlatformRuntimeHost(options: { if (device.platform !== 'web') return Object.freeze({ mode: 'local' as const }); const { resolveWebNetworkTransport } = await import('./platform-runtime-network-web-transport.ts'); - return await resolveWebNetworkTransport(device); + return await resolveWebNetworkTransport(device, options.web); }, }); const appleApplications = createAppleApplicationTools(env); @@ -124,11 +126,16 @@ export function createPlatformRuntimeHost(options: { screenRecording: createScreenRecordingRuntimeHost({ ownedProcesses: options.ownedProcesses, host, + web: options.web, + }), + audioProbe: createAudioProbeRuntimeHost({ + ownedProcesses: options.ownedProcesses, + host, + web: options.web, }), - audioProbe: createAudioProbeRuntimeHost({ ownedProcesses: options.ownedProcesses, host }), perf: createPerfRuntimeHost(), snapshot: options.snapshot, - localInteractors: createLocalApplicationInteractorHost(host), + localInteractors: createLocalApplicationInteractorHost(host, options.web), appleApplications, androidApplications, applicationResources: createApplicationResourceLifecycle({ diff --git a/src/platform-runtime-perf-host.test.ts b/src/platform-runtime-perf-host.test.ts index 2834110b47..c307d38d04 100644 --- a/src/platform-runtime-perf-host.test.ts +++ b/src/platform-runtime-perf-host.test.ts @@ -1,4 +1,3 @@ -import { readVersion } from '@agent-device/host-kit/version'; import type { DeviceInfo } from '@agent-device/kernel/device'; import { bindTestCommandHost, @@ -52,7 +51,6 @@ test('the composed Android perf operation reports an unavailable ADB memory samp adb.calls.length = 0; const sessionsDir = mkdtempForTestSync('platform-runtime-perf-host-'); const gateway = createPlatformRuntimeGateway({ - coreVersion: readVersion(), host: createLiveTestHostEnvironment(), sessionsDir, resolveSessionArtifacts: (sessionId) => ({ diff --git a/src/platform-runtime-provider-scope.test.ts b/src/platform-runtime-provider-scope.test.ts index fcb273c735..a95cc1dff7 100644 --- a/src/platform-runtime-provider-scope.test.ts +++ b/src/platform-runtime-provider-scope.test.ts @@ -1,3 +1,4 @@ +import { webSelectionFixture } from './platform-runtime-web-provider.fixtures.ts'; import assert from 'node:assert/strict'; import { test } from 'vitest'; import type { @@ -13,7 +14,7 @@ import { import { createLocalAppleToolProvider, runXcrun } from '@agent-device/platform-apple/tool-provider'; import { buildSimctlArgsForDevice } from '@agent-device/platform-apple/simctl'; import type { AndroidAdbExecutor } from '@agent-device/platform-android/mechanics'; -import { resolveRequestScopedWebProvider, type WebProvider } from '@agent-device/platform-web'; +import type { WebProvider } from '@agent-device/contracts/web-provider'; import { resolveAppleRunnerScreenRecordingTransport, type AppleRunnerScreenRecordingTransport, @@ -23,6 +24,9 @@ import { type PlatformProviderResolvers, } from './platform-runtime.ts'; +const web = webSelectionFixture(); +const resolveRequestScopedWebProvider = web.get().operations.resolveRequestProvider; + const OTHER_IOS_SIMULATOR = { platform: 'apple', id: 'sim-2', @@ -281,7 +285,7 @@ async function withRequestPlatformProviderScope( providers: PlatformProviderResolvers, task: (scope: RequestPlatformProviderScope) => Promise, ): Promise { - const scoped = createRequestPlatformProviders({ providers }); + const scoped = createRequestPlatformProviders({ providers, web }); return await scoped.run(providerContext, task); } diff --git a/src/platform-runtime-resource-cleanup.test.ts b/src/platform-runtime-resource-cleanup.test.ts index 97e5ff21ad..50e82d9f07 100644 --- a/src/platform-runtime-resource-cleanup.test.ts +++ b/src/platform-runtime-resource-cleanup.test.ts @@ -17,7 +17,7 @@ import { } from '@agent-device/test-kit'; import { createPlatformResourceCleanup } from './platform-runtime-resource-cleanup.ts'; -const platformResourceCleanup = createPlatformResourceCleanup(createLiveTestHostEnvironment()); +import { webSelectionFixture } from './platform-runtime-web-provider.fixtures.ts'; bindTestCommandHost(); @@ -30,6 +30,11 @@ afterEach(() => { async function closeBrowser(device: DeviceInfo): Promise { const stateDir = mkdtempForTestSync('agent-device-resource-cleanup-web-close-'); await installFakeManagedAgentBrowser(stateDir); + const host = createLiveTestHostEnvironment(); + const platformResourceCleanup = createPlatformResourceCleanup( + host, + webSelectionFixture(host, stateDir), + ); await platformResourceCleanup.closeManagedBrowser({ device, stateDir, diff --git a/src/platform-runtime-resource-cleanup.ts b/src/platform-runtime-resource-cleanup.ts index d5138c8fde..a368102f31 100644 --- a/src/platform-runtime-resource-cleanup.ts +++ b/src/platform-runtime-resource-cleanup.ts @@ -1,9 +1,9 @@ +import type { WebPlatformSelection } from '@agent-device/contracts/platform-plugin'; import type { DeviceInfo } from '@agent-device/kernel/device'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; import { isIosFamily, webBackendKeyOf } from '@agent-device/kernel/device'; import type { PlatformResourceCleanup } from '@agent-device/daemon'; import { emitDiagnostic, type ResourceDiagnostic } from '@agent-device/host-kit/diagnostics'; -import { type OwnedProcessRecordStore } from '@agent-device/host-kit/process'; import { loadAndroidMechanics } from './platform-runtime-android-mechanics.ts'; /** Focused durable-resource cleanup composed above daemon policy and concrete platforms. */ @@ -27,50 +27,9 @@ export async function restoreLegacyXctestDeviceSetRedirectRuntime( await restoreLegacyXctestDeviceSetRedirect(onDiagnostic); } -export async function cleanupManagedWebRuntimeOrphans( - params: { - stateDir: string; - openWebSessionNames: readonly string[]; - ownedProcessRecords?: OwnedProcessRecordStore; - }, - host: HostEnvironment, -): Promise { - const { getManagedAgentBrowserStatus } = await import('@agent-device/platform-web'); - const status = await getManagedAgentBrowserStatus({ stateDir: params.stateDir, host }); - if (!status.installed) return; - const { cleanupManagedAgentBrowserOrphans } = await import('@agent-device/platform-web'); - await cleanupManagedAgentBrowserOrphans(status, 'daemon-startup', { - env: host.env, - openWebSessionNames: params.openWebSessionNames, - ...(params.ownedProcessRecords === undefined - ? {} - : { ownedProcessRecords: params.ownedProcessRecords }), - }); -} - -async function closeManagedWebRuntimeSession( - params: { - backendKey: string; - stateDir: string; - openWebSessionNames: () => readonly string[]; - ownedProcessRecords?: OwnedProcessRecordStore; - }, - host: HostEnvironment, -): Promise { - const { createAgentBrowserWebProvider } = await import('@agent-device/platform-web'); - const provider = await createAgentBrowserWebProvider({ - host, - session: params.backendKey, - stateDir: params.stateDir, - openWebSessionNames: params.openWebSessionNames, - ownedProcessRecords: params.ownedProcessRecords, - }); - await provider.close(); -} - export function createPlatformResourceCleanup( host: HostEnvironment, - ownedProcessRecords?: OwnedProcessRecordStore, + web?: WebPlatformSelection, ): PlatformResourceCleanup { return Object.freeze({ async stopSnapshotHelper(device) { @@ -81,15 +40,8 @@ export function createPlatformResourceCleanup( if (params.device.platform !== 'web') return; const backendKey = webBackendKeyOf(params.device.id); if (backendKey === undefined) return; - await closeManagedWebRuntimeSession( - { - backendKey, - stateDir: params.stateDir, - openWebSessionNames: params.openSessionNames, - ownedProcessRecords, - }, - host, - ); + const provider = await web?.active?.operations.createProvider(backendKey); + await provider?.close(); }, async cleanupSessionlessExecutionHost(device) { if (!isIosFamily(device)) return; diff --git a/src/platform-runtime-screen-recording-host.ts b/src/platform-runtime-screen-recording-host.ts index 5068f04736..226f70d7be 100644 --- a/src/platform-runtime-screen-recording-host.ts +++ b/src/platform-runtime-screen-recording-host.ts @@ -1,3 +1,4 @@ +import type { WebPlatformSelection } from '@agent-device/contracts/platform-plugin'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; import type { OwnedProcessRecordWriter } from '@agent-device/contracts/platform-runtime-host'; import type { ScreenRecordingRuntimeHost } from '@agent-device/contracts/screen-recording-runtime-host'; @@ -6,6 +7,7 @@ import type { ScreenRecordingRuntimeHost } from '@agent-device/contracts/screen- export function createScreenRecordingRuntimeHost(options: { ownedProcesses?: OwnedProcessRecordWriter; host: HostEnvironment; + web?: WebPlatformSelection; }): ScreenRecordingRuntimeHost { const host = options.host; const android: ScreenRecordingRuntimeHost['android'] = Object.freeze({ @@ -19,7 +21,7 @@ export function createScreenRecordingRuntimeHost(options: { resolve: async (device) => { const { resolveWebScreenRecordingTransport } = await import('./platform-runtime-screen-recording-web-host.ts'); - return await resolveWebScreenRecordingTransport(device); + return await resolveWebScreenRecordingTransport(device, options.web); }, }); const outputs: ScreenRecordingRuntimeHost['outputs'] = Object.freeze({ diff --git a/src/platform-runtime-screen-recording-web-host.test.ts b/src/platform-runtime-screen-recording-web-host.test.ts index 4881bfff61..9bd01bb6b9 100644 --- a/src/platform-runtime-screen-recording-web-host.test.ts +++ b/src/platform-runtime-screen-recording-web-host.test.ts @@ -1,5 +1,5 @@ +import { makeWebProvider, webSelectionFixture } from './platform-runtime-web-provider.fixtures.ts'; import { expect, test } from 'vitest'; -import { withWebProvider } from '@agent-device/platform-web'; import { resolveWebScreenRecordingTransport } from './platform-runtime-screen-recording-web-host.ts'; const web = { @@ -11,16 +11,22 @@ const web = { booted: true, }; +const webPlugin = webSelectionFixture(); + test('never falls back to an unscoped local web recorder', async () => { - expect(await resolveWebScreenRecordingTransport(web)).toBeUndefined(); + expect(await resolveWebScreenRecordingTransport(web, webPlugin)).toBeUndefined(); const calls: string[] = []; - await withWebProvider( - { - startRecording: async (outputPath: string) => calls.push(`start:${outputPath}`), - stopRecording: async () => calls.push('stop'), - } as never, + await webPlugin.get().withRequestProvider( + makeWebProvider({ + startRecording: async (outputPath) => { + calls.push(`start:${outputPath}`); + }, + stopRecording: async () => { + calls.push('stop'); + }, + }), async () => { - const transport = await resolveWebScreenRecordingTransport(web); + const transport = await resolveWebScreenRecordingTransport(web, webPlugin); if (!transport) throw new Error('missing scoped web recording transport'); await transport.start('/tmp/capture.webm'); await transport.stop(); diff --git a/src/platform-runtime-screen-recording-web-host.ts b/src/platform-runtime-screen-recording-web-host.ts index 464989c3f5..d090dda53b 100644 --- a/src/platform-runtime-screen-recording-web-host.ts +++ b/src/platform-runtime-screen-recording-web-host.ts @@ -1,12 +1,13 @@ +import type { WebPlatformSelection } from '@agent-device/contracts/platform-plugin'; import type { ScreenRecordingRuntimeHost } from '@agent-device/contracts/screen-recording-runtime-host'; import type { DeviceInfo } from '@agent-device/kernel/device'; export async function resolveWebScreenRecordingTransport( device: DeviceInfo, + web?: WebPlatformSelection, ): ReturnType { if (device.platform !== 'web') return undefined; - const { resolveRequestScopedWebProvider } = await import('@agent-device/platform-web'); - const provider = await resolveRequestScopedWebProvider(); + const provider = await web?.get().operations.resolveRequestProvider(); if (!provider?.startRecording || !provider.stopRecording) return undefined; return Object.freeze({ start: async (outputPath: string) => await provider.startRecording!(outputPath), diff --git a/src/platform-runtime-web-provider.fixtures.ts b/src/platform-runtime-web-provider.fixtures.ts index e4ec426ecf..ca11247c0e 100644 --- a/src/platform-runtime-web-provider.fixtures.ts +++ b/src/platform-runtime-web-provider.fixtures.ts @@ -1,4 +1,33 @@ -import type { WebProvider } from '@agent-device/platform-web'; +import { createRequire } from 'node:module'; +import type { HostEnvironment } from '@agent-device/kernel/source-value'; +import { createLiveTestHostEnvironment } from '@agent-device/test-kit'; +import { createPlatformPluginHost } from './platform-runtime/plugin-host.ts'; +import type { + WebPlatformRegistration, + WebPlatformSelection, +} from '@agent-device/contracts/platform-plugin'; +import type { PlatformContribution, PlatformHost } from '@agent-device/plugins/contract'; + +const pluginRequire = createRequire( + new URL('../packages/platform-web/package.json', import.meta.url), +); +const { default: webPlatformPlugin } = (await import( + pluginRequire.resolve('@agent-device/web/agent-device') +)) as { + default(): { contributes: [Extract] }; +}; + +export function webSelectionFixture( + host: HostEnvironment = createLiveTestHostEnvironment(), + stateDir = '/test-web-state', + resources?: Pick, +): WebPlatformSelection { + const active = webPlatformPlugin().contributes[0].setup( + createPlatformPluginHost(host, stateDir, resources), + ) as WebPlatformRegistration; + return { active, get: () => active }; +} +import type { WebProvider } from '@agent-device/contracts/web-provider'; /** A web provider whose every operation succeeds with nothing; a test overrides the ones it reads. */ export function makeWebProvider(overrides: Partial = {}): WebProvider { diff --git a/src/platform-runtime.test.ts b/src/platform-runtime.test.ts index 9f310b6212..0e17107994 100644 --- a/src/platform-runtime.test.ts +++ b/src/platform-runtime.test.ts @@ -31,7 +31,7 @@ vi.mock('./platform-runtime-host.ts', () => { }; }); -import { readVersion } from '@agent-device/host-kit/version'; +import { webSelectionFixture } from './platform-runtime-web-provider.fixtures.ts'; import { createPlatformDeviceInventoryGateways, createPlatformModuleRegistryForHost, @@ -39,7 +39,7 @@ import { bindTestCommandHost(); -const platformModuleRegistry = createPlatformModuleRegistryForHost({}, readVersion()); +const platformModuleRegistry = createPlatformModuleRegistryForHost({}, webSelectionFixture()); describe('platform module metadata composition', () => { test('registers each canonical family exactly once in canonical order', () => { @@ -69,7 +69,6 @@ describe('platform module metadata composition', () => { } as const; const providerGateways = await createPlatformDeviceInventoryGateways( createLiveTestHostEnvironment(), - readVersion(), { discover: async () => ({ kind: 'inventory', @@ -93,7 +92,8 @@ describe('platform module metadata composition', () => { const localGateways = await createPlatformDeviceInventoryGateways( createLiveTestHostEnvironment(), - readVersion(), + undefined, + webSelectionFixture(), ); expect(await localGateways.localOnly.discover({ platform: 'web' }, scope)).toHaveLength(1); expect(hostAdapter.evaluations).toBe(0); diff --git a/src/platform-runtime.ts b/src/platform-runtime.ts index d4be3b94b9..ce09dd0e4b 100644 --- a/src/platform-runtime.ts +++ b/src/platform-runtime.ts @@ -49,10 +49,7 @@ import { inventoryModule as linuxInventoryModule, runtimeModule as linuxRuntimeModule, } from '@agent-device/platform-linux'; -import { - inventoryModule as webInventoryModule, - runtimeModule as webRuntimeModule, -} from '@agent-device/platform-web'; +import type { WebPlatformSelection } from '@agent-device/contracts/platform-plugin'; import { createComposedPlatformRuntimeGateway, type PlatformRuntimeProviderRegistration, @@ -86,13 +83,10 @@ const shutdownLoaders = Object.freeze({ await loadAndroidShutdownRuntime(dependencies), }); -// All six families stay registered in the packed core today. The registry completeness-checks only -// the required families, so an optional family (ADR 0034) may be absent from a composition and every -// lookup then reports plugin-not-installed with its install hint. The caller supplies `coreVersion`, -// which that hint names: this root does not read host mechanics. export function createPlatformModuleRegistryForHost( env: Readonly>, - coreVersion: string, + web?: WebPlatformSelection, + reportAbsent?: Parameters[1], ) { return createPlatformModuleRegistry( [ @@ -107,19 +101,23 @@ export function createPlatformModuleRegistryForHost( }), vegaInventoryModule, linuxInventoryModule, - webInventoryModule, + ...(web?.active ? [web.active.inventoryModule] : []), ], - coreVersion, + reportAbsent, + (family) => { + if (family === 'web') web?.get(); + }, ); } export async function createPlatformDeviceInventoryGateways( host: HostEnvironment, - coreVersion: string, provider?: ProviderDeviceInventorySource, + web?: WebPlatformSelection, + reportAbsent?: Parameters[1], ): Promise { return await attachAppleSelectionProbes({ - registry: createPlatformModuleRegistryForHost(host.env, coreVersion), + registry: createPlatformModuleRegistryForHost(host.env, web, reportAbsent), loadHost: async () => { const { createDeviceInventoryHost } = await import('./platform-runtime-host.ts'); return createDeviceInventoryHost(host); @@ -136,10 +134,10 @@ const androidRuntimeModule = createAndroidRuntimeModule({ }, }); -/** The root composition registry the platform runtime gateway reads. All six families are - * registered today; an optional family absent from a composition fails lookups with the typed - * `plugin-not-installed` outcome before any device binding (see platform-runtime-gateway.ts). */ -function createPlatformRuntimeModuleRegistry(coreVersion: string) { +function createPlatformRuntimeModuleRegistry( + web?: WebPlatformSelection, + reportAbsent?: Parameters[1], +) { return createPlatformModuleRegistry( [ appleRuntimeModule, @@ -147,17 +145,20 @@ function createPlatformRuntimeModuleRegistry(coreVersion: string) { harmonyosRuntimeModule, vegaRuntimeModule, linuxRuntimeModule, - webRuntimeModule, + ...(web?.active ? [web.active.runtimeModule] : []), ], - coreVersion, + reportAbsent, + (family) => { + if (family === 'web') web?.get(); + }, ); } export function createPlatformRuntimeGateway( options: Readonly<{ host: HostEnvironment; - /** The running core's version, which the typed absence outcome names in its install command. */ - coreVersion: string; + web?: WebPlatformSelection; + reportAbsent?: Parameters[1]; providerRuntimes?: readonly ProviderDeviceRuntime[]; providerModules?: readonly PlatformRuntimeProviderRegistration[]; resolveSessionArtifacts(sessionId: string): AppLogSessionArtifacts; @@ -167,12 +168,13 @@ export function createPlatformRuntimeGateway( }>, ): DeviceRuntimeGateway { return createComposedPlatformRuntimeGateway({ - modules: createPlatformRuntimeModuleRegistry(options.coreVersion), + modules: createPlatformRuntimeModuleRegistry(options.web, options.reportAbsent), loadHost: async () => { const { createPlatformRuntimeHost, createSnapshotRuntimeHost, loadMacOsSurfaceSnapshot } = await import('./platform-runtime-operation-host.ts'); return createPlatformRuntimeHost({ host: options.host, + web: options.web, sessionsDir: options.sessionsDir, resolveSessionArtifacts: options.resolveSessionArtifacts, shutdownLoaders, diff --git a/src/platform-runtime/plugin-host.ts b/src/platform-runtime/plugin-host.ts new file mode 100644 index 0000000000..ed3a12b106 --- /dev/null +++ b/src/platform-runtime/plugin-host.ts @@ -0,0 +1,21 @@ +import type { PlatformHost } from '@agent-device/plugins/contract'; +import type { HostEnvironment } from '@agent-device/kernel/source-value'; +import { emitDiagnostic, withDiagnosticTimer } from '@agent-device/host-kit/diagnostics'; + +export function createPlatformPluginHost( + host: HostEnvironment, + stateDir: string, + resources?: Pick, +): PlatformHost { + return Object.freeze({ + ...host, + stateDir, + ...resources, + emitDiagnostic, + withDiagnosticTimer, + runCommand: async (executable, args, options) => { + const { runCmd } = await import('@agent-device/host-kit/command'); + return await runCmd(executable, args, options); + }, + } satisfies PlatformHost); +} diff --git a/src/platform-runtime/request-providers.ts b/src/platform-runtime/request-providers.ts index 4c29a92de4..d4ca0fa788 100644 --- a/src/platform-runtime/request-providers.ts +++ b/src/platform-runtime/request-providers.ts @@ -1,3 +1,4 @@ +import { createPlatformModuleRegistry } from '@agent-device/contracts/platform-module'; import type { PlatformGatedProviderResolverKey, PlatformProviderRequestContext, @@ -9,15 +10,14 @@ import type { AndroidAdbProvider, } from '@agent-device/platform-android/mechanics'; import type { AppleRunnerCommandExecutor, AppleRunnerProvider } from '@agent-device/apple-runner'; -import type { WebProvider } from '@agent-device/platform-web'; +import type { WebProvider } from '@agent-device/contracts/web-provider'; +import type { WebPlatformSelection } from '@agent-device/contracts/platform-plugin'; import type { AppleToolProvider } from '@agent-device/platform-apple/tool-provider'; import type { LinuxToolProvider } from '@agent-device/platform-linux'; import type { VegaToolProvider } from '@agent-device/platform-vega'; import { webBackendKeyOf, type DeviceInfo } from '@agent-device/kernel/device'; -import type { HostEnvironment } from '@agent-device/kernel/source-value'; import type { AppleSimulatorScreenRecordingTransport } from '../platform-runtime-screen-recording-apple-transport.ts'; import type { AppleRunnerScreenRecordingTransport } from '../platform-runtime-screen-recording-apple-runner-transport.ts'; -import { type OwnedProcessRecordStore } from '@agent-device/host-kit/process'; import { tryGetPlugin } from '../core/platform-plugin-registry.ts'; import { registerBuiltinPlatformPlugins } from '../core/interactors/register-builtins.ts'; import { missingPlatformPlugin } from '../core/platform-plugin-absence.ts'; @@ -62,17 +62,9 @@ export type PlatformProviderResolvers = { appleSimulatorScreenRecordingTransport?: AppleSimulatorScreenRecordingTransportResolver; }; -export type DefaultWebProviderOptions = Readonly<{ - /** The composing runtime's host; the default web provider spawns managed backends with it. */ - host: HostEnvironment; - stateDir?: string; - openWebSessionNames: () => readonly string[]; - ownedProcessRecords?: OwnedProcessRecordStore; -}>; - export type RequestPlatformProviderOptions = Readonly<{ providers?: PlatformProviderResolvers; - defaultWebProvider?: DefaultWebProviderOptions; + web?: WebPlatformSelection; }>; type ResolvedRequestPlatformProviders = { @@ -105,6 +97,7 @@ type RequestPlatformProviderDescriptor = { appendWrapper: ( scopedProviders: ResolvedRequestPlatformProviders, wrappers: RequestPlatformProviderScopeWrapper[], + web?: WebPlatformSelection, ) => Promise; }; @@ -124,16 +117,12 @@ export function createComposedRequestPlatformProviders( context: PlatformProviderRequestContext, task: (scope: RequestPlatformProviderScope) => Promise, ): Promise => { - const effectiveProviders = await providersForContext( - providers, - options.defaultWebProvider, - context, - ); + const effectiveProviders = await providersForContext(providers, options.web, context); const scopedProviders = resolveRequestPlatformProviders(effectiveProviders, context); const scope: RequestPlatformProviderScope = { androidAdbExecutor: scopedProviders.androidAdb?.executor, }; - const wrappers = await requestPlatformProviderScopeWrappers(scopedProviders); + const wrappers = await requestPlatformProviderScopeWrappers(scopedProviders, options.web); return await runRequestPlatformProviderScopes(wrappers, async () => await task(scope)); }, }); @@ -141,26 +130,15 @@ export function createComposedRequestPlatformProviders( async function providersForContext( providers: PlatformProviderResolvers, - defaultWebProvider: DefaultWebProviderOptions | undefined, + web: WebPlatformSelection | undefined, context: PlatformProviderRequestContext, ): Promise { const session = webBackendKeyOf(context.device.id); - if ( - providers.webProvider || - !context.useDefaultWebProvider || - !defaultWebProvider || - session === undefined - ) { + if (context.device.platform !== 'web' || !web) return providers; + const platform = web.get(); + if (providers.webProvider || !context.useDefaultWebProvider || session === undefined) return providers; - } - const { createAgentBrowserWebProvider } = await import('@agent-device/platform-web'); - const defaultProvider = await createAgentBrowserWebProvider({ - host: defaultWebProvider.host, - session, - stateDir: defaultWebProvider.stateDir, - openWebSessionNames: defaultWebProvider.openWebSessionNames, - ownedProcessRecords: defaultWebProvider.ownedProcessRecords, - }); + const defaultProvider = await platform.operations.createProvider(session); return { ...providers, webProvider: () => defaultProvider, @@ -267,13 +245,12 @@ const REQUEST_PLATFORM_PROVIDER_DESCRIPTORS = [ resolverKey: 'webProvider', resolve(providers, context) { const resolver = providers.webProvider; - if (!resolver || !platformGatedResolverApplies('webProvider', context.device)) return {}; + if (!resolver || context.device.platform !== 'web') return {}; return { web: { provider: resolver(context) } }; }, - async appendWrapper(scopedProviders, wrappers) { - if (!scopedProviders.web?.provider) return; - const { withWebProvider } = await import('@agent-device/platform-web'); - appendRequestProviderWrapper(wrappers, scopedProviders.web, withWebProvider); + async appendWrapper(scopedProviders, wrappers, web) { + if (!scopedProviders.web?.provider || !web) return; + appendRequestProviderWrapper(wrappers, scopedProviders.web, web.get().withRequestProvider); }, }, { @@ -336,14 +313,15 @@ function platformGatedResolverApplies( return tryGetPlugin(device.platform)?.providers?.platformGatedResolvers.includes(key) ?? false; } -registerBuiltinPlatformPlugins(missingPlatformPlugin); +registerBuiltinPlatformPlugins(missingPlatformPlugin, createPlatformModuleRegistry); async function requestPlatformProviderScopeWrappers( scopedProviders: ResolvedRequestPlatformProviders, + web?: WebPlatformSelection, ): Promise { const wrappers: RequestPlatformProviderScopeWrapper[] = []; for (const descriptor of REQUEST_PLATFORM_PROVIDER_DESCRIPTORS) { - await descriptor.appendWrapper(scopedProviders, wrappers); + await descriptor.appendWrapper(scopedProviders, wrappers, web); } return wrappers; } diff --git a/src/provider-device-runtimes.ts b/src/provider-device-runtimes.ts index 00623ada19..327d28b637 100644 --- a/src/provider-device-runtimes.ts +++ b/src/provider-device-runtimes.ts @@ -1,15 +1,24 @@ +import { getOptionalPlatformPluginDeclaration } from '@agent-device/contracts/plugin-installation'; +import { missingPlatformPlugin } from './core/platform-plugin-absence.ts'; +import type { WebPlatformSelection } from '@agent-device/contracts/platform-plugin'; +import type { PlatformHost } from '@agent-device/plugins/contract'; +import type { + PluginCandidate, + PluginRegistryPolicy, + ProviderRegistry, +} from '@agent-device/plugins/registry'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; import type { ProviderDeviceRuntime } from '@agent-device/contracts/device'; import type { PluginCleanupOutcome, PluginInventoryEntry, } from '@agent-device/contracts/plugin-inventory'; -import type { PluginCandidate, PluginRegistryPolicy } from '@agent-device/plugins/registry'; import type { PlatformRuntimeProviderRegistration } from './platform-runtime-gateway.ts'; import { builtinProviderCandidates } from './builtin-provider-plugins.ts'; import { PROVIDER_PLUGIN_POLICY } from './provider-plugin-policy.ts'; export type ProviderRuntimeComposition = Readonly<{ + platformRegistry: Pick; resolveReplayBackend: import('@agent-device/plugins/replay-backend').ReplayBackendResolver; resolveReplayExecution: import('@agent-device/contracts/replay-execution').ReplayExecutionResolver; runtimes: readonly ProviderDeviceRuntime[]; @@ -26,12 +35,14 @@ export type ProviderRuntimeComposition = Readonly<{ */ export async function createDaemonProviderRuntimeComposition( host: HostEnvironment, + platformHost?: PlatformHost, ): Promise { const { storePluginCandidates, createPluginSelectionGuard } = await import('@agent-device/plugins/store'); const candidates = await storePluginCandidates(host.env); return await composeProviderRuntime(host, candidates, { ...PROVIDER_PLUGIN_POLICY, + platformHost, assertSelectionCurrent: createPluginSelectionGuard(candidates, host.env), }); } @@ -40,8 +51,12 @@ export async function createDaemonProviderRuntimeComposition( export async function createEmbeddedProviderRuntimeComposition( host: HostEnvironment, candidates: readonly PluginCandidate[], + platformHost?: PlatformHost, ): Promise { - return await composeProviderRuntime(host, candidates, PROVIDER_PLUGIN_POLICY); + return await composeProviderRuntime(host, candidates, { + ...PROVIDER_PLUGIN_POLICY, + platformHost, + }); } async function composeProviderRuntime( @@ -51,12 +66,26 @@ async function composeProviderRuntime( ): Promise { const { resolveProviderPlugins, startProviderRegistry } = await import('@agent-device/plugins/registry'); + const [{ BUILTIN_PLATFORM_PLUGINS }, { isOptionalPlatform }] = await Promise.all([ + import('./core/interactors/register-builtins.ts'), + import('@agent-device/contracts/platform-module'), + ]); + const bundledPlatforms = BUILTIN_PLATFORM_PLUGINS.flatMap((plugin) => [ + ...plugin.platforms, + ]).filter(isOptionalPlatform); const resolved = await resolveProviderPlugins([ + { + source: 'builtin', + dormant: true, + declaredClaims: bundledPlatforms.map((id) => ({ kind: 'platform', id })), + load: () => undefined, + }, ...builtinProviderCandidates(host), ...candidates, ]); const registry = await startProviderRegistry(resolved, host, policy); return Object.freeze({ + platformRegistry: registry, runtimes: Object.freeze(registry.registrations.map(({ runtime }) => runtime)), platformModules: Object.freeze( registry.registrations.map(({ runtime, platformModule }) => ({ @@ -70,3 +99,17 @@ async function composeProviderRuntime( shutdown: registry.close, }); } + +export function selectWebPlatform( + registry: Pick, +): WebPlatformSelection { + const packageName = getOptionalPlatformPluginDeclaration('web')?.package; + return Object.freeze({ + active: registry.platforms.find((platform) => platform.family === 'web'), + get: () => { + const platform = registry.resolvePlatform('web', missingPlatformPlugin, packageName); + if (platform.family !== 'web') throw new TypeError('Expected web platform registration'); + return platform; + }, + }); +} diff --git a/test/integration/provider-scenarios/harness.ts b/test/integration/provider-scenarios/harness.ts index 6342036a9b..b239103cab 100644 --- a/test/integration/provider-scenarios/harness.ts +++ b/test/integration/provider-scenarios/harness.ts @@ -1,4 +1,4 @@ -import { readVersion } from '@agent-device/host-kit/version'; +import { webSelectionFixture } from '../../../src/platform-runtime-web-provider.fixtures.ts'; import type { DaemonWireRequest } from '@agent-device/contracts/command'; import type { DaemonResponse } from '@agent-device/kernel/contracts'; import assert from 'node:assert/strict'; @@ -172,8 +172,12 @@ export async function createProviderScenarioHarness( const providerModules = platformRuntime?.providerModules ?? createProviderPlatformRuntimeRegistrations(configuredRuntimes); + const web = webSelectionFixture(input.host, input.baseDir, { + openWebSessionNames: input.openWebSessionNames, + ownedProcessRecords: rootDeps.ownedProcessRecords, + }); const defaultDeviceRuntimeGateway = createPlatformRuntimeGateway({ - coreVersion: readVersion(), + web, host: input.host, assertShutdownAllowed: input.assertShutdownAllowed, providerRuntimes: configuredRuntimes, @@ -213,12 +217,7 @@ export async function createProviderScenarioHarness( webProvider, appleSimulatorScreenRecordingTransport, }, - defaultWebProvider: { - host: input.host, - stateDir: input.baseDir, - openWebSessionNames: input.openWebSessionNames, - ownedProcessRecords: rootDeps.ownedProcessRecords, - }, + web, }); return Object.freeze({ ...rootDeps, diff --git a/test/integration/provider-scenarios/help-conformance-error-routes.ts b/test/integration/provider-scenarios/help-conformance-error-routes.ts index 906350c07e..b9311b0a44 100644 --- a/test/integration/provider-scenarios/help-conformance-error-routes.ts +++ b/test/integration/provider-scenarios/help-conformance-error-routes.ts @@ -2,7 +2,7 @@ import assert from 'node:assert/strict'; import type { AndroidAdbProvider } from '@agent-device/platform-android/mechanics'; import { deviceIdentity } from '@agent-device/kernel/device'; import type { RawSnapshotNode } from '@agent-device/kernel/snapshot'; -import type { WebProvider } from '@agent-device/platform-web'; +import type { WebProvider } from '@agent-device/contracts/web-provider'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; diff --git a/test/integration/provider-scenarios/web-provider.test.ts b/test/integration/provider-scenarios/web-provider.test.ts index a4dfd247c5..c802454af7 100644 --- a/test/integration/provider-scenarios/web-provider.test.ts +++ b/test/integration/provider-scenarios/web-provider.test.ts @@ -6,7 +6,8 @@ import { WEB_DESKTOP_DEVICE, withNodeRuntime, } from '@agent-device/test-kit'; -import { createAgentBrowserWebProvider, type WebProvider } from '@agent-device/platform-web'; +import { webSelectionFixture } from '../../../src/platform-runtime-web-provider.fixtures.ts'; +import type { WebProvider } from '@agent-device/contracts/web-provider'; import { withCommandExecutorOverride } from '@agent-device/host-kit/command'; import { createProviderScenarioHarness } from './harness.ts'; @@ -218,10 +219,8 @@ test('non-dense browser refs survive snapshot storage and routed fill and click' const stateDir = mkdtempForTestSync('web-ref-route-'); installFakeManagedAgentBrowser(stateDir); await withNodeRuntime({ version: '24.0.0' }, async () => { - const provider = await createAgentBrowserWebProvider({ - stateDir, - host: { env: process.env, cwd: process.cwd() }, - }); + const web = webSelectionFixture({ env: process.env, cwd: process.cwd() }, stateDir); + const provider = await web.get().operations.createProvider('default'); await withCommandExecutorOverride( async (_command, args, options) => { const [command, ref] = args.slice(1); diff --git a/test/integration/provider-scenarios/web-world.ts b/test/integration/provider-scenarios/web-world.ts index 845ea82218..82979157e4 100644 --- a/test/integration/provider-scenarios/web-world.ts +++ b/test/integration/provider-scenarios/web-world.ts @@ -1,6 +1,6 @@ import fs from 'node:fs'; import { likelyPlayableWebmContainer } from '@agent-device/test-kit'; -import type { WebProvider } from '@agent-device/platform-web'; +import type { WebProvider } from '@agent-device/contracts/web-provider'; import type { RawSnapshotNode } from '@agent-device/kernel/snapshot'; import { validPng } from './assertions.ts'; import { PROVIDER_SCENARIO_WEB } from './fixtures.ts'; diff --git a/test/integration/smoke-tvos-platform-coverage.test.ts b/test/integration/smoke-tvos-platform-coverage.test.ts index d47a371f17..98419bed98 100644 --- a/test/integration/smoke-tvos-platform-coverage.test.ts +++ b/test/integration/smoke-tvos-platform-coverage.test.ts @@ -1,4 +1,3 @@ -import { readVersion } from '@agent-device/host-kit/version'; import assert from 'node:assert/strict'; import fs from 'node:fs'; import path from 'node:path'; @@ -84,7 +83,6 @@ test('tvOS gesture contract preserves the typed multi-touch denial', async () => // R42: the denial is now the Apple owner's own fact for the tvOS leaf, and the refusal a // gesture reports is that fact's hint under the shared wording. const facts = await createPlatformRuntimeGateway({ - coreVersion: readVersion(), host: createLiveTestHostEnvironment(), resolveSessionArtifacts: () => ({ outputPath: '/sessions/tvos/app.log', diff --git a/test/integration/smoke-web-platform.test.ts b/test/integration/smoke-web-platform.test.ts index d431f26e3f..873f9d135d 100644 --- a/test/integration/smoke-web-platform.test.ts +++ b/test/integration/smoke-web-platform.test.ts @@ -8,15 +8,13 @@ import { setTimeout as delay } from 'node:timers/promises'; import { type CliJsonResult, formatResultDebug, runBuiltCliJson } from './cli-json.ts'; import { assertPngDimensions, assertPngFile } from './provider-scenarios/assertions.ts'; import { runCleanupWithCoverageReport } from './web-e2e/coverage-report.ts'; +import { + installWebPluginForSmoke, + stopWebPluginSmokeDaemon, +} from './web-e2e/web-plugin-artifact.ts'; import { runLiveFillScenario } from './web-e2e/fill-scenario.ts'; import { assertNoDaemonLeaks } from './support/daemon-leak-oracle.ts'; -import { - getManagedAgentBrowserStatus, - inspectManagedAgentBrowserProcesses, - summarizeAgentBrowserProcesses, - type AgentBrowserProcessSummary, - type AgentBrowserToolStatus, -} from '@agent-device/platform-web'; +import { webSelectionFixture } from '../../src/platform-runtime-web-provider.fixtures.ts'; import { stopDaemonProcess, waitForDaemonExit, @@ -187,22 +185,19 @@ async function runWebShutdownSmoke(context: WebSmokeContext): Promise { // above (including the very failure this test exists to catch: processes still alive when the // fix regresses) can never leave a daemon or a Chrome fleet running on the host afterward. let daemonIdentity: DaemonProcessIdentity | undefined; - let status: AgentBrowserToolStatus | undefined; + let inspect: InspectManagedBrowserProcesses | undefined; try { + await installWebPluginForSmoke(context.env); await runStep(context, 'set up managed web backend', ['web', 'setup', '--json']); await runStep(context, 'open local fixture', ['open', context.url, ...context.common]); const stateDir = context.env.AGENT_DEVICE_STATE_DIR; assert.ok(stateDir, 'expected the smoke context to configure a state dir'); - status = await getManagedAgentBrowserStatus({ - stateDir, - host: { env: process.env, cwd: process.cwd() }, - }); - - const before = await inspectManagedAgentBrowserProcesses(status); + inspect = inspectManagedBrowserProcesses(context.env, stateDir); + const before = await inspect(); assert.ok( before.count > 0, - `expected the managed browser fleet to be running after open, found none: ${formatProcessSummary(before)}`, + `expected the managed browser fleet to be running after open, found none: ${JSON.stringify(before)}`, ); const daemonPid = readDaemonPid(stateDir); @@ -216,7 +211,7 @@ async function runWebShutdownSmoke(context: WebSmokeContext): Promise { process.kill(daemonPid, 'SIGTERM'); const [after, daemonExit] = await Promise.all([ - settleManagedBrowserProcesses(status), + settleManagedBrowserProcesses(inspect), waitForDaemonExit(daemonIdentity, { timeoutMs: WEB_SHUTDOWN_SETTLE_TIMEOUT_MS, pollMs: WEB_SHUTDOWN_SETTLE_POLL_MS, @@ -225,7 +220,7 @@ async function runWebShutdownSmoke(context: WebSmokeContext): Promise { assert.equal( after.count, 0, - `expected zero owned Chrome processes after daemon shutdown, found: ${formatProcessSummary(after)}`, + `expected zero owned Chrome processes after daemon shutdown, found: ${JSON.stringify(after)}`, ); assert.equal( daemonExit.exited, @@ -237,7 +232,7 @@ async function runWebShutdownSmoke(context: WebSmokeContext): Promise { // state-dir residue either, on top of the process-level proof above. await assertNoDaemonLeaks({ stateDir, daemonPids: [daemonPid], phase: 'after-shutdown' }); } finally { - await cleanupWebShutdownSmoke(context, daemonIdentity, status); + await cleanupWebShutdownSmoke(context, daemonIdentity, inspect); } } @@ -250,7 +245,7 @@ async function runWebShutdownSmoke(context: WebSmokeContext): Promise { async function cleanupWebShutdownSmoke( context: WebSmokeContext, daemonIdentity: DaemonProcessIdentity | undefined, - status: AgentBrowserToolStatus | undefined, + inspect: InspectManagedBrowserProcesses | undefined, timeouts = { termTimeoutMs: WEB_SHUTDOWN_CLEANUP_TIMEOUT_MS, killTimeoutMs: WEB_SHUTDOWN_CLEANUP_TIMEOUT_MS, @@ -264,9 +259,9 @@ async function cleanupWebShutdownSmoke( errors.push(error); } } - if (status) { + if (inspect) { try { - await forceKillManagedBrowserProcesses(status); + await forceKillManagedBrowserProcesses(inspect); } catch (error) { errors.push(error); } @@ -297,9 +292,11 @@ async function stopWebSmokeDaemon( // of how recently it was used, so a planted regression (no active close on shutdown) cannot leave // Chrome processes running on the host just because cleanup honored the same idle guard the // regression exploits. -async function forceKillManagedBrowserProcesses(status: AgentBrowserToolStatus): Promise { +async function forceKillManagedBrowserProcesses( + inspect: InspectManagedBrowserProcesses, +): Promise { const processes = await listHostProcesses({ timeoutMs: WEB_SHUTDOWN_CLEANUP_TIMEOUT_MS }); - const summary = await summarizeAgentBrowserProcesses(processes, status); + const summary = await inspect(); if (summary.count === 0) return; // Chrome renderers share command lines, so each stop also names the lifetime read beside them. const fleet = expandProcessTree(summary.pids, processes); @@ -332,30 +329,42 @@ function readDaemonPid(stateDir: string): number { return info.pid as number; } +type ManagedBrowserProcessSummary = { count: number; pids: number[]; matchReasons: string[] }; +type InspectManagedBrowserProcesses = () => Promise; + +function inspectManagedBrowserProcesses( + env: NodeJS.ProcessEnv, + stateDir: string, +): InspectManagedBrowserProcesses { + const { operations } = webSelectionFixture({ env, cwd: process.cwd() }, stateDir).get(); + return async () => { + const result = await operations.browserLifecycleCheck(stateDir); + const { count, pids, matchReasons } = result.evidence ?? {}; + assert.ok( + typeof count === 'number' && Array.isArray(pids) && Array.isArray(matchReasons), + JSON.stringify(result), + ); + return { count, pids, matchReasons }; + }; +} + async function settleManagedBrowserProcesses( - status: AgentBrowserToolStatus, -): Promise { + inspect: InspectManagedBrowserProcesses, +): Promise { const deadline = Date.now() + WEB_SHUTDOWN_SETTLE_TIMEOUT_MS; - let summary = await inspectManagedAgentBrowserProcesses(status); + let summary = await inspect(); while (summary.count > 0 && Date.now() < deadline) { await new Promise((resolve) => setTimeout(resolve, WEB_SHUTDOWN_SETTLE_POLL_MS)); - summary = await inspectManagedAgentBrowserProcesses(status); + summary = await inspect(); } return summary; } -function formatProcessSummary(summary: AgentBrowserProcessSummary): string { - return JSON.stringify({ - count: summary.count, - pids: summary.pids, - reasons: summary.processes.map((match) => match.reason), - }); -} - async function runWebSmoke(context: WebSmokeContext): Promise { let opened = false; try { + await installWebPluginForSmoke(context.env); await runStep(context, 'set up managed web backend', ['web', 'setup', '--json']); await runStep(context, 'verify managed web backend', ['web', 'doctor', '--json']); await runStep(context, 'open local fixture', ['open', context.url, ...context.common]); @@ -391,6 +400,7 @@ async function createWebSmokeContext( const env = { ...process.env, AGENT_DEVICE_STATE_DIR: stateDir, + AGENT_DEVICE_HOME: path.join(artifactDir, 'plugin-home'), AGENT_BROWSER_CONFIG: agentBrowserConfigPath, AGENT_BROWSER_HEADED: 'false', ...(options.agentBrowserIdleTimeoutMs === undefined @@ -554,6 +564,11 @@ async function cleanupWebSmoke(context: WebSmokeContext, opened: boolean): Promi errors.push(error); } } + try { + await stopWebPluginSmokeDaemon(context.env); + } catch (error) { + errors.push(error); + } try { await closeServer(context.server); } catch (error) { diff --git a/test/integration/web-e2e/fill-scenario.ts b/test/integration/web-e2e/fill-scenario.ts index c4ac996f4c..3098ac670e 100644 --- a/test/integration/web-e2e/fill-scenario.ts +++ b/test/integration/web-e2e/fill-scenario.ts @@ -3,6 +3,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import type { Server } from 'node:http'; import { tmpdir } from 'node:os'; import path from 'node:path'; +import { installWebPluginForSmoke, stopWebPluginSmokeDaemon } from './web-plugin-artifact.ts'; import { type CliJsonResult, formatResultDebug, runBuiltCliJson } from '../cli-json.ts'; import { FILL_FIXTURE_POINTS, @@ -154,6 +155,7 @@ async function startLiveFill(): Promise { const env = { ...process.env, AGENT_DEVICE_STATE_DIR: stateDir, + AGENT_DEVICE_HOME: path.join(stateDir, 'plugin-home'), AGENT_BROWSER_CONFIG: configPath, AGENT_BROWSER_HEADED: 'false', AGENT_BROWSER_IDLE_TIMEOUT_MS: '30000', @@ -165,6 +167,7 @@ async function startLiveFill(): Promise { return { url: `http://127.0.0.1:${port}/`, setup: async () => { + await installWebPluginForSmoke(env); const result = await runBuiltCliJson(['web', 'setup', '--json'], env); assert.equal(result.status, 0, debug('web setup', result)); }, @@ -187,8 +190,12 @@ async function startLiveFill(): Promise { try { if (opened) await run(['close']); } finally { - await closeServer(server); - rmSync(root, { recursive: true, force: true }); + try { + await stopWebPluginSmokeDaemon(env); + } finally { + await closeServer(server); + rmSync(root, { recursive: true, force: true }); + } } }, }; diff --git a/test/integration/web-e2e/web-plugin-artifact.ts b/test/integration/web-e2e/web-plugin-artifact.ts new file mode 100644 index 0000000000..7caa3019b6 --- /dev/null +++ b/test/integration/web-e2e/web-plugin-artifact.ts @@ -0,0 +1,32 @@ +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { mkdtempSync } from 'node:fs'; +import path from 'node:path'; +import { formatResultDebug, runBuiltCliJson } from '../cli-json.ts'; + +let tarball: string | undefined; + +function webPluginArtifact(): string { + if (tarball) return tarball; + const scratch = mkdtempSync(path.join(process.env.TMPDIR ?? '/tmp', 'agent-device-web-plugin-')); + const output = path.join(scratch, 'web.tgz'); + execFileSync('pnpm', ['pack', '--out', output], { + cwd: path.resolve(import.meta.dirname, '../../../packages/platform-web'), + env: process.env, + stdio: ['ignore', 'ignore', 'inherit'], + }); + tarball = output; + return output; +} + +export async function installWebPluginForSmoke(env: NodeJS.ProcessEnv): Promise { + const args = ['plugins', 'add', webPluginArtifact(), '--json']; + const result = await runBuiltCliJson(args, env); + assert.equal(result.status, 0, formatResultDebug('install web plugin', args, result)); +} + +export async function stopWebPluginSmokeDaemon(env: NodeJS.ProcessEnv): Promise { + const args = ['daemon', 'stop', '--json']; + const result = await runBuiltCliJson(args, env); + assert.equal(result.status, 0, formatResultDebug('stop web smoke daemon', args, result)); +} diff --git a/test/output-economy/daemon-route-fixtures.ts b/test/output-economy/daemon-route-fixtures.ts index 8a68483e6a..eb90a0ad31 100644 --- a/test/output-economy/daemon-route-fixtures.ts +++ b/test/output-economy/daemon-route-fixtures.ts @@ -4,7 +4,7 @@ import path from 'node:path'; import { PNG } from '@agent-device/capture-kit/png'; import type { BackendDumpNetworkResult } from '@agent-device/contracts/backend-diagnostics'; import type { RawSnapshotNode } from '@agent-device/kernel/snapshot'; -import type { WebProvider } from '@agent-device/platform-web'; +import type { WebProvider } from '@agent-device/contracts/web-provider'; import { WEB_DESKTOP_DEVICE } from '@agent-device/test-kit'; import { createProviderScenarioHarness } from '../integration/provider-scenarios/harness.ts'; import { NETWORK_SELECTION_RESULT } from './selection-fixtures.ts'; diff --git a/website/docs/docs/agent-setup.md b/website/docs/docs/agent-setup.md index eb47545b01..cacb99c2da 100644 --- a/website/docs/docs/agent-setup.md +++ b/website/docs/docs/agent-setup.md @@ -58,7 +58,7 @@ Each tool declares a display title and separate read-only and destructive hints. `agent-device mcp` accepts no flags or arguments other than `--structured`, `--help`, and `--version`; any other argument fails with `INVALID_ARGS`. To configure the server, set `AGENT_DEVICE_*` environment variables or `AGENT_DEVICE_CONFIG` in the client's server entry. For example, set the state directory with `AGENT_DEVICE_STATE_DIR`, and the remote `tenant`, `runId`, and `leaseId` with `AGENT_DEVICE_TENANT`, `AGENT_DEVICE_RUN_ID`, and `AGENT_DEVICE_LEASE_ID` (or the same keys in `~/.agent-device/config.json`). Tool calls cannot pass these values. -For web automation, MCP tools can target `platform: "web"` once the managed browser backend is set up, but `agent-device web setup` and `agent-device web doctor` are CLI-only. Run setup from a terminal that uses the same state directory as the MCP server before you ask an MCP client to drive a browser session. +For web automation, run `agent-device plugins add @agent-device/web` in a terminal. Run `agent-device web setup` with the same state directory as the MCP server. Then use `platform: "web"` in MCP tools. Use `agent-device web doctor` from the terminal to check the backend. MCP-only clients don't need a separately installed skill. When a client connects (`initialize` and `server/discover`), the server returns short `instructions` with the core workflow: start with `open`, act with `settle: true`, verify, `close`, how to keep refs accurate, and how to recover when the accessibility tree is sparse. An MCP-only `help` tool returns the same guides as `agent-device help `. Agents don't call `help` at startup; they call it for specialized work (gestures, scripting, TV, macOS, web, remote, debugging) or when a command is unclear. diff --git a/website/docs/docs/client-api.md b/website/docs/docs/client-api.md index 4cd5b37611..236133e237 100644 --- a/website/docs/docs/client-api.md +++ b/website/docs/docs/client-api.md @@ -195,8 +195,8 @@ To fetch provider-hosted video and log URLs after close, pass `closed.provider?. ## Web sessions Pass `platform: 'web'` to drive a browser session with the same command methods. Web automation -requires Node 24+. No client method sets up the managed web backend: run `agent-device web setup` -before first use, in the same state directory the client uses. Run `agent-device web doctor` to check +requires Node 24+. Run `agent-device plugins add @agent-device/web`, then run `agent-device web setup` +in the same state directory the client uses. Run `agent-device web doctor` to check backend health. ```ts diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index c9daba39d8..d7e7ac5742 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -199,9 +199,10 @@ restart; reconnect and take the hold again. See [Remote proxy](/docs/remote-prox `--platform web` drives a browser through [agent-browser](https://github.com/vercel-labs/agent-browser) and requires Node 24+. Use it when a browser step belongs inside an `agent-device` session, replay, batch, MCP, or Node.js client flow. For standalone browser automation, use `agent-browser` directly. -Set up and verify the managed web backend before you open a web session: +Install the web plugin and set up its backend before you open a web session. ```bash +agent-device plugins add @agent-device/web agent-device web setup agent-device web doctor agent-device open "https://example.com" --platform web From 4ce15045aaee7aa7263c1b8af4eacd975d82ce32 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 20 Nov 2026 11:14:32 +0100 Subject: [PATCH 3/7] fix(web): compose platform plugins through the family registry --- packages/contracts/src/platform-module.ts | 2 +- packages/contracts/src/platform-plugin.ts | 15 +- packages/contracts/src/plugin-installation.ts | 2 +- .../src/server/http/daemon-runtime-deps.ts | 2 +- .../daemon/src/server/http/daemon-runtime.ts | 14 +- .../server/http/daemon-startup-diagnostics.ts | 23 +++ packages/kernel/package.json | 4 + packages/kernel/src/device-identity.ts | 9 +- packages/kernel/src/device.ts | 11 +- ...owser-provider-dispatch-disclosure.test.ts | 2 +- ...-browser-provider-record-retention.test.ts | 2 +- .../platform-web/src/__tests__/test-utils.ts | 2 +- .../src/agent-browser-audio-probe.ts | 5 +- .../src/agent-browser-provider-rects.test.ts | 2 +- .../src/agent-browser-provider.test.ts | 2 +- .../src/agent-browser-provider.ts | 6 +- .../src/agent-browser-snapshot.ts | 2 +- packages/platform-web/src/provider.ts | 8 - packages/platform-web/src/resolve-provider.ts | 2 +- packages/plugins/src/discovery.ts | 6 +- packages/plugins/src/platform.test.ts | 47 +---- packages/plugins/src/platform.ts | 71 ++++---- packages/plugins/src/registry.ts | 78 ++------ packages/plugins/src/store.ts | 5 +- packages/plugins/src/validate.ts | 117 ++++++------ .../install-workspace-replay-plugins.test.ts | 2 +- src/__tests__/cli-web.test.ts | 20 ++- .../contracts/platform-plugin-parity.test.ts | 64 ++++--- .../provider-device-runtimes.test.ts | 9 +- .../test-utils/absent-platform-registry.ts | 8 - src/builtin-provider-plugins.test.ts | 10 +- src/core/interactors.ts | 27 +-- .../builtin-platform-plugin-set.ts | 9 + src/core/interactors/register-builtins.ts | 28 +-- ...rm-plugin-registry-optional-family.test.ts | 42 ++--- ...m-plugin-registry-provider-routing.test.ts | 34 ++-- src/core/platform-plugin-registry.ts | 64 +------ src/daemon-composition-credentials.test.ts | 3 +- ...daemon-composition-platform-plugin.test.ts | 166 ++++++++++++++++++ src/daemon-composition.test.ts | 3 +- src/daemon-composition.ts | 18 +- src/daemon-runtime-limrun-public-http.test.ts | 5 +- src/host.test.ts | 3 +- ...-runtime-gateway-gesture-admission.test.ts | 4 +- ...m-runtime-local-application-interactors.ts | 6 +- src/platform-runtime-managed-web-backend.ts | 17 +- src/platform-runtime-operation-host.ts | 8 +- src/platform-runtime-web-provider.fixtures.ts | 11 +- src/platform-runtime.test.ts | 9 +- src/platform-runtime.ts | 38 ++-- src/platform-runtime/platform-plugins.ts | 102 +++++++++++ src/platform-runtime/request-providers.ts | 13 +- src/provider-device-runtimes.ts | 44 +---- .../integration/provider-scenarios/harness.ts | 7 +- 54 files changed, 681 insertions(+), 532 deletions(-) delete mode 100644 src/__tests__/test-utils/absent-platform-registry.ts create mode 100644 src/core/interactors/builtin-platform-plugin-set.ts create mode 100644 src/daemon-composition-platform-plugin.test.ts create mode 100644 src/platform-runtime/platform-plugins.ts diff --git a/packages/contracts/src/platform-module.ts b/packages/contracts/src/platform-module.ts index fe0c69bac0..0d1d4cd6ab 100644 --- a/packages/contracts/src/platform-module.ts +++ b/packages/contracts/src/platform-module.ts @@ -100,7 +100,7 @@ export function createPlatformModuleRegistry; + +export type PlatformPluginSet = + PlatformModuleRegistry<{ family: Platform; plugin: Plugin }>; + +export type PlatformModuleSelection = Readonly<{ + interactors: PlatformPluginSet; + web: WebPlatformSelection; + inventoryModules: readonly InventoryPlatformModule[]; + runtimeModules: readonly PlatformRuntimeModule[]; + reportAbsent(family: Platform): AppError; + assertSelectionCurrent(family: Platform): void; +}>; diff --git a/packages/contracts/src/plugin-installation.ts b/packages/contracts/src/plugin-installation.ts index 94350cd564..892f669b7c 100644 --- a/packages/contracts/src/plugin-installation.ts +++ b/packages/contracts/src/plugin-installation.ts @@ -66,7 +66,7 @@ export function pluginInstallationHint( const installCommand = pluginInstallCommand(declaration, coreVersion); return { installCommand, - hint: `Install:\n ${installCommand}\nThen retry the original command. If a local daemon is already running, close its sessions and run agent-device daemon stop with the same --state-dir before retrying.`, + hint: `Install:\n ${installCommand}\nThen retry your original command. If a local daemon is already running, close its sessions and run agent-device daemon stop with the same --state-dir before retrying.`, }; } /** diff --git a/packages/daemon/src/server/http/daemon-runtime-deps.ts b/packages/daemon/src/server/http/daemon-runtime-deps.ts index 1b5844fbba..4ec0615867 100644 --- a/packages/daemon/src/server/http/daemon-runtime-deps.ts +++ b/packages/daemon/src/server/http/daemon-runtime-deps.ts @@ -37,7 +37,7 @@ export type DaemonRuntimeDeps = Readonly<{ shutdownProviderRuntimes: () => Promise; /** * Every provider plugin the composition saw, active or failed. Data only: this server publishes - * it in the daemon registration and records each failed entry as a `provider_plugin_failed` + * it in the daemon registration and records each failed entry as a plugin failure * diagnostic, so log emission stays in this module. */ pluginInventory: readonly PluginInventoryEntry[]; diff --git a/packages/daemon/src/server/http/daemon-runtime.ts b/packages/daemon/src/server/http/daemon-runtime.ts index 8ada67cf48..38629ff5b8 100644 --- a/packages/daemon/src/server/http/daemon-runtime.ts +++ b/packages/daemon/src/server/http/daemon-runtime.ts @@ -202,6 +202,7 @@ async function startDaemonRuntimeOnHost( emitDaemonDiagnostic, finishDaemonRegistration, flushDaemonStartupDiagnostics, + reportPluginStartupFailures, } = await import('./daemon-startup-diagnostics.ts'); const daemonPaths = resolveDaemonPaths(env.AGENT_DEVICE_STATE_DIR, { env, cwd: host.cwd }); const { baseDir, infoPath, logPath, sessionsDir } = daemonPaths; @@ -665,18 +666,7 @@ async function startDaemonRuntimeOnHost( options.startupProgress?.close(); stopMetadataLossWatch = armDaemonMetadataLossWatch(baseDir, infoPath, logPath, daemonIdentity); await flushDaemonStartupDiagnostics(logPath, startupDiagnostics); - for (const plugin of deps.pluginInventory.filter(({ state }) => state === 'failed')) { - await emitDaemonDiagnostic(logPath, 'provider_plugin_failed', { - provider: plugin.provider, - platform: plugin.platform, - package: plugin.package, - source: plugin.source, - code: plugin.error?.code, - reason: plugin.error?.reason, - message: plugin.error?.message, - hint: plugin.error?.hint, - }); - } + await reportPluginStartupFailures(logPath, deps.pluginInventory); // After publication: publishDaemonInfo truncates daemon.log, so anything // written before it is lost — including reconciliation diagnostics. await reconcileDeviceClaimsForDaemonStartup( diff --git a/packages/daemon/src/server/http/daemon-startup-diagnostics.ts b/packages/daemon/src/server/http/daemon-startup-diagnostics.ts index a91a44d103..553722e58c 100644 --- a/packages/daemon/src/server/http/daemon-startup-diagnostics.ts +++ b/packages/daemon/src/server/http/daemon-startup-diagnostics.ts @@ -1,3 +1,4 @@ +import type { PluginInventoryEntry } from '@agent-device/contracts/plugin-inventory'; import { normalizeError } from '@agent-device/kernel/errors'; import { emitDiagnostic, @@ -25,6 +26,28 @@ export async function flushDaemonStartupDiagnostics( }); } +export async function reportPluginStartupFailures( + logPath: string, + inventory: readonly PluginInventoryEntry[], +): Promise { + for (const plugin of inventory.filter((plugin) => plugin.state === 'failed')) { + await emitDaemonDiagnostic( + logPath, + plugin.platform ? 'platform_plugin_failed' : 'provider_plugin_failed', + { + provider: plugin.provider, + platform: plugin.platform, + package: plugin.package, + source: plugin.source, + code: plugin.error.code, + reason: plugin.error.reason, + message: plugin.error.message, + hint: plugin.error.hint, + }, + ); + } +} + /** * Records one daemon-level event outside any request scope, with debug forced on. * `level` is the event's own severity; it defaults to `warn` because these events are all daemon diff --git a/packages/kernel/package.json b/packages/kernel/package.json index 53d24ec0fc..ec3579b4a8 100644 --- a/packages/kernel/package.json +++ b/packages/kernel/package.json @@ -17,6 +17,10 @@ "types": "./src/contracts.ts", "default": "./src/contracts.ts" }, + "./device-identity": { + "types": "./src/device-identity.ts", + "default": "./src/device-identity.ts" + }, "./device": { "types": "./src/device.ts", "default": "./src/device.ts" diff --git a/packages/kernel/src/device-identity.ts b/packages/kernel/src/device-identity.ts index 903dda9cd4..0963387965 100644 --- a/packages/kernel/src/device-identity.ts +++ b/packages/kernel/src/device-identity.ts @@ -1,4 +1,11 @@ -import type { AppleOS, DeviceInfo, DeviceKind, DeviceTarget, Platform } from './device.ts'; +import type { AppleOS, DeviceInfo, DeviceKind, DeviceTarget } from './device.ts'; + +export const PLATFORMS = ['apple', 'android', 'harmonyos', 'vega', 'linux', 'web'] as const; +export type Platform = (typeof PLATFORMS)[number]; + +export function isPlatform(value: unknown): value is Platform { + return (PLATFORMS as readonly unknown[]).includes(value); +} export type DeviceShape = Readonly<{ family: Platform; diff --git a/packages/kernel/src/device.ts b/packages/kernel/src/device.ts index 9ba9d4ddee..7f6c7b400c 100644 --- a/packages/kernel/src/device.ts +++ b/packages/kernel/src/device.ts @@ -1,9 +1,12 @@ import crypto from 'node:crypto'; import { AppError } from './errors.ts'; -import type { DeviceIdentity } from './device-identity.ts'; import type { EnvMap } from './source-value.ts'; +import { PLATFORMS, isPlatform, type DeviceIdentity, type Platform } from './device-identity.ts'; export { + PLATFORMS, + isPlatform, + type Platform, deviceIdentity, deviceIdentityKey, deviceShape, @@ -22,8 +25,6 @@ const APPLE_OS_VALUES = ['ios', 'ipados', 'tvos', 'watchos', 'visionos', 'macos' export type AppleOS = (typeof APPLE_OS_VALUES)[number]; // Internal device platforms. Apple OSes collapse to a single `apple` platform; the // `appleOs` field on DeviceInfo is the sole OS discriminant. -export const PLATFORMS = ['apple', 'android', 'harmonyos', 'vega', 'linux', 'web'] as const; -export type Platform = (typeof PLATFORMS)[number]; // The PUBLIC leaf platform strings the daemon emits and clients parse (approach b: // output never changes). Equals the pre-collapse `Platform` set. export const PUBLIC_PLATFORMS = [ @@ -376,10 +377,6 @@ export function resolveDeviceAppleOs( /** * @internal Type guard exposed for unit tests. */ -export function isPlatform(value: unknown): value is Platform { - // Internal device-platform membership derived from the canonical PLATFORMS tuple. - return (PLATFORMS as readonly unknown[]).includes(value); -} export function isPublicPlatform(value: unknown): value is PublicPlatform { // The PUBLIC leaf strings a daemon response carries (approach b). Used by the client diff --git a/packages/platform-web/src/__tests__/agent-browser-provider-dispatch-disclosure.test.ts b/packages/platform-web/src/__tests__/agent-browser-provider-dispatch-disclosure.test.ts index fae86dca32..3e660d0e58 100644 --- a/packages/platform-web/src/__tests__/agent-browser-provider-dispatch-disclosure.test.ts +++ b/packages/platform-web/src/__tests__/agent-browser-provider-dispatch-disclosure.test.ts @@ -20,7 +20,7 @@ import { withManagedAgentBrowserProvider, } from './test-utils.ts'; import { createAgentBrowserWebProvider } from '../agent-browser-provider.ts'; -import type { WebProvider } from '../provider.ts'; +import type { WebProvider } from '@agent-device/contracts/web-provider'; bindTestCommandHost(); diff --git a/packages/platform-web/src/__tests__/agent-browser-provider-record-retention.test.ts b/packages/platform-web/src/__tests__/agent-browser-provider-record-retention.test.ts index e6a573bcd5..589b213184 100644 --- a/packages/platform-web/src/__tests__/agent-browser-provider-record-retention.test.ts +++ b/packages/platform-web/src/__tests__/agent-browser-provider-record-retention.test.ts @@ -19,7 +19,7 @@ import { import { withCommandExecutorOverride, type ExecResult } from '@agent-device/host-kit/command'; import { MANAGED_WEB_BROWSER_PROCESS_PURPOSE } from '../agent-browser-process-record.ts'; import { createAgentBrowserWebProvider } from '../agent-browser-provider.ts'; -import type { WebProvider } from '../provider.ts'; +import type { WebProvider } from '@agent-device/contracts/web-provider'; import { agentBrowserJsonResult, mkdtempForTestSync } from './test-utils.ts'; bindTestCommandHost(); diff --git a/packages/platform-web/src/__tests__/test-utils.ts b/packages/platform-web/src/__tests__/test-utils.ts index b1ce155074..240bc5ace3 100644 --- a/packages/platform-web/src/__tests__/test-utils.ts +++ b/packages/platform-web/src/__tests__/test-utils.ts @@ -11,7 +11,7 @@ import type { OwnedProcessRecordStore } from '@agent-device/host-kit/process'; import { installFakeManagedAgentBrowser } from '@agent-device/test-kit'; import { vi } from 'vitest'; import { createAgentBrowserWebProvider } from '../agent-browser-provider.ts'; -import type { WebProvider } from '../provider.ts'; +import type { WebProvider } from '@agent-device/contracts/web-provider'; export function mkdtempForTestSync(prefix: string): string { return fs.mkdtempSync(path.join(os.tmpdir(), prefix)); diff --git a/packages/platform-web/src/agent-browser-audio-probe.ts b/packages/platform-web/src/agent-browser-audio-probe.ts index f1cbeedb0c..87e2a434c4 100644 --- a/packages/platform-web/src/agent-browser-audio-probe.ts +++ b/packages/platform-web/src/agent-browser-audio-probe.ts @@ -3,7 +3,10 @@ import { normalizeAudioProbeRecord, } from '@agent-device/contracts/audio-probe-result'; import { isJsonObject, type JsonObject } from './json-utils.ts'; -import type { WebAudioProbeOptions, WebAudioProbeResult } from './provider.ts'; +import type { + WebAudioProbeOptions, + WebAudioProbeResult, +} from '@agent-device/contracts/web-provider'; const audioProbePageScriptFunctions = [ audioProbeDbfs, diff --git a/packages/platform-web/src/agent-browser-provider-rects.test.ts b/packages/platform-web/src/agent-browser-provider-rects.test.ts index 253ede4791..6faf16b0c3 100644 --- a/packages/platform-web/src/agent-browser-provider-rects.test.ts +++ b/packages/platform-web/src/agent-browser-provider-rects.test.ts @@ -19,7 +19,7 @@ vi.mock('./agent-browser-lifecycle.ts', async (importOriginal) => { }); import { createAgentBrowserWebProvider } from './agent-browser-provider.ts'; -import type { WebSnapshotResult } from './provider.ts'; +import type { WebSnapshotResult } from '@agent-device/contracts/web-provider'; import { withCommandExecutorOverride, type ExecResult } from '@agent-device/host-kit/command'; import { AppError } from '@agent-device/kernel/errors'; diff --git a/packages/platform-web/src/agent-browser-provider.test.ts b/packages/platform-web/src/agent-browser-provider.test.ts index e706825714..7f883aa828 100644 --- a/packages/platform-web/src/agent-browser-provider.test.ts +++ b/packages/platform-web/src/agent-browser-provider.test.ts @@ -23,7 +23,7 @@ vi.mock('./agent-browser-lifecycle.ts', async (importOriginal) => { import { createAgentBrowserWebProvider } from './agent-browser-provider.ts'; import { buildSelectFocusedContentEvalScript } from './agent-browser-select-content.ts'; -import type { WebSnapshotResult } from './provider.ts'; +import type { WebSnapshotResult } from '@agent-device/contracts/web-provider'; import { withCommandExecutorOverride, type ExecResult } from '@agent-device/host-kit/command'; import { AppError, createRequestCanceledError } from '@agent-device/kernel/errors'; import { buildSelectorChainForNode, resolveRecordedTarget } from '@agent-device/selectors'; diff --git a/packages/platform-web/src/agent-browser-provider.ts b/packages/platform-web/src/agent-browser-provider.ts index d83e3934dc..098d5cf6dd 100644 --- a/packages/platform-web/src/agent-browser-provider.ts +++ b/packages/platform-web/src/agent-browser-provider.ts @@ -27,7 +27,11 @@ import { readStringProperty, type JsonObject, } from './json-utils.ts'; -import type { WebProvider, WebSnapshotOptions, WebSnapshotResult } from './provider.ts'; +import type { + WebProvider, + WebSnapshotOptions, + WebSnapshotResult, +} from '@agent-device/contracts/web-provider'; import { getManagedAgentBrowserStatus, mapManagedAgentBrowserError, diff --git a/packages/platform-web/src/agent-browser-snapshot.ts b/packages/platform-web/src/agent-browser-snapshot.ts index 769a24a5e0..49e0758415 100644 --- a/packages/platform-web/src/agent-browser-snapshot.ts +++ b/packages/platform-web/src/agent-browser-snapshot.ts @@ -7,7 +7,7 @@ import { readStringProperty, type JsonObject, } from './json-utils.ts'; -import type { WebSnapshotResult } from './provider.ts'; +import type { WebSnapshotResult } from '@agent-device/contracts/web-provider'; type SnapshotRefRecord = { ref: string; diff --git a/packages/platform-web/src/provider.ts b/packages/platform-web/src/provider.ts index 360e559f7f..fe57e14dcf 100644 --- a/packages/platform-web/src/provider.ts +++ b/packages/platform-web/src/provider.ts @@ -2,14 +2,6 @@ import { AppError } from '@agent-device/kernel/errors'; import { createScopedProvider } from '@agent-device/kernel/scoped-provider'; import type { WebProvider } from '@agent-device/contracts/web-provider'; -export type { - WebSnapshotOptions, - WebSnapshotResult, - WebAudioProbeOptions, - WebAudioProbeResult, - WebProvider, -} from '@agent-device/contracts/web-provider'; - /** * The un-composed fallback: a request that reaches a web device without a composed provider is a * composition bug, so it fails closed instead of borrowing a host it was never given (#3794). diff --git a/packages/platform-web/src/resolve-provider.ts b/packages/platform-web/src/resolve-provider.ts index cf5e05e12d..111e786256 100644 --- a/packages/platform-web/src/resolve-provider.ts +++ b/packages/platform-web/src/resolve-provider.ts @@ -1,5 +1,5 @@ import type { HostEnvironment } from '@agent-device/kernel/source-value'; -import type { WebProvider } from './provider.ts'; +import type { WebProvider } from '@agent-device/contracts/web-provider'; /** * The provider a web request composed for itself, or `undefined` outside one. A reader that must diff --git a/packages/plugins/src/discovery.ts b/packages/plugins/src/discovery.ts index 5625829a9a..09edb54a08 100644 --- a/packages/plugins/src/discovery.ts +++ b/packages/plugins/src/discovery.ts @@ -10,10 +10,8 @@ import { readPluginPackageClaims, type PluggedClaim } from './validate.ts'; * order. Read before any import: the apiVersion must be the supported one, and every declared claim * must be unreserved. After the factory runs, its returned claims must equal these, in any order. */ -export async function readAgentDeviceClaims( - manifest: Record, -): Promise { - return await readPluginPackageClaims(manifest['agent-device']); +export function readAgentDeviceClaims(manifest: Record): readonly PluggedClaim[] { + return readPluginPackageClaims(manifest['agent-device']); } /** diff --git a/packages/plugins/src/platform.test.ts b/packages/plugins/src/platform.test.ts index f52b53ab14..897f37bddb 100644 --- a/packages/plugins/src/platform.test.ts +++ b/packages/plugins/src/platform.test.ts @@ -1,15 +1,11 @@ import { expect, test } from 'vitest'; import { pluginHome, selectPlugin } from '@agent-device/test-kit'; -import { missingOptionalPlatformError } from '@agent-device/contracts/plugin-installation'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; -import { createPluginSelectionGuard, storePluginCandidates } from './store.ts'; +import { storePluginCandidates } from './store.ts'; import { resolveProviderPlugins, startProviderRegistry } from './registry.ts'; const WEB_PACKAGE = '@agent-device/web'; const stateDir = '/fixture-state'; -const reportAbsent = (family: Parameters[0]) => - missingOptionalPlatformError(family, '0.22.0'); - const platformClaim = `{ kind: 'platform', family: 'web', @@ -55,7 +51,6 @@ async function startStore(env: HostEnvironment['env']) { emitDiagnostic: () => {}, withDiagnosticTimer: async (_phase, run) => await run(), }, - assertSelectionCurrent: createPluginSelectionGuard(candidates, env), adaptWebDriver: async () => { throw new Error('unexpected WebDriver'); }, @@ -76,8 +71,8 @@ test('a managed platform registers its inventory against the supplied state dire credentials: { variables: [], byBackend: {} }, }, ]); - const platform = registry.resolvePlatform('web', reportAbsent, WEB_PACKAGE); - if (platform.family !== 'web') throw new Error('expected web'); + const [platform] = registry.platforms; + if (platform?.family !== 'web') throw new Error('expected web'); const inventory = await platform.inventoryModule.loadInventory(); expect( await inventory.discover( @@ -94,38 +89,9 @@ test('a managed platform registers its inventory against the supplied state dire await expect(closing).resolves.toEqual([ { platform: 'web', source: 'store', shutdown: { status: 'ok' }, dispose: { status: 'ok' } }, ]); - expect(() => registry.resolvePlatform('web', reportAbsent, WEB_PACKAGE)).toThrow( - expect.objectContaining({ details: { reason: 'plugin-registry-closed' } }), - ); -}); - -test('a missing platform has an install hint, and adding it to a running set requires restart', async () => { - const { home, env } = pluginHome(); - const registry = await startStore(env); - expect(() => registry.resolvePlatform('web', reportAbsent, WEB_PACKAGE)).toThrow( - expect.objectContaining({ - details: expect.objectContaining({ - reason: 'plugin-not-installed', - installCommand: 'agent-device plugins add @agent-device/web', - }), - }), - ); - selectWeb(home); - expect(() => registry.resolvePlatform('web', reportAbsent, WEB_PACKAGE)).toThrow( - expect.objectContaining({ - details: expect.objectContaining({ reason: 'daemon-plugin-set-stale', package: WEB_PACKAGE }), - }), - ); - await registry.close(); }); test.each([ - [ - 'required family', - 'apple', - platformClaim.replace("family: 'web'", "family: 'apple'"), - 'reserved_platform', - ], ['unknown family', 'example', platformClaim, 'invalid_plugin'], ['factory mismatch', 'linux', platformClaim, 'invalid_plugin'], [ @@ -170,11 +136,6 @@ test('a below-floor package retains its platform claim without importing its ent { platform: 'web', state: 'failed', error: { reason: 'node-below-floor' } }, { platform: 'web', state: 'failed', error: { reason: 'duplicate_platform' } }, ]); - expect(() => registry.resolvePlatform('web', reportAbsent, WEB_PACKAGE)).toThrow( - expect.objectContaining({ - details: expect.objectContaining({ reason: 'node-below-floor', package: WEB_PACKAGE }), - }), - ); await registry.close(); }); @@ -198,6 +159,6 @@ test('platform and replay claims in one package activate independently', async ( { platform: 'web', state: 'active' }, { backend: 'fixture', state: 'failed', error: { reason: 'plugin_setup_failed' } }, ]); - expect(registry.resolvePlatform('web', reportAbsent, WEB_PACKAGE).family).toBe('web'); + expect(registry.platforms.map(({ family }) => family)).toEqual(['web']); await registry.close(); }); diff --git a/packages/plugins/src/platform.ts b/packages/plugins/src/platform.ts index ed51d0d3e8..575bedb6ca 100644 --- a/packages/plugins/src/platform.ts +++ b/packages/plugins/src/platform.ts @@ -1,7 +1,5 @@ -import type { - InventoryPlatformModule, - OptionalPlatform, -} from '@agent-device/contracts/platform-module'; +import type { InventoryPlatformModule } from '@agent-device/contracts/platform-module'; +import type { Platform } from '@agent-device/kernel/device'; import type { PlatformPlugin, WebPlatformOperations, @@ -34,46 +32,43 @@ export type PlatformHost = HostEnvironment & withDiagnosticTimer: typeof withDiagnosticTimer; }>; -export type PlatformSetup = - Family extends OptionalPlatform - ? Readonly<{ +export type PlatformSetup = Family extends Platform + ? Readonly<{ + family: Family; + inventoryModule: Readonly<{ family: Family; - inventoryModule: Readonly<{ - family: Family; - loadInventory(...args: never[]): Promise; - }>; - runtimeModule: Readonly<{ - family: Family; - loadRuntime(...args: never[]): Promise; - }>; - createInteractor(...args: never[]): Promise; - }> & - (Family extends 'web' - ? Readonly<{ - withRequestProvider(provider: WebProvider, task: () => Promise): Promise; - operations: WebPlatformOperations; - }> - : unknown) - : never; - -/** Full module types used after the composing registry validates the declared family and loaders. */ -export type RegisteredPlatformSetup = - Family extends OptionalPlatform - ? Family extends 'web' - ? WebPlatformRegistration - : Omit, 'inventoryModule' | 'runtimeModule' | 'createInteractor'> & - Readonly<{ - createInteractor: PlatformPlugin['createInteractor']; - inventoryModule: InventoryPlatformModule; - runtimeModule: PlatformRuntimeModule & { readonly family: Family }; + loadInventory(...args: never[]): Promise; + }>; + runtimeModule: Readonly<{ + family: Family; + loadRuntime(...args: never[]): Promise; + }>; + createInteractor(...args: never[]): Promise; + }> & + (Family extends 'web' + ? Readonly<{ + withRequestProvider(provider: WebProvider, task: () => Promise): Promise; + operations: WebPlatformOperations; }> - : never; + : unknown) + : never; + +export type RegisteredPlatformSetup = Family extends Platform + ? Family extends 'web' + ? WebPlatformRegistration + : Readonly<{ + family: Family; + createInteractor: PlatformPlugin['createInteractor']; + inventoryModule: InventoryPlatformModule; + runtimeModule: PlatformRuntimeModule & { readonly family: Family }; + }> + : never; export type PlatformContribution = { - [Family in OptionalPlatform]: Readonly<{ + [Family in Platform]: Readonly<{ kind: 'platform'; family: Family; /** Registers modules and operations. Setup itself does not start or install the backend. */ setup(host: PlatformHost): PlatformSetup | Promise>; }>; -}[OptionalPlatform]; +}[Platform]; diff --git a/packages/plugins/src/registry.ts b/packages/plugins/src/registry.ts index 1bc15e8bf5..ff211ed3a9 100644 --- a/packages/plugins/src/registry.ts +++ b/packages/plugins/src/registry.ts @@ -1,9 +1,9 @@ -import type { OptionalPlatform } from '@agent-device/contracts/platform-module'; import type { PlatformHost, RegisteredPlatformSetup } from './platform.ts'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; -import type { - ReplayExecution, - ReplayExecutionResolver, +import { + NATIVE_REPLAY_BACKEND, + type ReplayExecution, + type ReplayExecutionResolver, } from '@agent-device/contracts/replay-execution'; import type { ReplayBackend } from '@agent-device/contracts/replay-backend'; import type { @@ -169,11 +169,6 @@ export type ResolvedProviderPlugins = Readonly<{ export type ProviderRegistry = Readonly<{ registrations: readonly ProviderRegistration[]; platforms: readonly RegisteredPlatformSetup[]; - resolvePlatform( - family: OptionalPlatform, - reportAbsent: (family: OptionalPlatform) => AppError, - packageName?: string, - ): RegisteredPlatformSetup; resolveReplayBackend: ReplayBackendResolver; resolveReplayExecution: ReplayExecutionResolver; claimedProviders: readonly string[]; @@ -199,7 +194,7 @@ export async function resolveProviderPlugins( for (const candidate of candidates) { const slot: Slot = { candidate, claims: [] }; slots.push(slot); - await reserveDeclaredClaims(slot, claimed, !candidate.dormant); + reserveDeclaredClaims(slot, claimed, !candidate.dormant); if (!candidate.dormant) await loadSlot(slot, claimed); } @@ -232,13 +227,9 @@ export async function resolveProviderPlugins( * of a kind and id wins; a later one is recorded as failed against its own slot, and so is a claim of * an id the host reserves. A dormant slot holds its claims without listing them. */ -async function reserveDeclaredClaims( - slot: Slot, - claimed: ClaimedClaims, - list: boolean, -): Promise { +function reserveDeclaredClaims(slot: Slot, claimed: ClaimedClaims, list: boolean): void { for (const claim of slot.candidate.declaredClaims ?? []) { - const obstacle = await claimObstacle(claimed, claim); + const obstacle = claimObstacle(claimed, claim); if (obstacle !== undefined) { if (list) slot.claims.push({ ...claim, slot, failure: obstacle }); continue; @@ -251,11 +242,8 @@ async function reserveDeclaredClaims( * Why this claim cannot be held: its id belongs to the host, or its space already names it. Nothing * is reserved when there is an obstacle. */ -async function claimObstacle( - claimed: ClaimedClaims, - claim: PluggedClaim, -): Promise { - const reserved = await reservedClaimError(claim); +function claimObstacle(claimed: ClaimedClaims, claim: PluggedClaim): AppError | undefined { + const reserved = reservedClaimError(claim); if (reserved !== undefined) return reserved; return reserveClaim(claimed, claim) ? undefined : duplicateClaimError(claim); } @@ -278,7 +266,7 @@ async function loadSlot(slot: Slot, claimed: ClaimedClaims): Promise { let raw: unknown; try { raw = await slot.candidate.load(); - const returnedClaims = await validateAgentDevicePlugin(raw); + const returnedClaims = validateAgentDevicePlugin(raw); assertDeclaredClaims(slot.candidate, returnedClaims); for (const { contribution, ...claim } of returnedClaims) { const reserved = slot.claims.find( @@ -302,7 +290,7 @@ async function loadSlot(slot: Slot, claimed: ClaimedClaims): Promise { // A reservation reason (a duplicate or reserved id) is the actionable one; keep it. if (claim.contribution === undefined) claim.failure ??= slot.failure; } - await nameFailedClaims(slot, claimed, raw); + nameFailedClaims(slot, claimed, raw); } } @@ -313,9 +301,9 @@ async function loadSlot(slot: Slot, claimed: ClaimedClaims): Promise { * before the load and is left alone. Each claim carries the slot's own reason, which is the one the * author can act on. */ -async function nameFailedClaims(slot: Slot, claimed: ClaimedClaims, raw: unknown): Promise { +function nameFailedClaims(slot: Slot, claimed: ClaimedClaims, raw: unknown): void { if (slot.candidate.declaredClaims !== undefined || slot.claims.length > 0) return; - for (const claim of await readableClaimsOfValue(raw)) { + for (const claim of readableClaimsOfValue(raw)) { reserveClaim(claimed, claim); slot.claims.push({ ...claim, slot, failure: slot.failure }); } @@ -371,24 +359,6 @@ export async function startProviderRegistry( claims.flatMap(({ platformSetup }) => (platformSetup ? [platformSetup] : [])), ), ), - resolvePlatform: (family, reportAbsent, packageName) => { - if (closed) - throw new AppError('COMMAND_FAILED', 'Plugin registry is closed', { - reason: 'plugin-registry-closed', - }); - const claim = findClaim( - resolved, - { kind: 'platform', id: family }, - packageName, - policy.assertSelectionCurrent, - ); - if (!claim) throw reportAbsent(family); - if (claim.failure !== undefined) { - throw platformClaimError(claim); - } - if (!claim.platformSetup) throw invalidPlugin(`Platform was not set up: ${family}`); - return claim.platformSetup; - }, claimedProviders: resolved.claimedProviders, inventory, resolveReplayBackend: async (id, host, packageName) => { @@ -405,7 +375,6 @@ export async function startProviderRegistry( return await resolveRegisteredReplayBackend(claim, refreshInventory, host); }, resolveReplayExecution: async (packageName) => { - const { NATIVE_REPLAY_BACKEND } = await import('@agent-device/contracts/replay-execution'); if (closed) throw new AppError('COMMAND_FAILED', 'Plugin registry is closed', { reason: 'plugin-registry-closed', @@ -477,10 +446,13 @@ async function setUpClaim( } if (contribution.kind === 'platform') { if (scope === 'replay-backends') return; - if (!policy.platformHost) throw invalidPlugin('Platform setup requires a platform host'); + if (!policy.platformHost) + throw new AppError('COMMAND_FAILED', 'Platform setup requires a platform host', { + reason: 'platform_host_missing', + }); const result = await contribution.setup(policy.platformHost); - validateClaimSetup(claim, result); - claim.platformSetup = Object.freeze(result as RegisteredPlatformSetup); + validateClaimSetup({ kind: contribution.kind, id: contribution.family }, result); + claim.platformSetup = Object.freeze(result); return; } if (scope === 'platforms') return; @@ -598,16 +570,6 @@ function requireReplayClaim( }); } -function platformClaimError(claim: Claim): AppError { - const error = asPluginFailure(claim.failure, 'plugin_load_failed'); - return new AppError( - error.code, - error.message, - { ...error.details, ...identityOfClaim(claim), package: claim.slot.candidate.package }, - error, - ); -} - function replayClaimError(claim: Claim): AppError { const error = asPluginFailure(claim.failure ?? claim.replayFailure, 'plugin_load_failed'); const packageName = claim.slot.candidate.package; @@ -841,5 +803,3 @@ function once(run: () => Promise): () => Promise { let started: Promise | undefined; return () => (started ??= run()); } - -export type { RegisteredPlatformSetup } from './platform.ts'; diff --git a/packages/plugins/src/store.ts b/packages/plugins/src/store.ts index 66866ad7f7..c98b9664b6 100644 --- a/packages/plugins/src/store.ts +++ b/packages/plugins/src/store.ts @@ -162,10 +162,9 @@ async function describeInstallation( throw new AppError('INVALID_ARGS', `Invalid artifact plugin metadata: ${name}`, { reason: 'invalid_plugin', }); - // Before any import: the supported contract version, the Node floor, and the static claims. The - // claims the factory returns must equal these once it runs with its options. + // Record the declared claims before checking the Node floor or importing the factory. const entry = discoverPluginEntry(directory); - const declaredClaims = await readAgentDeviceClaims(packageJson); + const declaredClaims = readAgentDeviceClaims(packageJson); return { name, version, diff --git a/packages/plugins/src/validate.ts b/packages/plugins/src/validate.ts index 6917f8b935..28d579ddf3 100644 --- a/packages/plugins/src/validate.ts +++ b/packages/plugins/src/validate.ts @@ -1,3 +1,7 @@ +import type { RegisteredPlatformSetup } from './platform.ts'; +import { isPlatform, type Platform } from '@agent-device/kernel/device-identity'; +import { NATIVE_REPLAY_BACKEND } from '@agent-device/contracts/replay-execution'; +import type { WebPlatformOperations } from '@agent-device/contracts/platform-plugin'; import type { ReplayExecution } from '@agent-device/contracts/replay-execution'; import type { ReplayBackend } from '@agent-device/contracts/replay-backend'; import type { ReplayBackendSetup, ReplayExecutionSetup } from './replay-backend.ts'; @@ -45,18 +49,8 @@ const CLAIM_KINDS: Readonly> = { platform: { metadataField: 'platform', contributionIdField: 'family', - reservedError: async (id) => { - const [{ isPlatform }, { isOptionalPlatform }] = await Promise.all([ - import('@agent-device/kernel/device'), - import('@agent-device/contracts/platform-module'), - ]); - if (!isPlatform(id)) return invalidPlugin(`Unknown platform family: ${id}`); - if (isOptionalPlatform(id)) return undefined; - return new AppError('INVALID_ARGS', `Platform family is reserved for core: ${id}`, { - reason: 'reserved_platform', - platform: id, - }); - }, + reservedError: (id) => + isPlatform(id) ? undefined : invalidPlugin(`Unknown platform family: ${id}`), duplicateReason: 'duplicate_platform', identityFor: (id) => ({ platform: id }), readMetadata: (value) => readableClaimId(value, 'platform'), @@ -72,9 +66,8 @@ const CLAIM_KINDS: Readonly> = { 'replay-backend': { metadataField: 'replayBackend', contributionIdField: 'backend', - reservedError: async (id) => { - const { NATIVE_REPLAY_BACKEND } = await import('@agent-device/contracts/replay-execution'); - return id === NATIVE_REPLAY_BACKEND + reservedError: (id) => + id === NATIVE_REPLAY_BACKEND ? new AppError( 'INVALID_ARGS', `Replay backend id is reserved for native execution: ${id}`, @@ -83,8 +76,7 @@ const CLAIM_KINDS: Readonly> = { backend: id, }, ) - : undefined; - }, + : undefined, duplicateReason: 'duplicate_replay_backend', identityFor: (id) => ({ backend: id }), readMetadata: (value) => readableClaimId(value, 'replayBackend'), @@ -106,13 +98,12 @@ const CLAIM_KINDS: Readonly> = { contributionIdField: 'id', duplicateReason: 'duplicate_replay_execution', identityFor: (id) => ({ backend: id }), - readMetadata: async (value) => { + readMetadata: (value) => { // One spelling for this claim: the id itself belongs to the kind, not to the package. if (value !== true) throw invalidPlugin('Plugin metadata replayExecution must be true'); - return (await import('@agent-device/contracts/replay-execution')).NATIVE_REPLAY_BACKEND; + return NATIVE_REPLAY_BACKEND; }, - readContribution: async (value) => { - const { NATIVE_REPLAY_BACKEND } = await import('@agent-device/contracts/replay-execution'); + readContribution: (value) => { if (value.id !== NATIVE_REPLAY_BACKEND) { throw invalidPlugin( `A replay-execution contribution must declare id ${NATIVE_REPLAY_BACKEND}`, @@ -140,15 +131,15 @@ type ClaimKindSpec = Readonly<{ /** The contribution field that spells this kind's id. */ contributionIdField: string; /** Ids no plugin may claim in this space. */ - reservedError?(id: string): AppError | undefined | Promise; + reservedError?(id: string): AppError | undefined; /** What a claim that loses this space's duplicate race reports. */ duplicateReason: string; /** How this space names the claim in the inventory and in cleanup outcomes. */ identityFor(id: string): ClaimIdentity; /** Reads the id out of the `agent-device` field. */ - readMetadata(value: unknown): string | Promise; + readMetadata(value: unknown): string; /** Validates one contribution of this kind and answers its claim. */ - readContribution(value: Record): PluggedClaim | Promise; + readContribution(value: Record): PluggedClaim; /** Checks what setup returned before the registry keeps the claim. */ validateSetup(value: unknown, id: string): void; }>; @@ -160,9 +151,9 @@ const CLAIM_KIND_ORDER = Object.keys(CLAIM_KINDS) as readonly ClaimKind[]; * The one validation of what a plugin factory returned, whichever source produced it: the whole * declaration is validated before any of its claims is published. */ -export async function validateAgentDevicePlugin( +export function validateAgentDevicePlugin( value: unknown, -): Promise { +): readonly (PluggedClaim & { contribution: Contribution })[] { if (!isRecord(value)) throw invalidPlugin('Plugin factory must return a plugin object'); if (value.apiVersion !== PLUGIN_API_VERSION) throw incompatiblePluginApi(value.apiVersion); if (!Array.isArray(value.contributes) || value.contributes.length === 0) { @@ -171,8 +162,8 @@ export async function validateAgentDevicePlugin( const keys = new Set(); const claims = []; for (const contribution of value.contributes as readonly unknown[]) { - const claim = await claimOfContribution(contribution); - await assertClaimAvailable(claim); + const claim = claimOfContribution(contribution); + assertClaimAvailable(claim); const key = claimKeyOf(claim); if (keys.has(key)) { throw invalidPlugin(`Plugin declares the same claim twice: ${key}`); @@ -184,11 +175,11 @@ export async function validateAgentDevicePlugin( } /** The claim a contribution names, after validating the contribution's own shape. */ -async function claimOfContribution(value: unknown): Promise { +function claimOfContribution(value: unknown): PluggedClaim { if (!isRecord(value)) throw invalidPlugin('Each contribution must be an object'); const spec = claimKindSpecOf(value.kind); if (spec === undefined) throw invalidPlugin(`Unknown contribution kind: ${String(value.kind)}`); - return await spec.readContribution(value); + return spec.readContribution(value); } /** One claim as the store's declared claims and the registry compare them: `kind:id`. */ @@ -197,13 +188,13 @@ export function claimKeyOf(claim: PluggedClaim): string { } /** Why a claim cannot be held at all: a reserved id belongs to the host, not to a package. */ -export async function reservedClaimError(claim: PluggedClaim): Promise { - return await CLAIM_KINDS[claim.kind].reservedError?.(claim.id); +export function reservedClaimError(claim: PluggedClaim): AppError | undefined { + return CLAIM_KINDS[claim.kind].reservedError?.(claim.id); } /** Whether anything may still claim this id: a reserved id belongs to the host, not to a package. */ -async function assertClaimAvailable(claim: PluggedClaim): Promise { - const reserved = await reservedClaimError(claim); +function assertClaimAvailable(claim: PluggedClaim): void { + const reserved = reservedClaimError(claim); if (reserved !== undefined) throw reserved; } @@ -212,12 +203,12 @@ async function assertClaimAvailable(claim: PluggedClaim): Promise { * a slot that failed before its claims were readable uses this, so the inventory and the plugin that * selected it can still say what it was meant to provide. */ -export async function readableClaimsOfValue(value: unknown): Promise { +export function readableClaimsOfValue(value: unknown): readonly PluggedClaim[] { if (!isRecord(value)) return []; const claims: PluggedClaim[] = [...versionTwoReplayClaims(value)]; for (const kind of CLAIM_KIND_ORDER) { const spec = CLAIM_KINDS[kind]; - const declared = await claimIdSpelledBy(kind, value[spec.metadataField]); + const declared = claimIdSpelledBy(kind, value[spec.metadataField]); if (declared !== undefined) { claims.push({ kind, id: declared }); continue; @@ -225,7 +216,7 @@ export async function readableClaimsOfValue(value: unknown): Promise): readonly Plugge } /** The id this value spells for a kind, or nothing when it does not spell one. */ -async function claimIdSpelledBy(kind: ClaimKind, value: unknown): Promise { +function claimIdSpelledBy(kind: ClaimKind, value: unknown): string | undefined { // The native claim's id belongs to the kind, so its metadata spells it as `true`. if (kind === 'replay-execution' && value === true) { - return (await import('@agent-device/contracts/replay-execution')).NATIVE_REPLAY_BACKEND; + return NATIVE_REPLAY_BACKEND; } return isClaimId(value) ? value : undefined; } @@ -269,6 +260,11 @@ export function identityOfClaim(claim: PluggedClaim): ClaimIdentity { } /** Checks a setup result against the kind that asked for it. */ +export function validateClaimSetup( + claim: PluggedClaim & { kind: 'platform' }, + value: unknown, +): asserts value is RegisteredPlatformSetup; +export function validateClaimSetup(claim: PluggedClaim, value: unknown): void; export function validateClaimSetup(claim: PluggedClaim, value: unknown): void { CLAIM_KINDS[claim.kind].validateSetup(value, claim.id); } @@ -278,7 +274,7 @@ export function validateClaimSetup(claim: PluggedClaim, value: unknown): void { * plus each static claim id, read through its own kind. Read before any import; after the factory * runs, its returned claims must equal these, in any order. */ -export async function readPluginPackageClaims(field: unknown): Promise { +export function readPluginPackageClaims(field: unknown): readonly PluggedClaim[] { if (!isRecord(field) || field.apiVersion !== PLUGIN_API_VERSION) { throw incompatiblePackageApi(field); } @@ -287,8 +283,8 @@ export async function readPluginPackageClaims(field: unknown): Promise = { + setup: true, + doctor: true, + cleanupOrphans: true, + browserLifecycleCheck: true, + createProvider: true, + resolveRequestProvider: true, +}; + +const PLATFORM_SETUP_CHECKS: Partial) => void>> = { + web(value) { + const operations = value.operations; + if ( + typeof value.withRequestProvider !== 'function' || + !isRecord(operations) || + Object.keys(WEB_OPERATIONS).some((operation) => typeof operations[operation] !== 'function') + ) { + throw invalidPlugin('Web platform setup must supply request scoping and web operations'); + } + }, +}; + function isClaimId(value: unknown): value is string { return typeof value === 'string' && CLAIM_ID.test(value); } diff --git a/scripts/__tests__/install-workspace-replay-plugins.test.ts b/scripts/__tests__/install-workspace-replay-plugins.test.ts index da8027bc3c..07b0733fb1 100644 --- a/scripts/__tests__/install-workspace-replay-plugins.test.ts +++ b/scripts/__tests__/install-workspace-replay-plugins.test.ts @@ -61,7 +61,7 @@ test('a non-source workspace install keeps the manifest fields the store reads b await Promise.all( (['maestro', 'replay'] as const).map(async (packageId) => [ packageId, - await readPluginPackageClaims(installedManifest(home, packageId)['agent-device']), + readPluginPackageClaims(installedManifest(home, packageId)['agent-device']), ]), ), ); diff --git a/src/__tests__/cli-web.test.ts b/src/__tests__/cli-web.test.ts index 636901ec03..68d9a4e549 100644 --- a/src/__tests__/cli-web.test.ts +++ b/src/__tests__/cli-web.test.ts @@ -1,10 +1,14 @@ import assert from 'node:assert/strict'; import fs from 'node:fs'; +import { createRequire } from 'node:module'; +import { pathToFileURL } from 'node:url'; import { test } from 'vitest'; import { runCliCapture } from './cli-capture.ts'; import { installFakeManagedAgentBrowser, mkdtempForTestSync, + pluginHome, + selectPlugin, withNodeRuntime, writeFakeManagedAgentBrowserPackage, } from '@agent-device/test-kit'; @@ -12,6 +16,18 @@ import { withCommandExecutorOverride } from '@agent-device/host-kit/command'; type SpawnedCommand = { cmd: string; args: readonly string[] }; +function webPluginEnv(stateDir: string) { + const { home, env } = pluginHome(); + const pluginRequire = createRequire( + new URL('../../packages/platform-web/package.json', import.meta.url), + ); + const entry = pathToFileURL(pluginRequire.resolve('@agent-device/web/agent-device')).href; + selectPlugin(home, '@agent-device/web', `export { default } from ${JSON.stringify(entry)};`, { + claims: { apiVersion: 3, platform: 'web' }, + }); + return { ...env, AGENT_DEVICE_STATE_DIR: stateDir }; +} + // `binaryPath` has been in the published `web setup`/`web doctor` JSON since #833. // The Windows spawn fix (#2022) moves execution to `node ` and adds // `entryScript`/`packageDir`, but the released field stays in the contract. @@ -28,7 +44,7 @@ test('web doctor --json keeps the published status fields and spawns the JS entr }, async () => await runCliCapture(['web', 'doctor', '--json'], { - env: { AGENT_DEVICE_STATE_DIR: stateDir }, + env: webPluginEnv(stateDir), }), ); @@ -65,7 +81,7 @@ test('web setup --json keeps the published status fields after installing', asyn }, async () => await runCliCapture(['web', 'setup', '--json'], { - env: { AGENT_DEVICE_STATE_DIR: stateDir }, + env: webPluginEnv(stateDir), }), ); stdout = result.stdout; diff --git a/src/__tests__/contracts/platform-plugin-parity.test.ts b/src/__tests__/contracts/platform-plugin-parity.test.ts index 0341d204a3..7a658dd737 100644 --- a/src/__tests__/contracts/platform-plugin-parity.test.ts +++ b/src/__tests__/contracts/platform-plugin-parity.test.ts @@ -1,26 +1,17 @@ -import { - createPlatformModuleRegistry, - REQUIRED_PLATFORMS, -} from '@agent-device/contracts/platform-module'; +import { builtinPlatformPlugins } from '../../core/interactors/builtin-platform-plugin-set.ts'; +import { REQUIRED_PLATFORMS } from '@agent-device/contracts/platform-module'; import assert from 'node:assert/strict'; import { test } from 'vitest'; import type { Platform } from '@agent-device/kernel/device'; import { AppError } from '@agent-device/kernel/errors'; -import { - getPlugin, - registeredPlatforms, - registerPlatformPluginSet, - tryGetPlugin, -} from '../../core/platform-plugin-registry.ts'; +import { registerPlatformPluginSet } from '../../core/platform-plugin-registry.ts'; import { BUILTIN_PLATFORM_PLUGINS, - registerBuiltinPlatformPlugins, type BuiltinPluginsCoverRequiredPlatforms, } from '../../core/interactors/register-builtins.ts'; import { missingPlatformPlugin } from '../../core/platform-plugin-absence.ts'; // Idempotently populate the root-owned registry for this test module. -registerBuiltinPlatformPlugins(missingPlatformPlugin, createPlatformModuleRegistry); // Independent copy of the internal platform accept-set. The CLI `--platform` // enum derives separately from `PLATFORM_SELECTORS`; this oracle keeps registry @@ -40,20 +31,29 @@ test('built-in platforms follow the canonical family order', () => { // Byte-for-byte allow-list parity: the registry derives exactly PLATFORMS, // in the same order. (Left as a parity assertion — PLATFORMS stays the // hand-authored source of truth; nothing is derived FROM the registry yet.) - assert.deepEqual(registeredPlatforms(), ['apple', 'android', 'harmonyos', 'vega', 'linux']); + assert.deepEqual(builtinPlatformPlugins.families, [ + 'apple', + 'android', + 'harmonyos', + 'vega', + 'linux', + ]); }); test('every required family is covered by a builtin plugin; optional families may be absent', () => { // Completeness (ADR 0034) is enforced for the required families only: apple and android must - // always resolve. All six builtins stay registered today, so registeredPlatforms() still + // always resolve. All six builtins stay registered today, so builtinPlatformPlugins.families still // equals PLATFORMS above; once an optional family moves to a `platform` plugin its row // disappears here without breaking this guarantee. The guard type only resolves to true // while every RequiredPlatform is covered, so materializing it pins the guarantee. const pin: BuiltinPluginsCoverRequiredPlatforms = true; assert.ok(pin); for (const family of REQUIRED_PLATFORMS) { - assert.ok(registeredPlatforms().includes(family), `required family ${family} is registered`); - assert.ok(getPlugin(family).platforms.includes(family)); + assert.ok( + builtinPlatformPlugins.families.includes(family), + `required family ${family} is registered`, + ); + assert.ok(builtinPlatformPlugins.get(family).plugin.platforms.includes(family)); } }); @@ -77,7 +77,7 @@ test('registry coverage is byte-for-byte equal to the parsePlatform hand allow-l undefined, ]; for (const candidate of candidates) { - const registered = tryGetPlugin(candidate as Platform) !== undefined; + const registered = builtinPlatformPlugins.tryGet(candidate as Platform) !== undefined; const parses = parsePlatformByHand(candidate) !== undefined && candidate !== 'web'; assert.equal(registered, parses, `coverage parity for ${JSON.stringify(candidate)}`); } @@ -85,17 +85,26 @@ test('registry coverage is byte-for-byte equal to the parsePlatform hand allow-l test('a family plugin resolves to the SAME instance for every leaf it owns', () => { // Apple owns both ios + macos (folds in the eventual macOS unwind). - assert.equal(getPlugin('apple'), getPlugin('apple')); - assert.equal(getPlugin('apple').id, 'apple'); - assert.equal(getPlugin('apple').familySelector, 'apple'); + assert.equal( + builtinPlatformPlugins.get('apple').plugin, + builtinPlatformPlugins.get('apple').plugin, + ); + assert.equal(builtinPlatformPlugins.get('apple').plugin.id, 'apple'); + assert.equal(builtinPlatformPlugins.get('apple').plugin.familySelector, 'apple'); // Single-platform plugins are distinct objects. - assert.notEqual(getPlugin('android'), getPlugin('linux')); - assert.notEqual(getPlugin('vega'), getPlugin('android')); + assert.notEqual( + builtinPlatformPlugins.get('android').plugin, + builtinPlatformPlugins.get('linux').plugin, + ); + assert.notEqual( + builtinPlatformPlugins.get('vega').plugin, + builtinPlatformPlugins.get('android').plugin, + ); }); test('each registered platform resolves to a plugin that owns it', () => { - for (const platform of registeredPlatforms()) { - const plugin = getPlugin(platform); + for (const platform of builtinPlatformPlugins.families) { + const plugin = builtinPlatformPlugins.get(platform).plugin; assert.ok( plugin.platforms.includes(platform), `${platform} plugin lists ${platform} in its platforms`, @@ -108,22 +117,21 @@ test('getPlugin throws UNSUPPORTED_PLATFORM (verbatim) for an unregistered platf // Same code + message the deleted getInteractor switch default produced. const unregistered = 'beos' as unknown as Platform; assert.throws( - () => getPlugin(unregistered), + () => builtinPlatformPlugins.get(unregistered).plugin, (error: unknown) => error instanceof AppError && error.code === 'UNSUPPORTED_PLATFORM' && error.message === 'Unsupported platform: beos', ); - assert.equal(tryGetPlugin(unregistered), undefined); + assert.equal(builtinPlatformPlugins.tryGet(unregistered), undefined); }); test('registering a duplicate platform is a hard error', () => { assert.throws( () => registerPlatformPluginSet( - [BUILTIN_PLATFORM_PLUGINS[0]], + [...BUILTIN_PLATFORM_PLUGINS, BUILTIN_PLATFORM_PLUGINS[0]], missingPlatformPlugin, - createPlatformModuleRegistry, ), /Duplicate platform family registration/, ); diff --git a/src/__tests__/provider-device-runtimes.test.ts b/src/__tests__/provider-device-runtimes.test.ts index cdb1463fd1..0088a0b21e 100644 --- a/src/__tests__/provider-device-runtimes.test.ts +++ b/src/__tests__/provider-device-runtimes.test.ts @@ -1,10 +1,17 @@ +import { createPlatformPluginHost } from '../platform-runtime/plugin-host.ts'; import assert from 'node:assert/strict'; import { test } from 'vitest'; -import { createDaemonProviderRuntimeComposition } from '../provider-device-runtimes.ts'; +import { createDaemonProviderRuntimeComposition as composeDaemonProviders } from '../provider-device-runtimes.ts'; import fs from 'node:fs'; import path from 'node:path'; import { pluginHome, selectPlugin, pluginSource } from '@agent-device/test-kit'; +function createDaemonProviderRuntimeComposition( + host: Parameters[0], +) { + return composeDaemonProviders(host, createPlatformPluginHost(host, host.cwd)); +} + test('daemon composition registers installed provider runtimes and their lazy platform modules', async () => { const { home, env } = pluginHome(); selectPlugin(home, 'example', pluginSource('example')); diff --git a/src/__tests__/test-utils/absent-platform-registry.ts b/src/__tests__/test-utils/absent-platform-registry.ts deleted file mode 100644 index 7f44444274..0000000000 --- a/src/__tests__/test-utils/absent-platform-registry.ts +++ /dev/null @@ -1,8 +0,0 @@ -import type { ProviderRegistry } from '@agent-device/plugins/registry'; - -export const absentPlatformRegistry: Pick = { - platforms: [], - resolvePlatform: (family, reportAbsent) => { - throw reportAbsent(family); - }, -}; diff --git a/src/builtin-provider-plugins.test.ts b/src/builtin-provider-plugins.test.ts index a1910fe947..d16c6a4b7f 100644 --- a/src/builtin-provider-plugins.test.ts +++ b/src/builtin-provider-plugins.test.ts @@ -1,8 +1,9 @@ +import { createPlatformPluginHost } from './platform-runtime/plugin-host.ts'; import assert from 'node:assert/strict'; import { afterEach, test, vi } from 'vitest'; import { mkdtempForTestSync } from '@agent-device/test-kit'; import { readVersion } from '@agent-device/host-kit/version'; -import { createEmbeddedProviderRuntimeComposition } from './provider-device-runtimes.ts'; +import { createEmbeddedProviderRuntimeComposition as composeEmbeddedProviders } from './provider-device-runtimes.ts'; import { builtinLimrunConnection } from './builtin-provider-plugins.ts'; // The built-in candidate is composed by the daemon's own registry, so the case runs the real plugin @@ -49,6 +50,13 @@ afterEach(() => { runtimeDependencies.create.mockClear(); }); +function createEmbeddedProviderRuntimeComposition( + host: Parameters[0], + candidates: Parameters[1], +) { + return composeEmbeddedProviders(host, candidates, createPlatformPluginHost(host, host.cwd)); +} + test('an unconfigured built-in Limrun claims its id without an inventory entry or a runtime', async () => { const composition = await createEmbeddedProviderRuntimeComposition( { env: {}, cwd: process.cwd() }, diff --git a/src/core/interactors.ts b/src/core/interactors.ts index 3381077172..8f5843bb63 100644 --- a/src/core/interactors.ts +++ b/src/core/interactors.ts @@ -1,23 +1,16 @@ -import { createPlatformModuleRegistry } from '@agent-device/contracts/platform-module'; -import type { WebPlatformSelection } from '@agent-device/contracts/platform-plugin'; import { publicPlatformString, type DeviceInfo } from '@agent-device/kernel/device'; import { AppError } from '@agent-device/kernel/errors'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; import { getProviderDeviceInteractor, isActiveProviderDevice } from '../provider-device-runtime.ts'; import type { Interactor, RunnerContext } from '@agent-device/contracts/interactor-types'; -import { getPlugin } from './platform-plugin-registry.ts'; -import { missingPlatformPlugin } from './platform-plugin-absence.ts'; -import { registerBuiltinPlatformPlugins } from './interactors/register-builtins.ts'; - -// Populate the platform-plugin registry once, at module load (only registers -// lazy closures — no leaf code is imported here, so CLI cold-start is unaffected). -registerBuiltinPlatformPlugins(missingPlatformPlugin, createPlatformModuleRegistry); +import { builtinPlatformPlugins } from './interactors/builtin-platform-plugin-set.ts'; +import type { PlatformPluginSet } from '@agent-device/contracts/platform-plugin'; export async function getInteractor( device: DeviceInfo, runnerContext: RunnerContext, host: HostEnvironment, - web?: WebPlatformSelection, + plugins: PlatformPluginSet = builtinPlatformPlugins, ): Promise { if (isActiveProviderDevice(device)) { const providerInteractor = getProviderDeviceInteractor(device, runnerContext); @@ -29,7 +22,7 @@ export async function getInteractor( ); } - return await getLocalInteractor(device, runnerContext, host, web); + return await getLocalInteractor(device, runnerContext, host, plugins); } /** @@ -42,15 +35,7 @@ export async function getLocalInteractor( device: DeviceInfo, runnerContext: RunnerContext, host: HostEnvironment, - web?: WebPlatformSelection, + plugins: PlatformPluginSet = builtinPlatformPlugins, ): Promise { - if (device.platform === 'web' && web) { - return await web.get().createInteractor(device, runnerContext, host); - } - // Byte-identical replacement for the former per-platform switch: each plugin's - // `createInteractor` is the SAME lazy dynamic import + factory call the switch - // arm performed, and `getPlugin` throws the SAME `UNSUPPORTED_PLATFORM` AppError - // the switch default threw. Registry exhaustiveness (BuiltinPluginsCoverRequiredPlatforms) - // guarantees every required family resolves; optional families may be absent (ADR 0034). - return await getPlugin(device.platform).createInteractor(device, runnerContext, host); + return await plugins.get(device.platform).plugin.createInteractor(device, runnerContext, host); } diff --git a/src/core/interactors/builtin-platform-plugin-set.ts b/src/core/interactors/builtin-platform-plugin-set.ts new file mode 100644 index 0000000000..5f1b55fac1 --- /dev/null +++ b/src/core/interactors/builtin-platform-plugin-set.ts @@ -0,0 +1,9 @@ +import { BUILTIN_PLATFORM_PLUGINS } from './register-builtins.ts'; +import { registerPlatformPluginSet } from '../platform-plugin-registry.ts'; +import { missingPlatformPlugin } from '../platform-plugin-absence.ts'; +import type { PlatformPlugin } from '@agent-device/contracts/platform-plugin'; + +export const builtinPlatformPlugins = registerPlatformPluginSet( + BUILTIN_PLATFORM_PLUGINS, + missingPlatformPlugin, +); diff --git a/src/core/interactors/register-builtins.ts b/src/core/interactors/register-builtins.ts index 667edde7c5..a3a971f441 100644 --- a/src/core/interactors/register-builtins.ts +++ b/src/core/interactors/register-builtins.ts @@ -1,13 +1,6 @@ import type { RunnerContext } from '@agent-device/contracts/interactor-types'; import type { PlatformPlugin } from '@agent-device/contracts/platform-plugin'; -import type { - RequiredPlatform, - createPlatformModuleRegistry, -} from '@agent-device/contracts/platform-module'; -import { - registerPlatformPluginSet, - type PlatformPluginAbsence, -} from '../platform-plugin-registry.ts'; +import type { RequiredPlatform } from '@agent-device/contracts/platform-module'; import { applePlugin } from '@agent-device/platform-apple'; import { vegaPlugin } from '@agent-device/platform-vega'; import type { DeviceInfo } from '@agent-device/kernel/device'; @@ -73,22 +66,3 @@ type AssertTrue = T; export type BuiltinPluginsCoverRequiredPlatforms = AssertTrue< [RequiredPlatform] extends [CoveredPlatform] ? true : false >; - -let registered = false; - -/** - * Composes every builtin plugin into the shared registry exactly once (idempotent), and gives the - * registry the builtin set's absence reporter as one input. Called at the top of `core/interactors.ts` - * so the registry is populated before any `getPlugin` lookup; safe to call again from tests. - * `reportAbsent` is how the registry reports a family the builtin set does not own, so the caller - * decides which core's plugin release an installation hint names (ADR 0034). It belongs to the set — - * not to a plugin — so no plugin can swap this process's absence policy. - */ -export function registerBuiltinPlatformPlugins( - reportAbsent: PlatformPluginAbsence, - createRegistry: typeof createPlatformModuleRegistry, -): void { - if (registered) return; - registerPlatformPluginSet(BUILTIN_PLATFORM_PLUGINS, reportAbsent, createRegistry); - registered = true; -} diff --git a/src/core/platform-plugin-registry-optional-family.test.ts b/src/core/platform-plugin-registry-optional-family.test.ts index a4e3b5ed63..d9833febaa 100644 --- a/src/core/platform-plugin-registry-optional-family.test.ts +++ b/src/core/platform-plugin-registry-optional-family.test.ts @@ -1,4 +1,3 @@ -import { createPlatformModuleRegistry } from '@agent-device/contracts/platform-module'; import type { PlatformProviderRequestContext } from '@agent-device/contracts/platform-providers'; import type { PlatformPlugin } from '@agent-device/contracts/platform-plugin'; import assert from 'node:assert/strict'; @@ -8,20 +7,17 @@ import type { DeviceInfo, Platform } from '@agent-device/kernel/device'; import type { PlatformPluginAbsence } from './platform-plugin-registry.ts'; // Simulates a composition whose builtin plugins do not include the extracted `vega` family: the -// module-level composition inside request-providers must then register only the five remaining +// module-level composition inside request-providers must then register only the remaining // builtins, leaving `vega` absent from the platform-plugin registry. -vi.mock('./interactors/register-builtins.ts', async (importOriginal) => { - const original = await importOriginal(); +vi.mock('./interactors/builtin-platform-plugin-set.ts', async () => { + const { BUILTIN_PLATFORM_PLUGINS } = await import('./interactors/register-builtins.ts'); const { registerPlatformPluginSet } = await import('./platform-plugin-registry.ts'); + const { missingPlatformPlugin } = await import('./platform-plugin-absence.ts'); return { - ...original, - registerBuiltinPlatformPlugins: (reportAbsent: PlatformPluginAbsence) => { - registerPlatformPluginSet( - original.BUILTIN_PLATFORM_PLUGINS.filter((plugin) => plugin.id !== 'vega'), - reportAbsent, - createPlatformModuleRegistry, - ); - }, + builtinPlatformPlugins: registerPlatformPluginSet( + BUILTIN_PLATFORM_PLUGINS.filter((plugin) => plugin.id !== 'vega'), + missingPlatformPlugin, + ), }; }); @@ -78,9 +74,9 @@ test('the request-provider scope for an absent optional family gates nothing, le // The interactor lookup answers presence through the same outcome the module registry raises // (#4781 review): the reporter is the one the composed set was given, so a caller of `getPlugin` // needs no guard of its own. - const { getPlugin } = await import('./platform-plugin-registry.ts'); + const { builtinPlatformPlugins } = await import('./interactors/builtin-platform-plugin-set.ts'); assert.throws( - () => getPlugin('vega'), + () => builtinPlatformPlugins.get('vega'), (error: unknown) => error instanceof AppError && error.code === 'UNSUPPORTED_PLATFORM' && @@ -103,14 +99,11 @@ test('a duplicate plugin set is rejected before it replaces the composed set or reason: 'plugin-not-installed', family, }); - registry.registerPlatformPluginSet( - [pluginOwning('apple', ['apple']), pluginOwning('android', ['android'])], - composedAbsence, - createPlatformModuleRegistry, - ); - assert.equal(registry.getPlugin('apple').id, 'apple'); + const builtins = [pluginOwning('apple', ['apple']), pluginOwning('android', ['android'])]; + const set = registry.registerPlatformPluginSet(builtins, composedAbsence); + assert.equal(set.get('apple').plugin.id, 'apple'); assert.throws( - () => registry.getPlugin('web'), + () => set.get('web'), (error: unknown) => error instanceof AppError && error.message === 'Composed absence: web', ); @@ -121,17 +114,16 @@ test('a duplicate plugin set is rejected before it replaces the composed set or assert.throws( () => registry.registerPlatformPluginSet( - [pluginOwning('web-and-apple', ['web', 'apple'])], + [...builtins, pluginOwning('web-and-apple', ['web', 'apple'])], rejectedAbsence, - createPlatformModuleRegistry, ), /Duplicate platform family registration: apple/, ); // Neither the duplicate's platform nor its absence policy reached the registry. - assert.equal(registry.tryGetPlugin('web'), undefined); + assert.equal(set.tryGet('web'), undefined); assert.throws( - () => registry.getPlugin('web'), + () => set.get('web'), (error: unknown) => error instanceof AppError && error.message === 'Composed absence: web', ); }); diff --git a/src/core/platform-plugin-registry-provider-routing.test.ts b/src/core/platform-plugin-registry-provider-routing.test.ts index ff9937ed8d..b37eeb2039 100644 --- a/src/core/platform-plugin-registry-provider-routing.test.ts +++ b/src/core/platform-plugin-registry-provider-routing.test.ts @@ -1,7 +1,4 @@ -import { - createPlatformModuleRegistry, - REQUIRED_PLATFORMS, -} from '@agent-device/contracts/platform-module'; +import { REQUIRED_PLATFORMS } from '@agent-device/contracts/platform-module'; import type { PlatformGatedProviderResolverKey, PlatformProviderRequestContext, @@ -28,16 +25,12 @@ import { VISIONOS_SIMULATOR, WEB_DESKTOP_DEVICE, } from '@agent-device/test-kit'; -import { getPlugin, tryGetPlugin } from './platform-plugin-registry.ts'; -import { registerBuiltinPlatformPlugins } from './interactors/register-builtins.ts'; -import { missingPlatformPlugin } from './platform-plugin-absence.ts'; +import { builtinPlatformPlugins } from './interactors/builtin-platform-plugin-set.ts'; import { createRequestPlatformProviders, type PlatformProviderResolvers, } from '../platform-runtime.ts'; -registerBuiltinPlatformPlugins(missingPlatformPlugin, createPlatformModuleRegistry); - const GATED_KEYS: PlatformGatedProviderResolverKey[] = [ 'androidAdbProvider', 'appleRunnerProvider', @@ -102,7 +95,7 @@ const SAMPLE_DEVICES: DeviceInfo[] = [ test('built-in provider facets retain the former routing', () => { for (const device of SAMPLE_DEVICES) { - const facet = tryGetPlugin(device.platform)?.providers; + const facet = builtinPlatformPlugins.tryGet(device.platform)?.plugin.providers; const expected = gatedResolversByHand(device); for (const key of GATED_KEYS) { const applies = facet?.platformGatedResolvers.includes(key) ?? false; @@ -116,17 +109,20 @@ test('built-in provider facets retain the former routing', () => { }); test('every family carries the providers facet with the resolvers it owns', () => { - assert.deepEqual([...getPlugin('apple').providers!.platformGatedResolvers].sort(), [ - 'appleRunnerProvider', - 'appleToolProvider', - ]); assert.deepEqual( - [...getPlugin('android').providers!.platformGatedResolvers], + [...builtinPlatformPlugins.get('apple').plugin.providers!.platformGatedResolvers].sort(), + ['appleRunnerProvider', 'appleToolProvider'], + ); + assert.deepEqual( + [...builtinPlatformPlugins.get('android').plugin.providers!.platformGatedResolvers], ['androidAdbProvider'], ); - assert.deepEqual([...getPlugin('vega').providers!.platformGatedResolvers], ['vegaToolProvider']); assert.deepEqual( - [...getPlugin('linux').providers!.platformGatedResolvers], + [...builtinPlatformPlugins.get('vega').plugin.providers!.platformGatedResolvers], + ['vegaToolProvider'], + ); + assert.deepEqual( + [...builtinPlatformPlugins.get('linux').plugin.providers!.platformGatedResolvers], ['linuxToolProvider'], ); }); @@ -176,8 +172,8 @@ test('every required family is registered at the provider gate; optional familie // exercises the full gate; their absence path is covered by // platform-plugin-registry-optional-family.test.ts. for (const family of REQUIRED_PLATFORMS) { - const plugin = getPlugin(family); + const plugin = builtinPlatformPlugins.get(family).plugin; assert.ok(plugin.platforms.includes(family), `${family} plugin owns ${family}`); - assert.equal(tryGetPlugin(family) !== undefined, true); + assert.equal(builtinPlatformPlugins.tryGet(family) !== undefined, true); } }); diff --git a/src/core/platform-plugin-registry.ts b/src/core/platform-plugin-registry.ts index 44b094424a..5325b69e96 100644 --- a/src/core/platform-plugin-registry.ts +++ b/src/core/platform-plugin-registry.ts @@ -1,64 +1,18 @@ +import { createPlatformModuleRegistry } from '@agent-device/contracts/platform-module'; +import type { PlatformPlugin, PlatformPluginSet } from '@agent-device/contracts/platform-plugin'; import type { Platform } from '@agent-device/kernel/device'; -import { AppError } from '@agent-device/kernel/errors'; -import type { - createPlatformModuleRegistry, - PlatformModuleRegistry, -} from '@agent-device/contracts/platform-module'; -import type { PlatformPlugin } from '@agent-device/contracts/platform-plugin'; +import type { AppError } from '@agent-device/kernel/errors'; -/** - * The outcome for a platform family this runtime does not have (ADR 0034). - * - * The plugin-set composition supplies it once, when it composes its plugins, because naming the - * package that provides a family needs the running core's version — a host read owned by - * `@agent-device/host-kit/version`. This registry is the interactor lookup every request reaches, so - * it stays free of that read and of the install-hint catalog: importing it evaluates neither. - */ export type PlatformPluginAbsence = (family: Platform) => AppError; -type InteractorRegistration = { family: Platform; plugin: PlatformPlugin }; - -let registry: PlatformModuleRegistry | undefined; - -/** - * Composes `plugins` as this process's platform-plugin set and takes, once for the whole set, the - * reporter for a family the set lacks. The set is the only registration path, so no single plugin can - * carry its own absence policy. - * - * Checks every leaf platform before it changes any state: a rejected set leaves the registry and the - * absence reporter exactly as they were, so a duplicate cannot replace the policy it came to install. - * Throws when one platform has two claimants — inside the set or against the registered set — so - * platform ownership cannot silently become last-writer-wins. - * One process holds one plugin set, and `registerBuiltinPlatformPlugins` runs once. - */ -export function registerPlatformPluginSet( - plugins: readonly PlatformPlugin[], +/** Registers one runtime's builtin and managed interactors through the family registry. */ +export function registerPlatformPluginSet( + plugins: readonly Plugin[], reportAbsent: PlatformPluginAbsence, - createRegistry: typeof createPlatformModuleRegistry, -): void { + assertSelectionCurrent?: (family: Platform) => void, +): PlatformPluginSet { const registrations = plugins.flatMap((plugin) => plugin.platforms.map((family) => ({ family, plugin })), ); - registry = createRegistry([...(registry?.modules ?? []), ...registrations], reportAbsent); -} - -/** - * Resolves the plugin that owns `platform`, or raises the same typed outcome the platform module - * registry raises for a family its composition lacks (ADR 0034): an absent optional family reports - * `plugin-not-installed` with the package that provides it and its installation command, so a caller - * needs no guard of its own. A family with no installation row keeps the plain unsupported-platform - * outcome with no package inferred. - */ -export function getPlugin(platform: Platform): PlatformPlugin { - if (!registry) throw new AppError('UNSUPPORTED_PLATFORM', `Unsupported platform: ${platform}`); - return registry.get(platform).plugin; -} - -export function tryGetPlugin(platform: Platform): PlatformPlugin | undefined { - return registry?.tryGet(platform)?.plugin; -} - -/** @internal Registered leaf platforms in insertion order, for parity gates. */ -export function registeredPlatforms(): Platform[] { - return [...(registry?.families ?? [])]; + return createPlatformModuleRegistry(registrations, reportAbsent, assertSelectionCurrent); } diff --git a/src/daemon-composition-credentials.test.ts b/src/daemon-composition-credentials.test.ts index 212093dc13..71dadac8b9 100644 --- a/src/daemon-composition-credentials.test.ts +++ b/src/daemon-composition-credentials.test.ts @@ -1,4 +1,3 @@ -import { absentPlatformRegistry } from './__tests__/test-utils/absent-platform-registry.ts'; import fs from 'node:fs'; import { expect, test, vi } from 'vitest'; import { startDaemonRuntime } from '@agent-device/daemon'; @@ -45,7 +44,7 @@ vi.mock('./provider-device-runtimes.ts', async (importOriginal) => ({ }, ], platformModules: [], - platformRegistry: absentPlatformRegistry, + platforms: [], shutdown: async () => [], inventory: [ ...(await ( diff --git a/src/daemon-composition-platform-plugin.test.ts b/src/daemon-composition-platform-plugin.test.ts new file mode 100644 index 0000000000..cd121b7e61 --- /dev/null +++ b/src/daemon-composition-platform-plugin.test.ts @@ -0,0 +1,166 @@ +import path from 'node:path'; +import { expect, test } from 'vitest'; +import { pluginHome, selectPlugin } from '@agent-device/test-kit'; +import { createRuntimeStateHandle } from '@agent-device/host-kit/runtime-slots'; +import { createDaemonRuntimeDeps } from './daemon-composition.ts'; +import { createManagedWebBackend } from './platform-runtime-managed-web-backend.ts'; + +const webPackage = '@agent-device/web'; +const webPlugin = ` + export default () => ({ + apiVersion: 3, + contributes: [{ + kind: 'platform', + family: 'web', + setup(host) { + return { + family: 'web', + createInteractor: async () => ({ activate: async () => {} }), + inventoryModule: { + family: 'web', + loadInventory: async () => ({ + discover: async () => [{ platform: 'web', kind: 'device', id: host.stateDir }], + }), + }, + runtimeModule: { family: 'web', loadRuntime() { throw new Error('must stay lazy'); } }, + withRequestProvider: async (_, task) => task(), + operations: { + setup() {}, + doctor: async () => ({ status: { stateDir: host.stateDir }, exitCode: 0 }), + cleanupOrphans() {}, + browserLifecycleCheck() {}, + createProvider() {}, + resolveRequestProvider() {}, + }, + }; + }, + }], + }); +`; + +function selectWeb(home: string) { + selectPlugin(home, webPackage, webPlugin, { claims: { apiVersion: 3, platform: 'web' } }); +} + +async function withDaemonComposition( + env: NodeJS.ProcessEnv, + baseDir: string, + run: ( + deps: Awaited>, + host: { env: NodeJS.ProcessEnv; cwd: string }, + ) => Promise, +) { + const host = { env: { ...env, AGENT_DEVICE_STATE_DIR: baseDir }, cwd: baseDir }; + const sessionsDir = path.join(baseDir, 'sessions'); + await createRuntimeStateHandle().run(async () => { + const deps = await createDaemonRuntimeDeps({ + host, + baseDir, + sessionsDir, + assertShutdownAllowed: undefined, + resolveSessionDir: (session) => path.join(sessionsDir, session), + resolveSessionArtifacts: () => { + throw new Error('unused'); + }, + openWebSessionNames: () => [], + }); + try { + await run(deps, host); + } finally { + await deps.shutdownProviderRuntimes(); + } + }); +} + +const inventoryScope = () => ({ + signal: new AbortController().signal, + diagnostics: { emit() {} }, + progress: { report() {} }, +}); + +test('daemon composition sets up a stored web platform and its inventory and doctor use the registration', async () => { + const { home, env } = pluginHome(); + const stateDir = path.join(home, 'state'); + selectWeb(home); + await withDaemonComposition(env, stateDir, async (deps, host) => { + expect(deps.pluginInventory).toContainEqual( + expect.objectContaining({ + package: webPackage, + platform: 'web', + source: 'store', + state: 'active', + }), + ); + const devices = await deps.requestRouter.deviceInventoryGateways.localOnly.discover( + { platform: 'web' }, + inventoryScope(), + ); + expect(devices).toEqual([expect.objectContaining({ id: stateDir, platform: 'web' })]); + await expect(deps.interactorResolution.resolve(devices[0]!, {})).resolves.toHaveProperty( + 'activate', + ); + await expect(createManagedWebBackend(host).doctor({ stateDir })).resolves.toMatchObject({ + status: { stateDir }, + exitCode: 0, + }); + }); +}); + +test.each(['linux', 'apple'])( + 'a store claim cannot replace the bundled %s family', + async (family) => { + const { home, env } = pluginHome(); + selectPlugin(home, webPackage, webPlugin.replaceAll("'web'", JSON.stringify(family)), { + claims: { apiVersion: 3, platform: family }, + }); + const stateDir = path.join(home, 'state'); + await withDaemonComposition(env, stateDir, async (deps, host) => { + expect(deps.pluginInventory).toContainEqual( + expect.objectContaining({ + package: webPackage, + platform: family, + state: 'failed', + error: expect.objectContaining({ reason: 'duplicate_platform' }), + }), + ); + await expect(createManagedWebBackend(host).doctor({ stateDir })).rejects.toMatchObject({ + details: expect.objectContaining({ reason: 'plugin-not-installed', family: 'web' }), + }); + }); + }, +); + +test('absent web reports the same install hint for daemon inventory, interactors and web doctor', async () => { + const { home, env } = pluginHome(); + const stateDir = path.join(home, 'state'); + await withDaemonComposition(env, stateDir, async (deps, host) => { + const gateway = deps.requestRouter.deviceInventoryGateways.localOnly; + const discover = () => gateway.discover({ platform: 'web' }, inventoryScope()); + const absent = { + code: 'UNSUPPORTED_PLATFORM', + details: expect.objectContaining({ + reason: 'plugin-not-installed', + package: webPackage, + installCommand: expect.stringContaining('agent-device plugins add @agent-device/web'), + }), + }; + await expect(discover()).rejects.toMatchObject(absent); + await expect( + deps.interactorResolution.resolve( + { + platform: 'web', + id: 'fixture', + kind: 'device', + name: 'Fixture', + }, + {}, + ), + ).rejects.toMatchObject(absent); + await expect(createManagedWebBackend(host).doctor({ stateDir })).rejects.toMatchObject(absent); + + selectWeb(home); + await expect(discover()).rejects.toMatchObject({ + details: expect.objectContaining({ reason: 'daemon-plugin-set-stale', package: webPackage }), + }); + }); +}); diff --git a/src/daemon-composition.test.ts b/src/daemon-composition.test.ts index 9fb0592877..dab016d995 100644 --- a/src/daemon-composition.test.ts +++ b/src/daemon-composition.test.ts @@ -1,4 +1,3 @@ -import { absentPlatformRegistry } from './__tests__/test-utils/absent-platform-registry.ts'; import { afterEach, expect, test, vi } from 'vitest'; import type { DeviceInfo } from '@agent-device/kernel/device'; import type { ProviderDeviceRuntime } from '@agent-device/contracts/device'; @@ -47,7 +46,7 @@ vi.mock('./provider-device-runtimes.ts', async (importOriginal) => ({ createDaemonProviderRuntimeComposition: async () => ({ runtimes: [], platformModules: [], - platformRegistry: absentPlatformRegistry, + platforms: [], shutdown: ports.shutdownProviders, inventory: [], resolveReplayBackend: async () => { diff --git a/src/daemon-composition.ts b/src/daemon-composition.ts index fee0a8613f..a13013cb1e 100644 --- a/src/daemon-composition.ts +++ b/src/daemon-composition.ts @@ -1,4 +1,3 @@ -import { missingPlatformPlugin } from './core/platform-plugin-absence.ts'; // The daemon runtime's dependency construction, extracted from `packages/daemon/src/server/http/daemon-runtime.ts` // so the operational server owns sequencing and this module owns naming runtimes (ADR 0019). // Everything here that names a platform runtime, a provider runtime, an interactor, host @@ -21,10 +20,10 @@ import { import { createDaemonProviderRuntimeComposition, createEmbeddedProviderRuntimeComposition, - selectWebPlatform, } from './provider-device-runtimes.ts'; import { readDaemonProviderCredentials } from './provider-credential-fingerprint.ts'; import { createPlatformPluginHost } from './platform-runtime/plugin-host.ts'; +import { composePlatformPlugins } from './platform-runtime/platform-plugins.ts'; import type { WebPlatformSelection } from '@agent-device/contracts/platform-plugin'; import { getInteractor } from './core/interactors.ts'; import { @@ -132,12 +131,16 @@ export async function composeDaemonRuntimeDeps( providerComposition.resolveReplayExecution, ); const providerDeviceRuntimes = [...providerComposition.runtimes]; - const web = selectWebPlatform(providerComposition.platformRegistry); + const platforms = composePlatformPlugins( + providerComposition.platforms, + providerComposition.inventory, + providerComposition.assertSelectionCurrent, + ); + const { web } = platforms; const hostDiagnostics = createHostDiagnostics(host, web); const deviceRuntimeGateway = createPlatformRuntimeGateway({ host, - web, - reportAbsent: missingPlatformPlugin, + platforms, assertShutdownAllowed, providerRuntimes: providerDeviceRuntimes, providerModules: providerComposition.platformModules, @@ -158,8 +161,7 @@ export async function composeDaemonRuntimeDeps( const deviceInventoryGateways = await createPlatformDeviceInventoryGateways( host, providerRuntimeProviders.deviceInventorySource, - web, - missingPlatformPlugin, + platforms, ); // Root composition of the platform-services port and the owner-scoped claim-recovery gateway. // platform-runtime.ts is already static in this module, so the deferred imports keep these thin @@ -191,7 +193,7 @@ export async function composeDaemonRuntimeDeps( claimRecoveryGateway: createClaimRecoveryGatewayFor(host), interactorResolution: Object.freeze({ resolve: async (device: DeviceInfo, runnerContext: RunnerContext) => - await getInteractor(device, runnerContext, host, web), + await getInteractor(device, runnerContext, host, platforms.interactors), }), providerDeviceAdmission: Object.freeze({ isActive: (device: DeviceInfo) => isActiveProviderDevice(device), diff --git a/src/daemon-runtime-limrun-public-http.test.ts b/src/daemon-runtime-limrun-public-http.test.ts index f93daa51c1..e3ca4e7e80 100644 --- a/src/daemon-runtime-limrun-public-http.test.ts +++ b/src/daemon-runtime-limrun-public-http.test.ts @@ -1,4 +1,3 @@ -import { absentPlatformRegistry } from './__tests__/test-utils/absent-platform-registry.ts'; import fs from 'node:fs'; import assert from 'node:assert/strict'; import { test, vi } from 'vitest'; @@ -30,7 +29,7 @@ const rootPorts = vi.hoisted(() => { () => Promise< Pick< ProviderRuntimeComposition, - 'runtimes' | 'platformModules' | 'platformRegistry' | 'inventory' | 'shutdown' + 'runtimes' | 'platformModules' | 'platforms' | 'inventory' | 'shutdown' > > >(), @@ -89,7 +88,7 @@ test('public HTTP rejects Limrun uploaded-app listing and allocation before prov rootPorts.providerComposition.mockResolvedValue({ runtimes: [limrun], platformModules: [], - platformRegistry: absentPlatformRegistry, + platforms: [], inventory: [], shutdown: async () => { await limrun.shutdown(); diff --git a/src/host.test.ts b/src/host.test.ts index ec6e7c3d4c..ff83d1178e 100644 --- a/src/host.test.ts +++ b/src/host.test.ts @@ -12,7 +12,6 @@ import { readProcessStartTime } from '@agent-device/host-kit/process'; import { createTestHostEnvironment, mkdtempForTestSync } from '@agent-device/test-kit'; import type { PluginCandidate } from '@agent-device/plugins/registry'; import type { AgentDevicePlugin } from './sdk/plugins.ts'; -import { absentPlatformRegistry } from './__tests__/test-utils/absent-platform-registry.ts'; import { builtinPluginInventory } from './__tests__/test-utils/builtin-plugin-inventory.ts'; import { stopRecordedDaemon } from '@agent-device/daemon-client'; import { startAgentDevice } from './host.ts'; @@ -79,7 +78,7 @@ vi.mock('./provider-device-runtimes.ts', async (importOriginal) => { return { runtimes: [], platformModules: [], - platformRegistry: absentPlatformRegistry, + platforms: [], shutdown: async () => [], inventory: [ ...(await ( diff --git a/src/platform-runtime-gateway-gesture-admission.test.ts b/src/platform-runtime-gateway-gesture-admission.test.ts index 707710c5fd..ed25ad83b2 100644 --- a/src/platform-runtime-gateway-gesture-admission.test.ts +++ b/src/platform-runtime-gateway-gesture-admission.test.ts @@ -1,4 +1,4 @@ -import { webSelectionFixture } from './platform-runtime-web-provider.fixtures.ts'; +import { webPlatformCompositionFixture } from './platform-runtime-web-provider.fixtures.ts'; import type { DeviceInfo } from '@agent-device/kernel/device'; import { expect, test } from 'vitest'; import { bindTestCommandHost, createLiveTestHostEnvironment } from '@agent-device/test-kit'; @@ -7,7 +7,7 @@ import { createPlatformRuntimeGateway } from './platform-runtime.ts'; bindTestCommandHost(); const gateway = createPlatformRuntimeGateway({ - web: webSelectionFixture(), + platforms: webPlatformCompositionFixture(), host: createLiveTestHostEnvironment(), resolveSessionArtifacts: () => ({ outputPath: '/sessions/gesture-admission/app.log', diff --git a/src/platform-runtime-local-application-interactors.ts b/src/platform-runtime-local-application-interactors.ts index b58e1ef994..4364cd13cc 100644 --- a/src/platform-runtime-local-application-interactors.ts +++ b/src/platform-runtime-local-application-interactors.ts @@ -1,4 +1,4 @@ -import type { WebPlatformSelection } from '@agent-device/contracts/platform-plugin'; +import type { PlatformPluginSet } from '@agent-device/contracts/platform-plugin'; import type { LocalApplicationInteractorHost } from '@agent-device/contracts/application-lifecycle-runtime'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; import type { DeviceInfo } from '@agent-device/kernel/device'; @@ -7,12 +7,12 @@ import type { RunnerContext } from '@agent-device/contracts/interactor-types'; /** Lazy local interactor construction; package bindings decide when it is needed. */ export function createLocalApplicationInteractorHost( host: HostEnvironment, - web?: WebPlatformSelection, + interactors?: PlatformPluginSet, ): LocalApplicationInteractorHost { return Object.freeze({ resolve: async (device: DeviceInfo, runner: RunnerContext) => { const { getLocalInteractor } = await import('./core/interactors.ts'); - return await getLocalInteractor(device, runner, host, web); + return await getLocalInteractor(device, runner, host, interactors); }, }); } diff --git a/src/platform-runtime-managed-web-backend.ts b/src/platform-runtime-managed-web-backend.ts index 7b71c32b6e..1ec058aa39 100644 --- a/src/platform-runtime-managed-web-backend.ts +++ b/src/platform-runtime-managed-web-backend.ts @@ -22,7 +22,7 @@ async function withWebPlatform( { getOptionalPlatformPluginDeclaration }, { createPlatformPluginHost }, { resolveDaemonPaths }, - { selectWebPlatform }, + { builtinPlatformCandidates, composePlatformPlugins }, { PROVIDER_PLUGIN_POLICY }, ] = await Promise.all([ import('@agent-device/plugins/registry'), @@ -30,7 +30,7 @@ async function withWebPlatform( import('@agent-device/contracts/plugin-installation'), import('./platform-runtime/plugin-host.ts'), import('@agent-device/daemon-contracts/daemon-resolution'), - import('./provider-device-runtimes.ts'), + import('./platform-runtime/platform-plugins.ts'), import('./provider-plugin-policy.ts'), ]); const packageName = getOptionalPlatformPluginDeclaration('web')?.package; @@ -40,13 +40,14 @@ async function withWebPlatform( candidate.package === packageName || candidate.declaredClaims?.some(({ kind, id }) => kind === 'platform' && id === 'web'), ); - const resolved = await resolveProviderPlugins(candidates); + const resolved = await resolveProviderPlugins([...builtinPlatformCandidates(), ...candidates]); + const assertSelectionCurrent = createPluginSelectionGuard(installed, host.env); const registry = await startProviderRegistry( resolved, host, { ...PROVIDER_PLUGIN_POLICY, - assertSelectionCurrent: createPluginSelectionGuard(installed, host.env), + assertSelectionCurrent, platformHost: createPlatformPluginHost( host, resolveDaemonPaths(stateDir, { env: host.env, cwd: host.cwd }).baseDir, @@ -55,7 +56,13 @@ async function withWebPlatform( 'platforms', ); try { - return await run(selectWebPlatform(registry).get()); + return await run( + composePlatformPlugins( + registry.platforms, + registry.inventory, + assertSelectionCurrent, + ).web.get(), + ); } finally { await registry.close(); } diff --git a/src/platform-runtime-operation-host.ts b/src/platform-runtime-operation-host.ts index cb5b1e4f6f..2ba2bdeb92 100644 --- a/src/platform-runtime-operation-host.ts +++ b/src/platform-runtime-operation-host.ts @@ -1,4 +1,7 @@ -import type { WebPlatformSelection } from '@agent-device/contracts/platform-plugin'; +import type { + PlatformPluginSet, + WebPlatformSelection, +} from '@agent-device/contracts/platform-plugin'; import type { EnvMap, HostEnvironment } from '@agent-device/kernel/source-value'; import type { AppLogSessionArtifacts } from '@agent-device/contracts/app-log-runtime'; import type { DeviceShutdownRuntimeLoaders } from '@agent-device/contracts/device-shutdown-runtime'; @@ -54,6 +57,7 @@ export async function loadMacOsSurfaceSnapshot( export function createPlatformRuntimeHost(options: { host: HostEnvironment; web?: WebPlatformSelection; + interactors?: PlatformPluginSet; sessionsDir: string; resolveSessionArtifacts(sessionId: string): AppLogSessionArtifacts; shutdownLoaders: DeviceShutdownRuntimeLoaders; @@ -135,7 +139,7 @@ export function createPlatformRuntimeHost(options: { }), perf: createPerfRuntimeHost(), snapshot: options.snapshot, - localInteractors: createLocalApplicationInteractorHost(host, options.web), + localInteractors: createLocalApplicationInteractorHost(host, options.interactors), appleApplications, androidApplications, applicationResources: createApplicationResourceLifecycle({ diff --git a/src/platform-runtime-web-provider.fixtures.ts b/src/platform-runtime-web-provider.fixtures.ts index ca11247c0e..43a9d546c0 100644 --- a/src/platform-runtime-web-provider.fixtures.ts +++ b/src/platform-runtime-web-provider.fixtures.ts @@ -1,12 +1,13 @@ import { createRequire } from 'node:module'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; import { createLiveTestHostEnvironment } from '@agent-device/test-kit'; +import { composePlatformPlugins } from './platform-runtime/platform-plugins.ts'; import { createPlatformPluginHost } from './platform-runtime/plugin-host.ts'; import type { WebPlatformRegistration, WebPlatformSelection, } from '@agent-device/contracts/platform-plugin'; -import type { PlatformContribution, PlatformHost } from '@agent-device/plugins/contract'; +import type { PlatformHost } from '@agent-device/plugins/contract'; const pluginRequire = createRequire( new URL('../packages/platform-web/package.json', import.meta.url), @@ -14,7 +15,7 @@ const pluginRequire = createRequire( const { default: webPlatformPlugin } = (await import( pluginRequire.resolve('@agent-device/web/agent-device') )) as { - default(): { contributes: [Extract] }; + default(): { contributes: [{ setup(host: PlatformHost): WebPlatformRegistration }] }; }; export function webSelectionFixture( @@ -24,9 +25,13 @@ export function webSelectionFixture( ): WebPlatformSelection { const active = webPlatformPlugin().contributes[0].setup( createPlatformPluginHost(host, stateDir, resources), - ) as WebPlatformRegistration; + ); return { active, get: () => active }; } +export function webPlatformCompositionFixture(...args: Parameters) { + return composePlatformPlugins([webSelectionFixture(...args).get()], []); +} + import type { WebProvider } from '@agent-device/contracts/web-provider'; /** A web provider whose every operation succeeds with nothing; a test overrides the ones it reads. */ diff --git a/src/platform-runtime.test.ts b/src/platform-runtime.test.ts index 0e17107994..56cb659623 100644 --- a/src/platform-runtime.test.ts +++ b/src/platform-runtime.test.ts @@ -31,7 +31,7 @@ vi.mock('./platform-runtime-host.ts', () => { }; }); -import { webSelectionFixture } from './platform-runtime-web-provider.fixtures.ts'; +import { webPlatformCompositionFixture } from './platform-runtime-web-provider.fixtures.ts'; import { createPlatformDeviceInventoryGateways, createPlatformModuleRegistryForHost, @@ -39,7 +39,10 @@ import { bindTestCommandHost(); -const platformModuleRegistry = createPlatformModuleRegistryForHost({}, webSelectionFixture()); +const platformModuleRegistry = createPlatformModuleRegistryForHost( + {}, + webPlatformCompositionFixture(), +); describe('platform module metadata composition', () => { test('registers each canonical family exactly once in canonical order', () => { @@ -93,7 +96,7 @@ describe('platform module metadata composition', () => { const localGateways = await createPlatformDeviceInventoryGateways( createLiveTestHostEnvironment(), undefined, - webSelectionFixture(), + webPlatformCompositionFixture(), ); expect(await localGateways.localOnly.discover({ platform: 'web' }, scope)).toHaveLength(1); expect(hostAdapter.evaluations).toBe(0); diff --git a/src/platform-runtime.ts b/src/platform-runtime.ts index ce09dd0e4b..7482f5283a 100644 --- a/src/platform-runtime.ts +++ b/src/platform-runtime.ts @@ -49,7 +49,7 @@ import { inventoryModule as linuxInventoryModule, runtimeModule as linuxRuntimeModule, } from '@agent-device/platform-linux'; -import type { WebPlatformSelection } from '@agent-device/contracts/platform-plugin'; +import type { PlatformModuleSelection } from '@agent-device/contracts/platform-plugin'; import { createComposedPlatformRuntimeGateway, type PlatformRuntimeProviderRegistration, @@ -85,8 +85,7 @@ const shutdownLoaders = Object.freeze({ export function createPlatformModuleRegistryForHost( env: Readonly>, - web?: WebPlatformSelection, - reportAbsent?: Parameters[1], + platforms?: PlatformModuleSelection, ) { return createPlatformModuleRegistry( [ @@ -101,23 +100,20 @@ export function createPlatformModuleRegistryForHost( }), vegaInventoryModule, linuxInventoryModule, - ...(web?.active ? [web.active.inventoryModule] : []), + ...(platforms?.inventoryModules ?? []), ], - reportAbsent, - (family) => { - if (family === 'web') web?.get(); - }, + platforms?.reportAbsent, + platforms?.assertSelectionCurrent, ); } export async function createPlatformDeviceInventoryGateways( host: HostEnvironment, provider?: ProviderDeviceInventorySource, - web?: WebPlatformSelection, - reportAbsent?: Parameters[1], + platforms?: PlatformModuleSelection, ): Promise { return await attachAppleSelectionProbes({ - registry: createPlatformModuleRegistryForHost(host.env, web, reportAbsent), + registry: createPlatformModuleRegistryForHost(host.env, platforms), loadHost: async () => { const { createDeviceInventoryHost } = await import('./platform-runtime-host.ts'); return createDeviceInventoryHost(host); @@ -135,8 +131,8 @@ const androidRuntimeModule = createAndroidRuntimeModule({ }); function createPlatformRuntimeModuleRegistry( - web?: WebPlatformSelection, - reportAbsent?: Parameters[1], + platforms?: PlatformModuleSelection, + reportAbsent = platforms?.reportAbsent, ) { return createPlatformModuleRegistry( [ @@ -145,19 +141,17 @@ function createPlatformRuntimeModuleRegistry( harmonyosRuntimeModule, vegaRuntimeModule, linuxRuntimeModule, - ...(web?.active ? [web.active.runtimeModule] : []), + ...(platforms?.runtimeModules ?? []), ], reportAbsent, - (family) => { - if (family === 'web') web?.get(); - }, + platforms?.assertSelectionCurrent, ); } export function createPlatformRuntimeGateway( options: Readonly<{ host: HostEnvironment; - web?: WebPlatformSelection; + platforms?: PlatformModuleSelection; reportAbsent?: Parameters[1]; providerRuntimes?: readonly ProviderDeviceRuntime[]; providerModules?: readonly PlatformRuntimeProviderRegistration[]; @@ -168,13 +162,17 @@ export function createPlatformRuntimeGateway( }>, ): DeviceRuntimeGateway { return createComposedPlatformRuntimeGateway({ - modules: createPlatformRuntimeModuleRegistry(options.web, options.reportAbsent), + modules: createPlatformRuntimeModuleRegistry( + options.platforms, + options.reportAbsent ?? options.platforms?.reportAbsent, + ), loadHost: async () => { const { createPlatformRuntimeHost, createSnapshotRuntimeHost, loadMacOsSurfaceSnapshot } = await import('./platform-runtime-operation-host.ts'); return createPlatformRuntimeHost({ host: options.host, - web: options.web, + web: options.platforms?.web, + interactors: options.platforms?.interactors, sessionsDir: options.sessionsDir, resolveSessionArtifacts: options.resolveSessionArtifacts, shutdownLoaders, diff --git a/src/platform-runtime/platform-plugins.ts b/src/platform-runtime/platform-plugins.ts new file mode 100644 index 0000000000..4413a39f0c --- /dev/null +++ b/src/platform-runtime/platform-plugins.ts @@ -0,0 +1,102 @@ +import type { + PlatformModuleSelection, + PlatformPlugin, + WebPlatformSelection, + WebPlatformRegistration, +} from '@agent-device/contracts/platform-plugin'; +import type { PluginInventoryEntry } from '@agent-device/contracts/plugin-inventory'; +import type { Platform } from '@agent-device/kernel/device'; +import { AppError } from '@agent-device/kernel/errors'; +import type { PluginCandidate, ProviderRegistry } from '@agent-device/plugins/registry'; +import { getOptionalPlatformPluginDeclaration } from '@agent-device/contracts/plugin-installation'; +import { BUILTIN_PLATFORM_PLUGINS } from '../core/interactors/register-builtins.ts'; +import { registerPlatformPluginSet } from '../core/platform-plugin-registry.ts'; +import { missingPlatformPlugin } from '../core/platform-plugin-absence.ts'; + +type RuntimePlatformPlugin = PlatformPlugin & { web?: WebPlatformRegistration }; + +export function builtinPlatformCandidates(): readonly PluginCandidate[] { + return [ + { + source: 'builtin', + dormant: true, + declaredClaims: BUILTIN_PLATFORM_PLUGINS.flatMap((plugin) => + plugin.platforms.map((id) => ({ kind: 'platform', id })), + ), + load: () => undefined, + }, + ]; +} + +export function composePlatformPlugins( + platforms: ProviderRegistry['platforms'], + inventory: readonly PluginInventoryEntry[], + assertPluginSelectionCurrent?: (packageName: string) => void, +): PlatformModuleSelection { + function selectedClaim(family: Platform) { + const expected = getOptionalPlatformPluginDeclaration(family)?.package; + return ( + inventory.find((entry) => entry.platform === family) ?? + inventory.find( + (entry) => + expected !== undefined && + entry.package === expected && + entry.state === 'failed' && + entry.platform === undefined && + entry.provider === undefined && + entry.backend === undefined, + ) + ); + } + + function reportAbsent(family: Platform): AppError { + const entry = selectedClaim(family); + if (entry?.state !== 'failed') return missingPlatformPlugin(family); + const { code, message, ...details } = entry.error; + return new AppError(code, message, { ...details, family, package: entry.package }); + } + + function assertSelectionCurrent(family: Platform): void { + if ( + !assertPluginSelectionCurrent || + BUILTIN_PLATFORM_PLUGINS.some((plugin) => plugin.platforms.some((owned) => owned === family)) + ) + return; + const claim = selectedClaim(family); + if (claim && claim.source !== 'store') return; + const packageName = claim?.package ?? getOptionalPlatformPluginDeclaration(family)?.package; + if (packageName) assertPluginSelectionCurrent(packageName); + } + + const interactors = registerPlatformPluginSet( + [ + ...BUILTIN_PLATFORM_PLUGINS, + ...platforms.map((platform) => ({ + id: platform.family, + platforms: [platform.family], + createInteractor: platform.createInteractor.bind(platform), + ...(platform.family === 'web' ? { web: platform } : {}), + })), + ], + reportAbsent, + assertSelectionCurrent, + ); + + const web: WebPlatformSelection = { + active: interactors.tryGet('web')?.plugin.web, + get() { + const { web } = interactors.get('web').plugin; + if (!web) throw new TypeError('Web platform registration is missing its operations'); + return web; + }, + }; + + return { + interactors, + web, + inventoryModules: platforms.map((platform) => platform.inventoryModule), + runtimeModules: platforms.map((platform) => platform.runtimeModule), + reportAbsent, + assertSelectionCurrent, + }; +} diff --git a/src/platform-runtime/request-providers.ts b/src/platform-runtime/request-providers.ts index d4ca0fa788..e4ef38b037 100644 --- a/src/platform-runtime/request-providers.ts +++ b/src/platform-runtime/request-providers.ts @@ -1,4 +1,3 @@ -import { createPlatformModuleRegistry } from '@agent-device/contracts/platform-module'; import type { PlatformGatedProviderResolverKey, PlatformProviderRequestContext, @@ -18,9 +17,7 @@ import type { VegaToolProvider } from '@agent-device/platform-vega'; import { webBackendKeyOf, type DeviceInfo } from '@agent-device/kernel/device'; import type { AppleSimulatorScreenRecordingTransport } from '../platform-runtime-screen-recording-apple-transport.ts'; import type { AppleRunnerScreenRecordingTransport } from '../platform-runtime-screen-recording-apple-runner-transport.ts'; -import { tryGetPlugin } from '../core/platform-plugin-registry.ts'; -import { registerBuiltinPlatformPlugins } from '../core/interactors/register-builtins.ts'; -import { missingPlatformPlugin } from '../core/platform-plugin-absence.ts'; +import { builtinPlatformPlugins } from '../core/interactors/builtin-platform-plugin-set.ts'; import { loadAndroidMechanics } from '../platform-runtime-android-mechanics.ts'; export type PlatformProviderResolver = ( @@ -310,11 +307,13 @@ function platformGatedResolverApplies( // A predicate, never a throw: an absent optional family gates no resolver, and the runtime or // interactor lookup the same request then performs raises the typed plugin-not-installed outcome. // The registry is intentionally loaded by the root composition, not by the daemon request path. - return tryGetPlugin(device.platform)?.providers?.platformGatedResolvers.includes(key) ?? false; + return ( + builtinPlatformPlugins + .tryGet(device.platform) + ?.plugin.providers?.platformGatedResolvers.includes(key) ?? false + ); } -registerBuiltinPlatformPlugins(missingPlatformPlugin, createPlatformModuleRegistry); - async function requestPlatformProviderScopeWrappers( scopedProviders: ResolvedRequestPlatformProviders, web?: WebPlatformSelection, diff --git a/src/provider-device-runtimes.ts b/src/provider-device-runtimes.ts index 327d28b637..d42bd9eedd 100644 --- a/src/provider-device-runtimes.ts +++ b/src/provider-device-runtimes.ts @@ -1,6 +1,3 @@ -import { getOptionalPlatformPluginDeclaration } from '@agent-device/contracts/plugin-installation'; -import { missingPlatformPlugin } from './core/platform-plugin-absence.ts'; -import type { WebPlatformSelection } from '@agent-device/contracts/platform-plugin'; import type { PlatformHost } from '@agent-device/plugins/contract'; import type { PluginCandidate, @@ -18,7 +15,8 @@ import { builtinProviderCandidates } from './builtin-provider-plugins.ts'; import { PROVIDER_PLUGIN_POLICY } from './provider-plugin-policy.ts'; export type ProviderRuntimeComposition = Readonly<{ - platformRegistry: Pick; + platforms: ProviderRegistry['platforms']; + assertSelectionCurrent?: PluginRegistryPolicy['assertSelectionCurrent']; resolveReplayBackend: import('@agent-device/plugins/replay-backend').ReplayBackendResolver; resolveReplayExecution: import('@agent-device/contracts/replay-execution').ReplayExecutionResolver; runtimes: readonly ProviderDeviceRuntime[]; @@ -35,7 +33,7 @@ export type ProviderRuntimeComposition = Readonly<{ */ export async function createDaemonProviderRuntimeComposition( host: HostEnvironment, - platformHost?: PlatformHost, + platformHost: PlatformHost, ): Promise { const { storePluginCandidates, createPluginSelectionGuard } = await import('@agent-device/plugins/store'); @@ -51,7 +49,7 @@ export async function createDaemonProviderRuntimeComposition( export async function createEmbeddedProviderRuntimeComposition( host: HostEnvironment, candidates: readonly PluginCandidate[], - platformHost?: PlatformHost, + platformHost: PlatformHost, ): Promise { return await composeProviderRuntime(host, candidates, { ...PROVIDER_PLUGIN_POLICY, @@ -62,30 +60,20 @@ export async function createEmbeddedProviderRuntimeComposition( async function composeProviderRuntime( host: HostEnvironment, candidates: readonly PluginCandidate[], - policy: PluginRegistryPolicy, + policy: PluginRegistryPolicy & { platformHost: PlatformHost }, ): Promise { const { resolveProviderPlugins, startProviderRegistry } = await import('@agent-device/plugins/registry'); - const [{ BUILTIN_PLATFORM_PLUGINS }, { isOptionalPlatform }] = await Promise.all([ - import('./core/interactors/register-builtins.ts'), - import('@agent-device/contracts/platform-module'), - ]); - const bundledPlatforms = BUILTIN_PLATFORM_PLUGINS.flatMap((plugin) => [ - ...plugin.platforms, - ]).filter(isOptionalPlatform); + const { builtinPlatformCandidates } = await import('./platform-runtime/platform-plugins.ts'); const resolved = await resolveProviderPlugins([ - { - source: 'builtin', - dormant: true, - declaredClaims: bundledPlatforms.map((id) => ({ kind: 'platform', id })), - load: () => undefined, - }, + ...builtinPlatformCandidates(), ...builtinProviderCandidates(host), ...candidates, ]); const registry = await startProviderRegistry(resolved, host, policy); return Object.freeze({ - platformRegistry: registry, + platforms: registry.platforms, + assertSelectionCurrent: policy.assertSelectionCurrent, runtimes: Object.freeze(registry.registrations.map(({ runtime }) => runtime)), platformModules: Object.freeze( registry.registrations.map(({ runtime, platformModule }) => ({ @@ -99,17 +87,3 @@ async function composeProviderRuntime( shutdown: registry.close, }); } - -export function selectWebPlatform( - registry: Pick, -): WebPlatformSelection { - const packageName = getOptionalPlatformPluginDeclaration('web')?.package; - return Object.freeze({ - active: registry.platforms.find((platform) => platform.family === 'web'), - get: () => { - const platform = registry.resolvePlatform('web', missingPlatformPlugin, packageName); - if (platform.family !== 'web') throw new TypeError('Expected web platform registration'); - return platform; - }, - }); -} diff --git a/test/integration/provider-scenarios/harness.ts b/test/integration/provider-scenarios/harness.ts index b239103cab..b39efbe111 100644 --- a/test/integration/provider-scenarios/harness.ts +++ b/test/integration/provider-scenarios/harness.ts @@ -1,4 +1,4 @@ -import { webSelectionFixture } from '../../../src/platform-runtime-web-provider.fixtures.ts'; +import { webPlatformCompositionFixture } from '../../../src/platform-runtime-web-provider.fixtures.ts'; import type { DaemonWireRequest } from '@agent-device/contracts/command'; import type { DaemonResponse } from '@agent-device/kernel/contracts'; import assert from 'node:assert/strict'; @@ -172,12 +172,13 @@ export async function createProviderScenarioHarness( const providerModules = platformRuntime?.providerModules ?? createProviderPlatformRuntimeRegistrations(configuredRuntimes); - const web = webSelectionFixture(input.host, input.baseDir, { + const platforms = webPlatformCompositionFixture(input.host, input.baseDir, { openWebSessionNames: input.openWebSessionNames, ownedProcessRecords: rootDeps.ownedProcessRecords, }); + const { web } = platforms; const defaultDeviceRuntimeGateway = createPlatformRuntimeGateway({ - web, + platforms, host: input.host, assertShutdownAllowed: input.assertShutdownAllowed, providerRuntimes: configuredRuntimes, From b3a10957eb7512307c34e058274b6ff51f7426d2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 20 Nov 2026 11:43:28 +0100 Subject: [PATCH 4/7] refactor(plugins): separate claim reservations from setup --- packages/plugins/src/registry.ts | 224 +++++++++++++------------------ packages/plugins/src/validate.ts | 151 +++++++++++---------- src/host-replay.test.ts | 75 +++++++---- 3 files changed, 222 insertions(+), 228 deletions(-) diff --git a/packages/plugins/src/registry.ts b/packages/plugins/src/registry.ts index ff211ed3a9..07af3c33d8 100644 --- a/packages/plugins/src/registry.ts +++ b/packages/plugins/src/registry.ts @@ -107,52 +107,28 @@ export type ProviderRegistration = Readonly<{ /** Every id held in one claim space. */ type ClaimedClaims = Map>; -/** - * One contribution expanded into its own claim: its own record, setup outcome and cleanup entry. A - * claim reserved before the load settles carries no contribution until the factory answers it. - */ type Claim = PluggedClaim & { slot: Slot; - contribution?: Contribution; - failure?: unknown; + contribution: Contribution; + failure?: AppError; registration?: ProviderRegistration; platformSetup?: RegisteredPlatformSetup; replaySetup?: ReplayBackendSetup | ReplayExecutionSetup; replayLoading?: Promise; executionLoading?: Promise; - replayFailure?: unknown; + replayFailure?: AppError; }; -/** A candidate, its load outcome, and the claims it holds. */ +type FailedClaim = PluggedClaim & { slot: Slot; failure: AppError }; +type ClaimEntry = Claim | FailedClaim; + +/** A candidate's finalized claims, after its reservations and load have settled. */ type Slot = { candidate: PluginCandidate; - /** Why this slot cannot answer its claims; each unclaimed entry reports it. */ - failure?: unknown; - claims: Claim[]; + failure?: AppError; + claims: ClaimEntry[]; }; -/** A claim as the composition reads it: its kind, id, contribution and owning candidate. */ -export type ResolvedClaim = Readonly<{ - kind: ClaimKind; - id: string; - candidate: PluginCandidate; - contribution?: Contribution; -}>; - -/** What a root reads from the slots it does not own: each claim with its contribution and candidate. */ -function claimsOf(slots: readonly Slot[]): readonly ResolvedClaim[] { - return slots.flatMap(({ claims }) => - claims.map((claim) => - Object.freeze({ - kind: claim.kind, - id: claim.id, - candidate: claim.slot.candidate, - contribution: claim.contribution, - }), - ), - ); -} - /** Candidates whose claims are already reserved, with every load outcome settled. */ export type ResolvedProviderPlugins = Readonly<{ /** The connection callbacks of every loaded provider claim, by provider. */ @@ -160,8 +136,6 @@ export type ResolvedProviderPlugins = Readonly<{ /** Every provider id claimed, including failed and dormant plugins. */ claimedProviders: readonly string[]; inventory(): readonly PluginInventoryEntry[]; - /** Every claim the registry holds, with its contribution and owning candidate. */ - claims: readonly ResolvedClaim[]; /** @internal Consumed by {@link startProviderRegistry}, which owns setup and cleanup. */ slots: readonly Slot[]; }>; @@ -194,16 +168,16 @@ export async function resolveProviderPlugins( for (const candidate of candidates) { const slot: Slot = { candidate, claims: [] }; slots.push(slot); - reserveDeclaredClaims(slot, claimed, !candidate.dormant); - if (!candidate.dormant) await loadSlot(slot, claimed); + const reservations = reserveDeclaredClaims(candidate, claimed); + if (!candidate.dormant) await loadSlot(slot, claimed, reservations); } return Object.freeze({ connections: new Map( slots.flatMap(({ claims }) => claims.flatMap((claim) => { - if (claim.kind !== 'provider' || claim.failure !== undefined) return []; - const connection = (claim.contribution as ProviderContribution | undefined)?.connection; + if (!('contribution' in claim) || claim.contribution.kind !== 'provider') return []; + const { connection } = claim.contribution; return connection ? [ [ @@ -217,7 +191,6 @@ export async function resolveProviderPlugins( ), claimedProviders: [...(claimed.get('provider') ?? [])], inventory: () => slots.flatMap(describeSlot), - claims: Object.freeze(claimsOf(slots)), slots, }); } @@ -227,15 +200,13 @@ export async function resolveProviderPlugins( * of a kind and id wins; a later one is recorded as failed against its own slot, and so is a claim of * an id the host reserves. A dormant slot holds its claims without listing them. */ -function reserveDeclaredClaims(slot: Slot, claimed: ClaimedClaims, list: boolean): void { - for (const claim of slot.candidate.declaredClaims ?? []) { - const obstacle = claimObstacle(claimed, claim); - if (obstacle !== undefined) { - if (list) slot.claims.push({ ...claim, slot, failure: obstacle }); - continue; - } - if (list) slot.claims.push({ ...claim, slot }); - } +function reserveDeclaredClaims(candidate: PluginCandidate, claimed: ClaimedClaims) { + return new Map( + (candidate.declaredClaims ?? []).map((claim) => [ + claimKeyOf(claim), + { claim, failure: claimObstacle(claimed, claim) }, + ]), + ); } /** @@ -262,51 +233,49 @@ function reserveClaim(claimed: ClaimedClaims, claim: PluggedClaim): boolean { * A slot that declares no claims claims what its factory returns, so an embedder's plugin competes * for the same spaces the same way. */ -async function loadSlot(slot: Slot, claimed: ClaimedClaims): Promise { +async function loadSlot( + slot: Slot, + claimed: ClaimedClaims, + reservations: ReturnType, +): Promise { let raw: unknown; try { raw = await slot.candidate.load(); - const returnedClaims = validateAgentDevicePlugin(raw); - assertDeclaredClaims(slot.candidate, returnedClaims); - for (const { contribution, ...claim } of returnedClaims) { - const reserved = slot.claims.find( - (entry) => entry.contribution === undefined && claimKeyOf(entry) === claimKeyOf(claim), - ); - if (reserved !== undefined) { - reserved.contribution = contribution; - continue; - } - const obstacle = reserveClaim(claimed, claim) ? undefined : duplicateClaimError(claim); - slot.claims.push({ - ...claim, - slot, - contribution, - ...(obstacle !== undefined ? { failure: obstacle } : {}), + const returned = validateAgentDevicePlugin(raw); + assertDeclaredClaims(slot.candidate, returned); + const declaredOrder = [...reservations.keys()]; + slot.claims = [...returned] + .sort((a, b) => declaredOrder.indexOf(claimKeyOf(a)) - declaredOrder.indexOf(claimKeyOf(b))) + .map(({ contribution, ...claim }) => { + const reserved = reservations.get(claimKeyOf(claim)); + const failure = reserved ? reserved.failure : claimObstacle(claimed, claim); + return failure ? { ...claim, slot, failure } : { ...claim, slot, contribution }; }); - } } catch (error) { - slot.failure = asPluginFailure(error, 'plugin_load_failed'); - for (const claim of slot.claims) { - // A reservation reason (a duplicate or reserved id) is the actionable one; keep it. - if (claim.contribution === undefined) claim.failure ??= slot.failure; - } - nameFailedClaims(slot, claimed, raw); + const failure = asPluginFailure(error, 'plugin_load_failed'); + slot.failure = failure; + slot.claims = failedLoadClaims(slot, claimed, reservations, raw, failure); } } -/** - * Names the claims of a slot that failed before its contributions were readable, from the value it - * returned, and holds them: what the inventory reports and what a selection resolves must still say - * what this plugin was meant to provide. A slot whose metadata already declared its claims was named - * before the load and is left alone. Each claim carries the slot's own reason, which is the one the - * author can act on. - */ -function nameFailedClaims(slot: Slot, claimed: ClaimedClaims, raw: unknown): void { - if (slot.candidate.declaredClaims !== undefined || slot.claims.length > 0) return; - for (const claim of readableClaimsOfValue(raw)) { - reserveClaim(claimed, claim); - slot.claims.push({ ...claim, slot, failure: slot.failure }); +function failedLoadClaims( + slot: Slot, + claimed: ClaimedClaims, + reservations: ReturnType, + raw: unknown, + failure: AppError, +): FailedClaim[] { + if (slot.candidate.declaredClaims !== undefined) { + return [...reservations.values()].map(({ claim, failure: reservationFailure }) => ({ + ...claim, + slot, + failure: reservationFailure ?? failure, + })); } + return readableClaimsOfValue(raw).map((claim) => { + reserveClaim(claimed, claim); + return { ...claim, slot, failure }; + }); } /** After the factory runs, declared and returned claims must be exactly equal, unordered. */ @@ -345,19 +314,18 @@ export async function startProviderRegistry( policy: PluginRegistryPolicy, scope: RegistryScope = 'all', ): Promise { - await setUpClaims(resolved.slots, host, policy, scope); - const registrations = resolved.slots.flatMap(({ claims }) => - claims.flatMap(({ registration }) => (registration ? [registration] : [])), + const claims = resolved.slots.flatMap((slot) => + slot.claims.filter((claim) => 'contribution' in claim), ); + await setUpClaims(claims, host, policy, scope); + const registrations = claims.flatMap(({ registration }) => (registration ? [registration] : [])); let closed = false; const inventory = [...resolved.inventory()]; const refreshInventory = () => inventory.splice(0, inventory.length, ...resolved.inventory()); return Object.freeze({ registrations, platforms: Object.freeze( - resolved.slots.flatMap(({ claims }) => - claims.flatMap(({ platformSetup }) => (platformSetup ? [platformSetup] : [])), - ), + claims.flatMap(({ platformSetup }) => (platformSetup ? [platformSetup] : [])), ), claimedProviders: resolved.claimedProviders, inventory, @@ -392,40 +360,28 @@ export async function startProviderRegistry( // their teardowns run concurrently and one hanging disposer cannot stall the others. close: once(async () => { closed = true; - const activated = resolved.slots.flatMap(({ claims }) => - claims.filter( - (claim) => - claim.registration !== undefined || - claim.replaySetup !== undefined || - claim.platformSetup !== undefined, - ), + const activated = claims.filter( + (claim) => claim.registration || claim.replaySetup || claim.platformSetup, ); return await Promise.all([...activated].reverse().map((claim) => cleanUpClaim(claim))); }), }); } -/** - * Sets up every claim of every slot that has not already failed, in candidate order. The provider - * path sets up provider claims only; the replay path sets up replay claims only. - */ async function setUpClaims( - slots: readonly Slot[], + claims: readonly Claim[], host: HostEnvironment, policy: PluginRegistryPolicy, scope: RegistryScope, ): Promise { - for (const slot of slots) { - for (const claim of slot.claims) { - if (claim.failure !== undefined) continue; - try { - await setUpClaim(claim, host, policy, scope); - } catch (error) { - claim.failure = asPluginFailure(error, 'plugin_setup_failed'); - claim.registration = undefined; - claim.replaySetup = undefined; - claim.platformSetup = undefined; - } + for (const claim of claims) { + try { + await setUpClaim(claim, host, policy, scope); + } catch (error) { + claim.failure = asPluginFailure(error, 'plugin_setup_failed'); + claim.registration = undefined; + claim.replaySetup = undefined; + claim.platformSetup = undefined; } } } @@ -437,9 +393,6 @@ async function setUpClaim( scope: RegistryScope, ): Promise { const contribution = claim.contribution; - if (contribution === undefined) { - throw invalidPlugin(`Plugin claim has no contribution: ${claimKeyOf(claim)}`); - } if (contribution.kind === 'provider') { if (scope === 'all') await setUpProviderClaim(claim, contribution, host, policy); return; @@ -451,15 +404,15 @@ async function setUpClaim( reason: 'platform_host_missing', }); const result = await contribution.setup(policy.platformHost); - validateClaimSetup({ kind: contribution.kind, id: contribution.family }, result); - claim.platformSetup = Object.freeze(result); + claim.platformSetup = Object.freeze( + validateClaimSetup({ kind: contribution.kind, id: contribution.family }, result), + ); return; } if (scope === 'platforms') return; const result = await contribution.setup(createReplaySetupHost()); try { - validateClaimSetup(claim, result); - claim.replaySetup = result as ReplayBackendSetup | ReplayExecutionSetup; + claim.replaySetup = validateClaimSetup({ kind: contribution.kind, id: claim.id }, result); } catch (error) { await cleanUpRejectedSetup(result); throw error; @@ -472,7 +425,8 @@ async function resolveRegisteredReplayBackend( host: import('@agent-device/contracts/replay-backend').ReplayBackendHost, ): Promise { if (claim.failure !== undefined) throw replayClaimError(claim); - const replayBackend = (claim.replaySetup as ReplayBackendSetup | undefined)?.replayBackend; + const setup = claim.replaySetup; + const replayBackend = setup && 'replayBackend' in setup ? setup.replayBackend : undefined; if (!replayBackend) throw invalidPlugin(`Replay backend was not set up: ${claim.id}`); return await (claim.replayLoading ??= Promise.resolve().then(async () => { try { @@ -494,7 +448,8 @@ async function resolveRegisteredReplayExecution( refreshInventory: () => void, ): Promise { if (claim.failure !== undefined) throw replayClaimError(claim); - const execution = (claim.replaySetup as ReplayExecutionSetup | undefined)?.execution; + const setup = claim.replaySetup; + const execution = setup && 'execution' in setup ? setup.execution : undefined; if (!execution) throw invalidPlugin('Native replay plugin must provide execution.create()'); return await (claim.executionLoading ??= Promise.resolve().then(async () => { try { @@ -531,7 +486,7 @@ function findClaim( claim: PluggedClaim, packageName: string | undefined, assertSelectionCurrent?: (packageName: string) => void, -): Claim | undefined { +): ClaimEntry | undefined { const wanted = claimKeyOf(claim); for (const slot of resolved.slots) { const held = slot.claims.find((entry) => claimKeyOf(entry) === wanted); @@ -548,7 +503,7 @@ function findClaim( slot.claims.length === 0 && slot.failure !== undefined, ); - if (failedSlot) { + if (failedSlot?.failure !== undefined) { assertStoreSelectionCurrent(failedSlot, assertSelectionCurrent); return { ...claim, slot: failedSlot, failure: failedSlot.failure }; } @@ -563,15 +518,18 @@ function requireReplayClaim( assertSelectionCurrent?: (packageName: string) => void, ): Claim { const found = findClaim(resolved, claim, packageName, assertSelectionCurrent); - if (found) return found; + if (found) { + if ('contribution' in found) return found; + throw replayClaimError(found); + } throw new AppError('INVALID_ARGS', `Replay backend is not installed: ${claim.id}`, { reason: 'plugin-not-installed', backend: claim.id, }); } -function replayClaimError(claim: Claim): AppError { - const error = asPluginFailure(claim.failure ?? claim.replayFailure, 'plugin_load_failed'); +function replayClaimError(claim: ClaimEntry): AppError { + const error = asPluginFailure(claimFailure(claim), 'plugin_load_failed'); const packageName = claim.slot.candidate.package; return new AppError( error.code, @@ -740,8 +698,12 @@ function describeSlot(slot: Slot): PluginInventoryEntry[] { ]; } -function describeClaim(claim: Claim): PluginInventoryEntry[] { - const failure = claim.failure ?? claim.replayFailure; +function claimFailure(claim: ClaimEntry): AppError | undefined { + return claim.failure ?? ('contribution' in claim ? claim.replayFailure : undefined); +} + +function describeClaim(claim: ClaimEntry): PluginInventoryEntry[] { + const failure = claimFailure(claim); const { candidate } = claim.slot; const base = { ...identityOfClaim(claim), @@ -762,7 +724,7 @@ function describeClaim(claim: Claim): PluginInventoryEntry[] { { ...base, state: 'active', - credentials: claimCredentials(claim.contribution), + credentials: claimCredentials('contribution' in claim ? claim.contribution : undefined), }, ]; } diff --git a/packages/plugins/src/validate.ts b/packages/plugins/src/validate.ts index 28d579ddf3..3186859ce7 100644 --- a/packages/plugins/src/validate.ts +++ b/packages/plugins/src/validate.ts @@ -29,28 +29,27 @@ export type ClaimIdentity = Readonly< >; /** Deterministic order for reading a package's static claims and for claim spaces. */ -const CLAIM_KINDS: Readonly> = { +const CLAIM_KINDS: { readonly [Kind in ClaimKind]: ClaimKindSpec } = { provider: { metadataField: 'provider', contributionIdField: 'provider', - reservedError: (id) => + rejectId: (id) => ROUTING_PROVIDER_IDENTITIES.includes(id) - ? new AppError('INVALID_ARGS', `Provider id is reserved for routing: ${id}`, { - reason: 'reserved_provider', - provider: id, - }) + ? { reason: 'reserved_provider', message: `Provider id is reserved for routing: ${id}` } : undefined, duplicateReason: 'duplicate_provider', identityFor: (id) => ({ provider: id }), readMetadata: (value) => readableClaimId(value, 'provider'), readContribution: (value) => ({ kind: 'provider', id: readProviderContribution(value) }), - validateSetup: () => {}, + validateSetup: () => undefined, }, platform: { metadataField: 'platform', contributionIdField: 'family', - reservedError: (id) => - isPlatform(id) ? undefined : invalidPlugin(`Unknown platform family: ${id}`), + rejectId: (id) => + isPlatform(id) + ? undefined + : { reason: 'invalid_plugin', message: `Unknown platform family: ${id}` }, duplicateReason: 'duplicate_platform', identityFor: (id) => ({ platform: id }), readMetadata: (value) => readableClaimId(value, 'platform'), @@ -66,16 +65,18 @@ const CLAIM_KINDS: Readonly> = { 'replay-backend': { metadataField: 'replayBackend', contributionIdField: 'backend', - reservedError: (id) => + rejectId: (id) => id === NATIVE_REPLAY_BACKEND - ? new AppError( - 'INVALID_ARGS', - `Replay backend id is reserved for native execution: ${id}`, - { - reason: 'reserved_replay_backend', - backend: id, - }, - ) + ? { + reason: 'reserved_replay_backend', + message: `Replay backend id is reserved for native execution: ${id}`, + } + : undefined, + readLegacyClaim: (value) => + value.kind === 'replay-backend' && + isClaimId(value.backend) && + value.backend !== NATIVE_REPLAY_BACKEND + ? value.backend : undefined, duplicateReason: 'duplicate_replay_backend', identityFor: (id) => ({ backend: id }), @@ -89,14 +90,17 @@ const CLAIM_KINDS: Readonly> = { } return { kind: 'replay-backend', id: value.backend }; }, - validateSetup: (value) => { - validateReplayBackendSetup(value); - }, + validateSetup: validateReplayBackendSetup, }, 'replay-execution': { metadataField: 'replayExecution', contributionIdField: 'id', duplicateReason: 'duplicate_replay_execution', + readNamedId: (value) => (value === true ? NATIVE_REPLAY_BACKEND : namedId(value)), + readLegacyClaim: (value) => + value.kind === 'replay-backend' && value.backend === NATIVE_REPLAY_BACKEND + ? NATIVE_REPLAY_BACKEND + : undefined, identityFor: (id) => ({ backend: id }), readMetadata: (value) => { // One spelling for this claim: the id itself belongs to the kind, not to the package. @@ -114,24 +118,29 @@ const CLAIM_KINDS: Readonly> = { } return { kind: 'replay-execution', id: NATIVE_REPLAY_BACKEND }; }, - validateSetup: (value) => { - validateReplayExecutionSetup(value); - }, + validateSetup: validateReplayExecutionSetup, }, -} satisfies Readonly>; +}; /** * One claim kind's whole contract: the metadata field that spells its id, how each source reads that * id, what its space reserves, what a lost duplicate race reports, and the setup shape it answers. * A new kind is one entry here plus its contribution type. */ -type ClaimKindSpec = Readonly<{ +type ClaimSetup = { + provider: undefined; + platform: RegisteredPlatformSetup; + 'replay-backend': ReplayBackendSetup; + 'replay-execution': ReplayExecutionSetup; +}; + +type ClaimKindSpec = Readonly<{ /** The `agent-device` package.json field that spells this kind's id. */ metadataField: string; /** The contribution field that spells this kind's id. */ contributionIdField: string; /** Ids no plugin may claim in this space. */ - reservedError?(id: string): AppError | undefined; + rejectId?(id: string): { reason: string; message: string } | undefined; /** What a claim that loses this space's duplicate race reports. */ duplicateReason: string; /** How this space names the claim in the inventory and in cleanup outcomes. */ @@ -140,8 +149,12 @@ type ClaimKindSpec = Readonly<{ readMetadata(value: unknown): string; /** Validates one contribution of this kind and answers its claim. */ readContribution(value: Record): PluggedClaim; + /** Reads the name of a malformed contribution for failure reporting. */ + readNamedId?(value: unknown): string | undefined; + /** Reads the identity of a refused legacy contribution. */ + readLegacyClaim?(value: Record): string | undefined; /** Checks what setup returned before the registry keeps the claim. */ - validateSetup(value: unknown, id: string): void; + validateSetup(value: unknown, id: string): ClaimSetup[Kind]; }>; /** The claim spaces, in the order a package's static claims are read and compared. */ @@ -189,7 +202,15 @@ export function claimKeyOf(claim: PluggedClaim): string { /** Why a claim cannot be held at all: a reserved id belongs to the host, not to a package. */ export function reservedClaimError(claim: PluggedClaim): AppError | undefined { - return CLAIM_KINDS[claim.kind].reservedError?.(claim.id); + const spec = CLAIM_KINDS[claim.kind]; + const rejection = spec.rejectId?.(claim.id); + if (rejection) { + return new AppError('INVALID_ARGS', rejection.message, { + reason: rejection.reason, + ...spec.identityFor(claim.id), + }); + } + return undefined; } /** Whether anything may still claim this id: a reserved id belongs to the host, not to a package. */ @@ -205,43 +226,27 @@ function assertClaimAvailable(claim: PluggedClaim): void { */ export function readableClaimsOfValue(value: unknown): readonly PluggedClaim[] { if (!isRecord(value)) return []; - const claims: PluggedClaim[] = [...versionTwoReplayClaims(value)]; - for (const kind of CLAIM_KIND_ORDER) { + return CLAIM_KIND_ORDER.flatMap((kind) => { const spec = CLAIM_KINDS[kind]; - const declared = claimIdSpelledBy(kind, value[spec.metadataField]); - if (declared !== undefined) { - claims.push({ kind, id: declared }); - continue; - } - if (!Array.isArray(value.contributes)) continue; - for (const contribution of value.contributes) { - if (!isRecord(contribution) || contribution.kind !== kind) continue; - const named = claimIdSpelledBy(kind, contribution[spec.contributionIdField]); - if (named !== undefined) claims.push({ kind, id: named }); - } - } - return claims; + const readNamedId = spec.readNamedId ?? namedId; + const declared = readNamedId(value[spec.metadataField]); + const legacy = spec.readLegacyClaim?.(value); + const ids = declared === undefined ? namedContributionIds(value.contributes, kind) : [declared]; + return (legacy === undefined ? ids : [legacy, ...ids]).map((id) => ({ kind, id })); + }); } -/** - * The version 2 replay shape, `{ kind: 'replay-backend', backend }` at the top level, which the host - * refuses. Its reserved id `ad` named native execution, so a refused candidate still names its claim. - */ -function versionTwoReplayClaims(value: Record): readonly PluggedClaim[] { - if (value.kind !== 'replay-backend' || !isClaimId(value.backend)) return []; - return [ - value.backend === NATIVE_REPLAY_BACKEND - ? { kind: 'replay-execution', id: NATIVE_REPLAY_BACKEND } - : { kind: 'replay-backend', id: value.backend }, - ]; -} - -/** The id this value spells for a kind, or nothing when it does not spell one. */ -function claimIdSpelledBy(kind: ClaimKind, value: unknown): string | undefined { - // The native claim's id belongs to the kind, so its metadata spells it as `true`. - if (kind === 'replay-execution' && value === true) { - return NATIVE_REPLAY_BACKEND; - } +function namedContributionIds(contributions: unknown, kind: ClaimKind): readonly string[] { + if (!Array.isArray(contributions)) return []; + const { contributionIdField, readNamedId = namedId } = CLAIM_KINDS[kind]; + return contributions.flatMap((contribution) => { + if (!isRecord(contribution) || contribution.kind !== kind) return []; + const id = readNamedId(contribution[contributionIdField]); + return id === undefined ? [] : [id]; + }); +} + +function namedId(value: unknown): string | undefined { return isClaimId(value) ? value : undefined; } @@ -260,13 +265,11 @@ export function identityOfClaim(claim: PluggedClaim): ClaimIdentity { } /** Checks a setup result against the kind that asked for it. */ -export function validateClaimSetup( - claim: PluggedClaim & { kind: 'platform' }, +export function validateClaimSetup( + claim: PluggedClaim & { kind: Kind }, value: unknown, -): asserts value is RegisteredPlatformSetup; -export function validateClaimSetup(claim: PluggedClaim, value: unknown): void; -export function validateClaimSetup(claim: PluggedClaim, value: unknown): void { - CLAIM_KINDS[claim.kind].validateSetup(value, claim.id); +): ClaimSetup[Kind] { + return CLAIM_KINDS[claim.kind].validateSetup(value, claim.id); } /** @@ -290,7 +293,15 @@ export function readPluginPackageClaims(field: unknown): readonly PluggedClaim[] return claims; } -function validatePlatformSetup(value: unknown, family: string): void { +function validatePlatformSetup(value: unknown, family: string): RegisteredPlatformSetup { + assertPlatformSetup(value, family); + return value; +} + +function assertPlatformSetup( + value: unknown, + family: string, +): asserts value is RegisteredPlatformSetup { if ( !isRecord(value) || value.family !== family || diff --git a/src/host-replay.test.ts b/src/host-replay.test.ts index 2831ed7389..394e1642bc 100644 --- a/src/host-replay.test.ts +++ b/src/host-replay.test.ts @@ -6,7 +6,8 @@ import { prepareDaemonCommandRequest } from '@agent-device/command-surface'; import { createAgentDeviceClient } from '@agent-device/client'; import type { AgentDevicePlugin } from './sdk/plugins.ts'; import type { ReplayBackendContribution } from '@agent-device/plugins/replay-backend'; -import { resolveProviderPlugins } from '@agent-device/plugins/registry'; +import { resolveProviderPlugins, startProviderRegistry } from '@agent-device/plugins/registry'; +import type { PluggedClaim } from '@agent-device/plugins/validate'; import { storePluginCandidates } from '@agent-device/plugins/store'; import { createRuntimeStateHandle } from '@agent-device/host-kit/runtime-slots'; import { createTestHostEnvironment, mkdtempForTestSync } from '@agent-device/test-kit'; @@ -115,39 +116,59 @@ function fixture() { return { root, entry, host, stateDir: path.join(root, 'state') }; } -async function nativePlugin(): Promise { - const resolved = await resolveProviderPlugins(await storePluginCandidates(process.env)); - const claim = resolved.claims.find( - (claim) => claim.kind === 'replay-execution' && claim.id === 'ad', +async function startReplayFixtureRegistry({ kind, id }: PluggedClaim) { + const host = { env: process.env, cwd: process.cwd() }; + const candidates = await storePluginCandidates(host.env); + return await startProviderRegistry( + await resolveProviderPlugins( + candidates.filter((candidate) => + candidate.declaredClaims?.some((claim) => claim.kind === kind && claim.id === id), + ), + ), + host, + { + adaptWebDriver: async () => { + throw new Error('Replay fixture cannot start providers'); + }, + }, + 'replay-backends', ); - if (!claim?.contribution) throw new Error('Native replay test installation is missing'); +} + +function nativePlugin(): AgentDevicePlugin { return { apiVersion: 3, - contributes: [claim.contribution as AgentDevicePlugin['contributes'][number]], - } satisfies AgentDevicePlugin; + contributes: [ + { + kind: 'replay-execution', + id: 'ad', + async setup() { + const registry = await startReplayFixtureRegistry({ kind: 'replay-execution', id: 'ad' }); + return { + execution: { create: () => registry.resolveReplayExecution() }, + dispose: async () => { + await registry.close(); + }, + }; + }, + }, + ], + }; } -async function trackedPlugin() { - const resolved = await resolveProviderPlugins(await storePluginCandidates(process.env)); - const claim = resolved.claims.find( - (claim) => claim.kind === 'replay-backend' && claim.id === 'maestro', - ); - const maestro = claim?.contribution; - if (!maestro || maestro.kind !== 'replay-backend') - throw new Error('Maestro test installation is missing'); +function trackedPlugin() { const calls = { setup: 0, create: 0, collect: 0, run: 0, dispose: 0 }; const contribution: ReplayBackendContribution = { - ...maestro, - setup: async (host) => { + kind: 'replay-backend', + backend: 'maestro', + setup: async () => { calls.setup += 1; - const setup = await maestro.setup(host); - if (!setup.replayBackend) throw new Error('Expected a format backend'); - const replayBackend = setup.replayBackend; + const registry = await startReplayFixtureRegistry({ kind: 'replay-backend', id: 'maestro' }); return { replayBackend: { create: async (host) => { calls.create += 1; - const backend = await replayBackend.create(host); + const backend = await registry.resolveReplayBackend('maestro', host); return { ...backend, collectSourceFiles: (params) => { @@ -163,7 +184,7 @@ async function trackedPlugin() { }, dispose: async () => { calls.dispose += 1; - await setup.dispose?.(); + await registry.close(); }, }; }, @@ -181,8 +202,8 @@ test.each(['replay', 'test', 'batch-test'] as const)( try { await state.run(async () => { const f = fixture(); - const { plugin, calls } = await trackedPlugin(); - const host = await startAgentDevice({ ...f, plugins: [plugin, await nativePlugin()] }); + const { plugin, calls } = trackedPlugin(); + const host = await startAgentDevice({ ...f, plugins: [plugin, nativePlugin()] }); const input = { path: f.entry, platform: 'ios' as const, backend: 'maestro' }; const testInput = { paths: [f.entry], platform: 'ios' as const, backend: 'maestro' }; try { @@ -244,8 +265,8 @@ test('isolated embedded clients ignore a conflicting store and never borrow anot path.join(f.host.env.AGENT_DEVICE_HOME!, 'config.json'), JSON.stringify({ plugins: { '@agent-device/maestro': { installation } } }), ); - const firstPlugin = await trackedPlugin(); - const secondPlugin = await trackedPlugin(); + const firstPlugin = trackedPlugin(); + const secondPlugin = trackedPlugin(); const first = await startAgentDevice({ ...f, plugins: [firstPlugin.plugin] }); let second: Awaited> | undefined; try { From 5df2b3cbc1103b1d49e6982327fda0eb491d6e36 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 20 Nov 2026 13:22:22 +0100 Subject: [PATCH 5/7] fix(plugins): use the left bound for Node hyphen ranges --- packages/plugins/src/discovery.test.ts | 10 ++++++++-- packages/plugins/src/discovery.ts | 3 ++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/packages/plugins/src/discovery.test.ts b/packages/plugins/src/discovery.test.ts index 31ea661dd9..061156ff61 100644 --- a/packages/plugins/src/discovery.test.ts +++ b/packages/plugins/src/discovery.test.ts @@ -3,8 +3,8 @@ import { execFileSync } from 'node:child_process'; import fs from 'node:fs'; import path from 'node:path'; import { test } from 'vitest'; -import { mkdtempForTestSync } from '@agent-device/test-kit'; -import { discoverPluginEntry } from './discovery.ts'; +import { mkdtempForTestSync, withNodeRuntime } from '@agent-device/test-kit'; +import { assertNodeFloor, discoverPluginEntry } from './discovery.ts'; type Case = { name: string; @@ -185,3 +185,9 @@ test('an entry outside the installed package is refused', () => { (error as { details?: { reason?: string } }).details?.reason === 'plugin_load_failed', ); }); + +test('the left side of a Node hyphen range accepts that version', async () => { + await withNodeRuntime({ version: '18.0.0' }, () => { + assert.doesNotThrow(() => assertNodeFloor({ engines: { node: '18 - 20' } })); + }); +}); diff --git a/packages/plugins/src/discovery.ts b/packages/plugins/src/discovery.ts index 09edb54a08..fd34378de1 100644 --- a/packages/plugins/src/discovery.ts +++ b/packages/plugins/src/discovery.ts @@ -40,7 +40,8 @@ function nodeRangeFloor(range: string): string | undefined { let lowest: Version | undefined; for (const branch of range.split('||')) { let branchFloor: Version | undefined; - for (const comparator of branch.trim().split(/\s+/)) { + const [lowerBound = ''] = branch.split(' - ', 1); + for (const comparator of lowerBound.trim().split(/\s+/)) { const parsed = parseComparator(comparator); if (parsed === undefined) continue; if (branchFloor === undefined || compareVersionsTuple(parsed, branchFloor) > 0) { From 5418f5f56b685ee5165e54f06ec51730dae5e5f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 20 Nov 2026 10:18:51 +0100 Subject: [PATCH 6/7] chore(gates): verify the web plugin stays outside packed core --- docs/agents/web-backend.md | 27 ++++----- packages/platform-web/build.mjs | 16 ++++++ scripts/__tests__/packed-core-absence.test.ts | 36 ++++++++++++ scripts/check-package.ts | 16 ++++++ .../layering/contracts-exports.snapshot.json | 1 + .../layering/platform-package-policy.test.ts | 47 ++++++++++++++-- scripts/layering/platform-package-policy.ts | 56 ++++++++++++++++++- .../layering/platform-package-repository.ts | 4 ++ scripts/lib/packed-core-absence.ts | 23 ++++++++ test/repo-guards/npm-package-scripts.test.ts | 2 +- 10 files changed, 206 insertions(+), 22 deletions(-) create mode 100644 scripts/__tests__/packed-core-absence.test.ts create mode 100644 scripts/lib/packed-core-absence.ts diff --git a/docs/agents/web-backend.md b/docs/agents/web-backend.md index e805ac95d6..de9ad99a85 100644 --- a/docs/agents/web-backend.md +++ b/docs/agents/web-backend.md @@ -1,22 +1,19 @@ # Web Backend -The `@agent-device/web` plugin provides web automation through a managed `agent-browser` backend. +The `@agent-device/web` plugin uses managed `agent-browser`. -- Runtime web commands resolve the backend only from the state-dir managed install at `tools/agent-browser/`. -- Normal `--platform web` commands do not install the managed backend on first use. - If the backend is missing, they fail with a setup hint. -- Before first web automation, install the plugin with `agent-device plugins add @agent-device/web`. -- After you install the plugin, run `agent-device web setup` for the state directory you will use. -- To run the backend health check, use `agent-device web doctor`. -- Each backend call spawns the package's declared `bin` entry with the current Node runtime. - It never spawns the `node_modules/.bin` console shim. - A shell would reintroduce hazards from argument quoting. - Only `runManagedAgentBrowser` executes the backend. +- Before web automation, run `agent-device plugins add @agent-device/web`. +- To install the backend in the state directory, run `agent-device web setup`. +- To check the backend, run `agent-device web doctor`. +- Runtime web commands use `tools/agent-browser/` in the state directory. +- Only `web setup` installs the backend. +- If the backend is absent, return the setup hint. +- Use `runManagedAgentBrowser` to run the package's declared JavaScript entry with the current Node runtime. +- Do not use the `node_modules/.bin` shim. -Do not document direct `agent-browser` commands as agent-device features. -Web `network dump` is the narrow exception. -It adapts `agent-browser network requests` to the existing agent-device network evidence shape. -Until an explicit agent-device command design exists for them, exclude these features from the minimal web surface: +Do not expose direct `agent-browser` commands. +Use `web network dump` to adapt `agent-browser network requests` to agent-device network evidence. +Keep these operations out of the web surface: - Browser-specific network routing/interception/HAR. - CDP. diff --git a/packages/platform-web/build.mjs b/packages/platform-web/build.mjs index 0374440887..e81d5a6bde 100644 --- a/packages/platform-web/build.mjs +++ b/packages/platform-web/build.mjs @@ -1,5 +1,21 @@ +import { readFileSync } from 'node:fs'; import { build } from 'tsdown'; import { providerPluginBuildConfig } from '@agent-device/build-config'; +import webPlatformPlugin from './src/index.ts'; + +const { 'agent-device': manifest } = JSON.parse( + readFileSync(new URL('./package.json', import.meta.url), 'utf8'), +); +const { apiVersion, contributes } = webPlatformPlugin(); +const [platform] = contributes; +if ( + apiVersion !== manifest.apiVersion || + contributes.length !== 1 || + platform.kind !== 'platform' || + platform.family !== manifest.platform +) { + throw new Error('The managed web factory must match its package claim'); +} await build({ ...providerPluginBuildConfig, diff --git a/scripts/__tests__/packed-core-absence.test.ts b/scripts/__tests__/packed-core-absence.test.ts new file mode 100644 index 0000000000..e55d848733 --- /dev/null +++ b/scripts/__tests__/packed-core-absence.test.ts @@ -0,0 +1,36 @@ +import { expect, test } from 'vitest'; +import { packedCoreAbsenceFailures } from '../lib/packed-core-absence.ts'; + +const exclusions = [ + { + owner: 'fixture', + paths: [/^dist\/src\/agent-browser-tool\.js$/], + markers: ['Managed web backend install produced no runnable entry.'], + }, +]; + +test('packed core can keep web help and adapters', () => { + expect( + packedCoreAbsenceFailures( + exclusions, + ['dist/src/platform-runtime-network-web-transport.js', 'dist/src/plugin.d.ts'], + () => 'agent-device plugins add @agent-device/web', + ), + ).toEqual([]); +}); + +test('packed core identifies the forbidden paths and bundled implementation markers', () => { + expect( + packedCoreAbsenceFailures( + exclusions, + ['dist/src/agent-browser-tool.js', 'dist/src/reassigned-chunk.js'], + (file) => + file.endsWith('reassigned-chunk.js') + ? 'Managed web backend install produced no runnable entry.' + : '', + ), + ).toEqual([ + 'fixture: forbidden packed path dist/src/agent-browser-tool.js', + 'fixture: forbidden implementation marker in dist/src/reassigned-chunk.js: Managed web backend install produced no runnable entry.', + ]); +}); diff --git a/scripts/check-package.ts b/scripts/check-package.ts index 0bb72f6733..525e363a9a 100644 --- a/scripts/check-package.ts +++ b/scripts/check-package.ts @@ -36,6 +36,7 @@ import { parseNpmPackOutput, type NpmPackEntry, } from './size-report-package.mjs'; +import { packedCoreAbsenceFailures } from './lib/packed-core-absence.ts'; import { testOnlyContentFailures, testOnlyPathFailures } from './lib/shipped-test-code.ts'; import { DAEMON_SOURCE_ENTRY, isSourceCheckoutProjectRoot } from '@agent-device/host-kit/version'; @@ -44,6 +45,17 @@ type PackedManifest = PackedDependencies & { bin: Record; }; +const EXCLUDED_IMPLEMENTATIONS = [ + { + owner: 'web platform', + paths: [/(?:^|\/)platform-web\//, /^dist\/src\/agent-browser-.*\.js$/], + markers: [ + 'Managed web backend install produced no runnable entry.', + 'web_agent_browser_process_reap_failed', + ], + }, +] as const; + const repoRoot = path.resolve(import.meta.dirname, '..'); const packDestinationFlag = '--pack-destination'; const verifySnapshotBridgePreparation = process.argv.includes( @@ -248,6 +260,10 @@ try { context: `The build packed from ${repoRoot}`, }); const packedPaths = packedEntries.map((file) => file.path); + const excluded = packedCoreAbsenceFailures(EXCLUDED_IMPLEMENTATIONS, packedPaths, (packedPath) => + fs.readFileSync(path.join(repoRoot, packedPath), 'utf8'), + ); + if (excluded.length > 0) throw new Error(excluded.join('\n')); lintTarball(tarball); const installedRoot = installIntoCleanConsumer(tarball); // A user's machine is the tree that has to carry the attribution, so the content policy runs again diff --git a/scripts/layering/contracts-exports.snapshot.json b/scripts/layering/contracts-exports.snapshot.json index 8da152a7db..303c160ed7 100644 --- a/scripts/layering/contracts-exports.snapshot.json +++ b/scripts/layering/contracts-exports.snapshot.json @@ -91,6 +91,7 @@ "@agent-device/contracts/platform-runtime-host", "@agent-device/contracts/platform-runtime-operations", "@agent-device/contracts/platform-runtime-unavailable", + "@agent-device/contracts/plugin-installation", "@agent-device/contracts/plugin-inventory", "@agent-device/contracts/progress", "@agent-device/contracts/provider-profile-fields", diff --git a/scripts/layering/platform-package-policy.test.ts b/scripts/layering/platform-package-policy.test.ts index 388696057f..06e78c1d59 100644 --- a/scripts/layering/platform-package-policy.test.ts +++ b/scripts/layering/platform-package-policy.test.ts @@ -1,4 +1,5 @@ import assert from 'node:assert/strict'; +import { createRequire } from 'node:module'; import { test } from 'node:test'; import { CANONICAL_PLATFORM_FAMILIES, @@ -21,7 +22,13 @@ function declarations(): PlatformPackageDeclaration[] { return CANONICAL_PLATFORM_FAMILIES.map((family) => ({ dir: `packages/platform-${family}`, family, - name: `@agent-device/platform-${family}`, + name: family === 'web' ? '@agent-device/web' : `@agent-device/platform-${family}`, + ...(family === 'web' + ? { + managedClaim: { platform: family, apiVersion: 3 }, + publishedSubpaths: ['./agent-device'], + } + : {}), private: true, exportedSubpaths: family === 'apple' @@ -53,9 +60,11 @@ function declarations(): PlatformPackageDeclaration[] { '@agent-device/platform-android/snapshot-capture-fixtures', '@agent-device/platform-android/ui-hierarchy-fixtures', ] - : family === 'harmonyos' || family === 'linux' || family === 'web' - ? [`@agent-device/platform-${family}`, `@agent-device/platform-${family}/interactor`] - : [`@agent-device/platform-${family}`], + : family === 'web' + ? ['@agent-device/web/agent-device'] + : family === 'harmonyos' || family === 'linux' + ? [`@agent-device/platform-${family}`, `@agent-device/platform-${family}/interactor`] + : [`@agent-device/platform-${family}`], })); } @@ -753,6 +762,7 @@ test('composition imports are category-based for future contracts and host adapt test('Node resolves only each platform package root facade', () => { for (const family of CANONICAL_PLATFORM_FAMILIES) { + if (family === 'web') continue; const specifier = `@agent-device/platform-${family}`; assert.ok(import.meta.resolve(specifier).endsWith(`packages/platform-${family}/src/index.ts`)); assert.throws( @@ -762,6 +772,18 @@ test('Node resolves only each platform package root facade', () => { } }); +test('only the plugin scope resolves the managed web entry', () => { + assert.throws(() => import.meta.resolve('@agent-device/web/agent-device'), /Cannot find package/); + const resolveWeb = createRequire( + new URL('../../packages/platform-web/package.json', import.meta.url), + ); + assert.match( + resolveWeb.resolve('@agent-device/web/agent-device'), + /platform-web[/\\]src[/\\]index\.ts$/, + ); + assert.throws(() => resolveWeb.resolve('@agent-device/web'), /No "exports" main/); +}); + test('the retired src/platforms zone rejects every production, test, and fixture file', () => { const planted = [ 'src/platforms/__tests__/install-source.test.ts', @@ -830,3 +852,20 @@ test('a provision-kit import of a concrete platform package fails closed', () => /may import '@agent-device\/platform-android'/, ); }); + +test('managed platform code enters core only through the registry', () => { + const file = 'src/platform-runtime/consumer.ts'; + const violations = checkPlatformPackagePolicy( + new Map([ + ['src/platform-runtime.ts', ''], + [file, "void import('@agent-device/web/agent-device')"], + ]), + declarations(), + ); + assert.ok( + violations.some( + (finding) => + finding.file === file && finding.message.includes('only through the plugin registry'), + ), + ); +}); diff --git a/scripts/layering/platform-package-policy.ts b/scripts/layering/platform-package-policy.ts index c3dfcd0dfd..40834d7699 100644 --- a/scripts/layering/platform-package-policy.ts +++ b/scripts/layering/platform-package-policy.ts @@ -36,6 +36,8 @@ export type PlatformPackageDeclaration = { family: string; name: string; private: boolean; + managedClaim?: { platform?: unknown; apiVersion?: unknown }; + publishedSubpaths?: readonly string[]; exportedSubpaths: readonly string[]; }; const COMPOSITION_FILE = 'src/platform-runtime.ts'; @@ -109,6 +111,10 @@ const MECHANICS_FACET_SUBPATHS: Readonly>> = { + web: '@agent-device/web', +}; + const INTERACTOR_COMPOSITION_FILE = 'src/core/interactors/register-builtins.ts'; function isInteractorSubpathImport( @@ -209,6 +215,31 @@ function isTestKitTestImport(file: string, specifier: string): boolean { return specifier === '@agent-device/test-kit' && !isProductionSourceFile(file); } +function managedPlatformDeclarationFailures( + declaration: PlatformPackageDeclaration, + expectedName: string, +): LayeringViolation[] { + const file = `${declaration.dir}/package.json`; + if ( + declaration.name !== expectedName || + declaration.managedClaim?.platform !== declaration.family || + declaration.managedClaim?.apiVersion !== 3 || + declaration.exportedSubpaths.length !== 1 || + declaration.exportedSubpaths[0] !== `${expectedName}/agent-device` || + declaration.publishedSubpaths?.length !== 1 || + declaration.publishedSubpaths[0] !== './agent-device' + ) { + return [ + violation( + file, + 1, + `Managed platform must declare its family and export only ${expectedName}/agent-device`, + ), + ]; + } + return []; +} + function checkDeclarations(packages: readonly PlatformPackageDeclaration[]): LayeringViolation[] { const violations: LayeringViolation[] = []; for (const family of CANONICAL_PLATFORM_FAMILIES) { @@ -225,6 +256,11 @@ function checkDeclarations(packages: readonly PlatformPackageDeclaration[]): Lay continue; } const declaration = matches[0]!; + const managedName = MANAGED_PLATFORMS[family]; + if (managedName) { + violations.push(...managedPlatformDeclarationFailures(declaration, managedName)); + continue; + } const expectedName = packageName(family); if (declaration.name !== expectedName) { violations.push( @@ -302,6 +338,18 @@ function checkSource(file: string, source: string): LayeringViolation[] { violations.push(...appleRunnerPackageSiteViolations(file, site)); } violations.push(...appleRunnerEntryImporterViolations(file, site)); + const managedImport = Object.values(MANAGED_PLATFORMS).some( + (name) => site.spec === name || site.spec.startsWith(name + '/'), + ); + if (managedImport && isProductionSourceFile(file)) { + violations.push( + violation( + file, + site.line, + 'Load managed platform entries only through the plugin registry', + ), + ); + } const importedFamily = concretePlatformFamily(site.spec); if (file.startsWith('packages/contracts/') && importedFamily) { violations.push( @@ -373,9 +421,13 @@ function checkSource(file: string, source: string): LayeringViolation[] { violation(file, site.line, `platform-${ownerFamily} may not import sibling '${site.spec}'`), ); } + const importsPluginTypes = + MANAGED_PLATFORMS[ownerFamily as PlatformFamily] && + site.typeOnly && + site.spec === 'agent-device/plugins'; if ( resolvesOutsidePackage(file, site.spec, ownerFamily) || - /^agent-device(?:\/|$)/.test(site.spec) + (/^agent-device(?:\/|$)/.test(site.spec) && !importsPluginTypes) ) { violations.push( violation(file, site.line, `platform-${ownerFamily} may not reach root or daemon code`), @@ -444,5 +496,5 @@ export function checkPlatformPackagePolicy( } export function platformPackagePolicySummary(): string { - return `R13 holds six private implementation-lazy platform packages above capture-kit behind one canonical composition root and its single private provider-composition submodule, with the android mechanics facet and the Apple runner package behind their enumerated seams; deferred or type-only edges are limited to the approved platform-runtime host watchlist and the dynamic-only HarmonyOS, Linux and Web interactor subpaths imported by ${INTERACTOR_COMPOSITION_FILE}`; + return `R13 holds built-in and managed implementation-lazy platform packages above capture-kit behind one canonical composition root and its single private provider-composition submodule, with the android mechanics facet and the Apple runner package behind their enumerated seams; deferred or type-only edges are limited to the approved platform-runtime host watchlist and the dynamic-only HarmonyOS, Linux and Web interactor subpaths imported by ${INTERACTOR_COMPOSITION_FILE}`; } diff --git a/scripts/layering/platform-package-repository.ts b/scripts/layering/platform-package-repository.ts index e0531237e4..52a8ad54b1 100644 --- a/scripts/layering/platform-package-repository.ts +++ b/scripts/layering/platform-package-repository.ts @@ -34,6 +34,8 @@ export function readTrackedPlatformPackageDeclarations( name?: string; private?: boolean; exports?: Record; + publishConfig?: { exports?: Record }; + 'agent-device'?: { platform?: unknown; apiVersion?: unknown }; }; const family = path.posix.basename(dir).slice('platform-'.length); return { @@ -41,6 +43,8 @@ export function readTrackedPlatformPackageDeclarations( family, name: manifest.name ?? '', private: manifest.private === true, + managedClaim: manifest['agent-device'], + publishedSubpaths: Object.keys(manifest.publishConfig?.exports ?? {}), exportedSubpaths: Object.keys(manifest.exports ?? {}).map((subpath) => path.posix.join(manifest.name ?? '', subpath), ), diff --git a/scripts/lib/packed-core-absence.ts b/scripts/lib/packed-core-absence.ts new file mode 100644 index 0000000000..b8f7dc589d --- /dev/null +++ b/scripts/lib/packed-core-absence.ts @@ -0,0 +1,23 @@ +export type ExcludedImplementation = Readonly<{ + owner: string; + paths: readonly RegExp[]; + markers: readonly string[]; +}>; + +export function packedCoreAbsenceFailures( + exclusions: readonly ExcludedImplementation[], + paths: readonly string[], + readFile: (path: string) => string, +): string[] { + return paths.flatMap((filename) => { + const contents = /^dist\/.*\.[cm]?js$/.test(filename) ? readFile(filename) : ''; + return exclusions.flatMap(({ owner, paths, markers }) => [ + ...(paths.some((pattern) => pattern.test(filename)) + ? [`${owner}: forbidden packed path ${filename}`] + : []), + ...markers + .filter((marker) => contents.includes(marker)) + .map((marker) => `${owner}: forbidden implementation marker in ${filename}: ${marker}`), + ]); + }); +} diff --git a/test/repo-guards/npm-package-scripts.test.ts b/test/repo-guards/npm-package-scripts.test.ts index 010adee62d..dc2e832c12 100644 --- a/test/repo-guards/npm-package-scripts.test.ts +++ b/test/repo-guards/npm-package-scripts.test.ts @@ -99,7 +99,7 @@ test('publishing cannot skip the package gate', () => { // The minimum-Node job runs the script directly — the repo's pinned pnpm needs a newer Node than // the floor that job covers — so it must still name the same entry point the script does. assert.deepEqual(script('check:package').split(' && '), [ - 'node --experimental-strip-types scripts/node-test-tmpdir.ts --experimental-strip-types --test packages/maestro/test/package-artifact.test.mjs packages/maestro/test/package-smoke.mjs packages/replay/test/package-smoke.mjs', + 'node --experimental-strip-types scripts/node-test-tmpdir.ts --experimental-strip-types --test packages/maestro/test/package-artifact.test.mjs packages/maestro/test/package-smoke.mjs packages/replay/test/package-smoke.mjs packages/platform-web/test/package-smoke.mjs', 'node --experimental-strip-types scripts/check-package.ts', ]); assert.match(packagedCliWorkflow, /with: \{ gate: package \}/); From ea6d77438cc06b7df65a185ce1eaf2debf408902 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 20 Nov 2026 15:12:26 +0100 Subject: [PATCH 7/7] refactor(platform-runtime): require the platform selection on the runtime gateway Claim recovery now binds through the process's platform selection: the daemon passes its composed platforms, and daemonless device release --stale starts one platforms-scoped plugin registry on first gateway use and closes it when the run ends. The registry start is shared with the managed web backend. --- .../platform-runtime-claim-recovery.test.ts | 16 +- src/cli/commands/device.ts | 1 + src/daemon-composition-claim-recovery.test.ts | 230 ++++++++++++++++++ src/daemon-composition.ts | 2 +- ...atform-runtime-android-adb-binding.test.ts | 3 + ...rm-runtime-apple-close-composition.test.ts | 2 + ...form-runtime-builtin-platforms.fixtures.ts | 7 + src/platform-runtime-claim-recovery.ts | 77 ++++-- ...platform-runtime-gateway-recording.test.ts | 2 + src/platform-runtime-managed-web-backend.ts | 51 +--- src/platform-runtime-perf-host.test.ts | 2 + src/platform-runtime.ts | 24 +- src/platform-runtime/installed-platforms.ts | 78 ++++++ .../smoke-tvos-platform-coverage.test.ts | 2 + 14 files changed, 409 insertions(+), 88 deletions(-) create mode 100644 src/daemon-composition-claim-recovery.test.ts create mode 100644 src/platform-runtime-builtin-platforms.fixtures.ts create mode 100644 src/platform-runtime/installed-platforms.ts diff --git a/src/__tests__/platform-runtime-claim-recovery.test.ts b/src/__tests__/platform-runtime-claim-recovery.test.ts index dd11498847..dd901fca1f 100644 --- a/src/__tests__/platform-runtime-claim-recovery.test.ts +++ b/src/__tests__/platform-runtime-claim-recovery.test.ts @@ -278,14 +278,12 @@ test('stale release inspects retained resource evidence before gateway compositi fs.writeFileSync(resourcePath, '{'); process.env.AGENT_DEVICE_CLAIMS_DIR = claimsDir; const composed: string[] = []; - const outcomes = await runStaleDeviceClaimRelease( - {}, - createLiveTestHostEnvironment(), - (stateDir) => { + const outcomes = await runStaleDeviceClaimRelease({}, createLiveTestHostEnvironment(), { + composeRecovery: (stateDir) => { composed.push(stateDir); throw new Error('retained evidence must not compose a gateway'); }, - ); + }); assert.deepEqual(composed, []); assert.equal(outcomes[0]?.status, 'retained'); assert.equal(outcomes[0]?.reason, 'app-log-descriptor-invalid'); @@ -326,10 +324,8 @@ test('recovery is composed per claim from the stale owner state dir, never the c process.env.AGENT_DEVICE_CLAIMS_DIR = claimsDir; const composedFor: string[] = []; - const outcomes = await runStaleDeviceClaimRelease( - {}, - createLiveTestHostEnvironment(), - (stateDir) => { + const outcomes = await runStaleDeviceClaimRelease({}, createLiveTestHostEnvironment(), { + composeRecovery: (stateDir) => { composedFor.push(stateDir); return { reconcile: async (claim) => { @@ -339,7 +335,7 @@ test('recovery is composed per claim from the stale owner state dir, never the c dispose: async () => {}, }; }, - ); + }); assert.deepEqual([...composedFor].sort(), [ownerDirA, ownerDirB].sort()); assert.equal(outcomes.filter((outcome) => outcome.status === 'released').length, 2); diff --git a/src/cli/commands/device.ts b/src/cli/commands/device.ts index bbf4fb2981..88ddad86ae 100644 --- a/src/cli/commands/device.ts +++ b/src/cli/commands/device.ts @@ -169,6 +169,7 @@ async function runDeviceRelease(flags: CliFlags, host: HostEnvironment): Promise serial: flags.serial, }, host, + { stateDir: flags.stateDir }, ); const data = { released: outcomes.filter((outcome) => outcome.status === 'released').map(serializeOutcome), diff --git a/src/daemon-composition-claim-recovery.test.ts b/src/daemon-composition-claim-recovery.test.ts new file mode 100644 index 0000000000..1d0fab637a --- /dev/null +++ b/src/daemon-composition-claim-recovery.test.ts @@ -0,0 +1,230 @@ +import crypto from 'node:crypto'; +import fs from 'node:fs'; +import path from 'node:path'; +import { expect, test } from 'vitest'; +import { createDurableResourceEnvelope } from '@agent-device/capture-kit'; +import { screenRecordingResourceStore } from '@agent-device/capture-kit/screen-recording-resource-store'; +import { localRuntimeOwner } from '@agent-device/contracts/platform-runtime'; +import { + createOwnerScopedDeviceClaimReconciler, + createRecoveryPlatformScope, + inspectDeviceClaimRecovery, +} from '@agent-device/daemon-contracts/device-claim-recovery'; +import { releaseProvenStaleDeviceClaims } from '@agent-device/daemon-contracts/device-claims'; +import { createRuntimeStateHandle } from '@agent-device/host-kit/runtime-slots'; +import { deviceIdentity, type DeviceInfo } from '@agent-device/kernel/device'; +import type { HostEnvironment } from '@agent-device/kernel/source-value'; +import { createTestHostEnvironment, pluginHome, selectPlugin } from '@agent-device/test-kit'; +import { createDaemonRuntimeDeps } from './daemon-composition.ts'; +import { runStaleDeviceClaimRelease } from './platform-runtime-claim-recovery.ts'; + +const webPackage = '@agent-device/web'; +// The runtime answers recovery as an owner whose recorder died with its daemon: nothing to reattach. +// The stock browser runtime answers `cleanup-pending` instead, so this double is the only web +// runtime a recovery can settle; what the test proves is which registration recovery binds. +const webPlugin = ` + const owner = { kind: 'local-family', family: 'web' }; + const available = { available: true }; + export default () => ({ + apiVersion: 3, + contributes: [{ + kind: 'platform', + family: 'web', + setup() { + return { + family: 'web', + createInteractor: async () => ({}), + inventoryModule: { family: 'web', loadInventory: async () => ({ discover: async () => [] }) }, + runtimeModule: { + family: 'web', + loadRuntime: async () => ({ + owner, + ownsDevice: (device) => device.platform === 'web', + inspectFacts() { throw new Error('unused'); }, + bind: async ({ device }) => ({ + device, + owner, + facts: { + device: { + family: 'web', + kind: device.kind, + target: device.target, + providerMode: 'local', + }, + operations: { + screenRecordingReattach: available, + screenRecordingCleanup: available, + }, + }, + operations: { + screenRecordingReattach: async () => ({ status: 'missing' }), + screenRecordingCleanup: async () => ({ status: 'already-missing' }), + }, + [Symbol.asyncDispose]: async () => {}, + }), + shutdown: async () => {}, + }), + }, + withRequestProvider: async (_, task) => task(), + operations: { + setup() {}, + doctor() {}, + cleanupOrphans() {}, + browserLifecycleCheck() {}, + createProvider() {}, + resolveRequestProvider() {}, + }, + }; + }, + }], + }); +`; + +const browser: DeviceInfo = { + platform: 'web', + id: 'agent-browser-chrome', + name: 'Agent Browser Chrome', + kind: 'device', + target: 'desktop', +}; +const session = 'dead-web-session'; +const deviceKey = 'local:web:none:agent-browser-chrome'; + +/** A dead owner's web claim whose state dir still records an open screen recording. */ +function seedStaleWebRecordingClaim(options: { webInstalled: boolean }) { + const { home, env } = pluginHome(); + if (options.webInstalled) { + selectPlugin(home, webPackage, webPlugin, { claims: { apiVersion: 3, platform: 'web' } }); + } + const ownerStateDir = path.join(home, 'owner-state'); + const stateDir = path.join(home, 'state'); + const claimsDir = path.join(home, 'claims'); + const claimPath = path.join( + claimsDir, + `${crypto.createHash('sha256').update(deviceKey).digest('hex')}.json`, + ); + fs.mkdirSync(claimsDir, { recursive: true }); + fs.writeFileSync( + claimPath, + JSON.stringify({ + schemaVersion: 1, + deviceKey, + device: browser, + session, + workspace: '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/worktrees/dead-owner', + stateDir: ownerStateDir, + ownerPid: 999_999_999, + ownerStartTime: 'old-start-time', + ownerToken: 'dead-owner-token', + createdAtMs: 1, + updatedAtMs: 1, + }), + ); + const recordingPath = screenRecordingResourceStore.resolvePath( + path.join(ownerStateDir, 'sessions', session), + ); + screenRecordingResourceStore.write( + recordingPath, + createDurableResourceEnvelope({ + resourceKind: 'screen-recording', + sessionId: session, + device: deviceIdentity(browser), + owner: localRuntimeOwner('web'), + fence: { token: 'dead-owner-recording', generation: 1 }, + lifecycle: 'open', + descriptor: { version: 1, body: {} }, + metadata: { phase: 'active' }, + }), + ); + const host = createTestHostEnvironment({ + env: { + ...process.env, + ...env, + AGENT_DEVICE_CLAIMS_DIR: claimsDir, + AGENT_DEVICE_STATE_DIR: stateDir, + }, + cwd: home, + }); + return { host, stateDir, claimPath, recordingPath }; +} + +/** Releases stale claims as the daemon does: through the recovery gateway its composition returns. */ +async function releaseThroughDaemonComposition(host: HostEnvironment, baseDir: string) { + const sessionsDir = path.join(baseDir, 'sessions'); + return await createRuntimeStateHandle().run(async () => { + const deps = await createDaemonRuntimeDeps({ + host, + baseDir, + sessionsDir, + assertShutdownAllowed: undefined, + resolveSessionDir: (name) => path.join(sessionsDir, name), + resolveSessionArtifacts: () => { + throw new Error('unused'); + }, + openWebSessionNames: () => [], + }); + try { + return await releaseProvenStaleDeviceClaims({ + selectors: {}, + env: host.env, + reconcile: createOwnerScopedDeviceClaimReconciler({ + scope: createRecoveryPlatformScope(), + composeGateway: deps.claimRecoveryGateway, + beforeGateway: inspectDeviceClaimRecovery, + }), + }); + } finally { + await deps.shutdownProviderRuntimes(); + } + }); +} + +const releases = [ + { + path: 'the daemon composition', + release: (host: HostEnvironment, stateDir: string) => + releaseThroughDaemonComposition(host, stateDir), + }, + { + path: 'daemonless device release --stale', + release: (host: HostEnvironment, stateDir: string) => + createRuntimeStateHandle().run(() => runStaleDeviceClaimRelease({}, host, { stateDir })), + }, +]; + +test.each(releases)( + '$path settles a stale web claim recording through the installed web platform', + async ({ release }) => { + const { host, stateDir, claimPath, recordingPath } = seedStaleWebRecordingClaim({ + webInstalled: true, + }); + + const outcomes = await release(host, stateDir); + + expect(outcomes).toEqual([expect.objectContaining({ status: 'released', session })]); + expect(fs.existsSync(claimPath)).toBe(false); + expect(screenRecordingResourceStore.read(recordingPath)).toMatchObject({ + status: 'decoded', + envelope: { lifecycle: 'completed', metadata: { recoveryStatus: 'already-missing' } }, + }); + }, +); + +test.each(releases)( + '$path keeps a stale web claim recording while no web platform is installed', + async ({ release }) => { + const { host, stateDir, claimPath, recordingPath } = seedStaleWebRecordingClaim({ + webInstalled: false, + }); + + const outcomes = await release(host, stateDir); + + expect(outcomes).toEqual([ + expect.objectContaining({ status: 'retained', reason: 'screen-recording-cleanup-pending' }), + ]); + expect(fs.existsSync(claimPath)).toBe(true); + expect(screenRecordingResourceStore.read(recordingPath)).toMatchObject({ + envelope: { lifecycle: 'open' }, + }); + }, +); diff --git a/src/daemon-composition.ts b/src/daemon-composition.ts index a13013cb1e..aba969b290 100644 --- a/src/daemon-composition.ts +++ b/src/daemon-composition.ts @@ -190,7 +190,7 @@ export async function composeDaemonRuntimeDeps( recoverableProviderIds: providerRuntimeProviders.recoverableProviderIds, deviceRuntimeGateway, platformResourceCleanup: createPlatformResourceCleanup(host, web), - claimRecoveryGateway: createClaimRecoveryGatewayFor(host), + claimRecoveryGateway: createClaimRecoveryGatewayFor(host, platforms), interactorResolution: Object.freeze({ resolve: async (device: DeviceInfo, runnerContext: RunnerContext) => await getInteractor(device, runnerContext, host, platforms.interactors), diff --git a/src/platform-runtime-android-adb-binding.test.ts b/src/platform-runtime-android-adb-binding.test.ts index 7e57cb1772..f278faffe6 100644 --- a/src/platform-runtime-android-adb-binding.test.ts +++ b/src/platform-runtime-android-adb-binding.test.ts @@ -26,6 +26,7 @@ vi.mock('@agent-device/host-kit/command', async (importOriginal) => { }); import { createPlatformRuntimeGateway } from './platform-runtime.ts'; +import { builtinPlatformSelectionFixture } from './platform-runtime-builtin-platforms.fixtures.ts'; import { bindTestCommandHost, createLiveTestHostEnvironment } from '@agent-device/test-kit'; const sessionArtifacts = { @@ -54,6 +55,7 @@ const device: DeviceInfo = { test('the composed gateway lists Android apps from inside the platform package', async () => { const gateway = createPlatformRuntimeGateway({ host: createLiveTestHostEnvironment(), + platforms: builtinPlatformSelectionFixture(), ...sessionArtifacts, }); const binding = await gateway.bind({ device, intent: { kind: 'ordinary' }, scope }); @@ -82,6 +84,7 @@ test('the composed gateway lists Android apps from inside the platform package', test('the composed gateway reads Android app state from inside the platform package', async () => { const gateway = createPlatformRuntimeGateway({ host: createLiveTestHostEnvironment(), + platforms: builtinPlatformSelectionFixture(), ...sessionArtifacts, }); const binding = await gateway.bind({ device, intent: { kind: 'ordinary' }, scope }); diff --git a/src/platform-runtime-apple-close-composition.test.ts b/src/platform-runtime-apple-close-composition.test.ts index 531d26f9b2..b6be0490ab 100644 --- a/src/platform-runtime-apple-close-composition.test.ts +++ b/src/platform-runtime-apple-close-composition.test.ts @@ -7,6 +7,7 @@ import { import type { DeviceInfo } from '@agent-device/kernel/device'; import { setAppleRunnerHostEnvironment } from '@agent-device/platform-apple/runner-owner'; import { createPlatformRuntimeGateway } from './platform-runtime.ts'; +import { builtinPlatformSelectionFixture } from './platform-runtime-builtin-platforms.fixtures.ts'; const events = vi.hoisted(() => [] as string[]); vi.mock('@agent-device/platform-apple/runner/operations', async (importOriginal) => { @@ -50,6 +51,7 @@ test('the composed close awaits the real runner release before dismissing alerts }; const gateway = createPlatformRuntimeGateway({ host, + platforms: builtinPlatformSelectionFixture(), sessionsDir: root, resolveSessionArtifacts: (sessionId) => ({ outputPath: `${root}/${sessionId}/app.log`, diff --git a/src/platform-runtime-builtin-platforms.fixtures.ts b/src/platform-runtime-builtin-platforms.fixtures.ts new file mode 100644 index 0000000000..c7c84b7569 --- /dev/null +++ b/src/platform-runtime-builtin-platforms.fixtures.ts @@ -0,0 +1,7 @@ +import type { PlatformModuleSelection } from '@agent-device/contracts/platform-plugin'; +import { composePlatformPlugins } from './platform-runtime/platform-plugins.ts'; + +/** The platform selection of a process with no installed platform plugin. */ +export function builtinPlatformSelectionFixture(): PlatformModuleSelection { + return composePlatformPlugins([], []); +} diff --git a/src/platform-runtime-claim-recovery.ts b/src/platform-runtime-claim-recovery.ts index 055c4556a5..824ecd1440 100644 --- a/src/platform-runtime-claim-recovery.ts +++ b/src/platform-runtime-claim-recovery.ts @@ -1,4 +1,3 @@ -import { missingPlatformPlugin } from './core/platform-plugin-absence.ts'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; import { createOwnerScopedDeviceClaimReconciler, @@ -12,6 +11,8 @@ import { type DeviceClaimSelectors, type DeviceClaimStaleReleaseOutcome, } from '@agent-device/daemon-contracts/device-claims'; +import type { PlatformModuleSelection } from '@agent-device/contracts/platform-plugin'; +import type { InstalledPlatforms } from './platform-runtime/installed-platforms.ts'; import { createPlatformRuntimeGateway } from './platform-runtime.ts'; /** @@ -20,44 +21,90 @@ import { createPlatformRuntimeGateway } from './platform-runtime.ts'; * runtime gateway the transaction runs on, because building a gateway is the one act that names * platform modules. A local-only gateway per transaction keeps provider runtimes out of recovery — * claims exist only for local devices — and instance-scopes every stateful piece the gateway owns, - * so disposal shuts down only this transaction's handles. + * so disposal shuts down only this transaction's handles. `platforms` is the process's one platform + * selection, so recovery binds an installed optional family through the same registration every + * other request of this process uses. */ export const createClaimRecoveryGatewayFor = - (host: HostEnvironment): ClaimRecoveryGatewayFactory => + (host: HostEnvironment, platforms: PlatformModuleSelection): ClaimRecoveryGatewayFactory => (input) => createPlatformRuntimeGateway({ host, - reportAbsent: missingPlatformPlugin, + platforms, sessionsDir: input.sessionsDir, ownedProcesses: input.ownedProcesses, resolveSessionArtifacts: input.resolveSessionArtifacts, }); +type ClaimRecoveryGateway = ReturnType; + +/** + * A gateway composed on the first bind or fact read. A release that settles no durable resource + * through a runtime never composes it, so it starts no plugin. + */ +function createDeferredGateway(compose: () => Promise): ClaimRecoveryGateway { + let composed: Promise | undefined; + const gateway = (): Promise => (composed ??= compose()); + return Object.freeze({ + inspectFacts: async (device) => await (await gateway()).inspectFacts(device), + bind: async (request) => await (await gateway()).bind(request), + // A composition that failed owns nothing to shut down; its error already failed the bind. + shutdown: async () => + await composed?.then( + (started) => started.shutdown(), + () => undefined, + ), + }); +} + /** * Daemonless `device release --stale`: settles each provably dead owner * through the same owner-scoped reconciliation the daemon uses at `open` and * startup — recovery composed from the stale claim's own state dir, resources * settled first, claim cleared last — without requiring the (typically dead) * owner daemon, or any daemon, to be running. + * + * The platform selection is this process's, as in the daemon: one plugin registry for the whole + * run, started from `stateDir` (the caller's state dir) on the first gateway use and closed when + * the run ends. Only the gateway's session paths and process records follow the stale owner. */ export async function runStaleDeviceClaimRelease( selectors: DeviceClaimSelectors, host: HostEnvironment, - composeRecovery?: OwnerScopedClaimRecoveryComposer, + options: Readonly<{ + stateDir?: string; + composeRecovery?: OwnerScopedClaimRecoveryComposer; + }> = {}, ): Promise { // Settling a transaction can reach runner code; this CLI process runs one host, and the // runner reads its configuration from it, entered as the runtime state the daemon route binds. const { setAppleRunnerHostEnvironment } = await import('@agent-device/platform-apple/runner-owner'); setAppleRunnerHostEnvironment(host); - return await releaseProvenStaleDeviceClaims({ - selectors, - env: host.env, - reconcile: createOwnerScopedDeviceClaimReconciler({ - scope: createRecoveryPlatformScope(), - composeGateway: createClaimRecoveryGatewayFor(host), - composeRecovery, - beforeGateway: inspectDeviceClaimRecovery, - }), - }); + let installed: Promise | undefined; + const startInstalled = (): Promise => + (installed ??= import('./platform-runtime/installed-platforms.ts').then( + ({ startInstalledPlatforms }) => startInstalledPlatforms(host, options.stateDir), + )); + try { + return await releaseProvenStaleDeviceClaims({ + selectors, + env: host.env, + reconcile: createOwnerScopedDeviceClaimReconciler({ + scope: createRecoveryPlatformScope(), + composeGateway: (input) => + createDeferredGateway(async () => + createClaimRecoveryGatewayFor(host, (await startInstalled()).platforms)(input), + ), + composeRecovery: options.composeRecovery, + beforeGateway: inspectDeviceClaimRecovery, + }), + }); + } finally { + // A registry that failed to start set nothing up, and its error already failed the bind. + await installed?.then( + (started) => started.close(), + () => undefined, + ); + } } diff --git a/src/platform-runtime-gateway-recording.test.ts b/src/platform-runtime-gateway-recording.test.ts index 3e4f612476..1a6a4e2eac 100644 --- a/src/platform-runtime-gateway-recording.test.ts +++ b/src/platform-runtime-gateway-recording.test.ts @@ -3,6 +3,7 @@ import { expect, test } from 'vitest'; import type { DeviceInfo } from '@agent-device/kernel/device'; import { createLiveTestHostEnvironment, mkdtempForTestSync } from '@agent-device/test-kit'; import { createPlatformRuntimeGateway } from './platform-runtime.ts'; +import { builtinPlatformSelectionFixture } from './platform-runtime-builtin-platforms.fixtures.ts'; const unsupportedRecordingDevices = [ { @@ -21,6 +22,7 @@ test.each(unsupportedRecordingDevices)( const sessionsDir = mkdtempForTestSync('platform-runtime-recording-'); const gateway = createPlatformRuntimeGateway({ host: createLiveTestHostEnvironment(), + platforms: builtinPlatformSelectionFixture(), sessionsDir, resolveSessionArtifacts: (sessionId) => ({ outputPath: path.join(sessionsDir, sessionId, 'app.log'), diff --git a/src/platform-runtime-managed-web-backend.ts b/src/platform-runtime-managed-web-backend.ts index 1ec058aa39..2f57d459e0 100644 --- a/src/platform-runtime-managed-web-backend.ts +++ b/src/platform-runtime-managed-web-backend.ts @@ -16,54 +16,11 @@ async function withWebPlatform( stateDir: string | undefined, run: (web: PlatformSetup<'web'>) => Promise, ): Promise { - const [ - { resolveProviderPlugins, startProviderRegistry }, - { storePluginCandidates, createPluginSelectionGuard }, - { getOptionalPlatformPluginDeclaration }, - { createPlatformPluginHost }, - { resolveDaemonPaths }, - { builtinPlatformCandidates, composePlatformPlugins }, - { PROVIDER_PLUGIN_POLICY }, - ] = await Promise.all([ - import('@agent-device/plugins/registry'), - import('@agent-device/plugins/store'), - import('@agent-device/contracts/plugin-installation'), - import('./platform-runtime/plugin-host.ts'), - import('@agent-device/daemon-contracts/daemon-resolution'), - import('./platform-runtime/platform-plugins.ts'), - import('./provider-plugin-policy.ts'), - ]); - const packageName = getOptionalPlatformPluginDeclaration('web')?.package; - const installed = await storePluginCandidates(host.env); - const candidates = installed.filter( - (candidate) => - candidate.package === packageName || - candidate.declaredClaims?.some(({ kind, id }) => kind === 'platform' && id === 'web'), - ); - const resolved = await resolveProviderPlugins([...builtinPlatformCandidates(), ...candidates]); - const assertSelectionCurrent = createPluginSelectionGuard(installed, host.env); - const registry = await startProviderRegistry( - resolved, - host, - { - ...PROVIDER_PLUGIN_POLICY, - assertSelectionCurrent, - platformHost: createPlatformPluginHost( - host, - resolveDaemonPaths(stateDir, { env: host.env, cwd: host.cwd }).baseDir, - ), - }, - 'platforms', - ); + const { startInstalledPlatforms } = await import('./platform-runtime/installed-platforms.ts'); + const installed = await startInstalledPlatforms(host, stateDir, 'web'); try { - return await run( - composePlatformPlugins( - registry.platforms, - registry.inventory, - assertSelectionCurrent, - ).web.get(), - ); + return await run(installed.platforms.web.get()); } finally { - await registry.close(); + await installed.close(); } } diff --git a/src/platform-runtime-perf-host.test.ts b/src/platform-runtime-perf-host.test.ts index c307d38d04..86cf96e530 100644 --- a/src/platform-runtime-perf-host.test.ts +++ b/src/platform-runtime-perf-host.test.ts @@ -7,6 +7,7 @@ import { import { expect, test, vi } from 'vitest'; import { createPerfRuntimeHost } from './platform-runtime-perf-host.ts'; import { createPlatformRuntimeGateway } from './platform-runtime.ts'; +import { builtinPlatformSelectionFixture } from './platform-runtime-builtin-platforms.fixtures.ts'; const adb = vi.hoisted(() => ({ calls: [] as string[][] })); @@ -52,6 +53,7 @@ test('the composed Android perf operation reports an unavailable ADB memory samp const sessionsDir = mkdtempForTestSync('platform-runtime-perf-host-'); const gateway = createPlatformRuntimeGateway({ host: createLiveTestHostEnvironment(), + platforms: builtinPlatformSelectionFixture(), sessionsDir, resolveSessionArtifacts: (sessionId) => ({ outputPath: `${sessionsDir}/${sessionId}/app.log`, diff --git a/src/platform-runtime.ts b/src/platform-runtime.ts index 7482f5283a..d107596a80 100644 --- a/src/platform-runtime.ts +++ b/src/platform-runtime.ts @@ -130,10 +130,7 @@ const androidRuntimeModule = createAndroidRuntimeModule({ }, }); -function createPlatformRuntimeModuleRegistry( - platforms?: PlatformModuleSelection, - reportAbsent = platforms?.reportAbsent, -) { +function createPlatformRuntimeModuleRegistry(platforms: PlatformModuleSelection) { return createPlatformModuleRegistry( [ appleRuntimeModule, @@ -141,18 +138,18 @@ function createPlatformRuntimeModuleRegistry( harmonyosRuntimeModule, vegaRuntimeModule, linuxRuntimeModule, - ...(platforms?.runtimeModules ?? []), + ...platforms.runtimeModules, ], - reportAbsent, - platforms?.assertSelectionCurrent, + platforms.reportAbsent, + platforms.assertSelectionCurrent, ); } export function createPlatformRuntimeGateway( options: Readonly<{ host: HostEnvironment; - platforms?: PlatformModuleSelection; - reportAbsent?: Parameters[1]; + /** The process's one platform selection: it carries the optional families and their absence. */ + platforms: PlatformModuleSelection; providerRuntimes?: readonly ProviderDeviceRuntime[]; providerModules?: readonly PlatformRuntimeProviderRegistration[]; resolveSessionArtifacts(sessionId: string): AppLogSessionArtifacts; @@ -162,17 +159,14 @@ export function createPlatformRuntimeGateway( }>, ): DeviceRuntimeGateway { return createComposedPlatformRuntimeGateway({ - modules: createPlatformRuntimeModuleRegistry( - options.platforms, - options.reportAbsent ?? options.platforms?.reportAbsent, - ), + modules: createPlatformRuntimeModuleRegistry(options.platforms), loadHost: async () => { const { createPlatformRuntimeHost, createSnapshotRuntimeHost, loadMacOsSurfaceSnapshot } = await import('./platform-runtime-operation-host.ts'); return createPlatformRuntimeHost({ host: options.host, - web: options.platforms?.web, - interactors: options.platforms?.interactors, + web: options.platforms.web, + interactors: options.platforms.interactors, sessionsDir: options.sessionsDir, resolveSessionArtifacts: options.resolveSessionArtifacts, shutdownLoaders, diff --git a/src/platform-runtime/installed-platforms.ts b/src/platform-runtime/installed-platforms.ts new file mode 100644 index 0000000000..454b8cfbc4 --- /dev/null +++ b/src/platform-runtime/installed-platforms.ts @@ -0,0 +1,78 @@ +import type { OptionalPlatform } from '@agent-device/contracts/platform-module'; +import { OPTIONAL_PLATFORMS } from '@agent-device/contracts/platform-module'; +import type { PlatformModuleSelection } from '@agent-device/contracts/platform-plugin'; +import { getOptionalPlatformPluginDeclaration } from '@agent-device/contracts/plugin-installation'; +import { resolveDaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution'; +import type { HostEnvironment } from '@agent-device/kernel/source-value'; +import { PROVIDER_PLUGIN_POLICY } from '../provider-plugin-policy.ts'; +import { builtinPlatformCandidates, composePlatformPlugins } from './platform-plugins.ts'; +import { createPlatformPluginHost } from './plugin-host.ts'; + +export type InstalledPlatforms = Readonly<{ + platforms: PlatformModuleSelection; + /** Runs every set-up plugin's cleanup. The caller that started the registry owns this call. */ + close(): Promise; +}>; + +/** + * The platform selection of a process that runs outside the daemon: the bundled families reserve + * their claims, then the plugin store's platform packages set up under a `'platforms'`-scoped + * registry, so no provider or replay backend loads. `family` narrows the store packages to the one + * family a command needs; without it every installed platform package sets up. `stateDir` is the + * state dir of the calling process, resolved as the daemon resolves its own. + */ +export async function startInstalledPlatforms( + host: HostEnvironment, + stateDir: string | undefined, + family?: OptionalPlatform, +): Promise { + const [ + { resolveProviderPlugins, startProviderRegistry }, + { storePluginCandidates, createPluginSelectionGuard }, + ] = await Promise.all([ + import('@agent-device/plugins/registry'), + import('@agent-device/plugins/store'), + ]); + const families: readonly OptionalPlatform[] = family ? [family] : OPTIONAL_PLATFORMS; + const packages = new Set( + families.map((optional) => getOptionalPlatformPluginDeclaration(optional)?.package), + ); + const installed = await storePluginCandidates(host.env); + const candidates = installed.filter( + (candidate) => + packages.has(candidate.package) || + candidate.declaredClaims?.some( + ({ kind, id }) => kind === 'platform' && (family === undefined || id === family), + ), + ); + const resolved = await resolveProviderPlugins([...builtinPlatformCandidates(), ...candidates]); + const assertSelectionCurrent = createPluginSelectionGuard(installed, host.env); + const registry = await startProviderRegistry( + resolved, + host, + { + ...PROVIDER_PLUGIN_POLICY, + assertSelectionCurrent, + platformHost: createPlatformPluginHost( + host, + resolveDaemonPaths(stateDir, { env: host.env, cwd: host.cwd }).baseDir, + ), + }, + 'platforms', + ); + try { + return Object.freeze({ + platforms: composePlatformPlugins( + registry.platforms, + registry.inventory, + assertSelectionCurrent, + ), + close: async () => { + await registry.close(); + }, + }); + } catch (error) { + await registry.close(); + throw error; + } +} diff --git a/test/integration/smoke-tvos-platform-coverage.test.ts b/test/integration/smoke-tvos-platform-coverage.test.ts index 98419bed98..ba36f8c81f 100644 --- a/test/integration/smoke-tvos-platform-coverage.test.ts +++ b/test/integration/smoke-tvos-platform-coverage.test.ts @@ -10,6 +10,7 @@ import { assertCoverageGapRowsAreOwned, } from './support/coverage-classification.ts'; import { createPlatformRuntimeGateway } from '../../src/platform-runtime.ts'; +import { builtinPlatformSelectionFixture } from '../../src/platform-runtime-builtin-platforms.fixtures.ts'; import { gestureRefusalMessage } from '@agent-device/contracts/gesture-admission'; import { TVOS_COVERAGE_GAP_ISSUE, @@ -84,6 +85,7 @@ test('tvOS gesture contract preserves the typed multi-touch denial', async () => // gesture reports is that fact's hint under the shared wording. const facts = await createPlatformRuntimeGateway({ host: createLiveTestHostEnvironment(), + platforms: builtinPlatformSelectionFixture(), resolveSessionArtifacts: () => ({ outputPath: '/sessions/tvos/app.log', pidPath: '/sessions/tvos/app-log.pid',