{"version":3,"file":"index.cjs","sources":["../src/schema/primitives.ts","../src/schema/remote-schema.ts","../src/remote/select-place.ts","../src/mobile/select-device.ts","../src/mobile/device-plan.ts","../src/schema/workspace-schema.ts","../src/schema/services-schema.ts","../src/schema/knowledge-schema.ts","../src/schema/retired-keys.ts","../src/schema/config-shape-scan.ts","../src/auth-state/schema.ts","../src/schema/registry-schema.ts","../src/schema/use-schema.ts","../src/schema/analytics-schema.ts","../src/plugin-loader-util.ts","../src/schema/config-schema.ts","../src/schema/leftover-local-file.ts","../src/schema/test-schema.ts","../src/schema/resolve-knowledge-root.ts","../src/schema/suite-schema.ts","../src/hooks/schema.ts","../src/validation/yaml-fault.ts","../src/parser/errors.ts","../src/parser/yaml-parser.ts","../src/parser/file-resolver.ts","../src/parser/suite-parser.ts","../src/parser/cst-patch.ts","../src/agent/token-budget.ts","../src/mobile/role-map.ts","../src/mobile/xml-parser.ts","../src/mobile/element-resolver.ts","../src/mobile/gestures.ts","../src/mobile/launch-resolver.ts","../src/mobile/find-device-here.ts","../src/mobile/appium-endpoint.ts","../src/mobile/webview-scrollers.ts","../src/runtime-paths.ts","../src/auth-state/resolver.ts","../src/auth-state/store.ts","../src/auth-state/runtime.ts","../src/auth/store.ts","../src/auth/plugin-registry.ts","../src/auth/resolver.ts","../src/utils/path-validation.ts","../src/plugins/manifest.ts","../src/plugins/resolve-entries.ts","../src/version.ts","../src/auth/plugin-loader.ts","../src/auth/pkce.ts","../src/auth/fetch-wrapper.ts","../src/providers/plugin-loader.ts","../src/logging/types.ts","../src/logging/run-text-output.ts","../src/logging/log-line.ts","../src/logging/log-manager.ts","../src/suite/member.ts","../src/hooks/parser.ts","../src/remote/connection-secrets.ts","../src/workspace/workspace-paths.ts","../src/validation/validate.ts","../src/validation/formatter.ts","../src/validation/coord-bounds.ts","../src/ids/hook-id.ts","../src/ids/run-id.ts","../src/run-attributes.ts","../src/plugins/options-check.ts","../src/plugins/describe.ts","../src/plugins/run-start.ts","../src/plugins/validate-package.ts","../src/remote/config-projection.ts","../src/remote/remote-device-connection.ts","../src/remote/remote-device-session.ts","../src/remote/plugin-device-session.ts","../src/remote/plugins/answer.ts","../src/remote/plugins/plugin-process.ts","../src/remote/plugins/host-pool.ts","../src/remote/plugins/host-versions.ts","../src/remote/plugins/secret-references.ts","../src/version-check/index.ts"],"sourcesContent":["import { z } from 'zod'\nimport ms from 'ms'\nimport bytes from 'bytes'\nimport { NAME_SLUG_PATTERN } from '@vostride/agent-qa-schema'\n\nexport const DurationString = z.string()\n  .refine((v) => ms(v as ms.StringValue) !== undefined, {\n    error: 'Invalid duration format (e.g., \"30s\", \"5m\", \"1h\")',\n  })\n  .transform((v) => ms(v as ms.StringValue) as number)\n\nconst VALID_SIZE_RE = /^\\d+(?:\\.\\d+)?\\s*(?:b|kb|mb|gb|tb|k|m|g|t)$/i\n\nfunction normalizeSize(v: string): string {\n  return v.replace(/^(\\d+(?:\\.\\d+)?)(k|m|g|t)$/i, '$1$2b')\n}\n\nexport const SizeString = z.string()\n  .refine((v) => VALID_SIZE_RE.test(v.trim()) && bytes(normalizeSize(v)) !== null, {\n    error: 'Invalid size format (e.g., \"256k\", \"1m\", \"5mb\")',\n  })\n  .transform((v) => bytes(normalizeSize(v)) as number)\n\nconst COMPATIBLE_PROVIDERS = new Set(['openai-compatible', 'anthropic-compatible'])\nconst SENSITIVE_HEADER_TERMS = ['authorization', 'cookie', 'x-api-key', 'api-key', 'token', 'secret']\nconst CONTROL_CHARACTER_RE = /[\\x00-\\x1F\\x7F]/\n\nfunction validateProviderHeaders(headers: Record<string, string>, ctx: z.RefinementCtx): void {\n  const seen = new Set<string>()\n\n  for (const [rawKey, rawValue] of Object.entries(headers)) {\n    const key = rawKey.trim()\n    const value = rawValue.trim()\n    const normalizedKey = key.toLowerCase()\n\n    if (key === '') {\n      ctx.addIssue({\n        code: 'custom',\n        path: ['providerHeaders'],\n        message: 'Provider header keys cannot be empty.',\n      })\n      continue\n    }\n\n    if (seen.has(normalizedKey)) {\n      ctx.addIssue({\n        code: 'custom',\n        path: ['providerHeaders'],\n        message: `Duplicate provider header \"${key}\" is not allowed.`,\n      })\n    }\n    seen.add(normalizedKey)\n\n    if (CONTROL_CHARACTER_RE.test(key) || CONTROL_CHARACTER_RE.test(value)) {\n      ctx.addIssue({\n        code: 'custom',\n        path: ['providerHeaders'],\n        message: `Provider header \"${key}\" cannot contain control characters.`,\n      })\n    }\n\n    const sensitiveTerm = SENSITIVE_HEADER_TERMS.find(term => normalizedKey.includes(term))\n    if (sensitiveTerm) {\n      ctx.addIssue({\n        code: 'custom',\n        path: ['providerHeaders'],\n        message: `Provider header \"${key}\" cannot contain auth-like term \"${sensitiveTerm}\".`,\n      })\n    }\n  }\n}\n\nfunction validateModelConfig(\n  config: { provider?: string; baseURL?: string; providerHeaders?: Record<string, string> },\n  ctx: z.RefinementCtx,\n) {\n  if (\n    config.provider\n    && COMPATIBLE_PROVIDERS.has(config.provider)\n    && (!config.baseURL || config.baseURL.trim() === '')\n  ) {\n    ctx.addIssue({\n      code: 'custom',\n      path: ['baseURL'],\n      message: `Base URL is required for ${config.provider} providers.`,\n    })\n  }\n\n  if (config.providerHeaders !== undefined && config.provider !== 'anthropic-compatible') {\n    ctx.addIssue({\n      code: 'custom',\n      path: ['providerHeaders'],\n      message: 'providerHeaders can only be used with anthropic-compatible providers.',\n    })\n  }\n\n  if (config.providerHeaders) {\n    validateProviderHeaders(config.providerHeaders, ctx)\n  }\n}\n\nconst REMOVED_LLM_PROVIDER_VALUES = new Set([\n  'anthropic',\n  'openai',\n  'google',\n  'ollama',\n  'lmstudio',\n  'custom',\n])\n\nconst LLMProviderIdSchema = z.string()\n  .regex(/^[a-z0-9][a-z0-9-]*$/, 'Provider must be lowercase alphanumeric + hyphens, starting with alphanumeric')\n  .superRefine((provider, ctx) => {\n    if (REMOVED_LLM_PROVIDER_VALUES.has(provider)) {\n      ctx.addIssue({\n        code: 'custom',\n        message: `Provider \"${provider}\" has been removed. Use a compatible provider or an auth plugin provider ID.`,\n      })\n    }\n  })\n\nconst ModelConfigBaseSchema = z.strictObject({\n  provider: LLMProviderIdSchema,\n  model: z.string(),\n  baseURL: z.string().optional(),\n  providerHeaders: z.record(z.string(), z.string()).optional(),\n  vision: z.boolean().default(true),\n})\n\nexport const ModelConfigSchema = ModelConfigBaseSchema.superRefine(validateModelConfig)\n\nexport const NameSlugSchema = z.string()\n  .regex(NAME_SLUG_PATTERN, 'Name must be lowercase letters, digits, hyphens and dots, starting with a letter or digit')\n\nexport const NamedLLMConfigSchema = z.strictObject({\n  ...ModelConfigBaseSchema.shape,\n  name: NameSlugSchema,\n  contextWindow: SizeString.optional(),\n}).superRefine(validateModelConfig)\n\nexport const TimeoutConfigSchema = z.strictObject({\n  step: DurationString,\n  test: DurationString,\n  navigation: DurationString.describe(\n    'How long a web page load or URL wait can take. Default 2m. Android and iOS runs do not use it.',\n  ),\n})\n\nexport const BrowserConfigSchema = z.strictObject({\n  name: z.enum(['chromium', 'firefox', 'webkit']),\n  headless: z.boolean(),\n  viewport: z.strictObject({\n    width: z.number(),\n    height: z.number(),\n  }).optional(),\n  remote: NameSlugSchema.optional(),\n})\n\n// Positive integers with no unlimited value; `resolvePlannerLimits` supplies the default.\nexport const PlannerConfigSchema = z.strictObject({\n  maxActions: z.number().int().positive().optional(),\n  maxPlanningTurns: z.number().int().positive().optional(),\n  previousStepCount: z.number(),\n})\n\nexport const LogCaptureConfigSchema = z.strictObject({\n  console: z.boolean(),\n  network: z.boolean(),\n})\n","import { z } from 'zod'\nimport {\n  REMOTE_PROTOCOLS,\n  capabilityCredentialIssues,\n  pluginValueCredentialIssues,\n  remoteEntryIssues,\n} from '@vostride/agent-qa-schema'\nimport { DurationString, NameSlugSchema } from './primitives.js'\n\nexport const UrlRemoteEntrySchema = z\n  .strictObject({\n    name: NameSlugSchema,\n    protocol: z.enum(REMOTE_PROTOCOLS),\n    url: z.string(),\n    query: z\n      .record(z.string(), z.union([z.string(), z.record(z.string(), z.unknown())]))\n      .optional(),\n    headers: z.record(z.string(), z.string()).optional(),\n    basicAuth: z\n      .strictObject({\n        user: z.string(),\n        password: z.string(),\n      })\n      .optional(),\n    connectTimeout: DurationString.optional(),\n    context: z.enum(['new', 'reuse']).optional(),\n    capabilities: z.record(z.string(), z.unknown()).optional(),\n  })\n  .superRefine((entry, ctx) => {\n    for (const issue of remoteEntryIssues(entry)) {\n      ctx.addIssue({ code: 'custom', path: issue.path, message: issue.message })\n    }\n  })\n\nexport const PluginRemoteEntrySchema = z\n  .strictObject({\n    name: NameSlugSchema,\n    plugin: NameSlugSchema,\n    settings: z.record(z.string(), z.unknown()).optional(),\n    connectTimeout: DurationString.optional(),\n    uploadTimeout: DurationString.optional(),\n    context: z.enum(['new', 'reuse']).optional(),\n    capabilities: z.record(z.string(), z.unknown()).optional(),\n  })\n  .superRefine((entry, ctx) => {\n    if (entry.capabilities !== undefined) {\n      for (const issue of capabilityCredentialIssues(entry.capabilities, ['capabilities'])) {\n        ctx.addIssue({\n          code: 'custom',\n          path: [...issue.path],\n          message: `Remote ${entry.name}: ${issue.message}`,\n        })\n      }\n    }\n    if (entry.settings !== undefined) {\n      const label = `Remote ${entry.name}: settings`\n      for (const issue of pluginValueCredentialIssues(entry.settings, ['settings'], label)) {\n        ctx.addIssue({ code: 'custom', path: [...issue.path], message: issue.message })\n      }\n    }\n  })\n\n// configShapeScan words a remote that fits neither form before this union sees it.\nexport const RemoteEntrySchema = z.union([UrlRemoteEntrySchema, PluginRemoteEntrySchema])\n\nexport type UrlRemoteEntry = z.infer<typeof UrlRemoteEntrySchema>\nexport type PluginRemoteEntry = z.infer<typeof PluginRemoteEntrySchema>\nexport type RemoteEntry = z.infer<typeof RemoteEntrySchema>\n\nexport function isPluginRemoteEntry(entry: RemoteEntry): entry is PluginRemoteEntry {\n  return 'plugin' in entry\n}\n\nexport function isUrlRemoteEntry(entry: RemoteEntry): entry is UrlRemoteEntry {\n  return 'url' in entry\n}\n","import {\n  DEFAULT_REMOTE_CONNECT_TIMEOUT_MS,\n  type RemoteBrowserConfig,\n  type RemoteBrowserProtocol,\n  type RemotePluginBrowserConfig,\n} from '@vostride/agent-qa-runner'\nimport type { DevicePlace } from '../mobile/select-device.js'\nimport type { RunAttributeRunner } from '../run-attributes.js'\nimport {\n  isPluginRemoteEntry,\n  type PluginRemoteEntry,\n  type RemoteEntry,\n  type UrlRemoteEntry,\n} from '../schema/remote-schema.js'\n\nexport type WebPlace =\n  | { kind: 'local' }\n  | { kind: 'remote'; remote: RemoteBrowserConfig | RemotePluginBrowserConfig }\n\nexport type BrowserEngine = 'chromium' | 'firefox' | 'webkit'\n\nexport interface SelectWebPlaceInput {\n  remotes: readonly RemoteEntry[]\n  suite?: string\n  test?: string\n  config?: string\n  // The file the pick came from, named in the refusal.\n  file?: string\n  // The engine the test runs in, after `--browser`.\n  engine?: BrowserEngine\n}\n\nexport interface SuiteMemberPick {\n  // The member file, relative to the config directory with forward slashes.\n  file: string\n  pick?: string\n}\n\nexport interface SelectSuitePlaceInput {\n  remotes: readonly RemoteEntry[]\n  suiteName: string\n  suiteFile: string\n  suite?: string\n  config?: string\n  members: readonly SuiteMemberPick[]\n  engine?: BrowserEngine\n}\n\nexport type SelectWebPlaceResult = { place: WebPlace } | { refusal: string }\n\nexport type BrowserRemoteEntry =\n  | (UrlRemoteEntry & { protocol: RemoteBrowserProtocol })\n  | PluginRemoteEntry\n\nconst LOCAL_PICK = 'local'\n\nexport function toRemoteBrowserConfig(\n  entry: UrlRemoteEntry & { protocol: RemoteBrowserProtocol },\n): RemoteBrowserConfig\nexport function toRemoteBrowserConfig(entry: PluginRemoteEntry): RemotePluginBrowserConfig\nexport function toRemoteBrowserConfig(\n  entry: BrowserRemoteEntry,\n): RemoteBrowserConfig | RemotePluginBrowserConfig\nexport function toRemoteBrowserConfig(\n  entry: BrowserRemoteEntry,\n): RemoteBrowserConfig | RemotePluginBrowserConfig {\n  if (isPluginRemoteEntry(entry)) {\n    return {\n      name: entry.name,\n      plugin: {\n        entry: entry.plugin,\n        ...(entry.settings ? { settings: entry.settings } : {}),\n      },\n      connectTimeoutMs: entry.connectTimeout ?? DEFAULT_REMOTE_CONNECT_TIMEOUT_MS,\n      ...(entry.context ? { context: entry.context } : {}),\n    }\n  }\n  return {\n    name: entry.name,\n    protocol: entry.protocol,\n    url: entry.url,\n    ...(entry.query ? { query: entry.query } : {}),\n    ...(entry.headers ? { headers: entry.headers } : {}),\n    ...(entry.basicAuth ? { basicAuth: entry.basicAuth } : {}),\n    connectTimeoutMs: entry.connectTimeout ?? DEFAULT_REMOTE_CONNECT_TIMEOUT_MS,\n    ...(entry.context ? { context: entry.context } : {}),\n  }\n}\n\n// The suite's pick wins, then the test's, then the config's; no pick runs here.\nexport function selectWebPlace(input: SelectWebPlaceInput): SelectWebPlaceResult {\n  const pick = input.suite ?? input.test ?? input.config\n  if (pick === undefined || pick === LOCAL_PICK) return { place: { kind: 'local' } }\n  const entry = input.remotes.find((remote) => remote.name === pick)\n  if (!entry) {\n    const from = input.file ?? pickedBy(input)\n    const listed =\n      input.remotes.length === 0\n        ? 'registry.remotes lists no remotes.'\n        : `registry.remotes lists: ${input.remotes.map((remote) => remote.name).join(', ')}.`\n    return { refusal: `Unknown remote \"${pick}\" in ${from}. ${listed}` }\n  }\n  // What a plugin remote serves is checked at run start, when its manifest is read.\n  if (isPluginRemoteEntry(entry)) {\n    return { place: { kind: 'remote', remote: toRemoteBrowserConfig(entry) } }\n  }\n  if (entry.protocol === 'appium') {\n    return {\n      refusal: `Remote ${entry.name} is an appium remote; use.browser.remote picks a playwright or cdp remote.`,\n    }\n  }\n  if (entry.protocol === 'cdp' && input.engine !== undefined && input.engine !== 'chromium') {\n    return {\n      refusal: `Remote ${entry.name} serves Chromium only; this test asks for ${input.engine}.`,\n    }\n  }\n  return {\n    place: {\n      kind: 'remote',\n      remote: toRemoteBrowserConfig({ ...entry, protocol: entry.protocol }),\n    },\n  }\n}\n\n// A suite shares one browser, so all its members run in one place.\nexport function selectSuitePlace(input: SelectSuitePlaceInput): SelectWebPlaceResult {\n  const { remotes, config, engine } = input\n  if (input.suite !== undefined) {\n    return selectWebPlace({ remotes, suite: input.suite, file: input.suiteFile, engine })\n  }\n  for (const member of input.members) {\n    const selected = selectWebPlace({\n      remotes,\n      test: member.pick,\n      config,\n      ...(member.pick === undefined ? {} : { file: member.file }),\n    })\n    if ('refusal' in selected) return selected\n  }\n  const picks = input.members.map((member) => ({\n    file: member.file,\n    pick: member.pick ?? config ?? LOCAL_PICK,\n  }))\n  const agreed = picks[0]?.pick ?? config\n  if (picks.some(({ pick }) => pick !== agreed)) {\n    const named = picks.map(({ file, pick }) => `${file} picks ${pick}`)\n    const listed = `${named.slice(0, -1).join(', ')} and ${named[named.length - 1]}`\n    return {\n      refusal:\n        `Suite ${input.suiteName} runs its tests in one place, but ${listed}. ` +\n        'Set use.browser.remote in the suite or make the tests agree.',\n    }\n  }\n  return selectWebPlace({ remotes, test: agreed, engine })\n}\n\n// A run is remote when any of its tests runs on a remote, in a browser or on a device.\nexport function runnerForPlaces(places: readonly (WebPlace | DevicePlace)[]): RunAttributeRunner {\n  return places.some((place) => place.kind === 'remote') ? 'remote' : 'local'\n}\n\nfunction pickedBy(input: SelectWebPlaceInput): string {\n  if (input.suite !== undefined) return 'the suite'\n  if (input.test !== undefined) return 'the test'\n  return 'the config'\n}\n","import {\n  DEFAULT_REMOTE_CONNECT_TIMEOUT_MS,\n  DEFAULT_REMOTE_UPLOAD_TIMEOUT_MS,\n  type RemoteDeviceConfig,\n  type RemotePluginDeviceConfig,\n} from '@vostride/agent-qa-runner'\nimport {\n  isUrlRemoteEntry,\n  type PluginRemoteEntry,\n  type RemoteEntry,\n  type UrlRemoteEntry,\n} from '../schema/remote-schema.js'\n\nexport type DevicePlace =\n  | { kind: 'local'; device: string }\n  | { kind: 'remote'; device: string; remote: RemoteDeviceConfig | RemotePluginDeviceConfig }\n\nexport interface SelectDevicePlaceInput {\n  devices: Record<string, { remote?: string }>\n  remotes: readonly RemoteEntry[]\n  device: string\n  // The file the device name came from, named in the refusal.\n  file?: string\n}\n\nexport type SelectDevicePlaceResult = { place: DevicePlace } | { refusal: string }\n\nexport function toRemoteDeviceConfig(entry: UrlRemoteEntry): RemoteDeviceConfig {\n  return {\n    name: entry.name,\n    protocol: 'appium',\n    url: entry.url,\n    ...(entry.headers ? { headers: entry.headers } : {}),\n    ...(entry.basicAuth ? { basicAuth: entry.basicAuth } : {}),\n    connectTimeoutMs: entry.connectTimeout ?? DEFAULT_REMOTE_CONNECT_TIMEOUT_MS,\n    ...(entry.capabilities ? { capabilities: entry.capabilities } : {}),\n  }\n}\n\nexport function toRemotePluginDeviceConfig(entry: PluginRemoteEntry): RemotePluginDeviceConfig {\n  return {\n    name: entry.name,\n    plugin: {\n      entry: entry.plugin,\n      ...(entry.settings ? { settings: entry.settings } : {}),\n    },\n    connectTimeoutMs: entry.connectTimeout ?? DEFAULT_REMOTE_CONNECT_TIMEOUT_MS,\n    uploadTimeoutMs: entry.uploadTimeout ?? DEFAULT_REMOTE_UPLOAD_TIMEOUT_MS,\n    ...(entry.capabilities ? { capabilities: entry.capabilities } : {}),\n  }\n}\n\nexport function selectDevicePlace(input: SelectDevicePlaceInput): SelectDevicePlaceResult {\n  const { device } = input\n  const profile = Object.hasOwn(input.devices, device) ? input.devices[device] : undefined\n  if (profile === undefined) {\n    const names = Object.keys(input.devices)\n    const listed =\n      names.length === 0\n        ? 'registry.devices lists no devices.'\n        : `registry.devices lists: ${names.join(', ')}.`\n    const from = input.file === undefined ? '' : ` in ${input.file}`\n    return { refusal: `Unknown device \"${device}\"${from}. ${listed}` }\n  }\n  if (profile.remote === undefined) return { place: { kind: 'local', device } }\n  const entry = input.remotes.find((remote) => remote.name === profile.remote)\n  if (!entry) {\n    const listed =\n      input.remotes.length === 0\n        ? 'registry.remotes lists no remotes.'\n        : `registry.remotes lists: ${input.remotes.map((remote) => remote.name).join(', ')}.`\n    return {\n      refusal: `Device ${device} names remote \"${profile.remote}\", which registry.remotes does not list. ${listed}`,\n    }\n  }\n  // What a plugin remote serves is checked at run start, when its manifest is read.\n  if (!isUrlRemoteEntry(entry)) {\n    return { place: { kind: 'remote', device, remote: toRemotePluginDeviceConfig(entry) } }\n  }\n  if (entry.protocol !== 'appium') {\n    return {\n      refusal: `Device ${device} names remote ${entry.name}, a ${entry.protocol} remote; a device's remote needs protocol: appium.`,\n    }\n  }\n  return { place: { kind: 'remote', device, remote: toRemoteDeviceConfig(entry) } }\n}\n\nexport type DeviceProfiles = Record<string, { platform?: string; remote?: string }>\n\nexport interface DeviceTarget {\n  name: string\n  platform: string\n  device?: string\n}\n\nexport interface SelectTestDeviceInput {\n  devices: DeviceProfiles\n  remotes: readonly RemoteEntry[]\n  target: DeviceTarget\n  // The `--device` value.\n  flag?: string\n  // The test's `use.device`.\n  test?: string\n  // The test file, named when its pick is refused.\n  file?: string\n}\n\nconst FLAG = '--device'\n\n// `--device` wins, then the test's pick, then its target's device.\nexport function selectTestDevice(input: SelectTestDeviceInput): SelectDevicePlaceResult {\n  const { devices, remotes, target } = input\n  if (input.flag !== undefined) {\n    return placeDevice({ devices, remotes, targets: [target], device: input.flag, from: FLAG })\n  }\n  if (input.test !== undefined) {\n    return placeDevice({\n      devices,\n      remotes,\n      targets: [target],\n      device: input.test,\n      from: input.file,\n    })\n  }\n  if (target.device !== undefined) {\n    return placeDevice({\n      devices,\n      remotes,\n      targets: [target],\n      device: target.device,\n      from: targetSource(target),\n    })\n  }\n  return {\n    refusal:\n      `No device specified for mobile target \"${target.name}\". ` +\n      `Set device on registry.targets.${target.name}, or use.device in the test or its suite.`,\n  }\n}\n\nexport interface SuiteMemberDevice {\n  // The member file, relative to the config directory with forward slashes.\n  file: string\n  // The member's `use.device`.\n  pick?: string\n  target: DeviceTarget\n}\n\nexport interface SelectSuiteDeviceInput {\n  devices: DeviceProfiles\n  remotes: readonly RemoteEntry[]\n  suiteName: string\n  suiteFile: string\n  flag?: string\n  // The suite's `use.device`.\n  suite?: string\n  members: readonly SuiteMemberDevice[]\n}\n\n// A suite runs on one device: `--device`, else the suite's pick, else the one its members agree on.\nexport function selectSuiteDevice(input: SelectSuiteDeviceInput): SelectDevicePlaceResult {\n  const { devices, remotes, suiteName } = input\n  const targets = input.members.map((member) => member.target)\n  if (input.flag !== undefined) {\n    return placeDevice({ devices, remotes, targets, device: input.flag, from: FLAG })\n  }\n  if (input.suite !== undefined) {\n    return placeDevice({ devices, remotes, targets, device: input.suite, from: input.suiteFile })\n  }\n  const picks: { file: string; device: string; place: DevicePlace }[] = []\n  for (const member of input.members) {\n    const device = member.pick ?? member.target.device\n    if (device === undefined) {\n      return {\n        refusal:\n          `Suite ${suiteName} runs its tests on one device, but ${member.file} picks none. ` +\n          'Set use.device in the suite, or device on its target.',\n      }\n    }\n    const from = member.pick === undefined ? targetSource(member.target) : member.file\n    const selected = placeDevice({ devices, remotes, targets: [member.target], device, from })\n    if ('refusal' in selected) return selected\n    picks.push({ file: member.file, device, place: selected.place })\n  }\n  const first = picks[0]\n  if (first === undefined) {\n    return {\n      refusal: `Suite ${suiteName} has no tests to pick a device. Set use.device in the suite.`,\n    }\n  }\n  if (picks.some(({ device }) => device !== first.device)) {\n    const named = picks.map(({ file, device }) => `${file} picks ${device}`)\n    const listed = `${named.slice(0, -1).join(', ')} and ${named[named.length - 1]}`\n    return {\n      refusal:\n        `Suite ${suiteName} runs its tests on one device, but ${listed}. ` +\n        'Set use.device in the suite or make the tests agree.',\n    }\n  }\n  return { place: first.place }\n}\n\nfunction placeDevice(input: {\n  devices: DeviceProfiles\n  remotes: readonly RemoteEntry[]\n  targets: readonly DeviceTarget[]\n  device: string\n  from?: string\n}): SelectDevicePlaceResult {\n  const { devices, remotes, device } = input\n  const profile = Object.hasOwn(devices, device) ? devices[device] : undefined\n  if (profile !== undefined) {\n    if (input.from === FLAG && profile.remote !== undefined) {\n      return {\n        refusal:\n          `Device ${device} runs on remote ${profile.remote}; --device picks a device on this machine. ` +\n          `Set use.device: ${device} in a suite or test to run there.`,\n      }\n    }\n    const platform = profile.platform\n    const other = input.targets.find(\n      (target) => platform !== undefined && target.platform !== platform,\n    )\n    if (other !== undefined) {\n      return {\n        refusal: `Device \"${device}\" is ${platform}, but target \"${other.name}\" is ${other.platform}.`,\n      }\n    }\n  }\n  return selectDevicePlace({\n    devices,\n    remotes,\n    device,\n    ...(input.from === undefined ? {} : { file: input.from }),\n  })\n}\n\nfunction targetSource(target: DeviceTarget): string {\n  return `registry.targets.${target.name}`\n}\n","import type { MobilePlatform } from './launch-resolver.js'\n\nexport const W3C_STANDARD_CAPABILITIES: readonly string[] = [\n  'browserName',\n  'browserVersion',\n  'platformName',\n  'acceptInsecureCerts',\n  'pageLoadStrategy',\n  'proxy',\n  'setWindowRect',\n  'timeouts',\n  'strictFileInteractability',\n  'unhandledPromptBehavior',\n  'userAgent',\n  'webSocketUrl',\n]\n\nexport type CapabilityMap = Record<string, unknown>\n\nconst APPIUM_OPTIONS = 'appium:options'\nconst ANDROID_DRIVERS = ['uiautomator2', 'espresso']\nconst IOS_DRIVERS = ['xcuitest']\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n  if (value === null || typeof value !== 'object' || Array.isArray(value)) return false\n  const proto = Object.getPrototypeOf(value)\n  return proto === Object.prototype || proto === null\n}\n\nfunction setKey(target: CapabilityMap, key: string, value: unknown): void {\n  Object.defineProperty(target, key, {\n    value,\n    enumerable: true,\n    writable: true,\n    configurable: true,\n  })\n}\n\nfunction copyValue(value: unknown): unknown {\n  if (isPlainObject(value)) return mergeLayer({}, value)\n  if (Array.isArray(value)) return [...value]\n  return value\n}\n\nfunction mergeLayer(base: CapabilityMap, layer: CapabilityMap): CapabilityMap {\n  const out: CapabilityMap = {}\n  for (const [key, value] of Object.entries(base)) setKey(out, key, value)\n  for (const [key, value] of Object.entries(layer)) {\n    if (value === null) {\n      delete out[key]\n      continue\n    }\n    const current = Object.hasOwn(out, key) ? out[key] : undefined\n    const merged =\n      isPlainObject(current) && isPlainObject(value) ? mergeLayer(current, value) : copyValue(value)\n    setKey(out, key, merged)\n  }\n  return out\n}\n\nexport function mergeCapabilities(...layers: (CapabilityMap | undefined)[]): CapabilityMap {\n  let merged: CapabilityMap = {}\n  for (const layer of layers) if (layer !== undefined) merged = mergeLayer(merged, layer)\n  return merged\n}\n\ninterface CapabilityEntry {\n  key: string\n  value: unknown\n}\n\n// Appium promotes appium:options children to appium: keys, overwriting a top-level one.\nfunction capabilityEntry(caps: CapabilityMap, name: string): CapabilityEntry | undefined {\n  if (W3C_STANDARD_CAPABILITIES.includes(name)) {\n    return Object.hasOwn(caps, name) ? { key: name, value: caps[name] } : undefined\n  }\n  const options = Object.hasOwn(caps, APPIUM_OPTIONS) ? caps[APPIUM_OPTIONS] : undefined\n  if (isPlainObject(options) && Object.hasOwn(options, name)) {\n    return { key: `${APPIUM_OPTIONS}.${name}`, value: options[name] }\n  }\n  const prefixed = `appium:${name}`\n  return Object.hasOwn(caps, prefixed) ? { key: prefixed, value: caps[prefixed] } : undefined\n}\n\nexport function capabilityValue(caps: CapabilityMap, name: string): unknown {\n  return capabilityEntry(caps, name)?.value\n}\n\nfunction asText(value: unknown): string | undefined {\n  if (typeof value === 'string') return value.trim()\n  if (typeof value === 'number' || typeof value === 'boolean') return String(value)\n  return undefined\n}\n\nfunction shown(value: unknown): string {\n  if (typeof value === 'string') return `\"${value}\"`\n  if (value === null || typeof value !== 'object') return String(value)\n  return JSON.stringify(value)\n}\n\nfunction differs(value: unknown, stated: string, caseless = false): boolean {\n  const text = asText(value)\n  if (text === undefined) return true\n  return caseless ? text.toLowerCase() !== stated.toLowerCase() : text !== stated\n}\n\ninterface CapabilityLayer {\n  owner: string\n  // How the second half of a refusal names the device: \"its\" or \"device <d>\".\n  device: string\n  capabilities: CapabilityMap\n}\n\nfunction layersOf(input: {\n  device: string\n  remote?: { name: string; capabilities?: CapabilityMap }\n  capabilities?: CapabilityMap\n}): CapabilityLayer[] {\n  const layers: CapabilityLayer[] = []\n  if (input.remote?.capabilities !== undefined) {\n    layers.push({\n      owner: `Remote ${input.remote.name}`,\n      device: `device ${input.device}`,\n      capabilities: input.remote.capabilities,\n    })\n  }\n  if (input.capabilities !== undefined) {\n    layers.push({\n      owner: `Device ${input.device}`,\n      device: 'the device',\n      capabilities: input.capabilities,\n    })\n  }\n  return layers\n}\n\nfunction sets(layer: CapabilityLayer, entry: CapabilityEntry): string {\n  return `${layer.owner} sets ${entry.key} ${shown(entry.value)} in its capabilities`\n}\n\nfunction possessive(layer: CapabilityLayer): string {\n  return layer.device === 'the device' ? 'its' : `${layer.device}'s`\n}\n\nfunction driverPlatform(driver: unknown): MobilePlatform | undefined {\n  const text = asText(driver)?.toLowerCase()\n  if (text === undefined) return undefined\n  if (ANDROID_DRIVERS.includes(text)) return 'android'\n  if (IOS_DRIVERS.includes(text)) return 'ios'\n  return undefined\n}\n\nexport interface StaticCapabilityInput {\n  device: string\n  platform: MobilePlatform\n  model?: string\n  os?: string\n  id?: string\n  remote?: { name: string; capabilities?: CapabilityMap }\n  capabilities?: CapabilityMap\n}\n\nexport function staticCapabilityContradictions(input: StaticCapabilityInput): string[] {\n  const found: string[] = []\n  const stated: [string, 'model' | 'os' | 'id', string | undefined][] = [\n    ['deviceName', 'model', input.model],\n    ['platformVersion', 'os', input.os],\n    ['udid', 'id', input.id],\n  ]\n  for (const layer of layersOf(input)) {\n    for (const key of Object.keys(layer.capabilities)) {\n      if (!key.includes(':') && !W3C_STANDARD_CAPABILITIES.includes(key)) {\n        const fix = `needs a vendor prefix, such as appium:${key}.`\n        found.push(`${layer.owner} capabilities \"${key}\" ${fix}`)\n      }\n    }\n\n    const platformName = capabilityEntry(layer.capabilities, 'platformName')\n    if (platformName && differs(platformName.value, input.platform, true)) {\n      found.push(`${sets(layer, platformName)}; ${layer.device} is ${input.platform}.`)\n    }\n\n    const driver = capabilityEntry(layer.capabilities, 'automationName')\n    const serves = driver ? driverPlatform(driver.value) : undefined\n    if (driver && serves !== undefined && serves !== input.platform) {\n      const platform = `${layer.device} is ${input.platform}`\n      found.push(`${sets(layer, driver)}; that driver serves ${serves}, and ${platform}.`)\n    }\n\n    for (const [name, field, value] of stated) {\n      const statedValue = value?.trim()\n      if (statedValue === undefined || statedValue === '') continue\n      const entry = capabilityEntry(layer.capabilities, name)\n      if (entry && differs(entry.value, statedValue)) {\n        found.push(`${sets(layer, entry)}; ${possessive(layer)} ${field} is ${statedValue}.`)\n      }\n    }\n  }\n  return found\n}\n\nexport interface RunStartCapabilityInput {\n  device: string\n  target: { name: string; appPackage?: string; appActivity?: string; bundleId?: string }\n  appState: 'preserve' | 'reset'\n  browserMode: boolean\n  remote?: { name: string; capabilities?: CapabilityMap }\n  capabilities?: CapabilityMap\n}\n\nconst APP_ID_FIELDS = ['appPackage', 'appActivity', 'bundleId'] as const\n\nexport function runStartCapabilityContradictions(input: RunStartCapabilityInput): string[] {\n  const found: string[] = []\n  const noReset = input.appState === 'preserve'\n  const appState = `use.mobile.appState is ${input.appState}`\n  for (const layer of layersOf(input)) {\n    for (const field of APP_ID_FIELDS) {\n      const stated = input.target[field]?.trim()\n      if (stated === undefined || stated === '') continue\n      const entry = capabilityEntry(layer.capabilities, field)\n      if (entry && differs(entry.value, stated)) {\n        found.push(`${sets(layer, entry)}; target ${input.target.name} has ${field} ${stated}.`)\n      }\n    }\n\n    if (input.browserMode) continue\n    const noResetEntry = capabilityEntry(layer.capabilities, 'noReset')\n    if (noResetEntry && differs(noResetEntry.value, String(noReset), true)) {\n      found.push(`${sets(layer, noResetEntry)}; ${appState}.`)\n    }\n    const fullReset = capabilityEntry(layer.capabilities, 'fullReset')\n    if (fullReset && noReset && asText(fullReset.value)?.toLowerCase() === 'true') {\n      found.push(`${sets(layer, fullReset)}; ${appState}.`)\n    }\n  }\n  return found\n}\n\nexport interface RemoteAppInput {\n  device: string\n  remote: string\n  target: string\n  appRef?: string\n  appPath?: string\n  // The merged capabilities the session would send.\n  capabilities: CapabilityMap\n}\n\nexport type RemoteAppResult = { app?: string } | { refusal: string }\n\nexport function remoteAppCapability(input: RemoteAppInput): RemoteAppResult {\n  if (capabilityEntry(input.capabilities, 'app') !== undefined) return {}\n  const appRef = input.appRef?.trim()\n  if (appRef) return { app: appRef }\n  if (input.appPath?.trim()) {\n    return {\n      refusal: `Device ${input.device} runs on remote ${input.remote}, and target ${input.target} has only app.path. Set app.ref to the app the server installs.`,\n    }\n  }\n  return {}\n}\n\nexport function remoteDerivedIdentity(input: {\n  model?: string\n  os?: string\n  id?: string\n}): CapabilityMap {\n  const identity: CapabilityMap = {}\n  if (input.model !== undefined) identity['appium:deviceName'] = input.model\n  if (input.os !== undefined) identity['appium:platformVersion'] = input.os\n  if (input.id !== undefined) identity['appium:udid'] = input.id\n  return identity\n}\n","import { z } from 'zod'\n\nexport const WorkspaceSchema = z.strictObject({\n  testMatch: z.array(z.string().min(1)).min(1),\n  suiteMatch: z.array(z.string().min(1)).min(1),\n  testPathIgnore: z.array(z.string()).optional(),\n  hooksFile: z.string().min(1, 'hooksFile is required.'),\n  envFile: z.string().min(1, 'envFile is required.'),\n  secretsFile: z.string().min(1, 'secretsFile is required.'),\n})\n","import { z } from 'zod'\nimport { SizeString } from './primitives.js'\n\n/**\n * Whether a configured value is an ABSOLUTE `http:`/`https:` URL.\n *\n * FILE-LOCAL, DELIBERATELY, unlike `isLoopbackHost` below, which is exported for the dashboard's\n * bind guard in another package. This one has exactly one decision site — the parse boundary,\n * immediately below. Exporting it would advertise a second place to make the same check, and the\n * whole point of a parse-time guard is that there is no second place: nothing downstream should be\n * re-deciding whether the base is safe.\n *\n * A RELATIVE VALUE IS REFUSED, not resolved. `new URL(value)` with no base throws for\n * `/relative/only` and for `not-a-url`, and the scheme test refuses `javascript:` and `mailto:`\n * — which parse fine and are exactly the shapes that must not reach an `href`.\n */\nfunction isAbsoluteHttpUrl(value: string): boolean {\n  try {\n    const url = new URL(value)\n    return url.protocol === 'http:' || url.protocol === 'https:'\n  } catch {\n    return false\n  }\n}\n\nconst DASHBOARD_PORT_MESSAGE = 'services.dashboard.port must be a whole number from 1 to 65535'\n\nexport const DashboardConfigSchema = z.strictObject({\n  port: z\n    .number()\n    .int({ error: DASHBOARD_PORT_MESSAGE })\n    .min(1, { error: DASHBOARD_PORT_MESSAGE })\n    .max(65535, { error: DASHBOARD_PORT_MESSAGE })\n    .optional(),\n  dbPath: z.string().optional(),\n  artifactsDir: z.string().optional(),\n  // Only an absolute http(s) URL: the base composes an `href` inside the served App document.\n  baseUrl: z.string().refine(\n    isAbsoluteHttpUrl,\n    { error: 'services.dashboard.baseUrl must be an absolute http(s) URL' },\n  ).optional(),\n  workspace: z.string().optional(),\n  // The run service and the other local doors are tokenless, so this block declares no token key.\n  // The interface the dashboard binds. A plain string, because the pre-listen bind guard refuses\n  // any non-loopback value at runtime, as the security refusal it is rather than a config-shape\n  // error, and a loopback spelling other than the default (`localhost`, `::1`) stays configurable.\n  host: z.string().trim().min(1).optional(),\n})\n\n/**\n * The one member set for \"this host is loopback\", used by the dashboard's pre-listen bind guard in\n * `startServer`, which refuses a non-loopback dashboard host at runtime with no exemption.\n */\nexport const LOOPBACK_HOSTS: readonly string[] = Object.freeze(['localhost', '127.0.0.1', '::1'])\n\n/** Whether a configured host names a loopback interface. The one predicate over the one set. */\nexport function isLoopbackHost(host: string): boolean {\n  return LOOPBACK_HOSTS.includes(host.trim())\n}\n\n// Whether the dashboard co-hosts the MCP endpoint, and the port it listens on.\nexport const McpConfigSchema = z.strictObject({\n  enabled: z.boolean().optional(),\n  port: z.number().int().min(0).max(65535).optional(),\n})\n\nexport const CacheConfigSchema = z.strictObject({\n  dir: z.string(),\n})\n\nexport const AuthStateConfigSchema = z.strictObject({\n  dir: z.string().trim().min(1),\n})\n\nexport const LoggingConfigSchema = z.strictObject({\n  level: z.enum(['silent', 'error', 'warn', 'info', 'debug']),\n})\n\nexport const RecordingConfigSchema = z.strictObject({\n  enabled: z.boolean().default(true),\n  keepFailuresOnly: z.boolean().optional(),\n})\n\nexport const AccessibilityConfigSchema = z.strictObject({\n  enabled: z.boolean(),\n  standard: z.enum(['wcag2a', 'wcag2aa', 'wcag2aaa']).optional(),\n  runAfter: z.enum(['every-step', 'test-end']).optional(),\n  failOnViolation: z.boolean().optional(),\n  disableRules: z.array(z.string()).optional(),\n  exclude: z.array(z.string()).optional(),\n})\n\nexport const VisionServiceSchema = z.strictObject({\n  screenshotSize: SizeString.optional(),\n  effectiveResolution: z.number().positive().int().optional(),\n})\n\nexport const ServicesSchema = z.strictObject({\n  dashboard: DashboardConfigSchema.optional(),\n  mcp: McpConfigSchema.optional(),\n  cache: CacheConfigSchema.optional(),\n  authState: AuthStateConfigSchema.optional(),\n  logging: LoggingConfigSchema.optional(),\n  // Parse omitted containers too, while retaining optional authoring/input compatibility.\n  recording: RecordingConfigSchema.prefault({}).optional(),\n  accessibility: AccessibilityConfigSchema.optional(),\n  vision: VisionServiceSchema.optional(),\n})\n","import { z } from 'zod'\n\n// A pure string predicate; composition roots resolve the path through `resolve-knowledge-root.ts`.\nconst isRepoRelative = (dir: string): boolean =>\n  !/^[/\\\\]|^[A-Za-z]:[\\\\/]/.test(dir) && !/^\\.\\.(?:[/\\\\]|$)/.test(dir)\n\nexport const KnowledgeConfigSchema = z.strictObject({\n  dir: z.string().trim().min(1)\n    .refine(isRepoRelative, {\n      error: 'knowledge.dir must be repo-relative — the committed knowledge root must live inside the repo for PR review and the committed .gitignore split',\n    })\n    .default('agent-qa-knowledge'),\n})\n","import { z } from 'zod'\n\n// Refusals for removed config keys. This scan is a zod pipe PRE-stage in front of the strict root\n// schema — a superRefine chained after a strict object never runs when strict rejects a value\n// (verified on zod 4.6.7), so these messages must fire first. The scan only ADDS issues; the strict stage-B\n// parse remains the acceptance authority. Every issue carries params.retired. Keys removed in v2\n// also carry params.hardCut, so the CLI closes the error with the hard-cut steps; any other removed\n// key closes with the ordinary key fix.\nconst RETIRED_MEMORY_KEY_MESSAGES: Record<string, string> = {\n  dir: 'services.memory.dir was removed in v2 — use knowledge.dir (default agent-qa-knowledge)',\n  enabled: 'services.memory.enabled was removed in v2 — memory is always on; delete this key (no disable switch)',\n  provider: 'services.memory.provider was removed in v2 — internalized — delete this key',\n  minTrust: 'services.memory.minTrust was removed in v2 — internalized — delete this key',\n  maxInjections: 'services.memory.maxInjections was removed in v2 — internalized — delete this key',\n  curatorEnabled: 'services.memory.curatorEnabled was removed in v2 — internalized — delete this key',\n  curatorLockTimeout: 'services.memory.curatorLockTimeout was removed in v2 — internalized — delete this key',\n  trustConfirmDelta: 'services.memory.trustConfirmDelta was removed in v2 — internalized — delete this key',\n  trustContradictDelta: 'services.memory.trustContradictDelta was removed in v2 — internalized — delete this key',\n  ablationEnabled: 'services.memory.ablationEnabled was removed — no ablation exists',\n  circuitBreakerEnabled: 'services.memory.circuitBreakerEnabled was removed — no circuit breaker exists',\n  circuitBreakerWindowSize: 'services.memory.circuitBreakerWindowSize was removed — no circuit breaker exists',\n  circuitBreakerBaselineSize: 'services.memory.circuitBreakerBaselineSize was removed — no circuit breaker exists',\n  circuitBreakerThreshold: 'services.memory.circuitBreakerThreshold was removed — no circuit breaker exists',\n}\n\nconst RETIRED_EVAL_KEY_MESSAGES: Record<string, string> = {\n  gate1: 'eval.gate1 was removed: memory is no longer screened by replay before promotion. Delete this block.',\n  gate2: 'eval.gate2 was removed: completed runs no longer replay served memory. Delete this block.',\n  adversarial: 'eval.adversarial was removed: runs no longer stage adversarial probes. Delete this block.',\n  seeding: 'eval.seeding was removed: runs no longer seed an eval corpus. Delete this block.',\n  judge: 'eval.judge was removed: pass --judge <name> to agent-qa eval replay. Delete this key.',\n  judges: 'eval.judges was removed: repeat --judge <name> on agent-qa eval replay. Delete this key.',\n  judgeAllowSameFamily:\n    'eval.judgeAllowSameFamily was removed: pass --judge-allow-same-family to agent-qa eval replay. Delete this key.',\n  k: 'eval.k was removed: pass --k <n> to agent-qa eval replay. Delete this key.',\n  seed: 'eval.seed was removed: pass --seed <n> to agent-qa eval replay. Delete this key.',\n}\n\nconst RETIRED_STEP_KEY_MESSAGES: Record<string, string> = {\n  retries:\n    'steps[].retries was removed: a test retries as a whole; set meta.retries. Delete this line.',\n  screenshot:\n    'steps[].screenshot was removed: screenshots are set per run; pass --screenshot-mode every-step to agent-qa run. Delete this line.',\n}\n\nconst RETIRED_EVAL_BLOCK_MESSAGE =\n  'eval was removed: agent-qa eval replay takes its settings as flags. Delete this block.'\n\nconst RETIRED_ALLOW_PRODUCTION_MESSAGE =\n  'allowProduction was removed: production targets run like any other target. Delete this line.'\n\nconst RETIRED_REGISTRY_PROVIDERS_MESSAGE =\n  'registry.providers was removed: list remote browsers and Appium servers under registry.remotes, with credentials as {{secret:NAME}} references to workspace.secretsFile. Delete this block.'\n\nconst RETIRED_PLUGINS_AUTH_MESSAGE =\n  'plugins.auth was removed: plugins is now a list of entries, each with a name and a package. For subscription sign-in, add name: subscription with package: @vostride/agent-qa-subscription-auth. Delete this block.'\n\nconst RETIRED_PLUGINS_PROVIDERS_MESSAGE =\n  'plugins.providers was removed: plugins is now a list of entries, each with a name and a package. Model-provider plugins load only from @vostride/agent-qa-* packages. Delete this block.'\n\nconst RETIRED_DEVICE_MATCH_MESSAGE =\n  'registry.devices.<name>.match was removed: describe the device with model and os (id pins one unit), move appPackage, appActivity and bundleId to the target, and put other Appium settings in capabilities. Delete this block.'\n\nconst RETIRED_DEVICE_TRANSPORT_MESSAGE =\n  \"registry.devices.<name>.transport was removed: to use an Appium server agent-qa doesn't start, list it under registry.remotes with protocol: appium and set the device's remote to its name. Delete this line.\"\n\nconst RETIRED_APP_BROWSERSTACK_MESSAGE =\n  \"registry.targets.<name>.app.browserstack was removed: set app.ref to the app a remote device installs, an https URL or the server's own reference; app.path stays the file for devices here. Delete this line.\"\n\nexport const LOCAL_FILE_NAME = 'agent-qa.local.yaml'\n\nexport const RETIRED_LOCAL_FILE_MESSAGE =\n  'agent-qa.local.yaml is no longer read: describe each device under registry.devices with model and os (id pins one unit), and set app.path on the target. Delete the file.'\n\nconst RETIRED_CACHE_TTL_MESSAGE =\n  'services.cache.ttl was removed: cached plans do not expire by age. Delete this line.'\n\nconst RETIRED_MCP_KEY_MESSAGES: Record<string, string> = {\n  host: 'services.mcp.host was removed: agent-qa mcp always listens on 127.0.0.1. Delete this line.',\n  path: 'services.mcp.path was removed: the MCP server answers on any path. Delete this line.',\n  transport:\n    'services.mcp.transport was removed: agent-qa mcp uses stdio, or HTTP with --http. Delete this line.',\n}\n\nconst RETIRED_RUN_AFTER_NAVIGATION_MESSAGE =\n  'services.accessibility.runAfter: navigation was removed: it never ran a check. Use test-end, or delete the line for every-step.'\n\nconst RETIRED_KNOWLEDGE_KEY_MESSAGES: Record<string, string> = {\n  contextBudgetTokens:\n    \"knowledge.contextBudgetTokens was removed: agent-qa sizes each run's knowledge itself. Delete this line.\",\n  commitArtifacts:\n    'knowledge.commitArtifacts was removed: knowledge bundles never commit images. Delete this line.',\n}\n\n// The old refilling planner key is cut with no alias, migration or fallback. The same message\n// fires for the project config and for test and suite `use` overrides.\nexport const RETIRED_MAX_SUB_ACTIONS_MESSAGE =\n  'use.planner.maxSubActions was removed in v2 — it was a refilling iteration count; set use.planner.maxActions (default 30) and use.planner.maxPlanningTurns (default 30)'\n\nconst RETIRED_PLANNER_KEY = 'maxSubActions'\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n  return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction hasRetiredPlannerKey(use: unknown): boolean {\n  return isPlainObject(use) && isPlainObject(use.planner) && Object.hasOwn(use.planner, RETIRED_PLANNER_KEY)\n}\n\nexport const retiredKeyScan = z.any().superRefine((value, ctx) => {\n  if (!isPlainObject(value)) return\n\n  if (isPlainObject(value.services) && value.services.memory !== undefined) {\n    ctx.addIssue({\n      code: 'custom',\n      params: { retired: true, hardCut: true },\n      path: ['services', 'memory'],\n      message: 'services.memory was removed in v2 — the memory config surface collapsed into the top-level knowledge block',\n    })\n    const memory = value.services.memory\n    if (isPlainObject(memory)) {\n      for (const key of Object.keys(memory)) {\n        const message = RETIRED_MEMORY_KEY_MESSAGES[key]\n        if (message) {\n          ctx.addIssue({\n            code: 'custom',\n            params: { retired: true, hardCut: true },\n            path: ['services', 'memory', key],\n            message,\n          })\n        }\n      }\n    }\n  }\n\n  if (isPlainObject(value.workspace) && value.workspace.agentRules !== undefined) {\n    ctx.addIssue({\n      code: 'custom',\n      params: { retired: true, hardCut: true },\n      path: ['workspace', 'agentRules'],\n      message: 'workspace.agentRules was removed in v2 — rules dissolve into agent-qa-knowledge/policies/<scope>.md files',\n    })\n  }\n\n  if (Object.hasOwn(value, 'eval')) {\n    let named = 0\n    if (isPlainObject(value.eval)) {\n      for (const key of Object.keys(value.eval)) {\n        if (Object.hasOwn(RETIRED_EVAL_KEY_MESSAGES, key)) {\n          named++\n          ctx.addIssue({\n            code: 'custom',\n            params: { retired: true },\n            path: ['eval', key],\n            message: RETIRED_EVAL_KEY_MESSAGES[key],\n          })\n        }\n      }\n    }\n    if (named === 0) {\n      ctx.addIssue({\n        code: 'custom',\n        params: { retired: true },\n        path: ['eval'],\n        message: RETIRED_EVAL_BLOCK_MESSAGE,\n      })\n    }\n  }\n\n  if (Object.hasOwn(value, 'allowProduction')) {\n    ctx.addIssue({\n      code: 'custom',\n      params: { retired: true },\n      path: ['allowProduction'],\n      message: RETIRED_ALLOW_PRODUCTION_MESSAGE,\n    })\n  }\n\n  if (isPlainObject(value.registry) && Object.hasOwn(value.registry, 'providers')) {\n    ctx.addIssue({\n      code: 'custom',\n      params: { retired: true },\n      path: ['registry', 'providers'],\n      message: RETIRED_REGISTRY_PROVIDERS_MESSAGE,\n    })\n  }\n\n  if (isPlainObject(value.plugins)) {\n    if (Object.hasOwn(value.plugins, 'auth')) {\n      ctx.addIssue({\n        code: 'custom',\n        params: { retired: true },\n        path: ['plugins', 'auth'],\n        message: RETIRED_PLUGINS_AUTH_MESSAGE,\n      })\n    }\n    if (Object.hasOwn(value.plugins, 'providers')) {\n      ctx.addIssue({\n        code: 'custom',\n        params: { retired: true },\n        path: ['plugins', 'providers'],\n        message: RETIRED_PLUGINS_PROVIDERS_MESSAGE,\n      })\n    }\n  }\n\n  if (isPlainObject(value.registry) && isPlainObject(value.registry.devices)) {\n    for (const [name, device] of Object.entries(value.registry.devices)) {\n      if (isPlainObject(device) && Object.hasOwn(device, 'match')) {\n        ctx.addIssue({\n          code: 'custom',\n          params: { retired: true },\n          path: ['registry', 'devices', name, 'match'],\n          message: RETIRED_DEVICE_MATCH_MESSAGE,\n        })\n      }\n      if (isPlainObject(device) && Object.hasOwn(device, 'transport')) {\n        ctx.addIssue({\n          code: 'custom',\n          params: { retired: true },\n          path: ['registry', 'devices', name, 'transport'],\n          message: RETIRED_DEVICE_TRANSPORT_MESSAGE,\n        })\n      }\n    }\n  }\n\n  if (isPlainObject(value.registry) && isPlainObject(value.registry.targets)) {\n    for (const [name, target] of Object.entries(value.registry.targets)) {\n      if (isPlainObject(target) && isPlainObject(target.app) && Object.hasOwn(target.app, 'browserstack')) {\n        ctx.addIssue({\n          code: 'custom',\n          params: { retired: true },\n          path: ['registry', 'targets', name, 'app', 'browserstack'],\n          message: RETIRED_APP_BROWSERSTACK_MESSAGE,\n        })\n      }\n    }\n  }\n\n  if (\n    isPlainObject(value.services) &&\n    isPlainObject(value.services.cache) &&\n    Object.hasOwn(value.services.cache, 'ttl')\n  ) {\n    ctx.addIssue({\n      code: 'custom',\n      params: { retired: true },\n      path: ['services', 'cache', 'ttl'],\n      message: RETIRED_CACHE_TTL_MESSAGE,\n    })\n  }\n\n  if (isPlainObject(value.services) && isPlainObject(value.services.mcp)) {\n    for (const key of Object.keys(value.services.mcp)) {\n      if (Object.hasOwn(RETIRED_MCP_KEY_MESSAGES, key)) {\n        ctx.addIssue({\n          code: 'custom',\n          params: { retired: true },\n          path: ['services', 'mcp', key],\n          message: RETIRED_MCP_KEY_MESSAGES[key],\n        })\n      }\n    }\n  }\n\n  if (\n    isPlainObject(value.services) &&\n    isPlainObject(value.services.accessibility) &&\n    value.services.accessibility.runAfter === 'navigation'\n  ) {\n    ctx.addIssue({\n      code: 'custom',\n      params: { retired: true },\n      path: ['services', 'accessibility', 'runAfter'],\n      message: RETIRED_RUN_AFTER_NAVIGATION_MESSAGE,\n    })\n  }\n\n  if (isPlainObject(value.knowledge)) {\n    for (const key of Object.keys(value.knowledge)) {\n      if (Object.hasOwn(RETIRED_KNOWLEDGE_KEY_MESSAGES, key)) {\n        ctx.addIssue({\n          code: 'custom',\n          params: { retired: true },\n          path: ['knowledge', key],\n          message: RETIRED_KNOWLEDGE_KEY_MESSAGES[key],\n        })\n      }\n    }\n  }\n\n  if (hasRetiredPlannerKey(value.use)) {\n    ctx.addIssue({\n      code: 'custom',\n      params: { retired: true, hardCut: true },\n      path: ['use', 'planner', RETIRED_PLANNER_KEY],\n      message: RETIRED_MAX_SUB_ACTIONS_MESSAGE,\n    })\n  }\n})\n\n// The pre-stage for a test or suite `use` override, for the same strict-parse reason as above.\nexport const retiredUseKeyScan = z.any().superRefine((value, ctx) => {\n  if (hasRetiredPlannerKey(value)) {\n    ctx.addIssue({\n      code: 'custom',\n      params: { retired: true, hardCut: true },\n      path: ['planner', RETIRED_PLANNER_KEY],\n      message: RETIRED_MAX_SUB_ACTIONS_MESSAGE,\n    })\n  }\n})\n\n// Pre-stage for a test step: the strict step union would otherwise report a generic error.\nexport const retiredStepKeyScan = z.any().superRefine((value, ctx) => {\n  if (!isPlainObject(value)) return\n  for (const [key, message] of Object.entries(RETIRED_STEP_KEY_MESSAGES)) {\n    if (!Object.hasOwn(value, key)) continue\n    ctx.addIssue({\n      code: 'custom',\n      params: { retired: true },\n      path: [key],\n      message,\n    })\n  }\n})\n","import { z } from 'zod'\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n  return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n// Shapes the strict parse would only report as a bare union or unknown-key error get one\n// sentence each here. Like the retired-key scan, this stage only adds issues.\nexport const configShapeScan = z.unknown().superRefine((value, ctx) => {\n  if (!isPlainObject(value)) return\n  if (isPlainObject(value.registry) && Array.isArray(value.registry.remotes)) {\n    value.registry.remotes.forEach((remote: unknown, index) => {\n      if (!isPlainObject(remote)) return\n      for (const issue of remoteShapeIssues(remote, index)) {\n        ctx.addIssue({\n          code: 'custom',\n          path: ['registry', 'remotes', index, ...issue.at],\n          message: issue.message,\n        })\n      }\n    })\n  }\n  if (!Array.isArray(value.plugins)) return\n  value.plugins.forEach((entry: unknown, index) => {\n    if (!isPlainObject(entry)) return\n    const name = typeof entry.name === 'string' ? entry.name : `#${index}`\n    const hasPackage = Object.hasOwn(entry, 'package')\n    const hasPath = Object.hasOwn(entry, 'path')\n    if (hasPackage && hasPath) {\n      ctx.addIssue({\n        code: 'custom',\n        path: ['plugins', index],\n        message: `Plugin entry ${name} names both package and path; an entry names one or the other.`,\n      })\n    } else if (!hasPackage && !hasPath) {\n      ctx.addIssue({\n        code: 'custom',\n        path: ['plugins', index],\n        message: `Plugin entry ${name} names no package or path; add package with the plugin's npm name, or path with its folder.`,\n      })\n    }\n    if (Object.hasOwn(entry, 'settings')) {\n      ctx.addIssue({\n        code: 'custom',\n        path: ['plugins', index, 'settings'],\n        message: `Plugin entry ${name} has settings; an entry's values go under options, and settings go on each remote that names the entry.`,\n      })\n    }\n  })\n})\n\nconst ENTRY_OPTION_KEYS = ['protocol', 'query', 'headers', 'basicAuth'] as const\n\ntype ShapeIssue = { at: string[]; message: string }\n\nfunction remoteShapeIssues(remote: Record<string, unknown>, index: number): ShapeIssue[] {\n  const name = typeof remote.name === 'string' ? remote.name : `#${index}`\n  const hasPlugin = Object.hasOwn(remote, 'plugin')\n  const hasUrl = Object.hasOwn(remote, 'url')\n  if (hasPlugin && hasUrl) {\n    return [\n      { at: [], message: `Remote ${name} has both plugin and url; a remote has one or the other.` },\n    ]\n  }\n  if (!hasPlugin && !hasUrl) {\n    return [\n      {\n        at: [],\n        message: `Remote ${name} names no url or plugin; add url with its protocol, or plugin with a plugins entry name.`,\n      },\n    ]\n  }\n  if (!hasPlugin) return []\n  const issues: ShapeIssue[] = ENTRY_OPTION_KEYS.filter((key) => Object.hasOwn(remote, key)).map(\n    (key) => ({\n      at: [key],\n      message: `Remote ${name} names a plugin, so ${key} belongs to its plugins entry's options; remove ${key} from the remote.`,\n    }),\n  )\n  if (Object.hasOwn(remote, 'options')) {\n    issues.push({\n      at: ['options'],\n      message: `Remote ${name} has options; a remote's plugin values go under settings, and account options go on its plugins entry.`,\n    })\n  }\n  return issues\n}\n","import { z } from 'zod'\n\nexport const AUTH_STATE_SCHEMA_VERSION = 2\nexport const AUTH_STATE_SLUG_PATTERN = /^[a-z][a-z0-9-]*[a-z0-9]$/\n\nexport const AuthStateNameSchema = z.string().regex(\n  AUTH_STATE_SLUG_PATTERN,\n  'Auth state name must match ^[a-z][a-z0-9-]*[a-z0-9]$',\n)\n\nexport const TargetNameSchema = z.string().regex(\n  AUTH_STATE_SLUG_PATTERN,\n  'Target name must match ^[a-z][a-z0-9-]*[a-z0-9]$',\n)\n\nexport const AuthStateMetadataSchema = z.object({\n  version: z.literal(AUTH_STATE_SCHEMA_VERSION),\n  kind: z.literal('web'),\n  target: TargetNameSchema,\n  name: AuthStateNameSchema,\n  capturedAt: z.iso.datetime(),\n}).strict()\n\nexport type AuthStateMetadata = z.infer<typeof AuthStateMetadataSchema>\n\n","import { z } from 'zod'\nimport { NameSlugSchema, NamedLLMConfigSchema } from './primitives.js'\nimport { RemoteEntrySchema } from './remote-schema.js'\nimport { TargetNameSchema } from '../auth-state/schema.js'\n\nfunction isAbsoluteAppPath(value: string): boolean {\n  return value.startsWith('/') || /^[A-Za-z]:[\\\\/]/.test(value) || value.startsWith('\\\\\\\\')\n}\n\nexport const AppInstallSchema = z.strictObject({\n  path: z.string()\n    .refine((v) => !isAbsoluteAppPath(v), { error: 'app.path must be relative' })\n    .optional(),\n  ref: z.string().trim().min(1).optional(),\n})\n\nexport const TargetSchema = z.strictObject({\n  product: z.string()\n    .refine(\n      (v) => !/\\.\\./.test(v) && !/[/\\\\]/.test(v) && !/\\0/.test(v),\n      { error: 'product must not contain \"..\", \"/\", \"\\\\\", or null bytes' }\n    )\n    .optional(),\n  platform: z.enum(['web', 'android', 'ios']),\n  bundleId: z.string().optional(),\n  appPackage: z.string().optional(),\n  appActivity: z.string().optional(),\n  app: AppInstallSchema.optional(),\n  device: z.string().trim().min(1).optional(),\n  url: z.string().optional(),\n  // A label only: agent-qa runs every target the same way, whatever it declares.\n  environment: z\n    .enum(['local', 'shared', 'production'])\n    .optional()\n    .describe(\"A label for this target's environment. agent-qa runs every target the same way.\"),\n}).superRefine((val, ctx) => {\n  if (val.platform === 'web' && !val.url) {\n    ctx.addIssue({ code: 'custom', message: 'Web targets must have a url' })\n  }\n})\n\nexport const DeviceProfileSchema = z.strictObject({\n  platform: z.enum(['android', 'ios']),\n  model: z.string().trim().min(1).optional(),\n  // YAML reads os: 17.10 as the number 17.1, so a number is refused rather than coerced.\n  os: z\n    .string({ error: 'os must be text, so write it in quotes, such as os: \"17.10\".' })\n    .trim()\n    .min(1)\n    .optional(),\n  id: z.string().trim().min(1).optional(),\n  remote: NameSlugSchema.optional(),\n  capabilities: z.record(z.string(), z.unknown()).optional(),\n})\n\nexport const RegistrySchema = z.strictObject({\n  llms: z.array(NamedLLMConfigSchema).optional().default([]),\n  remotes: z.array(RemoteEntrySchema).optional().default([]),\n  targets: z.record(TargetNameSchema, TargetSchema).optional(),\n  devices: z.record(z.string(), DeviceProfileSchema).optional(),\n})\n","import { z } from 'zod'\nimport {\n  BrowserConfigSchema,\n  DurationString,\n  TimeoutConfigSchema,\n  PlannerConfigSchema,\n  LogCaptureConfigSchema,\n  NameSlugSchema,\n} from './primitives.js'\nimport { AuthStateNameSchema } from '../auth-state/schema.js'\n\nexport const MobileAppStateSchema = z.enum(['preserve', 'reset'])\n\nexport const MobileUseSchema = z.strictObject({\n  appState: MobileAppStateSchema,\n})\n\nexport const MobileUseOverrideSchema = z.strictObject({\n  appState: MobileAppStateSchema.optional(),\n})\n\nexport const AuthStateUseSchema = z.union([\n  AuthStateNameSchema,\n  z.strictObject({\n    name: AuthStateNameSchema,\n    load: z.boolean().optional(),\n    capture: z.boolean().optional(),\n  }),\n])\n\nexport interface NormalizedAuthStateUse {\n  name: string\n  load: boolean\n  capture: boolean\n}\n\nexport function normalizeAuthStateUse(\n  use: { authState?: unknown } | undefined,\n): NormalizedAuthStateUse | undefined {\n  const parsed = AuthStateUseSchema.safeParse(use?.authState)\n  if (!parsed.success) return undefined\n\n  if (typeof parsed.data === 'string') {\n    return {\n      name: parsed.data,\n      load: true,\n      capture: false,\n    }\n  }\n\n  return {\n    name: parsed.data.name,\n    load: parsed.data.load ?? true,\n    capture: parsed.data.capture ?? false,\n  }\n}\n\nexport const UseSchema = z.strictObject({\n  browser: BrowserConfigSchema.optional(),\n  mobile: MobileUseSchema.optional(),\n  timeout: TimeoutConfigSchema.optional(),\n  planner: PlannerConfigSchema.optional(),\n  logCapture: LogCaptureConfigSchema.optional(),\n  cache: z.boolean().optional(),\n  llm: z.string().optional(),\n  // Precedence: CLI `--build-tag`, then `AGENT_QA_BUILD_TAG`, then this key.\n  buildTag: z.string().trim().min(1).optional(),\n  // Runs one run's members concurrently; absent or false runs one member at a time.\n  parallel: z.boolean().optional(),\n  // Not defaulted, so the parsed type is unchanged; `resolveEffectiveWorkers` owns the default.\n  workers: z.number().int().positive().optional(),\n})\n\nexport const UseOverrideSchema = z.strictObject({\n  browser: z.strictObject({\n    name: z.enum(['chromium', 'firefox', 'webkit']).optional(),\n    headless: z.boolean().optional(),\n    viewport: z.strictObject({\n      width: z.number().optional(),\n      height: z.number().optional(),\n    }).optional(),\n    remote: NameSlugSchema.optional(),\n  }).optional(),\n  timeout: z.strictObject({\n    step: DurationString.optional(),\n    test: DurationString.optional(),\n    navigation: DurationString.optional().describe(\n      'How long a web page load or URL wait can take. Default 2m. Android and iOS runs do not use it.',\n    ),\n  }).optional(),\n  planner: z.strictObject({\n    maxActions: z.number().int().positive().optional(),\n    maxPlanningTurns: z.number().int().positive().optional(),\n    previousStepCount: z.number().optional(),\n  }).optional(),\n  logCapture: z.strictObject({\n    console: z.boolean().optional(),\n    network: z.boolean().optional(),\n  }).optional(),\n  cache: z.boolean().optional(),\n  authState: AuthStateUseSchema.optional(),\n  mobile: MobileUseOverrideSchema.optional(),\n  llm: z.string().optional(),\n  parallel: z.boolean().optional(),\n  // The override half of `use.workers`, shaped like `UseSchema`'s.\n  workers: z.number().int().positive().optional(),\n  device: z.string().optional(),\n})\n","import { z } from 'zod'\n\nexport const AttributePredicateSchema = z.union([\n  z.string(),\n  z.strictObject({\n    regex: z.string().min(1),\n  }),\n])\n\nexport const AnalyticsSchema = z.strictObject({\n  privacy: z.literal(true).optional(),\n  passRateScope: z.strictObject({\n    attributes: z.record(z.string(), AttributePredicateSchema).optional(),\n  }).optional(),\n})\n\nexport type AnalyticsConfig = z.infer<typeof AnalyticsSchema>\n","import { existsSync, readFileSync, realpathSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { basename, dirname, isAbsolute, relative, resolve } from 'node:path'\nimport { fileURLToPath, pathToFileURL } from 'node:url'\n\nexport type PluginDeclarationLike = {\n  name: string\n  package?: string\n  path?: string\n}\n\n// Inside `baseDir` renders relative; elsewhere a fixed placeholder, never a `../` chain.\nfunction personFacingPath(candidate: string, baseDir: string): string {\n  let raw = candidate\n  if (raw.startsWith('file://')) {\n    try {\n      raw = fileURLToPath(raw)\n    } catch {\n      return '<path>'\n    }\n  }\n  const fromBase = relative(baseDir, raw)\n  if (fromBase === '' || fromBase.startsWith('..') || isAbsolute(fromBase)) return '<path>'\n  return fromBase\n}\n\n// A separator starts a path only after a boundary, so `and/or` and a relative path survive.\nconst ABSOLUTE_PATH_IN_TEXT = /(^|[\\s'\"`([<])((?:file:\\/\\/)?(?:[A-Za-z]:)?[\\\\/][^\\s'\"`)\\]>]*)/g\n\nfunction stripAbsolutePaths(text: string, baseDir: string): string {\n  return text.replace(\n    ABSOLUTE_PATH_IN_TEXT,\n    (_match, boundary: string, candidate: string) =>\n      `${boundary}${personFacingPath(candidate, baseDir)}`,\n  )\n}\n\n// npm's grammar, legacy capitals included: an optional scope, then a URL-safe name that starts\n// with no dot or underscore. A person runs what is suggested, and a name joins a node_modules path.\nexport const NPM_PACKAGE_NAME = /^(?:@[a-z0-9-~][a-z0-9-._~]*\\/)?[a-z0-9-~][a-z0-9-._~]*$/i\n\nexport function isNpmPackageName(name: string): boolean {\n  return name.length <= 214 && NPM_PACKAGE_NAME.test(name)\n}\n\nconst DEFAULT_CONFIG_FILE = 'agent-qa.config.yaml'\n\nfunction sameFolder(left: string, right: string): boolean {\n  if (resolve(left) === resolve(right)) return true\n  try {\n    return realpathSync(left) === realpathSync(right)\n  } catch {\n    return false\n  }\n}\n\nfunction shellWord(word: string): string {\n  if (/^[\\w@%+=:,./-]+$/u.test(word)) return word\n  return `'${word.replaceAll(\"'\", `'\\\\''`)}'`\n}\n\n// Run from the current folder, the line names --config unless the config is agent-qa.config.yaml\n// there, so it edits the config the refusing command read. The path is the shorter of the relative\n// and the absolute one.\nexport function pluginsAddLine(\n  packageName: string,\n  configPath?: string,\n  cwd: string = process.cwd(),\n): string {\n  const plain = `npx agent-qa plugins add ${packageName}`\n  if (configPath === undefined) return plain\n  const config = resolve(cwd, configPath)\n  if (basename(config) === DEFAULT_CONFIG_FILE && sameFolder(dirname(config), cwd)) return plain\n  const fromCwd = relative(cwd, config)\n  const shown = fromCwd.length <= config.length ? fromCwd : config\n  return `npx agent-qa --config ${shellWord(shown)} plugins add ${packageName}`\n}\n\nfunction joinsAsPackagePath(packageName: string): boolean {\n  if (packageName.includes('\\\\')) return false\n  return packageName.split('/').every((part) => part !== '' && part !== '.' && part !== '..')\n}\n\nexport function findPackageJson(packageName: string, baseDir: string): string | null {\n  if (!joinsAsPackagePath(packageName)) return null\n  let current = resolve(baseDir)\n  while (true) {\n    const candidate = resolve(current, 'node_modules', ...packageName.split('/'), 'package.json')\n    if (existsSync(candidate)) return candidate\n\n    const parent = dirname(current)\n    if (parent === current) return null\n    current = parent\n  }\n}\n\nexport function exportTargetFromPackageJson(pkg: Record<string, unknown>): string | null {\n  const exportsField = pkg.exports\n  if (typeof exportsField === 'string') return exportsField\n  if (exportsField && typeof exportsField === 'object') {\n    const rootExport = (exportsField as Record<string, unknown>)['.'] ?? exportsField\n    if (typeof rootExport === 'string') return rootExport\n    if (rootExport && typeof rootExport === 'object') {\n      const conditions = rootExport as Record<string, unknown>\n      if (typeof conditions.import === 'string') return conditions.import\n      if (typeof conditions.default === 'string') return conditions.default\n      if (typeof conditions.require === 'string') return conditions.require\n    }\n  }\n  if (typeof pkg.module === 'string') return pkg.module\n  if (typeof pkg.main === 'string') return pkg.main\n  return null\n}\n\n// Position, never content: Node's JSON `SyntaxError` quotes the file, so it is not the `cause`.\nexport class PluginPackageManifestError extends Error {\n  readonly packageJsonPath: string\n\n  constructor(packageJsonPath: string, baseDir: string) {\n    super(\n      `Plugin package manifest ${personFacingPath(packageJsonPath, baseDir)} could not be read `\n      + `as JSON.`,\n    )\n    this.name = 'PluginPackageManifestError'\n    this.packageJsonPath = packageJsonPath\n  }\n}\n\nexport function resolvePackageImportFromBase(packageName: string, baseDir: string): string | null {\n  const packageJsonPath = findPackageJson(packageName, baseDir)\n  if (!packageJsonPath) return null\n\n  let pkg: Record<string, unknown>\n  try {\n    pkg = JSON.parse(readFileSync(packageJsonPath, 'utf-8')) as Record<string, unknown>\n  } catch {\n    // Throw rather than return `null`, or a corrupt manifest falls through as not installed.\n    throw new PluginPackageManifestError(packageJsonPath, baseDir)\n  }\n  const target = exportTargetFromPackageJson(pkg)\n  if (!target || !target.startsWith('.')) return null\n  return pathToFileURL(resolve(dirname(packageJsonPath), target)).href\n}\n\nexport function packageDeclarationValue(declaration: PluginDeclarationLike): string {\n  return typeof declaration.package === 'string' ? declaration.package.trim() : ''\n}\n\nexport function pathDeclarationValue(declaration: PluginDeclarationLike): string {\n  return typeof declaration.path === 'string' ? declaration.path.trim() : ''\n}\n\n// A dedup key only; use `declarationLabel` for anything that reaches a message.\nexport function declarationKey(declaration: PluginDeclarationLike, baseDir: string): string {\n  const packageName = packageDeclarationValue(declaration)\n  if (packageName) return `package:${packageName}`\n  return `path:${resolve(baseDir, pathDeclarationValue(declaration))}`\n}\n\n// What a person reads: the declaration as written, never the absolute key.\nexport function declarationLabel(declaration: PluginDeclarationLike, baseDir: string): string {\n  const packageName = packageDeclarationValue(declaration)\n  if (packageName) return packageName\n\n  const declared = pathDeclarationValue(declaration)\n  if (!isAbsolute(declared)) return declared\n  const fromBase = relative(baseDir, declared)\n  return fromBase === '' || fromBase.startsWith('..') ? declared : fromBase\n}\n\nexport type PluginDeclarationKind = 'auth' | 'provider'\n\nexport class PluginNotInstalledError extends Error {\n  readonly pluginKind: PluginDeclarationKind\n  readonly pluginPackage: string | null\n  readonly pluginPath: string | null\n\n  constructor(\n    declaration: PluginDeclarationLike,\n    kind: PluginDeclarationKind,\n    configPath?: string,\n  ) {\n    const label = kind === 'auth' ? 'Auth' : 'Provider'\n    const packageName = packageDeclarationValue(declaration)\n    const pluginPath = pathDeclarationValue(declaration)\n    const removal = `remove the plugins entry ${declaration.name}.`\n    const remedy = isNpmPackageName(packageName)\n      ? `Install it with ${pluginsAddLine(packageName, configPath)}, or ${removal}`\n      : `Install it with your package manager, or ${removal}`\n    // No `cause`: the wrapped error's require stack holds absolute paths `util.inspect` prints.\n    super(\n      packageName\n        ? `${label} plugin package \"${packageName}\" is declared in agent-qa.config.yaml but is not `\n          + `installed. ${remedy}`\n        : `${label} plugin file \"${pluginPath}\" is declared in agent-qa.config.yaml but could not be `\n          + `loaded. Check that the path is correct and the file exists, or ${removal}`,\n    )\n    this.name = 'PluginNotInstalledError'\n    this.pluginKind = kind\n    this.pluginPackage = packageName === '' ? null : packageName\n    this.pluginPath = pluginPath === '' ? null : pluginPath\n  }\n}\n\nfunction isModuleResolutionFailure(err: unknown): boolean {\n  const code = (err as { code?: unknown } | null)?.code\n  return code === 'MODULE_NOT_FOUND' || code === 'ERR_MODULE_NOT_FOUND'\n}\n\n// Installed but unloadable; resolution codes also fire for a missing transitive dependency.\nexport class PluginLoadFailedError extends Error {\n  readonly pluginKind: PluginDeclarationKind\n  readonly pluginPackage: string\n\n  constructor(packageName: string, kind: PluginDeclarationKind, underlying: string) {\n    const label = kind === 'auth' ? 'Auth' : 'Provider'\n    super(\n      `${label} plugin package \"${packageName}\" is installed but failed to load: ${underlying}. `\n      + `This is a fault in the plugin or in its own dependencies, not a missing install.`,\n    )\n    this.name = 'PluginLoadFailedError'\n    this.pluginKind = kind\n    this.pluginPackage = packageName\n  }\n}\n\n// First line only, then absolute paths stripped: ESM writes its paths into the first line.\nfunction messageOf(err: unknown, baseDir: string): string {\n  const text = err instanceof Error ? err.message : String(err)\n  return stripAbsolutePaths(text.split('\\n', 1)[0] ?? '', baseDir)\n}\n\n/**\n * Translate a module-resolution failure into the error that names what is actually wrong.\n *\n * A PATH declaration keeps `PluginNotInstalledError` — its sentence is already about a file that\n * could not be loaded and says to check the path, which is the right thing to say either way.\n */\nfunction resolutionFailureFor(\n  declaration: PluginDeclarationLike,\n  baseDir: string,\n  kind: PluginDeclarationKind,\n  err: unknown,\n  configPath?: string,\n): Error {\n  const packageName = packageDeclarationValue(declaration)\n  if (packageName && findPackageJson(packageName, baseDir) !== null) {\n    return new PluginLoadFailedError(packageName, kind, messageOf(err, baseDir))\n  }\n  return new PluginNotInstalledError(declaration, kind, configPath)\n}\n\n/**\n * Resolve and import one declared plugin, answering the person when the module is not there.\n *\n * ONLY module-resolution failures are translated, and only for a package the filesystem says is\n * ABSENT. A plugin that IS installed rethrows as `PluginLoadFailedError` (resolution fault inside\n * its own graph) or untouched (its own runtime throw) — disguising either as \"not installed\" would\n * send the person to install something they already have.\n */\nexport async function importDeclaredPluginModule<T>(\n  declaration: PluginDeclarationLike,\n  baseDir: string,\n  kind: PluginDeclarationKind,\n  configPath?: string,\n): Promise<T> {\n  const failure = (err: unknown) =>\n    resolutionFailureFor(declaration, baseDir, kind, err, configPath)\n  let specifier: string\n  try {\n    specifier = resolveModuleSpecifier(declaration, baseDir)\n  } catch (err) {\n    if (isModuleResolutionFailure(err)) throw failure(err)\n    throw err\n  }\n\n  try {\n    return await import(specifier) as T\n  } catch (err) {\n    if (isModuleResolutionFailure(err)) throw failure(err)\n    throw err\n  }\n}\n\nexport function resolveModuleSpecifier(declaration: PluginDeclarationLike, baseDir: string): string {\n  const packageName = packageDeclarationValue(declaration)\n  if (packageName) {\n    const packageImport = resolvePackageImportFromBase(packageName, baseDir)\n    if (packageImport) return packageImport\n\n    const parentUrl = pathToFileURL(resolve(baseDir, 'agent-qa.config.yaml')).href\n    try {\n      const resolveImport = import.meta.resolve as (specifier: string, parent?: string) => string\n      return resolveImport(packageName, parentUrl)\n    } catch {\n      const require = createRequire(resolve(baseDir, 'agent-qa.config.yaml'))\n      return pathToFileURL(require.resolve(packageName)).href\n    }\n  }\n\n  const pluginPath = pathDeclarationValue(declaration)\n  const absolutePath = isAbsolute(pluginPath)\n    ? pluginPath\n    : resolve(baseDir, pluginPath)\n  return pathToFileURL(absolutePath).href\n}\n","import { z } from 'zod'\nimport {\n  appRefIssues,\n  capabilityCredentialIssues,\n  configConnectionSecretNames,\n  isLoopbackHost,\n  pluginValueCredentialIssues,\n  remoteOrigin,\n  secretReferenceNames,\n} from '@vostride/agent-qa-schema'\nimport { selectWebPlace } from '../remote/select-place.js'\nimport { selectDevicePlace } from '../mobile/select-device.js'\nimport { staticCapabilityContradictions } from '../mobile/device-plan.js'\nimport { WorkspaceSchema } from './workspace-schema.js'\nimport { ServicesSchema } from './services-schema.js'\nimport { KnowledgeConfigSchema } from './knowledge-schema.js'\nimport { retiredKeyScan } from './retired-keys.js'\nimport { configShapeScan } from './config-shape-scan.js'\nimport { NameSlugSchema } from './primitives.js'\nimport { isPluginRemoteEntry, isUrlRemoteEntry } from './remote-schema.js'\nimport { RegistrySchema } from './registry-schema.js'\nimport { UseSchema } from './use-schema.js'\nimport { AnalyticsSchema } from './analytics-schema.js'\nimport { isNpmPackageName } from '../plugin-loader-util.js'\n\nconst PluginOptionsSchema = z.record(z.string(), z.unknown()).optional()\n\nexport const PluginEntrySchema = z.union([\n  z.strictObject({\n    name: NameSlugSchema,\n    package: z.string().trim().min(1).refine(isNpmPackageName, {\n      error:\n        'package must be an npm package name, such as @vostride/agent-qa-plugin-kernel; '\n        + 'name a folder with path instead',\n    }),\n    options: PluginOptionsSchema,\n  }),\n  z.strictObject({\n    name: NameSlugSchema,\n    path: z.string().trim().min(1),\n    options: PluginOptionsSchema,\n  }),\n])\n\nexport type PluginEntry = z.infer<typeof PluginEntrySchema>\n\nexport const PluginsSchema = z.array(PluginEntrySchema)\n\nconst AgentQaConfigSchemaInner = z.strictObject({\n  workspace: WorkspaceSchema,\n  services: ServicesSchema.prefault({}).optional(),\n  // `.prefault` runs the inner defaults; zod 4's `.default()` short-circuits without parsing.\n  knowledge: KnowledgeConfigSchema.prefault({}),\n  registry: RegistrySchema.optional(),\n  use: UseSchema.optional(),\n  plugins: PluginsSchema.optional(),\n  analytics: AnalyticsSchema.optional(),\n  // There is no `safety` section: a file that still declares one gets the normal strict\n  // unrecognized-key error.\n})\n.superRefine((val, ctx) => {\n  const llms = val.registry?.llms ?? []\n  const names = llms.map(c => c.name)\n  const dupes = names.filter((n, i) => names.indexOf(n) !== i)\n  for (const dupe of new Set(dupes)) {\n    ctx.addIssue({\n      code: 'custom',\n      path: ['registry', 'llms'],\n      message: `Duplicate LLM config name: \"${dupe}\"`,\n    })\n  }\n  const plugins = val.plugins ?? []\n  const pluginNames = plugins.map(entry => entry.name)\n  const pluginDupes = pluginNames.filter((n, i) => pluginNames.indexOf(n) !== i)\n  for (const dupe of new Set(pluginDupes)) {\n    ctx.addIssue({\n      code: 'custom',\n      path: ['plugins'],\n      message: `Duplicate plugin entry name: \"${dupe}\"`,\n    })\n  }\n  plugins.forEach((entry, index) => {\n    if (entry.options === undefined) return\n    const path = ['plugins', index, 'options']\n    const label = `Plugin entry ${entry.name}: options`\n    for (const issue of pluginValueCredentialIssues(entry.options, path, label)) {\n      ctx.addIssue({ code: 'custom', path: [...issue.path], message: issue.message })\n    }\n  })\n  if ((val.use as any)?.platform) {\n    ctx.addIssue({\n      code: 'custom',\n      path: ['use', 'platform'],\n      message: 'use.platform cannot be set at global config level. Set platform in test or suite YAML instead.',\n    })\n  }\n  if (val.use?.llm && !names.includes(val.use.llm)) {\n    ctx.addIssue({\n      code: 'custom',\n      path: ['use', 'llm'],\n      message: `use.llm \"${val.use.llm}\" does not match any name in registry.llms`,\n    })\n  }\n\n  const remotes = val.registry?.remotes ?? []\n  const remoteNames = remotes.map(remote => remote.name)\n  const remoteDupes = remoteNames.filter((n, i) => remoteNames.indexOf(n) !== i)\n  for (const dupe of new Set(remoteDupes)) {\n    ctx.addIssue({\n      code: 'custom',\n      path: ['registry', 'remotes'],\n      message: `Duplicate remote name: \"${dupe}\"`,\n    })\n  }\n  remotes.forEach((remote, index) => {\n    if (remote.name === 'local') {\n      ctx.addIssue({\n        code: 'custom',\n        path: ['registry', 'remotes', index, 'name'],\n        message: 'Remote name \"local\" is reserved: local means this machine. Rename the remote.',\n      })\n    }\n    if (isPluginRemoteEntry(remote) && !pluginNames.includes(remote.plugin)) {\n      ctx.addIssue({\n        code: 'custom',\n        path: ['registry', 'remotes', index, 'plugin'],\n        message:\n          pluginNames.length === 0\n            ? `Remote ${remote.name} names plugin ${remote.plugin}, but plugins lists no entries.`\n            : `Remote ${remote.name} names plugin ${remote.plugin}; plugins lists: ${pluginNames.join(', ')}.`,\n      })\n    }\n  })\n  const pick = val.use?.browser?.remote\n  if (pick !== undefined) {\n    const selected = selectWebPlace({ remotes, config: pick, file: 'agent-qa.config.yaml' })\n    if ('refusal' in selected) {\n      ctx.addIssue({\n        code: 'custom',\n        path: ['use', 'browser', 'remote'],\n        message: selected.refusal,\n      })\n    }\n  }\n  const devices = val.registry?.devices ?? {}\n  for (const [device, profile] of Object.entries(devices)) {\n    if (profile.remote === undefined) continue\n    const selected = selectDevicePlace({ devices, remotes, device })\n    if ('refusal' in selected) {\n      ctx.addIssue({\n        code: 'custom',\n        path: ['registry', 'devices', device, 'remote'],\n        message: selected.refusal,\n      })\n    }\n  }\n  const reported = new Set<string>()\n  const report = (path: (string | number)[], message: string) => {\n    const key = JSON.stringify([path, message])\n    if (reported.has(key)) return\n    reported.add(key)\n    ctx.addIssue({ code: 'custom', path, message })\n  }\n  for (const [device, profile] of Object.entries(devices)) {\n    const at = remotes.findIndex(remote => remote.name === profile.remote)\n    const listed = at >= 0 ? remotes[at]! : undefined\n    const remote =\n      listed !== undefined && (isPluginRemoteEntry(listed) || listed.protocol === 'appium')\n        ? listed\n        : undefined\n    const stated = {\n      device,\n      platform: profile.platform,\n      model: profile.model,\n      os: profile.os,\n      id: profile.id,\n    }\n    if (remote?.capabilities !== undefined) {\n      const layer = { name: remote.name, capabilities: remote.capabilities }\n      for (const sentence of staticCapabilityContradictions({ ...stated, remote: layer })) {\n        report(['registry', 'remotes', at, 'capabilities'], sentence)\n      }\n    }\n    if (profile.capabilities === undefined) continue\n    const path = ['registry', 'devices', device, 'capabilities']\n    for (const sentence of staticCapabilityContradictions({\n      ...stated,\n      capabilities: profile.capabilities,\n    })) {\n      report(path, sentence)\n    }\n    for (const issue of capabilityCredentialIssues(profile.capabilities, path)) {\n      report([...issue.path], `Device ${device}: ${issue.message}`)\n    }\n    const host =\n      remote !== undefined && isUrlRemoteEntry(remote) ? cleartextHost(remote.url) : undefined\n    if (host !== undefined && carriesSecret(profile.capabilities)) {\n      report(\n        path,\n        `Device ${device} sends a credential in its capabilities over http:// to ${host}; use https://.`,\n      )\n    }\n  }\n  const deviceNames = Object.keys(devices)\n  const listedDevices =\n    deviceNames.length === 0\n      ? 'registry.devices lists no devices.'\n      : `registry.devices lists: ${deviceNames.join(', ')}.`\n  for (const [target, entry] of Object.entries(val.registry?.targets ?? {})) {\n    const pick = entry.device\n    const profile = pick !== undefined && Object.hasOwn(devices, pick) ? devices[pick] : undefined\n    if (pick !== undefined) {\n      const path = ['registry', 'targets', target, 'device']\n      if (entry.platform === 'web') {\n        report(path, `Target ${target} is a web target; device applies to android and ios targets.`)\n      } else if (profile === undefined) {\n        report(\n          path,\n          `Target ${target} names device \"${pick}\", which registry.devices does not list. ${listedDevices}`,\n        )\n      } else if (profile.platform !== entry.platform) {\n        report(\n          path,\n          `Target ${target} is ${entry.platform}, but its device ${pick} is ${profile.platform}.`,\n        )\n      }\n    }\n    const ref = entry.app?.ref\n    if (ref === undefined) continue\n    const refPath = ['registry', 'targets', target, 'app', 'ref']\n    for (const issue of appRefIssues(ref, refPath)) {\n      report([...issue.path], `Target ${target}: ${issue.message}`)\n    }\n    const remote = remotes.find(listed => listed.name === profile?.remote)\n    const host =\n      remote !== undefined && isUrlRemoteEntry(remote) && remote.protocol === 'appium'\n        ? cleartextHost(remote.url)\n        : undefined\n    if (host !== undefined && carriesSecret(ref)) {\n      report(\n        refPath,\n        `Target ${target} sends a credential in its app.ref over http:// to ${host} through device ${pick}; use https://.`,\n      )\n    }\n  }\n  const connectionSecrets = new Set(configConnectionSecretNames(val))\n  for (const [target, { url }] of Object.entries(val.registry?.targets ?? {})) {\n    if (url === undefined) continue\n    for (const name of new Set(secretReferenceNames(url))) {\n      if (!connectionSecrets.has(name)) continue\n      ctx.addIssue({\n        code: 'custom',\n        path: ['registry', 'targets', target, 'url'],\n        message: `registry.targets.${target}.url uses ${name}, a remote's or device's credential that only connects to it. Use another secret here.`,\n      })\n    }\n  }\n})\n\nfunction carriesSecret(value: unknown): boolean {\n  return secretReferenceNames(JSON.stringify(value)).length > 0\n}\n\n// The host a plain http:// url names when it is not this machine.\nfunction cleartextHost(url: string): string | undefined {\n  const origin = remoteOrigin(url)\n  if (origin === undefined || origin.scheme !== 'http' || isLoopbackHost(origin.host)) {\n    return undefined\n  }\n  return origin.host.includes(':') ? `[${origin.host}]` : origin.host\n}\n\n// The scan runs before the strict object: zod skips refinements after a strict parse rejects.\nexport const AgentQaConfigSchema =\n  retiredKeyScan.pipe(configShapeScan).pipe(AgentQaConfigSchemaInner)\n\nexport { WorkspaceSchema } from './workspace-schema.js'\nexport { AuthStateConfigSchema, ServicesSchema } from './services-schema.js'\nexport { KnowledgeConfigSchema } from './knowledge-schema.js'\nexport { RegistrySchema } from './registry-schema.js'\nexport {\n  AuthStateUseSchema,\n  MobileAppStateSchema,\n  MobileUseSchema,\n  MobileUseOverrideSchema,\n  UseSchema,\n  UseOverrideSchema,\n  normalizeAuthStateUse,\n  type NormalizedAuthStateUse,\n} from './use-schema.js'\nexport { AnalyticsSchema } from './analytics-schema.js'\nexport * from './primitives.js'\n","import { existsSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\nimport { LOCAL_FILE_NAME, RETIRED_LOCAL_FILE_MESSAGE } from './retired-keys.js'\n\n// Checks only that the file exists: its content may hold old serials or credentials.\nexport function leftoverLocalFileRefusal(dirs: readonly string[]): string | undefined {\n  for (const dir of new Set(dirs.map((dir) => resolve(dir)))) {\n    const path = join(dir, LOCAL_FILE_NAME)\n    if (existsSync(path)) return `${path}: ${RETIRED_LOCAL_FILE_MESSAGE}`\n  }\n  return undefined\n}\n","import { z } from 'zod'\nimport ms from 'ms'\nimport { isCanonicalHookId, isCanonicalTestId } from '@vostride/agent-qa-ids'\nimport { retiredStepKeyScan, retiredUseKeyScan } from './retired-keys.js'\nimport { UseOverrideSchema } from './use-schema.js'\n\nconst OptionalDuration = z.string()\n  .refine((v) => ms(v as ms.StringValue) !== undefined, {\n    error: 'Invalid duration format (e.g., \"30s\", \"5m\", \"1h\")',\n  })\n  .transform((v) => ms(v as ms.StringValue) as number)\n  .optional()\n\nexport const CaptureConfigSchema = z.strictObject({\n  variable: z.string(),\n  method: z.enum(['regex', 'selector', 'ai']),\n  pattern: z.string().optional(),\n  selector: z.string().optional(),\n  description: z.string().optional(),\n})\n\nexport const TestStepSchema = z.union([\n  z.string(),\n  z.strictObject({\n    step: z.string(),\n    timeout: OptionalDuration,\n    capture: CaptureConfigSchema.optional(),\n  }),\n])\n\nexport const TestMetaSchema = z.strictObject({\n  timeout: OptionalDuration,\n  retries: z.number().optional(),\n  record: z.boolean().optional(),\n})\n\nconst HookIdSchema = z.string().refine((value) => isCanonicalHookId(value), {\n  error: 'Hook ID must be h_ followed by 10 id-agent words',\n})\n\nexport const TestDefinitionSchema = z.strictObject({\n  'test-id': z.string().refine((value) => isCanonicalTestId(value), {\n    error: 'Test ID must be t_ followed by 10 id-agent words',\n  }),\n  name: z.string(),\n  target: z.string(),\n  context: z.string().optional(),\n  use: retiredUseKeyScan.pipe(UseOverrideSchema).optional(),\n  meta: TestMetaSchema.optional(),\n  setup: z.array(HookIdSchema).optional(),\n  teardown: z.array(HookIdSchema).optional(),\n  steps: z.array(retiredStepKeyScan.pipe(TestStepSchema)).min(1),\n})\n","import path from 'node:path'\n\n// `configDir` is the directory holding `agent-qa.config.yaml`.\nexport function resolveKnowledgeRoot(knowledge: { dir: string }, configDir: string): string {\n  return path.resolve(configDir, knowledge.dir)\n}\n","import { z } from 'zod'\nimport { isCanonicalHookId, isCanonicalSuiteId, isCanonicalTestId } from '@vostride/agent-qa-ids'\nimport { retiredUseKeyScan } from './retired-keys.js'\nimport { UseOverrideSchema } from './use-schema.js'\n\nexport const SuiteTestEntrySchema = z.strictObject({\n  test: z.string(),\n  id: z.string().refine((value) => isCanonicalTestId(value), {\n    error: 'Test ID must be t_ followed by 10 id-agent words',\n  }),\n})\n\nconst HookIdSchema = z.string().refine((value) => isCanonicalHookId(value), {\n  error: 'Hook ID must be h_ followed by 10 id-agent words',\n})\n\nexport const SuiteDefinitionSchema = z.strictObject({\n  'suite-id': z.string().refine((value) => isCanonicalSuiteId(value), {\n    error: 'Suite ID must be s_ followed by 10 id-agent words',\n  }).optional(),\n  name: z.string(),\n  target: z.string(),\n  context: z.string().optional(),\n  setup: z.array(HookIdSchema).optional(),\n  teardown: z.array(HookIdSchema).optional(),\n  tests: z.array(SuiteTestEntrySchema).min(1),\n  use: retiredUseKeyScan.pipe(UseOverrideSchema).optional(),\n})\n","import { z } from 'zod'\nimport ms from 'ms'\nimport { isCanonicalHookId } from '@vostride/agent-qa-ids'\n\nconst HookDurationString = z.string()\n  .refine((v) => ms(v as ms.StringValue) !== undefined, {\n    error: 'Invalid duration format (e.g., \"30s\", \"2m\", \"1h\")',\n  })\n  .transform((v) => ms(v as ms.StringValue) as number)\n\nconst HOOK_ID_MESSAGE = 'Hook ID must be h_ followed by 10 id-agent words'\n\nexport const HookDefinitionSchema = z.object({\n  id: z.string().refine((value) => isCanonicalHookId(value), {\n    error: HOOK_ID_MESSAGE,\n  }),\n  name: z.string().min(1),\n  runtime: z.enum(['node', 'bun', 'python', 'bash']),\n  file: z.string().min(1),\n  deps: z.array(z.string()).optional().default([]),\n  packageFile: z.string().optional(),\n  timeout: HookDurationString,\n  network: z.boolean().optional().default(true),\n})\n\nexport const HooksFileSchema = z.object({\n  hooks: z.array(HookDefinitionSchema),\n}).superRefine((val, ctx) => {\n  const ids = new Set<string>()\n  const names = new Set<string>()\n  for (let i = 0; i < val.hooks.length; i++) {\n    if (ids.has(val.hooks[i].id)) {\n      ctx.addIssue({\n        code: 'custom',\n        path: ['hooks', i, 'id'],\n        message: `Duplicate hook id: \"${val.hooks[i].id}\"`,\n      })\n    }\n    if (names.has(val.hooks[i].name)) {\n      ctx.addIssue({\n        code: 'custom',\n        path: ['hooks', i, 'name'],\n        message: `Duplicate hook name: \"${val.hooks[i].name}\"`,\n      })\n    }\n    ids.add(val.hooks[i].id)\n    names.add(val.hooks[i].name)\n  }\n})\n\nexport type HooksFileConfig = z.infer<typeof HooksFileSchema>\n","// Reads only the two `linePos` numbers; the error's message quotes the person's file.\nexport function yamlParseFailureMessage(error: unknown): string {\n  if (typeof error !== 'object' || error === null) {\n    return 'not readable as YAML (position unavailable)'\n  }\n  const linePos = (error as { linePos?: readonly { line?: unknown; col?: unknown }[] }).linePos\n  const first = Array.isArray(linePos) ? linePos[0] : undefined\n  if (typeof first?.line === 'number' && typeof first.col === 'number') {\n    return `not readable as YAML at line ${first.line}, column ${first.col}`\n  }\n  return 'not readable as YAML (position unavailable)'\n}\n","import pc from 'picocolors'\n\nimport type { LogColors } from '../logging/log-line.js'\nimport { yamlParseFailureMessage } from '../validation/yaml-fault.js'\n\nexport interface ParseError {\n  file: string\n  line: number\n  column: number\n  message: string\n  severity: 'error' | 'warning'\n  source: string\n  suggestion?: string\n}\n\ninterface FormatOptions {\n  noColor?: boolean\n  colors?: Pick<LogColors, 'red' | 'bold' | 'blue' | 'yellow'>\n}\n\nfunction shouldUseColor(opts?: FormatOptions): boolean {\n  if (opts?.noColor) return false\n  if (process.env.NO_COLOR !== undefined && process.env.NO_COLOR !== '') return false\n  return true\n}\n\nexport function formatParseError(\n  error: ParseError,\n  opts?: FormatOptions,\n): string {\n  const handed = opts?.noColor ? undefined : opts?.colors\n  const color = handed === undefined && shouldUseColor(opts)\n  const lineNum = String(error.line)\n  const pad = ' '.repeat(lineNum.length)\n\n  const plain = (s: string) => s\n  const red = handed?.red ?? (color ? pc.red : plain)\n  const bold = handed?.bold ?? (color ? pc.bold : plain)\n  const blue = handed?.blue ?? (color ? pc.blue : plain)\n  const yellow = handed?.yellow ?? pc.yellow\n  const boldRed = (s: string) => bold(red(s))\n  const boldBlue = (s: string) => bold(blue(s))\n\n  const severity =\n    error.severity === 'error' ? boldRed('error') : bold(yellow('warning'))\n\n  let output = ''\n  output += `${severity}: ${error.message}\\n`\n  output += `  ${boldBlue('-->')} ${error.file}:${error.line}:${error.column}\\n`\n  // `formatYamlError` returns an empty `source`, so the excerpt block is skipped.\n  if (error.source) {\n    output += `  ${boldBlue(`${pad} |`)}\\n`\n    output += `  ${boldBlue(`${lineNum} |`)} ${error.source}\\n`\n    output += `  ${boldBlue(`${pad} |`)} ${' '.repeat(Math.max(0, error.column - 1))}${boldRed('^')}\\n`\n  }\n\n  if (error.suggestion) {\n    output += `  ${boldBlue(`${pad} =`)} ${bold('help')}: ${error.suggestion}\\n`\n  }\n\n  return output\n}\n\nfunction getSourceLine(content: string, line: number): string {\n  const lines = content.split('\\n')\n  if (line < 1 || line > lines.length) return ''\n  return lines[line - 1] ?? ''\n}\n\n// Reports the fault's line and column only: yaml's pretty message quotes unvalidated source bytes.\nexport function formatYamlError(\n  err: { message: string; pos?: [number, number] },\n  linePos: { line: number; col: number } | undefined,\n  content: string,\n  filePath: string,\n): ParseError {\n  const line = linePos?.line ?? 1\n  const col = linePos?.col ?? 1\n\n  return {\n    file: filePath,\n    line,\n    column: col,\n    message: yamlParseFailureMessage(err),\n    severity: 'error',\n    source: '',\n    suggestion: undefined,\n  }\n}\n\nfunction zodPathToSuggestion(\n  code: string,\n  path: (string | number)[],\n  message: string,\n): string | undefined {\n  const field = path[path.length - 1]\n  if (code === 'invalid_type') {\n    if (typeof field === 'string') {\n      return `check that '${field}' has the correct type`\n    }\n    return `check the value type at this position`\n  }\n  if (code === 'too_small') {\n    if (typeof field === 'string' && field === 'steps') {\n      return 'tests must have at least one step'\n    }\n    return message\n  }\n  if (code === 'invalid_union') {\n    return 'steps must be strings like \"Click the login button\" or objects like { step: \"...\", timeout: \"30s\" }'\n  }\n  if (code === 'unrecognized_keys') {\n    return message\n  }\n  if (typeof field === 'string') {\n    return `did you forget to add '${field}'?`\n  }\n  return undefined\n}\n\ninterface YamlNode {\n  range?: [number, number, number]\n  items?: YamlNode[]\n  key?: YamlNode\n  value?: YamlNode | null\n  srcToken?: unknown\n}\n\ninterface YamlDoc {\n  contents: YamlNode | null\n}\n\ninterface LineCounterLike {\n  linePos(offset: number): { line: number; col: number }\n}\n\ninterface ZodIssue {\n  path: PropertyKey[]\n  message: string\n  code: string\n}\n\nfunction resolveNodeAtPath(\n  doc: YamlDoc,\n  path: (string | number)[],\n): YamlNode | null {\n  let current: YamlNode | null = doc.contents\n  if (!current) return null\n\n  for (const segment of path) {\n    if (!current) return null\n\n    if (typeof segment === 'number') {\n      // Array index — current should be a sequence node with items\n      const items: YamlNode[] | undefined = current.items\n      if (items && items[segment]) {\n        current = items[segment]\n      } else {\n        return current\n      }\n    } else {\n      // Object key — current should be a mapping node with items\n      const items: YamlNode[] | undefined = current.items\n      if (!items) return current\n\n      let found = false\n      for (const pair of items as YamlNode[]) {\n        const keyNode: YamlNode | undefined = pair.key\n        if (keyNode && 'value' in keyNode && keyNode.value === segment) {\n          current = pair.value ?? null\n          found = true\n          break\n        }\n        // Sometimes keyNode is the scalar itself\n        if (keyNode && 'source' in keyNode && (keyNode as { source?: string }).source === segment) {\n          current = pair.value ?? null\n          found = true\n          break\n        }\n      }\n      if (!found) return current\n    }\n  }\n\n  return current\n}\n\nexport function formatZodErrors(\n  zodError: { issues: ZodIssue[] },\n  doc: YamlDoc,\n  lineCounter: LineCounterLike,\n  content: string,\n  filePath: string,\n): ParseError[] {\n  const errors: ParseError[] = []\n\n  for (const issue of zodError.issues) {\n    let line = 1\n    let col = 1\n\n    // Try to resolve the node at the Zod error path\n    const issuePath = issue.path.filter((segment): segment is string | number => (\n      typeof segment === 'string' || typeof segment === 'number'\n    ))\n    const node = resolveNodeAtPath(doc, issuePath)\n    if (node?.range) {\n      const pos = lineCounter.linePos(node.range[0])\n      line = pos.line\n      col = pos.col\n    } else if (doc.contents?.range) {\n      const pos = lineCounter.linePos(doc.contents.range[0])\n      line = pos.line\n      col = pos.col\n    }\n\n    const suggestion = zodPathToSuggestion(issue.code, issuePath, issue.message)\n\n    errors.push({\n      file: filePath,\n      line,\n      column: col,\n      message: issuePath.length > 0\n        ? `${issuePath.join('.')}: ${issue.message}`\n        : issue.message,\n      severity: 'error',\n      source: getSourceLine(content, line),\n      suggestion,\n    })\n  }\n\n  return errors\n}\n","import { readFile } from 'node:fs/promises'\nimport { parseAllDocuments, LineCounter } from 'yaml'\nimport { TestDefinitionSchema } from '../schema/test-schema.js'\nimport type { TestDefinition } from '../types/test.js'\nimport { formatYamlError, formatZodErrors } from './errors.js'\nimport type { ParseError } from './errors.js'\nimport { findBareVariables } from '@vostride/agent-qa-runner'\n\nexport interface ParseResult {\n  tests: TestDefinition[]\n  errors: ParseError[]\n}\n\n// Identity is `filePath + test.name`; a flattened parse stamps every member with one file.\nexport interface ParsedTestBinding {\n  test: TestDefinition\n  filePath: string\n  fileContent: string\n}\n\nexport interface ParseAllTestBindingsResult {\n  bindings: ParsedTestBinding[]\n  errors: ParseError[]\n}\n\nexport function parseTestFile(\n  content: string,\n  filePath: string,\n): ParseResult {\n  const lineCounter = new LineCounter()\n  const docs = parseAllDocuments(content, {\n    lineCounter,\n    prettyErrors: true,\n    strict: true,\n    keepSourceTokens: true,\n  })\n\n  const tests: TestDefinition[] = []\n  const errors: ParseError[] = []\n\n  for (const doc of docs) {\n    // Skip empty documents (trailing --- or empty sections)\n    if (doc.contents === null || doc.contents === undefined) continue\n\n    // YAML-level syntax errors\n    if (doc.errors.length > 0) {\n      for (const err of doc.errors) {\n        const pos = err.pos?.[0]\n        const linePos =\n          pos !== undefined ? lineCounter.linePos(pos) : undefined\n        errors.push(formatYamlError(err, linePos, content, filePath))\n      }\n      continue\n    }\n\n    // Convert AST to plain JS object\n    const value = doc.toJS()\n\n    // Schema-level validation via Zod\n    const parsed = TestDefinitionSchema.safeParse(value)\n    if (!parsed.success) {\n      errors.push(\n        ...formatZodErrors(parsed.error, doc as unknown as Parameters<typeof formatZodErrors>[1], lineCounter, content, filePath),\n      )\n    } else {\n      const bareErrors = checkBareVariables(parsed.data, filePath)\n      if (bareErrors.length > 0) {\n        errors.push(...bareErrors)\n      } else {\n        tests.push(parsed.data)\n      }\n    }\n  }\n\n  return { tests, errors }\n}\n\nfunction checkBareVariables(test: TestDefinition, filePath: string): ParseError[] {\n  const errors: ParseError[] = []\n  const textsToCheck: string[] = []\n\n  if ((test as any).url) textsToCheck.push((test as any).url)\n  for (const step of test.steps) {\n    if (typeof step === 'string') {\n      textsToCheck.push(step)\n    } else {\n      textsToCheck.push(step.step)\n    }\n  }\n\n  for (const text of textsToCheck) {\n    for (const varName of findBareVariables(text)) {\n      errors.push({\n        file: filePath,\n        line: 1,\n        column: 1,\n        message: `Variable \"{{${varName}}}\" must use a namespace prefix: {{env:${varName}}}`,\n        severity: 'error',\n        source: text,\n      })\n    }\n  }\n\n  return errors\n}\n\nexport async function parseAllTestBindings(\n  filePaths: string[],\n): Promise<ParseAllTestBindingsResult> {\n  const bindings: ParsedTestBinding[] = []\n  const allErrors: ParseError[] = []\n\n  for (const filePath of filePaths) {\n    const content = await readFile(filePath, 'utf-8')\n    const result = parseTestFile(content, filePath)\n    bindings.push(\n      ...result.tests.map((test) => ({ test, filePath, fileContent: content })),\n    )\n    allErrors.push(...result.errors)\n  }\n\n  return { bindings, errors: allErrors }\n}\n\nexport async function parseAllTests(\n  filePaths: string[],\n): Promise<ParseResult> {\n  const { bindings, errors } = await parseAllTestBindings(filePaths)\n  return { tests: bindings.map(({ test }) => test), errors }\n}\n","import { readFile, access } from 'node:fs/promises'\nimport { dirname, resolve, extname } from 'node:path'\n\nexport interface FileAttachment {\n  name: string\n  path: string\n  content: Buffer\n  mimeType: string\n}\n\nconst MIME_TYPES: Record<string, string> = {\n  '.png': 'image/png',\n  '.jpg': 'image/jpeg',\n  '.jpeg': 'image/jpeg',\n  '.gif': 'image/gif',\n  '.webp': 'image/webp',\n  '.svg': 'image/svg+xml',\n  '.pdf': 'application/pdf',\n  '.doc': 'application/msword',\n  '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n  '.txt': 'text/plain',\n  '.csv': 'text/csv',\n  '.json': 'application/json',\n  '.xml': 'application/xml',\n  '.zip': 'application/zip',\n}\n\nfunction detectMimeType(filename: string): string {\n  const ext = extname(filename).toLowerCase()\n  return MIME_TYPES[ext] ?? 'application/octet-stream'\n}\n\nconst FILE_REF_PATTERN = /\\$\\{file:([^}]+)\\}/g\n\nexport async function resolveFileReferences(\n  stepText: string,\n  testFilePath: string,\n): Promise<{ resolvedText: string; attachments: FileAttachment[] }> {\n  const matches = [...stepText.matchAll(FILE_REF_PATTERN)]\n\n  if (matches.length === 0) {\n    return { resolvedText: stepText, attachments: [] }\n  }\n\n  const testDir = dirname(testFilePath)\n  const attachments: FileAttachment[] = []\n  let resolvedText = stepText\n\n  for (const match of matches) {\n    const filename = match[1]\n    const absolutePath = resolve(testDir, filename)\n\n    try {\n      await access(absolutePath)\n    } catch {\n      throw new Error(\n        `File attachment not found: \"${filename}\" (resolved to \"${absolutePath}\", referenced in test \"${testFilePath}\")`,\n      )\n    }\n\n    const content = await readFile(absolutePath) as Buffer\n\n    attachments.push({\n      name: filename,\n      path: absolutePath,\n      content,\n      mimeType: detectMimeType(filename),\n    })\n\n    resolvedText = resolvedText.replace(match[0], absolutePath)\n  }\n\n  return { resolvedText, attachments }\n}\n","import { readFile } from 'node:fs/promises'\nimport { parse as parseYaml } from 'yaml'\nimport { SuiteDefinitionSchema } from '../schema/suite-schema.js'\nimport { yamlParseFailureMessage } from '../validation/yaml-fault.js'\nimport type { SuiteDefinition } from '../suite/types.js'\n\nexport async function parseSuiteFile(filePath: string): Promise<SuiteDefinition> {\n  const content = await readFile(filePath, 'utf-8')\n\n  let raw: unknown\n  try {\n    raw = parseYaml(content)\n  } catch (err) {\n    // Still throws, with no `cause`: `util.inspect` would print the raw `YAMLParseError`.\n    throw new Error(`${filePath}: ${yamlParseFailureMessage(err)}`)\n  }\n\n  return SuiteDefinitionSchema.parse(raw)\n}\n","// RFC 6902 patches applied to the CST in place; `doc.toJS()` would reformat untouched lines.\n\nimport {\n  Composer,\n  CST,\n  Document,\n  Parser,\n  isMap,\n  isScalar,\n  isSeq,\n} from 'yaml'\nimport type { Node, Scalar, YAMLSeq } from 'yaml'\n\nimport {\n  EDITABLE_POINTER_ROOTS,\n  isEditablePointer,\n  parseJsonPointer,\n} from '@vostride/agent-qa-schema'\nimport type { PatchOp, TestEditPatchSet } from '@vostride/agent-qa-schema'\n\nimport { parseTestFile } from './yaml-parser.js'\n\n/**\n * A test document parsed so that BOTH halves survive: the composed model a pointer resolves\n * against, and the token array the render concatenates.\n *\n * The two are not redundant. Pointer resolution needs the model (`getIn`-shaped navigation over\n * maps and sequences); byte preservation needs the tokens. Handing a caller only one of them would\n * force it to re-parse to get the other, and a second parse is a second opinion about the source.\n */\nexport interface ParsedTestDocument {\n  readonly source: string\n  readonly filePath: string\n  readonly tokens: CST.Token[]\n  readonly doc: Document\n}\n\n// ---- Refusals -------------------------------------------------------------------------------\n//\n// Separate classes, never one error carrying a `kind`. A caller legitimately distinguishes \"you\n// addressed a region you may not edit\" (a boundary violation worth reporting) from \"your pointer\n// does not resolve\" (a stale or hallucinated path, worth retrying against a fresh read) from\n// \"your edit produced a document this project cannot run\" (worth repairing) from \"that op cannot\n// be applied to that kind of node\" (worth re-planning the edit). One class with a discriminator\n// would make every one of those `catch` blocks read a string.\n\n/** A pointer addressed a document root outside `EDITABLE_POINTER_ROOTS`. */\nexport class PatchPointerOutsideEditableRegionError extends Error {\n  constructor(readonly pointer: string) {\n    super(\n      `cst-patch: the pointer ${pointer} addresses a region no patch may edit; `\n        + `only ${EDITABLE_POINTER_ROOTS.join(', ')} are editable, because a patch that can reach `\n        + 'the identity fields can silently change which app the test drives',\n    )\n    this.name = 'PatchPointerOutsideEditableRegionError'\n  }\n}\n\n/** A pointer named a node the document does not have. */\nexport class PatchPointerUnresolvableError extends Error {\n  constructor(readonly pointer: string, readonly detail: string) {\n    super(\n      `cst-patch: the pointer ${pointer} does not resolve against this document (${detail}); `\n        + 'a patch is applied to the document it was written against, never to a guess',\n    )\n    this.name = 'PatchPointerUnresolvableError'\n  }\n}\n\n// `add` and `remove` act on block-sequence items only; a key change is a shape change.\nexport class PatchOpUnsupportedTargetError extends Error {\n  constructor(readonly pointer: string, readonly detail: string) {\n    super(`cst-patch: the pointer ${pointer} cannot carry this op: ${detail}`)\n    this.name = 'PatchOpUnsupportedTargetError'\n  }\n}\n\n/**\n * A document this project cannot run — checked on the SOURCE before anything is applied and on the\n * RENDERED bytes before anything may be written.\n *\n * Both directions matter. Validating only the render would let a pre-existing invalidity be\n * blamed on the patch; validating only the source would let a CST mutation that produced\n * structurally broken YAML reach a file. Same predicate, same evidence, two call sites.\n */\nexport class PatchedDocumentInvalidError extends Error {\n  constructor(readonly phase: 'source' | 'rendered', readonly detail: string) {\n    super(\n      `cst-patch: the ${phase} document is not a valid test: ${detail}; `\n        + 'a patched document is schema-validated before any caller may write it',\n    )\n    this.name = 'PatchedDocumentInvalidError'\n  }\n}\n\n// ---- Parse ----------------------------------------------------------------------------------\n\n/**\n * Parse a test file retaining the CST token array beside the composed document.\n *\n * The composer is given `keepSourceTokens` so every node carries a `srcToken` back-reference; that\n * back-reference is the entire bridge between a pointer (which addresses the model) and a mutation\n * (which must land on the syntax).\n */\nexport function parseTestFileWithTokens(source: string, filePath: string): ParsedTestDocument {\n  const tokens = [...new Parser().parse(source)]\n  const docs = [...new Composer({ keepSourceTokens: true }).compose(tokens)]\n\n  if (docs.length !== 1) {\n    throw new PatchedDocumentInvalidError(\n      'source',\n      `expected exactly one YAML document, found ${docs.length}`,\n    )\n  }\n  const doc = docs[0]!\n  if (doc.errors.length > 0) {\n    throw new PatchedDocumentInvalidError(\n      'source',\n      doc.errors.map((error) => error.message).join('; '),\n    )\n  }\n\n  assertRunnable('source', source, filePath)\n\n  return { source, filePath, tokens, doc }\n}\n\nfunction assertRunnable(phase: 'source' | 'rendered', content: string, filePath: string): void {\n  const { tests, errors } = parseTestFile(content, filePath)\n  if (errors.length > 0) {\n    throw new PatchedDocumentInvalidError(phase, errors.map((error) => error.message).join('; '))\n  }\n  if (tests.length !== 1) {\n    throw new PatchedDocumentInvalidError(\n      phase,\n      `expected exactly one test definition, found ${tests.length}`,\n    )\n  }\n}\n\n// ---- Apply ----------------------------------------------------------------------------------\n\n/**\n * Apply a patch set in document order, mutating `parsed.doc` and its tokens in place.\n *\n * TWO PROPERTIES THE ORDER BUYS. First, the fence runs over the WHOLE set before any mutation, so\n * a set mixing a legitimate op with an out-of-region one leaves nothing behind — a per-op check\n * would have already rewritten the legitimate target by the time it refused. Second, each pointer\n * resolves against the document as PRIOR ops left it, which is what RFC-6902 means by a sequence\n * of operations: an `add` earlier in an array shifts every later index, and resolving every\n * pointer against the original document would edit a plausible, schema-valid, wrong step.\n */\nexport function applyPatchSetToTestDoc(\n  parsed: ParsedTestDocument,\n  patchSet: TestEditPatchSet,\n): void {\n  for (const op of patchSet.patches) {\n    if (!isEditablePointer(op.path)) throw new PatchPointerOutsideEditableRegionError(op.path)\n  }\n  for (const op of patchSet.patches) {\n    applyOne(parsed.doc, op)\n  }\n}\n\nfunction applyOne(doc: Document, op: PatchOp): void {\n  const segments = parseJsonPointer(op.path)\n\n  switch (op.op) {\n    case 'replace': {\n      const node = resolveNode(doc, segments)\n      if (node === undefined) {\n        throw new PatchPointerUnresolvableError(op.path, 'no node at that path')\n      }\n      if (!isScalar(node) || node.srcToken === undefined) {\n        throw new PatchOpUnsupportedTargetError(\n          op.path,\n          'replace writes one scalar token, and that path is a collection',\n        )\n      }\n      CST.setScalarValue(node.srcToken, op.value)\n      return\n    }\n\n    case 'add': {\n      const { seqToken, index } = resolveSeqSlot(doc, op.path, segments, 'add')\n      if (index > seqToken.items.length) {\n        throw new PatchPointerUnresolvableError(\n          op.path,\n          `index ${index} is past the end of a ${seqToken.items.length}-item sequence`,\n        )\n      }\n      if (index > 0) terminateItem(seqToken.items[index - 1])\n      seqToken.items.splice(index, 0, newSeqItem(seqToken, op.value))\n      normalizeItemStarts(seqToken)\n      resyncSeqNode(doc, segments.slice(0, -1))\n      return\n    }\n\n    case 'remove': {\n      const { seqToken, index } = resolveSeqSlot(doc, op.path, segments, 'remove')\n      if (index >= seqToken.items.length) {\n        throw new PatchPointerUnresolvableError(\n          op.path,\n          `index ${index} is past the end of a ${seqToken.items.length}-item sequence`,\n        )\n      }\n      seqToken.items.splice(index, 1)\n      normalizeItemStarts(seqToken)\n      resyncSeqNode(doc, segments.slice(0, -1))\n      return\n    }\n  }\n}\n\ninterface SeqSlot {\n  seqToken: CST.BlockSequence\n  index: number\n}\n\n/** Resolve `<parent>/<index|->` to the parent's block-sequence token and a slot in it. */\nfunction resolveSeqSlot(\n  doc: Document,\n  pointer: string,\n  segments: string[],\n  op: 'add' | 'remove',\n): SeqSlot {\n  if (segments.length < 2) {\n    throw new PatchOpUnsupportedTargetError(\n      pointer,\n      `${op} operates on a sequence item, and that path names a top-level key; `\n        + 'adding or removing a key is a document rewrite, not a patch',\n    )\n  }\n\n  const parent = resolveNode(doc, segments.slice(0, -1))\n  if (parent === undefined) {\n    throw new PatchPointerUnresolvableError(pointer, 'the parent collection does not resolve')\n  }\n  if (!isSeq(parent)) {\n    throw new PatchOpUnsupportedTargetError(\n      pointer,\n      `${op} operates on a sequence item, and the parent at that path is not a sequence`,\n    )\n  }\n\n  const seqToken = (parent as YAMLSeq).srcToken\n  if (seqToken === undefined || seqToken.type !== 'block-seq') {\n    throw new PatchOpUnsupportedTargetError(\n      pointer,\n      `${op} rebuilds block-sequence indentation, and that sequence is written in flow style`,\n    )\n  }\n\n  const last = segments[segments.length - 1]!\n  if (op === 'add' && last === '-') return { seqToken, index: seqToken.items.length }\n\n  const index = asIndex(last)\n  if (index === undefined) {\n    throw new PatchPointerUnresolvableError(pointer, `${last} is not a sequence index`)\n  }\n  return { seqToken, index }\n}\n\nfunction asIndex(segment: string): number | undefined {\n  return /^(?:0|[1-9]\\d*)$/.test(segment) ? Number(segment) : undefined\n}\n\n/** Walk the composed model one reference token at a time. */\nfunction resolveNode(doc: Document, segments: string[]): Node | undefined {\n  let node: unknown = doc.contents\n  for (const segment of segments) {\n    if (isSeq(node)) {\n      const index = asIndex(segment)\n      if (index === undefined || index >= node.items.length) return undefined\n      node = node.items[index]\n    } else if (isMap(node)) {\n      const pair = node.items.find(\n        (candidate) => isScalar(candidate.key) && String((candidate.key as Scalar).value) === segment,\n      )\n      if (pair === undefined) return undefined\n      node = pair.value\n    } else {\n      return undefined\n    }\n  }\n  return (node ?? undefined) as Node | undefined\n}\n\n/**\n * Re-compose the sequence NODE after its token items changed.\n *\n * The composed model and the CST are two views of one document, and a structural edit moves them\n * out of step: splicing `srcToken.items` changes what the file says while `seq.items` still\n * describes what it said. Every later pointer in the same set resolves against the MODEL, so\n * leaving it stale is exactly how the second op of a two-op set lands on the wrong index.\n */\nfunction resyncSeqNode(doc: Document, parentSegments: string[]): void {\n  const parent = resolveNode(doc, parentSegments)\n  if (!isSeq(parent)) return\n\n  const seqToken = (parent as YAMLSeq).srcToken\n  if (seqToken === undefined || seqToken.type !== 'block-seq') return\n\n  const rebuilt = [\n    ...new Composer({ keepSourceTokens: true }).compose([\n      { type: 'document', offset: 0, start: [], value: seqToken },\n    ]),\n  ]\n  const contents = rebuilt[0]?.contents\n  if (!isSeq(contents)) return\n\n  const seq = parent as YAMLSeq\n  seq.items = contents.items\n}\n\n// `createScalarToken` adds its own newline; without it an appended item joins the previous line.\nfunction newSeqItem(seqToken: CST.BlockSequence, value: string): CST.BlockSequence['items'][number] {\n  return {\n    start: [\n      { type: 'seq-item-ind', offset: -1, indent: seqToken.indent, source: '-' },\n      { type: 'space', offset: -1, indent: seqToken.indent + 1, source: ' ' },\n    ],\n    value: CST.createScalarToken(value, { indent: seqToken.indent + 2 }),\n  }\n}\n\n/**\n * Give an item a trailing newline if it has none, so the next item starts on its own line.\n *\n * The absence of a terminator is expressed as an ABSENT `end` key, not an empty array: a file whose\n * last line has no newline yields a scalar token with no `end` property at all. Probing for the\n * key and returning early therefore skips exactly the case this function exists for — which is how\n * an append onto an unterminated last item produces two steps concatenated on one line. A\n * block-scalar carries its own terminator inside `source` and is left alone.\n */\nfunction terminateItem(item: CST.BlockSequence['items'][number] | undefined): void {\n  const value = item?.value\n  if (value === undefined || !CST.isScalar(value) || value.type === 'block-scalar') return\n  const end = (value.end ??= [])\n  if (end.some((token) => token.type === 'newline')) return\n  end.push({ type: 'newline', offset: -1, indent: 0, source: '\\n' })\n}\n\n/**\n * Restore the one positional invariant of a block sequence after items moved.\n *\n * Item 0 alone does NOT carry its own leading whitespace — the indentation before the first `-`\n * belongs to the parent mapping item's separator tokens, while items 1..n each carry a `space`\n * token of their own. So an insert at index 0, or a removal of index 0, silently produces a\n * document where one line's indentation is wrong. Only items whose position-0-ness actually\n * changed are touched; every other item's `start` array is left exactly as parsed, which is what\n * keeps `remove` from re-indenting lines nobody addressed.\n */\nfunction normalizeItemStarts(seqToken: CST.BlockSequence): void {\n  const pad = ' '.repeat(seqToken.indent)\n  seqToken.items.forEach((item, index) => {\n    const start = item.start\n    const leadsWithSpace = start[0]?.type === 'space'\n    if (index === 0 && leadsWithSpace) start.shift()\n    if (index > 0 && !leadsWithSpace) {\n      start.unshift({ type: 'space', offset: -1, indent: 0, source: pad })\n    }\n  })\n}\n\n// ---- Render ---------------------------------------------------------------------------------\n\n/**\n * Concatenate the whole token array back to bytes, then refuse anything unrunnable.\n *\n * THE RENDER IS OVER `parsed.tokens`, NEVER OVER THE DOCUMENT TOKEN ALONE. `CST.stringify`'s own\n * doc comment states it \"applies no validation whatsoever, and simply concatenates the sources in\n * their logical order\" — that concatenation IS the byte-preservation guarantee. A file's leading\n * comment is a separate token in the parser's output stream, positioned BEFORE the document token,\n * so `CST.stringify(documentToken)` drops it. That is the one genuinely non-obvious line here, it\n * was measured rather than reasoned about, and the frozen corpus's untouched-round-trip row is\n * the cell that catches a regression to it.\n */\nexport function renderPatchedTestDoc(parsed: ParsedTestDocument, filePath?: string): string {\n  const rendered = parsed.tokens.map((token) => CST.stringify(token)).join('')\n  assertRunnable('rendered', rendered, filePath ?? parsed.filePath)\n  return rendered\n}\n","const CHARS_PER_TOKEN = 4\n\nexport function estimateTokens(text: string): number {\n  return Math.ceil(text.length / CHARS_PER_TOKEN)\n}\n","export const ANDROID_ROLE_MAP: Record<string, string> = {\n  'android.widget.Button': 'button',\n  'android.widget.ImageButton': 'button',\n  'android.widget.EditText': 'textbox',\n  'android.widget.AutoCompleteTextView': 'textbox',\n  'android.widget.TextView': 'text',\n  'android.widget.CheckedTextView': 'text',\n  'android.widget.CheckBox': 'checkbox',\n  'android.widget.Switch': 'switch',\n  'android.widget.ImageView': 'image',\n  'android.widget.ListView': 'list',\n  'android.widget.ScrollView': 'scroll-area',\n  'android.widget.HorizontalScrollView': 'scroll-area',\n  'android.view.View': 'group',\n  'android.view.ViewGroup': 'group',\n  'android.widget.FrameLayout': 'group',\n  'android.widget.LinearLayout': 'group',\n  'android.widget.RelativeLayout': 'group',\n  'android.widget.SearchView': 'searchbox',\n  'android.widget.Spinner': 'combobox',\n  'android.widget.SeekBar': 'slider',\n  'android.widget.RadioButton': 'radio',\n  'android.widget.CompoundButton': 'button',\n  'android.widget.ToggleButton': 'button',\n  'android.widget.ProgressBar': 'progressbar',\n  'android.widget.Toolbar': 'toolbar',\n  'android.widget.TabWidget': 'tablist',\n  'android.webkit.WebView': 'webview',\n  'androidx.recyclerview.widget.RecyclerView': 'list',\n  'androidx.constraintlayout.widget.ConstraintLayout': 'group',\n  'androidx.appcompat.widget.Toolbar': 'toolbar',\n  'androidx.viewpager.widget.ViewPager': 'group',\n  'androidx.core.widget.NestedScrollView': 'scroll-area',\n  'android.widget.NumberPicker': 'spinbutton',\n  'android.widget.DatePicker': 'combobox',\n  'android.widget.TimePicker': 'combobox',\n  'android.widget.RatingBar': 'slider',\n  'android.widget.CalendarView': 'grid',\n  'android.widget.TabHost': 'tablist',\n  'com.google.android.material.chip.Chip': 'button',\n  'com.google.android.material.floatingactionbutton.FloatingActionButton': 'button',\n  'com.google.android.material.tabs.TabLayout': 'tablist',\n  'com.google.android.material.textfield.TextInputEditText': 'textbox',\n  'com.google.android.material.switchmaterial.SwitchMaterial': 'switch',\n  'com.google.android.material.checkbox.MaterialCheckBox': 'checkbox',\n}\n\nexport const IOS_ROLE_MAP: Record<string, string> = {\n  'XCUIElementTypeButton': 'button',\n  'XCUIElementTypeTextField': 'textbox',\n  'XCUIElementTypeSecureTextField': 'textbox',\n  'XCUIElementTypeStaticText': 'text',\n  'XCUIElementTypeTextView': 'text',\n  'XCUIElementTypeSwitch': 'switch',\n  'XCUIElementTypeSlider': 'slider',\n  'XCUIElementTypeImage': 'image',\n  'XCUIElementTypeCell': 'cell',\n  'XCUIElementTypeTable': 'list',\n  'XCUIElementTypeCollectionView': 'list',\n  'XCUIElementTypeScrollView': 'scroll-area',\n  'XCUIElementTypeOther': 'group',\n  'XCUIElementTypeGroup': 'group',\n  'XCUIElementTypeNavigationBar': 'navigation',\n  'XCUIElementTypeTabBar': 'tablist',\n  'XCUIElementTypeSearchField': 'searchbox',\n  'XCUIElementTypeCheckBox': 'checkbox',\n  'XCUIElementTypeLink': 'link',\n  'XCUIElementTypeAlert': 'alert',\n  'XCUIElementTypeWebView': 'webview',\n  'XCUIElementTypeApplication': 'application',\n  'XCUIElementTypeWindow': 'window',\n  'XCUIElementTypePicker': 'combobox',\n  'XCUIElementTypePickerWheel': 'pickerwheel',\n  'XCUIElementTypeSegmentedControl': 'tablist',\n  'XCUIElementTypeStepper': 'spinbutton',\n  'XCUIElementTypeDatePicker': 'combobox',\n  'XCUIElementTypeMenu': 'menu',\n  'XCUIElementTypeMenuItem': 'menuitem',\n  'XCUIElementTypeMenuButton': 'button',\n  'XCUIElementTypeToggle': 'switch',\n  'XCUIElementTypePopUpButton': 'combobox',\n  'XCUIElementTypeComboBox': 'combobox',\n  'XCUIElementTypeRadioButton': 'radio',\n  'XCUIElementTypeRadioGroup': 'group',\n  'XCUIElementTypeToolbar': 'toolbar',\n  'XCUIElementTypeProgressIndicator': 'progressbar',\n  'XCUIElementTypeActivityIndicator': 'progressbar',\n  'XCUIElementTypeColorWell': 'button',\n}\n\nexport const IOS_EDITABLE_TYPES: ReadonlySet<string> = new Set([\n  'XCUIElementTypeTextField',\n  'XCUIElementTypeSecureTextField',\n  'XCUIElementTypeSearchField',\n  'XCUIElementTypeTextView',\n])\n\nconst IOS_TRAIT_ROLE_PRECEDENCE: ReadonlyArray<[ReadonlyArray<string>, string]> = [\n  [['SearchField'], 'searchbox'],\n  [['Adjustable'], 'slider'],\n  [['TabBar'], 'tablist'],\n  [['Button', 'ToggleButton'], 'button'],\n  [['Link'], 'link'],\n  [['Header'], 'heading'],\n  [['Image'], 'image'],\n  [['StaticText', 'UpdatesFrequently', 'SummaryElement'], 'text'],\n]\n\n// WDA joins trait names in dictionary order, so the string is split rather than matched whole.\nexport function iosAccessibleOtherRole(traits: string | undefined): string {\n  const names = new Set(\n    (traits ?? '')\n      .split(',')\n      .map(t => t.trim())\n      .filter(t => t.length > 0),\n  )\n  for (const [traitNames, role] of IOS_TRAIT_ROLE_PRECEDENCE) {\n    if (traitNames.some(t => names.has(t))) return role\n  }\n  return 'button'\n}\n\nexport function normalizeRole(type: string, platform: 'android' | 'ios'): string {\n  const map = platform === 'android' ? ANDROID_ROLE_MAP : IOS_ROLE_MAP\n  const mapped = map[type]\n  if (mapped) return mapped\n\n  // Fallback: strip known prefixes and lowercase\n  let fallback = type\n  if (platform === 'ios') {\n    fallback = fallback.replace(/^XCUIElementType/, '')\n  } else {\n    fallback = fallback\n      .replace(/^android\\.widget\\./, '')\n      .replace(/^android\\.view\\./, '')\n      .replace(/^android\\.webkit\\./, '')\n      .replace(/^androidx\\.[\\w.]+\\./, '')\n      .replace(/^com\\.google\\.android\\.[\\w.]+\\./, '')\n      .replace(/^com\\.android\\.[\\w.]+\\./, '')\n  }\n  return fallback.toLowerCase() || 'element'\n}\n","import { XMLParser } from 'fast-xml-parser'\nimport type { InterimNode, RefBinding } from '@vostride/agent-qa-runner'\nimport { isToggleElement, type ElementLabels, type ElementState } from '@vostride/agent-qa-schema'\nimport type { ParsedMobileSource, RefEntry } from './types.js'\nimport { IOS_EDITABLE_TYPES, iosAccessibleOtherRole, normalizeRole } from './role-map.js'\n\nconst INTERACTIVE_ROLES = new Set([\n  'button', 'link', 'textbox', 'checkbox', 'radio', 'combobox',\n  'searchbox', 'slider', 'switch', 'tab', 'menuitem',\n  // Additional interactive roles (matching expanded web set and mobile types)\n  'spinbutton', 'option', 'menuitemradio', 'menuitemcheckbox',\n  'gridcell', 'scrollbar', 'separator',\n  'grid', 'menu', 'menubar', 'tree', 'treegrid', 'treeitem',\n  'listbox', 'pickerwheel',\n])\n\nconst CONTENT_ROLES = new Set([\n  'text', 'heading', 'cell', 'listitem', 'image', 'navigation', 'alert',\n  'progressbar',\n])\n\n// Only interactive and content roles become nodes; containers drop and their children reparent.\nfunction shouldEmit(role: string): boolean {\n  return INTERACTIVE_ROLES.has(role) || CONTENT_ROLES.has(role)\n}\n\n// fast-xml-parser leaves attributes as strings, so a real boolean is the literal `\"true\"`.\nfunction boolAttr(value: unknown): boolean {\n  return value === true || value === 'true'\n}\n\nfunction parseAndroidBounds(boundsStr: string): { x: number; y: number; width: number; height: number } | undefined {\n  const match = boundsStr.match(/^\\[(\\d+),(\\d+)\\]\\[(\\d+),(\\d+)\\]$/)\n  if (!match) return undefined\n  const x1 = parseInt(match[1], 10)\n  const y1 = parseInt(match[2], 10)\n  const x2 = parseInt(match[3], 10)\n  const y2 = parseInt(match[4], 10)\n  return { x: x1, y: y1, width: x2 - x1, height: y2 - y1 }\n}\n\nfunction parseIosBounds(attrs: Record<string, any>): { x: number; y: number; width: number; height: number } | undefined {\n  const x = parseFloat(attrs['@_x'])\n  const y = parseFloat(attrs['@_y'])\n  const width = parseFloat(attrs['@_width'])\n  const height = parseFloat(attrs['@_height'])\n  if (isNaN(x) || isNaN(y) || isNaN(width) || isNaN(height)) return undefined\n  return { x, y, width, height }\n}\n\nfunction extractLabel(attrs: Record<string, any>, platform: 'android' | 'ios'): string | undefined {\n  if (platform === 'android') {\n    const contentDesc = attrs['@_content-desc']\n    if (contentDesc) return contentDesc\n    const text = attrs['@_text']\n    if (text) return text\n    return undefined\n  }\n  // iOS\n  const label = attrs['@_label']\n  if (label) return label\n  const name = attrs['@_name']\n  if (name) return name\n  const value = attrs['@_value']\n  if (value) return value\n  return undefined\n}\n\nfunction extractValue(attrs: Record<string, any>, platform: 'android' | 'ios'): string | undefined {\n  const value = platform === 'android' ? attrs['@_text'] : attrs['@_value']\n  if (value === undefined || value === null || value === '') return undefined\n  return String(value)\n}\n\n// Only emitted signals populate `state`; iOS reports a toggle's state only as its `value`.\nfunction liftState(\n  tagName: string,\n  role: string,\n  attrs: Record<string, any>,\n  platform: 'android' | 'ios',\n  bounds: { x: number; y: number; width: number; height: number } | undefined,\n  viewport: { width: number; height: number } | undefined,\n): Partial<ElementState> {\n  const state: Partial<ElementState> = {}\n\n  if (attrs['@_enabled'] !== undefined) {\n    state.enabled = boolAttr(attrs['@_enabled'])\n  }\n  if (attrs['@_selected'] !== undefined) {\n    state.selected = boolAttr(attrs['@_selected'])\n  }\n\n  if (platform === 'android') {\n    // `checked` is only meaningful when the widget is `checkable` — otherwise typed-absent.\n    if (boolAttr(attrs['@_checkable']) && attrs['@_checked'] !== undefined) {\n      state.checked = boolAttr(attrs['@_checked'])\n    }\n    if (attrs['@_focused'] !== undefined) {\n      state.focused = boolAttr(attrs['@_focused'])\n    }\n    // visible derivation (documented): explicit displayed=false, else bounds fully\n    // outside the viewport ⇒ offscreen. Absent otherwise (builder defaults visible=true).\n    if (attrs['@_displayed'] !== undefined && !boolAttr(attrs['@_displayed'])) {\n      state.visible = false\n    } else if (bounds && viewport && (bounds.y + bounds.height < 0 || bounds.y > viewport.height)) {\n      state.visible = false\n    }\n  } else {\n    if ((role === 'switch' || role === 'checkbox') && isToggleElement({ role })) {\n      const value = attrs['@_value']\n      if (value === '1') state.checked = true\n      else if (value === '0') state.checked = false\n    }\n    if (attrs['@_visible'] !== undefined && !boolAttr(attrs['@_visible'])) {\n      state.visible = false\n    } else if (bounds && viewport && (bounds.y + bounds.height < 0 || bounds.y > viewport.height)) {\n      state.visible = false\n    }\n    if (IOS_EDITABLE_TYPES.has(tagName) && state.enabled !== false) {\n      state.editable = true\n    }\n  }\n\n  return state\n}\n\n/** Android maps `resource-id -> labels.testId` and `content-desc -> labels.ariaLabel`\n * (empty strings stay absent). iOS carries no dedicated label attributes here. */\nfunction liftLabels(attrs: Record<string, any>, platform: 'android' | 'ios'): ElementLabels {\n  const labels: ElementLabels = {}\n  if (platform === 'android') {\n    const resourceId = attrs['@_resource-id']\n    if (resourceId) labels.testId = String(resourceId)\n    const contentDesc = attrs['@_content-desc']\n    if (contentDesc) labels.ariaLabel = String(contentDesc)\n  }\n  return labels\n}\n\ninterface WalkContext {\n  platform: 'android' | 'ios'\n  nodes: InterimNode[]\n  viewport?: { width: number; height: number }\n  screenReference?: { width: number; height: number }\n}\n\nconst IOS_FULL_SCREEN_AREA_RATIO = 0.9\nconst IOS_PROMOTED_NAME_MAX = 120\n\nfunction collectAttrs(node: any): Record<string, any> {\n  const attrs: Record<string, any> = {}\n  for (const key of Object.keys(node)) {\n    if (key.startsWith('@_')) attrs[key] = node[key]\n  }\n  return attrs\n}\n\n// UIKit merges an accessible element's subviews into it and exposes no child text, so its\n// label is the only handle; React Native pressables without an accessibilityRole surface\n// this way as XCUIElementTypeOther.\nfunction isIosAccessibleLabelledOther(\n  tagName: string,\n  attrs: Record<string, any>,\n  ctx: WalkContext,\n): boolean {\n  if (ctx.platform !== 'ios' || tagName !== 'XCUIElementTypeOther') return false\n  if (!boolAttr(attrs['@_accessible'])) return false\n  const label = attrs['@_label']\n  if (label === undefined || label === null || String(label).trim() === '') return false\n  const bounds = parseIosBounds(attrs)\n  if (!bounds) return false\n  if (attrs['@_visible'] !== undefined && !boolAttr(attrs['@_visible'])) return false\n  // WDA reports a frame it cannot compute as (-1,-1,0,0).\n  if (!(bounds.width > 0 && bounds.height > 0)) return false\n  const ref = ctx.screenReference\n  if (ref && ref.width > 0 && ref.height > 0) {\n    const onScreen =\n      bounds.x < ref.width &&\n      bounds.y < ref.height &&\n      bounds.x + bounds.width > 0 &&\n      bounds.y + bounds.height > 0\n    if (!onScreen) return false\n    const area = bounds.width * bounds.height\n    if (area >= IOS_FULL_SCREEN_AREA_RATIO * ref.width * ref.height) return false\n  }\n  return true\n}\n\n// React Native joins a pressable's subtree text into its label, which can run to paragraphs.\nfunction capPromotedName(label: string): string {\n  const chars = Array.from(label)\n  if (chars.length <= IOS_PROMOTED_NAME_MAX) return label\n  return chars.slice(0, IOS_PROMOTED_NAME_MAX - 1).join('') + '…'\n}\n\nfunction descendantCarriesLabel(node: any, label: string, ctx: WalkContext): boolean {\n  for (const childKey of Object.keys(node)) {\n    if (childKey.startsWith('@_') || childKey === '#text') continue\n    const childVal = node[childKey]\n    const children = Array.isArray(childVal) ? childVal : [childVal]\n    for (const child of children) {\n      if (!child || typeof child !== 'object') continue\n      const attrs = collectAttrs(child)\n      const childLabel = extractLabel(attrs, ctx.platform)\n      if (\n        childLabel !== undefined &&\n        String(childLabel).trim() === label &&\n        shouldEmit(normalizeRole(childKey, ctx.platform))\n      ) {\n        return true\n      }\n      if (descendantCarriesLabel(child, label, ctx)) return true\n    }\n  }\n  return false\n}\n\nfunction walkNode(node: any, tagName: string, parentIndex: number | undefined, ctx: WalkContext): void {\n  const attrs: Record<string, any> = {}\n  // fast-xml-parser puts attributes with @_ prefix at the node level\n  for (const key of Object.keys(node)) {\n    if (key.startsWith('@_')) {\n      attrs[key] = node[key]\n    }\n  }\n\n  let role = normalizeRole(tagName, ctx.platform)\n  let emit = shouldEmit(role)\n  let promoted = false\n\n  if (ctx.platform === 'ios') {\n    if (\n      ctx.screenReference === undefined &&\n      (tagName === 'XCUIElementTypeApplication' || tagName === 'XCUIElementTypeWindow')\n    ) {\n      const reference = parseIosBounds(attrs)\n      if (reference && reference.width > 0 && reference.height > 0) {\n        ctx.screenReference = { width: reference.width, height: reference.height }\n      }\n    }\n    if (\n      !emit &&\n      isIosAccessibleLabelledOther(tagName, attrs, ctx) &&\n      !descendantCarriesLabel(node, String(attrs['@_label']).trim(), ctx)\n    ) {\n      const traits = attrs['@_traits']\n      role = iosAccessibleOtherRole(typeof traits === 'string' ? traits : undefined)\n      emit = true\n      promoted = true\n    }\n  }\n\n  // The index children reparent to: this node's own index if it is emitted, else the\n  // nearest surviving ancestor passed down.\n  let childParentIndex = parentIndex\n\n  if (emit) {\n    const rawLabel = extractLabel(attrs, ctx.platform)\n    const label = promoted && rawLabel !== undefined ? capPromotedName(String(rawLabel)) : rawLabel\n    const value = extractValue(attrs, ctx.platform)\n\n    let bounds: { x: number; y: number; width: number; height: number } | undefined\n    if (ctx.platform === 'android' && attrs['@_bounds']) {\n      bounds = parseAndroidBounds(attrs['@_bounds'])\n    } else if (ctx.platform === 'ios') {\n      bounds = parseIosBounds(attrs)\n    }\n\n    const state = liftState(tagName, role, attrs, ctx.platform, bounds, ctx.viewport)\n    const labels = liftLabels(attrs, ctx.platform)\n\n    // Retain the raw platform attribute bag (prefix stripped, values stringified).\n    const attributes: Record<string, string> = {}\n    for (const key of Object.keys(attrs)) {\n      attributes[key.slice(2)] = String(attrs[key])\n    }\n\n    const interim: InterimNode = {\n      role,\n      ...(label !== undefined ? { name: label } : {}),\n      ...(value !== undefined ? { value } : {}),\n      ...(parentIndex !== undefined ? { parentIndex } : {}),\n      ...(bounds !== undefined ? { bounds } : {}),\n      ...(Object.keys(state).length > 0 ? { state } : {}),\n      ...(Object.keys(labels).length > 0 ? { labels } : {}),\n      attributes,\n      nativeType: tagName,\n    }\n\n    childParentIndex = ctx.nodes.length\n    ctx.nodes.push(interim)\n  }\n\n  // Walk children\n  for (const childKey of Object.keys(node)) {\n    if (childKey.startsWith('@_') || childKey === '#text') continue\n    const childVal = node[childKey]\n    const children = Array.isArray(childVal) ? childVal : [childVal]\n    for (const child of children) {\n      if (child && typeof child === 'object') {\n        walkNode(child, childKey, childParentIndex, ctx)\n      }\n    }\n  }\n}\n\nexport function parseMobileSource(\n  xml: string,\n  platform: 'android' | 'ios',\n  viewport?: { width: number; height: number },\n): ParsedMobileSource {\n  // WDA writes a newline in an attribute as `&#10;`; numeric references are decoded on iOS\n  // only, so a multi-line value is observed as typed (Android parsing is left as it was).\n  const parser = new XMLParser({\n    ignoreAttributes: false,\n    attributeNamePrefix: '@_',\n    allowBooleanAttributes: true,\n    preserveOrder: false,\n    htmlEntities: platform === 'ios',\n  })\n\n  const parsed = parser.parse(xml)\n\n  const ctx: WalkContext = {\n    platform,\n    nodes: [],\n    viewport,\n    ...(platform === 'ios' && viewport ? { screenReference: viewport } : {}),\n  }\n\n  // Find root element(s) to walk\n  // Android: <hierarchy>...</hierarchy>\n  // iOS: <AppiumAUT>...</AppiumAUT>\n  const rootKeys = Object.keys(parsed).filter(k => !k.startsWith('?'))\n  for (const rootKey of rootKeys) {\n    const rootVal = parsed[rootKey]\n    if (rootVal && typeof rootVal === 'object') {\n      // Walk children of root container (hierarchy or AppiumAUT)\n      for (const childKey of Object.keys(rootVal)) {\n        if (childKey.startsWith('@_') || childKey === '#text') continue\n        const childVal = rootVal[childKey]\n        const children = Array.isArray(childVal) ? childVal : [childVal]\n        for (const child of children) {\n          if (child && typeof child === 'object') {\n            walkNode(child, childKey, undefined, ctx)\n          }\n        }\n      }\n    }\n  }\n\n  return { nodes: ctx.nodes }\n}\n\n// Planner-ref to live-node resolution for the adapters; no position lives on the binding.\nexport function buildRefEntries(\n  nodes: InterimNode[],\n  binding: Record<string, RefBinding>,\n): Record<string, RefEntry> {\n  const entries: Record<string, RefEntry> = {}\n  for (const [ref, { index }] of Object.entries(binding)) {\n    const node = nodes[index]\n    if (!node) continue\n    const rawInputType = node.attributes?.['input-type']\n    entries[ref] = {\n      role: node.role,\n      ...(node.name !== undefined ? { name: node.name } : {}),\n      ...(node.bounds !== undefined ? { bounds: node.bounds } : {}),\n      ...(node.nativeType !== undefined ? { nativeType: node.nativeType } : {}),\n      ...(node.value !== undefined ? { value: node.value } : {}),\n      ...(node.state?.editable === true ? { editable: true } : {}),\n      ...(rawInputType !== undefined && /^\\d+$/.test(rawInputType)\n        ? { inputType: Number(rawInputType) }\n        : {}),\n    }\n  }\n  return entries\n}\n\n// An approximation: page source has no scroll offset, so offsets are 0 and size is the node extent.\nexport function deriveMobileScroll(\n  nodes: InterimNode[],\n  viewport: { width: number; height: number },\n): { offsetX: number; offsetY: number; contentWidth: number; contentHeight: number } {\n  let maxX = viewport.width\n  let maxY = viewport.height\n  let sawBounds = false\n  for (const node of nodes) {\n    if (!node.bounds) continue\n    sawBounds = true\n    maxX = Math.max(maxX, node.bounds.x + node.bounds.width)\n    maxY = Math.max(maxY, node.bounds.y + node.bounds.height)\n  }\n  return {\n    offsetX: 0,\n    offsetY: 0,\n    contentWidth: sawBounds ? maxX : viewport.width,\n    contentHeight: sawBounds ? maxY : viewport.height,\n  }\n}\n","import type { Action } from '@vostride/agent-qa-runner'\nimport type { MobileRefMap } from './types.js'\n\nconst ACTIONS_WITHOUT_REF = new Set(['navigate', 'waitFor', 'delay', 'assert', 'scroll', 'swipe', 'pinch', 'multiTap'])\n\nexport class MobileElementResolver {\n  constructor(private refs: MobileRefMap) {}\n\n  resolve(ref: string): { role: string; name?: string; bounds: { x: number; y: number; width: number; height: number }; center: { x: number; y: number } } {\n    const data = this.refs[ref]\n    if (!data) {\n      const available = Object.keys(this.refs).join(', ') || 'none'\n      throw new Error(`Unknown ref \"${ref}\". Available refs: ${available}`)\n    }\n\n    if (!data.bounds) {\n      throw new Error(`Ref \"${ref}\" (${data.role}${data.name ? ` \"${data.name}\"` : ''}) has no bounds for coordinate resolution`)\n    }\n\n    const center = {\n      x: data.bounds.x + data.bounds.width / 2,\n      y: data.bounds.y + data.bounds.height / 2,\n    }\n\n    return {\n      role: data.role,\n      name: data.name,\n      bounds: data.bounds,\n      center,\n    }\n  }\n\n  resolveAction(action: Action): { bounds: { x: number; y: number; width: number; height: number }; center: { x: number; y: number } } | null {\n    if (ACTIONS_WITHOUT_REF.has(action.type)) {\n      // scroll/swipe may have optional ref\n      if (('ref' in action) && typeof (action as { ref?: string }).ref === 'string') {\n        const resolved = this.resolve((action as { ref: string }).ref)\n        return { bounds: resolved.bounds, center: resolved.center }\n      }\n      return null\n    }\n\n    if ('ref' in action && typeof (action as { ref?: string }).ref === 'string') {\n      const resolved = this.resolve((action as { ref: string }).ref)\n      return { bounds: resolved.bounds, center: resolved.center }\n    }\n\n    return null\n  }\n}\n","export const KEY_MAP: Record<string, string> = {\n  Enter: '\\uE007',\n  Tab: '\\uE004',\n  Escape: '\\uE00C',\n  Backspace: '\\uE003',\n  Space: '\\uE00D',\n  ArrowUp: '\\uE013',\n  ArrowDown: '\\uE014',\n  ArrowLeft: '\\uE012',\n  ArrowRight: '\\uE011',\n}\n\nexport function computePinch(\n  centerX: number, centerY: number,\n  scale: number,\n  startDistance = 100,\n): {\n  finger1Start: { x: number; y: number }; finger1End: { x: number; y: number }\n  finger2Start: { x: number; y: number }; finger2End: { x: number; y: number }\n} {\n  const halfStart = startDistance / 2\n  const halfEnd = (startDistance * scale) / 2\n\n  return {\n    finger1Start: { x: centerX - halfStart, y: centerY },\n    finger1End:   { x: centerX - halfEnd, y: centerY },\n    finger2Start: { x: centerX + halfStart, y: centerY },\n    finger2End:   { x: centerX + halfEnd, y: centerY },\n  }\n}\n\nexport function computeFingerPositions(\n  centerX: number, centerY: number,\n  fingers: number,\n  spacing = 40,\n): { x: number; y: number }[] {\n  if (fingers === 2) {\n    return [\n      { x: centerX - spacing / 2, y: centerY },\n      { x: centerX + spacing / 2, y: centerY },\n    ]\n  }\n  // 3 fingers: triangle arrangement\n  return [\n    { x: centerX, y: centerY - spacing / 2 },\n    { x: centerX - spacing / 2, y: centerY + spacing / 2 },\n    { x: centerX + spacing / 2, y: centerY + spacing / 2 },\n  ]\n}\n\nexport function computeSwipe(\n  centerX: number, centerY: number,\n  direction: 'up' | 'down' | 'left' | 'right',\n  distance: number,\n): { startX: number; startY: number; endX: number; endY: number } {\n  switch (direction) {\n    case 'up':\n      return { startX: centerX, startY: centerY + distance / 2, endX: centerX, endY: centerY - distance / 2 }\n    case 'down':\n      return { startX: centerX, startY: centerY - distance / 2, endX: centerX, endY: centerY + distance / 2 }\n    case 'left':\n      return { startX: centerX + distance / 2, startY: centerY, endX: centerX - distance / 2, endY: centerY }\n    case 'right':\n      return { startX: centerX - distance / 2, startY: centerY, endX: centerX + distance / 2, endY: centerY }\n  }\n}\n","import { existsSync } from 'node:fs'\nimport { dirname, resolve as resolvePath } from 'node:path'\nimport {\n  isPluginRemote,\n  RemoteRefusalError,\n  type RemoteDeviceConfig,\n  type RemotePluginDeviceConfig,\n} from '@vostride/agent-qa-runner'\nimport type { RemoteEntry } from '../schema/remote-schema.js'\nimport {\n  capabilityValue,\n  mergeCapabilities,\n  remoteAppCapability,\n  runStartCapabilityContradictions,\n} from './device-plan.js'\nimport { selectDevicePlace } from './select-device.js'\n\nexport type MobilePlatform = 'android' | 'ios'\nexport type MobileAppState = 'preserve' | 'reset'\n\nexport type MobileSetupErrorCategory =\n  | 'device-resolution'\n  | 'appium-startup'\n  | 'device-readiness'\n  | 'adapter-load'\n  | 'app-install'\n  | 'app-launch'\n\nexport interface MobileSetupErrorOptions {\n  category: MobileSetupErrorCategory\n  message: string\n  platform?: MobilePlatform\n  targetName?: string\n  deviceName?: string\n  appId?: string\n  cause?: unknown\n  sourceTrace?: string[]\n}\n\nexport class MobileSetupError extends Error {\n  readonly category: MobileSetupErrorCategory\n  readonly platform?: MobilePlatform\n  readonly targetName?: string\n  readonly deviceName?: string\n  readonly appId?: string\n  readonly sourceTrace?: string[]\n  override readonly cause?: unknown\n\n  constructor(options: MobileSetupErrorOptions) {\n    super(options.message)\n    this.name = 'MobileSetupError'\n    this.category = options.category\n    this.platform = options.platform\n    this.targetName = options.targetName\n    this.deviceName = options.deviceName\n    this.appId = options.appId\n    this.sourceTrace = options.sourceTrace\n    this.cause = options.cause\n  }\n}\n\nexport interface ResolvedMobileDevice {\n  name: string\n  platform: MobilePlatform\n  model?: string\n  os?: string\n  id?: string\n  capabilities?: Record<string, unknown>\n  remote?: RemoteDeviceConfig | RemotePluginDeviceConfig\n}\n\nexport interface ResolvedMobileAppInstall {\n  path?: string\n  sourceTrace: Record<string, string>\n}\n\nexport interface ResolvedMobileApp {\n  ref?: string\n  bundleId?: string\n  appPackage?: string\n  appActivity?: string\n  deepLinkAppId?: string\n  install?: ResolvedMobileAppInstall\n  sourceTrace: Record<string, string>\n}\n\n// A device on a remote connects there; a device here is searched for on this machine.\nexport type MobileDevicePlan =\n  | { kind: 'remote'; remote: RemoteDeviceConfig | RemotePluginDeviceConfig }\n  | { kind: 'here'; search: { model?: string; os?: string; id?: string } }\n\nexport interface ResolvedMobileRunConfig {\n  platform: MobilePlatform\n  targetName: string\n  deviceName: string\n  device: ResolvedMobileDevice\n  plan: MobileDevicePlan\n  app: ResolvedMobileApp\n  appState: MobileAppState\n  sourceTrace: string[]\n}\n\nexport interface ResolveMobileRunConfigInput {\n  config: Record<string, any>\n  targetName: string\n  platform?: MobilePlatform\n  explicitDeviceName?: string\n  useDeviceName?: string\n  appState?: MobileAppState\n  configFilePath?: string\n}\n\ninterface TargetEntry {\n  platform?: string\n  bundleId?: string\n  appPackage?: string\n  appActivity?: string\n  app?: {\n    path?: string\n    ref?: string\n  }\n  device?: string\n}\n\ninterface DeviceProfile {\n  platform?: string\n  model?: string\n  os?: string\n  id?: string\n  capabilities?: Record<string, unknown>\n  remote?: string\n}\n\nfunction isMobilePlatform(value: unknown): value is MobilePlatform {\n  return value === 'android' || value === 'ios'\n}\n\nfunction asOptionalString(value: unknown): string | undefined {\n  return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction isAbsoluteAppInstallValue(value: string): boolean {\n  return value.startsWith('/') || /^[A-Za-z]:[\\\\/]/.test(value) || value.startsWith('\\\\\\\\')\n}\n\nfunction baseDirFor(filePath?: string): string {\n  return filePath ? dirname(filePath) : process.cwd()\n}\n\nfunction setupError(\n  message: string,\n  input: ResolveMobileRunConfigInput,\n  extras: Partial<Omit<MobileSetupErrorOptions, 'category' | 'message' | 'targetName'>> = {},\n): MobileSetupError {\n  return new MobileSetupError({\n    category: 'device-resolution',\n    message,\n    targetName: input.targetName,\n    ...extras,\n  })\n}\n\nfunction appInstallError(\n  message: string,\n  input: ResolveMobileRunConfigInput,\n  extras: Partial<Omit<MobileSetupErrorOptions, 'category' | 'message' | 'targetName'>> = {},\n): MobileSetupError {\n  return new MobileSetupError({\n    category: 'app-install',\n    message,\n    targetName: input.targetName,\n    ...extras,\n  })\n}\n\nfunction chooseDeviceName(\n  input: ResolveMobileRunConfigInput,\n  target: TargetEntry,\n): { name?: string; source?: string } {\n  const candidates = [\n    ['explicitDeviceName', input.explicitDeviceName],\n    ['use.device', input.useDeviceName],\n    [`registry.targets.${input.targetName}.device`, target.device],\n  ] as const\n\n  for (const [source, value] of candidates) {\n    const name = asOptionalString(value)\n    if (name) return { name, source }\n  }\n\n  return {}\n}\n\nfunction resolveAppField(\n  field: 'bundleId' | 'appPackage' | 'appActivity',\n  targetValue: unknown,\n  targetName: string,\n): { value?: string; source?: string } {\n  const value = asOptionalString(targetValue)\n  return value ? { value, source: `registry.targets.${targetName}.${field}` } : {}\n}\n\n// The server installs a remote device's app, so its file is only needed here.\nfunction resolveAppInstall(\n  target: TargetEntry,\n  input: ResolveMobileRunConfigInput,\n  platform: MobilePlatform,\n  deviceName: string,\n  sourceTrace: string[],\n  here: boolean,\n): ResolvedMobileAppInstall | undefined {\n  const installSourceTrace: Record<string, string> = {}\n  const pathValue = asOptionalString(target.app?.path)\n  const pathSource = `agent-qa.config.yaml registry.targets.${input.targetName}.app.path`\n\n  const install: ResolvedMobileAppInstall = { sourceTrace: installSourceTrace }\n\n  if (pathValue) {\n    if (isAbsoluteAppInstallValue(pathValue)) {\n      throw appInstallError(`Configured app path must be relative: ${pathValue}`, input, {\n        platform,\n        deviceName,\n        appId: pathValue,\n        sourceTrace: [...sourceTrace, `app.path=${pathSource}`],\n      })\n    }\n    const resolvedPath = resolvePath(baseDirFor(input.configFilePath), pathValue)\n    if (here && !existsSync(resolvedPath)) {\n      throw appInstallError(`Configured app path not found: ${resolvedPath}`, input, {\n        platform,\n        deviceName,\n        appId: pathValue,\n        sourceTrace: [...sourceTrace, `app.path=${pathSource}`],\n      })\n    }\n    install.path = resolvedPath\n    installSourceTrace['app.path'] = pathSource\n    sourceTrace.push(`app.path=${pathSource}`)\n  }\n\n  return install.path ? install : undefined\n}\n\nexport function resolveMobileRunConfig(input: ResolveMobileRunConfigInput): ResolvedMobileRunConfig {\n  const targets = input.config.registry?.targets as Record<string, TargetEntry> | undefined\n  const target = targets?.[input.targetName]\n  if (!target) {\n    const available = targets ? Object.keys(targets).join(', ') : 'none'\n    throw setupError(\n      `Target \"${input.targetName}\" not found in config. Available targets: ${available}`,\n      input,\n    )\n  }\n\n  const platformCandidate = input.platform ?? target.platform\n  if (!isMobilePlatform(platformCandidate)) {\n    throw setupError(\n      `Target \"${input.targetName}\" is not a mobile target`,\n      input,\n    )\n  }\n  const platform = platformCandidate\n\n  const appState = input.appState\n  if (appState !== 'preserve' && appState !== 'reset') {\n    throw setupError(\n      'use.mobile.appState is required for native mobile app targets and must be one of: preserve | reset',\n      input,\n      { platform },\n    )\n  }\n\n  const chosenDevice = chooseDeviceName(input, target)\n  if (!chosenDevice.name) {\n    throw setupError(\n      `No device specified for mobile target \"${input.targetName}\". ` +\n        `Set device on registry.targets.${input.targetName}, ` +\n        'use.device in the test or its suite, or pass --device.',\n      input,\n      { platform },\n    )\n  }\n  const deviceName = chosenDevice.name\n\n  const devices = input.config.registry?.devices as Record<string, DeviceProfile> | undefined\n  const deviceProfile = devices?.[deviceName]\n  if (!deviceProfile) {\n    const available = devices ? Object.keys(devices).join(', ') : 'none'\n    throw setupError(\n      `Device \"${deviceName}\" not found in registry.devices. Available devices: ${available}`,\n      input,\n      { platform, deviceName },\n    )\n  }\n\n  if (deviceProfile.platform !== platform) {\n    throw setupError(\n      `Device \"${deviceName}\" platform \"${deviceProfile.platform ?? 'unknown'}\" does not match target \"${input.targetName}\" platform \"${platform}\"`,\n      input,\n      { platform, deviceName },\n    )\n  }\n\n  let remote: RemoteDeviceConfig | RemotePluginDeviceConfig | undefined\n  if (deviceProfile.remote !== undefined) {\n    const selected = selectDevicePlace({\n      devices: devices ?? {},\n      remotes: (input.config.registry?.remotes ?? []) as readonly RemoteEntry[],\n      device: deviceName,\n    })\n    if ('refusal' in selected) throw setupError(selected.refusal, input, { platform, deviceName })\n    if (selected.place.kind === 'remote') remote = selected.place.remote\n  }\n\n  const appSourceTrace: Record<string, string> = {}\n  const sourceTrace = [\n    `target=registry.targets.${input.targetName}`,\n    `platform=${platform}`,\n    `device=${chosenDevice.source}:${deviceName}`,\n    `appState=use.mobile.appState:${appState}`,\n  ]\n\n  let app: ResolvedMobileApp\n  if (platform === 'android') {\n    const appPackage = resolveAppField('appPackage', target.appPackage, input.targetName)\n    const appActivity = resolveAppField('appActivity', target.appActivity, input.targetName)\n    if (appPackage.source) appSourceTrace.appPackage = appPackage.source\n    if (appActivity.source) appSourceTrace.appActivity = appActivity.source\n    app = {\n      appPackage: appPackage.value,\n      appActivity: appActivity.value,\n      deepLinkAppId: appPackage.value,\n      sourceTrace: appSourceTrace,\n    }\n    if (appPackage.source) sourceTrace.push(`app.appPackage=${appPackage.source}`)\n    if (appActivity.source) sourceTrace.push(`app.appActivity=${appActivity.source}`)\n  } else {\n    const bundleId = resolveAppField('bundleId', target.bundleId, input.targetName)\n    if (bundleId.source) appSourceTrace.bundleId = bundleId.source\n    app = {\n      bundleId: bundleId.value,\n      deepLinkAppId: bundleId.value,\n      sourceTrace: appSourceTrace,\n    }\n    if (bundleId.source) sourceTrace.push(`app.bundleId=${bundleId.source}`)\n  }\n\n  const appRef = asOptionalString(target.app?.ref)\n  if (appRef) {\n    app.ref = appRef\n    appSourceTrace['app.ref'] = `registry.targets.${input.targetName}.app.ref`\n  }\n\n  const deviceCapabilities = isRecord(deviceProfile.capabilities)\n    ? deviceProfile.capabilities\n    : undefined\n  const stated = mergeCapabilities(remote?.capabilities, deviceCapabilities)\n  const browserMode = asOptionalString(capabilityValue(stated, 'browserName')) !== undefined\n  const refusalDetails = remote === undefined ? {} : { remote: remote.name }\n  const contradictions = runStartCapabilityContradictions({\n    device: deviceName,\n    target: {\n      name: input.targetName,\n      ...(app.appPackage ? { appPackage: app.appPackage } : {}),\n      ...(app.appActivity ? { appActivity: app.appActivity } : {}),\n      ...(app.bundleId ? { bundleId: app.bundleId } : {}),\n    },\n    appState,\n    browserMode,\n    ...(remote === undefined\n      ? {}\n      : {\n          remote: {\n            name: remote.name,\n            ...(remote.capabilities ? { capabilities: remote.capabilities } : {}),\n          },\n        }),\n    ...(deviceCapabilities ? { capabilities: deviceCapabilities } : {}),\n  })\n  if (contradictions.length > 0) {\n    throw new RemoteRefusalError(contradictions.join('\\n'), refusalDetails)\n  }\n\n  // A plugin remote may upload the target's app.path; its plugin refuses when it cannot.\n  if (remote !== undefined && !isPluginRemote(remote) && !browserMode) {\n    const pathValue = asOptionalString(target.app?.path)\n    const remoteApp = remoteAppCapability({\n      device: deviceName,\n      remote: remote.name,\n      target: input.targetName,\n      ...(appRef ? { appRef } : {}),\n      ...(pathValue ? { appPath: pathValue } : {}),\n      capabilities: stated,\n    })\n    if ('refusal' in remoteApp) throw new RemoteRefusalError(remoteApp.refusal, refusalDetails)\n  }\n\n  const install = resolveAppInstall(\n    target,\n    input,\n    platform,\n    deviceName,\n    sourceTrace,\n    remote === undefined,\n  )\n  if (install) {\n    app.install = install\n  }\n\n  const model = asOptionalString(deviceProfile.model)\n  const os = asOptionalString(deviceProfile.os)\n  const id = asOptionalString(deviceProfile.id)\n  const plan: MobileDevicePlan =\n    remote === undefined\n      ? {\n          kind: 'here',\n          search: {\n            ...(model ? { model } : {}),\n            ...(os ? { os } : {}),\n            ...(id ? { id } : {}),\n          },\n        }\n      : { kind: 'remote', remote }\n\n  return {\n    platform,\n    targetName: input.targetName,\n    deviceName,\n    device: {\n      name: deviceName,\n      platform,\n      ...(model ? { model } : {}),\n      ...(os ? { os } : {}),\n      ...(id ? { id } : {}),\n      ...(deviceCapabilities ? { capabilities: deviceCapabilities } : {}),\n      ...(remote === undefined ? {} : { remote }),\n    },\n    plan,\n    app,\n    appState,\n    sourceTrace,\n  }\n}\n","export interface AttachedAndroid {\n  serial: string\n  state: string\n  model?: string\n  os?: string\n  // A running emulator's AVD name.\n  avd?: string\n}\n\nexport interface AvdHere {\n  name: string\n  // The AVD's device profile, `hw.device.name` (for example `pixel_10_pro`).\n  profile?: string\n  displayName?: string\n  os?: string\n  apiLevel?: string\n}\n\nexport interface AndroidHere {\n  attached: AttachedAndroid[]\n  avds: AvdHere[]\n  problem?: string\n}\n\nexport interface SimulatorHere {\n  name: string\n  udid: string\n  os: string\n  state: string\n  available: boolean\n}\n\nexport interface IOSHere {\n  simulators: SimulatorHere[]\n  problem?: string\n}\n\nexport interface DeviceFound {\n  udid?: string\n  avd?: string\n  name?: string\n  os?: string\n  running: boolean\n  description: string\n}\n\nexport interface FindDeviceHereInput {\n  device: string\n  platform: 'android' | 'ios'\n  model?: string\n  os?: string\n  id?: string\n  android?: AndroidHere\n  ios?: IOSHere\n}\n\nexport type FindDeviceHereResult = { found: DeviceFound } | { refusal: string }\n\ntype CandidateKind = 'phone' | 'emulator' | 'avd' | 'simulator'\n\ninterface Candidate {\n  kind: CandidateKind\n  names: string[]\n  id?: string\n  model?: string\n  os?: string\n  running: boolean\n  label: string\n  found: DeviceFound\n}\n\nexport function normalizeDeviceText(text: string): string {\n  return text.toLowerCase().replace(/[\\s_-]+/g, ' ').trim()\n}\n\nfunction osParts(os: string): string[] {\n  return os.trim().split('.')\n}\n\nfunction partsEqual(want: string, have: string): boolean {\n  if (/^\\d+$/.test(want) && /^\\d+$/.test(have)) return Number(want) === Number(have)\n  return want.toLowerCase() === have.toLowerCase()\n}\n\n// `18` matches `18.2`, `18.4` matches `18.4.1` but not `18.40`, `8.1` matches `8.1.0`.\nexport function osMatches(want: string, have: string | undefined): boolean {\n  if (have === undefined) return false\n  const wanted = osParts(want)\n  const had = osParts(have)\n  return wanted.every((part, index) => {\n    const other = had[index]\n    return other === undefined ? /^0+$/.test(part) : partsEqual(part, other)\n  })\n}\n\nfunction compareOs(a: string | undefined, b: string | undefined): number {\n  if (a === undefined || b === undefined) return a === b ? 0 : a === undefined ? -1 : 1\n  const left = osParts(a).map((part) => Number.parseInt(part, 10) || 0)\n  const right = osParts(b).map((part) => Number.parseInt(part, 10) || 0)\n  for (let index = 0; index < Math.max(left.length, right.length); index++) {\n    const diff = (left[index] ?? 0) - (right[index] ?? 0)\n    if (diff !== 0) return diff\n  }\n  return 0\n}\n\nfunction joinParts(parts: (string | undefined)[]): string {\n  return parts.filter((part): part is string => part !== undefined && part !== '').join(', ')\n}\n\n// Android's published version for each API level, for an AVD whose image has no build.prop.\nconst ANDROID_VERSION_BY_API_LEVEL: Readonly<Record<string, string>> = {\n  '21': '5.0',\n  '22': '5.1',\n  '23': '6.0',\n  '24': '7.0',\n  '25': '7.1',\n  '26': '8.0',\n  '27': '8.1',\n  '28': '9',\n  '29': '10',\n  '30': '11',\n  '31': '12',\n  '32': '12',\n  '33': '13',\n  '34': '14',\n  '35': '15',\n  '36': '16',\n}\n\nfunction avdOs(avd: AvdHere | undefined): string | undefined {\n  if (avd?.os !== undefined) return avd.os\n  const level = avd?.apiLevel?.trim()\n  if (level === undefined || !Object.hasOwn(ANDROID_VERSION_BY_API_LEVEL, level)) return undefined\n  return ANDROID_VERSION_BY_API_LEVEL[level]\n}\n\nfunction avdDetail(avd: AvdHere): string {\n  const version =\n    avd.os !== undefined\n      ? `Android ${avd.os}`\n      : avd.apiLevel !== undefined\n        ? `API ${avd.apiLevel}`\n        : undefined\n  return joinParts([avd.displayName ?? avd.profile, version])\n}\n\nfunction avdLabel(avd: AvdHere): string {\n  const detail = avdDetail(avd)\n  return detail === '' ? avd.name : `${avd.name} (${detail})`\n}\n\nfunction isEmulator(device: AttachedAndroid): boolean {\n  return device.avd !== undefined || device.serial.startsWith('emulator-')\n}\n\nfunction attachedLabel(device: AttachedAndroid): string {\n  const kind = isEmulator(device) ? 'emulator' : 'phone'\n  const head = isEmulator(device) ? (device.avd ?? device.model) : device.model\n  const detail = joinParts([\n    device.os === undefined ? undefined : `Android ${device.os}`,\n    device.state === 'device' ? undefined : device.state,\n  ])\n  const base = head === undefined ? `${kind} ${device.serial}` : `${head} ${kind} ${device.serial}`\n  return detail === '' ? base : `${base} (${detail})`\n}\n\nfunction simulatorLabel(simulator: SimulatorHere): string {\n  return `${simulator.name} (${simulator.os})`\n}\n\nfunction androidCandidates(listing: AndroidHere): Candidate[] {\n  const avds = new Map(listing.avds.map((avd) => [avd.name, avd]))\n  const runningAvds = new Set(\n    listing.attached.flatMap((device) => (device.avd === undefined ? [] : [device.avd])),\n  )\n  const attached = listing.attached\n    .filter((device) => device.state === 'device')\n    .map((device): Candidate => {\n      const avd = device.avd === undefined ? undefined : avds.get(device.avd)\n      const os = device.os ?? avdOs(avd)\n      const kind = isEmulator(device) ? 'emulator' : 'phone'\n      const head = (kind === 'emulator' ? device.avd : undefined) ?? device.model ?? 'device'\n      return {\n        kind,\n        names: [device.model, device.avd, avd?.profile, avd?.displayName].filter(\n          (name): name is string => name !== undefined,\n        ),\n        id: device.serial,\n        model: device.model ?? avd?.displayName ?? device.avd,\n        os,\n        running: true,\n        label: attachedLabel(device),\n        found: {\n          udid: device.serial,\n          ...(os === undefined ? {} : { os }),\n          running: true,\n          description: `${head} ${kind} ${device.serial}`,\n        },\n      }\n    })\n  const idle = listing.avds\n    .filter((avd) => !runningAvds.has(avd.name))\n    .map((avd): Candidate => {\n      const os = avdOs(avd)\n      return {\n        kind: 'avd',\n        names: [avd.name, avd.profile, avd.displayName].filter(\n          (name): name is string => name !== undefined,\n        ),\n        model: avd.displayName ?? avd.name,\n        os,\n        running: false,\n        label: avdLabel(avd),\n        found: {\n          avd: avd.name,\n          ...(os === undefined ? {} : { os }),\n          running: false,\n          description: `${avdLabel(avd)}, not running`,\n        },\n      }\n    })\n  return [...attached, ...idle]\n}\n\nfunction iosCandidates(listing: IOSHere): Candidate[] {\n  return listing.simulators\n    .filter((simulator) => simulator.available)\n    .map((simulator): Candidate => {\n      const running = simulator.state === 'Booted'\n      return {\n        kind: 'simulator',\n        names: [simulator.name],\n        id: simulator.udid,\n        model: simulator.name,\n        os: simulator.os,\n        running,\n        label: simulatorLabel(simulator),\n        found: {\n          udid: simulator.udid,\n          name: simulator.name,\n          os: simulator.os,\n          running,\n          description: `${simulatorLabel(simulator)}, ${running ? 'booted' : 'shut down'}`,\n        },\n      }\n    })\n}\n\nfunction article(word: string): string {\n  return /^[aeiou]/i.test(word) ? 'an' : 'a'\n}\n\nfunction countWord(count: number): string {\n  return ['', 'one', 'two', 'three', 'four', 'five'][count] ?? String(count)\n}\n\nfunction listWords(items: readonly string[]): string {\n  if (items.length <= 1) return items.join('')\n  return `${items.slice(0, -1).join(', ')} and ${items[items.length - 1]}`\n}\n\nfunction capitalize(text: string): string {\n  return text.charAt(0).toUpperCase() + text.slice(1)\n}\n\n// What the machine has, written to sit after a semicolon.\nfunction machineHas(platform: 'android' | 'ios', problem: string | undefined, labels: string[]) {\n  const ios = platform === 'ios'\n  if (problem !== undefined) {\n    const lister = ios ? \"this Mac's simulators\" : \"this machine's Android devices\"\n    return `${lister} cannot be listed: ${problem}`\n  }\n  if (labels.length === 0) {\n    return ios ? 'this Mac has no simulators' : 'this machine has no Android devices or AVDs'\n  }\n  return `${ios ? 'this Mac' : 'this machine'} has: ${labels.join(', ')}`\n}\n\nfunction tieNoun(kinds: Set<CandidateKind>): string {\n  if (kinds.size !== 1) return 'devices'\n  const [kind] = [...kinds]\n  if (kind === 'phone') return 'attached phones'\n  if (kind === 'emulator') return 'running emulators'\n  if (kind === 'avd') return 'AVDs'\n  return 'simulators'\n}\n\nfunction refuseTie(input: FindDeviceHereInput, tied: Candidate[]): string {\n  const first = tied[0] as Candidate\n  const kinds = new Set(tied.map((candidate) => candidate.kind))\n  const names = tied.map((candidate) =>\n    candidate.kind === 'avd' ? (candidate.found.avd as string) : (candidate.id as string),\n  )\n  const system = input.platform === 'ios' ? 'iOS' : 'Android'\n  const version = first.os === undefined ? undefined : `${system} ${first.os}`\n  const detail = joinParts([first.model, version])\n  const remedy = kinds.has('avd')\n    ? `Set model in registry.devices.${input.device} to one AVD's name.`\n    : `Set id in registry.devices.${input.device} to pick one.`\n  return (\n    `Device ${input.device} matches ${countWord(tied.length)} ${tieNoun(kinds)}, ` +\n    `${listWords(names)}${detail === '' ? '' : ` (${detail})`}. ${remedy}`\n  )\n}\n\nfunction pick(input: FindDeviceHereInput, matches: Candidate[]): FindDeviceHereResult {\n  const ranked = [...matches].sort(\n    (a, b) => compareOs(b.os, a.os) || Number(b.running) - Number(a.running),\n  )\n  const best = ranked[0] as Candidate\n  const tied = ranked.filter(\n    (candidate) => compareOs(candidate.os, best.os) === 0 && candidate.running === best.running,\n  )\n  if (tied.length > 1) return { refusal: refuseTie(input, tied) }\n  return { found: best.found }\n}\n\nfunction refuseNoModel(\n  input: FindDeviceHereInput,\n  running: Candidate[],\n  labels: string[],\n  problem: string | undefined,\n): string {\n  const ios = input.platform === 'ios'\n  const where = ios ? 'this Mac' : 'this machine'\n  const what = ios ? 'iOS simulator' : 'Android device'\n  if (running.length === 0) {\n    return (\n      `Device ${input.device} names no model, and ${where} runs no ${what}. ` +\n      `Start one, or set model in registry.devices.${input.device}. ` +\n      `${capitalize(machineHas(input.platform, problem, labels))}.`\n    )\n  }\n  const named = running.map((candidate) => candidate.label).join(', ')\n  return (\n    `Device ${input.device} names no model, and ${where} runs ` +\n    `${countWord(running.length)} ${what}s: ${named}. ` +\n    `Set model in registry.devices.${input.device}.`\n  )\n}\n\nfunction refuseNoMatch(\n  input: FindDeviceHereInput,\n  labels: string[],\n  problem: string | undefined,\n): string {\n  const model = input.model as string\n  const ios = input.platform === 'ios'\n  const wants = ios\n    ? `${article(model)} ${model} simulator${input.os === undefined ? '' : ` on iOS ${input.os}`}`\n    : `${article(model)} ${model}${input.os === undefined ? '' : ` on Android ${input.os}`}`\n  const unit = input.id === undefined ? '' : ` with ${ios ? 'udid' : 'serial'} ${input.id}`\n  return (\n    `Device ${input.device} wants ${wants}${unit}; ` +\n    `${machineHas(input.platform, problem, labels)}. ` +\n    `Set model or os in registry.devices.${input.device}.`\n  )\n}\n\nexport function findDeviceHere(input: FindDeviceHereInput): FindDeviceHereResult {\n  const ios = input.platform === 'ios'\n  const listing = ios ? input.ios : input.android\n  const problem = listing?.problem\n  const candidates = ios\n    ? iosCandidates(input.ios ?? { simulators: [] })\n    : androidCandidates(input.android ?? { attached: [], avds: [] })\n  const labels = ios\n    ? candidates.map((candidate) => candidate.label)\n    : [\n        ...(input.android?.attached ?? []).map(attachedLabel),\n        ...candidates.filter((candidate) => candidate.kind === 'avd').map((c) => c.label),\n      ]\n  const narrowed = candidates.filter(\n    (candidate) =>\n      (input.id === undefined || candidate.id === input.id) &&\n      (input.os === undefined || osMatches(input.os, candidate.os)),\n  )\n  if (input.model === undefined) {\n    const running = narrowed.filter((candidate) => candidate.running)\n    if (running.length !== 1) return { refusal: refuseNoModel(input, running, labels, problem) }\n    return { found: (running[0] as Candidate).found }\n  }\n  const wanted = normalizeDeviceText(input.model)\n  const matches = narrowed.filter((candidate) =>\n    candidate.names.some((name) => normalizeDeviceText(name) === wanted),\n  )\n  if (matches.length === 0) return { refusal: refuseNoMatch(input, labels, problem) }\n  return pick(input, matches)\n}\n\nconst LABEL_WIDTH = 12\n\nfunction labelled(label: string, rows: string[]): string[] {\n  const indent = ' '.repeat(LABEL_WIDTH)\n  return rows.map((row, index) => `${index === 0 ? label.padEnd(LABEL_WIDTH) : indent}${row}`)\n}\n\nfunction columns(rows: string[][]): string[] {\n  const widths = rows.reduce<number[]>(\n    (acc, row) => row.map((cell, index) => Math.max(acc[index] ?? 0, cell.length)),\n    [],\n  )\n  return rows.map((row) =>\n    row\n      .map((cell, index) => (index === row.length - 1 ? cell : cell.padEnd(widths[index] ?? 0)))\n      .filter((_, index) => (widths[index] ?? 0) > 0)\n      .join('  ')\n      .trimEnd(),\n  )\n}\n\n// The Attached and Emulators lines of `agent-qa devices`.\nexport function describeAndroidHere(listing: AndroidHere): string[] {\n  const phones = listing.attached.filter((device) => !isEmulator(device))\n  const attached =\n    listing.problem !== undefined\n      ? [listing.problem]\n      : phones.length === 0\n        ? ['none']\n        : columns(\n            phones.map((device) => [\n              device.model ?? '',\n              device.os === undefined ? '' : `Android ${device.os}`,\n              device.state === 'device' ? device.serial : `${device.serial} ${device.state}`,\n            ]),\n          )\n  const avds = new Map(listing.avds.map((avd) => [avd.name, avd]))\n  const running = listing.attached.filter(isEmulator).map((device) => {\n    const avd = device.avd === undefined ? undefined : avds.get(device.avd)\n    const name = device.avd ?? device.serial\n    const os = device.os ?? avd?.os\n    const detail = joinParts([\n      avd?.displayName ?? avd?.profile,\n      os === undefined ? undefined : `Android ${os}`,\n      device.state === 'device' ? `running ${device.serial}` : `${device.state} ${device.serial}`,\n    ])\n    return `${name} (${detail})`\n  })\n  const runningNames = new Set(listing.attached.flatMap((device) => device.avd ?? []))\n  const idle = listing.avds.filter((avd) => !runningNames.has(avd.name)).map(avdLabel)\n  const emulators = [...running, ...idle]\n  return [\n    ...labelled('Attached:', attached),\n    ...labelled('Emulators:', [emulators.length === 0 ? 'none' : emulators.join(', ')]),\n  ]\n}\n\n// The Simulators line of `agent-qa devices`.\nexport function describeIOSHere(listing: IOSHere): string[] {\n  if (listing.problem !== undefined) return labelled('Simulators:', [listing.problem])\n  const simulators = listing.simulators\n    .filter((simulator) => simulator.available)\n    .map((simulator) =>\n      simulator.state === 'Booted'\n        ? `${simulator.name} (${simulator.os}, booted)`\n        : simulatorLabel(simulator),\n    )\n  return labelled('Simulators:', [simulators.length === 0 ? 'none' : simulators.join(', ')])\n}\n","import { isLoopbackHost } from '@vostride/agent-qa-schema'\n\nexport type AppiumEndpointChoice =\n  | { kind: 'remote' }\n  | { kind: 'given'; url: string }\n  | { kind: 'host-or-start' }\n  | { refusal: string }\n\nexport interface ChooseAppiumEndpointInput {\n  device: { name: string; remote?: unknown }\n  // The value of AGENT_QA_APPIUM_URL.\n  envUrl?: string\n}\n\nconst DEFAULT_PORTS: Record<string, string> = { 'http:': '80', 'https:': '443' }\n\n// A device with a remote uses it; a device here uses AGENT_QA_APPIUM_URL, else the host's Appium,\n// else the one agent-qa starts.\nexport function chooseAppiumEndpoint(input: ChooseAppiumEndpointInput): AppiumEndpointChoice {\n  if (input.device.remote !== undefined) return { kind: 'remote' }\n  const raw = input.envUrl?.trim()\n  if (raw === undefined || raw === '') return { kind: 'host-or-start' }\n  let url: URL\n  try {\n    url = new URL(raw)\n  } catch {\n    return {\n      refusal:\n        'AGENT_QA_APPIUM_URL is not a URL; set it to your Appium on this machine, ' +\n        'for example http://127.0.0.1:4723.',\n    }\n  }\n  const defaultPort = DEFAULT_PORTS[url.protocol]\n  if (defaultPort === undefined) {\n    return { refusal: 'AGENT_QA_APPIUM_URL must start with http:// or https://.' }\n  }\n  if (url.username !== '' || url.password !== '' || url.search !== '' || raw.includes('?')) {\n    return {\n      refusal:\n        'AGENT_QA_APPIUM_URL must not carry a user, password or query; ' +\n        'it names your own Appium on this machine.',\n    }\n  }\n  if (!isLoopbackHost(url.hostname)) {\n    return {\n      refusal:\n        `AGENT_QA_APPIUM_URL names ${url.hostname}, which is not this machine. ` +\n        \"List that server under registry.remotes with protocol: appium and set the device's remote to its name.\",\n    }\n  }\n  const port = url.port === '' ? defaultPort : url.port\n  return { kind: 'given', url: `${url.protocol}//${url.hostname}:${port}${url.pathname}` }\n}\n","import { scrollerSetSwipeSignal } from '@vostride/agent-qa-runner'\nimport type { Direction, DocumentScrollOffsets, SwipeSignal } from '@vostride/agent-qa-runner'\n\n// Judged over identified on-screen scrollers; a frame in view makes the read null.\n\n/** One WebView scroller with a structural identity: `document`, or a flat-tree path plus tag, id and class. */\nexport interface IdentifiedScrollOffsets extends DocumentScrollOffsets {\n  id: string\n}\n\n/**\n * A WebDriver `execute` function body. It answers `null` when a frame (`iframe`, `frame`, `embed`,\n * `object`, `fencedframe`) with positive area intersects the viewport, because a swipe over it\n * moves content the page cannot measure. Otherwise it answers the document scroller first (id\n * `document`), then every on-screen element scroller in the document and its open shadow roots,\n * in tree order. A body whose overflow propagates to the viewport is not a member. Nothing is\n * written to the page: ids derive from structure alone. Closed shadow roots are unreachable.\n */\nexport const WEBVIEW_SCROLLERS_SCRIPT: string =\n  'var d = document, w = window, s = d.scrollingElement || d.documentElement;'\n  + 'var vw = w.innerWidth, vh = w.innerHeight;'\n  + 'var frames = { IFRAME: 1, FRAME: 1, EMBED: 1, OBJECT: 1, FENCEDFRAME: 1 };'\n  + 'var sc = function (v) { return v === \"auto\" || v === \"scroll\" || v === \"overlay\"; };'\n  + 'var inView = function (el) {'\n  + ' var r = el.getBoundingClientRect();'\n  + ' return Math.min(r.right, vw) > Math.max(r.left, 0) && Math.min(r.bottom, vh) > Math.max(r.top, 0);'\n  + '};'\n  + 'var rs = getComputedStyle(d.documentElement);'\n  + 'var bodyPropagates = rs.overflowX === \"visible\" && rs.overflowY === \"visible\";'\n  + 'var out = [{ id: \"document\", x: w.scrollX, y: w.scrollY,'\n  + ' maxX: s.scrollWidth - s.clientWidth, maxY: s.scrollHeight - s.clientHeight }];'\n  + 'var stack = [{ el: d.documentElement, path: \"0\" }];'\n  + 'while (stack.length > 0) {'\n  + ' var item = stack.pop(), el = item.el, path = item.path;'\n  + ' var kids = [], i;'\n  + ' if (el.shadowRoot) { for (i = 0; i < el.shadowRoot.children.length; i++) kids.push({ el: el.shadowRoot.children[i], path: path + \"/s\" + i }); }'\n  + ' for (i = 0; i < el.children.length; i++) kids.push({ el: el.children[i], path: path + \"/\" + i });'\n  + ' for (i = kids.length - 1; i >= 0; i--) stack.push(kids[i]);'\n  + ' if (frames[String(el.tagName).toUpperCase()] && inView(el)) return null;'\n  + ' if (el === s || el === d.documentElement || (el === d.body && bodyPropagates)) continue;'\n  + ' var mx = el.scrollWidth - el.clientWidth, my = el.scrollHeight - el.clientHeight;'\n  + ' if (!(mx > 0 || my > 0)) continue;'\n  + ' var st = getComputedStyle(el);'\n  + ' var sx = mx > 0 && sc(st.overflowX), sy = my > 0 && sc(st.overflowY);'\n  + ' if ((!sx && !sy) || !inView(el)) continue;'\n  + ' out.push({ id: path + \"|\" + String(el.localName) + \"#\" + (el.getAttribute(\"id\") || \"\") + \".\" + (el.getAttribute(\"class\") || \"\"),'\n  + ' x: el.scrollLeft, y: el.scrollTop, maxX: sx ? mx : 0, maxY: sy ? my : 0 });'\n  + '}'\n  + 'return out;'\n\nfunction memberOf(value: unknown): IdentifiedScrollOffsets | undefined {\n  if (!value || typeof value !== 'object') return undefined\n  const { id, x, y, maxX, maxY } = value as Record<string, unknown>\n  if (typeof id !== 'string' || id.length === 0) return undefined\n  const offsets = [x, y, maxX, maxY]\n  if (!offsets.every((n) => typeof n === 'number' && Number.isFinite(n))) return undefined\n  return { id, x, y, maxX, maxY } as IdentifiedScrollOffsets\n}\n\nfunction byId(members: readonly unknown[]): Map<string, IdentifiedScrollOffsets> | undefined {\n  if (members.length === 0) return undefined\n  const map = new Map<string, IdentifiedScrollOffsets>()\n  for (const value of members) {\n    const member = memberOf(value)\n    if (!member || map.has(member.id)) return undefined\n    map.set(member.id, member)\n  }\n  return map\n}\n\n/** A non-empty array of members with string ids, finite offsets and no duplicate id; else undefined. */\nexport function parseWebViewScrollers(raw: unknown): IdentifiedScrollOffsets[] | undefined {\n  if (!Array.isArray(raw)) return undefined\n  const map = byId(raw)\n  return map ? [...map.values()] : undefined\n}\n\n/**\n * Before and after are paired by id. The same membership is judged by the scroller-set rule; a\n * changed membership is `moved` only when a member present in both reads moved, else `unknown`.\n */\nexport function webViewSwipeSignal(\n  direction: Direction,\n  before: readonly IdentifiedScrollOffsets[] | undefined,\n  after: readonly IdentifiedScrollOffsets[] | undefined,\n): SwipeSignal {\n  if (!before || !after) return 'unknown'\n  const b = byId(before)\n  const a = byId(after)\n  if (!b || !a) return 'unknown'\n  const common = [...b.keys()].filter((id) => a.has(id))\n  const signal = scrollerSetSwipeSignal(\n    direction,\n    common.map((id) => b.get(id)!),\n    common.map((id) => a.get(id)!),\n  )\n  const same = common.length === b.size && common.length === a.size\n  if (same) return signal\n  return signal === 'moved' ? 'moved' : 'unknown'\n}\n","import { existsSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nexport const DEFAULT_AGENT_QA_RUNTIME_DIR = '.agent-qa'\nexport const DEFAULT_AGENT_QA_ARTIFACTS_DIR = '.agent-qa/artifacts'\nexport const DEFAULT_AGENT_QA_CACHE_DIR = '.agent-qa/cache'\nexport const DEFAULT_AGENT_QA_AUTH_STATES_DIR = '.agent-qa/auth-states'\nexport const DEFAULT_AGENT_QA_SCREENSHOTS_DIR = '.agent-qa/artifacts/screenshots'\nexport const DEFAULT_AGENT_QA_VIDEOS_DIR = '.agent-qa/artifacts/videos'\nexport const DEFAULT_AGENT_QA_RUNS_DB_PATH = '.agent-qa/runs.db'\nexport const LEGACY_AGENT_QA_DASHBOARD_DB_PATH = '.agent-qa/dashboard.db'\n\n/**\n * The runs database a config names, without migrating anything: the configured path, else the\n * default, else a legacy dashboard.db nothing has renamed yet. The writer's resolver renames that\n * legacy file on top of this; the CLI reader binds only the configured or default path.\n */\nexport function locateRunsDbPath(configDir: string, configuredDbPath?: string): string {\n  const configured = configuredDbPath?.trim()\n  if (configured) return resolve(configDir, configured)\n  const defaultPath = resolve(configDir, DEFAULT_AGENT_QA_RUNS_DB_PATH)\n  const legacyPath = resolve(configDir, LEGACY_AGENT_QA_DASHBOARD_DB_PATH)\n  return !existsSync(defaultPath) && existsSync(legacyPath) ? legacyPath : defaultPath\n}\n","import path from 'node:path'\nimport { DEFAULT_AGENT_QA_AUTH_STATES_DIR } from '../runtime-paths.js'\nimport { AuthStateNameSchema, TargetNameSchema } from './schema.js'\n\nexport type AuthStateTargetPlatform = 'web' | 'android' | 'ios'\n\nexport interface ResolveAuthStatePathsInput {\n  configDir: string\n  authStateDir?: string\n  targetName: string\n  stateName: string\n  target?: {\n    platform: AuthStateTargetPlatform\n  }\n  platform?: AuthStateTargetPlatform\n}\n\nexport interface ResolvedAuthStatePaths {\n  targetName: string\n  stateName: string\n  rootDir: string\n  targetDir: string\n  payloadPath: string\n  metadataPath: string\n}\n\nexport interface ResolveAuthStateRootInput {\n  configDir: string\n  authStateDir?: string\n}\n\nconst MOBILE_AUTH_STATE_ERROR = [\n  'auth state is only supported for web targets.',\n  'For native mobile, use use.mobile.appState: preserve when keeping app data between sessions.',\n  'App-state preservation is broader than auth and does not export generic secure-storage/keychain tokens.',\n].join(' ')\n\nfunction assertInsideRoot(rootDir: string, filePath: string): void {\n  const relativePath = path.relative(rootDir, filePath)\n  if (!relativePath || relativePath.startsWith('..') || path.isAbsolute(relativePath)) {\n    throw new Error(`Resolved auth-state path escapes auth-state directory: ${filePath}`)\n  }\n}\n\nexport function resolveAuthStateRoot(input: ResolveAuthStateRootInput): string {\n  const { configDir, authStateDir } = input\n  const configuredDir = authStateDir ?? DEFAULT_AGENT_QA_AUTH_STATES_DIR\n  if (configuredDir.trim().length === 0) {\n    throw new Error('authState.dir must be a non-empty path')\n  }\n  return path.isAbsolute(configuredDir)\n    ? path.resolve(configuredDir)\n    : path.resolve(configDir, configuredDir)\n}\n\nexport function resolveAuthStatePaths(input: ResolveAuthStatePathsInput): ResolvedAuthStatePaths {\n  const targetName = TargetNameSchema.parse(input.targetName)\n  const stateName = AuthStateNameSchema.parse(input.stateName)\n  const platform = input.target?.platform ?? input.platform\n\n  if (platform !== 'web') {\n    throw new Error(MOBILE_AUTH_STATE_ERROR)\n  }\n\n  const rootDir = resolveAuthStateRoot({\n    configDir: input.configDir,\n    authStateDir: input.authStateDir,\n  })\n  const targetDir = path.join(rootDir, targetName)\n  const payloadPath = path.join(targetDir, `${stateName}.json`)\n  const metadataPath = path.join(targetDir, `${stateName}.meta.json`)\n\n  assertInsideRoot(rootDir, payloadPath)\n  assertInsideRoot(rootDir, metadataPath)\n\n  return {\n    targetName,\n    stateName,\n    rootDir,\n    targetDir,\n    payloadPath,\n    metadataPath,\n  }\n}\n","import { randomUUID } from 'node:crypto'\nimport type { Dirent } from 'node:fs'\nimport { mkdir, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises'\nimport path from 'node:path'\nimport { AuthStateMetadataSchema, TargetNameSchema, type AuthStateMetadata } from './schema.js'\nimport { resolveAuthStatePaths, resolveAuthStateRoot, type ResolvedAuthStatePaths } from './resolver.js'\n\nexport interface WriteAuthStateFilesInput {\n  payload: unknown\n  metadata: AuthStateMetadata\n}\n\nexport interface ListAuthStateMetadataInput {\n  configDir: string\n  authStateDir?: string\n  targetName?: string\n}\n\nexport interface RemoveAuthStateFilesInput {\n  configDir: string\n  authStateDir?: string\n  targetName: string\n  stateName: string\n  target?: Parameters<typeof resolveAuthStatePaths>[0]['target']\n  platform?: Parameters<typeof resolveAuthStatePaths>[0]['platform']\n}\n\nexport interface RemoveAuthStateTargetInput {\n  configDir: string\n  authStateDir?: string\n  targetName: string\n  target?: Parameters<typeof resolveAuthStatePaths>[0]['target']\n  platform?: Parameters<typeof resolveAuthStatePaths>[0]['platform']\n}\n\nfunction assertMetadataMatches(paths: ResolvedAuthStatePaths, metadata: AuthStateMetadata): void {\n  if (metadata.target !== paths.targetName) {\n    throw new Error(`Auth-state metadata target \"${metadata.target}\" does not match resolved target \"${paths.targetName}\"`)\n  }\n  if (metadata.name !== paths.stateName) {\n    throw new Error(`Auth-state metadata name \"${metadata.name}\" does not match resolved state \"${paths.stateName}\"`)\n  }\n}\n\nasync function writeJsonAtomic(filePath: string, value: unknown): Promise<void> {\n  const serialized = `${JSON.stringify(value, null, 2)}\\n`\n  const directory = path.dirname(filePath)\n  const tempPath = path.join(directory, `.${path.basename(filePath)}.${process.pid}.${randomUUID()}.tmp`)\n\n  await mkdir(directory, { recursive: true })\n  try {\n    await writeFile(tempPath, serialized, { mode: 0o600 })\n    await rename(tempPath, filePath)\n  } catch (error) {\n    await rm(tempPath, { force: true }).catch(() => undefined)\n    throw error\n  }\n}\n\nexport async function readAuthStateMetadata(paths: ResolvedAuthStatePaths): Promise<AuthStateMetadata> {\n  let raw: string\n  try {\n    raw = await readFile(paths.metadataPath, 'utf-8')\n  } catch (error) {\n    if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n      throw new Error(`Auth-state metadata not found: ${paths.metadataPath}`)\n    }\n    throw error\n  }\n\n  let parsed: unknown\n  try {\n    parsed = JSON.parse(raw)\n  } catch {\n    throw new Error(`Invalid auth-state metadata JSON: ${paths.metadataPath}`)\n  }\n\n  const result = AuthStateMetadataSchema.safeParse(parsed)\n  if (!result.success) {\n    throw new Error(`Invalid auth-state metadata: ${result.error.issues.map(issue => issue.message).join('; ')}`)\n  }\n\n  assertMetadataMatches(paths, result.data)\n  return result.data\n}\n\nexport async function writeAuthStateFiles(\n  paths: ResolvedAuthStatePaths,\n  input: WriteAuthStateFilesInput,\n): Promise<void> {\n  const metadata = AuthStateMetadataSchema.parse(input.metadata)\n  assertMetadataMatches(paths, metadata)\n\n  await writeJsonAtomic(paths.payloadPath, input.payload)\n  await writeJsonAtomic(paths.metadataPath, metadata)\n}\n\nexport async function listAuthStateMetadata(\n  input: ListAuthStateMetadataInput,\n): Promise<AuthStateMetadata[]> {\n  const rootDir = resolveAuthStateRoot({\n    configDir: input.configDir,\n    authStateDir: input.authStateDir,\n  })\n  const targetFilter = input.targetName ? TargetNameSchema.parse(input.targetName) : undefined\n\n  let targetEntries: Dirent<string>[]\n  try {\n    targetEntries = await readdir(rootDir, { withFileTypes: true })\n  } catch (error) {\n    if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n      return []\n    }\n    throw error\n  }\n\n  const metadata: AuthStateMetadata[] = []\n  for (const targetEntry of targetEntries) {\n    if (!targetEntry.isDirectory()) continue\n    const targetNameResult = TargetNameSchema.safeParse(targetEntry.name)\n    if (!targetNameResult.success) continue\n    const targetName = targetNameResult.data\n    if (targetFilter && targetName !== targetFilter) continue\n\n    let stateEntries: Dirent<string>[]\n    const targetDir = path.join(rootDir, targetName)\n    try {\n      stateEntries = await readdir(targetDir, { withFileTypes: true })\n    } catch {\n      continue\n    }\n\n    for (const stateEntry of stateEntries) {\n      if (!stateEntry.isFile() || !stateEntry.name.endsWith('.meta.json')) continue\n      const stateName = stateEntry.name.slice(0, -'.meta.json'.length)\n      const paths = (() => {\n        try {\n          return resolveAuthStatePaths({\n            configDir: input.configDir,\n            authStateDir: input.authStateDir,\n            targetName,\n            stateName,\n            platform: 'web',\n          })\n        } catch {\n          return null\n        }\n      })()\n      if (!paths) continue\n\n      try {\n        const entry = await readAuthStateMetadata(paths)\n        metadata.push(entry)\n      } catch {\n        continue\n      }\n    }\n  }\n\n  return metadata.sort((a, b) => {\n    const targetOrder = a.target.localeCompare(b.target)\n    return targetOrder === 0 ? a.name.localeCompare(b.name) : targetOrder\n  })\n}\n\nexport async function removeAuthStateFiles(input: RemoveAuthStateFilesInput): Promise<void> {\n  const paths = resolveAuthStatePaths(input)\n  await rm(paths.payloadPath, { force: true })\n  await rm(paths.metadataPath, { force: true })\n}\n\nexport async function removeAuthStateTarget(input: RemoveAuthStateTargetInput): Promise<void> {\n  const paths = resolveAuthStatePaths({\n    ...input,\n    stateName: 'placeholder',\n  })\n  await rm(paths.targetDir, { recursive: true, force: true })\n}\n","import { readFile } from 'node:fs/promises'\nimport { readAuthStateMetadata } from './store.js'\nimport {\n  resolveAuthStatePaths,\n  type AuthStateTargetPlatform,\n  type ResolvedAuthStatePaths,\n} from './resolver.js'\n\nexport interface ResolveAuthStateForRunInput {\n  configDir: string\n  authStateDir?: string\n  targetName: string\n  stateName: string\n  target?: {\n    platform: AuthStateTargetPlatform\n  }\n  platform?: AuthStateTargetPlatform\n}\n\nexport interface ResolvedAuthStateForRun {\n  version: number\n  kind: 'web'\n  targetName: string\n  stateName: string\n  capturedAt: string\n  storageStatePath: string\n}\n\nfunction createAuthStateReadError(targetName: string, stateName: string): Error {\n  return new Error(\n    `Auth state \"${stateName}\" for target \"${targetName}\" was not found or could not be read. ` +\n    `Run agent-qa auth-state capture --target ${targetName} --name ${stateName}.`,\n  )\n}\n\nasync function assertPayloadReadable(paths: ResolvedAuthStatePaths): Promise<void> {\n  const raw = await readFile(paths.payloadPath, 'utf-8')\n  JSON.parse(raw)\n}\n\nexport async function resolveAuthStateForRun(\n  input: ResolveAuthStateForRunInput,\n): Promise<ResolvedAuthStateForRun> {\n  const paths = resolveAuthStatePaths(input)\n\n  try {\n    const metadata = await readAuthStateMetadata(paths)\n    await assertPayloadReadable(paths)\n    return {\n      version: metadata.version,\n      kind: metadata.kind,\n      targetName: metadata.target,\n      stateName: metadata.name,\n      capturedAt: metadata.capturedAt,\n      storageStatePath: paths.payloadPath,\n    }\n  } catch {\n    throw createAuthStateReadError(paths.targetName, paths.stateName)\n  }\n}\n","import { randomUUID } from 'node:crypto'\nimport {\n  readFile,\n  writeFile,\n  mkdir,\n  unlink,\n  rename,\n  rm,\n  lstat,\n  realpath,\n  readlink,\n} from 'node:fs/promises'\nimport { basename, dirname, join, resolve } from 'node:path'\nimport { homedir } from 'node:os'\nimport type { AuthCredential, AuthStore } from './types.js'\n\nexport function getAuthPath(options?: { env?: NodeJS.ProcessEnv; homeDir?: string }): string {\n  const xdg = (options?.env ?? process.env).XDG_DATA_HOME\n  if (xdg) return join(xdg, 'agent-qa', 'auth.json')\n  return join(options?.homeDir ?? homedir(), '.agent-qa', 'auth.json')\n}\n\nfunction isMissingFile(error: unknown): boolean {\n  return (error as NodeJS.ErrnoException | null)?.code === 'ENOENT'\n}\n\nasync function isSymlink(authPath: string): Promise<boolean> {\n  return lstat(authPath).then(\n    stats => stats.isSymbolicLink(),\n    (error: unknown) => {\n      if (isMissingFile(error)) return false\n      throw error\n    },\n  )\n}\n\n// A symlinked auth.json keeps its link: the file it points at is the one replaced, the same rule\n// ConfigManager.writeTarget applies to the config file.\nasync function authWriteTarget(authPath: string): Promise<string> {\n  if (!(await isSymlink(authPath))) return authPath\n  try {\n    return await realpath(authPath)\n  } catch (error) {\n    if (!isMissingFile(error)) throw error\n    return resolve(dirname(authPath), await readlink(authPath))\n  }\n}\n\nasync function writeStoreAtomic(authPath: string, store: AuthStore): Promise<void> {\n  const target = await authWriteTarget(authPath)\n  const directory = dirname(target)\n  const tempPath = join(directory, `.${basename(target)}.${process.pid}.${randomUUID()}.tmp`)\n  await mkdir(directory, { recursive: true })\n  try {\n    await writeFile(tempPath, JSON.stringify(store, null, 2), { mode: 0o600 })\n    await rename(tempPath, target)\n  } catch (error) {\n    await rm(tempPath, { force: true }).catch(() => undefined)\n    throw error\n  }\n}\n\nexport async function readAuth(path?: string): Promise<AuthStore> {\n  const authPath = path ?? getAuthPath()\n  try {\n    const data = await readFile(authPath, 'utf-8')\n    return JSON.parse(data) as AuthStore\n  } catch {\n    return {}\n  }\n}\n\nexport type SavedCredential =\n  | {\n    name: string\n    type: 'oauth'\n    provider: string\n    signIn: { renews: boolean; expires?: number; signedInAt?: number }\n  }\n  | { name: string; type: 'api' | 'bearer'; provider: string }\n\nconst SAVED_CREDENTIAL_TYPES: ReadonlySet<string> = new Set(['oauth', 'api', 'bearer'])\n\nfunction finiteNumber(value: unknown): number | undefined {\n  return typeof value === 'number' && Number.isFinite(value) ? value : undefined\n}\n\nfunction signInOf(entry: object): Extract<SavedCredential, { type: 'oauth' }>['signIn'] {\n  const { tokens, signedInAt } = entry as { tokens?: unknown; signedInAt?: unknown }\n  const held =\n    typeof tokens === 'object' && tokens !== null\n      ? (tokens as { refresh?: unknown; expires?: unknown })\n      : {}\n  const expires = finiteNumber(held.expires)\n  const at = finiteNumber(signedInAt)\n  return {\n    renews: typeof held.refresh === 'string' && held.refresh !== '',\n    ...(expires === undefined ? {} : { expires }),\n    ...(at === undefined ? {} : { signedInAt: at }),\n  }\n}\n\n// The name, kind and provider leave, and for a sign-in its stored times and whether it holds a\n// refresh token; a key or token never does.\nexport async function listSavedCredentials(path?: string): Promise<SavedCredential[]> {\n  const store: unknown = await readAuth(path)\n  if (typeof store !== 'object' || store === null || Array.isArray(store)) return []\n  const saved: SavedCredential[] = []\n  for (const [name, entry] of Object.entries(store)) {\n    if (typeof entry !== 'object' || entry === null) continue\n    const { type, provider } = entry as { type?: unknown; provider?: unknown }\n    if (typeof type !== 'string' || !SAVED_CREDENTIAL_TYPES.has(type)) continue\n    if (typeof provider !== 'string') continue\n    saved.push(\n      type === 'oauth'\n        ? { name, type, provider, signIn: signInOf(entry) }\n        : { name, type: type as 'api' | 'bearer', provider },\n    )\n  }\n  return saved\n}\n\nexport async function writeAuth(\n  provider: string,\n  credential: AuthCredential,\n  path?: string,\n): Promise<void> {\n  const authPath = path ?? getAuthPath()\n  const store = await readAuth(authPath)\n  store[provider] = credential\n  await writeStoreAtomic(authPath, store)\n}\n\nexport async function removeAuth(provider: string, path?: string): Promise<void> {\n  const authPath = path ?? getAuthPath()\n  const store = await readAuth(authPath)\n  delete store[provider]\n  if (Object.keys(store).length === 0 && !(await isSymlink(authPath))) {\n    try {\n      await unlink(authPath)\n    } catch {\n      // file already gone\n    }\n    return\n  }\n  await writeStoreAtomic(authPath, store)\n}\n\nexport async function getCredential(\n  provider: string,\n  path?: string,\n): Promise<AuthCredential | null> {\n  const store = await readAuth(path)\n  return store[provider] ?? null\n}\n","import type { LLMModelAdapter, OAuthTokens } from './types.js'\n\nexport type DashboardAuthMode = 'browser-poll' | 'manual-code'\n\nexport interface DashboardAuthMetadata {\n  mode: DashboardAuthMode\n  buttonLabel?: string\n}\n\nexport interface StartAuthContext {\n  configName: string\n  callbackUrl?: string\n}\n\nexport interface StartAuthResult {\n  authorizeUrl: string\n  sessionState?: unknown\n  waitForTokens?: Promise<OAuthTokens>\n  cleanup?: () => void\n}\n\nexport interface ExchangeCodeContext {\n  code: string\n  sessionState: unknown\n}\n\nexport interface CreateAuthFetchContext {\n  getTokens: () => Promise<OAuthTokens>\n  onRefreshed: (tokens: OAuthTokens) => Promise<void>\n}\n\nexport interface LLMAuthProviderPlugin {\n  providerId: string\n  credentialProviderId: string\n  label: string\n  modelAdapter: LLMModelAdapter\n  dashboardAuth: DashboardAuthMetadata\n  startAuth?: (ctx: StartAuthContext) => Promise<StartAuthResult>\n  exchangeCode?: (ctx: ExchangeCodeContext) => Promise<OAuthTokens>\n  createAuthFetch: (ctx: CreateAuthFetchContext) => typeof globalThis.fetch\n}\n\nconst plugins = new Map<string, LLMAuthProviderPlugin>()\n\nfunction validatePlugin(plugin: LLMAuthProviderPlugin): void {\n  if (!plugin.providerId.trim()) {\n    throw new Error('LLM auth plugin providerId is required')\n  }\n  if (!plugin.credentialProviderId.trim()) {\n    throw new Error(`LLM auth plugin \"${plugin.providerId}\" credentialProviderId is required`)\n  }\n  if (!plugin.label.trim()) {\n    throw new Error(`LLM auth plugin \"${plugin.providerId}\" label is required`)\n  }\n}\n\nexport function registerLLMAuthProviderPlugin(plugin: LLMAuthProviderPlugin): void {\n  validatePlugin(plugin)\n  if (plugins.has(plugin.providerId)) {\n    throw new Error(`LLM auth provider plugin \"${plugin.providerId}\" is already registered`)\n  }\n  plugins.set(plugin.providerId, plugin)\n}\n\nexport function registerLLMAuthProviderPlugins(providerPlugins: LLMAuthProviderPlugin[]): void {\n  for (const plugin of providerPlugins) {\n    registerLLMAuthProviderPlugin(plugin)\n  }\n}\n\nexport function getLLMAuthProviderPlugin(providerId: string): LLMAuthProviderPlugin | undefined {\n  return plugins.get(providerId)\n}\n\nexport function listLLMAuthProviderPlugins(): LLMAuthProviderPlugin[] {\n  return [...plugins.values()]\n}\n\nexport function clearLLMAuthProviderPlugins(): void {\n  plugins.clear()\n}\n","import { pluginsAddLine } from '../plugin-loader-util.js'\nimport { getLLMAuthProviderPlugin, type LLMAuthProviderPlugin } from './plugin-registry.js'\nimport { getCredential, writeAuth } from './store.js'\nimport type { AuthCredential, LLMProviderMode, OAuthTokens, ResolvedLLMAuth } from './types.js'\n\ninterface LLMAuthConfig {\n  provider: LLMProviderMode | string\n  model: string\n  baseURL?: string\n  providerHeaders?: Record<string, string>\n}\n\nconst SUBSCRIPTION_AUTH_PACKAGE = '@vostride/agent-qa-subscription-auth'\n\nexport const PUBLIC_PROVIDER_API_HOSTS: readonly string[] = Object.freeze([\n  'api.openai.com',\n  'api.anthropic.com',\n])\n\nfunction onPublicProviderApi(baseURL: string | undefined): boolean {\n  if (typeof baseURL !== 'string' || !URL.canParse(baseURL)) return false\n  return PUBLIC_PROVIDER_API_HOSTS.includes(new URL(baseURL).hostname)\n}\n\nfunction missingMessage(\n  configName: string,\n  provider: string,\n  plugin?: LLMAuthProviderPlugin,\n  configPath?: string,\n): string {\n  if (plugin) {\n    return `Sign in to \"${plugin.label}\" for the \"${configName}\" config: agent-qa auth login --config ${configName}`\n  }\n\n  const setKey = `agent-qa auth set --config ${configName} --type api-key`\n  switch (provider) {\n    case 'gemini':\n      return `Save a Gemini API key for the \"${configName}\" config: ${setKey}`\n    case 'openai-compatible':\n      return `Save an API key for the \"${configName}\" config: ${setKey}`\n    case 'anthropic-compatible':\n      return `Save an API key for the \"${configName}\" config: ${setKey} (or --type bearer-token)`\n    case 'openai-subscription':\n    case 'anthropic-subscription':\n      return `Provider \"${provider}\" needs the subscription-auth plugin: run ${pluginsAddLine(SUBSCRIPTION_AUTH_PACKAGE, configPath)}.`\n    default:\n      return `Provider \"${provider}\" requires an auth plugin.`\n  }\n}\n\nfunction unauthenticated(configName: string, provider: 'openai-compatible' | 'anthropic-compatible'): ResolvedLLMAuth {\n  return {\n    kind: 'unauthenticated',\n    credentialKey: configName,\n    provider,\n    optional: true,\n    message: 'Testing without a saved credential.',\n  }\n}\n\nfunction isCompatibleProvider(provider: string): provider is 'openai-compatible' | 'anthropic-compatible' {\n  return provider === 'openai-compatible' || provider === 'anthropic-compatible'\n}\n\nfunction usesApiKey(\n  provider: string,\n  plugin?: LLMAuthProviderPlugin,\n): provider is 'openai-compatible' | 'anthropic-compatible' | 'gemini' {\n  return !plugin && (provider === 'openai-compatible' || provider === 'anthropic-compatible' || provider === 'gemini')\n}\n\nfunction unusableCredential(\n  configName: string,\n  provider: string,\n  plugin?: LLMAuthProviderPlugin,\n  configPath?: string,\n): ResolvedLLMAuth {\n  return isCompatibleProvider(provider)\n    ? unauthenticated(configName, provider)\n    : missing(configName, provider, plugin, configPath)\n}\n\nfunction missing(\n  configName: string,\n  provider: string,\n  plugin?: LLMAuthProviderPlugin,\n  configPath?: string,\n): ResolvedLLMAuth {\n  return {\n    kind: 'missing',\n    credentialKey: configName,\n    provider,\n    required: true,\n    message: missingMessage(configName, provider, plugin, configPath),\n  }\n}\n\nfunction getOAuthTokens(\n  configName: string,\n  expectedProvider: string,\n  authPath?: string,\n): () => Promise<OAuthTokens> {\n  return async () => {\n    const credential = await getCredential(configName, authPath)\n    if (credential?.type !== 'oauth' || credential.provider !== expectedProvider) {\n      throw new Error(`Expected ${expectedProvider} OAuth credential for ${configName}`)\n    }\n    return credential.tokens\n  }\n}\n\nfunction writeRefreshedOAuth(\n  configName: string,\n  expectedProvider: string,\n  authPath?: string,\n): (tokens: OAuthTokens) => Promise<void> {\n  return async (tokens) => {\n    const current = await getCredential(configName, authPath)\n    if (current?.type !== 'oauth' || current.provider !== expectedProvider) {\n      throw new Error(`Expected ${expectedProvider} OAuth credential for ${configName}`)\n    }\n    await writeAuth(configName, { ...current, tokens }, authPath)\n  }\n}\n\nfunction authFetch(\n  configName: string,\n  plugin: LLMAuthProviderPlugin,\n  credential: Extract<AuthCredential, { type: 'oauth' }>,\n  authPath?: string,\n): ResolvedLLMAuth {\n  const expectedProvider = plugin.credentialProviderId\n  const getTokens = getOAuthTokens(configName, expectedProvider, authPath)\n  const onRefreshed = writeRefreshedOAuth(configName, expectedProvider, authPath)\n\n  return {\n    kind: 'auth-fetch',\n    credentialKey: configName,\n    provider: plugin.providerId,\n    modelAdapter: plugin.modelAdapter,\n    fetch: plugin.createAuthFetch({ getTokens, onRefreshed }),\n    expires: credential.tokens.expires,\n  }\n}\n\n// configPath is the config the person named; the plugin fix line carries it when not the default.\nexport async function resolveLLMAuth(\n  configName: string,\n  llmConfig: LLMAuthConfig,\n  authPath?: string,\n  configPath?: string,\n): Promise<ResolvedLLMAuth> {\n  const credential = await getCredential(configName, authPath)\n  const plugin = getLLMAuthProviderPlugin(llmConfig.provider)\n\n  if (!credential) {\n    // A keyless config on the public provider API cannot run.\n    if (isCompatibleProvider(llmConfig.provider) && !onPublicProviderApi(llmConfig.baseURL)) {\n      return unauthenticated(configName, llmConfig.provider)\n    }\n    return missing(configName, llmConfig.provider, plugin, configPath)\n  }\n\n  if (credential.type === 'api') {\n    if (credential.provider !== llmConfig.provider) {\n      return unusableCredential(configName, llmConfig.provider, plugin, configPath)\n    }\n    if (!usesApiKey(llmConfig.provider, plugin)) {\n      return missing(configName, llmConfig.provider, plugin, configPath)\n    }\n    return {\n      kind: 'api-key',\n      credentialKey: configName,\n      provider: llmConfig.provider,\n      apiKey: credential.key,\n    }\n  }\n\n  if (credential.type === 'bearer') {\n    if (credential.provider !== llmConfig.provider || llmConfig.provider !== 'anthropic-compatible') {\n      return unusableCredential(configName, llmConfig.provider, plugin, configPath)\n    }\n    return {\n      kind: 'bearer-token',\n      credentialKey: configName,\n      provider: 'anthropic-compatible',\n      token: credential.token,\n    }\n  }\n\n  if (credential.type === 'oauth') {\n    if (plugin) {\n      if (credential.provider !== plugin.credentialProviderId) {\n        return missing(configName, llmConfig.provider, plugin, configPath)\n      }\n      return authFetch(configName, plugin, credential, authPath)\n    }\n    return unusableCredential(configName, llmConfig.provider, undefined, configPath)\n  }\n\n  return missing(configName, llmConfig.provider, plugin, configPath)\n}\n","import path from 'node:path'\n\nexport function isPathInsideDir(childPath: string, parentDir: string): boolean {\n  if (!childPath) return false\n  const resolved = path.resolve(parentDir, childPath)\n  const relative = path.relative(parentDir, resolved)\n  return !!relative && !relative.startsWith('..') && !path.isAbsolute(relative)\n}\n","import { existsSync, readFileSync, realpathSync } from 'node:fs'\nimport { basename, dirname, join, resolve } from 'node:path'\n\nimport {\n  PLUGIN_MANIFEST_FIELD,\n  PluginManifestSchema,\n  type PluginManifest,\n} from '@vostride/agent-qa-plugin-kit/protocol'\n\nimport { exportTargetFromPackageJson } from '../plugin-loader-util.js'\nimport { isPathInsideDir } from '../utils/path-validation.js'\n\nexport const SUBSCRIPTION_AUTH_PACKAGE = '@vostride/agent-qa-subscription-auth'\n\nexport type PluginManifestRead =\n  | { ok: true; manifest: PluginManifest; name: string; version: string; packageDir: string }\n  | { ok: false; issue: string; name?: string; version?: string; packageDir: string }\n\nconst MANIFEST_POSITION = `${PLUGIN_MANIFEST_FIELD}.plugin`\nconst MANIFEST_PATH_FIELDS = ['entry', 'options', 'settings', 'skill'] as const\n\n// A file that does not exist yet still resolves through its nearest existing folder.\nfunction realpathOfNearest(target: string): string {\n  let current = target\n  const rest: string[] = []\n  while (!existsSync(current)) {\n    const parent = dirname(current)\n    if (parent === current) return target\n    rest.unshift(basename(current))\n    current = parent\n  }\n  return join(realpathSync(current), ...rest)\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction issuePosition(issue: { path: PropertyKey[]; code: string; keys?: string[] }): string {\n  const path = issue.path.map(String)\n  if (issue.code === 'unrecognized_keys' && issue.keys?.[0]) path.push(issue.keys[0])\n  return [MANIFEST_POSITION, ...path].join('.')\n}\n\nfunction declaredManifest(pkg: Record<string, unknown>, name: string): unknown {\n  const field = pkg[PLUGIN_MANIFEST_FIELD]\n  if (field === undefined && name === SUBSCRIPTION_AUTH_PACKAGE) {\n    const entry = exportTargetFromPackageJson(pkg)\n    return entry ? { kind: 'model-auth', runs: 'in-process', entry } : undefined\n  }\n  return isRecord(field) ? field.plugin : undefined\n}\n\nexport function readPluginManifest(packageJsonPath: string): PluginManifestRead {\n  const packageDir = dirname(packageJsonPath)\n  let pkg: unknown\n  try {\n    pkg = JSON.parse(readFileSync(packageJsonPath, 'utf-8'))\n  } catch {\n    return { ok: false, issue: 'package.json is not readable JSON', packageDir }\n  }\n  if (!isRecord(pkg)) return { ok: false, issue: 'package.json is not an object', packageDir }\n\n  const name = typeof pkg.name === 'string' ? pkg.name : ''\n  const version = typeof pkg.version === 'string' ? pkg.version : ''\n  const declared = declaredManifest(pkg, name)\n  if (declared === undefined) {\n    return { ok: false, issue: `${MANIFEST_POSITION} is missing`, name, version, packageDir }\n  }\n\n  const parsed = PluginManifestSchema.safeParse(declared)\n  if (!parsed.success) {\n    const first = parsed.error.issues[0]\n    const issue = first ? issuePosition(first) : MANIFEST_POSITION\n    return { ok: false, issue, name, version, packageDir }\n  }\n\n  const realPackageDir = realpathSync(packageDir)\n  const manifest = parsed.data\n  const fields: Record<string, unknown> = manifest\n  for (const field of MANIFEST_PATH_FIELDS) {\n    const value = fields[field]\n    if (typeof value !== 'string') continue\n    const real = realpathOfNearest(resolve(realPackageDir, value))\n    if (!isPathInsideDir(real, realPackageDir)) {\n      const issue = `${field} resolves outside the package`\n      return { ok: false, issue, name, version, packageDir }\n    }\n  }\n\n  return { ok: true, manifest, name, version, packageDir }\n}\n","import { existsSync, realpathSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\n\nimport {\n  PLUGIN_PROTOCOL_VERSION,\n  type PluginManifest,\n} from '@vostride/agent-qa-plugin-kit/protocol'\n\nimport {\n  declarationLabel,\n  findPackageJson,\n  isNpmPackageName,\n  packageDeclarationValue,\n  pathDeclarationValue,\n  pluginsAddLine,\n} from '../plugin-loader-util.js'\nimport { isPathInsideDir } from '../utils/path-validation.js'\nimport { readPluginManifest } from './manifest.js'\n\nexport type PluginOrigin = 'first-party' | 'third-party' | 'path'\n\nexport type PluginEntryState =\n  | 'ok'\n  | 'not_installed'\n  | 'version_mismatch'\n  | 'protocol_mismatch'\n  | 'bad_manifest'\n  | 'unused'\n\nexport interface PluginEntryInput {\n  name: string\n  package?: string\n  path?: string\n  options?: unknown\n}\n\nexport interface PluginRemoteInput {\n  name: string\n  plugin?: string\n}\n\nexport interface ResolvePluginEntryOptions {\n  configDir: string\n  // The config the person named; fix lines carry it when it is not the default.\n  configPath?: string\n  agentQaVersion: string\n  protocols?: { current: number }\n}\n\nexport interface ResolvedPluginEntry {\n  name: string\n  label: string\n  origin: PluginOrigin\n  state: PluginEntryState\n  reason?: string\n  install?: string\n  packageDir?: string\n  packageJsonPath?: string\n  version?: string\n  manifest?: PluginManifest\n  inProcess: boolean\n}\n\nexport type InProcessPluginKind = 'model-auth' | 'model-provider'\n\nexport interface InProcessRefusal {\n  entry: string\n  state: 'not_installed' | 'version_mismatch' | 'bad_manifest'\n  reason: string\n}\n\nexport interface InProcessSelection {\n  load: ResolvedPluginEntry[]\n  refusals: InProcessRefusal[]\n}\n\nconst FIRST_PARTY_PREFIX = '@vostride/agent-qa-'\nconst FIRST_PARTY_PLUGIN_PREFIX = '@vostride/agent-qa-plugin-'\n\nexport function supportedPluginProtocols(current: number = PLUGIN_PROTOCOL_VERSION): number[] {\n  return [current, current - 1].filter((protocol) => protocol >= 1)\n}\n\nexport function pluginInstallLine(\n  entry: PluginEntryInput,\n  configPath?: string,\n): string | undefined {\n  const packageName = packageDeclarationValue(entry)\n  // A person runs this line, so it is only ever built from an npm name.\n  if (!isNpmPackageName(packageName)) return undefined\n  return pluginsAddLine(packageName, configPath)\n}\n\nfunction pluginOrigin(entry: PluginEntryInput): PluginOrigin {\n  const packageName = packageDeclarationValue(entry)\n  if (!packageName) return 'path'\n  return packageName.startsWith(FIRST_PARTY_PREFIX) && isNpmPackageName(packageName)\n    ? 'first-party'\n    : 'third-party'\n}\n\nfunction packageJsonInsideProject(declaredPath: string, configDir: string): string | undefined {\n  const target = resolve(configDir, declaredPath)\n  const packageJsonPath = join(target, 'package.json')\n  if (!existsSync(packageJsonPath)) return undefined\n  const realTarget = realpathSync(target)\n  if (!isPathInsideDir(realTarget, realpathSync(configDir))) return undefined\n  return join(realTarget, 'package.json')\n}\n\nexport function resolvePluginEntry(\n  entry: PluginEntryInput,\n  options: ResolvePluginEntryOptions,\n): ResolvedPluginEntry {\n  const { configDir, agentQaVersion } = options\n  const origin = pluginOrigin(entry)\n  const label = declarationLabel(entry, configDir)\n  const install = pluginInstallLine(entry, options.configPath)\n  const base = { name: entry.name, label, origin, inProcess: false }\n\n  let packageJsonPath: string | undefined\n  if (origin === 'path') {\n    packageJsonPath = packageJsonInsideProject(pathDeclarationValue(entry), configDir)\n    if (!packageJsonPath) {\n      return {\n        ...base,\n        state: 'not_installed',\n        reason:\n          `Plugin entry ${entry.name} names the path ${label}, which has no package.json inside `\n          + 'this project. Fix the path in plugins, or make the plugin a workspace package and '\n          + 'name it with package.',\n      }\n    }\n  } else {\n    packageJsonPath = findPackageJson(packageDeclarationValue(entry), configDir) ?? undefined\n    if (!packageJsonPath) {\n      if (install === undefined) {\n        return {\n          ...base,\n          state: 'not_installed',\n          reason:\n            `Plugin entry ${entry.name} names a package that is not an npm package name. Fix `\n            + 'package in plugins, or name a folder with path.',\n        }\n      }\n      return {\n        ...base,\n        state: 'not_installed',\n        reason:\n          `Plugin entry ${entry.name} names ${label}, which is not installed. Run ${install}.`,\n        install,\n      }\n    }\n  }\n\n  const read = readPluginManifest(packageJsonPath)\n  const found = {\n    ...base,\n    packageDir: read.packageDir,\n    packageJsonPath,\n    ...(read.version === undefined ? {} : { version: read.version }),\n  }\n\n  // An npm alias installs another package under the declared name; its origin is not the name's.\n  if (origin !== 'path' && read.name !== undefined && read.name !== label) {\n    return {\n      ...found,\n      state: 'bad_manifest',\n      reason:\n        `Plugin entry ${entry.name} names ${label}, but the package installed under that name is `\n        + `${read.name === '' ? 'unnamed' : read.name}. Install ${label} itself, not an alias.`,\n    }\n  }\n\n  if (\n    install !== undefined\n    && label.startsWith(FIRST_PARTY_PLUGIN_PREFIX)\n    && read.version !== undefined\n    && read.version !== agentQaVersion\n  ) {\n    return {\n      ...found,\n      state: 'version_mismatch',\n      reason:\n        `Plugin entry ${entry.name} names ${label} at ${read.version}, and agent-qa is at `\n        + `${agentQaVersion}. Run ${install}.`,\n      install,\n    }\n  }\n\n  if (!read.ok) {\n    return {\n      ...found,\n      state: 'bad_manifest',\n      reason:\n        `Plugin entry ${entry.name} names ${label}, whose package.json has no valid agent-qa `\n        + `plugin manifest (${read.issue}). Fix the plugin's manifest.`,\n    }\n  }\n\n  const manifest = read.manifest\n  const resolved = { ...found, manifest, inProcess: manifest.runs === 'in-process' }\n\n  if (manifest.runs === 'in-process' && origin !== 'first-party') {\n    return {\n      ...resolved,\n      state: 'bad_manifest',\n      reason:\n        `Plugin entry ${entry.name} names ${label}, which declares a ${manifest.kind} plugin; `\n        + `only ${FIRST_PARTY_PREFIX}* packages load inside agent-qa. Remove the entry.`,\n    }\n  }\n\n  if (manifest.kind === 'remote' && origin !== 'first-party') {\n    const current = options.protocols?.current ?? PLUGIN_PROTOCOL_VERSION\n    const window = supportedPluginProtocols(current)\n    const speaks =\n      `Plugin entry ${entry.name} names ${label}, which speaks plugin protocol ${manifest.protocol}`\n    if (manifest.protocol > current) {\n      return {\n        ...resolved,\n        state: 'protocol_mismatch',\n        reason: `${speaks}, newer than this agent-qa's ${current}. Update agent-qa.`,\n      }\n    }\n    if (!window.includes(manifest.protocol)) {\n      return {\n        ...resolved,\n        state: 'protocol_mismatch',\n        reason:\n          `${speaks}; this agent-qa speaks ${window.join(' and ')}. Rebuild the plugin with `\n          + `@vostride/agent-qa-plugin-kit@${agentQaVersion}.`,\n      }\n    }\n  }\n\n  return { ...resolved, state: 'ok' }\n}\n\nexport function resolvePluginEntries(\n  config: { plugins: readonly PluginEntryInput[]; remotes?: readonly PluginRemoteInput[] },\n  options: ResolvePluginEntryOptions,\n): ResolvedPluginEntry[] {\n  const named = new Set((config.remotes ?? []).map((remote) => remote.plugin))\n  return config.plugins.map((entry) => {\n    const resolved = resolvePluginEntry(entry, options)\n    if (resolved.state !== 'ok' || resolved.manifest?.kind !== 'remote') return resolved\n    if (named.has(entry.name)) return resolved\n    return {\n      ...resolved,\n      state: 'unused',\n      reason:\n        `Plugin entry ${entry.name} is used by no remote. Name it from a remote in `\n        + 'registry.remotes, or remove it.',\n    }\n  })\n}\n\n// An entry whose kind cannot be read, because it is missing, at the wrong version or unreadable,\n// is refused unless a remote names it; run start refuses those for the remotes that use them.\nexport function selectInProcessPluginEntries(\n  entries: readonly PluginEntryInput[],\n  kind: InProcessPluginKind,\n  options: ResolvePluginEntryOptions,\n  remotes: readonly PluginRemoteInput[] = [],\n): InProcessSelection {\n  const named = new Set(remotes.map((remote) => remote.plugin))\n  const selection: InProcessSelection = { load: [], refusals: [] }\n  for (const entry of entries) {\n    const resolved = resolvePluginEntry(entry, options)\n    const ofKind = resolved.manifest?.kind === kind\n    if (resolved.state === 'ok' && ofKind) {\n      selection.load.push(resolved)\n    } else if (resolved.state === 'bad_manifest' && ofKind) {\n      selection.refusals.push(refusal(resolved, 'bad_manifest'))\n    } else if (\n      resolved.manifest === undefined\n      && isRefusedState(resolved.state)\n      && !named.has(entry.name)\n    ) {\n      selection.refusals.push(refusal(resolved, resolved.state))\n    }\n  }\n  return selection\n}\n\nfunction isRefusedState(state: PluginEntryState): state is InProcessRefusal['state'] {\n  return state === 'not_installed' || state === 'version_mismatch' || state === 'bad_manifest'\n}\n\nfunction refusal(\n  resolved: ResolvedPluginEntry,\n  state: InProcessRefusal['state'],\n): InProcessRefusal {\n  return { entry: resolved.name, state, reason: resolved.reason ?? '' }\n}\n","import { createRequire } from 'node:module'\n\nconst require = createRequire(typeof __filename === 'string' ? __filename : import.meta.url)\n\nfunction readPackageVersion(): string {\n  try {\n    const manifest = require('../package.json') as { version?: unknown }\n    if (typeof manifest.version === 'string' && manifest.version.trim()) {\n      return manifest.version.trim()\n    }\n  } catch {\n    // Keep public version consumers non-throwing if package metadata is unavailable.\n  }\n\n  return '0.0.0'\n}\n\nexport const AGENT_QA_VERSION = readPackageVersion()\n\nexport function getAgentQaVersion(): string {\n  return AGENT_QA_VERSION\n}\n","import { registerLLMAuthProviderPlugins, type LLMAuthProviderPlugin } from './plugin-registry.js'\nimport {\n  PluginNotInstalledError,\n  declarationKey,\n  importDeclaredPluginModule,\n  packageDeclarationValue,\n} from '../plugin-loader-util.js'\nimport { SUBSCRIPTION_AUTH_PACKAGE } from '../plugins/manifest.js'\nimport {\n  selectInProcessPluginEntries,\n  type PluginRemoteInput,\n} from '../plugins/resolve-entries.js'\nimport type { PluginEntry } from '../schema/config-schema.js'\nimport { getAgentQaVersion } from '../version.js'\n\nexport interface AuthPluginBundle {\n  providers: LLMAuthProviderPlugin[]\n}\n\nexport interface LoadLLMAuthPluginsOptions {\n  baseDir?: string\n  // The config's registry.remotes; an entry one of them names is refused at run start instead.\n  remotes?: readonly PluginRemoteInput[]\n  // The config the person named; fix lines carry it when it is not the default.\n  configPath?: string\n}\n\ntype AuthPluginFactory = () => AuthPluginBundle | Promise<AuthPluginBundle>\ntype AuthPluginModule = {\n  createSubscriptionAuthPlugin?: AuthPluginFactory\n  createAuthPlugin?: AuthPluginFactory\n  default?: AuthPluginFactory | AuthPluginBundle | AuthPluginModule\n  providers?: LLMAuthProviderPlugin[]\n}\n\nconst loadedDeclarations = new Set<string>()\n\nasync function resolvePluginBundle(module: AuthPluginModule, source: string): Promise<AuthPluginBundle> {\n  if (typeof module.createSubscriptionAuthPlugin === 'function') {\n    return await module.createSubscriptionAuthPlugin()\n  }\n  if (typeof module.createAuthPlugin === 'function') {\n    return await module.createAuthPlugin()\n  }\n  if (typeof module.default === 'function') {\n    return await module.default()\n  }\n  if (module.default && typeof module.default === 'object') {\n    const defaultModule = module.default as AuthPluginModule\n    if (typeof defaultModule.createSubscriptionAuthPlugin === 'function') {\n      return await defaultModule.createSubscriptionAuthPlugin()\n    }\n    if (typeof defaultModule.createAuthPlugin === 'function') {\n      return await defaultModule.createAuthPlugin()\n    }\n  }\n  if (module.default && typeof module.default === 'object' && Array.isArray(module.default.providers)) {\n    return { providers: module.default.providers }\n  }\n  if (Array.isArray(module.providers)) {\n    return { providers: module.providers }\n  }\n  throw new Error(`Auth plugin \"${source}\" must export createSubscriptionAuthPlugin(), createAuthPlugin(), default, or providers.`)\n}\n\nexport async function loadLLMAuthPlugins(\n  entries: readonly PluginEntry[] | undefined,\n  options: LoadLLMAuthPluginsOptions = {},\n): Promise<LLMAuthProviderPlugin[]> {\n  if (!entries?.length) return []\n  const baseDir = options.baseDir ?? process.cwd()\n  const { load, refusals } = selectInProcessPluginEntries(\n    entries,\n    'model-auth',\n    {\n      configDir: baseDir,\n      agentQaVersion: getAgentQaVersion(),\n      ...(options.configPath === undefined ? {} : { configPath: options.configPath }),\n    },\n    options.remotes,\n  )\n  const [refused] = refusals\n  if (refused) {\n    const entry = entries.find((candidate) => candidate.name === refused.entry)\n    const subscription =\n      entry !== undefined && packageDeclarationValue(entry) === SUBSCRIPTION_AUTH_PACKAGE\n    if (refused.state === 'not_installed' && subscription) {\n      throw new PluginNotInstalledError(entry, 'auth', options.configPath)\n    }\n    throw new Error(refused.reason)\n  }\n\n  const loadedProviders: LLMAuthProviderPlugin[] = []\n  for (const resolved of load) {\n    const declaration = { name: resolved.name, package: resolved.label }\n    const key = declarationKey(declaration, baseDir)\n    if (loadedDeclarations.has(key)) continue\n\n    const module = await importDeclaredPluginModule<AuthPluginModule>(\n      declaration,\n      baseDir,\n      'auth',\n      options.configPath,\n    )\n    const bundle = await resolvePluginBundle(module, resolved.label)\n\n    registerLLMAuthProviderPlugins(bundle.providers)\n    loadedDeclarations.add(key)\n    loadedProviders.push(...bundle.providers)\n  }\n\n  return loadedProviders\n}\n\nexport function clearLoadedLLMAuthPluginModules(): void {\n  loadedDeclarations.clear()\n}\n","import { randomBytes, createHash } from 'node:crypto'\n\nexport function generatePKCE(): { verifier: string; challenge: string } {\n  const verifier = randomBytes(32).toString('base64url')\n  const challenge = createHash('sha256').update(verifier).digest('base64url')\n  return { verifier, challenge }\n}\n\nexport function generateState(): string {\n  return randomBytes(16).toString('hex')\n}\n","import type { AuthProvider, OAuthTokens, TokenRefreshFn } from './types.js'\n\nexport interface CreateAuthFetchOptions {\n  provider: AuthProvider\n  getTokens: () => Promise<OAuthTokens>\n  refreshTokens: TokenRefreshFn\n  onTokensRefreshed: (tokens: OAuthTokens) => Promise<void>\n  headerTransform?: (headers: Headers, tokens: OAuthTokens) => void\n  urlTransform?: (url: string) => string\n}\n\nexport function createAuthFetch(options: CreateAuthFetchOptions): typeof globalThis.fetch {\n  const { provider, getTokens, refreshTokens, onTokensRefreshed, headerTransform, urlTransform } =\n    options\n\n  return async (input: string | URL | Request, init?: RequestInit): Promise<Response> => {\n    let tokens = await getTokens()\n\n    if (tokens.expires < Date.now()) {\n      tokens = await refreshTokens(provider, tokens.refresh)\n      await onTokensRefreshed(tokens)\n    }\n\n    // Build headers without creating a Request (avoids Node duplex stream issue)\n    const headers = new Headers()\n    if (input instanceof Request) {\n      input.headers.forEach((value, key) => { headers.set(key, value) })\n    }\n    if (init?.headers) {\n      if (init.headers instanceof Headers) {\n        init.headers.forEach((value, key) => { headers.set(key, value) })\n      } else if (Array.isArray(init.headers)) {\n        for (const [key, value] of init.headers) {\n          if (value !== undefined) headers.set(key, String(value))\n        }\n      } else {\n        for (const [key, value] of Object.entries(init.headers)) {\n          if (value !== undefined) headers.set(key, String(value))\n        }\n      }\n    }\n\n    // Strip existing auth headers\n    headers.delete('authorization')\n    headers.delete('x-api-key')\n\n    // Inject Bearer token\n    headers.set('Authorization', `Bearer ${tokens.access}`)\n\n    if (headerTransform) {\n      headerTransform(headers, tokens)\n    }\n\n    // Extract URL\n    let url: string\n    if (typeof input === 'string') url = input\n    else if (input instanceof URL) url = input.toString()\n    else url = input.url\n\n    if (urlTransform) {\n      url = urlTransform(url)\n    }\n\n    const response = await globalThis.fetch(url, {\n      ...init,\n      headers,\n    })\n\n    if (!response.ok) {\n      const respBody = await response.text()\n      return new Response(respBody, {\n        status: response.status,\n        statusText: response.statusText,\n        headers: response.headers,\n      })\n    }\n\n    return response\n  }\n}\n","import { declarationKey, importDeclaredPluginModule } from '../plugin-loader-util.js'\nimport {\n  selectInProcessPluginEntries,\n  type PluginRemoteInput,\n} from '../plugins/resolve-entries.js'\nimport type { PluginEntry } from '../schema/config-schema.js'\nimport { getAgentQaVersion } from '../version.js'\n\nexport interface ProviderPluginDescriptor {\n  id: string\n  label: string\n  adapter: (transport: unknown, modelId: string) => unknown\n  authModes: string[]\n  needsBaseURL?: boolean\n  subscription?: boolean\n  credentialOptional?: boolean\n  modelAdapter?: string\n  baseURLPlaceholder?: string\n  defaultModel?: string\n}\n\nexport interface LoadProviderPluginsOptions {\n  baseDir?: string\n  // The config's registry.remotes; an entry one of them names is refused at run start instead.\n  remotes?: readonly PluginRemoteInput[]\n  // The config the person named; fix lines carry it when it is not the default.\n  configPath?: string\n}\n\ntype ProviderPluginModule = {\n  default?: unknown\n  providers?: unknown\n  [key: string]: unknown\n}\n\nconst loadedDeclarations = new Set<string>()\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === 'object' && value !== null\n}\n\nfunction isProviderDescriptorCandidate(value: unknown): boolean {\n  return isRecord(value) && (\n    'id' in value ||\n    'label' in value ||\n    'adapter' in value ||\n    'authModes' in value\n  )\n}\n\nfunction assertProviderDescriptor(value: unknown, source: string): asserts value is ProviderPluginDescriptor {\n  if (!isRecord(value)) {\n    throw new Error(`Provider plugin \"${source}\" exported a descriptor that is not an object.`)\n  }\n  if (typeof value.id !== 'string' || !value.id.trim()) {\n    throw new Error(`Provider plugin \"${source}\" descriptor id is required.`)\n  }\n  if (typeof value.label !== 'string' || !value.label.trim()) {\n    throw new Error(`Provider plugin \"${source}\" descriptor label is required.`)\n  }\n  if (typeof value.adapter !== 'function') {\n    throw new Error(`Provider plugin \"${source}\" descriptor adapter is required.`)\n  }\n  if (!Array.isArray(value.authModes) || !value.authModes.every((mode) => typeof mode === 'string')) {\n    throw new Error(`Provider plugin \"${source}\" descriptor authModes must be a string array.`)\n  }\n}\n\nfunction extractProvidersArray(value: unknown, source: string): ProviderPluginDescriptor[] | null {\n  if (!isRecord(value) || !Array.isArray(value.providers)) return null\n  for (const descriptor of value.providers) {\n    assertProviderDescriptor(descriptor, source)\n  }\n  return value.providers as ProviderPluginDescriptor[]\n}\n\nfunction extractDescriptors(module: ProviderPluginModule, source: string): ProviderPluginDescriptor[] {\n  const defaultProviders = extractProvidersArray(module.default, source)\n  if (defaultProviders) return defaultProviders\n\n  if (isProviderDescriptorCandidate(module.default)) {\n    assertProviderDescriptor(module.default, source)\n    return [module.default]\n  }\n\n  const namedProviders = extractProvidersArray(module, source)\n  if (namedProviders) return namedProviders\n\n  const namedDescriptors: ProviderPluginDescriptor[] = []\n  for (const [name, value] of Object.entries(module)) {\n    if (name === 'default' || name === 'providers') continue\n    if (!isProviderDescriptorCandidate(value)) continue\n    assertProviderDescriptor(value, source)\n    namedDescriptors.push(value)\n  }\n  if (namedDescriptors.length > 0) return namedDescriptors\n\n  throw new Error(`Provider plugin \"${source}\" must export a provider descriptor or providers array.`)\n}\n\nexport async function loadProviderPlugins(\n  entries: readonly PluginEntry[] | undefined,\n  options: LoadProviderPluginsOptions = {},\n): Promise<ProviderPluginDescriptor[]> {\n  if (!entries?.length) return []\n  const baseDir = options.baseDir ?? process.cwd()\n  const { load, refusals } = selectInProcessPluginEntries(\n    entries,\n    'model-provider',\n    {\n      configDir: baseDir,\n      agentQaVersion: getAgentQaVersion(),\n      ...(options.configPath === undefined ? {} : { configPath: options.configPath }),\n    },\n    options.remotes,\n  )\n  const [refused] = refusals\n  if (refused) throw new Error(refused.reason)\n\n  const loadedProviders: ProviderPluginDescriptor[] = []\n  for (const resolved of load) {\n    const declaration = { name: resolved.name, package: resolved.label }\n    const key = declarationKey(declaration, baseDir)\n    if (loadedDeclarations.has(key)) continue\n\n    const module = await importDeclaredPluginModule<ProviderPluginModule>(\n      declaration,\n      baseDir,\n      'provider',\n      options.configPath,\n    )\n    const descriptors = extractDescriptors(module, resolved.label)\n\n    loadedDeclarations.add(key)\n    loadedProviders.push(...descriptors)\n  }\n\n  return loadedProviders\n}\n\nexport function clearLoadedProviderPluginModules(): void {\n  loadedDeclarations.clear()\n}\n","import { z } from 'zod'\n\nexport type LogLevel = 'silent' | 'error' | 'warn' | 'info' | 'debug'\n\nexport const LOG_LEVEL_PRIORITY: Record<LogLevel, number> = {\n  silent: 0,\n  error: 1,\n  warn: 2,\n  info: 3,\n  debug: 4,\n}\n\nexport type LogSource = 'agent' | 'adapter' | 'cache' | 'planner' | 'hook' | 'runner'\n\nexport interface LogEntry {\n  id: string\n  stepId: string | null\n  runId: string\n  level: Exclude<LogLevel, 'silent'>\n  source: LogSource\n  message: string\n  data: Record<string, unknown>\n  timestamp: string\n}\n\nexport interface LogStorage {\n  insertLogs(entries: LogEntry[]): void\n  getLogs(opts: {\n    runId?: string\n    stepId?: string\n    level?: string\n    source?: string\n    limit?: number\n    offset?: number\n  }): LogEntry[]\n}\n\nexport interface ScopedLogger {\n  debug(msg: string, data?: Record<string, unknown>): void\n  info(msg: string, data?: Record<string, unknown>): void\n  warn(msg: string, data?: Record<string, unknown>): void\n  error(msg: string, data?: Record<string, unknown>): void\n}\n\n// Per-source Zod data schemas\nexport const AgentLogDataSchema = z.object({\n  hasScreenshot: z.boolean().optional(),\n  duration: z.number().optional(),\n  elementCount: z.number().optional(),\n})\n\nexport const AdapterLogDataSchema = z.object({\n  actionType: z.string().optional(),\n  selector: z.string().optional(),\n  coordinates: z.object({ x: z.number(), y: z.number() }).optional(),\n  elementProperties: z.record(z.string(), z.unknown()).optional(),\n  duration: z.number().optional(),\n})\n\nexport const CacheLogDataSchema = z.object({\n  operation: z.enum(['get', 'set', 'invalidate', 'bypass', 'batch-purge']),\n  stepHash: z.string().optional(),\n  screenHash: z.string().optional(),\n  hit: z.boolean().optional(),\n  age: z.number().optional(),\n  entriesDeleted: z.number().optional(),\n})\n\nexport const PlannerLogDataSchema = z.object({\n  model: z.string().optional(),\n  promptTokens: z.number().optional(),\n  completionTokens: z.number().optional(),\n  latencyMs: z.number().optional(),\n  confidence: z.number().optional(),\n  actionType: z.string().optional(),\n})\n\nexport const HookLogDataSchema = z.object({\n  hookName: z.string().optional(),\n  phase: z.enum(['setup', 'teardown']).optional(),\n  duration: z.number().optional(),\n  success: z.boolean().optional(),\n})\n\nexport const RunnerLogDataSchema = z.object({\n  stepIndex: z.number().optional(),\n  totalSteps: z.number().optional(),\n  testName: z.string().optional(),\n  variablesCaptured: z.number().optional(),\n})\n\nexport const LogSourceDataSchemas: Record<LogSource, z.ZodType> = {\n  agent: AgentLogDataSchema,\n  adapter: AdapterLogDataSchema,\n  cache: CacheLogDataSchema,\n  planner: PlannerLogDataSchema,\n  hook: HookLogDataSchema,\n  runner: RunnerLogDataSchema,\n}\n","import { randomBytes } from 'node:crypto'\n\nexport type RunTextEnv = Readonly<Record<string, string | undefined>>\n\nexport interface PrintRunTextOptions {\n  readonly env?: RunTextEnv\n  readonly stdoutIsData?: boolean\n}\n\n// The root entry and the subpath entry each bundle a copy of this module, so the count lives on\n// globalThis where a reservation taken through either is seen by both.\nconst STDOUT_RESERVATIONS = Symbol.for('agent-qa.run-text-output.stdout-reservations')\n\ninterface StdoutReservations {\n  count: number\n}\n\nfunction stdoutReservations(): StdoutReservations {\n  const holder = globalThis as typeof globalThis & { [STDOUT_RESERVATIONS]?: StdoutReservations }\n  holder[STDOUT_RESERVATIONS] ??= { count: 0 }\n  return holder[STDOUT_RESERVATIONS]\n}\n\nexport function isGitHubActions(env: RunTextEnv = process.env): boolean {\n  const value = env.GITHUB_ACTIONS\n  return value !== undefined && value !== '' && value.toLowerCase() !== 'false' && value !== '0'\n}\n\nexport function guardRunText(text: string, env: RunTextEnv = process.env): string {\n  if (!isGitHubActions(env)) return text\n  // Longer than 6 characters, so the runner masks the token in the log.\n  const token = randomBytes(16).toString('hex')\n  const block = text.endsWith('\\n') ? text : `${text}\\n`\n  return `::stop-commands::${token}\\n${block}::${token}::\\n`\n}\n\nexport function guardJsonText(serialized: string, env: RunTextEnv = process.env): string {\n  return isGitHubActions(env) ? serialized.replaceAll('#', '\\\\u0023') : serialized\n}\n\n/** Marks this process's stdout as carrying a JSON document or protocol; returns the release. */\nexport function reserveStdoutForData(): () => void {\n  const reservations = stdoutReservations()\n  reservations.count += 1\n  let released = false\n  return () => {\n    if (released) return\n    released = true\n    reservations.count -= 1\n  }\n}\n\nexport function stdoutCarriesData(): boolean {\n  return stdoutReservations().count > 0\n}\n\nexport function printRunText(\n  text: string,\n  print: (text: string) => void = (line) => console.log(line),\n  options: PrintRunTextOptions = {},\n): void {\n  const env = options.env ?? process.env\n  if (!isGitHubActions(env)) {\n    print(text)\n    return\n  }\n  const block = guardRunText(text, env)\n  // The runner reads stdout and stderr on separate threads, so every wrapped block shares one\n  // stream: stdout, or stderr when stdout carries data. The caller's print never sees a block.\n  if (options.stdoutIsData ?? stdoutCarriesData()) {\n    process.stderr.write(block)\n    return\n  }\n  process.stdout.write(block)\n}\n","import pc from 'picocolors'\nimport {\n  isGitHubActions,\n  printRunText,\n  stdoutCarriesData,\n  type RunTextEnv,\n} from './run-text-output.js'\n\nexport type LogColors = ReturnType<typeof pc.createColors>\nexport type LogLineLevel = 'error' | 'warn' | 'info' | 'debug'\n\nexport interface LogLine {\n  tag: string\n  message: string\n  level?: LogLineLevel\n  data?: Record<string, unknown>\n  time?: Date\n}\n\ntype TagColor = 'cyan' | 'cyanBright' | 'blue' | 'blueBright' | 'magenta' | 'magentaBright' | 'gray'\n\n// Green, red and yellow mean a status, so no tag takes them.\nconst TAG_COLORS: Readonly<Record<string, TagColor>> = {\n  server: 'cyan',\n  mcp: 'cyan',\n  daemon: 'cyan',\n  queue: 'blue',\n  'post-run': 'blue',\n  jobs: 'blue',\n  run: 'cyanBright',\n  appium: 'magenta',\n  live: 'magentaBright',\n  embedder: 'magentaBright',\n  knowledge: 'blueBright',\n  plugin: 'gray',\n  agent: 'cyan',\n  adapter: 'cyan',\n  cache: 'cyan',\n  planner: 'cyan',\n  hook: 'cyan',\n  runner: 'cyan',\n  procedure: 'cyan',\n  evidence: 'cyan',\n}\n\nconst TAG_WIDTH = 9\nconst CONTINUATION = ' '.repeat('HH:MM:SS'.length + 2 + TAG_WIDTH + 2)\n\nexport function isCi(env: RunTextEnv = process.env): boolean {\n  const ci = env.CI\n  return (ci !== undefined && ci !== '' && ci !== '0' && ci !== 'false') || isGitHubActions(env)\n}\n\ntype ColorVariable = 'NO_COLOR' | 'FORCE_COLOR'\n\ninterface ColorPosture {\n  asked: Readonly<Record<ColorVariable, string | undefined>>\n  left: Readonly<Record<ColorVariable, string | undefined>>\n}\n\nconst COLOR_POSTURE = Symbol.for('agent-qa.color-posture')\n\n// The CLI's colour posture rewrites the process's two variables to fit stdout and records what the\n// user had set. A variable that still holds what the posture left reads as the user's value.\nfunction userSet(env: RunTextEnv, name: ColorVariable): string | undefined {\n  if (env !== process.env) return env[name]\n  const posture = (globalThis as { [COLOR_POSTURE]?: ColorPosture })[COLOR_POSTURE]\n  return posture !== undefined && env[name] === posture.left[name] ? posture.asked[name] : env[name]\n}\n\nexport function colorEnabled(env: RunTextEnv, isTTY: boolean): boolean {\n  const noColor = userSet(env, 'NO_COLOR')\n  if (noColor !== undefined && noColor !== '') return false\n  const force = userSet(env, 'FORCE_COLOR')\n  if (force !== undefined) return force !== '0' && force !== 'false'\n  if (isTTY) return env.TERM !== 'dumb'\n  return isCi(env)\n}\n\nexport function colorsFor(stream: { isTTY?: boolean }, env?: RunTextEnv): LogColors {\n  return pc.createColors(colorEnabled(env ?? process.env, stream.isTTY === true))\n}\n\nfunction twoDigits(value: number): string {\n  return String(value).padStart(2, '0')\n}\n\nexport function formatLogLine(line: LogLine, colors: LogColors): string {\n  const at = line.time ?? new Date()\n  const time = colors.dim(\n    `${twoDigits(at.getHours())}:${twoDigits(at.getMinutes())}:${twoDigits(at.getSeconds())}`,\n  )\n  const tag = colors[TAG_COLORS[line.tag] ?? 'cyan'](line.tag.padEnd(TAG_WIDTH))\n  const tint =\n    line.level === 'error' ? colors.red : line.level === 'warn' ? colors.yellow : undefined\n  const body = line.message\n    .split('\\n')\n    .map((part) => (tint === undefined ? part : tint(part)))\n    .join(`\\n${CONTINUATION}`)\n  const data = line.data ?? {}\n  const keys = Object.keys(data)\n  const suffix =\n    keys.length === 0\n      ? ''\n      : ` ${colors.dim(keys.map((key) => `${key}=${JSON.stringify(data[key])}`).join(' '))}`\n  return `${time}  ${tag}  ${body}${suffix}`\n}\n\nexport function printLogLine(\n  line: LogLine,\n  options: { env?: RunTextEnv; to?: 'stdout' | 'stderr' } = {},\n): void {\n  const env = options.env ?? process.env\n  const level = line.level ?? 'info'\n  const wantsStdout =\n    options.to === 'stdout' || (options.to === undefined && level !== 'error' && level !== 'warn')\n  let print: (text: string) => void\n  let stream: { isTTY?: boolean }\n  if (wantsStdout && !stdoutCarriesData()) {\n    print = (text) => console.log(text)\n    stream = process.stdout\n  } else if (options.to === undefined && level === 'warn') {\n    print = (text) => console.warn(text)\n    stream = process.stderr\n  } else {\n    print = (text) => console.error(text)\n    stream = process.stderr\n  }\n  printRunText(formatLogLine(line, colorsFor(stream, env)), print, { env })\n}\n","import { randomUUID } from 'node:crypto'\nimport { LOG_LEVEL_PRIORITY } from './types.js'\nimport type { LogLevel, LogSource, LogEntry, LogStorage, ScopedLogger } from './types.js'\nimport { colorsFor, formatLogLine } from './log-line.js'\nimport { guardJsonText, printRunText, type RunTextEnv } from './run-text-output.js'\nimport { redactSecretValue, type SecretRedactor } from '@vostride/agent-qa-runner'\n\n// `pending` holds only this member's unattributed lines, so a sibling's `setRunId` skips them.\nexport interface MemberLogScope {\n  runId: string\n  readonly pending: LogEntry[]\n}\n\n/**\n * The host's async-context primitive, named STRUCTURALLY so this package never imports\n * `node:async_hooks`.\n *\n * `packages/core`'s host baseline is a regenerable DEBT record with a per-area clearance map — a\n * list that is meant to shrink — so a new host import here would be new debt, not a permission.\n * The composition root already owns every other reach into the world, so it owns this one too and\n * injects it. `node:async_hooks`'s `AsyncLocalStorage<MemberLogScope>` satisfies this exactly, with\n * no adapter.\n */\nexport interface AsyncScopeStore<T> {\n  getStore(): T | undefined\n  run<R>(store: T, fn: () => R): R\n}\n\n/** Thrown when a caller asks for member isolation the composition root never wired up. */\nexport class MemberLogScopeUnavailableError extends Error {\n  constructor() {\n    super(\n      'LogManager.runInMemberScope requires a memberScope store. Construct the manager with ' +\n        '`memberScope: new AsyncLocalStorage()` — without it, concurrent members would silently ' +\n        'share one run id.',\n    )\n    this.name = 'MemberLogScopeUnavailableError'\n  }\n}\n\nexport class LogManager {\n  private buffer: LogEntry[] = []\n  private currentStepId: string | null = null\n  private runId: string\n  private runIdSet = false\n  private readonly displayLevel: LogLevel\n  private readonly storage?: LogStorage\n  private readonly ndjson: boolean\n  private redactor?: SecretRedactor\n  private readonly memberScope?: AsyncScopeStore<MemberLogScope>\n  private readonly env?: RunTextEnv\n\n  constructor(opts: {\n    runId?: string\n    displayLevel: LogLevel\n    storage?: LogStorage\n    ndjson?: boolean\n    redactor?: SecretRedactor\n    memberScope?: AsyncScopeStore<MemberLogScope>\n    env?: RunTextEnv\n  }) {\n    this.runId = opts.runId ?? ''\n    this.runIdSet = !!opts.runId\n    this.displayLevel = opts.displayLevel\n    this.storage = opts.storage\n    this.ndjson = opts.ndjson ?? false\n    this.redactor = opts.redactor\n    this.memberScope = opts.memberScope\n    this.env = opts.env\n  }\n\n  setRedactor(redactor: SecretRedactor | undefined): void {\n    this.redactor = redactor\n  }\n\n  // One manager serves every concurrent member; outside a scope `setRunId` backfills the buffer.\n  runInMemberScope<T>(fn: () => T): T {\n    if (!this.memberScope) throw new MemberLogScopeUnavailableError()\n    return this.memberScope.run({ runId: this.runId, pending: [] }, fn)\n  }\n\n  log(\n    level: Exclude<LogLevel, 'silent'>,\n    source: LogSource,\n    message: string,\n    data?: Record<string, unknown>,\n  ): void {\n    const scope = this.memberScope?.getStore()\n    const entry: LogEntry = {\n      id: randomUUID(),\n      stepId: this.currentStepId,\n      runId: scope ? scope.runId : this.runId,\n      level,\n      source,\n      message: redactSecretValue(message, this.redactor),\n      data: redactSecretValue(data ?? {}, this.redactor),\n      timestamp: new Date().toISOString(),\n    }\n    this.buffer.push(entry)\n    if (scope && !entry.runId) scope.pending.push(entry)\n\n    if (this.shouldDisplay(level)) {\n      printRunText(\n        formatLogLine(\n          {\n            tag: entry.source,\n            message: entry.message,\n            level: entry.level,\n            data: entry.data,\n            time: new Date(entry.timestamp),\n          },\n          colorsFor(process.stderr, this.env),\n        ),\n        (line) => {\n          process.stderr.write(`${line}\\n`)\n        },\n        { env: this.env },\n      )\n    }\n\n    if (this.ndjson) {\n      this.emitNdjson(entry)\n    }\n  }\n\n  private shouldDisplay(entryLevel: Exclude<LogLevel, 'silent'>): boolean {\n    if (this.displayLevel === 'silent') return false\n    return LOG_LEVEL_PRIORITY[entryLevel] <= LOG_LEVEL_PRIORITY[this.displayLevel]\n  }\n\n  /**\n   * The SECOND writer on the `AGENT_QA_EVENT:` stdout channel — the first is the CLI's\n   * `reporters/wire-reporter.ts`, which prints run-event envelopes on the same prefix. Both are\n   * armed by `AGENT_QA_LIVE_EVENTS=true` (this one indirectly: `commands/run.ts` passes\n   * `ndjson: process.env.AGENT_QA_LIVE_EVENTS === 'true'`), both are off by default, and nothing in\n   * the product sets that variable. Entries are already redacted above, and are printed verbatim.\n   * A supported opt-in; the user-facing contract for both writers is the CLI README's\n   * \"Live events on stdout (opt-in)\". Do not change this line shape without mirroring it there.\n   */\n  private emitNdjson(entry: LogEntry): void {\n    process.stdout.write(\n      `AGENT_QA_EVENT:${guardJsonText(JSON.stringify({ type: 'log', ...entry }), this.env)}\\n`,\n    )\n  }\n\n  setCurrentStep(stepId: string): void {\n    this.currentStepId = stepId\n  }\n\n  clearCurrentStep(): void {\n    this.currentStepId = null\n  }\n\n  setRunId(runId: string): void {\n    const scope = this.memberScope?.getStore()\n    if (scope) {\n      scope.runId = runId\n      // This member's OWN pre-mint lines only. A sibling's unattributed lines live in ITS scope.\n      for (const entry of scope.pending) entry.runId = runId\n      scope.pending.length = 0\n      // The flush gate is a manager-level fact: a scoped stamp is still a real run id, and without\n      // this a fully-attributed concurrent run would be silently discarded at flush().\n      this.runIdSet = true\n      return\n    }\n    this.runId = runId\n    this.runIdSet = true\n    for (const entry of this.buffer) {\n      entry.runId = runId\n    }\n  }\n\n  flush(): void {\n    if (this.storage && this.buffer.length > 0) {\n      if (!this.runIdSet) {\n        this.buffer = []\n        return\n      }\n      this.storage.insertLogs(this.buffer)\n    }\n    this.buffer = []\n  }\n\n  getBuffer(): LogEntry[] {\n    return [...this.buffer]\n  }\n\n  createScopedLogger(source: LogSource): ScopedLogger {\n    return {\n      debug: (msg: string, data?: Record<string, unknown>) =>\n        this.log('debug', source, msg, data),\n      info: (msg: string, data?: Record<string, unknown>) =>\n        this.log('info', source, msg, data),\n      warn: (msg: string, data?: Record<string, unknown>) =>\n        this.log('warn', source, msg, data),\n      error: (msg: string, data?: Record<string, unknown>) =>\n        this.log('error', source, msg, data),\n    }\n  }\n}\n","import type { TestDefinition } from '../types/test.js'\nimport type { SuiteDefinition } from './types.js'\n\nfunction isPlainObject(val: unknown): val is Record<string, unknown> {\n  return typeof val === 'object' && val !== null && !Array.isArray(val)\n}\n\nfunction deepMerge(base: unknown, override: unknown): unknown {\n  if (!isPlainObject(base) || !isPlainObject(override)) return override\n  const result: Record<string, unknown> = { ...base }\n  for (const key of Object.keys(override)) {\n    if (key in result && isPlainObject(result[key]) && isPlainObject(override[key])) {\n      result[key] = deepMerge(result[key], override[key])\n    } else {\n      result[key] = override[key]\n    }\n  }\n  return result\n}\n\n// Merges the suite's target and use into a member and drops its `url`: the suite owns startup.\nexport function patchTestForSuite(\n  test: TestDefinition,\n  suite: SuiteDefinition,\n  _index: number,\n): TestDefinition {\n  const patched = structuredClone(test)\n\n  if (suite.target) {\n    ;(patched as any).target = suite.target\n  }\n\n  if (suite.use && (patched as any).use) {\n    ;(patched as any).use = deepMerge(suite.use, (patched as any).use)\n  } else {\n    ;(patched as any).use = (patched as any).use ?? suite.use\n  }\n\n  delete (patched as any).url\n\n  return patched\n}\n","import { readFile } from 'node:fs/promises'\nimport { dirname, resolve } from 'node:path'\nimport { parse as parseYaml } from 'yaml'\nimport { HooksFileSchema } from './schema.js'\nimport { yamlParseFailureMessage } from '../validation/yaml-fault.js'\nimport type { HookDefinition } from '@vostride/agent-qa-runner'\n\nexport async function parseHooksFile(filePath: string): Promise<{ hooks: HookDefinition[]; errors: string[] }> {\n  let raw: string\n  try {\n    raw = await readFile(filePath, 'utf-8')\n  } catch (err) {\n    return { hooks: [], errors: [`Failed to read hooks file: ${(err as Error).message}`] }\n  }\n\n  let parsed: unknown\n  try {\n    parsed = parseYaml(raw)\n  } catch (err) {\n    // The message says where the parse failed, never the excerpt, which can carry a credential.\n    return { hooks: [], errors: [`${filePath}: ${yamlParseFailureMessage(err)}`] }\n  }\n\n  const result = HooksFileSchema.safeParse(parsed)\n  if (!result.success) {\n    const errors = result.error.issues.map((issue) =>\n      `${issue.path.join('.')}: ${issue.message}`\n    )\n    return { hooks: [], errors }\n  }\n\n  const dir = dirname(filePath)\n  const hooks: HookDefinition[] = result.data.hooks.map((h) => ({\n    ...h,\n    file: resolve(dir, h.file),\n    deps: h.deps.map((d) => resolve(dir, d)),\n    packageFile: h.packageFile ? resolve(dir, h.packageFile) : undefined,\n  }))\n\n  return { hooks, errors: [] }\n}\n","import type { SecretStore } from '@vostride/agent-qa-runner'\nimport {\n  configConnectionSecretNames,\n  connectionSecretNames,\n  remoteLabel,\n  secretReferenceNames,\n} from '@vostride/agent-qa-schema'\nimport type { RemoteEntryLike } from '@vostride/agent-qa-schema'\n\nexport type RemoteConnectionFields = Pick<\n  RemoteEntryLike,\n  'name' | 'protocol' | 'url' | 'query' | 'headers' | 'basicAuth'\n>\n\nexport interface ConnectionSecretSplit {\n  // Everything a step, a hook, a target url or the planner may reach.\n  readonly stepStore: SecretStore\n  // Every name a remote, a device's capabilities or a target's app.ref references.\n  readonly connectionNames: ReadonlySet<string>\n}\n\nexport function splitConnectionSecrets(store: SecretStore, config: unknown): ConnectionSecretSplit {\n  const connectionNames = new Set(configConnectionSecretNames(config))\n  return { stepStore: store.without(connectionNames), connectionNames }\n}\n\nexport interface MissingRemoteSecret<R extends RemoteConnectionFields = RemoteConnectionFields> {\n  readonly remote: R\n  readonly name: string\n}\n\nexport function missingRemoteSecrets<R extends RemoteConnectionFields>(\n  remotes: readonly R[],\n  store: { has(name: string): boolean },\n): MissingRemoteSecret<R>[] {\n  const missing: MissingRemoteSecret<R>[] = []\n  const seen = new Set<string>()\n  for (const remote of remotes) {\n    if (seen.has(remote.name)) continue\n    seen.add(remote.name)\n    for (const name of connectionSecretNames([remote])) {\n      if (!store.has(name)) missing.push({ remote, name })\n    }\n  }\n  return missing\n}\n\nexport function missingRemoteSecretSentence(\n  missing: MissingRemoteSecret,\n  secretsFile: string | undefined,\n): string {\n  const file = secretsFile ?? 'workspace.secretsFile'\n  return `Remote ${remoteLabel(missing.remote)} needs ${missing.name}, which ${file} does not declare. Add it there.`\n}\n\nexport interface DeviceUse {\n  readonly device: string\n  // Absent for a device here, whose capabilities still resolve their references at connect.\n  readonly remote?: RemoteConnectionFields | undefined\n  // The app.ref of a target the device runs; a remote device's server installs from it.\n  readonly appRef?: string | undefined\n}\n\nexport interface MissingDeviceSecret {\n  readonly device: string\n  readonly remote?: RemoteConnectionFields | undefined\n  readonly name: string\n}\n\n// What a used device's connection needs: its remote's values, if any, its own capabilities and,\n// on a remote, the app.ref of each target it runs.\nexport function missingDeviceSecrets(\n  used: readonly DeviceUse[],\n  devices: Readonly<Record<string, { readonly capabilities?: unknown }>>,\n  store: { has(name: string): boolean },\n): MissingDeviceSecret[] {\n  const uses = new Map<string, { remote?: RemoteConnectionFields | undefined; appRefs: string[] }>()\n  for (const { device, remote, appRef } of used) {\n    const use = uses.get(device) ?? { remote, appRefs: [] }\n    if (appRef !== undefined) use.appRefs.push(appRef)\n    uses.set(device, use)\n  }\n  const missing: MissingDeviceSecret[] = []\n  for (const [device, { remote, appRefs }] of uses) {\n    const capabilities = Object.hasOwn(devices, device) ? devices[device]?.capabilities : undefined\n    const names = new Set([\n      ...(remote === undefined ? [] : connectionSecretNames([remote])),\n      ...secretReferenceNames(JSON.stringify(capabilities ?? {})),\n      ...(remote === undefined ? [] : appRefs.flatMap(secretReferenceNames)),\n    ])\n    for (const name of names) {\n      if (!store.has(name)) missing.push({ device, remote, name })\n    }\n  }\n  return missing\n}\n\nexport function missingDeviceSecretSentence(\n  missing: MissingDeviceSecret,\n  secretsFile: string | undefined,\n): string {\n  const file = secretsFile ?? 'workspace.secretsFile'\n  const where = missing.remote === undefined ? '' : ` on remote ${remoteLabel(missing.remote)}`\n  return `Device ${missing.device}${where} needs ${missing.name}, which ${file} does not declare. Add it there.`\n}\n\nexport interface ConnectionSecretMisuseInput {\n  readonly names: ReadonlySet<string>\n  // The file the sentence names, as the run and validate print it.\n  readonly file: string\n  readonly steps: readonly unknown[]\n  // A url held outside the config; a config target url is refused by the config's own parse.\n  readonly target?: string\n}\n\nfunction stringLeaves(value: unknown): string[] {\n  if (typeof value === 'string') return [value]\n  if (Array.isArray(value)) return value.flatMap(stringLeaves)\n  if (typeof value === 'object' && value !== null) return Object.values(value).flatMap(stringLeaves)\n  return []\n}\n\nfunction misusedNames(texts: readonly string[], names: ReadonlySet<string>): string[] {\n  const used = new Set<string>()\n  for (const text of texts) {\n    for (const name of secretReferenceNames(text)) if (names.has(name)) used.add(name)\n  }\n  return [...used]\n}\n\nexport function connectionSecretMisuse(input: ConnectionSecretMisuseInput): string[] {\n  if (input.names.size === 0) return []\n  const sentence = (name: string, place: string): string =>\n    `${name} is a remote's or device's credential and only connects to it; ${input.file} uses it in ${place}. Use another secret there.`\n  return [\n    ...misusedNames(input.steps.flatMap(stringLeaves), input.names).map((name) =>\n      sentence(name, 'a step'),\n    ),\n    ...misusedNames(input.target === undefined ? [] : [input.target], input.names).map((name) =>\n      sentence(name, 'its target url'),\n    ),\n  ]\n}\n","import { existsSync } from 'node:fs'\nimport path from 'node:path'\nimport { glob } from 'glob'\nimport type { AgentQaConfig } from '../types/config.js'\n\nexport type WorkspaceFileKind = 'test' | 'suite'\n\nexport interface ResolvedWorkspaceFile {\n  configuredPath: string\n  absolutePath: string\n  workspaceRelativePath: string\n}\n\nexport interface WorkspaceFileRecord {\n  kind: WorkspaceFileKind\n  absolutePath: string\n  workspaceRelativePath: string\n}\n\nexport interface ResolvedWorkspacePaths {\n  configPath: string\n  configDir: string\n  testMatch: string[]\n  suiteMatch: string[]\n  testPathIgnore: string[]\n  hooksFile: ResolvedWorkspaceFile\n  envFile: ResolvedWorkspaceFile\n  secretsFile: ResolvedWorkspaceFile\n}\n\ninterface ResolveWorkspacePathsInput {\n  config: AgentQaConfig\n  configPath: string\n  requireExistingFiles?: boolean\n}\n\nfunction toForwardSlash(value: string): string {\n  return value.split(path.sep).join('/')\n}\n\nfunction trimLeadingCurrentDir(value: string): string {\n  return toForwardSlash(value).replace(/^\\.\\//, '')\n}\n\nfunction assertNonEmptyArray(value: unknown, key: string): string[] {\n  if (!Array.isArray(value) || value.length === 0 || value.some(item => typeof item !== 'string' || item.trim().length === 0)) {\n    throw new Error(`Missing required workspace config key: ${key}`)\n  }\n  return value\n}\n\nfunction assertNonEmptyString(value: unknown, key: string): string {\n  if (typeof value !== 'string' || value.trim().length === 0) {\n    throw new Error(`Missing required workspace config key: ${key}`)\n  }\n  return value\n}\n\nfunction resolveWorkspaceScalar(configDir: string, key: string, configuredPath: unknown): ResolvedWorkspaceFile {\n  const value = assertNonEmptyString(configuredPath, key)\n  const absolutePath = path.isAbsolute(value) ? path.resolve(value) : path.resolve(configDir, value)\n  return {\n    configuredPath: value,\n    absolutePath,\n    workspaceRelativePath: trimLeadingCurrentDir(path.relative(configDir, absolutePath)),\n  }\n}\n\nfunction assertInsideWorkspace(configDir: string, absolutePath: string, filePath: string): string {\n  const relativePath = path.relative(configDir, absolutePath)\n  if (!relativePath || relativePath.startsWith('..') || path.isAbsolute(relativePath)) {\n    throw new Error(`Workspace file path escapes config directory: ${filePath}`)\n  }\n  return trimLeadingCurrentDir(relativePath)\n}\n\n// Identity only, never file access: a ledger keyed on absolute paths matches on no other machine.\nexport function workspaceRelativeIdentityPath(configDir: string, filePath: string): string {\n  const absolutePath = path.isAbsolute(filePath)\n    ? path.resolve(filePath)\n    : path.resolve(configDir, filePath)\n  return assertInsideWorkspace(configDir, absolutePath, filePath)\n}\n\nfunction escapeRegexChar(char: string): string {\n  return char.replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\nfunction globToRegex(pattern: string): RegExp {\n  const normalized = trimLeadingCurrentDir(pattern)\n  let source = ''\n\n  for (let i = 0; i < normalized.length; i++) {\n    const char = normalized[i]\n    const next = normalized[i + 1]\n\n    if (char === '*') {\n      if (next === '*') {\n        const afterGlobstar = normalized[i + 2]\n        if (afterGlobstar === '/') {\n          source += '(?:.*/)?'\n          i += 2\n        } else {\n          source += '.*'\n          i += 1\n        }\n      } else {\n        source += '[^/]*'\n      }\n      continue\n    }\n\n    if (char === '?') {\n      source += '[^/]'\n      continue\n    }\n\n    if (char === '{') {\n      const end = normalized.indexOf('}', i + 1)\n      if (end !== -1) {\n        const alternatives = normalized\n          .slice(i + 1, end)\n          .split(',')\n          .map(part => part.split('').map(escapeRegexChar).join(''))\n        source += `(?:${alternatives.join('|')})`\n        i = end\n        continue\n      }\n    }\n\n    source += escapeRegexChar(char)\n  }\n\n  return new RegExp(`^${source}$`)\n}\n\nfunction matchesAnyPattern(workspaceRelativePath: string, patterns: string[]): boolean {\n  const normalized = trimLeadingCurrentDir(workspaceRelativePath)\n  return patterns.some(pattern => globToRegex(pattern).test(normalized))\n}\n\nfunction getKindPatterns(workspace: ResolvedWorkspacePaths, kind: WorkspaceFileKind): string[] {\n  return kind === 'test' ? workspace.testMatch : workspace.suiteMatch\n}\n\nfunction isIgnored(workspace: ResolvedWorkspacePaths, workspaceRelativePath: string): boolean {\n  return workspace.testPathIgnore.length > 0 && matchesAnyPattern(workspaceRelativePath, workspace.testPathIgnore)\n}\n\nexport function resolveWorkspacePaths(input: ResolveWorkspacePathsInput): ResolvedWorkspacePaths {\n  const configPath = path.resolve(input.configPath)\n  const configDir = path.dirname(configPath)\n  const workspace = input.config.workspace\n\n  if (!workspace) {\n    throw new Error('Missing required workspace config key: workspace')\n  }\n\n  const resolved: ResolvedWorkspacePaths = {\n    configPath,\n    configDir,\n    testMatch: assertNonEmptyArray(workspace.testMatch, 'workspace.testMatch'),\n    suiteMatch: assertNonEmptyArray(workspace.suiteMatch, 'workspace.suiteMatch'),\n    testPathIgnore: workspace.testPathIgnore ?? [],\n    hooksFile: resolveWorkspaceScalar(configDir, 'workspace.hooksFile', workspace.hooksFile),\n    envFile: resolveWorkspaceScalar(configDir, 'workspace.envFile', workspace.envFile),\n    secretsFile: resolveWorkspaceScalar(configDir, 'workspace.secretsFile', workspace.secretsFile),\n  }\n\n  if (input.requireExistingFiles) {\n    for (const [key, file] of [\n      ['workspace.hooksFile', resolved.hooksFile],\n      ['workspace.envFile', resolved.envFile],\n      ['workspace.secretsFile', resolved.secretsFile],\n    ] as const) {\n      if (!existsSync(file.absolutePath)) {\n        throw new Error(`Configured workspace file not found: ${key} -> ${file.absolutePath}`)\n      }\n    }\n  }\n\n  return resolved\n}\n\nexport async function discoverWorkspaceFiles(input: {\n  workspace: ResolvedWorkspacePaths\n  kind: WorkspaceFileKind\n}): Promise<WorkspaceFileRecord[]> {\n  const patterns = getKindPatterns(input.workspace, input.kind)\n  const matches = await glob(patterns, {\n    cwd: input.workspace.configDir,\n    ignore: input.workspace.testPathIgnore,\n    absolute: true,\n    nodir: true,\n  })\n\n  return matches\n    .map(match => path.resolve(match))\n    .map(absolutePath => ({\n      kind: input.kind,\n      absolutePath,\n      workspaceRelativePath: trimLeadingCurrentDir(path.relative(input.workspace.configDir, absolutePath)),\n    }))\n    .sort((a, b) => a.workspaceRelativePath.localeCompare(b.workspaceRelativePath))\n}\n\nexport async function resolveWorkspaceFileTarget(input: {\n  workspace: ResolvedWorkspacePaths\n  kind: WorkspaceFileKind\n  filePath: string\n  requireExisting?: boolean\n}): Promise<WorkspaceFileRecord> {\n  const absolutePath = path.isAbsolute(input.filePath)\n    ? path.resolve(input.filePath)\n    : path.resolve(input.workspace.configDir, input.filePath)\n  const workspaceRelativePath = assertInsideWorkspace(input.workspace.configDir, absolutePath, input.filePath)\n\n  if (!isWorkspacePathMatch({\n    workspace: input.workspace,\n    kind: input.kind,\n    workspaceRelativePath,\n  })) {\n    throw new Error(`Workspace ${input.kind} file is not matched by configured workspace patterns: ${workspaceRelativePath}`)\n  }\n\n  if (input.requireExisting && !existsSync(absolutePath)) {\n    throw new Error(`Workspace ${input.kind} file not found: ${workspaceRelativePath}`)\n  }\n\n  return {\n    kind: input.kind,\n    absolutePath,\n    workspaceRelativePath,\n  }\n}\n\nexport function isWorkspacePathMatch(input: {\n  workspace: ResolvedWorkspacePaths\n  kind: WorkspaceFileKind\n  workspaceRelativePath: string\n}): boolean {\n  return matchesAnyPattern(input.workspaceRelativePath, getKindPatterns(input.workspace, input.kind))\n    && !isIgnored(input.workspace, input.workspaceRelativePath)\n}\n","import { readFile } from 'node:fs/promises'\nimport { existsSync } from 'node:fs'\nimport path from 'node:path'\nimport { parse as parseYaml, LineCounter, parseDocument } from 'yaml'\nimport { glob } from 'glob'\nimport { AgentQaConfigSchema } from '../schema/config-schema.js'\nimport { SuiteDefinitionSchema } from '../schema/suite-schema.js'\nimport { parseTestFile } from '../parser/yaml-parser.js'\nimport { parseHooksFile } from '../hooks/parser.js'\nimport { configConnectionSecretNames } from '@vostride/agent-qa-schema'\nimport { connectionSecretMisuse } from '../remote/connection-secrets.js'\nimport { isPathInsideDir } from '../utils/path-validation.js'\nimport { selectSuitePlace, selectWebPlace, type BrowserEngine } from '../remote/select-place.js'\nimport type { AgentQaConfig } from '../types/config.js'\nimport { yamlParseFailureMessage } from './yaml-fault.js'\nimport {\n  discoverWorkspaceFiles,\n  isWorkspacePathMatch,\n  resolveWorkspaceFileTarget,\n  type ResolvedWorkspacePaths,\n  type WorkspaceFileKind,\n} from '../workspace/workspace-paths.js'\n\nexport interface ValidationDiagnostic {\n  file: string\n  line: number\n  column: number\n  message: string\n  severity: 'error' | 'warning'\n}\n\nexport interface ValidationResult {\n  diagnostics: ValidationDiagnostic[]\n  fileCount: number\n  errorCount: number\n  warningCount: number\n}\n\nexport const VALID_FILENAME_RE = /^[a-zA-Z0-9._-]+\\.(suite\\.)?(yaml|yml)$/\n\nexport async function validateConfig(configPath: string): Promise<ValidationDiagnostic[]> {\n  const diagnostics: ValidationDiagnostic[] = []\n\n  let content: string\n  try {\n    content = await readFile(configPath, 'utf-8')\n  } catch (err) {\n    diagnostics.push({\n      file: configPath,\n      line: 1,\n      column: 1,\n      message: `Cannot read config file: ${(err as Error).message}`,\n      severity: 'error',\n    })\n    return diagnostics\n  }\n\n  let parsed: unknown\n  try {\n    // yaml's warnings quote the file's text, so only its errors are reported.\n    parsed = parseYaml(content, { logLevel: 'error' })\n  } catch (err) {\n    // The `file` field names the file, so the message is the position; an excerpt can leak.\n    diagnostics.push({\n      file: configPath,\n      line: 1,\n      column: 1,\n      message: yamlParseFailureMessage(err),\n      severity: 'error',\n    })\n    return diagnostics\n  }\n\n  const result = AgentQaConfigSchema.safeParse(parsed)\n  if (!result.success) {\n    for (const issue of result.error.issues) {\n      diagnostics.push({\n        file: configPath,\n        line: 1,\n        column: 1,\n        message: `${issue.path.join('.')}: ${issue.message}`,\n        severity: 'error',\n      })\n    }\n  }\n\n  return diagnostics\n}\n\nfunction buildDiagnostic(file: string, message: string, severity: 'error' | 'warning' = 'error'): ValidationDiagnostic {\n  return {\n    file,\n    line: 1,\n    column: 1,\n    message,\n    severity,\n  }\n}\n\nexport function validateTestFile(filePath: string, content: string): ValidationDiagnostic[] {\n  const result = parseTestFile(content, filePath)\n  return result.errors.map((e) => ({\n    file: e.file,\n    line: e.line,\n    column: e.column,\n    message: e.message,\n    severity: e.severity,\n  }))\n}\n\nexport function validateSuiteFile(filePath: string, content: string, basedir: string): ValidationDiagnostic[] {\n  const diagnostics: ValidationDiagnostic[] = []\n\n  const lineCounter = new LineCounter()\n  let parsed: unknown\n  try {\n    parsed = parseYaml(content, { lineCounter })\n  } catch (err) {\n    // The message is the position only, as in the config and hooks arms.\n    diagnostics.push({\n      file: filePath,\n      line: 1,\n      column: 1,\n      message: yamlParseFailureMessage(err),\n      severity: 'error',\n    })\n    return diagnostics\n  }\n\n  const result = SuiteDefinitionSchema.safeParse(parsed)\n  if (!result.success) {\n    for (const issue of result.error.issues) {\n      diagnostics.push({\n        file: filePath,\n        line: 1,\n        column: 1,\n        message: `${issue.path.join('.')}: ${issue.message}`,\n        severity: 'error',\n      })\n    }\n    return diagnostics\n  }\n\n  // Check test references exist on disk\n  const doc = parseDocument(content, { lineCounter })\n  const testsNode = doc.contents && 'get' in doc.contents ? (doc.contents as { get: (key: string, keepScalar?: boolean) => unknown }).get('tests', true) : undefined\n\n  const tests = result.data.tests\n  for (let i = 0; i < tests.length; i++) {\n    const entry = tests[i]\n    const testPath = entry.test\n\n    if (!isPathInsideDir(testPath, basedir)) {\n      diagnostics.push({\n        file: filePath, line: 1, column: 1,\n        message: `Path traversal rejected: ${testPath}`,\n        severity: 'error',\n      })\n      continue\n    }\n\n    const resolved = path.resolve(basedir, testPath)\n    if (!existsSync(resolved)) {\n      let line = 1\n      let column = 1\n      const seqNode = testsNode as { items?: { range?: [number, number] }[] } | undefined\n      if (seqNode?.items?.[i]?.range) {\n        const pos = lineCounter.linePos(seqNode.items[i].range![0])\n        line = pos.line\n        column = pos.col\n      }\n      diagnostics.push({\n        file: filePath,\n        line,\n        column,\n        message: `Test reference not found: ${testPath} (resolved: ${resolved})`,\n        severity: 'error',\n      })\n    }\n  }\n\n  return diagnostics\n}\n\nexport function validateFilename(filePath: string): ValidationDiagnostic[] {\n  const basename = path.basename(filePath)\n  if (!VALID_FILENAME_RE.test(basename)) {\n    return [{\n      file: filePath,\n      line: 1,\n      column: 1,\n      message: `Invalid filename \"${basename}\" — expected pattern: [a-zA-Z0-9._-]+.(suite.)?(yaml|yml)`,\n      severity: 'warning',\n    }]\n  }\n  return []\n}\n\nexport async function validateHooksFile(\n  hooksFilePath: string,\n  options: { required?: boolean } = {},\n): Promise<ValidationDiagnostic[]> {\n  const diagnostics: ValidationDiagnostic[] = []\n\n  if (!existsSync(hooksFilePath)) {\n    if (options.required) {\n      return [buildDiagnostic(hooksFilePath, `Configured hooks file not found: ${hooksFilePath}`)]\n    }\n    return []\n  }\n\n  const { hooks, errors } = await parseHooksFile(hooksFilePath)\n  if (errors.length > 0) {\n    for (const err of errors) {\n      diagnostics.push({\n        file: hooksFilePath,\n        line: 1,\n        column: 1,\n        message: err,\n        severity: 'error',\n      })\n    }\n    return diagnostics\n  }\n\n  for (const hook of hooks) {\n    if (!existsSync(hook.file)) {\n      diagnostics.push({\n        file: hooksFilePath,\n        line: 1,\n        column: 1,\n        message: `Hook \"${hook.name}\": script file not found: ${hook.file}`,\n        severity: 'error',\n      })\n    }\n\n    for (const dep of hook.deps) {\n      if (!existsSync(dep)) {\n        diagnostics.push({\n          file: hooksFilePath,\n          line: 1,\n          column: 1,\n          message: `Hook \"${hook.name}\": dependency file not found: ${dep}`,\n          severity: 'error',\n        })\n      }\n    }\n\n    if (hook.packageFile && !existsSync(hook.packageFile)) {\n      diagnostics.push({\n        file: hooksFilePath,\n        line: 1,\n        column: 1,\n        message: `Hook \"${hook.name}\": package file not found: ${hook.packageFile}`,\n        severity: 'error',\n      })\n    }\n  }\n\n  return diagnostics\n}\n\nexport function validateHookReferences(\n  setupOrTeardown: string[],\n  hookIds: Set<string>,\n  filePath: string,\n  context: string,\n): ValidationDiagnostic[] {\n  const diagnostics: ValidationDiagnostic[] = []\n  for (const hookId of setupOrTeardown) {\n    if (!hookIds.has(hookId)) {\n      diagnostics.push({\n        file: filePath,\n        line: 1,\n        column: 1,\n        message: `Hook ID \"${hookId}\" referenced in ${context} but not defined in the configured hooks file`,\n        severity: 'warning',\n      })\n    }\n  }\n  return diagnostics\n}\n\nexport async function detectGlobOverlap(\n  testMatch: string[],\n  suiteMatch: string[],\n  ignore: string[],\n  cwd?: string,\n): Promise<string[]> {\n  if (testMatch.length === 0 || suiteMatch.length === 0) return []\n  const globOptions = {\n    ignore,\n    absolute: true,\n    ...(cwd ? { cwd } : {}),\n  }\n  const [testFiles, suiteFiles] = await Promise.all([\n    glob(testMatch, globOptions),\n    glob(suiteMatch, globOptions),\n  ])\n  const testSet = new Set(testFiles)\n  return suiteFiles.filter((f) => testSet.has(f))\n}\n\nfunction isSuiteFile(filePath: string): boolean {\n  return /\\.suite\\.(yaml|yml)$/.test(filePath)\n}\n\nexport async function validateFiles(\n  filePaths: string[],\n  configPath?: string,\n  options: { basedir?: string } = {},\n): Promise<ValidationResult> {\n  const diagnostics: ValidationDiagnostic[] = []\n\n  if (configPath) {\n    diagnostics.push(...await validateConfig(configPath))\n  }\n\n  for (const filePath of filePaths) {\n    diagnostics.push(...validateFilename(filePath))\n\n    let content: string\n    try {\n      content = await readFile(filePath, 'utf-8')\n    } catch (err) {\n      diagnostics.push({\n        file: filePath,\n        line: 1,\n        column: 1,\n        message: `Cannot read file: ${(err as Error).message}`,\n        severity: 'error',\n      })\n      continue\n    }\n\n    if (isSuiteFile(filePath)) {\n      diagnostics.push(...validateSuiteFile(filePath, content, options.basedir ?? process.cwd()))\n    } else {\n      diagnostics.push(...validateTestFile(filePath, content))\n    }\n  }\n\n  const errorCount = diagnostics.filter((d) => d.severity === 'error').length\n  const warningCount = diagnostics.filter((d) => d.severity === 'warning').length\n  const files = new Set(diagnostics.map((d) => d.file))\n\n  return {\n    diagnostics,\n    fileCount: filePaths.length,\n    errorCount,\n    warningCount,\n  }\n}\n\nasync function resolveExplicitWorkspaceFile(\n  workspace: ResolvedWorkspacePaths,\n  filePath: string,\n): Promise<{ record?: { absolutePath: string }; diagnostic?: ValidationDiagnostic }> {\n  const preferredKinds: WorkspaceFileKind[] = isSuiteFile(filePath)\n    ? ['suite', 'test']\n    : ['test', 'suite']\n\n  for (const kind of preferredKinds) {\n    try {\n      const record = await resolveWorkspaceFileTarget({\n        workspace,\n        kind,\n        filePath,\n        requireExisting: true,\n      })\n      return { record }\n    } catch {\n      // Try the other configured file kind before reporting the path as invalid.\n    }\n  }\n\n  return {\n    diagnostic: buildDiagnostic(\n      filePath,\n      `File is not matched by configured workspace testMatch or suiteMatch patterns: ${filePath}`,\n    ),\n  }\n}\n\nfunction appendDiagnostics(result: ValidationResult, diagnostics: ValidationDiagnostic[]): void {\n  for (const diagnostic of diagnostics) {\n    result.diagnostics.push(diagnostic)\n    if (diagnostic.severity === 'error') result.errorCount++\n    else result.warningCount++\n  }\n}\n\nasync function readConfigForPicks(configPath: string): Promise<AgentQaConfig | undefined> {\n  try {\n    const parsed = AgentQaConfigSchema.safeParse(\n      parseYaml(await readFile(configPath, 'utf-8'), { logLevel: 'error' }),\n    )\n    return parsed.success ? (parsed.data as AgentQaConfig) : undefined\n  } catch {\n    return undefined\n  }\n}\n\nasync function readSuiteForPicks(filePath: string) {\n  try {\n    const parsed = SuiteDefinitionSchema.safeParse(parseYaml(await readFile(filePath, 'utf-8')))\n    return parsed.success ? parsed.data : undefined\n  } catch {\n    return undefined\n  }\n}\n\nasync function readTestsForPicks(filePath: string) {\n  try {\n    const parsed = parseTestFile(await readFile(filePath, 'utf-8'), filePath)\n    return parsed.errors.length > 0 ? [] : parsed.tests\n  } catch {\n    return []\n  }\n}\n\nfunction browserEngine(name: unknown): BrowserEngine | undefined {\n  return name === 'chromium' || name === 'firefox' || name === 'webkit' ? name : undefined\n}\n\n// The same picks, through the same selectors, as `agent-qa run`, so both print the same words.\nasync function validateRemotePicks(\n  filePaths: readonly string[],\n  configPath: string,\n  configDir: string,\n): Promise<ValidationDiagnostic[]> {\n  const config = await readConfigForPicks(configPath)\n  if (config === undefined) return []\n  const remotes = config.registry?.remotes ?? []\n  const configBrowser = config.use?.browser\n  const runsInBrowser = (target: string | undefined) =>\n    target !== undefined && config.registry?.targets?.[target]?.platform === 'web'\n  const relative = (absolutePath: string) =>\n    path.relative(configDir, absolutePath).split(path.sep).join('/')\n\n  const diagnostics: ValidationDiagnostic[] = []\n  const reported = new Set<string>()\n  const report = (file: string, message: string) => {\n    const key = `${file}\\0${message}`\n    if (reported.has(key)) return\n    reported.add(key)\n    diagnostics.push(buildDiagnostic(file, message))\n  }\n\n  for (const filePath of filePaths) {\n    if (!isSuiteFile(filePath)) {\n      for (const test of await readTestsForPicks(filePath)) {\n        if (!runsInBrowser(test.target)) continue\n        const selected = selectWebPlace({\n          remotes,\n          test: test.use?.browser?.remote,\n          config: configBrowser?.remote,\n          file: relative(filePath),\n          engine: browserEngine(test.use?.browser?.name ?? configBrowser?.name),\n        })\n        if ('refusal' in selected) report(filePath, selected.refusal)\n      }\n      continue\n    }\n\n    const suite = await readSuiteForPicks(filePath)\n    if (suite === undefined || !runsInBrowser(suite.target)) continue\n    const members: { absolutePath: string; file: string; pick?: string }[] = []\n    for (const entry of suite.tests) {\n      if (!isPathInsideDir(entry.test, configDir)) continue\n      const absolutePath = path.resolve(configDir, entry.test)\n      const [member] = await readTestsForPicks(absolutePath)\n      if (member === undefined) continue\n      const pick = member.use?.browser?.remote\n      members.push({ absolutePath, file: relative(absolutePath), pick })\n    }\n    const selected = selectSuitePlace({\n      remotes,\n      suiteName: suite.name,\n      suiteFile: relative(filePath),\n      suite: suite.use?.browser?.remote,\n      config: configBrowser?.remote,\n      members: members.map(({ file, pick }) => ({ file, pick })),\n      engine: browserEngine(suite.use?.browser?.name ?? configBrowser?.name),\n    })\n    if (!('refusal' in selected)) continue\n    // An unknown member pick names the member file; every other refusal is the suite's.\n    const named = selected.refusal.startsWith('Unknown remote ')\n      ? members.find(({ file }) => selected.refusal.includes(` in ${file}. `))\n      : undefined\n    report(named?.absolutePath ?? filePath, selected.refusal)\n  }\n  return diagnostics\n}\n\n// The run-start refusal of a connection-only secret in a step, with the same sentence.\nasync function validateConnectionSecrets(\n  filePaths: readonly string[],\n  configPath: string,\n  configDir: string,\n): Promise<ValidationDiagnostic[]> {\n  const config = await readConfigForPicks(configPath)\n  if (config === undefined) return []\n  const names = new Set(configConnectionSecretNames(config))\n  if (names.size === 0) return []\n  const relative = (absolutePath: string) =>\n    path.relative(configDir, absolutePath).split(path.sep).join('/')\n\n  const diagnostics: ValidationDiagnostic[] = []\n  const reported = new Set<string>()\n  const check = async (absolutePath: string) => {\n    for (const test of await readTestsForPicks(absolutePath)) {\n      const steps = test.steps ?? []\n      for (const message of connectionSecretMisuse({ names, file: relative(absolutePath), steps })) {\n        const key = `${absolutePath}\\0${message}`\n        if (reported.has(key)) continue\n        reported.add(key)\n        diagnostics.push(buildDiagnostic(absolutePath, message))\n      }\n    }\n  }\n\n  for (const filePath of filePaths) {\n    if (!isSuiteFile(filePath)) {\n      await check(filePath)\n      continue\n    }\n    const suite = await readSuiteForPicks(filePath)\n    if (suite === undefined) continue\n    for (const entry of suite.tests) {\n      if (!isPathInsideDir(entry.test, configDir)) continue\n      await check(path.resolve(configDir, entry.test))\n    }\n  }\n  return diagnostics\n}\n\nfunction validateRequiredWorkspaceFiles(workspace: ResolvedWorkspacePaths): ValidationDiagnostic[] {\n  const diagnostics: ValidationDiagnostic[] = []\n  for (const [key, file] of [\n    ['workspace.envFile', workspace.envFile],\n    ['workspace.secretsFile', workspace.secretsFile],\n  ] as const) {\n    if (!existsSync(file.absolutePath)) {\n      diagnostics.push(buildDiagnostic(file.absolutePath, `Configured workspace file not found: ${key} -> ${file.absolutePath}`))\n    }\n  }\n  return diagnostics\n}\n\nexport async function validateProject(options: {\n  configPath?: string\n  files?: string[]\n  testMatch?: string[]\n  testPathIgnore?: string[]\n  suiteMatch?: string[]\n  hooksFile?: string\n  workspace?: ResolvedWorkspacePaths\n} = {}): Promise<ValidationResult> {\n  let filePaths: string[]\n  const preDiagnostics: ValidationDiagnostic[] = []\n\n  if (options.files && options.files.length > 0 && options.workspace) {\n    const resolvedFiles: string[] = []\n    for (const file of options.files) {\n      const { record, diagnostic } = await resolveExplicitWorkspaceFile(options.workspace, file)\n      if (record) resolvedFiles.push(record.absolutePath)\n      if (diagnostic) preDiagnostics.push(diagnostic)\n    }\n    filePaths = resolvedFiles\n  } else if (options.files && options.files.length > 0) {\n    filePaths = options.files.map((f) => path.resolve(f))\n  } else if (options.workspace) {\n    const [testFiles, suiteFiles] = await Promise.all([\n      discoverWorkspaceFiles({ workspace: options.workspace, kind: 'test' }),\n      discoverWorkspaceFiles({ workspace: options.workspace, kind: 'suite' }),\n    ])\n    filePaths = [...testFiles, ...suiteFiles].map(file => file.absolutePath)\n  } else {\n    const testPatterns = options.testMatch ?? []\n    const suitePatterns = options.suiteMatch ?? []\n    const allPatterns = [...testPatterns, ...suitePatterns]\n    const ignore = options.testPathIgnore ?? []\n    filePaths = allPatterns.length > 0\n      ? await glob(allPatterns, { ignore, absolute: true })\n      : []\n  }\n\n  const configPath = options.configPath ?? options.workspace?.configPath\n\n  const result = await validateFiles(filePaths, configPath, {\n    basedir: options.workspace?.configDir,\n  })\n  appendDiagnostics(result, preDiagnostics)\n  if (configPath) {\n    const configDir = options.workspace?.configDir ?? process.cwd()\n    appendDiagnostics(result, await validateRemotePicks(filePaths, configPath, configDir))\n    appendDiagnostics(result, await validateConnectionSecrets(filePaths, configPath, configDir))\n  }\n\n  const testPatterns = options.workspace?.testMatch ?? options.testMatch ?? []\n  const suitePatterns = options.workspace?.suiteMatch ?? options.suiteMatch ?? []\n  if (testPatterns.length > 0 && suitePatterns.length > 0) {\n    const ignore = options.workspace?.testPathIgnore ?? options.testPathIgnore ?? []\n    const overlapping = await detectGlobOverlap(testPatterns, suitePatterns, ignore, options.workspace?.configDir)\n    for (const filePath of overlapping) {\n      result.diagnostics.push({\n        file: filePath,\n        line: 1,\n        column: 1,\n        message: 'File matched by both testMatch and suiteMatch — may cause duplicate validation',\n        severity: 'warning',\n      })\n      result.warningCount++\n    }\n  }\n\n  appendDiagnostics(result, options.workspace ? validateRequiredWorkspaceFiles(options.workspace) : [])\n\n  const hooksFilePath = options.workspace?.hooksFile.absolutePath ?? options.hooksFile\n  const hooksDiags = hooksFilePath\n    ? await validateHooksFile(hooksFilePath, { required: Boolean(options.workspace) })\n    : []\n  for (const d of hooksDiags) {\n    result.diagnostics.push(d)\n    if (d.severity === 'error') result.errorCount++\n    else result.warningCount++\n  }\n\n  // Check hook ID references in test/suite files\n  if (hooksFilePath && hooksDiags.length === 0 && existsSync(hooksFilePath)) {\n    const { hooks } = await parseHooksFile(hooksFilePath)\n    const hookIds = new Set(hooks.map(h => h.id))\n\n    for (const filePath of filePaths) {\n      const workspaceRelativePath = options.workspace\n        ? path.relative(options.workspace.configDir, filePath).split(path.sep).join('/')\n        : filePath\n      const isWorkspaceFile = options.workspace\n        ? isWorkspacePathMatch({ workspace: options.workspace, kind: isSuiteFile(filePath) ? 'suite' : 'test', workspaceRelativePath })\n        : true\n      if (!isWorkspaceFile) continue\n\n      try {\n        const content = await readFile(filePath, 'utf-8')\n        const parsed = parseYaml(content)\n        if (parsed && typeof parsed === 'object') {\n          const setup = (parsed as Record<string, unknown>).setup as string[] | undefined\n          const teardown = (parsed as Record<string, unknown>).teardown as string[] | undefined\n          if (setup?.length) {\n            const refDiags = validateHookReferences(setup, hookIds, filePath, 'setup')\n            for (const d of refDiags) { result.diagnostics.push(d); result.warningCount++ }\n          }\n          if (teardown?.length) {\n            const refDiags = validateHookReferences(teardown, hookIds, filePath, 'teardown')\n            for (const d of refDiags) { result.diagnostics.push(d); result.warningCount++ }\n          }\n        }\n      } catch { /* skip files that can't be parsed */ }\n    }\n  }\n\n  return result\n}\n","import pc from 'picocolors'\nimport type { ValidationResult, ValidationDiagnostic } from './validate.js'\n\nfunction groupByFile(diagnostics: ValidationDiagnostic[]): Map<string, ValidationDiagnostic[]> {\n  const groups = new Map<string, ValidationDiagnostic[]>()\n  for (const d of diagnostics) {\n    const existing = groups.get(d.file)\n    if (existing) {\n      existing.push(d)\n    } else {\n      groups.set(d.file, [d])\n    }\n  }\n  return groups\n}\n\nfunction formatSeverity(severity: 'error' | 'warning', color: boolean): string {\n  if (severity === 'error') {\n    return color ? pc.red('error') : 'error'\n  }\n  return color ? pc.yellow('warning') : 'warning'\n}\n\nfunction formatOutput(result: ValidationResult, color: boolean): string {\n  if (result.diagnostics.length === 0) {\n    const check = color ? pc.green('\\u2714') : '\\u2714'\n    return `\\n${check} All files valid (${result.fileCount} file(s) checked)\\n`\n  }\n\n  const groups = groupByFile(result.diagnostics)\n  const lines: string[] = ['']\n\n  for (const [file, diagnostics] of groups) {\n    const header = color ? pc.underline(pc.bold(file)) : file\n    lines.push(header)\n\n    for (const d of diagnostics) {\n      const loc = `${d.line}:${d.column}`\n      const sev = formatSeverity(d.severity, color).padEnd(color ? 20 : 7)\n      lines.push(`  ${loc}  ${sev}  ${d.message}`)\n    }\n\n    lines.push('')\n  }\n\n  const filesWithIssues = groups.size\n  if (result.errorCount > 0) {\n    const cross = color ? pc.red('\\u2716') : '\\u2716'\n    lines.push(`${cross} ${result.errorCount} error(s), ${result.warningCount} warning(s) in ${filesWithIssues} file(s)`)\n  } else {\n    const warn = color ? pc.yellow('\\u26A0') : '\\u26A0'\n    lines.push(`${warn} ${result.warningCount} warning(s) in ${filesWithIssues} file(s)`)\n  }\n  lines.push('')\n\n  return lines.join('\\n')\n}\n\nexport function formatDiagnostics(result: ValidationResult): string {\n  return formatOutput(result, true)\n}\n\nexport function formatDiagnosticsPlain(result: ValidationResult): string {\n  return formatOutput(result, false)\n}\n","export function warnIfOutOfBounds(\n  coords: { x?: number; y?: number },\n  viewport: { width: number; height: number },\n  actionType: string,\n): void {\n  const { x, y } = coords\n  const { width, height } = viewport\n  if (x !== undefined && (x < 0 || x > width)) {\n    console.warn(`[${actionType}] x=${x} outside viewport bounds [0, ${width}]`)\n  }\n  if (y !== undefined && (y < 0 || y > height)) {\n    console.warn(`[${actionType}] y=${y} outside viewport bounds [0, ${height}]`)\n  }\n}\n","import { generateHookId as generateSharedHookId } from '@vostride/agent-qa-ids'\n\n// Re-exported so a caller that can validate a hook id can also mint one through core.\nexport function generateHookId(): string {\n  return generateSharedHookId()\n}\n","import { generateRunId as generateSharedRunId, isCanonicalRunId as isSharedCanonicalRunId } from '@vostride/agent-qa-ids'\n\nexport function generateRunId(): string {\n  return generateSharedRunId()\n}\n\n// The mint's inverse beside it, so the two never disagree on the id shape.\nexport function isCanonicalRunId(value: string): boolean {\n  return isSharedCanonicalRunId(value)\n}\n","export type RunAttributes = Record<string, string>\n\nexport const INTERNAL_ATTRIBUTE_PREFIX = 'agent-qa.'\nexport const ATTR_TRIGGER = 'agent-qa.trigger'\nexport const ATTR_RUNNER = 'agent-qa.runner'\nexport const ATTR_GATE_RUN = 'agent-qa.gate-run'\n\nexport type RunAttributeTrigger = 'cli' | 'dashboard' | 'api' | 'mcp'\nexport type RunAttributeRunner = 'local' | 'remote'\n\nexport const RUN_ATTRIBUTE_KEY_MAX_LENGTH = 256\nexport const RUN_ATTRIBUTE_VALUE_MAX_LENGTH = 4096\n\nexport interface ParsedRunAttrFlags {\n  attributes: RunAttributes\n  duplicateKeys: string[]\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction assertValidUserAttributeKey(key: string, sourceLabel: string): void {\n  if (key.length === 0) {\n    throw new Error(`${sourceLabel}: Attribute key must be non-empty`)\n  }\n  if (key.startsWith(INTERNAL_ATTRIBUTE_PREFIX)) {\n    throw new Error(`${sourceLabel}: Attribute key \"${key}\" uses the reserved prefix \"${INTERNAL_ATTRIBUTE_PREFIX}\"`)\n  }\n  if (key.length > RUN_ATTRIBUTE_KEY_MAX_LENGTH) {\n    throw new Error(`${sourceLabel}: Attribute key \"${key}\" exceeds ${RUN_ATTRIBUTE_KEY_MAX_LENGTH} characters`)\n  }\n}\n\nexport function validateUserRunAttributes(input: unknown, sourceLabel = 'run attributes'): RunAttributes {\n  if (input === undefined || input === null) return {}\n  if (!isPlainRecord(input)) {\n    throw new Error(`${sourceLabel}: attributes must be a plain object`)\n  }\n\n  const attributes = Object.create(null) as RunAttributes\n  for (const [key, value] of Object.entries(input)) {\n    assertValidUserAttributeKey(key, sourceLabel)\n    if (typeof value !== 'string') {\n      throw new Error(`${sourceLabel}: Attribute value for \"${key}\" must be a string`)\n    }\n    if (value.length > RUN_ATTRIBUTE_VALUE_MAX_LENGTH) {\n      throw new Error(`${sourceLabel}: Attribute value for \"${key}\" exceeds ${RUN_ATTRIBUTE_VALUE_MAX_LENGTH} characters`)\n    }\n    attributes[key] = value\n  }\n  return attributes\n}\n\nexport function parseRunAttrFlags(flags: string[] | undefined): ParsedRunAttrFlags {\n  const rawAttributes = Object.create(null) as Record<string, string>\n  const seen = new Set<string>()\n  const duplicateKeys = new Set<string>()\n\n  for (const flag of flags ?? []) {\n    const separator = flag.indexOf('=')\n    if (separator <= 0) {\n      throw new Error(`--run-attr must use KEY=VALUE format: \"${flag}\"`)\n    }\n    const key = flag.slice(0, separator)\n    const value = flag.slice(separator + 1)\n    if (seen.has(key)) duplicateKeys.add(key)\n    seen.add(key)\n    rawAttributes[key] = value\n  }\n\n  return {\n    attributes: validateUserRunAttributes(rawAttributes, '--run-attr'),\n    duplicateKeys: [...duplicateKeys].sort((left, right) => left.localeCompare(right)),\n  }\n}\n\nexport function buildInternalRunAttributes(input: {\n  trigger: RunAttributeTrigger\n  runner: RunAttributeRunner\n}): RunAttributes {\n  return {\n    [ATTR_TRIGGER]: input.trigger,\n    [ATTR_RUNNER]: input.runner,\n  }\n}\n\nexport function mergeRunAttributes(internal: RunAttributes, user: RunAttributes): RunAttributes {\n  return {\n    ...user,\n    ...internal,\n  }\n}\n\nexport function sortRunAttributesForDisplay(\n  attributes: RunAttributes,\n  activeKeys: string[] = [],\n): Array<[string, string]> {\n  const entries = Object.entries(attributes)\n  const rank = (key: string): [number, number, string] => {\n    const activeIndex = activeKeys.indexOf(key)\n    if (activeIndex >= 0) return [0, activeIndex, key]\n    if (key === ATTR_TRIGGER) return [1, 0, key]\n    if (key === ATTR_RUNNER) return [1, 1, key]\n    if (key === ATTR_GATE_RUN) return [1, 2, key]\n    if (key.startsWith(INTERNAL_ATTRIBUTE_PREFIX)) return [1, 3, key]\n    return [2, 0, key]\n  }\n\n  return entries.sort(([left], [right]) => {\n    const leftRank = rank(left)\n    const rightRank = rank(right)\n    return leftRank[0] - rightRank[0] ||\n      leftRank[1] - rightRank[1] ||\n      leftRank[2].localeCompare(rightRank[2])\n  })\n}\n\nexport function formatRunAttributesBlock(attributes: RunAttributes): string {\n  const entries = sortRunAttributesForDisplay(attributes)\n  if (entries.length === 0) return ''\n  return [\n    'Run attributes:',\n    ...entries.map(([key, value]) => `  ${key}=${value}`),\n  ].join('\\n')\n}\n","import { readFileSync, statSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport { SECRET_REFERENCE_PATTERN } from '@vostride/agent-qa-schema'\nimport { Ajv2020, type ErrorObject, type ValidateFunction } from 'ajv/dist/2020.js'\n\nimport type { ResolvedPluginEntry } from './resolve-entries.js'\n\nexport const MAX_PLUGIN_SCHEMA_BYTES = 256 * 1024\nexport const MAX_PLUGIN_SCHEMA_DEPTH = 64\n\nexport interface PluginConfigIssue {\n  scope: 'options' | 'settings'\n  remote?: string\n  path: (string | number)[]\n  message: string\n}\n\nexport interface PluginConfigInput {\n  options: unknown\n  remotes: readonly { name: string; settings?: unknown }[]\n}\n\ntype Scope = PluginConfigIssue['scope']\ntype DataPath = (string | number)[]\ntype JsonObject = Record<string, unknown>\n\nexport type LoadedPluginSchema =\n  | { ok: true; schema: JsonObject; validate: ValidateFunction }\n  | { ok: false; message: string }\n\nconst WHOLE_REFERENCE = new RegExp(`^${SECRET_REFERENCE_PATTERN.source}$`)\nconst REFERENCE_PLACEHOLDER = 'secret-reference'\nconst COMBINATORS = ['allOf', 'anyOf', 'oneOf'] as const\n\nfunction isObject(value: unknown): value is JsonObject {\n  return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction exceedsDepth(value: unknown, depth: number): boolean {\n  if (typeof value !== 'object' || value === null) return false\n  if (depth > MAX_PLUGIN_SCHEMA_DEPTH) return true\n  const children = Array.isArray(value) ? value : Object.values(value)\n  return children.some((child) => exceedsDepth(child, depth + 1))\n}\n\nexport function loadPluginSchema(packageDir: string, file: string): LoadedPluginSchema {\n  const path = resolve(packageDir, file)\n  let text: string\n  try {\n    if (statSync(path).size > MAX_PLUGIN_SCHEMA_BYTES) {\n      const kib = MAX_PLUGIN_SCHEMA_BYTES / 1024\n      const message = `${file} is larger than ${kib} KiB, the most a plugin schema may be`\n      return { ok: false, message }\n    }\n    text = readFileSync(path, 'utf-8')\n  } catch {\n    return { ok: false, message: `${file} is not readable JSON` }\n  }\n\n  let schema: unknown\n  try {\n    schema = JSON.parse(text)\n  } catch {\n    return { ok: false, message: `${file} is not readable JSON` }\n  }\n  if (exceedsDepth(schema, 1)) {\n    const levels = MAX_PLUGIN_SCHEMA_DEPTH\n    const message = `${file} nests deeper than ${levels} levels, the most a plugin schema may`\n    return { ok: false, message }\n  }\n  if (!isObject(schema)) {\n    return { ok: false, message: `${file} is not a valid JSON Schema (not an object)` }\n  }\n\n  // Formats stay annotations: strict mode refuses any format it has no validator for.\n  const ajv = new Ajv2020({ allErrors: true, strict: true, validateFormats: false })\n  ajv.addKeyword('credential')\n  try {\n    return { ok: true, schema, validate: ajv.compile(schema) }\n  } catch (error) {\n    const reason = (error instanceof Error ? error.message : String(error)).split('\\n', 1)[0]\n    return { ok: false, message: `${file} is not a valid JSON Schema (${reason})` }\n  }\n}\n\nfunction localDefinition(root: JsonObject, ref: unknown): JsonObject | undefined {\n  if (typeof ref !== 'string' || !ref.startsWith('#/$defs/')) return undefined\n  const defs = root.$defs\n  if (!isObject(defs)) return undefined\n  const found = defs[ref.slice('#/$defs/'.length)]\n  return isObject(found) ? found : undefined\n}\n\n// Pairs each credential-marked schema node with the data at the same place.\nfunction credentialPaths(\n  root: JsonObject,\n  schema: unknown,\n  data: unknown,\n  path: DataPath,\n  refs: ReadonlySet<string>,\n  found: DataPath[],\n): void {\n  if (!isObject(schema) || data === undefined) return\n  if (schema.credential === true) found.push(path)\n\n  const ref = schema.$ref\n  const definition = localDefinition(root, ref)\n  if (definition && typeof ref === 'string' && !refs.has(ref)) {\n    credentialPaths(root, definition, data, path, new Set([...refs, ref]), found)\n  }\n  for (const combinator of COMBINATORS) {\n    const branches = schema[combinator]\n    if (!Array.isArray(branches)) continue\n    for (const branch of branches) credentialPaths(root, branch, data, path, refs, found)\n  }\n  if (isObject(schema.properties) && isObject(data)) {\n    for (const [key, child] of Object.entries(schema.properties)) {\n      if (!Object.hasOwn(data, key)) continue\n      credentialPaths(root, child, data[key], [...path, key], refs, found)\n    }\n  }\n  if (isObject(schema.items) && Array.isArray(data)) {\n    data.forEach((item, index) => {\n      credentialPaths(root, schema.items, item, [...path, index], refs, found)\n    })\n  }\n}\n\nfunction valueAt(data: unknown, path: DataPath): unknown {\n  let current = data\n  for (const segment of path) {\n    if (typeof current !== 'object' || current === null) return undefined\n    current = (current as Record<string | number, unknown>)[segment]\n  }\n  return current\n}\n\nfunction replaceAt(data: unknown, path: DataPath, value: unknown): unknown {\n  const [head, ...rest] = path\n  if (head === undefined) return value\n  if (Array.isArray(data)) {\n    const copy = [...data]\n    copy[head as number] = replaceAt(copy[head as number], rest, value)\n    return copy\n  }\n  const record = data as JsonObject\n  return { ...record, [head]: replaceAt(record[head], rest, value) }\n}\n\nfunction pointerOf(path: DataPath): string {\n  return path\n    .map((segment) => `/${String(segment).replace(/~/g, '~0').replace(/\\//g, '~1')}`)\n    .join('')\n}\n\nfunction pathOfPointer(pointer: string): DataPath {\n  if (pointer === '') return []\n  return pointer\n    .slice(1)\n    .split('/')\n    .map((segment) => segment.replace(/~1/g, '/').replace(/~0/g, '~'))\n    .map((segment) => (/^\\d+$/.test(segment) ? Number(segment) : segment))\n}\n\nfunction dotted(scope: Scope, path: DataPath): string {\n  return path.reduce<string>(\n    (text, segment) =>\n      typeof segment === 'number' ? `${text}[${segment}]` : `${text}.${segment}`,\n    scope,\n  )\n}\n\nfunction describeError(scope: Scope, error: ErrorObject): { path: DataPath; sentence: string } {\n  const at = pathOfPointer(error.instancePath)\n  const params = error.params as Record<string, unknown>\n  const extra = params.additionalProperty ?? params.unevaluatedProperty\n  if (\n    (error.keyword === 'additionalProperties' || error.keyword === 'unevaluatedProperties')\n    && typeof extra === 'string'\n  ) {\n    const path = [...at, extra]\n    const noun = scope === 'options' ? 'an option' : 'a setting'\n    return { path, sentence: `${dotted(scope, path)} is not ${noun} this plugin takes` }\n  }\n  if (error.keyword === 'required' && typeof params.missingProperty === 'string') {\n    const path = [...at, params.missingProperty]\n    return { path, sentence: `${dotted(scope, path)} is required` }\n  }\n  return { path: at, sentence: `${dotted(scope, at)} ${error.message ?? 'is not valid'}` }\n}\n\nfunction checkValue(\n  loaded: Extract<LoadedPluginSchema, { ok: true }>,\n  scope: Scope,\n  value: unknown,\n  speaker: string,\n  remote: string | undefined,\n): PluginConfigIssue[] {\n  const data: unknown = value ?? {}\n  const marked: DataPath[] = []\n  credentialPaths(loaded.schema, loaded.schema, data, [], new Set(), marked)\n\n  let checked = data\n  const references = new Set<string>()\n  const literals = new Map<string, DataPath>()\n  for (const path of marked) {\n    const held = valueAt(data, path)\n    if (typeof held !== 'string') continue\n    if (WHOLE_REFERENCE.test(held)) {\n      checked = replaceAt(checked, path, REFERENCE_PLACEHOLDER)\n      references.add(pointerOf(path))\n    } else {\n      literals.set(pointerOf(path), path)\n    }\n  }\n\n  const issue = (path: DataPath, sentence: string): PluginConfigIssue => ({\n    scope,\n    ...(remote === undefined ? {} : { remote }),\n    path,\n    message: `${speaker}: ${sentence}.`,\n  })\n\n  const issues: PluginConfigIssue[] = []\n  if (!loaded.validate(checked)) {\n    for (const error of loaded.validate.errors ?? []) {\n      if (references.has(error.instancePath)) continue\n      const { path, sentence } = describeError(scope, error)\n      issues.push(issue(path, sentence))\n    }\n  }\n  for (const path of literals.values()) {\n    const sentence =\n      `${dotted(scope, path)} is a credential; write it as a {{secret:NAME}} reference to `\n      + 'workspace.secretsFile'\n    issues.push(issue(path, sentence))\n  }\n  return issues\n}\n\nexport function checkPluginConfig(\n  resolved: ResolvedPluginEntry,\n  config: PluginConfigInput,\n): PluginConfigIssue[] {\n  const { manifest, packageDir } = resolved\n  if (!manifest || !packageDir) return []\n  const entrySpeaker = `Plugin entry ${resolved.name}`\n  const issues: PluginConfigIssue[] = []\n\n  if (manifest.options !== undefined) {\n    const loaded = loadPluginSchema(packageDir, manifest.options)\n    if (loaded.ok) {\n      issues.push(...checkValue(loaded, 'options', config.options, entrySpeaker, undefined))\n    } else {\n      issues.push({ scope: 'options', path: [], message: `${entrySpeaker}: ${loaded.message}.` })\n    }\n  }\n\n  if (manifest.kind === 'remote' && config.remotes.length > 0) {\n    const loaded = loadPluginSchema(packageDir, manifest.settings)\n    if (!loaded.ok) {\n      issues.push({ scope: 'settings', path: [], message: `${entrySpeaker}: ${loaded.message}.` })\n      return issues\n    }\n    for (const remote of config.remotes) {\n      const speaker = `Remote ${remote.name}`\n      issues.push(...checkValue(loaded, 'settings', remote.settings, speaker, remote.name))\n    }\n  }\n\n  return issues\n}\n","import { loadPluginSchema } from './options-check.js'\nimport type { ResolvedPluginEntry } from './resolve-entries.js'\n\nexport interface PluginField {\n  path: string\n  type: string\n  required: boolean\n  default?: unknown\n  description?: string\n  credential: boolean\n}\n\nexport interface PluginDescription {\n  entry: string\n  package?: string\n  path?: string\n  origin: ResolvedPluginEntry['origin']\n  version?: string\n  protocol?: number\n  serves: string[]\n  methods: string[]\n  runFacts: string[]\n  skill?: string\n  options: PluginField[]\n  settings: PluginField[]\n}\n\ntype JsonObject = Record<string, unknown>\n\ninterface SchemaNode {\n  node: JsonObject\n  refs: ReadonlySet<string>\n}\n\nconst CHOICES = ['anyOf', 'oneOf'] as const\n\nfunction isObject(value: unknown): value is JsonObject {\n  return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n// A local $ref is followed into $defs, with the referring node's own keywords kept over it.\nfunction follow(root: JsonObject, value: unknown, refs: ReadonlySet<string>): SchemaNode {\n  if (!isObject(value)) return { node: {}, refs }\n  const ref = value.$ref\n  const defs = root.$defs\n  if (typeof ref !== 'string' || !ref.startsWith('#/$defs/') || refs.has(ref) || !isObject(defs)) {\n    return { node: value, refs }\n  }\n  const { $ref: _ref, ...own } = value\n  const target = follow(root, defs[ref.slice('#/$defs/'.length)], new Set([...refs, ref]))\n  return { node: { ...target.node, ...own }, refs: target.refs }\n}\n\nfunction literal(value: unknown): string {\n  return typeof value === 'string' ? `'${value}'` : JSON.stringify(value)\n}\n\nfunction typeOf(root: JsonObject, schema: SchemaNode): string {\n  const { node, refs } = schema\n  if (Array.isArray(node.enum)) return node.enum.map(literal).join(' | ')\n  if ('const' in node) return literal(node.const)\n  for (const choice of CHOICES) {\n    const branches = node[choice]\n    if (!Array.isArray(branches)) continue\n    const types = branches.map((branch) => typeOf(root, follow(root, branch, refs)))\n    return [...new Set(types)].join(' | ')\n  }\n  const type = node.type\n  if (type === 'array') {\n    const items = typeOf(root, follow(root, node.items, refs))\n    return items.includes(' | ') ? `(${items})[]` : `${items}[]`\n  }\n  if (typeof type === 'string') return type\n  if (Array.isArray(type)) return type.map(String).join(' | ')\n  return isObject(node.properties) ? 'object' : 'any'\n}\n\nfunction isCredential(root: JsonObject, schema: SchemaNode): boolean {\n  const { node, refs } = schema\n  if (node.credential === true) return true\n  return CHOICES.some((choice) => {\n    const branches = node[choice]\n    return Array.isArray(branches)\n      && branches.some((branch) => isCredential(root, follow(root, branch, refs)))\n  })\n}\n\nfunction collectFields(\n  root: JsonObject,\n  parent: SchemaNode,\n  prefix: string,\n  fields: PluginField[],\n): void {\n  const properties = parent.node.properties\n  if (!isObject(properties)) return\n  const required = Array.isArray(parent.node.required) ? parent.node.required : []\n  for (const [key, child] of Object.entries(properties)) {\n    const schema = follow(root, child, parent.refs)\n    const path = prefix === '' ? key : `${prefix}.${key}`\n    const { node } = schema\n    fields.push({\n      path,\n      type: typeOf(root, schema),\n      required: required.includes(key),\n      ...('default' in node ? { default: node.default } : {}),\n      ...(typeof node.description === 'string' ? { description: node.description } : {}),\n      credential: isCredential(root, schema),\n    })\n    collectFields(root, schema, path, fields)\n  }\n}\n\nexport function schemaFieldsOf(schema: JsonObject): PluginField[] {\n  const fields: PluginField[] = []\n  collectFields(schema, { node: schema, refs: new Set() }, '', fields)\n  return fields\n}\n\nfunction schemaFields(resolved: ResolvedPluginEntry, packageDir: string, file: string) {\n  const loaded = loadPluginSchema(packageDir, file)\n  if (!loaded.ok) throw new Error(`Plugin entry ${resolved.name}: ${loaded.message}.`)\n  return schemaFieldsOf(loaded.schema)\n}\n\nexport function describePlugin(resolved: ResolvedPluginEntry): PluginDescription {\n  const { manifest, packageDir } = resolved\n  if (manifest === undefined || packageDir === undefined) {\n    throw new Error(resolved.reason ?? `Plugin entry ${resolved.name} has no readable manifest.`)\n  }\n  const remote = manifest.kind === 'remote' ? manifest : undefined\n  return {\n    entry: resolved.name,\n    ...(resolved.origin === 'path' ? { path: resolved.label } : { package: resolved.label }),\n    origin: resolved.origin,\n    ...(resolved.version ? { version: resolved.version } : {}),\n    ...(remote === undefined ? {} : { protocol: remote.protocol }),\n    serves: [...(remote?.serves ?? [])],\n    methods: [...(remote?.methods ?? [])],\n    runFacts: [...(remote?.runFacts ?? [])],\n    ...(remote?.skill === undefined ? {} : { skill: remote.skill }),\n    options:\n      manifest.options === undefined ? [] : schemaFields(resolved, packageDir, manifest.options),\n    settings: remote === undefined ? [] : schemaFields(resolved, packageDir, remote.settings),\n  }\n}\n","import { secretReferenceNames } from '@vostride/agent-qa-schema'\n\nimport { checkPluginConfig } from './options-check.js'\nimport {\n  resolvePluginEntry,\n  type PluginEntryInput,\n  type ResolvedPluginEntry,\n  type ResolvePluginEntryOptions,\n} from './resolve-entries.js'\n\nexport interface PluginRemoteUse {\n  remote: string\n  place: 'web' | 'device'\n}\n\nexport interface PluginRemoteRefusal {\n  remote: string\n  entry: string\n  kind: 'version' | 'refused' | 'auth'\n  message: string\n  // Set when the refusal concerns only the remote's web tests or only its devices.\n  place?: PluginRemoteUse['place']\n}\n\nexport interface PluginRemoteRefusalsInput extends ResolvePluginEntryOptions {\n  plugins: readonly PluginEntryInput[]\n  remotes: readonly { name: string; plugin?: string; settings?: unknown }[]\n  uses: readonly PluginRemoteUse[]\n  // Absent, references are not checked against the secrets file.\n  declaredSecrets?: { has(name: string): boolean }\n}\n\nconst WEB_PROTOCOLS = ['playwright', 'cdp'] as const\n\nfunction listed(items: readonly string[]): string {\n  if (items.length <= 1) return items.join('')\n  return `${items.slice(0, -1).join(', ')} and ${items[items.length - 1]}`\n}\n\nfunction referenceNames(value: unknown): string[] {\n  if (typeof value === 'string') return secretReferenceNames(value)\n  if (Array.isArray(value)) return value.flatMap(referenceNames)\n  if (typeof value === 'object' && value !== null) {\n    return Object.values(value).flatMap(referenceNames)\n  }\n  return []\n}\n\nfunction servesSentences(\n  resolved: ResolvedPluginEntry,\n  places: ReadonlySet<PluginRemoteUse['place']>,\n): { place: PluginRemoteUse['place']; sentence: string }[] {\n  const manifest = resolved.manifest\n  if (manifest?.kind !== 'remote') return []\n  const serves: readonly string[] = manifest.serves\n  const sentences: { place: PluginRemoteUse['place']; sentence: string }[] = []\n  const what = `plugin entry ${resolved.name} serves ${listed(serves)}`\n  if (places.has('web') && !WEB_PROTOCOLS.some((protocol) => serves.includes(protocol))) {\n    sentences.push({ place: 'web', sentence: `${what}, and a web test needs playwright or cdp.` })\n  }\n  if (places.has('device') && !serves.includes('appium')) {\n    sentences.push({ place: 'device', sentence: `${what}, and a device needs appium.` })\n  }\n  return sentences\n}\n\n// What a run and validate can tell about a plugin remote without running its plugin.\nexport function pluginRemoteRefusals(input: PluginRemoteRefusalsInput): PluginRemoteRefusal[] {\n  const options = {\n    configDir: input.configDir,\n    ...(input.configPath === undefined ? {} : { configPath: input.configPath }),\n    agentQaVersion: input.agentQaVersion,\n    ...(input.protocols === undefined ? {} : { protocols: input.protocols }),\n  }\n  const places = new Map<string, Set<PluginRemoteUse['place']>>()\n  for (const use of input.uses) {\n    const seen = places.get(use.remote) ?? new Set()\n    seen.add(use.place)\n    places.set(use.remote, seen)\n  }\n\n  const resolvedEntries = new Map<string, ResolvedPluginEntry>()\n  const refusals: PluginRemoteRefusal[] = []\n  for (const [remoteName, used] of places) {\n    const remote = input.remotes.find((candidate) => candidate.name === remoteName)\n    if (remote?.plugin === undefined) continue\n    const entry = input.plugins.find((candidate) => candidate.name === remote.plugin)\n    if (entry === undefined) continue\n\n    let resolved = resolvedEntries.get(entry.name)\n    if (resolved === undefined) {\n      resolved = resolvePluginEntry(entry, options)\n      resolvedEntries.set(entry.name, resolved)\n    }\n    const refuse = (\n      kind: PluginRemoteRefusal['kind'],\n      sentence: string,\n      place?: PluginRemoteUse['place'],\n    ): void => {\n      refusals.push({\n        remote: remoteName,\n        entry: entry.name,\n        kind,\n        message: `Remote ${remoteName} cannot start: ${sentence}`,\n        ...(place === undefined ? {} : { place }),\n      })\n    }\n\n    if (resolved.state !== 'ok') {\n      const version =\n        resolved.state === 'version_mismatch' || resolved.state === 'protocol_mismatch'\n      refuse(version ? 'version' : 'refused', resolved.reason ?? '')\n      continue\n    }\n    if (resolved.manifest?.kind !== 'remote') {\n      refuse(\n        'refused',\n        `plugin entry ${entry.name} is a ${resolved.manifest?.kind ?? 'unknown'} plugin, and a `\n          + 'remote needs a remote plugin.',\n      )\n      continue\n    }\n\n    for (const { place, sentence } of servesSentences(resolved, used)) {\n      refuse('refused', sentence, place)\n    }\n\n    const issues = checkPluginConfig(resolved, {\n      options: entry.options,\n      remotes: [{ name: remoteName, settings: remote.settings }],\n    })\n    const ownPrefix = `Remote ${remoteName}: `\n    for (const issue of issues) {\n      const sentence = issue.message.startsWith(ownPrefix)\n        ? issue.message.slice(ownPrefix.length)\n        : issue.message\n      refuse('refused', sentence)\n    }\n\n    if (input.declaredSecrets !== undefined) {\n      const names = new Set([\n        ...referenceNames(entry.options),\n        ...referenceNames(remote.settings),\n      ])\n      for (const name of names) {\n        if (input.declaredSecrets.has(name)) continue\n        refuse(\n          'auth',\n          `plugin entry ${entry.name} uses secret ${name}, which workspace.secretsFile does `\n            + 'not declare.',\n        )\n      }\n    }\n  }\n  return refusals\n}\n","import { existsSync, lstatSync, readdirSync, readFileSync, statSync } from 'node:fs'\nimport { dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path'\n\nimport type { PluginManifest } from '@vostride/agent-qa-plugin-kit/protocol'\nimport { parse as parseYaml } from 'yaml'\n\nimport { findPackageJson } from '../plugin-loader-util.js'\nimport { schemaFieldsOf } from './describe.js'\nimport { readPluginManifest } from './manifest.js'\nimport { MAX_PLUGIN_SCHEMA_BYTES, loadPluginSchema } from './options-check.js'\nimport { pluginInstallLine, supportedPluginProtocols } from './resolve-entries.js'\n\nexport interface PluginPackageCheck {\n  name: string\n  ok: boolean\n  detail?: string\n  warning?: boolean\n}\n\nexport interface PluginPackageReport {\n  packageDir?: string\n  remote: boolean\n  checks: PluginPackageCheck[]\n}\n\nexport interface ValidatePluginPackageOptions {\n  configDir: string\n  configPath?: string\n  agentQaVersion: string\n  cwd?: string\n}\n\ntype JsonObject = Record<string, unknown>\ntype Scope = 'options' | 'settings'\n\ninterface SchemaFile {\n  scope: Scope\n  file: string\n}\n\nconst DRAFT_2020_12 = /^https:\\/\\/json-schema\\.org\\/draft\\/2020-12\\/schema#?$/\nconst CODE_EXTENSIONS = new Set(['.js', '.mjs', '.cjs', '.ts', '.sh', '.py'])\nconst CREDENTIAL_TERM =\n  /token|secret|password|passwd|passphrase|api[-_]?key|access[-_]?key|private[-_]?key|credential/i\nconst INSTALL_SCRIPTS = ['preinstall', 'install', 'postinstall']\nconst AGENT_QA_PACKAGE = /^(agent-qa|@vostride\\/agent-qa(-.+)?)$/\nconst PLUGIN_KEYWORD = 'agent-qa-plugin'\nconst FRONTMATTER = /^---\\r?\\n([\\s\\S]*?)\\r?\\n---(?:\\r?\\n|$)/\n\nfunction isObject(value: unknown): value is JsonObject {\n  return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction passed(name: string): PluginPackageCheck {\n  return { name, ok: true }\n}\n\nfunction failed(name: string, problems: readonly string[]): PluginPackageCheck {\n  return problems.length === 0 ? passed(name) : { name, ok: false, detail: problems.join('; ') }\n}\n\nfunction warned(name: string, problems: readonly string[]): PluginPackageCheck {\n  return problems.length === 0\n    ? passed(name)\n    : { name, ok: true, warning: true, detail: problems.join('; ') }\n}\n\nfunction shown(path: string): string {\n  return path.split(sep).join('/')\n}\n\nfunction isPathTarget(target: string): boolean {\n  if (target.startsWith('.') || isAbsolute(target)) return true\n  return !target.startsWith('@') && (target.includes('/') || target.includes('\\\\'))\n}\n\nfunction locate(\n  target: string,\n  options: ValidatePluginPackageOptions,\n): { packageJsonPath: string } | { check: PluginPackageCheck } {\n  if (isPathTarget(target)) {\n    const packageJsonPath = join(resolve(options.cwd ?? process.cwd(), target), 'package.json')\n    if (existsSync(packageJsonPath)) return { packageJsonPath }\n    return { check: failed('package', [`${target} has no package.json`]) }\n  }\n  const packageJsonPath = findPackageJson(target, options.configDir)\n  if (packageJsonPath !== null) return { packageJsonPath }\n  const install = pluginInstallLine({ name: target, package: target }, options.configPath)\n  if (install === undefined) {\n    return { check: failed('package', [`${target} is not an npm package name or a folder`]) }\n  }\n  return {\n    check: failed('package', [`${target} is not installed in this project. Run ${install}.`]),\n  }\n}\n\nfunction manifestCheck(manifest: PluginManifest): PluginPackageCheck {\n  if (manifest.kind !== 'remote') return passed('manifest')\n  const window = supportedPluginProtocols()\n  if (window.includes(manifest.protocol)) return passed('manifest')\n  return failed('manifest', [\n    `the manifest speaks plugin protocol ${manifest.protocol}; this agent-qa speaks `\n      + `${window.join(' and ')}`,\n  ])\n}\n\nfunction declaredSchemaOf(packageDir: string, file: string): unknown {\n  const path = resolve(packageDir, file)\n  try {\n    if (statSync(path).size > MAX_PLUGIN_SCHEMA_BYTES) return undefined\n    return JSON.parse(readFileSync(path, 'utf-8'))\n  } catch {\n    return undefined\n  }\n}\n\nfunction draftProblem(file: string, schema: unknown): string | undefined {\n  if (!isObject(schema)) return undefined\n  if (typeof schema.$schema !== 'string') return `${file} names no $schema`\n  if (DRAFT_2020_12.test(schema.$schema)) return undefined\n  return `${file} names ${schema.$schema}, not JSON Schema draft 2020-12`\n}\n\nfunction checkSchemas(\n  packageDir: string,\n  files: readonly SchemaFile[],\n): { check: PluginPackageCheck; loaded: { scope: Scope; schema: JsonObject }[] } {\n  const problems: string[] = []\n  const loaded: { scope: Scope; schema: JsonObject }[] = []\n  for (const { scope, file } of files) {\n    const declared = declaredSchemaOf(packageDir, file)\n    const draft = draftProblem(file, declared)\n    if (draft !== undefined) {\n      problems.push(draft)\n      continue\n    }\n    const schema = loadPluginSchema(packageDir, file)\n    if (schema.ok) loaded.push({ scope, schema: schema.schema })\n    else problems.push(schema.message)\n  }\n  return { check: failed('schemas', problems), loaded }\n}\n\nfunction checkCredentialMarks(loaded: readonly { scope: Scope; schema: JsonObject }[]) {\n  const problems = loaded.flatMap(({ scope, schema }) =>\n    schemaFieldsOf(schema)\n      .filter((field) => !field.credential && field.type.includes('string'))\n      .filter((field) => CREDENTIAL_TERM.test(field.path.split('.').at(-1) ?? ''))\n      .map(\n        (field) =>\n          `${scope}.${field.path} looks like a credential and has no credential mark; mark it `\n          + 'with credential() so config must hold a {{secret:NAME}} reference',\n      ),\n  )\n  return warned('credential-marks', problems)\n}\n\nfunction codeFiles(root: string, dir: string = root): string[] {\n  return readdirSync(dir).flatMap((name) => {\n    const path = join(dir, name)\n    const stats = lstatSync(path)\n    if (stats.isDirectory()) return codeFiles(root, path)\n    const code =\n      stats.isSymbolicLink()\n      || CODE_EXTENSIONS.has(extname(name).toLowerCase())\n      || (stats.mode & 0o111) !== 0\n    return code ? [shown(relative(root, path))] : []\n  })\n}\n\nfunction frontmatterProblems(skillFile: string, text: string): string[] {\n  const match = FRONTMATTER.exec(text)\n  let fields: unknown\n  try {\n    fields = match === null ? undefined : parseYaml(match[1] ?? '')\n  } catch {\n    return [`${skillFile} frontmatter is not YAML`]\n  }\n  if (!isObject(fields)) return [`${skillFile} has no frontmatter with name and description`]\n  return (['name', 'description'] as const)\n    .filter((key) => typeof fields[key] !== 'string' || fields[key].trim() === '')\n    .map((key) => `${skillFile} has no ${key} in its frontmatter`)\n}\n\nfunction checkSkill(packageDir: string, manifest: PluginManifest): PluginPackageCheck {\n  if (manifest.kind !== 'remote') return passed('skill')\n  if (manifest.skill === undefined) {\n    return warned('skill', [\n      'the manifest names no skill; a skill tells coding agents how to configure the plugin',\n    ])\n  }\n  const dir = resolve(packageDir, manifest.skill)\n  if (!existsSync(dir) || !statSync(dir).isDirectory()) {\n    return failed('skill', [`${manifest.skill} is not a folder in the package`])\n  }\n  const problems: string[] = []\n  const code = codeFiles(dir)\n  if (code.length > 0) {\n    problems.push(`the skill folder holds code (${code.join(', ')}); a skill is plain files`)\n  }\n  const skillPath = join(dir, 'SKILL.md')\n  const skillFile = shown(relative(packageDir, skillPath))\n  if (!existsSync(skillPath)) problems.push(`${skillFile} is missing`)\n  else problems.push(...frontmatterProblems(skillFile, readFileSync(skillPath, 'utf-8')))\n  return failed('skill', problems)\n}\n\nfunction checkPackage(packageJsonPath: string): PluginPackageCheck {\n  let pkg: unknown\n  try {\n    pkg = JSON.parse(readFileSync(packageJsonPath, 'utf-8'))\n  } catch {\n    return failed('package', ['package.json is not readable JSON'])\n  }\n  if (!isObject(pkg)) return failed('package', ['package.json is not an object'])\n  const problems: string[] = []\n  const scripts = isObject(pkg.scripts) ? Object.keys(pkg.scripts) : []\n  const installs = INSTALL_SCRIPTS.filter((name) => scripts.includes(name))\n  if (installs.length > 0) {\n    const names = installs.join(', ')\n    problems.push(`package.json runs ${names} on install; a plugin installs with no scripts`)\n  }\n  const peers = isObject(pkg.peerDependencies) ? Object.keys(pkg.peerDependencies) : []\n  for (const peer of peers.filter((name) => AGENT_QA_PACKAGE.test(name))) {\n    problems.push(\n      `package.json lists ${peer} in peerDependencies; agent-qa checks a plugin by its protocol, `\n        + 'not peerDependencies',\n    )\n  }\n  const keywords = Array.isArray(pkg.keywords) ? pkg.keywords : []\n  if (!keywords.includes(PLUGIN_KEYWORD)) {\n    problems.push(`package.json keywords lack ${PLUGIN_KEYWORD}, which npm search finds plugins by`)\n  }\n  return warned('package', problems)\n}\n\nexport function validatePluginPackage(\n  target: string,\n  options: ValidatePluginPackageOptions,\n): PluginPackageReport {\n  const located = locate(target, options)\n  if ('check' in located) return { remote: false, checks: [located.check] }\n\n  const { packageJsonPath } = located\n  const packageDir = dirname(packageJsonPath)\n  const read = readPluginManifest(packageJsonPath)\n  if (!read.ok) {\n    return {\n      packageDir,\n      remote: false,\n      checks: [failed('manifest', [read.issue]), checkPackage(packageJsonPath)],\n    }\n  }\n\n  const { manifest } = read\n  const files: SchemaFile[] = []\n  if (manifest.options !== undefined) files.push({ scope: 'options', file: manifest.options })\n  if (manifest.kind === 'remote') files.push({ scope: 'settings', file: manifest.settings })\n  const schemas = checkSchemas(packageDir, files)\n  return {\n    packageDir,\n    remote: manifest.kind === 'remote',\n    checks: [\n      manifestCheck(manifest),\n      schemas.check,\n      checkCredentialMarks(schemas.loaded),\n      checkSkill(packageDir, manifest),\n      checkPackage(packageJsonPath),\n    ],\n  }\n}\n","import { isAlias, isMap, isNode, isScalar, isSeq, parseDocument, Scalar, visit } from 'yaml'\nimport type { Document, Node, YAMLMap } from 'yaml'\nimport { projectConfigRemotes } from '@vostride/agent-qa-schema'\n\nconst MARK_KEY = 'agent-qa-mark'\n\ninterface ShownBlock {\n  readonly path: readonly [string, ...string[]]\n  readonly unshowable: string\n  readonly named: RegExp\n  shown(doc: Document, block: Node): unknown\n  // What an anchor the block reaches outside itself shows as.\n  reached(doc: Document, block: Node, shown: unknown, target: Node): unknown\n}\n\nfunction resolved(doc: Document, node: unknown): unknown {\n  return isAlias(node) ? node.resolve(doc) : node\n}\n\nfunction shownRemotes(doc: Document, remotes: Node): unknown[] {\n  try {\n    const projected = projectConfigRemotes({ registry: { remotes: remotes.toJS(doc) as unknown } })\n    return projected.registry.remotes as unknown[]\n  } catch {\n    return []\n  }\n}\n\nfunction entryUrls(doc: Document, remotes: Node): unknown[] {\n  if (!isSeq(remotes)) return []\n  return remotes.items.map((item) => {\n    const entry = resolved(doc, item)\n    const url = isMap(entry) ? resolved(doc, entry.get('url', true)) : undefined\n    return isScalar(url) && typeof url.value === 'string' ? url.value : undefined\n  })\n}\n\nconst REMOTES: ShownBlock = {\n  path: ['registry', 'remotes'],\n  unshowable: '# This config cannot be shown without its remote endpoints.\\n',\n  named: /(?<![\\w-])remotes(?![\\w-])/,\n  shown: shownRemotes,\n  reached(doc, remotes, shown, target) {\n    const urls = entryUrls(doc, remotes)\n    const index =\n      isScalar(target) && typeof target.value === 'string' ? urls.indexOf(target.value) : -1\n    const entry = (shown as unknown[])[index] as { url?: unknown } | undefined\n    return index >= 0 && entry !== undefined ? entry.url : null\n  },\n}\n\nconst PLUGINS: ShownBlock = {\n  path: ['plugins'],\n  unshowable: '# This config cannot be shown without its plugin options.\\n',\n  named: /(?<![\\w-])plugins(?![\\w-])/,\n  shown(doc, plugins) {\n    try {\n      return projectConfigRemotes({ plugins: plugins.toJS(doc) as unknown }).plugins\n    } catch {\n      return []\n    }\n  },\n  reached: () => null,\n}\n\ninterface FoundBlock {\n  readonly root: YAMLMap\n  // Every map on the path from the root, the block's own parent last.\n  readonly maps: readonly YAMLMap[]\n  readonly block: Node\n}\n\nfunction blockAt(doc: Document, path: ShownBlock['path']): FoundBlock | undefined {\n  const root = resolved(doc, doc.contents)\n  if (!isMap(root)) return undefined\n  const maps: YAMLMap[] = [root]\n  for (const key of path.slice(0, -1)) {\n    const next = resolved(doc, maps[maps.length - 1]!.get(key, true))\n    if (!isMap(next)) return undefined\n    maps.push(next)\n  }\n  const block = resolved(doc, maps[maps.length - 1]!.get(path[path.length - 1], true))\n  if (!isNode(block) || (isScalar(block) && block.value === null)) return undefined\n  return { root, maps, block }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n// What the config loader reads: yaml's parse is parseDocument followed by toJS.\nfunction loadedAt(doc: Document, path: ShownBlock['path']): unknown {\n  let loaded: unknown = doc.toJS()\n  for (const key of path) {\n    if (!isRecord(loaded)) return undefined\n    loaded = loaded[key]\n  }\n  return loaded\n}\n\n// The marker goes inside the block, not in its place, so every anchor in the block still resolves.\nfunction loadsFromBlock(doc: Document, path: ShownBlock['path']): boolean {\n  const copy = doc.clone()\n  const found = blockAt(copy, path)\n  if (found === undefined) return false\n  const mark = {}\n  const { block } = found\n  if (isSeq(block)) {\n    block.add(new Scalar(mark))\n    const loaded = loadedAt(copy, path)\n    return Array.isArray(loaded) && loaded[loaded.length - 1] === mark\n  }\n  if (isMap(block)) {\n    // A merge converts the map it copies again, so a second conversion means a merge reached it.\n    let conversions = 0\n    block.set(MARK_KEY, {\n      toJSON: () => {\n        conversions += 1\n        return mark\n      },\n    })\n    const loaded = loadedAt(copy, path)\n    return conversions === 1 && isRecord(loaded) && loaded[MARK_KEY] === mark\n  }\n  if (!isScalar(block)) return false\n  const marker = new Scalar(mark)\n  marker.anchor = block.anchor\n  found.maps[found.maps.length - 1]!.set(path[path.length - 1], marker)\n  return loadedAt(copy, path) === mark\n}\n\nfunction nodesUnder(node: Node): unknown[] {\n  const nodes: unknown[] = []\n  visit(node, (_key, child) => {\n    nodes.push(child)\n  })\n  return nodes\n}\n\n// The block is replaced whole: comments inside it can sit beside endpoints and credentials.\n// Every anchor the block holds or reaches through aliases is replaced, and so is every alias of it.\n// Text whose block may not be that block, or that does not parse and names it: one line.\nfunction projectBlockInText(raw: string, shape: ShownBlock): string {\n  // yaml's warnings quote the file's text, so only its errors are reported.\n  const doc = parseDocument(raw, { logLevel: 'error' })\n  if (doc.errors.length > 0) return shape.named.test(raw) ? shape.unshowable : raw\n  try {\n    const found = blockAt(doc, shape.path)\n    if (found === undefined) return loadedAt(doc, shape.path) == null ? raw : shape.unshowable\n    if (!loadsFromBlock(doc, shape.path)) return shape.unshowable\n    const { root, maps, block } = found\n\n    const hidden = new Set<unknown>(nodesUnder(block))\n    const reached: Node[] = []\n    const pending = nodesUnder(block).filter(isAlias)\n    for (let alias = pending.pop(); alias !== undefined; alias = pending.pop()) {\n      const target = alias.resolve(doc)\n      if (!isNode(target) || hidden.has(target)) continue\n      const under = nodesUnder(target)\n      if (\n        target === root ||\n        maps.some((map) => map !== root && under.includes(map)) ||\n        under.includes(block)\n      ) {\n        return shape.unshowable\n      }\n      for (const node of under) hidden.add(node)\n      reached.push(target)\n      pending.push(...under.filter(isAlias))\n    }\n\n    const shown = shape.shown(doc, block)\n    const replacements = new Map<unknown, unknown>([[block, shown]])\n    for (const target of reached) {\n      replacements.set(target, shape.reached(doc, block, shown, target))\n    }\n    // Each alias of a hidden node is resolved before any node is replaced, while its anchor exists.\n    visit(doc, (_key, node) => {\n      if (!isAlias(node)) return\n      const target = node.resolve(doc)\n      if (hidden.has(target)) replacements.set(node, replacements.get(target) ?? null)\n    })\n\n    visit(doc, (_key, node) =>\n      replacements.has(node) ? doc.createNode(replacements.get(node)) : undefined,\n    )\n    maps[maps.length - 1]!.set(shape.path[shape.path.length - 1], doc.createNode(shown))\n    return doc.toString({ lineWidth: 0, flowCollectionPadding: false })\n  } catch {\n    return shape.unshowable\n  }\n}\n\n// A served config's text shows remotes by name and protocol or plugins entry, and plugins entries\n// by name and package or path; endpoints, credentials and plugin options stay in the file.\nexport function projectRemotesInConfigText(raw: string): string {\n  const withoutRemotes = projectBlockInText(raw, REMOTES)\n  if (withoutRemotes === REMOTES.unshowable) return withoutRemotes\n  return projectBlockInText(withoutRemotes, PLUGINS)\n}\n","import {\n  basicAuthorizationValue,\n  RemoteRefusalError,\n  resolveSecretTemplatesInValue,\n} from '@vostride/agent-qa-runner'\nimport type { RemoteDeviceConfig, SecretResolver } from '@vostride/agent-qa-runner'\nimport {\n  connectionSecretNames,\n  remoteLabel,\n  SECRET_REFERENCE_PATTERN,\n} from '@vostride/agent-qa-schema'\n\nexport interface RemoteDeviceEndpoint {\n  readonly protocol: 'http' | 'https'\n  readonly hostname: string\n  readonly port: number\n  readonly path: string\n  // Sent on every request; a key the url repeats keeps its last value.\n  readonly query?: Readonly<Record<string, string>>\n}\n\nexport interface RemoteDeviceConnection extends RemoteDeviceEndpoint {\n  readonly headers: Readonly<Record<string, string>>\n}\n\n// Undefined for a url that is neither http nor https.\nexport function remoteDeviceEndpoint(url: URL): RemoteDeviceEndpoint | undefined {\n  const protocol =\n    url.protocol === 'https:' ? 'https' : url.protocol === 'http:' ? 'http' : undefined\n  if (protocol === undefined) return undefined\n  const query = Object.fromEntries(url.searchParams)\n  return {\n    protocol,\n    hostname: url.hostname,\n    port: url.port === '' ? (protocol === 'https' ? 443 : 80) : Number(url.port),\n    path: url.pathname === '' ? '/' : url.pathname,\n    ...(Object.keys(query).length === 0 ? {} : { query }),\n  }\n}\n\nexport interface RemoteDeviceConnectionInput {\n  readonly remote: RemoteDeviceConfig\n  readonly device: string\n  readonly secrets?: SecretResolver | undefined\n  readonly secretsFile?: string | undefined\n}\n\n// Resolved at connect into fresh values; the remote config keeps its references.\nexport function resolveRemoteDeviceConnection(\n  input: RemoteDeviceConnectionInput,\n): RemoteDeviceConnection {\n  const { remote, device, secrets } = input\n  const label = remoteLabel(remote)\n  const missing = connectionSecretNames([remote]).find((name) => secrets?.has(name) !== true)\n  if (missing !== undefined) {\n    const secretsFile = input.secretsFile ?? 'workspace.secretsFile'\n    throw new RemoteRefusalError(\n      `Device ${device} on remote ${label} needs ${missing}, which ${secretsFile} does not declare. Add it there.`,\n      { remote: label },\n    )\n  }\n  const pattern = new RegExp(SECRET_REFERENCE_PATTERN.source, 'g')\n  const url = new URL(\n    secrets === undefined\n      ? remote.url\n      : remote.url.replace(pattern, (_found, name: string) =>\n          encodeURIComponent(secrets.require(name)),\n        ),\n  )\n  const endpoint = remoteDeviceEndpoint(url)\n  if (endpoint === undefined) {\n    throw new RemoteRefusalError(\n      `Device ${device} on remote ${label}: an appium url starts with http:// or https://.`,\n      { remote: label },\n    )\n  }\n  const headers: Record<string, string> = resolveSecretTemplatesInValue(\n    { ...remote.headers },\n    secrets,\n  )\n  if (remote.basicAuth !== undefined) {\n    const { user, password } = resolveSecretTemplatesInValue(remote.basicAuth, secrets)\n    headers.Authorization = `Basic ${basicAuthorizationValue(user, password)}`\n  }\n  return { ...endpoint, headers }\n}\n","import type {\n  IOSDeviceType,\n  RemoteDeviceConfig,\n  RemoteFailureKind,\n} from '@vostride/agent-qa-runner'\nimport { formatRemoteOrigin, remoteLabel, remoteOrigin } from '@vostride/agent-qa-schema'\n\n/** How long any request after the new session may go unanswered before the test ends as lost. */\nexport const REMOTE_COMMAND_BOUND_MS = 120_000\n\ntype RemoteNamed = Pick<RemoteDeviceConfig, 'name' | 'protocol' | 'url'>\n\nexport function remoteDeviceLabel(remote: RemoteNamed): string {\n  return remoteLabel(remote)\n}\n\nexport interface RemoteDeviceReply {\n  readonly statusCode: number\n  readonly body: unknown\n}\n\nexport interface RemoteDeviceRequestBounds {\n  readonly clientTimeoutMs: number\n  boundRequest<T extends { signal?: AbortSignal | null | undefined }>(request: T): T\n  captureReply<T extends RemoteDeviceReply>(reply: T): T\n  markOpened(): void\n  newSessionReply(): RemoteDeviceReply | undefined\n}\n\n// The new session waits up to the connect timeout and every later request up to the command bound.\n// WebdriverIO's own per-request timeout must be at least the larger of the two.\nexport function createRemoteDeviceRequestBounds(options: {\n  connectTimeoutMs: number\n  commandBoundMs: number\n}): RemoteDeviceRequestBounds {\n  let opened = false\n  let reply: RemoteDeviceReply | undefined\n  return {\n    clientTimeoutMs: Math.max(options.connectTimeoutMs, options.commandBoundMs),\n    boundRequest(request) {\n      const bound = AbortSignal.timeout(opened ? options.commandBoundMs : options.connectTimeoutMs)\n      const existing = request.signal ?? undefined\n      const signal = existing === undefined ? bound : AbortSignal.any([existing, bound])\n      return Object.assign(request, { signal })\n    },\n    captureReply(received) {\n      if (!opened) reply ??= { statusCode: received.statusCode, body: received.body }\n      return received\n    },\n    markOpened() {\n      opened = true\n    },\n    newSessionReply() {\n      return reply\n    },\n  }\n}\n\nfunction messageOf(error: unknown): string {\n  if (error instanceof Error) return error.message\n  if (typeof error === 'object' && error !== null && 'message' in error) {\n    const { message } = error as { message: unknown }\n    return typeof message === 'string' ? message : ''\n  }\n  return ''\n}\n\nfunction nameOf(error: unknown): string {\n  if (typeof error === 'object' && error !== null && 'name' in error) {\n    const { name } = error as { name: unknown }\n    return typeof name === 'string' ? name : ''\n  }\n  return ''\n}\n\nconst REQUEST_TIMED_OUT = 'Request timed out!'\nconst UNPARSABLE_BODY = 'Could not parse response body'\n\nexport function classifyNewSessionFailure(\n  reply: RemoteDeviceReply | undefined,\n  error: unknown,\n): RemoteFailureKind {\n  if (reply === undefined) {\n    const message = messageOf(error)\n    if (message.includes(REQUEST_TIMED_OUT)) return 'timeout'\n    if (message.includes(UNPARSABLE_BODY)) return 'refused'\n    return 'unreachable'\n  }\n  if (reply.statusCode === 401 || reply.statusCode === 403) return 'auth'\n  if (reply.statusCode === 429 || reply.statusCode === 503) return 'capacity'\n  return 'refused'\n}\n\nconst ENDPOINT_URL = /\\b(?:wss?|https?):\\/\\/[^\\s'\"`<>]+/gi\nconst TRAILING_PUNCTUATION = /[.,;:!?)'\"]+$/\nconst SERVER_REASON_MAX = 200\n\nfunction originText(url: string): string {\n  const origin = remoteOrigin(url)\n  if (origin !== undefined) return formatRemoteOrigin(origin)\n  const scheme = /^([a-z]+):\\/\\//i.exec(url)?.[1]?.toLowerCase() ?? ''\n  const authority = url.replace(/^[a-z]+:\\/\\//i, '').split(/[/?#]/, 1)[0] ?? ''\n  return `${scheme}://${authority.slice(authority.lastIndexOf('@') + 1)}`\n}\n\nfunction replaceUrls(text: string, replace: (url: string) => string): string {\n  return text.replace(ENDPOINT_URL, (found) => {\n    const trailing = TRAILING_PUNCTUATION.exec(found)?.[0] ?? ''\n    return `${replace(found.slice(0, found.length - trailing.length))}${trailing}`\n  })\n}\n\nfunction replyMessage(reply: RemoteDeviceReply | undefined): string | undefined {\n  const body = reply?.body\n  if (typeof body !== 'object' || body === null) return undefined\n  const value = (body as { value?: unknown }).value\n  if (typeof value !== 'object' || value === null) return undefined\n  const message = (value as { message?: unknown }).message\n  return typeof message === 'string' ? message : undefined\n}\n\nfunction unparsableBody(error: unknown): string | undefined {\n  const message = messageOf(error)\n  const start = message.indexOf(`${UNPARSABLE_BODY}: \"`)\n  if (start === -1) return undefined\n  const body = message.slice(start + UNPARSABLE_BODY.length + 3)\n  const end = body.lastIndexOf('\" when running \"')\n  return end === -1 ? body.replace(/\"$/, '') : body.slice(0, end)\n}\n\n// The server's text can hold the endpoint, path tokens and echoed secrets.\nexport function serverReasonLine(\n  source: { reply?: RemoteDeviceReply | undefined; error?: unknown },\n  mask: (text: string) => string,\n): string | undefined {\n  const text = replyMessage(source.reply) ?? unparsableBody(source.error)\n  if (text === undefined) return undefined\n  const line = text\n    .replace(/<[^>]*>/g, ' ')\n    .split(/\\r?\\n/)\n    .map((part) => part.replace(/\\s+/g, ' ').trim())\n    .find((part) => part !== '')\n  if (line === undefined) return undefined\n  const masked = mask(replaceUrls(line, originText))\n  if (masked.length <= SERVER_REASON_MAX) return masked\n  return `${masked.slice(0, SERVER_REASON_MAX - 1).trimEnd()}…`\n}\n\nexport interface RemoteDeviceRefusalContext {\n  readonly remote: RemoteDeviceConfig\n  readonly device: string\n  readonly secretsFile?: string | undefined\n  readonly secretNames: readonly string[]\n  readonly reason?: string | undefined\n}\n\nfunction formatDuration(ms: number): string {\n  if (ms > 0 && ms % 60_000 === 0) return `${String(ms / 60_000)}m`\n  if (ms > 0 && ms % 1_000 === 0) return `${String(ms / 1_000)}s`\n  return `${String(ms)}ms`\n}\n\nfunction listNames(names: readonly string[]): string {\n  if (names.length <= 1) return names.join('')\n  return `${names.slice(0, -1).join(', ')} and ${names[names.length - 1] as string}`\n}\n\nexport function remoteDeviceRefusalSentence(\n  kind: RemoteFailureKind,\n  context: RemoteDeviceRefusalContext,\n): string {\n  const label = remoteDeviceLabel(context.remote)\n  const device = context.device\n  switch (kind) {\n    case 'auth': {\n      if (context.secretNames.length === 0) {\n        return `Remote ${label} refused the credentials for device ${device}. Check its headers and basicAuth in registry.remotes.`\n      }\n      const secretsFile = context.secretsFile ?? 'workspace.secretsFile'\n      return `Remote ${label} refused the credentials for device ${device}. Check ${listNames(context.secretNames)} in ${secretsFile}.`\n    }\n    case 'refused': {\n      const reason = context.reason?.replace(/[\\s.]+$/, '')\n      if (reason === undefined || reason === '') {\n        return `Remote ${label} refused a session for device ${device}.`\n      }\n      return `Remote ${label} refused a session for device ${device}: ${reason}.`\n    }\n    case 'timeout':\n      return `Remote ${label} did not open a session for device ${device} within ${formatDuration(context.remote.connectTimeoutMs)}. Raise its connectTimeout or check the service.`\n    case 'capacity':\n      return `Remote ${label} has no free device for ${device}. Lower use.workers or raise the service's limit.`\n    default:\n      return `Remote ${label} did not answer for device ${device}. Check its url and that the server is running.`\n  }\n}\n\nconst SOCKET_FAILURE =\n  /Failed to fetch|fetch failed|socket hang up|other side closed|Request failed with error code|ECONNRESET|ECONNREFUSED|EPIPE|ETIMEDOUT|ENOTFOUND|EHOSTUNREACH|ENETUNREACH|UND_ERR_/i\nconst SESSION_ENDED =\n  /invalid session id|session (?:is )?not found|no such session|terminated or not started|session (?:was |has )?ended/i\n\nfunction isRequestTimeout(error: unknown): boolean {\n  const name = nameOf(error)\n  return (\n    messageOf(error).includes(REQUEST_TIMED_OUT) || name === 'TimeoutError' || name === 'AbortError'\n  )\n}\n\n// A reply carries its status or names its W3C error; a transport failure is a plain Error.\nfunction serverAnswered(error: unknown): boolean {\n  if (typeof error === 'object' && error !== null && 'statusCode' in error) {\n    if (typeof (error as { statusCode: unknown }).statusCode === 'number') return true\n  }\n  const name = nameOf(error)\n  return name !== '' && name !== 'Error'\n}\n\n// A server that answered is still reachable, whatever its text says about its own connections.\nexport function classifyCommandFailure(error: unknown): 'lost' | 'ended' | undefined {\n  const text = `${nameOf(error)} ${messageOf(error)}`\n  if (SESSION_ENDED.test(text)) return 'ended'\n  if (isRequestTimeout(error)) return 'lost'\n  if (!serverAnswered(error) && SOCKET_FAILURE.test(text)) return 'lost'\n  return undefined\n}\n\n// A lost session that timed out names the command bound; any other loss is the connection.\nexport function remoteDeviceLostSentence(\n  kind: 'lost' | 'ended',\n  context: { remote: RemoteNamed; device: string; error?: unknown },\n): string {\n  const label = remoteDeviceLabel(context.remote)\n  if (kind === 'ended') {\n    return `Remote ${label} ended the session for device ${context.device} while this test ran.`\n  }\n  if (context.error !== undefined && isRequestTimeout(context.error)) {\n    return `Remote ${label} did not answer a command for device ${context.device} within ${formatDuration(REMOTE_COMMAND_BOUND_MS)}.`\n  }\n  return `The connection to remote ${label} was lost while device ${context.device} ran this test.`\n}\n\n// WebdriverIO's errors repeat the full request url, with its path, session id and query.\nexport function scrubDeviceEndpoint(text: string, remote: RemoteNamed): string {\n  const label = remoteDeviceLabel(remote)\n  const origin = remoteOrigin(remote.url)\n  if (origin === undefined) return remote.url === '' ? text : text.split(remote.url).join(label)\n  const remoteOriginText = formatRemoteOrigin(origin)\n  // The label holds the remote's origin itself, so it is kept as it is.\n  return text\n    .split(label)\n    .map((part) =>\n      replaceUrls(part, (url) => {\n        const found = originText(url)\n        return found === remoteOriginText ? label : found\n      }),\n    )\n    .join(label)\n}\n\nfunction debugNames(value: string): RegExp[] {\n  return value\n    .split(',')\n    .map((part) => part.trim())\n    .filter((part) => part !== '')\n    .map((part) => {\n      const escaped = part.split('*').map((piece) => piece.replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&'))\n      return new RegExp(`^${escaped.join('.*')}$`, 'i')\n    })\n}\n\nexport function deviceDebugLoggingRefusal(\n  env: { WDIO_LOG_LEVEL?: string | undefined; NODE_DEBUG?: string | undefined },\n  context: { remote: Pick<RemoteDeviceConfig, 'name'>; device: string },\n): string | undefined {\n  const { remote, device } = context\n  const level = env.WDIO_LOG_LEVEL?.trim() ?? ''\n  if (level !== '' && level.toLowerCase() !== 'silent') {\n    return `WDIO_LOG_LEVEL turns on WebdriverIO's own logging, which would print remote ${remote.name}'s address and requests. Unset WDIO_LOG_LEVEL to run device ${device}.`\n  }\n  const patterns = debugNames(env.NODE_DEBUG ?? '')\n  const named = ['undici', 'fetch'].find((name) => patterns.some((pattern) => pattern.test(name)))\n  if (named !== undefined) {\n    return `NODE_DEBUG names ${named}, which prints remote ${remote.name}'s request paths. Remove undici and fetch from NODE_DEBUG to run device ${device}.`\n  }\n  return undefined\n}\n\n// WebdriverIO's logger level is global, so one remote device keeps every session silent.\nexport function webdriverLogLevel(options: {\n  verbose: boolean\n  anyRemoteDevice: boolean\n}): 'info' | 'silent' {\n  return options.verbose && !options.anyRemoteDevice ? 'info' : 'silent'\n}\n\nexport function anyRemoteDevice(config: {\n  registry?: { devices?: Record<string, { remote?: unknown }> | undefined } | undefined\n}): boolean {\n  return Object.values(config.registry?.devices ?? {}).some((device) => device.remote !== undefined)\n}\n\nexport function iosDeviceTypeFromInfo(info: unknown): IOSDeviceType {\n  if (typeof info !== 'object' || info === null) return 'unknown'\n  const reply = info as { isSimulator?: unknown; lockdownInfo?: unknown }\n  if (reply.isSimulator === true) return 'simulator'\n  if (reply.isSimulator === false || reply.lockdownInfo !== undefined) return 'real device'\n  return 'unknown'\n}\n\nexport function isUnknownCommandError(error: unknown): boolean {\n  const name = nameOf(error)\n  return name === 'unknown command' || name === 'unknown method'\n}\n\n// A server may refuse one device and serve another, so a refused session is kept per device.\nexport function remoteDeviceRefusalKey(\n  remote: Pick<RemoteDeviceConfig, 'name'>,\n  device: string,\n  kind: RemoteFailureKind | undefined,\n): string {\n  return kind === 'refused' ? `${remote.name}/${device}` : remote.name\n}\n","import {\n  MIN_PLUGIN_CONNECT_MS,\n  releasingOnce,\n  RemoteRefusalError,\n  resolveSecretTemplatesInValue,\n} from '@vostride/agent-qa-runner'\nimport type {\n  RemoteDeviceConfig,\n  RemoteLease,\n  RemoteLeaseSource,\n  RemotePluginDeviceConfig,\n  RemoteRefusalMemory,\n  SecretResolver,\n} from '@vostride/agent-qa-runner'\nimport { remoteLabel, secretReferenceNames } from '@vostride/agent-qa-schema'\nimport {\n  capabilityValue,\n  mergeCapabilities,\n  remoteAppCapability,\n  runStartCapabilityContradictions,\n  staticCapabilityContradictions,\n} from '../mobile/device-plan.js'\nimport type { CapabilityMap, RunStartCapabilityInput } from '../mobile/device-plan.js'\nimport type { MobilePlatform } from '../mobile/launch-resolver.js'\nimport { remoteDeviceEndpoint } from './remote-device-connection.js'\nimport type { RemoteDeviceConnection } from './remote-device-connection.js'\nimport { deviceDebugLoggingRefusal, remoteDeviceRefusalKey } from './remote-device-session.js'\n\nexport function referencedSecretNames(value: unknown): string[] {\n  if (typeof value === 'string') return secretReferenceNames(value)\n  if (Array.isArray(value)) return value.flatMap(referencedSecretNames)\n  if (typeof value === 'object' && value !== null) {\n    return Object.values(value as Record<string, unknown>).flatMap(referencedSecretNames)\n  }\n  return []\n}\n\nexport interface DeviceSecretsInput {\n  readonly connectionSecrets?: SecretResolver | undefined\n  readonly secretsFile?: string | undefined\n}\n\n// A reference the secrets file does not declare is refused before any request.\nexport function withDeviceSecretsResolved(\n  capabilities: CapabilityMap,\n  options: DeviceSecretsInput,\n  subject: string,\n  details: { remote?: string } = {},\n): CapabilityMap {\n  const secrets = options.connectionSecrets\n  const missing = referencedSecretNames(capabilities).find((name) => secrets?.has(name) !== true)\n  if (missing !== undefined) {\n    const secretsFile = options.secretsFile ?? 'workspace.secretsFile'\n    throw new RemoteRefusalError(\n      `${subject} needs ${missing}, which ${secretsFile} does not declare. Add it there.`,\n      details,\n    )\n  }\n  return resolveSecretTemplatesInValue(capabilities, secrets)\n}\n\nexport function rememberedDeviceRefusal(\n  memory: RemoteRefusalMemory | undefined,\n  remoteDevice: Pick<RemoteDeviceConfig, 'name'>,\n  device: string,\n): RemoteRefusalError | undefined {\n  if (memory === undefined) return undefined\n  return (\n    memory.refusalFor(remoteDeviceRefusalKey(remoteDevice, device, undefined)) ??\n    memory.refusalFor(remoteDeviceRefusalKey(remoteDevice, device, 'refused'))\n  )\n}\n\nexport function refuseLeakingDeviceLogs(\n  device: string,\n  remote: { name: string },\n  label: string,\n): void {\n  const logging = deviceDebugLoggingRefusal(\n    { WDIO_LOG_LEVEL: process.env.WDIO_LOG_LEVEL, NODE_DEBUG: process.env.NODE_DEBUG },\n    { remote, device },\n  )\n  if (logging !== undefined) throw new RemoteRefusalError(logging, { remote: label })\n}\n\nexport interface RemoteDeviceProfile {\n  readonly name: string\n  readonly model?: string | undefined\n  readonly os?: string | undefined\n  readonly id?: string | undefined\n  readonly capabilities?: CapabilityMap | undefined\n}\n\n// What a device test asks of a remote, whichever kind serves it.\nexport interface RemoteDeviceTest {\n  readonly platform: MobilePlatform\n  readonly device: RemoteDeviceProfile\n  readonly target: RunStartCapabilityInput['target']\n  readonly appState: 'preserve' | 'reset'\n  // The browser a mobile browser test opens; undefined for an app test.\n  readonly browserName: string | undefined\n  readonly appRef?: string | undefined\n  readonly appPath?: string | undefined\n  readonly testName?: string | undefined\n  // What the platform derives for the test; the remote's and the device's capabilities go over it.\n  readonly derived: CapabilityMap\n}\n\nexport interface PluginDeviceSessionOptions extends DeviceSecretsInput {\n  readonly refusalMemory?: RemoteRefusalMemory | undefined\n  readonly pluginSessions?: RemoteLeaseSource | undefined\n}\n\nexport interface PluginDeviceSessionInput<Driver> extends RemoteDeviceTest {\n  readonly remote: RemotePluginDeviceConfig\n  readonly options: PluginDeviceSessionOptions\n  // Sends the new session to the answered server, with its capabilities resolved.\n  open(session: {\n    remote: RemoteDeviceConfig\n    connection: RemoteDeviceConnection\n    capabilities: CapabilityMap\n  }): Promise<Driver>\n}\n\nexport interface PluginDeviceSession<Driver> {\n  readonly driver: Driver\n  readonly lease: RemoteLease\n  // Sends the lease back once, whoever asks first.\n  readonly release: () => Promise<void>\n  // The plugin's answer as a url remote, with the remote's own capabilities: what the session\n  // connected to.\n  readonly remote: RemoteDeviceConfig\n}\n\n// Derived, then the remote's capabilities, then the device's, with their references as written.\nfunction statedCapabilities(\n  test: RemoteDeviceTest,\n  remoteCapabilities: CapabilityMap | undefined,\n): CapabilityMap {\n  return mergeCapabilities(test.derived, remoteCapabilities, test.device.capabilities)\n}\n\n// The answer is checked like a remote's capabilities, so it cannot change what the test runs on.\nfunction answerContradictions(\n  test: RemoteDeviceTest,\n  remote: string,\n  capabilities: CapabilityMap | undefined,\n): string[] {\n  if (capabilities === undefined) return []\n  const { device } = test\n  const layer = { name: remote, capabilities }\n  return [\n    ...staticCapabilityContradictions({\n      device: device.name,\n      platform: test.platform,\n      ...(device.model !== undefined ? { model: device.model } : {}),\n      ...(device.os !== undefined ? { os: device.os } : {}),\n      ...(device.id !== undefined ? { id: device.id } : {}),\n      remote: layer,\n    }),\n    ...runStartCapabilityContradictions({\n      device: device.name,\n      target: test.target,\n      appState: test.appState,\n      browserMode: test.browserName !== undefined,\n      remote: layer,\n    }),\n  ]\n}\n\n// The app the session installs, when the target names one and the capabilities do not.\nfunction remoteDeviceApp(\n  test: RemoteDeviceTest,\n  remote: RemoteDeviceConfig,\n  capabilities: CapabilityMap,\n): string | undefined {\n  if (test.browserName !== undefined) return undefined\n  const app = remoteAppCapability({\n    device: test.device.name,\n    remote: remote.name,\n    target: test.target.name,\n    ...(test.appRef !== undefined ? { appRef: test.appRef } : {}),\n    ...(test.appPath !== undefined ? { appPath: test.appPath } : {}),\n    capabilities,\n  })\n  if ('refusal' in app) throw new RemoteRefusalError(app.refusal, { remote: remoteLabel(remote) })\n  return app.app\n}\n\n// The capabilities a url remote's device session sends; references resolve after the merge.\nexport function remoteDeviceCapabilities(\n  test: RemoteDeviceTest,\n  remote: RemoteDeviceConfig,\n  options: DeviceSecretsInput,\n): CapabilityMap {\n  const merged = statedCapabilities(test, remote.capabilities)\n  const app = remoteDeviceApp(test, remote, merged)\n  if (app !== undefined) merged['appium:app'] = app\n  const label = remoteLabel(remote)\n  const subject = `Device ${test.device.name} on remote ${label}`\n  return withDeviceSecretsResolved(merged, options, subject, { remote: label })\n}\n\n// A plugin's answer carries values, so it goes in as given between the derived capabilities and\n// the remote's; only what the project states resolves, one layer at a time.\nfunction answeredCapabilities(\n  test: RemoteDeviceTest,\n  remote: RemoteDeviceConfig,\n  options: DeviceSecretsInput,\n  answer: CapabilityMap | undefined,\n): CapabilityMap {\n  const label = remoteLabel(remote)\n  const subject = `Device ${test.device.name} on remote ${label}`\n  const resolved = (capabilities: CapabilityMap | undefined): CapabilityMap | undefined =>\n    capabilities === undefined\n      ? undefined\n      : withDeviceSecretsResolved(capabilities, options, subject, { remote: label })\n  const merged = mergeCapabilities(\n    resolved(test.derived),\n    answer,\n    resolved(remote.capabilities),\n    resolved(test.device.capabilities),\n  )\n  const app = remoteDeviceApp(test, remote, merged)\n  if (app !== undefined) Object.assign(merged, resolved({ 'appium:app': app }))\n  return merged\n}\n\n// The plugin leases the device; its answer then takes the url remote's path, so refusals, bounds\n// and capability checks are the same as on a url remote.\nexport async function createPluginDeviceSession<Driver>(\n  input: PluginDeviceSessionInput<Driver>,\n): Promise<PluginDeviceSession<Driver>> {\n  const { remote: pluginDevice, options, platform } = input\n  const device = input.device.name\n  const { name } = pluginDevice\n  const entry = pluginDevice.plugin.entry\n  const sessions = options.pluginSessions\n  if (sessions === undefined) {\n    throw new RemoteRefusalError(\n      `Remote ${name} names plugin entry ${entry}, and this host started no plugin host for it.`,\n      { remote: name, kind: 'refused' },\n    )\n  }\n  refuseLeakingDeviceLogs(device, pluginDevice, name)\n  const memory = options.refusalMemory\n  const remembered = rememberedDeviceRefusal(memory, pluginDevice, device)\n  if (remembered !== undefined) throw remembered\n  const remember = (error: RemoteRefusalError): RemoteRefusalError =>\n    memory?.remember(remoteDeviceRefusalKey(pluginDevice, device, error.kind), error) ?? error\n\n  const capabilities = statedCapabilities(input, pluginDevice.capabilities)\n  // A set app.ref, or an app the capabilities name, wins; only an app.path alone uploads.\n  let appRef = input.appRef\n  const appPath = input.appPath?.trim()\n  if (\n    input.browserName === undefined &&\n    capabilityValue(capabilities, 'app') === undefined &&\n    !appRef?.trim() &&\n    appPath\n  ) {\n    if (sessions.uploadApp === undefined) {\n      throw new RemoteRefusalError(\n        `Remote ${name}: plugin entry ${entry} uploads no apps; set app.ref on the target to an app the service already has.`,\n        { remote: name, kind: 'refused' },\n      )\n    }\n    const uploaded = await sessions.uploadApp({\n      remote: name,\n      plugin: pluginDevice.plugin,\n      platform,\n      path: appPath,\n      deadlineMs: pluginDevice.uploadTimeoutMs,\n    })\n    appRef = uploaded.ref\n  }\n\n  const startedAt = Date.now()\n  let lease: RemoteLease\n  try {\n    lease = await sessions.acquire({\n      remote: name,\n      plugin: pluginDevice.plugin,\n      deadlineMs: pluginDevice.connectTimeoutMs,\n      session: { platform, capabilities },\n      ...(input.testName === undefined ? {} : { testName: input.testName }),\n    })\n  } catch (error) {\n    if (!(error instanceof RemoteRefusalError)) throw error\n    throw remember(error)\n  }\n  const release = releasingOnce(lease)\n  const answer = lease.connection\n  const refuse = async (sentence: string): Promise<never> => {\n    await release()\n    throw remember(new RemoteRefusalError(sentence, { remote: name, kind: 'refused' }))\n  }\n  if (answer.protocol !== 'appium') {\n    return refuse(\n      `Remote ${name}: plugin entry ${entry} answered a device with a ${answer.protocol} session.`,\n    )\n  }\n  const label = remoteLabel({ name, plugin: entry })\n  const contradictions = answerContradictions(input, label, answer.capabilities)\n  if (contradictions.length > 0) return refuse(contradictions.join('\\n'))\n  // The answer carries values, not references, and its query rides along on every request.\n  const endpoint = URL.canParse(answer.url) ? remoteDeviceEndpoint(new URL(answer.url)) : undefined\n  if (endpoint === undefined) {\n    return refuse(\n      `Remote ${name}: plugin entry ${entry} answered with a url that an appium connection cannot use.`,\n    )\n  }\n\n  const remaining = pluginDevice.connectTimeoutMs - (Date.now() - startedAt)\n  const remote: RemoteDeviceConfig = {\n    name,\n    protocol: 'appium',\n    url: answer.url,\n    ...(answer.headers === undefined ? {} : { headers: answer.headers }),\n    connectTimeoutMs: Math.max(MIN_PLUGIN_CONNECT_MS, remaining),\n    ...(pluginDevice.capabilities === undefined ? {} : { capabilities: pluginDevice.capabilities }),\n  }\n  try {\n    const test = { ...input, appRef }\n    const driver = await input.open({\n      remote,\n      connection: { ...endpoint, headers: { ...answer.headers } },\n      capabilities: answeredCapabilities(test, remote, options, answer.capabilities),\n    })\n    return { driver, lease, release, remote }\n  } catch (error) {\n    await release()\n    throw error\n  }\n}\n","import { RemoteRefusalError, type RemoteProtocol } from '@vostride/agent-qa-runner'\nimport { formatRemoteOrigin, isLoopbackHost, remoteOrigin } from '@vostride/agent-qa-schema'\n\nexport interface PluginAnswerContext {\n  serves: readonly string[]\n  place: 'web' | 'device'\n  // The browser a web session asked for; cdp drives Chromium only.\n  engine?: string\n  remote: string\n  entry: string\n}\n\nconst PLACE_PROTOCOLS: Record<PluginAnswerContext['place'], readonly RemoteProtocol[]> = {\n  web: ['playwright', 'cdp'],\n  device: ['appium'],\n}\n\nconst PROTOCOL_SCHEMES: Record<RemoteProtocol, readonly string[]> = {\n  playwright: ['ws', 'wss'],\n  cdp: ['ws', 'wss', 'http', 'https'],\n  appium: ['http', 'https'],\n}\n\nconst CLEARTEXT_SCHEMES = new Set(['ws', 'http'])\n\nfunction hasUserinfo(url: string): boolean {\n  try {\n    const parsed = new URL(url)\n    return parsed.username !== '' || parsed.password !== ''\n  } catch {\n    return false\n  }\n}\n\n// A credential query is a vendor's own business here; only what agent-qa connects over is judged.\nexport function checkPluginAnswer(\n  answer: { protocol: RemoteProtocol; url: string },\n  context: PluginAnswerContext,\n): RemoteRefusalError | undefined {\n  const { remote, entry } = context\n  const refuse = (what: string) =>\n    new RemoteRefusalError(`Remote ${remote}: plugin entry ${entry} answered with ${what}`, {\n      remote,\n      kind: 'refused',\n    })\n\n  if (\n    !context.serves.includes(answer.protocol)\n    || !PLACE_PROTOCOLS[context.place].includes(answer.protocol)\n  ) {\n    return refuse(`${answer.protocol}, which it does not serve for this test.`)\n  }\n  if (answer.protocol === 'cdp' && context.engine !== undefined && context.engine !== 'chromium') {\n    return refuse(`cdp for a ${context.engine} test; cdp drives Chromium only.`)\n  }\n\n  const origin = remoteOrigin(answer.url)\n  if (origin === undefined || !PROTOCOL_SCHEMES[answer.protocol].includes(origin.scheme)) {\n    return refuse(`a url that a ${answer.protocol} connection cannot use.`)\n  }\n  if (hasUserinfo(answer.url)) {\n    return refuse('a url that carries credentials; plugins send them in headers.')\n  }\n  if (CLEARTEXT_SCHEMES.has(origin.scheme) && !isLoopbackHost(origin.host)) {\n    return refuse(`a cleartext url to ${formatRemoteOrigin(origin)}; use wss:// or https://.`)\n  }\n  return undefined\n}\n","import { spawn } from 'node:child_process'\n\nimport {\n  CANCEL_METHOD,\n  MAX_MESSAGE_BYTES,\n  PROGRESS_METHOD,\n  ProgressParamsSchema,\n  createLineDecoder,\n  encodeMessage,\n  type ProgressParams,\n} from '@vostride/agent-qa-plugin-kit/protocol'\n\nimport { pluginEnvironment } from './environment.js'\n\nexport interface PluginProcessInput {\n  entryFile: string\n  cwd: string\n  mask: (text: string) => string\n  debugLog?: (line: string) => void\n  onProgress?: (progress: ProgressParams) => void\n  // Called once, at the first stdout line that is not a protocol message.\n  onStray?: () => void\n  cancelGraceMs: number\n  killAfterMs: number\n}\n\n// `stderr` is the first stderr line that is not a Node runtime warning, masked, written while the\n// call was open.\nexport type PluginCallOutcome =\n  | { status: 'result'; result: unknown; cancelled: boolean }\n  | {\n      status: 'error'\n      code: number\n      message: string\n      data: unknown\n      cancelled: boolean\n      stderr?: string\n    }\n  | { status: 'silent' }\n  | { status: 'exited'; stderr?: string }\n  | { status: 'stray' }\n\nexport type PluginLateAnswer = Extract<PluginCallOutcome, { status: 'result' | 'error' }>\n\nexport interface PluginRequestOptions {\n  timeoutMs: number\n  // In place of the process's own cancel grace, such as what a signal's bound leaves.\n  cancelGraceMs?: number\n  onProgress?: (progress: ProgressParams) => void\n  // An answer that arrives after the grace, when the call has already been given up on.\n  onLate?: (answer: PluginLateAnswer) => void\n}\n\nexport interface PluginProcess {\n  readonly pid: number | undefined\n  readonly exited: Promise<void>\n  // The first stderr line that is not a Node runtime warning, masked, since the last request was\n  // sent.\n  readonly stderrLine: string | undefined\n  request(\n    method: string,\n    params: unknown,\n    options: PluginRequestOptions,\n  ): Promise<PluginCallOutcome>\n  // stdin closes; after killAfterMs whatever is left of the group gets SIGTERM, then SIGKILL\n  // after termMs, even when the plugin itself has exited.\n  stop(killAfterMs?: number, termMs?: number): Promise<void>\n}\n\ninterface Pending {\n  settle: (outcome: PluginCallOutcome) => void\n  cancelled: boolean\n  options: PluginRequestOptions\n  timers: ReturnType<typeof setTimeout>[]\n  stderr?: string\n  // An error answer with no message, held briefly for the stderr line that explains it.\n  awaiting?: PluginLateAnswer\n}\n\n// After exit, how long stdout and stderr may take to deliver what the plugin wrote last.\nconst STDIO_DRAIN_MS = 250\n// stderr and stdout are separate pipes, so a reason logged before an answer can arrive after it.\nconst STDERR_REASON_WAIT_MS = 150\n// How often a stop looks for the plugin's group after SIGTERM.\nconst GROUP_POLL_MS = 50\n// Node's own runtime warnings, such as a dependency's deprecation, never explain a failure.\nconst NODE_WARNING_LINE =\n  /^\\(node:\\d+\\) |^\\(Use `[^`]* --trace-[a-z-]+ [^`]*` to show where the warning was created\\)$/\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nexport function startPluginProcess(input: PluginProcessInput): PluginProcess {\n  const child = spawn(process.execPath, [input.entryFile], {\n    cwd: input.cwd,\n    env: pluginEnvironment(process.env, process.platform),\n    stdio: ['pipe', 'pipe', 'pipe'],\n    detached: true,\n    windowsHide: true,\n  })\n  const debug = (line: string): void => {\n    if (input.debugLog !== undefined && line.trim() !== '') input.debugLog(input.mask(line))\n  }\n\n  let gone = false\n  let finished = false\n  let strayed = false\n  let stderrLine: string | undefined\n  const pending = new Map<number, Pending>()\n  const late = new Map<number, (answer: PluginLateAnswer) => void>()\n  let nextId = 0\n\n  const exited = new Promise<void>((resolve) => {\n    const finish = (): void => {\n      if (finished) return\n      finished = true\n      gone = true\n      const outcome: PluginCallOutcome = {\n        status: 'exited',\n        ...(stderrLine === undefined ? {} : { stderr: stderrLine }),\n      }\n      for (const [id, call] of pending) {\n        if (call.awaiting !== undefined) {\n          finishCall(id, call, call.awaiting)\n          continue\n        }\n        pending.delete(id)\n        for (const timer of call.timers) clearTimeout(timer)\n        call.settle(outcome)\n      }\n      late.clear()\n      resolve()\n    }\n    child.once('exit', () => {\n      gone = true\n      setTimeout(finish, STDIO_DRAIN_MS)\n    })\n    child.once('close', finish)\n    child.once('error', (error) => {\n      debug(`plugin process error: ${error.message}`)\n      finish()\n    })\n  })\n\n  child.stdin.on('error', () => {})\n\n  const send = (message: unknown): void => {\n    if (gone || child.stdin.destroyed || child.stdin.writableEnded) return\n    child.stdin.write(encodeMessage(message))\n  }\n\n  const finishCall = (id: number, call: Pending, outcome: PluginLateAnswer): void => {\n    pending.delete(id)\n    for (const timer of call.timers) clearTimeout(timer)\n    call.settle(\n      outcome.status === 'error' && call.stderr !== undefined\n        ? { ...outcome, stderr: call.stderr }\n        : outcome,\n    )\n  }\n\n  const answer = (id: number, message: Record<string, unknown>): void => {\n    const call = pending.get(id)\n    const error = message.error\n    const outcome: PluginLateAnswer = isRecord(error)\n      ? {\n          status: 'error',\n          code: typeof error.code === 'number' ? error.code : 0,\n          message: typeof error.message === 'string' ? error.message : '',\n          data: error.data,\n          cancelled: call?.cancelled ?? true,\n        }\n      : { status: 'result', result: message.result, cancelled: call?.cancelled ?? true }\n    if (call !== undefined) {\n      const unexplained =\n        outcome.status === 'error' && outcome.message.trim() === '' && call.stderr === undefined\n      if (unexplained) {\n        for (const timer of call.timers) clearTimeout(timer)\n        call.awaiting = outcome\n        call.timers = [setTimeout(() => finishCall(id, call, outcome), STDERR_REASON_WAIT_MS)]\n        return\n      }\n      finishCall(id, call, outcome)\n      return\n    }\n    const onLate = late.get(id)\n    if (onLate !== undefined) {\n      late.delete(id)\n      onLate(outcome)\n    }\n  }\n\n  const progress = (params: unknown): void => {\n    const parsed = ProgressParamsSchema.safeParse(params)\n    if (!parsed.success) return\n    const id = parsed.data.id\n    const call = typeof id === 'number' ? pending.get(id) : undefined\n    call?.options.onProgress?.(parsed.data)\n    input.onProgress?.(parsed.data)\n  }\n\n  // Anything on stdout that is not a protocol message gives up every open call; an answer that\n  // still follows goes to its call's late handler.\n  const stray = (line: string): void => {\n    debug(`plugin stdout: ${line}`)\n    if (strayed) return\n    strayed = true\n    for (const [id, call] of pending) {\n      pending.delete(id)\n      for (const timer of call.timers) clearTimeout(timer)\n      if (call.options.onLate !== undefined) late.set(id, call.options.onLate)\n      call.settle({ status: 'stray' })\n    }\n    input.onStray?.()\n  }\n\n  const decoder = createLineDecoder({\n    maxLineBytes: MAX_MESSAGE_BYTES,\n    onLine(line) {\n      let message: unknown\n      try {\n        message = JSON.parse(line)\n      } catch {\n        stray(line)\n        return\n      }\n      if (!isRecord(message) || message.jsonrpc !== '2.0') {\n        stray(line)\n        return\n      }\n      if (message.method === PROGRESS_METHOD) {\n        progress(message.params)\n        return\n      }\n      if (typeof message.id === 'number' && ('result' in message || 'error' in message)) {\n        answer(message.id, message)\n      }\n    },\n    onOverflow() {\n      stray('a line over the message size limit')\n    },\n  })\n  child.stdout.on('data', (chunk: Buffer) => decoder.push(chunk))\n  child.stdout.on('end', () => decoder.end())\n\n  const logLine = (raw: string): void => {\n    const line = input.mask(raw.replace(/\\r$/, ''))\n    if (line.trim() === '') return\n    input.debugLog?.(line)\n    if (NODE_WARNING_LINE.test(line.trim())) return\n    stderrLine ??= line.trim()\n    for (const [id, call] of pending) {\n      if (call.stderr !== undefined) continue\n      call.stderr = line.trim()\n      if (call.awaiting !== undefined) finishCall(id, call, call.awaiting)\n    }\n  }\n  let stderrRest = ''\n  child.stderr.on('data', (chunk: Buffer) => {\n    const lines = (stderrRest + chunk.toString('utf8')).split('\\n')\n    stderrRest = lines.pop() ?? ''\n    for (const line of lines) logLine(line)\n  })\n  child.stderr.on('end', () => {\n    if (stderrRest !== '') logLine(stderrRest)\n    stderrRest = ''\n  })\n\n  // Two stops can overlap, such as a signal's kill and a stop already under way; each signal\n  // still reaches the group once.\n  const signalled = new Set<NodeJS.Signals>()\n  const signalGroup = (signal: NodeJS.Signals): void => {\n    const pid = child.pid\n    if (pid === undefined || signalled.has(signal)) return\n    signalled.add(signal)\n    try {\n      if (process.platform === 'win32') child.kill()\n      else process.kill(-pid, signal)\n    } catch {\n      // The group is already gone.\n    }\n  }\n\n  // A grandchild the plugin started stays in its group after the plugin itself exits.\n  const groupAlive = (): boolean => {\n    const pid = child.pid\n    if (pid === undefined || process.platform === 'win32') return !gone\n    try {\n      process.kill(-pid, 0)\n      return true\n    } catch (error) {\n      return (error as NodeJS.ErrnoException).code === 'EPERM'\n    }\n  }\n\n  const groupGoneWithin = async (ms: number): Promise<boolean> => {\n    const until = Date.now() + ms\n    while (groupAlive()) {\n      const remaining = until - Date.now()\n      if (remaining <= 0) return false\n      await new Promise((resolve) => setTimeout(resolve, Math.min(GROUP_POLL_MS, remaining)))\n    }\n    return true\n  }\n\n  const exitsWithin = async (ms: number): Promise<boolean> => {\n    if (gone) return true\n    let timer: ReturnType<typeof setTimeout> | undefined\n    const timedOut = new Promise<false>((resolve) => {\n      timer = setTimeout(() => resolve(false), ms)\n    })\n    const result = await Promise.race([exited.then(() => true as const), timedOut])\n    clearTimeout(timer)\n    return result\n  }\n\n  return {\n    pid: child.pid,\n    exited,\n    get stderrLine() {\n      return stderrLine\n    },\n    request(method, params, options) {\n      if (strayed) return Promise.resolve({ status: 'stray' })\n      if (gone) return Promise.resolve({ status: 'exited' })\n      nextId += 1\n      const id = nextId\n      stderrLine = undefined\n      return new Promise<PluginCallOutcome>((settle) => {\n        const call: Pending = { settle, cancelled: false, options, timers: [] }\n        pending.set(id, call)\n        call.timers.push(\n          setTimeout(() => {\n            if (!pending.has(id)) return\n            call.cancelled = true\n            send({ jsonrpc: '2.0', method: CANCEL_METHOD, params: { id } })\n            call.timers.push(\n              setTimeout(() => {\n                if (!pending.has(id)) return\n                pending.delete(id)\n                if (options.onLate !== undefined) late.set(id, options.onLate)\n                settle({ status: 'silent' })\n              }, options.cancelGraceMs ?? input.cancelGraceMs),\n            )\n          }, options.timeoutMs),\n        )\n        send({ jsonrpc: '2.0', id, method, params })\n      })\n    },\n    async stop(killAfterMs = input.killAfterMs, termMs = killAfterMs) {\n      if (!child.stdin.destroyed) child.stdin.end()\n      await exitsWithin(killAfterMs)\n      if (!groupAlive()) return\n      signalGroup('SIGTERM')\n      if (await groupGoneWithin(termMs)) return\n      signalGroup('SIGKILL')\n      await exitsWithin(termMs)\n    },\n  }\n}\n","import { createHash } from 'node:crypto'\nimport { createReadStream } from 'node:fs'\nimport { stat } from 'node:fs/promises'\nimport { resolve } from 'node:path'\n\nimport {\n  AcquireResultSchema,\n  CheckResultSchema,\n  InitializeResultSchema,\n  PLUGIN_ERROR_CODES,\n  PluginErrorDataSchema,\n  StartedResultSchema,\n  UploadAppResultSchema,\n  type AcquireResult,\n  type CheckResult,\n  type OptionalPluginMethod,\n  type ProgressParams,\n  type RemotePluginManifest,\n} from '@vostride/agent-qa-plugin-kit/protocol'\nimport {\n  PLUGIN_RELEASE_BOUND_MS,\n  REMOTE_RELEASE_BOUND_MS,\n  RemoteRefusalError,\n  type RemoteFailureKind,\n  type RemoteLease,\n  type RemoteLeaseEnded,\n  type RemoteLeaseOutcome,\n  type RemoteLeaseRequest,\n  type RemoteLeaseSource,\n  type RemotePluginEvidence,\n  type RemoteProgress,\n  type RemoteSessionRegistry,\n} from '@vostride/agent-qa-runner'\n\nimport {\n  resolvePluginEntry,\n  supportedPluginProtocols,\n  type PluginEntryInput,\n} from '../../plugins/resolve-entries.js'\nimport { checkPluginAnswer } from './answer.js'\nimport {\n  startPluginProcess,\n  type PluginCallOutcome,\n  type PluginLateAnswer,\n  type PluginProcess,\n} from './plugin-process.js'\n\nexport interface PluginHostBounds {\n  initializeMs: number\n  checkMs: number\n  startedMs: number\n  endMs: number\n  releaseMs: number\n  shutdownMs: number\n  signalMs: number\n  cancelGraceMs: number\n  killAfterMs: number\n}\n\nexport const DEFAULT_PLUGIN_HOST_BOUNDS: PluginHostBounds = {\n  initializeMs: 10_000,\n  checkMs: 15_000,\n  startedMs: 30_000,\n  endMs: 30_000,\n  releaseMs: 30_000,\n  shutdownMs: 30_000,\n  signalMs: 5_000,\n  cancelGraceMs: 5_000,\n  killAfterMs: 5_000,\n}\n\n// On a signal, once SIGTERM is sent, how long a plugin's group has before SIGKILL.\nconst SIGNAL_KILL_AFTER_MS = 500\n// What the session registry waits past signalMs, so SIGTERM and SIGKILL go out before it stops.\nconst SIGNAL_KILL_RESERVE_MS = SIGNAL_KILL_AFTER_MS + 500\n\nconst PROGRESS_LINE_MAX = 200\n\n// Terminal escape sequences: CSI, OSC to its terminator or the end, and two-character escapes.\nconst ESCAPE_SEQUENCE = /\\x1b(?:\\[[0-?]*[ -\\/]*[@-~]|\\][^\\x07\\x1b]*(?:\\x07|\\x1b\\\\|$)|[ -\\/]*[0-~])/g\nconst CONTROL_CHARACTER = /[\\x00-\\x1f\\x7f-\\x9f]/g\n\nfunction plainText(text: string): string {\n  return text.replace(ESCAPE_SEQUENCE, '').replace(CONTROL_CHARACTER, ' ')\n}\n\n// One line a terminal or a page shows as plain text: no escape sequence and no C0 or C1 control.\nfunction plainFirstLine(text: string): string {\n  const first = text.replace(ESCAPE_SEQUENCE, '').split(/\\r?\\n/, 1)[0] ?? ''\n  return first.replace(CONTROL_CHARACTER, ' ').trim()\n}\n\nexport interface PluginHostProgress extends RemoteProgress {\n  remote: string\n  entry: string\n}\n\nexport interface PluginHostPoolInput {\n  configDir: string\n  // The config the person named; fix lines carry it when it is not the default.\n  configPath?: string\n  plugins: readonly PluginEntryInput[]\n  agentQaVersion: string\n  hostVersions: { playwright: string; webdriverio: string }\n  // Turns `{{secret:NAME}}` references into values; may throw a RemoteRefusalError.\n  resolveSecrets: (value: Record<string, unknown>) => Record<string, unknown>\n  runFacts?: { runId?: string }\n  // A run marks every session it ends, so on a signal one it has not marked yet was cancelled.\n  // The live editor marks none.\n  marksSessions?: boolean\n  mask: (text: string) => string\n  // Values an acquire answer asks to mask; they reach the run's mask before the session is used.\n  onMask?: (entry: string, values: readonly string[]) => void\n  // Every call's progress, masked and cut to one plain line, after the call's own onProgress.\n  onProgress?: (event: PluginHostProgress) => void\n  debugLog?: (line: string) => void\n  sessions?: RemoteSessionRegistry\n  bounds?: Partial<PluginHostBounds>\n}\n\nexport type PluginUploadRequest = Parameters<NonNullable<RemoteLeaseSource['uploadApp']>>[0]\n\nexport interface PluginCheckRemote {\n  name: string\n  settings?: Record<string, unknown>\n}\n\nexport interface PluginHostPool extends RemoteLeaseSource {\n  uploadApp(request: PluginUploadRequest): Promise<{ ref: string }>\n  // Undefined when the plugin declares no check.\n  check(entry: string, remotes: readonly PluginCheckRemote[]): Promise<CheckResult | undefined>\n  shutdown(options?: { signal?: boolean }): Promise<void>\n}\n\ntype Refusal = (remote: string) => RemoteRefusalError\n\ninterface OpenLease {\n  remote: string\n  release(boundMs: number): Promise<void>\n  end(ended: RemoteLeaseEnded): void\n}\n\ninterface EntryFault {\n  line: (remote: string) => string\n  // The lease whose own call went unanswered ends timeout; every other lease ends lost.\n  timedOut?: OpenLease\n}\n\ninterface RunningEntry {\n  name: string\n  manifest: RemotePluginManifest\n  entryFile: string\n  initialize: Record<string, unknown>\n  process: PluginProcess\n  evidence: RemotePluginEvidence\n  leases: Set<OpenLease>\n  // Lease releases sent and not yet settled; shutdown waits for them.\n  releasing: Set<Promise<void>>\n  // Every session handle this process gave out and has not answered a release for.\n  held: Set<unknown>\n  stopping: boolean\n  fault?: EntryFault\n  restarted?: Promise<void>\n}\n\ntype EntryStart = { ok: true; running: RunningEntry } | { ok: false; refusal: Refusal }\n\nasync function fileFacts(path: string): Promise<{ sha256: string; size: number }> {\n  const { size } = await stat(path)\n  const hash = createHash('sha256')\n  for await (const chunk of createReadStream(path)) hash.update(chunk as Buffer)\n  return { sha256: hash.digest('hex'), size }\n}\n\ntype ErrorScope = { call: 'initialize' | 'remote'; entry: string }\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction formatMs(ms: number): string {\n  return ms < 1000 ? `${ms}ms` : `${Number((ms / 1000).toFixed(1))}s`\n}\n\nfunction crashLine(entry: string, reason: string | undefined): (remote: string) => string {\n  const why = reason === undefined ? '' : `: ${reason.replace(/\\.+$/, '')}`\n  return (remote) => `Remote ${remote}: plugin entry ${entry} stopped unexpectedly${why}.`\n}\n\nfunction silentLine(entry: string, deadlineMs: number): (remote: string) => string {\n  return (remote) =>\n    `Remote ${remote}: plugin entry ${entry} did not answer within ${formatMs(deadlineMs)} and was stopped.`\n}\n\nfunction strayLine(entry: string): (remote: string) => string {\n  return (remote) =>\n    `Remote ${remote}: plugin entry ${entry} wrote to stdout outside the protocol and was stopped.`\n}\n\nfunction refusalOf(kind: RemoteFailureKind, line: (remote: string) => string): Refusal {\n  return (remote) => new RemoteRefusalError(line(remote), { remote, kind })\n}\n\nconst shutDown: Refusal = refusalOf(\n  'ended',\n  (remote) => `Remote ${remote}: the plugin host has shut down.`,\n)\n\nfunction carriedHandle(answer: PluginLateAnswer): unknown {\n  if (answer.status === 'result') {\n    return isRecord(answer.result) ? answer.result.handle : undefined\n  }\n  return isRecord(answer.data) ? answer.data.handle : undefined\n}\n\nexport function createPluginHostPool(input: PluginHostPoolInput): PluginHostPool {\n  const bounds: PluginHostBounds = { ...DEFAULT_PLUGIN_HOST_BOUNDS, ...input.bounds }\n  const starts = new Map<string, Promise<EntryStart>>()\n  // One upload per plugins entry, platform and content for the pool's life, refusals included.\n  const uploads = new Map<string, Promise<{ ref: string }>>()\n  const background = new Set<Promise<void>>()\n  const live = new Set<PluginProcess>()\n  // Stops under way, and whether each already fits in a signal's bound.\n  const stops = new Map<PluginProcess, { done: Promise<void>; bounded: boolean }>()\n  let closing: Promise<void> | undefined\n  let signalClosing: Promise<void> | undefined\n  let signalDeadline: number | undefined\n  let unregisterShutdown: (() => void) | undefined\n\n  // What is left of a signal's bound; unbounded until a signal comes.\n  const left = (): number =>\n    signalDeadline === undefined\n      ? Number.POSITIVE_INFINITY\n      : Math.max(0, signalDeadline - Date.now())\n\n  // After a signal, a call and its cancel grace together fit in what is left of the bound.\n  const within = (timeoutMs: number): { timeoutMs: number; cancelGraceMs?: number } => {\n    const remaining = left()\n    if (remaining === Number.POSITIVE_INFINITY) return { timeoutMs }\n    const bounded = Math.min(timeoutMs, remaining)\n    return {\n      timeoutMs: bounded,\n      cancelGraceMs: Math.min(bounds.cancelGraceMs, remaining - bounded),\n    }\n  }\n\n  const settledWithin = async (work: Promise<unknown>, boundMs: number): Promise<void> => {\n    const settled = work.then(\n      () => undefined,\n      () => undefined,\n    )\n    if (boundMs === Number.POSITIVE_INFINITY) return settled\n    let timer: ReturnType<typeof setTimeout> | undefined\n    await Promise.race([\n      settled,\n      new Promise<void>((done) => {\n        timer = setTimeout(done, boundMs)\n      }),\n    ])\n    clearTimeout(timer)\n  }\n\n  const settledWithinLeft = (work: Promise<unknown>): Promise<void> => settledWithin(work, left())\n\n  const stopChild = (child: PluginProcess, killAfterMs = bounds.killAfterMs): Promise<void> => {\n    const remaining = left()\n    const bounded = remaining !== Number.POSITIVE_INFINITY\n    const done = bounded\n      ? child.stop(Math.min(killAfterMs, remaining), SIGNAL_KILL_AFTER_MS)\n      : child.stop(killAfterMs)\n    const stop = { done, bounded }\n    stops.set(child, stop)\n    void done.finally(() => {\n      if (stops.get(child) === stop) stops.delete(child)\n    })\n    return done\n  }\n\n  // Masked again once plain, in case an escape sequence split a secret.\n  const debugText = (line: string): string => input.mask(plainText(input.mask(line)))\n  const debug = (line: string): void => input.debugLog?.(debugText(line))\n\n  const track = (work: Promise<void>): Promise<void> => {\n    background.add(work)\n    void work.finally(() => background.delete(work))\n    return work\n  }\n\n  const pluginLine = (message: string, stderr?: string): string => {\n    const first = input.mask(message).split(/\\r?\\n/, 1)[0]?.trim() ?? ''\n    if (first !== '') return first\n    const logged = input.mask(stderr ?? '').trim()\n    return logged === '' ? 'the plugin gave no reason.' : logged\n  }\n\n  const pluginErrorKind = (outcome: Extract<PluginCallOutcome, { status: 'error' }>) => {\n    if (outcome.code === PLUGIN_ERROR_CODES.cancelled) return 'timeout' as const\n    const data = PluginErrorDataSchema.safeParse(outcome.data)\n    return data.success ? data.data.kind : ('refused' as const)\n  }\n\n  const pluginErrorLine = (\n    remote: string,\n    outcome: Extract<PluginCallOutcome, { status: 'error' }>,\n    scope: ErrorScope,\n  ): string => {\n    const reason = pluginLine(outcome.message, outcome.stderr).replace(/\\.+$/, '')\n    const line = `Remote ${remote}: ${reason}.`\n    const data = PluginErrorDataSchema.safeParse(outcome.data)\n    const path = data.success ? input.mask(data.data.path ?? '').split(/\\r?\\n/, 1)[0]?.trim() : ''\n    if (path === undefined || path === '') return line\n    const options = `in plugins entry ${scope.entry}.`\n    const settings = `in remote ${remote}.`\n    // A prefix names the block in any call; a path without one belongs to the call's own block.\n    if (path.startsWith('options.')) return `${line} Check ${path} ${options}`\n    if (path.startsWith('settings.')) return `${line} Check ${path} ${settings}`\n    if (scope.call === 'initialize') return `${line} Check options.${path} ${options}`\n    return `${line} Check settings.${path} ${settings}`\n  }\n\n  // A progress report reaches its own request's listener and the pool's; neither touches the\n  // call's deadline, and a listener that throws only reaches the debug log.\n  const progressRelay =\n    (remote: string, entry: string, own: ((progress: RemoteProgress) => void) | undefined) =>\n    (update: ProgressParams): void => {\n      // Masked again once plain, in case an escape sequence split a secret.\n      const message = input.mask(plainFirstLine(input.mask(update.message)))\n      const progress: RemoteProgress = {\n        message: message.slice(0, PROGRESS_LINE_MAX),\n        ...(update.queued === undefined ? {} : { queued: update.queued }),\n        ...(update.percent === undefined ? {} : { percent: update.percent }),\n      }\n      const tell = (send: () => void): void => {\n        try {\n          send()\n        } catch (error) {\n          debug(`a progress listener for remote ${remote} failed: ${String(error)}`)\n        }\n      }\n      tell(() => own?.(progress))\n      tell(() => input.onProgress?.({ remote, entry, ...progress }))\n    }\n\n  const asRefusal = (error: unknown, remote: string, entry: string): RemoteRefusalError => {\n    if (error instanceof RemoteRefusalError) {\n      return new RemoteRefusalError(error.message, {\n        remote,\n        ...(error.kind === undefined ? {} : { kind: error.kind }),\n      })\n    }\n    const message = error instanceof Error ? error.message : String(error)\n    return new RemoteRefusalError(\n      `Remote ${remote}: plugin entry ${entry} could not start: ${pluginLine(message)}`,\n      { remote, kind: 'refused' },\n    )\n  }\n\n  const spawnPlugin = (name: string, entryFile: string, onStray?: () => void): PluginProcess => {\n    const debugLog = input.debugLog\n    const child = startPluginProcess({\n      entryFile,\n      cwd: input.configDir,\n      mask: input.mask,\n      // Several plugins can run at once, so each line names its entry.\n      ...(debugLog === undefined\n        ? {}\n        : { debugLog: (line: string) => debugLog(`plugin ${name}: ${debugText(line)}`) }),\n      ...(onStray === undefined ? {} : { onStray }),\n      cancelGraceMs: bounds.cancelGraceMs,\n      killAfterMs: bounds.killAfterMs,\n    })\n    live.add(child)\n    void child.exited.then(() => live.delete(child))\n    return child\n  }\n\n  // A handle stays held until the plugin answers its release; a stopped plugin's held handles\n  // go to the restart.\n  const releaseHandle = (\n    running: RunningEntry,\n    handle: unknown,\n    boundMs: number,\n  ): Promise<void> => {\n    if (running.fault !== undefined) return running.restarted ?? Promise.resolve()\n    return track(\n      (async () => {\n        const outcome = await running.process.request('release', { handle }, within(boundMs))\n        if (outcome.status === 'result' || outcome.status === 'error') {\n          running.held.delete(handle)\n        }\n        if (outcome.status !== 'result') {\n          debug(`plugin entry ${running.name} did not release a session: ${outcome.status}`)\n        }\n        if (outcome.status === 'silent') hung(running, boundMs)\n        if (outcome.status === 'exited') await running.process.exited\n        await running.restarted\n      })(),\n    )\n  }\n\n  const releaseCarried = (running: RunningEntry, answer: PluginLateAnswer): Promise<void> => {\n    const handle = carriedHandle(answer)\n    if (handle === undefined) return Promise.resolve()\n    running.held.add(handle)\n    return releaseHandle(running, handle, bounds.releaseMs)\n  }\n\n  const stopInBackground = (child: PluginProcess): void => {\n    void track(stopChild(child))\n  }\n\n  // A fresh process with the same options only releases what the stopped one held; nothing is\n  // acquired again.\n  async function releaseOnly(running: RunningEntry, handles: readonly unknown[]): Promise<void> {\n    if (left() === 0) {\n      debug(`plugin entry ${running.name} had no time left on the signal to release its sessions`)\n      return\n    }\n    const child = spawnPlugin(running.name, running.entryFile)\n    try {\n      const started = await child.request(\n        'initialize',\n        running.initialize,\n        within(bounds.initializeMs),\n      )\n      if (started.status !== 'result' || started.cancelled) {\n        debug(`plugin entry ${running.name} did not restart to release its sessions`)\n        return\n      }\n      await Promise.all(\n        handles.map(async (handle) => {\n          const outcome = await child.request('release', { handle }, within(bounds.releaseMs))\n          if (outcome.status !== 'result') {\n            debug(`plugin entry ${running.name} did not release a session after its restart`)\n          }\n        }),\n      )\n      await child.request('shutdown', {}, within(bounds.shutdownMs))\n    } finally {\n      await stopChild(child)\n    }\n  }\n\n  function fault(running: RunningEntry, found: EntryFault): void {\n    if (running.fault !== undefined) return\n    running.fault = found\n    const leases = [...running.leases]\n    running.leases.clear()\n    for (const lease of leases) {\n      const kind = lease === found.timedOut ? 'timeout' : 'lost'\n      lease.end({ kind, message: found.line(lease.remote) })\n    }\n    running.restarted = track(\n      (async () => {\n        await stopChild(running.process)\n        await running.process.exited\n        const handles = [...running.held]\n        running.held.clear()\n        if (handles.length > 0) await releaseOnly(running, handles)\n      })(),\n    )\n  }\n\n  // A plugin silent past a call's deadline and the cancel grace is stopped, unless agent-qa is\n  // already stopping it.\n  const hung = (running: RunningEntry, deadlineMs: number, own?: OpenLease): void => {\n    if (running.stopping) return\n    fault(running, {\n      line: silentLine(running.name, deadlineMs),\n      ...(own === undefined ? {} : { timedOut: own }),\n    })\n  }\n\n  const silentRefusal = (\n    running: RunningEntry,\n    remote: string,\n    deadlineMs: number,\n  ): RemoteRefusalError => {\n    hung(running, deadlineMs)\n    return new RemoteRefusalError(silentLine(running.name, deadlineMs)(remote), {\n      remote,\n      kind: 'timeout',\n    })\n  }\n\n  const stoppedRefusal = (\n    running: RunningEntry,\n    remote: string,\n    outcome?: Extract<PluginCallOutcome, { status: 'exited' | 'stray' }>,\n  ): RemoteRefusalError => {\n    const stderr = outcome?.status === 'exited' ? outcome.stderr : undefined\n    const line = running.fault?.line ?? crashLine(running.name, stderr)\n    return new RemoteRefusalError(line(remote), { remote, kind: 'lost' })\n  }\n\n  // An unexpected throw, such as a folder changing under resolution, refuses only this entry.\n  async function startEntry(name: string): Promise<EntryStart> {\n    try {\n      return await startEntryProcess(name)\n    } catch (error) {\n      return { ok: false, refusal: (remote) => asRefusal(error, remote, name) }\n    }\n  }\n\n  async function startEntryProcess(name: string): Promise<EntryStart> {\n    const entry = input.plugins.find((candidate) => candidate.name === name)\n    if (entry === undefined) {\n      return {\n        ok: false,\n        refusal: refusalOf(\n          'refused',\n          (remote) => `Remote ${remote} names plugins entry ${name}, which plugins does not list.`,\n        ),\n      }\n    }\n\n    const resolved = resolvePluginEntry(entry, {\n      configDir: input.configDir,\n      ...(input.configPath === undefined ? {} : { configPath: input.configPath }),\n      agentQaVersion: input.agentQaVersion,\n    })\n    if (resolved.state !== 'ok') {\n      const kind =\n        resolved.state === 'version_mismatch' || resolved.state === 'protocol_mismatch'\n          ? 'version'\n          : 'refused'\n      const reason = resolved.reason ?? `Plugin entry ${name} cannot start.`\n      return { ok: false, refusal: refusalOf(kind, (remote) => `Remote ${remote}: ${reason}`) }\n    }\n    const manifest = resolved.manifest\n    if (manifest?.kind !== 'remote' || resolved.packageDir === undefined) {\n      return {\n        ok: false,\n        refusal: refusalOf(\n          'refused',\n          (remote) =>\n            `Remote ${remote}: plugin entry ${name} names ${resolved.label}, which is not a remote plugin.`,\n        ),\n      }\n    }\n\n    let options: Record<string, unknown>\n    try {\n      options = input.resolveSecrets(isRecord(entry.options) ? entry.options : {})\n    } catch (error) {\n      return { ok: false, refusal: (remote) => asRefusal(error, remote, name) }\n    }\n\n    const entryFile = resolve(resolved.packageDir, manifest.entry)\n    let running: RunningEntry | undefined\n    const child = spawnPlugin(name, entryFile, () => {\n      if (running !== undefined) fault(running, { line: strayLine(name) })\n    })\n    const runId = input.runFacts?.runId\n    const sendsRunId = manifest.runFacts?.includes('runId') === true && runId !== undefined\n    const initialize = {\n      protocolVersions: supportedPluginProtocols(),\n      host: {\n        pid: process.pid,\n        agentQaVersion: input.agentQaVersion,\n        playwrightVersion: input.hostVersions.playwright,\n        webdriverioVersion: input.hostVersions.webdriverio,\n      },\n      entry: name,\n      options,\n      ...(sendsRunId ? { runFacts: { runId } } : {}),\n    }\n    const outcome = await child.request('initialize', initialize, within(bounds.initializeMs))\n\n    const fail = (refusal: Refusal): EntryStart => {\n      stopInBackground(child)\n      return { ok: false, refusal }\n    }\n\n    if (outcome.status === 'stray') {\n      return fail(refusalOf('refused', strayLine(name)))\n    }\n    if (outcome.status === 'silent' || (outcome.status !== 'exited' && outcome.cancelled)) {\n      return fail(\n        refusalOf(\n          'timeout',\n          (remote) =>\n            `Remote ${remote}: plugin entry ${name} did not answer initialize within ${formatMs(bounds.initializeMs)}.`,\n        ),\n      )\n    }\n    if (outcome.status === 'exited') {\n      return fail(\n        refusalOf(\n          'refused',\n          (remote) => `Remote ${remote}: plugin entry ${name} exited before it answered initialize.`,\n        ),\n      )\n    }\n    if (outcome.status === 'error') {\n      const kind = pluginErrorKind(outcome)\n      return fail(\n        refusalOf(kind, (remote) =>\n          pluginErrorLine(remote, outcome, { call: 'initialize', entry: name }),\n        ),\n      )\n    }\n\n    const parsed = InitializeResultSchema.safeParse(outcome.result)\n    if (!parsed.success) {\n      return fail(\n        refusalOf(\n          'refused',\n          (remote) =>\n            `Remote ${remote}: plugin entry ${name} answered initialize with something that is not a plugin protocol answer.`,\n        ),\n      )\n    }\n    const window = supportedPluginProtocols()\n    if (!window.includes(parsed.data.protocolVersion)) {\n      return fail(\n        refusalOf(\n          'version',\n          (remote) =>\n            `Remote ${remote}: plugin entry ${name} answered with plugin protocol ${parsed.data.protocolVersion}; this agent-qa speaks ${window.join(' and ')}.`,\n        ),\n      )\n    }\n\n    running = {\n      name,\n      manifest,\n      entryFile,\n      initialize,\n      process: child,\n      evidence: {\n        entry: name,\n        ...(entry.package === undefined ? {} : { package: entry.package }),\n        ...(entry.path === undefined ? {} : { path: entry.path }),\n        version: resolved.version ?? parsed.data.plugin.version,\n        protocol: parsed.data.protocolVersion,\n        origin: resolved.origin,\n      },\n      leases: new Set(),\n      releasing: new Set(),\n      held: new Set(),\n      stopping: false,\n    }\n    const started = running\n    void child.exited.then(() => {\n      if (started.stopping) return\n      fault(started, { line: crashLine(name, child.stderrLine) })\n    })\n    return { ok: true, running: started }\n  }\n\n  // Once shutdown has begun nothing new starts, so nothing escapes it.\n  const entryStart = (name: string): Promise<EntryStart> => {\n    if (closing !== undefined) return Promise.resolve({ ok: false, refusal: shutDown })\n    let start = starts.get(name)\n    if (start === undefined) {\n      // A signal shuts every started entry down after its leases' releases, in the same bound.\n      unregisterShutdown ??= input.sessions?.register(() => shutdown({ signal: true }), {\n        boundMs: bounds.signalMs + SIGNAL_KILL_RESERVE_MS,\n      })\n      start = startEntry(name)\n      starts.set(name, start)\n    }\n    return start\n  }\n\n  const declares = (running: RunningEntry, method: OptionalPluginMethod): boolean =>\n    running.manifest.methods.includes(method)\n\n  function openLease(running: RunningEntry, remote: string, answer: AcquireResult): RemoteLease {\n    let releasing: Promise<void> | undefined\n    let ending: Promise<void> | undefined\n    let unregister: (() => void) | undefined\n    let before: (() => Promise<void>) | undefined\n    let ended: RemoteLeaseEnded | undefined\n    const listeners = new Set<(ended: RemoteLeaseEnded) => void>()\n    const tell = (listener: (ended: RemoteLeaseEnded) => void, value: RemoteLeaseEnded) => {\n      try {\n        listener(value)\n      } catch (error) {\n        debug(`a listener for remote ${remote} failed: ${String(error)}`)\n      }\n    }\n    // Sent once, and never after the session's release has begun.\n    const end = (outcome: RemoteLeaseOutcome, reason?: string): Promise<void> => {\n      if (releasing !== undefined) return ending ?? Promise.resolve()\n      ending ??= (async () => {\n        if (!declares(running, 'end') || running.fault !== undefined) return\n        const sendsReason = running.manifest.runFacts?.includes('failure') === true\n        const answered = await running.process.request(\n          'end',\n          {\n            handle: answer.handle,\n            outcome,\n            ...(sendsReason && reason !== undefined ? { reason: input.mask(reason) } : {}),\n          },\n          within(bounds.endMs),\n        )\n        if (answered.status === 'silent') hung(running, bounds.endMs, open)\n        if (answered.status !== 'result') debug(`plugin entry ${running.name} did not answer end`)\n      })()\n      return ending\n    }\n    const release = (boundMs: number): Promise<void> => {\n      if (releasing === undefined) {\n        running.leases.delete(open)\n        unregister?.()\n        const marked =\n          signalDeadline !== undefined && input.marksSessions === true\n            ? end('cancelled')\n            : Promise.resolve()\n        // Whoever asks first, the holder's own teardown, such as deleting its session, goes first.\n        const held = marked.then(() =>\n          before === undefined\n            ? undefined\n            : settledWithin(\n                Promise.resolve().then(before),\n                Math.min(REMOTE_RELEASE_BOUND_MS, left()),\n              ),\n        )\n        const sent = held.then(() => releaseHandle(running, answer.handle, boundMs))\n        releasing = sent\n        running.releasing.add(sent)\n        void sent.finally(() => running.releasing.delete(sent))\n      }\n      return releasing\n    }\n    const open: OpenLease = {\n      remote,\n      release,\n      end(value) {\n        if (ended !== undefined) return\n        ended = value\n        for (const listener of [...listeners]) tell(listener, value)\n        listeners.clear()\n      },\n    }\n    running.held.add(answer.handle)\n    running.leases.add(open)\n    unregister = input.sessions?.register(release, { boundMs: PLUGIN_RELEASE_BOUND_MS })\n\n    return {\n      connection: {\n        protocol: answer.protocol,\n        url: answer.url,\n        ...(answer.headers === undefined ? {} : { headers: answer.headers }),\n        ...(answer.capabilities === undefined ? {} : { capabilities: answer.capabilities }),\n      },\n      plugin: running.evidence,\n      ...(answer.link === undefined ? {} : { link: answer.link }),\n      async started({ sessionId }) {\n        if (!declares(running, 'started') || running.fault !== undefined) return {}\n        const outcome = await running.process.request(\n          'started',\n          { handle: answer.handle, ...(sessionId === undefined ? {} : { sessionId }) },\n          within(bounds.startedMs),\n        )\n        if (outcome.status === 'silent') hung(running, bounds.startedMs, open)\n        const parsed =\n          outcome.status === 'result' ? StartedResultSchema.safeParse(outcome.result) : undefined\n        if (parsed?.success !== true) {\n          debug(`plugin entry ${running.name} did not answer started`)\n          return {}\n        }\n        return {\n          ...(parsed.data.link === undefined ? {} : { link: parsed.data.link }),\n          ...(parsed.data.appiumVersion === undefined\n            ? {}\n            : { appiumVersion: parsed.data.appiumVersion }),\n        }\n      },\n      end,\n      beforeRelease(step) {\n        if (releasing === undefined) before = step\n      },\n      release: () => release(bounds.releaseMs),\n      onEnded(listener) {\n        if (ended !== undefined) {\n          const value = ended\n          let live = true\n          queueMicrotask(() => {\n            if (live) tell(listener, value)\n          })\n          return () => {\n            live = false\n          }\n        }\n        listeners.add(listener)\n        return () => {\n          listeners.delete(listener)\n        }\n      },\n    }\n  }\n\n  async function acquire(request: RemoteLeaseRequest): Promise<RemoteLease> {\n    const { remote } = request\n    const entry = request.plugin.entry\n    const start = await entryStart(entry)\n    if (!start.ok) throw start.refusal(remote)\n    if (closing !== undefined) throw shutDown(remote)\n    const running = start.running\n    if (running.fault !== undefined) throw stoppedRefusal(running, remote)\n\n    let settings: Record<string, unknown>\n    try {\n      settings = input.resolveSecrets(request.plugin.settings ?? {})\n    } catch (error) {\n      throw asRefusal(error, remote, entry)\n    }\n    const sendsTestName =\n      running.manifest.runFacts?.includes('testName') === true && request.testName !== undefined\n    const outcome = await running.process.request(\n      'acquire',\n      {\n        remote,\n        settings,\n        session: request.session,\n        ...(sendsTestName ? { run: { testName: request.testName } } : {}),\n      },\n      {\n        timeoutMs: request.deadlineMs,\n        onProgress: progressRelay(remote, entry, request.onProgress?.bind(request)),\n        onLate: (late) => void releaseCarried(running, late),\n      },\n    )\n\n    const timedOut = () =>\n      new RemoteRefusalError(\n        `Remote ${remote}: plugin entry ${entry} did not answer acquire within ${formatMs(request.deadlineMs)}.`,\n        { remote, kind: 'timeout' },\n      )\n    if (outcome.status === 'silent') throw silentRefusal(running, remote, request.deadlineMs)\n    if (outcome.status === 'exited' || outcome.status === 'stray') {\n      throw stoppedRefusal(running, remote, outcome)\n    }\n    if (outcome.cancelled) {\n      await releaseCarried(running, outcome)\n      throw timedOut()\n    }\n    if (outcome.status === 'error') {\n      await releaseCarried(running, outcome)\n      throw new RemoteRefusalError(\n        pluginErrorLine(remote, outcome, { call: 'remote', entry }),\n        { remote, kind: pluginErrorKind(outcome) },\n      )\n    }\n\n    const parsed = AcquireResultSchema.safeParse(outcome.result)\n    if (!parsed.success) {\n      await releaseCarried(running, outcome)\n      throw new RemoteRefusalError(\n        `Remote ${remote}: plugin entry ${entry} answered acquire with something that is not a session.`,\n        { remote, kind: 'refused' },\n      )\n    }\n    input.onMask?.(entry, parsed.data.mask ?? [])\n    const session = request.session\n    const unsafe = checkPluginAnswer(parsed.data, {\n      serves: running.manifest.serves,\n      place: session.platform === 'web' ? 'web' : 'device',\n      ...(session.platform === 'web' ? { engine: session.engine } : {}),\n      remote,\n      entry,\n    })\n    if (unsafe !== undefined) {\n      await releaseCarried(running, outcome)\n      throw unsafe\n    }\n    // A session answered once shutdown has begun is released, never handed out.\n    if (closing !== undefined || running.stopping) {\n      void releaseCarried(running, outcome)\n      throw shutDown(remote)\n    }\n    if (running.fault !== undefined) {\n      running.held.add(parsed.data.handle)\n      throw stoppedRefusal(running, remote)\n    }\n    return openLease(running, remote, parsed.data)\n  }\n\n  async function uploadApp(request: PluginUploadRequest): Promise<{ ref: string }> {\n    const { remote, path, platform } = request\n    const entry = request.plugin.entry\n    if (closing !== undefined) throw shutDown(remote)\n    let facts: { sha256: string; size: number }\n    try {\n      facts = await fileFacts(path)\n    } catch {\n      throw new RemoteRefusalError(`Remote ${remote}: the app at ${path} could not be read.`, {\n        remote,\n        kind: 'refused',\n      })\n    }\n    if (closing !== undefined) throw shutDown(remote)\n    const key = JSON.stringify([entry, platform, facts.sha256])\n    let upload = uploads.get(key)\n    if (upload === undefined) {\n      upload = sendUpload(request, facts)\n      uploads.set(key, upload)\n    }\n    return upload\n  }\n\n  async function sendUpload(\n    request: PluginUploadRequest,\n    facts: { sha256: string; size: number },\n  ): Promise<{ ref: string }> {\n    const { remote, path, platform } = request\n    const entry = request.plugin.entry\n    const start = await entryStart(entry)\n    if (!start.ok) throw start.refusal(remote)\n    const running = start.running\n    if (running.fault !== undefined) throw stoppedRefusal(running, remote)\n    if (!declares(running, 'uploadApp')) {\n      throw new RemoteRefusalError(\n        `Remote ${remote}: plugin entry ${entry} uploads no apps; set app.ref on the target to an app the service already has.`,\n        { remote, kind: 'refused' },\n      )\n    }\n    let settings: Record<string, unknown>\n    try {\n      settings = input.resolveSecrets(request.plugin.settings ?? {})\n    } catch (error) {\n      throw asRefusal(error, remote, entry)\n    }\n    const outcome = await running.process.request(\n      'uploadApp',\n      { remote, settings, platform, path, sha256: facts.sha256, size: facts.size },\n      {\n        timeoutMs: request.deadlineMs,\n        onProgress: progressRelay(remote, entry, request.onProgress?.bind(request)),\n      },\n    )\n    if (outcome.status === 'silent') throw silentRefusal(running, remote, request.deadlineMs)\n    if (outcome.status === 'exited' || outcome.status === 'stray') {\n      throw stoppedRefusal(running, remote, outcome)\n    }\n    if (outcome.cancelled) {\n      throw new RemoteRefusalError(\n        `Remote ${remote}: plugin entry ${entry} did not answer uploadApp within ${formatMs(request.deadlineMs)}.`,\n        { remote, kind: 'timeout' },\n      )\n    }\n    if (outcome.status === 'error') {\n      throw new RemoteRefusalError(\n        pluginErrorLine(remote, outcome, { call: 'remote', entry }),\n        { remote, kind: pluginErrorKind(outcome) },\n      )\n    }\n    const parsed = UploadAppResultSchema.safeParse(outcome.result)\n    if (!parsed.success || parsed.data.ref.trim() === '') {\n      throw new RemoteRefusalError(\n        `Remote ${remote}: plugin entry ${entry} answered uploadApp with something that is not an app ref.`,\n        { remote, kind: 'refused' },\n      )\n    }\n    return { ref: parsed.data.ref }\n  }\n\n  async function check(\n    entry: string,\n    remotes: readonly PluginCheckRemote[],\n  ): Promise<CheckResult | undefined> {\n    const remote = remotes[0]?.name ?? entry\n    const start = await entryStart(entry)\n    if (!start.ok) throw start.refusal(remote)\n    const running = start.running\n    if (!declares(running, 'check')) return undefined\n    if (running.fault !== undefined) throw stoppedRefusal(running, remote)\n\n    let params: { remotes: { name: string; settings: Record<string, unknown> }[] }\n    try {\n      params = {\n        remotes: remotes.map((candidate) => ({\n          name: candidate.name,\n          settings: input.resolveSecrets(candidate.settings ?? {}),\n        })),\n      }\n    } catch (error) {\n      throw asRefusal(error, remote, entry)\n    }\n    const outcome = await running.process.request('check', params, within(bounds.checkMs))\n    if (outcome.status === 'result' && !outcome.cancelled) {\n      const parsed = CheckResultSchema.safeParse(outcome.result)\n      if (parsed.success) return parsed.data\n      throw new RemoteRefusalError(\n        `Remote ${remote}: plugin entry ${entry} answered check with something that is not a check result.`,\n        { remote, kind: 'refused' },\n      )\n    }\n    if (outcome.status === 'error' && !outcome.cancelled) {\n      throw new RemoteRefusalError(\n        pluginErrorLine(remote, outcome, { call: 'remote', entry }),\n        { remote, kind: pluginErrorKind(outcome) },\n      )\n    }\n    if (outcome.status === 'exited' || outcome.status === 'stray') {\n      throw stoppedRefusal(running, remote, outcome)\n    }\n    if (outcome.status === 'silent') throw silentRefusal(running, remote, bounds.checkMs)\n    throw new RemoteRefusalError(\n      `Remote ${remote}: plugin entry ${entry} did not answer check within ${formatMs(bounds.checkMs)}.`,\n      { remote, kind: 'timeout' },\n    )\n  }\n\n  async function stopEntry(running: RunningEntry, signal: boolean): Promise<void> {\n    const bound = (ms: number): number => (signal ? bounds.signalMs : ms)\n    if (running.fault === undefined) {\n      await settledWithinLeft(\n        Promise.all([\n          ...[...running.leases].map((lease) => lease.release(bound(bounds.releaseMs))),\n          ...running.releasing,\n        ]),\n      )\n    }\n    if (running.fault !== undefined) {\n      await settledWithinLeft(running.restarted ?? Promise.resolve())\n      return\n    }\n    running.stopping = true\n    await running.process.request('shutdown', {}, within(bound(bounds.shutdownMs)))\n    await stopChild(running.process, bound(bounds.killAfterMs))\n  }\n\n  // On a signal every step shares one bound: calls, waits and the release-only restart get what\n  // is left of it, and whatever still runs when it is spent is killed.\n  // The signal hook stays registered until shutdown settles, so a signal during a slow normal\n  // shutdown still reaches the bounded path.\n  function shutdown(options: { signal?: boolean } = {}): Promise<void> {\n    const signal = options.signal === true\n    if (signal) signalDeadline ??= Date.now() + bounds.signalMs\n    const closed = (closing ??= (async () => {\n      const started = await Promise.allSettled(starts.values())\n      await Promise.allSettled(\n        started.map((start) =>\n          start.status === 'fulfilled' && start.value.ok\n            ? stopEntry(start.value.running, signal)\n            : undefined,\n        ),\n      )\n      while (background.size > 0) await Promise.all(background)\n    })().finally(() => unregisterShutdown?.()))\n    if (signalDeadline === undefined) return closed\n    signalClosing ??= (async () => {\n      await settledWithinLeft(closed)\n      await Promise.all(\n        [...live].map((child) => {\n          const stop = stops.get(child)\n          return stop?.bounded === true ? stop.done : child.stop(0, SIGNAL_KILL_AFTER_MS)\n        }),\n      )\n    })()\n    return signalClosing\n  }\n\n  return { acquire, uploadApp, check, shutdown }\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { dirname, join } from 'node:path'\nimport { pathToFileURL } from 'node:url'\n\nexport interface PluginHostVersions {\n  playwright: string\n  webdriverio: string\n}\n\nfunction resolvedFrom(specifier: string, fromUrl: string): string | undefined {\n  try {\n    return createRequire(fromUrl).resolve(specifier)\n  } catch {\n    return undefined\n  }\n}\n\n// The package may not export its package.json, so the folder holding it is found from its entry.\nfunction versionAbove(name: string, entry: string): string | undefined {\n  for (let dir = dirname(entry); ; dir = dirname(dir)) {\n    const manifest = join(dir, 'package.json')\n    if (existsSync(manifest)) {\n      try {\n        const parsed = JSON.parse(readFileSync(manifest, 'utf8')) as {\n          name?: unknown\n          version?: unknown\n        }\n        if (parsed.name === name && typeof parsed.version === 'string') return parsed.version\n      } catch {\n        return undefined\n      }\n    }\n    if (dirname(dir) === dir) return undefined\n  }\n}\n\nexport function installedPackageVersion(specifier: string, fromUrl: string): string {\n  const entry = resolvedFrom(specifier, fromUrl)\n  return (entry === undefined ? undefined : versionAbove(specifier, entry)) ?? 'unknown'\n}\n\n// Read where the adapter loads it, so a plugin is told the version its session is driven with.\nfunction adapterLibraryVersion(name: string, adapterPackage: string, fromUrl: string): string {\n  const adapter = resolvedFrom(adapterPackage, fromUrl)\n  const viaAdapter =\n    adapter === undefined ? 'unknown' : installedPackageVersion(name, pathToFileURL(adapter).href)\n  return viaAdapter === 'unknown' ? installedPackageVersion(name, fromUrl) : viaAdapter\n}\n\nexport function pluginHostVersions(fromUrl: string): PluginHostVersions {\n  return {\n    playwright: adapterLibraryVersion('playwright-core', '@vostride/agent-qa-web', fromUrl),\n    webdriverio: adapterLibraryVersion('webdriverio', '@vostride/agent-qa-android', fromUrl),\n  }\n}\n","import { RemoteRefusalError } from '@vostride/agent-qa-runner'\nimport type { SecretResolver } from '@vostride/agent-qa-runner'\nimport { SECRET_REFERENCE_PATTERN } from '@vostride/agent-qa-schema'\n\nfunction resolveReferences(\n  value: unknown,\n  secrets: SecretResolver | undefined,\n  secretsFile: string,\n): unknown {\n  if (typeof value === 'string') {\n    const pattern = new RegExp(SECRET_REFERENCE_PATTERN.source, 'g')\n    return value.replace(pattern, (_found, name: string) => {\n      if (secrets?.has(name) !== true) {\n        throw new RemoteRefusalError(\n          `A plugin value needs ${name}, which ${secretsFile} does not declare. Add it there.`,\n          { kind: 'auth' },\n        )\n      }\n      return secrets.require(name)\n    })\n  }\n  if (Array.isArray(value)) {\n    return value.map((item) => resolveReferences(item, secrets, secretsFile))\n  }\n  if (typeof value === 'object' && value !== null) {\n    return Object.fromEntries(\n      Object.entries(value).map(([key, item]) => [\n        key,\n        resolveReferences(item, secrets, secretsFile),\n      ]),\n    )\n  }\n  return value\n}\n\n// Resolves `{{secret:NAME}}` in plugin options and remote settings against declared secrets only.\nexport function pluginSecretResolver(\n  secrets: SecretResolver | undefined,\n  secretsFile: string,\n): (value: Record<string, unknown>) => Record<string, unknown> {\n  return (value) => resolveReferences(value, secrets, secretsFile) as Record<string, unknown>\n}\n","import { chmod, mkdir, readFile, writeFile } from 'node:fs/promises'\nimport { createRequire } from 'node:module'\nimport { homedir } from 'node:os'\nimport { dirname, join } from 'node:path'\nimport { getAgentQaVersion } from '../version.js'\n\nconst require = createRequire(typeof __filename === 'string' ? __filename : import.meta.url)\n\nconst AGENT_QA_NPM_REGISTRY_URL = 'https://registry.npmjs.org/agent-qa'\n\nexport const VERSION_CHECK_CACHE_TTL_MS = 24 * 60 * 60 * 1000\nexport const VERSION_CHECK_TIMEOUT_MS = 5000\n\nexport interface AgentQaUpdateStatus {\n  installedVersion: string\n  latestVersion?: string\n  updateAvailable: boolean\n  checkedAt?: string\n}\n\ntype VersionCheckFetch = (input: string | URL | Request, init?: RequestInit) => Promise<Response>\n\nexport interface VersionCheckOptions {\n  cachePath?: string\n  fetchImpl?: VersionCheckFetch\n  now?: () => Date\n  timeoutMs?: number\n  cacheTtlMs?: number\n  homeDir?: string\n}\n\nexport interface VersionCheckResponse {\n  statusCode?: number\n  setEncoding(encoding: BufferEncoding): unknown\n  on(event: string, listener: (...args: any[]) => void): unknown\n  resume(): unknown\n}\n\nexport interface VersionCheckClientRequest {\n  on(event: string, listener: (...args: any[]) => void): unknown\n  destroy(): unknown\n}\n\n// The shape of `https.get`. Core opens no socket itself: the host passes `https.get` in, and tests\n// pass a stand-in for the registry.\nexport type VersionCheckRequest = (\n  url: string,\n  options: { headers: Record<string, string>; timeout: number },\n  onResponse: (response: VersionCheckResponse) => void,\n) => VersionCheckClientRequest\n\nconst MAX_REGISTRY_RESPONSE_CHARS = 4 * 1024 * 1024\n\ninterface VersionCheckCacheFile {\n  latestVersion?: string\n  checkedAt?: string\n  lastAttemptedAt?: string\n  refreshStartedAt?: string\n}\n\ninterface SemverApi {\n  valid(version: string): string | null\n  gt(version: string, otherVersion: string): boolean\n  compare(version: string, otherVersion: string): -1 | 0 | 1\n  minVersion(range: string): { version: string } | null\n  validRange(range: string): string | null\n  major(version: string): number\n  minor(version: string): number\n}\n\nlet semverApi: SemverApi | undefined\n\nexport function getAgentQaVersionCheckCachePath(homeDir?: string): string {\n  return join(homeDir ?? homedir(), '.agent-qa', 'version-check.json')\n}\n\nexport function compareSemverVersions(left: string, right: string): -1 | 0 | 1 | undefined {\n  const semver = getSemverApi()\n  if (!semver) return undefined\n  const leftVersion = getValidVersion(left, semver)\n  const rightVersion = getValidVersion(right, semver)\n  if (leftVersion === undefined || rightVersion === undefined) return undefined\n  return semver.compare(leftVersion, rightVersion)\n}\n\nexport function validSemverVersion(version: unknown): string | undefined {\n  const semver = getSemverApi()\n  return semver ? getValidVersion(version, semver) : undefined\n}\n\nexport interface AgentQaBreakingStep {\n  from: string\n  to: string\n}\n\n// A crafted version such as 0.9007199254740991.0 must not make the walk run for ever.\nconst MAX_BREAKING_STEPS = 100\n\n// A breaking step is a minor bump in 0.x and a major bump from 1.0 on. Each side is named by its\n// line: `<major>-<minor>` in 0.x, `<major>` from 1.0 on. A prerelease is on its release's line.\nexport function agentQaBreakingSteps(from: string, to: string): AgentQaBreakingStep[] {\n  const semver = getSemverApi()\n  if (!semver) return []\n  const fromVersion = getValidVersion(from, semver)\n  const toVersion = getValidVersion(to, semver)\n  if (fromVersion === undefined || toVersion === undefined) return []\n  try {\n    if (semver.compare(toVersion, fromVersion) !== 1) return []\n    const fromMajor = semver.major(fromVersion)\n    const fromMinor = semver.minor(fromVersion)\n    const toMajor = semver.major(toVersion)\n    const toMinor = semver.minor(toVersion)\n    const fromLine = fromMajor === 0 ? `0-${fromMinor}` : `${fromMajor}`\n    const toLine = toMajor === 0 ? `0-${toMinor}` : `${toMajor}`\n    if (fromLine === toLine) return []\n\n    const stepCount =\n      toMajor === 0\n        ? toMinor - fromMinor\n        : toMajor - Math.max(fromMajor, 1) + (fromMajor === 0 ? 1 : 0)\n    if (stepCount > MAX_BREAKING_STEPS) return [{ from: fromLine, to: toLine }]\n\n    const steps: AgentQaBreakingStep[] = []\n    if (toMajor === 0) {\n      for (let minor = fromMinor; minor < toMinor; minor += 1) {\n        steps.push({ from: `0-${minor}`, to: `0-${minor + 1}` })\n      }\n      return steps\n    }\n    let major = fromMajor\n    if (fromMajor === 0) {\n      steps.push({ from: fromLine, to: '1' })\n      major = 1\n    }\n    for (; major < toMajor; major += 1) {\n      steps.push({ from: `${major}`, to: `${major + 1}` })\n    }\n    return steps\n  } catch {\n    return []\n  }\n}\n\nexport function semverRangeFloor(range: string): string | undefined {\n  const semver = getSemverApi()\n  if (!semver) return undefined\n  try {\n    if (semver.validRange(range) === null) return undefined\n    return semver.minVersion(range)?.version\n  } catch {\n    return undefined\n  }\n}\n\nexport async function getAgentQaUpdateStatus(\n  options: VersionCheckOptions = {},\n): Promise<AgentQaUpdateStatus> {\n  const installedVersion = getInstalledVersion()\n\n  try {\n    return await getAgentQaUpdateStatusInternal(installedVersion, options)\n  } catch {\n    return createStatus(installedVersion)\n  }\n}\n\nexport async function readCachedAgentQaUpdateStatus(options: {\n  homeDir?: string\n  currentVersion: string\n}): Promise<AgentQaUpdateStatus> {\n  const installedVersion = options.currentVersion.trim()\n  try {\n    const semver = getSemverApi()\n    if (!semver) return createStatus(installedVersion)\n    const cache = await readVersionCheckCache(getAgentQaVersionCheckCachePath(options.homeDir))\n    const latestVersion = getValidVersion(cache?.latestVersion, semver)\n    if (!latestVersion || getTimestamp(cache?.checkedAt) === undefined) {\n      return createStatus(installedVersion)\n    }\n    return createStatus(installedVersion, semver, latestVersion, cache?.checkedAt)\n  } catch {\n    return createStatus(installedVersion)\n  }\n}\n\nexport interface LatestAgentQaAnswer {\n  source: 'registry' | 'cache' | 'none'\n  latestVersion?: string\n}\n\n// Asks the registry once under the deadline. Only a fresh answer is written back, so a failed ask\n// never holds back the daily refresh.\nexport async function askLatestAgentQaVersion(options: {\n  homeDir?: string\n  fetchImpl: VersionCheckFetch\n  timeoutMs: number\n  now?: () => Date\n}): Promise<LatestAgentQaAnswer> {\n  try {\n    const semver = getSemverApi()\n    if (!semver) return { source: 'none' }\n    const cachePath = getAgentQaVersionCheckCachePath(options.homeDir)\n    const timeoutMs = getPositiveNumber(options.timeoutMs, VERSION_CHECK_TIMEOUT_MS)\n    const latestVersion =\n      typeof options.fetchImpl === 'function'\n        ? await withDeadline(fetchLatestVersion(options.fetchImpl, timeoutMs, semver), timeoutMs)\n        : undefined\n    const cache = await readVersionCheckCache(cachePath)\n    if (latestVersion !== undefined) {\n      const nowIso = getNow(options.now).toISOString()\n      await writeVersionCheckCache(cachePath, {\n        ...cache,\n        latestVersion,\n        checkedAt: nowIso,\n        lastAttemptedAt: nowIso,\n      })\n      return { source: 'registry', latestVersion }\n    }\n    const cachedLatestVersion = getValidVersion(cache?.latestVersion, semver)\n    return cachedLatestVersion === undefined\n      ? { source: 'none' }\n      : { source: 'cache', latestVersion: cachedLatestVersion }\n  } catch {\n    return { source: 'none' }\n  }\n}\n\n// A fetch that ignores its abort signal must not hold the caller past the deadline either.\nfunction withDeadline<T>(work: Promise<T | undefined>, ms: number): Promise<T | undefined> {\n  return new Promise((resolve) => {\n    const timer = setTimeout(() => resolve(undefined), ms)\n    work.then(\n      (value) => {\n        clearTimeout(timer)\n        resolve(value)\n      },\n      () => {\n        clearTimeout(timer)\n        resolve(undefined)\n      },\n    )\n  })\n}\n\n// A refresh that started this recently is still running, or its process was stopped; either way\n// the next command leaves it alone.\nexport const VERSION_REFRESH_START_WINDOW_MS = 10 * 60 * 1000\nexport const VERSION_REFRESH_DEADLINE_MS = 15_000\n\n// Decides whether the caller should start a refresh, and marks it started. The daily attempt is\n// recorded only by the refresh itself, once its request ends.\nexport async function claimAgentQaVersionRefresh(options: {\n  homeDir?: string\n  now: number\n}): Promise<boolean> {\n  try {\n    const semver = getSemverApi()\n    if (!semver) return false\n    const cachePath = getAgentQaVersionCheckCachePath(options.homeDir)\n    const cache = await readVersionCheckCache(cachePath)\n    const checkedAtMs = getTimestamp(cache?.checkedAt)\n    if (\n      getValidVersion(cache?.latestVersion, semver) &&\n      checkedAtMs !== undefined &&\n      options.now - checkedAtMs < VERSION_CHECK_CACHE_TTL_MS\n    ) {\n      return false\n    }\n    const lastAttemptedAtMs = getTimestamp(cache?.lastAttemptedAt)\n    if (\n      lastAttemptedAtMs !== undefined &&\n      options.now - lastAttemptedAtMs < VERSION_CHECK_CACHE_TTL_MS\n    ) {\n      return false\n    }\n    const refreshStartedAtMs = getTimestamp(cache?.refreshStartedAt)\n    if (\n      refreshStartedAtMs !== undefined &&\n      options.now - refreshStartedAtMs < VERSION_REFRESH_START_WINDOW_MS\n    ) {\n      return false\n    }\n    return await writeVersionCheckCache(cachePath, {\n      ...cache,\n      refreshStartedAt: new Date(options.now).toISOString(),\n    })\n  } catch {\n    return false\n  }\n}\n\n// Asks the registry once and waits for the request to end, then records the attempt, and the\n// version when one came back. Meant for a process of its own, so nothing here unrefs.\nexport async function refreshAgentQaVersionCheck(options: {\n  homeDir?: string\n  now: number\n  request: VersionCheckRequest\n  deadlineMs?: number\n}): Promise<void> {\n  try {\n    const semver = getSemverApi()\n    if (!semver) return\n    const cachePath = getAgentQaVersionCheckCachePath(options.homeDir)\n    const latestVersion = await requestLatestVersion(\n      options.request,\n      semver,\n      getPositiveNumber(options.deadlineMs, VERSION_REFRESH_DEADLINE_MS),\n    )\n    const nowIso = new Date(options.now).toISOString()\n    const cache = await readVersionCheckCache(cachePath)\n    await writeVersionCheckCache(cachePath, {\n      latestVersion: latestVersion ?? cache?.latestVersion,\n      checkedAt: latestVersion === undefined ? cache?.checkedAt : nowIso,\n      lastAttemptedAt: nowIso,\n    })\n  } catch {\n    // Version checks must never block CLI work.\n  }\n}\n\nfunction requestLatestVersion(\n  request: VersionCheckRequest,\n  semver: SemverApi,\n  deadlineMs: number,\n): Promise<string | undefined> {\n  return new Promise((resolve) => {\n    let req: VersionCheckClientRequest | undefined\n    let settled = false\n    const settle = (latestVersion?: string) => {\n      if (settled) return\n      settled = true\n      clearTimeout(deadline)\n      resolve(latestVersion)\n    }\n    // A resolver that never answers is not covered by the request's own idle timeout.\n    const deadline = setTimeout(() => {\n      req?.destroy()\n      settle()\n    }, deadlineMs)\n    try {\n      req = request(\n        AGENT_QA_NPM_REGISTRY_URL,\n        {\n          headers: {\n            accept: 'application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8',\n          },\n          timeout: VERSION_CHECK_TIMEOUT_MS,\n        },\n        (response) => {\n          try {\n            if (response.statusCode !== 200) {\n              response.resume()\n              settle()\n              return\n            }\n            response.setEncoding('utf8')\n            let body = ''\n            response.on('data', (chunk: string) => {\n              body += chunk\n              if (body.length > MAX_REGISTRY_RESPONSE_CHARS) {\n                req?.destroy()\n                settle()\n              }\n            })\n            response.on('error', () => settle())\n            response.on('close', () => settle())\n            response.on('end', () => {\n              try {\n                const parsed = JSON.parse(body) as unknown\n                if (!isRecord(parsed) || !isRecord(parsed['dist-tags'])) return settle()\n                settle(getValidVersion(parsed['dist-tags'].latest, semver))\n              } catch {\n                settle()\n              }\n            })\n          } catch {\n            settle()\n          }\n        },\n      )\n      req.on('timeout', () => {\n        req?.destroy()\n        settle()\n      })\n      req.on('error', () => settle())\n      req.on('close', () => settle())\n    } catch {\n      settle()\n    }\n  })\n}\n\nasync function getAgentQaUpdateStatusInternal(\n  installedVersion: string,\n  options: VersionCheckOptions,\n): Promise<AgentQaUpdateStatus> {\n  const semver = getSemverApi()\n  if (!semver) {\n    return createStatus(installedVersion)\n  }\n\n  const now = getNow(options.now)\n  const nowMs = now.getTime()\n  const nowIso = now.toISOString()\n  const cacheTtlMs = getPositiveNumber(options.cacheTtlMs, VERSION_CHECK_CACHE_TTL_MS)\n  const timeoutMs = getPositiveNumber(options.timeoutMs, VERSION_CHECK_TIMEOUT_MS)\n  const cachePath = options.cachePath ?? getAgentQaVersionCheckCachePath(options.homeDir)\n  const cache = await readVersionCheckCache(cachePath)\n  const cachedLatestVersion = getValidVersion(cache?.latestVersion, semver)\n  const checkedAtMs = getTimestamp(cache?.checkedAt)\n\n  if (cachedLatestVersion && checkedAtMs !== undefined && nowMs - checkedAtMs < cacheTtlMs) {\n    return createStatus(installedVersion, semver, cachedLatestVersion, cache?.checkedAt)\n  }\n\n  const lastAttemptedAtMs = getTimestamp(cache?.lastAttemptedAt)\n  if (lastAttemptedAtMs !== undefined && nowMs - lastAttemptedAtMs < cacheTtlMs) {\n    if (cachedLatestVersion && checkedAtMs !== undefined) {\n      return createStatus(installedVersion, semver, cachedLatestVersion, cache?.checkedAt)\n    }\n\n    return createStatus(installedVersion)\n  }\n\n  const nextCache = { ...cache, lastAttemptedAt: nowIso }\n  const refreshedLatestVersion = await fetchLatestVersion(options.fetchImpl, timeoutMs, semver)\n  if (refreshedLatestVersion) {\n    const refreshedCache = {\n      latestVersion: refreshedLatestVersion,\n      checkedAt: nowIso,\n      lastAttemptedAt: nowIso,\n    }\n    await writeVersionCheckCache(cachePath, refreshedCache)\n    return createStatus(installedVersion, semver, refreshedLatestVersion, nowIso)\n  }\n\n  await writeVersionCheckCache(cachePath, nextCache)\n  if (cachedLatestVersion && checkedAtMs !== undefined) {\n    return createStatus(installedVersion, semver, cachedLatestVersion, cache?.checkedAt)\n  }\n\n  return createStatus(installedVersion)\n}\n\nfunction getInstalledVersion(): string {\n  try {\n    return getAgentQaVersion().trim() || '0.0.0'\n  } catch {\n    return '0.0.0'\n  }\n}\n\nfunction getSemverApi(): SemverApi | undefined {\n  if (semverApi) return semverApi\n\n  try {\n    semverApi = require('semver') as SemverApi\n    return semverApi\n  } catch {\n    return undefined\n  }\n}\n\nfunction getValidVersion(version: unknown, semver: SemverApi): string | undefined {\n  if (typeof version !== 'string') return undefined\n\n  try {\n    return semver.valid(version) ?? undefined\n  } catch {\n    return undefined\n  }\n}\n\nfunction getTimestamp(value: unknown): number | undefined {\n  if (typeof value !== 'string') return undefined\n\n  const timestamp = Date.parse(value)\n  return Number.isFinite(timestamp) ? timestamp : undefined\n}\n\nfunction getPositiveNumber(value: number | undefined, fallback: number): number {\n  return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : fallback\n}\n\nfunction getNow(now: (() => Date) | undefined): Date {\n  try {\n    const candidate = now?.()\n    if (candidate instanceof Date && Number.isFinite(candidate.getTime())) {\n      return candidate\n    }\n  } catch {\n    // Fall through to the system clock.\n  }\n\n  return new Date()\n}\n\nfunction createStatus(\n  installedVersion: string,\n  semver?: SemverApi,\n  latestVersion?: string,\n  checkedAt?: string,\n): AgentQaUpdateStatus {\n  if (!latestVersion) {\n    return {\n      installedVersion,\n      updateAvailable: false,\n    }\n  }\n\n  const installedSemver = semver ? getValidVersion(installedVersion, semver) : undefined\n  const updateAvailable = Boolean(\n    installedSemver && semver && safeSemverGreaterThan(semver, latestVersion, installedSemver),\n  )\n\n  return {\n    installedVersion,\n    latestVersion,\n    updateAvailable,\n    checkedAt,\n  }\n}\n\nfunction safeSemverGreaterThan(semver: SemverApi, version: string, otherVersion: string): boolean {\n  try {\n    return semver.gt(version, otherVersion)\n  } catch {\n    return false\n  }\n}\n\nasync function readVersionCheckCache(\n  cachePath: string,\n): Promise<VersionCheckCacheFile | undefined> {\n  try {\n    const raw = await readFile(cachePath, 'utf-8')\n    const parsed = JSON.parse(raw) as unknown\n    if (!isRecord(parsed)) return undefined\n\n    return {\n      latestVersion: typeof parsed.latestVersion === 'string' ? parsed.latestVersion : undefined,\n      checkedAt: typeof parsed.checkedAt === 'string' ? parsed.checkedAt : undefined,\n      lastAttemptedAt:\n        typeof parsed.lastAttemptedAt === 'string' ? parsed.lastAttemptedAt : undefined,\n      refreshStartedAt:\n        typeof parsed.refreshStartedAt === 'string' ? parsed.refreshStartedAt : undefined,\n    }\n  } catch {\n    return undefined\n  }\n}\n\nasync function writeVersionCheckCache(\n  cachePath: string,\n  cache: VersionCheckCacheFile,\n): Promise<boolean> {\n  try {\n    await mkdir(dirname(cachePath), { recursive: true })\n    await writeFile(cachePath, JSON.stringify(cache, null, 2), {\n      encoding: 'utf-8',\n      mode: 0o600,\n    })\n    try {\n      await chmod(cachePath, 0o600)\n    } catch {\n      // Cache permissions are best effort.\n    }\n    return true\n  } catch {\n    // Version checks must never block CLI or dashboard work.\n    return false\n  }\n}\n\nasync function fetchLatestVersion(\n  fetchImpl: VersionCheckFetch | undefined,\n  timeoutMs: number,\n  semver: SemverApi,\n): Promise<string | undefined> {\n  try {\n    const fetcher = fetchImpl ?? globalThis.fetch?.bind(globalThis)\n    if (typeof fetcher !== 'function') return undefined\n\n    const response = await fetcher(AGENT_QA_NPM_REGISTRY_URL, {\n      headers: { accept: 'application/json' },\n      signal: AbortSignal.timeout(timeoutMs),\n    })\n    if (!response.ok) return undefined\n\n    const body = (await response.json()) as unknown\n    if (!isRecord(body) || !isRecord(body['dist-tags'])) return undefined\n\n    return getValidVersion(body['dist-tags'].latest, semver)\n  } catch {\n    return undefined\n  }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n"],"names":["z","NAME_SLUG_PATTERN","z","REMOTE_PROTOCOLS","remoteEntryIssues","capabilityCredentialIssues","pluginValueCredentialIssues","DEFAULT_REMOTE_CONNECT_TIMEOUT_MS","DEFAULT_REMOTE_CONNECT_TIMEOUT_MS","DEFAULT_REMOTE_UPLOAD_TIMEOUT_MS","isPlainObject","shown","z","z","z","isPlainObject","z","isPlainObject","z","z","z","z","z","fileURLToPath","relative","isAbsolute","resolve","realpathSync","basename","dirname","existsSync","readFileSync","pathToFileURL","messageOf","require","createRequire","z","pluginValueCredentialIssues","capabilityCredentialIssues","appRefIssues","configConnectionSecretNames","secretReferenceNames","remoteOrigin","isLoopbackHost","resolve","join","existsSync","z","HookIdSchema","isCanonicalHookId","isCanonicalTestId","path","z","isCanonicalTestId","isCanonicalHookId","isCanonicalSuiteId","z","isCanonicalHookId","pc","LineCounter","parseAllDocuments","findBareVariables","readFile","extname","dirname","resolve","access","readFile","readFile","parseYaml","EDITABLE_POINTER_ROOTS","Parser","Composer","isEditablePointer","parseJsonPointer","isScalar","isSeq","isMap","CST","isToggleElement","XMLParser","isRecord","dirname","resolvePath","existsSync","RemoteRefusalError","isPluginRemote","isLoopbackHost","scrollerSetSwipeSignal","resolve","existsSync","path","path","randomUUID","mkdir","writeFile","rename","rm","readFile","readdir","readFile","join","homedir","lstat","realpath","resolve","dirname","readlink","basename","randomUUID","mkdir","writeFile","rename","rm","readFile","unlink","SUBSCRIPTION_AUTH_PACKAGE","path","PLUGIN_MANIFEST_FIELD","existsSync","dirname","basename","join","realpathSync","isRecord","readFileSync","PluginManifestSchema","resolve","PLUGIN_PROTOCOL_VERSION","resolve","join","existsSync","realpathSync","require","createRequire","loadedDeclarations","randomBytes","createHash","isRecord","z","randomBytes","pc","randomUUID","redactSecretValue","readFile","parseYaml","dirname","resolve","configConnectionSecretNames","connectionSecretNames","remoteLabel","secretReferenceNames","path","existsSync","readFile","parseYaml","LineCounter","parseDocument","path","existsSync","configConnectionSecretNames","pc","generateSharedHookId","generateSharedRunId","isSharedCanonicalRunId","SECRET_REFERENCE_PATTERN","isObject","resolve","statSync","readFileSync","Ajv2020","isObject","secretReferenceNames","sep","isAbsolute","join","resolve","existsSync","statSync","readFileSync","readdirSync","lstatSync","extname","relative","parseYaml","dirname","isAlias","projectConfigRemotes","isSeq","isMap","isScalar","isNode","isRecord","Scalar","parseDocument","remoteLabel","connectionSecretNames","RemoteRefusalError","SECRET_REFERENCE_PATTERN","resolveSecretTemplatesInValue","basicAuthorizationValue","remoteLabel","remoteOrigin","formatRemoteOrigin","secretReferenceNames","RemoteRefusalError","resolveSecretTemplatesInValue","remoteLabel","releasingOnce","MIN_PLUGIN_CONNECT_MS","RemoteRefusalError","remoteOrigin","isLoopbackHost","formatRemoteOrigin","isRecord","spawn","pluginEnvironment","encodeMessage","ProgressParamsSchema","createLineDecoder","MAX_MESSAGE_BYTES","PROGRESS_METHOD","CANCEL_METHOD","stat","createHash","createReadStream","isRecord","RemoteRefusalError","PLUGIN_ERROR_CODES","PluginErrorDataSchema","resolve","InitializeResultSchema","REMOTE_RELEASE_BOUND_MS","PLUGIN_RELEASE_BOUND_MS","StartedResultSchema","AcquireResultSchema","UploadAppResultSchema","CheckResultSchema","createRequire","dirname","join","existsSync","readFileSync","pathToFileURL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