diff --git a/.github/scripts/run-agent-task/build-codebox-task-request.mjs b/.github/scripts/run-agent-task/build-codebox-task-request.mjs index c3ce4efd..652710e4 100644 --- a/.github/scripts/run-agent-task/build-codebox-task-request.mjs +++ b/.github/scripts/run-agent-task/build-codebox-task-request.mjs @@ -1,5 +1,6 @@ import { mkdirSync, writeFileSync, appendFileSync } from "node:fs" import { normalizeExternalPackageSource, normalizeRuntimeSources, parseExternalPackageSourcePolicy } from "./materialize-external-native-package.mjs" +import { parseProductSiteInput } from "./product-site-request.mjs" function parseJson(name, fallback, expected) { const raw = process.env[name] @@ -127,6 +128,8 @@ const request = { run_agent: booleanEnv("RUN_AGENT"), dry_run: booleanEnv("DRY_RUN"), } +const productSite = parseProductSiteInput(process.env.PRODUCT_SITE) +if (productSite) request.product_site = productSite if (request.access.allowed_repos.some((repository) => typeof repository !== "string" || !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repository))) { throw new Error("ALLOWED_REPOS must be a JSON array of OWNER/REPO values.") diff --git a/.github/scripts/run-agent-task/execute-native-agent-task.mjs b/.github/scripts/run-agent-task/execute-native-agent-task.mjs index 799ebca6..85829996 100644 --- a/.github/scripts/run-agent-task/execute-native-agent-task.mjs +++ b/.github/scripts/run-agent-task/execute-native-agent-task.mjs @@ -7,6 +7,7 @@ import { spawn } from "node:child_process" import { createHash } from "node:crypto" import { canonicalExternalNativeAgentIdentity, materializeExternalNativePackage, materializeRuntimeSources, normalizeExternalPackageSource, normalizeRuntimeSources, parseExternalPackageSourcePolicy, sha256BytesV1, validateRuntimeSourceModel } from "./materialize-external-native-package.mjs" import { readNativeResult } from "./native-result-file.mjs" +import { normalizeProductSiteRequest } from "./product-site-request.mjs" import { assertNoRuntimeSourcePaths, sanitizeArtifactUploadText, sanitizeRuntimeSourceJson, sanitizeRuntimeSourceText, sanitizeRuntimeSourceValue } from "./runtime-source-sanitizer.mjs" import { publishRunnerWorkspace } from "./runner-workspace-publisher.mjs" import { createRunnerWorkspaceSeedSnapshot, RUNNER_WORKSPACE_SEED_EXCLUDES } from "./runner-workspace-seed-snapshot.mjs" @@ -739,9 +740,12 @@ const runtimeInputPath = join(workspace, ".codebox", "native-agent-task-input.js const resultPath = join(workspace, ".codebox", "agent-task-workflow-result.json") const controlledCodeboxPath = resolve(requestPath, "..") const nativeResultPath = join(controlledCodeboxPath, "native-agent-task-result.json") + const productSite = normalizeProductSiteRequest(request.product_site) const runnerWorkspaceTools = [ "workspace_read", "workspace_ls", "workspace_grep", "workspace_write", "workspace_edit", "workspace_apply_patch", "workspace_show", "workspace_git_status", "workspace_git_diff", + // Read-only product page viewer; only declared when product_site is set. + ...(productSite ? ["product_page_view"] : []), ] function runtimeMetadataForExecutionLocation(executionLocation) { @@ -836,6 +840,8 @@ const taskInput = { metadata: { workload: request.workload, ...(materializedPackage ? { imported_agent: materializedPackage.identity } : {}), runtime_sources: materializedRuntimeSources?.descriptors ?? [], ...(runnerWorkspaceSeedSnapshot ? { runner_workspace_seed: runnerWorkspaceSeedSnapshot.provenance } : {}) }, }, }, + // The CLI boots this site before the agent turn and tears it down after. + ...(productSite ? { product_site: productSite } : {}), // agent-task-run unwraps task_input before building the recipe. The // external snapshot prevents the recipe from ever mounting the checkout. workspaces: runnerWorkspaceSeedSnapshot ? [{ target: "/workspace", mode: "readwrite", sourceMode: "repo-backed", seed: { type: "directory", source: runnerWorkspaceSeedSnapshot.source, excludePaths: RUNNER_WORKSPACE_SEED_EXCLUDES } }] : [], diff --git a/.github/scripts/run-agent-task/prepare-agent-task-upload.mjs b/.github/scripts/run-agent-task/prepare-agent-task-upload.mjs index caa83239..a90a62d4 100644 --- a/.github/scripts/run-agent-task/prepare-agent-task-upload.mjs +++ b/.github/scripts/run-agent-task/prepare-agent-task-upload.mjs @@ -118,6 +118,44 @@ async function stageTextFile(source, destination, options = {}) { return true } +const PRODUCT_SITE_SCREENSHOT_DIRECTORY = "product-site/screenshots" +const PRODUCT_SITE_SCREENSHOT_NAME = /^page-\d{3}\.png$/ +const PRODUCT_SITE_MAX_SCREENSHOTS = 50 +const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]) + +// product_site screenshots are the only binary upload: bounded, non-symlink +// PNG files with the exact names the page viewer writes, copied byte-for-byte. +async function stageProductSiteScreenshots(request) { + const staged = new Set() + if (!record(request.product_site).start_url) return staged + const directory = join(artifactsPath, PRODUCT_SITE_SCREENSHOT_DIRECTORY) + const directoryMetadata = await lstat(directory).catch(() => null) + if (!directoryMetadata?.isDirectory()) return staged + const names = (await readdir(directory, { withFileTypes: true }).catch(() => [])) + .filter((entry) => entry.isFile() && PRODUCT_SITE_SCREENSHOT_NAME.test(entry.name)) + .map((entry) => entry.name) + .sort() + .slice(0, PRODUCT_SITE_MAX_SCREENSHOTS) + for (const name of names) { + const path = `${PRODUCT_SITE_SCREENSHOT_DIRECTORY}/${name}` + const source = join(directory, name) + if (sourceCategory(path, source)) continue + const metadata = await lstat(source).catch(() => null) + if (!metadata?.isFile() || metadata.size > MAX_UPLOAD_FILE_BYTES) continue + const handle = await open(source, constants.O_RDONLY | constants.O_NOFOLLOW).catch(() => null) + if (!handle) continue + const openedMetadata = await handle.stat() + const bytes = openedMetadata.isFile() && openedMetadata.size <= MAX_UPLOAD_FILE_BYTES ? await readBoundedFile(handle, MAX_UPLOAD_FILE_BYTES) : null + await handle.close() + if (!bytes || bytes.length > MAX_UPLOAD_FILE_BYTES || !bytes.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE)) continue + const destination = join(uploadPath, ".codebox", "agent-task-artifacts", path) + await mkdir(resolve(destination, ".."), { recursive: true }) + await writeFile(destination, bytes) + staged.add(path) + } + return staged +} + function canonicalTranscript(result) { const descriptor = record(record(result).reviewer_evidence).transcript if (descriptor === undefined) return undefined @@ -558,6 +596,7 @@ for (const [path, reference] of workflowOutputArtifactsToStage) { } await stageTextFile(source, join(uploadPath, ".codebox", "agent-task-artifacts", path)) } +for (const path of await stageProductSiteScreenshots(request)) declaredPaths.add(path) const transcript = await stageCanonicalTranscript(result) if (transcript?.provenance?.source_sha256) { const stagedResultPath = join(uploadPath, ".codebox", "agent-task-workflow-result.json") diff --git a/.github/scripts/run-agent-task/product-site-request.mjs b/.github/scripts/run-agent-task/product-site-request.mjs new file mode 100644 index 00000000..4793dbc2 --- /dev/null +++ b/.github/scripts/run-agent-task/product-site-request.mjs @@ -0,0 +1,66 @@ +// Validates the optional `product_site` workflow input. An empty value keeps the +// run unchanged; a declared site is booted read-only beside the agent runtime. +const MAX_PRODUCT_SITE_BYTES = 64 * 1024 +const ROLE_PATTERN = /^[a-z0-9_-]{1,64}$/ +const SLUG_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/ +const ALLOWED_FIELDS = new Set(["blueprint", "plugins", "start_url", "login_role", "wp"]) + +function isRecord(value) { + return Boolean(value) && typeof value === "object" && !Array.isArray(value) +} + +function workspaceRelativePath(value, field) { + if (typeof value !== "string" || !value.trim()) throw new Error(`${field} must be a non-empty workspace-relative path.`) + const path = value.trim().replace(/\\/g, "/").replace(/^\.\//, "").replace(/\/+$/, "") + if (!path || path.startsWith("/") || /^[A-Za-z]:/.test(path) || path.split("/").some((part) => !part || part === "." || part === "..")) { + throw new Error(`${field} must be a workspace-relative path without traversal.`) + } + return path +} + +function siteRelativePath(value, field) { + if (typeof value !== "string") throw new Error(`${field} must be a string.`) + const path = value.trim() || "/" + if (path.length > 2048 || /[\u0000-\u001f\u007f\\]/.test(path) || /^[a-z][a-z0-9+.-]*:/i.test(path) || path.startsWith("//")) { + throw new Error(`${field} must be a site-relative path such as /about/.`) + } + return path.startsWith("/") ? path : `/${path}` +} + +export function parseProductSiteInput(raw) { + const text = typeof raw === "string" ? raw.trim() : "" + if (!text) return undefined + if (Buffer.byteLength(text) > MAX_PRODUCT_SITE_BYTES) throw new Error("PRODUCT_SITE exceeds 64 KiB.") + return normalizeProductSiteRequest(JSON.parse(text)) +} + +export function normalizeProductSiteRequest(value) { + if (value === undefined || value === null) return undefined + if (!isRecord(value)) throw new Error("product_site must be a JSON object.") + if (Object.keys(value).length === 0) return undefined + const unknown = Object.keys(value).filter((key) => !ALLOWED_FIELDS.has(key)) + if (unknown.length) throw new Error(`product_site has unsupported fields: ${unknown.join(", ")}.`) + if (value.blueprint !== undefined && !isRecord(value.blueprint)) throw new Error("product_site.blueprint must be a Playground blueprint object.") + if (value.plugins !== undefined && !Array.isArray(value.plugins)) throw new Error("product_site.plugins must be an array.") + const plugins = (value.plugins ?? []).map((entry, index) => { + const field = `product_site.plugins[${index}]` + if (typeof entry === "string") return workspaceRelativePath(entry, field) + if (!isRecord(entry)) throw new Error(`${field} must be a path string or {path, slug, activate}.`) + const extra = Object.keys(entry).filter((key) => !["path", "slug", "activate"].includes(key)) + if (extra.length) throw new Error(`${field} has unsupported fields: ${extra.join(", ")}.`) + if (entry.slug !== undefined && (typeof entry.slug !== "string" || !SLUG_PATTERN.test(entry.slug))) throw new Error(`${field}.slug must be a plugin directory slug.`) + if (entry.activate !== undefined && typeof entry.activate !== "boolean") throw new Error(`${field}.activate must be a boolean.`) + return Object.fromEntries(Object.entries({ path: workspaceRelativePath(entry.path, `${field}.path`), slug: entry.slug, activate: entry.activate }).filter(([, item]) => item !== undefined)) + }) + if (value.login_role !== undefined && value.login_role !== "" && (typeof value.login_role !== "string" || !ROLE_PATTERN.test(value.login_role))) { + throw new Error("product_site.login_role must be a WordPress role slug.") + } + if (value.wp !== undefined && (typeof value.wp !== "string" || !/^[A-Za-z0-9._-]{1,32}$/.test(value.wp))) throw new Error("product_site.wp must be a WordPress version.") + return Object.fromEntries(Object.entries({ + blueprint: value.blueprint ?? {}, + plugins, + start_url: siteRelativePath(value.start_url ?? "/", "product_site.start_url"), + login_role: value.login_role || undefined, + wp: value.wp, + }).filter(([, item]) => item !== undefined)) +} diff --git a/.github/workflows/run-agent-task.yml b/.github/workflows/run-agent-task.yml index 093bbc7a..8370e5be 100644 --- a/.github/workflows/run-agent-task.yml +++ b/.github/workflows/run-agent-task.yml @@ -55,6 +55,10 @@ name: Run Agent Task (reusable) description: JSON runner-owned workspace publication request. type: string default: '{}' + product_site: + description: "Optional JSON read-only product site {blueprint, plugins, start_url, login_role}. When set, the site boots before the agent turn and the agent gets the product_page_view tool; plugin paths are relative to the target workspace." + type: string + default: "" validation_dependencies: description: Optional validation dependency install command. type: string @@ -229,6 +233,11 @@ jobs: working-directory: .wp-codebox-workflow run: npm ci + - name: Install product site browser + if: inputs.product_site != '' && inputs.product_site != '{}' + working-directory: .wp-codebox-workflow + run: npx playwright install --with-deps chromium + - name: Prepare GitHub App token configuration id: access-app-config env: @@ -308,6 +317,7 @@ jobs: # value set under it is ignored and the script receives the runner's # workspace path instead of this JSON config. RUNNER_WORKSPACE_CONFIG: ${{ inputs.runner_workspace }} + PRODUCT_SITE: ${{ inputs.product_site }} VALIDATION_DEPENDENCIES: ${{ inputs.validation_dependencies }} VERIFICATION_COMMANDS: ${{ inputs.verification_commands }} DRIFT_CHECKS: ${{ inputs.drift_checks }} diff --git a/contracts/run-agent-task-reusable-workflow-interface.v1.json b/contracts/run-agent-task-reusable-workflow-interface.v1.json index 2183a9d7..471f89c3 100644 --- a/contracts/run-agent-task-reusable-workflow-interface.v1.json +++ b/contracts/run-agent-task-reusable-workflow-interface.v1.json @@ -24,6 +24,7 @@ "max_turns": { "required": false, "type": "number", "default": 12 }, "time_budget_ms": { "required": false, "type": "number", "default": 600000 }, "output_projections": { "required": false, "type": "string", "default": "{}" }, + "product_site": { "required": false, "type": "string", "default": "" }, "transcript_artifact_name": { "required": false, "type": "string", "default": "agent-task-transcript" }, "replay_bundle_artifact_name": { "required": false, "type": "string", "default": "" }, "expected_artifacts": { "required": false, "type": "string", "default": "[]" }, diff --git a/docs/agent-task-reusable-workflow.md b/docs/agent-task-reusable-workflow.md index 71ed1c0a..d064a3c9 100644 --- a/docs/agent-task-reusable-workflow.md +++ b/docs/agent-task-reusable-workflow.md @@ -65,6 +65,7 @@ This release-coherence contract fixes [#1759](https://github.com/Automattic/wp-c - `target_repo`: `OWNER/REPO` target repository. - `prompt`, `writable_paths`, provider/model, `max_turns`, `time_budget_ms`, callback data, and artifact declarations: native task inputs. - `runner_workspace`: JSON runner-workspace publication request owned by the package. +- `product_site`: optional JSON read-only product site, `{ "blueprint": {...}, "plugins": ["path/to/plugin"], "start_url": "/", "login_role": "subscriber" }`. Empty (the default) leaves the run unchanged. When set, the workflow installs Playwright Chromium, the runner boots the site from the Playground `blueprint` with each plugin directory (relative to the target workspace, or `{path, slug, activate}`) mounted read-only and activated, and tears it down after the agent turn. The agent gets one extra tool, `product_page_view({ path })`, which loads a site-relative path in Chromium and returns the title, bounded visible text, heading outline, links/buttons/form labels, and the artifact path of a PNG screenshot staged under `product-site/screenshots/`. Navigation is GET-only: non-GET requests, form submissions, and requests to other origins are blocked, and the only credential is an optional fixture user with the declared `login_role`. - `validation_dependencies`: optional shell command that installs validation dependencies in the target workspace. - `verification_commands` and `drift_checks`: JSON arrays of non-empty command strings or `{command, description}` objects. Every entry runs and must pass. An object may declare one output as `artifact: {name, type, path}`. All three artifact fields are required, `path` is relative to `.codebox/agent-task-artifacts`, and the exact name/type pair must also be an output in `artifact_declarations`. After an exit-zero command, the workflow accepts only an existing regular UTF-8 file of at most 4 MiB without path traversal or symlinks. It adds a canonical `wp-codebox/typed-artifact/v1` reference to that verification record so declared-artifact upload staging collects the file. Artifact validation fails that verification before publication; failed commands never accept an artifact. Strings and command/description-only objects retain their existing behavior. - `success_requires_pr`: require a successful, published runner-workspace pull request for `target_repo`. @@ -246,6 +247,6 @@ workflow itself cannot inspect the caller's `uses:` declaration at runtime. ## Upload safety limits -The reusable workflow stages every uploaded file through a fail-closed policy. Only regular UTF-8 files of 4 MiB or less are uploaded, after configured secret values are redacted. Symlinks, special files, binary files, and files larger than 4 MiB are excluded from the upload staging directory. This applies to task artifacts and workflow request, input, and result files. +The reusable workflow stages every uploaded file through a fail-closed policy. Only regular UTF-8 files of 4 MiB or less are uploaded, after configured secret values are redacted. The one binary exception is `product_site` screenshots: regular, non-symlink PNG files named `product-site/screenshots/page-NNN.png` of 4 MiB or less are copied byte-for-byte after their PNG signature is verified. Symlinks, special files, binary files, and files larger than 4 MiB are excluded from the upload staging directory. This applies to task artifacts and workflow request, input, and result files. Native task execution, validation-dependency installation, verification, drift checks, and GitHub pull-request validation retain at most 32 KiB from each stdout and stderr stream while continuing to drain both streams. Command results expose `stdout_truncated` and `stderr_truncated` when retained output is incomplete. Native `agent-task-run` structured output is instead read from a controlled `.codebox/native-agent-task-result.json` file outside the agent-writable target checkout. The executor accepts only a regular, non-symlink JSON file up to 1 MiB with the required result schemas, rejects configured secret values, redacts the accepted record before persistence, and removes the transient native result file after reading it. diff --git a/package.json b/package.json index 98a3c520..5cddae54 100644 --- a/package.json +++ b/package.json @@ -135,6 +135,7 @@ "test:runtime-package-boundaries": "node --test tests/derive-cloudflare-core-contract-atomic.test.mjs && node tests/runtime-package-boundaries.test.mjs", "test:agent-task-contracts": "tsx tests/agent-task-contracts.test.ts && tsx tests/agent-task-canonical-evidence.test.ts && npm run test:agent-task-workflow-interface && npm run test:runtime-sources-materialization && tsx tests/agent-task-reusable-workflow.test.ts", "test:agent-task-workflow-interface": "tsx tests/run-agent-task-reusable-workflow-interface.test.ts", + "test:product-site": "tsx tests/product-site-workflow.test.ts && php scripts/php-product-site-executor-smoke.php && tsx --test tests/product-site-page-view.browser.test.ts", "test:agent-task-runtime-package-staging": "tsx tests/agent-task-runtime-package-staging.test.ts", "test:external-native-package-materialization": "tsx tests/external-native-package-materialization.test.ts", "test:runtime-sources-materialization": "tsx tests/runtime-sources-materialization.test.ts", diff --git a/packages/cli/src/commands/agent-task-run.ts b/packages/cli/src/commands/agent-task-run.ts index e10e6007..e5649838 100644 --- a/packages/cli/src/commands/agent-task-run.ts +++ b/packages/cli/src/commands/agent-task-run.ts @@ -3,6 +3,7 @@ import { tmpdir } from "node:os" import { dirname, isAbsolute, join, relative, resolve } from "node:path" import { AGENT_TASK_RUN_REQUEST_SCHEMA, HEADLESS_AGENT_TASK_REQUEST_SCHEMA, artifactResultEnvelope, buildAgentTaskRecipe, DEFAULT_WORDPRESS_VERSION, headlessAgentTaskRequestToRunInput, normalizeAgentRuntimeExecutionChanges, normalizeAgentRuntimeWorkload, normalizeAgentTaskRunResult, normalizeAgentTerminalResult, normalizeArtifactResultTypedArtifacts, normalizeHeadlessAgentTaskRequest, normalizeHeadlessAgentTaskResult, normalizeTaskInput, parseCommandOptions, publicArtifactRefGroups, resolveEffectiveRuntimeToolPolicy, type AgentTaskRunInput, type AgentTaskRunResultSummary, type AgentTerminalResult, type ArtifactResultEnvelope, type HeadlessAgentTaskResult, type SandboxToolPolicySnapshot, type TypedArtifactDTO } from "@automattic/wp-codebox-core" import { stripUndefined } from "@automattic/wp-codebox-core/internals" +import { normalizeProductSiteSpec, startProductSite, type ProductSiteSession, type ProductSiteSpec } from "@automattic/wp-codebox-playground" import { parsePreviewBind, parsePreviewHoldSeconds, parsePreviewLease, parsePreviewPort, parsePreviewPublicUrl } from "../preview-options.js" import { createRecipeRunOptions, executeRecipeRun } from "./recipe-run.js" import type { RecipeRunCommandOutput } from "./recipe-run-types.js" @@ -128,9 +129,15 @@ export async function runAgentTask(input: AgentTaskRunInput, options: AgentTaskR let runOutput: RecipeRunCommandOutput | undefined let recipeJson = "" let generatedRecipeArtifact: GeneratedRecipeArtifactRef | undefined + let productSite: ProductSiteSession | undefined try { - const recipe = buildAgentTaskRecipe({ ...input, artifacts_path: artifacts }, taskInput, wpVersion) + // The product site is booted before the agent turn and torn down in the + // finally below. Without product_site the run is unchanged. + const productSiteSpec = normalizeProductSiteSpec(input.product_site, { baseDirectory: process.cwd() }) + productSite = productSiteSpec ? await startProductSite(productSiteSpec, { artifactsDirectory: artifacts }) : undefined + const recipeInput = productSiteSpec ? withProductSiteRuntimeTask(input, productSiteSpec) : input + const recipe = buildAgentTaskRecipe({ ...recipeInput, artifacts_path: artifacts }, taskInput, wpVersion) recipeJson = `${JSON.stringify(recipe, null, 2)}\n` runOutput = await executeRecipeRun(createRecipeRunOptions({ recipePath, @@ -143,6 +150,7 @@ export async function runAgentTask(input: AgentTaskRunInput, options: AgentTaskR previewHoldBlocking: options.previewHoldBlocking ?? false, previewPublicUrl: options.previewPublicUrl ? parsePreviewPublicUrl(options.previewPublicUrl) : undefined, previewLease: options.previewLeaseJson ? parsePreviewLease(options.previewLeaseJson) : undefined, + hostTools: productSite ? [productSite.hostTool()] : undefined, })) generatedRecipeArtifact = await persistGeneratedRecipeArtifact(artifacts, recipeJson) const run = runOutput as unknown as Record @@ -249,6 +257,7 @@ export async function runAgentTask(input: AgentTaskRunInput, options: AgentTaskR workload, }, artifact_result: artifactResult, + ...(productSite ? { product_site: productSiteSummary(productSite) } : {}), }, } return output @@ -316,11 +325,37 @@ export async function runAgentTask(input: AgentTaskRunInput, options: AgentTaskR }, }, artifact_result: artifactResult, + ...(productSite ? { product_site: productSiteSummary(productSite) } : {}), }, } + } finally { + await productSite?.close() } } +/** + * Tells the sandboxed runtime package that `product_page_view` is available. + * Only non-secret, site-relative hints cross into the sandbox. + */ +export function withProductSiteRuntimeTask(input: AgentTaskRunInput, spec: ProductSiteSpec): AgentTaskRunInput { + const runtimeTask = objectValue(input.runtime_task) + const packageTask = objectValue(runtimeTask?.input) + const workflowInput = objectValue(packageTask?.input) + if (!runtimeTask || !packageTask || !workflowInput) return input + const productSite = stripUndefined({ enabled: true, start_url: spec.start_url, login_role: spec.login_role }) + return { ...input, runtime_task: { ...runtimeTask, input: { ...packageTask, input: { ...workflowInput, product_site: productSite } } } } +} + +function productSiteSummary(session: ProductSiteSession): Record { + return stripUndefined({ + schema: session.spec.schema, + start_url: session.spec.start_url, + login_role: session.spec.login_role, + plugins: session.spec.plugins.map(({ slug, activate }) => ({ slug, activate })), + screenshots: session.screenshots(), + }) +} + function maybeHeadlessAgentTaskResult(input: AgentTaskRunInput, agentTaskRunResult: AgentTaskRunResultSummary): HeadlessAgentTaskResult | undefined { if (stringValue(input.parent_request?.schema) !== HEADLESS_AGENT_TASK_REQUEST_SCHEMA) { return undefined diff --git a/packages/cli/src/commands/recipe-run-types.ts b/packages/cli/src/commands/recipe-run-types.ts index 7fef1fc7..96363d5a 100644 --- a/packages/cli/src/commands/recipe-run-types.ts +++ b/packages/cli/src/commands/recipe-run-types.ts @@ -1,4 +1,4 @@ -import type { AgentTerminalResult, ArtifactBundle, ArtifactPackageProvenance, BenchResults, ExecutionResult, PreviewLease, RecipeRunSummary, RuntimeInfo, RuntimePolicy, RuntimeRunRecord, TypedArtifactRef, WorkspaceRecipe, WorkspaceRecipeFuzzCasePhase } from "@automattic/wp-codebox-core" +import type { AgentTerminalResult, ArtifactBundle, HostToolDefinition, ArtifactPackageProvenance, BenchResults, ExecutionResult, PreviewLease, RecipeRunSummary, RuntimeInfo, RuntimePolicy, RuntimeRunRecord, TypedArtifactRef, WorkspaceRecipe, WorkspaceRecipeFuzzCasePhase } from "@automattic/wp-codebox-core" import type { RecipeDryRunOutput, RecipeDryRunSiteSeed, RecipeDryRunStagedFile } from "../recipe-dry-run.js" import type { AgentSandboxResultSummary, AgentTaskSingleResult, RecipeReplayStatusSummary, SandboxCompletionOutcome } from "../recipe-evidence.js" import type { RecipeExternalServiceBoundaryHostCorrelation } from "../recipe-external-services.js" @@ -33,6 +33,8 @@ export interface RecipeRunOptions { summary: boolean dryRun: boolean hostNodeHeapMiB?: number + /** Run-scoped host tools, e.g. the product site page viewer. Never serialized into the recipe. */ + hostTools?: HostToolDefinition[] } export type RecipeRunOptionsInput = Pick & Partial> diff --git a/packages/cli/src/commands/recipe-run.ts b/packages/cli/src/commands/recipe-run.ts index f701e813..8e5d38ba 100644 --- a/packages/cli/src/commands/recipe-run.ts +++ b/packages/cli/src/commands/recipe-run.ts @@ -305,6 +305,7 @@ export async function runRecipe(options: RecipeRunOptions, interruption?: Recipe ...recipeRunMetadata(recipe, recipePath, recipeDirectory, workspaceMounts, extraPlugins, dependencyOverlays, stagedFiles, overlays, backendPackage, effectivePreview), }, preview: previewSpec(effectivePreview.publicUrl, effectivePreview.port, effectivePreview.bind, effectivePreview.siteUrl, effectivePreview.lease), + ...(options.hostTools?.length ? { hostTools: options.hostTools } : {}), } try { const startupStartedAtMs = Date.now() diff --git a/packages/runtime-core/src/agent-task-recipe.ts b/packages/runtime-core/src/agent-task-recipe.ts index 307ffb16..cde61ef1 100644 --- a/packages/runtime-core/src/agent-task-recipe.ts +++ b/packages/runtime-core/src/agent-task-recipe.ts @@ -64,6 +64,12 @@ export interface AgentTaskRunInput { parent_request?: Record orchestrator?: Record target?: Record + /** + * Optional read-only product site booted beside the agent runtime + * (`{ blueprint, plugins, start_url, login_role }`). The CLI owns its + * lifecycle; the recipe itself never carries it. + */ + product_site?: Record } interface RuntimeOverlayProfileDefaults { diff --git a/packages/runtime-playground/src/index.ts b/packages/runtime-playground/src/index.ts index b7e0a917..0a88b827 100644 --- a/packages/runtime-playground/src/index.ts +++ b/packages/runtime-playground/src/index.ts @@ -11,6 +11,7 @@ export { runBrowserMultiActorScenarioCommand } from "./browser-multi-actor-scena export { runBrowserActionsCommand, runBrowserScenarioCommand, type BrowserActionsRunPlan } from "./browser-actions-runner.js" export { browserStorageStateCookieHostSummary, browserStorageStateFromWordPressAuthCookies, normalizeBrowserStorageStatePayload, wordpressFixtureUserStorageStatePhpCode, type BrowserAuthStorageState, type BrowserStorageStateCookie, type BrowserStorageStateImportResult, type BrowserStorageStateImportSummary, type WordPressFixtureUserSpec, type WordPressFixtureUserStorageStateEnvelope } from "./browser-auth-storage-state.js" export { createHostCommandTool, type HostCommandToolConfig } from "./host-command-tool.js" +export { PRODUCT_PAGE_VIEW_SCHEMA, PRODUCT_PAGE_VIEW_TOOL, PRODUCT_SITE_SCHEMA, PRODUCT_SITE_SCREENSHOT_DIRECTORY, normalizeProductSitePath, normalizeProductSiteSpec, productSiteBlueprint, startProductSite, type ProductPageInteractiveElement, type ProductPageView, type ProductSitePlugin, type ProductSiteSession, type ProductSiteSpec, type ProductSiteStartOptions } from "./product-site.js" export { PlaygroundRuntimeBackend, createPlaygroundRuntimeBackend, playgroundRuntimeBackendProvider } from "./playground-runtime.js" export { maintainPlaygroundCustomArchiveCache, playgroundWordPressArchiveCacheDirectory, type PlaygroundCustomArchiveCacheMaintenance, type PlaygroundCustomArchiveCacheMaintenanceOptions, type PlaygroundCustomArchiveCachePolicy } from "./playground-wordpress-archive-cache.js" export { WORDPRESS_SOURCE_SCHEMA, materializePlaygroundWordPressSource, playgroundWordPressSourceDirectory, type PlaygroundWordPressSource, type PlaygroundWordPressSourceOptions } from "./playground-wordpress-source.js" diff --git a/packages/runtime-playground/src/php-host-tool-bridge.ts b/packages/runtime-playground/src/php-host-tool-bridge.ts new file mode 100644 index 00000000..decefea5 --- /dev/null +++ b/packages/runtime-playground/src/php-host-tool-bridge.ts @@ -0,0 +1,46 @@ +import { HostToolRegistry, createHostToolRegistry, createHostToolTransportError, executeHostTool, type HostToolDefinition, type JsonValue, type RuntimeCreateSpec } from "@automattic/wp-codebox-core" + +/** + * Sandbox PHP -> host tool calls carried over Playground's post_message_to_js. + * + * Only host tools that opt in with `runtime.php_bridge === true` are reachable; + * every other registered host tool stays a recipe-only command. + */ +export const PHP_HOST_TOOL_CALL_SCHEMA = "wp-codebox/php-host-tool-call/v1" as const +const PHP_HOST_TOOL_CALL_MAX_BYTES = 64 * 1024 + +export interface PhpHostToolCallMessage { + schema: typeof PHP_HOST_TOOL_CALL_SCHEMA + tool: string + input: JsonValue +} + +export function parsePhpHostToolCallMessage(data: string): PhpHostToolCallMessage | undefined { + if (Buffer.byteLength(data) > PHP_HOST_TOOL_CALL_MAX_BYTES) return undefined + let value: unknown + try { + value = JSON.parse(data) + } catch { + return undefined + } + if (!value || typeof value !== "object" || Array.isArray(value)) return undefined + const message = value as Partial + if (message.schema !== PHP_HOST_TOOL_CALL_SCHEMA || typeof message.tool !== "string" || message.tool.length < 1 || message.tool.length > 128) return undefined + return { schema: PHP_HOST_TOOL_CALL_SCHEMA, tool: message.tool, input: message.input === undefined ? {} : message.input } +} + +export function phpBridgeHostTools(runtimeSpec: Pick): HostToolRegistry | undefined { + const hostTools = runtimeSpec.hostTools + if (hostTools instanceof HostToolRegistry) return hostTools + if (Array.isArray(hostTools) && hostTools.length > 0) return createHostToolRegistry(hostTools as HostToolDefinition[]) + return undefined +} + +export async function executePhpHostToolCall(message: PhpHostToolCallMessage, registry: HostToolRegistry | undefined): Promise { + const startedAt = new Date().toISOString() + const definition = registry?.get(message.tool) + if (!definition || definition.runtime?.php_bridge !== true) { + return createHostToolTransportError(message.tool, "php-host-tool-call", startedAt, "host-tool-unavailable", "This host tool is not available to sandbox PHP.") as unknown as JsonValue + } + return await executeHostTool(definition, message.input, { tool: definition.name, policyCommand: "php-host-tool-call" }) as unknown as JsonValue +} diff --git a/packages/runtime-playground/src/product-site.ts b/packages/runtime-playground/src/product-site.ts new file mode 100644 index 00000000..332ea643 --- /dev/null +++ b/packages/runtime-playground/src/product-site.ts @@ -0,0 +1,375 @@ +import { mkdir, stat, writeFile } from "node:fs/promises" +import { basename, isAbsolute, join, relative, resolve } from "node:path" +import { DEFAULT_WORDPRESS_VERSION, type HostToolDefinition, type JsonObject, type MountSpec, type RuntimeCreateSpec } from "@automattic/wp-codebox-core" +import type { Browser, BrowserContext } from "playwright" +import { browserStorageStateFromWordPressAuthCookies, wordpressFixtureUserStorageStatePhpCode } from "./browser-auth-storage-state.js" +import { launchChromiumBrowser } from "./browser-capture-session.js" +import { bootstrapPhpCode } from "./php-bootstrap.js" +import { startPlaygroundCliServer } from "./playground-cli-runner.js" +import type { PlaygroundCliServer } from "./preview-server.js" + +export const PRODUCT_SITE_SCHEMA = "wp-codebox/product-site/v1" as const +export const PRODUCT_PAGE_VIEW_SCHEMA = "wp-codebox/product-page-view/v1" as const +/** Canonical client tool id shared with the sandbox `product_page_view` declaration. */ +export const PRODUCT_PAGE_VIEW_TOOL = "client/product_page_view" as const +/** Screenshots are staged under this artifact-relative directory so uploads can find them. */ +export const PRODUCT_SITE_SCREENSHOT_DIRECTORY = "product-site/screenshots" as const + +const MAX_PATH_CHARS = 2048 +const MAX_TEXT_CHARS = 12_000 +const MAX_OUTLINE_ENTRIES = 80 +const MAX_INTERACTIVE_ENTRIES = 80 +const MAX_LABEL_CHARS = 160 +const MAX_SCREENSHOTS = 50 +const MAX_SCREENSHOT_BYTES = 4 * 1024 * 1024 +const NAVIGATION_TIMEOUT_MS = 30_000 +const VIEWPORT = { width: 1280, height: 800 } +const ROLE_PATTERN = /^[a-z0-9_-]{1,64}$/ +const SLUG_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/ + +export interface ProductSitePlugin { + /** Host directory containing the plugin. Relative paths resolve against the caller's base directory. */ + path: string + /** Directory name under wp-content/plugins. Defaults to the source directory name. */ + slug: string + /** Activates the plugin through the blueprint. Defaults to true. */ + activate: boolean +} + +export interface ProductSiteSpec { + schema: typeof PRODUCT_SITE_SCHEMA + /** Playground blueprint applied when the site boots. */ + blueprint: Record + plugins: ProductSitePlugin[] + /** Site-relative path the agent should start from. */ + start_url: string + /** Optional WordPress role for a logged-in view. No other credentials are ever provided. */ + login_role?: string + wp?: string +} + +export interface ProductPageInteractiveElement { + kind: "link" | "button" | "field" + label: string + href?: string + type?: string +} + +export interface ProductPageView { + schema: typeof PRODUCT_PAGE_VIEW_SCHEMA + path: string + status: number | null + title: string + text: string + text_truncated: boolean + outline: Array<{ level: number; text: string }> + interactive: ProductPageInteractiveElement[] + screenshot?: { artifact_path: string; bytes: number; content_type: "image/png" } + screenshot_error?: string + logged_in_role?: string +} + +export interface ProductSiteSession { + readonly spec: ProductSiteSpec + readonly baseUrl: string + viewPage(path: string): Promise + /** Artifact-relative paths of screenshots staged so far. */ + screenshots(): string[] + hostTool(): HostToolDefinition + close(): Promise +} + +export interface ProductSiteStartOptions { + /** Agent-task artifact root. Screenshots are written below it at PRODUCT_SITE_SCREENSHOT_DIRECTORY. */ + artifactsDirectory: string + startServer?: (spec: RuntimeCreateSpec, mounts: MountSpec[]) => Promise + launchBrowser?: () => Promise +} + +/** + * Validates a caller-supplied `product_site` request field. Returns undefined + * when the field is absent or empty so runs without it behave exactly as before. + */ +export function normalizeProductSiteSpec(value: unknown, options: { baseDirectory?: string } = {}): ProductSiteSpec | undefined { + if (value === undefined || value === null) return undefined + if (!isRecord(value)) throw new Error("product_site must be an object.") + if (Object.keys(value).length === 0) return undefined + const allowed = new Set(["schema", "blueprint", "plugins", "start_url", "login_role", "wp"]) + const unknown = Object.keys(value).filter((key) => !allowed.has(key)) + if (unknown.length > 0) throw new Error(`product_site has unsupported fields: ${unknown.join(", ")}.`) + if (value.schema !== undefined && value.schema !== PRODUCT_SITE_SCHEMA) throw new Error(`product_site.schema must be ${PRODUCT_SITE_SCHEMA}.`) + if (value.blueprint !== undefined && !isRecord(value.blueprint)) throw new Error("product_site.blueprint must be a Playground blueprint object.") + if (value.plugins !== undefined && !Array.isArray(value.plugins)) throw new Error("product_site.plugins must be an array.") + const baseDirectory = resolve(options.baseDirectory ?? process.cwd()) + const plugins = ((value.plugins as unknown[] | undefined) ?? []).map((entry, index) => normalizeProductSitePlugin(entry, index, baseDirectory)) + const slugs = new Set() + for (const plugin of plugins) { + if (slugs.has(plugin.slug)) throw new Error(`product_site.plugins declares ${plugin.slug} more than once.`) + slugs.add(plugin.slug) + } + const startUrl = value.start_url === undefined ? "/" : normalizeProductSitePath(value.start_url, "product_site.start_url") + let loginRole: string | undefined + if (value.login_role !== undefined && value.login_role !== "") { + if (typeof value.login_role !== "string" || !ROLE_PATTERN.test(value.login_role)) throw new Error("product_site.login_role must be a WordPress role slug.") + loginRole = value.login_role + } + if (value.wp !== undefined && (typeof value.wp !== "string" || !/^[A-Za-z0-9._-]{1,32}$/.test(value.wp))) throw new Error("product_site.wp must be a WordPress version.") + return { + schema: PRODUCT_SITE_SCHEMA, + blueprint: (value.blueprint as Record | undefined) ?? {}, + plugins, + start_url: startUrl, + ...(loginRole ? { login_role: loginRole } : {}), + ...(typeof value.wp === "string" ? { wp: value.wp } : {}), + } +} + +function normalizeProductSitePlugin(entry: unknown, index: number, baseDirectory: string): ProductSitePlugin { + const record = typeof entry === "string" ? { path: entry } : entry + if (!isRecord(record) || typeof record.path !== "string" || !record.path.trim()) throw new Error(`product_site.plugins[${index}] must be a path string or an object with a path.`) + const path = resolve(baseDirectory, record.path.trim()) + if (!isAbsolute(record.path.trim())) { + const contained = relative(baseDirectory, path) + if (contained.startsWith("..") || isAbsolute(contained)) throw new Error(`product_site.plugins[${index}].path must stay inside the caller workspace.`) + } + const slug = record.slug === undefined ? basename(path).toLowerCase() : record.slug + if (typeof slug !== "string" || !SLUG_PATTERN.test(slug)) throw new Error(`product_site.plugins[${index}].slug must be a plugin directory slug.`) + if (record.activate !== undefined && typeof record.activate !== "boolean") throw new Error(`product_site.plugins[${index}].activate must be a boolean.`) + return { path, slug, activate: record.activate !== false } +} + +/** Accepts site-relative GET paths only: no scheme, host, credentials, or traversal outside the site. */ +export function normalizeProductSitePath(value: unknown, field = "path"): string { + if (typeof value !== "string") throw new Error(`${field} must be a string.`) + const trimmed = value.trim() + if (!trimmed) return "/" + if (trimmed.length > MAX_PATH_CHARS) throw new Error(`${field} is too long.`) + if (/[\u0000-\u001f\u007f\\]/.test(trimmed)) throw new Error(`${field} contains unsupported characters.`) + if (/^[a-z][a-z0-9+.-]*:/i.test(trimmed) || trimmed.startsWith("//")) throw new Error(`${field} must be a site-relative path, not a URL.`) + const parsed = new URL(trimmed.startsWith("/") ? trimmed : `/${trimmed}`, "http://product-site.invalid") + if (parsed.origin !== "http://product-site.invalid") throw new Error(`${field} must stay on the product site.`) + return `${parsed.pathname}${parsed.search}${parsed.hash}` +} + +export function productSiteBlueprint(spec: ProductSiteSpec): Record { + const steps = Array.isArray(spec.blueprint.steps) ? [...spec.blueprint.steps as unknown[]] : [] + for (const plugin of spec.plugins) { + if (plugin.activate) steps.push({ step: "activatePlugin", pluginPath: `/wordpress/wp-content/plugins/${plugin.slug}` }) + } + return { ...spec.blueprint, steps } +} + +export function productSiteRuntimeSpec(spec: ProductSiteSpec, artifactsDirectory: string): RuntimeCreateSpec { + return { + backend: "wordpress-playground", + environment: { kind: "wordpress", version: spec.wp ?? DEFAULT_WORDPRESS_VERSION, blueprint: productSiteBlueprint(spec) }, + policy: { network: "deny", filesystem: "readonly-mounts", commands: [], secrets: "none", approvals: "never" }, + artifactsDirectory: join(artifactsDirectory, "product-site", "runtime"), + metadata: { productSite: { schema: PRODUCT_SITE_SCHEMA, plugins: spec.plugins.map(({ slug, activate }) => ({ slug, activate })) } }, + } +} + +/** Boots the product site and returns a session the agent can read but never mutate. */ +export async function startProductSite(spec: ProductSiteSpec, options: ProductSiteStartOptions): Promise { + const runtimeSpec = productSiteRuntimeSpec(spec, options.artifactsDirectory) + const mounts: MountSpec[] = spec.plugins.map((plugin) => ({ type: "directory", source: plugin.path, target: `/wordpress/wp-content/plugins/${plugin.slug}`, mode: "readonly" })) + const server = await (options.startServer ?? startPlaygroundCliServer)(runtimeSpec, mounts) + return new PlaygroundProductSiteSession(spec, runtimeSpec, server, options) +} + +class PlaygroundProductSiteSession implements ProductSiteSession { + readonly baseUrl: string + private browser?: Promise + private context?: Promise + private readonly staged: string[] = [] + private closed = false + private queue: Promise = Promise.resolve() + + constructor(readonly spec: ProductSiteSpec, private readonly runtimeSpec: RuntimeCreateSpec, private readonly server: PlaygroundCliServer, private readonly options: ProductSiteStartOptions) { + this.baseUrl = server.serverUrl.replace(/\/+$/, "") + } + + viewPage(path: string): Promise { + // One page at a time keeps screenshot numbering and the shared context deterministic. + const run = this.queue.then(() => this.view(path)) + this.queue = run.catch(() => undefined) + return run + } + + screenshots(): string[] { + return [...this.staged] + } + + hostTool(): HostToolDefinition { + return { + name: PRODUCT_PAGE_VIEW_TOOL, + description: "Load a page of the running product site (GET only) and return its title, visible text, outline, interactive elements, and a screenshot artifact path.", + parameters: { type: "object", required: ["path"], properties: { path: { type: "string" } }, additionalProperties: false }, + outputSchema: { type: "object", required: ["schema", "path", "title", "text"] }, + policy: { capability: "product-site.read", risk: "read", permissions: ["product-site:get"] }, + // Only php_bridge tools may be invoked from sandbox PHP through post_message_to_js. + runtime: { php_bridge: true, side_effect_boundary: "wp-codebox-product-site" }, + handler: async (input) => await this.viewPage(isRecord(input) ? input.path as string : "") as unknown as JsonObject, + } + } + + async close(): Promise { + if (this.closed) return + this.closed = true + await this.queue.catch(() => undefined) + const browser = await this.browser?.catch(() => undefined) + await browser?.close().catch(() => undefined) + await this.server[Symbol.asyncDispose]() + } + + private async view(rawPath: string): Promise { + if (this.closed) throw new Error("The product site has been torn down.") + const path = normalizeProductSitePath(rawPath) + const context = await this.browserContext() + const page = await context.newPage() + try { + const response = await page.goto(`${this.baseUrl}${path}`, { waitUntil: "load", timeout: NAVIGATION_TIMEOUT_MS }) + // tsx/esbuild keepNames wraps nested functions in __name(); define it in the page. + await page.evaluate("globalThis.__name ??= (value) => value") + const snapshot = await page.evaluate(extractPageSnapshot, { maxText: MAX_TEXT_CHARS, maxOutline: MAX_OUTLINE_ENTRIES, maxInteractive: MAX_INTERACTIVE_ENTRIES, maxLabel: MAX_LABEL_CHARS }) as PageSnapshot + const view: ProductPageView = { + schema: PRODUCT_PAGE_VIEW_SCHEMA, + path: sitePath(page.url(), this.baseUrl) ?? path, + status: response?.status() ?? null, + title: snapshot.title, + text: snapshot.text, + text_truncated: snapshot.textTruncated, + outline: snapshot.outline, + interactive: snapshot.interactive.map((element) => { + if (element.kind !== "link" || !element.href) return element + const href = sitePath(element.href, this.baseUrl) + return href ? { ...element, href } : { kind: element.kind, label: element.label, href: "external" } + }), + ...(this.spec.login_role ? { logged_in_role: this.spec.login_role } : {}), + } + try { + Object.assign(view, { screenshot: await this.stageScreenshot(await page.screenshot({ type: "png", fullPage: false })) }) + } catch (error) { + view.screenshot_error = error instanceof Error ? error.message : String(error) + } + return view + } finally { + await page.close().catch(() => undefined) + } + } + + private async stageScreenshot(bytes: Buffer): Promise> { + if (this.staged.length >= MAX_SCREENSHOTS) throw new Error(`Screenshot limit of ${MAX_SCREENSHOTS} reached for this run.`) + if (bytes.length > MAX_SCREENSHOT_BYTES) throw new Error("Screenshot exceeds the artifact size limit.") + const artifactPath = `${PRODUCT_SITE_SCREENSHOT_DIRECTORY}/page-${String(this.staged.length + 1).padStart(3, "0")}.png` + const absolutePath = join(this.options.artifactsDirectory, artifactPath) + await mkdir(join(this.options.artifactsDirectory, PRODUCT_SITE_SCREENSHOT_DIRECTORY), { recursive: true }) + await writeFile(absolutePath, bytes) + this.staged.push(artifactPath) + return { artifact_path: artifactPath, bytes: (await stat(absolutePath)).size, content_type: "image/png" } + } + + private browserContext(): Promise { + this.context ??= (async () => { + this.browser ??= (this.options.launchBrowser ?? launchChromiumBrowser)() + const browser = await this.browser + const context = await browser.newContext({ viewport: VIEWPORT, javaScriptEnabled: true, acceptDownloads: false }) + const origin = new URL(this.baseUrl).origin + // Read-only boundary: GET/HEAD to the product site only. Form posts, + // REST writes, and requests to any other origin never leave the browser. + await context.route("**/*", async (route) => { + const request = route.request() + const url = new URL(request.url()) + const local = url.origin === origin || url.protocol === "data:" || url.protocol === "blob:" + if (!local || !["GET", "HEAD"].includes(request.method())) return route.abort("blockedbyclient") + return route.continue() + }) + if (this.spec.login_role) await context.addCookies(await this.loginCookies(this.spec.login_role)) + return context + })() + return this.context + } + + private async loginCookies(role: string) { + const code = wordpressFixtureUserStorageStatePhpCode({ browserUrls: [this.baseUrl], user: { username: `product_site_${role}`, role } }) + const response = await this.server.playground.run({ code: bootstrapPhpCode(this.runtimeSpec, code, []) }) + let envelope: unknown + try { + envelope = JSON.parse(response.text) + } catch { + throw new Error(`product_site.login_role ${role} could not be prepared.`) + } + const cookies = isRecord(envelope) && isRecord(envelope.storageState) && Array.isArray(envelope.storageState.cookies) ? envelope.storageState.cookies : [] + return browserStorageStateFromWordPressAuthCookies(cookies as Array>).cookies.map((cookie) => ({ ...cookie, sameSite: cookie.sameSite ?? "Lax" as const })) + } +} + +interface PageSnapshot { + title: string + text: string + textTruncated: boolean + outline: Array<{ level: number; text: string }> + interactive: ProductPageInteractiveElement[] +} + +/** Runs in the page. Must stay self-contained so Playwright can serialize it. */ +function extractPageSnapshot(limits: { maxText: number; maxOutline: number; maxInteractive: number; maxLabel: number }): PageSnapshot { + const clean = (value: string | null | undefined, max = limits.maxLabel) => (value ?? "").replace(/\s+/g, " ").trim().slice(0, max) + const visible = (element: Element) => { + const html = element as HTMLElement + if (html.hidden || html.closest("[aria-hidden='true']")) return false + const style = window.getComputedStyle(html) + return style.display !== "none" && style.visibility !== "hidden" && html.getClientRects().length > 0 + } + const rawText = (document.body?.innerText ?? "").replace(/[ \t]+\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim() + const outline = Array.from(document.querySelectorAll("h1, h2, h3, h4, h5, h6")) + .filter(visible) + .map((heading) => ({ level: Number(heading.tagName.slice(1)), text: clean(heading.textContent) })) + .filter((entry) => entry.text) + .slice(0, limits.maxOutline) + const labelFor = (element: Element) => { + const html = element as HTMLInputElement + const labelled = html.labels && html.labels.length > 0 ? Array.from(html.labels).map((label) => label.textContent).join(" ") : "" + const describedBy = html.getAttribute("aria-labelledby") + const ariaText = describedBy ? describedBy.split(/\s+/).map((id) => document.getElementById(id)?.textContent ?? "").join(" ") : "" + return clean(html.getAttribute("aria-label") || ariaText || labelled || html.getAttribute("placeholder") || html.getAttribute("title") || html.getAttribute("name") || (element.textContent ?? "") || html.value) + } + const interactive: ProductPageInteractiveElement[] = [] + for (const element of Array.from(document.querySelectorAll("a[href], button, [role='button'], input:not([type='hidden']), select, textarea"))) { + if (interactive.length >= limits.maxInteractive) break + if (!visible(element)) continue + const tag = element.tagName.toLowerCase() + const type = (element.getAttribute("type") ?? "").toLowerCase() + if (tag === "a") { + const label = labelFor(element) + if (label) interactive.push({ kind: "link", label, href: (element as HTMLAnchorElement).href }) + } else if (tag === "button" || element.getAttribute("role") === "button" || ["submit", "button", "reset", "image"].includes(type)) { + const label = labelFor(element) + if (label) interactive.push({ kind: "button", label }) + } else { + interactive.push({ kind: "field", label: labelFor(element) || "(unlabelled)", type: tag === "input" ? type || "text" : tag }) + } + } + return { + title: clean(document.title, 300), + text: rawText.slice(0, limits.maxText), + textTruncated: rawText.length > limits.maxText, + outline, + interactive, + } +} + +function sitePath(url: string, baseUrl: string): string | undefined { + try { + const parsed = new URL(url) + const base = new URL(baseUrl) + if (parsed.origin !== base.origin) return undefined + return `${parsed.pathname}${parsed.search}${parsed.hash}` + } catch { + return undefined + } +} + +function isRecord(value: unknown): value is Record { + return Boolean(value) && typeof value === "object" && !Array.isArray(value) +} diff --git a/packages/runtime-playground/src/wordpress-command-runners.ts b/packages/runtime-playground/src/wordpress-command-runners.ts index 07285f76..83ec8e72 100644 --- a/packages/runtime-playground/src/wordpress-command-runners.ts +++ b/packages/runtime-playground/src/wordpress-command-runners.ts @@ -3,6 +3,7 @@ import { mkdir, writeFile } from "node:fs/promises" import { dirname, join, posix } from "node:path" import type { BrowserArtifact } from "./browser-artifacts.js" import { promoteBrowserMetricsToBenchResults } from "./browser-metrics.js" +import { executePhpHostToolCall, parsePhpHostToolCallMessage, phpBridgeHostTools } from "./php-host-tool-bridge.js" import { writePluginCheckArtifacts, writeThemeCheckArtifacts, type PluginCheckArtifact, type ThemeCheckArtifact } from "./check-artifacts.js" import { abilityInputFromArgs, @@ -96,7 +97,7 @@ export async function runPhpCommand({ const commandCode = diagnosticsCapture && marker ? runPhpCommandDiagnosticsPhp(code, marker, diagnosticsCapture.maxItems ?? 50, diagnosticsCapture.maxBytes ?? 64 * 1024) : code const bridge = argValue(spec.args ?? [], "wp-cli-bridge") === "1" ? await createRuntimeWpCliBridge(server) : undefined let response: PlaygroundRunResponse - const removeProviderProxy = installPhpMessageBridges(server, runtimeSpec.policy.network) + const removeProviderProxy = installPhpMessageBridges(server, runtimeSpec) try { response = await runPlaygroundCommand("wordpress.run-php", server, { code: bootstrapPhpCode(runtimeSpec, commandCode, bootstrapArgs, bridge, undefined, server.hostHttpTransport) }) assertPlaygroundResponseOk("wordpress.run-php", response) @@ -294,13 +295,19 @@ async function writeCommandDiagnosticsArtifact(artifactRoot: string, diagnostics } } -function installPhpMessageBridges(server: PlaygroundCliServer, networkPolicy: RuntimeCreateSpec["policy"]["network"]): (() => Promise) | undefined { +function installPhpMessageBridges(server: PlaygroundCliServer, runtimeSpec: Pick): (() => Promise) | undefined { if (!server.playground.onMessage) { return undefined } + const networkPolicy = runtimeSpec.policy.network + const hostTools = phpBridgeHostTools(runtimeSpec) const activeHostRequests = new Set() const remove = server.playground.onMessage(async (data) => { + const hostToolCall = hostTools ? parsePhpHostToolCallMessage(data) : undefined + if (hostToolCall) { + return JSON.stringify(await executePhpHostToolCall(hostToolCall, hostTools)) + } const hostHttpMessage = parseHostHttpTransportMessage(data) if (hostHttpMessage) { const controller = new AbortController() @@ -671,7 +678,7 @@ export async function runAbilityCommand({ throw new Error("wordpress.ability accepts either user/session or principal, not both") } const expectedResultSchema = expectedAbilityResultSchemaFromArgs(spec.args ?? []) - const removeMessageBridges = installPhpMessageBridges(server, runtimeSpec.policy.network) + const removeMessageBridges = installPhpMessageBridges(server, runtimeSpec) let response: PlaygroundRunResponse try { response = await runPlaygroundCommand("wordpress.ability", server, { code: bootstrapAbilityPhpCode(runtimeSpec, abilityPhpCode({ name, input, userSession, principal }), server.hostHttpTransport) }) diff --git a/packages/wordpress-plugin/src/class-wp-codebox-product-site-executor.php b/packages/wordpress-plugin/src/class-wp-codebox-product-site-executor.php new file mode 100644 index 00000000..08e4f264 --- /dev/null +++ b/packages/wordpress-plugin/src/class-wp-codebox-product-site-executor.php @@ -0,0 +1,197 @@ + $input Runtime package workflow input. + * @return array Empty when no product site was declared. + */ + public static function context_from_input( array $input ): array { + $site = is_array( $input['product_site'] ?? null ) ? $input['product_site'] : array(); + if ( empty( $site['enabled'] ) ) { + return array(); + } + $start_url = is_string( $site['start_url'] ?? null ) && '' !== $site['start_url'] ? $site['start_url'] : '/'; + $context = array( + 'product_site' => true, + 'start_url' => $start_url, + ); + if ( is_string( $site['login_role'] ?? null ) && '' !== $site['login_role'] ) { + $context['login_role'] = $site['login_role']; + } + + return $context; + } + + /** + * Declarations for the product page viewer; empty unless a product site is set. + * + * @param array $context Trusted context from context_from_input(). + * @return array> + */ + public static function tool_declarations( array $context ): array { + if ( empty( $context['product_site'] ) ) { + return array(); + } + $start_url = (string) ( $context['start_url'] ?? '/' ); + $description = 'Load a page of the running product site in a real browser (read-only, GET only) and return its title, visible text, heading outline, interactive elements (links, buttons, form labels), and the artifact path of a staged screenshot. Start at ' . $start_url . '.'; + if ( ! empty( $context['login_role'] ) ) { + $description .= ' Pages are viewed logged in as a ' . (string) $context['login_role'] . ' user.'; + } + + return array( + self::TOOL_NAME => array( + 'name' => self::TOOL_NAME, + 'source' => self::SOURCE_SLUG, + 'description' => $description, + 'parameters' => array( + 'type' => 'object', + 'required' => array( 'path' ), + 'properties' => array( + 'path' => array( + 'type' => 'string', + 'description' => 'Site-relative path such as / or /wp-admin/options-general.php?page=example. Full URLs and other sites are rejected.', + ), + ), + ), + 'executor' => 'client', + 'scope' => 'run', + 'runtime' => self::runtime_metadata(), + ), + ); + } + + /** + * Executor bound to the trusted context for one run. + * + * @param array $context Trusted context from context_from_input(). + */ + public static function executor_for_context( array $context ): \AgentsAPI\AI\Tools\WP_Agent_Tool_Executor { + return new class( $context ) implements \AgentsAPI\AI\Tools\WP_Agent_Tool_Executor { + /** @param array $context */ + public function __construct( private array $context ) {} + + /** @param array $tool_call @param array $tool_definition @param array $context @return array */ + public function executeWP_Agent_Tool_Call( array $tool_call, array $tool_definition, array $context = array() ): array { + unset( $context ); + return WP_Codebox_Product_Site_Executor::execute( $tool_call, $tool_definition, $this->context ); + } + }; + } + + /** + * Execute one product_page_view call. + * + * @param array $tool_call Tool call. + * @param array $tool_definition Tool declaration. + * @param array $context Trusted context. + * @param callable|null $transport Test seam; defaults to post_message_to_js. + * @return array + */ + public static function execute( array $tool_call, array $tool_definition, array $context, ?callable $transport = null ): array { + $tool_name = (string) ( $tool_call['tool_name'] ?? $tool_definition['name'] ?? self::TOOL_NAME ); + $base = str_contains( $tool_name, '/' ) ? substr( $tool_name, strrpos( $tool_name, '/' ) + 1 ) : $tool_name; + if ( self::TOOL_NAME !== $base ) { + return self::error( $tool_name, 'unsupported_tool', 'Product site executor does not provide this tool.' ); + } + if ( empty( $context['product_site'] ) ) { + return self::error( $tool_name, 'product_site_unavailable', 'No product site was declared for this run.' ); + } + $parameters = is_array( $tool_call['parameters'] ?? null ) ? $tool_call['parameters'] : array(); + $path = self::path( $parameters['path'] ?? '' ); + if ( null === $path ) { + return self::error( $tool_name, 'invalid_path', 'path must be a site-relative path such as /about/.' ); + } + + $transport = $transport ?? ( function_exists( 'post_message_to_js' ) ? 'post_message_to_js' : null ); + if ( null === $transport ) { + return self::error( $tool_name, 'product_site_unavailable', 'The product site bridge is unavailable in this runtime.' ); + } + $message = array( + 'schema' => self::MESSAGE_SCHEMA, + 'tool' => self::HOST_TOOL, + 'input' => array( 'path' => $path ), + ); + $encoded = function_exists( 'wp_json_encode' ) ? wp_json_encode( $message, JSON_UNESCAPED_SLASHES ) : json_encode( $message, JSON_UNESCAPED_SLASHES ); + $response = json_decode( (string) call_user_func( $transport, (string) $encoded ), true ); + if ( ! is_array( $response ) || self::RESULT_SCHEMA !== ( $response['schema'] ?? null ) ) { + return self::error( $tool_name, 'product_site_bridge_error', 'The product site returned a malformed response.' ); + } + if ( 'ok' !== ( $response['status'] ?? null ) || ! is_array( $response['output'] ?? null ) ) { + $error = is_array( $response['error'] ?? null ) ? $response['error'] : array(); + return self::error( $tool_name, (string) ( $error['code'] ?? 'product_site_error' ), (string) ( $error['message'] ?? 'The product page could not be loaded.' ) ); + } + + return array( + 'success' => true, + 'tool_name' => $tool_name, + 'result' => $response['output'], + 'runtime' => self::runtime_metadata(), + ); + } + + /** @return string|null Normalized site-relative path, or null when the value is not one. */ + private static function path( mixed $value ): ?string { + if ( ! is_string( $value ) ) { + return null; + } + $path = trim( $value ); + if ( '' === $path ) { + return '/'; + } + if ( strlen( $path ) > self::MAX_PATH_CHARS || 1 === preg_match( '/[\x00-\x1f\x7f\\\\]/', $path ) || 1 === preg_match( '/^[a-z][a-z0-9+.-]*:/i', $path ) || str_starts_with( $path, '//' ) ) { + return null; + } + + return str_starts_with( $path, '/' ) ? $path : '/' . $path; + } + + /** @return array */ + private static function runtime_metadata(): array { + return array( + 'executor_target' => self::TARGET_ID, + 'capability' => 'product-site.read', + 'side_effects' => array(), + 'side_effect_boundary' => 'wp-codebox-product-site', + ); + } + + /** @return array */ + private static function error( string $tool_name, string $type, string $message ): array { + return array( + 'success' => false, + 'tool_name' => $tool_name, + 'error' => $message, + 'error_type' => $type, + 'runtime' => self::runtime_metadata(), + ); + } +} diff --git a/packages/wordpress-plugin/src/class-wp-codebox-runtime-package-executor.php b/packages/wordpress-plugin/src/class-wp-codebox-runtime-package-executor.php index f1112a71..0e83a072 100644 --- a/packages/wordpress-plugin/src/class-wp-codebox-runtime-package-executor.php +++ b/packages/wordpress-plugin/src/class-wp-codebox-runtime-package-executor.php @@ -7,6 +7,8 @@ defined( 'ABSPATH' ) || exit; +require_once __DIR__ . '/class-wp-codebox-product-site-executor.php'; + /** * Executes runtime packages through the local WordPress ability surface. */ @@ -132,22 +134,31 @@ private function execute_workflow( array $task ): array|WP_Error { $input['max_turns'] = $turn_limit['max_turns']; } $workspace_context = $this->sandbox_workspace_context( $input ); + $product_site_context = WP_Codebox_Product_Site_Executor::context_from_input( $input ); $ability_object = function_exists( 'wp_get_ability' ) ? wp_get_ability( $ability ) : null; if ( ! is_object( $ability_object ) || ! method_exists( $ability_object, 'execute' ) ) { return new WP_Error( 'wp_codebox_runtime_package_workflow_unavailable', 'Runtime package workflow ability is unavailable.', array( 'status' => 500, 'ability' => $ability ) ); } - $runtime_tool_declarations = static function ( array $declarations, $agent, array $runtime_context ) use ( $input, $workspace_context ): array { + $runtime_tool_declarations = static function ( array $declarations, $agent, array $runtime_context ) use ( $input, $workspace_context, $product_site_context ): array { if ( ! $agent instanceof \WP_Agent || ! hash_equals( (string) $input['agent'], (string) $runtime_context['agent_slug'] ) || ! hash_equals( (string) $input['run_id'], (string) $runtime_context['run_id'] ) ) { return $declarations; } - return array_merge( $declarations, WP_Codebox_Sandbox_Workspace_Executor::tool_declarations_for_enabled_tools( $agent->get_default_config(), $workspace_context ) ); + // product_page_view exists only when the caller declared a product site. + return array_merge( + $declarations, + WP_Codebox_Sandbox_Workspace_Executor::tool_declarations_for_enabled_tools( $agent->get_default_config(), $workspace_context ), + WP_Codebox_Product_Site_Executor::tool_declarations( $product_site_context ) + ); }; - $tool_executors = static function ( array $executors, array $runtime_context ) use ( $input, $workspace_context ): array { + $tool_executors = static function ( array $executors, array $runtime_context ) use ( $input, $workspace_context, $product_site_context ): array { if ( ! hash_equals( (string) $input['agent'], (string) ( $runtime_context['agent_slug'] ?? '' ) ) || ! hash_equals( (string) $input['run_id'], (string) ( $runtime_context['run_id'] ?? '' ) ) ) { return $executors; } $executors[ WP_Codebox_Sandbox_Workspace_Executor::TARGET_ID ] = WP_Codebox_Sandbox_Workspace_Executor::executor_for_context( $workspace_context ); + if ( ! empty( $product_site_context ) ) { + $executors[ WP_Codebox_Product_Site_Executor::TARGET_ID ] = WP_Codebox_Product_Site_Executor::executor_for_context( $product_site_context ); + } return $executors; }; $filters_available = function_exists( 'add_filter' ) && function_exists( 'remove_filter' ); diff --git a/scripts/php-product-site-executor-smoke.php b/scripts/php-product-site-executor-smoke.php new file mode 100644 index 00000000..82ce3dad --- /dev/null +++ b/scripts/php-product-site-executor-smoke.php @@ -0,0 +1,81 @@ + $tool_call @param array $tool_definition @param array $context @return array */ + public function executeWP_Agent_Tool_Call( array $tool_call, array $tool_definition, array $context = array() ): array; + } +} + +namespace { + error_reporting( E_ALL ); + define( 'ABSPATH', __DIR__ . '/' ); + + require_once __DIR__ . '/../packages/wordpress-plugin/src/class-wp-codebox-product-site-executor.php'; + + function product_site_assert( bool $condition, string $message ): void { + if ( ! $condition ) { + fwrite( STDERR, "FAIL: {$message}\n" ); + exit( 1 ); + } + } + + // Absent product_site: no declaration, no executor context. + product_site_assert( array() === WP_Codebox_Product_Site_Executor::context_from_input( array() ), 'absent product_site yields no context' ); + product_site_assert( array() === WP_Codebox_Product_Site_Executor::tool_declarations( array() ), 'absent product_site declares no tool' ); + + $context = WP_Codebox_Product_Site_Executor::context_from_input( array( 'product_site' => array( 'enabled' => true, 'start_url' => '/shop/', 'login_role' => 'subscriber' ) ) ); + $declarations = WP_Codebox_Product_Site_Executor::tool_declarations( $context ); + product_site_assert( isset( $declarations['product_page_view'] ), 'product_page_view is declared' ); + product_site_assert( 'wp-codebox/product-site' === $declarations['product_page_view']['runtime']['executor_target'], 'declaration targets the product site executor' ); + product_site_assert( str_contains( $declarations['product_page_view']['description'], '/shop/' ), 'description names the start URL' ); + product_site_assert( array( 'path' ) === $declarations['product_page_view']['parameters']['required'], 'path is required' ); + + $messages = array(); + $transport = static function ( string $message ) use ( &$messages ): string { + $messages[] = json_decode( $message, true ); + return (string) json_encode( + array( + 'schema' => 'wp-codebox/host-tool-result/v1', + 'status' => 'ok', + 'output' => array( 'schema' => 'wp-codebox/product-page-view/v1', 'path' => '/shop/', 'title' => 'Shop', 'text' => 'Real page text' ), + ) + ); + }; + $call = array( 'tool_name' => 'client/product_page_view', 'parameters' => array( 'path' => 'shop/' ) ); + $result = WP_Codebox_Product_Site_Executor::execute( $call, $declarations['product_page_view'], $context, $transport ); + product_site_assert( true === $result['success'], 'successful call' ); + product_site_assert( 'Real page text' === $result['result']['text'], 'host output reaches the agent' ); + product_site_assert( array( 'schema' => 'wp-codebox/php-host-tool-call/v1', 'tool' => 'client/product_page_view', 'input' => array( 'path' => '/shop/' ) ) === $messages[0], 'bridge message is site-relative' ); + + foreach ( array( 'https://example.com/', '//example.com/', "javascript:alert(1)", "/a\nb", 42 ) as $bad ) { + $rejected = WP_Codebox_Product_Site_Executor::execute( array( 'tool_name' => 'product_page_view', 'parameters' => array( 'path' => $bad ) ), $declarations['product_page_view'], $context, $transport ); + product_site_assert( false === $rejected['success'] && 'invalid_path' === $rejected['error_type'], 'rejects non site-relative path' ); + } + product_site_assert( 1 === count( $messages ), 'rejected paths never reach the bridge' ); + + $unavailable = WP_Codebox_Product_Site_Executor::execute( $call, $declarations['product_page_view'], array(), $transport ); + product_site_assert( 'product_site_unavailable' === $unavailable['error_type'], 'no product site, no call' ); + + $host_error = WP_Codebox_Product_Site_Executor::execute( + $call, + $declarations['product_page_view'], + $context, + static fn(): string => (string) json_encode( array( 'schema' => 'wp-codebox/host-tool-result/v1', 'status' => 'error', 'error' => array( 'code' => 'navigation-failed', 'message' => 'Timed out' ) ) ) + ); + product_site_assert( false === $host_error['success'] && 'navigation-failed' === $host_error['error_type'], 'host errors are surfaced' ); + + $malformed = WP_Codebox_Product_Site_Executor::execute( $call, $declarations['product_page_view'], $context, static fn(): string => 'nope' ); + product_site_assert( 'product_site_bridge_error' === $malformed['error_type'], 'malformed responses are rejected' ); + + echo "PHP product site executor smoke passed\n"; +} diff --git a/tests/product-site-page-view.browser.test.ts b/tests/product-site-page-view.browser.test.ts new file mode 100644 index 00000000..c863b72f --- /dev/null +++ b/tests/product-site-page-view.browser.test.ts @@ -0,0 +1,104 @@ +import assert from "node:assert/strict" +import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { after, before, test } from "node:test" + +import { createHostToolRegistry } from "../packages/runtime-core/src/index.js" +import { PHP_HOST_TOOL_CALL_SCHEMA, executePhpHostToolCall, parsePhpHostToolCallMessage } from "../packages/runtime-playground/src/php-host-tool-bridge.js" +import { PRODUCT_PAGE_VIEW_SCHEMA, PRODUCT_PAGE_VIEW_TOOL, normalizeProductSitePath, normalizeProductSiteSpec, startProductSite, type ProductSiteSession } from "../packages/runtime-playground/src/product-site.js" + +const PLUGIN_PHP = `

Fixture Storefront

Hello from the product plugin.

'; + echo 'Sample page Outside'; + echo '
'; + echo '

Posted: ' . esc_html( get_option( 'product_site_fixture_posted', 'no' ) ) . '

'; + if ( isset( $_GET['autosubmit'] ) ) { + echo ''; + } +} ); +add_action( 'init', static function () { + if ( 'POST' === ( $_SERVER['REQUEST_METHOD'] ?? '' ) && isset( $_POST['email'] ) ) { + update_option( 'product_site_fixture_posted', 'yes' ); + } +} ); +` + +let root: string +let workspace: string +let artifacts: string +let session: ProductSiteSession + +before(async () => { + root = await mkdtemp(join(tmpdir(), "wp-codebox-product-site-")) + workspace = join(root, "workspace") + artifacts = join(root, "artifacts") + await mkdir(join(workspace, "plugins", "product-fixture"), { recursive: true }) + await writeFile(join(workspace, "plugins", "product-fixture", "product-fixture.php"), PLUGIN_PHP) + const spec = normalizeProductSiteSpec({ blueprint: {}, plugins: ["plugins/product-fixture"], start_url: "/" }, { baseDirectory: workspace }) + assert.ok(spec) + session = await startProductSite(spec, { artifactsDirectory: artifacts }) +}) + +after(async () => { + await session?.close() + await rm(root, { recursive: true, force: true }) +}) + +test("product_site is optional and validated", () => { + assert.equal(normalizeProductSiteSpec(undefined), undefined) + assert.equal(normalizeProductSiteSpec({}), undefined) + assert.throws(() => normalizeProductSiteSpec({ plugins: ["../escape"] }, { baseDirectory: "/tmp/workspace" }), /inside the caller workspace/) + assert.throws(() => normalizeProductSiteSpec({ password: "x" }), /unsupported fields/) + assert.throws(() => normalizeProductSiteSpec({ login_role: "Admin Role" }), /role slug/) + assert.equal(normalizeProductSitePath("about/?x=1"), "/about/?x=1") + assert.throws(() => normalizeProductSitePath("https://example.com/"), /site-relative/) + assert.throws(() => normalizeProductSitePath("//example.com/"), /site-relative/) +}) + +test("product_page_view returns the real page text and stages a screenshot", async () => { + const view = await session.viewPage("/") + assert.equal(view.schema, PRODUCT_PAGE_VIEW_SCHEMA) + assert.equal(view.status, 200) + assert.match(view.text, /Hello from the product plugin\./) + assert.ok(view.outline.some((entry) => entry.level === 1 && entry.text === "Fixture Storefront")) + assert.ok(view.interactive.some((element) => element.kind === "link" && element.label === "Sample page" && element.href === "/sample-page/")) + assert.ok(view.interactive.some((element) => element.kind === "link" && element.label === "Outside" && element.href === "external")) + assert.ok(view.interactive.some((element) => element.kind === "button" && element.label === "Subscribe")) + assert.ok(view.interactive.some((element) => element.kind === "field" && element.label === "Email address" && element.type === "email")) + assert.equal(view.screenshot?.artifact_path, "product-site/screenshots/page-001.png") + const png = await readFile(join(artifacts, view.screenshot!.artifact_path)) + assert.equal(png.subarray(0, 8).toString("hex"), "89504e470d0a1a0a") + assert.equal((await stat(join(artifacts, view.screenshot!.artifact_path))).size, view.screenshot!.bytes) + assert.deepEqual(session.screenshots(), ["product-site/screenshots/page-001.png"]) +}) + +test("sandbox PHP reaches the viewer only through the php_bridge host tool", async () => { + const registry = createHostToolRegistry([session.hostTool()]) + const message = parsePhpHostToolCallMessage(JSON.stringify({ schema: PHP_HOST_TOOL_CALL_SCHEMA, tool: PRODUCT_PAGE_VIEW_TOOL, input: { path: "/" } })) + assert.ok(message) + const result = await executePhpHostToolCall(message, registry) as Record + assert.equal(result.status, "ok") + assert.match(result.output.text, /Hello from the product plugin\./) + assert.equal(result.output.screenshot.artifact_path, "product-site/screenshots/page-002.png") + + const rejected = await executePhpHostToolCall({ schema: PHP_HOST_TOOL_CALL_SCHEMA, tool: PRODUCT_PAGE_VIEW_TOOL, input: { path: "https://example.com/" } }, registry) as Record + assert.notEqual(rejected.status, "ok") + + const unbridged = createHostToolRegistry([{ ...session.hostTool(), runtime: {} }]) + const unavailable = await executePhpHostToolCall(message, unbridged) as Record + assert.equal(unavailable.status, "error") + assert.equal(unavailable.error.code, "host-tool-unavailable") +}) + +test("the viewer is read-only: form posts never reach the site", async () => { + // The page submits its form and fires a fetch POST on load; the browser + // route aborts every non-GET request so site state never changes. + await session.viewPage("/?autosubmit=1") + const view = await session.viewPage("/") + assert.match(view.text, /Posted: no/) +}) diff --git a/tests/product-site-workflow.test.ts b/tests/product-site-workflow.test.ts new file mode 100644 index 00000000..9f4dbdfc --- /dev/null +++ b/tests/product-site-workflow.test.ts @@ -0,0 +1,80 @@ +import assert from "node:assert/strict" +import { execFile } from "node:child_process" +import { mkdir, mkdtemp, readFile, rm, symlink, writeFile } from "node:fs/promises" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { promisify } from "node:util" + +import { parseProductSiteInput } from "../.github/scripts/run-agent-task/product-site-request.mjs" +import { withProductSiteRuntimeTask } from "../packages/cli/src/commands/agent-task-run.js" +import { normalizeProductSiteSpec } from "../packages/runtime-playground/src/product-site.js" + +const execFileAsync = promisify(execFile) + +// The reusable workflow exposes product_site and threads it to the request builder. +const workflow = await readFile(new URL("../.github/workflows/run-agent-task.yml", import.meta.url), "utf8") +assert.match(workflow, /\n product_site:\n description: .+\n type: string\n default: ""\n/) +assert.match(workflow, /PRODUCT_SITE: \$\{\{ inputs\.product_site \}\}/) +assert.match(workflow, /if: inputs\.product_site != '' && inputs\.product_site != '\{\}'\n\s+working-directory: \.wp-codebox-workflow\n\s+run: npx playwright install --with-deps chromium/) + +// Request validation: absent stays absent, declared sites are normalized. +assert.equal(parseProductSiteInput(""), undefined) +assert.equal(parseProductSiteInput("{}"), undefined) +assert.deepEqual(parseProductSiteInput('{"plugins":["./plugins/demo/",{"path":"vendor/x","slug":"x","activate":false}],"start_url":"shop/","login_role":"subscriber"}'), { + blueprint: {}, + plugins: ["plugins/demo", { path: "vendor/x", slug: "x", activate: false }], + start_url: "/shop/", + login_role: "subscriber", +}) +assert.throws(() => parseProductSiteInput('{"plugins":["../outside"]}'), /without traversal/) +assert.throws(() => parseProductSiteInput('{"plugins":["/abs/path"]}'), /without traversal/) +assert.throws(() => parseProductSiteInput('{"start_url":"https://example.com/"}'), /site-relative/) +assert.throws(() => parseProductSiteInput('{"credentials":{"user":"admin"}}'), /unsupported fields/) + +// The CLI tells the runtime package that product_page_view exists, without paths or blueprint. +const spec = normalizeProductSiteSpec({ plugins: ["plugins/demo"], start_url: "/shop/", login_role: "subscriber" }, { baseDirectory: "/tmp/workspace" }) +assert.ok(spec) +const runInput = { runtime_task: { kind: "bundle", input: { schema: "wp-codebox/runtime-package-task/v1", input: { prompt: "x" } } } } +assert.deepEqual(withProductSiteRuntimeTask(runInput as never, spec).runtime_task, { + kind: "bundle", + input: { schema: "wp-codebox/runtime-package-task/v1", input: { prompt: "x", product_site: { enabled: true, start_url: "/shop/", login_role: "subscriber" } } }, +}) +assert.equal(withProductSiteRuntimeTask({} as never, spec).runtime_task, undefined) + +// Upload staging copies real product-site PNG screenshots byte-for-byte and nothing else binary. +const root = await mkdtemp(join(tmpdir(), "wp-codebox-product-site-upload-")) +try { + const codebox = join(root, ".codebox") + const screenshots = join(codebox, "agent-task-artifacts", "product-site", "screenshots") + await mkdir(screenshots, { recursive: true }) + const png = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), Buffer.from([0, 1, 2, 255, 254])]) + await writeFile(join(screenshots, "page-001.png"), png) + await writeFile(join(screenshots, "page-002.png"), Buffer.from([0, 1, 2, 3])) + await writeFile(join(screenshots, "notes.png"), png) + await writeFile(join(root, "outside.png"), png) + await symlink(join(root, "outside.png"), join(screenshots, "page-003.png")) + const requestPath = join(codebox, "agent-task-request.json") + const uploadPath = join(codebox, "agent-task-upload") + const stage = async (request: Record) => { + await writeFile(requestPath, `${JSON.stringify(request)}\n`) + await execFileAsync(process.execPath, [new URL("../.github/scripts/run-agent-task/prepare-agent-task-upload.mjs", import.meta.url).pathname], { + cwd: root, + env: { ...process.env, AGENT_TASK_WORKSPACE: root, AGENT_TASK_REQUEST_PATH: requestPath, AGENT_TASK_UPLOAD_PATH: uploadPath }, + }) + return join(uploadPath, ".codebox", "agent-task-artifacts", "product-site", "screenshots") + } + + const staged = await stage({ schema: "wp-codebox/agent-task-workflow-request/v1", product_site: { blueprint: {}, plugins: [], start_url: "/" } }) + assert.deepEqual(await readFile(join(staged, "page-001.png")), png) + for (const name of ["page-002.png", "notes.png", "page-003.png"]) { + await assert.rejects(readFile(join(staged, name)), undefined, `${name} must not be uploaded`) + } + + // Without product_site, screenshots are not part of the upload contract. + const unstaged = await stage({ schema: "wp-codebox/agent-task-workflow-request/v1" }) + await assert.rejects(readFile(join(unstaged, "page-001.png"))) +} finally { + await rm(root, { recursive: true, force: true }) +} + +console.log("product site workflow ok")