Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat(diagnostics): wire private report uploads
Gusbdc1798f8fa5
diff --git a/src/daemon/src/cli/daemonRunner.test.ts b/src/daemon/src/cli/daemonRunner.test.tsindex 0e06a275b..7b66551f7 100644--- a/src/daemon/src/cli/daemonRunner.test.ts+++ b/src/daemon/src/cli/daemonRunner.test.ts@@ -1,9 +1,124 @@-import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import * as fs from "node:fs";import * as os from "node:os";import * as path from "node:path";import type { PreparedDaemon } from "./daemonRunner";-import { createDaemonProcessLogger, DAEMON_LOG_MAX_BYTES, logDaemonStartup, logDaemonUp } from "./daemonRunner";+import {+ createDaemonProcessLogger,+ DAEMON_LOG_MAX_BYTES,+ logDaemonStartup,+ logDaemonUp,+ runPreparedDaemon,+} from "./daemonRunner";++const runnerDaemonHarness = vi.hoisted(() => {+ const create = vi.fn();+ return { create };+});++const runnerDiagnosticHarness = vi.hoisted(() => {+ const upload = vi.fn(async () => ({ kind: "retryable" as const }));+ const fail = vi.fn(async () => ({ kind: "terminal" as const, status: "failed" as const }));+ const transport = { upload, fail };+ const collect = vi.fn(async () => ({ status: "pending" as const }));+ const recover = vi.fn(async () => {});+ const shutdown = vi.fn(async () => {});+ const coordinator = { collect, recover, shutdown };+ const createTransport = vi.fn(() => transport);+ const createCoordinator = vi.fn(() => coordinator);+ return {+ upload,+ fail,+ transport,+ collect,+ recover,+ shutdown,+ coordinator,+ createTransport,+ createCoordinator,+ };+});++vi.mock("../daemon/createDaemon.js", () => ({+ createDaemon: (...args: unknown[]) => runnerDaemonHarness.create(...args),+}));++vi.mock("../diagnostics/index.js", async (importOriginal) => {+ const actual = await importOriginal<typeof import("../diagnostics/index.js")>();+ return {+ ...actual,+ createDiagnosticHttpTransport: (...args: unknown[]) => runnerDiagnosticHarness.createTransport(...args),+ createDiagnosticReportCoordinator: (...args: unknown[]) => runnerDiagnosticHarness.createCoordinator(...args),+ };+});++const RUNNER_PROCESS_EVENTS = ["uncaughtException", "unhandledRejection", "SIGINT", "SIGTERM"] as const;++function preparedDaemon(dir: string): PreparedDaemon {+ return {+ machineId: "machine-1",+ machineKey: "cmk_PRIVATE_RUNNER_KEY",+ serverUrl: "https://community.example",+ wsUrl: "wss://community.example/ws",+ baseDir: path.join(dir, "agents"),+ daemonDir: dir,+ statusFilePath: path.join(dir, "status.json"),+ agentCliPath: undefined,+ runtimeReport: [],+ healthyRuntimeIds: [],+ hostname: "host",+ platform: "test",+ arch: "test",+ osRelease: "test",+ daemonVersion: "1.2.3",+ ownerToken: "owner-private",+ startedAt: "2026-08-12T00:00:00.000Z",+ };+}++function resetDiagnosticHarness(): void {+ runnerDaemonHarness.create.mockReset();+ runnerDiagnosticHarness.upload.mockReset().mockResolvedValue({ kind: "retryable" });+ runnerDiagnosticHarness.fail.mockReset().mockResolvedValue({ kind: "terminal", status: "failed" });+ runnerDiagnosticHarness.collect.mockReset().mockResolvedValue({ status: "pending" });+ runnerDiagnosticHarness.recover.mockReset().mockResolvedValue(undefined);+ runnerDiagnosticHarness.shutdown.mockReset().mockResolvedValue(undefined);+ runnerDiagnosticHarness.createTransport.mockReset().mockReturnValue(runnerDiagnosticHarness.transport);+ runnerDiagnosticHarness.createCoordinator.mockReset().mockReturnValue(runnerDiagnosticHarness.coordinator);+}++function processListenerSnapshot(): Map<string, Set<(...args: never[]) => unknown>> {+ return new Map(RUNNER_PROCESS_EVENTS.map((event) => [+ event,+ new Set(process.listeners(event) as Array<(...args: never[]) => unknown>),+ ]));+}++function removeNewProcessListeners(before: Map<string, Set<(...args: never[]) => unknown>>): void {+ for (const event of RUNNER_PROCESS_EVENTS) {+ const existing = before.get(event)!;+ for (const listener of process.listeners(event) as Array<(...args: never[]) => unknown>) {+ if (!existing.has(listener)) process.removeListener(event, listener as never);+ }+ }+}++function installDaemonHarness(dir: string, events: string[] = []) {+ const state: { options?: Record<string, unknown> } = {};+ const stop = vi.fn(async () => { events.push("daemon-stop"); });+ const fsmTraceSource = { openSnapshot: vi.fn() };+ runnerDaemonHarness.create.mockImplementation(async (options: Record<string, unknown>) => {+ state.options = options;+ const supplySources = options.onDiagnosticSources as ((sources: unknown) => void) | undefined;+ supplySources?.({ fsmTraceSource, statusFilePath: path.join(dir, "status.json") });+ return {+ proxyUrl: "http://127.0.0.1:1234",+ onOpen: vi.fn(),+ stop,+ };+ });+ return { state, stop, fsmTraceSource };+}describe("daemon runner logger", () => {let dir: string;@@ -107,4 +222,187 @@ describe("daemon runner logger", () => {expect(JSON.stringify(record)).not.toContain("secret");expect(JSON.stringify(record)).not.toContain("control.example");});++ it("wires one diagnostic lifecycle and starts unresolved recovery without blocking ready", async () => {+ resetDiagnosticHarness();+ vi.useFakeTimers();+ const listenersBefore = processListenerSnapshot();+ const events: string[] = [];+ const daemonHarness = installDaemonHarness(dir);+ runnerDiagnosticHarness.recover.mockImplementation(() => {+ events.push("recover");+ return new Promise<void>(() => {});+ });+ const readyError = new Error("stop after ready receipt");+ const prepared = preparedDaemon(dir);++ try {+ await expect(runPreparedDaemon(prepared, {+ foreground: false,+ releaseOwnership: vi.fn(),+ onReady: () => {+ events.push("ready");+ throw readyError;+ },+ })).rejects.toBe(readyError);++ expect(runnerDiagnosticHarness.createTransport).toHaveBeenCalledOnce();+ expect(runnerDiagnosticHarness.createTransport).toHaveBeenCalledWith({+ serverUrl: prepared.serverUrl,+ machineKey: prepared.machineKey,+ });+ expect(runnerDiagnosticHarness.createCoordinator).toHaveBeenCalledOnce();+ expect(runnerDiagnosticHarness.createCoordinator).toHaveBeenCalledWith(expect.objectContaining({+ machineDir: prepared.daemonDir,+ transport: runnerDiagnosticHarness.transport,+ buildBundle: expect.any(Function),+ logger: expect.any(Object),+ }));+ expect(daemonHarness.state.options?.onDiagnosticSources).toEqual(expect.any(Function));+ expect(daemonHarness.state.options?.handleDiagnosticCommand).toEqual(expect.any(Function));+ expect(daemonHarness.state.options?.reportDiagnosticFailure).toEqual(expect.any(Function));+ expect(events).toEqual(["recover", "ready"]);++ const command = {+ type: "diagnostics:collect",+ reportId: "dbr_0123456789abcdef",+ agentId: "bot_1",+ fromMs: 1_700_000_000_000,+ deadlineAt: 1_700_087_000_000,+ };+ await (daemonHarness.state.options?.handleDiagnosticCommand as (value: typeof command) => Promise<void>)(command);+ expect(runnerDiagnosticHarness.collect).toHaveBeenCalledWith(command);+ await (daemonHarness.state.options?.reportDiagnosticFailure as (value: { reportId: string; failureCode: string }) => Promise<void>)({+ reportId: command.reportId,+ failureCode: "diagnostics_unavailable",+ });+ expect(runnerDiagnosticHarness.fail).toHaveBeenCalledWith(+ command.reportId,+ "diagnostics_unavailable",+ );+ } finally {+ removeNewProcessListeners(listenersBefore);+ vi.clearAllTimers();+ vi.useRealTimers();+ }+ });++ it("observes a rejected fire-and-observe recovery through the safe logger", async () => {+ resetDiagnosticHarness();+ vi.useFakeTimers();+ const listenersBefore = processListenerSnapshot();+ installDaemonHarness(dir);+ runnerDiagnosticHarness.recover.mockRejectedValue(+ new Error("recovery failed cmk_PRIVATE_RECOVERY_KEY"),+ );+ const readyError = new Error("stop after ready receipt");++ try {+ await expect(runPreparedDaemon(preparedDaemon(dir), {+ foreground: false,+ releaseOwnership: vi.fn(),+ onReady: () => { throw readyError; },+ })).rejects.toBe(readyError);+ await Promise.resolve();+ await Promise.resolve();++ const records = fs.readFileSync(path.join(dir, "daemon.log"), "utf8")+ .trimEnd()+ .split("\n")+ .map((line) => JSON.parse(line));+ expect(records).toContainEqual(expect.objectContaining({+ level: "warn",+ message: "diagnostic recovery failed",+ fields: expect.objectContaining({ errorClass: "Error" }),+ }));+ expect(JSON.stringify(records)).not.toContain("cmk_PRIVATE_RECOVERY_KEY");+ } finally {+ removeNewProcessListeners(listenersBefore);+ vi.clearAllTimers();+ vi.useRealTimers();+ }+ });++ it("shuts down the coordinator before the daemon process exits", async () => {+ resetDiagnosticHarness();+ vi.useFakeTimers();+ const listenersBefore = processListenerSnapshot();+ const events: string[] = [];+ installDaemonHarness(dir, events);+ runnerDiagnosticHarness.shutdown.mockImplementation(async () => { events.push("coordinator-shutdown"); });+ const exit = vi.spyOn(process, "exit").mockImplementation((() => undefined) as never);+ let ready!: () => void;+ const readyPromise = new Promise<void>((resolve) => { ready = resolve; });++ try {+ void runPreparedDaemon(preparedDaemon(dir), {+ foreground: false,+ releaseOwnership: vi.fn(),+ onReady: ready,+ });+ await readyPromise;+ const original = listenersBefore.get("SIGTERM")!;+ const signalHandler = (process.listeners("SIGTERM") as Array<(...args: never[]) => unknown>)+ .find((listener) => !original.has(listener));+ expect(signalHandler).toEqual(expect.any(Function));+ signalHandler!();+ await vi.waitFor(() => expect(exit).toHaveBeenCalledWith(0));++ expect(runnerDiagnosticHarness.shutdown).toHaveBeenCalledOnce();+ expect(events).toEqual(["coordinator-shutdown", "daemon-stop"]);+ } finally {+ removeNewProcessListeners(listenersBefore);+ vi.clearAllTimers();+ vi.useRealTimers();+ }+ });++ it("maps collection errors to fixed PATCH codes without leaking a rejection to createDaemon", async () => {+ resetDiagnosticHarness();+ vi.useFakeTimers();+ const listenersBefore = processListenerSnapshot();+ const daemonHarness = installDaemonHarness(dir);+ const readyError = new Error("stop after ready receipt");+ const command = {+ type: "diagnostics:collect",+ reportId: "dbr_0123456789abcdef",+ agentId: "bot_1",+ fromMs: 1_700_000_000_000,+ deadlineAt: 1_700_087_000_000,+ };++ try {+ await expect(runPreparedDaemon(preparedDaemon(dir), {+ foreground: false,+ releaseOwnership: vi.fn(),+ onReady: () => { throw readyError; },+ })).rejects.toBe(readyError);+ const handle = daemonHarness.state.options?.handleDiagnosticCommand as+ (value: typeof command) => Promise<void>;++ runnerDiagnosticHarness.collect.mockRejectedValueOnce(+ Object.assign(new Error("bundle is too large"), { code: "bundle_too_large" }),+ );+ await expect(handle(command)).resolves.toBeUndefined();+ expect(runnerDiagnosticHarness.fail).toHaveBeenLastCalledWith(+ command.reportId,+ "bundle_too_large",+ );++ runnerDiagnosticHarness.collect.mockRejectedValueOnce(new Error("ordinary collection failure"));+ await expect(handle(command)).resolves.toBeUndefined();+ expect(runnerDiagnosticHarness.fail).toHaveBeenLastCalledWith(+ command.reportId,+ "collection_failed",+ );+ expect(runnerDiagnosticHarness.fail).not.toHaveBeenCalledWith(+ command.reportId,+ "diagnostics_unavailable",+ );+ } finally {+ removeNewProcessListeners(listenersBefore);+ vi.clearAllTimers();+ vi.useRealTimers();+ }+ });});diff --git a/src/daemon/src/cli/daemonRunner.ts b/src/daemon/src/cli/daemonRunner.tsindex faadc90d6..acda5f073 100644--- a/src/daemon/src/cli/daemonRunner.ts+++ b/src/daemon/src/cli/daemonRunner.ts@@ -1,7 +1,21 @@import * as fs from "node:fs";import * as path from "node:path";import { WebSocket } from "ws";+import type { DiagnosticCollectCommand, DiagnosticReportFailureCode } from "@alook/shared";import { createDaemon } from "../daemon/createDaemon.js";+import {+ buildDiagnosticBundle,+ createDiagnosticHttpTransport,+ createDiagnosticReportCoordinator,+ mergeChronologicalSnapshotRows,+ projectDaemonLogRow,+ projectFsmTraceRow,+ projectStatusRow,+ readPinnedJsonFile,+ readSnapshotJsonLines,+ type DiagnosticEventRow,+ type SnapshotReadResult,+} from "../diagnostics/index.js";import { getDriver, listRuntimeIds } from "../drivers/index.js";import type { RuntimeInfo } from "../discovery.js";import { createLogger, type Logger } from "../logger.js";@@ -12,6 +26,8 @@ import { createRotatingFileSink, type RotatingFileSink } from "../util/rotatingFconst CAPABILITIES = ["send", "read", "mentions", "tasks", "reactions", "server", "channels", "knowledge", "attach", "friend"];export const DAEMON_LOG_MAX_BYTES = 8 * 1024 * 1024;const DAEMON_ERROR_MESSAGE_MAX_CHARS = 512;+const DIAGNOSTIC_MAX_LINE_BYTES = 128 * 1024;+const DIAGNOSTIC_MAX_STATUS_BYTES = 1024 * 1024;export interface PreparedDaemon {machineId: string;@@ -83,6 +99,88 @@ function safeDaemonError(error: unknown): { errorClass: string; error: string }return { errorClass, error: scrubbed };}+function diagnosticTimestamp(source: "daemon_log" | "fsm_trace", value: Record<string, unknown>): number | null {+ if (source === "fsm_trace") {+ return typeof value.nowMs === "number" && Number.isSafeInteger(value.nowMs) ? value.nowMs : null;+ }+ if (typeof value.time !== "string") return null;+ const parsed = Date.parse(value.time);+ return Number.isSafeInteger(parsed) ? parsed : null;+}++async function diagnosticRows(args: {+ source: Pick<RotatingFileSink, "openSnapshot"> | null;+ sourceName: "daemon_log" | "fsm_trace";+ fromMs: number;+}): Promise<SnapshotReadResult> {+ if (!args.source) return { rows: [], warnings: ["source_unavailable"], droppedRows: 0 };+ return readSnapshotJsonLines({+ source: args.source,+ sourceName: args.sourceName,+ fromMs: args.fromMs,+ maxLineBytes: DIAGNOSTIC_MAX_LINE_BYTES,+ timestampOf: (value) => diagnosticTimestamp(args.sourceName, value),+ });+}++async function buildRunnerDiagnosticBundle(args: {+ command: DiagnosticCollectCommand;+ outputPath: string;+ machineId: string;+ daemonLogSource: Pick<RotatingFileSink, "openSnapshot">;+ fsmTraceSource: Pick<RotatingFileSink, "openSnapshot"> | null;+ statusFilePath: string | undefined;+ now: () => number;+}) {+ const [daemon, fsm, statusRead] = await Promise.all([+ diagnosticRows({ source: args.daemonLogSource, sourceName: "daemon_log", fromMs: args.command.fromMs }),+ diagnosticRows({ source: args.fsmTraceSource, sourceName: "fsm_trace", fromMs: args.command.fromMs }),+ args.statusFilePath+ ? readPinnedJsonFile({ path: args.statusFilePath, maxBytes: DIAGNOSTIC_MAX_STATUS_BYTES })+ : Promise.resolve({ value: null, warnings: ["source_unavailable"] as const }),+ ]);+ const warnings: string[] = [...daemon.warnings, ...fsm.warnings, ...statusRead.warnings];+ if (daemon.warnings.includes("source_unavailable")) warnings.push("daemon_log_missing");+ if (fsm.warnings.includes("source_unavailable")) warnings.push("fsm_trace_missing");+ const status = projectStatusRow(statusRead.value, args.command.agentId);+ if (!status) warnings.push("status_missing");++ const droppedRows = {+ daemon_log: daemon.droppedRows,+ fsm: fsm.droppedRows,+ status: statusRead.value !== null && !status ? 1 : 0,+ };+ const events: DiagnosticEventRow[] = [];+ for (const row of mergeChronologicalSnapshotRows([daemon.rows, fsm.rows])) {+ const projected = row.source === "daemon_log"+ ? projectDaemonLogRow(row.value, args.command.agentId)+ : projectFsmTraceRow(row.value, args.command.agentId);+ if (!projected || (projected.recordType !== "daemon_log" && projected.recordType !== "fsm")) {+ droppedRows[row.source === "daemon_log" ? "daemon_log" : "fsm"] += 1;+ continue;+ }+ events.push(projected as DiagnosticEventRow);+ }++ return buildDiagnosticBundle({+ outputPath: args.outputPath,+ header: {+ recordType: "bundle_header",+ schemaVersion: 1,+ reportId: args.command.reportId,+ agentId: args.command.agentId,+ machineId: args.machineId,+ capturedAt: args.now(),+ fromMs: args.command.fromMs,+ deadlineAt: args.command.deadlineAt,+ },+ status,+ events,+ sourceWarnings: warnings,+ sourceDroppedRows: droppedRows,+ });+}+export function createDaemonProcessLogger(daemonDir: string,foreground: boolean,@@ -130,11 +228,47 @@ export async function runPreparedDaemon(opts.releaseOwnership();throw error;}- const { logger: log, logPath } = processLogger;+ const { logger: log, logPath, sink: daemonLogSource } = processLogger;let shuttingDown = false;let daemon: Awaited<ReturnType<typeof createDaemon>> | null = null;+ const diagnosticLifecycle: {+ coordinator: ReturnType<typeof createDiagnosticReportCoordinator> | null;+ } = { coordinator: null };+ const diagnosticTransport = createDiagnosticHttpTransport({+ serverUrl: prepared.serverUrl,+ machineKey: prepared.machineKey,+ });const keepAlive = setInterval(() => {}, 24 * 60 * 60 * 1000);+ const reportDiagnosticFailure = async (failure: {+ reportId: string;+ failureCode: DiagnosticReportFailureCode;+ }): Promise<void> => {+ await diagnosticTransport.fail(failure.reportId, failure.failureCode);+ };++ const handleDiagnosticCommand = async (command: DiagnosticCollectCommand): Promise<void> => {+ try {+ if (!diagnosticLifecycle.coordinator) {+ await reportDiagnosticFailure({+ reportId: command.reportId,+ failureCode: "diagnostics_unavailable",+ });+ return;+ }+ await diagnosticLifecycle.coordinator.collect(command);+ } catch (error) {+ const failureCode: DiagnosticReportFailureCode =+ error !== null+ && typeof error === "object"+ && "code" in error+ && error.code === "bundle_too_large"+ ? "bundle_too_large"+ : "collection_failed";+ await reportDiagnosticFailure({ reportId: command.reportId, failureCode });+ }+ };+const testShutdownDelay = async (): Promise<void> => {if (process.env.NODE_ENV !== "test") return;const delayMs = Number(process.env.ALOOK_DAEMON_TEST_SHUTDOWN_DELAY_MS);@@ -148,7 +282,11 @@ export async function runPreparedDaemon(if (process.env.NODE_ENV === "test" && process.env.ALOOK_DAEMON_TEST_STOP_REJECT === "1") {throw new Error("test teardown failed cmk_B0_FATAL_SECRET");}- await daemon?.stop();+ try {+ await diagnosticLifecycle.coordinator?.shutdown();+ } finally {+ await daemon?.stop();+ }};const shutdown = async (exitCode: number): Promise<never> => {@@ -210,6 +348,39 @@ export async function runPreparedDaemon(osRelease: prepared.osRelease,daemonVersion: prepared.daemonVersion,logger: log,+ handleDiagnosticCommand,+ reportDiagnosticFailure,+ onDiagnosticSources: ({ fsmTraceSource, statusFilePath }) => {+ if (diagnosticLifecycle.coordinator) return;+ diagnosticLifecycle.coordinator = createDiagnosticReportCoordinator({+ machineDir: prepared.daemonDir,+ buildBundle: ({ command, outputPath }) => buildRunnerDiagnosticBundle({+ command,+ outputPath,+ machineId: prepared.machineId,+ daemonLogSource,+ fsmTraceSource,+ statusFilePath,+ now: Date.now,+ }),+ transport: diagnosticTransport,+ now: Date.now,+ sleep: (delayMs) => new Promise((resolve) => setTimeout(resolve, delayMs)),+ scheduleRetry: (delayMs, task) => {+ const timer = setTimeout(() => {+ void task().catch((error) => {+ log.warn("diagnostic retry failed", safeDaemonError(error));+ });+ }, delayMs);+ timer.unref?.();+ return () => clearTimeout(timer);+ },+ retry: { maxAttemptsPerRound: 3, baseDelayMs: 250, maxDelayMs: 30_000 },+ logger: {+ warn: (message, fields) => log.warn(message, fields),+ },+ });+ },onAuthRejected: () => {log.error("machine key rejected by server — is it correct / has it expired?");void shutdown(1);@@ -217,11 +388,18 @@ export async function runPreparedDaemon(});} catch (error) {clearInterval(keepAlive);+ await diagnosticLifecycle.coordinator?.shutdown().catch(() => {});log.error("daemon runner initialization failed", safeDaemonError(error));opts.releaseOwnership();throw error;}+ if (diagnosticLifecycle.coordinator) {+ void diagnosticLifecycle.coordinator.recover().catch((error: unknown) => {+ log.warn("diagnostic recovery failed", safeDaemonError(error));+ });+ }+logDaemonUp(log, daemon.proxyUrl, prepared.wsUrl);daemon.onOpen(() => log.info("control plane OPEN"));opts.onReady?.({diff --git a/src/daemon/src/cli/diagnosticsLifecycle.real.test.ts b/src/daemon/src/cli/diagnosticsLifecycle.real.test.tsnew file mode 100644index 000000000..e19abe198--- /dev/null+++ b/src/daemon/src/cli/diagnosticsLifecycle.real.test.ts@@ -0,0 +1,190 @@+import { createHash } from "node:crypto";+import { spawn } from "node:child_process";+import { createServer } from "node:http";+import { mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";+import { gzipSync } from "node:zlib";+import { afterEach, describe, expect, it, vi } from "vitest";++interface HttpTransportModule {+ createDiagnosticHttpTransport(args: {+ serverUrl: string;+ machineKey: string;+ }): unknown;+}++async function loadSubject(): Promise<HttpTransportModule> {+ return vi.importActual<HttpTransportModule>("../diagnostics/httpTransport.js");+}++const roots = new Set<string>();++function tempRoot(): string {+ const root = mkdtempSync(join(tmpdir(), "diagnostics-lifecycle-real-"));+ roots.add(root);+ return root;+}++afterEach(() => {+ for (const root of roots) rmSync(root, { recursive: true, force: true });+ roots.clear();+});++function runChild(args: {+ mode: "collect" | "recover";+ machineDir: string;+ serverUrl: string;+ machineKey: string;+ archiveBase64: string;+}): Promise<{ stdout: string; stderr: string }> {+ const sourceRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");+ const packageRoot = resolve(sourceRoot, "..");+ const coordinatorUrl = pathToFileURL(join(sourceRoot, "diagnostics/coordinator.ts")).href;+ const transportUrl = pathToFileURL(join(sourceRoot, "diagnostics/httpTransport.ts")).href;+ const script = `+ import { createHash } from "node:crypto";+ import { writeFileSync } from "node:fs";+ import { createDiagnosticReportCoordinator } from ${JSON.stringify(coordinatorUrl)};+ import { createDiagnosticHttpTransport } from ${JSON.stringify(transportUrl)};+ const command = {+ type: "diagnostics:collect",+ reportId: "dbr_0123456789abcdef",+ agentId: "bot_1",+ fromMs: 1700000000000,+ deadlineAt: 1700087000000,+ };+ const bytes = Buffer.from(process.env.TEST_ARCHIVE_BASE64, "base64");+ const coordinator = createDiagnosticReportCoordinator({+ machineDir: process.env.TEST_MACHINE_DIR,+ buildBundle: async ({ outputPath }) => {+ writeFileSync(outputPath, bytes, { mode: 0o600, flag: "wx" });+ return {+ path: outputPath,+ sizeBytes: bytes.byteLength,+ sha256: createHash("sha256").update(bytes).digest("hex"),+ };+ },+ transport: createDiagnosticHttpTransport({+ serverUrl: process.env.TEST_SERVER_URL,+ machineKey: process.env.TEST_MACHINE_KEY,+ }),+ now: () => 1700000001000,+ sleep: async () => {},+ scheduleRetry: () => () => {},+ retry: { maxAttemptsPerRound: 1, baseDelayMs: 1, maxDelayMs: 1 },+ });+ const result = process.env.TEST_MODE === "collect"+ ? await Promise.all([coordinator.collect(command), coordinator.collect(command)])+ : (await coordinator.recover(), []);+ process.stdout.write(JSON.stringify(result));+ `;+ return new Promise((resolvePromise, reject) => {+ const child = spawn(process.execPath, ["--import", "tsx", "--input-type=module", "--eval", script], {+ cwd: packageRoot,+ env: {+ ...process.env,+ TEST_MODE: args.mode,+ TEST_MACHINE_DIR: args.machineDir,+ TEST_SERVER_URL: args.serverUrl,+ TEST_MACHINE_KEY: args.machineKey,+ TEST_ARCHIVE_BASE64: args.archiveBase64,+ },+ stdio: ["ignore", "pipe", "pipe"],+ });+ let stdout = "";+ let stderr = "";+ child.stdout.on("data", (chunk) => { stdout += String(chunk); });+ child.stderr.on("data", (chunk) => { stderr += String(chunk); });+ child.once("error", reject);+ child.once("exit", (code) => {+ if (code === 0) resolvePromise({ stdout, stderr });+ else reject(new Error(`diagnostic child exited ${code}: ${stderr}`));+ });+ });+}++describe("B2d real-process diagnostic lifecycle", () => {+ it("restarts after body-received disconnect and retries the identical committed bytes", async () => {+ await loadSubject();+ const machineDir = tempRoot();+ const machineKey = "cmk_REAL_PROCESS_PRIVATE_KEY";+ const archive = gzipSync(Buffer.from('{"recordType":"bundle_header","schemaVersion":1}\n'));+ const expectedSha = createHash("sha256").update(archive).digest("hex");+ const received: Array<{ body: Buffer; length: string | null; sha256: string | null; url: string }> = [];+ let disconnectFirst = true;+ const server = createServer((request, response) => {+ const chunks: Buffer[] = [];+ request.on("data", (chunk) => chunks.push(Buffer.from(chunk)));+ request.on("end", () => {+ received.push({+ body: Buffer.concat(chunks),+ length: request.headers["content-length"] ?? null,+ sha256: request.headers["x-alook-content-sha256"] as string | null,+ url: request.url ?? "",+ });+ if (disconnectFirst) {+ disconnectFirst = false;+ request.socket.destroy();+ return;+ }+ response.writeHead(200, { "content-type": "application/json" });+ response.end(JSON.stringify({ kind: "terminal", status: "uploaded" }));+ });+ });+ await new Promise<void>((resolvePromise) => server.listen(0, "127.0.0.1", resolvePromise));+ const address = server.address();+ if (!address || typeof address === "string") throw new Error("local HTTP server did not bind");+ const serverUrl = `http://127.0.0.1:${address.port}`;++ try {+ const first = await runChild({+ mode: "collect",+ machineDir,+ serverUrl,+ machineKey,+ archiveBase64: archive.toString("base64"),+ });+ expect(JSON.parse(first.stdout)).toEqual([+ { status: "pending" },+ { status: "pending" },+ ]);+ expect(received).toHaveLength(1);++ const diagnosticDir = join(machineDir, "diagnostics");+ const filesAfterDisconnect = readdirSync(diagnosticDir).sort();+ expect(filesAfterDisconnect).toEqual([+ "report-dbr_0123456789abcdef.json",+ "report-dbr_0123456789abcdef.ndjson.gz",+ ]);+ const persistedText = filesAfterDisconnect+ .map((file) => readFileSync(join(diagnosticDir, file)))+ .map((value) => value.toString("latin1"))+ .join("\n");+ expect(`${diagnosticDir}\n${first.stdout}\n${first.stderr}\n${persistedText}`).not.toContain(machineKey);++ await runChild({+ mode: "recover",+ machineDir,+ serverUrl,+ machineKey,+ archiveBase64: archive.toString("base64"),+ });++ expect(received).toHaveLength(2);+ for (const attempt of received) {+ expect(attempt.body).toEqual(archive);+ expect(attempt.length).toBe(String(archive.byteLength));+ expect(attempt.sha256).toBe(expectedSha);+ expect(attempt.url).toBe(+ "/api/community/daemon/diagnostics/dbr_0123456789abcdef/bundle",+ );+ expect(attempt.url).not.toContain(machineKey);+ }+ expect(readdirSync(diagnosticDir)).toEqual([]);+ } finally {+ await new Promise<void>((resolvePromise) => server.close(() => resolvePromise()));+ }+ }, 30_000);+});diff --git a/src/daemon/src/daemon/createDaemon.test.ts b/src/daemon/src/daemon/createDaemon.test.tsindex d52c2b070..fc85b002b 100644--- a/src/daemon/src/daemon/createDaemon.test.ts+++ b/src/daemon/src/daemon/createDaemon.test.ts@@ -139,6 +139,40 @@ function factory(sockets: FakeSocket[]) {}describe("createDaemon", () => {+ it("supplies only the canonical default FSM snapshot source and status path", async () => {+ const sockets: FakeSocket[] = [];+ const root = mkdtempSync(join(tmpdir(), "daemon-diagnostic-sources-"));+ startupSweepDirs.push(root);+ const onDiagnosticSources = vi.fn();+ vi.stubEnv("ALOOK_FSM_TRACE", "");+ vi.stubGlobal("fetch", vi.fn(async () => Response.json({ bots: [] })));++ const daemon = await createDaemon({+ machineKey: "cmk_diagnostics_sources",+ serverUrl: "http://localhost:9999",+ serverWsUrl: "ws://x",+ webSocketFactory: factory(sockets) as any,+ runtimeReport: [],+ driverFor: () => fakeDriver,+ capabilities: [],+ fsmTraceDir: root,+ statusFilePath: join(root, "status.json"),+ onDiagnosticSources,+ } as Parameters<typeof createDaemon>[0]);++ try {+ expect(onDiagnosticSources).toHaveBeenCalledOnce();+ const sources = onDiagnosticSources.mock.calls[0]![0] as Record<string, unknown>;+ expect(Object.keys(sources).sort()).toEqual(["fsmTraceSource", "statusFilePath"]);+ expect(sources.statusFilePath).toBe(join(root, "status.json"));+ expect(sources.fsmTraceSource).toEqual(expect.objectContaining({+ openSnapshot: expect.any(Function),+ }));+ } finally {+ await daemon.stop();+ }+ });+it("consumes diagnostics before Router and invokes the injected handler once", async () => {const sockets: FakeSocket[] = [];const routerEntry = spyOnRouterCommandEntry();diff --git a/src/daemon/src/daemon/createDaemon.ts b/src/daemon/src/daemon/createDaemon.tsindex 54108c1c5..6efe8c252 100644--- a/src/daemon/src/daemon/createDaemon.ts+++ b/src/daemon/src/daemon/createDaemon.ts@@ -24,7 +24,7 @@*/import { homedir } from "os";import { appendFileSync, mkdirSync } from "node:fs";-import { createRotatingFileSink } from "../util/rotatingFileSink.js";+import { createRotatingFileSink, type RotatingFileSink } from "../util/rotatingFileSink.js";import { createTraceSampler, DEFAULT_TRACE_FILE_MAX_BYTES } from "../util/traceSampler.js";import { writeStatusFile } from "../util/statusFile.js";import { WsControlChannel } from "../server/wsControlChannel.js";@@ -291,6 +291,11 @@ export interface CreateDaemonOptions {handleDiagnosticCommand?: (command: DiagnosticCollectCommand) => void | Promise<void>;/** Fixed-code failure callback used when diagnostics is not available. */reportDiagnosticFailure?: (failure: DiagnosticFailureReport) => void | Promise<void>;+ /** Supplies only the bounded default FSM snapshot source and status snapshot path. */+ onDiagnosticSources?: (sources: {+ fsmTraceSource: Pick<RotatingFileSink, "openSnapshot"> | null;+ statusFilePath: string | undefined;+ }) => void;}export interface RunningDaemon {@@ -669,6 +674,37 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa// command dispatch, so runtime code always sees a populated cell.let router: AgentRouter | null = null;+ const diagnosticTrace = (() => {+ const overridePath = process.env.ALOOK_FSM_TRACE;+ if (overridePath) {+ return {+ source: null,+ onFsmTransition: (rec: ManagerTraceRecord) => {+ try {+ appendFileSync(overridePath, JSON.stringify(rec) + "\n");+ } catch {+ /* never let tracing break the daemon */+ }+ },+ };+ }+ if (!opts.fsmTraceDir) return { source: null };+ try {+ mkdirSync(opts.fsmTraceDir, { recursive: true });+ } catch {+ /* best-effort: if the dir can't be made, sink writes just no-op */+ }+ const source = createRotatingFileSink(+ `${opts.fsmTraceDir}/fsm-trace.jsonl`,+ DEFAULT_TRACE_FILE_MAX_BYTES,+ );+ const sampler = createTraceSampler((rec) => source.write(JSON.stringify(rec)));+ return {+ source,+ onFsmTransition: (rec: ManagerTraceRecord) => sampler.offer(rec),+ };+ })();+const manager = new AgentProcessManager({// Wrap the caller's driverFor to short-circuit dispatch to a known-unhealthy// runtime. If the router flags the runtime as unhealthy we throw@@ -752,43 +788,9 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa// - `ALOOK_FSM_TRACE=<path>` OVERRIDE: unbounded single-file append at// that path (deep-investigation mode; takes precedence over the// default). Content is FSM metadata only (no PII) — safe to default on.- ...(() => {- const overridePath = process.env.ALOOK_FSM_TRACE;- if (overridePath) {- return {- onFsmTransition: (rec: ManagerTraceRecord) => {- try {- appendFileSync(overridePath, JSON.stringify(rec) + "\n");- } catch {- /* never let tracing break the daemon */- }- },- };- }- if (opts.fsmTraceDir) {- try {- mkdirSync(opts.fsmTraceDir, { recursive: true });- } catch {- /* best-effort: if the dir can't be made, sink writes just no-op */- }- const sink = createRotatingFileSink(- `${opts.fsmTraceDir}/fsm-trace.jsonl`,- DEFAULT_TRACE_FILE_MAX_BYTES,- );- // Heartbeat sampler between the manager and the sink (batch T4): folds- // redundant unchanged-state ticks + progress/runtime_signal noise so the- // bounded two-generation file retains ~16.73h at the executable N=8- // operational envelope.- // Transitions and watchdog-fired (effects-carrying) frames are never- // dropped. The ALOOK_FSM_TRACE override above is unbounded → unsampled,- // for full-fidelity deep dives.- const sampler = createTraceSampler((rec) => sink.write(JSON.stringify(rec)));- return {- onFsmTransition: (rec: ManagerTraceRecord) => sampler.offer(rec),- };- }- return {};- })(),+ ...(diagnosticTrace.onFsmTransition+ ? { onFsmTransition: diagnosticTrace.onFsmTransition }+ : {}),// Only the "pi" runtime declares `Driver.createSession` today (in-process// SDK, no child process) — this is only ever consulted for that case.sdkDriverDepsFor: (ctx) => createPiSdkDriverDeps(ctx),@@ -815,6 +817,10 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDastatusTimer = setInterval(writeStatus, STATUS_WRITE_INTERVAL_MS);statusTimer.unref?.();}+ opts.onDiagnosticSources?.({+ fsmTraceSource: diagnosticTrace.source,+ statusFilePath: opts.statusFilePath,+ });router = new AgentRouter({manager,diff --git a/src/daemon/src/diagnostics/httpTransport.test.ts b/src/daemon/src/diagnostics/httpTransport.test.tsnew file mode 100644index 000000000..9cd20875e--- /dev/null+++ b/src/daemon/src/diagnostics/httpTransport.test.ts@@ -0,0 +1,154 @@+import { Readable } from "node:stream";+import { describe, expect, it, vi } from "vitest";+import type { DiagnosticReportFailureCode } from "@alook/shared";++type TransportResult =+ | { kind: "terminal"; status: "uploaded" | "failed" }+ | { kind: "retryable" };++interface HttpTransportModule {+ createDiagnosticHttpTransport(args: {+ serverUrl: string;+ machineKey: string;+ fetchImpl?: typeof fetch;+ }): {+ upload(+ meta: { reportId: string; sizeBytes: number; sha256: string },+ body: Readable,+ ): Promise<TransportResult>;+ fail(reportId: string, failureCode: DiagnosticReportFailureCode): Promise<TransportResult>;+ };+}++async function loadSubject(): Promise<HttpTransportModule> {+ return vi.importActual<HttpTransportModule>("./httpTransport.js");+}++async function streamBytes(value: unknown): Promise<Buffer> {+ const chunks: Buffer[] = [];+ for await (const chunk of value as AsyncIterable<Uint8Array | string>) {+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));+ }+ return Buffer.concat(chunks);+}++const REPORT_ID = "dbr_0123456789abcdef";+const SHA256 = "a".repeat(64);++describe("B2d daemon diagnostic HTTP transport", () => {+ it("streams an exact authenticated PUT without putting credentials in the URL or body", async () => {+ const api = await loadSubject();+ const archive = Buffer.from("diagnostic-gzip-bytes");+ const requests: Array<{ input: RequestInfo | URL; init?: RequestInit; body: Buffer }> = [];+ const fetchImpl = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ requests.push({ input, init, body: await streamBytes(init?.body) });+ return Response.json({ kind: "terminal", status: "uploaded" });+ });+ const transport = api.createDiagnosticHttpTransport({+ serverUrl: "https://alook.test/",+ machineKey: "cmk_PRIVATE_UPLOAD_KEY",+ fetchImpl: fetchImpl as typeof fetch,+ });++ await expect(transport.upload({+ reportId: REPORT_ID,+ sizeBytes: archive.byteLength,+ sha256: SHA256,+ }, Readable.from([archive]))).resolves.toEqual({ kind: "terminal", status: "uploaded" });++ expect(requests).toHaveLength(1);+ expect(String(requests[0]!.input)).toBe(+ `https://alook.test/api/community/daemon/diagnostics/${REPORT_ID}/bundle`,+ );+ expect(requests[0]!.init).toMatchObject({ method: "PUT", duplex: "half" });+ expect(new Headers(requests[0]!.init?.headers)).toEqual(new Headers({+ authorization: "Bearer cmk_PRIVATE_UPLOAD_KEY",+ "content-type": "application/x-ndjson",+ "content-encoding": "gzip",+ "content-length": String(archive.byteLength),+ "x-alook-content-sha256": SHA256,+ }));+ expect(requests[0]!.body).toEqual(archive);+ expect(`${String(requests[0]!.input)}${requests[0]!.body.toString("utf8")}`).not.toContain(+ "cmk_PRIVATE_UPLOAD_KEY",+ );+ });++ it.each([+ ["uploaded", 200, { kind: "terminal", status: "uploaded" }],+ ["failed", 409, { kind: "terminal", status: "failed" }],+ ] as const)("accepts a strict %s terminal envelope", async (_name, status, body) => {+ const api = await loadSubject();+ const transport = api.createDiagnosticHttpTransport({+ serverUrl: "https://alook.test",+ machineKey: "cmk_test",+ fetchImpl: vi.fn(async () => Response.json(body, { status })) as typeof fetch,+ });++ await expect(transport.upload({ reportId: REPORT_ID, sizeBytes: 1, sha256: SHA256 }, Readable.from(["x"])))+ .resolves.toEqual(body);+ });++ it.each([+ ["network throw", () => Promise.reject(new Error("socket reset secret"))],+ ["server error", () => Promise.resolve(new Response("private server detail", { status: 503 }))],+ ["non-terminal JSON", () => Promise.resolve(Response.json({ status: "pending", detail: "secret" }))],+ ["malformed JSON", () => Promise.resolve(new Response("{", { status: 200 }))],+ ["unknown terminal", () => Promise.resolve(Response.json({ kind: "terminal", status: "other" }))],+ ])("normalizes %s to retryable and never rejects", async (_name, outcome) => {+ const api = await loadSubject();+ const transport = api.createDiagnosticHttpTransport({+ serverUrl: "https://alook.test",+ machineKey: "cmk_test",+ fetchImpl: vi.fn(outcome) as unknown as typeof fetch,+ });++ await expect(transport.upload({ reportId: REPORT_ID, sizeBytes: 1, sha256: SHA256 }, Readable.from(["x"])))+ .resolves.toEqual({ kind: "retryable" });+ });++ it("sends PATCH with only the fixed failure code and normalizes its terminal response", async () => {+ const api = await loadSubject();+ const calls: Array<{ input: RequestInfo | URL; init?: RequestInit }> = [];+ const transport = api.createDiagnosticHttpTransport({+ serverUrl: "https://alook.test/",+ machineKey: "cmk_PATCH_KEY",+ fetchImpl: vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ calls.push({ input, init });+ return Response.json({ kind: "terminal", status: "failed" });+ }) as typeof fetch,+ });++ await expect(transport.fail(REPORT_ID, "local_artifact_invalid")).resolves.toEqual({+ kind: "terminal",+ status: "failed",+ });+ expect(String(calls[0]!.input)).toBe(+ `https://alook.test/api/community/daemon/diagnostics/${REPORT_ID}`,+ );+ expect(calls[0]!.init).toMatchObject({+ method: "PATCH",+ body: JSON.stringify({ status: "failed", failureCode: "local_artifact_invalid" }),+ });+ expect(new Headers(calls[0]!.init?.headers)).toEqual(new Headers({+ authorization: "Bearer cmk_PATCH_KEY",+ "content-type": "application/json",+ }));+ });++ it("normalizes PATCH disconnects and non-terminal responses to retryable", async () => {+ const api = await loadSubject();+ for (const fetchImpl of [+ vi.fn(async () => { throw new Error("disconnect"); }),+ vi.fn(async () => Response.json({ kind: "retryable" }, { status: 503 })),+ vi.fn(async () => Response.json({ status: "pending" })),+ ]) {+ const transport = api.createDiagnosticHttpTransport({+ serverUrl: "https://alook.test",+ machineKey: "cmk_test",+ fetchImpl: fetchImpl as typeof fetch,+ });+ await expect(transport.fail(REPORT_ID, "upload_failed")).resolves.toEqual({ kind: "retryable" });+ }+ });+});diff --git a/src/daemon/src/diagnostics/httpTransport.ts b/src/daemon/src/diagnostics/httpTransport.tsnew file mode 100644index 000000000..c76e6f72a--- /dev/null+++ b/src/daemon/src/diagnostics/httpTransport.ts@@ -0,0 +1,86 @@+import { Readable } from "node:stream";+import type { DiagnosticReportFailureCode } from "@alook/shared";+import type { DiagnosticTransport, DiagnosticTransportResult } from "./types.js";++type TransportOutcome = DiagnosticTransportResult | { kind: "retryable" };++function endpoint(serverUrl: string, path: string): string {+ const base = serverUrl.endsWith("/") ? serverUrl : `${serverUrl}/`;+ return new URL(path.replace(/^\//, ""), base).toString();+}++async function strictOutcome(+ response: Response,+ allowed: Readonly<Record<string, number>>,+): Promise<TransportOutcome> {+ try {+ const value = await response.json() as unknown;+ if (value === null || typeof value !== "object" || Array.isArray(value)) {+ return { kind: "retryable" };+ }+ const record = value as Record<string, unknown>;+ if (Object.keys(record).length !== 2 || record.kind !== "terminal") {+ return { kind: "retryable" };+ }+ const status = record.status;+ if ((status !== "uploaded" && status !== "failed") || allowed[status] !== response.status) {+ return { kind: "retryable" };+ }+ return { kind: "terminal", status };+ } catch {+ return { kind: "retryable" };+ }+}++export function createDiagnosticHttpTransport(args: {+ serverUrl: string;+ machineKey: string;+ fetchImpl?: typeof fetch;+}): DiagnosticTransport {+ const fetchImpl = args.fetchImpl ?? fetch;+ const authorization = `Bearer ${args.machineKey}`;++ return {+ async upload(meta, body: Readable): Promise<TransportOutcome> {+ try {+ const response = await fetchImpl(endpoint(+ args.serverUrl,+ `/api/community/daemon/diagnostics/${encodeURIComponent(meta.reportId)}/bundle`,+ ), {+ method: "PUT",+ headers: {+ authorization,+ "content-type": "application/x-ndjson",+ "content-encoding": "gzip",+ "content-length": String(meta.sizeBytes),+ "x-alook-content-sha256": meta.sha256,+ },+ body: Readable.toWeb(body),+ duplex: "half",+ } as RequestInit & { duplex: "half" });+ return strictOutcome(response, { uploaded: 200, failed: 409 });+ } catch {+ return { kind: "retryable" };+ }+ },++ async fail(reportId: string, failureCode: DiagnosticReportFailureCode): Promise<TransportOutcome> {+ try {+ const response = await fetchImpl(endpoint(+ args.serverUrl,+ `/api/community/daemon/diagnostics/${encodeURIComponent(reportId)}`,+ ), {+ method: "PATCH",+ headers: {+ authorization,+ "content-type": "application/json",+ },+ body: JSON.stringify({ status: "failed", failureCode }),+ });+ return strictOutcome(response, { failed: 200 });+ } catch {+ return { kind: "retryable" };+ }+ },+ };+}diff --git a/src/daemon/src/diagnostics/index.ts b/src/daemon/src/diagnostics/index.tsindex 93e758922..9b629adc6 100644--- a/src/daemon/src/diagnostics/index.ts+++ b/src/daemon/src/diagnostics/index.ts@@ -3,3 +3,4 @@ export * from "./snapshotReader.js";export * from "./privacyPolicy.js";export * from "./bundle.js";export * from "./coordinator.js";+export * from "./httpTransport.js";diff --git a/src/web/cloudflare-env.d.ts b/src/web/cloudflare-env.d.tsindex 2c69f3667..da16b0652 100644--- a/src/web/cloudflare-env.d.ts+++ b/src/web/cloudflare-env.d.ts@@ -1,19 +1,44 @@/* eslint-disable */-// Generated by Wrangler by running `wrangler types --env-interface CloudflareEnv ./cloudflare-env.d.ts` (hash: 72778ce875081623d6602e8d778dd96b)-// Runtime types generated with [email protected] 2026-04-09 global_fetch_strictly_public,nodejs_compat+// Generated by Wrangler by running `wrangler types --env-interface=CloudflareEnv ./cloudflare-env.d.ts` (hash: d75aadbc99481d079ae2cbfa7547585d)+// Runtime types generated with [email protected] 2026-04-09 nodejs_compat+interface __BaseEnv_CloudflareEnv {+ CACHE_KV: KVNamespace;+ NEXT_INC_CACHE_R2_BUCKET: R2Bucket;+ EMAIL_BUCKET: R2Bucket;+ COMMUNITY_MEDIA: R2Bucket;+ BUG_REPORTS: R2Bucket;+ NEXT_TAG_CACHE_D1: D1Database;+ DB: D1Database;+ WAKE_QUEUE: Queue;+ ASSETS: Fetcher;+ BUG_REPORTS_ENABLED: "false";+ RUNTIME_MODEL_OPTIONS: "{\"claude\":[\"claude-opus-4-6\",\"claude-sonnet-4-6\",\"claude-haiku-4-5\"],\"codex\":[\"gpt-5.4\",\"gpt-5.3-codex\"]}";+ MIN_CLI_VERSION: "0.0.159";+ BETTER_AUTH_SECRET: string;+ BETTER_AUTH_URL: string;+ GITHUB_CLIENT_ID: string;+ GITHUB_CLIENT_SECRET: string;+ GOOGLE_CLIENT_ID: string;+ GOOGLE_CLIENT_SECRET: string;+ NEXT_CACHE_DO_QUEUE: DurableObjectNamespace<import("./custom-worker").DOQueueHandler>;+ WORKER_SELF_REFERENCE: Service<typeof import("./custom-worker").default>;+ WS_DO_WORKER: Fetcher /* alook-ws-do */;+ EMAIL_WORKER: Fetcher /* alook-email-worker */;+ WAKE_WORKER: Fetcher /* alook-wake-worker */;+}declare namespace Cloudflare {- interface Env {- IMAGES: ImagesBinding;- ASSETS: Fetcher;- WORKER_SELF_REFERENCE: Fetcher /* web */;+ interface GlobalProps {+ mainModule: typeof import("./custom-worker");+ durableNamespaces: "DOQueueHandler";}+ interface Env extends __BaseEnv_CloudflareEnv {}}-interface CloudflareEnv extends Cloudflare.Env {}+interface CloudflareEnv extends __BaseEnv_CloudflareEnv {}type StringifyValues<EnvType extends Record<string, unknown>> = {[Binding in keyof EnvType]: EnvType[Binding] extends string ? EnvType[Binding] : string;};declare namespace NodeJS {- interface ProcessEnv {}+ interface ProcessEnv extends StringifyValues<Pick<Cloudflare.Env, "BUG_REPORTS_ENABLED" | "RUNTIME_MODEL_OPTIONS" | "MIN_CLI_VERSION" | "BETTER_AUTH_SECRET" | "BETTER_AUTH_URL" | "GITHUB_CLIENT_ID" | "GITHUB_CLIENT_SECRET" | "GOOGLE_CLIENT_ID" | "GOOGLE_CLIENT_SECRET">> {}}// Begin runtime types@@ -438,6 +463,9 @@ interface ExecutionContext<Props = unknown> {passThroughOnException(): void;readonly exports: Cloudflare.Exports;readonly props: Props;+ cache?: CacheContext;+ readonly access?: CloudflareAccessContext;+ tracing: Tracing;}type ExportedHandlerFetchHandler<Env = unknown, CfHostMetadata = unknown, Props = unknown> = (request: Request<CfHostMetadata, IncomingRequestCfProperties<CfHostMetadata>>, env: Env, ctx: ExecutionContext<Props>) => Response | Promise<Response>;type ExportedHandlerConnectHandler<Env = unknown, Props = unknown> = (socket: Socket, env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;@@ -465,6 +493,7 @@ declare abstract class Navigator {sendBeacon(url: string, body?: BodyInit): boolean;readonly userAgent: string;readonly hardwareConcurrency: number;+ readonly platform: string;readonly language: string;readonly languages: string[];}@@ -476,6 +505,29 @@ interface AlarmInvocationInfo {interface Cloudflare {readonly compatibilityFlags: Record<string, boolean>;}+interface CachePurgeError {+ code: number;+ message: string;+}+interface CachePurgeResult {+ success: boolean;+ errors: CachePurgeError[];+}+interface CachePurgeOptions {+ tags?: string[];+ pathPrefixes?: string[];+ purgeEverything?: boolean;+}+interface CacheContext {+ purge(options: CachePurgeOptions): Promise<CachePurgeResult>;+}+interface CloudflareAccessContext {+ readonly aud: string;+ getIdentity(): Promise<CloudflareAccessIdentity | undefined>;+}+declare abstract class ColoLocalActorNamespace {+ get(actorId: string): Fetcher;+}interface DurableObject {fetch(request: Request): Response | Promise<Response>;connect?(socket: Socket): void | Promise<void>;@@ -502,11 +554,11 @@ declare abstract class DurableObjectNamespace<T extends Rpc.DurableObjectBrandedgetByName(name: string, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub<T>;jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace<T>;}-type DurableObjectJurisdiction = "eu" | "fedramp" | "fedramp-high";+type DurableObjectJurisdiction = "eu" | "fedramp" | "fedramp-high" | "us";interface DurableObjectNamespaceNewUniqueIdOptions {jurisdiction?: DurableObjectJurisdiction;}-type DurableObjectLocationHint = "wnam" | "enam" | "sam" | "weur" | "eeur" | "apac" | "oc" | "afr" | "me";+type DurableObjectLocationHint = "wnam" | "enam" | "sam" | "weur" | "eeur" | "apac" | "apac-ne" | "apac-se" | "oc" | "afr" | "me";type DurableObjectRoutingMode = "primary-only";interface DurableObjectNamespaceGetDurableObjectOptions {locationHint?: DurableObjectLocationHint;@@ -521,6 +573,7 @@ interface DurableObjectState<Props = unknown> {readonly id: DurableObjectId;readonly storage: DurableObjectStorage;container?: Container;+ facets: DurableObjectFacets;blockConcurrencyWhile<T>(callback: () => Promise<T>): Promise<T>;acceptWebSocket(ws: WebSocket, tags?: string[]): void;getWebSockets(tag?: string): WebSocket[];@@ -597,6 +650,16 @@ declare class WebSocketRequestResponsePair {get request(): string;get response(): string;}+interface DurableObjectFacets {+ get<T extends Rpc.DurableObjectBranded | undefined = undefined>(name: string, getStartupOptions: () => FacetStartupOptions<T> | Promise<FacetStartupOptions<T>>): Fetcher<T>;+ abort(name: string, reason: any): void;+ delete(name: string): void;+ clone(src: string, dst: string): void;+}+interface FacetStartupOptions<T extends Rpc.DurableObjectBranded | undefined = undefined> {+ id?: DurableObjectId | string;+ class: DurableObjectClass<T>;+}interface AnalyticsEngineDataset {writeDataPoint(event?: AnalyticsEngineDataPoint): void;}@@ -889,7 +952,7 @@ interface CustomEventCustomEventInit {* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob)*/declare class Blob {- constructor(type?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], options?: BlobOptions);+ constructor(bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], options?: BlobOptions);/*** The **`size`** read-only property of the Blob interface returns the size of the Blob or File in bytes.*@@ -1885,8 +1948,31 @@ interface KVNamespaceGetWithMetadataResult<Value, Metadata> {}type QueueContentType = "text" | "bytes" | "json" | "v8";interface Queue<Body = unknown> {- send(message: Body, options?: QueueSendOptions): Promise<void>;- sendBatch(messages: Iterable<MessageSendRequest<Body>>, options?: QueueSendBatchOptions): Promise<void>;+ metrics(): Promise<QueueMetrics>;+ send(message: Body, options?: QueueSendOptions): Promise<QueueSendResponse>;+ sendBatch(messages: Iterable<MessageSendRequest<Body>>, options?: QueueSendBatchOptions): Promise<QueueSendBatchResponse>;+}+interface QueueSendMetrics {+ backlogCount: number;+ backlogBytes: number;+ oldestMessageTimestamp?: Date;+}+interface QueueSendMetadata {+ metrics: QueueSendMetrics;+}+interface QueueSendResponse {+ metadata: QueueSendMetadata;+}+interface QueueSendBatchMetrics {+ backlogCount: number;+ backlogBytes: number;+ oldestMessageTimestamp?: Date;+}+interface QueueSendBatchMetadata {+ metrics: QueueSendBatchMetrics;+}+interface QueueSendBatchResponse {+ metadata: QueueSendBatchMetadata;}interface QueueSendOptions {contentType?: QueueContentType;@@ -1900,6 +1986,19 @@ interface MessageSendRequest<Body = unknown> {contentType?: QueueContentType;delaySeconds?: number;}+interface QueueMetrics {+ backlogCount: number;+ backlogBytes: number;+ oldestMessageTimestamp?: Date;+}+interface MessageBatchMetrics {+ backlogCount: number;+ backlogBytes: number;+ oldestMessageTimestamp?: Date;+}+interface MessageBatchMetadata {+ metrics: MessageBatchMetrics;+}interface QueueRetryOptions {delaySeconds?: number;}@@ -1914,12 +2013,14 @@ interface Message<Body = unknown> {interface QueueEvent<Body = unknown> extends ExtendableEvent {readonly messages: readonly Message<Body>[];readonly queue: string;+ readonly metadata: MessageBatchMetadata;retryAll(options?: QueueRetryOptions): void;ackAll(): void;}interface MessageBatch<Body = unknown> {readonly messages: readonly Message<Body>[];readonly queue: string;+ readonly metadata: MessageBatchMetadata;retryAll(options?: QueueRetryOptions): void;ackAll(): void;}@@ -1938,7 +2039,7 @@ interface R2ListOptions {startAfter?: string;include?: ("httpMetadata" | "customMetadata")[];}-declare abstract class R2Bucket {+interface R2Bucket {head(key: string): Promise<R2Object | null>;get(key: string, options: R2GetOptions & {onlyIf: R2Conditional | Headers;@@ -3229,6 +3330,28 @@ interface EventSourceEventSourceInit {withCredentials?: boolean;fetcher?: Fetcher;}+interface ExecOutput {+ readonly stdout: ArrayBuffer;+ readonly stderr: ArrayBuffer;+ readonly exitCode: number;+}+interface ContainerExecOptions {+ cwd?: string;+ env?: Record<string, string>;+ user?: string;+ stdin?: ReadableStream | "pipe";+ stdout?: "pipe" | "ignore";+ stderr?: "pipe" | "ignore" | "combined";+}+interface ExecProcess {+ readonly stdin: WritableStream | null;+ readonly stdout: ReadableStream | null;+ readonly stderr: ReadableStream | null;+ readonly pid: number;+ readonly exitCode: Promise<number>;+ output(): Promise<ExecOutput>;+ kill(signal?: number): void;+}interface Container {get running(): boolean;start(options?: ContainerStartupOptions): void;@@ -3242,6 +3365,7 @@ interface Container {snapshotDirectory(options: ContainerDirectorySnapshotOptions): Promise<ContainerDirectorySnapshot>;snapshotContainer(options: ContainerSnapshotOptions): Promise<ContainerSnapshot>;interceptOutboundHttps(addr: string, binding: Fetcher): Promise<void>;+ exec(cmd: string[], options?: ContainerExecOptions): Promise<ExecProcess>;}interface ContainerDirectorySnapshot {id: string;@@ -3334,6 +3458,10 @@ type LoopbackDurableObjectClass<T extends Rpc.DurableObjectBranded | undefined =}) => DurableObjectClass<T> : (opts: {props?: any;}) => DurableObjectClass<T>);+interface LoopbackDurableObjectNamespace extends DurableObjectNamespace {+}+interface LoopbackColoLocalActorNamespace extends ColoLocalActorNamespace {+}interface SyncKvStorage {get<T = unknown>(key: string): T | undefined;list<T = unknown>(options?: SyncKvListOptions): Iterable<[@@ -3353,9 +3481,11 @@ interface SyncKvListOptions {}interface WorkerStub {getEntrypoint<T extends Rpc.WorkerEntrypointBranded | undefined>(name?: string, options?: WorkerStubEntrypointOptions): Fetcher<T>;+ getDurableObjectClass<T extends Rpc.DurableObjectBranded | undefined>(name?: string, options?: WorkerStubEntrypointOptions): DurableObjectClass<T>;}interface WorkerStubEntrypointOptions {props?: any;+ limits?: workerdResourceLimits;}interface WorkerLoader {get(name: string | null, getCode: () => WorkerLoaderWorkerCode | Promise<WorkerLoaderWorkerCode>): WorkerStub;@@ -3374,6 +3504,7 @@ interface WorkerLoaderWorkerCode {compatibilityDate: string;compatibilityFlags?: string[];allowExperimental?: boolean;+ limits?: workerdResourceLimits;mainModule: string;modules: Record<string, WorkerLoaderModule | string>;env?: any;@@ -3381,6 +3512,10 @@ interface WorkerLoaderWorkerCode {tails?: Fetcher[];streamingTails?: Fetcher[];}+interface workerdResourceLimits {+ cpuMs?: number;+ subRequests?: number;+}/*** The Workers runtime supports a subset of the Performance API, used to measure timing and performance,* as well as timing of subrequests and other operations.@@ -3399,78 +3534,414 @@ declare abstract class Performance {*/toJSON(): object;}+interface Tracing {+ enterSpan<T, A extends unknown[]>(name: string, callback: (span: Span, ...args: A) => T, ...args: A): T;+ startActiveSpan<T, A extends unknown[]>(name: string, callback: (span: Span, ...args: A) => T, ...args: A): T;+ Span: typeof Span;+}+declare abstract class Span {+ get isTraced(): boolean;+ setAttribute(key: string, value?: (boolean | number | string)): void;+ end(): void;+}+/**+ * Represents the identity of a user authenticated via Cloudflare Access.+ * This matches the result of calling /cdn-cgi/access/get-identity.+ *+ * The exact structure of the returned object depends on the identity provider+ * configuration for the Access application. The fields below represent commonly+ * available properties, but additional provider-specific fields may be present.+ */+interface CloudflareAccessIdentity extends Record<string, unknown> {+ /** The user's email address, if available from the identity provider. */+ email?: string;+ /** The user's display name. */+ name?: string;+ /** The user's unique identifier. */+ user_uuid?: string;+ /** The Cloudflare account ID. */+ account_id?: string;+ /** Login timestamp (Unix epoch seconds). */+ iat?: number;+ /** The user's IP address at authentication time. */+ ip?: string;+ /** Authentication methods used (e.g., "pwd"). */+ amr?: string[];+ /** Identity provider information. */+ idp?: {+ id: string;+ type: string;+ };+ /** Geographic information about where the user authenticated. */+ geo?: {+ country: string;+ };+ /** Group memberships from the identity provider. */+ groups?: Array<{+ id: string;+ name: string;+ email?: string;+ }>;+ /** Device posture check results, keyed by check ID. */+ devicePosture?: Record<string, unknown>;+ /** True if the user connected via Cloudflare WARP. */+ is_warp?: boolean;+ /** True if the user is authenticated via Cloudflare Gateway. */+ is_gateway?: boolean;+}+// ============================================================================+// Agent Memory+//+// Public type surface for user Workers binding to an Agent Memory namespace.+// ============================================================================+/** Memory type — every memory is classified into exactly one. */+type AgentMemoryMemoryType = "fact" | "event" | "instruction" | "task";+/** Search intensity for recall. */+type AgentMemoryThinkingLevel = "low" | "medium" | "high";+/** Response verbosity for recall. */+type AgentMemoryResponseLength = "short" | "medium" | "long";+/** A conversation message passed to ingest(). */+interface AgentMemoryMessage {+ role: "system" | "user" | "assistant";+ content: string;+ /** Optional message timestamp. */+ timestamp?: Date;+}+/** Raw memory content passed to remember(). */+interface AgentMemoryIncomingMemory {+ /** Raw memory content. The service classifies and summarizes automatically. */+ content: string;+ /** Optional session identifier to associate with this memory. */+ sessionId?: string | null | undefined;+}+/** A stored memory returned from remember(), get(), and delete(). */+interface AgentMemoryMemory {+ /** Memory ID. */+ id: string;+ /** Memory type. */+ type: AgentMemoryMemoryType;+ /** Text summary. */+ summary: string;+ /** Memory text. */+ content: string;+ /** Session that created this memory. */+ sessionId: string | null;+ /** Memory creation time. */+ createdAt: Date;+ /** Memory last-update time. */+ updatedAt: Date;+}+/** Single entry in a list() response. Same shape as Memory minus full content. */+type AgentMemoryMemoryListEntry = Omit<AgentMemoryMemory, "content">;+/** A scored memory candidate in a recall result. */+interface AgentMemoryScoredCandidate {+ /** Candidate ID. */+ id: string;+ /** Text summary. */+ summary: string;+ /** Session that created this candidate, when known. */+ sessionId: string | null;+ /** Relevance score (higher is better). Comparable only within a single query. */+ score: number;+}+/** Options for the ingest() method. */+interface AgentMemoryIngestOptions {+ /** Session identifier to associate with memories created during ingestion. */+ sessionId?: string | null | undefined;+}+/** Options for the getSummary() method. */+interface AgentMemoryGetSummaryOptions {+ /** Session identifier to retrieve session summary for. */+ sessionId?: string | null | undefined;+}+/** Response from the getSummary() method. */+interface AgentMemoryGetSummaryResponse {+ /** Markdown summary. */+ summary: string;+}+/**+ * Options for the recall() method.+ *+ * `referenceDate` accepts a Date object, an ISO-8601 date string+ * (YYYY-MM-DD), or a full ISO-8601 datetime string. When provided, this+ * date is used as "today" for resolving relative time references+ * ("how many days ago", "last week") instead of the server's wall-clock time.+ */+interface AgentMemoryRecallOptions {+ /** Recall intensity: "low" (default), "medium", or "high". */+ thinkingLevel?: AgentMemoryThinkingLevel;+ /** Response verbosity: "short", "medium" (default), or "long". */+ responseLength?: AgentMemoryResponseLength;+ /** Temporal anchor for date arithmetic. */+ referenceDate?: Date | string;+}+/** Response from the recall() method. */+interface AgentMemoryRecallResult {+ /** Number of memories retrieved. */+ count: number;+ /** LLM-generated answer synthesizing the matching memories. */+ answer: string;+ /** Matching memories ranked by relevance. */+ candidates: AgentMemoryScoredCandidate[];+}+/**+ * Options for the list() method.+ *+ * `cursor` is the opaque continuation token returned by the previous page;+ * pass it back unchanged to fetch the next page. `sessionId` and `type`+ * are exact-match filters; combining them is allowed.+ */+interface AgentMemoryListMemoriesOptions {+ /** Maximum number of memories to return. Default 20, max 500. */+ limit?: number;+ /** Opaque cursor from a previous page. */+ cursor?: string;+ /** Exact-match session filter. */+ sessionId?: string;+ /** Exact-match memory-type filter. */+ type?: AgentMemoryMemoryType;+}+/** Response from the list() method. */+interface AgentMemoryListMemoriesResult {+ memories: AgentMemoryMemoryListEntry[];+ /** Continuation cursor; absent when this page exhausted the result set. */+ cursor?: string;+}+/**+ * A single Agent Memory profile, scoped to a profile name.+ *+ * Returned by {@link AgentMemoryNamespace.getProfile}.+ */+declare abstract class AgentMemoryProfile {+ /**+ * Retrieve a memory by ID.+ *+ * @param memoryId - ULID of the memory to retrieve.+ * @throws if the memory does not exist.+ */+ get(memoryId: string): Promise<AgentMemoryMemory>;+ /**+ * Delete a memory by ID.+ *+ * Removes the memory and any source messages linked by the memory's+ * source message IDs.+ *+ * @param memoryId - ULID of the memory to delete.+ * @throws if the memory does not exist.+ */+ delete(memoryId: string): Promise<AgentMemoryMemory>;+ /**+ * Store a memory in this profile. The content is automatically classified,+ * summarized, and indexed.+ *+ * @param memory - Raw memory content to persist.+ */+ remember(memory: AgentMemoryIncomingMemory): Promise<AgentMemoryMemory>;+ /**+ * Extract memories from a conversation.+ *+ * @param messages - Conversation messages to extract memories from.+ * @param options - Optional ingest options.+ */+ ingest(messages: Iterable<AgentMemoryMessage>, options?: AgentMemoryIngestOptions): Promise<void>;+ /**+ * Get a profile summary.+ *+ * @param options - Optional getSummary options.+ */+ getSummary(options?: AgentMemoryGetSummaryOptions): Promise<AgentMemoryGetSummaryResponse>;+ /**+ * Recall memories in this profile.+ *+ * @param query - Recall query matched against memory content and keywords.+ * @param options - Optional recall parameters.+ * @returns Matching memories with relevance scores and a synthesized answer.+ */+ recall(query: string, options?: AgentMemoryRecallOptions): Promise<AgentMemoryRecallResult>;+ /**+ * List active memories in this profile.+ *+ * Returns a paginated, filterable view of stored memories. Superseded+ * versions are excluded. Use the returned `cursor` (when present) to+ * fetch the next page.+ *+ * @param options - Optional pagination and filter options.+ */+ list(options?: AgentMemoryListMemoriesOptions): Promise<AgentMemoryListMemoriesResult>;+ /**+ * Soft-delete every memory and message in this profile that is tagged+ * with `sessionId`.+ *+ * Idempotent: deleting a sessionId that has no rows is a no-op.+ *+ * @param sessionId - Session to delete.+ */+ deleteSession(sessionId: string): Promise<void>;+}+/**+ * Namespace-level Agent Memory binding.+ *+ * Used as the type of an `env.MEMORY`-style binding backed by the Agent+ * Memory product.+ *+ * @example+ * ```ts+ * export default {+ * async fetch(_request: Request, env: Env): Promise<Response> {+ * const profile = await env.MEMORY.getProfile("wrangler-e2e");+ * const summary = await profile.getSummary();+ * return Response.json(summary);+ * },+ * };+ * ```+ */+declare abstract class AgentMemoryNamespace {+ /**+ * Get a memory profile by name. Profiles are isolated by namespace and+ * addressed by a compound key (namespaceId:profileName).+ *+ * @param profileName - Profile name (validated against naming rules).+ * @returns RPC target for interacting with the profile.+ */+ getProfile(profileName: string): Promise<AgentMemoryProfile>;+ /**+ * Soft-delete a profile and schedule deferred purge. Marks all+ * memories and messages as deleted.+ *+ * @param profileName - Name of the profile to delete.+ */+ deleteProfile(profileName: string): Promise<void>;+}// ============ AI Search Error Interfaces ============interface AiSearchInternalError extends Error {}interface AiSearchNotFoundError extends Error {}-// ============ AI Search Request Types ============-type AiSearchSearchRequest = {- messages: Array<{- role: 'system' | 'developer' | 'user' | 'assistant' | 'tool';- content: string | null;- }>;- ai_search_options?: {- retrieval?: {- retrieval_type?: 'vector' | 'keyword' | 'hybrid';- /** Match threshold (0-1, default 0.4) */- match_threshold?: number;- /** Maximum number of results (1-50, default 10) */- max_num_results?: number;- filters?: VectorizeVectorMetadataFilter;- /** Context expansion (0-3, default 0) */- context_expansion?: number;- [key: string]: unknown;- };- query_rewrite?: {- enabled?: boolean;- model?: string;- rewrite_prompt?: string;- [key: string]: unknown;- };- reranking?: {- enabled?: boolean;- model?: '@cf/baai/bge-reranker-base' | string;- /** Match threshold (0-1, default 0.4) */- match_threshold?: number;- [key: string]: unknown;- };+// ============ AI Search Common Types ============+/** A single message in a conversation-style search or chat request. */+type AiSearchMessage = {+ role: 'system' | 'developer' | 'user' | 'assistant' | 'tool';+ content: string | null;+};+/**+ * Common shape for `ai_search_options` used by both single-instance and multi-instance requests.+ * Contains retrieval, query rewrite, reranking, and cache sub-options.+ */+type AiSearchOptions = {+ retrieval?: {+ /** Which retrieval backend to use. Defaults to the instance's configured index_method. */+ retrieval_type?: 'vector' | 'keyword' | 'hybrid';+ /** Fusion method for combining vector + keyword results. */+ fusion_method?: 'max' | 'rrf';+ /** How keyword terms are combined: "and" = all terms must match, "or" = any term matches. */+ keyword_match_mode?: 'and' | 'or';+ /** Minimum similarity score (0-1) for a result to be included. Default 0.4. */+ match_threshold?: number;+ /** Maximum number of results to return (1-50). Default 10. */+ max_num_results?: number;+ /** Vectorize metadata filters applied to the search. */+ filters?: VectorizeVectorMetadataFilter;+ /** Number of surrounding chunks to include for context (0-3). Default 0. */+ context_expansion?: number;+ /** If true, return only item metadata without chunk text. */+ metadata_only?: boolean;+ /** If true (default), return empty results on retrieval failure instead of throwing. */+ return_on_failure?: boolean;+ /** Boost results by metadata field values. Max 3 entries. */+ boost_by?: Array<{+ field: string;+ direction?: 'asc' | 'desc' | 'exists' | 'not_exists';+ }>;+ [key: string]: unknown;+ };+ query_rewrite?: {+ enabled?: boolean;+ model?: string;+ rewrite_prompt?: string;+ [key: string]: unknown;+ };+ reranking?: {+ enabled?: boolean;+ model?: string;+ /** Match threshold (0-1, default 0.4) */+ match_threshold?: number;[key: string]: unknown;};+ cache?: {+ enabled?: boolean;+ cache_threshold?: 'super_strict_match' | 'close_enough' | 'flexible_friend' | 'anything_goes';+ };+ [key: string]: unknown;+};+// ============ AI Search Request Types ============+/**+ * Request body for single-instance search.+ * Exactly one of `query` or `messages` must be provided.+ */+type AiSearchSearchRequest = {+ /** Simple query string. */+ query: string;+ messages?: never;+ ai_search_options?: AiSearchOptions;+} | {+ query?: never;+ /** Conversation-style input. At least one user message with non-empty content is required. */+ messages: AiSearchMessage[];+ ai_search_options?: AiSearchOptions;};type AiSearchChatCompletionsRequest = {- messages: Array<{- role: 'system' | 'developer' | 'user' | 'assistant' | 'tool';- content: string | null;- [key: string]: unknown;- }>;+ messages: AiSearchMessage[];model?: string;stream?: boolean;- ai_search_options?: {- retrieval?: {- retrieval_type?: 'vector' | 'keyword' | 'hybrid';- match_threshold?: number;- max_num_results?: number;- filters?: VectorizeVectorMetadataFilter;- context_expansion?: number;- [key: string]: unknown;- };- query_rewrite?: {- enabled?: boolean;- model?: string;- rewrite_prompt?: string;- [key: string]: unknown;- };- reranking?: {- enabled?: boolean;- model?: '@cf/baai/bge-reranker-base' | string;- match_threshold?: number;- [key: string]: unknown;- };- [key: string]: unknown;- };+ ai_search_options?: AiSearchOptions;[key: string]: unknown;};+// ============ AI Search Multi-Instance Types (Namespace-Scoped) ============+/** `ai_search_options` shape for multi-instance requests — requires `instance_ids`. */+type AiSearchMultiSearchOptions = AiSearchOptions & {+ /** Instance IDs to search across (1-10). */+ instance_ids: string[];+};+/**+ * Request for searching across multiple instances within a namespace.+ * `ai_search_options` is required and must include `instance_ids`.+ * Exactly one of `query` or `messages` must be provided.+ */+type AiSearchMultiSearchRequest = {+ /** Simple query string. */+ query: string;+ messages?: never;+ ai_search_options: AiSearchMultiSearchOptions;+} | {+ query?: never;+ /** Conversation-style input. */+ messages: AiSearchMessage[];+ ai_search_options: AiSearchMultiSearchOptions;+};+/** A search result chunk tagged with the instance it originated from. */+type AiSearchMultiSearchChunk = AiSearchSearchResponse['chunks'][number] & {+ instance_id: string;+};+/** Describes a per-instance error during a multi-instance operation. */+type AiSearchMultiSearchError = {+ instance_id: string;+ message: string;+};+/** Response from a multi-instance search, with chunks tagged by instance and optional partial-failure errors. */+type AiSearchMultiSearchResponse = {+ search_query: string;+ chunks: AiSearchMultiSearchChunk[];+ errors?: AiSearchMultiSearchError[];+};+/** Request for chat completions across multiple instances within a namespace. `ai_search_options` is required and must include `instance_ids`. */+type AiSearchMultiChatCompletionsRequest = Omit<AiSearchChatCompletionsRequest, 'ai_search_options'> & {+ ai_search_options: AiSearchMultiSearchOptions;+};+/** Response from multi-instance chat completions, with chunks tagged by instance and optional partial-failure errors. */+type AiSearchMultiChatCompletionsResponse = Omit<AiSearchChatCompletionsResponse, 'chunks'> & {+ chunks: AiSearchMultiSearchChunk[];+ errors?: AiSearchMultiSearchError[];+};// ============ AI Search Response Types ============type AiSearchSearchResponse = {search_query: string;@@ -3490,6 +3961,14 @@ type AiSearchSearchResponse = {keyword_score?: number;/** Vector similarity score (0-1) */vector_score?: number;+ /** Keyword rank position */+ keyword_rank?: number;+ /** Vector rank position */+ vector_rank?: number;+ /** Reranking model score */+ reranking_score?: number;+ /** Fusion method used to combine results */+ fusion_method?: 'rrf' | 'max';[key: string]: unknown;};}>;@@ -3518,19 +3997,84 @@ type AiSearchStatsResponse = {skipped?: number;outdated?: number;last_activity?: string;+ /** Storage engine statistics. */+ engine?: {+ vectorize?: {+ vectorsCount: number;+ dimensions: number;+ };+ r2?: {+ payloadSizeBytes: number;+ metadataSizeBytes: number;+ objectCount: number;+ };+ };};// ============ AI Search Instance Info Types ============type AiSearchInstanceInfo = {id: string;type?: 'r2' | 'web-crawler' | string;source?: string;+ source_params?: unknown;paused?: boolean;status?: string;namespace?: string;created_at?: string;modified_at?: string;+ token_id?: string;+ ai_gateway_id?: string;+ rewrite_query?: boolean;+ reranking?: boolean;+ embedding_model?: string;+ ai_search_model?: string;+ rewrite_model?: string;+ reranking_model?: string;+ /** @deprecated Use index_method instead. */+ hybrid_search_enabled?: boolean;+ /** Controls which storage backends are active. */+ index_method?: {+ vector?: boolean;+ keyword?: boolean;+ };+ /** Fusion method for combining vector and keyword results. */+ fusion_method?: 'max' | 'rrf';+ indexing_options?: {+ keyword_tokenizer?: 'porter' | 'trigram';+ } | null;+ retrieval_options?: {+ keyword_match_mode?: 'and' | 'or';+ boost_by?: Array<{+ field: string;+ direction?: 'asc' | 'desc' | 'exists' | 'not_exists';+ }>;+ } | null;+ chunk?: boolean;+ chunk_size?: number;+ chunk_overlap?: number;+ score_threshold?: number;+ max_num_results?: number;+ cache?: boolean;+ cache_threshold?: 'super_strict_match' | 'close_enough' | 'flexible_friend' | 'anything_goes';+ custom_metadata?: Array<{+ field_name: string;+ data_type: 'text' | 'number' | 'boolean' | 'datetime';+ }>;+ /** Sync interval in seconds. */+ sync_interval?: 3600 | 7200 | 14400 | 21600 | 43200 | 86400;+ metadata?: Record<string, unknown>;[key: string]: unknown;};+/** Pagination, search, and ordering parameters for listing instances within a namespace. */+type AiSearchListInstancesParams = {+ page?: number;+ per_page?: number;+ /** Search instances by ID. */+ search?: string;+ /** Field to sort by. */+ order_by?: 'created_at';+ /** Sort direction. */+ order_by_direction?: 'asc' | 'desc';+};type AiSearchListResponse = {result: AiSearchInstanceInfo[];result_info?: {@@ -3558,13 +4102,60 @@ type AiSearchConfig = {reranking?: boolean;embedding_model?: string;ai_search_model?: string;+ rewrite_model?: string;+ reranking_model?: string;+ /** @deprecated Use index_method instead. */+ hybrid_search_enabled?: boolean;+ /** Controls which storage backends are used during indexing. Defaults to vector-only. */+ index_method?: {+ vector?: boolean;+ keyword?: boolean;+ };+ /** Fusion method for combining vector and keyword results. "rrf" = reciprocal rank fusion (default), "max" = maximum score. */+ fusion_method?: 'max' | 'rrf';+ indexing_options?: {+ keyword_tokenizer?: 'porter' | 'trigram';+ } | null;+ retrieval_options?: {+ keyword_match_mode?: 'and' | 'or';+ boost_by?: Array<{+ field: string;+ direction?: 'asc' | 'desc' | 'exists' | 'not_exists';+ }>;+ } | null;+ chunk?: boolean;+ chunk_size?: number;+ chunk_overlap?: number;+ /** Minimum similarity score (0-1) for a result to be included. */+ score_threshold?: number;+ max_num_results?: number;+ cache?: boolean;+ /** Similarity threshold for cache hits. Stricter = fewer cache hits but higher relevance. */+ cache_threshold?: 'super_strict_match' | 'close_enough' | 'flexible_friend' | 'anything_goes';+ custom_metadata?: Array<{+ field_name: string;+ data_type: 'text' | 'number' | 'boolean' | 'datetime';+ }>;+ namespace?: string;+ /** Sync interval in seconds. 3600=1h, 7200=2h, 14400=4h, 21600=6h, 43200=12h, 86400=24h. */+ sync_interval?: 3600 | 7200 | 14400 | 21600 | 43200 | 86400;+ metadata?: Record<string, unknown>;[key: string]: unknown;};// ============ AI Search Item Types ============type AiSearchItemInfo = {id: string;key: string;- status: 'completed' | 'error' | 'skipped' | 'queued' | 'processing' | 'outdated';+ status: 'completed' | 'error' | 'skipped' | 'queued' | 'running' | 'outdated';+ next_action?: 'INDEX' | 'DELETE' | null;+ error?: string;+ checksum?: string;+ namespace?: string;+ chunks_count?: number | null;+ file_size?: number | null;+ source_id?: string | null;+ last_seen_at?: string;+ created_at?: string;metadata?: Record<string, unknown>;[key: string]: unknown;};@@ -3580,6 +4171,16 @@ type AiSearchUploadItemOptions = {type AiSearchListItemsParams = {page?: number;per_page?: number;+ /** Search items by key name. */+ search?: string;+ /** Sort order for results. */+ sort_by?: 'status' | 'modified_at';+ /** Filter items by processing status. */+ status?: 'queued' | 'running' | 'completed' | 'error' | 'skipped' | 'outdated';+ /** Filter items by source (e.g. "builtin" or "web-crawler:https://example.com"). */+ source?: string;+ /** JSON-encoded Vectorize filter for metadata filtering. */+ metadata_filter?: string;};type AiSearchListItemsResponse = {result: AiSearchItemInfo[];@@ -3590,6 +4191,61 @@ type AiSearchListItemsResponse = {total_count: number;};};+// ============ AI Search Item Logs Types ============+type AiSearchItemLogsParams = {+ /** Maximum number of log entries to return (1-100, default 50). */+ limit?: number;+ /** Opaque cursor for pagination. Pass the `cursor` value from a previous response. */+ cursor?: string;+};+type AiSearchItemLog = {+ timestamp: string;+ action: string;+ message: string;+ fileKey?: string;+ chunkCount?: number;+ processingTimeMs?: number;+ errorType?: string;+};+/** Paginated response for item processing logs (cursor-based). */+type AiSearchItemLogsResponse = {+ result: AiSearchItemLog[];+ result_info: {+ count: number;+ per_page: number;+ cursor: string | null;+ truncated: boolean;+ };+};+// ============ AI Search Item Chunks Types ============+type AiSearchItemChunksParams = {+ /** Maximum number of chunks to return (1-100, default 20). */+ limit?: number;+ /** Offset into the chunks list (default 0). */+ offset?: number;+};+/** A single indexed chunk belonging to an item, including its text content and byte range. */+type AiSearchItemChunk = {+ id: string;+ text: string;+ start_byte: number;+ end_byte: number;+ item?: {+ timestamp?: number;+ key: string;+ metadata?: Record<string, unknown>;+ };+};+/** Paginated response for item chunks (offset-based). */+type AiSearchItemChunksResponse = {+ result: AiSearchItemChunk[];+ result_info: {+ count: number;+ total: number;+ limit: number;+ offset: number;+ };+};// ============ AI Search Job Types ============type AiSearchJobInfo = {id: string;@@ -3638,7 +4294,7 @@ type AiSearchJobLogsResponse = {// ============ AI Search Sub-Service Classes ============/*** Single item service for an AI Search instance.- * Provides info, delete, and download operations on a specific item.+ * Provides info, download, sync, logs, and chunks operations on a specific item.*/declare abstract class AiSearchItem {/** Get metadata about this item. */@@ -3648,6 +4304,23 @@ declare abstract class AiSearchItem {* @returns Object with body stream, content type, filename, and size.*/download(): Promise<AiSearchItemContentResult>;+ /**+ * Trigger re-indexing of this item.+ * @returns The updated item info.+ */+ sync(): Promise<AiSearchItemInfo>;+ /**+ * Retrieve processing logs for this item (cursor-based pagination).+ * @param params Optional pagination parameters (limit, cursor).+ * @returns Paginated log entries for this item.+ */+ logs(params?: AiSearchItemLogsParams): Promise<AiSearchItemLogsResponse>;+ /**+ * List indexed chunks for this item (offset-based pagination).+ * @param params Optional pagination parameters (limit, offset).+ * @returns Paginated chunk entries for this item.+ */+ chunks(params?: AiSearchItemChunksParams): Promise<AiSearchItemChunksResponse>;}/*** Items collection service for an AI Search instance.@@ -3657,41 +4330,56 @@ declare abstract class AiSearchItems {/** List items in this instance. */list(params?: AiSearchListItemsParams): Promise<AiSearchListItemsResponse>;/**- * Upload a file as an item.+ * Upload a file as an item. Behaves as an upsert: if an item with the same+ * filename already exists, it is overwritten and re-indexed.* @param name Filename for the uploaded item.- * @param content File content as a ReadableStream, ArrayBuffer, or string.+ * @param content File content as a ReadableStream, Blob, or string.* @param options Optional metadata to attach to the item.* @returns The created item info.*/- upload(name: string, content: ReadableStream | ArrayBuffer | string, options?: AiSearchUploadItemOptions): Promise<AiSearchItemInfo>;+ upload(name: string, content: ReadableStream | Blob | string, options?: AiSearchUploadItemOptions): Promise<AiSearchItemInfo>;/*** Upload a file and poll until processing completes.+ * Behaves as an upsert: if an item with the same filename already exists,+ * it is overwritten and re-indexed.* @param name Filename for the uploaded item.- * @param content File content as a ReadableStream, ArrayBuffer, or string.- * @param options Optional metadata to attach to the item.+ * @param content File content as a ReadableStream, Blob, or string.+ * @param options Optional metadata and polling configuration.* @returns The item info after processing completes (or timeout).*/- uploadAndPoll(name: string, content: ReadableStream | ArrayBuffer | string, options?: AiSearchUploadItemOptions): Promise<AiSearchItemInfo>;+ uploadAndPoll(name: string, content: ReadableStream | Blob | string, options?: AiSearchUploadItemOptions & {+ /** Polling interval in milliseconds (default 1000). */+ pollIntervalMs?: number;+ /** Maximum time to wait in milliseconds (default 30000). */+ timeoutMs?: number;+ }): Promise<AiSearchItemInfo>;/*** Get an item by ID.* @param itemId The item identifier.- * @returns Item service for info, delete, and download operations.+ * @returns Item service for info, download, sync, logs, and chunks operations.*/get(itemId: string): AiSearchItem;- /** Delete this item from the instance.+ /**+ * Delete an item from the instance.* @param itemId The item identifier.*/delete(itemId: string): Promise<void>;}/*** Single job service for an AI Search instance.- * Provides info and logs for a specific job.+ * Provides info, logs, and cancel operations for a specific job.*/declare abstract class AiSearchJob {/** Get metadata about this job. */info(): Promise<AiSearchJobInfo>;/** Get logs for this job. */logs(params?: AiSearchJobLogsParams): Promise<AiSearchJobLogsResponse>;+ /**+ * Cancel a running job.+ * @returns The updated job info.+ * @throws AiSearchNotFoundError if the job does not exist.+ */+ cancel(): Promise<AiSearchJobInfo>;}/*** Jobs collection service for an AI Search instance.@@ -3709,7 +4397,7 @@ declare abstract class AiSearchJobs {/*** Get a job by ID.* @param jobId The job identifier.- * @returns Job service for info and logs operations.+ * @returns Job service for info, logs, and cancel operations.*/get(jobId: string): AiSearchJob;}@@ -3728,7 +4416,7 @@ declare abstract class AiSearchJobs {* // Via namespace binding* const instance = env.AI_SEARCH.get("blog");* const results = await instance.search({- * messages: [{ role: "user", content: "How does caching work?" }],+ * query: "How does caching work?",* });** // Via single instance binding@@ -3740,7 +4428,7 @@ declare abstract class AiSearchJobs {declare abstract class AiSearchInstance {/*** Search the AI Search instance for relevant chunks.- * @param params Search request with messages and optional AI search options.+ * @param params Search request with query or messages and optional AI search options.* @returns Search response with matching chunks and search query.*/search(params: AiSearchSearchRequest): Promise<AiSearchSearchResponse>;@@ -3768,7 +4456,7 @@ declare abstract class AiSearchInstance {info(): Promise<AiSearchInstanceInfo>;/*** Get instance statistics (item count, indexing status, etc.).- * @returns Statistics with counts per status and last activity time.+ * @returns Statistics with counts per status, last activity time, and engine details.*/stats(): Promise<AiSearchStatsResponse>;/** Items collection — list, upload, and manage items in this instance. */@@ -3780,27 +4468,30 @@ declare abstract class AiSearchInstance {* Namespace-level AI Search service.** Used as the type of `env.AI_SEARCH` (namespace binding via `ai_search_namespaces`).- * Scoped to a single namespace. Provides dynamic instance access, creation, and deletion.+ * Scoped to a single namespace. Provides dynamic instance access, creation, deletion,+ * and multi-instance search/chat operations.** @example* ```ts* // Access an instance within the namespace* const blog = env.AI_SEARCH.get("blog");- * const results = await blog.search({- * messages: [{ role: "user", content: "How does caching work?" }],- * });+ * const results = await blog.search({ query: "How does caching work?" });** // List all instances in the namespace* const instances = await env.AI_SEARCH.list();** // Create a new instance with built-in storage- * const tenant = await env.AI_SEARCH.create({- * id: "tenant-123",- * });+ * const tenant = await env.AI_SEARCH.create({ id: "tenant-123" });** // Upload items into the instance* await tenant.items.upload("doc.pdf", fileContent);*+ * // Search across multiple instances+ * const multi = await env.AI_SEARCH.search({+ * query: "caching",+ * ai_search_options: { instance_ids: ["blog", "docs"] },+ * });+ ** // Delete an instance* await env.AI_SEARCH.delete("tenant-123");* ```@@ -3813,10 +4504,11 @@ declare abstract class AiSearchNamespace {*/get(name: string): AiSearchInstance;/**- * List all instances in the bound namespace.- * @returns Array of instance metadata.+ * List instances in the bound namespace.+ * @param params Optional pagination, search, and ordering parameters.+ * @returns Array of instance metadata with pagination info.*/- list(): Promise<AiSearchListResponse>;+ list(params?: AiSearchListInstancesParams): Promise<AiSearchListResponse>;/*** Create a new instance within the bound namespace.* @param config Instance configuration. Only `id` is required — omit `type` and `source` to create with built-in storage.@@ -3841,6 +4533,29 @@ declare abstract class AiSearchNamespace {* @param name Instance name to delete.*/delete(name: string): Promise<void>;+ /**+ * Search across multiple instances within the bound namespace.+ * Fans out to the specified instance_ids and merges results.+ * @param params Search request with required `ai_search_options.instance_ids`.+ * @returns Search response with chunks tagged by instance_id and optional partial-failure errors.+ */+ search(params: AiSearchMultiSearchRequest): Promise<AiSearchMultiSearchResponse>;+ /**+ * Generate chat completions across multiple instances within the bound namespace (streaming).+ * Fans out to the specified instance_ids, merges context, and generates a response.+ * @param params Chat completions request with stream: true and required `ai_search_options.instance_ids`.+ * @returns ReadableStream of server-sent events.+ */+ chatCompletions(params: AiSearchMultiChatCompletionsRequest & {+ stream: true;+ }): Promise<ReadableStream>;+ /**+ * Generate chat completions across multiple instances within the bound namespace.+ * Fans out to the specified instance_ids, merges context, and generates a response.+ * @param params Chat completions request with required `ai_search_options.instance_ids`.+ * @returns Chat completion response with choices, chunks tagged by instance_id, and optional partial-failure errors.+ */+ chatCompletions(params: AiSearchMultiChatCompletionsRequest): Promise<AiSearchMultiChatCompletionsResponse>;}type AiImageClassificationInput = {image: number[];@@ -4442,9 +5157,6 @@ type ChatCompletionChoice = {finish_reason: "stop" | "length" | "tool_calls" | "content_filter" | "function_call";logprobs: ChatCompletionLogprobs | null;};-type ChatCompletionsPromptInput = {- prompt: string;-} & ChatCompletionsCommonOptions;type ChatCompletionsMessagesInput = {messages: Array<ChatCompletionMessageParam>;} & ChatCompletionsCommonOptions;@@ -8374,11 +9086,11 @@ declare abstract class Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2 {postProcessedOutputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output;}declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_120B {- inputs: XOR<ResponsesInput, ChatCompletionsInput>;+ inputs: XOR<ResponsesInput, ChatCompletionsMessagesInput>;postProcessedOutputs: XOR<ResponsesOutput, ChatCompletionsOutput>;}declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_20B {- inputs: XOR<ResponsesInput, ChatCompletionsInput>;+ inputs: XOR<ResponsesInput, ChatCompletionsMessagesInput>;postProcessedOutputs: XOR<ResponsesOutput, ChatCompletionsOutput>;}interface Ai_Cf_Leonardo_Phoenix_1_0_Input {@@ -9354,10 +10066,18 @@ declare abstract class Base_Ai_Cf_Moonshotai_Kimi_K2_5 {inputs: ChatCompletionsInput;postProcessedOutputs: ChatCompletionsOutput;}+declare abstract class Base_Ai_Cf_Moonshotai_Kimi_K2_6 {+ inputs: ChatCompletionsInput;+ postProcessedOutputs: ChatCompletionsOutput;+}declare abstract class Base_Ai_Cf_Nvidia_Nemotron_3_120B_A12B {inputs: ChatCompletionsInput;postProcessedOutputs: ChatCompletionsOutput;}+declare abstract class Base_Ai_Cf_Google_Gemma_4_26B_A4B_IT {+ inputs: ChatCompletionsInput;+ postProcessedOutputs: ChatCompletionsOutput;+}interface AiModels {"@cf/huggingface/distilbert-sst-2-int8": BaseAiTextClassification;"@cf/stabilityai/stable-diffusion-xl-base-1.0": BaseAiTextToImage;@@ -9447,7 +10167,9 @@ interface AiModels {"@cf/black-forest-labs/flux-2-klein-9b": Base_Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B;"@cf/zai-org/glm-4.7-flash": Base_Ai_Cf_Zai_Org_Glm_4_7_Flash;"@cf/moonshotai/kimi-k2.5": Base_Ai_Cf_Moonshotai_Kimi_K2_5;+ "@cf/moonshotai/kimi-k2.6": Base_Ai_Cf_Moonshotai_Kimi_K2_6;"@cf/nvidia/nemotron-3-120b-a12b": Base_Ai_Cf_Nvidia_Nemotron_3_120B_A12B;+ "@cf/google/gemma-4-26b-a4b-it": Base_Ai_Cf_Google_Gemma_4_26B_A4B_IT;}type AiOptions = {/**@@ -9500,15 +10222,16 @@ type AiModelsSearchObject = {value: string;}[];};-type ChatCompletionsBase = XOR<ChatCompletionsPromptInput, ChatCompletionsMessagesInput>;-type ChatCompletionsInput = XOR<ChatCompletionsBase, {- requests: ChatCompletionsBase[];-}>;+type ChatCompletionsBase = ChatCompletionsMessagesInput;+type ChatCompletionsInput = ChatCompletionsMessagesInput;interface InferenceUpstreamError extends Error {}interface AiInternalError extends Error {}type AiModelListType = Record<string, any>;+type AiAsyncBatchResponse = {+ request_id: string;+};declare abstract class Ai<AiModelList extends AiModelListType = AiModels> {aiGatewayLogId: string | null;gateway(gatewayId: string): AiGateway;@@ -9525,13 +10248,35 @@ declare abstract class Ai<AiModelList extends AiModelListType = AiModels> {* @param autoragId Instance ID*/autorag(autoragId: string): AutoRAG;- run<Name extends keyof AiModelList, Options extends AiOptions, InputOptions extends AiModelList[Name]["inputs"]>(model: Name, inputs: InputOptions, options?: Options): Promise<Options extends {+ // Batch request+ run<Name extends keyof AiModelList>(model: Name, inputs: {+ requests: AiModelList[Name]['inputs'][];+ }, options: AiOptions & {+ queueRequest: true;+ }): Promise<AiAsyncBatchResponse>;+ // Raw response+ run<Name extends keyof AiModelList>(model: Name, inputs: AiModelList[Name]['inputs'], options: AiOptions & {returnRawResponse: true;- } | {+ }): Promise<Response>;+ // WebSocket+ run<Name extends keyof AiModelList>(model: Name, inputs: AiModelList[Name]['inputs'], options: AiOptions & {websocket: true;- } ? Response : InputOptions extends {+ }): Promise<Response>;+ // Streaming+ run<Name extends keyof AiModelList>(model: Name, inputs: AiModelList[Name]['inputs'] & {stream: true;- } ? ReadableStream : AiModelList[Name]["postProcessedOutputs"]>;+ }, options?: AiOptions): Promise<ReadableStream>;+ // Normal (default) - known model+ run<Name extends keyof AiModelList>(model: Name, inputs: AiModelList[Name]['inputs'], options?: AiOptions): Promise<AiModelList[Name]['postProcessedOutputs']>;+ // Unknown model (fallback).+ //+ // The `Exclude<..., keyof AiModelList>` constraint forces TypeScript to+ // route any model name that is a literal key of `AiModelList` to one of+ // the known-model overloads above (so input/output mismatches surface as+ // type errors rather than silently falling back to `Record<string, unknown>`).+ // Names that aren't in `AiModelList` — e.g. third-party gateway models+ // like `"google/nano-banana"` — still hit this overload.+ run<Model extends string>(model: Model extends keyof AiModelList ? never : Model, inputs: Record<string, unknown>, options?: AiOptions): Promise<Record<string, unknown>>;models(params?: AiModelsSearchParams): Promise<AiModelsSearchObject[]>;toMarkdown(): ToMarkdownService;toMarkdown(files: MarkdownDocument[], options?: ConversionRequestOptions): Promise<ConversionResponse[]>;@@ -9629,9 +10374,229 @@ declare abstract class AiGateway {run(data: AIGatewayUniversalRequest | AIGatewayUniversalRequest[], options?: {gateway?: UniversalGatewayOptions;extraHeaders?: object;+ signal?: AbortSignal;}): Promise<Response>;getUrl(provider?: AIGatewayProviders | string): Promise<string>; // eslint-disable-line}+// Copyright (c) 2022-2025 Cloudflare, Inc.+// Licensed under the Apache 2.0 license found in the LICENSE file or at:+// https://opensource.org/licenses/Apache-2.0+/**+ * Artifacts — Git-compatible file storage on Cloudflare Workers.+ *+ * Provides programmatic access to create, manage, and fork repositories,+ * and to issue and revoke scoped access tokens.+ */+/** Information about a repository. */+interface ArtifactsRepoInfo {+ /** Unique repository ID. */+ id: string;+ /** Repository name. */+ name: string;+ /** Repository description, or null if not set. */+ description: string | null;+ /** Default branch name (e.g. "main"). */+ defaultBranch: string;+ /** ISO 8601 creation timestamp. */+ createdAt: string;+ /** ISO 8601 last-updated timestamp. */+ updatedAt: string;+ /** ISO 8601 timestamp of the last push, or null if never pushed. */+ lastPushAt: string | null;+ /** Fork source (e.g. "github:owner/repo", "artifacts:namespace/repo"), or null if not a fork. */+ source: string | null;+ /** Whether the repository is read-only. */+ readOnly: boolean;+ /** HTTPS git remote URL. */+ remote: string;+}+/** Result of creating a repository — includes the initial access token. */+interface ArtifactsCreateRepoResult {+ /** Unique repository ID. */+ id: string;+ /** Repository name. */+ name: string;+ /** Repository description, or null if not set. */+ description: string | null;+ /** Default branch name. */+ defaultBranch: string;+ /** HTTPS git remote URL. */+ remote: string;+ /** Plaintext access token (only returned at creation time). */+ token: string;+ /** ISO 8601 token expiry timestamp. */+ tokenExpiresAt: string;+}+/** Paginated list of repositories. */+interface ArtifactsRepoListResult {+ /** Repositories in this page (without the `remote` field). */+ repos: Omit<ArtifactsRepoInfo, 'remote'>[];+ /** Total number of repositories in the namespace. */+ total: number;+ /** Cursor for the next page, if there are more results. */+ cursor?: string;+}+/** Result of creating an access token. */+interface ArtifactsCreateTokenResult {+ /** Unique token ID. */+ id: string;+ /** Plaintext token (only returned at creation time). */+ plaintext: string;+ /** Token scope: "read" or "write". */+ scope: 'read' | 'write';+ /** ISO 8601 token expiry timestamp. */+ expiresAt: string;+}+/** Token metadata (no plaintext). */+interface ArtifactsTokenInfo {+ /** Unique token ID. */+ id: string;+ /** Token scope: "read" or "write". */+ scope: 'read' | 'write';+ /** Token state: "active", "expired", or "revoked". */+ state: 'active' | 'expired' | 'revoked';+ /** ISO 8601 creation timestamp. */+ createdAt: string;+ /** ISO 8601 expiry timestamp. */+ expiresAt: string;+}+/** Paginated list of tokens for a repository. */+interface ArtifactsTokenListResult {+ /** Tokens in this page. */+ tokens: ArtifactsTokenInfo[];+ /** Total number of tokens for the repository. */+ total: number;+}+/**+ * Handle for a single repository. Returned by Artifacts.get().+ *+ * Methods may throw `ArtifactsError` with code `INTERNAL_ERROR` if an unexpected service error occurs.+ */+interface ArtifactsRepo extends ArtifactsRepoInfo {+ /**+ * Create an access token for this repo.+ * @param scope Token scope: "write" (default) or "read".+ * @param ttl Time-to-live in seconds (default 86400, min 60, max 31536000).+ * @throws {ArtifactsError} with code `INVALID_TTL` if ttl is out of range.+ */+ createToken(scope?: 'write' | 'read', ttl?: number): Promise<ArtifactsCreateTokenResult>;+ /** List tokens for this repo (metadata only, no plaintext). */+ listTokens(): Promise<ArtifactsTokenListResult>;+ /**+ * Revoke a token by plaintext or ID.+ * @param tokenOrId Plaintext token or token ID.+ * @returns true if revoked, false if not found.+ * @throws {ArtifactsError} with code `INVALID_INPUT` if tokenOrId is empty.+ */+ revokeToken(tokenOrId: string): Promise<boolean>;+ // ── Fork ──+ /**+ * Fork this repo to a new repo.+ * @param name Target repository name.+ * @param opts Optional: description, readOnly flag, defaultBranchOnly (default true).+ * @throws {ArtifactsError} with code `INVALID_REPO_NAME` if name is invalid.+ * @throws {ArtifactsError} with code `ALREADY_EXISTS` if the target repo already exists.+ * @throws {ArtifactsError} with code `FORK_IN_PROGRESS` if a fork is already running.+ */+ fork(name: string, opts?: {+ description?: string;+ readOnly?: boolean;+ defaultBranchOnly?: boolean;+ }): Promise<ArtifactsCreateRepoResult>;+}+// ── Error types ──────────────────────────────────────────────────────────────+/**+ * Error codes returned by Artifacts binding operations.+ *+ * Each code maps to a numeric code available on `ArtifactsError.numericCode`.+ */+type ArtifactsErrorCode = 'ALREADY_EXISTS' | 'NOT_FOUND' | 'IMPORT_IN_PROGRESS' | 'FORK_IN_PROGRESS' | 'INVALID_INPUT' | 'INVALID_REPO_NAME' | 'INVALID_TTL' | 'INVALID_URL' | 'REMOTE_AUTH_REQUIRED' | 'UPSTREAM_UNAVAILABLE' | 'MEMORY_LIMIT' | 'INTERNAL_ERROR';+/**+ * Error thrown by Artifacts binding operations.+ *+ * Uses a string `.code` discriminator following the Cloudflare platform+ * convention (StreamError, ImagesError, etc.). The `.numericCode` matches+ * the REST API `errors[].code` values.+ */+interface ArtifactsError extends Error {+ readonly name: 'ArtifactsError';+ /** String error code for programmatic matching. */+ readonly code: ArtifactsErrorCode;+ /** Numeric error code matching the REST API. */+ readonly numericCode: number;+}+// ── Binding ──────────────────────────────────────────────────────────────────+/**+ * Artifacts binding — namespace-level operations.+ *+ * Methods may throw `ArtifactsError` with code `INTERNAL_ERROR` if an unexpected service error occurs.+ */+interface Artifacts {+ /**+ * Create a new repository with an initial access token.+ * @param name Repository name (alphanumeric, dots, hyphens, underscores).+ * @param opts Optional: readOnly flag, description, default branch name.+ * @returns Repo metadata with initial token.+ * @throws {ArtifactsError} with code `INVALID_REPO_NAME` if name is invalid.+ * @throws {ArtifactsError} with code `ALREADY_EXISTS` if the repo already exists.+ */+ create(name: string, opts?: {+ readOnly?: boolean;+ description?: string;+ setDefaultBranch?: string;+ }): Promise<ArtifactsCreateRepoResult>;+ /**+ * Get a handle to an existing repository.+ * @param name Repository name.+ * @returns Repo handle.+ * @throws {ArtifactsError} with code `NOT_FOUND` if the repo does not exist.+ * @throws {ArtifactsError} with code `IMPORT_IN_PROGRESS` if the repo is still importing.+ * @throws {ArtifactsError} with code `FORK_IN_PROGRESS` if the repo is still forking.+ */+ get(name: string): Promise<ArtifactsRepo>;+ /**+ * Import a repository from an external git remote.+ * @param params Source URL and optional branch/depth, plus target name and options.+ * @returns Repo metadata with initial token.+ * @throws {ArtifactsError} with code `INVALID_REPO_NAME` if the target name is invalid.+ * @throws {ArtifactsError} with code `INVALID_INPUT` if the source URL is not valid HTTPS.+ * @throws {ArtifactsError} with code `INVALID_URL` if the source URL does not point to a git repository.+ * @throws {ArtifactsError} with code `REMOTE_AUTH_REQUIRED` if the remote requires authentication.+ * @throws {ArtifactsError} with code `NOT_FOUND` if the remote repository does not exist.+ * @throws {ArtifactsError} with code `UPSTREAM_UNAVAILABLE` if the remote cannot be reached.+ * @throws {ArtifactsError} with code `MEMORY_LIMIT` if the import exceeds service memory limits.+ * @throws {ArtifactsError} with code `ALREADY_EXISTS` if the target repo already exists.+ */+ import(params: {+ source: {+ url: string;+ branch?: string;+ depth?: number;+ };+ target: {+ name: string;+ opts?: {+ description?: string;+ readOnly?: boolean;+ };+ };+ }): Promise<ArtifactsCreateRepoResult>;+ /**+ * List repositories with cursor-based pagination.+ * @param opts Optional: limit (1–200, default 50), cursor for next page.+ */+ list(opts?: {+ limit?: number;+ cursor?: string;+ }): Promise<ArtifactsRepoListResult>;+ /**+ * Delete a repository and all associated tokens.+ * @param name Repository name.+ * @returns true if deleted, false if not found.+ * @throws {ArtifactsError} with code `INVALID_REPO_NAME` if name is invalid.+ */+ delete(name: string): Promise<boolean>;+}/*** @deprecated Use the standalone AI Search Workers binding instead.* See https://developers.cloudflare.com/ai-search/usage/workers-binding/@@ -9769,77 +10734,451 @@ declare abstract class AutoRAG {*/aiSearch(params: AutoRagAiSearchRequest): Promise<AutoRagAiSearchResponse | Response>;}-interface BasicImageTransformations {+type BrowserRunLifecycleEvent = 'load' | 'domcontentloaded' | 'networkidle0' | 'networkidle2';+type BrowserRunResourceType = 'document' | 'stylesheet' | 'image' | 'media' | 'font' | 'script' | 'texttrack' | 'xhr' | 'fetch' | 'prefetch' | 'eventsource' | 'websocket' | 'manifest' | 'signedexchange' | 'ping' | 'cspviolationreport' | 'preflight' | 'other';+/** Options fields shared by all quick actions. */+interface BrowserRunBaseOptions {+ /** Adds `<script>` tags into the page with the desired URL or content.+ * @see https://pptr.dev/api/puppeteer.frameaddscripttagoptions+ */+ addScriptTag?: Array<{+ content?: string;+ url?: string;+ type?: string;+ id?: string;+ }>;+ /** Adds `<link rel="stylesheet">` or `<style>` tags into the page.+ * @see https://pptr.dev/api/puppeteer.frameaddstyletagoptions+ */+ addStyleTag?: Array<{+ content?: string;+ url?: string;+ }>;+ /** Provide credentials for HTTP authentication. @see https://pptr.dev/api/puppeteer.credentials */+ authenticate?: {+ username: string;+ password: string;+ };+ /** Set cookies before navigating. @see https://pptr.dev/api/puppeteer.cookieparam */+ cookies?: Array<{+ name: string;+ value: string;+ url?: string;+ domain?: string;+ path?: string;+ secure?: boolean;+ httpOnly?: boolean;+ sameSite?: 'Strict' | 'Lax' | 'None';+ expires?: number;+ priority?: 'Low' | 'Medium' | 'High';+ sameParty?: boolean;+ sourceScheme?: 'Unset' | 'NonSecure' | 'Secure';+ sourcePort?: number;+ partitionKey?: string;+ }>;+ /** Emulate a specific CSS media type (e.g. `"screen"`, `"print"`). */+ emulateMediaType?: string;+ /** Navigation options. @see https://pptr.dev/api/puppeteer.gotooptions */+ gotoOptions?: {+ /** Navigation timeout in milliseconds (max 60 000). @default 30000 */+ timeout?: number;+ /** When to consider navigation complete. @default "domcontentloaded" */+ waitUntil?: BrowserRunLifecycleEvent | BrowserRunLifecycleEvent[];+ referer?: string;+ referrerPolicy?: string;+ };+ /** Block requests matching these regex patterns. Mutually exclusive with `allowRequestPattern`. */+ rejectRequestPattern?: string[];+ /** Only allow requests matching these regex patterns. Mutually exclusive with `rejectRequestPattern`. */+ allowRequestPattern?: string[];+ /** Block requests of these resource types. Mutually exclusive with `allowResourceTypes`. */+ rejectResourceTypes?: BrowserRunResourceType[];+ /** Only allow requests of these resource types. Mutually exclusive with `rejectResourceTypes`. */+ allowResourceTypes?: BrowserRunResourceType[];+ /** Additional HTTP headers sent with every request. */+ setExtraHTTPHeaders?: Record<string, string>;+ /** Whether JavaScript is enabled on the page. */+ setJavaScriptEnabled?: boolean;+ /** Override the default user agent string.+ * @default "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36"+ * */+ userAgent?: string;+ /** Set the browser viewport size.+ * @see https://pptr.dev/api/puppeteer.viewport+ * @default {width:1920,height:1080}+ * */+ viewport?: {+ width: number;+ height: number;+ deviceScaleFactor?: number;+ isMobile?: boolean;+ isLandscape?: boolean;+ hasTouch?: boolean;+ };+ /** Wait for a CSS selector to appear in the page before proceeding.+ * @see https://pptr.dev/api/puppeteer.waitforselectoroptions+ */+ waitForSelector?: {+ selector: string;+ hidden?: true;+ visible?: true;+ /** Timeout in milliseconds. Max 120000 */+ timeout?: number;+ };+ /** Wait for a fixed delay in milliseconds before proceeding. Max 120000 */+ waitForTimeout?: number;+ /** When true, continue on best-effort when awaited events fail or timeout. */+ bestAttempt?: boolean;+ /** Maximum duration in milliseconds for the browser action after page load. Max 120000 */+ actionTimeout?: number;+ /** Cache time to live in seconds (0-86400). Set to 0 to disable.+ * @default 5+ */+ cacheTTL?: number;+}+/** Common options shared by all quick actions. Exactly one of `url` or `html` must be provided.*/+type BrowserRunCommonOptions = (BrowserRunBaseOptions & {+ /** URL to navigate to, e.g. `"https://example.com"`. */+ url: string;+}) | (BrowserRunBaseOptions & {+ /** Set the HTML content of the page directly. */+ html: string;+});+type BrowserRunPuppeteerScreenshotOptions = {+ /** @default "png" */+ type?: 'png' | 'jpeg' | 'webp';+ /** @default "binary" */+ encoding?: 'binary' | 'base64';+ quality?: number;+ fullPage?: boolean;+ clip?: {+ x: number;+ y: number;+ width: number;+ height: number;+ scale?: number;+ };+ omitBackground?: boolean;+ optimizeForSpeed?: boolean;+ captureBeyondViewport?: boolean;+ fromSurface?: boolean;+};+type BrowserRunScreenshotOptions = BrowserRunCommonOptions & {+ /** CSS selector of the element to screenshot. */+ selector?: string;+ /** When true, scroll the entire page before taking the screenshot. */+ scrollPage?: boolean;+ /** @see https://pptr.dev/api/puppeteer.screenshotoptions */+ screenshotOptions?: BrowserRunPuppeteerScreenshotOptions;+};+type BrowserRunPDFOptions = BrowserRunCommonOptions & {+ /** @see https://pptr.dev/api/puppeteer.pdfoptions */+ pdfOptions?: {+ /** @default 1 */+ scale?: number;+ /** @default false */+ displayHeaderFooter?: boolean;+ headerTemplate?: string;+ footerTemplate?: string;+ /** @default false */+ printBackground?: boolean;+ /** @default false */+ landscape?: boolean;+ pageRanges?: string;+ /** @default "letter" */+ format?: 'letter' | 'legal' | 'tabloid' | 'ledger' | 'a0' | 'a1' | 'a2' | 'a3' | 'a4' | 'a5' | 'a6';+ width?: string | number;+ height?: string | number;+ /** @default false */+ preferCSSPageSize?: boolean;+ margin?: {+ top?: string | number;+ right?: string | number;+ bottom?: string | number;+ left?: string | number;+ };+ /** @default false */+ omitBackground?: boolean;+ /** @default true */+ tagged?: boolean;+ /** @default false */+ outline?: boolean;+ /** @default 30000 */+ timeout?: number;+ };+};+type BrowserRunScrapeOptions = BrowserRunCommonOptions & {+ /** CSS selectors to scrape. At least one element is required. */+ elements: Array<{+ selector: string;+ }>;+};+type BrowserRunLinksOptions = BrowserRunCommonOptions & {+ /** When true, only return links that are visible on the page. @default false */+ visibleLinksOnly?: boolean;+ /** When true, exclude links pointing to external domains. @default false */+ excludeExternalLinks?: boolean;+};+type BrowserRunSnapshotOptions = BrowserRunCommonOptions & {+ /** @see https://pptr.dev/api/puppeteer.screenshotoptions */+ screenshotOptions?: Omit<BrowserRunPuppeteerScreenshotOptions, 'encoding'>;+};+interface BrowserRunJsonBaseOptions {+ /** Custom AI models to try in order. Max 3. Falls back to next on error. */+ custom_ai?: Array<{+ /** Model ID in `<provider>/<model_name>` format, e.g. `"workers-ai/@cf/meta/llama-3.3-70b-instruct-fp8-fast"`. */+ model: string;+ /** Bearer token. Not needed for workers-ai models. */+ authorization?: string;+ }>;+}+/**+ * Options for the `json` quick action.+ * At least one of `prompt` or `response_format` must be provided.+ */+type BrowserRunJsonOptions = BrowserRunCommonOptions & BrowserRunJsonBaseOptions & ({+ /** Natural-language prompt describing what data to extract. */+ prompt: string;+ /** Structured output schema for the AI model. @see https://developers.cloudflare.com/workers-ai/json-mode/ */+ response_format?: AiTextGenerationResponseFormat;+} | {+ /** Natural-language prompt describing what data to extract. */+ prompt?: string;+ /** Structured output schema for the AI model. @see https://developers.cloudflare.com/workers-ai/json-mode/ */+ response_format: AiTextGenerationResponseFormat;+});+type BrowserRunContentOptions = BrowserRunCommonOptions;+type BrowserRunMarkdownOptions = BrowserRunCommonOptions;+type BrowserRunResponseMeta = {+ /** HTTP status code of the rendered page */+ status: number;+ /** Page title */+ title: string;+};+/** Success response for `content` action. */+type BrowserRunContentSuccessResponse = {+ success: true;+ /** Extracted HTML content */+ result: string;+ meta: BrowserRunResponseMeta;+};+/** Success response for `links` action. */+type BrowserRunLinksSuccessResponse = {+ success: true;+ /** Extracted links */+ result: string[];+};+/** Success response for `scrape` action. */+type BrowserRunScrapeSuccessResponse = {+ success: true;+ result: Array<{+ /** The CSS selector used to find elements. */+ selector: string;+ /** Array of elements matching the selector. */+ results: Array<{+ /** Outer HTML of the element. */+ html: string;+ /** Text content of the element. */+ text: string;+ /** Width of the element in pixels. */+ width: number;+ /** Height of the element in pixels. */+ height: number;+ /** Top position of the element relative to the viewport in pixels. */+ top: number;+ /** Left position of the element relative to the viewport in pixels. */+ left: number;+ /** Array of HTML attributes on the element. */+ attributes: Array<{+ /** Attribute name. */+ name: string;+ /** Attribute value. */+ value: string;+ }>;+ }>;+ }>;+};+/** Success response for `snapshot` action. */+type BrowserRunSnapshotSuccessResponse = {+ success: true;+ result: {+ /** HTML content of the page. */+ content: string;+ /** Base64-encoded screenshot image. */+ screenshot: string;+ };+ meta: BrowserRunResponseMeta;+};+/** Success response for `json` action. */+type BrowserRunJsonSuccessResponse = {+ success: true;+ /** JSON data extracted from the page using an AI model */+ result: Record<string, unknown>;+};+/** Success response for `markdown` action. */+type BrowserRunMarkdownSuccessResponse = {+ success: true;+ /** Extracted markdown content */+ result: string;+};+/** Error response for BrowserRun actions. */+type BrowserRunErrorResponse = {+ success: false;+ errors: {+ message: string;+ code?: number;+ detail?: string;+ path?: string;+ }[];+};+/** Error response for BrowserRun `json` action. */+type BrowserRunJsonErrorResponse = BrowserRunErrorResponse & {+ /** Raw AI response text for debugging */+ rawAiResponse?: string;+};+/**+ * Browser Run API binding for automating headless browsers.+ * @see https://developers.cloudflare.com/browser-run/+ */+declare abstract class BrowserRun {/**- * Maximum width in image pixels. The value must be an integer.+ * Send a raw HTTP request to the Browser Run API.+ * Used by libraries like `@cloudflare/puppeteer` to acquire and connect to a browser instance.+ * @see https://developers.cloudflare.com/browser-run/*/- width?: number;+ fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;/**- * Maximum height in image pixels. The value must be an integer.+ * Take a screenshot of a web page.+ * @param action - Must be `'screenshot'`.+ * @param options - Screenshot options including viewport, selectors, and image format.+ * @returns A `Response` containing one of:+ *+ * **Success (HTTP 200):**+ * - Binary image data with `Content-Type: image/png`, `image/jpeg`, or `image/webp` (when `encoding: 'binary'`, the default)+ * - Data URI string with `Content-Type: text/plain` (when `encoding: 'base64'`)+ *+ * **Error:**+ * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)+ *+ * **Headers:**+ * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)*/- height?: number;+ quickAction(action: 'screenshot', options: BrowserRunScreenshotOptions): Promise<Response>;/**- * Resizing mode as a string. It affects interpretation of width and height- * options:- * - scale-down: Similar to contain, but the image is never enlarged. If- * the image is larger than given width or height, it will be resized.- * Otherwise its original size will be kept.- * - contain: Resizes to maximum size that fits within the given width and- * height. If only a single dimension is given (e.g. only width), the- * image will be shrunk or enlarged to exactly match that dimension.- * Aspect ratio is always preserved.- * - cover: Resizes (shrinks or enlarges) to fill the entire area of width- * and height. If the image has an aspect ratio different from the ratio- * of width and height, it will be cropped to fit.- * - crop: The image will be shrunk and cropped to fit within the area- * specified by width and height. The image will not be enlarged. For images- * smaller than the given dimensions it's the same as scale-down. For- * images larger than the given dimensions, it's the same as cover.- * See also trim.- * - pad: Resizes to the maximum size that fits within the given width and- * height, and then fills the remaining area with a background color- * (white by default). Use of this mode is not recommended, as the same- * effect can be more efficiently achieved with the contain mode and the- * CSS object-fit: contain property.- * - squeeze: Stretches and deforms to the width and height given, even if it- * breaks aspect ratio+ * Generate a PDF of a web page.+ * @param action - Must be `'pdf'`.+ * @param options - PDF generation options including page size, margins, and headers/footers.+ * @returns A `Response` containing one of:+ *+ * **Success (HTTP 200):**+ * - Binary PDF data with `Content-Type: application/pdf`+ *+ * **Error:**+ * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)+ *+ * **Headers:**+ * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)*/- fit?: "scale-down" | "contain" | "cover" | "crop" | "pad" | "squeeze";+ quickAction(action: 'pdf', options: BrowserRunPDFOptions): Promise<Response>;/**- * Image segmentation using artificial intelligence models. Sets pixels not- * within selected segment area to transparent e.g "foreground" sets every- * background pixel as transparent.+ * Get the HTML content of a web page.+ * @param action - Must be `'content'`.+ * @param options - Navigation and page interaction options.+ * @returns A `Response` containing one of:+ *+ * **Success (HTTP 200):**+ * - `BrowserRunContentSuccessResponse` JSON with `Content-Type: application/json`+ *+ * **Error:**+ * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)+ *+ * **Headers:**+ * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)*/- segment?: "foreground";+ quickAction(action: 'content', options: BrowserRunContentOptions): Promise<Response>;/**- * When cropping with fit: "cover", this defines the side or point that should- * be left uncropped. The value is either a string- * "left", "right", "top", "bottom", "auto", or "center" (the default),- * or an object {x, y} containing focal point coordinates in the original- * image expressed as fractions ranging from 0.0 (top or left) to 1.0- * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will- * crop bottom or left and right sides as necessary, but won’t crop anything- * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to- * preserve as much as possible around a point at 20% of the height of the- * source image.+ * Scrape elements from a web page by CSS selector.+ * @param action - Must be `'scrape'`.+ * @param options - Scrape options with CSS selectors for elements to extract.+ * @returns A `Response` containing one of:+ *+ * **Success (HTTP 200):**+ * - `BrowserRunScrapeSuccessResponse` JSON with `Content-Type: application/json`+ *+ * **Error:**+ * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)+ *+ * **Headers:**+ * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)*/- gravity?: 'face' | 'left' | 'right' | 'top' | 'bottom' | 'center' | 'auto' | 'entropy' | BasicImageTransformationsGravityCoordinates;+ quickAction(action: 'scrape', options: BrowserRunScrapeOptions): Promise<Response>;/**- * Background color to add underneath the image. Applies only to images with- * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…),- * hsl(…), etc.)+ * Extract all links from a web page.+ * @param action - Must be `'links'`.+ * @param options - Options to filter visible or internal links only.+ * @returns A `Response` containing one of:+ *+ * **Success (HTTP 200):**+ * - `BrowserRunLinksSuccessResponse` JSON with `Content-Type: application/json`+ *+ * **Error:**+ * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)+ *+ * **Headers:**+ * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)*/- background?: string;+ quickAction(action: 'links', options: BrowserRunLinksOptions): Promise<Response>;/**- * Number of degrees (90, 180, 270) to rotate the image by. width and height- * options refer to axes after rotation.+ * Get both the HTML content and a base64-encoded screenshot of a web page.+ * @param action - Must be `'snapshot'`.+ * @param options - Snapshot options including screenshot settings (encoding is always base64).+ * @returns A `Response` containing one of:+ *+ * **Success (HTTP 200):**+ * - `BrowserRunSnapshotSuccessResponse` JSON with `Content-Type: application/json`+ *+ * **Error:**+ * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)+ *+ * **Headers:**+ * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)*/- rotate?: 0 | 90 | 180 | 270 | 360;-}-interface BasicImageTransformationsGravityCoordinates {- x?: number;- y?: number;- mode?: 'remainder' | 'box-center';+ quickAction(action: 'snapshot', options: BrowserRunSnapshotOptions): Promise<Response>;+ /**+ * Extract structured JSON data from a web page using AI.+ * @param action - Must be `'json'`.+ * @param options - JSON extraction options with prompt or response_format schema.+ * @returns A `Response` containing one of:+ *+ * **Success (HTTP 200):**+ * - `BrowserRunJsonSuccessResponse` JSON with `Content-Type: application/json`+ *+ * **Error:**+ * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)+ * - HTTP 422 with code `2012` for HTML-to-markdown conversion failures+ * - HTTP 422/500 for AI extraction failures (may include `rawAiResponse` field)+ *+ * **Headers:**+ * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)+ */+ quickAction(action: 'json', options: BrowserRunJsonOptions): Promise<Response>;+ /**+ * Convert a web page to Markdown.+ * @param action - Must be `'markdown'`.+ * @param options - Navigation and page interaction options.+ * @returns A `Response` containing one of:+ *+ * **Success (HTTP 200):**+ * - `BrowserRunMarkdownSuccessResponse` JSON with `Content-Type: application/json`+ *+ * **Error:**+ * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)+ * - HTTP 422 with code `2012` for HTML-to-markdown conversion failures+ *+ * **Headers:**+ * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)+ */+ quickAction(action: 'markdown', options: BrowserRunMarkdownOptions): Promise<Response>;}/*** In addition to the properties you can set in the RequestInit dict@@ -9879,6 +11218,8 @@ interface RequestInitCfProperties extends Record<string, unknown> {* (e.g. { '200-299': 86400, '404': 1, '500-599': 0 })*/cacheTtlByStatus?: Record<string, number>;+ /** Controls how responses with a `Vary` header are cached for this request. */+ vary?: RequestInitCfPropertiesVary;/*** Explicit Cache-Control header value to set on the response stored in cache.* This gives full control over cache directives (e.g. 'public, max-age=3600, s-maxage=86400').@@ -9909,32 +11250,281 @@ interface RequestInitCfProperties extends Record<string, unknown> {* Whether to enable Cache Deception Armor, which protects against web cache* deception attacks by verifying the Content-Type matches the URL extension.*/- cacheDeceptionArmor?: boolean;+ cacheDeceptionArmor?: boolean;+ /**+ * Minimum file size in bytes for a response to be eligible for Cache Reserve storage.+ */+ cacheReserveMinimumFileSize?: number;+ scrapeShield?: boolean;+ apps?: boolean;+ /**+ * Controls whether an outbound gRPC-web subrequest from this Worker is+ * converted to gRPC at the Cloudflare edge.+ *+ * - `"passthrough"`: forward the subrequest unchanged as gRPC-web (default).+ * - `"convert"`: convert the gRPC-web subrequest to gRPC at the edge.+ *+ * Provides per-request control over the same edge conversion behavior+ * gated by the `auto_grpc_convert` compatibility flag.+ */+ grpcWeb?: "passthrough" | "convert";+ image?: RequestInitCfPropertiesImage;+ minify?: RequestInitCfPropertiesImageMinify;+ mirage?: boolean;+ polish?: "lossy" | "lossless" | "off";+ r2?: RequestInitCfPropertiesR2;+ /**+ * Redirects the request to an alternate origin server. You can use this,+ * for example, to implement load balancing across several origins.+ * (e.g.us-east.example.com)+ *+ * Note - For security reasons, the hostname set in resolveOverride must+ * be proxied on the same Cloudflare zone of the incoming request.+ * Otherwise, the setting is ignored. CNAME hosts are allowed, so to+ * resolve to a host under a different domain or a DNS only domain first+ * declare a CNAME record within your own zone’s DNS mapping to the+ * external hostname, set proxy on Cloudflare, then set resolveOverride+ * to point to that CNAME record.+ */+ resolveOverride?: string;+}+/**+ * Controls how Workers Standard Vary handles a request header listed by an+ * origin `Vary` response header:+ *+ * - `"normalize"`: normalize the request header value before it is used in the+ * cache variance key.+ * - `"passthrough"`: use the raw request header value in the cache variance+ * key.+ * - `"bypass"`: bypass cache when the header appears in the origin `Vary`+ * response header.+ */+type RequestInitCfPropertiesVaryAction = "normalize" | "passthrough" | "bypass";+/** Configuration for Workers Standard Vary support. */+interface RequestInitCfPropertiesVary {+ /** The fallback action for varied request headers not listed in `headers`. */+ default: RequestInitCfPropertiesVaryHeader;+ /**+ * Lowercase request header names and their Vary configuration.+ *+ * The `accept` header can include `media_types`, the `accept-language`+ * header can include `languages`, and other headers support only `action`.+ */+ headers?: RequestInitCfPropertiesVaryHeaders;+}+/** Common Vary behavior for a single request header. */+interface RequestInitCfPropertiesVaryHeader {+ /** How this request header contributes to cache variance. */+ action: RequestInitCfPropertiesVaryAction;+}+/** Vary behavior for the `accept` request header. */+interface RequestInitCfPropertiesVaryAcceptHeader extends RequestInitCfPropertiesVaryHeader {+ /**+ * Media types to keep when normalizing the `Accept` request header.+ *+ * Named `media_types` to match the serialized `cf.vary` configuration.+ */+ media_types?: string[];+}+/** Vary behavior for the `accept-language` request header. */+interface RequestInitCfPropertiesVaryAcceptLanguageHeader extends RequestInitCfPropertiesVaryHeader {+ /**+ * Language tags to keep when normalizing the `Accept-Language` request+ * header.+ */+ languages?: string[];+}+/**+ * Lowercase request header names and their Vary behavior.+ *+ * The index signature allows arbitrary custom request headers beyond the+ * well-known `accept` and `accept-language` specializations.+ */+interface RequestInitCfPropertiesVaryHeaders {+ accept?: RequestInitCfPropertiesVaryAcceptHeader;+ "accept-language"?: RequestInitCfPropertiesVaryAcceptLanguageHeader;+ [header: string]: RequestInitCfPropertiesVaryHeader | RequestInitCfPropertiesVaryAcceptHeader | RequestInitCfPropertiesVaryAcceptLanguageHeader | undefined;+}+interface BasicImageTransformations {+ /**+ * Maximum width in image pixels. The value must be an integer.+ */+ width?: number;+ /**+ * Maximum height in image pixels. The value must be an integer.+ */+ height?: number;+ /**+ * When cropping with fit: "cover", this defines the side or point that should+ * be left uncropped. The value is either a string+ * "left", "right", "top", "bottom", "auto", or "center" (the default),+ * or an object {x, y} containing focal point coordinates in the original+ * image expressed as fractions ranging from 0.0 (top or left) to 1.0+ * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will+ * crop bottom or left and right sides as necessary, but won’t crop anything+ * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to+ * preserve as much as possible around a point at 20% of the height of the+ * source image.+ */+ gravity?: 'face' | 'left' | 'right' | 'top' | 'bottom' | 'center' | 'auto' | 'entropy' | BasicImageTransformationsGravityCoordinates;+ /**+ * Specifies how closely the image is cropped toward detected faces when combined+ * with the gravity=face option. Accepts a valid range between 0.0 (includes as much+ * of the background as possible) and 1.0 (crops the image as closely to the face as+ * possible). The default is 0.+ */+ zoom?: number;+ /**+ * Resizing mode as a string. It affects interpretation of width and height+ * options:+ * - scale-down: Similar to contain, but the image is never enlarged. If+ * the image is larger than given width or height, it will be resized.+ * Otherwise its original size will be kept.+ * - scale-up: Similar to contain, but the image is never shrunk. If the+ * image is smaller than the given width or height, it will be resized.+ * Otherwise its original size will be kept.+ * - contain: Resizes to maximum size that fits within the given width and+ * height. If only a single dimension is given (e.g. only width), the+ * image will be shrunk or enlarged to exactly match that dimension.+ * Aspect ratio is always preserved.+ * - cover: Resizes (shrinks or enlarges) to fill the entire area of width+ * and height. If the image has an aspect ratio different from the ratio+ * of width and height, it will be cropped to fit.+ * - crop: The image will be shrunk and cropped to fit within the area+ * specified by width and height. The image will not be enlarged. For images+ * smaller than the given dimensions it's the same as scale-down. For+ * images larger than the given dimensions, it's the same as cover.+ * See also trim.+ * - pad: Resizes to the maximum size that fits within the given width and+ * height, and then fills the remaining area with a background color+ * (white by default). Use of this mode is not recommended, as the same+ * effect can be more efficiently achieved with the contain mode and the+ * CSS object-fit: contain property.+ * - squeeze: Stretches and deforms to the width and height given, even if it+ * breaks aspect ratio+ */+ fit?: "scale-down" | "scale-up" | "contain" | "cover" | "crop" | "pad" | "squeeze";+ /**+ * Allows you to trim your image. Takes dpr into account and is performed before+ * resizing or rotation.+ *+ * It can be used as:+ * - left, top, right, bottom - it will specify the number of pixels to cut+ * off each side+ * - width, height - the width/height you'd like to end up with - can be used+ * in combination with the properties above+ * - border - this will automatically trim the surroundings of an image based on+ * it's color. It consists of three properties:+ * - color: rgb or hex representation of the color you wish to trim (todo: verify the rgba bit)+ * - tolerance: difference from color to treat as color+ * - keep: the number of pixels of border to keep+ */+ trim?: "border" | {+ top?: number;+ bottom?: number;+ left?: number;+ right?: number;+ width?: number;+ height?: number;+ border?: boolean | {+ color?: string;+ tolerance?: number;+ keep?: number;+ };+ };+ /**+ * Background color to add underneath the image. Applies only to images with+ * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…),+ * hsl(…), etc.)+ */+ background?: string;+ /**+ * Flips the images horizontally, vertically, or both. Flipping is applied before+ * rotation, so if you apply flip=h,rotate=90 then the image will be flipped+ * horizontally, then rotated by 90 degrees.+ */+ flip?: 'h' | 'v' | 'hv';+ /**+ * Number of degrees (90, 180, 270) to rotate the image by. width and height+ * options refer to axes after rotation.+ */+ rotate?: 0 | 90 | 180 | 270 | 360;+ /**+ * Strength of sharpening filter to apply to the image. Floating-point+ * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a+ * recommended value for downscaled images.+ */+ sharpen?: number;+ /**+ * Radius of a blur filter (approximate gaussian). Maximum supported radius+ * is 250.+ */+ blur?: number;+ /**+ * Increase contrast by a factor. A value of 1.0 equals no change, a value of+ * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is+ * ignored.+ */+ contrast?: number;+ /**+ * Increase brightness by a factor. A value of 1.0 equals no change, a value+ * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright.+ * 0 is ignored.+ */+ brightness?: number;+ /**+ * Increase exposure by a factor. A value of 1.0 equals no change, a value of+ * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored.+ */+ gamma?: number;+ /**+ * Increase contrast by a factor. A value of 1.0 equals no change, a value of+ * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is+ * ignored.+ */+ saturation?: number;+ /**+ * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it+ * easier to specify higher-DPI sizes in <img srcset>.+ */+ dpr?: number;+ /**+ * Adds a border around the image. The border is added after resizing. Border+ * width takes dpr into account, and can be specified either using a single+ * width property, or individually for each side.+ */+ border?: {+ color: string;+ width: number;+ } | {+ color: string;+ top: number;+ right: number;+ bottom: number;+ left: number;+ };/**- * Minimum file size in bytes for a response to be eligible for Cache Reserve storage.+ * Image segmentation using artificial intelligence models. Sets pixels not+ * within selected segment area to transparent e.g "foreground" sets every+ * background pixel as transparent.*/- cacheReserveMinimumFileSize?: number;- scrapeShield?: boolean;- apps?: boolean;- image?: RequestInitCfPropertiesImage;- minify?: RequestInitCfPropertiesImageMinify;- mirage?: boolean;- polish?: "lossy" | "lossless" | "off";- r2?: RequestInitCfPropertiesR2;+ segment?: "foreground";/**- * Redirects the request to an alternate origin server. You can use this,- * for example, to implement load balancing across several origins.- * (e.g.us-east.example.com)- *- * Note - For security reasons, the hostname set in resolveOverride must- * be proxied on the same Cloudflare zone of the incoming request.- * Otherwise, the setting is ignored. CNAME hosts are allowed, so to- * resolve to a host under a different domain or a DNS only domain first- * declare a CNAME record within your own zone’s DNS mapping to the- * external hostname, set proxy on Cloudflare, then set resolveOverride- * to point to that CNAME record.+ * Controls the algorithm used when an image needs to be enlarged. This+ * parameter works with any fit mode that upscales, such as `contain`,+ * `cover`, and `scale-up`. It has no effect when `fit=scale-down` or when+ * the target dimensions are smaller than the source.+ * - interpolate: Uses bicubic interpolation, which may reduce image quality.+ * This is the default behavior when `upscale` is not specified.+ * - generate: Uses AI upscaling to produce sharper, more detailed results+ * when enlarging images.*/- resolveOverride?: string;+ upscale?: "interpolate" | "generate";+}+interface BasicImageTransformationsGravityCoordinates {+ x?: number;+ y?: number;+ mode?: 'remainder' | 'box-center';}interface RequestInitCfPropertiesImageDraw extends BasicImageTransformations {/**@@ -9957,6 +11547,22 @@ interface RequestInitCfPropertiesImageDraw extends BasicImageTransformations {* (form a line).*/repeat?: true | "x" | "y";+ /**+ * How to combine the foreground and backdrop pixels to create the result+ */+ composite?:+ /** Foreground drawn on top of backdrop (default) */+ 'over'+ /** Foreground shown only where backdrop is opaque */+ | 'in'+ /** Foreground drawn on top, but clipped to the backdrop's shape */+ | 'atop'+ /** Foreground shown only where backdrop is transparent */+ | 'out'+ /** Foreground and backdrop visible only where the other is not */+ | 'xor'+ /** Foreground and backdrop channels added (brightening) */+ | 'lighter';/*** Position of the overlay image relative to a given edge. Each property is* an offset in pixels. 0 aligns exactly to the edge. For example, left: 10@@ -9974,39 +11580,6 @@ interface RequestInitCfPropertiesImageDraw extends BasicImageTransformations {right?: number;}interface RequestInitCfPropertiesImage extends BasicImageTransformations {- /**- * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it- * easier to specify higher-DPI sizes in <img srcset>.- */- dpr?: number;- /**- * Allows you to trim your image. Takes dpr into account and is performed before- * resizing or rotation.- *- * It can be used as:- * - left, top, right, bottom - it will specify the number of pixels to cut- * off each side- * - width, height - the width/height you'd like to end up with - can be used- * in combination with the properties above- * - border - this will automatically trim the surroundings of an image based on- * it's color. It consists of three properties:- * - color: rgb or hex representation of the color you wish to trim (todo: verify the rgba bit)- * - tolerance: difference from color to treat as color- * - keep: the number of pixels of border to keep- */- trim?: "border" | {- top?: number;- bottom?: number;- left?: number;- right?: number;- width?: number;- height?: number;- border?: boolean | {- color?: string;- tolerance?: number;- keep?: number;- };- };/*** Quality setting from 1-100 (useful values are in 60-90 range). Lower values* make images look worse, but load faster. The default is 85. It applies only@@ -10048,17 +11621,6 @@ interface RequestInitCfPropertiesImage extends BasicImageTransformations {* output formats always discard metadata.*/metadata?: "keep" | "copyright" | "none";- /**- * Strength of sharpening filter to apply to the image. Floating-point- * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a- * recommended value for downscaled images.- */- sharpen?: number;- /**- * Radius of a blur filter (approximate gaussian). Maximum supported radius- * is 250.- */- blur?: number;/*** Overlays are drawn in the order they appear in the array (last array* entry is the topmost layer).@@ -10070,50 +11632,6 @@ interface RequestInitCfPropertiesImage extends BasicImageTransformations {* the origin.*/"origin-auth"?: "share-publicly";- /**- * Adds a border around the image. The border is added after resizing. Border- * width takes dpr into account, and can be specified either using a single- * width property, or individually for each side.- */- border?: {- color: string;- width: number;- } | {- color: string;- top: number;- right: number;- bottom: number;- left: number;- };- /**- * Increase brightness by a factor. A value of 1.0 equals no change, a value- * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright.- * 0 is ignored.- */- brightness?: number;- /**- * Increase contrast by a factor. A value of 1.0 equals no change, a value of- * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is- * ignored.- */- contrast?: number;- /**- * Increase exposure by a factor. A value of 1.0 equals no change, a value of- * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored.- */- gamma?: number;- /**- * Increase contrast by a factor. A value of 1.0 equals no change, a value of- * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is- * ignored.- */- saturation?: number;- /**- * Flips the images horizontally, vertically, or both. Flipping is applied before- * rotation, so if you apply flip=h,rotate=90 then the image will be flipped- * horizontally, then rotated by 90 degrees.- */- flip?: 'h' | 'v' | 'hv';/*** Slightly reduces latency on a cache miss by selecting a* quickest-to-compress file format, at a cost of increased file size and@@ -10494,6 +12012,32 @@ interface IncomingRequestCfPropertiesTLSClientAuth {* @example "Dec 22 19:39:00 2018 GMT"*/certNotAfter: string;+ /**+ * The client leaf certificate in [RFC 9440](https://www.rfc-editor.org/rfc/rfc9440)+ * format (`:base64-DER:`). Empty if no client certificate was presented or if+ * the leaf certificate exceeded 10 KB (see {@link certRFC9440TooLarge}).+ *+ * Suitable for forwarding to an origin via the `Client-Cert` HTTP header.+ */+ certRFC9440: string;+ /**+ * `true` if the leaf certificate exceeded 10 KB and was omitted from+ * {@link certRFC9440}.+ */+ certRFC9440TooLarge: boolean;+ /**+ * The intermediate certificate chain in [RFC 9440](https://www.rfc-editor.org/rfc/rfc9440)+ * format as a comma-separated list. Empty if no intermediates were sent or+ * if the chain exceeded 16 KB (see {@link certChainRFC9440TooLarge}).+ *+ * Suitable for forwarding to an origin via the `Client-Cert-Chain` HTTP header.+ */+ certChainRFC9440: string;+ /**+ * `true` if the intermediate chain exceeded 16 KB and was omitted from+ * {@link certChainRFC9440}.+ */+ certChainRFC9440TooLarge: boolean;}/** Placeholder values for TLS Client Authorization */interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder {@@ -10514,9 +12058,13 @@ interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder {certFingerprintSHA256: "";certNotBefore: "";certNotAfter: "";+ certRFC9440: "";+ certRFC9440TooLarge: false;+ certChainRFC9440: "";+ certChainRFC9440TooLarge: false;}/** Possible outcomes of TLS verification */-declare type CertVerificationStatus =+declare type CertVerificationStatus =/** Authentication succeeded */"SUCCESS"/** No certificate was presented */@@ -10584,7 +12132,7 @@ interface D1ExecResult {count: number;duration: number;}-type D1SessionConstraint =+type D1SessionConstraint =// Indicates that the first query should go to the primary, and the rest queries// using the same D1DatabaseSession will go to any replica that is consistent with// the bookmark maintained by the session (returned by the first query).@@ -10701,6 +12249,13 @@ interface ForwardableEmailMessage extends EmailMessage {* @returns A promise that resolves when the email message is replied.*/reply(message: EmailMessage): Promise<EmailSendResult>;+ /**+ * Reply to the sender of this email message with a message built from the given+ * fields. Threading headers (In-Reply-To/References) are set automatically.+ * @param builder The reply message contents.+ * @returns A promise that resolves when the email message is replied.+ */+ reply(builder: EmailReplyMessageBuilder): Promise<EmailSendResult>;}/** A file attachment for an email message */type EmailAttachment = {@@ -10721,23 +12276,46 @@ interface EmailAddress {name: string;email: string;}+/**+ * Recipient fields for `SendEmail.send()`. At least one of `to`, `cc`, or+ * `bcc` must be provided.+ */+type EmailDestinations = {+ to?: string | EmailAddress | (string | EmailAddress)[];+ cc?: string | EmailAddress | (string | EmailAddress)[];+ bcc?: string | EmailAddress | (string | EmailAddress)[];+} & ({+ to: string | EmailAddress | (string | EmailAddress)[];+} | {+ cc: string | EmailAddress | (string | EmailAddress)[];+} | {+ bcc: string | EmailAddress | (string | EmailAddress)[];+});+/**+ * Fields shared by all composed emails (no recipients). Used directly by+ * `ForwardableEmailMessage.reply()`, which always replies to the original+ * sender, and extended by `EmailMessageBuilder` for `SendEmail.send()`.+ */+interface EmailReplyMessageBuilder {+ from: string | EmailAddress;+ subject: string;+ replyTo?: string | EmailAddress;+ headers?: Record<string, string>;+ text?: string;+ html?: string;+ attachments?: EmailAttachment[];+}+/**+ * Fields for composing an email without constructing raw MIME, for+ * `SendEmail.send()`. Requires at least one of `to`, `cc`, or `bcc`.+ */+type EmailMessageBuilder = EmailReplyMessageBuilder & EmailDestinations;/*** A binding that allows a Worker to send email messages.*/interface SendEmail {send(message: EmailMessage): Promise<EmailSendResult>;- send(builder: {- from: string | EmailAddress;- to: string | string[];- subject: string;- replyTo?: string | EmailAddress;- cc?: string | string[];- bcc?: string | string[];- headers?: Record<string, string>;- text?: string;- html?: string;- attachments?: EmailAttachment[];- }): Promise<EmailSendResult>;+ send(builder: EmailMessageBuilder): Promise<EmailSendResult>;}declare abstract class EmailEvent extends ExtendableEvent {readonly message: ForwardableEmailMessage;@@ -10750,6 +12328,105 @@ declare module "cloudflare:email" {};export { _EmailMessage as EmailMessage };}+/**+ * Evaluation context for targeting rules.+ * Keys are attribute names (e.g. "userId", "country"), values are the attribute values.+ */+type FlagshipEvaluationContext = Record<string, string | number | boolean>;+interface FlagshipEvaluationDetails<T> {+ flagKey: string;+ value: T;+ variant?: string | undefined;+ reason?: string | undefined;+ errorCode?: string | undefined;+ errorMessage?: string | undefined;+}+interface FlagshipEvaluationError extends Error {+}+/**+ * Feature flags binding for evaluating feature flags from a Cloudflare Workers script.+ *+ * @example+ * ```typescript+ * // Get a boolean flag value with a default+ * const enabled = await env.FLAGS.getBooleanValue('my-feature', false);+ *+ * // Get a flag value with evaluation context for targeting+ * const variant = await env.FLAGS.getStringValue('experiment', 'control', {+ * userId: 'user-123',+ * country: 'US',+ * });+ *+ * // Get full evaluation details including variant and reason+ * const details = await env.FLAGS.getBooleanDetails('my-feature', false);+ * console.log(details.variant, details.reason);+ * ```+ */+declare abstract class Flagship {+ /**+ * Get a flag value without type checking.+ * @param flagKey The key of the flag to evaluate.+ * @param defaultValue Optional default value returned when evaluation fails.+ * @param context Optional evaluation context for targeting rules.+ */+ get(flagKey: string, defaultValue?: unknown, context?: FlagshipEvaluationContext): Promise<unknown>;+ /**+ * Get a boolean flag value.+ * @param flagKey The key of the flag to evaluate.+ * @param defaultValue Default value returned when evaluation fails or the flag type does not match.+ * @param context Optional evaluation context for targeting rules.+ */+ getBooleanValue(flagKey: string, defaultValue: boolean, context?: FlagshipEvaluationContext): Promise<boolean>;+ /**+ * Get a string flag value.+ * @param flagKey The key of the flag to evaluate.+ * @param defaultValue Default value returned when evaluation fails or the flag type does not match.+ * @param context Optional evaluation context for targeting rules.+ */+ getStringValue(flagKey: string, defaultValue: string, context?: FlagshipEvaluationContext): Promise<string>;+ /**+ * Get a number flag value.+ * @param flagKey The key of the flag to evaluate.+ * @param defaultValue Default value returned when evaluation fails or the flag type does not match.+ * @param context Optional evaluation context for targeting rules.+ */+ getNumberValue(flagKey: string, defaultValue: number, context?: FlagshipEvaluationContext): Promise<number>;+ /**+ * Get an object flag value.+ * @param flagKey The key of the flag to evaluate.+ * @param defaultValue Default value returned when evaluation fails or the flag type does not match.+ * @param context Optional evaluation context for targeting rules.+ */+ getObjectValue<T extends object>(flagKey: string, defaultValue: T, context?: FlagshipEvaluationContext): Promise<T>;+ /**+ * Get a boolean flag value with full evaluation details.+ * @param flagKey The key of the flag to evaluate.+ * @param defaultValue Default value returned when evaluation fails or the flag type does not match.+ * @param context Optional evaluation context for targeting rules.+ */+ getBooleanDetails(flagKey: string, defaultValue: boolean, context?: FlagshipEvaluationContext): Promise<FlagshipEvaluationDetails<boolean>>;+ /**+ * Get a string flag value with full evaluation details.+ * @param flagKey The key of the flag to evaluate.+ * @param defaultValue Default value returned when evaluation fails or the flag type does not match.+ * @param context Optional evaluation context for targeting rules.+ */+ getStringDetails(flagKey: string, defaultValue: string, context?: FlagshipEvaluationContext): Promise<FlagshipEvaluationDetails<string>>;+ /**+ * Get a number flag value with full evaluation details.+ * @param flagKey The key of the flag to evaluate.+ * @param defaultValue Default value returned when evaluation fails or the flag type does not match.+ * @param context Optional evaluation context for targeting rules.+ */+ getNumberDetails(flagKey: string, defaultValue: number, context?: FlagshipEvaluationContext): Promise<FlagshipEvaluationDetails<number>>;+ /**+ * Get an object flag value with full evaluation details.+ * @param flagKey The key of the flag to evaluate.+ * @param defaultValue Default value returned when evaluation fails or the flag type does not match.+ * @param context Optional evaluation context for targeting rules.+ */+ getObjectDetails<T extends object>(flagKey: string, defaultValue: T, context?: FlagshipEvaluationContext): Promise<FlagshipEvaluationDetails<T>>;+}/*** Hello World binding to serve as an explanatory example. DO NOT USE*/@@ -10869,11 +12546,25 @@ type ImageTransform = {type ImageDrawOptions = {opacity?: number;repeat?: boolean | string;+ composite?: ImageCompositeMode;top?: number;left?: number;bottom?: number;right?: number;};+type ImageCompositeMode =+/** Foreground drawn on top of backdrop (default) */+'over'+/** Foreground shown only where backdrop is opaque */+ | 'in'+/** Foreground drawn on top, but clipped to the backdrop's shape */+ | 'atop'+/** Foreground shown only where backdrop is transparent */+ | 'out'+/** Foreground and backdrop visible only where the other is not */+ | 'xor'+/** Foreground and backdrop channels added (brightening) */+ | 'lighter';type ImageInputOptions = {encoding?: 'base64';};@@ -11296,7 +12987,7 @@ declare namespace Rpc {// The reason for using a generic type here is to build a serializable subset of structured// cloneable composite types. This allows types defined with the "interface" keyword to pass the// serializable check as well. Otherwise, only types defined with the "type" keyword would pass.- type Serializable<T> =+ type Serializable<T> =// Structured cloneablesBaseType// Structured cloneable composites@@ -11424,7 +13115,7 @@ declare namespace CloudflareWorkersModule {email?(message: ForwardableEmailMessage): void | Promise<void>;fetch?(request: Request): Response | Promise<Response>;connect?(socket: Socket): void | Promise<void>;- queue?(batch: MessageBatch<unknown>): void | Promise<void>;+ queue?(batch: MessageBatch): void | Promise<void>;scheduled?(controller: ScheduledController): void | Promise<void>;tail?(events: TraceItem[]): void | Promise<void>;tailStream?(event: TailStream.TailEvent<TailStream.Onset>): TailStream.TailEventHandlerType | Promise<TailStream.TailEventHandlerType>;@@ -11446,33 +13137,78 @@ declare namespace CloudflareWorkersModule {export type WorkflowDurationLabel = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year';export type WorkflowSleepDuration = `${number} ${WorkflowDurationLabel}${'s' | ''}` | number;export type WorkflowDelayDuration = WorkflowSleepDuration;+ export type WorkflowDynamicDelayContext = {+ ctx: WorkflowStepContext<WorkflowDelayFunction>;+ error: Error;+ };+ export type WorkflowDelayFunction = (input: WorkflowDynamicDelayContext) => WorkflowDelayDuration | Promise<WorkflowDelayDuration>;export type WorkflowTimeoutDuration = WorkflowSleepDuration;export type WorkflowRetentionDuration = WorkflowSleepDuration;export type WorkflowBackoff = 'constant' | 'linear' | 'exponential';+ export type WorkflowStepSensitivity = 'output';export type WorkflowStepConfig = {retries?: {limit: number;- delay: WorkflowDelayDuration | number;+ delay: WorkflowDelayDuration | number | WorkflowDelayFunction;backoff?: WorkflowBackoff;};timeout?: WorkflowTimeoutDuration | number;+ sensitive?: WorkflowStepSensitivity;+ };+ export type WorkflowStepRollbackConfig = Pick<WorkflowStepConfig, 'retries' | 'timeout'>;+ export type WorkflowCronSchedule = {+ /** Cron expression that triggered this event. */+ cron: string;+ /** Timestamp of the scheduled trigger, in milliseconds since the Unix epoch. */+ scheduledTime: number;};export type WorkflowEvent<T> = {payload: Readonly<T>;timestamp: Date;instanceId: string;+ workflowName: string;+ schedule?: WorkflowCronSchedule;};export type WorkflowStepEvent<T> = {payload: Readonly<T>;timestamp: Date;type: string;+ sensitive?: WorkflowStepSensitivity;};- export type WorkflowStepContext = {+ export type WorkflowStepContext<Delay = WorkflowDelayDuration | number> = {+ step: {+ name: string;+ count: number;+ };attempt: number;+ config: {+ retries?: {+ limit: number;+ backoff?: WorkflowBackoff;+ } & (Delay extends WorkflowDelayFunction ? {} : {+ delay: WorkflowDelayDuration | number;+ });+ timeout?: WorkflowTimeoutDuration | number;+ sensitive?: WorkflowStepSensitivity;+ };+ };+ export type WorkflowRollbackContext<T = unknown> = {+ ctx: WorkflowStepContext;+ error: Error;+ output: T | undefined;+ /** @deprecated Use `ctx.step.name` and `ctx.step.count` instead. */+ stepName: string;+ };+ export type WorkflowRollbackHandler<T = unknown> = (ctx: WorkflowRollbackContext<T>) => Promise<void>;+ export type WorkflowStepRollbackOptions<T = unknown> = {+ rollback: WorkflowRollbackHandler<T>;+ rollbackConfig?: WorkflowStepRollbackConfig;};export abstract class WorkflowStep {- do<T extends Rpc.Serializable<T>>(name: string, callback: (ctx: WorkflowStepContext) => Promise<T>): Promise<T>;- do<T extends Rpc.Serializable<T>>(name: string, config: WorkflowStepConfig, callback: (ctx: WorkflowStepContext) => Promise<T>): Promise<T>;+ do<T extends Rpc.Serializable<T>>(name: string, callback: (ctx: WorkflowStepContext) => Promise<T>, rollbackOptions?: WorkflowStepRollbackOptions<T>): Promise<T>;+ do<T extends Rpc.Serializable<T>, const C extends WorkflowStepConfig>(name: string, config: C, callback: (ctx: WorkflowStepContext<C['retries'] extends {+ delay: infer D;+ } ? D : WorkflowDelayDuration | number>) => Promise<T>, rollbackOptions?: WorkflowStepRollbackOptions<T>): Promise<T>;sleep: (name: string, duration: WorkflowSleepDuration) => Promise<void>;sleepUntil: (name: string, timestamp: Date | number) => Promise<void>;waitForEvent<T extends Rpc.Serializable<T>>(name: string, options: {@@ -11494,6 +13230,8 @@ declare namespace CloudflareWorkersModule {export function withEnvAndExports(newEnv: unknown, newExports: unknown, fn: () => unknown): unknown;export const env: Cloudflare.Env;export const exports: Cloudflare.Exports;+ export const cache: CacheContext;+ export const tracing: Tracing;}declare module 'cloudflare:workers' {export = CloudflareWorkersModule;@@ -12361,12 +14099,17 @@ declare namespace TailStream {interface ConnectEventInfo {readonly type: "connect";}- type EventOutcome = "ok" | "canceled" | "exception" | "unknown" | "killSwitch" | "daemonDown" | "exceededCpu" | "exceededMemory" | "loadShed" | "responseStreamDisconnected" | "scriptNotFound";+ type EventOutcome = "ok" | "canceled" | "exception" | "unknown" | "killSwitch" | "daemonDown" | "exceededCpu" | "exceededMemory" | "loadShed" | "responseStreamDisconnected" | "scriptNotFound" | "internalError" | "exceededWallTime";interface ScriptVersion {readonly id: string;readonly tag?: string;readonly message?: string;}+ interface TracePreviewInfo {+ readonly id: string;+ readonly slug: string;+ readonly name: string;+ }interface Onset {readonly type: "onset";readonly attributes: Attribute[];@@ -12375,9 +14118,11 @@ declare namespace TailStream {readonly dispatchNamespace?: string;readonly entrypoint?: string;readonly executionModel: string;+ readonly durableObjectId?: string;readonly scriptName?: string;readonly scriptTags?: string[];readonly scriptVersion?: ScriptVersion;+ readonly preview?: TracePreviewInfo;readonly info: FetchEventInfo | ConnectEventInfo | JsRpcEventInfo | ScheduledEventInfo | AlarmEventInfo | QueueEventInfo | EmailEventInfo | TraceEventInfo | HibernatableWebSocketEventInfo | CustomEventInfo;}interface Outcome {@@ -12454,6 +14199,9 @@ declare namespace TailStream {// 1. This is an Onset event// 2. We are not inheriting any SpanContext. (e.g. this is a cross-account service binding or a new top-level invocation)readonly spanId?: string;+ // W3C trace flags from an upstream traceparent. Absent when no upstream+ // sampling decision was made.+ readonly traceFlags?: number;}interface TailEvent<Event extends EventType> {// invocation id of the currently invoked worker stage.@@ -12727,6 +14475,103 @@ type WorkerVersionMetadata = {/** The timestamp of when the Worker Version was uploaded */timestamp: string;};+// ============ Web Search Request Types ============+/**+ * Options for a Web Search query.+ */+type WebSearchSearchOptions = {+ /** The search query. */+ query: string;+ /**+ * Maximum number of results to return. Defaults to 10, capped at 20.+ * The actual count may be lower if fewer matches exist.+ */+ limit?: number;+};+// ============ Web Search Response Types ============+/**+ * A single Web Search result.+ *+ * Web Search is discovery-only -- results carry catalog metadata about a page+ * but never the page body. To read a result's content the caller invokes the+ * global `fetch()` API against the result's `url`, at which point the+ * destination's own access controls apply (including Cloudflare Pay-per-Crawl).+ */+type WebSearchResult = {+ /** Canonical URL. */+ url: string;+ /** Page title. */+ title: string;+ /** Page-level description. May be absent. */+ description?: string;+ /**+ * Last-modified date for the page, when known. Naive (no timezone)+ * ISO-8601 datetime, e.g. `"2025-11-30T04:39:48"`.+ */+ lastModifiedDate?: string;+ /**+ * Page meta image URL (typically the `og:image`). May be absent.+ */+ imageUrl?: string;+ /** Optional favicon URL for UI hints. */+ faviconUrl?: string;+};+/**+ * Per-response metadata for a Web Search query. Carries operational+ * fields useful for support and debugging.+ */+type WebSearchResponseMetadata = {+ /** The query that was executed. */+ query: string;+ /** Opaque request identifier used for support and debugging. */+ requestId: string;+ /** End-to-end latency for this search request, in milliseconds. */+ latencyMs: number;+};+/**+ * Response from a Web Search query.+ */+type WebSearchSearchResponse = {+ items: WebSearchResult[];+ metadata: WebSearchResponseMetadata;+};+// ============ Web Search Binding Class ============+/**+ * Cloudflare Web Search binding.+ *+ * Discovery-only primitive for agents and Workers. Returns URLs and catalog+ * metadata for a query; never returns page content or excerpts. To read a+ * result's body, fetch the URL with the global `fetch()` API.+ *+ * Declared in wrangler with a single object (there is exactly one corpus, the+ * public web, so there is no name, namespace, or instance to specify):+ *+ * ```jsonc+ * { "web_search": { "binding": "WEBSEARCH" } }+ * ```+ *+ * @example+ * ```ts+ * const { items, metadata } = await env.WEBSEARCH.search({+ * query: "Cloudflare Workers",+ * });+ *+ * const top = items[0];+ * console.log(top.url, top.title, metadata.latencyMs);+ *+ * // Read content yourself; pay-per-crawl and other publisher+ * // controls apply at the fetch site, not at search time.+ * const page = await fetch(top.url);+ * ```+ */+declare abstract class WebSearch {+ /**+ * Run a Web Search query.+ * @param options Search options. Only `query` is required.+ * @returns The matching results plus per-response metadata.+ */+ search(options: WebSearchSearchOptions): Promise<WebSearchSearchResponse>;+}interface DynamicDispatchLimits {/*** Limit CPU time in milliseconds.@@ -12828,6 +14673,34 @@ interface WorkflowError {code?: number;message: string;}+interface WorkflowInstanceTerminateOptions {+ /**+ * If true, run registered rollback handlers before terminating the instance.+ * Only steps that registered rollback handlers are rolled back.+ */+ rollback?: boolean;+}+interface WorkflowInstanceRestartOptions {+ /**+ * Restart from a specific step. If omitted, the instance restarts from the beginning.+ * The step must exist in the instance's execution history.+ */+ from?: {+ /**+ * The step name as defined in your workflow code.+ */+ name: string;+ /**+ * 1-indexed occurrence of this step name. Use when the same step name appears multiple times (e.g. in a loop).+ * @default 1+ */+ count?: number;+ /**+ * Step type filter. Use when different step types share the same name.+ */+ type?: 'do' | 'sleep' | 'waitForEvent';+ };+}declare abstract class WorkflowInstance {public id: string;/**@@ -12840,12 +14713,15 @@ declare abstract class WorkflowInstance {public resume(): Promise<void>;/*** Terminate the instance. If it is errored, terminated or complete, an error will be thrown.+ * @param options Options for termination, including whether registered rollback handlers should run.*/- public terminate(): Promise<void>;+ public terminate(options?: WorkflowInstanceTerminateOptions): Promise<void>;/**- * Restart the instance.+ * Restart the instance. Optionally restart from a specific step, preserving+ * cached results for all steps before it.+ * @param options Options for the restart, including an optional step to restart from.*/- public restart(): Promise<void>;+ public restart(options?: WorkflowInstanceRestartOptions): Promise<void>;/*** Returns the current status of the instance.*/diff --git a/src/web/package.json b/src/web/package.jsonindex 8f4f3e2d6..8e2463c28 100644--- a/src/web/package.json+++ b/src/web/package.json@@ -6,6 +6,7 @@"dev": "next dev","build": "tsx scripts/validate-blog-assets.ts && next build","validate:blog": "tsx scripts/validate-blog-assets.ts",+ "preflight:bug-reports": "tsx scripts/preflight-bug-reports.ts","start": "next start","lint": "eslint src/","deploy": "opennextjs-cloudflare build && opennextjs-cloudflare deploy",diff --git a/src/web/scripts/preflight-bug-reports.test.ts b/src/web/scripts/preflight-bug-reports.test.tsnew file mode 100644index 000000000..04819d0cd--- /dev/null+++ b/src/web/scripts/preflight-bug-reports.test.ts@@ -0,0 +1,226 @@+import { spawnSync } from "node:child_process";+import { fileURLToPath } from "node:url";+import { describe, expect, it, vi } from "vitest";++interface PreflightResult {+ ok: boolean;+ checks: {+ bucketStandard: boolean;+ managedDomainDisabled: boolean;+ customDomainsEmpty: boolean;+ sevenDayLifecycle: boolean;+ };+}++interface PreflightModule {+ verifyBugReportR2Preflight(args: {+ accountId: string;+ bucketName: string;+ apiToken: string;+ fetchImpl?: typeof fetch;+ log?: (message: string) => void;+ }): Promise<PreflightResult>;+}++async function loadSubject(): Promise<PreflightModule> {+ return vi.importActual<PreflightModule>("./preflight-bug-reports.js");+}++const ACCOUNT = "0123456789abcdef0123456789abcdef";+const BUCKET = "alook-bug-reports";+const TOKEN = "CF_PRIVATE_PREFLIGHT_TOKEN";+const BASE = `https://api.cloudflare.com/client/v4/accounts/${ACCOUNT}/r2/buckets/${BUCKET}`;+const FAILED_CHECKS = {+ bucketStandard: false,+ managedDomainDisabled: false,+ customDomainsEmpty: false,+ sevenDayLifecycle: false,+} as const;++const validResults = {+ [BASE]: { name: BUCKET, storage_class: "Standard" },+ [`${BASE}/domains/managed`]: { bucketId: "bucket-id", domain: `${BUCKET}.r2.dev`, enabled: false },+ [`${BASE}/domains/custom`]: { domains: [] },+ [`${BASE}/lifecycle`]: {+ rules: [{+ id: "delete-bug-reports-after-seven-days",+ enabled: true,+ conditions: { prefix: "bug-reports/" },+ deleteObjectsTransition: { condition: { type: "Age", maxAge: 604_800 } },+ }],+ },+} as const;++function fixtureFetch(overrides: Record<string, unknown> = {}) {+ const calls: Array<{ url: string; init?: RequestInit }> = [];+ const values: Record<string, unknown> = { ...validResults, ...overrides };+ const fetchImpl = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input);+ calls.push({ url, init });+ if (!(url in values)) return Response.json({ success: false, errors: [] }, { status: 404 });+ return Response.json({ success: true, errors: [], messages: [], result: values[url] });+ });+ return { calls, fetchImpl: fetchImpl as typeof fetch };+}++describe("B2d read-only bug-report R2 preflight", () => {+ it("runs the package CLI fail-closed without credentials", () => {+ const packageRoot = fileURLToPath(new URL("..", import.meta.url));+ const secretMarker = "PREFLIGHT_SECRET_MUST_NOT_LEAK";+ const child = spawnSync("pnpm", ["preflight:bug-reports"], {+ cwd: packageRoot,+ encoding: "utf8",+ env: {+ ...process.env,+ CLOUDFLARE_ACCOUNT_ID: "",+ CLOUDFLARE_API_TOKEN: "",+ UNRELATED_PREFLIGHT_SECRET: secretMarker,+ },+ timeout: 10_000,+ });++ expect(child.error).toBeUndefined();+ expect(child.status).toBe(1);+ const jsonLines = child.stdout.split("\n").map((line) => line.trim()).filter((line) => line.startsWith("{"));+ expect(jsonLines).toHaveLength(1);+ expect(JSON.parse(jsonLines[0] ?? "null")).toEqual({+ ok: false,+ checks: FAILED_CHECKS,+ });+ expect(`${child.stdout}\n${child.stderr}`).not.toContain(secretMarker);+ });++ it("passes only the exact private Standard bucket and seven-day lifecycle contract", async () => {+ const api = await loadSubject();+ const fixture = fixtureFetch();+ const logs: string[] = [];++ await expect(api.verifyBugReportR2Preflight({+ accountId: ACCOUNT,+ bucketName: BUCKET,+ apiToken: TOKEN,+ fetchImpl: fixture.fetchImpl,+ log: (message) => logs.push(message),+ })).resolves.toEqual({+ ok: true,+ checks: {+ bucketStandard: true,+ managedDomainDisabled: true,+ customDomainsEmpty: true,+ sevenDayLifecycle: true,+ },+ });++ expect(fixture.calls.map((call) => call.url)).toEqual([+ BASE,+ `${BASE}/domains/managed`,+ `${BASE}/domains/custom`,+ `${BASE}/lifecycle`,+ ]);+ for (const call of fixture.calls) {+ expect(call.init?.method ?? "GET").toBe("GET");+ expect(new Headers(call.init?.headers).get("authorization")).toBe(`Bearer ${TOKEN}`);+ expect(call.init?.body).toBeUndefined();+ }+ expect(JSON.stringify(logs)).not.toContain(TOKEN);+ });++ it.each([+ ["bucket missing", { [BASE]: undefined }],+ ["non-Standard default", { [BASE]: { name: BUCKET, storage_class: "InfrequentAccess" } }],+ ["missing storage class", { [BASE]: { name: BUCKET } }],+ ["r2.dev enabled", { [`${BASE}/domains/managed`]: { enabled: true } }],+ ["managed response malformed", { [`${BASE}/domains/managed`]: {} }],+ ["one custom domain", { [`${BASE}/domains/custom`]: { domains: [{ domain: "public.example", enabled: false }] } }],+ ["custom response malformed", { [`${BASE}/domains/custom`]: {} }],+ ["lifecycle missing", { [`${BASE}/lifecycle`]: { rules: [] } }],+ ["lifecycle disabled", { [`${BASE}/lifecycle`]: { rules: [{+ enabled: false,+ conditions: { prefix: "bug-reports/" },+ deleteObjectsTransition: { condition: { type: "Age", maxAge: 604_800 } },+ }] } }],+ ["wrong prefix", { [`${BASE}/lifecycle`]: { rules: [{+ enabled: true,+ conditions: { prefix: "" },+ deleteObjectsTransition: { condition: { type: "Age", maxAge: 604_800 } },+ }] } }],+ ["wrong age", { [`${BASE}/lifecycle`]: { rules: [{+ enabled: true,+ conditions: { prefix: "bug-reports/" },+ deleteObjectsTransition: { condition: { type: "Age", maxAge: 604_801 } },+ }] } }],+ ["date transition", { [`${BASE}/lifecycle`]: { rules: [{+ enabled: true,+ conditions: { prefix: "bug-reports/" },+ deleteObjectsTransition: { condition: { type: "Date", date: "2026-08-19T00:00:00Z" } },+ }] } }],+ ["duplicate matching rules", { [`${BASE}/lifecycle`]: { rules: [+ validResults[`${BASE}/lifecycle`].rules[0],+ validResults[`${BASE}/lifecycle`].rules[0],+ ] } }],+ ["additional deletion rule", { [`${BASE}/lifecycle`]: { rules: [+ validResults[`${BASE}/lifecycle`].rules[0],+ {+ enabled: true,+ conditions: { prefix: "" },+ deleteObjectsTransition: { condition: { type: "Age", maxAge: 86_400 } },+ },+ ] } }],+ ])("fails closed for %s", async (_name, overrides) => {+ const api = await loadSubject();+ const fixture = fixtureFetch(overrides);++ const result = await api.verifyBugReportR2Preflight({+ accountId: ACCOUNT,+ bucketName: BUCKET,+ apiToken: TOKEN,+ fetchImpl: fixture.fetchImpl,+ });++ expect(result.ok).toBe(false);+ });++ it("fails closed on non-OK, API success=false, malformed JSON, and network errors", async () => {+ const api = await loadSubject();+ const outcomes = [+ vi.fn(async () => new Response("unavailable", { status: 503 })),+ vi.fn(async () => Response.json({ success: false, result: null, errors: [{ message: TOKEN }] })),+ vi.fn(async () => new Response("{", { status: 200 })),+ vi.fn(async () => { throw new Error(`network ${TOKEN}`); }),+ ];++ for (const fetchImpl of outcomes) {+ const logs: string[] = [];+ await expect(api.verifyBugReportR2Preflight({+ accountId: ACCOUNT,+ bucketName: BUCKET,+ apiToken: TOKEN,+ fetchImpl: fetchImpl as typeof fetch,+ log: (message) => logs.push(message),+ })).resolves.toMatchObject({ ok: false });+ expect(JSON.stringify(logs)).not.toContain(TOKEN);+ }+ });++ it("rejects unsafe or missing inputs before any network request", async () => {+ const api = await loadSubject();+ const fetchImpl = vi.fn();++ for (const [accountId, bucketName, apiToken] of [+ ["../account", BUCKET, TOKEN],+ [ACCOUNT, "../bucket", TOKEN],+ ["", BUCKET, TOKEN],+ [ACCOUNT, "", TOKEN],+ [ACCOUNT, BUCKET, ""],+ [ACCOUNT, BUCKET, " "],+ ]) {+ await expect(api.verifyBugReportR2Preflight({+ accountId,+ bucketName,+ apiToken,+ fetchImpl: fetchImpl as typeof fetch,+ })).resolves.toMatchObject({ ok: false });+ }+ expect(fetchImpl).not.toHaveBeenCalled();+ });+});diff --git a/src/web/scripts/preflight-bug-reports.ts b/src/web/scripts/preflight-bug-reports.tsnew file mode 100644index 000000000..c3685a4fb--- /dev/null+++ b/src/web/scripts/preflight-bug-reports.ts@@ -0,0 +1,109 @@+interface CloudflareEnvelope {+ success?: unknown;+ result?: unknown;+}++export interface BugReportPreflightResult {+ ok: boolean;+ checks: {+ bucketStandard: boolean;+ managedDomainDisabled: boolean;+ customDomainsEmpty: boolean;+ sevenDayLifecycle: boolean;+ };+}++const failedChecks = (): BugReportPreflightResult["checks"] => ({+ bucketStandard: false,+ managedDomainDisabled: false,+ customDomainsEmpty: false,+ sevenDayLifecycle: false,+});++function record(value: unknown): Record<string, unknown> | null {+ return value !== null && typeof value === "object" && !Array.isArray(value)+ ? value as Record<string, unknown>+ : null;+}++async function readResult(+ fetchImpl: typeof fetch,+ url: string,+ apiToken: string,+): Promise<unknown> {+ const response = await fetchImpl(url, {+ method: "GET",+ headers: { authorization: `Bearer ${apiToken}` },+ });+ if (!response.ok) throw new Error("Cloudflare API request failed");+ const envelope = await response.json() as CloudflareEnvelope;+ if (envelope.success !== true || !("result" in envelope)) {+ throw new Error("Cloudflare API response was unsuccessful");+ }+ return envelope.result;+}++export async function verifyBugReportR2Preflight(args: {+ accountId: string;+ bucketName: string;+ apiToken: string;+ fetchImpl?: typeof fetch;+ log?: (message: string) => void;+}): Promise<BugReportPreflightResult> {+ const fail = (): BugReportPreflightResult => ({ ok: false, checks: failedChecks() });+ if (!/^[0-9a-f]{32}$/.test(args.accountId)+ || !/^[a-z0-9](?:[a-z0-9.-]{1,61}[a-z0-9])?$/.test(args.bucketName)+ || args.apiToken.trim().length === 0) {+ return fail();+ }++ const fetchImpl = args.fetchImpl ?? fetch;+ const base = `https://api.cloudflare.com/client/v4/accounts/${args.accountId}/r2/buckets/${args.bucketName}`;+ try {+ const bucket = record(await readResult(fetchImpl, base, args.apiToken));+ const managed = record(await readResult(fetchImpl, `${base}/domains/managed`, args.apiToken));+ const custom = record(await readResult(fetchImpl, `${base}/domains/custom`, args.apiToken));+ const lifecycle = record(await readResult(fetchImpl, `${base}/lifecycle`, args.apiToken));++ const rules = Array.isArray(lifecycle?.rules) ? lifecycle.rules : [];+ const matchingRules = rules.filter((value) => {+ const rule = record(value);+ const conditions = record(rule?.conditions);+ const transition = record(rule?.deleteObjectsTransition);+ const condition = record(transition?.condition);+ return rule?.enabled === true+ && conditions?.prefix === "bug-reports/"+ && condition?.type === "Age"+ && condition?.maxAge === 604_800;+ });+ const checks = {+ bucketStandard: bucket?.storage_class === "Standard",+ managedDomainDisabled: managed?.enabled === false,+ customDomainsEmpty: Array.isArray(custom?.domains) && custom.domains.length === 0,+ sevenDayLifecycle: rules.length === 1 && matchingRules.length === 1,+ };+ return { ok: Object.values(checks).every(Boolean), checks };+ } catch {+ args.log?.("bug-report R2 preflight failed closed");+ return fail();+ }+}++async function main(): Promise<void> {+ const result = await verifyBugReportR2Preflight({+ accountId: process.env.CLOUDFLARE_ACCOUNT_ID ?? "",+ bucketName: process.env.BUG_REPORTS_BUCKET_NAME ?? "alook-bug-reports",+ apiToken: process.env.CLOUDFLARE_API_TOKEN ?? "",+ log: (message) => process.stderr.write(`${message}\n`),+ });+ process.stdout.write(`${JSON.stringify(result)}\n`);+ if (!result.ok) process.exitCode = 1;+}++if (import.meta.url === `file://${process.argv[1]}`) {+ void main().catch(() => {+ process.stderr.write("bug-report R2 preflight failed closed\n");+ process.stdout.write(`${JSON.stringify({ ok: false, checks: failedChecks() })}\n`);+ process.exitCode = 1;+ });+}diff --git a/src/web/src/app/api/community/daemon/diagnostics/[reportId]/bundle/route.test.ts b/src/web/src/app/api/community/daemon/diagnostics/[reportId]/bundle/route.test.tsnew file mode 100644index 000000000..413ea65db--- /dev/null+++ b/src/web/src/app/api/community/daemon/diagnostics/[reportId]/bundle/route.test.ts@@ -0,0 +1,153 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { NextRequest, NextResponse } from "next/server";++const upload = vi.fn();+const queryPort = { diagnosticQueries: true };+const createQueryPort = vi.fn(() => queryPort);+const createService = vi.fn(() => ({ upload, fail: vi.fn() }));++vi.mock("@/lib/community/diagnostic-upload", () => ({+ createDiagnosticUploadQueryPort: (...args: unknown[]) => createQueryPort(...args),+ createDiagnosticUploadService: (...args: unknown[]) => createService(...args),+}));++vi.mock("@/lib/db", () => ({ getDb: () => ({ diagnosticDb: true }) }));++vi.mock("@/lib/middleware/community-daemon-auth", () => ({+ withCommunityDaemonAuth: (handler: (...args: unknown[]) => Promise<Response>) =>+ async (request: NextRequest, context?: { params?: Promise<Record<string, string>> }) => {+ if (request.headers.get("authorization") !== "Bearer cmk_valid") {+ return NextResponse.json({ error: "unauthorized" }, { status: 401 });+ }+ return handler(request, {+ env: { DB: {}, BUG_REPORTS: { privateBucket: true }, BUG_REPORTS_ENABLED: "false" },+ machineId: "cm_original",+ userId: "owner_1",+ credentialId: "cred_1",+ params: await context?.params,+ });+ },+}));++interface BundleRouteModule {+ PUT(request: NextRequest, context: { params: Promise<{ reportId: string }> }): Promise<Response>;+}++async function loadSubject(): Promise<BundleRouteModule> {+ return vi.importActual<BundleRouteModule>("./route.js");+}++const REPORT_ID = "dbr_0123456789abcdef";+const SHA256 = "a".repeat(64);+const BODY = new Uint8Array([1, 2, 3, 4]);+const context = { params: Promise.resolve({ reportId: REPORT_ID }) };++function request(overrides: {+ authorization?: string;+ headers?: Record<string, string>;+ omitHeaders?: string[];+ body?: BodyInit | null;+} = {}): NextRequest {+ const headers = new Headers({+ authorization: overrides.authorization ?? "Bearer cmk_valid",+ "content-type": "application/x-ndjson",+ "content-encoding": "gzip",+ "content-length": String(BODY.byteLength),+ "x-alook-content-sha256": SHA256,+ ...overrides.headers,+ });+ for (const name of overrides.omitHeaders ?? []) headers.delete(name);+ return new NextRequest(`http://localhost/api/community/daemon/diagnostics/${REPORT_ID}/bundle`, {+ method: "PUT",+ headers,+ body: overrides.body === undefined ? BODY : overrides.body,+ });+}++describe("PUT /api/community/daemon/diagnostics/:reportId/bundle", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ upload.mockResolvedValue({ kind: "terminal", status: "uploaded" });+ });++ it("requires cmk authentication before upload work", async () => {+ const api = await loadSubject();++ expect((await api.PUT(request({ authorization: "Bearer cmt_pairing" }), context)).status).toBe(401);+ expect((await api.PUT(request({ authorization: "" }), context)).status).toBe(401);+ expect(createService).not.toHaveBeenCalled();+ expect(upload).not.toHaveBeenCalled();+ });++ it("ignores the false creation flag and drains an existing report for the authenticated machine", async () => {+ const api = await loadSubject();+ const response = await api.PUT(request(), context);++ expect(createQueryPort).toHaveBeenCalledWith({ diagnosticDb: true });+ expect(createService).toHaveBeenCalledWith(expect.objectContaining({+ bucket: { privateBucket: true },+ queries: queryPort,+ }));+ expect(upload).toHaveBeenCalledWith({+ reportId: REPORT_ID,+ machineId: "cm_original",+ sizeBytes: BODY.byteLength,+ sha256: SHA256,+ body: expect.any(ReadableStream),+ });+ expect(response.status).toBe(200);+ await expect(response.json()).resolves.toEqual({ kind: "terminal", status: "uploaded" });+ });++ it.each([+ ["invalid report id", { params: Promise.resolve({ reportId: "../foreign" }) }, request()],+ ["missing content type", context, request({ omitHeaders: ["content-type"] })],+ ["wrong content type", context, request({ headers: { "content-type": "application/gzip" } })],+ ["combined content type", context, request({ headers: { "content-type": "application/x-ndjson, application/x-ndjson" } })],+ ["absent encoding", context, request({ omitHeaders: ["content-encoding"] })],+ ["missing encoding", context, request({ headers: { "content-encoding": "" } })],+ ["combined encoding", context, request({ headers: { "content-encoding": "gzip, gzip" } })],+ ["missing length", context, request({ omitHeaders: ["content-length"] })],+ ["zero length", context, request({ headers: { "content-length": "0" } })],+ ["leading-zero length", context, request({ headers: { "content-length": "04" } })],+ ["signed length", context, request({ headers: { "content-length": "+4" } })],+ ["oversized length", context, request({ headers: { "content-length": String(10 * 1024 * 1024 + 1) } })],+ ["combined length", context, request({ headers: { "content-length": "4, 4" } })],+ ["missing checksum", context, request({ omitHeaders: ["x-alook-content-sha256"] })],+ ["short checksum", context, request({ headers: { "x-alook-content-sha256": "a".repeat(63) } })],+ ["uppercase checksum", context, request({ headers: { "x-alook-content-sha256": "A".repeat(64) } })],+ ["combined checksum", context, request({ headers: { "x-alook-content-sha256": `${SHA256},${SHA256}` } })],+ ])("rejects %s before R2/query service work", async (_name, targetContext, targetRequest) => {+ const api = await loadSubject();+ const response = await api.PUT(targetRequest, targetContext);++ expect(response.status).toBe(400);+ expect(createService).not.toHaveBeenCalled();+ expect(upload).not.toHaveBeenCalled();+ });++ it("rejects a null body before upload work", async () => {+ const api = await loadSubject();+ const response = await api.PUT(request({ body: null }), context);++ expect(response.status).toBe(400);+ expect(upload).not.toHaveBeenCalled();+ });++ it.each([+ { name: "uploaded terminal", outcome: { kind: "terminal", status: "uploaded" }, status: 200 },+ { name: "failed terminal", outcome: { kind: "terminal", status: "failed" }, status: 409 },+ { name: "retryable", outcome: { kind: "retryable" }, status: 503 },+ { name: "rejected 400", outcome: { kind: "rejected", status: 400 }, status: 400 },+ { name: "rejected 404", outcome: { kind: "rejected", status: 404 }, status: 404 },+ { name: "rejected 409", outcome: { kind: "rejected", status: 409 }, status: 409 },+ ])("maps the strict $name service outcome to HTTP $status", async ({ outcome, status }) => {+ const api = await loadSubject();+ upload.mockResolvedValue(outcome);++ const response = await api.PUT(request(), context);++ expect(response.status).toBe(status);+ await expect(response.json()).resolves.toEqual(outcome);+ });+});diff --git a/src/web/src/app/api/community/daemon/diagnostics/[reportId]/bundle/route.ts b/src/web/src/app/api/community/daemon/diagnostics/[reportId]/bundle/route.tsnew file mode 100644index 000000000..ef502300a--- /dev/null+++ b/src/web/src/app/api/community/daemon/diagnostics/[reportId]/bundle/route.ts@@ -0,0 +1,55 @@+import { NextResponse } from "next/server";+import { DiagnosticReportIdSchema } from "@alook/shared";+import { getDb } from "@/lib/db";+import { withCommunityDaemonAuth } from "@/lib/middleware/community-daemon-auth";+import {+ createDiagnosticUploadQueryPort,+ createDiagnosticUploadService,+ type DiagnosticUploadResult,+} from "@/lib/community/diagnostic-upload";++const MAX_BUNDLE_BYTES = 10 * 1024 * 1024;++function responseStatus(result: DiagnosticUploadResult): number {+ if (result.kind === "retryable") return 503;+ if (result.kind === "rejected") return result.status;+ return result.status === "uploaded" ? 200 : 409;+}++export const PUT = withCommunityDaemonAuth(async (request, ctx) => {+ const parsedReportId = DiagnosticReportIdSchema.safeParse(ctx.params?.reportId);+ if (!parsedReportId.success) {+ return NextResponse.json({ error: "invalid diagnostic report id" }, { status: 400 });+ }+ const reportId = parsedReportId.data;+ if (request.headers.get("content-type") !== "application/x-ndjson"+ || request.headers.get("content-encoding") !== "gzip") {+ return NextResponse.json({ error: "invalid diagnostic content headers" }, { status: 400 });+ }+ const rawLength = request.headers.get("content-length");+ if (!rawLength || !/^[1-9][0-9]*$/.test(rawLength)) {+ return NextResponse.json({ error: "invalid diagnostic content length" }, { status: 400 });+ }+ const sizeBytes = Number(rawLength);+ if (!Number.isSafeInteger(sizeBytes) || sizeBytes > MAX_BUNDLE_BYTES) {+ return NextResponse.json({ error: "invalid diagnostic content length" }, { status: 400 });+ }+ const sha256 = request.headers.get("x-alook-content-sha256");+ if (!sha256 || !/^[0-9a-f]{64}$/.test(sha256) || request.body === null) {+ return NextResponse.json({ error: "invalid diagnostic upload" }, { status: 400 });+ }++ const db = getDb(ctx.env.DB);+ const service = createDiagnosticUploadService({+ bucket: ctx.env.BUG_REPORTS,+ queries: createDiagnosticUploadQueryPort(db),+ });+ const result = await service.upload({+ reportId,+ machineId: ctx.machineId,+ sizeBytes,+ sha256,+ body: request.body,+ });+ return NextResponse.json(result, { status: responseStatus(result) });+});diff --git a/src/web/src/app/api/community/daemon/diagnostics/[reportId]/route.test.ts b/src/web/src/app/api/community/daemon/diagnostics/[reportId]/route.test.tsnew file mode 100644index 000000000..b99bbf9f2--- /dev/null+++ b/src/web/src/app/api/community/daemon/diagnostics/[reportId]/route.test.ts@@ -0,0 +1,145 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { NextRequest, NextResponse } from "next/server";++const fail = vi.fn();+const queryPort = { diagnosticQueries: true };+const createQueryPort = vi.fn(() => queryPort);+const createService = vi.fn(() => ({ upload: vi.fn(), fail }));++vi.mock("@/lib/community/diagnostic-upload", () => ({+ createDiagnosticUploadQueryPort: (...args: unknown[]) => createQueryPort(...args),+ createDiagnosticUploadService: (...args: unknown[]) => createService(...args),+}));++vi.mock("@/lib/db", () => ({ getDb: () => ({ diagnosticDb: true }) }));++vi.mock("@/lib/middleware/community-daemon-auth", () => ({+ withCommunityDaemonAuth: (handler: (...args: unknown[]) => Promise<Response>) =>+ async (request: NextRequest, context?: { params?: Promise<Record<string, string>> }) => {+ if (request.headers.get("authorization") !== "Bearer cmk_valid") {+ return NextResponse.json({ error: "unauthorized" }, { status: 401 });+ }+ return handler(request, {+ env: { DB: {}, BUG_REPORTS: { privateBucket: true }, BUG_REPORTS_ENABLED: "false" },+ machineId: "cm_original",+ userId: "owner_1",+ credentialId: "cred_1",+ params: await context?.params,+ });+ },+}));++interface FailureRouteModule {+ PATCH(request: NextRequest, context: { params: Promise<{ reportId: string }> }): Promise<Response>;+}++async function loadSubject(): Promise<FailureRouteModule> {+ return vi.importActual<FailureRouteModule>("./route.js");+}++const REPORT_ID = "dbr_0123456789abcdef";+const context = { params: Promise.resolve({ reportId: REPORT_ID }) };+const DAEMON_FAILURE_CODES = [+ "diagnostics_unavailable",+ "collector_busy",+ "bot_not_bound",+ "collection_failed",+ "local_artifact_invalid",+ "bundle_too_large",+ "upload_failed",+] as const;++function request(body: unknown, authorization = "Bearer cmk_valid"): NextRequest {+ return new NextRequest(`http://localhost/api/community/daemon/diagnostics/${REPORT_ID}`, {+ method: "PATCH",+ headers: { authorization, "content-type": "application/json" },+ body: JSON.stringify(body),+ });+}++describe("PATCH /api/community/daemon/diagnostics/:reportId", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ fail.mockResolvedValue({ kind: "terminal", status: "failed" });+ });++ it("requires cmk authentication before failure work", async () => {+ const api = await loadSubject();+ const response = await api.PATCH(+ request({ status: "failed", failureCode: "upload_failed" }, "Bearer cmt_pairing"),+ context,+ );++ expect(response.status).toBe(401);+ expect(fail).not.toHaveBeenCalled();+ });++ it.each(DAEMON_FAILURE_CODES)("accepts daemon failure code %s while the creation flag is false", async (failureCode) => {+ const api = await loadSubject();+ const response = await api.PATCH(request({ status: "failed", failureCode }), context);++ expect(createQueryPort).toHaveBeenCalledWith({ diagnosticDb: true });+ expect(createService).toHaveBeenCalledWith(expect.objectContaining({+ bucket: { privateBucket: true },+ queries: queryPort,+ }));+ expect(fail).toHaveBeenCalledWith({+ reportId: REPORT_ID,+ machineId: "cm_original",+ failureCode,+ });+ expect(response.status).toBe(200);+ await expect(response.json()).resolves.toEqual({ kind: "terminal", status: "failed" });+ });++ it.each([+ ["missing status", { failureCode: "upload_failed" }],+ ["wrong status", { status: "uploaded", failureCode: "upload_failed" }],+ ["missing failure", { status: "failed" }],+ ["server-owned failure", { status: "failed", failureCode: "offline" }],+ ["server internal failure", { status: "failed", failureCode: "internal_error" }],+ ["unknown failure", { status: "failed", failureCode: "hostile_secret" }],+ ["unknown key", { status: "failed", failureCode: "upload_failed", detail: "private" }],+ ])("rejects a strict body with %s", async (_name, body) => {+ const api = await loadSubject();+ const response = await api.PATCH(request(body), context);++ expect(response.status).toBe(400);+ expect(fail).not.toHaveBeenCalled();+ });++ it("rejects malformed JSON and an invalid report id", async () => {+ const api = await loadSubject();+ const malformed = new NextRequest(`http://localhost/api/community/daemon/diagnostics/${REPORT_ID}`, {+ method: "PATCH",+ headers: { authorization: "Bearer cmk_valid", "content-type": "application/json" },+ body: "{",+ });++ expect((await api.PATCH(malformed, context)).status).toBe(400);+ expect((await api.PATCH(+ request({ status: "failed", failureCode: "upload_failed" }),+ { params: Promise.resolve({ reportId: "../foreign" }) },+ )).status).toBe(400);+ expect(fail).not.toHaveBeenCalled();+ });++ it.each([+ { name: "failed terminal", outcome: { kind: "terminal", status: "failed" }, status: 200 },+ { name: "uploaded terminal", outcome: { kind: "terminal", status: "uploaded" }, status: 409 },+ { name: "retryable", outcome: { kind: "retryable" }, status: 503 },+ { name: "rejected 404", outcome: { kind: "rejected", status: 404 }, status: 404 },+ { name: "rejected 409", outcome: { kind: "rejected", status: 409 }, status: 409 },+ ])("maps the $name service outcome to HTTP $status", async ({ outcome, status }) => {+ const api = await loadSubject();+ fail.mockResolvedValue(outcome);++ const response = await api.PATCH(+ request({ status: "failed", failureCode: "upload_failed" }),+ context,+ );++ expect(response.status).toBe(status);+ await expect(response.json()).resolves.toEqual(outcome);+ });+});diff --git a/src/web/src/app/api/community/daemon/diagnostics/[reportId]/route.ts b/src/web/src/app/api/community/daemon/diagnostics/[reportId]/route.tsnew file mode 100644index 000000000..796e47795--- /dev/null+++ b/src/web/src/app/api/community/daemon/diagnostics/[reportId]/route.ts@@ -0,0 +1,69 @@+import { NextResponse } from "next/server";+import {+ DiagnosticReportIdSchema,+ type DiagnosticReportFailureCode,+} from "@alook/shared";+import { getDb } from "@/lib/db";+import { withCommunityDaemonAuth } from "@/lib/middleware/community-daemon-auth";+import {+ createDiagnosticUploadQueryPort,+ createDiagnosticUploadService,+ type DiagnosticUploadResult,+} from "@/lib/community/diagnostic-upload";++const DAEMON_FAILURE_CODES = new Set<DiagnosticReportFailureCode>([+ "diagnostics_unavailable",+ "collector_busy",+ "bot_not_bound",+ "collection_failed",+ "local_artifact_invalid",+ "bundle_too_large",+ "upload_failed",+]);++function responseStatus(result: DiagnosticUploadResult): number {+ if (result.kind === "retryable") return 503;+ if (result.kind === "rejected") return result.status;+ return result.status === "failed" ? 200 : 409;+}++function parseFailure(value: unknown): DiagnosticReportFailureCode | null {+ if (value === null || typeof value !== "object" || Array.isArray(value)) return null;+ const body = value as Record<string, unknown>;+ if (Object.keys(body).length !== 2 || body.status !== "failed" || typeof body.failureCode !== "string") {+ return null;+ }+ return DAEMON_FAILURE_CODES.has(body.failureCode as DiagnosticReportFailureCode)+ ? body.failureCode as DiagnosticReportFailureCode+ : null;+}++export const PATCH = withCommunityDaemonAuth(async (request, ctx) => {+ const parsedReportId = DiagnosticReportIdSchema.safeParse(ctx.params?.reportId);+ if (!parsedReportId.success) {+ return NextResponse.json({ error: "invalid diagnostic report id" }, { status: 400 });+ }+ const reportId = parsedReportId.data;+ let value: unknown;+ try {+ value = await request.json();+ } catch {+ return NextResponse.json({ error: "invalid diagnostic failure body" }, { status: 400 });+ }+ const failureCode = parseFailure(value);+ if (!failureCode) {+ return NextResponse.json({ error: "invalid diagnostic failure body" }, { status: 400 });+ }++ const db = getDb(ctx.env.DB);+ const service = createDiagnosticUploadService({+ bucket: ctx.env.BUG_REPORTS,+ queries: createDiagnosticUploadQueryPort(db),+ });+ const result = await service.fail({+ reportId,+ machineId: ctx.machineId,+ failureCode,+ });+ return NextResponse.json(result, { status: responseStatus(result) });+});diff --git a/src/web/src/env.d.ts b/src/web/src/env.d.tsindex ae4a2a9ca..982bece1c 100644--- a/src/web/src/env.d.ts+++ b/src/web/src/env.d.ts@@ -1,8 +1,19 @@+interface RuntimeEnv {+ ENCRYPTION_KEY: string+ AUTH_OTP_RATE_LIMIT_MAX?: string+ AUTH_OTP_RATE_LIMIT_WINDOW_SEC?: string+ DEVICE_CLIENT_IDS?: string+ NODE_ENV?: string+ DEV_WS_DO_URL?: string+ DEV_WAKE_WORKER_URL?: string+}+declare namespace Cloudflare {- interface Env {+ interface Env extends RuntimeEnv {DB: D1DatabaseEMAIL_BUCKET: R2BucketCOMMUNITY_MEDIA: R2Bucket+ BUG_REPORTS: R2BucketWS_DO_WORKER: FetcherEMAIL_WORKER: FetcherWAKE_QUEUE: Queue<import("@alook/shared").WakePayload>@@ -17,18 +28,16 @@ declare namespace Cloudflare {GOOGLE_CLIENT_SECRET: stringBETTER_AUTH_SECRET: stringBETTER_AUTH_URL: string- ENCRYPTION_KEY: stringCACHE_KV: KVNamespace- AUTH_OTP_RATE_LIMIT_MAX?: string- AUTH_OTP_RATE_LIMIT_WINDOW_SEC?: stringBUG_REPORTS_ENABLED?: stringRUNTIME_MODEL_OPTIONS?: stringMIN_CLI_VERSION?: string- DEVICE_CLIENT_IDS?: string- NODE_ENV?: string- DEV_WS_DO_URL?: string- DEV_WAKE_WORKER_URL?: string}}type Env = CloudflareEnv++// Wrangler 4.119 emits CloudflareEnv from config bindings directly. Merge the+// app's non-config runtime variables above back into that generated interface.+// eslint-disable-next-line @typescript-eslint/no-empty-object-type+interface CloudflareEnv extends RuntimeEnv {}diff --git a/src/web/src/lib/community/diagnostic-upload.test.ts b/src/web/src/lib/community/diagnostic-upload.test.tsnew file mode 100644index 000000000..37d8ca069--- /dev/null+++ b/src/web/src/lib/community/diagnostic-upload.test.ts@@ -0,0 +1,733 @@+import { createHash } from "node:crypto";+import { beforeEach, describe, expect, it, vi } from "vitest";++type ReportRow = {+ id: string;+ ownerUserId: string;+ machineId: string;+ status: "pending" | "uploaded" | "failed";+ deadlineAt: number;+ failureCode: string | null;+ r2Key: string | null;+ sha256: string | null;+ sizeBytes: number | null;+};++type UploadResult =+ | { kind: "terminal"; status: "uploaded" | "failed" }+ | { kind: "retryable" }+ | { kind: "rejected"; status: 400 | 404 | 409 };++interface QueryPort {+ getPending(input: { reportId: string; machineId: string; nowMs: number }): Promise<ReportRow | null>;+ get(input: { reportId: string; machineId: string }): Promise<ReportRow | null>;+ finalize(input: {+ reportId: string;+ machineId: string;+ r2Key: string;+ sha256: string;+ sizeBytes: number;+ nowMs: number;+ }): Promise<ReportRow | null>;+ fail(input: {+ reportId: string;+ machineId: string;+ failureCode: string;+ nowMs: number;+ }): Promise<ReportRow | null>;+ timeout(input: { reportId: string; ownerUserId: string; nowMs: number }): Promise<ReportRow | null>;+}++interface R2Port {+ put(key: string, body: ReadableStream<Uint8Array>, options: Record<string, unknown>): Promise<unknown | null>;+ head(key: string): Promise<{+ size: number;+ checksums?: { sha256?: ArrayBuffer };+ } | null>;+ delete(key: string): Promise<void>;+}++interface DiagnosticUploadModule {+ createDiagnosticUploadService(args: {+ bucket: R2Port;+ queries: QueryPort;+ now: () => number;+ fixedLengthStream: (sizeBytes: number) => {+ readable: ReadableStream<Uint8Array>;+ writable: WritableStream<Uint8Array>;+ };+ }): {+ upload(args: {+ reportId: string;+ machineId: string;+ sizeBytes: number;+ sha256: string;+ body: ReadableStream<Uint8Array>;+ }): Promise<UploadResult>;+ fail(args: {+ reportId: string;+ machineId: string;+ failureCode: string;+ }): Promise<UploadResult>;+ };+}++async function loadSubject(): Promise<DiagnosticUploadModule> {+ return vi.importActual<DiagnosticUploadModule>("./diagnostic-upload.js");+}++const NOW = 1_700_086_400_000;+const REPORT_ID = "dbr_0123456789abcdef";+const MACHINE_ID = "cm_machine_original";+const OWNER_ID = "owner_private";+const SHA256 = createHash("sha256").update("bundle").digest("hex");+const KEY = `bug-reports/${OWNER_ID}/${REPORT_ID}.ndjson.gz`;++function row(overrides: Partial<ReportRow> = {}): ReportRow {+ return {+ id: REPORT_ID,+ ownerUserId: OWNER_ID,+ machineId: MACHINE_ID,+ status: "pending",+ deadlineAt: NOW + 600_000,+ failureCode: null,+ r2Key: null,+ sha256: null,+ sizeBytes: null,+ ...overrides,+ };+}++function bytes(value = "bundle"): ReadableStream<Uint8Array> {+ return new ReadableStream({+ start(controller) {+ controller.enqueue(new TextEncoder().encode(value));+ controller.close();+ },+ });+}++function gatedBytes(value: string, onRead: () => void, release: Promise<void>): ReadableStream<Uint8Array> {+ let emitted = false;+ return new ReadableStream({+ async pull(controller) {+ if (emitted) return;+ emitted = true;+ onRead();+ await release;+ controller.enqueue(new TextEncoder().encode(value));+ controller.close();+ },+ });+}++function exactShaArrayBuffer(hex: string): ArrayBuffer {+ const value = Uint8Array.from(Buffer.from(hex, "hex"));+ if (value.byteLength !== 32 || value.buffer.byteLength !== 32) {+ throw new Error("test checksum fixture must be an exact 32-byte ArrayBuffer");+ }+ return value.buffer;+}++function strictFixedLengthFactory(calls: number[]) {+ return (expected: number) => {+ calls.push(expected);+ let seen = 0;+ const transform = new TransformStream<Uint8Array, Uint8Array>({+ transform(chunk, controller) {+ seen += chunk.byteLength;+ if (seen > expected) throw new Error("fixed length overflow");+ controller.enqueue(chunk);+ },+ flush() {+ if (seen !== expected) throw new Error("fixed length underflow");+ },+ });+ return transform;+ };+}++function queryFake() {+ return {+ getPending: vi.fn(async () => row()),+ get: vi.fn(async () => row()),+ finalize: vi.fn(async (input) => row({+ status: "uploaded",+ r2Key: input.r2Key,+ sha256: input.sha256,+ sizeBytes: input.sizeBytes,+ })),+ fail: vi.fn(async (input) => row({ status: "failed", failureCode: input.failureCode })),+ timeout: vi.fn(async () => row({ status: "failed", failureCode: "timeout" })),+ } satisfies QueryPort;+}++function r2Fake() {+ const objects = new Map<string, { body: Uint8Array; sha256: string }>();+ const claims = new Map<string, Promise<void>>();+ const put = vi.fn(async (key: string, body: ReadableStream<Uint8Array>, options: Record<string, unknown>) => {+ const existingClaim = claims.get(key);+ const isWinner = !objects.has(key) && existingClaim === undefined;+ let releaseClaim: (() => void) | undefined;+ if (isWinner) {+ claims.set(key, new Promise<void>((resolve) => { releaseClaim = resolve; }));+ }+ try {+ const chunks: Uint8Array[] = [];+ const reader = body.getReader();+ while (true) {+ const next = await reader.read();+ if (next.done) break;+ chunks.push(next.value);+ }+ const merged = Buffer.concat(chunks.map((chunk) => Buffer.from(chunk)));+ const checksum = createHash("sha256").update(merged).digest("hex");+ expect((options.sha256 as ArrayBuffer).byteLength).toBe(32);+ const claimed = Buffer.from(options.sha256 as ArrayBuffer).toString("hex");+ if (checksum !== claimed) throw new Error("R2 checksum mismatch");+ if (!isWinner) {+ await existingClaim;+ return null;+ }+ objects.set(key, { body: merged, sha256: checksum });+ return { key };+ } finally {+ if (isWinner) {+ releaseClaim?.();+ claims.delete(key);+ }+ }+ });+ return {+ objects,+ put,+ head: vi.fn(async (key: string) => {+ const object = objects.get(key);+ return object+ ? { size: object.body.byteLength, checksums: { sha256: exactShaArrayBuffer(object.sha256) } }+ : null;+ }),+ delete: vi.fn(async (key: string) => { objects.delete(key); }),+ };+}++describe("B2d diagnostic upload service", () => {+ beforeEach(() => vi.restoreAllMocks());++ it("authorizes the immutable machine snapshot before R2 and streams a fixed-length conditional Standard object", async () => {+ const api = await loadSubject();+ const queries = queryFake();+ const bucket = r2Fake();+ const fixedLengths: number[] = [];+ const service = api.createDiagnosticUploadService({+ bucket,+ queries,+ now: () => NOW,+ fixedLengthStream: strictFixedLengthFactory(fixedLengths),+ });++ await expect(service.upload({+ reportId: REPORT_ID,+ machineId: MACHINE_ID,+ sizeBytes: 6,+ sha256: SHA256,+ body: bytes(),+ })).resolves.toEqual({ kind: "terminal", status: "uploaded" });++ expect(queries.getPending).toHaveBeenCalledWith({+ reportId: REPORT_ID,+ machineId: MACHINE_ID,+ nowMs: NOW,+ });+ expect(fixedLengths).toEqual([6]);+ expect(bucket.put).toHaveBeenCalledWith(KEY, expect.any(ReadableStream), {+ onlyIf: { etagDoesNotMatch: "*" },+ sha256: expect.any(ArrayBuffer),+ storageClass: "Standard",+ httpMetadata: {+ contentType: "application/x-ndjson",+ contentEncoding: "gzip",+ },+ });+ expect((bucket.put.mock.calls[0]![2].sha256 as ArrayBuffer).byteLength).toBe(32);+ expect(queries.finalize).toHaveBeenCalledWith({+ reportId: REPORT_ID,+ machineId: MACHINE_ID,+ r2Key: KEY,+ sha256: SHA256,+ sizeBytes: 6,+ nowMs: NOW,+ });+ expect(KEY).not.toMatch(/^https?:/);+ });++ it("rejects a cross-machine or non-pending report before touching R2", async () => {+ const api = await loadSubject();+ const queries = queryFake();+ queries.getPending.mockResolvedValue(null);+ queries.get.mockResolvedValue(null);+ const bucket = r2Fake();+ const service = api.createDiagnosticUploadService({+ bucket,+ queries,+ now: () => NOW,+ fixedLengthStream: strictFixedLengthFactory([]),+ });++ await expect(service.upload({+ reportId: REPORT_ID,+ machineId: "cm_foreign",+ sizeBytes: 6,+ sha256: SHA256,+ body: bytes(),+ })).resolves.toEqual({ kind: "rejected", status: 404 });+ expect(bucket.put).not.toHaveBeenCalled();+ expect(queries.finalize).not.toHaveBeenCalled();+ });++ it.each([+ ["under length", "short", 6],+ ["over length", "bundle!", 6],+ ["checksum mismatch", "bundle", 6, "b".repeat(64)],+ ])("fails %s as invalid_upload without retaining an object", async (_name, value, sizeBytes, sha = SHA256) => {+ const api = await loadSubject();+ const queries = queryFake();+ const bucket = r2Fake();+ bucket.put.mockRejectedValue(new Error("indistinguishable R2 rejection"));+ const service = api.createDiagnosticUploadService({+ bucket,+ queries,+ now: () => NOW,+ fixedLengthStream: strictFixedLengthFactory([]),+ });++ await expect(service.upload({+ reportId: REPORT_ID,+ machineId: MACHINE_ID,+ sizeBytes,+ sha256: sha,+ body: bytes(value),+ })).resolves.toEqual({ kind: "terminal", status: "failed" });+ expect(queries.fail).toHaveBeenCalledWith({+ reportId: REPORT_ID,+ machineId: MACHINE_ID,+ failureCode: "invalid_upload",+ nowMs: NOW,+ });+ expect(bucket.objects.has(KEY)).toBe(false);+ });++ it("treats an R2 put throw as retryable and preserves the pending row", async () => {+ const api = await loadSubject();+ const queries = queryFake();+ const bucket = r2Fake();+ bucket.put.mockRejectedValue(new Error("indistinguishable R2 rejection"));+ const service = api.createDiagnosticUploadService({+ bucket,+ queries,+ now: () => NOW,+ fixedLengthStream: strictFixedLengthFactory([]),+ });++ await expect(service.upload({+ reportId: REPORT_ID,+ machineId: MACHINE_ID,+ sizeBytes: 6,+ sha256: SHA256,+ body: bytes(),+ })).resolves.toEqual({ kind: "retryable" });+ expect(queries.finalize).not.toHaveBeenCalled();+ expect(queries.fail).not.toHaveBeenCalled();+ });++ it("treats a destination close rejection after a valid source as retryable", async () => {+ const api = await loadSubject();+ const queries = queryFake();+ const bucket = r2Fake();+ let signalCloseAttempted!: () => void;+ const closeAttempted = new Promise<void>((resolve) => { signalCloseAttempted = resolve; });+ const opaqueError = new Error("indistinguishable destination rejection");+ bucket.put.mockImplementation(async () => {+ await closeAttempted;+ throw opaqueError;+ });+ const service = api.createDiagnosticUploadService({+ bucket,+ queries,+ now: () => NOW,+ fixedLengthStream: () => ({+ readable: new ReadableStream<Uint8Array>({+ start(controller) {+ controller.close();+ },+ }),+ writable: new WritableStream<Uint8Array>({+ close() {+ signalCloseAttempted();+ throw opaqueError;+ },+ }),+ }),+ });++ await expect(service.upload({+ reportId: REPORT_ID,+ machineId: MACHINE_ID,+ sizeBytes: 6,+ sha256: SHA256,+ body: bytes(),+ })).resolves.toEqual({ kind: "retryable" });+ expect(queries.finalize).not.toHaveBeenCalled();+ expect(queries.fail).not.toHaveBeenCalled();+ expect(bucket.delete).not.toHaveBeenCalled();+ });++ it("normalizes a D1 failure-CAS throw to retryable after local invalid upload detection", async () => {+ const api = await loadSubject();+ const queries = queryFake();+ queries.fail.mockRejectedValue(new Error("D1 transient"));+ const bucket = r2Fake();+ bucket.put.mockRejectedValue(new Error("indistinguishable R2 rejection"));+ const service = api.createDiagnosticUploadService({+ bucket,+ queries,+ now: () => NOW,+ fixedLengthStream: strictFixedLengthFactory([]),+ });++ await expect(service.upload({+ reportId: REPORT_ID,+ machineId: MACHINE_ID,+ sizeBytes: 6,+ sha256: "b".repeat(64),+ body: bytes(),+ })).resolves.toEqual({ kind: "retryable" });+ });++ it("accepts a conditional-put loser only when HEAD has the exact size and canonical SHA", async () => {+ const api = await loadSubject();+ const queries = queryFake();+ const bucket = r2Fake();+ bucket.objects.set(KEY, { body: Buffer.from("bundle"), sha256: SHA256 });+ const service = api.createDiagnosticUploadService({+ bucket,+ queries,+ now: () => NOW,+ fixedLengthStream: strictFixedLengthFactory([]),+ });++ await expect(service.upload({+ reportId: REPORT_ID,+ machineId: MACHINE_ID,+ sizeBytes: 6,+ sha256: SHA256,+ body: bytes(),+ })).resolves.toEqual({ kind: "terminal", status: "uploaded" });+ expect(bucket.head).toHaveBeenCalledWith(KEY);+ expect(bucket.delete).not.toHaveBeenCalled();+ });++ it.each([+ {+ name: "equal",+ secondValue: "bundle",+ secondSize: 6,+ secondSha: SHA256,+ expected: { kind: "terminal", status: "uploaded" },+ failureCode: undefined,+ },+ {+ name: "different",+ secondValue: "bundlex",+ secondSize: 7,+ secondSha: createHash("sha256").update("bundlex").digest("hex"),+ expected: { kind: "terminal", status: "failed" },+ failureCode: "upload_conflict",+ },+ ])("resolves $name concurrent conditional PUTs by authoritative HEAD", async ({+ secondValue,+ secondSize,+ secondSha,+ expected,+ failureCode,+ }) => {+ const api = await loadSubject();+ const queries = queryFake();+ const bucket = r2Fake();+ const service = api.createDiagnosticUploadService({+ bucket,+ queries,+ now: () => NOW,+ fixedLengthStream: strictFixedLengthFactory([]),+ });+ let releaseFirst!: () => void;+ let firstRead!: () => void;+ const firstReadPromise = new Promise<void>((resolve) => { firstRead = resolve; });+ const releasePromise = new Promise<void>((resolve) => { releaseFirst = resolve; });+ const first = service.upload({+ reportId: REPORT_ID,+ machineId: MACHINE_ID,+ sizeBytes: 6,+ sha256: SHA256,+ body: gatedBytes("bundle", firstRead, releasePromise),+ });+ await firstReadPromise;+ const second = service.upload({+ reportId: REPORT_ID,+ machineId: MACHINE_ID,+ sizeBytes: secondSize,+ sha256: secondSha,+ body: bytes(secondValue),+ });+ await vi.waitFor(() => expect(bucket.put).toHaveBeenCalledTimes(2));+ releaseFirst();++ await expect(first).resolves.toEqual({ kind: "terminal", status: "uploaded" });+ await expect(second).resolves.toEqual(expected);+ expect(bucket.head).toHaveBeenCalledWith(KEY);+ expect(bucket.delete).not.toHaveBeenCalled();+ if (failureCode) {+ expect(queries.fail).toHaveBeenCalledWith(expect.objectContaining({ failureCode }));+ }+ });++ it.each([+ ["missing HEAD", null],+ ["wrong size", { size: 7, checksums: { sha256: exactShaArrayBuffer(SHA256) } }],+ ["missing checksum", { size: 6, checksums: {} }],+ ["wrong checksum", { size: 6, checksums: { sha256: exactShaArrayBuffer("b".repeat(64)) } }],+ ])("CASes upload_conflict for %s after a conditional-put loser", async (_name, head) => {+ const api = await loadSubject();+ const queries = queryFake();+ const bucket = r2Fake();+ bucket.put.mockResolvedValue(null);+ bucket.head.mockResolvedValue(head);+ const service = api.createDiagnosticUploadService({+ bucket,+ queries,+ now: () => NOW,+ fixedLengthStream: strictFixedLengthFactory([]),+ });++ await expect(service.upload({+ reportId: REPORT_ID,+ machineId: MACHINE_ID,+ sizeBytes: 6,+ sha256: SHA256,+ body: bytes(),+ })).resolves.toEqual({ kind: "terminal", status: "failed" });+ expect(queries.fail).toHaveBeenCalledWith(expect.objectContaining({ failureCode: "upload_conflict" }));+ expect(bucket.delete).not.toHaveBeenCalled();+ });++ it("compensates a lost finalize CAS from authoritative readback without deleting another request's object", async () => {+ const api = await loadSubject();+ const queries = queryFake();+ const bucket = r2Fake();+ queries.finalize.mockResolvedValue(null);+ queries.get.mockResolvedValue(row({ status: "uploaded", r2Key: KEY, sha256: SHA256, sizeBytes: 6 }));+ const service = api.createDiagnosticUploadService({+ bucket,+ queries,+ now: () => NOW,+ fixedLengthStream: strictFixedLengthFactory([]),+ });++ await expect(service.upload({+ reportId: REPORT_ID,+ machineId: MACHINE_ID,+ sizeBytes: 6,+ sha256: SHA256,+ body: bytes(),+ })).resolves.toEqual({ kind: "terminal", status: "uploaded" });+ expect(bucket.delete).not.toHaveBeenCalled();+ });++ it("deletes only an object definitely created by this request after terminal failure is confirmed", async () => {+ const api = await loadSubject();+ const queries = queryFake();+ const bucket = r2Fake();+ queries.finalize.mockResolvedValue(null);+ queries.get.mockResolvedValue(row({ status: "failed", failureCode: "timeout" }));+ const service = api.createDiagnosticUploadService({+ bucket,+ queries,+ now: () => NOW,+ fixedLengthStream: strictFixedLengthFactory([]),+ });++ await expect(service.upload({+ reportId: REPORT_ID,+ machineId: MACHINE_ID,+ sizeBytes: 6,+ sha256: SHA256,+ body: bytes(),+ })).resolves.toEqual({ kind: "terminal", status: "failed" });+ expect(bucket.delete).toHaveBeenCalledWith(KEY);+ });++ it("keeps an authoritative failed terminal when best-effort R2 deletion throws", async () => {+ const api = await loadSubject();+ const queries = queryFake();+ const bucket = r2Fake();+ queries.finalize.mockResolvedValue(null);+ queries.get.mockResolvedValue(row({ status: "failed", failureCode: "timeout" }));+ bucket.delete.mockRejectedValue(new Error("R2 delete transient"));+ const service = api.createDiagnosticUploadService({+ bucket,+ queries,+ now: () => NOW,+ fixedLengthStream: strictFixedLengthFactory([]),+ });++ await expect(service.upload({+ reportId: REPORT_ID,+ machineId: MACHINE_ID,+ sizeBytes: 6,+ sha256: SHA256,+ body: bytes(),+ })).resolves.toEqual({ kind: "terminal", status: "failed" });+ expect(bucket.delete).toHaveBeenCalledWith(KEY);+ });++ it("times out an expired pending readback and deletes only after terminal timeout is confirmed", async () => {+ const api = await loadSubject();+ const queries = queryFake();+ const bucket = r2Fake();+ queries.finalize.mockResolvedValue(null);+ queries.get.mockResolvedValue(row({ deadlineAt: NOW }));+ queries.timeout.mockResolvedValue(row({ status: "failed", failureCode: "timeout", deadlineAt: NOW }));+ const service = api.createDiagnosticUploadService({+ bucket,+ queries,+ now: () => NOW,+ fixedLengthStream: strictFixedLengthFactory([]),+ });++ await expect(service.upload({+ reportId: REPORT_ID,+ machineId: MACHINE_ID,+ sizeBytes: 6,+ sha256: SHA256,+ body: bytes(),+ })).resolves.toEqual({ kind: "terminal", status: "failed" });+ expect(queries.timeout).toHaveBeenCalledWith({+ reportId: REPORT_ID,+ ownerUserId: OWNER_ID,+ nowMs: NOW,+ });+ expect(bucket.delete).toHaveBeenCalledWith(KEY);+ });++ it("retains a created object when the expired pending timeout CAS remains ambiguous", async () => {+ const api = await loadSubject();+ const queries = queryFake();+ const bucket = r2Fake();+ queries.finalize.mockResolvedValue(null);+ queries.get.mockResolvedValue(row({ deadlineAt: NOW }));+ queries.timeout.mockResolvedValue(null);+ const service = api.createDiagnosticUploadService({+ bucket,+ queries,+ now: () => NOW,+ fixedLengthStream: strictFixedLengthFactory([]),+ });++ await expect(service.upload({+ reportId: REPORT_ID,+ machineId: MACHINE_ID,+ sizeBytes: 6,+ sha256: SHA256,+ body: bytes(),+ })).resolves.toEqual({ kind: "retryable" });+ expect(bucket.delete).not.toHaveBeenCalled();+ });++ it("returns conflict for uploaded_different readback and never deletes the authoritative object", async () => {+ const api = await loadSubject();+ const queries = queryFake();+ const bucket = r2Fake();+ queries.finalize.mockResolvedValue(null);+ queries.get.mockResolvedValue(row({+ status: "uploaded",+ r2Key: KEY,+ sha256: "b".repeat(64),+ sizeBytes: 7,+ }));+ const service = api.createDiagnosticUploadService({+ bucket,+ queries,+ now: () => NOW,+ fixedLengthStream: strictFixedLengthFactory([]),+ });++ await expect(service.upload({+ reportId: REPORT_ID,+ machineId: MACHINE_ID,+ sizeBytes: 6,+ sha256: SHA256,+ body: bytes(),+ })).resolves.toEqual({ kind: "terminal", status: "failed" });+ expect(bucket.delete).not.toHaveBeenCalled();+ expect(queries.fail).not.toHaveBeenCalled();+ });++ it("retains a created object when finalize readback is transient or still pending", async () => {+ const api = await loadSubject();+ for (const readback of [new Error("D1 transient"), row()]) {+ const queries = queryFake();+ const bucket = r2Fake();+ queries.finalize.mockResolvedValue(null);+ if (readback instanceof Error) queries.get.mockRejectedValue(readback);+ else queries.get.mockResolvedValue(readback);+ const service = api.createDiagnosticUploadService({+ bucket,+ queries,+ now: () => NOW,+ fixedLengthStream: strictFixedLengthFactory([]),+ });++ await expect(service.upload({+ reportId: REPORT_ID,+ machineId: MACHINE_ID,+ sizeBytes: 6,+ sha256: SHA256,+ body: bytes(),+ })).resolves.toEqual({ kind: "retryable" });+ expect(bucket.delete).not.toHaveBeenCalled();+ }+ });++ it("PATCH is guarded, same-code idempotent, and cannot downgrade an uploaded row", async () => {+ const api = await loadSubject();+ const queries = queryFake();+ const bucket = r2Fake();+ const service = api.createDiagnosticUploadService({+ bucket,+ queries,+ now: () => NOW,+ fixedLengthStream: strictFixedLengthFactory([]),+ });++ await expect(service.fail({+ reportId: REPORT_ID,+ machineId: MACHINE_ID,+ failureCode: "upload_failed",+ })).resolves.toEqual({ kind: "terminal", status: "failed" });++ queries.fail.mockResolvedValue(null);+ queries.get.mockResolvedValue(row({ status: "failed", failureCode: "upload_failed" }));+ await expect(service.fail({+ reportId: REPORT_ID,+ machineId: MACHINE_ID,+ failureCode: "upload_failed",+ })).resolves.toEqual({ kind: "terminal", status: "failed" });++ queries.get.mockResolvedValue(row({ status: "uploaded", r2Key: KEY, sha256: SHA256, sizeBytes: 6 }));+ await expect(service.fail({+ reportId: REPORT_ID,+ machineId: MACHINE_ID,+ failureCode: "upload_failed",+ })).resolves.toEqual({ kind: "rejected", status: 409 });+ });+});diff --git a/src/web/src/lib/community/diagnostic-upload.ts b/src/web/src/lib/community/diagnostic-upload.tsnew file mode 100644index 000000000..2b49fc904--- /dev/null+++ b/src/web/src/lib/community/diagnostic-upload.ts@@ -0,0 +1,403 @@+import { createHash } from "node:crypto";+import {+ queries,+ withD1Retry,+ type Database,+ type DiagnosticReportFailureCode,+} from "@alook/shared";++type ReportRow = {+ id: string;+ ownerUserId: string;+ machineId: string;+ status: "pending" | "uploaded" | "failed";+ deadlineAt: number;+ failureCode: string | null;+ r2Key: string | null;+ sha256: string | null;+ sizeBytes: number | null;+};++export type DiagnosticUploadResult =+ | { kind: "terminal"; status: "uploaded" | "failed" }+ | { kind: "retryable" }+ | { kind: "rejected"; status: 400 | 404 | 409 };++export interface DiagnosticUploadQueryPort {+ getPending(input: { reportId: string; machineId: string; nowMs: number }): Promise<ReportRow | null>;+ get(input: { reportId: string; machineId: string }): Promise<ReportRow | null>;+ finalize(input: {+ reportId: string;+ machineId: string;+ r2Key: string;+ sha256: string;+ sizeBytes: number;+ nowMs: number;+ }): Promise<ReportRow | null>;+ fail(input: {+ reportId: string;+ machineId: string;+ failureCode: DiagnosticReportFailureCode;+ nowMs: number;+ }): Promise<ReportRow | null>;+ timeout(input: { reportId: string; ownerUserId: string; nowMs: number }): Promise<ReportRow | null>;+}++interface R2Port {+ put(+ key: string,+ body: ReadableStream<Uint8Array>,+ options: R2PutOptions,+ ): Promise<R2Object | object | null>;+ head(key: string): Promise<Pick<R2Object, "size" | "checksums"> | null>;+ delete(key: string): Promise<void>;+}++type FixedLengthFactory = (sizeBytes: number) => {+ readable: ReadableStream<Uint8Array>;+ writable: WritableStream<Uint8Array>;+};++function exactSha256Bytes(hex: string): ArrayBuffer | null {+ if (!/^[0-9a-f]{64}$/.test(hex)) return null;+ const bytes = new Uint8Array(32);+ for (let index = 0; index < bytes.length; index += 1) {+ bytes[index] = Number.parseInt(hex.slice(index * 2, index * 2 + 2), 16);+ }+ return bytes.buffer;+}++function checksumHex(value: ArrayBuffer | undefined): string | null {+ if (!value || value.byteLength !== 32) return null;+ return Array.from(new Uint8Array(value), (byte) => byte.toString(16).padStart(2, "0")).join("");+}++function uploadedSame(+ row: ReportRow,+ expected: { r2Key: string; sha256: string; sizeBytes: number },+): boolean {+ return row.status === "uploaded"+ && row.r2Key === expected.r2Key+ && row.sha256 === expected.sha256+ && row.sizeBytes === expected.sizeBytes;+}++export function createDiagnosticUploadQueryPort(db: Database): DiagnosticUploadQueryPort {+ const q = queries.communityDiagnosticReport;+ return {+ getPending: (input) => withD1Retry(+ () => q.getPendingDiagnosticReportForMachine(db, input),+ { route: "community/diagnostics-upload:get-pending" },+ ),+ get: (input) => withD1Retry(+ () => q.getDiagnosticReportForMachine(db, input),+ { route: "community/diagnostics-upload:get" },+ ),+ finalize: (input) => withD1Retry(+ () => q.finalizeDiagnosticReportUpload(db, input),+ { route: "community/diagnostics-upload:finalize" },+ ),+ fail: (input) => withD1Retry(+ () => q.failPendingDiagnosticReport(db, input),+ { route: "community/diagnostics-upload:fail" },+ ),+ timeout: (input) => withD1Retry(+ () => q.timeoutPendingDiagnosticReport(db, input),+ { route: "community/diagnostics-upload:timeout" },+ ),+ };+}++export function createDiagnosticUploadService(args: {+ bucket: R2Port;+ queries: DiagnosticUploadQueryPort;+ now?: () => number;+ fixedLengthStream?: FixedLengthFactory;+}) {+ const now = args.now ?? Date.now;+ const fixedLengthStream: FixedLengthFactory = args.fixedLengthStream+ ?? ((sizeBytes) => new FixedLengthStream(sizeBytes));++ const convergeFailure = async (input: {+ reportId: string;+ machineId: string;+ failureCode: DiagnosticReportFailureCode;+ nowMs: number;+ }): Promise<DiagnosticUploadResult> => {+ let failed: ReportRow | null;+ try {+ failed = await args.queries.fail(input);+ } catch {+ return { kind: "retryable" };+ }+ if (failed) return { kind: "terminal", status: "failed" };+ let authoritative: ReportRow | null;+ try {+ authoritative = await args.queries.get({+ reportId: input.reportId,+ machineId: input.machineId,+ });+ } catch {+ return { kind: "retryable" };+ }+ if (!authoritative) return { kind: "rejected", status: 404 };+ if (authoritative.status === "pending") return { kind: "retryable" };+ if (authoritative.status === "failed" && authoritative.failureCode === input.failureCode) {+ return { kind: "terminal", status: "failed" };+ }+ return { kind: "rejected", status: 409 };+ };++ const deleteCreatedObject = async (key: string): Promise<void> => {+ try {+ await args.bucket.delete(key);+ } catch {+ // The database terminal is authoritative. The private bucket's lifecycle+ // remains the bounded cleanup fallback when best-effort deletion fails.+ }+ };++ const compensateFinalize = async (input: {+ report: ReportRow;+ reportId: string;+ machineId: string;+ r2Key: string;+ sha256: string;+ sizeBytes: number;+ nowMs: number;+ createdByThisRequest: boolean;+ }): Promise<DiagnosticUploadResult> => {+ let authoritative: ReportRow | null;+ try {+ authoritative = await args.queries.get({ reportId: input.reportId, machineId: input.machineId });+ } catch {+ return { kind: "retryable" };+ }+ if (!authoritative) return { kind: "retryable" };+ const expected = { r2Key: input.r2Key, sha256: input.sha256, sizeBytes: input.sizeBytes };+ if (uploadedSame(authoritative, expected)) return { kind: "terminal", status: "uploaded" };+ if (authoritative.status === "uploaded") return { kind: "terminal", status: "failed" };+ if (authoritative.status === "failed") {+ if (input.createdByThisRequest) await deleteCreatedObject(input.r2Key);+ return { kind: "terminal", status: "failed" };+ }+ if (authoritative.deadlineAt > input.nowMs) return { kind: "retryable" };++ let timedOut: ReportRow | null;+ try {+ timedOut = await args.queries.timeout({+ reportId: input.reportId,+ ownerUserId: input.report.ownerUserId,+ nowMs: input.nowMs,+ });+ } catch {+ return { kind: "retryable" };+ }+ if (!timedOut) return { kind: "retryable" };+ if (timedOut.status === "failed") {+ if (input.createdByThisRequest) await deleteCreatedObject(input.r2Key);+ return { kind: "terminal", status: "failed" };+ }+ if (uploadedSame(timedOut, expected)) return { kind: "terminal", status: "uploaded" };+ return { kind: "retryable" };+ };++ return {+ async upload(input: {+ reportId: string;+ machineId: string;+ sizeBytes: number;+ sha256: string;+ body: ReadableStream<Uint8Array>;+ }): Promise<DiagnosticUploadResult> {+ const sha256Bytes = exactSha256Bytes(input.sha256);+ if (!Number.isSafeInteger(input.sizeBytes) || input.sizeBytes < 1 || input.sizeBytes > 10 * 1024 * 1024 || !sha256Bytes) {+ return { kind: "rejected", status: 400 };+ }+ const nowMs = now();+ let report: ReportRow | null;+ try {+ report = await args.queries.getPending({+ reportId: input.reportId,+ machineId: input.machineId,+ nowMs,+ });+ } catch {+ return { kind: "retryable" };+ }+ if (!report) {+ let authoritative: ReportRow | null;+ try {+ authoritative = await args.queries.get({ reportId: input.reportId, machineId: input.machineId });+ } catch {+ return { kind: "retryable" };+ }+ if (!authoritative) return { kind: "rejected", status: 404 };+ if (uploadedSame(authoritative, {+ r2Key: `bug-reports/${authoritative.ownerUserId}/${input.reportId}.ndjson.gz`,+ sha256: input.sha256,+ sizeBytes: input.sizeBytes,+ })) return { kind: "terminal", status: "uploaded" };+ if (authoritative.status === "failed") return { kind: "terminal", status: "failed" };+ return { kind: "rejected", status: 409 };+ }++ const r2Key = `bug-reports/${report.ownerUserId}/${input.reportId}.ndjson.gz`;+ const fixed = fixedLengthStream(input.sizeBytes);+ const writer = fixed.writable.getWriter();+ const reader = input.body.getReader();+ const hash = createHash("sha256");+ let seen = 0;+ let localInvalid = false;+ let destinationFailed = false;+ let destinationDetached = false;+ let pumpFinished = false;++ const pump = (async () => {+ try {+ while (true) {+ const next = await reader.read();+ if (next.done) break;+ seen += next.value.byteLength;+ if (seen > input.sizeBytes) {+ localInvalid = true;+ await reader.cancel().catch(() => {});+ break;+ }+ hash.update(next.value);+ if (!destinationFailed && !destinationDetached) {+ try {+ await writer.write(next.value);+ } catch {+ if (!destinationDetached) destinationFailed = true;+ }+ }+ }+ if (!localInvalid && (seen !== input.sizeBytes || hash.digest("hex") !== input.sha256)) {+ localInvalid = true;+ }+ } catch {+ localInvalid = true;+ }++ try {+ if (destinationDetached) {+ // The destination settled before source validation completed. Its+ // settlement handler already released the writer.+ } else if (localInvalid || destinationFailed) {+ try {+ await writer.abort();+ } catch {+ destinationFailed = true;+ }+ } else {+ try {+ await writer.close();+ } catch {+ destinationFailed = true;+ }+ }+ } finally {+ pumpFinished = true;+ }+ })();++ const put = Promise.resolve(args.bucket.put(r2Key, fixed.readable, {+ onlyIf: { etagDoesNotMatch: "*" },+ sha256: sha256Bytes,+ storageClass: "Standard",+ httpMetadata: {+ contentType: "application/x-ndjson",+ contentEncoding: "gzip",+ },+ })).then(async (result) => {+ if (!pumpFinished) {+ destinationDetached = true;+ try {+ await writer.abort();+ } catch {+ destinationFailed = true;+ }+ }+ return result;+ }, async (error) => {+ destinationDetached = true;+ try {+ await writer.abort(error);+ } catch {+ destinationFailed = true;+ }+ throw error;+ });++ const [pumpResult, putResult] = await Promise.allSettled([pump, put]);+ if (localInvalid) {+ return convergeFailure({+ reportId: input.reportId,+ machineId: input.machineId,+ failureCode: "invalid_upload",+ nowMs,+ });+ }+ if (pumpResult.status === "rejected" || putResult.status === "rejected") {+ return { kind: "retryable" };+ }++ const createdByThisRequest = putResult.value !== null;+ if (createdByThisRequest && destinationFailed) return { kind: "retryable" };+ if (!createdByThisRequest) {+ let head: Awaited<ReturnType<R2Port["head"]>>;+ try {+ head = await args.bucket.head(r2Key);+ } catch {+ return { kind: "retryable" };+ }+ if (!head || head.size !== input.sizeBytes || checksumHex(head.checksums?.sha256) !== input.sha256) {+ return convergeFailure({+ reportId: input.reportId,+ machineId: input.machineId,+ failureCode: "upload_conflict",+ nowMs,+ });+ }+ }++ let finalized: ReportRow | null;+ try {+ finalized = await args.queries.finalize({+ reportId: input.reportId,+ machineId: input.machineId,+ r2Key,+ sha256: input.sha256,+ sizeBytes: input.sizeBytes,+ nowMs,+ });+ } catch {+ return { kind: "retryable" };+ }+ if (finalized) return { kind: "terminal", status: "uploaded" };+ return compensateFinalize({+ report,+ reportId: input.reportId,+ machineId: input.machineId,+ r2Key,+ sha256: input.sha256,+ sizeBytes: input.sizeBytes,+ nowMs,+ createdByThisRequest,+ });+ },++ async fail(input: {+ reportId: string;+ machineId: string;+ failureCode: DiagnosticReportFailureCode;+ }): Promise<DiagnosticUploadResult> {+ try {+ return await convergeFailure({ ...input, nowMs: now() });+ } catch {+ return { kind: "retryable" };+ }+ },+ };+}diff --git a/src/web/src/test/e2e/community-diagnostic-report-upload.test.ts b/src/web/src/test/e2e/community-diagnostic-report-upload.test.tsnew file mode 100644index 000000000..c16ff7146--- /dev/null+++ b/src/web/src/test/e2e/community-diagnostic-report-upload.test.ts@@ -0,0 +1,228 @@+import { createHash } from "node:crypto";+import { afterAll, beforeEach, describe, expect, it, vi } from "vitest";+import { createDb } from "@alook/shared";+import { sqlQuery, sqlRun } from "@alook/test-utils";++interface UploadModule {+ createDiagnosticUploadQueryPort(db: unknown): unknown;+ createDiagnosticUploadService(args: {+ bucket: R2Bucket;+ queries: unknown;+ now: () => number;+ fixedLengthStream: (sizeBytes: number) => {+ readable: ReadableStream<Uint8Array>;+ writable: WritableStream<Uint8Array>;+ };+ }): {+ upload(args: {+ reportId: string;+ machineId: string;+ sizeBytes: number;+ sha256: string;+ body: ReadableStream<Uint8Array>;+ }): Promise<{ kind: string; status?: string }>;+ fail(args: {+ reportId: string;+ machineId: string;+ failureCode: string;+ }): Promise<{ kind: string; status?: string }>;+ };+}++async function loadSubject(): Promise<UploadModule> {+ return vi.importActual<UploadModule>("../../lib/community/diagnostic-upload.js");+}++const NOW = 1_786_531_200_000;+const OWNER = "e2e_upload_owner";+const AGENT = "e2e_upload_agent";+const MACHINE = "cm_e2e_upload_machine";+const REPORT = "dbr_e2e_upload_report";+const NONCE = "nonce_e2e_upload_1234";+const BODY = Buffer.from("real-e2e-diagnostic-gzip");+const SHA = createHash("sha256").update(BODY).digest("hex");+const KEY = `bug-reports/${OWNER}/${REPORT}.ndjson.gz`;++function realQueryDb() {+ const binding = {+ prepare(query: string) {+ return {+ bind(...params: unknown[]) {+ return {+ async all() {+ return { results: sqlQuery(query, ...params) };+ },+ async raw() {+ return sqlQuery<Record<string, unknown>>(query, ...params).map(Object.values);+ },+ };+ },+ };+ },+ };+ return createDb(binding as never);+}++function stream(value: Uint8Array): ReadableStream<Uint8Array> {+ return new ReadableStream({+ start(controller) {+ controller.enqueue(value);+ controller.close();+ },+ });+}++function fixedLength(expected: number) {+ let seen = 0;+ return new TransformStream<Uint8Array, Uint8Array>({+ transform(chunk, controller) {+ seen += chunk.byteLength;+ if (seen > expected) throw new Error("overflow");+ controller.enqueue(chunk);+ },+ flush() {+ if (seen !== expected) throw new Error("underflow");+ },+ });+}++function strictBucket() {+ const objects = new Map<string, Buffer>();+ const put = vi.fn(async (key: string, body: ReadableStream<Uint8Array>, options: R2PutOptions) => {+ if (objects.has(key)) return null;+ const chunks: Buffer[] = [];+ for await (const chunk of body as unknown as AsyncIterable<Uint8Array>) chunks.push(Buffer.from(chunk));+ const value = Buffer.concat(chunks);+ const expected = Buffer.from(options.sha256 as ArrayBuffer).toString("hex");+ if (createHash("sha256").update(value).digest("hex") !== expected) throw new Error("checksum");+ objects.set(key, value);+ return { key };+ });+ return {+ objects,+ binding: {+ put,+ head: vi.fn(async (key: string) => {+ const value = objects.get(key);+ if (!value) return null;+ const digest = Uint8Array.from(createHash("sha256").update(value).digest());+ return { size: value.byteLength, checksums: { sha256: digest.buffer } };+ }),+ delete: vi.fn(async (key: string) => { objects.delete(key); }),+ } as unknown as R2Bucket,+ put,+ };+}++function cleanup(): void {+ sqlRun("DELETE FROM community_diagnostic_report WHERE id = ?", REPORT);+}++function seedPending(): void {+ sqlRun(+ `INSERT INTO community_diagnostic_report (+ id, owner_user_id, agent_id, machine_id, client_nonce, rate_bucket,+ status, failure_code, from_ms, created_at, deadline_at, completed_at,+ r2_key, sha256, size_bytes, uploaded_at, object_expires_at+ ) VALUES (?, ?, ?, ?, ?, ?, 'pending', NULL, ?, ?, ?, NULL, NULL, NULL, NULL, NULL, NULL)`,+ REPORT,+ OWNER,+ AGENT,+ MACHINE,+ NONCE,+ Math.floor(NOW / 60_000),+ NOW - 86_400_000,+ NOW,+ NOW + 600_000,+ );+}++beforeEach(() => {+ cleanup();+ seedPending();+});++afterAll(cleanup);++describe("B2d real SQLite diagnostic upload", () => {+ it("streams a private object and atomically finalizes the real report row", async () => {+ const api = await loadSubject();+ const bucket = strictBucket();+ const service = api.createDiagnosticUploadService({+ bucket: bucket.binding,+ queries: api.createDiagnosticUploadQueryPort(realQueryDb()),+ now: () => NOW + 1_000,+ fixedLengthStream: fixedLength,+ });++ await expect(service.upload({+ reportId: REPORT,+ machineId: MACHINE,+ sizeBytes: BODY.byteLength,+ sha256: SHA,+ body: stream(BODY),+ })).resolves.toEqual({ kind: "terminal", status: "uploaded" });++ expect(bucket.objects.get(KEY)).toEqual(BODY);+ expect(sqlQuery<Record<string, unknown>>(+ "SELECT status, r2_key, sha256, size_bytes FROM community_diagnostic_report WHERE id = ?",+ REPORT,+ )).toEqual([{+ status: "uploaded",+ r2_key: KEY,+ sha256: SHA,+ size_bytes: BODY.byteLength,+ }]);+ });++ it("denies a foreign machine before R2 and leaves the real row pending", async () => {+ const api = await loadSubject();+ const bucket = strictBucket();+ const service = api.createDiagnosticUploadService({+ bucket: bucket.binding,+ queries: api.createDiagnosticUploadQueryPort(realQueryDb()),+ now: () => NOW + 1_000,+ fixedLengthStream: fixedLength,+ });++ await expect(service.upload({+ reportId: REPORT,+ machineId: "cm_foreign",+ sizeBytes: BODY.byteLength,+ sha256: SHA,+ body: stream(BODY),+ })).resolves.toEqual({ kind: "rejected", status: 404 });+ expect(bucket.put).not.toHaveBeenCalled();+ expect(sqlQuery<{ status: string }>(+ "SELECT status FROM community_diagnostic_report WHERE id = ?",+ REPORT,+ )).toEqual([{ status: "pending" }]);+ });++ it("PATCHes one fixed daemon failure and preserves terminal immutability on retry", async () => {+ const api = await loadSubject();+ const bucket = strictBucket();+ const service = api.createDiagnosticUploadService({+ bucket: bucket.binding,+ queries: api.createDiagnosticUploadQueryPort(realQueryDb()),+ now: () => NOW + 1_000,+ fixedLengthStream: fixedLength,+ });++ await expect(service.fail({+ reportId: REPORT,+ machineId: MACHINE,+ failureCode: "diagnostics_unavailable",+ })).resolves.toEqual({ kind: "terminal", status: "failed" });+ await expect(service.fail({+ reportId: REPORT,+ machineId: MACHINE,+ failureCode: "diagnostics_unavailable",+ })).resolves.toEqual({ kind: "terminal", status: "failed" });+ expect(sqlQuery<Record<string, unknown>>(+ "SELECT status, failure_code FROM community_diagnostic_report WHERE id = ?",+ REPORT,+ )).toEqual([{ status: "failed", failure_code: "diagnostics_unavailable" }]);+ expect(bucket.put).not.toHaveBeenCalled();+ });+});diff --git a/src/web/wrangler.toml b/src/web/wrangler.tomlindex ff19ccdca..5bb4cbcaf 100644--- a/src/web/wrangler.toml+++ b/src/web/wrangler.toml@@ -62,6 +62,10 @@ bucket_name = "alook-emails"binding = "COMMUNITY_MEDIA"bucket_name = "alook-community-media"+[[r2_buckets]]+binding = "BUG_REPORTS"+bucket_name = "alook-bug-reports"+# WS Durable Object is in a separate worker — access via Service Binding[[services]]binding = "WS_DO_WORKER"