From 5eb350e0382d5762183a309a229c7608e003d4fc Mon Sep 17 00:00:00 2001 From: John Fawcett Date: Wed, 4 Mar 2026 14:24:11 -0600 Subject: [PATCH 1/5] feat(gastown): configurable merge strategy, agent-driven PR creation, review bead fixes - Add configurable merge strategy (direct/PR) for rigs and towns - Refinery agents now handle merging (direct) or PR creation (gh/glab CLI) themselves - Strategy-aware refinery system prompt with explicit merge/PR instructions - Fix review beads missing PR link: write pr_url to beads.metadata on submission - Fix PR beads not closing: validate pr_url is a real PR, add polling diagnostics - Add small_model to TownConfig for configurable lightweight model - Use resolveModel()/resolveSmallModel() throughout instead of hardcoded model strings - All kilo config sub-agent roles derive model from town config - Add PR link display to BeadPanel.tsx drawer - Polecat prompt: clarify not to pass git push convenience URLs as pr_url --- cloudflare-gastown/container/.dockerignore | 2 + cloudflare-gastown/container/.gitignore | 5 + cloudflare-gastown/container/Dockerfile | 14 +- cloudflare-gastown/container/Dockerfile.dev | 14 +- cloudflare-gastown/container/bun.lock | 241 - cloudflare-gastown/container/package.json | 4 +- cloudflare-gastown/container/plugin/client.ts | 1 - .../container/src/agent-runner.ts | 141 +- .../container/src/process-manager.ts | 16 +- cloudflare-gastown/container/src/types.ts | 2 + cloudflare-gastown/package.json | 9 +- .../scripts/prepare-container.mjs | 61 + .../src/db/tables/bead-events.table.ts | 2 + cloudflare-gastown/src/dos/Town.do.ts | 232 +- cloudflare-gastown/src/dos/town/config.ts | 45 +- .../src/dos/town/container-dispatch.ts | 32 +- .../src/dos/town/review-queue.ts | 162 +- .../src/prompts/polecat-system.prompt.ts | 4 + .../src/prompts/refinery-system.prompt.ts | 45 +- cloudflare-gastown/src/types.ts | 54 +- .../src/util/platform-pr.util.ts | 295 + .../test/unit/merge-strategy.test.ts | 219 + cloudflare-gastown/worker-configuration.d.ts | 19740 ++++++++-------- cloudflare-gastown/wrangler.jsonc | 12 +- pnpm-lock.yaml | 22 +- pnpm-workspace.yaml | 2 + .../[townId]/TownOverviewPageClient.tsx | 2 +- .../settings/TownSettingsPageClient.tsx | 69 +- src/components/gastown/ActivityFeed.tsx | 14 +- src/components/gastown/BeadDetailDrawer.tsx | 34 +- src/components/gastown/CreateTownDialog.tsx | 5 +- .../gastown/drawer-panels/BeadPanel.tsx | 22 +- src/lib/gastown/gastown-client.ts | 1 + src/lib/providers/index.ts | 4 + 34 files changed, 10774 insertions(+), 10753 deletions(-) create mode 100644 cloudflare-gastown/container/.dockerignore create mode 100644 cloudflare-gastown/container/.gitignore delete mode 100644 cloudflare-gastown/container/bun.lock create mode 100644 cloudflare-gastown/scripts/prepare-container.mjs create mode 100644 cloudflare-gastown/src/util/platform-pr.util.ts create mode 100644 cloudflare-gastown/test/unit/merge-strategy.test.ts diff --git a/cloudflare-gastown/container/.dockerignore b/cloudflare-gastown/container/.dockerignore new file mode 100644 index 0000000000..f25034b51f --- /dev/null +++ b/cloudflare-gastown/container/.dockerignore @@ -0,0 +1,2 @@ +node_modules +.wrangler \ No newline at end of file diff --git a/cloudflare-gastown/container/.gitignore b/cloudflare-gastown/container/.gitignore new file mode 100644 index 0000000000..b2b69fe9e1 --- /dev/null +++ b/cloudflare-gastown/container/.gitignore @@ -0,0 +1,5 @@ +# Generated by scripts/prepare-container.mjs for Docker builds. +# pnpm needs the workspace yaml and lockfile to resolve catalog: references. +pnpm-workspace.yaml +pnpm-lock.yaml +package.prod.json diff --git a/cloudflare-gastown/container/Dockerfile b/cloudflare-gastown/container/Dockerfile index ed01efa1eb..7a83c7a6e2 100644 --- a/cloudflare-gastown/container/Dockerfile +++ b/cloudflare-gastown/container/Dockerfile @@ -44,15 +44,23 @@ RUN cd /opt/gastown-plugin && npm install --omit=dev && \ WORKDIR /app -# Copy package files and install deps deterministically -COPY package.json bun.lock ./ -RUN bun install --frozen-lockfile --production +# ── Install production deps via pnpm ──────────────────────────────── +# package.json uses pnpm catalog: references for shared versions. +# pnpm-workspace.yaml (catalog only) and pnpm-lock.yaml are copied +# from the monorepo root by `pnpm container:prepare`. +# package.prod.json is package.json with workspace: devDeps removed. +COPY pnpm-workspace.yaml pnpm-lock.yaml ./ +COPY package.prod.json package.json +RUN pnpm install --prod # Copy source (bun runs TypeScript directly — no build step needed) COPY src/ ./src/ RUN chown -R agent:agent /app +# Explicitly set HOME so kilo resolves XDG paths correctly. +# Some container runtimes don't set HOME when switching USER. +ENV HOME=/home/agent USER agent EXPOSE 8080 diff --git a/cloudflare-gastown/container/Dockerfile.dev b/cloudflare-gastown/container/Dockerfile.dev index 703f63cdec..0593bcd9e3 100644 --- a/cloudflare-gastown/container/Dockerfile.dev +++ b/cloudflare-gastown/container/Dockerfile.dev @@ -43,15 +43,23 @@ RUN cd /opt/gastown-plugin && npm install --omit=dev && \ WORKDIR /app -# Copy package files and install deps deterministically -COPY package.json bun.lock ./ -RUN bun install --frozen-lockfile --production +# ── Install production deps via pnpm ──────────────────────────────── +# package.json uses pnpm catalog: references for shared versions. +# pnpm-workspace.yaml (catalog only) and pnpm-lock.yaml are copied +# from the monorepo root by `pnpm container:prepare`. +# package.prod.json is package.json with workspace: devDeps removed. +COPY pnpm-workspace.yaml pnpm-lock.yaml ./ +COPY package.prod.json package.json +RUN pnpm install --prod # Copy source (bun runs TypeScript directly — no build step needed) COPY src/ ./src/ RUN chown -R agent:agent /app +# Explicitly set HOME so kilo resolves XDG paths correctly. +# Some container runtimes don't set HOME when switching USER. +ENV HOME=/home/agent USER agent EXPOSE 8080 diff --git a/cloudflare-gastown/container/bun.lock b/cloudflare-gastown/container/bun.lock deleted file mode 100644 index 76bbb09468..0000000000 --- a/cloudflare-gastown/container/bun.lock +++ /dev/null @@ -1,241 +0,0 @@ -{ - "lockfileVersion": 1, - "configVersion": 1, - "workspaces": { - "": { - "name": "gastown-container", - "dependencies": { - "@kilocode/plugin": "1.0.23", - "@kilocode/sdk": "1.0.23", - "hono": "^4.11.4", - "zod": "^4.3.5", - }, - "devDependencies": { - "@types/bun": "^1.2.17", - "typescript": "^5.9.3", - "vitest": "^3.2.4", - }, - }, - }, - "packages": { - "@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.27.3", "", { "os": "aix", "cpu": "ppc64" }, "sha512-9fJMTNFTWZMh5qwrBItuziu834eOCUcEqymSH7pY+zoMVEZg3gcPuBNxH1EvfVYe9h0x/Ptw8KBzv7qxb7l8dg=="], - - "@esbuild/android-arm": ["@esbuild/android-arm@0.27.3", "", { "os": "android", "cpu": "arm" }, "sha512-i5D1hPY7GIQmXlXhs2w8AWHhenb00+GxjxRncS2ZM7YNVGNfaMxgzSGuO8o8SJzRc/oZwU2bcScvVERk03QhzA=="], - - "@esbuild/android-arm64": ["@esbuild/android-arm64@0.27.3", "", { "os": "android", "cpu": "arm64" }, "sha512-YdghPYUmj/FX2SYKJ0OZxf+iaKgMsKHVPF1MAq/P8WirnSpCStzKJFjOjzsW0QQ7oIAiccHdcqjbHmJxRb/dmg=="], - - "@esbuild/android-x64": ["@esbuild/android-x64@0.27.3", "", { "os": "android", "cpu": "x64" }, "sha512-IN/0BNTkHtk8lkOM8JWAYFg4ORxBkZQf9zXiEOfERX/CzxW3Vg1ewAhU7QSWQpVIzTW+b8Xy+lGzdYXV6UZObQ=="], - - "@esbuild/darwin-arm64": ["@esbuild/darwin-arm64@0.27.3", "", { "os": "darwin", "cpu": "arm64" }, "sha512-Re491k7ByTVRy0t3EKWajdLIr0gz2kKKfzafkth4Q8A5n1xTHrkqZgLLjFEHVD+AXdUGgQMq+Godfq45mGpCKg=="], - - "@esbuild/darwin-x64": ["@esbuild/darwin-x64@0.27.3", "", { "os": "darwin", "cpu": "x64" }, "sha512-vHk/hA7/1AckjGzRqi6wbo+jaShzRowYip6rt6q7VYEDX4LEy1pZfDpdxCBnGtl+A5zq8iXDcyuxwtv3hNtHFg=="], - - "@esbuild/freebsd-arm64": ["@esbuild/freebsd-arm64@0.27.3", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-ipTYM2fjt3kQAYOvo6vcxJx3nBYAzPjgTCk7QEgZG8AUO3ydUhvelmhrbOheMnGOlaSFUoHXB6un+A7q4ygY9w=="], - - "@esbuild/freebsd-x64": ["@esbuild/freebsd-x64@0.27.3", "", { "os": "freebsd", "cpu": "x64" }, "sha512-dDk0X87T7mI6U3K9VjWtHOXqwAMJBNN2r7bejDsc+j03SEjtD9HrOl8gVFByeM0aJksoUuUVU9TBaZa2rgj0oA=="], - - "@esbuild/linux-arm": ["@esbuild/linux-arm@0.27.3", "", { "os": "linux", "cpu": "arm" }, "sha512-s6nPv2QkSupJwLYyfS+gwdirm0ukyTFNl3KTgZEAiJDd+iHZcbTPPcWCcRYH+WlNbwChgH2QkE9NSlNrMT8Gfw=="], - - "@esbuild/linux-arm64": ["@esbuild/linux-arm64@0.27.3", "", { "os": "linux", "cpu": "arm64" }, "sha512-sZOuFz/xWnZ4KH3YfFrKCf1WyPZHakVzTiqji3WDc0BCl2kBwiJLCXpzLzUBLgmp4veFZdvN5ChW4Eq/8Fc2Fg=="], - - "@esbuild/linux-ia32": ["@esbuild/linux-ia32@0.27.3", "", { "os": "linux", "cpu": "ia32" }, "sha512-yGlQYjdxtLdh0a3jHjuwOrxQjOZYD/C9PfdbgJJF3TIZWnm/tMd/RcNiLngiu4iwcBAOezdnSLAwQDPqTmtTYg=="], - - "@esbuild/linux-loong64": ["@esbuild/linux-loong64@0.27.3", "", { "os": "linux", "cpu": "none" }, "sha512-WO60Sn8ly3gtzhyjATDgieJNet/KqsDlX5nRC5Y3oTFcS1l0KWba+SEa9Ja1GfDqSF1z6hif/SkpQJbL63cgOA=="], - - "@esbuild/linux-mips64el": ["@esbuild/linux-mips64el@0.27.3", "", { "os": "linux", "cpu": "none" }, "sha512-APsymYA6sGcZ4pD6k+UxbDjOFSvPWyZhjaiPyl/f79xKxwTnrn5QUnXR5prvetuaSMsb4jgeHewIDCIWljrSxw=="], - - "@esbuild/linux-ppc64": ["@esbuild/linux-ppc64@0.27.3", "", { "os": "linux", "cpu": "ppc64" }, "sha512-eizBnTeBefojtDb9nSh4vvVQ3V9Qf9Df01PfawPcRzJH4gFSgrObw+LveUyDoKU3kxi5+9RJTCWlj4FjYXVPEA=="], - - "@esbuild/linux-riscv64": ["@esbuild/linux-riscv64@0.27.3", "", { "os": "linux", "cpu": "none" }, "sha512-3Emwh0r5wmfm3ssTWRQSyVhbOHvqegUDRd0WhmXKX2mkHJe1SFCMJhagUleMq+Uci34wLSipf8Lagt4LlpRFWQ=="], - - "@esbuild/linux-s390x": ["@esbuild/linux-s390x@0.27.3", "", { "os": "linux", "cpu": "s390x" }, "sha512-pBHUx9LzXWBc7MFIEEL0yD/ZVtNgLytvx60gES28GcWMqil8ElCYR4kvbV2BDqsHOvVDRrOxGySBM9Fcv744hw=="], - - "@esbuild/linux-x64": ["@esbuild/linux-x64@0.27.3", "", { "os": "linux", "cpu": "x64" }, "sha512-Czi8yzXUWIQYAtL/2y6vogER8pvcsOsk5cpwL4Gk5nJqH5UZiVByIY8Eorm5R13gq+DQKYg0+JyQoytLQas4dA=="], - - "@esbuild/netbsd-arm64": ["@esbuild/netbsd-arm64@0.27.3", "", { "os": "none", "cpu": "arm64" }, "sha512-sDpk0RgmTCR/5HguIZa9n9u+HVKf40fbEUt+iTzSnCaGvY9kFP0YKBWZtJaraonFnqef5SlJ8/TiPAxzyS+UoA=="], - - "@esbuild/netbsd-x64": ["@esbuild/netbsd-x64@0.27.3", "", { "os": "none", "cpu": "x64" }, "sha512-P14lFKJl/DdaE00LItAukUdZO5iqNH7+PjoBm+fLQjtxfcfFE20Xf5CrLsmZdq5LFFZzb5JMZ9grUwvtVYzjiA=="], - - "@esbuild/openbsd-arm64": ["@esbuild/openbsd-arm64@0.27.3", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-AIcMP77AvirGbRl/UZFTq5hjXK+2wC7qFRGoHSDrZ5v5b8DK/GYpXW3CPRL53NkvDqb9D+alBiC/dV0Fb7eJcw=="], - - "@esbuild/openbsd-x64": ["@esbuild/openbsd-x64@0.27.3", "", { "os": "openbsd", "cpu": "x64" }, "sha512-DnW2sRrBzA+YnE70LKqnM3P+z8vehfJWHXECbwBmH/CU51z6FiqTQTHFenPlHmo3a8UgpLyH3PT+87OViOh1AQ=="], - - "@esbuild/openharmony-arm64": ["@esbuild/openharmony-arm64@0.27.3", "", { "os": "none", "cpu": "arm64" }, "sha512-NinAEgr/etERPTsZJ7aEZQvvg/A6IsZG/LgZy+81wON2huV7SrK3e63dU0XhyZP4RKGyTm7aOgmQk0bGp0fy2g=="], - - "@esbuild/sunos-x64": ["@esbuild/sunos-x64@0.27.3", "", { "os": "sunos", "cpu": "x64" }, "sha512-PanZ+nEz+eWoBJ8/f8HKxTTD172SKwdXebZ0ndd953gt1HRBbhMsaNqjTyYLGLPdoWHy4zLU7bDVJztF5f3BHA=="], - - "@esbuild/win32-arm64": ["@esbuild/win32-arm64@0.27.3", "", { "os": "win32", "cpu": "arm64" }, "sha512-B2t59lWWYrbRDw/tjiWOuzSsFh1Y/E95ofKz7rIVYSQkUYBjfSgf6oeYPNWHToFRr2zx52JKApIcAS/D5TUBnA=="], - - "@esbuild/win32-ia32": ["@esbuild/win32-ia32@0.27.3", "", { "os": "win32", "cpu": "ia32" }, "sha512-QLKSFeXNS8+tHW7tZpMtjlNb7HKau0QDpwm49u0vUp9y1WOF+PEzkU84y9GqYaAVW8aH8f3GcBck26jh54cX4Q=="], - - "@esbuild/win32-x64": ["@esbuild/win32-x64@0.27.3", "", { "os": "win32", "cpu": "x64" }, "sha512-4uJGhsxuptu3OcpVAzli+/gWusVGwZZHTlS63hh++ehExkVT8SgiEf7/uC/PclrPPkLhZqGgCTjd0VWLo6xMqA=="], - - "@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.5.5", "", {}, "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og=="], - - "@kilocode/plugin": ["@kilocode/plugin@1.0.23", "", { "dependencies": { "@kilocode/sdk": "1.0.23", "zod": "4.1.8" } }, "sha512-iP273WjkN1veQF0ygpVEVGZviIl/bynxH7RXwmkyODKtlgHbs3QzxeUoLbd5r4ZDYDIcA5+4NITCTjcE3YlPEQ=="], - - "@kilocode/sdk": ["@kilocode/sdk@1.0.23", "", {}, "sha512-4z7xdfHyoRm+iUwQtu0k+BMy1ovNhA3yCy+94Hwz0jH5329ZVmaTjoPq4QleWihMthzsxaJCVFx7bonphsr1PA=="], - - "@rollup/rollup-android-arm-eabi": ["@rollup/rollup-android-arm-eabi@4.57.1", "", { "os": "android", "cpu": "arm" }, "sha512-A6ehUVSiSaaliTxai040ZpZ2zTevHYbvu/lDoeAteHI8QnaosIzm4qwtezfRg1jOYaUmnzLX1AOD6Z+UJjtifg=="], - - "@rollup/rollup-android-arm64": ["@rollup/rollup-android-arm64@4.57.1", "", { "os": "android", "cpu": "arm64" }, "sha512-dQaAddCY9YgkFHZcFNS/606Exo8vcLHwArFZ7vxXq4rigo2bb494/xKMMwRRQW6ug7Js6yXmBZhSBRuBvCCQ3w=="], - - "@rollup/rollup-darwin-arm64": ["@rollup/rollup-darwin-arm64@4.57.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-crNPrwJOrRxagUYeMn/DZwqN88SDmwaJ8Cvi/TN1HnWBU7GwknckyosC2gd0IqYRsHDEnXf328o9/HC6OkPgOg=="], - - "@rollup/rollup-darwin-x64": ["@rollup/rollup-darwin-x64@4.57.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-Ji8g8ChVbKrhFtig5QBV7iMaJrGtpHelkB3lsaKzadFBe58gmjfGXAOfI5FV0lYMH8wiqsxKQ1C9B0YTRXVy4w=="], - - "@rollup/rollup-freebsd-arm64": ["@rollup/rollup-freebsd-arm64@4.57.1", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-R+/WwhsjmwodAcz65guCGFRkMb4gKWTcIeLy60JJQbXrJ97BOXHxnkPFrP+YwFlaS0m+uWJTstrUA9o+UchFug=="], - - "@rollup/rollup-freebsd-x64": ["@rollup/rollup-freebsd-x64@4.57.1", "", { "os": "freebsd", "cpu": "x64" }, "sha512-IEQTCHeiTOnAUC3IDQdzRAGj3jOAYNr9kBguI7MQAAZK3caezRrg0GxAb6Hchg4lxdZEI5Oq3iov/w/hnFWY9Q=="], - - "@rollup/rollup-linux-arm-gnueabihf": ["@rollup/rollup-linux-arm-gnueabihf@4.57.1", "", { "os": "linux", "cpu": "arm" }, "sha512-F8sWbhZ7tyuEfsmOxwc2giKDQzN3+kuBLPwwZGyVkLlKGdV1nvnNwYD0fKQ8+XS6hp9nY7B+ZeK01EBUE7aHaw=="], - - "@rollup/rollup-linux-arm-musleabihf": ["@rollup/rollup-linux-arm-musleabihf@4.57.1", "", { "os": "linux", "cpu": "arm" }, "sha512-rGfNUfn0GIeXtBP1wL5MnzSj98+PZe/AXaGBCRmT0ts80lU5CATYGxXukeTX39XBKsxzFpEeK+Mrp9faXOlmrw=="], - - "@rollup/rollup-linux-arm64-gnu": ["@rollup/rollup-linux-arm64-gnu@4.57.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-MMtej3YHWeg/0klK2Qodf3yrNzz6CGjo2UntLvk2RSPlhzgLvYEB3frRvbEF2wRKh1Z2fDIg9KRPe1fawv7C+g=="], - - "@rollup/rollup-linux-arm64-musl": ["@rollup/rollup-linux-arm64-musl@4.57.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-1a/qhaaOXhqXGpMFMET9VqwZakkljWHLmZOX48R0I/YLbhdxr1m4gtG1Hq7++VhVUmf+L3sTAf9op4JlhQ5u1Q=="], - - "@rollup/rollup-linux-loong64-gnu": ["@rollup/rollup-linux-loong64-gnu@4.57.1", "", { "os": "linux", "cpu": "none" }, "sha512-QWO6RQTZ/cqYtJMtxhkRkidoNGXc7ERPbZN7dVW5SdURuLeVU7lwKMpo18XdcmpWYd0qsP1bwKPf7DNSUinhvA=="], - - "@rollup/rollup-linux-loong64-musl": ["@rollup/rollup-linux-loong64-musl@4.57.1", "", { "os": "linux", "cpu": "none" }, "sha512-xpObYIf+8gprgWaPP32xiN5RVTi/s5FCR+XMXSKmhfoJjrpRAjCuuqQXyxUa/eJTdAE6eJ+KDKaoEqjZQxh3Gw=="], - - "@rollup/rollup-linux-ppc64-gnu": ["@rollup/rollup-linux-ppc64-gnu@4.57.1", "", { "os": "linux", "cpu": "ppc64" }, "sha512-4BrCgrpZo4hvzMDKRqEaW1zeecScDCR+2nZ86ATLhAoJ5FQ+lbHVD3ttKe74/c7tNT9c6F2viwB3ufwp01Oh2w=="], - - "@rollup/rollup-linux-ppc64-musl": ["@rollup/rollup-linux-ppc64-musl@4.57.1", "", { "os": "linux", "cpu": "ppc64" }, "sha512-NOlUuzesGauESAyEYFSe3QTUguL+lvrN1HtwEEsU2rOwdUDeTMJdO5dUYl/2hKf9jWydJrO9OL/XSSf65R5+Xw=="], - - "@rollup/rollup-linux-riscv64-gnu": ["@rollup/rollup-linux-riscv64-gnu@4.57.1", "", { "os": "linux", "cpu": "none" }, "sha512-ptA88htVp0AwUUqhVghwDIKlvJMD/fmL/wrQj99PRHFRAG6Z5nbWoWG4o81Nt9FT+IuqUQi+L31ZKAFeJ5Is+A=="], - - "@rollup/rollup-linux-riscv64-musl": ["@rollup/rollup-linux-riscv64-musl@4.57.1", "", { "os": "linux", "cpu": "none" }, "sha512-S51t7aMMTNdmAMPpBg7OOsTdn4tySRQvklmL3RpDRyknk87+Sp3xaumlatU+ppQ+5raY7sSTcC2beGgvhENfuw=="], - - "@rollup/rollup-linux-s390x-gnu": ["@rollup/rollup-linux-s390x-gnu@4.57.1", "", { "os": "linux", "cpu": "s390x" }, "sha512-Bl00OFnVFkL82FHbEqy3k5CUCKH6OEJL54KCyx2oqsmZnFTR8IoNqBF+mjQVcRCT5sB6yOvK8A37LNm/kPJiZg=="], - - "@rollup/rollup-linux-x64-gnu": ["@rollup/rollup-linux-x64-gnu@4.57.1", "", { "os": "linux", "cpu": "x64" }, "sha512-ABca4ceT4N+Tv/GtotnWAeXZUZuM/9AQyCyKYyKnpk4yoA7QIAuBt6Hkgpw8kActYlew2mvckXkvx0FfoInnLg=="], - - "@rollup/rollup-linux-x64-musl": ["@rollup/rollup-linux-x64-musl@4.57.1", "", { "os": "linux", "cpu": "x64" }, "sha512-HFps0JeGtuOR2convgRRkHCekD7j+gdAuXM+/i6kGzQtFhlCtQkpwtNzkNj6QhCDp7DRJ7+qC/1Vg2jt5iSOFw=="], - - "@rollup/rollup-openbsd-x64": ["@rollup/rollup-openbsd-x64@4.57.1", "", { "os": "openbsd", "cpu": "x64" }, "sha512-H+hXEv9gdVQuDTgnqD+SQffoWoc0Of59AStSzTEj/feWTBAnSfSD3+Dql1ZruJQxmykT/JVY0dE8Ka7z0DH1hw=="], - - "@rollup/rollup-openharmony-arm64": ["@rollup/rollup-openharmony-arm64@4.57.1", "", { "os": "none", "cpu": "arm64" }, "sha512-4wYoDpNg6o/oPximyc/NG+mYUejZrCU2q+2w6YZqrAs2UcNUChIZXjtafAiiZSUc7On8v5NyNj34Kzj/Ltk6dQ=="], - - "@rollup/rollup-win32-arm64-msvc": ["@rollup/rollup-win32-arm64-msvc@4.57.1", "", { "os": "win32", "cpu": "arm64" }, "sha512-O54mtsV/6LW3P8qdTcamQmuC990HDfR71lo44oZMZlXU4tzLrbvTii87Ni9opq60ds0YzuAlEr/GNwuNluZyMQ=="], - - "@rollup/rollup-win32-ia32-msvc": ["@rollup/rollup-win32-ia32-msvc@4.57.1", "", { "os": "win32", "cpu": "ia32" }, "sha512-P3dLS+IerxCT/7D2q2FYcRdWRl22dNbrbBEtxdWhXrfIMPP9lQhb5h4Du04mdl5Woq05jVCDPCMF7Ub0NAjIew=="], - - "@rollup/rollup-win32-x64-gnu": ["@rollup/rollup-win32-x64-gnu@4.57.1", "", { "os": "win32", "cpu": "x64" }, "sha512-VMBH2eOOaKGtIJYleXsi2B8CPVADrh+TyNxJ4mWPnKfLB/DBUmzW+5m1xUrcwWoMfSLagIRpjUFeW5CO5hyciQ=="], - - "@rollup/rollup-win32-x64-msvc": ["@rollup/rollup-win32-x64-msvc@4.57.1", "", { "os": "win32", "cpu": "x64" }, "sha512-mxRFDdHIWRxg3UfIIAwCm6NzvxG0jDX/wBN6KsQFTvKFqqg9vTrWUE68qEjHt19A5wwx5X5aUi2zuZT7YR0jrA=="], - - "@types/bun": ["@types/bun@1.3.9", "", { "dependencies": { "bun-types": "1.3.9" } }, "sha512-KQ571yULOdWJiMH+RIWIOZ7B2RXQGpL1YQrBtLIV3FqDcCu6FsbFUBwhdKUlCKUpS3PJDsHlJ1QKlpxoVR+xtw=="], - - "@types/chai": ["@types/chai@5.2.3", "", { "dependencies": { "@types/deep-eql": "*", "assertion-error": "^2.0.1" } }, "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA=="], - - "@types/deep-eql": ["@types/deep-eql@4.0.2", "", {}, "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw=="], - - "@types/estree": ["@types/estree@1.0.8", "", {}, "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w=="], - - "@types/node": ["@types/node@25.2.3", "", { "dependencies": { "undici-types": "~7.16.0" } }, "sha512-m0jEgYlYz+mDJZ2+F4v8D1AyQb+QzsNqRuI7xg1VQX/KlKS0qT9r1Mo16yo5F/MtifXFgaofIFsdFMox2SxIbQ=="], - - "@vitest/expect": ["@vitest/expect@3.2.4", "", { "dependencies": { "@types/chai": "^5.2.2", "@vitest/spy": "3.2.4", "@vitest/utils": "3.2.4", "chai": "^5.2.0", "tinyrainbow": "^2.0.0" } }, "sha512-Io0yyORnB6sikFlt8QW5K7slY4OjqNX9jmJQ02QDda8lyM6B5oNgVWoSoKPac8/kgnCUzuHQKrSLtu/uOqqrig=="], - - "@vitest/mocker": ["@vitest/mocker@3.2.4", "", { "dependencies": { "@vitest/spy": "3.2.4", "estree-walker": "^3.0.3", "magic-string": "^0.30.17" }, "peerDependencies": { "msw": "^2.4.9", "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" }, "optionalPeers": ["msw", "vite"] }, "sha512-46ryTE9RZO/rfDd7pEqFl7etuyzekzEhUbTW3BvmeO/BcCMEgq59BKhek3dXDWgAj4oMK6OZi+vRr1wPW6qjEQ=="], - - "@vitest/pretty-format": ["@vitest/pretty-format@3.2.4", "", { "dependencies": { "tinyrainbow": "^2.0.0" } }, "sha512-IVNZik8IVRJRTr9fxlitMKeJeXFFFN0JaB9PHPGQ8NKQbGpfjlTx9zO4RefN8gp7eqjNy8nyK3NZmBzOPeIxtA=="], - - "@vitest/runner": ["@vitest/runner@3.2.4", "", { "dependencies": { "@vitest/utils": "3.2.4", "pathe": "^2.0.3", "strip-literal": "^3.0.0" } }, "sha512-oukfKT9Mk41LreEW09vt45f8wx7DordoWUZMYdY/cyAk7w5TWkTRCNZYF7sX7n2wB7jyGAl74OxgwhPgKaqDMQ=="], - - "@vitest/snapshot": ["@vitest/snapshot@3.2.4", "", { "dependencies": { "@vitest/pretty-format": "3.2.4", "magic-string": "^0.30.17", "pathe": "^2.0.3" } }, "sha512-dEYtS7qQP2CjU27QBC5oUOxLE/v5eLkGqPE0ZKEIDGMs4vKWe7IjgLOeauHsR0D5YuuycGRO5oSRXnwnmA78fQ=="], - - "@vitest/spy": ["@vitest/spy@3.2.4", "", { "dependencies": { "tinyspy": "^4.0.3" } }, "sha512-vAfasCOe6AIK70iP5UD11Ac4siNUNJ9i/9PZ3NKx07sG6sUxeag1LWdNrMWeKKYBLlzuK+Gn65Yd5nyL6ds+nw=="], - - "@vitest/utils": ["@vitest/utils@3.2.4", "", { "dependencies": { "@vitest/pretty-format": "3.2.4", "loupe": "^3.1.4", "tinyrainbow": "^2.0.0" } }, "sha512-fB2V0JFrQSMsCo9HiSq3Ezpdv4iYaXRG1Sx8edX3MwxfyNn83mKiGzOcH+Fkxt4MHxr3y42fQi1oeAInqgX2QA=="], - - "assertion-error": ["assertion-error@2.0.1", "", {}, "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA=="], - - "bun-types": ["bun-types@1.3.9", "", { "dependencies": { "@types/node": "*" } }, "sha512-+UBWWOakIP4Tswh0Bt0QD0alpTY8cb5hvgiYeWCMet9YukHbzuruIEeXC2D7nMJPB12kbh8C7XJykSexEqGKJg=="], - - "cac": ["cac@6.7.14", "", {}, "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ=="], - - "chai": ["chai@5.3.3", "", { "dependencies": { "assertion-error": "^2.0.1", "check-error": "^2.1.1", "deep-eql": "^5.0.1", "loupe": "^3.1.0", "pathval": "^2.0.0" } }, "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw=="], - - "check-error": ["check-error@2.1.3", "", {}, "sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA=="], - - "debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], - - "deep-eql": ["deep-eql@5.0.2", "", {}, "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q=="], - - "es-module-lexer": ["es-module-lexer@1.7.0", "", {}, "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA=="], - - "esbuild": ["esbuild@0.27.3", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.27.3", "@esbuild/android-arm": "0.27.3", "@esbuild/android-arm64": "0.27.3", "@esbuild/android-x64": "0.27.3", "@esbuild/darwin-arm64": "0.27.3", "@esbuild/darwin-x64": "0.27.3", "@esbuild/freebsd-arm64": "0.27.3", "@esbuild/freebsd-x64": "0.27.3", "@esbuild/linux-arm": "0.27.3", "@esbuild/linux-arm64": "0.27.3", "@esbuild/linux-ia32": "0.27.3", "@esbuild/linux-loong64": "0.27.3", "@esbuild/linux-mips64el": "0.27.3", "@esbuild/linux-ppc64": "0.27.3", "@esbuild/linux-riscv64": "0.27.3", "@esbuild/linux-s390x": "0.27.3", "@esbuild/linux-x64": "0.27.3", "@esbuild/netbsd-arm64": "0.27.3", "@esbuild/netbsd-x64": "0.27.3", "@esbuild/openbsd-arm64": "0.27.3", "@esbuild/openbsd-x64": "0.27.3", "@esbuild/openharmony-arm64": "0.27.3", "@esbuild/sunos-x64": "0.27.3", "@esbuild/win32-arm64": "0.27.3", "@esbuild/win32-ia32": "0.27.3", "@esbuild/win32-x64": "0.27.3" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-8VwMnyGCONIs6cWue2IdpHxHnAjzxnw2Zr7MkVxB2vjmQ2ivqGFb4LEG3SMnv0Gb2F/G/2yA8zUaiL1gywDCCg=="], - - "estree-walker": ["estree-walker@3.0.3", "", { "dependencies": { "@types/estree": "^1.0.0" } }, "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g=="], - - "expect-type": ["expect-type@1.3.0", "", {}, "sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA=="], - - "fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="], - - "fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="], - - "hono": ["hono@4.11.9", "", {}, "sha512-Eaw2YTGM6WOxA6CXbckaEvslr2Ne4NFsKrvc0v97JD5awbmeBLO5w9Ho9L9kmKonrwF9RJlW6BxT1PVv/agBHQ=="], - - "js-tokens": ["js-tokens@9.0.1", "", {}, "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ=="], - - "loupe": ["loupe@3.2.1", "", {}, "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ=="], - - "magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="], - - "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], - - "nanoid": ["nanoid@3.3.11", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w=="], - - "pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="], - - "pathval": ["pathval@2.0.1", "", {}, "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ=="], - - "picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="], - - "picomatch": ["picomatch@4.0.3", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="], - - "postcss": ["postcss@8.5.6", "", { "dependencies": { "nanoid": "^3.3.11", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg=="], - - "rollup": ["rollup@4.57.1", "", { "dependencies": { "@types/estree": "1.0.8" }, "optionalDependencies": { "@rollup/rollup-android-arm-eabi": "4.57.1", "@rollup/rollup-android-arm64": "4.57.1", "@rollup/rollup-darwin-arm64": "4.57.1", "@rollup/rollup-darwin-x64": "4.57.1", "@rollup/rollup-freebsd-arm64": "4.57.1", "@rollup/rollup-freebsd-x64": "4.57.1", "@rollup/rollup-linux-arm-gnueabihf": "4.57.1", "@rollup/rollup-linux-arm-musleabihf": "4.57.1", "@rollup/rollup-linux-arm64-gnu": "4.57.1", "@rollup/rollup-linux-arm64-musl": "4.57.1", "@rollup/rollup-linux-loong64-gnu": "4.57.1", "@rollup/rollup-linux-loong64-musl": "4.57.1", "@rollup/rollup-linux-ppc64-gnu": "4.57.1", "@rollup/rollup-linux-ppc64-musl": "4.57.1", "@rollup/rollup-linux-riscv64-gnu": "4.57.1", "@rollup/rollup-linux-riscv64-musl": "4.57.1", "@rollup/rollup-linux-s390x-gnu": "4.57.1", "@rollup/rollup-linux-x64-gnu": "4.57.1", "@rollup/rollup-linux-x64-musl": "4.57.1", "@rollup/rollup-openbsd-x64": "4.57.1", "@rollup/rollup-openharmony-arm64": "4.57.1", "@rollup/rollup-win32-arm64-msvc": "4.57.1", "@rollup/rollup-win32-ia32-msvc": "4.57.1", "@rollup/rollup-win32-x64-gnu": "4.57.1", "@rollup/rollup-win32-x64-msvc": "4.57.1", "fsevents": "~2.3.2" }, "bin": { "rollup": "dist/bin/rollup" } }, "sha512-oQL6lgK3e2QZeQ7gcgIkS2YZPg5slw37hYufJ3edKlfQSGGm8ICoxswK15ntSzF/a8+h7ekRy7k7oWc3BQ7y8A=="], - - "siginfo": ["siginfo@2.0.0", "", {}, "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g=="], - - "source-map-js": ["source-map-js@1.2.1", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="], - - "stackback": ["stackback@0.0.2", "", {}, "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw=="], - - "std-env": ["std-env@3.10.0", "", {}, "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg=="], - - "strip-literal": ["strip-literal@3.1.0", "", { "dependencies": { "js-tokens": "^9.0.1" } }, "sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg=="], - - "tinybench": ["tinybench@2.9.0", "", {}, "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg=="], - - "tinyexec": ["tinyexec@0.3.2", "", {}, "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA=="], - - "tinyglobby": ["tinyglobby@0.2.15", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.3" } }, "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ=="], - - "tinypool": ["tinypool@1.1.1", "", {}, "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg=="], - - "tinyrainbow": ["tinyrainbow@2.0.0", "", {}, "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw=="], - - "tinyspy": ["tinyspy@4.0.4", "", {}, "sha512-azl+t0z7pw/z958Gy9svOTuzqIk6xq+NSheJzn5MMWtWTFywIacg2wUlzKFGtt3cthx0r2SxMK0yzJOR0IES7Q=="], - - "typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="], - - "undici-types": ["undici-types@7.16.0", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="], - - "vite": ["vite@7.3.1", "", { "dependencies": { "esbuild": "^0.27.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA=="], - - "vite-node": ["vite-node@3.2.4", "", { "dependencies": { "cac": "^6.7.14", "debug": "^4.4.1", "es-module-lexer": "^1.7.0", "pathe": "^2.0.3", "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" }, "bin": { "vite-node": "vite-node.mjs" } }, "sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg=="], - - "vitest": ["vitest@3.2.4", "", { "dependencies": { "@types/chai": "^5.2.2", "@vitest/expect": "3.2.4", "@vitest/mocker": "3.2.4", "@vitest/pretty-format": "^3.2.4", "@vitest/runner": "3.2.4", "@vitest/snapshot": "3.2.4", "@vitest/spy": "3.2.4", "@vitest/utils": "3.2.4", "chai": "^5.2.0", "debug": "^4.4.1", "expect-type": "^1.2.1", "magic-string": "^0.30.17", "pathe": "^2.0.3", "picomatch": "^4.0.2", "std-env": "^3.9.0", "tinybench": "^2.9.0", "tinyexec": "^0.3.2", "tinyglobby": "^0.2.14", "tinypool": "^1.1.1", "tinyrainbow": "^2.0.0", "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0", "vite-node": "3.2.4", "why-is-node-running": "^2.3.0" }, "peerDependencies": { "@edge-runtime/vm": "*", "@types/debug": "^4.1.12", "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", "@vitest/browser": "3.2.4", "@vitest/ui": "3.2.4", "happy-dom": "*", "jsdom": "*" }, "optionalPeers": ["@edge-runtime/vm", "@types/debug", "@types/node", "@vitest/browser", "@vitest/ui", "happy-dom", "jsdom"], "bin": { "vitest": "vitest.mjs" } }, "sha512-LUCP5ev3GURDysTWiP47wRRUpLKMOfPh+yKTx3kVIEiu5KOMeqzpnYNsKyOoVrULivR8tLcks4+lga33Whn90A=="], - - "why-is-node-running": ["why-is-node-running@2.3.0", "", { "dependencies": { "siginfo": "^2.0.0", "stackback": "0.0.2" }, "bin": { "why-is-node-running": "cli.js" } }, "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w=="], - - "zod": ["zod@4.3.6", "", {}, "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg=="], - - "@kilocode/plugin/zod": ["zod@4.1.8", "", {}, "sha512-5R1P+WwQqmmMIEACyzSvo4JXHY5WiAFHRMg+zBZKgKS+Q1viRa0C1hmUKtHltoIFKtIdki3pRxkmpP74jnNYHQ=="], - } -} diff --git a/cloudflare-gastown/container/package.json b/cloudflare-gastown/container/package.json index 4ce53545a6..74bc8dbeaf 100644 --- a/cloudflare-gastown/container/package.json +++ b/cloudflare-gastown/container/package.json @@ -12,8 +12,8 @@ "lint": "eslint --config eslint.config.mjs --cache 'src/**/*.ts'" }, "dependencies": { - "@kilocode/plugin": "1.0.23", - "@kilocode/sdk": "1.0.23", + "@kilocode/plugin": "7.0.37", + "@kilocode/sdk": "7.0.37", "hono": "catalog:", "zod": "catalog:" }, diff --git a/cloudflare-gastown/container/plugin/client.ts b/cloudflare-gastown/container/plugin/client.ts index 5f74d2e223..7af95cf8ae 100644 --- a/cloudflare-gastown/container/plugin/client.ts +++ b/cloudflare-gastown/container/plugin/client.ts @@ -27,7 +27,6 @@ export class GastownClient { private agentId: string; private rigId: string; private townId: string; - constructor(env: GastownEnv) { this.baseUrl = env.apiUrl.replace(/\/+$/, ''); this.token = env.sessionToken; diff --git a/cloudflare-gastown/container/src/agent-runner.ts b/cloudflare-gastown/container/src/agent-runner.ts index f2ce037f2c..2477c8ef4c 100644 --- a/cloudflare-gastown/container/src/agent-runner.ts +++ b/cloudflare-gastown/container/src/agent-runner.ts @@ -15,13 +15,28 @@ function resolveEnv(request: StartAgentRequest, key: string): string | undefined return request.envVars?.[key] ?? process.env[key]; } +/** Prepend the kilo provider prefix to an OpenRouter-style model ID. */ +function kiloModel(openrouterModel: string): string { + return openrouterModel.startsWith('kilo/') ? openrouterModel : `kilo/${openrouterModel}`; +} + +const HEADLESS_PERMISSIONS = { + edit: 'allow' as const, + bash: 'allow' as const, + webfetch: 'allow' as const, + doom_loop: 'allow' as const, + external_directory: 'allow' as const, +}; + /** * Build KILO_CONFIG_CONTENT JSON so kilo serve can authenticate with - * the Kilo LLM gateway. Mirrors the pattern in cloud-agent-next's - * session-service.ts getSaferEnvVars(). + * the Kilo LLM gateway. Both `model` and `smallModel` are OpenRouter-style + * IDs (e.g. "anthropic/claude-sonnet-4.6") resolved from the town config. */ -function buildKiloConfigContent(kilocodeToken: string, model?: string): string { - const resolvedModel = model ?? 'kilo/anthropic/claude-sonnet-4.6'; +function buildKiloConfigContent(kilocodeToken: string, model: string, smallModel: string): string { + const primaryModel = kiloModel(model); + const smModel = kiloModel(smallModel); + return JSON.stringify({ provider: { kilo: { @@ -29,86 +44,31 @@ function buildKiloConfigContent(kilocodeToken: string, model?: string): string { apiKey: kilocodeToken, kilocodeToken, }, - // Explicitly register models so the kilo server doesn't reject them - // before routing to the gateway. The gateway handles actual validation. + // Register models so the kilo server doesn't reject them before + // routing to the gateway. models: { - [resolvedModel]: {}, - 'kilo/anthropic/claude-haiku-4.5': {}, + [primaryModel]: {}, + [smModel]: {}, }, }, }, - // Override the small model (used for title generation) to a valid - // kilo-provider model. Without this, kilo serve defaults to - // openai/gpt-5-nano which doesn't exist in the kilo provider, - // causing ProviderModelNotFoundError that kills the entire prompt loop. - small_model: 'kilo/anthropic/claude-haiku-4.5', - model: resolvedModel, - // Override the title agent to use a valid model (same as small_model). - // kilo serve v1.0.23 resolves title model independently and the - // small_model fallback doesn't prevent ProviderModelNotFoundError. + // Override small_model (used for title generation). Without this, kilo + // serve defaults to a model that doesn't exist in the kilo provider, + // causing ProviderModelNotFoundError. + small_model: smModel, + model: primaryModel, agent: { - code: { - model: 'kilo/anthropic/claude-sonnet-4.6', - // Auto-approve everything — agents run headless in a container, - // there's no human to answer permission prompts. - permission: { - edit: 'allow', - bash: 'allow', - webfetch: 'allow', - doom_loop: 'allow', - external_directory: 'allow', - }, - }, - general: { - model: 'kilo/anthropic/claude-sonnet-4.6', - // Auto-approve everything — agents run headless in a container, - // there's no human to answer permission prompts. - permission: { - edit: 'allow', - bash: 'allow', - webfetch: 'allow', - doom_loop: 'allow', - external_directory: 'allow', - }, - }, - plan: { - model: 'kilo/anthropic/claude-sonnet-4.6', - // Auto-approve everything — agents run headless in a container, - // there's no human to answer permission prompts. - permission: { - edit: 'allow', - bash: 'allow', - webfetch: 'allow', - doom_loop: 'allow', - external_directory: 'allow', - }, - }, - title: { - model: 'kilo/anthropic/claude-haiku-4.5', - }, + code: { model: primaryModel, permission: HEADLESS_PERMISSIONS }, + general: { model: primaryModel, permission: HEADLESS_PERMISSIONS }, + plan: { model: primaryModel, permission: HEADLESS_PERMISSIONS }, + title: { model: smModel }, explore: { - small_model: 'kilo/anthropic/claude-haiku-4.5', - model: 'kilo/anthropic/claude-sonnet-4.6', - // Auto-approve everything — agents run headless in a container, - // there's no human to answer permission prompts. - permission: { - edit: 'allow', - bash: 'allow', - webfetch: 'allow', - doom_loop: 'allow', - external_directory: 'allow', - }, + small_model: smModel, + model: primaryModel, + permission: HEADLESS_PERMISSIONS, }, }, - // Auto-approve everything — agents run headless in a container, - // there's no human to answer permission prompts. - permission: { - edit: 'allow', - bash: 'allow', - webfetch: 'allow', - doom_loop: 'allow', - external_directory: 'allow', - }, + permission: HEADLESS_PERMISSIONS, } satisfies Config); } @@ -137,6 +97,12 @@ function buildAgentEnv(request: StartAgentRequest): Record { } } + console.log(`GASTOWN_API_URL="${env.GASTOWN_API_URL}" +GASTOWN_SESSION_TOKEN=${env.GASTOWN_SESSION_TOKEN ? '(set)' : '(not set)'} +GASTOWN_AGENT_ID="${env.GASTOWN_AGENT_ID}" +GASTOWN_RIG_ID="${env.GASTOWN_RIG_ID}" +GASTOWN_TOWN_ID="${env.GASTOWN_TOWN_ID}"`); + // Fall back to X-Town-Config for KILOCODE_TOKEN if not in request or process.env if (!env.KILOCODE_TOKEN) { const townConfig = getCurrentTownConfig(); @@ -156,15 +122,32 @@ function buildAgentEnv(request: StartAgentRequest): Record { // Must also set OPENCODE_CONFIG_CONTENT — kilo serve checks both names. const kilocodeToken = env.KILOCODE_TOKEN; if (kilocodeToken) { - const configJson = buildKiloConfigContent(kilocodeToken, request.model); + const configJson = buildKiloConfigContent( + kilocodeToken, + request.model, + request.smallModel ?? 'anthropic/claude-haiku-4.5' + ); env.KILO_CONFIG_CONTENT = configJson; env.OPENCODE_CONFIG_CONTENT = configJson; - const resolvedModel = request.model ?? 'kilo/anthropic/claude-sonnet-4.6'; - console.log(`[buildAgentEnv] KILO_CONFIG_CONTENT set (model=${resolvedModel})`); + console.log( + `[buildAgentEnv] KILO_CONFIG_CONTENT set (model=${request.model}, smallModel=${request.smallModel ?? '(default)'})` + ); } else { console.warn('[buildAgentEnv] No KILOCODE_TOKEN available — KILO_CONFIG_CONTENT not set'); } + // Authenticate the gh CLI via GH_TOKEN so agents can use `gh` commands. + // GIT_TOKEN is a GitHub access token set by the town config's git_auth. + // Set before the envVars loop so user-provided GH_TOKEN in town env vars + // cannot override the platform credential (intentional — prevents agents + // from being pointed at a different GitHub identity). + const ghToken = resolveEnv(request, 'GIT_TOKEN') ?? resolveEnv(request, 'GITHUB_TOKEN'); + if (ghToken) { + env.GH_TOKEN = ghToken; + } + + // Town-level env vars. The `!(key in env)` guard means infra-set vars + // (GASTOWN_*, KILO_*, GH_TOKEN, etc.) take precedence over user config. if (request.envVars) { for (const [key, value] of Object.entries(request.envVars)) { if (!(key in env)) { diff --git a/cloudflare-gastown/container/src/process-manager.ts b/cloudflare-gastown/container/src/process-manager.ts index 0e03547879..1a1db0aa9e 100644 --- a/cloudflare-gastown/container/src/process-manager.ts +++ b/cloudflare-gastown/container/src/process-manager.ts @@ -1,12 +1,12 @@ /** - * Agent manager — tracks agents as SDK-managed opencode sessions. + * Agent manager — tracks agents as SDK-managed kilo sessions. * - * Uses @kilocode/sdk's createOpencode() to start server instances in-process + * Uses @kilocode/sdk's createKilo() to start server instances in-process * and client.event.subscribe() for typed event streams. No subprocesses, * no SSE text parsing, no ring buffers. */ -import { createOpencode, type OpencodeClient } from '@kilocode/sdk'; +import { createKilo, type KiloClient } from '@kilocode/sdk'; import { z } from 'zod'; import type { ManagedAgent, StartAgentRequest } from './types'; import { reportAgentCompleted } from './completion-reporter'; @@ -18,7 +18,7 @@ const MANAGER_LOG = '[process-manager]'; const SessionResponse = z.object({ id: z.string().min(1) }).passthrough(); type SDKInstance = { - client: OpencodeClient; + client: KiloClient; server: { url: string; close(): void }; sessionCount: number; }; @@ -119,7 +119,7 @@ function broadcastEvent(agentId: string, event: string, data: unknown): void { async function ensureSDKServer( workdir: string, env: Record -): Promise<{ client: OpencodeClient; port: number }> { +): Promise<{ client: KiloClient; port: number }> { const existing = sdkInstances.get(workdir); if (existing) { return { @@ -131,7 +131,7 @@ async function ensureSDKServer( const port = nextPort++; console.log(`${MANAGER_LOG} Starting SDK server on port ${port} for ${workdir}`); - // Save env vars that we'll mutate, set them for createOpencode, then restore. + // Save env vars that we'll mutate, set them for createKilo, then restore. // This avoids permanent global mutation when multiple agents start with // different env — each server gets the env it was started with. const envSnapshot: Record = {}; @@ -144,7 +144,7 @@ async function ensureSDKServer( const prevCwd = process.cwd(); try { process.chdir(workdir); - const { client, server } = await createOpencode({ + const { client, server } = await createKilo({ hostname: '127.0.0.1', port, timeout: 30_000, @@ -172,7 +172,7 @@ async function ensureSDKServer( * Subscribe to SDK events for an agent's session and forward them. */ async function subscribeToEvents( - client: OpencodeClient, + client: KiloClient, agent: ManagedAgent, request: StartAgentRequest ): Promise { diff --git a/cloudflare-gastown/container/src/types.ts b/cloudflare-gastown/container/src/types.ts index 635865feda..55ae3847c0 100644 --- a/cloudflare-gastown/container/src/types.ts +++ b/cloudflare-gastown/container/src/types.ts @@ -16,6 +16,8 @@ export const StartAgentRequest = z.object({ identity: z.string(), prompt: z.string(), model: z.string(), + /** Lightweight model for title generation, explore subagent, etc. */ + smallModel: z.string().optional(), systemPrompt: z.string(), gitUrl: z.string(), branch: z.string(), diff --git a/cloudflare-gastown/package.json b/cloudflare-gastown/package.json index 72290d3a41..f0726a3a4b 100644 --- a/cloudflare-gastown/package.json +++ b/cloudflare-gastown/package.json @@ -6,10 +6,11 @@ "description": "Gastown: AI agent orchestration via Durable Objects", "scripts": { "preinstall": "npx only-allow pnpm", - "deploy:prod": "wrangler deploy --env=\"\"", - "deploy:dev": "wrangler deploy --env dev", - "dev": "wrangler dev --env dev", - "start": "wrangler dev --env dev", + "container:prepare": "node scripts/prepare-container.mjs", + "deploy:prod": "pnpm container:prepare && wrangler deploy --env=\"\"", + "deploy:dev": "pnpm container:prepare && wrangler deploy --env dev", + "dev": "pnpm container:prepare && wrangler dev --env dev --ip 0.0.0.0", + "start": "pnpm container:prepare && wrangler dev --env dev --ip 0.0.0.0", "types": "wrangler types", "test": "vitest run", "test:watch": "vitest", diff --git a/cloudflare-gastown/scripts/prepare-container.mjs b/cloudflare-gastown/scripts/prepare-container.mjs new file mode 100644 index 0000000000..3774e7fe75 --- /dev/null +++ b/cloudflare-gastown/scripts/prepare-container.mjs @@ -0,0 +1,61 @@ +/** + * Copy the root pnpm-workspace.yaml (catalog only) and pnpm-lock.yaml + * into the container build context so pnpm can resolve catalog: references. + * + * The packages: section and other non-catalog sections are stripped because + * those workspace paths don't exist inside the container and would cause + * pnpm to error on workspace: references. + */ + +import { readFileSync, writeFileSync, copyFileSync } from 'node:fs'; +import { resolve, dirname } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const gastownRoot = resolve(__dirname, '..'); +const repoRoot = resolve(gastownRoot, '..'); +const containerDir = resolve(gastownRoot, 'container'); + +// Read root workspace yaml and extract only the catalog: section. +// Parse line-by-line: keep lines from `catalog:` until the next +// top-level key (a line starting with a non-space, non-comment char). +const lines = readFileSync(resolve(repoRoot, 'pnpm-workspace.yaml'), 'utf8').split('\n'); +const catalogLines = []; +let inCatalog = false; + +for (const line of lines) { + if (line.startsWith('catalog:')) { + inCatalog = true; + catalogLines.push(line); + continue; + } + if (inCatalog) { + // Still in catalog if line is indented, empty, or a comment + if (line === '' || line.startsWith(' ') || line.startsWith('\t') || line.startsWith('#')) { + catalogLines.push(line); + } else { + break; + } + } +} + +writeFileSync(resolve(containerDir, 'pnpm-workspace.yaml'), catalogLines.join('\n') + '\n'); + +// Create a production-only package.json that strips workspace: references +// (they can't be resolved outside the monorepo). +const pkg = JSON.parse(readFileSync(resolve(containerDir, 'package.json'), 'utf8')); +if (pkg.devDependencies) { + for (const [name, version] of Object.entries(pkg.devDependencies)) { + if (typeof version === 'string' && version.startsWith('workspace:')) { + delete pkg.devDependencies[name]; + } + } +} +writeFileSync(resolve(containerDir, 'package.prod.json'), JSON.stringify(pkg, null, 2) + '\n'); + +// Copy the lockfile as-is +copyFileSync(resolve(repoRoot, 'pnpm-lock.yaml'), resolve(containerDir, 'pnpm-lock.yaml')); + +console.log( + 'Prepared container build context with pnpm-workspace.yaml (catalog only) and pnpm-lock.yaml' +); diff --git a/cloudflare-gastown/src/db/tables/bead-events.table.ts b/cloudflare-gastown/src/db/tables/bead-events.table.ts index f3e1ca7177..10d1ca28f0 100644 --- a/cloudflare-gastown/src/db/tables/bead-events.table.ts +++ b/cloudflare-gastown/src/db/tables/bead-events.table.ts @@ -15,6 +15,8 @@ export const BeadEventType = z.enum([ 'review_completed', 'agent_spawned', 'agent_exited', + 'pr_created', + 'pr_creation_failed', ]); export type BeadEventType = z.infer; diff --git a/cloudflare-gastown/src/dos/Town.do.ts b/cloudflare-gastown/src/dos/Town.do.ts index 6c9e95d3cd..37b9e90005 100644 --- a/cloudflare-gastown/src/dos/Town.do.ts +++ b/cloudflare-gastown/src/dos/Town.do.ts @@ -24,6 +24,7 @@ import * as reviewQueue from './town/review-queue'; import * as config from './town/config'; import * as rigs from './town/rigs'; import * as dispatch from './town/container-dispatch'; +import { GitHubPRStatusSchema, GitLabMRStatusSchema } from '../util/platform-pr.util'; // Table imports for beads-centric operations import { @@ -60,13 +61,14 @@ import type { PrimeContext, Molecule, BeadEventRecord, + MergeStrategy, } from '../types'; const TOWN_LOG = '[Town.do]'; // Alarm intervals -const ACTIVE_ALARM_INTERVAL_MS = 15_000; // 15s when agents are active -const IDLE_ALARM_INTERVAL_MS = 5 * 60_000; // 5m when idle +const ACTIVE_ALARM_INTERVAL_MS = 5_000; // 5s when agents are active +const IDLE_ALARM_INTERVAL_MS = 1 * 60_000; // 1m when idle const DISPATCH_COOLDOWN_MS = 2 * 60_000; // 2 min — skip agents with recent dispatch activity const GUPP_THRESHOLD_MS = 30 * 60_000; // 30 min const MAX_DISPATCH_ATTEMPTS = 5; @@ -93,6 +95,8 @@ type RigConfig = { userId: string; kilocodeToken?: string; platformIntegrationId?: string; + /** Per-rig merge strategy override. When unset, inherits from town config. */ + merge_strategy?: MergeStrategy; }; // ── Escalation API type (derived from EscalationBeadRecord) ───────── @@ -1442,6 +1446,9 @@ export class TownDO extends DurableObject { private async processReviewQueue(): Promise { reviewQueue.recoverStuckReviews(this.sql); + // Poll open PRs created by the 'pr' strategy + await this.pollPendingPRs(); + const entry = reviewQueue.popReviewQueue(this.sql); if (!entry) return; @@ -1460,78 +1467,185 @@ export class TownDO extends DurableObject { } const townConfig = await this.getTownConfig(); + const mergeStrategy = config.resolveMergeStrategy(townConfig, rigConfig.merge_strategy); const gates = townConfig.refinery?.gates ?? []; - if (gates.length > 0) { - const refineryAgent = agents.getOrCreateAgent(this.sql, 'refinery', rigId, this.townId); - - const { buildRefinerySystemPrompt } = await import('../prompts/refinery-system.prompt'); - const systemPrompt = buildRefinerySystemPrompt({ - identity: refineryAgent.identity, - rigId, - townId: this.townId, - gates, - branch: entry.branch, - targetBranch: rigConfig.defaultBranch, - polecatAgentId: entry.agent_id, - }); - - // Hook the refinery to the MR bead (entry.id), not the source bead - // (entry.bead_id). The source bead stays closed with its original - // polecat assignee preserved. - agents.hookBead(this.sql, refineryAgent.id, entry.id); - - const started = await dispatch.startAgentInContainer(this.env, this.ctx.storage, { - townId: this.townId, - rigId, - userId: rigConfig.userId, - agentId: refineryAgent.id, - agentName: refineryAgent.name, - role: 'refinery', - identity: refineryAgent.identity, - beadId: entry.id, - beadTitle: `Review merge: ${entry.branch} → ${rigConfig.defaultBranch}`, - beadBody: entry.summary ?? '', - checkpoint: null, - gitUrl: rigConfig.gitUrl, - defaultBranch: rigConfig.defaultBranch, - kilocodeToken: rigConfig.kilocodeToken, - townConfig, - systemPromptOverride: systemPrompt, - platformIntegrationId: rigConfig.platformIntegrationId, - }); + console.log( + `${TOWN_LOG} processReviewQueue: entry=${entry.id} branch=${entry.branch} ` + + `mergeStrategy=${mergeStrategy} gates=${gates.length}` + ); - if (!started) { - agents.unhookBead(this.sql, refineryAgent.id); - await this.triggerDeterministicMerge(rigConfig, entry, townConfig); - } - } else { - await this.triggerDeterministicMerge(rigConfig, entry, townConfig); - } - } + // Always spawn a refinery agent — it handles quality gates (if any), + // code review, and the merge/PR creation step via CLI tools. + const refineryAgent = agents.getOrCreateAgent(this.sql, 'refinery', rigId, this.townId); - private async triggerDeterministicMerge( - rigConfig: RigConfig, - entry: ReviewQueueEntry, - townConfig: TownConfig - ): Promise { - const ok = await dispatch.startMergeInContainer(this.env, this.ctx.storage, { + const { buildRefinerySystemPrompt } = await import('../prompts/refinery-system.prompt'); + const systemPrompt = buildRefinerySystemPrompt({ + identity: refineryAgent.identity, + rigId, townId: this.townId, - rigId: rigConfig.rigId, - agentId: entry.agent_id, - entryId: entry.id, - beadId: entry.bead_id, + gates, branch: entry.branch, targetBranch: rigConfig.defaultBranch, + polecatAgentId: entry.agent_id, + mergeStrategy, + }); + + // Hook the refinery to the MR bead (entry.id), not the source bead + // (entry.bead_id). The source bead stays closed with its original + // polecat assignee preserved. + agents.hookBead(this.sql, refineryAgent.id, entry.id); + + const started = await dispatch.startAgentInContainer(this.env, this.ctx.storage, { + townId: this.townId, + rigId, + userId: rigConfig.userId, + agentId: refineryAgent.id, + agentName: refineryAgent.name, + role: 'refinery', + identity: refineryAgent.identity, + beadId: entry.id, + beadTitle: `Review merge: ${entry.branch} → ${rigConfig.defaultBranch}`, + beadBody: entry.summary ?? '', + checkpoint: null, gitUrl: rigConfig.gitUrl, + defaultBranch: rigConfig.defaultBranch, kilocodeToken: rigConfig.kilocodeToken, townConfig, + systemPromptOverride: systemPrompt, + platformIntegrationId: rigConfig.platformIntegrationId, }); - if (!ok) { + + if (!started) { + agents.unhookBead(this.sql, refineryAgent.id); + console.error( + `${TOWN_LOG} processReviewQueue: refinery agent failed to start for entry=${entry.id}` + ); reviewQueue.completeReview(this.sql, entry.id, 'failed'); } } + /** + * Poll external PRs created by the 'pr' merge strategy. + * Checks if PRs have been merged or closed and updates the MR bead status. + */ + private async pollPendingPRs(): Promise { + const pendingReviews = reviewQueue.listPendingPRReviews(this.sql); + if (pendingReviews.length === 0) return; + + console.log(`${TOWN_LOG} pollPendingPRs: checking ${pendingReviews.length} pending PR(s)`); + + const townConfig = await this.getTownConfig(); + + // Cap the number of PRs polled per alarm tick to avoid exhausting + // GitHub/GitLab API rate limits when many PRs are pending. + const MAX_POLLS_PER_TICK = 10; + for (const review of pendingReviews.slice(0, MAX_POLLS_PER_TICK)) { + const prUrl = review.pr_url; + if (!prUrl) continue; + // review.bead_id is the MR bead's own ID (not the source bead). + // MergeRequestBeadRecord.bead_id == the merge_request bead PK. + + try { + const status = await this.checkPRStatus(prUrl, townConfig); + console.log( + `${TOWN_LOG} pollPendingPRs: entry=${review.bead_id} url=${prUrl} status=${status ?? 'null (could not determine)'}` + ); + if (!status) continue; + + if (status === 'merged') { + reviewQueue.completeReviewWithResult(this.sql, { + entry_id: review.bead_id, + status: 'merged', + message: 'PR merged externally', + }); + console.log(`${TOWN_LOG} pollPendingPRs: PR merged for entry=${review.bead_id}`); + } else if (status === 'closed') { + reviewQueue.completeReviewWithResult(this.sql, { + entry_id: review.bead_id, + status: 'failed', + message: 'PR closed without merge', + }); + console.log( + `${TOWN_LOG} pollPendingPRs: PR closed without merge for entry=${review.bead_id}` + ); + } + // 'open' — still waiting, do nothing + } catch (err) { + console.warn(`${TOWN_LOG} pollPendingPRs: failed to check PR status for ${prUrl}:`, err); + } + } + } + + /** + * Check the status of a PR/MR via its URL. + * Returns 'open', 'merged', or 'closed' (null if cannot determine). + */ + private async checkPRStatus( + prUrl: string, + townConfig: TownConfig + ): Promise<'open' | 'merged' | 'closed' | null> { + // GitHub PR URL format: https://github.com/{owner}/{repo}/pull/{number} + const ghMatch = prUrl.match(/^https:\/\/github\.com\/([^/]+)\/([^/]+)\/pull\/(\d+)/); + if (ghMatch) { + const [, owner, repo, numberStr] = ghMatch; + const token = townConfig.git_auth.github_token; + if (!token) { + console.warn(`${TOWN_LOG} checkPRStatus: no github_token configured, cannot poll ${prUrl}`); + return null; + } + + const response = await fetch( + `https://api.github.com/repos/${owner}/${repo}/pulls/${numberStr}`, + { + headers: { + Authorization: `token ${token}`, + Accept: 'application/vnd.github.v3+json', + 'User-Agent': 'Gastown-Refinery/1.0', + }, + } + ); + if (!response.ok) return null; + + const json = await response.json().catch(() => null); + if (!json) return null; + const data = GitHubPRStatusSchema.safeParse(json); + if (!data.success) return null; + + if (data.data.merged) return 'merged'; + if (data.data.state === 'closed') return 'closed'; + return 'open'; + } + + // GitLab MR URL format: https://{host}/{path}/-/merge_requests/{iid} + const glMatch = prUrl.match(/^(https:\/\/[^/]+)\/(.+)\/-\/merge_requests\/(\d+)/); + if (glMatch) { + const [, instanceUrl, projectPath, iidStr] = glMatch; + const token = townConfig.git_auth.gitlab_token; + if (!token) return null; + + const encodedPath = encodeURIComponent(projectPath); + const response = await fetch( + `${instanceUrl}/api/v4/projects/${encodedPath}/merge_requests/${iidStr}`, + { + headers: { 'PRIVATE-TOKEN': token }, + } + ); + if (!response.ok) return null; + + const glJson = await response.json().catch(() => null); + if (!glJson) return null; + const data = GitLabMRStatusSchema.safeParse(glJson); + if (!data.success) return null; + + if (data.data.state === 'merged') return 'merged'; + if (data.data.state === 'closed') return 'closed'; + return 'open'; + } + + return null; + } + /** * Bump severity of stale unacknowledged escalations. */ diff --git a/cloudflare-gastown/src/dos/town/config.ts b/cloudflare-gastown/src/dos/town/config.ts index e208d13236..2661f55177 100644 --- a/cloudflare-gastown/src/dos/town/config.ts +++ b/cloudflare-gastown/src/dos/town/config.ts @@ -2,7 +2,12 @@ * Town configuration management. */ -import { TownConfigSchema, type TownConfig, type TownConfigUpdate } from '../../types'; +import { + TownConfigSchema, + type TownConfig, + type TownConfigUpdate, + type MergeStrategy, +} from '../../types'; const CONFIG_KEY = 'town:config'; @@ -57,11 +62,19 @@ export async function updateTownConfig( git_auth: resolvedGitAuth, refinery: update.refinery !== undefined - ? { ...current.refinery, ...update.refinery } + ? { + gates: update.refinery.gates ?? current.refinery?.gates ?? [], + auto_merge: update.refinery.auto_merge ?? current.refinery?.auto_merge ?? true, + require_clean_merge: + update.refinery.require_clean_merge ?? current.refinery?.require_clean_merge ?? true, + } : current.refinery, container: update.container !== undefined - ? { ...current.container, ...update.container } + ? { + sleep_after_minutes: + update.container.sleep_after_minutes ?? current.container?.sleep_after_minutes, + } : current.container, }; @@ -74,15 +87,32 @@ export async function updateTownConfig( } /** - * Resolve the model for an agent role from town config. + * Resolve the primary model from town config. * Priority: rig override → role-specific → town default → hardcoded default. */ export function resolveModel(townConfig: TownConfig, _rigId: string, _role: string): string { - // OPEN QUESTION: Should we add rig_overrides to TownConfig? - // For now, just use the town default. return townConfig.default_model ?? 'anthropic/claude-sonnet-4.6'; } +/** + * Resolve the small (lightweight) model from town config. + * Used for title generation, explore subagent, etc. + */ +export function resolveSmallModel(townConfig: TownConfig): string { + return townConfig.small_model ?? 'anthropic/claude-haiku-4.5'; +} + +/** + * Resolve the effective merge strategy for a rig. + * Priority: rig-level override → town-level default → 'direct'. + */ +export function resolveMergeStrategy( + townConfig: TownConfig, + rigMergeStrategy: MergeStrategy | undefined +): MergeStrategy { + return rigMergeStrategy ?? townConfig.merge_strategy; +} + /** * Build the ContainerConfig payload for X-Town-Config header. * Sent with every fetch() to the container. @@ -94,7 +124,8 @@ export async function buildContainerConfig( const config = await getTownConfig(storage); return { env_vars: config.env_vars, - default_model: config.default_model ?? 'anthropic/claude-sonnet-4.6', + default_model: resolveModel(config, '', ''), + small_model: resolveSmallModel(config), git_auth: config.git_auth, kilocode_token: config.kilocode_token, kilo_api_url: env.KILO_API_URL ?? '', diff --git a/cloudflare-gastown/src/dos/town/container-dispatch.ts b/cloudflare-gastown/src/dos/town/container-dispatch.ts index 8889d2ad22..5980a430b9 100644 --- a/cloudflare-gastown/src/dos/town/container-dispatch.ts +++ b/cloudflare-gastown/src/dos/town/container-dispatch.ts @@ -8,7 +8,7 @@ import { signAgentJWT } from '../../util/jwt.util'; import { buildPolecatSystemPrompt } from '../../prompts/polecat-system.prompt'; import { buildMayorSystemPrompt } from '../../prompts/mayor-system.prompt'; import type { TownConfig } from '../../types'; -import { buildContainerConfig } from './config'; +import { buildContainerConfig, resolveModel, resolveSmallModel } from './config'; const TOWN_LOG = '[Town.do]'; @@ -17,12 +17,23 @@ const TOWN_LOG = '[Town.do]'; */ export async function resolveJWTSecret(env: Env): Promise { const binding = env.GASTOWN_JWT_SECRET; - if (!binding) return null; + if (!binding) { + console.error(`${TOWN_LOG} resolveJWTSecret: GASTOWN_JWT_SECRET binding is falsy`); + return null; + } if (typeof binding === 'string') return binding; try { - return await binding.get(); - } catch { - console.error('Failed to resolve GASTOWN_JWT_SECRET'); + const secret = await binding.get(); + if (!secret) { + console.error(`${TOWN_LOG} resolveJWTSecret: binding.get() returned falsy value`); + return null; + } + return secret ?? null; + } catch (err) { + console.error( + `${TOWN_LOG} resolveJWTSecret: binding.get() threw:`, + err instanceof Error ? err.message : err + ); return null; } } @@ -145,6 +156,14 @@ export async function startAgentInContainer( userId: params.userId, }); + if (!token) { + console.error( + `${TOWN_LOG} startAgentInContainer: ABORTING — failed to mint JWT for agent ${params.agentId}. ` + + 'The agent would start without GASTOWN_SESSION_TOKEN and be unable to call back to the worker.' + ); + return false; + } + // Build env vars from town config const envVars: Record = { ...(params.townConfig.env_vars ?? {}) }; @@ -189,7 +208,8 @@ export async function startAgentInContainer( beadBody: params.beadBody, checkpoint: params.checkpoint, }), - model: params.townConfig.default_model ?? 'anthropic/claude-sonnet-4.6', + model: resolveModel(params.townConfig, params.rigId, params.role), + smallModel: resolveSmallModel(params.townConfig), systemPrompt: params.systemPromptOverride ?? systemPromptForRole({ diff --git a/cloudflare-gastown/src/dos/town/review-queue.ts b/cloudflare-gastown/src/dos/town/review-queue.ts index 16978647d2..779e8f1ee2 100644 --- a/cloudflare-gastown/src/dos/town/review-queue.ts +++ b/cloudflare-gastown/src/dos/town/review-queue.ts @@ -76,6 +76,16 @@ export function submitToReviewQueue(sql: SqlStorage, input: ReviewQueueInput): v const id = generateId(); const timestamp = now(); + // Build metadata — include pr_url if the agent already created a PR so + // the link is visible via the standard bead list endpoint. + const metadata: Record = { + source_bead_id: input.bead_id, + source_agent_id: input.agent_id, + }; + if (input.pr_url) { + metadata.pr_url = input.pr_url; + } + // Create the merge_request bead query( sql, @@ -100,7 +110,7 @@ export function submitToReviewQueue(sql: SqlStorage, input: ReviewQueueInput): v null, // assignee left null — refinery claims it via hookBead 'medium', JSON.stringify(['gt:merge-request']), - JSON.stringify({ source_bead_id: input.bead_id, source_agent_id: input.agent_id }), + JSON.stringify(metadata), input.agent_id, // created_by records who submitted timestamp, timestamp, @@ -250,6 +260,84 @@ export function completeReviewWithResult( } } +/** + * Set the platform PR/MR URL on an MR bead's review_metadata and bead metadata. + * Called after a PR is created in the 'pr' merge strategy path. + * Writes to both review_metadata.pr_url (for query) and beads.metadata.pr_url + * (so the URL is available via the standard bead list endpoint). + */ +export function setReviewPrUrl(sql: SqlStorage, entryId: string, prUrl: string): boolean { + // Reject non-HTTPS URLs to prevent storing garbage from LLM output. + // Invalid URLs would cause pollPendingPRs to poll indefinitely. + if (!prUrl.startsWith('https://')) { + console.warn(`[review-queue] setReviewPrUrl: rejecting non-HTTPS pr_url: ${prUrl}`); + return false; + } + query( + sql, + /* sql */ ` + UPDATE ${review_metadata} + SET ${review_metadata.columns.pr_url} = ? + WHERE ${review_metadata.bead_id} = ? + `, + [prUrl, entryId] + ); + + // Also write to bead metadata so the PR URL is visible in the standard bead list + query( + sql, + /* sql */ ` + UPDATE ${beads} + SET ${beads.columns.metadata} = json_set(COALESCE(${beads.metadata}, '{}'), '$.pr_url', ?) + WHERE ${beads.bead_id} = ? + `, + [prUrl, entryId] + ); + return true; +} + +/** + * Set an MR bead status to 'in_review' (maps to bead status 'in_progress'). + * Used when the PR strategy creates a PR and waits for human review. + */ +export function markReviewInReview(sql: SqlStorage, entryId: string): void { + query( + sql, + /* sql */ ` + UPDATE ${beads} + SET ${beads.columns.status} = 'in_progress', + ${beads.columns.updated_at} = ? + WHERE ${beads.bead_id} = ? + `, + [new Date().toISOString(), entryId] + ); +} + +/** + * List MR beads that are in_progress and have a pr_url (PR-strategy merges + * waiting for external review). Used by the alarm to poll PR status. + */ +export function listPendingPRReviews(sql: SqlStorage): MergeRequestBeadRecord[] { + const rows = [ + ...query( + sql, + /* sql */ ` + ${REVIEW_JOIN} + WHERE ${beads.status} = 'in_progress' + AND ${review_metadata.pr_url} IS NOT NULL + `, + [] + ), + ]; + return MergeRequestBeadRecord.array().parse(rows); +} + +/** + * Reset MR beads stuck in 'in_progress' back to 'open' so they can be + * re-processed. Excludes beads that have a pr_url set — those are + * legitimately waiting for external human review (PR strategy) and may + * take hours or days. + */ export function recoverStuckReviews(sql: SqlStorage): void { const timeout = new Date(Date.now() - REVIEW_RUNNING_TIMEOUT_MS).toISOString(); query( @@ -261,6 +349,11 @@ export function recoverStuckReviews(sql: SqlStorage): void { WHERE ${beads.type} = 'merge_request' AND ${beads.status} = 'in_progress' AND ${beads.updated_at} < ? + AND ${beads.bead_id} NOT IN ( + SELECT ${review_metadata.bead_id} + FROM ${review_metadata} + WHERE ${review_metadata.pr_url} IS NOT NULL + ) `, [now(), timeout] ); @@ -274,10 +367,42 @@ export function agentDone(sql: SqlStorage, agentId: string, input: AgentDoneInpu if (!agent.current_hook_bead_id) throw new Error(`Agent ${agentId} has no hooked bead`); if (agent.role === 'refinery') { - // The refinery is hooked to the MR bead. Mark it as merged and log - // the review_completed event on the source bead. + // The refinery handles merging (direct strategy) or PR creation (pr strategy) + // itself. When it calls gt_done: + // - With pr_url: refinery created a PR → store URL, mark as in_review, poll it + // - Without pr_url: refinery merged directly → mark as merged const mrBeadId = agent.current_hook_bead_id; - completeReviewFromMRBead(sql, mrBeadId, agentId); + + if (input.pr_url) { + // PR strategy: refinery created a PR via gh/glab CLI. + // Validate the URL — LLM output may contain garbage URLs. + const stored = setReviewPrUrl(sql, mrBeadId, input.pr_url); + if (stored) { + markReviewInReview(sql, mrBeadId); + logBeadEvent(sql, { + beadId: mrBeadId, + agentId, + eventType: 'pr_created', + newValue: input.pr_url, + metadata: { pr_url: input.pr_url, created_by: 'refinery' }, + }); + } else { + // Invalid URL — fail the review so it doesn't poll forever + completeReviewWithResult(sql, { + entry_id: mrBeadId, + status: 'failed', + message: `Refinery provided invalid pr_url: ${input.pr_url}`, + }); + } + } else { + // Direct strategy: refinery already merged and pushed + completeReviewWithResult(sql, { + entry_id: mrBeadId, + status: 'merged', + message: input.summary ?? 'Merged by refinery agent', + }); + } + unhookBead(sql, agentId); return; } @@ -306,35 +431,6 @@ export function agentDone(sql: SqlStorage, agentId: string, input: AgentDoneInpu closeBead(sql, sourceBead, agentId); } -/** - * Complete a review given the MR bead id directly (the refinery is hooked - * to the MR bead). Marks the MR as merged and logs a review_completed - * event on the source bead. The source bead itself is already closed by - * the polecat's agentDone path. - */ -function completeReviewFromMRBead(sql: SqlStorage, mrBeadId: string, agentId: string): void { - const mrBead = getBead(sql, mrBeadId); - if (!mrBead) { - console.error( - `[review-queue] completeReviewFromMRBead: MR bead ${mrBeadId} not found — data integrity issue` - ); - return; - } - const sourceBeadId: unknown = mrBead.metadata?.source_bead_id; - - completeReview(sql, mrBeadId, 'merged'); - - if (typeof sourceBeadId === 'string') { - logBeadEvent(sql, { - beadId: sourceBeadId, - agentId, - eventType: 'review_completed', - newValue: 'merged', - metadata: { completedBy: 'refinery', mr_bead_id: mrBeadId }, - }); - } -} - /** * Called by the container when an agent process completes (or fails). * Closes/fails the bead and unhooks the agent. diff --git a/cloudflare-gastown/src/prompts/polecat-system.prompt.ts b/cloudflare-gastown/src/prompts/polecat-system.prompt.ts index 70fa8caafe..c12b074776 100644 --- a/cloudflare-gastown/src/prompts/polecat-system.prompt.ts +++ b/cloudflare-gastown/src/prompts/polecat-system.prompt.ts @@ -59,6 +59,10 @@ If you are stuck for more than a few attempts at the same problem: ## Important +- Do NOT create pull requests or merge requests. Your job is to write code on your branch. The Refinery handles merging and PR creation. +- Do NOT merge your branch into the default branch yourself. +- Do NOT use \`gh pr create\`, \`git merge\`, or any equivalent. Just push your branch and call gt_done. +- Do NOT pass a \`pr_url\` to \`gt_done\`. The URL that \`git push\` prints (e.g. \`https://github.com/.../pull/new/...\`) is NOT a pull request — it is a convenience link for humans. Ignore it. - Do NOT modify files outside your worktree. - Do NOT run destructive git operations (force push, hard reset to remote). - Do NOT install global packages or modify the container environment. diff --git a/cloudflare-gastown/src/prompts/refinery-system.prompt.ts b/cloudflare-gastown/src/prompts/refinery-system.prompt.ts index 7a8296a177..00bf59da62 100644 --- a/cloudflare-gastown/src/prompts/refinery-system.prompt.ts +++ b/cloudflare-gastown/src/prompts/refinery-system.prompt.ts @@ -1,8 +1,8 @@ /** * Build the system prompt for a refinery agent. * - * The refinery reviews polecat branches, runs quality gates, - * and decides whether to merge or request rework. + * The refinery reviews polecat branches, runs quality gates, and either + * merges directly or creates a PR depending on the configured merge strategy. */ export function buildRefinerySystemPrompt(params: { identity: string; @@ -12,22 +12,28 @@ export function buildRefinerySystemPrompt(params: { branch: string; targetBranch: string; polecatAgentId: string; + mergeStrategy: 'direct' | 'pr'; }): string { const gateList = params.gates.length > 0 ? params.gates.map((g, i) => `${i + 1}. \`${g}\``).join('\n') : '(No quality gates configured — skip to code review)'; + const mergeInstructions = + params.mergeStrategy === 'direct' + ? buildDirectMergeInstructions(params) + : buildPRMergeInstructions(params); + return `You are the Refinery agent for rig "${params.rigId}" (town "${params.townId}"). Your identity: ${params.identity} ## Your Role -You review code changes from polecat agents before they are merged into the default branch. -You are the quality gate — nothing merges without your approval. +You review code changes from polecat agents and, if they pass review, either merge them or create a pull request for human review. ## Current Review - **Branch to review:** \`${params.branch}\` - **Target branch:** \`${params.targetBranch}\` +- **Merge strategy:** ${params.mergeStrategy === 'direct' ? 'Direct merge (you merge and push)' : 'Pull request (you create a PR)'} - **Polecat agent ID:** ${params.polecatAgentId} ## Review Process @@ -50,8 +56,7 @@ If all gates pass (or no gates are configured), review the diff: ### Step 3: Decision **If everything passes:** -1. Merge the branch: \`git checkout ${params.targetBranch} && git merge --no-ff ${params.branch} && git push origin ${params.targetBranch}\` -2. Call \`gt_done\` to signal completion +${mergeInstructions} **If quality gates fail or code review finds issues:** 1. Analyze the failure output carefully @@ -60,18 +65,40 @@ If all gates pass (or no gates are configured), review the diff: - Specific files and line numbers that need changes - Clear instructions on what to fix 3. Call \`gt_escalate\` with severity "low" to record the rework request -4. Do NOT merge. Call \`gt_done\` to signal your review is complete (the bead stays open for rework). +4. Do NOT call \`gt_done\` — your session will end automatically. The system detects that no merge or PR was performed and marks the review as needing rework. ## Available Gastown Tools - \`gt_prime\` — Get your role context and current assignment -- \`gt_done\` — Signal your review is complete +- \`gt_done\` — Signal your review is complete (pass pr_url if you created a PR) - \`gt_mail_send\` — Send rework request to the polecat - \`gt_escalate\` — Record issues for visibility - \`gt_checkpoint\` — Save progress for crash recovery ## Important - Be specific in rework requests. "Fix the tests" is not actionable. "Test \`calculateTotal\` in \`tests/cart.test.ts\` fails because the discount logic in \`src/cart.ts:47\` doesn't handle the zero-quantity case" is actionable. -- Do not modify the code yourself. Your job is to review and decide, not to fix. +- Do not modify the code yourself. Your job is to review, merge/create PRs, and decide — not to fix code. - If you cannot determine whether the code is correct (e.g., you don't understand the domain), escalate with severity "medium" instead of guessing. +- The URL that \`git push\` prints (e.g. \`https://github.com/.../pull/new/...\`) is NOT a pull request — it is a convenience link for humans. Never use that as a pr_url. `; } + +function buildDirectMergeInstructions(params: { branch: string; targetBranch: string }): string { + return `1. Fetch the latest target branch: \`git fetch origin ${params.targetBranch}\` +2. Check out the target branch: \`git checkout ${params.targetBranch} && git pull origin ${params.targetBranch}\` +3. Merge the feature branch: \`git merge --no-ff ${params.branch}\` + - If there are merge conflicts, resolve them, then \`git add\` the resolved files and \`git commit\`. + - If the conflicts are too complex to resolve confidently, call \`gt_escalate\` with severity "high" instead. +4. Push the merged result: \`git push origin ${params.targetBranch}\` +5. Call \`gt_done\` with branch="${params.branch}". Do NOT pass a \`pr_url\` — the system will detect that the merge was done directly.`; +} + +function buildPRMergeInstructions(params: { branch: string; targetBranch: string }): string { + return `1. Ensure the branch is pushed to origin: \`git push origin ${params.branch}\` +2. Create a pull request using the GitHub or GitLab CLI: + - **GitHub:** \`gh pr create --base ${params.targetBranch} --head ${params.branch} --title "" --body ""\` + - **GitLab:** \`glab mr create --source-branch ${params.branch} --target-branch ${params.targetBranch} --title "" --description ""\` +3. Capture the PR/MR URL from the command output. +4. Call \`gt_done\` with branch="${params.branch}" and pr_url="". + - The pr_url MUST be the URL of the created pull request (e.g. \`https://github.com/owner/repo/pull/123\`). + - Do NOT use the URL that \`git push\` prints — that is a "create new PR" link, not an existing PR.`; +} diff --git a/cloudflare-gastown/src/types.ts b/cloudflare-gastown/src/types.ts index 5dac6b4183..d87d7b5e7d 100644 --- a/cloudflare-gastown/src/types.ts +++ b/cloudflare-gastown/src/types.ts @@ -176,6 +176,11 @@ export type PatrolResult = { orphaned_beads: string[]; }; +// -- Merge Strategy -- + +export const MergeStrategy = z.enum(['direct', 'pr']); +export type MergeStrategy = z.infer; + // -- Town Configuration -- export const TownConfigSchema = z.object({ @@ -202,9 +207,19 @@ export const TownConfigSchema = z.object({ /** Default LLM model for new agent sessions */ default_model: z.string().optional(), + /** Lightweight model for title generation, explore subagent, etc. */ + small_model: z.string().optional(), + /** Maximum concurrent polecats per rig */ max_polecats_per_rig: z.number().int().min(1).max(20).optional(), + /** + * Town-level merge strategy. Rigs inherit this when they don't set their own. + * - 'direct': Refinery pushes directly to main (no PR) + * - 'pr': Refinery creates a GitHub PR / GitLab MR for human review + */ + merge_strategy: MergeStrategy.default('direct'), + /** Refinery configuration */ refinery: z .object({ @@ -230,8 +245,43 @@ export const TownConfigSchema = z.object({ export type TownConfig = z.infer; -/** Partial update schema — all fields optional for merge updates */ -export const TownConfigUpdateSchema = TownConfigSchema.partial(); +/** + * Partial update schema — all fields optional, NO defaults. + * TownConfigSchema.partial() can't be used here because Zod still fires + * .default() during parsing, injecting phantom values (e.g. merge_strategy: + * 'direct') that overwrite existing config on partial updates. + */ +export const TownConfigUpdateSchema = z.object({ + env_vars: z.record(z.string(), z.string()).optional(), + git_auth: z + .object({ + github_token: z.string().optional(), + gitlab_token: z.string().optional(), + gitlab_instance_url: z.string().optional(), + platform_integration_id: z.string().optional(), + }) + .optional(), + owner_user_id: z.string().optional(), + kilocode_token: z.string().optional(), + default_model: z.string().optional(), + small_model: z.string().optional(), + max_polecats_per_rig: z.number().int().min(1).max(20).optional(), + merge_strategy: MergeStrategy.optional(), + refinery: z + .object({ + gates: z.array(z.string()).optional(), + auto_merge: z.boolean().optional(), + require_clean_merge: z.boolean().optional(), + }) + .optional(), + alarm_interval_active: z.number().int().min(5).max(600).optional(), + alarm_interval_idle: z.number().int().min(30).max(3600).optional(), + container: z + .object({ + sleep_after_minutes: z.number().int().min(5).max(120).optional(), + }) + .optional(), +}); export type TownConfigUpdate = z.infer; /** Agent-level config overrides (merged on top of town config) */ diff --git a/cloudflare-gastown/src/util/platform-pr.util.ts b/cloudflare-gastown/src/util/platform-pr.util.ts new file mode 100644 index 0000000000..6aef0fa359 --- /dev/null +++ b/cloudflare-gastown/src/util/platform-pr.util.ts @@ -0,0 +1,295 @@ +/** + * Platform PR/MR creation utilities. + * + * Creates GitHub Pull Requests or GitLab Merge Requests via their REST APIs. + * Used by the deterministic merge path when merge_strategy is 'pr'. + */ + +import { z } from 'zod'; + +// -- Git URL parsing -- + +export type RepoCoordinates = { + platform: 'github' | 'gitlab'; + owner: string; + repo: string; +}; + +/** + * Parse the hostname from a URL string, returning null on failure. + */ +function hostnameOf(urlStr: string): string | null { + try { + return new URL(urlStr).hostname; + } catch { + return null; + } +} + +/** + * Check whether a host is a known GitLab host (gitlab.com or matches + * the configured instance URL by exact hostname comparison). + */ +function isGitLabHost(host: string, gitlabInstanceUrl?: string): boolean { + if (host === 'gitlab.com') return true; + if (gitlabInstanceUrl && hostnameOf(gitlabInstanceUrl) === host) return true; + return false; +} + +/** + * Extract owner/repo from a git URL. + * Supports https and git@ formats: + * https://github.com/org/repo.git + * git@github.com:org/repo.git + * https://gitlab.example.com/org/repo.git + * https://gitlab.com/group/subgroup/project.git (GitLab subgroups) + */ +export function parseGitUrl(gitUrl: string, gitlabInstanceUrl?: string): RepoCoordinates | null { + // Normalize: strip trailing .git and embedded credentials (e.g. https://token@github.com/...) + const url = gitUrl.replace(/\.git$/, '').replace(/\/\/[^@]+@/, '//'); + + // HTTPS format: https://host/path... + const httpsMatch = url.match(/^https?:\/\/([^/]+)\/(.+)/); + if (httpsMatch) { + const host = httpsMatch[1]; + const fullPath = httpsMatch[2]; + + if (host === 'github.com') { + // GitHub: always owner/repo (two segments) + const parts = fullPath.split('/'); + if (parts.length >= 2) { + return { platform: 'github', owner: parts[0], repo: parts[1] }; + } + return null; + } + + if (isGitLabHost(host, gitlabInstanceUrl)) { + // GitLab: supports subgroups — owner is everything except the last + // segment, repo is the last segment. + const lastSlash = fullPath.lastIndexOf('/'); + if (lastSlash > 0) { + return { + platform: 'gitlab', + owner: fullPath.slice(0, lastSlash), + repo: fullPath.slice(lastSlash + 1), + }; + } + return null; + } + + return null; + } + + // SSH format: git@host:path + const sshMatch = url.match(/^git@([^:]+):(.+)/); + if (sshMatch) { + const host = sshMatch[1]; + const fullPath = sshMatch[2]; + + if (host === 'github.com') { + const parts = fullPath.split('/'); + if (parts.length >= 2) { + return { platform: 'github', owner: parts[0], repo: parts[1] }; + } + return null; + } + + if (isGitLabHost(host, gitlabInstanceUrl)) { + const lastSlash = fullPath.lastIndexOf('/'); + if (lastSlash > 0) { + return { + platform: 'gitlab', + owner: fullPath.slice(0, lastSlash), + repo: fullPath.slice(lastSlash + 1), + }; + } + return null; + } + + return null; + } + + return null; +} + +// -- PR body template -- + +export type QualityGateResult = { + name: string; + passed: boolean; + duration_seconds?: number; +}; + +export function buildPRBody(params: { + sourceBeadId: string; + beadTitle: string; + polecatName: string; + model: string; + convoyId?: string; + dashboardBaseUrl?: string; + gateResults: QualityGateResult[]; + diffStat?: string; +}): string { + const dashboardUrl = params.dashboardBaseUrl ?? ''; + const beadLink = dashboardUrl + ? `[${params.sourceBeadId.slice(0, 8)}](${dashboardUrl})` + : params.sourceBeadId.slice(0, 8); + + const convoyLine = params.convoyId ? `**Convoy**: ${params.convoyId.slice(0, 8)}\n` : ''; + + const gateRows = + params.gateResults.length > 0 + ? params.gateResults + .map(g => { + const status = g.passed ? 'Passed' : 'Failed'; + const duration = g.duration_seconds !== undefined ? `${g.duration_seconds}s` : '-'; + return `| ${g.name} | ${status} | ${duration} |`; + }) + .join('\n') + : '| (no gates configured) | - | - |'; + + const diffSection = params.diffStat + ? `\n### Changes\n\n\`\`\`\n${params.diffStat}\n\`\`\`\n` + : ''; + + return `## Gastown Agent Work + +**Source**: ${beadLink} — ${params.beadTitle} +**Agent**: ${params.polecatName} (${params.model}) +${convoyLine} +### Quality Gates + +| Gate | Status | Duration | +|------|--------|----------| +${gateRows} +${diffSection} +--- + +*Created by Gastown Refinery.*`; +} + +// -- PR/MR status polling schemas -- + +/** Schema for GitHub PR status responses (used by checkPRStatus). */ +export const GitHubPRStatusSchema = z.object({ + state: z.string(), + merged: z.boolean().optional(), +}); + +/** Schema for GitLab MR status responses (used by checkPRStatus). */ +export const GitLabMRStatusSchema = z.object({ + state: z.string(), +}); + +// -- GitHub PR creation -- + +const GitHubPRResponse = z.object({ + html_url: z.string(), + number: z.number(), + state: z.string(), +}); + +export async function createGitHubPR(params: { + owner: string; + repo: string; + token: string; + title: string; + body: string; + head: string; + base: string; + labels?: string[]; +}): Promise<{ pr_url: string; pr_number: number }> { + const response = await fetch( + `https://api.github.com/repos/${params.owner}/${params.repo}/pulls`, + { + method: 'POST', + headers: { + Authorization: `token ${params.token}`, + Accept: 'application/vnd.github.v3+json', + 'Content-Type': 'application/json', + 'User-Agent': 'Gastown-Refinery/1.0', + }, + body: JSON.stringify({ + title: params.title, + body: params.body, + head: params.head, + base: params.base, + }), + } + ); + + if (!response.ok) { + const text = await response.text().catch(() => '(unreadable)'); + throw new Error(`GitHub PR creation failed (${response.status}): ${text.slice(0, 500)}`); + } + + const data: unknown = await response.json(); + const parsed = GitHubPRResponse.parse(data); + + // Add labels if requested (separate API call, best-effort) + if (params.labels && params.labels.length > 0) { + await fetch( + `https://api.github.com/repos/${params.owner}/${params.repo}/issues/${parsed.number}/labels`, + { + method: 'POST', + headers: { + Authorization: `token ${params.token}`, + Accept: 'application/vnd.github.v3+json', + 'Content-Type': 'application/json', + 'User-Agent': 'Gastown-Refinery/1.0', + }, + body: JSON.stringify({ labels: params.labels }), + } + ).catch(() => { + // Best-effort label application + }); + } + + return { pr_url: parsed.html_url, pr_number: parsed.number }; +} + +// -- GitLab MR creation -- + +const GitLabMRResponse = z.object({ + web_url: z.string(), + iid: z.number(), + state: z.string(), +}); + +export async function createGitLabMR(params: { + instanceUrl: string; + projectPath: string; + token: string; + title: string; + description: string; + source_branch: string; + target_branch: string; + labels?: string[]; +}): Promise<{ mr_url: string; mr_iid: number }> { + const encodedPath = encodeURIComponent(params.projectPath); + const baseUrl = params.instanceUrl.replace(/\/$/, ''); + + const response = await fetch(`${baseUrl}/api/v4/projects/${encodedPath}/merge_requests`, { + method: 'POST', + headers: { + 'PRIVATE-TOKEN': params.token, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + title: params.title, + description: params.description, + source_branch: params.source_branch, + target_branch: params.target_branch, + labels: params.labels?.join(','), + }), + }); + + if (!response.ok) { + const text = await response.text().catch(() => '(unreadable)'); + throw new Error(`GitLab MR creation failed (${response.status}): ${text.slice(0, 500)}`); + } + + const data: unknown = await response.json(); + const parsed = GitLabMRResponse.parse(data); + return { mr_url: parsed.web_url, mr_iid: parsed.iid }; +} diff --git a/cloudflare-gastown/test/unit/merge-strategy.test.ts b/cloudflare-gastown/test/unit/merge-strategy.test.ts new file mode 100644 index 0000000000..55a49936e8 --- /dev/null +++ b/cloudflare-gastown/test/unit/merge-strategy.test.ts @@ -0,0 +1,219 @@ +import { describe, it, expect } from 'vitest'; +import { TownConfigSchema, MergeStrategy } from '../../src/types'; +import { resolveMergeStrategy } from '../../src/dos/town/config'; +import { parseGitUrl, buildPRBody, type QualityGateResult } from '../../src/util/platform-pr.util'; + +describe('merge strategy', () => { + describe('TownConfigSchema merge_strategy field', () => { + it('defaults to "direct" when not specified', () => { + const config = TownConfigSchema.parse({}); + expect(config.merge_strategy).toBe('direct'); + }); + + it('accepts "direct" as a valid value', () => { + const config = TownConfigSchema.parse({ merge_strategy: 'direct' }); + expect(config.merge_strategy).toBe('direct'); + }); + + it('accepts "pr" as a valid value', () => { + const config = TownConfigSchema.parse({ merge_strategy: 'pr' }); + expect(config.merge_strategy).toBe('pr'); + }); + + it('rejects invalid merge_strategy values', () => { + expect(() => TownConfigSchema.parse({ merge_strategy: 'rebase' })).toThrow(); + }); + + it('preserves merge_strategy through TownConfigSchema.partial()', () => { + const partial = TownConfigSchema.partial().parse({ merge_strategy: 'pr' }); + expect(partial.merge_strategy).toBe('pr'); + }); + }); + + describe('MergeStrategy enum', () => { + it('parses "direct"', () => { + expect(MergeStrategy.parse('direct')).toBe('direct'); + }); + + it('parses "pr"', () => { + expect(MergeStrategy.parse('pr')).toBe('pr'); + }); + + it('rejects invalid values', () => { + expect(() => MergeStrategy.parse('squash')).toThrow(); + }); + }); + + describe('resolveMergeStrategy', () => { + const townConfig = (strategy: 'direct' | 'pr') => + TownConfigSchema.parse({ merge_strategy: strategy }); + + it('returns town config strategy when rig override is undefined', () => { + expect(resolveMergeStrategy(townConfig('direct'), undefined)).toBe('direct'); + expect(resolveMergeStrategy(townConfig('pr'), undefined)).toBe('pr'); + }); + + it('returns rig override when set', () => { + expect(resolveMergeStrategy(townConfig('direct'), 'pr')).toBe('pr'); + expect(resolveMergeStrategy(townConfig('pr'), 'direct')).toBe('direct'); + }); + + it('rig override takes precedence over town default', () => { + const config = townConfig('direct'); + expect(resolveMergeStrategy(config, 'pr')).toBe('pr'); + }); + }); +}); + +describe('parseGitUrl', () => { + it('parses GitHub HTTPS URLs', () => { + const result = parseGitUrl('https://github.com/org/repo.git'); + expect(result).toEqual({ platform: 'github', owner: 'org', repo: 'repo' }); + }); + + it('parses GitHub HTTPS URLs without .git suffix', () => { + const result = parseGitUrl('https://github.com/org/repo'); + expect(result).toEqual({ platform: 'github', owner: 'org', repo: 'repo' }); + }); + + it('parses GitHub SSH URLs', () => { + const result = parseGitUrl('git@github.com:org/repo.git'); + expect(result).toEqual({ platform: 'github', owner: 'org', repo: 'repo' }); + }); + + it('parses GitLab.com HTTPS URLs', () => { + const result = parseGitUrl('https://gitlab.com/group/project.git'); + expect(result).toEqual({ platform: 'gitlab', owner: 'group', repo: 'project' }); + }); + + it('parses self-hosted GitLab HTTPS URLs when instance URL is provided', () => { + const result = parseGitUrl( + 'https://gitlab.example.com/team/repo.git', + 'https://gitlab.example.com' + ); + expect(result).toEqual({ platform: 'gitlab', owner: 'team', repo: 'repo' }); + }); + + it('parses SSH URLs from gitlab.com', () => { + const result = parseGitUrl('git@gitlab.com:team/repo.git'); + expect(result).toEqual({ platform: 'gitlab', owner: 'team', repo: 'repo' }); + }); + + it('parses SSH URLs from configured gitlab instance', () => { + const result = parseGitUrl( + 'git@gitlab.example.com:team/repo.git', + 'https://gitlab.example.com' + ); + expect(result).toEqual({ platform: 'gitlab', owner: 'team', repo: 'repo' }); + }); + + it('returns null for SSH URLs from unknown non-GitHub hosts without gitlab instance', () => { + const result = parseGitUrl('git@bitbucket.org:team/repo.git'); + expect(result).toBeNull(); + }); + + it('returns null for unrecognizable HTTPS URLs without gitlab instance', () => { + const result = parseGitUrl('https://example.com/team/repo.git'); + expect(result).toBeNull(); + }); + + it('handles GitLab subgroups in HTTPS URLs', () => { + const result = parseGitUrl('https://gitlab.com/group/subgroup/project.git'); + expect(result).toEqual({ platform: 'gitlab', owner: 'group/subgroup', repo: 'project' }); + }); + + it('handles GitLab subgroups in SSH URLs', () => { + const result = parseGitUrl('git@gitlab.com:group/subgroup/deep/project.git'); + expect(result).toEqual({ + platform: 'gitlab', + owner: 'group/subgroup/deep', + repo: 'project', + }); + }); + + it('strips embedded credentials from HTTPS URLs', () => { + const result = parseGitUrl('https://x-access-token:ghp_abc123@github.com/org/repo.git'); + expect(result).toEqual({ platform: 'github', owner: 'org', repo: 'repo' }); + }); + + it('strips embedded credentials from GitLab HTTPS URLs', () => { + const result = parseGitUrl('https://oauth2:token@gitlab.com/group/project.git'); + expect(result).toEqual({ platform: 'gitlab', owner: 'group', repo: 'project' }); + }); + + it('does not false-positive on substring hostname match', () => { + // gitlabInstanceUrl is gitlab.example.com but host is just example.com + const result = parseGitUrl('https://example.com/team/repo.git', 'https://gitlab.example.com'); + expect(result).toBeNull(); + }); + + it('handles trailing .git in all formats', () => { + expect(parseGitUrl('https://github.com/a/b.git')?.repo).toBe('b'); + expect(parseGitUrl('https://github.com/a/b')?.repo).toBe('b'); + expect(parseGitUrl('git@github.com:a/b.git')?.repo).toBe('b'); + }); +}); + +describe('buildPRBody', () => { + it('generates a Markdown PR body with gate results', () => { + const gates: QualityGateResult[] = [ + { name: 'Tests', passed: true, duration_seconds: 42 }, + { name: 'Typecheck', passed: true, duration_seconds: 8 }, + { name: 'Lint', passed: false, duration_seconds: 3 }, + ]; + + const body = buildPRBody({ + sourceBeadId: 'bead-uuid-1234-5678', + beadTitle: 'Add dark mode toggle', + polecatName: 'Finnick', + model: 'anthropic/claude-sonnet-4.6', + gateResults: gates, + }); + + expect(body).toContain('## Gastown Agent Work'); + expect(body).toContain('bead-uui'); + expect(body).toContain('Add dark mode toggle'); + expect(body).toContain('Finnick'); + expect(body).toContain('anthropic/claude-sonnet-4.6'); + expect(body).toContain('| Tests | Passed | 42s |'); + expect(body).toContain('| Typecheck | Passed | 8s |'); + expect(body).toContain('| Lint | Failed | 3s |'); + }); + + it('shows "no gates configured" when no gate results', () => { + const body = buildPRBody({ + sourceBeadId: 'bead-id', + beadTitle: 'Fix bug', + polecatName: 'Nutkin', + model: 'gpt-4', + gateResults: [], + }); + expect(body).toContain('(no gates configured)'); + }); + + it('includes convoy line when convoyId is provided', () => { + const body = buildPRBody({ + sourceBeadId: 'bead-id', + beadTitle: 'Task', + polecatName: 'Patch', + model: 'model-1', + convoyId: 'convoy-uuid-1234', + gateResults: [], + }); + expect(body).toContain('**Convoy**'); + expect(body).toContain('convoy-u'); + }); + + it('includes diff stat when provided', () => { + const body = buildPRBody({ + sourceBeadId: 'bead-id', + beadTitle: 'Task', + polecatName: 'Patch', + model: 'model-1', + gateResults: [], + diffStat: ' 3 files changed, 42 insertions(+), 5 deletions(-)', + }); + expect(body).toContain('### Changes'); + expect(body).toContain('3 files changed'); + }); +}); diff --git a/cloudflare-gastown/worker-configuration.d.ts b/cloudflare-gastown/worker-configuration.d.ts index 0feb61a719..e5d0b69246 100644 --- a/cloudflare-gastown/worker-configuration.d.ts +++ b/cloudflare-gastown/worker-configuration.d.ts @@ -1,6 +1,6 @@ /* eslint-disable */ -// Generated by Wrangler by running `wrangler types` (hash: 07009cddcdcaca5feb272eddad76a352) -// Runtime types generated with workerd@1.20260128.0 2026-01-27 nodejs_compat +// Generated by Wrangler by running `wrangler types` (hash: 92be991b49e955fa61e3c3d593df5c1a) +// Runtime types generated with workerd@1.20260302.0 2026-01-27 nodejs_compat declare namespace Cloudflare { interface GlobalProps { mainModule: typeof import("./src/gastown.worker"); @@ -10,9 +10,9 @@ declare namespace Cloudflare { GASTOWN_JWT_SECRET: SecretsStoreSecret; ENVIRONMENT: "development"; CF_ACCESS_TEAM: "engineering-e11"; - CF_ACCESS_AUD: "f30e3fd893df52fa3ffc50fbdb5ee6a4f111625ae92234233429684e1429d809"; - KILO_API_URL: "http://host.docker.internal:3000"; - GASTOWN_API_URL: "http://host.docker.internal:8787"; + CF_ACCESS_AUD: "7f6eda4c0714f6ea2afb74a3f055db65659b67571a913eab42468636a9b8c8be"; + KILO_API_URL: "http://192.168.65.254:3000"; + GASTOWN_API_URL: "http://192.168.65.254:8787"; GASTOWN_USER: DurableObjectNamespace; AGENT_IDENTITY: DurableObjectNamespace; TOWN: DurableObjectNamespace; @@ -23,9 +23,9 @@ declare namespace Cloudflare { GASTOWN_JWT_SECRET: SecretsStoreSecret; ENVIRONMENT: "development" | "production"; CF_ACCESS_TEAM: "engineering-e11"; - CF_ACCESS_AUD: "f30e3fd893df52fa3ffc50fbdb5ee6a4f111625ae92234233429684e1429d809"; - KILO_API_URL: "http://host.docker.internal:3000" | "https://api.kilo.ai"; - GASTOWN_API_URL: "http://host.docker.internal:8787" | "https://gastown.kiloapps.io"; + CF_ACCESS_AUD: "7f6eda4c0714f6ea2afb74a3f055db65659b67571a913eab42468636a9b8c8be"; + KILO_API_URL: "http://192.168.65.254:3000" | "https://api.kilo.ai"; + GASTOWN_API_URL: "http://192.168.65.254:8787" | "https://gastown.kiloapps.io"; GASTOWN_USER: DurableObjectNamespace; AGENT_IDENTITY: DurableObjectNamespace; TOWN: DurableObjectNamespace; @@ -65,63 +65,63 @@ declare var onmessage: never; * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException) */ declare class DOMException extends Error { - constructor(message?: string, name?: string); - /** - * The **`message`** read-only property of the a message or description associated with the given error name. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) - */ - readonly message: string; - /** - * The **`name`** read-only property of the one of the strings associated with an error name. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) - */ - readonly name: string; - /** - * The **`code`** read-only property of the DOMException interface returns one of the legacy error code constants, or `0` if none match. - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) - */ - readonly code: number; - static readonly INDEX_SIZE_ERR: number; - static readonly DOMSTRING_SIZE_ERR: number; - static readonly HIERARCHY_REQUEST_ERR: number; - static readonly WRONG_DOCUMENT_ERR: number; - static readonly INVALID_CHARACTER_ERR: number; - static readonly NO_DATA_ALLOWED_ERR: number; - static readonly NO_MODIFICATION_ALLOWED_ERR: number; - static readonly NOT_FOUND_ERR: number; - static readonly NOT_SUPPORTED_ERR: number; - static readonly INUSE_ATTRIBUTE_ERR: number; - static readonly INVALID_STATE_ERR: number; - static readonly SYNTAX_ERR: number; - static readonly INVALID_MODIFICATION_ERR: number; - static readonly NAMESPACE_ERR: number; - static readonly INVALID_ACCESS_ERR: number; - static readonly VALIDATION_ERR: number; - static readonly TYPE_MISMATCH_ERR: number; - static readonly SECURITY_ERR: number; - static readonly NETWORK_ERR: number; - static readonly ABORT_ERR: number; - static readonly URL_MISMATCH_ERR: number; - static readonly QUOTA_EXCEEDED_ERR: number; - static readonly TIMEOUT_ERR: number; - static readonly INVALID_NODE_TYPE_ERR: number; - static readonly DATA_CLONE_ERR: number; - get stack(): any; - set stack(value: any); + constructor(message?: string, name?: string); + /** + * The **`message`** read-only property of the a message or description associated with the given error name. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) + */ + readonly message: string; + /** + * The **`name`** read-only property of the one of the strings associated with an error name. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) + */ + readonly name: string; + /** + * The **`code`** read-only property of the DOMException interface returns one of the legacy error code constants, or `0` if none match. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) + */ + readonly code: number; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; + get stack(): any; + set stack(value: any); } type WorkerGlobalScopeEventMap = { - fetch: FetchEvent; - scheduled: ScheduledEvent; - queue: QueueEvent; - unhandledrejection: PromiseRejectionEvent; - rejectionhandled: PromiseRejectionEvent; + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; }; declare abstract class WorkerGlobalScope extends EventTarget { - EventTarget: typeof EventTarget; + EventTarget: typeof EventTarget; } /* The **`console`** object provides access to the debugging console (e.g., the Web console in Firefox). * * The **`console`** object provides access to the debugging console (e.g., the Web console in Firefox). @@ -129,197 +129,186 @@ declare abstract class WorkerGlobalScope extends EventTarget; - type Imports = Record; - type ExportValue = Function | Global | Memory | Table; - type Exports = Record; - class Instance { - constructor(module: Module, imports?: Imports); - readonly exports: Exports; - } - interface MemoryDescriptor { - initial: number; - maximum?: number; - shared?: boolean; - } - class Memory { - constructor(descriptor: MemoryDescriptor); - readonly buffer: ArrayBuffer; - grow(delta: number): number; - } - type ImportExportKind = 'function' | 'global' | 'memory' | 'table'; - interface ModuleExportDescriptor { - kind: ImportExportKind; - name: string; - } - interface ModuleImportDescriptor { - kind: ImportExportKind; - module: string; - name: string; - } - abstract class Module { - static customSections(module: Module, sectionName: string): ArrayBuffer[]; - static exports(module: Module): ModuleExportDescriptor[]; - static imports(module: Module): ModuleImportDescriptor[]; - } - type TableKind = 'anyfunc' | 'externref'; - interface TableDescriptor { - element: TableKind; - initial: number; - maximum?: number; - } - class Table { - constructor(descriptor: TableDescriptor, value?: any); - readonly length: number; - get(index: number): any; - grow(delta: number, value?: any): number; - set(index: number, value?: any): void; - } - function instantiate(module: Module, imports?: Imports): Promise; - function validate(bytes: BufferSource): boolean; + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = "anyfunc" | "externref" | "f32" | "f64" | "i32" | "i64" | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record; + type Imports = Record; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise; + function validate(bytes: BufferSource): boolean; } /** * The **`ServiceWorkerGlobalScope`** interface of the Service Worker API represents the global execution context of a service worker. @@ -328,112 +317,94 @@ declare namespace WebAssembly { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope) */ interface ServiceWorkerGlobalScope extends WorkerGlobalScope { - DOMException: typeof DOMException; - WorkerGlobalScope: typeof WorkerGlobalScope; - btoa(data: string): string; - atob(data: string): string; - setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; - setTimeout( - callback: (...args: Args) => void, - msDelay?: number, - ...args: Args - ): number; - clearTimeout(timeoutId: number | null): void; - setInterval(callback: (...args: any[]) => void, msDelay?: number): number; - setInterval( - callback: (...args: Args) => void, - msDelay?: number, - ...args: Args - ): number; - clearInterval(timeoutId: number | null): void; - queueMicrotask(task: Function): void; - structuredClone(value: T, options?: StructuredSerializeOptions): T; - reportError(error: any): void; - fetch(input: RequestInfo | URL, init?: RequestInit): Promise; - self: ServiceWorkerGlobalScope; - crypto: Crypto; - caches: CacheStorage; - scheduler: Scheduler; - performance: Performance; - Cloudflare: Cloudflare; - readonly origin: string; - Event: typeof Event; - ExtendableEvent: typeof ExtendableEvent; - CustomEvent: typeof CustomEvent; - PromiseRejectionEvent: typeof PromiseRejectionEvent; - FetchEvent: typeof FetchEvent; - TailEvent: typeof TailEvent; - TraceEvent: typeof TailEvent; - ScheduledEvent: typeof ScheduledEvent; - MessageEvent: typeof MessageEvent; - CloseEvent: typeof CloseEvent; - ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; - ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; - ReadableStream: typeof ReadableStream; - WritableStream: typeof WritableStream; - WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; - TransformStream: typeof TransformStream; - ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; - CountQueuingStrategy: typeof CountQueuingStrategy; - ErrorEvent: typeof ErrorEvent; - MessageChannel: typeof MessageChannel; - MessagePort: typeof MessagePort; - EventSource: typeof EventSource; - ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest; - ReadableStreamDefaultController: typeof ReadableStreamDefaultController; - ReadableByteStreamController: typeof ReadableByteStreamController; - WritableStreamDefaultController: typeof WritableStreamDefaultController; - TransformStreamDefaultController: typeof TransformStreamDefaultController; - CompressionStream: typeof CompressionStream; - DecompressionStream: typeof DecompressionStream; - TextEncoderStream: typeof TextEncoderStream; - TextDecoderStream: typeof TextDecoderStream; - Headers: typeof Headers; - Body: typeof Body; - Request: typeof Request; - Response: typeof Response; - WebSocket: typeof WebSocket; - WebSocketPair: typeof WebSocketPair; - WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; - AbortController: typeof AbortController; - AbortSignal: typeof AbortSignal; - TextDecoder: typeof TextDecoder; - TextEncoder: typeof TextEncoder; - navigator: Navigator; - Navigator: typeof Navigator; - URL: typeof URL; - URLSearchParams: typeof URLSearchParams; - URLPattern: typeof URLPattern; - Blob: typeof Blob; - File: typeof File; - FormData: typeof FormData; - Crypto: typeof Crypto; - SubtleCrypto: typeof SubtleCrypto; - CryptoKey: typeof CryptoKey; - CacheStorage: typeof CacheStorage; - Cache: typeof Cache; - FixedLengthStream: typeof FixedLengthStream; - IdentityTransformStream: typeof IdentityTransformStream; - HTMLRewriter: typeof HTMLRewriter; -} -declare function addEventListener( - type: Type, - handler: EventListenerOrEventListenerObject, - options?: EventTargetAddEventListenerOptions | boolean -): void; -declare function removeEventListener( - type: Type, - handler: EventListenerOrEventListenerObject, - options?: EventTargetEventListenerOptions | boolean -): void; + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone(value: T, options?: StructuredSerializeOptions): T; + reportError(error: any): void; + fetch(input: RequestInfo | URL, init?: RequestInit): Promise; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + Cloudflare: Cloudflare; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + CustomEvent: typeof CustomEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + ErrorEvent: typeof ErrorEvent; + MessageChannel: typeof MessageChannel; + MessagePort: typeof MessagePort; + EventSource: typeof EventSource; + ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest; + ReadableStreamDefaultController: typeof ReadableStreamDefaultController; + ReadableByteStreamController: typeof ReadableByteStreamController; + WritableStreamDefaultController: typeof WritableStreamDefaultController; + TransformStreamDefaultController: typeof TransformStreamDefaultController; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + navigator: Navigator; + Navigator: typeof Navigator; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; +} +declare function addEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetAddEventListenerOptions | boolean): void; +declare function removeEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetEventListenerOptions | boolean): void; /** * The **`dispatchEvent()`** method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) */ -declare function dispatchEvent( - event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap] -): boolean; +declare function dispatchEvent(event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap]): boolean; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/btoa) */ declare function btoa(data: string): string; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/atob) */ @@ -441,21 +412,13 @@ declare function atob(data: string): string; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout) */ declare function setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout) */ -declare function setTimeout( - callback: (...args: Args) => void, - msDelay?: number, - ...args: Args -): number; +declare function setTimeout(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearTimeout) */ declare function clearTimeout(timeoutId: number | null): void; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval) */ declare function setInterval(callback: (...args: any[]) => void, msDelay?: number): number; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval) */ -declare function setInterval( - callback: (...args: Args) => void, - msDelay?: number, - ...args: Args -): number; +declare function setInterval(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearInterval) */ declare function clearInterval(timeoutId: number | null): void; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/queueMicrotask) */ @@ -465,256 +428,202 @@ declare function structuredClone(value: T, options?: StructuredSerializeOptio /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/reportError) */ declare function reportError(error: any): void; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch) */ -declare function fetch( - input: RequestInfo | URL, - init?: RequestInit -): Promise; +declare function fetch(input: RequestInfo | URL, init?: RequestInit): Promise; declare const self: ServiceWorkerGlobalScope; /** - * The Web Crypto API provides a set of low-level functions for common cryptographic tasks. - * The Workers runtime implements the full surface of this API, but with some differences in - * the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms) - * compared to those implemented in most browsers. - * - * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/) - */ +* The Web Crypto API provides a set of low-level functions for common cryptographic tasks. +* The Workers runtime implements the full surface of this API, but with some differences in +* the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms) +* compared to those implemented in most browsers. +* +* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/) +*/ declare const crypto: Crypto; /** - * The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. - * - * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) - */ +* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. +* +* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) +*/ declare const caches: CacheStorage; declare const scheduler: Scheduler; /** - * 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. - * - * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/) - */ +* 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. +* +* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/) +*/ declare const performance: Performance; declare const Cloudflare: Cloudflare; declare const origin: string; declare const navigator: Navigator; -interface TestController {} +interface TestController { +} interface ExecutionContext { - waitUntil(promise: Promise): void; - passThroughOnException(): void; - readonly exports: Cloudflare.Exports; - readonly props: Props; -} -type ExportedHandlerFetchHandler = ( - request: Request>, - env: Env, - ctx: ExecutionContext -) => Response | Promise; -type ExportedHandlerTailHandler = ( - events: TraceItem[], - env: Env, - ctx: ExecutionContext -) => void | Promise; -type ExportedHandlerTraceHandler = ( - traces: TraceItem[], - env: Env, - ctx: ExecutionContext -) => void | Promise; -type ExportedHandlerTailStreamHandler = ( - event: TailStream.TailEvent, - env: Env, - ctx: ExecutionContext -) => TailStream.TailEventHandlerType | Promise; -type ExportedHandlerScheduledHandler = ( - controller: ScheduledController, - env: Env, - ctx: ExecutionContext -) => void | Promise; -type ExportedHandlerQueueHandler = ( - batch: MessageBatch, - env: Env, - ctx: ExecutionContext -) => void | Promise; -type ExportedHandlerTestHandler = ( - controller: TestController, - env: Env, - ctx: ExecutionContext -) => void | Promise; + waitUntil(promise: Promise): void; + passThroughOnException(): void; + readonly exports: Cloudflare.Exports; + readonly props: Props; +} +type ExportedHandlerFetchHandler = (request: Request>, env: Env, ctx: ExecutionContext) => Response | Promise; +type ExportedHandlerTailHandler = (events: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; +type ExportedHandlerTraceHandler = (traces: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; +type ExportedHandlerTailStreamHandler = (event: TailStream.TailEvent, env: Env, ctx: ExecutionContext) => TailStream.TailEventHandlerType | Promise; +type ExportedHandlerScheduledHandler = (controller: ScheduledController, env: Env, ctx: ExecutionContext) => void | Promise; +type ExportedHandlerQueueHandler = (batch: MessageBatch, env: Env, ctx: ExecutionContext) => void | Promise; +type ExportedHandlerTestHandler = (controller: TestController, env: Env, ctx: ExecutionContext) => void | Promise; interface ExportedHandler { - fetch?: ExportedHandlerFetchHandler; - tail?: ExportedHandlerTailHandler; - trace?: ExportedHandlerTraceHandler; - tailStream?: ExportedHandlerTailStreamHandler; - scheduled?: ExportedHandlerScheduledHandler; - test?: ExportedHandlerTestHandler; - email?: EmailExportedHandler; - queue?: ExportedHandlerQueueHandler; + fetch?: ExportedHandlerFetchHandler; + tail?: ExportedHandlerTailHandler; + trace?: ExportedHandlerTraceHandler; + tailStream?: ExportedHandlerTailStreamHandler; + scheduled?: ExportedHandlerScheduledHandler; + test?: ExportedHandlerTestHandler; + email?: EmailExportedHandler; + queue?: ExportedHandlerQueueHandler; } interface StructuredSerializeOptions { - transfer?: any[]; + transfer?: any[]; } declare abstract class Navigator { - sendBeacon(url: string, body?: BodyInit): boolean; - readonly userAgent: string; - readonly hardwareConcurrency: number; - readonly language: string; - readonly languages: string[]; + sendBeacon(url: string, body?: BodyInit): boolean; + readonly userAgent: string; + readonly hardwareConcurrency: number; + readonly language: string; + readonly languages: string[]; } interface AlarmInvocationInfo { - readonly isRetry: boolean; - readonly retryCount: number; + readonly isRetry: boolean; + readonly retryCount: number; } interface Cloudflare { - readonly compatibilityFlags: Record; + readonly compatibilityFlags: Record; } interface DurableObject { - fetch(request: Request): Response | Promise; - alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise; - webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise; - webSocketClose?( - ws: WebSocket, - code: number, - reason: string, - wasClean: boolean - ): void | Promise; - webSocketError?(ws: WebSocket, error: unknown): void | Promise; -} -type DurableObjectStub = Fetcher< - T, - 'alarm' | 'webSocketMessage' | 'webSocketClose' | 'webSocketError' -> & { - readonly id: DurableObjectId; - readonly name?: string; + fetch(request: Request): Response | Promise; + alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise; + webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise; + webSocketClose?(ws: WebSocket, code: number, reason: string, wasClean: boolean): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; +} +type DurableObjectStub = Fetcher & { + readonly id: DurableObjectId; + readonly name?: string; }; interface DurableObjectId { - toString(): string; - equals(other: DurableObjectId): boolean; - readonly name?: string; -} -declare abstract class DurableObjectNamespace< - T extends Rpc.DurableObjectBranded | undefined = undefined, -> { - newUniqueId(options?: DurableObjectNamespaceNewUniqueIdOptions): DurableObjectId; - idFromName(name: string): DurableObjectId; - idFromString(id: string): DurableObjectId; - get( - id: DurableObjectId, - options?: DurableObjectNamespaceGetDurableObjectOptions - ): DurableObjectStub; - getByName( - name: string, - options?: DurableObjectNamespaceGetDurableObjectOptions - ): DurableObjectStub; - jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; -} -type DurableObjectJurisdiction = 'eu' | 'fedramp' | 'fedramp-high'; + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +declare abstract class DurableObjectNamespace { + newUniqueId(options?: DurableObjectNamespaceNewUniqueIdOptions): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get(id: DurableObjectId, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub; + getByName(name: string, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub; + jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; +} +type DurableObjectJurisdiction = "eu" | "fedramp" | "fedramp-high"; interface DurableObjectNamespaceNewUniqueIdOptions { - jurisdiction?: DurableObjectJurisdiction; -} -type DurableObjectLocationHint = - | 'wnam' - | 'enam' - | 'sam' - | 'weur' - | 'eeur' - | 'apac' - | 'oc' - | 'afr' - | 'me'; -type DurableObjectRoutingMode = 'primary-only'; + jurisdiction?: DurableObjectJurisdiction; +} +type DurableObjectLocationHint = "wnam" | "enam" | "sam" | "weur" | "eeur" | "apac" | "oc" | "afr" | "me"; +type DurableObjectRoutingMode = "primary-only"; interface DurableObjectNamespaceGetDurableObjectOptions { - locationHint?: DurableObjectLocationHint; - routingMode?: DurableObjectRoutingMode; + locationHint?: DurableObjectLocationHint; + routingMode?: DurableObjectRoutingMode; +} +interface DurableObjectClass<_T extends Rpc.DurableObjectBranded | undefined = undefined> { } -interface DurableObjectClass<_T extends Rpc.DurableObjectBranded | undefined = undefined> {} interface DurableObjectState { - waitUntil(promise: Promise): void; - readonly exports: Cloudflare.Exports; - readonly props: Props; - readonly id: DurableObjectId; - readonly storage: DurableObjectStorage; - container?: Container; - blockConcurrencyWhile(callback: () => Promise): Promise; - acceptWebSocket(ws: WebSocket, tags?: string[]): void; - getWebSockets(tag?: string): WebSocket[]; - setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; - getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; - getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; - setHibernatableWebSocketEventTimeout(timeoutMs?: number): void; - getHibernatableWebSocketEventTimeout(): number | null; - getTags(ws: WebSocket): string[]; - abort(reason?: string): void; + waitUntil(promise: Promise): void; + readonly exports: Cloudflare.Exports; + readonly props: Props; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + container?: Container; + blockConcurrencyWhile(callback: () => Promise): Promise; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; + setHibernatableWebSocketEventTimeout(timeoutMs?: number): void; + getHibernatableWebSocketEventTimeout(): number | null; + getTags(ws: WebSocket): string[]; + abort(reason?: string): void; } interface DurableObjectTransaction { - get(key: string, options?: DurableObjectGetOptions): Promise; - get(keys: string[], options?: DurableObjectGetOptions): Promise>; - list(options?: DurableObjectListOptions): Promise>; - put(key: string, value: T, options?: DurableObjectPutOptions): Promise; - put(entries: Record, options?: DurableObjectPutOptions): Promise; - delete(key: string, options?: DurableObjectPutOptions): Promise; - delete(keys: string[], options?: DurableObjectPutOptions): Promise; - rollback(): void; - getAlarm(options?: DurableObjectGetAlarmOptions): Promise; - setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise; - deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; + get(key: string, options?: DurableObjectGetOptions): Promise; + get(keys: string[], options?: DurableObjectGetOptions): Promise>; + list(options?: DurableObjectListOptions): Promise>; + put(key: string, value: T, options?: DurableObjectPutOptions): Promise; + put(entries: Record, options?: DurableObjectPutOptions): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; } interface DurableObjectStorage { - get(key: string, options?: DurableObjectGetOptions): Promise; - get(keys: string[], options?: DurableObjectGetOptions): Promise>; - list(options?: DurableObjectListOptions): Promise>; - put(key: string, value: T, options?: DurableObjectPutOptions): Promise; - put(entries: Record, options?: DurableObjectPutOptions): Promise; - delete(key: string, options?: DurableObjectPutOptions): Promise; - delete(keys: string[], options?: DurableObjectPutOptions): Promise; - deleteAll(options?: DurableObjectPutOptions): Promise; - transaction(closure: (txn: DurableObjectTransaction) => Promise): Promise; - getAlarm(options?: DurableObjectGetAlarmOptions): Promise; - setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise; - deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; - sync(): Promise; - sql: SqlStorage; - kv: SyncKvStorage; - transactionSync(closure: () => T): T; - getCurrentBookmark(): Promise; - getBookmarkForTime(timestamp: number | Date): Promise; - onNextSessionRestoreBookmark(bookmark: string): Promise; + get(key: string, options?: DurableObjectGetOptions): Promise; + get(keys: string[], options?: DurableObjectGetOptions): Promise>; + list(options?: DurableObjectListOptions): Promise>; + put(key: string, value: T, options?: DurableObjectPutOptions): Promise; + put(entries: Record, options?: DurableObjectPutOptions): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + deleteAll(options?: DurableObjectPutOptions): Promise; + transaction(closure: (txn: DurableObjectTransaction) => Promise): Promise; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; + sync(): Promise; + sql: SqlStorage; + kv: SyncKvStorage; + transactionSync(closure: () => T): T; + getCurrentBookmark(): Promise; + getBookmarkForTime(timestamp: number | Date): Promise; + onNextSessionRestoreBookmark(bookmark: string): Promise; } interface DurableObjectListOptions { - start?: string; - startAfter?: string; - end?: string; - prefix?: string; - reverse?: boolean; - limit?: number; - allowConcurrency?: boolean; - noCache?: boolean; + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; } interface DurableObjectGetOptions { - allowConcurrency?: boolean; - noCache?: boolean; + allowConcurrency?: boolean; + noCache?: boolean; } interface DurableObjectGetAlarmOptions { - allowConcurrency?: boolean; + allowConcurrency?: boolean; } interface DurableObjectPutOptions { - allowConcurrency?: boolean; - allowUnconfirmed?: boolean; - noCache?: boolean; + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; } interface DurableObjectSetAlarmOptions { - allowConcurrency?: boolean; - allowUnconfirmed?: boolean; + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; } declare class WebSocketRequestResponsePair { - constructor(request: string, response: string); - get request(): string; - get response(): string; + constructor(request: string, response: string); + get request(): string; + get response(): string; } interface AnalyticsEngineDataset { - writeDataPoint(event?: AnalyticsEngineDataPoint): void; + writeDataPoint(event?: AnalyticsEngineDataPoint): void; } interface AnalyticsEngineDataPoint { - indexes?: ((ArrayBuffer | string) | null)[]; - doubles?: number[]; - blobs?: ((ArrayBuffer | string) | null)[]; + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; } /** * The **`Event`** interface represents an event which takes place on an `EventTarget`. @@ -722,181 +631,171 @@ interface AnalyticsEngineDataPoint { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event) */ declare class Event { - constructor(type: string, init?: EventInit); - /** - * The **`type`** read-only property of the Event interface returns a string containing the event's type. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) - */ - get type(): string; - /** - * The **`eventPhase`** read-only property of the being evaluated. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) - */ - get eventPhase(): number; - /** - * The read-only **`composed`** property of the or not the event will propagate across the shadow DOM boundary into the standard DOM. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed) - */ - get composed(): boolean; - /** - * The **`bubbles`** read-only property of the Event interface indicates whether the event bubbles up through the DOM tree or not. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles) - */ - get bubbles(): boolean; - /** - * The **`cancelable`** read-only property of the Event interface indicates whether the event can be canceled, and therefore prevented as if the event never happened. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable) - */ - get cancelable(): boolean; - /** - * The **`defaultPrevented`** read-only property of the Event interface returns a boolean value indicating whether or not the call to Event.preventDefault() canceled the event. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented) - */ - get defaultPrevented(): boolean; - /** - * The Event property **`returnValue`** indicates whether the default action for this event has been prevented or not. - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue) - */ - get returnValue(): boolean; - /** - * The **`currentTarget`** read-only property of the Event interface identifies the element to which the event handler has been attached. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget) - */ - get currentTarget(): EventTarget | undefined; - /** - * The read-only **`target`** property of the dispatched. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/target) - */ - get target(): EventTarget | undefined; - /** - * The deprecated **`Event.srcElement`** is an alias for the Event.target property. - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement) - */ - get srcElement(): EventTarget | undefined; - /** - * The **`timeStamp`** read-only property of the Event interface returns the time (in milliseconds) at which the event was created. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp) - */ - get timeStamp(): number; - /** - * The **`isTrusted`** read-only property of the when the event was generated by the user agent (including via user actions and programmatic methods such as HTMLElement.focus()), and `false` when the event was dispatched via The only exception is the `click` event, which initializes the `isTrusted` property to `false` in user agents. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted) - */ - get isTrusted(): boolean; - /** - * The **`cancelBubble`** property of the Event interface is deprecated. - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) - */ - get cancelBubble(): boolean; - /** - * The **`cancelBubble`** property of the Event interface is deprecated. - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) - */ - set cancelBubble(value: boolean); - /** - * The **`stopImmediatePropagation()`** method of the If several listeners are attached to the same element for the same event type, they are called in the order in which they were added. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation) - */ - stopImmediatePropagation(): void; - /** - * The **`preventDefault()`** method of the Event interface tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) - */ - preventDefault(): void; - /** - * The **`stopPropagation()`** method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) - */ - stopPropagation(): void; - /** - * The **`composedPath()`** method of the Event interface returns the event's path which is an array of the objects on which listeners will be invoked. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath) - */ - composedPath(): EventTarget[]; - static readonly NONE: number; - static readonly CAPTURING_PHASE: number; - static readonly AT_TARGET: number; - static readonly BUBBLING_PHASE: number; + constructor(type: string, init?: EventInit); + /** + * The **`type`** read-only property of the Event interface returns a string containing the event's type. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) + */ + get type(): string; + /** + * The **`eventPhase`** read-only property of the being evaluated. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) + */ + get eventPhase(): number; + /** + * The read-only **`composed`** property of the or not the event will propagate across the shadow DOM boundary into the standard DOM. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed) + */ + get composed(): boolean; + /** + * The **`bubbles`** read-only property of the Event interface indicates whether the event bubbles up through the DOM tree or not. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles) + */ + get bubbles(): boolean; + /** + * The **`cancelable`** read-only property of the Event interface indicates whether the event can be canceled, and therefore prevented as if the event never happened. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable) + */ + get cancelable(): boolean; + /** + * The **`defaultPrevented`** read-only property of the Event interface returns a boolean value indicating whether or not the call to Event.preventDefault() canceled the event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented) + */ + get defaultPrevented(): boolean; + /** + * The Event property **`returnValue`** indicates whether the default action for this event has been prevented or not. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue) + */ + get returnValue(): boolean; + /** + * The **`currentTarget`** read-only property of the Event interface identifies the element to which the event handler has been attached. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget) + */ + get currentTarget(): EventTarget | undefined; + /** + * The read-only **`target`** property of the dispatched. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/target) + */ + get target(): EventTarget | undefined; + /** + * The deprecated **`Event.srcElement`** is an alias for the Event.target property. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement) + */ + get srcElement(): EventTarget | undefined; + /** + * The **`timeStamp`** read-only property of the Event interface returns the time (in milliseconds) at which the event was created. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp) + */ + get timeStamp(): number; + /** + * The **`isTrusted`** read-only property of the when the event was generated by the user agent (including via user actions and programmatic methods such as HTMLElement.focus()), and `false` when the event was dispatched via The only exception is the `click` event, which initializes the `isTrusted` property to `false` in user agents. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted) + */ + get isTrusted(): boolean; + /** + * The **`cancelBubble`** property of the Event interface is deprecated. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + get cancelBubble(): boolean; + /** + * The **`cancelBubble`** property of the Event interface is deprecated. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + set cancelBubble(value: boolean); + /** + * The **`stopImmediatePropagation()`** method of the If several listeners are attached to the same element for the same event type, they are called in the order in which they were added. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation) + */ + stopImmediatePropagation(): void; + /** + * The **`preventDefault()`** method of the Event interface tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) + */ + preventDefault(): void; + /** + * The **`stopPropagation()`** method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) + */ + stopPropagation(): void; + /** + * The **`composedPath()`** method of the Event interface returns the event's path which is an array of the objects on which listeners will be invoked. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath) + */ + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; } interface EventInit { - bubbles?: boolean; - cancelable?: boolean; - composed?: boolean; + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; } type EventListener = (event: EventType) => void; interface EventListenerObject { - handleEvent(event: EventType): void; + handleEvent(event: EventType): void; } -type EventListenerOrEventListenerObject = - | EventListener - | EventListenerObject; +type EventListenerOrEventListenerObject = EventListener | EventListenerObject; /** * The **`EventTarget`** interface is implemented by objects that can receive events and may have listeners for them. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget) */ declare class EventTarget = Record> { - constructor(); - /** - * The **`addEventListener()`** method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) - */ - addEventListener( - type: Type, - handler: EventListenerOrEventListenerObject, - options?: EventTargetAddEventListenerOptions | boolean - ): void; - /** - * The **`removeEventListener()`** method of the EventTarget interface removes an event listener previously registered with EventTarget.addEventListener() from the target. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) - */ - removeEventListener( - type: Type, - handler: EventListenerOrEventListenerObject, - options?: EventTargetEventListenerOptions | boolean - ): void; - /** - * The **`dispatchEvent()`** method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) - */ - dispatchEvent(event: EventMap[keyof EventMap]): boolean; + constructor(); + /** + * The **`addEventListener()`** method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) + */ + addEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetAddEventListenerOptions | boolean): void; + /** + * The **`removeEventListener()`** method of the EventTarget interface removes an event listener previously registered with EventTarget.addEventListener() from the target. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) + */ + removeEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetEventListenerOptions | boolean): void; + /** + * The **`dispatchEvent()`** method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ + dispatchEvent(event: EventMap[keyof EventMap]): boolean; } interface EventTargetEventListenerOptions { - capture?: boolean; + capture?: boolean; } interface EventTargetAddEventListenerOptions { - capture?: boolean; - passive?: boolean; - once?: boolean; - signal?: AbortSignal; + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; } interface EventTargetHandlerObject { - handleEvent: (event: Event) => any | undefined; + handleEvent: (event: Event) => any | undefined; } /** * The **`AbortController`** interface represents a controller object that allows you to abort one or more Web requests as and when desired. @@ -904,19 +803,19 @@ interface EventTargetHandlerObject { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController) */ declare class AbortController { - constructor(); - /** - * The **`signal`** read-only property of the AbortController interface returns an AbortSignal object instance, which can be used to communicate with/abort an asynchronous operation as desired. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal) - */ - get signal(): AbortSignal; - /** - * The **`abort()`** method of the AbortController interface aborts an asynchronous operation before it has completed. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort) - */ - abort(reason?: any): void; + constructor(); + /** + * The **`signal`** read-only property of the AbortController interface returns an AbortSignal object instance, which can be used to communicate with/abort an asynchronous operation as desired. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal) + */ + get signal(): AbortSignal; + /** + * The **`abort()`** method of the AbortController interface aborts an asynchronous operation before it has completed. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort) + */ + abort(reason?: any): void; } /** * The **`AbortSignal`** interface represents a signal object that allows you to communicate with an asynchronous operation (such as a fetch request) and abort it if required via an AbortController object. @@ -924,52 +823,52 @@ declare class AbortController { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal) */ declare abstract class AbortSignal extends EventTarget { - /** - * The **`AbortSignal.abort()`** static method returns an AbortSignal that is already set as aborted (and which does not trigger an AbortSignal/abort_event event). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) - */ - static abort(reason?: any): AbortSignal; - /** - * The **`AbortSignal.timeout()`** static method returns an AbortSignal that will automatically abort after a specified time. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) - */ - static timeout(delay: number): AbortSignal; - /** - * The **`AbortSignal.any()`** static method takes an iterable of abort signals and returns an AbortSignal. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/any_static) - */ - static any(signals: AbortSignal[]): AbortSignal; - /** - * The **`aborted`** read-only property returns a value that indicates whether the asynchronous operations the signal is communicating with are aborted (`true`) or not (`false`). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted) - */ - get aborted(): boolean; - /** - * The **`reason`** read-only property returns a JavaScript value that indicates the abort reason. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) - */ - get reason(): any; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ - get onabort(): any | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ - set onabort(value: any | null); - /** - * The **`throwIfAborted()`** method throws the signal's abort AbortSignal.reason if the signal has been aborted; otherwise it does nothing. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) - */ - throwIfAborted(): void; + /** + * The **`AbortSignal.abort()`** static method returns an AbortSignal that is already set as aborted (and which does not trigger an AbortSignal/abort_event event). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) + */ + static abort(reason?: any): AbortSignal; + /** + * The **`AbortSignal.timeout()`** static method returns an AbortSignal that will automatically abort after a specified time. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) + */ + static timeout(delay: number): AbortSignal; + /** + * The **`AbortSignal.any()`** static method takes an iterable of abort signals and returns an AbortSignal. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/any_static) + */ + static any(signals: AbortSignal[]): AbortSignal; + /** + * The **`aborted`** read-only property returns a value that indicates whether the asynchronous operations the signal is communicating with are aborted (`true`) or not (`false`). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted) + */ + get aborted(): boolean; + /** + * The **`reason`** read-only property returns a JavaScript value that indicates the abort reason. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) + */ + get reason(): any; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + get onabort(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + set onabort(value: any | null); + /** + * The **`throwIfAborted()`** method throws the signal's abort AbortSignal.reason if the signal has been aborted; otherwise it does nothing. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) + */ + throwIfAborted(): void; } interface Scheduler { - wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise; + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise; } interface SchedulerWaitOptions { - signal?: AbortSignal; + signal?: AbortSignal; } /** * The **`ExtendableEvent`** interface extends the lifetime of the `install` and `activate` events dispatched on the global scope as part of the service worker lifecycle. @@ -977,12 +876,12 @@ interface SchedulerWaitOptions { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent) */ declare abstract class ExtendableEvent extends Event { - /** - * The **`ExtendableEvent.waitUntil()`** method tells the event dispatcher that work is ongoing. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) - */ - waitUntil(promise: Promise): void; + /** + * The **`ExtendableEvent.waitUntil()`** method tells the event dispatcher that work is ongoing. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) + */ + waitUntil(promise: Promise): void; } /** * The **`CustomEvent`** interface represents events initialized by an application for any purpose. @@ -990,19 +889,19 @@ declare abstract class ExtendableEvent extends Event { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent) */ declare class CustomEvent extends Event { - constructor(type: string, init?: CustomEventCustomEventInit); - /** - * The read-only **`detail`** property of the CustomEvent interface returns any data passed when initializing the event. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail) - */ - get detail(): T; + constructor(type: string, init?: CustomEventCustomEventInit); + /** + * The read-only **`detail`** property of the CustomEvent interface returns any data passed when initializing the event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail) + */ + get detail(): T; } interface CustomEventCustomEventInit { - bubbles?: boolean; - cancelable?: boolean; - composed?: boolean; - detail?: any; + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; + detail?: any; } /** * The **`Blob`** interface represents a blob, which is a file-like object of immutable, raw data; they can be read as text or binary data, or converted into a ReadableStream so its methods can be used for processing the data. @@ -1010,52 +909,52 @@ interface CustomEventCustomEventInit { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob) */ declare class Blob { - constructor(type?: ((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. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) - */ - get size(): number; - /** - * The **`type`** read-only property of the Blob interface returns the MIME type of the file. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) - */ - get type(): string; - /** - * The **`slice()`** method of the Blob interface creates and returns a new `Blob` object which contains data from a subset of the blob on which it's called. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) - */ - slice(start?: number, end?: number, type?: string): Blob; - /** - * The **`arrayBuffer()`** method of the Blob interface returns a Promise that resolves with the contents of the blob as binary data contained in an ArrayBuffer. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) - */ - arrayBuffer(): Promise; - /** - * The **`bytes()`** method of the Blob interface returns a Promise that resolves with a Uint8Array containing the contents of the blob as an array of bytes. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/bytes) - */ - bytes(): Promise; - /** - * The **`text()`** method of the string containing the contents of the blob, interpreted as UTF-8. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) - */ - text(): Promise; - /** - * The **`stream()`** method of the Blob interface returns a ReadableStream which upon reading returns the data contained within the `Blob`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) - */ - stream(): ReadableStream; + constructor(type?: ((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. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) + */ + get size(): number; + /** + * The **`type`** read-only property of the Blob interface returns the MIME type of the file. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) + */ + get type(): string; + /** + * The **`slice()`** method of the Blob interface creates and returns a new `Blob` object which contains data from a subset of the blob on which it's called. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) + */ + slice(start?: number, end?: number, type?: string): Blob; + /** + * The **`arrayBuffer()`** method of the Blob interface returns a Promise that resolves with the contents of the blob as binary data contained in an ArrayBuffer. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) + */ + arrayBuffer(): Promise; + /** + * The **`bytes()`** method of the Blob interface returns a Promise that resolves with a Uint8Array containing the contents of the blob as an array of bytes. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/bytes) + */ + bytes(): Promise; + /** + * The **`text()`** method of the string containing the contents of the blob, interpreted as UTF-8. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) + */ + text(): Promise; + /** + * The **`stream()`** method of the Blob interface returns a ReadableStream which upon reading returns the data contained within the `Blob`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) + */ + stream(): ReadableStream; } interface BlobOptions { - type?: string; + type?: string; } /** * The **`File`** interface provides information about files and allows JavaScript in a web page to access their content. @@ -1063,98 +962,84 @@ interface BlobOptions { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File) */ declare class File extends Blob { - constructor( - bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, - name: string, - options?: FileOptions - ); - /** - * The **`name`** read-only property of the File interface returns the name of the file represented by a File object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) - */ - get name(): string; - /** - * The **`lastModified`** read-only property of the File interface provides the last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) - */ - get lastModified(): number; + constructor(bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, name: string, options?: FileOptions); + /** + * The **`name`** read-only property of the File interface returns the name of the file represented by a File object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) + */ + get name(): string; + /** + * The **`lastModified`** read-only property of the File interface provides the last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) + */ + get lastModified(): number; } interface FileOptions { - type?: string; - lastModified?: number; + type?: string; + lastModified?: number; } /** - * The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. - * - * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) - */ +* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. +* +* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) +*/ declare abstract class CacheStorage { - /** - * The **`open()`** method of the the Cache object matching the `cacheName`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) - */ - open(cacheName: string): Promise; - readonly default: Cache; + /** + * The **`open()`** method of the the Cache object matching the `cacheName`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) + */ + open(cacheName: string): Promise; + readonly default: Cache; } /** - * The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. - * - * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) - */ +* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. +* +* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) +*/ declare abstract class Cache { - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#delete) */ - delete(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#match) */ - match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#put) */ - put(request: RequestInfo | URL, response: Response): Promise; + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#delete) */ + delete(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#match) */ + match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#put) */ + put(request: RequestInfo | URL, response: Response): Promise; } interface CacheQueryOptions { - ignoreMethod?: boolean; + ignoreMethod?: boolean; } /** - * The Web Crypto API provides a set of low-level functions for common cryptographic tasks. - * The Workers runtime implements the full surface of this API, but with some differences in - * the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms) - * compared to those implemented in most browsers. - * - * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/) - */ +* The Web Crypto API provides a set of low-level functions for common cryptographic tasks. +* The Workers runtime implements the full surface of this API, but with some differences in +* the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms) +* compared to those implemented in most browsers. +* +* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/) +*/ declare abstract class Crypto { - /** - * The **`Crypto.subtle`** read-only property returns a cryptographic operations. - * Available only in secure contexts. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle) - */ - get subtle(): SubtleCrypto; - /** - * The **`Crypto.getRandomValues()`** method lets you get cryptographically strong random values. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) - */ - getRandomValues< - T extends - | Int8Array - | Uint8Array - | Int16Array - | Uint16Array - | Int32Array - | Uint32Array - | BigInt64Array - | BigUint64Array, - >(buffer: T): T; - /** - * The **`randomUUID()`** method of the Crypto interface is used to generate a v4 UUID using a cryptographically secure random number generator. - * Available only in secure contexts. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID) - */ - randomUUID(): string; - DigestStream: typeof DigestStream; + /** + * The **`Crypto.subtle`** read-only property returns a cryptographic operations. + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle) + */ + get subtle(): SubtleCrypto; + /** + * The **`Crypto.getRandomValues()`** method lets you get cryptographically strong random values. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) + */ + getRandomValues(buffer: T): T; + /** + * The **`randomUUID()`** method of the Crypto interface is used to generate a v4 UUID using a cryptographically secure random number generator. + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID) + */ + randomUUID(): string; + DigestStream: typeof DigestStream; } /** * The **`SubtleCrypto`** interface of the Web Crypto API provides a number of low-level cryptographic functions. @@ -1163,273 +1048,214 @@ declare abstract class Crypto { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto) */ declare abstract class SubtleCrypto { - /** - * The **`encrypt()`** method of the SubtleCrypto interface encrypts data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/encrypt) - */ - encrypt( - algorithm: string | SubtleCryptoEncryptAlgorithm, - key: CryptoKey, - plainText: ArrayBuffer | ArrayBufferView - ): Promise; - /** - * The **`decrypt()`** method of the SubtleCrypto interface decrypts some encrypted data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/decrypt) - */ - decrypt( - algorithm: string | SubtleCryptoEncryptAlgorithm, - key: CryptoKey, - cipherText: ArrayBuffer | ArrayBufferView - ): Promise; - /** - * The **`sign()`** method of the SubtleCrypto interface generates a digital signature. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/sign) - */ - sign( - algorithm: string | SubtleCryptoSignAlgorithm, - key: CryptoKey, - data: ArrayBuffer | ArrayBufferView - ): Promise; - /** - * The **`verify()`** method of the SubtleCrypto interface verifies a digital signature. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/verify) - */ - verify( - algorithm: string | SubtleCryptoSignAlgorithm, - key: CryptoKey, - signature: ArrayBuffer | ArrayBufferView, - data: ArrayBuffer | ArrayBufferView - ): Promise; - /** - * The **`digest()`** method of the SubtleCrypto interface generates a _digest_ of the given data, using the specified hash function. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/digest) - */ - digest( - algorithm: string | SubtleCryptoHashAlgorithm, - data: ArrayBuffer | ArrayBufferView - ): Promise; - /** - * The **`generateKey()`** method of the SubtleCrypto interface is used to generate a new key (for symmetric algorithms) or key pair (for public-key algorithms). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) - */ - generateKey( - algorithm: string | SubtleCryptoGenerateKeyAlgorithm, - extractable: boolean, - keyUsages: string[] - ): Promise; - /** - * The **`deriveKey()`** method of the SubtleCrypto interface can be used to derive a secret key from a master key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) - */ - deriveKey( - algorithm: string | SubtleCryptoDeriveKeyAlgorithm, - baseKey: CryptoKey, - derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, - extractable: boolean, - keyUsages: string[] - ): Promise; - /** - * The **`deriveBits()`** method of the key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveBits) - */ - deriveBits( - algorithm: string | SubtleCryptoDeriveKeyAlgorithm, - baseKey: CryptoKey, - length?: number | null - ): Promise; - /** - * The **`importKey()`** method of the SubtleCrypto interface imports a key: that is, it takes as input a key in an external, portable format and gives you a CryptoKey object that you can use in the Web Crypto API. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) - */ - importKey( - format: string, - keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, - algorithm: string | SubtleCryptoImportKeyAlgorithm, - extractable: boolean, - keyUsages: string[] - ): Promise; - /** - * The **`exportKey()`** method of the SubtleCrypto interface exports a key: that is, it takes as input a CryptoKey object and gives you the key in an external, portable format. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/exportKey) - */ - exportKey(format: string, key: CryptoKey): Promise; - /** - * The **`wrapKey()`** method of the SubtleCrypto interface 'wraps' a key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/wrapKey) - */ - wrapKey( - format: string, - key: CryptoKey, - wrappingKey: CryptoKey, - wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm - ): Promise; - /** - * The **`unwrapKey()`** method of the SubtleCrypto interface 'unwraps' a key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) - */ - unwrapKey( - format: string, - wrappedKey: ArrayBuffer | ArrayBufferView, - unwrappingKey: CryptoKey, - unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, - unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, - extractable: boolean, - keyUsages: string[] - ): Promise; - timingSafeEqual(a: ArrayBuffer | ArrayBufferView, b: ArrayBuffer | ArrayBufferView): boolean; -} -/** - * The **`CryptoKey`** interface of the Web Crypto API represents a cryptographic key obtained from one of the SubtleCrypto methods SubtleCrypto.generateKey, SubtleCrypto.deriveKey, SubtleCrypto.importKey, or SubtleCrypto.unwrapKey. - * Available only in secure contexts. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey) - */ -declare abstract class CryptoKey { - /** - * The read-only **`type`** property of the CryptoKey interface indicates which kind of key is represented by the object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) - */ - readonly type: string; - /** - * The read-only **`extractable`** property of the CryptoKey interface indicates whether or not the key may be extracted using `SubtleCrypto.exportKey()` or `SubtleCrypto.wrapKey()`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) - */ - readonly extractable: boolean; - /** - * The read-only **`algorithm`** property of the CryptoKey interface returns an object describing the algorithm for which this key can be used, and any associated extra parameters. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) - */ - readonly algorithm: - | CryptoKeyKeyAlgorithm - | CryptoKeyAesKeyAlgorithm - | CryptoKeyHmacKeyAlgorithm - | CryptoKeyRsaKeyAlgorithm - | CryptoKeyEllipticKeyAlgorithm - | CryptoKeyArbitraryKeyAlgorithm; - /** - * The read-only **`usages`** property of the CryptoKey interface indicates what can be done with the key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) - */ - readonly usages: string[]; -} -interface CryptoKeyPair { - publicKey: CryptoKey; - privateKey: CryptoKey; -} -interface JsonWebKey { - kty: string; - use?: string; - key_ops?: string[]; - alg?: string; - ext?: boolean; - crv?: string; - x?: string; - y?: string; - d?: string; - n?: string; - e?: string; - p?: string; - q?: string; - dp?: string; - dq?: string; - qi?: string; - oth?: RsaOtherPrimesInfo[]; - k?: string; -} -interface RsaOtherPrimesInfo { - r?: string; - d?: string; - t?: string; -} -interface SubtleCryptoDeriveKeyAlgorithm { - name: string; - salt?: ArrayBuffer | ArrayBufferView; - iterations?: number; - hash?: string | SubtleCryptoHashAlgorithm; - $public?: CryptoKey; - info?: ArrayBuffer | ArrayBufferView; -} -interface SubtleCryptoEncryptAlgorithm { - name: string; - iv?: ArrayBuffer | ArrayBufferView; - additionalData?: ArrayBuffer | ArrayBufferView; - tagLength?: number; - counter?: ArrayBuffer | ArrayBufferView; - length?: number; - label?: ArrayBuffer | ArrayBufferView; -} -interface SubtleCryptoGenerateKeyAlgorithm { - name: string; - hash?: string | SubtleCryptoHashAlgorithm; - modulusLength?: number; - publicExponent?: ArrayBuffer | ArrayBufferView; - length?: number; - namedCurve?: string; -} + /** + * The **`encrypt()`** method of the SubtleCrypto interface encrypts data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/encrypt) + */ + encrypt(algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, plainText: ArrayBuffer | ArrayBufferView): Promise; + /** + * The **`decrypt()`** method of the SubtleCrypto interface decrypts some encrypted data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/decrypt) + */ + decrypt(algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, cipherText: ArrayBuffer | ArrayBufferView): Promise; + /** + * The **`sign()`** method of the SubtleCrypto interface generates a digital signature. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/sign) + */ + sign(algorithm: string | SubtleCryptoSignAlgorithm, key: CryptoKey, data: ArrayBuffer | ArrayBufferView): Promise; + /** + * The **`verify()`** method of the SubtleCrypto interface verifies a digital signature. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/verify) + */ + verify(algorithm: string | SubtleCryptoSignAlgorithm, key: CryptoKey, signature: ArrayBuffer | ArrayBufferView, data: ArrayBuffer | ArrayBufferView): Promise; + /** + * The **`digest()`** method of the SubtleCrypto interface generates a _digest_ of the given data, using the specified hash function. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/digest) + */ + digest(algorithm: string | SubtleCryptoHashAlgorithm, data: ArrayBuffer | ArrayBufferView): Promise; + /** + * The **`generateKey()`** method of the SubtleCrypto interface is used to generate a new key (for symmetric algorithms) or key pair (for public-key algorithms). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) + */ + generateKey(algorithm: string | SubtleCryptoGenerateKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; + /** + * The **`deriveKey()`** method of the SubtleCrypto interface can be used to derive a secret key from a master key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) + */ + deriveKey(algorithm: string | SubtleCryptoDeriveKeyAlgorithm, baseKey: CryptoKey, derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; + /** + * The **`deriveBits()`** method of the key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveBits) + */ + deriveBits(algorithm: string | SubtleCryptoDeriveKeyAlgorithm, baseKey: CryptoKey, length?: number | null): Promise; + /** + * The **`importKey()`** method of the SubtleCrypto interface imports a key: that is, it takes as input a key in an external, portable format and gives you a CryptoKey object that you can use in the Web Crypto API. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) + */ + importKey(format: string, keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, algorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; + /** + * The **`exportKey()`** method of the SubtleCrypto interface exports a key: that is, it takes as input a CryptoKey object and gives you the key in an external, portable format. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/exportKey) + */ + exportKey(format: string, key: CryptoKey): Promise; + /** + * The **`wrapKey()`** method of the SubtleCrypto interface 'wraps' a key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/wrapKey) + */ + wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm): Promise; + /** + * The **`unwrapKey()`** method of the SubtleCrypto interface 'unwraps' a key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) + */ + unwrapKey(format: string, wrappedKey: ArrayBuffer | ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; + timingSafeEqual(a: ArrayBuffer | ArrayBufferView, b: ArrayBuffer | ArrayBufferView): boolean; +} +/** + * The **`CryptoKey`** interface of the Web Crypto API represents a cryptographic key obtained from one of the SubtleCrypto methods SubtleCrypto.generateKey, SubtleCrypto.deriveKey, SubtleCrypto.importKey, or SubtleCrypto.unwrapKey. + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey) + */ +declare abstract class CryptoKey { + /** + * The read-only **`type`** property of the CryptoKey interface indicates which kind of key is represented by the object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) + */ + readonly type: string; + /** + * The read-only **`extractable`** property of the CryptoKey interface indicates whether or not the key may be extracted using `SubtleCrypto.exportKey()` or `SubtleCrypto.wrapKey()`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) + */ + readonly extractable: boolean; + /** + * The read-only **`algorithm`** property of the CryptoKey interface returns an object describing the algorithm for which this key can be used, and any associated extra parameters. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) + */ + readonly algorithm: CryptoKeyKeyAlgorithm | CryptoKeyAesKeyAlgorithm | CryptoKeyHmacKeyAlgorithm | CryptoKeyRsaKeyAlgorithm | CryptoKeyEllipticKeyAlgorithm | CryptoKeyArbitraryKeyAlgorithm; + /** + * The read-only **`usages`** property of the CryptoKey interface indicates what can be done with the key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) + */ + readonly usages: string[]; +} +interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: (ArrayBuffer | ArrayBufferView); + iterations?: number; + hash?: (string | SubtleCryptoHashAlgorithm); + $public?: CryptoKey; + info?: (ArrayBuffer | ArrayBufferView); +} +interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: (ArrayBuffer | ArrayBufferView); + additionalData?: (ArrayBuffer | ArrayBufferView); + tagLength?: number; + counter?: (ArrayBuffer | ArrayBufferView); + length?: number; + label?: (ArrayBuffer | ArrayBufferView); +} +interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: (string | SubtleCryptoHashAlgorithm); + modulusLength?: number; + publicExponent?: (ArrayBuffer | ArrayBufferView); + length?: number; + namedCurve?: string; +} interface SubtleCryptoHashAlgorithm { - name: string; + name: string; } interface SubtleCryptoImportKeyAlgorithm { - name: string; - hash?: string | SubtleCryptoHashAlgorithm; - length?: number; - namedCurve?: string; - compressed?: boolean; + name: string; + hash?: (string | SubtleCryptoHashAlgorithm); + length?: number; + namedCurve?: string; + compressed?: boolean; } interface SubtleCryptoSignAlgorithm { - name: string; - hash?: string | SubtleCryptoHashAlgorithm; - dataLength?: number; - saltLength?: number; + name: string; + hash?: (string | SubtleCryptoHashAlgorithm); + dataLength?: number; + saltLength?: number; } interface CryptoKeyKeyAlgorithm { - name: string; + name: string; } interface CryptoKeyAesKeyAlgorithm { - name: string; - length: number; + name: string; + length: number; } interface CryptoKeyHmacKeyAlgorithm { - name: string; - hash: CryptoKeyKeyAlgorithm; - length: number; + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; } interface CryptoKeyRsaKeyAlgorithm { - name: string; - modulusLength: number; - publicExponent: ArrayBuffer | ArrayBufferView; - hash?: CryptoKeyKeyAlgorithm; + name: string; + modulusLength: number; + publicExponent: ArrayBuffer | ArrayBufferView; + hash?: CryptoKeyKeyAlgorithm; } interface CryptoKeyEllipticKeyAlgorithm { - name: string; - namedCurve: string; + name: string; + namedCurve: string; } interface CryptoKeyArbitraryKeyAlgorithm { - name: string; - hash?: CryptoKeyKeyAlgorithm; - namedCurve?: string; - length?: number; + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; } declare class DigestStream extends WritableStream { - constructor(algorithm: string | SubtleCryptoHashAlgorithm); - readonly digest: Promise; - get bytesWritten(): number | bigint; + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + readonly digest: Promise; + get bytesWritten(): number | bigint; } /** * The **`TextDecoder`** interface represents a decoder for a specific text encoding, such as `UTF-8`, `ISO-8859-2`, `KOI8-R`, `GBK`, etc. @@ -1437,16 +1263,16 @@ declare class DigestStream extends WritableStream * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder) */ declare class TextDecoder { - constructor(label?: string, options?: TextDecoderConstructorOptions); - /** - * The **`TextDecoder.decode()`** method returns a string containing text decoded from the buffer passed as a parameter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode) - */ - decode(input?: ArrayBuffer | ArrayBufferView, options?: TextDecoderDecodeOptions): string; - get encoding(): string; - get fatal(): boolean; - get ignoreBOM(): boolean; + constructor(label?: string, options?: TextDecoderConstructorOptions); + /** + * The **`TextDecoder.decode()`** method returns a string containing text decoded from the buffer passed as a parameter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode) + */ + decode(input?: (ArrayBuffer | ArrayBufferView), options?: TextDecoderDecodeOptions): string; + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; } /** * The **`TextEncoder`** interface takes a stream of code points as input and emits a stream of UTF-8 bytes. @@ -1454,31 +1280,31 @@ declare class TextDecoder { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder) */ declare class TextEncoder { - constructor(); - /** - * The **`TextEncoder.encode()`** method takes a string as input, and returns a Global_Objects/Uint8Array containing the text given in parameters encoded with the specific method for that TextEncoder object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode) - */ - encode(input?: string): Uint8Array; - /** - * The **`TextEncoder.encodeInto()`** method takes a string to encode and a destination Uint8Array to put resulting UTF-8 encoded text into, and returns a dictionary object indicating the progress of the encoding. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto) - */ - encodeInto(input: string, buffer: Uint8Array): TextEncoderEncodeIntoResult; - get encoding(): string; + constructor(); + /** + * The **`TextEncoder.encode()`** method takes a string as input, and returns a Global_Objects/Uint8Array containing the text given in parameters encoded with the specific method for that TextEncoder object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode) + */ + encode(input?: string): Uint8Array; + /** + * The **`TextEncoder.encodeInto()`** method takes a string to encode and a destination Uint8Array to put resulting UTF-8 encoded text into, and returns a dictionary object indicating the progress of the encoding. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto) + */ + encodeInto(input: string, buffer: Uint8Array): TextEncoderEncodeIntoResult; + get encoding(): string; } interface TextDecoderConstructorOptions { - fatal: boolean; - ignoreBOM: boolean; + fatal: boolean; + ignoreBOM: boolean; } interface TextDecoderDecodeOptions { - stream: boolean; + stream: boolean; } interface TextEncoderEncodeIntoResult { - read: number; - written: number; + read: number; + written: number; } /** * The **`ErrorEvent`** interface represents events providing information related to errors in scripts or in files. @@ -1486,44 +1312,44 @@ interface TextEncoderEncodeIntoResult { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent) */ declare class ErrorEvent extends Event { - constructor(type: string, init?: ErrorEventErrorEventInit); - /** - * The **`filename`** read-only property of the ErrorEvent interface returns a string containing the name of the script file in which the error occurred. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) - */ - get filename(): string; - /** - * The **`message`** read-only property of the ErrorEvent interface returns a string containing a human-readable error message describing the problem. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) - */ - get message(): string; - /** - * The **`lineno`** read-only property of the ErrorEvent interface returns an integer containing the line number of the script file on which the error occurred. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) - */ - get lineno(): number; - /** - * The **`colno`** read-only property of the ErrorEvent interface returns an integer containing the column number of the script file on which the error occurred. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) - */ - get colno(): number; - /** - * The **`error`** read-only property of the ErrorEvent interface returns a JavaScript value, such as an Error or DOMException, representing the error associated with this event. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) - */ - get error(): any; + constructor(type: string, init?: ErrorEventErrorEventInit); + /** + * The **`filename`** read-only property of the ErrorEvent interface returns a string containing the name of the script file in which the error occurred. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) + */ + get filename(): string; + /** + * The **`message`** read-only property of the ErrorEvent interface returns a string containing a human-readable error message describing the problem. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) + */ + get message(): string; + /** + * The **`lineno`** read-only property of the ErrorEvent interface returns an integer containing the line number of the script file on which the error occurred. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) + */ + get lineno(): number; + /** + * The **`colno`** read-only property of the ErrorEvent interface returns an integer containing the column number of the script file on which the error occurred. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) + */ + get colno(): number; + /** + * The **`error`** read-only property of the ErrorEvent interface returns a JavaScript value, such as an Error or DOMException, representing the error associated with this event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) + */ + get error(): any; } interface ErrorEventErrorEventInit { - message?: string; - filename?: string; - lineno?: number; - colno?: number; - error?: any; + message?: string; + filename?: string; + lineno?: number; + colno?: number; + error?: any; } /** * The **`MessageEvent`** interface represents a message received by a target object. @@ -1531,40 +1357,40 @@ interface ErrorEventErrorEventInit { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent) */ declare class MessageEvent extends Event { - constructor(type: string, initializer: MessageEventInit); - /** - * The **`data`** read-only property of the The data sent by the message emitter; this can be any data type, depending on what originated this event. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/data) - */ - readonly data: any; - /** - * The **`origin`** read-only property of the origin of the message emitter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/origin) - */ - readonly origin: string | null; - /** - * The **`lastEventId`** read-only property of the unique ID for the event. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/lastEventId) - */ - readonly lastEventId: string; - /** - * The **`source`** read-only property of the a WindowProxy, MessagePort, or a `MessageEventSource` (which can be a WindowProxy, message emitter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/source) - */ - readonly source: MessagePort | null; - /** - * The **`ports`** read-only property of the containing all MessagePort objects sent with the message, in order. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/ports) - */ - readonly ports: MessagePort[]; + constructor(type: string, initializer: MessageEventInit); + /** + * The **`data`** read-only property of the The data sent by the message emitter; this can be any data type, depending on what originated this event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/data) + */ + readonly data: any; + /** + * The **`origin`** read-only property of the origin of the message emitter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/origin) + */ + readonly origin: string | null; + /** + * The **`lastEventId`** read-only property of the unique ID for the event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/lastEventId) + */ + readonly lastEventId: string; + /** + * The **`source`** read-only property of the a WindowProxy, MessagePort, or a `MessageEventSource` (which can be a WindowProxy, message emitter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/source) + */ + readonly source: MessagePort | null; + /** + * The **`ports`** read-only property of the containing all MessagePort objects sent with the message, in order. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/ports) + */ + readonly ports: MessagePort[]; } interface MessageEventInit { - data: ArrayBuffer | string; + data: ArrayBuffer | string; } /** * The **`PromiseRejectionEvent`** interface represents events which are sent to the global script context when JavaScript Promises are rejected. @@ -1572,18 +1398,18 @@ interface MessageEventInit { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent) */ declare abstract class PromiseRejectionEvent extends Event { - /** - * The PromiseRejectionEvent interface's **`promise`** read-only property indicates the JavaScript rejected. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) - */ - readonly promise: Promise; - /** - * The PromiseRejectionEvent **`reason`** read-only property is any JavaScript value or Object which provides the reason passed into Promise.reject(). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) - */ - readonly reason: any; + /** + * The PromiseRejectionEvent interface's **`promise`** read-only property indicates the JavaScript rejected. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) + */ + readonly promise: Promise; + /** + * The PromiseRejectionEvent **`reason`** read-only property is any JavaScript value or Object which provides the reason passed into Promise.reject(). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) + */ + readonly reason: any; } /** * The **`FormData`** interface provides a way to construct a set of key/value pairs representing form fields and their values, which can be sent using the Window/fetch, XMLHttpRequest.send() or navigator.sendBeacon() methods. @@ -1591,148 +1417,151 @@ declare abstract class PromiseRejectionEvent extends Event { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData) */ declare class FormData { - constructor(); - /** - * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) - */ - append(name: string, value: string | Blob): void; - /** - * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) - */ - append(name: string, value: string): void; - /** - * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) - */ - append(name: string, value: Blob, filename?: string): void; - /** - * The **`delete()`** method of the FormData interface deletes a key and its value(s) from a `FormData` object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/delete) - */ - delete(name: string): void; - /** - * The **`get()`** method of the FormData interface returns the first value associated with a given key from within a `FormData` object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/get) - */ - get(name: string): (File | string) | null; - /** - * The **`getAll()`** method of the FormData interface returns all the values associated with a given key from within a `FormData` object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/getAll) - */ - getAll(name: string): (File | string)[]; - /** - * The **`has()`** method of the FormData interface returns whether a `FormData` object contains a certain key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/has) - */ - has(name: string): boolean; - /** - * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) - */ - set(name: string, value: string | Blob): void; - /** - * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) - */ - set(name: string, value: string): void; - /** - * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) - */ - set(name: string, value: Blob, filename?: string): void; - /* Returns an array of key, value pairs for every entry in the list. */ - entries(): IterableIterator<[key: string, value: File | string]>; - /* Returns a list of keys in the list. */ - keys(): IterableIterator; - /* Returns a list of values in the list. */ - values(): IterableIterator; - forEach( - callback: (this: This, value: File | string, key: string, parent: FormData) => void, - thisArg?: This - ): void; - [Symbol.iterator](): IterableIterator<[key: string, value: File | string]>; + constructor(); + /** + * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) + */ + append(name: string, value: string | Blob): void; + /** + * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) + */ + append(name: string, value: string): void; + /** + * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) + */ + append(name: string, value: Blob, filename?: string): void; + /** + * The **`delete()`** method of the FormData interface deletes a key and its value(s) from a `FormData` object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/delete) + */ + delete(name: string): void; + /** + * The **`get()`** method of the FormData interface returns the first value associated with a given key from within a `FormData` object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/get) + */ + get(name: string): (File | string) | null; + /** + * The **`getAll()`** method of the FormData interface returns all the values associated with a given key from within a `FormData` object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/getAll) + */ + getAll(name: string): (File | string)[]; + /** + * The **`has()`** method of the FormData interface returns whether a `FormData` object contains a certain key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/has) + */ + has(name: string): boolean; + /** + * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) + */ + set(name: string, value: string | Blob): void; + /** + * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) + */ + set(name: string, value: string): void; + /** + * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) + */ + set(name: string, value: Blob, filename?: string): void; + /* Returns an array of key, value pairs for every entry in the list. */ + entries(): IterableIterator<[ + key: string, + value: File | string + ]>; + /* Returns a list of keys in the list. */ + keys(): IterableIterator; + /* Returns a list of values in the list. */ + values(): IterableIterator<(File | string)>; + forEach(callback: (this: This, value: File | string, key: string, parent: FormData) => void, thisArg?: This): void; + [Symbol.iterator](): IterableIterator<[ + key: string, + value: File | string + ]>; } interface ContentOptions { - html?: boolean; + html?: boolean; } declare class HTMLRewriter { - constructor(); - on(selector: string, handlers: HTMLRewriterElementContentHandlers): HTMLRewriter; - onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; - transform(response: Response): Response; + constructor(); + on(selector: string, handlers: HTMLRewriterElementContentHandlers): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; } interface HTMLRewriterElementContentHandlers { - element?(element: Element): void | Promise; - comments?(comment: Comment): void | Promise; - text?(element: Text): void | Promise; + element?(element: Element): void | Promise; + comments?(comment: Comment): void | Promise; + text?(element: Text): void | Promise; } interface HTMLRewriterDocumentContentHandlers { - doctype?(doctype: Doctype): void | Promise; - comments?(comment: Comment): void | Promise; - text?(text: Text): void | Promise; - end?(end: DocumentEnd): void | Promise; + doctype?(doctype: Doctype): void | Promise; + comments?(comment: Comment): void | Promise; + text?(text: Text): void | Promise; + end?(end: DocumentEnd): void | Promise; } interface Doctype { - readonly name: string | null; - readonly publicId: string | null; - readonly systemId: string | null; + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; } interface Element { - tagName: string; - readonly attributes: IterableIterator; - readonly removed: boolean; - readonly namespaceURI: string; - getAttribute(name: string): string | null; - hasAttribute(name: string): boolean; - setAttribute(name: string, value: string): Element; - removeAttribute(name: string): Element; - before(content: string | ReadableStream | Response, options?: ContentOptions): Element; - after(content: string | ReadableStream | Response, options?: ContentOptions): Element; - prepend(content: string | ReadableStream | Response, options?: ContentOptions): Element; - append(content: string | ReadableStream | Response, options?: ContentOptions): Element; - replace(content: string | ReadableStream | Response, options?: ContentOptions): Element; - remove(): Element; - removeAndKeepContent(): Element; - setInnerContent(content: string | ReadableStream | Response, options?: ContentOptions): Element; - onEndTag(handler: (tag: EndTag) => void | Promise): void; + tagName: string; + readonly attributes: IterableIterator; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string | ReadableStream | Response, options?: ContentOptions): Element; + after(content: string | ReadableStream | Response, options?: ContentOptions): Element; + prepend(content: string | ReadableStream | Response, options?: ContentOptions): Element; + append(content: string | ReadableStream | Response, options?: ContentOptions): Element; + replace(content: string | ReadableStream | Response, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string | ReadableStream | Response, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise): void; } interface EndTag { - name: string; - before(content: string | ReadableStream | Response, options?: ContentOptions): EndTag; - after(content: string | ReadableStream | Response, options?: ContentOptions): EndTag; - remove(): EndTag; + name: string; + before(content: string | ReadableStream | Response, options?: ContentOptions): EndTag; + after(content: string | ReadableStream | Response, options?: ContentOptions): EndTag; + remove(): EndTag; } interface Comment { - text: string; - readonly removed: boolean; - before(content: string, options?: ContentOptions): Comment; - after(content: string, options?: ContentOptions): Comment; - replace(content: string, options?: ContentOptions): Comment; - remove(): Comment; + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; } interface Text { - readonly text: string; - readonly lastInTextNode: boolean; - readonly removed: boolean; - before(content: string | ReadableStream | Response, options?: ContentOptions): Text; - after(content: string | ReadableStream | Response, options?: ContentOptions): Text; - replace(content: string | ReadableStream | Response, options?: ContentOptions): Text; - remove(): Text; + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string | ReadableStream | Response, options?: ContentOptions): Text; + after(content: string | ReadableStream | Response, options?: ContentOptions): Text; + replace(content: string | ReadableStream | Response, options?: ContentOptions): Text; + remove(): Text; } interface DocumentEnd { - append(content: string, options?: ContentOptions): DocumentEnd; + append(content: string, options?: ContentOptions): DocumentEnd; } /** * This is the event type for `fetch` events dispatched on the ServiceWorkerGlobalScope. @@ -1740,19 +1569,19 @@ interface DocumentEnd { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent) */ declare abstract class FetchEvent extends ExtendableEvent { - /** - * The **`request`** read-only property of the the event handler. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) - */ - readonly request: Request; - /** - * The **`respondWith()`** method of allows you to provide a promise for a Response yourself. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) - */ - respondWith(promise: Response | Promise): void; - passThroughOnException(): void; + /** + * The **`request`** read-only property of the the event handler. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) + */ + readonly request: Request; + /** + * The **`respondWith()`** method of allows you to provide a promise for a Response yourself. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) + */ + respondWith(promise: Response | Promise): void; + passThroughOnException(): void; } type HeadersInit = Headers | Iterable> | Record; /** @@ -1761,81 +1590,77 @@ type HeadersInit = Headers | Iterable> | Record * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers) */ declare class Headers { - constructor(init?: HeadersInit); - /** - * The **`get()`** method of the Headers interface returns a byte string of all the values of a header within a `Headers` object with a given name. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/get) - */ - get(name: string): string | null; - getAll(name: string): string[]; - /** - * The **`getSetCookie()`** method of the Headers interface returns an array containing the values of all Set-Cookie headers associated with a response. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/getSetCookie) - */ - getSetCookie(): string[]; - /** - * The **`has()`** method of the Headers interface returns a boolean stating whether a `Headers` object contains a certain header. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/has) - */ - has(name: string): boolean; - /** - * The **`set()`** method of the Headers interface sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/set) - */ - set(name: string, value: string): void; - /** - * The **`append()`** method of the Headers interface appends a new value onto an existing header inside a `Headers` object, or adds the header if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/append) - */ - append(name: string, value: string): void; - /** - * The **`delete()`** method of the Headers interface deletes a header from the current `Headers` object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/delete) - */ - delete(name: string): void; - forEach( - callback: (this: This, value: string, key: string, parent: Headers) => void, - thisArg?: This - ): void; - /* Returns an iterator allowing to go through all key/value pairs contained in this object. */ - entries(): IterableIterator<[key: string, value: string]>; - /* Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ - keys(): IterableIterator; - /* Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ - values(): IterableIterator; - [Symbol.iterator](): IterableIterator<[key: string, value: string]>; -} -type BodyInit = - | ReadableStream - | string - | ArrayBuffer - | ArrayBufferView - | Blob - | URLSearchParams - | FormData; + constructor(init?: HeadersInit); + /** + * The **`get()`** method of the Headers interface returns a byte string of all the values of a header within a `Headers` object with a given name. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/get) + */ + get(name: string): string | null; + getAll(name: string): string[]; + /** + * The **`getSetCookie()`** method of the Headers interface returns an array containing the values of all Set-Cookie headers associated with a response. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/getSetCookie) + */ + getSetCookie(): string[]; + /** + * The **`has()`** method of the Headers interface returns a boolean stating whether a `Headers` object contains a certain header. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/has) + */ + has(name: string): boolean; + /** + * The **`set()`** method of the Headers interface sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/set) + */ + set(name: string, value: string): void; + /** + * The **`append()`** method of the Headers interface appends a new value onto an existing header inside a `Headers` object, or adds the header if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/append) + */ + append(name: string, value: string): void; + /** + * The **`delete()`** method of the Headers interface deletes a header from the current `Headers` object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/delete) + */ + delete(name: string): void; + forEach(callback: (this: This, value: string, key: string, parent: Headers) => void, thisArg?: This): void; + /* Returns an iterator allowing to go through all key/value pairs contained in this object. */ + entries(): IterableIterator<[ + key: string, + value: string + ]>; + /* Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ + keys(): IterableIterator; + /* Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[ + key: string, + value: string + ]>; +} +type BodyInit = ReadableStream | string | ArrayBuffer | ArrayBufferView | Blob | URLSearchParams | FormData; declare abstract class Body { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/body) */ - get body(): ReadableStream | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bodyUsed) */ - get bodyUsed(): boolean; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/arrayBuffer) */ - arrayBuffer(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bytes) */ - bytes(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/text) */ - text(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/json) */ - json(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/formData) */ - formData(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/blob) */ - blob(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/body) */ + get body(): ReadableStream | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bodyUsed) */ + get bodyUsed(): boolean; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/arrayBuffer) */ + arrayBuffer(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bytes) */ + bytes(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/text) */ + text(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/json) */ + json(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/formData) */ + formData(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/blob) */ + blob(): Promise; } /** * The **`Response`** interface of the Fetch API represents the response to a request. @@ -1843,11 +1668,11 @@ declare abstract class Body { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response) */ declare var Response: { - prototype: Response; - new (body?: BodyInit | null, init?: ResponseInit): Response; - error(): Response; - redirect(url: string, status?: number): Response; - json(any: any, maybeInit?: ResponseInit | Response): Response; + prototype: Response; + new (body?: BodyInit | null, init?: ResponseInit): Response; + error(): Response; + redirect(url: string, status?: number): Response; + json(any: any, maybeInit?: (ResponseInit | Response)): Response; }; /** * The **`Response`** interface of the Fetch API represents the response to a request. @@ -1855,79 +1680,74 @@ declare var Response: { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response) */ interface Response extends Body { - /** - * The **`clone()`** method of the Response interface creates a clone of a response object, identical in every way, but stored in a different variable. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) - */ - clone(): Response; - /** - * The **`status`** read-only property of the Response interface contains the HTTP status codes of the response. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) - */ - status: number; - /** - * The **`statusText`** read-only property of the Response interface contains the status message corresponding to the HTTP status code in Response.status. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) - */ - statusText: string; - /** - * The **`headers`** read-only property of the with the response. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) - */ - headers: Headers; - /** - * The **`ok`** read-only property of the Response interface contains a Boolean stating whether the response was successful (status in the range 200-299) or not. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) - */ - ok: boolean; - /** - * The **`redirected`** read-only property of the Response interface indicates whether or not the response is the result of a request you made which was redirected. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) - */ - redirected: boolean; - /** - * The **`url`** read-only property of the Response interface contains the URL of the response. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) - */ - url: string; - webSocket: WebSocket | null; - cf: any | undefined; - /** - * The **`type`** read-only property of the Response interface contains the type of the response. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/type) - */ - type: 'default' | 'error'; + /** + * The **`clone()`** method of the Response interface creates a clone of a response object, identical in every way, but stored in a different variable. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) + */ + clone(): Response; + /** + * The **`status`** read-only property of the Response interface contains the HTTP status codes of the response. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) + */ + status: number; + /** + * The **`statusText`** read-only property of the Response interface contains the status message corresponding to the HTTP status code in Response.status. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) + */ + statusText: string; + /** + * The **`headers`** read-only property of the with the response. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) + */ + headers: Headers; + /** + * The **`ok`** read-only property of the Response interface contains a Boolean stating whether the response was successful (status in the range 200-299) or not. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) + */ + ok: boolean; + /** + * The **`redirected`** read-only property of the Response interface indicates whether or not the response is the result of a request you made which was redirected. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) + */ + redirected: boolean; + /** + * The **`url`** read-only property of the Response interface contains the URL of the response. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) + */ + url: string; + webSocket: WebSocket | null; + cf: any | undefined; + /** + * The **`type`** read-only property of the Response interface contains the type of the response. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/type) + */ + type: "default" | "error"; } interface ResponseInit { - status?: number; - statusText?: string; - headers?: HeadersInit; - cf?: any; - webSocket?: WebSocket | null; - encodeBody?: 'automatic' | 'manual'; -} -type RequestInfo> = - | Request - | string; + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: (WebSocket | null); + encodeBody?: "automatic" | "manual"; +} +type RequestInfo> = Request | string; /** * The **`Request`** interface of the Fetch API represents a resource request. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request) */ declare var Request: { - prototype: Request; - new >( - input: RequestInfo | URL, - init?: RequestInit - ): Request; + prototype: Request; + new >(input: RequestInfo | URL, init?: RequestInit): Request; }; /** * The **`Request`** interface of the Fetch API represents a resource request. @@ -1935,568 +1755,460 @@ declare var Request: { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request) */ interface Request> extends Body { - /** - * The **`clone()`** method of the Request interface creates a copy of the current `Request` object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) - */ - clone(): Request; - /** - * The **`method`** read-only property of the `POST`, etc.) A String indicating the method of the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method) - */ - method: string; - /** - * The **`url`** read-only property of the Request interface contains the URL of the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url) - */ - url: string; - /** - * The **`headers`** read-only property of the with the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) - */ - headers: Headers; - /** - * The **`redirect`** read-only property of the Request interface contains the mode for how redirects are handled. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect) - */ - redirect: string; - fetcher: Fetcher | null; - /** - * The read-only **`signal`** property of the Request interface returns the AbortSignal associated with the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) - */ - signal: AbortSignal; - cf: Cf | undefined; - /** - * The **`integrity`** read-only property of the Request interface contains the subresource integrity value of the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity) - */ - integrity: string; - /** - * The **`keepalive`** read-only property of the Request interface contains the request's `keepalive` setting (`true` or `false`), which indicates whether the browser will keep the associated request alive if the page that initiated it is unloaded before the request is complete. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive) - */ - keepalive: boolean; - /** - * The **`cache`** read-only property of the Request interface contains the cache mode of the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/cache) - */ - cache?: 'no-store' | 'no-cache'; + /** + * The **`clone()`** method of the Request interface creates a copy of the current `Request` object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) + */ + clone(): Request; + /** + * The **`method`** read-only property of the `POST`, etc.) A String indicating the method of the request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method) + */ + method: string; + /** + * The **`url`** read-only property of the Request interface contains the URL of the request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url) + */ + url: string; + /** + * The **`headers`** read-only property of the with the request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) + */ + headers: Headers; + /** + * The **`redirect`** read-only property of the Request interface contains the mode for how redirects are handled. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect) + */ + redirect: string; + fetcher: Fetcher | null; + /** + * The read-only **`signal`** property of the Request interface returns the AbortSignal associated with the request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) + */ + signal: AbortSignal; + cf?: Cf; + /** + * The **`integrity`** read-only property of the Request interface contains the subresource integrity value of the request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity) + */ + integrity: string; + /** + * The **`keepalive`** read-only property of the Request interface contains the request's `keepalive` setting (`true` or `false`), which indicates whether the browser will keep the associated request alive if the page that initiated it is unloaded before the request is complete. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive) + */ + keepalive: boolean; + /** + * The **`cache`** read-only property of the Request interface contains the cache mode of the request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/cache) + */ + cache?: "no-store" | "no-cache"; } interface RequestInit { - /* A string to set request's method. */ - method?: string; - /* A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ - headers?: HeadersInit; - /* A BodyInit object or null to set request's body. */ - body?: BodyInit | null; - /* A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ - redirect?: string; - fetcher?: Fetcher | null; - cf?: Cf; - /* A string indicating how the request will interact with the browser's cache to set request's cache. */ - cache?: 'no-store' | 'no-cache'; - /* A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ - integrity?: string; - /* An AbortSignal to set request's signal. */ - signal?: AbortSignal | null; - encodeResponseBody?: 'automatic' | 'manual'; -} -type Service< - T extends - | (new (...args: any[]) => Rpc.WorkerEntrypointBranded) - | Rpc.WorkerEntrypointBranded - | ExportedHandler - | undefined = undefined, -> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded - ? Fetcher> - : T extends Rpc.WorkerEntrypointBranded - ? Fetcher - : T extends Exclude - ? never - : Fetcher; -type Fetcher< - T extends Rpc.EntrypointBranded | undefined = undefined, - Reserved extends string = never, -> = (T extends Rpc.EntrypointBranded - ? Rpc.Provider - : unknown) & { - fetch(input: RequestInfo | URL, init?: RequestInit): Promise; - connect(address: SocketAddress | string, options?: SocketOptions): Socket; + /* A string to set request's method. */ + method?: string; + /* A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /* A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /* A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ + redirect?: string; + fetcher?: (Fetcher | null); + cf?: Cf; + /* A string indicating how the request will interact with the browser's cache to set request's cache. */ + cache?: "no-store" | "no-cache"; + /* A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /* An AbortSignal to set request's signal. */ + signal?: (AbortSignal | null); + encodeResponseBody?: "automatic" | "manual"; +} +type Service Rpc.WorkerEntrypointBranded) | Rpc.WorkerEntrypointBranded | ExportedHandler | undefined = undefined> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded ? Fetcher> : T extends Rpc.WorkerEntrypointBranded ? Fetcher : T extends Exclude ? never : Fetcher; +type Fetcher = (T extends Rpc.EntrypointBranded ? Rpc.Provider : unknown) & { + fetch(input: RequestInfo | URL, init?: RequestInit): Promise; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; }; interface KVNamespaceListKey { - name: Key; - expiration?: number; - metadata?: Metadata; -} -type KVNamespaceListResult = - | { - list_complete: false; - keys: KVNamespaceListKey[]; - cursor: string; - cacheStatus: string | null; - } - | { - list_complete: true; - keys: KVNamespaceListKey[]; - cacheStatus: string | null; - }; + name: Key; + expiration?: number; + metadata?: Metadata; +} +type KVNamespaceListResult = { + list_complete: false; + keys: KVNamespaceListKey[]; + cursor: string; + cacheStatus: string | null; +} | { + list_complete: true; + keys: KVNamespaceListKey[]; + cacheStatus: string | null; +}; interface KVNamespace { - get(key: Key, options?: Partial>): Promise; - get(key: Key, type: 'text'): Promise; - get(key: Key, type: 'json'): Promise; - get(key: Key, type: 'arrayBuffer'): Promise; - get(key: Key, type: 'stream'): Promise; - get(key: Key, options?: KVNamespaceGetOptions<'text'>): Promise; - get( - key: Key, - options?: KVNamespaceGetOptions<'json'> - ): Promise; - get(key: Key, options?: KVNamespaceGetOptions<'arrayBuffer'>): Promise; - get(key: Key, options?: KVNamespaceGetOptions<'stream'>): Promise; - get(key: Array, type: 'text'): Promise>; - get( - key: Array, - type: 'json' - ): Promise>; - get( - key: Array, - options?: Partial> - ): Promise>; - get( - key: Array, - options?: KVNamespaceGetOptions<'text'> - ): Promise>; - get( - key: Array, - options?: KVNamespaceGetOptions<'json'> - ): Promise>; - list( - options?: KVNamespaceListOptions - ): Promise>; - put( - key: Key, - value: string | ArrayBuffer | ArrayBufferView | ReadableStream, - options?: KVNamespacePutOptions - ): Promise; - getWithMetadata( - key: Key, - options?: Partial> - ): Promise>; - getWithMetadata( - key: Key, - type: 'text' - ): Promise>; - getWithMetadata( - key: Key, - type: 'json' - ): Promise>; - getWithMetadata( - key: Key, - type: 'arrayBuffer' - ): Promise>; - getWithMetadata( - key: Key, - type: 'stream' - ): Promise>; - getWithMetadata( - key: Key, - options: KVNamespaceGetOptions<'text'> - ): Promise>; - getWithMetadata( - key: Key, - options: KVNamespaceGetOptions<'json'> - ): Promise>; - getWithMetadata( - key: Key, - options: KVNamespaceGetOptions<'arrayBuffer'> - ): Promise>; - getWithMetadata( - key: Key, - options: KVNamespaceGetOptions<'stream'> - ): Promise>; - getWithMetadata( - key: Array, - type: 'text' - ): Promise>>; - getWithMetadata( - key: Array, - type: 'json' - ): Promise>>; - getWithMetadata( - key: Array, - options?: Partial> - ): Promise>>; - getWithMetadata( - key: Array, - options?: KVNamespaceGetOptions<'text'> - ): Promise>>; - getWithMetadata( - key: Array, - options?: KVNamespaceGetOptions<'json'> - ): Promise>>; - delete(key: Key): Promise; + get(key: Key, options?: Partial>): Promise; + get(key: Key, type: "text"): Promise; + get(key: Key, type: "json"): Promise; + get(key: Key, type: "arrayBuffer"): Promise; + get(key: Key, type: "stream"): Promise; + get(key: Key, options?: KVNamespaceGetOptions<"text">): Promise; + get(key: Key, options?: KVNamespaceGetOptions<"json">): Promise; + get(key: Key, options?: KVNamespaceGetOptions<"arrayBuffer">): Promise; + get(key: Key, options?: KVNamespaceGetOptions<"stream">): Promise; + get(key: Array, type: "text"): Promise>; + get(key: Array, type: "json"): Promise>; + get(key: Array, options?: Partial>): Promise>; + get(key: Array, options?: KVNamespaceGetOptions<"text">): Promise>; + get(key: Array, options?: KVNamespaceGetOptions<"json">): Promise>; + list(options?: KVNamespaceListOptions): Promise>; + put(key: Key, value: string | ArrayBuffer | ArrayBufferView | ReadableStream, options?: KVNamespacePutOptions): Promise; + getWithMetadata(key: Key, options?: Partial>): Promise>; + getWithMetadata(key: Key, type: "text"): Promise>; + getWithMetadata(key: Key, type: "json"): Promise>; + getWithMetadata(key: Key, type: "arrayBuffer"): Promise>; + getWithMetadata(key: Key, type: "stream"): Promise>; + getWithMetadata(key: Key, options: KVNamespaceGetOptions<"text">): Promise>; + getWithMetadata(key: Key, options: KVNamespaceGetOptions<"json">): Promise>; + getWithMetadata(key: Key, options: KVNamespaceGetOptions<"arrayBuffer">): Promise>; + getWithMetadata(key: Key, options: KVNamespaceGetOptions<"stream">): Promise>; + getWithMetadata(key: Array, type: "text"): Promise>>; + getWithMetadata(key: Array, type: "json"): Promise>>; + getWithMetadata(key: Array, options?: Partial>): Promise>>; + getWithMetadata(key: Array, options?: KVNamespaceGetOptions<"text">): Promise>>; + getWithMetadata(key: Array, options?: KVNamespaceGetOptions<"json">): Promise>>; + delete(key: Key): Promise; } interface KVNamespaceListOptions { - limit?: number; - prefix?: string | null; - cursor?: string | null; + limit?: number; + prefix?: (string | null); + cursor?: (string | null); } interface KVNamespaceGetOptions { - type: Type; - cacheTtl?: number; + type: Type; + cacheTtl?: number; } interface KVNamespacePutOptions { - expiration?: number; - expirationTtl?: number; - metadata?: any | null; + expiration?: number; + expirationTtl?: number; + metadata?: (any | null); } interface KVNamespaceGetWithMetadataResult { - value: Value | null; - metadata: Metadata | null; - cacheStatus: string | null; + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; } -type QueueContentType = 'text' | 'bytes' | 'json' | 'v8'; +type QueueContentType = "text" | "bytes" | "json" | "v8"; interface Queue { - send(message: Body, options?: QueueSendOptions): Promise; - sendBatch( - messages: Iterable>, - options?: QueueSendBatchOptions - ): Promise; + send(message: Body, options?: QueueSendOptions): Promise; + sendBatch(messages: Iterable>, options?: QueueSendBatchOptions): Promise; } interface QueueSendOptions { - contentType?: QueueContentType; - delaySeconds?: number; + contentType?: QueueContentType; + delaySeconds?: number; } interface QueueSendBatchOptions { - delaySeconds?: number; + delaySeconds?: number; } interface MessageSendRequest { - body: Body; - contentType?: QueueContentType; - delaySeconds?: number; + body: Body; + contentType?: QueueContentType; + delaySeconds?: number; } interface QueueRetryOptions { - delaySeconds?: number; + delaySeconds?: number; } interface Message { - readonly id: string; - readonly timestamp: Date; - readonly body: Body; - readonly attempts: number; - retry(options?: QueueRetryOptions): void; - ack(): void; + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + readonly attempts: number; + retry(options?: QueueRetryOptions): void; + ack(): void; } interface QueueEvent extends ExtendableEvent { - readonly messages: readonly Message[]; - readonly queue: string; - retryAll(options?: QueueRetryOptions): void; - ackAll(): void; + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; } interface MessageBatch { - readonly messages: readonly Message[]; - readonly queue: string; - retryAll(options?: QueueRetryOptions): void; - ackAll(): void; + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; } interface R2Error extends Error { - readonly name: string; - readonly code: number; - readonly message: string; - readonly action: string; - readonly stack: any; + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; } interface R2ListOptions { - limit?: number; - prefix?: string; - cursor?: string; - delimiter?: string; - startAfter?: string; - include?: ('httpMetadata' | 'customMetadata')[]; + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; + include?: ("httpMetadata" | "customMetadata")[]; } declare abstract class R2Bucket { - head(key: string): Promise; - get( - key: string, - options: R2GetOptions & { - onlyIf: R2Conditional | Headers; - } - ): Promise; - get(key: string, options?: R2GetOptions): Promise; - put( - key: string, - value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, - options?: R2PutOptions & { - onlyIf: R2Conditional | Headers; - } - ): Promise; - put( - key: string, - value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, - options?: R2PutOptions - ): Promise; - createMultipartUpload(key: string, options?: R2MultipartOptions): Promise; - resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; - delete(keys: string | string[]): Promise; - list(options?: R2ListOptions): Promise; + head(key: string): Promise; + get(key: string, options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + }): Promise; + get(key: string, options?: R2GetOptions): Promise; + put(key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + }): Promise; + put(key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions): Promise; + createMultipartUpload(key: string, options?: R2MultipartOptions): Promise; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise; + list(options?: R2ListOptions): Promise; } interface R2MultipartUpload { - readonly key: string; - readonly uploadId: string; - uploadPart( - partNumber: number, - value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, - options?: R2UploadPartOptions - ): Promise; - abort(): Promise; - complete(uploadedParts: R2UploadedPart[]): Promise; + readonly key: string; + readonly uploadId: string; + uploadPart(partNumber: number, value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, options?: R2UploadPartOptions): Promise; + abort(): Promise; + complete(uploadedParts: R2UploadedPart[]): Promise; } interface R2UploadedPart { - partNumber: number; - etag: string; + partNumber: number; + etag: string; } declare abstract class R2Object { - readonly key: string; - readonly version: string; - readonly size: number; - readonly etag: string; - readonly httpEtag: string; - readonly checksums: R2Checksums; - readonly uploaded: Date; - readonly httpMetadata?: R2HTTPMetadata; - readonly customMetadata?: Record; - readonly range?: R2Range; - readonly storageClass: string; - readonly ssecKeyMd5?: string; - writeHttpMetadata(headers: Headers): void; + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record; + readonly range?: R2Range; + readonly storageClass: string; + readonly ssecKeyMd5?: string; + writeHttpMetadata(headers: Headers): void; } interface R2ObjectBody extends R2Object { - get body(): ReadableStream; - get bodyUsed(): boolean; - arrayBuffer(): Promise; - bytes(): Promise; - text(): Promise; - json(): Promise; - blob(): Promise; -} -type R2Range = - | { - offset: number; - length?: number; - } - | { - offset?: number; - length: number; - } - | { - suffix: number; - }; + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + bytes(): Promise; + text(): Promise; + json(): Promise; + blob(): Promise; +} +type R2Range = { + offset: number; + length?: number; +} | { + offset?: number; + length: number; +} | { + suffix: number; +}; interface R2Conditional { - etagMatches?: string; - etagDoesNotMatch?: string; - uploadedBefore?: Date; - uploadedAfter?: Date; - secondsGranularity?: boolean; + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; } interface R2GetOptions { - onlyIf?: R2Conditional | Headers; - range?: R2Range | Headers; - ssecKey?: ArrayBuffer | string; + onlyIf?: (R2Conditional | Headers); + range?: (R2Range | Headers); + ssecKey?: (ArrayBuffer | string); } interface R2PutOptions { - onlyIf?: R2Conditional | Headers; - httpMetadata?: R2HTTPMetadata | Headers; - customMetadata?: Record; - md5?: (ArrayBuffer | ArrayBufferView) | string; - sha1?: (ArrayBuffer | ArrayBufferView) | string; - sha256?: (ArrayBuffer | ArrayBufferView) | string; - sha384?: (ArrayBuffer | ArrayBufferView) | string; - sha512?: (ArrayBuffer | ArrayBufferView) | string; - storageClass?: string; - ssecKey?: ArrayBuffer | string; + onlyIf?: (R2Conditional | Headers); + httpMetadata?: (R2HTTPMetadata | Headers); + customMetadata?: Record; + md5?: ((ArrayBuffer | ArrayBufferView) | string); + sha1?: ((ArrayBuffer | ArrayBufferView) | string); + sha256?: ((ArrayBuffer | ArrayBufferView) | string); + sha384?: ((ArrayBuffer | ArrayBufferView) | string); + sha512?: ((ArrayBuffer | ArrayBufferView) | string); + storageClass?: string; + ssecKey?: (ArrayBuffer | string); } interface R2MultipartOptions { - httpMetadata?: R2HTTPMetadata | Headers; - customMetadata?: Record; - storageClass?: string; - ssecKey?: ArrayBuffer | string; + httpMetadata?: (R2HTTPMetadata | Headers); + customMetadata?: Record; + storageClass?: string; + ssecKey?: (ArrayBuffer | string); } interface R2Checksums { - readonly md5?: ArrayBuffer; - readonly sha1?: ArrayBuffer; - readonly sha256?: ArrayBuffer; - readonly sha384?: ArrayBuffer; - readonly sha512?: ArrayBuffer; - toJSON(): R2StringChecksums; + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; } interface R2StringChecksums { - md5?: string; - sha1?: string; - sha256?: string; - sha384?: string; - sha512?: string; + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; } interface R2HTTPMetadata { - contentType?: string; - contentLanguage?: string; - contentDisposition?: string; - contentEncoding?: string; - cacheControl?: string; - cacheExpiry?: Date; + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; } type R2Objects = { - objects: R2Object[]; - delimitedPrefixes: string[]; -} & ( - | { - truncated: true; - cursor: string; - } - | { - truncated: false; - } -); + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ({ + truncated: true; + cursor: string; +} | { + truncated: false; +}); interface R2UploadPartOptions { - ssecKey?: ArrayBuffer | string; + ssecKey?: (ArrayBuffer | string); } declare abstract class ScheduledEvent extends ExtendableEvent { - readonly scheduledTime: number; - readonly cron: string; - noRetry(): void; + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; } interface ScheduledController { - readonly scheduledTime: number; - readonly cron: string; - noRetry(): void; + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; } interface QueuingStrategy { - highWaterMark?: number | bigint; - size?: (chunk: T) => number | bigint; + highWaterMark?: (number | bigint); + size?: (chunk: T) => number | bigint; } interface UnderlyingSink { - type?: string; - start?: (controller: WritableStreamDefaultController) => void | Promise; - write?: (chunk: W, controller: WritableStreamDefaultController) => void | Promise; - abort?: (reason: any) => void | Promise; - close?: () => void | Promise; + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise; + write?: (chunk: W, controller: WritableStreamDefaultController) => void | Promise; + abort?: (reason: any) => void | Promise; + close?: () => void | Promise; } interface UnderlyingByteSource { - type: 'bytes'; - autoAllocateChunkSize?: number; - start?: (controller: ReadableByteStreamController) => void | Promise; - pull?: (controller: ReadableByteStreamController) => void | Promise; - cancel?: (reason: any) => void | Promise; + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise; + pull?: (controller: ReadableByteStreamController) => void | Promise; + cancel?: (reason: any) => void | Promise; } interface UnderlyingSource { - type?: '' | undefined; - start?: (controller: ReadableStreamDefaultController) => void | Promise; - pull?: (controller: ReadableStreamDefaultController) => void | Promise; - cancel?: (reason: any) => void | Promise; - expectedLength?: number | bigint; + type?: "" | undefined; + start?: (controller: ReadableStreamDefaultController) => void | Promise; + pull?: (controller: ReadableStreamDefaultController) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: (number | bigint); } interface Transformer { - readableType?: string; - writableType?: string; - start?: (controller: TransformStreamDefaultController) => void | Promise; - transform?: (chunk: I, controller: TransformStreamDefaultController) => void | Promise; - flush?: (controller: TransformStreamDefaultController) => void | Promise; - cancel?: (reason: any) => void | Promise; - expectedLength?: number; + readableType?: string; + writableType?: string; + start?: (controller: TransformStreamDefaultController) => void | Promise; + transform?: (chunk: I, controller: TransformStreamDefaultController) => void | Promise; + flush?: (controller: TransformStreamDefaultController) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number; } interface StreamPipeOptions { - preventAbort?: boolean; - preventCancel?: boolean; - /** - * Pipes this readable stream to a given writable stream destination. The way in which the piping process behaves under various error conditions can be customized with a number of passed options. It returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. - * - * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. - * - * Errors and closures of the source and destination streams propagate as follows: - * - * An error in this source readable stream will abort destination, unless preventAbort is truthy. The returned promise will be rejected with the source's error, or with any error that occurs during aborting the destination. - * - * An error in destination will cancel this source readable stream, unless preventCancel is truthy. The returned promise will be rejected with the destination's error, or with any error that occurs during canceling the source. - * - * When this source readable stream closes, destination will be closed, unless preventClose is truthy. The returned promise will be fulfilled once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error. - * - * If destination starts out closed or closing, this source readable stream will be canceled, unless preventCancel is true. The returned promise will be rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. - * - * The signal option can be set to an AbortSignal to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set. - */ - preventClose?: boolean; - signal?: AbortSignal; -} -type ReadableStreamReadResult = - | { - done: false; - value: R; - } - | { - done: true; - value?: undefined; - }; -/** - * The `ReadableStream` interface of the Streams API represents a readable stream of byte data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) + preventAbort?: boolean; + preventCancel?: boolean; + /** + * Pipes this readable stream to a given writable stream destination. The way in which the piping process behaves under various error conditions can be customized with a number of passed options. It returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate as follows: + * + * An error in this source readable stream will abort destination, unless preventAbort is truthy. The returned promise will be rejected with the source's error, or with any error that occurs during aborting the destination. + * + * An error in destination will cancel this source readable stream, unless preventCancel is truthy. The returned promise will be rejected with the destination's error, or with any error that occurs during canceling the source. + * + * When this source readable stream closes, destination will be closed, unless preventClose is truthy. The returned promise will be fulfilled once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error. + * + * If destination starts out closed or closing, this source readable stream will be canceled, unless preventCancel is true. The returned promise will be rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. + * + * The signal option can be set to an AbortSignal to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set. + */ + preventClose?: boolean; + signal?: AbortSignal; +} +type ReadableStreamReadResult = { + done: false; + value: R; +} | { + done: true; + value?: undefined; +}; +/** + * The `ReadableStream` interface of the Streams API represents a readable stream of byte data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) */ interface ReadableStream { - /** - * The **`locked`** read-only property of the ReadableStream interface returns whether or not the readable stream is locked to a reader. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) - */ - get locked(): boolean; - /** - * The **`cancel()`** method of the ReadableStream interface returns a Promise that resolves when the stream is canceled. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) - */ - cancel(reason?: any): Promise; - /** - * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) - */ - getReader(): ReadableStreamDefaultReader; - /** - * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) - */ - getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; - /** - * The **`pipeThrough()`** method of the ReadableStream interface provides a chainable way of piping the current stream through a transform stream or any other writable/readable pair. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) - */ - pipeThrough( - transform: ReadableWritablePair, - options?: StreamPipeOptions - ): ReadableStream; - /** - * The **`pipeTo()`** method of the ReadableStream interface pipes the current `ReadableStream` to a given WritableStream and returns a Promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) - */ - pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; - /** - * The **`tee()`** method of the two-element array containing the two resulting branches as new ReadableStream instances. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) - */ - tee(): [ReadableStream, ReadableStream]; - values(options?: ReadableStreamValuesOptions): AsyncIterableIterator; - [Symbol.asyncIterator](options?: ReadableStreamValuesOptions): AsyncIterableIterator; + /** + * The **`locked`** read-only property of the ReadableStream interface returns whether or not the readable stream is locked to a reader. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) + */ + get locked(): boolean; + /** + * The **`cancel()`** method of the ReadableStream interface returns a Promise that resolves when the stream is canceled. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) + */ + cancel(reason?: any): Promise; + /** + * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) + */ + getReader(): ReadableStreamDefaultReader; + /** + * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) + */ + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + /** + * The **`pipeThrough()`** method of the ReadableStream interface provides a chainable way of piping the current stream through a transform stream or any other writable/readable pair. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) + */ + pipeThrough(transform: ReadableWritablePair, options?: StreamPipeOptions): ReadableStream; + /** + * The **`pipeTo()`** method of the ReadableStream interface pipes the current `ReadableStream` to a given WritableStream and returns a Promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) + */ + pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; + /** + * The **`tee()`** method of the two-element array containing the two resulting branches as new ReadableStream instances. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) + */ + tee(): [ + ReadableStream, + ReadableStream + ]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator; + [Symbol.asyncIterator](options?: ReadableStreamValuesOptions): AsyncIterableIterator; } /** * The `ReadableStream` interface of the Streams API represents a readable stream of byte data. @@ -2504,15 +2216,9 @@ interface ReadableStream { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) */ declare const ReadableStream: { - prototype: ReadableStream; - new ( - underlyingSource: UnderlyingByteSource, - strategy?: QueuingStrategy - ): ReadableStream; - new ( - underlyingSource?: UnderlyingSource, - strategy?: QueuingStrategy - ): ReadableStream; + prototype: ReadableStream; + new (underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy): ReadableStream; + new (underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; }; /** * The **`ReadableStreamDefaultReader`** interface of the Streams API represents a default reader that can be used to read stream data supplied from a network (such as a fetch request). @@ -2520,21 +2226,21 @@ declare const ReadableStream: { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader) */ declare class ReadableStreamDefaultReader { - constructor(stream: ReadableStream); - get closed(): Promise; - cancel(reason?: any): Promise; - /** - * The **`read()`** method of the ReadableStreamDefaultReader interface returns a Promise providing access to the next chunk in the stream's internal queue. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) - */ - read(): Promise>; - /** - * The **`releaseLock()`** method of the ReadableStreamDefaultReader interface releases the reader's lock on the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) - */ - releaseLock(): void; + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** + * The **`read()`** method of the ReadableStreamDefaultReader interface returns a Promise providing access to the next chunk in the stream's internal queue. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) + */ + read(): Promise>; + /** + * The **`releaseLock()`** method of the ReadableStreamDefaultReader interface releases the reader's lock on the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) + */ + releaseLock(): void; } /** * The `ReadableStreamBYOBReader` interface of the Streams API defines a reader for a ReadableStream that supports zero-copy reading from an underlying byte source. @@ -2542,36 +2248,33 @@ declare class ReadableStreamDefaultReader { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader) */ declare class ReadableStreamBYOBReader { - constructor(stream: ReadableStream); - get closed(): Promise; - cancel(reason?: any): Promise; - /** - * The **`read()`** method of the ReadableStreamBYOBReader interface is used to read data into a view on a user-supplied buffer from an associated readable byte stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) - */ - read(view: T): Promise>; - /** - * The **`releaseLock()`** method of the ReadableStreamBYOBReader interface releases the reader's lock on the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) - */ - releaseLock(): void; - readAtLeast( - minElements: number, - view: T - ): Promise>; + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** + * The **`read()`** method of the ReadableStreamBYOBReader interface is used to read data into a view on a user-supplied buffer from an associated readable byte stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) + */ + read(view: T): Promise>; + /** + * The **`releaseLock()`** method of the ReadableStreamBYOBReader interface releases the reader's lock on the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) + */ + releaseLock(): void; + readAtLeast(minElements: number, view: T): Promise>; } interface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions { - min?: number; + min?: number; } interface ReadableStreamGetReaderOptions { - /** - * Creates a ReadableStreamBYOBReader and locks the stream to the new reader. - * - * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. The returned BYOB reader provides the ability to directly read individual chunks from the stream via its read() method, into developer-supplied buffers, allowing more precise control over allocation. - */ - mode: 'byob'; + /** + * Creates a ReadableStreamBYOBReader and locks the stream to the new reader. + * + * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. The returned BYOB reader provides the ability to directly read individual chunks from the stream via its read() method, into developer-supplied buffers, allowing more precise control over allocation. + */ + mode: "byob"; } /** * The **`ReadableStreamBYOBRequest`** interface of the Streams API represents a 'pull request' for data from an underlying source that will made as a zero-copy transfer to a consumer (bypassing the stream's internal queues). @@ -2579,25 +2282,25 @@ interface ReadableStreamGetReaderOptions { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) */ declare abstract class ReadableStreamBYOBRequest { - /** - * The **`view`** getter property of the ReadableStreamBYOBRequest interface returns the current view. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) - */ - get view(): Uint8Array | null; - /** - * The **`respond()`** method of the ReadableStreamBYOBRequest interface is used to signal to the associated readable byte stream that the specified number of bytes were written into the ReadableStreamBYOBRequest.view. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) - */ - respond(bytesWritten: number): void; - /** - * The **`respondWithNewView()`** method of the ReadableStreamBYOBRequest interface specifies a new view that the consumer of the associated readable byte stream should write to instead of ReadableStreamBYOBRequest.view. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) - */ - respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; - get atLeast(): number | null; + /** + * The **`view`** getter property of the ReadableStreamBYOBRequest interface returns the current view. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) + */ + get view(): Uint8Array | null; + /** + * The **`respond()`** method of the ReadableStreamBYOBRequest interface is used to signal to the associated readable byte stream that the specified number of bytes were written into the ReadableStreamBYOBRequest.view. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) + */ + respond(bytesWritten: number): void; + /** + * The **`respondWithNewView()`** method of the ReadableStreamBYOBRequest interface specifies a new view that the consumer of the associated readable byte stream should write to instead of ReadableStreamBYOBRequest.view. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) + */ + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + get atLeast(): number | null; } /** * The **`ReadableStreamDefaultController`** interface of the Streams API represents a controller allowing control of a ReadableStream's state and internal queue. @@ -2605,30 +2308,30 @@ declare abstract class ReadableStreamBYOBRequest { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController) */ declare abstract class ReadableStreamDefaultController { - /** - * The **`desiredSize`** read-only property of the required to fill the stream's internal queue. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) - */ - get desiredSize(): number | null; - /** - * The **`close()`** method of the ReadableStreamDefaultController interface closes the associated stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) - */ - close(): void; - /** - * The **`enqueue()`** method of the ```js-nolint enqueue(chunk) ``` - `chunk` - : The chunk to enqueue. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) - */ - enqueue(chunk?: R): void; - /** - * The **`error()`** method of the with the associated stream to error. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) - */ - error(reason: any): void; + /** + * The **`desiredSize`** read-only property of the required to fill the stream's internal queue. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) + */ + get desiredSize(): number | null; + /** + * The **`close()`** method of the ReadableStreamDefaultController interface closes the associated stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) + */ + close(): void; + /** + * The **`enqueue()`** method of the ```js-nolint enqueue(chunk) ``` - `chunk` - : The chunk to enqueue. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) + */ + enqueue(chunk?: R): void; + /** + * The **`error()`** method of the with the associated stream to error. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) + */ + error(reason: any): void; } /** * The **`ReadableByteStreamController`** interface of the Streams API represents a controller for a readable byte stream. @@ -2636,36 +2339,36 @@ declare abstract class ReadableStreamDefaultController { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController) */ declare abstract class ReadableByteStreamController { - /** - * The **`byobRequest`** read-only property of the ReadableByteStreamController interface returns the current BYOB request, or `null` if there are no pending requests. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) - */ - get byobRequest(): ReadableStreamBYOBRequest | null; - /** - * The **`desiredSize`** read-only property of the ReadableByteStreamController interface returns the number of bytes required to fill the stream's internal queue to its 'desired size'. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) - */ - get desiredSize(): number | null; - /** - * The **`close()`** method of the ReadableByteStreamController interface closes the associated stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) - */ - close(): void; - /** - * The **`enqueue()`** method of the ReadableByteStreamController interface enqueues a given chunk on the associated readable byte stream (the chunk is copied into the stream's internal queues). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) - */ - enqueue(chunk: ArrayBuffer | ArrayBufferView): void; - /** - * The **`error()`** method of the ReadableByteStreamController interface causes any future interactions with the associated stream to error with the specified reason. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) - */ - error(reason: any): void; + /** + * The **`byobRequest`** read-only property of the ReadableByteStreamController interface returns the current BYOB request, or `null` if there are no pending requests. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) + */ + get byobRequest(): ReadableStreamBYOBRequest | null; + /** + * The **`desiredSize`** read-only property of the ReadableByteStreamController interface returns the number of bytes required to fill the stream's internal queue to its 'desired size'. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) + */ + get desiredSize(): number | null; + /** + * The **`close()`** method of the ReadableByteStreamController interface closes the associated stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) + */ + close(): void; + /** + * The **`enqueue()`** method of the ReadableByteStreamController interface enqueues a given chunk on the associated readable byte stream (the chunk is copied into the stream's internal queues). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) + */ + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + /** + * The **`error()`** method of the ReadableByteStreamController interface causes any future interactions with the associated stream to error with the specified reason. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) + */ + error(reason: any): void; } /** * The **`WritableStreamDefaultController`** interface of the Streams API represents a controller allowing control of a WritableStream's state. @@ -2673,18 +2376,18 @@ declare abstract class ReadableByteStreamController { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController) */ declare abstract class WritableStreamDefaultController { - /** - * The read-only **`signal`** property of the WritableStreamDefaultController interface returns the AbortSignal associated with the controller. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) - */ - get signal(): AbortSignal; - /** - * The **`error()`** method of the with the associated stream to error. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) - */ - error(reason?: any): void; + /** + * The read-only **`signal`** property of the WritableStreamDefaultController interface returns the AbortSignal associated with the controller. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) + */ + get signal(): AbortSignal; + /** + * The **`error()`** method of the with the associated stream to error. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) + */ + error(reason?: any): void; } /** * The **`TransformStreamDefaultController`** interface of the Streams API provides methods to manipulate the associated ReadableStream and WritableStream. @@ -2692,39 +2395,39 @@ declare abstract class WritableStreamDefaultController { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) */ declare abstract class TransformStreamDefaultController { - /** - * The **`desiredSize`** read-only property of the TransformStreamDefaultController interface returns the desired size to fill the queue of the associated ReadableStream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) - */ - get desiredSize(): number | null; - /** - * The **`enqueue()`** method of the TransformStreamDefaultController interface enqueues the given chunk in the readable side of the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) - */ - enqueue(chunk?: O): void; - /** - * The **`error()`** method of the TransformStreamDefaultController interface errors both sides of the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) - */ - error(reason: any): void; - /** - * The **`terminate()`** method of the TransformStreamDefaultController interface closes the readable side and errors the writable side of the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) - */ - terminate(): void; + /** + * The **`desiredSize`** read-only property of the TransformStreamDefaultController interface returns the desired size to fill the queue of the associated ReadableStream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) + */ + get desiredSize(): number | null; + /** + * The **`enqueue()`** method of the TransformStreamDefaultController interface enqueues the given chunk in the readable side of the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) + */ + enqueue(chunk?: O): void; + /** + * The **`error()`** method of the TransformStreamDefaultController interface errors both sides of the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) + */ + error(reason: any): void; + /** + * The **`terminate()`** method of the TransformStreamDefaultController interface closes the readable side and errors the writable side of the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) + */ + terminate(): void; } interface ReadableWritablePair { - readable: ReadableStream; - /** - * Provides a convenient, chainable way of piping this readable stream through a transform stream (or any other { writable, readable } pair). It simply pipes the stream into the writable side of the supplied pair, and returns the readable side for further use. - * - * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. - */ - writable: WritableStream; + readable: ReadableStream; + /** + * Provides a convenient, chainable way of piping this readable stream through a transform stream (or any other { writable, readable } pair). It simply pipes the stream into the writable side of the supplied pair, and returns the readable side for further use. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + writable: WritableStream; } /** * The **`WritableStream`** interface of the Streams API provides a standard abstraction for writing streaming data to a destination, known as a sink. @@ -2732,31 +2435,31 @@ interface ReadableWritablePair { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream) */ declare class WritableStream { - constructor(underlyingSink?: UnderlyingSink, queuingStrategy?: QueuingStrategy); - /** - * The **`locked`** read-only property of the WritableStream interface returns a boolean indicating whether the `WritableStream` is locked to a writer. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) - */ - get locked(): boolean; - /** - * The **`abort()`** method of the WritableStream interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) - */ - abort(reason?: any): Promise; - /** - * The **`close()`** method of the WritableStream interface closes the associated stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) - */ - close(): Promise; - /** - * The **`getWriter()`** method of the WritableStream interface returns a new instance of WritableStreamDefaultWriter and locks the stream to that instance. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) - */ - getWriter(): WritableStreamDefaultWriter; + constructor(underlyingSink?: UnderlyingSink, queuingStrategy?: QueuingStrategy); + /** + * The **`locked`** read-only property of the WritableStream interface returns a boolean indicating whether the `WritableStream` is locked to a writer. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) + */ + get locked(): boolean; + /** + * The **`abort()`** method of the WritableStream interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) + */ + abort(reason?: any): Promise; + /** + * The **`close()`** method of the WritableStream interface closes the associated stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) + */ + close(): Promise; + /** + * The **`getWriter()`** method of the WritableStream interface returns a new instance of WritableStreamDefaultWriter and locks the stream to that instance. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) + */ + getWriter(): WritableStreamDefaultWriter; } /** * The **`WritableStreamDefaultWriter`** interface of the Streams API is the object returned by WritableStream.getWriter() and once created locks the writer to the `WritableStream` ensuring that no other streams can write to the underlying sink. @@ -2764,49 +2467,49 @@ declare class WritableStream { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter) */ declare class WritableStreamDefaultWriter { - constructor(stream: WritableStream); - /** - * The **`closed`** read-only property of the the stream errors or the writer's lock is released. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) - */ - get closed(): Promise; - /** - * The **`ready`** read-only property of the that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) - */ - get ready(): Promise; - /** - * The **`desiredSize`** read-only property of the to fill the stream's internal queue. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) - */ - get desiredSize(): number | null; - /** - * The **`abort()`** method of the the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) - */ - abort(reason?: any): Promise; - /** - * The **`close()`** method of the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) - */ - close(): Promise; - /** - * The **`write()`** method of the operation. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) - */ - write(chunk?: W): Promise; - /** - * The **`releaseLock()`** method of the corresponding stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) - */ - releaseLock(): void; + constructor(stream: WritableStream); + /** + * The **`closed`** read-only property of the the stream errors or the writer's lock is released. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) + */ + get closed(): Promise; + /** + * The **`ready`** read-only property of the that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) + */ + get ready(): Promise; + /** + * The **`desiredSize`** read-only property of the to fill the stream's internal queue. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) + */ + get desiredSize(): number | null; + /** + * The **`abort()`** method of the the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) + */ + abort(reason?: any): Promise; + /** + * The **`close()`** method of the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) + */ + close(): Promise; + /** + * The **`write()`** method of the operation. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) + */ + write(chunk?: W): Promise; + /** + * The **`releaseLock()`** method of the corresponding stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) + */ + releaseLock(): void; } /** * The **`TransformStream`** interface of the Streams API represents a concrete implementation of the pipe chain _transform stream_ concept. @@ -2814,41 +2517,31 @@ declare class WritableStreamDefaultWriter { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream) */ declare class TransformStream { - constructor( - transformer?: Transformer, - writableStrategy?: QueuingStrategy, - readableStrategy?: QueuingStrategy - ); - /** - * The **`readable`** read-only property of the TransformStream interface returns the ReadableStream instance controlled by this `TransformStream`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) - */ - get readable(): ReadableStream; - /** - * The **`writable`** read-only property of the TransformStream interface returns the WritableStream instance controlled by this `TransformStream`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) - */ - get writable(): WritableStream; + constructor(transformer?: Transformer, writableStrategy?: QueuingStrategy, readableStrategy?: QueuingStrategy); + /** + * The **`readable`** read-only property of the TransformStream interface returns the ReadableStream instance controlled by this `TransformStream`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) + */ + get readable(): ReadableStream; + /** + * The **`writable`** read-only property of the TransformStream interface returns the WritableStream instance controlled by this `TransformStream`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) + */ + get writable(): WritableStream; } declare class FixedLengthStream extends IdentityTransformStream { - constructor( - expectedLength: number | bigint, - queuingStrategy?: IdentityTransformStreamQueuingStrategy - ); + constructor(expectedLength: number | bigint, queuingStrategy?: IdentityTransformStreamQueuingStrategy); } -declare class IdentityTransformStream extends TransformStream< - ArrayBuffer | ArrayBufferView, - Uint8Array -> { - constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +declare class IdentityTransformStream extends TransformStream { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); } interface IdentityTransformStreamQueuingStrategy { - highWaterMark?: number | bigint; + highWaterMark?: (number | bigint); } interface ReadableStreamValuesOptions { - preventCancel?: boolean; + preventCancel?: boolean; } /** * The **`CompressionStream`** interface of the Compression Streams API is an API for compressing a stream of data. @@ -2856,18 +2549,15 @@ interface ReadableStreamValuesOptions { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CompressionStream) */ declare class CompressionStream extends TransformStream { - constructor(format: 'gzip' | 'deflate' | 'deflate-raw'); + constructor(format: "gzip" | "deflate" | "deflate-raw"); } /** * The **`DecompressionStream`** interface of the Compression Streams API is an API for decompressing a stream of data. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DecompressionStream) */ -declare class DecompressionStream extends TransformStream< - ArrayBuffer | ArrayBufferView, - Uint8Array -> { - constructor(format: 'gzip' | 'deflate' | 'deflate-raw'); +declare class DecompressionStream extends TransformStream { + constructor(format: "gzip" | "deflate" | "deflate-raw"); } /** * The **`TextEncoderStream`** interface of the Encoding API converts a stream of strings into bytes in the UTF-8 encoding. @@ -2875,8 +2565,8 @@ declare class DecompressionStream extends TransformStream< * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoderStream) */ declare class TextEncoderStream extends TransformStream { - constructor(); - get encoding(): string; + constructor(); + get encoding(): string; } /** * The **`TextDecoderStream`** interface of the Encoding API converts a stream of text in a binary encoding, such as UTF-8 etc., to a stream of strings. @@ -2884,14 +2574,14 @@ declare class TextEncoderStream extends TransformStream { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoderStream) */ declare class TextDecoderStream extends TransformStream { - constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); - get encoding(): string; - get fatal(): boolean; - get ignoreBOM(): boolean; + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; } interface TextDecoderStreamTextDecoderStreamInit { - fatal?: boolean; - ignoreBOM?: boolean; + fatal?: boolean; + ignoreBOM?: boolean; } /** * The **`ByteLengthQueuingStrategy`** interface of the Streams API provides a built-in byte length queuing strategy that can be used when constructing streams. @@ -2899,15 +2589,15 @@ interface TextDecoderStreamTextDecoderStreamInit { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy) */ declare class ByteLengthQueuingStrategy implements QueuingStrategy { - constructor(init: QueuingStrategyInit); - /** - * The read-only **`ByteLengthQueuingStrategy.highWaterMark`** property returns the total number of bytes that can be contained in the internal queue before backpressure is applied. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) - */ - get highWaterMark(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */ - get size(): (chunk?: any) => number; + constructor(init: QueuingStrategyInit); + /** + * The read-only **`ByteLengthQueuingStrategy.highWaterMark`** property returns the total number of bytes that can be contained in the internal queue before backpressure is applied. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) + */ + get highWaterMark(): number; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */ + get size(): (chunk?: any) => number; } /** * The **`CountQueuingStrategy`** interface of the Streams API provides a built-in chunk counting queuing strategy that can be used when constructing streams. @@ -2915,142 +2605,128 @@ declare class ByteLengthQueuingStrategy implements QueuingStrategy number; + constructor(init: QueuingStrategyInit); + /** + * The read-only **`CountQueuingStrategy.highWaterMark`** property returns the total number of chunks that can be contained in the internal queue before backpressure is applied. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark) + */ + get highWaterMark(): number; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */ + get size(): (chunk?: any) => number; } interface QueuingStrategyInit { - /** - * Creates a new ByteLengthQueuingStrategy with the provided high water mark. - * - * Note that the provided high water mark will not be validated ahead of time. Instead, if it is negative, NaN, or not a number, the resulting ByteLengthQueuingStrategy will cause the corresponding stream constructor to throw. - */ - highWaterMark: number; + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water mark. + * + * Note that the provided high water mark will not be validated ahead of time. Instead, if it is negative, NaN, or not a number, the resulting ByteLengthQueuingStrategy will cause the corresponding stream constructor to throw. + */ + highWaterMark: number; } interface ScriptVersion { - id?: string; - tag?: string; - message?: string; + id?: string; + tag?: string; + message?: string; } declare abstract class TailEvent extends ExtendableEvent { - readonly events: TraceItem[]; - readonly traces: TraceItem[]; + readonly events: TraceItem[]; + readonly traces: TraceItem[]; } interface TraceItem { - readonly event: - | ( - | TraceItemFetchEventInfo - | TraceItemJsRpcEventInfo - | TraceItemScheduledEventInfo - | TraceItemAlarmEventInfo - | TraceItemQueueEventInfo - | TraceItemEmailEventInfo - | TraceItemTailEventInfo - | TraceItemCustomEventInfo - | TraceItemHibernatableWebSocketEventInfo - ) - | null; - readonly eventTimestamp: number | null; - readonly logs: TraceLog[]; - readonly exceptions: TraceException[]; - readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; - readonly scriptName: string | null; - readonly entrypoint?: string; - readonly scriptVersion?: ScriptVersion; - readonly dispatchNamespace?: string; - readonly scriptTags?: string[]; - readonly durableObjectId?: string; - readonly outcome: string; - readonly executionModel: string; - readonly truncated: boolean; - readonly cpuTime: number; - readonly wallTime: number; + readonly event: (TraceItemFetchEventInfo | TraceItemJsRpcEventInfo | TraceItemScheduledEventInfo | TraceItemAlarmEventInfo | TraceItemQueueEventInfo | TraceItemEmailEventInfo | TraceItemTailEventInfo | TraceItemCustomEventInfo | TraceItemHibernatableWebSocketEventInfo) | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly entrypoint?: string; + readonly scriptVersion?: ScriptVersion; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly durableObjectId?: string; + readonly outcome: string; + readonly executionModel: string; + readonly truncated: boolean; + readonly cpuTime: number; + readonly wallTime: number; } interface TraceItemAlarmEventInfo { - readonly scheduledTime: Date; + readonly scheduledTime: Date; +} +interface TraceItemCustomEventInfo { } -interface TraceItemCustomEventInfo {} interface TraceItemScheduledEventInfo { - readonly scheduledTime: number; - readonly cron: string; + readonly scheduledTime: number; + readonly cron: string; } interface TraceItemQueueEventInfo { - readonly queue: string; - readonly batchSize: number; + readonly queue: string; + readonly batchSize: number; } interface TraceItemEmailEventInfo { - readonly mailFrom: string; - readonly rcptTo: string; - readonly rawSize: number; + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; } interface TraceItemTailEventInfo { - readonly consumedEvents: TraceItemTailEventInfoTailItem[]; + readonly consumedEvents: TraceItemTailEventInfoTailItem[]; } interface TraceItemTailEventInfoTailItem { - readonly scriptName: string | null; + readonly scriptName: string | null; } interface TraceItemFetchEventInfo { - readonly response?: TraceItemFetchEventInfoResponse; - readonly request: TraceItemFetchEventInfoRequest; + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; } interface TraceItemFetchEventInfoRequest { - readonly cf?: any; - readonly headers: Record; - readonly method: string; - readonly url: string; - getUnredacted(): TraceItemFetchEventInfoRequest; + readonly cf?: any; + readonly headers: Record; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; } interface TraceItemFetchEventInfoResponse { - readonly status: number; + readonly status: number; } interface TraceItemJsRpcEventInfo { - readonly rpcMethod: string; + readonly rpcMethod: string; } interface TraceItemHibernatableWebSocketEventInfo { - readonly getWebSocketEvent: - | TraceItemHibernatableWebSocketEventInfoMessage - | TraceItemHibernatableWebSocketEventInfoClose - | TraceItemHibernatableWebSocketEventInfoError; + readonly getWebSocketEvent: TraceItemHibernatableWebSocketEventInfoMessage | TraceItemHibernatableWebSocketEventInfoClose | TraceItemHibernatableWebSocketEventInfoError; } interface TraceItemHibernatableWebSocketEventInfoMessage { - readonly webSocketEventType: string; + readonly webSocketEventType: string; } interface TraceItemHibernatableWebSocketEventInfoClose { - readonly webSocketEventType: string; - readonly code: number; - readonly wasClean: boolean; + readonly webSocketEventType: string; + readonly code: number; + readonly wasClean: boolean; } interface TraceItemHibernatableWebSocketEventInfoError { - readonly webSocketEventType: string; + readonly webSocketEventType: string; } interface TraceLog { - readonly timestamp: number; - readonly level: string; - readonly message: any; + readonly timestamp: number; + readonly level: string; + readonly message: any; } interface TraceException { - readonly timestamp: number; - readonly message: string; - readonly name: string; - readonly stack?: string; + readonly timestamp: number; + readonly message: string; + readonly name: string; + readonly stack?: string; } interface TraceDiagnosticChannelEvent { - readonly timestamp: number; - readonly channel: string; - readonly message: any; + readonly timestamp: number; + readonly channel: string; + readonly message: any; } interface TraceMetrics { - readonly cpuTime: number; - readonly wallTime: number; + readonly cpuTime: number; + readonly wallTime: number; } interface UnsafeTraceMetrics { - fromTrace(item: TraceItem): TraceMetrics; + fromTrace(item: TraceItem): TraceMetrics; } /** * The **`URL`** interface is used to parse, construct, normalize, and encode URL. @@ -3058,515 +2734,510 @@ interface UnsafeTraceMetrics { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL) */ declare class URL { - constructor(url: string | URL, base?: string | URL); - /** - * The **`origin`** read-only property of the URL interface returns a string containing the Unicode serialization of the origin of the represented URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) - */ - get origin(): string; - /** - * The **`href`** property of the URL interface is a string containing the whole URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) - */ - get href(): string; - /** - * The **`href`** property of the URL interface is a string containing the whole URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) - */ - set href(value: string); - /** - * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final `':'`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) - */ - get protocol(): string; - /** - * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final `':'`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) - */ - set protocol(value: string); - /** - * The **`username`** property of the URL interface is a string containing the username component of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) - */ - get username(): string; - /** - * The **`username`** property of the URL interface is a string containing the username component of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) - */ - set username(value: string); - /** - * The **`password`** property of the URL interface is a string containing the password component of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) - */ - get password(): string; - /** - * The **`password`** property of the URL interface is a string containing the password component of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) - */ - set password(value: string); - /** - * The **`host`** property of the URL interface is a string containing the host, which is the URL.hostname, and then, if the port of the URL is nonempty, a `':'`, followed by the URL.port of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) - */ - get host(): string; - /** - * The **`host`** property of the URL interface is a string containing the host, which is the URL.hostname, and then, if the port of the URL is nonempty, a `':'`, followed by the URL.port of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) - */ - set host(value: string); - /** - * The **`hostname`** property of the URL interface is a string containing either the domain name or IP address of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) - */ - get hostname(): string; - /** - * The **`hostname`** property of the URL interface is a string containing either the domain name or IP address of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) - */ - set hostname(value: string); - /** - * The **`port`** property of the URL interface is a string containing the port number of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) - */ - get port(): string; - /** - * The **`port`** property of the URL interface is a string containing the port number of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) - */ - set port(value: string); - /** - * The **`pathname`** property of the URL interface represents a location in a hierarchical structure. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) - */ - get pathname(): string; - /** - * The **`pathname`** property of the URL interface represents a location in a hierarchical structure. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) - */ - set pathname(value: string); - /** - * The **`search`** property of the URL interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) - */ - get search(): string; - /** - * The **`search`** property of the URL interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) - */ - set search(value: string); - /** - * The **`hash`** property of the URL interface is a string containing a `'#'` followed by the fragment identifier of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) - */ - get hash(): string; - /** - * The **`hash`** property of the URL interface is a string containing a `'#'` followed by the fragment identifier of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) - */ - set hash(value: string); - /** - * The **`searchParams`** read-only property of the access to the [MISSING: httpmethod('GET')] decoded query arguments contained in the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) - */ - get searchParams(): URLSearchParams; - /** - * The **`toJSON()`** method of the URL interface returns a string containing a serialized version of the URL, although in practice it seems to have the same effect as ```js-nolint toJSON() ``` None. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) - */ - toJSON(): string; - /*function toString() { [native code] }*/ - toString(): string; - /** - * The **`URL.canParse()`** static method of the URL interface returns a boolean indicating whether or not an absolute URL, or a relative URL combined with a base URL, are parsable and valid. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/canParse_static) - */ - static canParse(url: string, base?: string): boolean; - /** - * The **`URL.parse()`** static method of the URL interface returns a newly created URL object representing the URL defined by the parameters. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/parse_static) - */ - static parse(url: string, base?: string): URL | null; - /** - * The **`createObjectURL()`** static method of the URL interface creates a string containing a URL representing the object given in the parameter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/createObjectURL_static) - */ - static createObjectURL(object: File | Blob): string; - /** - * The **`revokeObjectURL()`** static method of the URL interface releases an existing object URL which was previously created by calling Call this method when you've finished using an object URL to let the browser know not to keep the reference to the file any longer. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/revokeObjectURL_static) - */ - static revokeObjectURL(object_url: string): void; -} -/** - * The **`URLSearchParams`** interface defines utility methods to work with the query string of a URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams) - */ -declare class URLSearchParams { - constructor(init?: Iterable> | Record | string); - /** - * The **`size`** read-only property of the URLSearchParams interface indicates the total number of search parameter entries. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/size) - */ - get size(): number; - /** - * The **`append()`** method of the URLSearchParams interface appends a specified key/value pair as a new search parameter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/append) - */ - append(name: string, value: string): void; - /** - * The **`delete()`** method of the URLSearchParams interface deletes specified parameters and their associated value(s) from the list of all search parameters. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/delete) - */ - delete(name: string, value?: string): void; - /** - * The **`get()`** method of the URLSearchParams interface returns the first value associated to the given search parameter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/get) - */ - get(name: string): string | null; - /** - * The **`getAll()`** method of the URLSearchParams interface returns all the values associated with a given search parameter as an array. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/getAll) - */ - getAll(name: string): string[]; - /** - * The **`has()`** method of the URLSearchParams interface returns a boolean value that indicates whether the specified parameter is in the search parameters. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/has) - */ - has(name: string, value?: string): boolean; - /** - * The **`set()`** method of the URLSearchParams interface sets the value associated with a given search parameter to the given value. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/set) - */ - set(name: string, value: string): void; - /** - * The **`URLSearchParams.sort()`** method sorts all key/value pairs contained in this object in place and returns `undefined`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/sort) - */ - sort(): void; - /* Returns an array of key, value pairs for every entry in the search params. */ - entries(): IterableIterator<[key: string, value: string]>; - /* Returns a list of keys in the search params. */ - keys(): IterableIterator; - /* Returns a list of values in the search params. */ - values(): IterableIterator; - forEach( - callback: (this: This, value: string, key: string, parent: URLSearchParams) => void, - thisArg?: This - ): void; - /*function toString() { [native code] }*/ - toString(): string; - [Symbol.iterator](): IterableIterator<[key: string, value: string]>; -} -declare class URLPattern { - constructor( - input?: string | URLPatternInit, - baseURL?: string | URLPatternOptions, - patternOptions?: URLPatternOptions - ); - get protocol(): string; - get username(): string; - get password(): string; - get hostname(): string; - get port(): string; - get pathname(): string; - get search(): string; - get hash(): string; - get hasRegExpGroups(): boolean; - test(input?: string | URLPatternInit, baseURL?: string): boolean; - exec(input?: string | URLPatternInit, baseURL?: string): URLPatternResult | null; -} -interface URLPatternInit { - protocol?: string; - username?: string; - password?: string; - hostname?: string; - port?: string; - pathname?: string; - search?: string; - hash?: string; - baseURL?: string; -} -interface URLPatternComponentResult { - input: string; - groups: Record; -} -interface URLPatternResult { - inputs: (string | URLPatternInit)[]; - protocol: URLPatternComponentResult; - username: URLPatternComponentResult; - password: URLPatternComponentResult; - hostname: URLPatternComponentResult; - port: URLPatternComponentResult; - pathname: URLPatternComponentResult; - search: URLPatternComponentResult; - hash: URLPatternComponentResult; -} -interface URLPatternOptions { - ignoreCase?: boolean; -} -/** - * A `CloseEvent` is sent to clients using WebSockets when the connection is closed. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent) - */ -declare class CloseEvent extends Event { - constructor(type: string, initializer?: CloseEventInit); - /** - * The **`code`** read-only property of the CloseEvent interface returns a WebSocket connection close code indicating the reason the connection was closed. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code) - */ - readonly code: number; - /** - * The **`reason`** read-only property of the CloseEvent interface returns the WebSocket connection close reason the server gave for closing the connection; that is, a concise human-readable prose explanation for the closure. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason) - */ - readonly reason: string; - /** - * The **`wasClean`** read-only property of the CloseEvent interface returns `true` if the connection closed cleanly. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean) - */ - readonly wasClean: boolean; -} -interface CloseEventInit { - code?: number; - reason?: string; - wasClean?: boolean; -} -type WebSocketEventMap = { - close: CloseEvent; - message: MessageEvent; - open: Event; - error: ErrorEvent; -}; -/** - * The `WebSocket` object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket) - */ -declare var WebSocket: { - prototype: WebSocket; - new (url: string, protocols?: string[] | string): WebSocket; - readonly READY_STATE_CONNECTING: number; - readonly CONNECTING: number; - readonly READY_STATE_OPEN: number; - readonly OPEN: number; - readonly READY_STATE_CLOSING: number; - readonly CLOSING: number; - readonly READY_STATE_CLOSED: number; - readonly CLOSED: number; -}; -/** - * The `WebSocket` object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket) - */ -interface WebSocket extends EventTarget { - accept(): void; - /** - * The **`WebSocket.send()`** method enqueues the specified data to be transmitted to the server over the WebSocket connection, increasing the value of `bufferedAmount` by the number of bytes needed to contain the data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send) - */ - send(message: (ArrayBuffer | ArrayBufferView) | string): void; - /** - * The **`WebSocket.close()`** method closes the already `CLOSED`, this method does nothing. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) - */ - close(code?: number, reason?: string): void; - serializeAttachment(attachment: any): void; - deserializeAttachment(): any | null; - /** - * The **`WebSocket.readyState`** read-only property returns the current state of the WebSocket connection. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState) - */ - readyState: number; - /** - * The **`WebSocket.url`** read-only property returns the absolute URL of the WebSocket as resolved by the constructor. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url) - */ - url: string | null; - /** - * The **`WebSocket.protocol`** read-only property returns the name of the sub-protocol the server selected; this will be one of the strings specified in the `protocols` parameter when creating the WebSocket object, or the empty string if no connection is established. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol) - */ - protocol: string | null; - /** - * The **`WebSocket.extensions`** read-only property returns the extensions selected by the server. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) - */ - extensions: string | null; -} -declare const WebSocketPair: { - new (): { - 0: WebSocket; - 1: WebSocket; - }; -}; -interface SqlStorage { - exec>( - query: string, - ...bindings: any[] - ): SqlStorageCursor; - get databaseSize(): number; - Cursor: typeof SqlStorageCursor; - Statement: typeof SqlStorageStatement; -} -declare abstract class SqlStorageStatement {} -type SqlStorageValue = ArrayBuffer | string | number | null; -declare abstract class SqlStorageCursor> { - next(): - | { - done?: false; - value: T; - } - | { - done: true; - value?: never; - }; - toArray(): T[]; - one(): T; - raw(): IterableIterator; - columnNames: string[]; - get rowsRead(): number; - get rowsWritten(): number; - [Symbol.iterator](): IterableIterator; -} -interface Socket { - get readable(): ReadableStream; - get writable(): WritableStream; - get closed(): Promise; - get opened(): Promise; - get upgraded(): boolean; - get secureTransport(): 'on' | 'off' | 'starttls'; - close(): Promise; - startTls(options?: TlsOptions): Socket; -} -interface SocketOptions { - secureTransport?: string; - allowHalfOpen: boolean; - highWaterMark?: number | bigint; -} -interface SocketAddress { - hostname: string; - port: number; -} -interface TlsOptions { - expectedServerHostname?: string; -} -interface SocketInfo { - remoteAddress?: string; - localAddress?: string; -} -/** - * The **`EventSource`** interface is web content's interface to server-sent events. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource) - */ -declare class EventSource extends EventTarget { - constructor(url: string, init?: EventSourceEventSourceInit); - /** - * The **`close()`** method of the EventSource interface closes the connection, if one is made, and sets the ```js-nolint close() ``` None. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close) - */ - close(): void; - /** - * The **`url`** read-only property of the URL of the source. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url) - */ - get url(): string; - /** - * The **`withCredentials`** read-only property of the the `EventSource` object was instantiated with CORS credentials set. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials) - */ - get withCredentials(): boolean; - /** - * The **`readyState`** read-only property of the connection. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState) - */ - get readyState(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ - get onopen(): any | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ - set onopen(value: any | null); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ - get onmessage(): any | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ - set onmessage(value: any | null); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ - get onerror(): any | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ - set onerror(value: any | null); - static readonly CONNECTING: number; - static readonly OPEN: number; - static readonly CLOSED: number; - static from(stream: ReadableStream): EventSource; -} -interface EventSourceEventSourceInit { - withCredentials?: boolean; - fetcher?: Fetcher; -} -interface Container { - get running(): boolean; - start(options?: ContainerStartupOptions): void; - monitor(): Promise; - destroy(error?: any): Promise; - signal(signo: number): void; - getTcpPort(port: number): Fetcher; - setInactivityTimeout(durationMs: number | bigint): Promise; + constructor(url: string | URL, base?: string | URL); + /** + * The **`origin`** read-only property of the URL interface returns a string containing the Unicode serialization of the origin of the represented URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) + */ + get origin(): string; + /** + * The **`href`** property of the URL interface is a string containing the whole URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) + */ + get href(): string; + /** + * The **`href`** property of the URL interface is a string containing the whole URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) + */ + set href(value: string); + /** + * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final `':'`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) + */ + get protocol(): string; + /** + * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final `':'`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) + */ + set protocol(value: string); + /** + * The **`username`** property of the URL interface is a string containing the username component of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) + */ + get username(): string; + /** + * The **`username`** property of the URL interface is a string containing the username component of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) + */ + set username(value: string); + /** + * The **`password`** property of the URL interface is a string containing the password component of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) + */ + get password(): string; + /** + * The **`password`** property of the URL interface is a string containing the password component of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) + */ + set password(value: string); + /** + * The **`host`** property of the URL interface is a string containing the host, which is the URL.hostname, and then, if the port of the URL is nonempty, a `':'`, followed by the URL.port of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) + */ + get host(): string; + /** + * The **`host`** property of the URL interface is a string containing the host, which is the URL.hostname, and then, if the port of the URL is nonempty, a `':'`, followed by the URL.port of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) + */ + set host(value: string); + /** + * The **`hostname`** property of the URL interface is a string containing either the domain name or IP address of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) + */ + get hostname(): string; + /** + * The **`hostname`** property of the URL interface is a string containing either the domain name or IP address of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) + */ + set hostname(value: string); + /** + * The **`port`** property of the URL interface is a string containing the port number of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) + */ + get port(): string; + /** + * The **`port`** property of the URL interface is a string containing the port number of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) + */ + set port(value: string); + /** + * The **`pathname`** property of the URL interface represents a location in a hierarchical structure. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) + */ + get pathname(): string; + /** + * The **`pathname`** property of the URL interface represents a location in a hierarchical structure. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) + */ + set pathname(value: string); + /** + * The **`search`** property of the URL interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) + */ + get search(): string; + /** + * The **`search`** property of the URL interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) + */ + set search(value: string); + /** + * The **`hash`** property of the URL interface is a string containing a `'#'` followed by the fragment identifier of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) + */ + get hash(): string; + /** + * The **`hash`** property of the URL interface is a string containing a `'#'` followed by the fragment identifier of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) + */ + set hash(value: string); + /** + * The **`searchParams`** read-only property of the access to the [MISSING: httpmethod('GET')] decoded query arguments contained in the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) + */ + get searchParams(): URLSearchParams; + /** + * The **`toJSON()`** method of the URL interface returns a string containing a serialized version of the URL, although in practice it seems to have the same effect as ```js-nolint toJSON() ``` None. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) + */ + toJSON(): string; + /*function toString() { [native code] }*/ + toString(): string; + /** + * The **`URL.canParse()`** static method of the URL interface returns a boolean indicating whether or not an absolute URL, or a relative URL combined with a base URL, are parsable and valid. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/canParse_static) + */ + static canParse(url: string, base?: string): boolean; + /** + * The **`URL.parse()`** static method of the URL interface returns a newly created URL object representing the URL defined by the parameters. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/parse_static) + */ + static parse(url: string, base?: string): URL | null; + /** + * The **`createObjectURL()`** static method of the URL interface creates a string containing a URL representing the object given in the parameter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/createObjectURL_static) + */ + static createObjectURL(object: File | Blob): string; + /** + * The **`revokeObjectURL()`** static method of the URL interface releases an existing object URL which was previously created by calling Call this method when you've finished using an object URL to let the browser know not to keep the reference to the file any longer. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/revokeObjectURL_static) + */ + static revokeObjectURL(object_url: string): void; +} +/** + * The **`URLSearchParams`** interface defines utility methods to work with the query string of a URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams) + */ +declare class URLSearchParams { + constructor(init?: (Iterable> | Record | string)); + /** + * The **`size`** read-only property of the URLSearchParams interface indicates the total number of search parameter entries. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/size) + */ + get size(): number; + /** + * The **`append()`** method of the URLSearchParams interface appends a specified key/value pair as a new search parameter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/append) + */ + append(name: string, value: string): void; + /** + * The **`delete()`** method of the URLSearchParams interface deletes specified parameters and their associated value(s) from the list of all search parameters. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/delete) + */ + delete(name: string, value?: string): void; + /** + * The **`get()`** method of the URLSearchParams interface returns the first value associated to the given search parameter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/get) + */ + get(name: string): string | null; + /** + * The **`getAll()`** method of the URLSearchParams interface returns all the values associated with a given search parameter as an array. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/getAll) + */ + getAll(name: string): string[]; + /** + * The **`has()`** method of the URLSearchParams interface returns a boolean value that indicates whether the specified parameter is in the search parameters. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/has) + */ + has(name: string, value?: string): boolean; + /** + * The **`set()`** method of the URLSearchParams interface sets the value associated with a given search parameter to the given value. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/set) + */ + set(name: string, value: string): void; + /** + * The **`URLSearchParams.sort()`** method sorts all key/value pairs contained in this object in place and returns `undefined`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/sort) + */ + sort(): void; + /* Returns an array of key, value pairs for every entry in the search params. */ + entries(): IterableIterator<[ + key: string, + value: string + ]>; + /* Returns a list of keys in the search params. */ + keys(): IterableIterator; + /* Returns a list of values in the search params. */ + values(): IterableIterator; + forEach(callback: (this: This, value: string, key: string, parent: URLSearchParams) => void, thisArg?: This): void; + /*function toString() { [native code] }*/ + toString(): string; + [Symbol.iterator](): IterableIterator<[ + key: string, + value: string + ]>; +} +declare class URLPattern { + constructor(input?: (string | URLPatternInit), baseURL?: (string | URLPatternOptions), patternOptions?: URLPatternOptions); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + get hasRegExpGroups(): boolean; + test(input?: (string | URLPatternInit), baseURL?: string): boolean; + exec(input?: (string | URLPatternInit), baseURL?: string): URLPatternResult | null; +} +interface URLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +interface URLPatternComponentResult { + input: string; + groups: Record; +} +interface URLPatternResult { + inputs: (string | URLPatternInit)[]; + protocol: URLPatternComponentResult; + username: URLPatternComponentResult; + password: URLPatternComponentResult; + hostname: URLPatternComponentResult; + port: URLPatternComponentResult; + pathname: URLPatternComponentResult; + search: URLPatternComponentResult; + hash: URLPatternComponentResult; +} +interface URLPatternOptions { + ignoreCase?: boolean; +} +/** + * A `CloseEvent` is sent to clients using WebSockets when the connection is closed. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent) + */ +declare class CloseEvent extends Event { + constructor(type: string, initializer?: CloseEventInit); + /** + * The **`code`** read-only property of the CloseEvent interface returns a WebSocket connection close code indicating the reason the connection was closed. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code) + */ + readonly code: number; + /** + * The **`reason`** read-only property of the CloseEvent interface returns the WebSocket connection close reason the server gave for closing the connection; that is, a concise human-readable prose explanation for the closure. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason) + */ + readonly reason: string; + /** + * The **`wasClean`** read-only property of the CloseEvent interface returns `true` if the connection closed cleanly. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean) + */ + readonly wasClean: boolean; +} +interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +/** + * The `WebSocket` object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket) + */ +declare var WebSocket: { + prototype: WebSocket; + new (url: string, protocols?: (string[] | string)): WebSocket; + readonly READY_STATE_CONNECTING: number; + readonly CONNECTING: number; + readonly READY_STATE_OPEN: number; + readonly OPEN: number; + readonly READY_STATE_CLOSING: number; + readonly CLOSING: number; + readonly READY_STATE_CLOSED: number; + readonly CLOSED: number; +}; +/** + * The `WebSocket` object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket) + */ +interface WebSocket extends EventTarget { + accept(): void; + /** + * The **`WebSocket.send()`** method enqueues the specified data to be transmitted to the server over the WebSocket connection, increasing the value of `bufferedAmount` by the number of bytes needed to contain the data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send) + */ + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + /** + * The **`WebSocket.close()`** method closes the already `CLOSED`, this method does nothing. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) + */ + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + /** + * The **`WebSocket.readyState`** read-only property returns the current state of the WebSocket connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState) + */ + readyState: number; + /** + * The **`WebSocket.url`** read-only property returns the absolute URL of the WebSocket as resolved by the constructor. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url) + */ + url: string | null; + /** + * The **`WebSocket.protocol`** read-only property returns the name of the sub-protocol the server selected; this will be one of the strings specified in the `protocols` parameter when creating the WebSocket object, or the empty string if no connection is established. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol) + */ + protocol: string | null; + /** + * The **`WebSocket.extensions`** read-only property returns the extensions selected by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) + */ + extensions: string | null; +} +declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +interface SqlStorage { + exec>(query: string, ...bindings: any[]): SqlStorageCursor; + get databaseSize(): number; + Cursor: typeof SqlStorageCursor; + Statement: typeof SqlStorageStatement; +} +declare abstract class SqlStorageStatement { +} +type SqlStorageValue = ArrayBuffer | string | number | null; +declare abstract class SqlStorageCursor> { + next(): { + done?: false; + value: T; + } | { + done: true; + value?: never; + }; + toArray(): T[]; + one(): T; + raw(): IterableIterator; + columnNames: string[]; + get rowsRead(): number; + get rowsWritten(): number; + [Symbol.iterator](): IterableIterator; +} +interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise; + get opened(): Promise; + get upgraded(): boolean; + get secureTransport(): "on" | "off" | "starttls"; + close(): Promise; + startTls(options?: TlsOptions): Socket; +} +interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; + highWaterMark?: (number | bigint); +} +interface SocketAddress { + hostname: string; + port: number; +} +interface TlsOptions { + expectedServerHostname?: string; +} +interface SocketInfo { + remoteAddress?: string; + localAddress?: string; +} +/** + * The **`EventSource`** interface is web content's interface to server-sent events. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource) + */ +declare class EventSource extends EventTarget { + constructor(url: string, init?: EventSourceEventSourceInit); + /** + * The **`close()`** method of the EventSource interface closes the connection, if one is made, and sets the ```js-nolint close() ``` None. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close) + */ + close(): void; + /** + * The **`url`** read-only property of the URL of the source. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url) + */ + get url(): string; + /** + * The **`withCredentials`** read-only property of the the `EventSource` object was instantiated with CORS credentials set. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials) + */ + get withCredentials(): boolean; + /** + * The **`readyState`** read-only property of the connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState) + */ + get readyState(): number; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ + get onopen(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ + set onopen(value: any | null); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ + get onmessage(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ + set onmessage(value: any | null); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ + get onerror(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ + set onerror(value: any | null); + static readonly CONNECTING: number; + static readonly OPEN: number; + static readonly CLOSED: number; + static from(stream: ReadableStream): EventSource; +} +interface EventSourceEventSourceInit { + withCredentials?: boolean; + fetcher?: Fetcher; +} +interface Container { + get running(): boolean; + start(options?: ContainerStartupOptions): void; + monitor(): Promise; + destroy(error?: any): Promise; + signal(signo: number): void; + getTcpPort(port: number): Fetcher; + setInactivityTimeout(durationMs: number | bigint): Promise; } interface ContainerStartupOptions { - entrypoint?: string[]; - enableInternet: boolean; - env?: Record; - hardTimeout?: number | bigint; + entrypoint?: string[]; + enableInternet: boolean; + env?: Record; + hardTimeout?: (number | bigint); } /** * The **`MessagePort`** interface of the Channel Messaging API represents one of the two ports of a MessageChannel, allowing messages to be sent from one port and listening out for them arriving at the other. @@ -3574,26 +3245,26 @@ interface ContainerStartupOptions { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort) */ declare abstract class MessagePort extends EventTarget { - /** - * The **`postMessage()`** method of the transfers ownership of objects to other browsing contexts. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/postMessage) - */ - postMessage(data?: any, options?: any[] | MessagePortPostMessageOptions): void; - /** - * The **`close()`** method of the MessagePort interface disconnects the port, so it is no longer active. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/close) - */ - close(): void; - /** - * The **`start()`** method of the MessagePort interface starts the sending of messages queued on the port. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/start) - */ - start(): void; - get onmessage(): any | null; - set onmessage(value: any | null); + /** + * The **`postMessage()`** method of the transfers ownership of objects to other browsing contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/postMessage) + */ + postMessage(data?: any, options?: (any[] | MessagePortPostMessageOptions)): void; + /** + * The **`close()`** method of the MessagePort interface disconnects the port, so it is no longer active. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/close) + */ + close(): void; + /** + * The **`start()`** method of the MessagePort interface starts the sending of messages queued on the port. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/start) + */ + start(): void; + get onmessage(): any | null; + set onmessage(value: any | null); } /** * The **`MessageChannel`** interface of the Channel Messaging API allows us to create a new message channel and send data through it via its two MessagePort properties. @@ -3601,373 +3272,533 @@ declare abstract class MessagePort extends EventTarget { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel) */ declare class MessageChannel { - constructor(); - /** - * The **`port1`** read-only property of the the port attached to the context that originated the channel. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port1) - */ - readonly port1: MessagePort; - /** - * The **`port2`** read-only property of the the port attached to the context at the other end of the channel, which the message is initially sent to. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port2) - */ - readonly port2: MessagePort; + constructor(); + /** + * The **`port1`** read-only property of the the port attached to the context that originated the channel. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port1) + */ + readonly port1: MessagePort; + /** + * The **`port2`** read-only property of the the port attached to the context at the other end of the channel, which the message is initially sent to. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port2) + */ + readonly port2: MessagePort; } interface MessagePortPostMessageOptions { - transfer?: any[]; -} -type LoopbackForExport< - T extends - | (new (...args: any[]) => Rpc.EntrypointBranded) - | ExportedHandler - | undefined = undefined, -> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded - ? LoopbackServiceStub> - : T extends new (...args: any[]) => Rpc.DurableObjectBranded - ? LoopbackDurableObjectClass> - : T extends ExportedHandler - ? LoopbackServiceStub - : undefined; -type LoopbackServiceStub = - Fetcher & - (T extends CloudflareWorkersModule.WorkerEntrypoint - ? (opts: { props?: Props }) => Fetcher - : (opts: { props?: any }) => Fetcher); -type LoopbackDurableObjectClass = - DurableObjectClass & - (T extends CloudflareWorkersModule.DurableObject - ? (opts: { props?: Props }) => DurableObjectClass - : (opts: { props?: any }) => DurableObjectClass); + transfer?: any[]; +} +type LoopbackForExport Rpc.EntrypointBranded) | ExportedHandler | undefined = undefined> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded ? LoopbackServiceStub> : T extends new (...args: any[]) => Rpc.DurableObjectBranded ? LoopbackDurableObjectClass> : T extends ExportedHandler ? LoopbackServiceStub : undefined; +type LoopbackServiceStub = Fetcher & (T extends CloudflareWorkersModule.WorkerEntrypoint ? (opts: { + props?: Props; +}) => Fetcher : (opts: { + props?: any; +}) => Fetcher); +type LoopbackDurableObjectClass = DurableObjectClass & (T extends CloudflareWorkersModule.DurableObject ? (opts: { + props?: Props; +}) => DurableObjectClass : (opts: { + props?: any; +}) => DurableObjectClass); interface SyncKvStorage { - get(key: string): T | undefined; - list(options?: SyncKvListOptions): Iterable<[string, T]>; - put(key: string, value: T): void; - delete(key: string): boolean; + get(key: string): T | undefined; + list(options?: SyncKvListOptions): Iterable<[ + string, + T + ]>; + put(key: string, value: T): void; + delete(key: string): boolean; } interface SyncKvListOptions { - start?: string; - startAfter?: string; - end?: string; - prefix?: string; - reverse?: boolean; - limit?: number; + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; } interface WorkerStub { - getEntrypoint( - name?: string, - options?: WorkerStubEntrypointOptions - ): Fetcher; + getEntrypoint(name?: string, options?: WorkerStubEntrypointOptions): Fetcher; } interface WorkerStubEntrypointOptions { - props?: any; + props?: any; } interface WorkerLoader { - get( - name: string | null, - getCode: () => WorkerLoaderWorkerCode | Promise - ): WorkerStub; + get(name: string | null, getCode: () => WorkerLoaderWorkerCode | Promise): WorkerStub; } interface WorkerLoaderModule { - js?: string; - cjs?: string; - text?: string; - data?: ArrayBuffer; - json?: any; - py?: string; - wasm?: ArrayBuffer; + js?: string; + cjs?: string; + text?: string; + data?: ArrayBuffer; + json?: any; + py?: string; + wasm?: ArrayBuffer; } interface WorkerLoaderWorkerCode { - compatibilityDate: string; - compatibilityFlags?: string[]; - allowExperimental?: boolean; - mainModule: string; - modules: Record; - env?: any; - globalOutbound?: Fetcher | null; - tails?: Fetcher[]; - streamingTails?: Fetcher[]; + compatibilityDate: string; + compatibilityFlags?: string[]; + allowExperimental?: boolean; + mainModule: string; + modules: Record; + env?: any; + globalOutbound?: (Fetcher | null); + tails?: Fetcher[]; + streamingTails?: Fetcher[]; } /** - * 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. - * - * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/) - */ +* 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. +* +* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/) +*/ declare abstract class Performance { - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancetimeorigin) */ - get timeOrigin(): number; - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancenow) */ - now(): number; + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancetimeorigin) */ + get timeOrigin(): number; + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancenow) */ + now(): number; } -type AiImageClassificationInput = { - image: number[]; -}; -type AiImageClassificationOutput = { - score?: number; - label?: string; -}[]; -declare abstract class BaseAiImageClassification { - inputs: AiImageClassificationInput; - postProcessedOutputs: AiImageClassificationOutput; +// AI Search V2 API Error Interfaces +interface AiSearchInternalError extends Error { } -type AiImageToTextInput = { - image: number[]; - prompt?: string; - max_tokens?: number; - temperature?: number; - top_p?: number; - top_k?: number; - seed?: number; - repetition_penalty?: number; - frequency_penalty?: number; - presence_penalty?: number; - raw?: boolean; - messages?: RoleScopedChatInput[]; -}; -type AiImageToTextOutput = { - description: string; -}; -declare abstract class BaseAiImageToText { - inputs: AiImageToTextInput; - postProcessedOutputs: AiImageToTextOutput; +interface AiSearchNotFoundError extends Error { } -type AiImageTextToTextInput = { - image: string; - prompt?: string; - max_tokens?: number; - temperature?: number; - ignore_eos?: boolean; - top_p?: number; - top_k?: number; - seed?: number; - repetition_penalty?: number; - frequency_penalty?: number; - presence_penalty?: number; - raw?: boolean; - messages?: RoleScopedChatInput[]; -}; -type AiImageTextToTextOutput = { - description: string; -}; -declare abstract class BaseAiImageTextToText { - inputs: AiImageTextToTextInput; - postProcessedOutputs: AiImageTextToTextOutput; +interface AiSearchNameNotSetError extends Error { } -type AiMultimodalEmbeddingsInput = { - image: string; - text: string[]; +// Filter types (shared with AutoRAG for compatibility) +type ComparisonFilter = { + key: string; + type: 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte'; + value: string | number | boolean; +}; +type CompoundFilter = { + type: 'and' | 'or'; + filters: ComparisonFilter[]; +}; +// AI Search V2 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?: CompoundFilter | ComparisonFilter; + /** 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?: { + /** Enable reranking (default false) */ + enabled?: boolean; + model?: '@cf/baai/bge-reranker-base' | ''; + /** Match threshold (0-1, default 0.4) */ + match_threshold?: number; + [key: string]: unknown; + }; + [key: string]: unknown; + }; +}; +type AiSearchChatCompletionsRequest = { + messages: Array<{ + role: 'system' | 'developer' | 'user' | 'assistant' | 'tool'; + content: string | null; + }>; + model?: string; + stream?: boolean; + ai_search_options?: { + retrieval?: { + retrieval_type?: 'vector' | 'keyword' | 'hybrid'; + match_threshold?: number; + max_num_results?: number; + filters?: CompoundFilter | ComparisonFilter; + 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' | ''; + match_threshold?: number; + [key: string]: unknown; + }; + [key: string]: unknown; + }; + [key: string]: unknown; +}; +// AI Search V2 Response Types +type AiSearchSearchResponse = { + search_query: string; + chunks: Array<{ + id: string; + type: string; + /** Match score (0-1) */ + score: number; + text: string; + item: { + timestamp?: number; + key: string; + metadata?: Record; + }; + scoring_details?: { + /** Keyword match score (0-1) */ + keyword_score?: number; + /** Vector similarity score (0-1) */ + vector_score?: number; + }; + }>; +}; +type AiSearchListResponse = Array<{ + id: string; + internal_id?: string; + account_id?: string; + account_tag?: string; + /** Whether the instance is enabled (default true) */ + enable?: boolean; + type?: 'r2' | 'web-crawler'; + source?: string; + [key: string]: unknown; +}>; +type AiSearchConfig = { + /** Instance ID (1-32 chars, pattern: ^[a-z0-9_]+(?:-[a-z0-9_]+)*$) */ + id: string; + type: 'r2' | 'web-crawler'; + source: string; + source_params?: object; + /** Token ID (UUID format) */ + token_id?: string; + ai_gateway_id?: string; + /** Enable query rewriting (default false) */ + rewrite_query?: boolean; + /** Enable reranking (default false) */ + reranking?: boolean; + embedding_model?: string; + ai_search_model?: string; +}; +type AiSearchInstance = { + id: string; + enable?: boolean; + type?: 'r2' | 'web-crawler'; + source?: string; + [key: string]: unknown; +}; +// AI Search Instance Service - Instance-level operations +declare abstract class AiSearchInstanceService { + /** + * Search the AI Search instance for relevant chunks. + * @param params Search request with messages and AI search options + * @returns Search response with matching chunks + */ + search(params: AiSearchSearchRequest): Promise; + /** + * Generate chat completions with AI Search context. + * @param params Chat completions request with optional streaming + * @returns Response object (if streaming) or chat completion result + */ + chatCompletions(params: AiSearchChatCompletionsRequest): Promise; + /** + * Delete this AI Search instance. + */ + delete(): Promise; +} +// AI Search Account Service - Account-level operations +declare abstract class AiSearchAccountService { + /** + * List all AI Search instances in the account. + * @returns Array of AI Search instances + */ + list(): Promise; + /** + * Get an AI Search instance by ID. + * @param name Instance ID + * @returns Instance service for performing operations + */ + get(name: string): AiSearchInstanceService; + /** + * Create a new AI Search instance. + * @param config Instance configuration + * @returns Instance service for performing operations + */ + create(config: AiSearchConfig): Promise; +} +type AiImageClassificationInput = { + image: number[]; +}; +type AiImageClassificationOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiImageClassification { + inputs: AiImageClassificationInput; + postProcessedOutputs: AiImageClassificationOutput; +} +type AiImageToTextInput = { + image: number[]; + prompt?: string; + max_tokens?: number; + temperature?: number; + top_p?: number; + top_k?: number; + seed?: number; + repetition_penalty?: number; + frequency_penalty?: number; + presence_penalty?: number; + raw?: boolean; + messages?: RoleScopedChatInput[]; +}; +type AiImageToTextOutput = { + description: string; +}; +declare abstract class BaseAiImageToText { + inputs: AiImageToTextInput; + postProcessedOutputs: AiImageToTextOutput; +} +type AiImageTextToTextInput = { + image: string; + prompt?: string; + max_tokens?: number; + temperature?: number; + ignore_eos?: boolean; + top_p?: number; + top_k?: number; + seed?: number; + repetition_penalty?: number; + frequency_penalty?: number; + presence_penalty?: number; + raw?: boolean; + messages?: RoleScopedChatInput[]; +}; +type AiImageTextToTextOutput = { + description: string; +}; +declare abstract class BaseAiImageTextToText { + inputs: AiImageTextToTextInput; + postProcessedOutputs: AiImageTextToTextOutput; +} +type AiMultimodalEmbeddingsInput = { + image: string; + text: string[]; }; type AiIMultimodalEmbeddingsOutput = { - data: number[][]; - shape: number[]; + data: number[][]; + shape: number[]; }; declare abstract class BaseAiMultimodalEmbeddings { - inputs: AiImageTextToTextInput; - postProcessedOutputs: AiImageTextToTextOutput; + inputs: AiImageTextToTextInput; + postProcessedOutputs: AiImageTextToTextOutput; } type AiObjectDetectionInput = { - image: number[]; + image: number[]; }; type AiObjectDetectionOutput = { - score?: number; - label?: string; + score?: number; + label?: string; }[]; declare abstract class BaseAiObjectDetection { - inputs: AiObjectDetectionInput; - postProcessedOutputs: AiObjectDetectionOutput; + inputs: AiObjectDetectionInput; + postProcessedOutputs: AiObjectDetectionOutput; } type AiSentenceSimilarityInput = { - source: string; - sentences: string[]; + source: string; + sentences: string[]; }; type AiSentenceSimilarityOutput = number[]; declare abstract class BaseAiSentenceSimilarity { - inputs: AiSentenceSimilarityInput; - postProcessedOutputs: AiSentenceSimilarityOutput; + inputs: AiSentenceSimilarityInput; + postProcessedOutputs: AiSentenceSimilarityOutput; } type AiAutomaticSpeechRecognitionInput = { - audio: number[]; + audio: number[]; }; type AiAutomaticSpeechRecognitionOutput = { - text?: string; - words?: { - word: string; - start: number; - end: number; - }[]; - vtt?: string; + text?: string; + words?: { + word: string; + start: number; + end: number; + }[]; + vtt?: string; }; declare abstract class BaseAiAutomaticSpeechRecognition { - inputs: AiAutomaticSpeechRecognitionInput; - postProcessedOutputs: AiAutomaticSpeechRecognitionOutput; + inputs: AiAutomaticSpeechRecognitionInput; + postProcessedOutputs: AiAutomaticSpeechRecognitionOutput; } type AiSummarizationInput = { - input_text: string; - max_length?: number; + input_text: string; + max_length?: number; }; type AiSummarizationOutput = { - summary: string; + summary: string; }; declare abstract class BaseAiSummarization { - inputs: AiSummarizationInput; - postProcessedOutputs: AiSummarizationOutput; + inputs: AiSummarizationInput; + postProcessedOutputs: AiSummarizationOutput; } type AiTextClassificationInput = { - text: string; + text: string; }; type AiTextClassificationOutput = { - score?: number; - label?: string; + score?: number; + label?: string; }[]; declare abstract class BaseAiTextClassification { - inputs: AiTextClassificationInput; - postProcessedOutputs: AiTextClassificationOutput; + inputs: AiTextClassificationInput; + postProcessedOutputs: AiTextClassificationOutput; } type AiTextEmbeddingsInput = { - text: string | string[]; + text: string | string[]; }; type AiTextEmbeddingsOutput = { - shape: number[]; - data: number[][]; + shape: number[]; + data: number[][]; }; declare abstract class BaseAiTextEmbeddings { - inputs: AiTextEmbeddingsInput; - postProcessedOutputs: AiTextEmbeddingsOutput; + inputs: AiTextEmbeddingsInput; + postProcessedOutputs: AiTextEmbeddingsOutput; } type RoleScopedChatInput = { - role: 'user' | 'assistant' | 'system' | 'tool' | (string & NonNullable); - content: string; - name?: string; + role: "user" | "assistant" | "system" | "tool" | (string & NonNullable); + content: string; + name?: string; }; type AiTextGenerationToolLegacyInput = { - name: string; - description: string; - parameters?: { - type: 'object' | (string & NonNullable); - properties: { - [key: string]: { - type: string; - description?: string; - }; - }; - required: string[]; - }; -}; -type AiTextGenerationToolInput = { - type: 'function' | (string & NonNullable); - function: { name: string; description: string; parameters?: { - type: 'object' | (string & NonNullable); - properties: { - [key: string]: { - type: string; - description?: string; + type: "object" | (string & NonNullable); + properties: { + [key: string]: { + type: string; + description?: string; + }; + }; + required: string[]; + }; +}; +type AiTextGenerationToolInput = { + type: "function" | (string & NonNullable); + function: { + name: string; + description: string; + parameters?: { + type: "object" | (string & NonNullable); + properties: { + [key: string]: { + type: string; + description?: string; + }; + }; + required: string[]; }; - }; - required: string[]; }; - }; }; type AiTextGenerationFunctionsInput = { - name: string; - code: string; + name: string; + code: string; }; type AiTextGenerationResponseFormat = { - type: string; - json_schema?: any; + type: string; + json_schema?: any; }; type AiTextGenerationInput = { - prompt?: string; - raw?: boolean; - stream?: boolean; - max_tokens?: number; - temperature?: number; - top_p?: number; - top_k?: number; - seed?: number; - repetition_penalty?: number; - frequency_penalty?: number; - presence_penalty?: number; - messages?: RoleScopedChatInput[]; - response_format?: AiTextGenerationResponseFormat; - tools?: - | AiTextGenerationToolInput[] - | AiTextGenerationToolLegacyInput[] - | (object & NonNullable); - functions?: AiTextGenerationFunctionsInput[]; + prompt?: string; + raw?: boolean; + stream?: boolean; + max_tokens?: number; + temperature?: number; + top_p?: number; + top_k?: number; + seed?: number; + repetition_penalty?: number; + frequency_penalty?: number; + presence_penalty?: number; + messages?: RoleScopedChatInput[]; + response_format?: AiTextGenerationResponseFormat; + tools?: AiTextGenerationToolInput[] | AiTextGenerationToolLegacyInput[] | (object & NonNullable); + functions?: AiTextGenerationFunctionsInput[]; }; type AiTextGenerationToolLegacyOutput = { - name: string; - arguments: unknown; + name: string; + arguments: unknown; }; type AiTextGenerationToolOutput = { - id: string; - type: 'function'; - function: { - name: string; - arguments: string; - }; + id: string; + type: "function"; + function: { + name: string; + arguments: string; + }; }; type UsageTags = { - prompt_tokens: number; - completion_tokens: number; - total_tokens: number; + prompt_tokens: number; + completion_tokens: number; + total_tokens: number; }; type AiTextGenerationOutput = { - response?: string; - tool_calls?: AiTextGenerationToolLegacyOutput[] & AiTextGenerationToolOutput[]; - usage?: UsageTags; + response?: string; + tool_calls?: AiTextGenerationToolLegacyOutput[] & AiTextGenerationToolOutput[]; + usage?: UsageTags; }; declare abstract class BaseAiTextGeneration { - inputs: AiTextGenerationInput; - postProcessedOutputs: AiTextGenerationOutput; + inputs: AiTextGenerationInput; + postProcessedOutputs: AiTextGenerationOutput; } type AiTextToSpeechInput = { - prompt: string; - lang?: string; + prompt: string; + lang?: string; +}; +type AiTextToSpeechOutput = Uint8Array | { + audio: string; }; -type AiTextToSpeechOutput = - | Uint8Array - | { - audio: string; - }; declare abstract class BaseAiTextToSpeech { - inputs: AiTextToSpeechInput; - postProcessedOutputs: AiTextToSpeechOutput; + inputs: AiTextToSpeechInput; + postProcessedOutputs: AiTextToSpeechOutput; } type AiTextToImageInput = { - prompt: string; - negative_prompt?: string; - height?: number; - width?: number; - image?: number[]; - image_b64?: string; - mask?: number[]; - num_steps?: number; - strength?: number; - guidance?: number; - seed?: number; + prompt: string; + negative_prompt?: string; + height?: number; + width?: number; + image?: number[]; + image_b64?: string; + mask?: number[]; + num_steps?: number; + strength?: number; + guidance?: number; + seed?: number; }; type AiTextToImageOutput = ReadableStream; declare abstract class BaseAiTextToImage { - inputs: AiTextToImageInput; - postProcessedOutputs: AiTextToImageOutput; + inputs: AiTextToImageInput; + postProcessedOutputs: AiTextToImageOutput; } type AiTranslationInput = { - text: string; - target_lang: string; - source_lang?: string; + text: string; + target_lang: string; + source_lang?: string; }; type AiTranslationOutput = { - translated_text?: string; + translated_text?: string; }; declare abstract class BaseAiTranslation { - inputs: AiTranslationInput; - postProcessedOutputs: AiTranslationOutput; + inputs: AiTranslationInput; + postProcessedOutputs: AiTranslationOutput; } /** * Workers AI support for OpenAI's Responses API @@ -3980,1042 +3811,3322 @@ declare abstract class BaseAiTranslation { * We plan to add those incrementally as model + platform capabilities evolve. */ type ResponsesInput = { - background?: boolean | null; - conversation?: string | ResponseConversationParam | null; - include?: Array | null; - input?: string | ResponseInput; - instructions?: string | null; - max_output_tokens?: number | null; - parallel_tool_calls?: boolean | null; - previous_response_id?: string | null; - prompt_cache_key?: string; - reasoning?: Reasoning | null; - safety_identifier?: string; - service_tier?: 'auto' | 'default' | 'flex' | 'scale' | 'priority' | null; - stream?: boolean | null; - stream_options?: StreamOptions | null; - temperature?: number | null; - text?: ResponseTextConfig; - tool_choice?: ToolChoiceOptions | ToolChoiceFunction; - tools?: Array; - top_p?: number | null; - truncation?: 'auto' | 'disabled' | null; + background?: boolean | null; + conversation?: string | ResponseConversationParam | null; + include?: Array | null; + input?: string | ResponseInput; + instructions?: string | null; + max_output_tokens?: number | null; + parallel_tool_calls?: boolean | null; + previous_response_id?: string | null; + prompt_cache_key?: string; + reasoning?: Reasoning | null; + safety_identifier?: string; + service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null; + stream?: boolean | null; + stream_options?: StreamOptions | null; + temperature?: number | null; + text?: ResponseTextConfig; + tool_choice?: ToolChoiceOptions | ToolChoiceFunction; + tools?: Array; + top_p?: number | null; + truncation?: "auto" | "disabled" | null; }; type ResponsesOutput = { - id?: string; - created_at?: number; - output_text?: string; - error?: ResponseError | null; - incomplete_details?: ResponseIncompleteDetails | null; - instructions?: string | Array | null; - object?: 'response'; - output?: Array; - parallel_tool_calls?: boolean; - temperature?: number | null; - tool_choice?: ToolChoiceOptions | ToolChoiceFunction; - tools?: Array; - top_p?: number | null; - max_output_tokens?: number | null; - previous_response_id?: string | null; - prompt?: ResponsePrompt | null; - reasoning?: Reasoning | null; - safety_identifier?: string; - service_tier?: 'auto' | 'default' | 'flex' | 'scale' | 'priority' | null; - status?: ResponseStatus; - text?: ResponseTextConfig; - truncation?: 'auto' | 'disabled' | null; - usage?: ResponseUsage; + id?: string; + created_at?: number; + output_text?: string; + error?: ResponseError | null; + incomplete_details?: ResponseIncompleteDetails | null; + instructions?: string | Array | null; + object?: "response"; + output?: Array; + parallel_tool_calls?: boolean; + temperature?: number | null; + tool_choice?: ToolChoiceOptions | ToolChoiceFunction; + tools?: Array; + top_p?: number | null; + max_output_tokens?: number | null; + previous_response_id?: string | null; + prompt?: ResponsePrompt | null; + reasoning?: Reasoning | null; + safety_identifier?: string; + service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null; + status?: ResponseStatus; + text?: ResponseTextConfig; + truncation?: "auto" | "disabled" | null; + usage?: ResponseUsage; }; type EasyInputMessage = { - content: string | ResponseInputMessageContentList; - role: 'user' | 'assistant' | 'system' | 'developer'; - type?: 'message'; + content: string | ResponseInputMessageContentList; + role: "user" | "assistant" | "system" | "developer"; + type?: "message"; }; type ResponsesFunctionTool = { - name: string; - parameters: { - [key: string]: unknown; - } | null; - strict: boolean | null; - type: 'function'; - description?: string | null; + name: string; + parameters: { + [key: string]: unknown; + } | null; + strict: boolean | null; + type: "function"; + description?: string | null; }; type ResponseIncompleteDetails = { - reason?: 'max_output_tokens' | 'content_filter'; + reason?: "max_output_tokens" | "content_filter"; }; type ResponsePrompt = { - id: string; - variables?: { - [key: string]: string | ResponseInputText | ResponseInputImage; - } | null; - version?: string | null; + id: string; + variables?: { + [key: string]: string | ResponseInputText | ResponseInputImage; + } | null; + version?: string | null; }; type Reasoning = { - effort?: ReasoningEffort | null; - generate_summary?: 'auto' | 'concise' | 'detailed' | null; - summary?: 'auto' | 'concise' | 'detailed' | null; -}; -type ResponseContent = - | ResponseInputText - | ResponseInputImage - | ResponseOutputText - | ResponseOutputRefusal - | ResponseContentReasoningText; + effort?: ReasoningEffort | null; + generate_summary?: "auto" | "concise" | "detailed" | null; + summary?: "auto" | "concise" | "detailed" | null; +}; +type ResponseContent = ResponseInputText | ResponseInputImage | ResponseOutputText | ResponseOutputRefusal | ResponseContentReasoningText; type ResponseContentReasoningText = { - text: string; - type: 'reasoning_text'; + text: string; + type: "reasoning_text"; }; type ResponseConversationParam = { - id: string; + id: string; }; type ResponseCreatedEvent = { - response: Response; - sequence_number: number; - type: 'response.created'; + response: Response; + sequence_number: number; + type: "response.created"; }; type ResponseCustomToolCallOutput = { - call_id: string; - output: string | Array; - type: 'custom_tool_call_output'; - id?: string; + call_id: string; + output: string | Array; + type: "custom_tool_call_output"; + id?: string; }; type ResponseError = { - code: - | 'server_error' - | 'rate_limit_exceeded' - | 'invalid_prompt' - | 'vector_store_timeout' - | 'invalid_image' - | 'invalid_image_format' - | 'invalid_base64_image' - | 'invalid_image_url' - | 'image_too_large' - | 'image_too_small' - | 'image_parse_error' - | 'image_content_policy_violation' - | 'invalid_image_mode' - | 'image_file_too_large' - | 'unsupported_image_media_type' - | 'empty_image_file' - | 'failed_to_download_image' - | 'image_file_not_found'; - message: string; + code: "server_error" | "rate_limit_exceeded" | "invalid_prompt" | "vector_store_timeout" | "invalid_image" | "invalid_image_format" | "invalid_base64_image" | "invalid_image_url" | "image_too_large" | "image_too_small" | "image_parse_error" | "image_content_policy_violation" | "invalid_image_mode" | "image_file_too_large" | "unsupported_image_media_type" | "empty_image_file" | "failed_to_download_image" | "image_file_not_found"; + message: string; }; type ResponseErrorEvent = { - code: string | null; - message: string; - param: string | null; - sequence_number: number; - type: 'error'; + code: string | null; + message: string; + param: string | null; + sequence_number: number; + type: "error"; }; type ResponseFailedEvent = { - response: Response; - sequence_number: number; - type: 'response.failed'; + response: Response; + sequence_number: number; + type: "response.failed"; }; type ResponseFormatText = { - type: 'text'; + type: "text"; }; type ResponseFormatJSONObject = { - type: 'json_object'; + type: "json_object"; }; -type ResponseFormatTextConfig = - | ResponseFormatText - | ResponseFormatTextJSONSchemaConfig - | ResponseFormatJSONObject; +type ResponseFormatTextConfig = ResponseFormatText | ResponseFormatTextJSONSchemaConfig | ResponseFormatJSONObject; type ResponseFormatTextJSONSchemaConfig = { - name: string; - schema: { - [key: string]: unknown; - }; - type: 'json_schema'; - description?: string; - strict?: boolean | null; + name: string; + schema: { + [key: string]: unknown; + }; + type: "json_schema"; + description?: string; + strict?: boolean | null; }; type ResponseFunctionCallArgumentsDeltaEvent = { - delta: string; - item_id: string; - output_index: number; - sequence_number: number; - type: 'response.function_call_arguments.delta'; + delta: string; + item_id: string; + output_index: number; + sequence_number: number; + type: "response.function_call_arguments.delta"; }; type ResponseFunctionCallArgumentsDoneEvent = { - arguments: string; - item_id: string; - name: string; - output_index: number; - sequence_number: number; - type: 'response.function_call_arguments.done'; + arguments: string; + item_id: string; + name: string; + output_index: number; + sequence_number: number; + type: "response.function_call_arguments.done"; }; type ResponseFunctionCallOutputItem = ResponseInputTextContent | ResponseInputImageContent; type ResponseFunctionCallOutputItemList = Array; type ResponseFunctionToolCall = { - arguments: string; - call_id: string; - name: string; - type: 'function_call'; - id?: string; - status?: 'in_progress' | 'completed' | 'incomplete'; + arguments: string; + call_id: string; + name: string; + type: "function_call"; + id?: string; + status?: "in_progress" | "completed" | "incomplete"; }; interface ResponseFunctionToolCallItem extends ResponseFunctionToolCall { - id: string; + id: string; } type ResponseFunctionToolCallOutputItem = { - id: string; - call_id: string; - output: string | Array; - type: 'function_call_output'; - status?: 'in_progress' | 'completed' | 'incomplete'; + id: string; + call_id: string; + output: string | Array; + type: "function_call_output"; + status?: "in_progress" | "completed" | "incomplete"; }; -type ResponseIncludable = 'message.input_image.image_url' | 'message.output_text.logprobs'; +type ResponseIncludable = "message.input_image.image_url" | "message.output_text.logprobs"; type ResponseIncompleteEvent = { - response: Response; - sequence_number: number; - type: 'response.incomplete'; + response: Response; + sequence_number: number; + type: "response.incomplete"; }; type ResponseInput = Array; type ResponseInputContent = ResponseInputText | ResponseInputImage; type ResponseInputImage = { - detail: 'low' | 'high' | 'auto'; - type: 'input_image'; - /** - * Base64 encoded image - */ - image_url?: string | null; + detail: "low" | "high" | "auto"; + type: "input_image"; + /** + * Base64 encoded image + */ + image_url?: string | null; }; type ResponseInputImageContent = { - type: 'input_image'; - detail?: 'low' | 'high' | 'auto' | null; - /** - * Base64 encoded image - */ - image_url?: string | null; -}; -type ResponseInputItem = - | EasyInputMessage - | ResponseInputItemMessage - | ResponseOutputMessage - | ResponseFunctionToolCall - | ResponseInputItemFunctionCallOutput - | ResponseReasoningItem; + type: "input_image"; + detail?: "low" | "high" | "auto" | null; + /** + * Base64 encoded image + */ + image_url?: string | null; +}; +type ResponseInputItem = EasyInputMessage | ResponseInputItemMessage | ResponseOutputMessage | ResponseFunctionToolCall | ResponseInputItemFunctionCallOutput | ResponseReasoningItem; type ResponseInputItemFunctionCallOutput = { - call_id: string; - output: string | ResponseFunctionCallOutputItemList; - type: 'function_call_output'; - id?: string | null; - status?: 'in_progress' | 'completed' | 'incomplete' | null; + call_id: string; + output: string | ResponseFunctionCallOutputItemList; + type: "function_call_output"; + id?: string | null; + status?: "in_progress" | "completed" | "incomplete" | null; }; type ResponseInputItemMessage = { - content: ResponseInputMessageContentList; - role: 'user' | 'system' | 'developer'; - status?: 'in_progress' | 'completed' | 'incomplete'; - type?: 'message'; + content: ResponseInputMessageContentList; + role: "user" | "system" | "developer"; + status?: "in_progress" | "completed" | "incomplete"; + type?: "message"; }; type ResponseInputMessageContentList = Array; type ResponseInputMessageItem = { - id: string; - content: ResponseInputMessageContentList; - role: 'user' | 'system' | 'developer'; - status?: 'in_progress' | 'completed' | 'incomplete'; - type?: 'message'; + id: string; + content: ResponseInputMessageContentList; + role: "user" | "system" | "developer"; + status?: "in_progress" | "completed" | "incomplete"; + type?: "message"; }; type ResponseInputText = { - text: string; - type: 'input_text'; + text: string; + type: "input_text"; }; type ResponseInputTextContent = { - text: string; - type: 'input_text'; -}; -type ResponseItem = - | ResponseInputMessageItem - | ResponseOutputMessage - | ResponseFunctionToolCallItem - | ResponseFunctionToolCallOutputItem; + text: string; + type: "input_text"; +}; +type ResponseItem = ResponseInputMessageItem | ResponseOutputMessage | ResponseFunctionToolCallItem | ResponseFunctionToolCallOutputItem; type ResponseOutputItem = ResponseOutputMessage | ResponseFunctionToolCall | ResponseReasoningItem; type ResponseOutputItemAddedEvent = { - item: ResponseOutputItem; - output_index: number; - sequence_number: number; - type: 'response.output_item.added'; + item: ResponseOutputItem; + output_index: number; + sequence_number: number; + type: "response.output_item.added"; }; type ResponseOutputItemDoneEvent = { - item: ResponseOutputItem; - output_index: number; - sequence_number: number; - type: 'response.output_item.done'; + item: ResponseOutputItem; + output_index: number; + sequence_number: number; + type: "response.output_item.done"; }; type ResponseOutputMessage = { - id: string; - content: Array; - role: 'assistant'; - status: 'in_progress' | 'completed' | 'incomplete'; - type: 'message'; + id: string; + content: Array; + role: "assistant"; + status: "in_progress" | "completed" | "incomplete"; + type: "message"; }; type ResponseOutputRefusal = { - refusal: string; - type: 'refusal'; + refusal: string; + type: "refusal"; }; type ResponseOutputText = { - text: string; - type: 'output_text'; - logprobs?: Array; + text: string; + type: "output_text"; + logprobs?: Array; }; type ResponseReasoningItem = { - id: string; - summary: Array; - type: 'reasoning'; - content?: Array; - encrypted_content?: string | null; - status?: 'in_progress' | 'completed' | 'incomplete'; + id: string; + summary: Array; + type: "reasoning"; + content?: Array; + encrypted_content?: string | null; + status?: "in_progress" | "completed" | "incomplete"; }; type ResponseReasoningSummaryItem = { - text: string; - type: 'summary_text'; + text: string; + type: "summary_text"; }; type ResponseReasoningContentItem = { - text: string; - type: 'reasoning_text'; + text: string; + type: "reasoning_text"; }; type ResponseReasoningTextDeltaEvent = { - content_index: number; - delta: string; - item_id: string; - output_index: number; - sequence_number: number; - type: 'response.reasoning_text.delta'; + content_index: number; + delta: string; + item_id: string; + output_index: number; + sequence_number: number; + type: "response.reasoning_text.delta"; }; type ResponseReasoningTextDoneEvent = { - content_index: number; - item_id: string; - output_index: number; - sequence_number: number; - text: string; - type: 'response.reasoning_text.done'; + content_index: number; + item_id: string; + output_index: number; + sequence_number: number; + text: string; + type: "response.reasoning_text.done"; }; type ResponseRefusalDeltaEvent = { - content_index: number; - delta: string; - item_id: string; - output_index: number; - sequence_number: number; - type: 'response.refusal.delta'; + content_index: number; + delta: string; + item_id: string; + output_index: number; + sequence_number: number; + type: "response.refusal.delta"; }; type ResponseRefusalDoneEvent = { - content_index: number; - item_id: string; - output_index: number; - refusal: string; - sequence_number: number; - type: 'response.refusal.done'; -}; -type ResponseStatus = - | 'completed' - | 'failed' - | 'in_progress' - | 'cancelled' - | 'queued' - | 'incomplete'; -type ResponseStreamEvent = - | ResponseCompletedEvent - | ResponseCreatedEvent - | ResponseErrorEvent - | ResponseFunctionCallArgumentsDeltaEvent - | ResponseFunctionCallArgumentsDoneEvent - | ResponseFailedEvent - | ResponseIncompleteEvent - | ResponseOutputItemAddedEvent - | ResponseOutputItemDoneEvent - | ResponseReasoningTextDeltaEvent - | ResponseReasoningTextDoneEvent - | ResponseRefusalDeltaEvent - | ResponseRefusalDoneEvent - | ResponseTextDeltaEvent - | ResponseTextDoneEvent; + content_index: number; + item_id: string; + output_index: number; + refusal: string; + sequence_number: number; + type: "response.refusal.done"; +}; +type ResponseStatus = "completed" | "failed" | "in_progress" | "cancelled" | "queued" | "incomplete"; +type ResponseStreamEvent = ResponseCompletedEvent | ResponseCreatedEvent | ResponseErrorEvent | ResponseFunctionCallArgumentsDeltaEvent | ResponseFunctionCallArgumentsDoneEvent | ResponseFailedEvent | ResponseIncompleteEvent | ResponseOutputItemAddedEvent | ResponseOutputItemDoneEvent | ResponseReasoningTextDeltaEvent | ResponseReasoningTextDoneEvent | ResponseRefusalDeltaEvent | ResponseRefusalDoneEvent | ResponseTextDeltaEvent | ResponseTextDoneEvent; type ResponseCompletedEvent = { - response: Response; - sequence_number: number; - type: 'response.completed'; + response: Response; + sequence_number: number; + type: "response.completed"; }; type ResponseTextConfig = { - format?: ResponseFormatTextConfig; - verbosity?: 'low' | 'medium' | 'high' | null; + format?: ResponseFormatTextConfig; + verbosity?: "low" | "medium" | "high" | null; }; type ResponseTextDeltaEvent = { - content_index: number; - delta: string; - item_id: string; - logprobs: Array; - output_index: number; - sequence_number: number; - type: 'response.output_text.delta'; + content_index: number; + delta: string; + item_id: string; + logprobs: Array; + output_index: number; + sequence_number: number; + type: "response.output_text.delta"; }; type ResponseTextDoneEvent = { - content_index: number; - item_id: string; - logprobs: Array; - output_index: number; - sequence_number: number; - text: string; - type: 'response.output_text.done'; + content_index: number; + item_id: string; + logprobs: Array; + output_index: number; + sequence_number: number; + text: string; + type: "response.output_text.done"; }; type Logprob = { - token: string; - logprob: number; - top_logprobs?: Array; + token: string; + logprob: number; + top_logprobs?: Array; }; type TopLogprob = { - token?: string; - logprob?: number; + token?: string; + logprob?: number; }; type ResponseUsage = { - input_tokens: number; - output_tokens: number; - total_tokens: number; + input_tokens: number; + output_tokens: number; + total_tokens: number; }; type Tool = ResponsesFunctionTool; type ToolChoiceFunction = { - name: string; - type: 'function'; + name: string; + type: "function"; }; -type ToolChoiceOptions = 'none'; -type ReasoningEffort = 'minimal' | 'low' | 'medium' | 'high' | null; +type ToolChoiceOptions = "none"; +type ReasoningEffort = "minimal" | "low" | "medium" | "high" | null; type StreamOptions = { - include_obfuscation?: boolean; -}; -type Ai_Cf_Baai_Bge_Base_En_V1_5_Input = - | { - text: string | string[]; - /** - * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. - */ - pooling?: 'mean' | 'cls'; - } - | { - /** - * Batch of the embeddings requests to run using async-queue - */ - requests: { + include_obfuscation?: boolean; +}; +type Ai_Cf_Baai_Bge_Base_En_V1_5_Input = { + text: string | string[]; + /** + * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. + */ + pooling?: "mean" | "cls"; +} | { + /** + * Batch of the embeddings requests to run using async-queue + */ + requests: { text: string | string[]; /** * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. */ - pooling?: 'mean' | 'cls'; - }[]; - }; -type Ai_Cf_Baai_Bge_Base_En_V1_5_Output = - | { - shape?: number[]; - /** - * Embeddings of the requested text values - */ - data?: number[][]; - /** - * The pooling method used in the embedding process. - */ - pooling?: 'mean' | 'cls'; - } - | Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse; + pooling?: "mean" | "cls"; + }[]; +}; +type Ai_Cf_Baai_Bge_Base_En_V1_5_Output = { + shape?: number[]; + /** + * Embeddings of the requested text values + */ + data?: number[][]; + /** + * The pooling method used in the embedding process. + */ + pooling?: "mean" | "cls"; +} | Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse; interface Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; } declare abstract class Base_Ai_Cf_Baai_Bge_Base_En_V1_5 { - inputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Input; - postProcessedOutputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Output; -} -type Ai_Cf_Openai_Whisper_Input = - | string - | { - /** - * An array of integers that represent the audio data constrained to 8-bit unsigned integer values - */ - audio: number[]; - }; + inputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Input; + postProcessedOutputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Output; +} +type Ai_Cf_Openai_Whisper_Input = string | { + /** + * An array of integers that represent the audio data constrained to 8-bit unsigned integer values + */ + audio: number[]; +}; interface Ai_Cf_Openai_Whisper_Output { - /** - * The transcription - */ - text: string; - word_count?: number; - words?: { - word?: string; /** - * The second this word begins in the recording + * The transcription + */ + text: string; + word_count?: number; + words?: { + word?: string; + /** + * The second this word begins in the recording + */ + start?: number; + /** + * The ending second when the word completes + */ + end?: number; + }[]; + vtt?: string; +} +declare abstract class Base_Ai_Cf_Openai_Whisper { + inputs: Ai_Cf_Openai_Whisper_Input; + postProcessedOutputs: Ai_Cf_Openai_Whisper_Output; +} +type Ai_Cf_Meta_M2M100_1_2B_Input = { + /** + * The text to be translated + */ + text: string; + /** + * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified + */ + source_lang?: string; + /** + * The language code to translate the text into (e.g., 'es' for Spanish) + */ + target_lang: string; +} | { + /** + * Batch of the embeddings requests to run using async-queue + */ + requests: { + /** + * The text to be translated + */ + text: string; + /** + * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified + */ + source_lang?: string; + /** + * The language code to translate the text into (e.g., 'es' for Spanish) + */ + target_lang: string; + }[]; +}; +type Ai_Cf_Meta_M2M100_1_2B_Output = { + /** + * The translated text in the target language + */ + translated_text?: string; +} | Ai_Cf_Meta_M2M100_1_2B_AsyncResponse; +interface Ai_Cf_Meta_M2M100_1_2B_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Meta_M2M100_1_2B { + inputs: Ai_Cf_Meta_M2M100_1_2B_Input; + postProcessedOutputs: Ai_Cf_Meta_M2M100_1_2B_Output; +} +type Ai_Cf_Baai_Bge_Small_En_V1_5_Input = { + text: string | string[]; + /** + * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. + */ + pooling?: "mean" | "cls"; +} | { + /** + * Batch of the embeddings requests to run using async-queue + */ + requests: { + text: string | string[]; + /** + * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. + */ + pooling?: "mean" | "cls"; + }[]; +}; +type Ai_Cf_Baai_Bge_Small_En_V1_5_Output = { + shape?: number[]; + /** + * Embeddings of the requested text values + */ + data?: number[][]; + /** + * The pooling method used in the embedding process. + */ + pooling?: "mean" | "cls"; +} | Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse; +interface Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Baai_Bge_Small_En_V1_5 { + inputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Input; + postProcessedOutputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Output; +} +type Ai_Cf_Baai_Bge_Large_En_V1_5_Input = { + text: string | string[]; + /** + * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. + */ + pooling?: "mean" | "cls"; +} | { + /** + * Batch of the embeddings requests to run using async-queue + */ + requests: { + text: string | string[]; + /** + * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. + */ + pooling?: "mean" | "cls"; + }[]; +}; +type Ai_Cf_Baai_Bge_Large_En_V1_5_Output = { + shape?: number[]; + /** + * Embeddings of the requested text values + */ + data?: number[][]; + /** + * The pooling method used in the embedding process. + */ + pooling?: "mean" | "cls"; +} | Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse; +interface Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Baai_Bge_Large_En_V1_5 { + inputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Input; + postProcessedOutputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Output; +} +type Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input = string | { + /** + * The input text prompt for the model to generate a response. + */ + prompt?: string; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; + image: number[] | (string & NonNullable); + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; +}; +interface Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output { + description?: string; +} +declare abstract class Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M { + inputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input; + postProcessedOutputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output; +} +type Ai_Cf_Openai_Whisper_Tiny_En_Input = string | { + /** + * An array of integers that represent the audio data constrained to 8-bit unsigned integer values + */ + audio: number[]; +}; +interface Ai_Cf_Openai_Whisper_Tiny_En_Output { + /** + * The transcription + */ + text: string; + word_count?: number; + words?: { + word?: string; + /** + * The second this word begins in the recording + */ + start?: number; + /** + * The ending second when the word completes + */ + end?: number; + }[]; + vtt?: string; +} +declare abstract class Base_Ai_Cf_Openai_Whisper_Tiny_En { + inputs: Ai_Cf_Openai_Whisper_Tiny_En_Input; + postProcessedOutputs: Ai_Cf_Openai_Whisper_Tiny_En_Output; +} +interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input { + /** + * Base64 encoded value of the audio data. + */ + audio: string; + /** + * Supported tasks are 'translate' or 'transcribe'. + */ + task?: string; + /** + * The language of the audio being transcribed or translated. + */ + language?: string; + /** + * Preprocess the audio with a voice activity detection model. + */ + vad_filter?: boolean; + /** + * A text prompt to help provide context to the model on the contents of the audio. + */ + initial_prompt?: string; + /** + * The prefix it appended the the beginning of the output of the transcription and can guide the transcription result. + */ + prefix?: string; +} +interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output { + transcription_info?: { + /** + * The language of the audio being transcribed or translated. + */ + language?: string; + /** + * The confidence level or probability of the detected language being accurate, represented as a decimal between 0 and 1. + */ + language_probability?: number; + /** + * The total duration of the original audio file, in seconds. + */ + duration?: number; + /** + * The duration of the audio after applying Voice Activity Detection (VAD) to remove silent or irrelevant sections, in seconds. + */ + duration_after_vad?: number; + }; + /** + * The complete transcription of the audio. + */ + text: string; + /** + * The total number of words in the transcription. + */ + word_count?: number; + segments?: { + /** + * The starting time of the segment within the audio, in seconds. + */ + start?: number; + /** + * The ending time of the segment within the audio, in seconds. + */ + end?: number; + /** + * The transcription of the segment. + */ + text?: string; + /** + * The temperature used in the decoding process, controlling randomness in predictions. Lower values result in more deterministic outputs. + */ + temperature?: number; + /** + * The average log probability of the predictions for the words in this segment, indicating overall confidence. + */ + avg_logprob?: number; + /** + * The compression ratio of the input to the output, measuring how much the text was compressed during the transcription process. + */ + compression_ratio?: number; + /** + * The probability that the segment contains no speech, represented as a decimal between 0 and 1. + */ + no_speech_prob?: number; + words?: { + /** + * The individual word transcribed from the audio. + */ + word?: string; + /** + * The starting time of the word within the audio, in seconds. + */ + start?: number; + /** + * The ending time of the word within the audio, in seconds. + */ + end?: number; + }[]; + }[]; + /** + * The transcription in WebVTT format, which includes timing and text information for use in subtitles. + */ + vtt?: string; +} +declare abstract class Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo { + inputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input; + postProcessedOutputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output; +} +type Ai_Cf_Baai_Bge_M3_Input = Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts | Ai_Cf_Baai_Bge_M3_Input_Embedding | { + /** + * Batch of the embeddings requests to run using async-queue + */ + requests: (Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 | Ai_Cf_Baai_Bge_M3_Input_Embedding_1)[]; +}; +interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts { + /** + * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts + */ + query?: string; + /** + * List of provided contexts. Note that the index in this array is important, as the response will refer to it. + */ + contexts: { + /** + * One of the provided context content + */ + text?: string; + }[]; + /** + * When provided with too long context should the model error out or truncate the context to fit? + */ + truncate_inputs?: boolean; +} +interface Ai_Cf_Baai_Bge_M3_Input_Embedding { + text: string | string[]; + /** + * When provided with too long context should the model error out or truncate the context to fit? + */ + truncate_inputs?: boolean; +} +interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 { + /** + * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts + */ + query?: string; + /** + * List of provided contexts. Note that the index in this array is important, as the response will refer to it. + */ + contexts: { + /** + * One of the provided context content + */ + text?: string; + }[]; + /** + * When provided with too long context should the model error out or truncate the context to fit? + */ + truncate_inputs?: boolean; +} +interface Ai_Cf_Baai_Bge_M3_Input_Embedding_1 { + text: string | string[]; + /** + * When provided with too long context should the model error out or truncate the context to fit? + */ + truncate_inputs?: boolean; +} +type Ai_Cf_Baai_Bge_M3_Output = Ai_Cf_Baai_Bge_M3_Ouput_Query | Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts | Ai_Cf_Baai_Bge_M3_Ouput_Embedding | Ai_Cf_Baai_Bge_M3_AsyncResponse; +interface Ai_Cf_Baai_Bge_M3_Ouput_Query { + response?: { + /** + * Index of the context in the request + */ + id?: number; + /** + * Score of the context under the index. + */ + score?: number; + }[]; +} +interface Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts { + response?: number[][]; + shape?: number[]; + /** + * The pooling method used in the embedding process. + */ + pooling?: "mean" | "cls"; +} +interface Ai_Cf_Baai_Bge_M3_Ouput_Embedding { + shape?: number[]; + /** + * Embeddings of the requested text values + */ + data?: number[][]; + /** + * The pooling method used in the embedding process. + */ + pooling?: "mean" | "cls"; +} +interface Ai_Cf_Baai_Bge_M3_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Baai_Bge_M3 { + inputs: Ai_Cf_Baai_Bge_M3_Input; + postProcessedOutputs: Ai_Cf_Baai_Bge_M3_Output; +} +interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input { + /** + * A text description of the image you want to generate. + */ + prompt: string; + /** + * The number of diffusion steps; higher values can improve quality but take longer. + */ + steps?: number; +} +interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output { + /** + * The generated image in Base64 format. + */ + image?: string; +} +declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell { + inputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input; + postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output; +} +type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input = Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Prompt | Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages; +interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + image?: number[] | (string & NonNullable); + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; +} +interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role?: string; + /** + * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 + */ + tool_call_id?: string; + content?: string | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }[] | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }; + }[]; + image?: number[] | (string & NonNullable); + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + /** + * If true, the response will be streamed back incrementally. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output = { + /** + * The generated text response from the model + */ + response?: string; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + /** + * The name of the tool to be called + */ + name?: string; + }[]; +}; +declare abstract class Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct { + inputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input; + postProcessedOutputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output; +} +type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input = Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch; +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + /** + * The content of the message as a string. + */ + content: string; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch { + requests?: { + /** + * User-supplied reference. This field will be present in the response as well it can be used to reference the request and response. It's NOT validated to be unique. + */ + external_reference?: string; + /** + * Prompt for the text generation model + */ + prompt?: string; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; + response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2; + }[]; +} +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output = { + /** + * The generated text response from the model + */ + response: string; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + /** + * The name of the tool to be called + */ + name?: string; + }[]; +} | string | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse; +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast { + inputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input; + postProcessedOutputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output; +} +interface Ai_Cf_Meta_Llama_Guard_3_8B_Input { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender must alternate between 'user' and 'assistant'. + */ + role: "user" | "assistant"; + /** + * The content of the message as a string. + */ + content: string; + }[]; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Dictate the output format of the generated response. + */ + response_format?: { + /** + * Set to json_object to process and output generated text as JSON. + */ + type?: string; + }; +} +interface Ai_Cf_Meta_Llama_Guard_3_8B_Output { + response?: string | { + /** + * Whether the conversation is safe or not. + */ + safe?: boolean; + /** + * A list of what hazard categories predicted for the conversation, if the conversation is deemed unsafe. + */ + categories?: string[]; + }; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; +} +declare abstract class Base_Ai_Cf_Meta_Llama_Guard_3_8B { + inputs: Ai_Cf_Meta_Llama_Guard_3_8B_Input; + postProcessedOutputs: Ai_Cf_Meta_Llama_Guard_3_8B_Output; +} +interface Ai_Cf_Baai_Bge_Reranker_Base_Input { + /** + * A query you wish to perform against the provided contexts. + */ + /** + * Number of returned results starting with the best score. + */ + top_k?: number; + /** + * List of provided contexts. Note that the index in this array is important, as the response will refer to it. + */ + contexts: { + /** + * One of the provided context content + */ + text?: string; + }[]; +} +interface Ai_Cf_Baai_Bge_Reranker_Base_Output { + response?: { + /** + * Index of the context in the request + */ + id?: number; + /** + * Score of the context under the index. + */ + score?: number; + }[]; +} +declare abstract class Base_Ai_Cf_Baai_Bge_Reranker_Base { + inputs: Ai_Cf_Baai_Bge_Reranker_Base_Input; + postProcessedOutputs: Ai_Cf_Baai_Bge_Reranker_Base_Output; +} +type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input = Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt | Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages; +interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + /** + * The content of the message as a string. + */ + content: string; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output = { + /** + * The generated text response from the model + */ + response: string; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + /** + * The name of the tool to be called + */ + name?: string; + }[]; +}; +declare abstract class Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct { + inputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input; + postProcessedOutputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output; +} +type Ai_Cf_Qwen_Qwq_32B_Input = Ai_Cf_Qwen_Qwq_32B_Prompt | Ai_Cf_Qwen_Qwq_32B_Messages; +interface Ai_Cf_Qwen_Qwq_32B_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwq_32B_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role?: string; + /** + * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 + */ + tool_call_id?: string; + content?: string | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }[] | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +type Ai_Cf_Qwen_Qwq_32B_Output = { + /** + * The generated text response from the model + */ + response: string; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + /** + * The name of the tool to be called + */ + name?: string; + }[]; +}; +declare abstract class Base_Ai_Cf_Qwen_Qwq_32B { + inputs: Ai_Cf_Qwen_Qwq_32B_Input; + postProcessedOutputs: Ai_Cf_Qwen_Qwq_32B_Output; +} +type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input = Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Prompt | Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages; +interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role?: string; + /** + * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 + */ + tool_call_id?: string; + content?: string | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }[] | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output = { + /** + * The generated text response from the model + */ + response: string; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + /** + * The name of the tool to be called + */ + name?: string; + }[]; +}; +declare abstract class Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct { + inputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input; + postProcessedOutputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output; +} +type Ai_Cf_Google_Gemma_3_12B_It_Input = Ai_Cf_Google_Gemma_3_12B_It_Prompt | Ai_Cf_Google_Gemma_3_12B_It_Messages; +interface Ai_Cf_Google_Gemma_3_12B_It_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Google_Gemma_3_12B_It_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role?: string; + content?: string | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }[]; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +type Ai_Cf_Google_Gemma_3_12B_It_Output = { + /** + * The generated text response from the model + */ + response: string; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + /** + * The name of the tool to be called + */ + name?: string; + }[]; +}; +declare abstract class Base_Ai_Cf_Google_Gemma_3_12B_It { + inputs: Ai_Cf_Google_Gemma_3_12B_It_Input; + postProcessedOutputs: Ai_Cf_Google_Gemma_3_12B_It_Output; +} +type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input = Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Async_Batch; +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role?: string; + /** + * The tool call id. If you don't know what to put here you can fall back to 000000001 + */ + tool_call_id?: string; + content?: string | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }[] | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Async_Batch { + requests: (Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner)[]; +} +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role?: string; + /** + * The tool call id. If you don't know what to put here you can fall back to 000000001 + */ + tool_call_id?: string; + content?: string | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }[] | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. */ - start?: number; + frequency_penalty?: number; /** - * The ending second when the word completes + * Increases the likelihood of the model introducing new topics. */ - end?: number; - }[]; - vtt?: string; + presence_penalty?: number; } -declare abstract class Base_Ai_Cf_Openai_Whisper { - inputs: Ai_Cf_Openai_Whisper_Input; - postProcessedOutputs: Ai_Cf_Openai_Whisper_Output; -} -type Ai_Cf_Meta_M2M100_1_2B_Input = - | { - /** - * The text to be translated - */ - text: string; - /** - * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified - */ - source_lang?: string; - /** - * The language code to translate the text into (e.g., 'es' for Spanish) - */ - target_lang: string; - } - | { - /** - * Batch of the embeddings requests to run using async-queue - */ - requests: { +type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output = { + /** + * The generated text response from the model + */ + response: string; + /** + * Usage statistics for the inference request + */ + usage?: { /** - * The text to be translated + * Total number of tokens in input */ - text: string; + prompt_tokens?: number; /** - * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified + * Total number of tokens in output */ - source_lang?: string; + completion_tokens?: number; /** - * The language code to translate the text into (e.g., 'es' for Spanish) + * Total number of input and output tokens */ - target_lang: string; - }[]; + total_tokens?: number; }; -type Ai_Cf_Meta_M2M100_1_2B_Output = - | { - /** - * The translated text in the target language - */ - translated_text?: string; - } - | Ai_Cf_Meta_M2M100_1_2B_AsyncResponse; -interface Ai_Cf_Meta_M2M100_1_2B_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} -declare abstract class Base_Ai_Cf_Meta_M2M100_1_2B { - inputs: Ai_Cf_Meta_M2M100_1_2B_Input; - postProcessedOutputs: Ai_Cf_Meta_M2M100_1_2B_Output; -} -type Ai_Cf_Baai_Bge_Small_En_V1_5_Input = - | { - text: string | string[]; - /** - * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. - */ - pooling?: 'mean' | 'cls'; - } - | { - /** - * Batch of the embeddings requests to run using async-queue - */ - requests: { - text: string | string[]; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { /** - * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. + * The tool call id. */ - pooling?: 'mean' | 'cls'; - }[]; - }; -type Ai_Cf_Baai_Bge_Small_En_V1_5_Output = - | { - shape?: number[]; - /** - * Embeddings of the requested text values - */ - data?: number[][]; - /** - * The pooling method used in the embedding process. - */ - pooling?: 'mean' | 'cls'; - } - | Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse; -interface Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} -declare abstract class Base_Ai_Cf_Baai_Bge_Small_En_V1_5 { - inputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Input; - postProcessedOutputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Output; -} -type Ai_Cf_Baai_Bge_Large_En_V1_5_Input = - | { - text: string | string[]; - /** - * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. - */ - pooling?: 'mean' | 'cls'; - } - | { - /** - * Batch of the embeddings requests to run using async-queue - */ - requests: { - text: string | string[]; + id?: string; /** - * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. + * Specifies the type of tool (e.g., 'function'). */ - pooling?: 'mean' | 'cls'; - }[]; - }; -type Ai_Cf_Baai_Bge_Large_En_V1_5_Output = - | { - shape?: number[]; - /** - * Embeddings of the requested text values - */ - data?: number[][]; - /** - * The pooling method used in the embedding process. - */ - pooling?: 'mean' | 'cls'; - } - | Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse; -interface Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} -declare abstract class Base_Ai_Cf_Baai_Bge_Large_En_V1_5 { - inputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Input; - postProcessedOutputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Output; -} -type Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input = - | string - | { - /** - * The input text prompt for the model to generate a response. - */ - prompt?: string; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; - image: number[] | (string & NonNullable); - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - }; -interface Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output { - description?: string; + type?: string; + /** + * Details of the function tool. + */ + function?: { + /** + * The name of the tool to be called + */ + name?: string; + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + }; + }[]; +}; +declare abstract class Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct { + inputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input; + postProcessedOutputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output; } -declare abstract class Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M { - inputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input; - postProcessedOutputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output; -} -type Ai_Cf_Openai_Whisper_Tiny_En_Input = - | string - | { - /** - * An array of integers that represent the audio data constrained to 8-bit unsigned integer values - */ - audio: number[]; - }; -interface Ai_Cf_Openai_Whisper_Tiny_En_Output { - /** - * The transcription - */ - text: string; - word_count?: number; - words?: { - word?: string; +type Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Input = Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Async_Batch; +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt { /** - * The second this word begins in the recording + * The input text prompt for the model to generate a response. */ - start?: number; + prompt: string; /** - * The ending second when the word completes + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. */ - end?: number; - }[]; - vtt?: string; -} -declare abstract class Base_Ai_Cf_Openai_Whisper_Tiny_En { - inputs: Ai_Cf_Openai_Whisper_Tiny_En_Input; - postProcessedOutputs: Ai_Cf_Openai_Whisper_Tiny_En_Output; + lora?: string; + response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; } -interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input { - /** - * Base64 encoded value of the audio data. - */ - audio: string; - /** - * Supported tasks are 'translate' or 'transcribe'. - */ - task?: string; - /** - * The language of the audio being transcribed or translated. - */ - language?: string; - /** - * Preprocess the audio with a voice activity detection model. - */ - vad_filter?: boolean; - /** - * A text prompt to help provide context to the model on the contents of the audio. - */ - initial_prompt?: string; - /** - * The prefix it appended the the beginning of the output of the transcription and can guide the transcription result. - */ - prefix?: string; +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode { + type?: "json_object" | "json_schema"; + json_schema?: unknown; } -interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output { - transcription_info?: { +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages { /** - * The language of the audio being transcribed or translated. + * An array of message objects representing the conversation history. */ - language?: string; + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + /** + * The content of the message as a string. + */ + content: string; + }[]; + functions?: { + name: string; + code: string; + }[]; /** - * The confidence level or probability of the detected language being accurate, represented as a decimal between 0 and 1. + * A list of tools available for the assistant to use. */ - language_probability?: number; + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1; /** - * The total duration of the original audio file, in seconds. + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ - duration?: number; + raw?: boolean; /** - * The duration of the audio after applying Voice Activity Detection (VAD) to remove silent or irrelevant sections, in seconds. + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. */ - duration_after_vad?: number; - }; - /** - * The complete transcription of the audio. - */ - text: string; - /** - * The total number of words in the transcription. - */ - word_count?: number; - segments?: { + stream?: boolean; /** - * The starting time of the segment within the audio, in seconds. + * The maximum number of tokens to generate in the response. */ - start?: number; + max_tokens?: number; /** - * The ending time of the segment within the audio, in seconds. + * Controls the randomness of the output; higher values produce more random results. */ - end?: number; + temperature?: number; /** - * The transcription of the segment. + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. */ - text?: string; + top_p?: number; /** - * The temperature used in the decoding process, controlling randomness in predictions. Lower values result in more deterministic outputs. + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. */ - temperature?: number; + top_k?: number; /** - * The average log probability of the predictions for the words in this segment, indicating overall confidence. + * Random seed for reproducibility of the generation. */ - avg_logprob?: number; + seed?: number; /** - * The compression ratio of the input to the output, measuring how much the text was compressed during the transcription process. + * Penalty for repeated tokens; higher values discourage repetition. */ - compression_ratio?: number; + repetition_penalty?: number; /** - * The probability that the segment contains no speech, represented as a decimal between 0 and 1. + * Decreases the likelihood of the model repeating the same lines verbatim. */ - no_speech_prob?: number; - words?: { - /** - * The individual word transcribed from the audio. - */ - word?: string; - /** - * The starting time of the word within the audio, in seconds. - */ - start?: number; - /** - * The ending time of the word within the audio, in seconds. - */ - end?: number; - }[]; - }[]; - /** - * The transcription in WebVTT format, which includes timing and text information for use in subtitles. - */ - vtt?: string; -} -declare abstract class Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo { - inputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input; - postProcessedOutputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output; -} -type Ai_Cf_Baai_Bge_M3_Input = - | Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts - | Ai_Cf_Baai_Bge_M3_Input_Embedding - | { - /** - * Batch of the embeddings requests to run using async-queue - */ - requests: ( - | Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 - | Ai_Cf_Baai_Bge_M3_Input_Embedding_1 - )[]; - }; -interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts { - /** - * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts - */ - query?: string; - /** - * List of provided contexts. Note that the index in this array is important, as the response will refer to it. - */ - contexts: { + frequency_penalty?: number; /** - * One of the provided context content + * Increases the likelihood of the model introducing new topics. */ - text?: string; - }[]; - /** - * When provided with too long context should the model error out or truncate the context to fit? - */ - truncate_inputs?: boolean; + presence_penalty?: number; } -interface Ai_Cf_Baai_Bge_M3_Input_Embedding { - text: string | string[]; - /** - * When provided with too long context should the model error out or truncate the context to fit? - */ - truncate_inputs?: boolean; +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; } -interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 { - /** - * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts - */ - query?: string; - /** - * List of provided contexts. Note that the index in this array is important, as the response will refer to it. - */ - contexts: { +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Async_Batch { + requests: (Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt_1 | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1)[]; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt_1 { /** - * One of the provided context content + * The input text prompt for the model to generate a response. */ - text?: string; - }[]; - /** - * When provided with too long context should the model error out or truncate the context to fit? - */ - truncate_inputs?: boolean; + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; } -interface Ai_Cf_Baai_Bge_M3_Input_Embedding_1 { - text: string | string[]; - /** - * When provided with too long context should the model error out or truncate the context to fit? - */ - truncate_inputs?: boolean; -} -type Ai_Cf_Baai_Bge_M3_Output = - | Ai_Cf_Baai_Bge_M3_Ouput_Query - | Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts - | Ai_Cf_Baai_Bge_M3_Ouput_Embedding - | Ai_Cf_Baai_Bge_M3_AsyncResponse; -interface Ai_Cf_Baai_Bge_M3_Ouput_Query { - response?: { +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1 { /** - * Index of the context in the request + * An array of message objects representing the conversation history. */ - id?: number; + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + /** + * The content of the message as a string. + */ + content: string; + }[]; + functions?: { + name: string; + code: string; + }[]; /** - * Score of the context under the index. + * A list of tools available for the assistant to use. */ - score?: number; - }[]; -} -interface Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts { - response?: number[][]; - shape?: number[]; - /** - * The pooling method used in the embedding process. - */ - pooling?: 'mean' | 'cls'; -} -interface Ai_Cf_Baai_Bge_M3_Ouput_Embedding { - shape?: number[]; - /** - * Embeddings of the requested text values - */ - data?: number[][]; - /** - * The pooling method used in the embedding process. - */ - pooling?: 'mean' | 'cls'; -} -interface Ai_Cf_Baai_Bge_M3_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} -declare abstract class Base_Ai_Cf_Baai_Bge_M3 { - inputs: Ai_Cf_Baai_Bge_M3_Input; - postProcessedOutputs: Ai_Cf_Baai_Bge_M3_Output; -} -interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input { - /** - * A text description of the image you want to generate. - */ - prompt: string; - /** - * The number of diffusion steps; higher values can improve quality but take longer. - */ - steps?: number; -} -interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output { - /** - * The generated image in Base64 format. - */ - image?: string; -} -declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell { - inputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input; - postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output; -} -type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input = - | Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Prompt - | Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages; -interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - image?: number[] | (string & NonNullable); - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; -} -interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role?: string; - /** - * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 - */ - tool_call_id?: string; - content?: - | string - | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }[] - | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }; - }[]; - image?: number[] | (string & NonNullable); - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ( - | { + tools?: ({ /** * The name of the tool. More descriptive the better. */ @@ -5028,52 +7139,6 @@ interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages { * Schema defining the parameters accepted by the tool. */ parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } - | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { /** * The type of the parameters object (usually 'object'). */ @@ -5086,201 +7151,19 @@ interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages { * Definitions of each parameter. */ properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - } - )[]; - /** - * If true, the response will be streamed back incrementally. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output = { - /** - * The generated text response from the model - */ - response?: string; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object; - /** - * The name of the tool to be called - */ - name?: string; - }[]; -}; -declare abstract class Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct { - inputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input; - postProcessedOutputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output; -} -type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input = - | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt - | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages - | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch; -interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; - response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode { - type?: 'json_object' | 'json_schema'; - json_schema?: unknown; -} -interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role: string; - /** - * The content of the message as a string. - */ - content: string; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ( - | { - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; }; - }; }; - } - | { + } | { /** * Specifies the type of tool (e.g., 'function'). */ @@ -5289,101 +7172,49 @@ interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { * Details of the function tool. */ function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { /** - * The type of the parameters object (usually 'object'). + * The name of the function. */ - type: string; + name: string; /** - * List of required parameter names. + * A brief description of what the function does. */ - required?: string[]; + description: string; /** - * Definitions of each parameter. + * Schema defining the parameters accepted by the function. */ - properties: { - [k: string]: { + parameters: { /** - * The data type of the parameter. + * The type of the parameters object (usually 'object'). */ type: string; /** - * A description of the expected parameter. + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. */ - description: string; - }; + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; }; - }; }; - } - )[]; - response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1 { - type?: 'json_object' | 'json_schema'; - json_schema?: unknown; -} -interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch { - requests?: { + })[]; + response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_3; /** - * User-supplied reference. This field will be present in the response as well it can be used to reference the request and response. It's NOT validated to be unique. + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ - external_reference?: string; - /** - * Prompt for the text generation model - */ - prompt?: string; + raw?: boolean; /** * If true, the response will be streamed back incrementally using SSE, Server Sent Events. */ @@ -5400,6 +7231,10 @@ interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch { * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. */ top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; /** * Random seed for reproducibility of the generation. */ @@ -5416,23 +7251,94 @@ interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch { * Increases the likelihood of the model introducing new topics. */ presence_penalty?: number; - response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2; - }[]; } -interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2 { - type?: 'json_object' | 'json_schema'; - json_schema?: unknown; -} -type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output = - | { - /** - * The generated text response from the model - */ - response: string; - /** - * Usage statistics for the inference request - */ - usage?: { +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_3 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +type Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Output = Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Chat_Completion_Response | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Text_Completion_Response | string | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_AsyncResponse; +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Chat_Completion_Response { + /** + * Unique identifier for the completion + */ + id?: string; + /** + * Object type identifier + */ + object?: "chat.completion"; + /** + * Unix timestamp of when the completion was created + */ + created?: number; + /** + * Model used for the completion + */ + model?: string; + /** + * List of completion choices + */ + choices?: { + /** + * Index of the choice in the list + */ + index?: number; + /** + * The message generated by the model + */ + message?: { + /** + * Role of the message author + */ + role: string; + /** + * The content of the message + */ + content: string; + /** + * Internal reasoning content (if available) + */ + reasoning_content?: string; + /** + * Tool calls made by the assistant + */ + tool_calls?: { + /** + * Unique identifier for the tool call + */ + id: string; + /** + * Type of tool call + */ + type: "function"; + function: { + /** + * Name of the function to call + */ + name: string; + /** + * JSON string of arguments for the function + */ + arguments: string; + }; + }[]; + }; + /** + * Reason why the model stopped generating + */ + finish_reason?: string; + /** + * Stop reason (may be null) + */ + stop_reason?: string | null; + /** + * Log probabilities (if requested) + */ + logprobs?: {} | null; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { /** * Total number of tokens in input */ @@ -5445,1804 +7351,540 @@ type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output = * Total number of input and output tokens */ total_tokens?: number; - }; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { + }; + /** + * Log probabilities for the prompt (if requested) + */ + prompt_logprobs?: {} | null; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Text_Completion_Response { + /** + * Unique identifier for the completion + */ + id?: string; + /** + * Object type identifier + */ + object?: "text_completion"; + /** + * Unix timestamp of when the completion was created + */ + created?: number; + /** + * Model used for the completion + */ + model?: string; + /** + * List of completion choices + */ + choices?: { /** - * The arguments passed to be passed to the tool call request + * Index of the choice in the list */ - arguments?: object; + index: number; /** - * The name of the tool to be called + * The generated text completion */ - name?: string; - }[]; - } - | string - | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse; -interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; + text: string; + /** + * Reason why the model stopped generating + */ + finish_reason: string; + /** + * Stop reason (may be null) + */ + stop_reason?: string | null; + /** + * Log probabilities (if requested) + */ + logprobs?: {} | null; + /** + * Log probabilities for the prompt (if requested) + */ + prompt_logprobs?: {} | null; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; } -declare abstract class Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast { - inputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input; - postProcessedOutputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output; +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; } -interface Ai_Cf_Meta_Llama_Guard_3_8B_Input { - /** - * An array of message objects representing the conversation history. - */ - messages: { +declare abstract class Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8 { + inputs: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Input; + postProcessedOutputs: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Output; +} +interface Ai_Cf_Deepgram_Nova_3_Input { + audio: { + body: object; + contentType: string; + }; /** - * The role of the message sender must alternate between 'user' and 'assistant'. + * Sets how the model will interpret strings submitted to the custom_topic param. When strict, the model will only return topics submitted using the custom_topic param. When extended, the model will return its own detected topics in addition to those submitted using the custom_topic param. */ - role: 'user' | 'assistant'; + custom_topic_mode?: "extended" | "strict"; /** - * The content of the message as a string. + * Custom topics you want the model to detect within your input audio or text if present Submit up to 100 */ - content: string; - }[]; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Dictate the output format of the generated response. - */ - response_format?: { - /** - * Set to json_object to process and output generated text as JSON. + custom_topic?: string; + /** + * Sets how the model will interpret intents submitted to the custom_intent param. When strict, the model will only return intents submitted using the custom_intent param. When extended, the model will return its own detected intents in addition those submitted using the custom_intents param */ - type?: string; - }; -} -interface Ai_Cf_Meta_Llama_Guard_3_8B_Output { - response?: - | string - | { - /** - * Whether the conversation is safe or not. - */ - safe?: boolean; - /** - * A list of what hazard categories predicted for the conversation, if the conversation is deemed unsafe. - */ - categories?: string[]; - }; - /** - * Usage statistics for the inference request - */ - usage?: { + custom_intent_mode?: "extended" | "strict"; + /** + * Custom intents you want the model to detect within your input audio if present + */ + custom_intent?: string; + /** + * Identifies and extracts key entities from content in submitted audio + */ + detect_entities?: boolean; + /** + * Identifies the dominant language spoken in submitted audio + */ + detect_language?: boolean; + /** + * Recognize speaker changes. Each word in the transcript will be assigned a speaker number starting at 0 + */ + diarize?: boolean; + /** + * Identify and extract key entities from content in submitted audio + */ + dictation?: boolean; + /** + * Specify the expected encoding of your submitted audio + */ + encoding?: "linear16" | "flac" | "mulaw" | "amr-nb" | "amr-wb" | "opus" | "speex" | "g729"; + /** + * Arbitrary key-value pairs that are attached to the API response for usage in downstream processing + */ + extra?: string; + /** + * Filler Words can help transcribe interruptions in your audio, like 'uh' and 'um' + */ + filler_words?: boolean; + /** + * Key term prompting can boost or suppress specialized terminology and brands. + */ + keyterm?: string; + /** + * Keywords can boost or suppress specialized terminology and brands. + */ + keywords?: string; + /** + * The BCP-47 language tag that hints at the primary spoken language. Depending on the Model and API endpoint you choose only certain languages are available. + */ + language?: string; + /** + * Spoken measurements will be converted to their corresponding abbreviations. + */ + measurements?: boolean; + /** + * Opts out requests from the Deepgram Model Improvement Program. Refer to our Docs for pricing impacts before setting this to true. https://dpgr.am/deepgram-mip. + */ + mip_opt_out?: boolean; + /** + * Mode of operation for the model representing broad area of topic that will be talked about in the supplied audio + */ + mode?: "general" | "medical" | "finance"; + /** + * Transcribe each audio channel independently. + */ + multichannel?: boolean; + /** + * Numerals converts numbers from written format to numerical format. + */ + numerals?: boolean; + /** + * Splits audio into paragraphs to improve transcript readability. + */ + paragraphs?: boolean; /** - * Total number of tokens in input + * Profanity Filter looks for recognized profanity and converts it to the nearest recognized non-profane word or removes it from the transcript completely. */ - prompt_tokens?: number; + profanity_filter?: boolean; /** - * Total number of tokens in output + * Add punctuation and capitalization to the transcript. */ - completion_tokens?: number; + punctuate?: boolean; /** - * Total number of input and output tokens + * Redaction removes sensitive information from your transcripts. */ - total_tokens?: number; - }; -} -declare abstract class Base_Ai_Cf_Meta_Llama_Guard_3_8B { - inputs: Ai_Cf_Meta_Llama_Guard_3_8B_Input; - postProcessedOutputs: Ai_Cf_Meta_Llama_Guard_3_8B_Output; -} -interface Ai_Cf_Baai_Bge_Reranker_Base_Input { - /** - * A query you wish to perform against the provided contexts. - */ - /** - * Number of returned results starting with the best score. - */ - top_k?: number; - /** - * List of provided contexts. Note that the index in this array is important, as the response will refer to it. - */ - contexts: { - /** - * One of the provided context content + redact?: string; + /** + * Search for terms or phrases in submitted audio and replaces them. */ - text?: string; - }[]; -} -interface Ai_Cf_Baai_Bge_Reranker_Base_Output { - response?: { + replace?: string; /** - * Index of the context in the request + * Search for terms or phrases in submitted audio. */ - id?: number; + search?: string; /** - * Score of the context under the index. + * Recognizes the sentiment throughout a transcript or text. */ - score?: number; - }[]; -} -declare abstract class Base_Ai_Cf_Baai_Bge_Reranker_Base { - inputs: Ai_Cf_Baai_Bge_Reranker_Base_Input; - postProcessedOutputs: Ai_Cf_Baai_Bge_Reranker_Base_Output; -} -type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input = - | Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt - | Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages; -interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; - response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode { - type?: 'json_object' | 'json_schema'; - json_schema?: unknown; -} -interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { + sentiment?: boolean; /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + * Apply formatting to transcript output. When set to true, additional formatting will be applied to transcripts to improve readability. */ - role: string; + smart_format?: boolean; /** - * The content of the message as a string. + * Detect topics throughout a transcript or text. */ - content: string; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ( - | { - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } - | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - } - )[]; - response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1 { - type?: 'json_object' | 'json_schema'; - json_schema?: unknown; -} -type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output = { - /** - * The generated text response from the model - */ - response: string; - /** - * Usage statistics for the inference request - */ - usage?: { + topics?: boolean; /** - * Total number of tokens in input + * Segments speech into meaningful semantic units. */ - prompt_tokens?: number; + utterances?: boolean; /** - * Total number of tokens in output + * Seconds to wait before detecting a pause between words in submitted audio. */ - completion_tokens?: number; + utt_split?: number; /** - * Total number of input and output tokens + * The number of channels in the submitted audio */ - total_tokens?: number; - }; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { + channels?: number; /** - * The arguments passed to be passed to the tool call request + * Specifies whether the streaming endpoint should provide ongoing transcription updates as more audio is received. When set to true, the endpoint sends continuous updates, meaning transcription results may evolve over time. Note: Supported only for webosockets. */ - arguments?: object; + interim_results?: boolean; /** - * The name of the tool to be called + * Indicates how long model will wait to detect whether a speaker has finished speaking or pauses for a significant period of time. When set to a value, the streaming endpoint immediately finalizes the transcription for the processed time range and returns the transcript with a speech_final parameter set to true. Can also be set to false to disable endpointing */ - name?: string; - }[]; -}; -declare abstract class Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct { - inputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input; - postProcessedOutputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output; -} -type Ai_Cf_Qwen_Qwq_32B_Input = Ai_Cf_Qwen_Qwq_32B_Prompt | Ai_Cf_Qwen_Qwq_32B_Messages; -interface Ai_Cf_Qwen_Qwq_32B_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; + endpointing?: string; + /** + * Indicates that speech has started. You'll begin receiving Speech Started messages upon speech starting. Note: Supported only for webosockets. + */ + vad_events?: boolean; + /** + * Indicates how long model will wait to send an UtteranceEnd message after a word has been transcribed. Use with interim_results. Note: Supported only for webosockets. + */ + utterance_end_ms?: boolean; } -interface Ai_Cf_Qwen_Qwq_32B_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role?: string; - /** - * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 - */ - tool_call_id?: string; - content?: - | string - | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }[] - | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ( - | { - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; +interface Ai_Cf_Deepgram_Nova_3_Output { + results?: { + channels?: { + alternatives?: { + confidence?: number; + transcript?: string; + words?: { + confidence?: number; + end?: number; + start?: number; + word?: string; + }[]; + }[]; + }[]; + summary?: { + result?: string; + short?: string; }; - } - | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; + sentiments?: { + segments?: { + text?: string; + start_word?: number; + end_word?: number; + sentiment?: string; + sentiment_score?: number; + }[]; + average?: { + sentiment?: string; + sentiment_score?: number; }; - }; }; - } - )[]; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; + }; } -type Ai_Cf_Qwen_Qwq_32B_Output = { - /** - * The generated text response from the model - */ - response: string; - /** - * Usage statistics for the inference request - */ - usage?: { +declare abstract class Base_Ai_Cf_Deepgram_Nova_3 { + inputs: Ai_Cf_Deepgram_Nova_3_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Nova_3_Output; +} +interface Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Input { + queries?: string | string[]; /** - * Total number of tokens in input + * Optional instruction for the task */ - prompt_tokens?: number; + instruction?: string; + documents?: string | string[]; + text?: string | string[]; +} +interface Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Output { + data?: number[][]; + shape?: number[]; +} +declare abstract class Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B { + inputs: Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Input; + postProcessedOutputs: Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Output; +} +type Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input = { /** - * Total number of tokens in output + * readable stream with audio data and content-type specified for that data */ - completion_tokens?: number; + audio: { + body: object; + contentType: string; + }; /** - * Total number of input and output tokens + * type of data PCM data that's sent to the inference server as raw array */ - total_tokens?: number; - }; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { + dtype?: "uint8" | "float32" | "float64"; +} | { /** - * The arguments passed to be passed to the tool call request + * base64 encoded audio data */ - arguments?: object; + audio: string; /** - * The name of the tool to be called + * type of data PCM data that's sent to the inference server as raw array */ - name?: string; - }[]; + dtype?: "uint8" | "float32" | "float64"; }; -declare abstract class Base_Ai_Cf_Qwen_Qwq_32B { - inputs: Ai_Cf_Qwen_Qwq_32B_Input; - postProcessedOutputs: Ai_Cf_Qwen_Qwq_32B_Output; +interface Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output { + /** + * if true, end-of-turn was detected + */ + is_complete?: boolean; + /** + * probability of the end-of-turn detection + */ + probability?: number; } -type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input = - | Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Prompt - | Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages; -interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; +declare abstract class Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2 { + inputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input; + postProcessedOutputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output; } -interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role?: string; - /** - * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 - */ - tool_call_id?: string; - content?: - | string - | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }[] - | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ( - | { - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } - | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - } - )[]; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; +declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_120B { + inputs: ResponsesInput; + postProcessedOutputs: ResponsesOutput; } -type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output = { - /** - * The generated text response from the model - */ - response: string; - /** - * Usage statistics for the inference request - */ - usage?: { +declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_20B { + inputs: ResponsesInput; + postProcessedOutputs: ResponsesOutput; +} +interface Ai_Cf_Leonardo_Phoenix_1_0_Input { /** - * Total number of tokens in input + * A text description of the image you want to generate. */ - prompt_tokens?: number; + prompt: string; /** - * Total number of tokens in output + * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt */ - completion_tokens?: number; + guidance?: number; /** - * Total number of input and output tokens + * Random seed for reproducibility of the image generation */ - total_tokens?: number; - }; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { + seed?: number; /** - * The arguments passed to be passed to the tool call request + * The height of the generated image in pixels */ - arguments?: object; + height?: number; /** - * The name of the tool to be called + * The width of the generated image in pixels */ - name?: string; - }[]; -}; -declare abstract class Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct { - inputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input; - postProcessedOutputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output; -} -type Ai_Cf_Google_Gemma_3_12B_It_Input = - | Ai_Cf_Google_Gemma_3_12B_It_Prompt - | Ai_Cf_Google_Gemma_3_12B_It_Messages; -interface Ai_Cf_Google_Gemma_3_12B_It_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Google_Gemma_3_12B_It_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role?: string; - content?: - | string - | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }[]; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ( - | { - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } - | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - } - )[]; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; + width?: number; + /** + * The number of diffusion steps; higher values can improve quality but take longer + */ + num_steps?: number; + /** + * Specify what to exclude from the generated images + */ + negative_prompt?: string; } -type Ai_Cf_Google_Gemma_3_12B_It_Output = { - /** - * The generated text response from the model - */ - response: string; - /** - * Usage statistics for the inference request - */ - usage?: { +/** + * The generated image in JPEG format + */ +type Ai_Cf_Leonardo_Phoenix_1_0_Output = string; +declare abstract class Base_Ai_Cf_Leonardo_Phoenix_1_0 { + inputs: Ai_Cf_Leonardo_Phoenix_1_0_Input; + postProcessedOutputs: Ai_Cf_Leonardo_Phoenix_1_0_Output; +} +interface Ai_Cf_Leonardo_Lucid_Origin_Input { /** - * Total number of tokens in input + * A text description of the image you want to generate. */ - prompt_tokens?: number; + prompt: string; /** - * Total number of tokens in output + * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt */ - completion_tokens?: number; + guidance?: number; /** - * Total number of input and output tokens + * Random seed for reproducibility of the image generation */ - total_tokens?: number; - }; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { + seed?: number; /** - * The arguments passed to be passed to the tool call request + * The height of the generated image in pixels */ - arguments?: object; + height?: number; /** - * The name of the tool to be called + * The width of the generated image in pixels */ - name?: string; - }[]; -}; -declare abstract class Base_Ai_Cf_Google_Gemma_3_12B_It { - inputs: Ai_Cf_Google_Gemma_3_12B_It_Input; - postProcessedOutputs: Ai_Cf_Google_Gemma_3_12B_It_Output; + width?: number; + /** + * The number of diffusion steps; higher values can improve quality but take longer + */ + num_steps?: number; + /** + * The number of diffusion steps; higher values can improve quality but take longer + */ + steps?: number; } -type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input = - | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt - | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages - | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Async_Batch; -interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; +interface Ai_Cf_Leonardo_Lucid_Origin_Output { + /** + * The generated image in Base64 format. + */ + image?: string; } -interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode { - type?: 'json_object' | 'json_schema'; - json_schema?: unknown; +declare abstract class Base_Ai_Cf_Leonardo_Lucid_Origin { + inputs: Ai_Cf_Leonardo_Lucid_Origin_Input; + postProcessedOutputs: Ai_Cf_Leonardo_Lucid_Origin_Output; } -interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role?: string; - /** - * The tool call id. If you don't know what to put here you can fall back to 000000001 - */ - tool_call_id?: string; - content?: - | string - | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }[] - | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ( - | { - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } - | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - } - )[]; - response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; +interface Ai_Cf_Deepgram_Aura_1_Input { + /** + * Speaker used to produce the audio. + */ + speaker?: "angus" | "asteria" | "arcas" | "orion" | "orpheus" | "athena" | "luna" | "zeus" | "perseus" | "helios" | "hera" | "stella"; + /** + * Encoding of the output audio. + */ + encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac"; + /** + * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. + */ + container?: "none" | "wav" | "ogg"; + /** + * The text content to be converted to speech + */ + text: string; + /** + * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable + */ + sample_rate?: number; + /** + * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. + */ + bit_rate?: number; } -interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Async_Batch { - requests: ( - | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner - | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner - )[]; +/** + * The generated audio in MP3 format + */ +type Ai_Cf_Deepgram_Aura_1_Output = string; +declare abstract class Base_Ai_Cf_Deepgram_Aura_1 { + inputs: Ai_Cf_Deepgram_Aura_1_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Aura_1_Output; } -interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; +interface Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Input { + /** + * Input text to translate. Can be a single string or a list of strings. + */ + text: string | string[]; + /** + * Target language to translate to + */ + target_language: "asm_Beng" | "awa_Deva" | "ben_Beng" | "bho_Deva" | "brx_Deva" | "doi_Deva" | "eng_Latn" | "gom_Deva" | "gon_Deva" | "guj_Gujr" | "hin_Deva" | "hne_Deva" | "kan_Knda" | "kas_Arab" | "kas_Deva" | "kha_Latn" | "lus_Latn" | "mag_Deva" | "mai_Deva" | "mal_Mlym" | "mar_Deva" | "mni_Beng" | "mni_Mtei" | "npi_Deva" | "ory_Orya" | "pan_Guru" | "san_Deva" | "sat_Olck" | "snd_Arab" | "snd_Deva" | "tam_Taml" | "tel_Telu" | "urd_Arab" | "unr_Deva"; } -interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role?: string; - /** - * The tool call id. If you don't know what to put here you can fall back to 000000001 - */ - tool_call_id?: string; - content?: - | string - | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }[] - | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ( - | { - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } - | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - } - )[]; - response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; +interface Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Output { + /** + * Translated texts + */ + translations: string[]; } -type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output = { - /** - * The generated text response from the model - */ - response: string; - /** - * Usage statistics for the inference request - */ - usage?: { +declare abstract class Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B { + inputs: Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Input; + postProcessedOutputs: Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Output; +} +type Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Input = Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Async_Batch; +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt { /** - * Total number of tokens in input + * The input text prompt for the model to generate a response. */ - prompt_tokens?: number; + prompt: string; /** - * Total number of tokens in output + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. */ - completion_tokens?: number; + lora?: string; + response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode; /** - * Total number of input and output tokens + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ - total_tokens?: number; - }; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { + raw?: boolean; /** - * The tool call id. + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. */ - id?: string; + stream?: boolean; /** - * Specifies the type of tool (e.g., 'function'). + * The maximum number of tokens to generate in the response. */ - type?: string; + max_tokens?: number; /** - * Details of the function tool. - */ - function?: { - /** - * The name of the tool to be called - */ - name?: string; - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object; - }; - }[]; -}; -declare abstract class Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct { - inputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input; - postProcessedOutputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output; -} -type Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Input = - | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt - | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages - | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Async_Batch; -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; - response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; } -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode { - type?: 'json_object' | 'json_schema'; - json_schema?: unknown; +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode { + type?: "json_object" | "json_schema"; + json_schema?: unknown; } -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages { /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + * An array of message objects representing the conversation history. */ - role: string; + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + /** + * The content of the message as a string. + */ + content: string; + }[]; + functions?: { + name: string; + code: string; + }[]; /** - * The content of the message as a string. + * A list of tools available for the assistant to use. */ - content: string; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ( - | { + tools?: ({ /** * The name of the tool. More descriptive the better. */ @@ -7255,244 +7897,31 @@ interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages { * Schema defining the parameters accepted by the tool. */ parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } - | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { /** * The type of the parameters object (usually 'object'). */ type: string; /** * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - } - )[]; - response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1 { - type?: 'json_object' | 'json_schema'; - json_schema?: unknown; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Async_Batch { - requests: (Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt_1 | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1)[]; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt_1 { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; - response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2 { - type?: 'json_object' | 'json_schema'; - json_schema?: unknown; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1 { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role: string; - /** - * The content of the message as a string. - */ - content: string; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ( - | { - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; }; - }; }; - } - | { + } | { /** * Specifies the type of tool (e.g., 'function'). */ @@ -7501,776 +7930,170 @@ interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1 { * Details of the function tool. */ function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { /** - * The type of the parameters object (usually 'object'). + * The name of the function. */ - type: string; + name: string; /** - * List of required parameter names. + * A brief description of what the function does. */ - required?: string[]; + description: string; /** - * Definitions of each parameter. + * Schema defining the parameters accepted by the function. */ - properties: { - [k: string]: { + parameters: { /** - * The data type of the parameter. + * The type of the parameters object (usually 'object'). */ type: string; /** - * A description of the expected parameter. + * List of required parameter names. */ - description: string; - }; + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; }; - }; - }; - } - )[]; - response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_3; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_3 { - type?: 'json_object' | 'json_schema'; - json_schema?: unknown; -} -type Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Output = - | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Chat_Completion_Response - | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Text_Completion_Response - | string - | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_AsyncResponse; -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Chat_Completion_Response { - /** - * Unique identifier for the completion - */ - id?: string; - /** - * Object type identifier - */ - object?: 'chat.completion'; - /** - * Unix timestamp of when the completion was created - */ - created?: number; - /** - * Model used for the completion - */ - model?: string; - /** - * List of completion choices - */ - choices?: { - /** - * Index of the choice in the list - */ - index?: number; - /** - * The message generated by the model - */ - message?: { - /** - * Role of the message author - */ - role: string; - /** - * The content of the message - */ - content: string; - /** - * Internal reasoning content (if available) - */ - reasoning_content?: string; - /** - * Tool calls made by the assistant - */ - tool_calls?: { - /** - * Unique identifier for the tool call - */ - id: string; - /** - * Type of tool call - */ - type: 'function'; - function: { - /** - * Name of the function to call - */ - name: string; - /** - * JSON string of arguments for the function - */ - arguments: string; }; - }[]; - }; + })[]; + response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_1; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; /** - * Reason why the model stopped generating + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. */ - finish_reason?: string; + top_p?: number; /** - * Stop reason (may be null) + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. */ - stop_reason?: string | null; + top_k?: number; /** - * Log probabilities (if requested) + * Random seed for reproducibility of the generation. */ - logprobs?: {} | null; - }[]; - /** - * Usage statistics for the inference request - */ - usage?: { + seed?: number; /** - * Total number of tokens in input + * Penalty for repeated tokens; higher values discourage repetition. */ - prompt_tokens?: number; + repetition_penalty?: number; /** - * Total number of tokens in output + * Decreases the likelihood of the model repeating the same lines verbatim. */ - completion_tokens?: number; + frequency_penalty?: number; /** - * Total number of input and output tokens + * Increases the likelihood of the model introducing new topics. */ - total_tokens?: number; - }; - /** - * Log probabilities for the prompt (if requested) - */ - prompt_logprobs?: {} | null; + presence_penalty?: number; } -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Text_Completion_Response { - /** - * Unique identifier for the completion - */ - id?: string; - /** - * Object type identifier - */ - object?: 'text_completion'; - /** - * Unix timestamp of when the completion was created - */ - created?: number; - /** - * Model used for the completion - */ - model?: string; - /** - * List of completion choices - */ - choices?: { - /** - * Index of the choice in the list - */ - index: number; - /** - * The generated text completion +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_1 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Async_Batch { + requests: (Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt_1 | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages_1)[]; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt_1 { + /** + * The input text prompt for the model to generate a response. */ - text: string; + prompt: string; /** - * Reason why the model stopped generating + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. */ - finish_reason: string; + lora?: string; + response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_2; /** - * Stop reason (may be null) + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ - stop_reason?: string | null; + raw?: boolean; /** - * Log probabilities (if requested) + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. */ - logprobs?: {} | null; + stream?: boolean; /** - * Log probabilities for the prompt (if requested) + * The maximum number of tokens to generate in the response. */ - prompt_logprobs?: {} | null; - }[]; - /** - * Usage statistics for the inference request - */ - usage?: { + max_tokens?: number; /** - * Total number of tokens in input + * Controls the randomness of the output; higher values produce more random results. */ - prompt_tokens?: number; + temperature?: number; /** - * Total number of tokens in output + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. */ - completion_tokens?: number; + top_p?: number; /** - * Total number of input and output tokens + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. */ - total_tokens?: number; - }; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} -declare abstract class Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8 { - inputs: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Input; - postProcessedOutputs: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Output; -} -interface Ai_Cf_Deepgram_Nova_3_Input { - audio: { - body: object; - contentType: string; - }; - /** - * Sets how the model will interpret strings submitted to the custom_topic param. When strict, the model will only return topics submitted using the custom_topic param. When extended, the model will return its own detected topics in addition to those submitted using the custom_topic param. - */ - custom_topic_mode?: 'extended' | 'strict'; - /** - * Custom topics you want the model to detect within your input audio or text if present Submit up to 100 - */ - custom_topic?: string; - /** - * Sets how the model will interpret intents submitted to the custom_intent param. When strict, the model will only return intents submitted using the custom_intent param. When extended, the model will return its own detected intents in addition those submitted using the custom_intents param - */ - custom_intent_mode?: 'extended' | 'strict'; - /** - * Custom intents you want the model to detect within your input audio if present - */ - custom_intent?: string; - /** - * Identifies and extracts key entities from content in submitted audio - */ - detect_entities?: boolean; - /** - * Identifies the dominant language spoken in submitted audio - */ - detect_language?: boolean; - /** - * Recognize speaker changes. Each word in the transcript will be assigned a speaker number starting at 0 - */ - diarize?: boolean; - /** - * Identify and extract key entities from content in submitted audio - */ - dictation?: boolean; - /** - * Specify the expected encoding of your submitted audio - */ - encoding?: 'linear16' | 'flac' | 'mulaw' | 'amr-nb' | 'amr-wb' | 'opus' | 'speex' | 'g729'; - /** - * Arbitrary key-value pairs that are attached to the API response for usage in downstream processing - */ - extra?: string; - /** - * Filler Words can help transcribe interruptions in your audio, like 'uh' and 'um' - */ - filler_words?: boolean; - /** - * Key term prompting can boost or suppress specialized terminology and brands. - */ - keyterm?: string; - /** - * Keywords can boost or suppress specialized terminology and brands. - */ - keywords?: string; - /** - * The BCP-47 language tag that hints at the primary spoken language. Depending on the Model and API endpoint you choose only certain languages are available. - */ - language?: string; - /** - * Spoken measurements will be converted to their corresponding abbreviations. - */ - measurements?: boolean; - /** - * Opts out requests from the Deepgram Model Improvement Program. Refer to our Docs for pricing impacts before setting this to true. https://dpgr.am/deepgram-mip. - */ - mip_opt_out?: boolean; - /** - * Mode of operation for the model representing broad area of topic that will be talked about in the supplied audio - */ - mode?: 'general' | 'medical' | 'finance'; - /** - * Transcribe each audio channel independently. - */ - multichannel?: boolean; - /** - * Numerals converts numbers from written format to numerical format. - */ - numerals?: boolean; - /** - * Splits audio into paragraphs to improve transcript readability. - */ - paragraphs?: boolean; - /** - * Profanity Filter looks for recognized profanity and converts it to the nearest recognized non-profane word or removes it from the transcript completely. - */ - profanity_filter?: boolean; - /** - * Add punctuation and capitalization to the transcript. - */ - punctuate?: boolean; - /** - * Redaction removes sensitive information from your transcripts. - */ - redact?: string; - /** - * Search for terms or phrases in submitted audio and replaces them. - */ - replace?: string; - /** - * Search for terms or phrases in submitted audio. - */ - search?: string; - /** - * Recognizes the sentiment throughout a transcript or text. - */ - sentiment?: boolean; - /** - * Apply formatting to transcript output. When set to true, additional formatting will be applied to transcripts to improve readability. - */ - smart_format?: boolean; - /** - * Detect topics throughout a transcript or text. - */ - topics?: boolean; - /** - * Segments speech into meaningful semantic units. - */ - utterances?: boolean; - /** - * Seconds to wait before detecting a pause between words in submitted audio. - */ - utt_split?: number; - /** - * The number of channels in the submitted audio - */ - channels?: number; - /** - * Specifies whether the streaming endpoint should provide ongoing transcription updates as more audio is received. When set to true, the endpoint sends continuous updates, meaning transcription results may evolve over time. Note: Supported only for webosockets. - */ - interim_results?: boolean; - /** - * Indicates how long model will wait to detect whether a speaker has finished speaking or pauses for a significant period of time. When set to a value, the streaming endpoint immediately finalizes the transcription for the processed time range and returns the transcript with a speech_final parameter set to true. Can also be set to false to disable endpointing - */ - endpointing?: string; - /** - * Indicates that speech has started. You'll begin receiving Speech Started messages upon speech starting. Note: Supported only for webosockets. - */ - vad_events?: boolean; - /** - * Indicates how long model will wait to send an UtteranceEnd message after a word has been transcribed. Use with interim_results. Note: Supported only for webosockets. - */ - utterance_end_ms?: boolean; -} -interface Ai_Cf_Deepgram_Nova_3_Output { - results?: { - channels?: { - alternatives?: { - confidence?: number; - transcript?: string; - words?: { - confidence?: number; - end?: number; - start?: number; - word?: string; - }[]; - }[]; - }[]; - summary?: { - result?: string; - short?: string; - }; - sentiments?: { - segments?: { - text?: string; - start_word?: number; - end_word?: number; - sentiment?: string; - sentiment_score?: number; - }[]; - average?: { - sentiment?: string; - sentiment_score?: number; - }; - }; - }; -} -declare abstract class Base_Ai_Cf_Deepgram_Nova_3 { - inputs: Ai_Cf_Deepgram_Nova_3_Input; - postProcessedOutputs: Ai_Cf_Deepgram_Nova_3_Output; -} -interface Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Input { - queries?: string | string[]; - /** - * Optional instruction for the task - */ - instruction?: string; - documents?: string | string[]; - text?: string | string[]; -} -interface Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Output { - data?: number[][]; - shape?: number[]; -} -declare abstract class Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B { - inputs: Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Input; - postProcessedOutputs: Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Output; -} -type Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input = - | { - /** - * readable stream with audio data and content-type specified for that data - */ - audio: { - body: object; - contentType: string; - }; - /** - * type of data PCM data that's sent to the inference server as raw array - */ - dtype?: 'uint8' | 'float32' | 'float64'; - } - | { - /** - * base64 encoded audio data - */ - audio: string; - /** - * type of data PCM data that's sent to the inference server as raw array - */ - dtype?: 'uint8' | 'float32' | 'float64'; - }; -interface Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output { - /** - * if true, end-of-turn was detected - */ - is_complete?: boolean; - /** - * probability of the end-of-turn detection - */ - probability?: number; -} -declare abstract class Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2 { - inputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input; - postProcessedOutputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output; -} -declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_120B { - inputs: ResponsesInput; - postProcessedOutputs: ResponsesOutput; -} -declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_20B { - inputs: ResponsesInput; - postProcessedOutputs: ResponsesOutput; -} -interface Ai_Cf_Leonardo_Phoenix_1_0_Input { - /** - * A text description of the image you want to generate. - */ - prompt: string; - /** - * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt - */ - guidance?: number; - /** - * Random seed for reproducibility of the image generation - */ - seed?: number; - /** - * The height of the generated image in pixels - */ - height?: number; - /** - * The width of the generated image in pixels - */ - width?: number; - /** - * The number of diffusion steps; higher values can improve quality but take longer - */ - num_steps?: number; - /** - * Specify what to exclude from the generated images - */ - negative_prompt?: string; -} -/** - * The generated image in JPEG format - */ -type Ai_Cf_Leonardo_Phoenix_1_0_Output = string; -declare abstract class Base_Ai_Cf_Leonardo_Phoenix_1_0 { - inputs: Ai_Cf_Leonardo_Phoenix_1_0_Input; - postProcessedOutputs: Ai_Cf_Leonardo_Phoenix_1_0_Output; -} -interface Ai_Cf_Leonardo_Lucid_Origin_Input { - /** - * A text description of the image you want to generate. - */ - prompt: string; - /** - * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt - */ - guidance?: number; - /** - * Random seed for reproducibility of the image generation - */ - seed?: number; - /** - * The height of the generated image in pixels - */ - height?: number; - /** - * The width of the generated image in pixels - */ - width?: number; - /** - * The number of diffusion steps; higher values can improve quality but take longer - */ - num_steps?: number; - /** - * The number of diffusion steps; higher values can improve quality but take longer - */ - steps?: number; -} -interface Ai_Cf_Leonardo_Lucid_Origin_Output { - /** - * The generated image in Base64 format. - */ - image?: string; -} -declare abstract class Base_Ai_Cf_Leonardo_Lucid_Origin { - inputs: Ai_Cf_Leonardo_Lucid_Origin_Input; - postProcessedOutputs: Ai_Cf_Leonardo_Lucid_Origin_Output; -} -interface Ai_Cf_Deepgram_Aura_1_Input { - /** - * Speaker used to produce the audio. - */ - speaker?: - | 'angus' - | 'asteria' - | 'arcas' - | 'orion' - | 'orpheus' - | 'athena' - | 'luna' - | 'zeus' - | 'perseus' - | 'helios' - | 'hera' - | 'stella'; - /** - * Encoding of the output audio. - */ - encoding?: 'linear16' | 'flac' | 'mulaw' | 'alaw' | 'mp3' | 'opus' | 'aac'; - /** - * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. - */ - container?: 'none' | 'wav' | 'ogg'; - /** - * The text content to be converted to speech - */ - text: string; - /** - * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable - */ - sample_rate?: number; - /** - * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. - */ - bit_rate?: number; -} -/** - * The generated audio in MP3 format - */ -type Ai_Cf_Deepgram_Aura_1_Output = string; -declare abstract class Base_Ai_Cf_Deepgram_Aura_1 { - inputs: Ai_Cf_Deepgram_Aura_1_Input; - postProcessedOutputs: Ai_Cf_Deepgram_Aura_1_Output; -} -interface Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Input { - /** - * Input text to translate. Can be a single string or a list of strings. - */ - text: string | string[]; - /** - * Target language to translate to - */ - target_language: - | 'asm_Beng' - | 'awa_Deva' - | 'ben_Beng' - | 'bho_Deva' - | 'brx_Deva' - | 'doi_Deva' - | 'eng_Latn' - | 'gom_Deva' - | 'gon_Deva' - | 'guj_Gujr' - | 'hin_Deva' - | 'hne_Deva' - | 'kan_Knda' - | 'kas_Arab' - | 'kas_Deva' - | 'kha_Latn' - | 'lus_Latn' - | 'mag_Deva' - | 'mai_Deva' - | 'mal_Mlym' - | 'mar_Deva' - | 'mni_Beng' - | 'mni_Mtei' - | 'npi_Deva' - | 'ory_Orya' - | 'pan_Guru' - | 'san_Deva' - | 'sat_Olck' - | 'snd_Arab' - | 'snd_Deva' - | 'tam_Taml' - | 'tel_Telu' - | 'urd_Arab' - | 'unr_Deva'; -} -interface Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Output { - /** - * Translated texts - */ - translations: string[]; -} -declare abstract class Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B { - inputs: Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Input; - postProcessedOutputs: Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Output; -} -type Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Input = - | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt - | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages - | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Async_Batch; -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; - response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; } -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode { - type?: 'json_object' | 'json_schema'; - json_schema?: unknown; +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_2 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; } -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages_1 { /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + * An array of message objects representing the conversation history. */ - role: string; + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + /** + * The content of the message as a string. + */ + content: string; + }[]; + functions?: { + name: string; + code: string; + }[]; /** - * The content of the message as a string. + * A list of tools available for the assistant to use. */ - content: string; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ( - | { + tools?: ({ /** * The name of the tool. More descriptive the better. */ @@ -8283,32 +8106,31 @@ interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages { * Schema defining the parameters accepted by the tool. */ parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; }; - }; }; - } - | { + } | { /** * Specifies the type of tool (e.g., 'function'). */ @@ -8317,1159 +8139,953 @@ interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages { * Details of the function tool. */ function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { /** - * The type of the parameters object (usually 'object'). + * The name of the function. */ - type: string; + name: string; /** - * List of required parameter names. + * A brief description of what the function does. */ - required?: string[]; + description: string; /** - * Definitions of each parameter. + * Schema defining the parameters accepted by the function. */ - properties: { - [k: string]: { + parameters: { /** - * The data type of the parameter. + * The type of the parameters object (usually 'object'). */ type: string; /** - * A description of the expected parameter. + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. */ - description: string; - }; + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; }; - }; }; - } - )[]; - response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_1; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_1 { - type?: 'json_object' | 'json_schema'; - json_schema?: unknown; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Async_Batch { - requests: ( - | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt_1 - | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages_1 - )[]; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt_1 { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; - response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_2; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; + })[]; + response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_3; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; } -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_2 { - type?: 'json_object' | 'json_schema'; - json_schema?: unknown; +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_3 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; } -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages_1 { - /** - * An array of message objects representing the conversation history. - */ - messages: { +type Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Output = Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Chat_Completion_Response | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Text_Completion_Response | string | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_AsyncResponse; +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Chat_Completion_Response { /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + * Unique identifier for the completion */ - role: string; + id?: string; /** - * The content of the message as a string. + * Object type identifier */ - content: string; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ( - | { - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } - | { + object?: "chat.completion"; + /** + * Unix timestamp of when the completion was created + */ + created?: number; + /** + * Model used for the completion + */ + model?: string; + /** + * List of completion choices + */ + choices?: { /** - * Specifies the type of tool (e.g., 'function'). + * Index of the choice in the list */ - type: string; + index?: number; /** - * Details of the function tool. + * The message generated by the model */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { + message?: { + /** + * Role of the message author + */ + role: string; /** - * The type of the parameters object (usually 'object'). + * The content of the message */ - type: string; + content: string; /** - * List of required parameter names. + * Internal reasoning content (if available) */ - required?: string[]; + reasoning_content?: string; /** - * Definitions of each parameter. + * Tool calls made by the assistant */ - properties: { - [k: string]: { + tool_calls?: { /** - * The data type of the parameter. + * Unique identifier for the tool call */ - type: string; + id: string; /** - * A description of the expected parameter. + * Type of tool call */ - description: string; - }; - }; - }; + type: "function"; + function: { + /** + * Name of the function to call + */ + name: string; + /** + * JSON string of arguments for the function + */ + arguments: string; + }; + }[]; }; - } - )[]; - response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_3; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_3 { - type?: 'json_object' | 'json_schema'; - json_schema?: unknown; -} -type Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Output = - | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Chat_Completion_Response - | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Text_Completion_Response - | string - | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_AsyncResponse; -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Chat_Completion_Response { - /** - * Unique identifier for the completion - */ - id?: string; - /** - * Object type identifier - */ - object?: 'chat.completion'; - /** - * Unix timestamp of when the completion was created - */ - created?: number; - /** - * Model used for the completion - */ - model?: string; - /** - * List of completion choices - */ - choices?: { - /** - * Index of the choice in the list - */ - index?: number; - /** - * The message generated by the model - */ - message?: { - /** - * Role of the message author - */ - role: string; - /** - * The content of the message - */ - content: string; - /** - * Internal reasoning content (if available) - */ - reasoning_content?: string; - /** - * Tool calls made by the assistant - */ - tool_calls?: { - /** - * Unique identifier for the tool call + /** + * Reason why the model stopped generating */ - id: string; + finish_reason?: string; /** - * Type of tool call + * Stop reason (may be null) */ - type: 'function'; - function: { - /** - * Name of the function to call - */ - name: string; - /** - * JSON string of arguments for the function - */ - arguments: string; - }; - }[]; - }; - /** - * Reason why the model stopped generating - */ - finish_reason?: string; - /** - * Stop reason (may be null) - */ - stop_reason?: string | null; - /** - * Log probabilities (if requested) - */ - logprobs?: {} | null; - }[]; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; + stop_reason?: string | null; + /** + * Log probabilities (if requested) + */ + logprobs?: {} | null; + }[]; /** - * Total number of tokens in output + * Usage statistics for the inference request */ - completion_tokens?: number; + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; /** - * Total number of input and output tokens + * Log probabilities for the prompt (if requested) */ - total_tokens?: number; - }; - /** - * Log probabilities for the prompt (if requested) - */ - prompt_logprobs?: {} | null; + prompt_logprobs?: {} | null; } interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Text_Completion_Response { - /** - * Unique identifier for the completion - */ - id?: string; - /** - * Object type identifier - */ - object?: 'text_completion'; - /** - * Unix timestamp of when the completion was created - */ - created?: number; - /** - * Model used for the completion - */ - model?: string; - /** - * List of completion choices - */ - choices?: { - /** - * Index of the choice in the list - */ - index: number; - /** - * The generated text completion - */ - text: string; /** - * Reason why the model stopped generating + * Unique identifier for the completion */ - finish_reason: string; - /** - * Stop reason (may be null) - */ - stop_reason?: string | null; + id?: string; /** - * Log probabilities (if requested) + * Object type identifier */ - logprobs?: {} | null; + object?: "text_completion"; /** - * Log probabilities for the prompt (if requested) + * Unix timestamp of when the completion was created */ - prompt_logprobs?: {} | null; - }[]; - /** - * Usage statistics for the inference request - */ - usage?: { + created?: number; /** - * Total number of tokens in input + * Model used for the completion */ - prompt_tokens?: number; + model?: string; /** - * Total number of tokens in output + * List of completion choices */ - completion_tokens?: number; + choices?: { + /** + * Index of the choice in the list + */ + index: number; + /** + * The generated text completion + */ + text: string; + /** + * Reason why the model stopped generating + */ + finish_reason: string; + /** + * Stop reason (may be null) + */ + stop_reason?: string | null; + /** + * Log probabilities (if requested) + */ + logprobs?: {} | null; + /** + * Log probabilities for the prompt (if requested) + */ + prompt_logprobs?: {} | null; + }[]; /** - * Total number of input and output tokens + * Usage statistics for the inference request */ - total_tokens?: number; - }; + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; } interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; } declare abstract class Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It { - inputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Input; - postProcessedOutputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Output; + inputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Input; + postProcessedOutputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Output; } interface Ai_Cf_Pfnet_Plamo_Embedding_1B_Input { - /** - * Input text to embed. Can be a single string or a list of strings. - */ - text: string | string[]; + /** + * Input text to embed. Can be a single string or a list of strings. + */ + text: string | string[]; } interface Ai_Cf_Pfnet_Plamo_Embedding_1B_Output { - /** - * Embedding vectors, where each vector is a list of floats. - */ - data: number[][]; - /** - * Shape of the embedding data as [number_of_embeddings, embedding_dimension]. - * - * @minItems 2 - * @maxItems 2 - */ - shape: [number, number]; + /** + * Embedding vectors, where each vector is a list of floats. + */ + data: number[][]; + /** + * Shape of the embedding data as [number_of_embeddings, embedding_dimension]. + * + * @minItems 2 + * @maxItems 2 + */ + shape: [ + number, + number + ]; } declare abstract class Base_Ai_Cf_Pfnet_Plamo_Embedding_1B { - inputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Input; - postProcessedOutputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Output; + inputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Input; + postProcessedOutputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Output; } interface Ai_Cf_Deepgram_Flux_Input { - /** - * Encoding of the audio stream. Currently only supports raw signed little-endian 16-bit PCM. - */ - encoding: 'linear16'; - /** - * Sample rate of the audio stream in Hz. - */ - sample_rate: string; - /** - * End-of-turn confidence required to fire an eager end-of-turn event. When set, enables EagerEndOfTurn and TurnResumed events. Valid Values 0.3 - 0.9. - */ - eager_eot_threshold?: string; - /** - * End-of-turn confidence required to finish a turn. Valid Values 0.5 - 0.9. - */ - eot_threshold?: string; - /** - * A turn will be finished when this much time has passed after speech, regardless of EOT confidence. - */ - eot_timeout_ms?: string; - /** - * Keyterm prompting can improve recognition of specialized terminology. Pass multiple keyterm query parameters to boost multiple keyterms. - */ - keyterm?: string; - /** - * Opts out requests from the Deepgram Model Improvement Program. Refer to Deepgram Docs for pricing impacts before setting this to true. https://dpgr.am/deepgram-mip - */ - mip_opt_out?: 'true' | 'false'; - /** - * Label your requests for the purpose of identification during usage reporting - */ - tag?: string; + /** + * Encoding of the audio stream. Currently only supports raw signed little-endian 16-bit PCM. + */ + encoding: "linear16"; + /** + * Sample rate of the audio stream in Hz. + */ + sample_rate: string; + /** + * End-of-turn confidence required to fire an eager end-of-turn event. When set, enables EagerEndOfTurn and TurnResumed events. Valid Values 0.3 - 0.9. + */ + eager_eot_threshold?: string; + /** + * End-of-turn confidence required to finish a turn. Valid Values 0.5 - 0.9. + */ + eot_threshold?: string; + /** + * A turn will be finished when this much time has passed after speech, regardless of EOT confidence. + */ + eot_timeout_ms?: string; + /** + * Keyterm prompting can improve recognition of specialized terminology. Pass multiple keyterm query parameters to boost multiple keyterms. + */ + keyterm?: string; + /** + * Opts out requests from the Deepgram Model Improvement Program. Refer to Deepgram Docs for pricing impacts before setting this to true. https://dpgr.am/deepgram-mip + */ + mip_opt_out?: "true" | "false"; + /** + * Label your requests for the purpose of identification during usage reporting + */ + tag?: string; } /** * Output will be returned as websocket messages. */ interface Ai_Cf_Deepgram_Flux_Output { - /** - * The unique identifier of the request (uuid) - */ - request_id?: string; - /** - * Starts at 0 and increments for each message the server sends to the client. - */ - sequence_id?: number; - /** - * The type of event being reported. - */ - event?: 'Update' | 'StartOfTurn' | 'EagerEndOfTurn' | 'TurnResumed' | 'EndOfTurn'; - /** - * The index of the current turn - */ - turn_index?: number; - /** - * Start time in seconds of the audio range that was transcribed - */ - audio_window_start?: number; - /** - * End time in seconds of the audio range that was transcribed - */ - audio_window_end?: number; - /** - * Text that was said over the course of the current turn - */ - transcript?: string; - /** - * The words in the transcript - */ - words?: { - /** - * The individual punctuated, properly-cased word from the transcript - */ - word: string; - /** - * Confidence that this word was transcribed correctly - */ - confidence: number; - }[]; - /** - * Confidence that no more speech is coming in this turn - */ - end_of_turn_confidence?: number; + /** + * The unique identifier of the request (uuid) + */ + request_id?: string; + /** + * Starts at 0 and increments for each message the server sends to the client. + */ + sequence_id?: number; + /** + * The type of event being reported. + */ + event?: "Update" | "StartOfTurn" | "EagerEndOfTurn" | "TurnResumed" | "EndOfTurn"; + /** + * The index of the current turn + */ + turn_index?: number; + /** + * Start time in seconds of the audio range that was transcribed + */ + audio_window_start?: number; + /** + * End time in seconds of the audio range that was transcribed + */ + audio_window_end?: number; + /** + * Text that was said over the course of the current turn + */ + transcript?: string; + /** + * The words in the transcript + */ + words?: { + /** + * The individual punctuated, properly-cased word from the transcript + */ + word: string; + /** + * Confidence that this word was transcribed correctly + */ + confidence: number; + }[]; + /** + * Confidence that no more speech is coming in this turn + */ + end_of_turn_confidence?: number; } declare abstract class Base_Ai_Cf_Deepgram_Flux { - inputs: Ai_Cf_Deepgram_Flux_Input; - postProcessedOutputs: Ai_Cf_Deepgram_Flux_Output; + inputs: Ai_Cf_Deepgram_Flux_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Flux_Output; } interface Ai_Cf_Deepgram_Aura_2_En_Input { - /** - * Speaker used to produce the audio. - */ - speaker?: - | 'amalthea' - | 'andromeda' - | 'apollo' - | 'arcas' - | 'aries' - | 'asteria' - | 'athena' - | 'atlas' - | 'aurora' - | 'callista' - | 'cora' - | 'cordelia' - | 'delia' - | 'draco' - | 'electra' - | 'harmonia' - | 'helena' - | 'hera' - | 'hermes' - | 'hyperion' - | 'iris' - | 'janus' - | 'juno' - | 'jupiter' - | 'luna' - | 'mars' - | 'minerva' - | 'neptune' - | 'odysseus' - | 'ophelia' - | 'orion' - | 'orpheus' - | 'pandora' - | 'phoebe' - | 'pluto' - | 'saturn' - | 'thalia' - | 'theia' - | 'vesta' - | 'zeus'; - /** - * Encoding of the output audio. - */ - encoding?: 'linear16' | 'flac' | 'mulaw' | 'alaw' | 'mp3' | 'opus' | 'aac'; - /** - * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. - */ - container?: 'none' | 'wav' | 'ogg'; - /** - * The text content to be converted to speech - */ - text: string; - /** - * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable - */ - sample_rate?: number; - /** - * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. - */ - bit_rate?: number; + /** + * Speaker used to produce the audio. + */ + speaker?: "amalthea" | "andromeda" | "apollo" | "arcas" | "aries" | "asteria" | "athena" | "atlas" | "aurora" | "callista" | "cora" | "cordelia" | "delia" | "draco" | "electra" | "harmonia" | "helena" | "hera" | "hermes" | "hyperion" | "iris" | "janus" | "juno" | "jupiter" | "luna" | "mars" | "minerva" | "neptune" | "odysseus" | "ophelia" | "orion" | "orpheus" | "pandora" | "phoebe" | "pluto" | "saturn" | "thalia" | "theia" | "vesta" | "zeus"; + /** + * Encoding of the output audio. + */ + encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac"; + /** + * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. + */ + container?: "none" | "wav" | "ogg"; + /** + * The text content to be converted to speech + */ + text: string; + /** + * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable + */ + sample_rate?: number; + /** + * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. + */ + bit_rate?: number; } /** * The generated audio in MP3 format */ type Ai_Cf_Deepgram_Aura_2_En_Output = string; declare abstract class Base_Ai_Cf_Deepgram_Aura_2_En { - inputs: Ai_Cf_Deepgram_Aura_2_En_Input; - postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_En_Output; + inputs: Ai_Cf_Deepgram_Aura_2_En_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_En_Output; } interface Ai_Cf_Deepgram_Aura_2_Es_Input { - /** - * Speaker used to produce the audio. - */ - speaker?: - | 'sirio' - | 'nestor' - | 'carina' - | 'celeste' - | 'alvaro' - | 'diana' - | 'aquila' - | 'selena' - | 'estrella' - | 'javier'; - /** - * Encoding of the output audio. - */ - encoding?: 'linear16' | 'flac' | 'mulaw' | 'alaw' | 'mp3' | 'opus' | 'aac'; - /** - * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. - */ - container?: 'none' | 'wav' | 'ogg'; - /** - * The text content to be converted to speech - */ - text: string; - /** - * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable - */ - sample_rate?: number; - /** - * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. - */ - bit_rate?: number; + /** + * Speaker used to produce the audio. + */ + speaker?: "sirio" | "nestor" | "carina" | "celeste" | "alvaro" | "diana" | "aquila" | "selena" | "estrella" | "javier"; + /** + * Encoding of the output audio. + */ + encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac"; + /** + * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. + */ + container?: "none" | "wav" | "ogg"; + /** + * The text content to be converted to speech + */ + text: string; + /** + * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable + */ + sample_rate?: number; + /** + * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. + */ + bit_rate?: number; } /** * The generated audio in MP3 format */ type Ai_Cf_Deepgram_Aura_2_Es_Output = string; declare abstract class Base_Ai_Cf_Deepgram_Aura_2_Es { - inputs: Ai_Cf_Deepgram_Aura_2_Es_Input; - postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_Es_Output; + inputs: Ai_Cf_Deepgram_Aura_2_Es_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_Es_Output; } interface AiModels { - '@cf/huggingface/distilbert-sst-2-int8': BaseAiTextClassification; - '@cf/stabilityai/stable-diffusion-xl-base-1.0': BaseAiTextToImage; - '@cf/runwayml/stable-diffusion-v1-5-inpainting': BaseAiTextToImage; - '@cf/runwayml/stable-diffusion-v1-5-img2img': BaseAiTextToImage; - '@cf/lykon/dreamshaper-8-lcm': BaseAiTextToImage; - '@cf/bytedance/stable-diffusion-xl-lightning': BaseAiTextToImage; - '@cf/myshell-ai/melotts': BaseAiTextToSpeech; - '@cf/google/embeddinggemma-300m': BaseAiTextEmbeddings; - '@cf/microsoft/resnet-50': BaseAiImageClassification; - '@cf/meta/llama-2-7b-chat-int8': BaseAiTextGeneration; - '@cf/mistral/mistral-7b-instruct-v0.1': BaseAiTextGeneration; - '@cf/meta/llama-2-7b-chat-fp16': BaseAiTextGeneration; - '@hf/thebloke/llama-2-13b-chat-awq': BaseAiTextGeneration; - '@hf/thebloke/mistral-7b-instruct-v0.1-awq': BaseAiTextGeneration; - '@hf/thebloke/zephyr-7b-beta-awq': BaseAiTextGeneration; - '@hf/thebloke/openhermes-2.5-mistral-7b-awq': BaseAiTextGeneration; - '@hf/thebloke/neural-chat-7b-v3-1-awq': BaseAiTextGeneration; - '@hf/thebloke/llamaguard-7b-awq': BaseAiTextGeneration; - '@hf/thebloke/deepseek-coder-6.7b-base-awq': BaseAiTextGeneration; - '@hf/thebloke/deepseek-coder-6.7b-instruct-awq': BaseAiTextGeneration; - '@cf/deepseek-ai/deepseek-math-7b-instruct': BaseAiTextGeneration; - '@cf/defog/sqlcoder-7b-2': BaseAiTextGeneration; - '@cf/openchat/openchat-3.5-0106': BaseAiTextGeneration; - '@cf/tiiuae/falcon-7b-instruct': BaseAiTextGeneration; - '@cf/thebloke/discolm-german-7b-v1-awq': BaseAiTextGeneration; - '@cf/qwen/qwen1.5-0.5b-chat': BaseAiTextGeneration; - '@cf/qwen/qwen1.5-7b-chat-awq': BaseAiTextGeneration; - '@cf/qwen/qwen1.5-14b-chat-awq': BaseAiTextGeneration; - '@cf/tinyllama/tinyllama-1.1b-chat-v1.0': BaseAiTextGeneration; - '@cf/microsoft/phi-2': BaseAiTextGeneration; - '@cf/qwen/qwen1.5-1.8b-chat': BaseAiTextGeneration; - '@cf/mistral/mistral-7b-instruct-v0.2-lora': BaseAiTextGeneration; - '@hf/nousresearch/hermes-2-pro-mistral-7b': BaseAiTextGeneration; - '@hf/nexusflow/starling-lm-7b-beta': BaseAiTextGeneration; - '@hf/google/gemma-7b-it': BaseAiTextGeneration; - '@cf/meta-llama/llama-2-7b-chat-hf-lora': BaseAiTextGeneration; - '@cf/google/gemma-2b-it-lora': BaseAiTextGeneration; - '@cf/google/gemma-7b-it-lora': BaseAiTextGeneration; - '@hf/mistral/mistral-7b-instruct-v0.2': BaseAiTextGeneration; - '@cf/meta/llama-3-8b-instruct': BaseAiTextGeneration; - '@cf/fblgit/una-cybertron-7b-v2-bf16': BaseAiTextGeneration; - '@cf/meta/llama-3-8b-instruct-awq': BaseAiTextGeneration; - '@cf/meta/llama-3.1-8b-instruct-fp8': BaseAiTextGeneration; - '@cf/meta/llama-3.1-8b-instruct-awq': BaseAiTextGeneration; - '@cf/meta/llama-3.2-3b-instruct': BaseAiTextGeneration; - '@cf/meta/llama-3.2-1b-instruct': BaseAiTextGeneration; - '@cf/deepseek-ai/deepseek-r1-distill-qwen-32b': BaseAiTextGeneration; - '@cf/ibm-granite/granite-4.0-h-micro': BaseAiTextGeneration; - '@cf/facebook/bart-large-cnn': BaseAiSummarization; - '@cf/llava-hf/llava-1.5-7b-hf': BaseAiImageToText; - '@cf/baai/bge-base-en-v1.5': Base_Ai_Cf_Baai_Bge_Base_En_V1_5; - '@cf/openai/whisper': Base_Ai_Cf_Openai_Whisper; - '@cf/meta/m2m100-1.2b': Base_Ai_Cf_Meta_M2M100_1_2B; - '@cf/baai/bge-small-en-v1.5': Base_Ai_Cf_Baai_Bge_Small_En_V1_5; - '@cf/baai/bge-large-en-v1.5': Base_Ai_Cf_Baai_Bge_Large_En_V1_5; - '@cf/unum/uform-gen2-qwen-500m': Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M; - '@cf/openai/whisper-tiny-en': Base_Ai_Cf_Openai_Whisper_Tiny_En; - '@cf/openai/whisper-large-v3-turbo': Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo; - '@cf/baai/bge-m3': Base_Ai_Cf_Baai_Bge_M3; - '@cf/black-forest-labs/flux-1-schnell': Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell; - '@cf/meta/llama-3.2-11b-vision-instruct': Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct; - '@cf/meta/llama-3.3-70b-instruct-fp8-fast': Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast; - '@cf/meta/llama-guard-3-8b': Base_Ai_Cf_Meta_Llama_Guard_3_8B; - '@cf/baai/bge-reranker-base': Base_Ai_Cf_Baai_Bge_Reranker_Base; - '@cf/qwen/qwen2.5-coder-32b-instruct': Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct; - '@cf/qwen/qwq-32b': Base_Ai_Cf_Qwen_Qwq_32B; - '@cf/mistralai/mistral-small-3.1-24b-instruct': Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct; - '@cf/google/gemma-3-12b-it': Base_Ai_Cf_Google_Gemma_3_12B_It; - '@cf/meta/llama-4-scout-17b-16e-instruct': Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct; - '@cf/qwen/qwen3-30b-a3b-fp8': Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8; - '@cf/deepgram/nova-3': Base_Ai_Cf_Deepgram_Nova_3; - '@cf/qwen/qwen3-embedding-0.6b': Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B; - '@cf/pipecat-ai/smart-turn-v2': Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2; - '@cf/openai/gpt-oss-120b': Base_Ai_Cf_Openai_Gpt_Oss_120B; - '@cf/openai/gpt-oss-20b': Base_Ai_Cf_Openai_Gpt_Oss_20B; - '@cf/leonardo/phoenix-1.0': Base_Ai_Cf_Leonardo_Phoenix_1_0; - '@cf/leonardo/lucid-origin': Base_Ai_Cf_Leonardo_Lucid_Origin; - '@cf/deepgram/aura-1': Base_Ai_Cf_Deepgram_Aura_1; - '@cf/ai4bharat/indictrans2-en-indic-1B': Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B; - '@cf/aisingapore/gemma-sea-lion-v4-27b-it': Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It; - '@cf/pfnet/plamo-embedding-1b': Base_Ai_Cf_Pfnet_Plamo_Embedding_1B; - '@cf/deepgram/flux': Base_Ai_Cf_Deepgram_Flux; - '@cf/deepgram/aura-2-en': Base_Ai_Cf_Deepgram_Aura_2_En; - '@cf/deepgram/aura-2-es': Base_Ai_Cf_Deepgram_Aura_2_Es; + "@cf/huggingface/distilbert-sst-2-int8": BaseAiTextClassification; + "@cf/stabilityai/stable-diffusion-xl-base-1.0": BaseAiTextToImage; + "@cf/runwayml/stable-diffusion-v1-5-inpainting": BaseAiTextToImage; + "@cf/runwayml/stable-diffusion-v1-5-img2img": BaseAiTextToImage; + "@cf/lykon/dreamshaper-8-lcm": BaseAiTextToImage; + "@cf/bytedance/stable-diffusion-xl-lightning": BaseAiTextToImage; + "@cf/myshell-ai/melotts": BaseAiTextToSpeech; + "@cf/google/embeddinggemma-300m": BaseAiTextEmbeddings; + "@cf/microsoft/resnet-50": BaseAiImageClassification; + "@cf/meta/llama-2-7b-chat-int8": BaseAiTextGeneration; + "@cf/mistral/mistral-7b-instruct-v0.1": BaseAiTextGeneration; + "@cf/meta/llama-2-7b-chat-fp16": BaseAiTextGeneration; + "@hf/thebloke/llama-2-13b-chat-awq": BaseAiTextGeneration; + "@hf/thebloke/mistral-7b-instruct-v0.1-awq": BaseAiTextGeneration; + "@hf/thebloke/zephyr-7b-beta-awq": BaseAiTextGeneration; + "@hf/thebloke/openhermes-2.5-mistral-7b-awq": BaseAiTextGeneration; + "@hf/thebloke/neural-chat-7b-v3-1-awq": BaseAiTextGeneration; + "@hf/thebloke/llamaguard-7b-awq": BaseAiTextGeneration; + "@hf/thebloke/deepseek-coder-6.7b-base-awq": BaseAiTextGeneration; + "@hf/thebloke/deepseek-coder-6.7b-instruct-awq": BaseAiTextGeneration; + "@cf/deepseek-ai/deepseek-math-7b-instruct": BaseAiTextGeneration; + "@cf/defog/sqlcoder-7b-2": BaseAiTextGeneration; + "@cf/openchat/openchat-3.5-0106": BaseAiTextGeneration; + "@cf/tiiuae/falcon-7b-instruct": BaseAiTextGeneration; + "@cf/thebloke/discolm-german-7b-v1-awq": BaseAiTextGeneration; + "@cf/qwen/qwen1.5-0.5b-chat": BaseAiTextGeneration; + "@cf/qwen/qwen1.5-7b-chat-awq": BaseAiTextGeneration; + "@cf/qwen/qwen1.5-14b-chat-awq": BaseAiTextGeneration; + "@cf/tinyllama/tinyllama-1.1b-chat-v1.0": BaseAiTextGeneration; + "@cf/microsoft/phi-2": BaseAiTextGeneration; + "@cf/qwen/qwen1.5-1.8b-chat": BaseAiTextGeneration; + "@cf/mistral/mistral-7b-instruct-v0.2-lora": BaseAiTextGeneration; + "@hf/nousresearch/hermes-2-pro-mistral-7b": BaseAiTextGeneration; + "@hf/nexusflow/starling-lm-7b-beta": BaseAiTextGeneration; + "@hf/google/gemma-7b-it": BaseAiTextGeneration; + "@cf/meta-llama/llama-2-7b-chat-hf-lora": BaseAiTextGeneration; + "@cf/google/gemma-2b-it-lora": BaseAiTextGeneration; + "@cf/google/gemma-7b-it-lora": BaseAiTextGeneration; + "@hf/mistral/mistral-7b-instruct-v0.2": BaseAiTextGeneration; + "@cf/meta/llama-3-8b-instruct": BaseAiTextGeneration; + "@cf/fblgit/una-cybertron-7b-v2-bf16": BaseAiTextGeneration; + "@cf/meta/llama-3-8b-instruct-awq": BaseAiTextGeneration; + "@cf/meta/llama-3.1-8b-instruct-fp8": BaseAiTextGeneration; + "@cf/meta/llama-3.1-8b-instruct-awq": BaseAiTextGeneration; + "@cf/meta/llama-3.2-3b-instruct": BaseAiTextGeneration; + "@cf/meta/llama-3.2-1b-instruct": BaseAiTextGeneration; + "@cf/deepseek-ai/deepseek-r1-distill-qwen-32b": BaseAiTextGeneration; + "@cf/ibm-granite/granite-4.0-h-micro": BaseAiTextGeneration; + "@cf/facebook/bart-large-cnn": BaseAiSummarization; + "@cf/llava-hf/llava-1.5-7b-hf": BaseAiImageToText; + "@cf/baai/bge-base-en-v1.5": Base_Ai_Cf_Baai_Bge_Base_En_V1_5; + "@cf/openai/whisper": Base_Ai_Cf_Openai_Whisper; + "@cf/meta/m2m100-1.2b": Base_Ai_Cf_Meta_M2M100_1_2B; + "@cf/baai/bge-small-en-v1.5": Base_Ai_Cf_Baai_Bge_Small_En_V1_5; + "@cf/baai/bge-large-en-v1.5": Base_Ai_Cf_Baai_Bge_Large_En_V1_5; + "@cf/unum/uform-gen2-qwen-500m": Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M; + "@cf/openai/whisper-tiny-en": Base_Ai_Cf_Openai_Whisper_Tiny_En; + "@cf/openai/whisper-large-v3-turbo": Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo; + "@cf/baai/bge-m3": Base_Ai_Cf_Baai_Bge_M3; + "@cf/black-forest-labs/flux-1-schnell": Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell; + "@cf/meta/llama-3.2-11b-vision-instruct": Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct; + "@cf/meta/llama-3.3-70b-instruct-fp8-fast": Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast; + "@cf/meta/llama-guard-3-8b": Base_Ai_Cf_Meta_Llama_Guard_3_8B; + "@cf/baai/bge-reranker-base": Base_Ai_Cf_Baai_Bge_Reranker_Base; + "@cf/qwen/qwen2.5-coder-32b-instruct": Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct; + "@cf/qwen/qwq-32b": Base_Ai_Cf_Qwen_Qwq_32B; + "@cf/mistralai/mistral-small-3.1-24b-instruct": Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct; + "@cf/google/gemma-3-12b-it": Base_Ai_Cf_Google_Gemma_3_12B_It; + "@cf/meta/llama-4-scout-17b-16e-instruct": Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct; + "@cf/qwen/qwen3-30b-a3b-fp8": Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8; + "@cf/deepgram/nova-3": Base_Ai_Cf_Deepgram_Nova_3; + "@cf/qwen/qwen3-embedding-0.6b": Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B; + "@cf/pipecat-ai/smart-turn-v2": Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2; + "@cf/openai/gpt-oss-120b": Base_Ai_Cf_Openai_Gpt_Oss_120B; + "@cf/openai/gpt-oss-20b": Base_Ai_Cf_Openai_Gpt_Oss_20B; + "@cf/leonardo/phoenix-1.0": Base_Ai_Cf_Leonardo_Phoenix_1_0; + "@cf/leonardo/lucid-origin": Base_Ai_Cf_Leonardo_Lucid_Origin; + "@cf/deepgram/aura-1": Base_Ai_Cf_Deepgram_Aura_1; + "@cf/ai4bharat/indictrans2-en-indic-1B": Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B; + "@cf/aisingapore/gemma-sea-lion-v4-27b-it": Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It; + "@cf/pfnet/plamo-embedding-1b": Base_Ai_Cf_Pfnet_Plamo_Embedding_1B; + "@cf/deepgram/flux": Base_Ai_Cf_Deepgram_Flux; + "@cf/deepgram/aura-2-en": Base_Ai_Cf_Deepgram_Aura_2_En; + "@cf/deepgram/aura-2-es": Base_Ai_Cf_Deepgram_Aura_2_Es; } type AiOptions = { - /** - * Send requests as an asynchronous batch job, only works for supported models - * https://developers.cloudflare.com/workers-ai/features/batch-api - */ - queueRequest?: boolean; - /** - * Establish websocket connections, only works for supported models - */ - websocket?: boolean; - /** - * Tag your requests to group and view them in Cloudflare dashboard. - * - * Rules: - * Tags must only contain letters, numbers, and the symbols: : - . / @ - * Each tag can have maximum 50 characters. - * Maximum 5 tags are allowed each request. - * Duplicate tags will removed. - */ - tags?: string[]; - gateway?: GatewayOptions; - returnRawResponse?: boolean; - prefix?: string; - extraHeaders?: object; + /** + * Send requests as an asynchronous batch job, only works for supported models + * https://developers.cloudflare.com/workers-ai/features/batch-api + */ + queueRequest?: boolean; + /** + * Establish websocket connections, only works for supported models + */ + websocket?: boolean; + /** + * Tag your requests to group and view them in Cloudflare dashboard. + * + * Rules: + * Tags must only contain letters, numbers, and the symbols: : - . / @ + * Each tag can have maximum 50 characters. + * Maximum 5 tags are allowed each request. + * Duplicate tags will removed. + */ + tags?: string[]; + gateway?: GatewayOptions; + returnRawResponse?: boolean; + prefix?: string; + extraHeaders?: object; }; type AiModelsSearchParams = { - author?: string; - hide_experimental?: boolean; - page?: number; - per_page?: number; - search?: string; - source?: number; - task?: string; + author?: string; + hide_experimental?: boolean; + page?: number; + per_page?: number; + search?: string; + source?: number; + task?: string; }; type AiModelsSearchObject = { - id: string; - source: number; - name: string; - description: string; - task: { id: string; + source: number; name: string; description: string; - }; - tags: string[]; - properties: { - property_id: string; - value: string; - }[]; -}; -interface InferenceUpstreamError extends Error {} -interface AiInternalError extends Error {} + task: { + id: string; + name: string; + description: string; + }; + tags: string[]; + properties: { + property_id: string; + value: string; + }[]; +}; +interface InferenceUpstreamError extends Error { +} +interface AiInternalError extends Error { +} type AiModelListType = Record; declare abstract class Ai { - aiGatewayLogId: string | null; - gateway(gatewayId: string): AiGateway; - 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 - | { - returnRawResponse: true; - } - | { - websocket: true; - } - ? Response - : InputOptions extends { - stream: true; - } - ? ReadableStream - : AiModelList[Name]['postProcessedOutputs'] - >; - models(params?: AiModelsSearchParams): Promise; - toMarkdown(): ToMarkdownService; - toMarkdown( - files: MarkdownDocument[], - options?: ConversionRequestOptions - ): Promise; - toMarkdown( - files: MarkdownDocument, - options?: ConversionRequestOptions - ): Promise; + aiGatewayLogId: string | null; + gateway(gatewayId: string): AiGateway; + /** + * Access the AI Search API for managing AI-powered search instances. + * + * This is the new API that replaces AutoRAG with better namespace separation: + * - Account-level operations: `list()`, `create()` + * - Instance-level operations: `get(id).search()`, `get(id).chatCompletions()`, `get(id).delete()` + * + * @example + * ```typescript + * // List all AI Search instances + * const instances = await env.AI.aiSearch.list(); + * + * // Search an instance + * const results = await env.AI.aiSearch.get('my-search').search({ + * messages: [{ role: 'user', content: 'What is the policy?' }], + * ai_search_options: { + * retrieval: { max_num_results: 10 } + * } + * }); + * + * // Generate chat completions with AI Search context + * const response = await env.AI.aiSearch.get('my-search').chatCompletions({ + * messages: [{ role: 'user', content: 'What is the policy?' }], + * model: '@cf/meta/llama-3.3-70b-instruct-fp8-fast' + * }); + * ``` + */ + aiSearch: AiSearchAccountService; + /** + * @deprecated AutoRAG has been replaced by AI Search. + * Use `env.AI.aiSearch` instead for better API design and new features. + * + * Migration guide: + * - `env.AI.autorag().list()` → `env.AI.aiSearch.list()` + * - `env.AI.autorag('id').search({ query: '...' })` → `env.AI.aiSearch.get('id').search({ messages: [{ role: 'user', content: '...' }] })` + * - `env.AI.autorag('id').aiSearch(...)` → `env.AI.aiSearch.get('id').chatCompletions(...)` + * + * Note: The old API continues to work for backwards compatibility, but new projects should use AI Search. + * + * @see AiSearchAccountService + * @param autoragId Optional instance ID (omit for account-level operations) + */ + autorag(autoragId: string): AutoRAG; + run(model: Name, inputs: InputOptions, options?: Options): Promise; + models(params?: AiModelsSearchParams): Promise; + toMarkdown(): ToMarkdownService; + toMarkdown(files: MarkdownDocument[], options?: ConversionRequestOptions): Promise; + toMarkdown(files: MarkdownDocument, options?: ConversionRequestOptions): Promise; } type GatewayRetries = { - maxAttempts?: 1 | 2 | 3 | 4 | 5; - retryDelayMs?: number; - backoff?: 'constant' | 'linear' | 'exponential'; + maxAttempts?: 1 | 2 | 3 | 4 | 5; + retryDelayMs?: number; + backoff?: 'constant' | 'linear' | 'exponential'; }; type GatewayOptions = { - id: string; - cacheKey?: string; - cacheTtl?: number; - skipCache?: boolean; - metadata?: Record; - collectLog?: boolean; - eventId?: string; - requestTimeoutMs?: number; - retries?: GatewayRetries; + id: string; + cacheKey?: string; + cacheTtl?: number; + skipCache?: boolean; + metadata?: Record; + collectLog?: boolean; + eventId?: string; + requestTimeoutMs?: number; + retries?: GatewayRetries; }; type UniversalGatewayOptions = Exclude & { - /** - ** @deprecated - */ - id?: string; + /** + ** @deprecated + */ + id?: string; }; type AiGatewayPatchLog = { - score?: number | null; - feedback?: -1 | 1 | null; - metadata?: Record | null; + score?: number | null; + feedback?: -1 | 1 | null; + metadata?: Record | null; }; type AiGatewayLog = { - id: string; - provider: string; - model: string; - model_type?: string; - path: string; - duration: number; - request_type?: string; - request_content_type?: string; - status_code: number; - response_content_type?: string; - success: boolean; - cached: boolean; - tokens_in?: number; - tokens_out?: number; - metadata?: Record; - step?: number; - cost?: number; - custom_cost?: boolean; - request_size: number; - request_head?: string; - request_head_complete: boolean; - response_size: number; - response_head?: string; - response_head_complete: boolean; - created_at: Date; -}; -type AIGatewayProviders = - | 'workers-ai' - | 'anthropic' - | 'aws-bedrock' - | 'azure-openai' - | 'google-vertex-ai' - | 'huggingface' - | 'openai' - | 'perplexity-ai' - | 'replicate' - | 'groq' - | 'cohere' - | 'google-ai-studio' - | 'mistral' - | 'grok' - | 'openrouter' - | 'deepseek' - | 'cerebras' - | 'cartesia' - | 'elevenlabs' - | 'adobe-firefly'; + id: string; + provider: string; + model: string; + model_type?: string; + path: string; + duration: number; + request_type?: string; + request_content_type?: string; + status_code: number; + response_content_type?: string; + success: boolean; + cached: boolean; + tokens_in?: number; + tokens_out?: number; + metadata?: Record; + step?: number; + cost?: number; + custom_cost?: boolean; + request_size: number; + request_head?: string; + request_head_complete: boolean; + response_size: number; + response_head?: string; + response_head_complete: boolean; + created_at: Date; +}; +type AIGatewayProviders = 'workers-ai' | 'anthropic' | 'aws-bedrock' | 'azure-openai' | 'google-vertex-ai' | 'huggingface' | 'openai' | 'perplexity-ai' | 'replicate' | 'groq' | 'cohere' | 'google-ai-studio' | 'mistral' | 'grok' | 'openrouter' | 'deepseek' | 'cerebras' | 'cartesia' | 'elevenlabs' | 'adobe-firefly'; type AIGatewayHeaders = { - 'cf-aig-metadata': Record | string; - 'cf-aig-custom-cost': - | { + 'cf-aig-metadata': Record | string; + 'cf-aig-custom-cost': { per_token_in?: number; per_token_out?: number; - } - | { + } | { total_cost?: number; - } - | string; - 'cf-aig-cache-ttl': number | string; - 'cf-aig-skip-cache': boolean | string; - 'cf-aig-cache-key': string; - 'cf-aig-event-id': string; - 'cf-aig-request-timeout': number | string; - 'cf-aig-max-attempts': number | string; - 'cf-aig-retry-delay': number | string; - 'cf-aig-backoff': string; - 'cf-aig-collect-log': boolean | string; - Authorization: string; - 'Content-Type': string; - [key: string]: string | number | boolean | object; + } | string; + 'cf-aig-cache-ttl': number | string; + 'cf-aig-skip-cache': boolean | string; + 'cf-aig-cache-key': string; + 'cf-aig-event-id': string; + 'cf-aig-request-timeout': number | string; + 'cf-aig-max-attempts': number | string; + 'cf-aig-retry-delay': number | string; + 'cf-aig-backoff': string; + 'cf-aig-collect-log': boolean | string; + Authorization: string; + 'Content-Type': string; + [key: string]: string | number | boolean | object; }; type AIGatewayUniversalRequest = { - provider: AIGatewayProviders | string; // eslint-disable-line - endpoint: string; - headers: Partial; - query: unknown; + provider: AIGatewayProviders | string; // eslint-disable-line + endpoint: string; + headers: Partial; + query: unknown; }; -interface AiGatewayInternalError extends Error {} -interface AiGatewayLogNotFound extends Error {} +interface AiGatewayInternalError extends Error { +} +interface AiGatewayLogNotFound extends Error { +} declare abstract class AiGateway { - patchLog(logId: string, data: AiGatewayPatchLog): Promise; - getLog(logId: string): Promise; - run( - data: AIGatewayUniversalRequest | AIGatewayUniversalRequest[], - options?: { - gateway?: UniversalGatewayOptions; - extraHeaders?: object; - } - ): Promise; - getUrl(provider?: AIGatewayProviders | string): Promise; // eslint-disable-line + patchLog(logId: string, data: AiGatewayPatchLog): Promise; + getLog(logId: string): Promise; + run(data: AIGatewayUniversalRequest | AIGatewayUniversalRequest[], options?: { + gateway?: UniversalGatewayOptions; + extraHeaders?: object; + }): Promise; + getUrl(provider?: AIGatewayProviders | string): Promise; // eslint-disable-line } -interface AutoRAGInternalError extends Error {} -interface AutoRAGNotFoundError extends Error {} -interface AutoRAGUnauthorizedError extends Error {} -interface AutoRAGNameNotSetError extends Error {} -type ComparisonFilter = { - key: string; - type: 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte'; - value: string | number | boolean; -}; -type CompoundFilter = { - type: 'and' | 'or'; - filters: ComparisonFilter[]; -}; +/** + * @deprecated AutoRAG has been replaced by AI Search. Use AiSearchInternalError instead. + * @see AiSearchInternalError + */ +interface AutoRAGInternalError extends Error { +} +/** + * @deprecated AutoRAG has been replaced by AI Search. Use AiSearchNotFoundError instead. + * @see AiSearchNotFoundError + */ +interface AutoRAGNotFoundError extends Error { +} +/** + * @deprecated This error type is no longer used in the AI Search API. + */ +interface AutoRAGUnauthorizedError extends Error { +} +/** + * @deprecated AutoRAG has been replaced by AI Search. Use AiSearchNameNotSetError instead. + * @see AiSearchNameNotSetError + */ +interface AutoRAGNameNotSetError extends Error { +} +/** + * @deprecated AutoRAG has been replaced by AI Search. + * Use AiSearchSearchRequest with the new API instead. + * @see AiSearchSearchRequest + */ type AutoRagSearchRequest = { - query: string; - filters?: CompoundFilter | ComparisonFilter; - max_num_results?: number; - ranking_options?: { - ranker?: string; - score_threshold?: number; - }; - reranking?: { - enabled?: boolean; - model?: string; - }; - rewrite_query?: boolean; + query: string; + filters?: CompoundFilter | ComparisonFilter; + max_num_results?: number; + ranking_options?: { + ranker?: string; + score_threshold?: number; + }; + reranking?: { + enabled?: boolean; + model?: string; + }; + rewrite_query?: boolean; }; +/** + * @deprecated AutoRAG has been replaced by AI Search. + * Use AiSearchChatCompletionsRequest with the new API instead. + * @see AiSearchChatCompletionsRequest + */ type AutoRagAiSearchRequest = AutoRagSearchRequest & { - stream?: boolean; - system_prompt?: string; + stream?: boolean; + system_prompt?: string; }; +/** + * @deprecated AutoRAG has been replaced by AI Search. + * Use AiSearchChatCompletionsRequest with stream: true instead. + * @see AiSearchChatCompletionsRequest + */ type AutoRagAiSearchRequestStreaming = Omit & { - stream: true; + stream: true; }; +/** + * @deprecated AutoRAG has been replaced by AI Search. + * Use AiSearchSearchResponse with the new API instead. + * @see AiSearchSearchResponse + */ type AutoRagSearchResponse = { - object: 'vector_store.search_results.page'; - search_query: string; - data: { - file_id: string; - filename: string; - score: number; - attributes: Record; - content: { - type: 'text'; - text: string; + object: 'vector_store.search_results.page'; + search_query: string; + data: { + file_id: string; + filename: string; + score: number; + attributes: Record; + content: { + type: 'text'; + text: string; + }[]; }[]; - }[]; - has_more: boolean; - next_page: string | null; + has_more: boolean; + next_page: string | null; }; +/** + * @deprecated AutoRAG has been replaced by AI Search. + * Use AiSearchListResponse with the new API instead. + * @see AiSearchListResponse + */ type AutoRagListResponse = { - id: string; - enable: boolean; - type: string; - source: string; - vectorize_name: string; - paused: boolean; - status: string; + id: string; + enable: boolean; + type: string; + source: string; + vectorize_name: string; + paused: boolean; + status: string; }[]; +/** + * @deprecated AutoRAG has been replaced by AI Search. + * The new API returns different response formats for chat completions. + */ type AutoRagAiSearchResponse = AutoRagSearchResponse & { - response: string; + response: string; }; +/** + * @deprecated AutoRAG has been replaced by AI Search. + * Use the new AI Search API instead: `env.AI.aiSearch` + * + * Migration guide: + * - `env.AI.autorag().list()` → `env.AI.aiSearch.list()` + * - `env.AI.autorag('id').search(...)` → `env.AI.aiSearch.get('id').search(...)` + * - `env.AI.autorag('id').aiSearch(...)` → `env.AI.aiSearch.get('id').chatCompletions(...)` + * + * @see AiSearchAccountService + * @see AiSearchInstanceService + */ declare abstract class AutoRAG { - list(): Promise; - search(params: AutoRagSearchRequest): Promise; - aiSearch(params: AutoRagAiSearchRequestStreaming): Promise; - aiSearch(params: AutoRagAiSearchRequest): Promise; - aiSearch(params: AutoRagAiSearchRequest): Promise; + /** + * @deprecated Use `env.AI.aiSearch.list()` instead. + * @see AiSearchAccountService.list + */ + list(): Promise; + /** + * @deprecated Use `env.AI.aiSearch.get(id).search(...)` instead. + * Note: The new API uses a messages array instead of a query string. + * @see AiSearchInstanceService.search + */ + search(params: AutoRagSearchRequest): Promise; + /** + * @deprecated Use `env.AI.aiSearch.get(id).chatCompletions(...)` instead. + * @see AiSearchInstanceService.chatCompletions + */ + aiSearch(params: AutoRagAiSearchRequestStreaming): Promise; + /** + * @deprecated Use `env.AI.aiSearch.get(id).chatCompletions(...)` instead. + * @see AiSearchInstanceService.chatCompletions + */ + aiSearch(params: AutoRagAiSearchRequest): Promise; + /** + * @deprecated Use `env.AI.aiSearch.get(id).chatCompletions(...)` instead. + * @see AiSearchInstanceService.chatCompletions + */ + aiSearch(params: AutoRagAiSearchRequest): Promise; } 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; - /** - * 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 - */ - fit?: 'scale-down' | 'contain' | 'cover' | 'crop' | 'pad' | 'squeeze'; - /** - * Image segmentation using artificial intelligence models. Sets pixels not - * within selected segment area to transparent e.g "foreground" sets every - * background pixel as transparent. - */ - segment?: 'foreground'; - /** - * 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; - /** - * 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; - /** - * 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; + /** + * 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; + /** + * 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 + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad" | "squeeze"; + /** + * Image segmentation using artificial intelligence models. Sets pixels not + * within selected segment area to transparent e.g "foreground" sets every + * background pixel as transparent. + */ + segment?: "foreground"; + /** + * 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; + /** + * 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; + /** + * 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; } interface BasicImageTransformationsGravityCoordinates { - x?: number; - y?: number; - mode?: 'remainder' | 'box-center'; + x?: number; + y?: number; + mode?: 'remainder' | 'box-center'; } /** * In addition to the properties you can set in the RequestInit dict @@ -9481,1018 +9097,755 @@ interface BasicImageTransformationsGravityCoordinates { * playground. */ interface RequestInitCfProperties extends Record { - cacheEverything?: boolean; - /** - * A request's cache key is what determines if two requests are - * "the same" for caching purposes. If a request has the same cache key - * as some previous request, then we can serve the same cached response for - * both. (e.g. 'some-key') - * - * Only available for Enterprise customers. - */ - cacheKey?: string; - /** - * This allows you to append additional Cache-Tag response headers - * to the origin response without modifications to the origin server. - * This will allow for greater control over the Purge by Cache Tag feature - * utilizing changes only in the Workers process. - * - * Only available for Enterprise customers. - */ - cacheTags?: string[]; - /** - * Force response to be cached for a given number of seconds. (e.g. 300) - */ - cacheTtl?: number; - /** - * Force response to be cached for a given number of seconds based on the Origin status code. - * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) - */ - cacheTtlByStatus?: Record; - scrapeShield?: boolean; - apps?: boolean; - 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; + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record; + scrapeShield?: boolean; + apps?: boolean; + 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; } interface RequestInitCfPropertiesImageDraw extends BasicImageTransformations { - /** - * Absolute URL of the image file to use for the drawing. It can be any of - * the supported file formats. For drawing of watermarks or non-rectangular - * overlays we recommend using PNG or WebP images. - */ - url: string; - /** - * Floating-point number between 0 (transparent) and 1 (opaque). - * For example, opacity: 0.5 makes overlay semitransparent. - */ - opacity?: number; - /** - * - If set to true, the overlay image will be tiled to cover the entire - * area. This is useful for stock-photo-like watermarks. - * - If set to "x", the overlay image will be tiled horizontally only - * (form a line). - * - If set to "y", the overlay image will be tiled vertically only - * (form a line). - */ - repeat?: true | 'x' | 'y'; - /** - * 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 - * positions left side of the overlay 10 pixels from the left edge of the - * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom - * of the background image. - * - * Setting both left & right, or both top & bottom is an error. - * - * If no position is specified, the image will be centered. - */ - top?: number; - left?: number; - bottom?: number; - right?: number; + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * 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 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + 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 . - */ - 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' - | { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in . + */ + 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 - * to JPEG and WebP images. It doesn’t have any effect on PNG. - */ - quality?: number | 'low' | 'medium-low' | 'medium-high' | 'high'; - /** - * Output format to generate. It can be: - * - avif: generate images in AVIF format. - * - webp: generate images in Google WebP format. Set quality to 100 to get - * the WebP-lossless format. - * - json: instead of generating an image, outputs information about the - * image, in JSON format. The JSON object will contain image size - * (before and after resizing), source image’s MIME type, file size, etc. - * - jpeg: generate images in JPEG format. - * - png: generate images in PNG format. - */ - format?: 'avif' | 'webp' | 'json' | 'jpeg' | 'png' | 'baseline-jpeg' | 'png-force' | 'svg'; - /** - * Whether to preserve animation frames from input files. Default is true. - * Setting it to false reduces animations to still images. This setting is - * recommended when enlarging images or processing arbitrary user content, - * because large GIF animations can weigh tens or even hundreds of megabytes. - * It is also useful to set anim:false when using format:"json" to get the - * response quicker without the number of frames. - */ - anim?: boolean; - /** - * What EXIF data should be preserved in the output image. Note that EXIF - * rotation and embedded color profiles are always applied ("baked in" into - * the image), and aren't affected by this option. Note that if the Polish - * feature is enabled, all metadata may have been removed already and this - * option may have no effect. - * - keep: Preserve most of EXIF metadata, including GPS location if there's - * any. - * - copyright: Only keep the copyright tag, and discard everything else. - * This is the default behavior for JPEG files. - * - none: Discard all invisible EXIF metadata. Currently WebP and PNG - * 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). - */ - draw?: RequestInitCfPropertiesImageDraw[]; - /** - * Fetching image from authenticated origin. Setting this property will - * pass authentication headers (Authorization, Cookie, etc.) through to - * 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?: - | { + 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 + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number | "low" | "medium-low" | "medium-high" | "high"; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png" | "baseline-jpeg" | "png-force" | "svg"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * 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). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * 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 - * lower image quality. It will usually override the format option and choose - * JPEG over WebP or AVIF. We do not recommend using this option, except in - * unusual circumstances like resizing uncacheable dynamically-generated - * images. - */ - compression?: 'fast'; + }; + /** + * 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 + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; } interface RequestInitCfPropertiesImageMinify { - javascript?: boolean; - css?: boolean; - html?: boolean; + javascript?: boolean; + css?: boolean; + html?: boolean; } interface RequestInitCfPropertiesR2 { - /** - * Colo id of bucket that an object is stored in - */ - bucketColoId?: number; + /** + * Colo id of bucket that an object is stored in + */ + bucketColoId?: number; } /** * Request metadata provided by Cloudflare's edge. */ -type IncomingRequestCfProperties = IncomingRequestCfPropertiesBase & - IncomingRequestCfPropertiesBotManagementEnterprise & - IncomingRequestCfPropertiesCloudflareForSaaSEnterprise & - IncomingRequestCfPropertiesGeographicInformation & - IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +type IncomingRequestCfProperties = IncomingRequestCfPropertiesBase & IncomingRequestCfPropertiesBotManagementEnterprise & IncomingRequestCfPropertiesCloudflareForSaaSEnterprise & IncomingRequestCfPropertiesGeographicInformation & IncomingRequestCfPropertiesCloudflareAccessOrApiShield; interface IncomingRequestCfPropertiesBase extends Record { - /** - * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. - * - * @example 395747 - */ - asn?: number; - /** - * The organization which owns the ASN of the incoming request. - * - * @example "Google Cloud" - */ - asOrganization?: string; - /** - * The original value of the `Accept-Encoding` header if Cloudflare modified it. - * - * @example "gzip, deflate, br" - */ - clientAcceptEncoding?: string; - /** - * The number of milliseconds it took for the request to reach your worker. - * - * @example 22 - */ - clientTcpRtt?: number; - /** - * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) - * airport code of the data center that the request hit. - * - * @example "DFW" - */ - colo: string; - /** - * Represents the upstream's response to a - * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) - * from cloudflare. - * - * For workers with no upstream, this will always be `1`. - * - * @example 3 - */ - edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; - /** - * The HTTP Protocol the request used. - * - * @example "HTTP/2" - */ - httpProtocol: string; - /** - * The browser-requested prioritization information in the request object. - * - * If no information was set, defaults to the empty string `""` - * - * @example "weight=192;exclusive=0;group=3;group-weight=127" - * @default "" - */ - requestPriority: string; - /** - * The TLS version of the connection to Cloudflare. - * In requests served over plaintext (without TLS), this property is the empty string `""`. - * - * @example "TLSv1.3" - */ - tlsVersion: string; - /** - * The cipher for the connection to Cloudflare. - * In requests served over plaintext (without TLS), this property is the empty string `""`. - * - * @example "AEAD-AES128-GCM-SHA256" - */ - tlsCipher: string; - /** - * Metadata containing the [`HELLO`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2) and [`FINISHED`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9) messages from this request's TLS handshake. - * - * If the incoming request was served over plaintext (without TLS) this field is undefined. - */ - tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn?: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization?: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * Metadata containing the [`HELLO`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2) and [`FINISHED`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9) messages from this request's TLS handshake. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; } interface IncomingRequestCfPropertiesBotManagementBase { - /** - * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, - * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). - * - * @example 54 - */ - score: number; - /** - * A boolean value that is true if the request comes from a good bot, like Google or Bing. - * Most customers choose to allow this traffic. For more details, see [Traffic from known bots](https://developers.cloudflare.com/firewall/known-issues-and-faq/#how-does-firewall-rules-handle-traffic-from-known-bots). - */ - verifiedBot: boolean; - /** - * A boolean value that is true if the request originates from a - * Cloudflare-verified proxy service. - */ - corporateProxy: boolean; - /** - * A boolean value that's true if the request matches [file extensions](https://developers.cloudflare.com/bots/reference/static-resources/) for many types of static resources. - */ - staticResource: boolean; - /** - * List of IDs that correlate to the Bot Management heuristic detections made on a request (you can have multiple heuristic detections on the same request). - */ - detectionIds: number[]; + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * Most customers choose to allow this traffic. For more details, see [Traffic from known bots](https://developers.cloudflare.com/firewall/known-issues-and-faq/#how-does-firewall-rules-handle-traffic-from-known-bots). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * A boolean value that's true if the request matches [file extensions](https://developers.cloudflare.com/bots/reference/static-resources/) for many types of static resources. + */ + staticResource: boolean; + /** + * List of IDs that correlate to the Bot Management heuristic detections made on a request (you can have multiple heuristic detections on the same request). + */ + detectionIds: number[]; } interface IncomingRequestCfPropertiesBotManagement { - /** - * Results of Cloudflare's Bot Management analysis - */ - botManagement: IncomingRequestCfPropertiesBotManagementBase; - /** - * Duplicate of `botManagement.score`. - * - * @deprecated - */ - clientTrustScore: number; -} -interface IncomingRequestCfPropertiesBotManagementEnterprise - extends IncomingRequestCfPropertiesBotManagement { - /** - * Results of Cloudflare's Bot Management analysis - */ - botManagement: IncomingRequestCfPropertiesBotManagementBase & { - /** - * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients - * across different destination IPs, Ports, and X509 certificates. - */ - ja3Hash: string; - }; + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +interface IncomingRequestCfPropertiesBotManagementEnterprise extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; } interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise { - /** - * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). - * - * This field is only present if you have Cloudflare for SaaS enabled on your account - * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). - */ - hostMetadata?: HostMetadata; + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata?: HostMetadata; } interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { - /** - * Information about the client certificate presented to Cloudflare. - * - * This is populated when the incoming request is served over TLS using - * either Cloudflare Access or API Shield (mTLS) - * and the presented SSL certificate has a valid - * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) - * (i.e., not `null` or `""`). - * - * Otherwise, a set of placeholder values are used. - * - * The property `certPresented` will be set to `"1"` when - * the object is populated (i.e. the above conditions were met). - */ - tlsClientAuth: - | IncomingRequestCfPropertiesTLSClientAuth - | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: IncomingRequestCfPropertiesTLSClientAuth | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; } /** * Metadata about the request's TLS handshake */ interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { - /** - * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal - * - * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" - */ - clientHandshake: string; - /** - * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal - * - * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" - */ - serverHandshake: string; - /** - * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal - * - * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" - */ - clientFinished: string; - /** - * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal - * - * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" - */ - serverFinished: string; + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; } /** * Geographic data about the request's origin. */ interface IncomingRequestCfPropertiesGeographicInformation { - /** - * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. - * - * If your worker is [configured to accept TOR connections](https://support.cloudflare.com/hc/en-us/articles/203306930-Understanding-Cloudflare-Tor-support-and-Onion-Routing), this may also be `"T1"`, indicating a request that originated over TOR. - * - * If Cloudflare is unable to determine where the request originated this property is omitted. - * - * The country code `"T1"` is used for requests originating on TOR. - * - * @example "GB" - */ - country?: Iso3166Alpha2Code | 'T1'; - /** - * If present, this property indicates that the request originated in the EU - * - * @example "1" - */ - isEUCountry?: '1'; - /** - * A two-letter code indicating the continent the request originated from. - * - * @example "AN" - */ - continent?: ContinentCode; - /** - * The city the request originated from - * - * @example "Austin" - */ - city?: string; - /** - * Postal code of the incoming request - * - * @example "78701" - */ - postalCode?: string; - /** - * Latitude of the incoming request - * - * @example "30.27130" - */ - latitude?: string; - /** - * Longitude of the incoming request - * - * @example "-97.74260" - */ - longitude?: string; - /** - * Timezone of the incoming request - * - * @example "America/Chicago" - */ - timezone?: string; - /** - * If known, the ISO 3166-2 name for the first level region associated with - * the IP address of the incoming request - * - * @example "Texas" - */ - region?: string; - /** - * If known, the ISO 3166-2 code for the first-level region associated with - * the IP address of the incoming request - * - * @example "TX" - */ - regionCode?: string; - /** - * Metro code (DMA) of the incoming request - * - * @example "635" - */ - metroCode?: string; + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * If your worker is [configured to accept TOR connections](https://support.cloudflare.com/hc/en-us/articles/203306930-Understanding-Cloudflare-Tor-support-and-Onion-Routing), this may also be `"T1"`, indicating a request that originated over TOR. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; } /** Data about the incoming request's TLS certificate */ interface IncomingRequestCfPropertiesTLSClientAuth { - /** Always `"1"`, indicating that the certificate was presented */ - certPresented: '1'; - /** - * Result of certificate verification. - * - * @example "FAILED:self signed certificate" - */ - certVerified: Exclude; - /** The presented certificate's revokation status. - * - * - A value of `"1"` indicates the certificate has been revoked - * - A value of `"0"` indicates the certificate has not been revoked - */ - certRevoked: '1' | '0'; - /** - * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) - * - * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" - */ - certIssuerDN: string; - /** - * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) - * - * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" - */ - certSubjectDN: string; - /** - * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) - * - * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" - */ - certIssuerDNRFC2253: string; - /** - * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) - * - * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" - */ - certSubjectDNRFC2253: string; - /** The certificate issuer's distinguished name (legacy policies) */ - certIssuerDNLegacy: string; - /** The certificate subject's distinguished name (legacy policies) */ - certSubjectDNLegacy: string; - /** - * The certificate's serial number - * - * @example "00936EACBE07F201DF" - */ - certSerial: string; - /** - * The certificate issuer's serial number - * - * @example "2489002934BDFEA34" - */ - certIssuerSerial: string; - /** - * The certificate's Subject Key Identifier - * - * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" - */ - certSKI: string; - /** - * The certificate issuer's Subject Key Identifier - * - * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" - */ - certIssuerSKI: string; - /** - * The certificate's SHA-1 fingerprint - * - * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" - */ - certFingerprintSHA1: string; - /** - * The certificate's SHA-256 fingerprint - * - * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" - */ - certFingerprintSHA256: string; - /** - * The effective starting date of the certificate - * - * @example "Dec 22 19:39:00 2018 GMT" - */ - certNotBefore: string; - /** - * The effective expiration date of the certificate - * - * @example "Dec 22 19:39:00 2018 GMT" - */ - certNotAfter: string; + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; } /** Placeholder values for TLS Client Authorization */ interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { - certPresented: '0'; - certVerified: 'NONE'; - certRevoked: '0'; - certIssuerDN: ''; - certSubjectDN: ''; - certIssuerDNRFC2253: ''; - certSubjectDNRFC2253: ''; - certIssuerDNLegacy: ''; - certSubjectDNLegacy: ''; - certSerial: ''; - certIssuerSerial: ''; - certSKI: ''; - certIssuerSKI: ''; - certFingerprintSHA1: ''; - certFingerprintSHA256: ''; - certNotBefore: ''; - certNotAfter: ''; + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; } /** Possible outcomes of TLS verification */ -declare type CertVerificationStatus = - /** Authentication succeeded */ - | 'SUCCESS' - /** No certificate was presented */ - | 'NONE' - /** Failed because the certificate was self-signed */ - | 'FAILED:self signed certificate' - /** Failed because the certificate failed a trust chain check */ - | 'FAILED:unable to verify the first certificate' - /** Failed because the certificate not yet valid */ - | 'FAILED:certificate is not yet valid' - /** Failed because the certificate is expired */ - | 'FAILED:certificate has expired' - /** Failed for another unspecified reason */ - | 'FAILED'; +declare type CertVerificationStatus = +/** Authentication succeeded */ +"SUCCESS" +/** No certificate was presented */ + | "NONE" +/** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" +/** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" +/** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" +/** Failed because the certificate is expired */ + | "FAILED:certificate has expired" +/** Failed for another unspecified reason */ + | "FAILED"; /** * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. */ -declare type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus = - | 0 /** Unknown */ - | 1 /** no keepalives (not found) */ - | 2 /** no connection re-use, opening keepalive connection failed */ - | 3 /** no connection re-use, keepalive accepted and saved */ - | 4 /** connection re-use, refused by the origin server (`TCP FIN`) */ - | 5; /** connection re-use, accepted by the origin server */ +declare type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus = 0 /** Unknown */ | 1 /** no keepalives (not found) */ | 2 /** no connection re-use, opening keepalive connection failed */ | 3 /** no connection re-use, keepalive accepted and saved */ | 4 /** connection re-use, refused by the origin server (`TCP FIN`) */ | 5; /** connection re-use, accepted by the origin server */ /** ISO 3166-1 Alpha-2 codes */ -declare type Iso3166Alpha2Code = - | 'AD' - | 'AE' - | 'AF' - | 'AG' - | 'AI' - | 'AL' - | 'AM' - | 'AO' - | 'AQ' - | 'AR' - | 'AS' - | 'AT' - | 'AU' - | 'AW' - | 'AX' - | 'AZ' - | 'BA' - | 'BB' - | 'BD' - | 'BE' - | 'BF' - | 'BG' - | 'BH' - | 'BI' - | 'BJ' - | 'BL' - | 'BM' - | 'BN' - | 'BO' - | 'BQ' - | 'BR' - | 'BS' - | 'BT' - | 'BV' - | 'BW' - | 'BY' - | 'BZ' - | 'CA' - | 'CC' - | 'CD' - | 'CF' - | 'CG' - | 'CH' - | 'CI' - | 'CK' - | 'CL' - | 'CM' - | 'CN' - | 'CO' - | 'CR' - | 'CU' - | 'CV' - | 'CW' - | 'CX' - | 'CY' - | 'CZ' - | 'DE' - | 'DJ' - | 'DK' - | 'DM' - | 'DO' - | 'DZ' - | 'EC' - | 'EE' - | 'EG' - | 'EH' - | 'ER' - | 'ES' - | 'ET' - | 'FI' - | 'FJ' - | 'FK' - | 'FM' - | 'FO' - | 'FR' - | 'GA' - | 'GB' - | 'GD' - | 'GE' - | 'GF' - | 'GG' - | 'GH' - | 'GI' - | 'GL' - | 'GM' - | 'GN' - | 'GP' - | 'GQ' - | 'GR' - | 'GS' - | 'GT' - | 'GU' - | 'GW' - | 'GY' - | 'HK' - | 'HM' - | 'HN' - | 'HR' - | 'HT' - | 'HU' - | 'ID' - | 'IE' - | 'IL' - | 'IM' - | 'IN' - | 'IO' - | 'IQ' - | 'IR' - | 'IS' - | 'IT' - | 'JE' - | 'JM' - | 'JO' - | 'JP' - | 'KE' - | 'KG' - | 'KH' - | 'KI' - | 'KM' - | 'KN' - | 'KP' - | 'KR' - | 'KW' - | 'KY' - | 'KZ' - | 'LA' - | 'LB' - | 'LC' - | 'LI' - | 'LK' - | 'LR' - | 'LS' - | 'LT' - | 'LU' - | 'LV' - | 'LY' - | 'MA' - | 'MC' - | 'MD' - | 'ME' - | 'MF' - | 'MG' - | 'MH' - | 'MK' - | 'ML' - | 'MM' - | 'MN' - | 'MO' - | 'MP' - | 'MQ' - | 'MR' - | 'MS' - | 'MT' - | 'MU' - | 'MV' - | 'MW' - | 'MX' - | 'MY' - | 'MZ' - | 'NA' - | 'NC' - | 'NE' - | 'NF' - | 'NG' - | 'NI' - | 'NL' - | 'NO' - | 'NP' - | 'NR' - | 'NU' - | 'NZ' - | 'OM' - | 'PA' - | 'PE' - | 'PF' - | 'PG' - | 'PH' - | 'PK' - | 'PL' - | 'PM' - | 'PN' - | 'PR' - | 'PS' - | 'PT' - | 'PW' - | 'PY' - | 'QA' - | 'RE' - | 'RO' - | 'RS' - | 'RU' - | 'RW' - | 'SA' - | 'SB' - | 'SC' - | 'SD' - | 'SE' - | 'SG' - | 'SH' - | 'SI' - | 'SJ' - | 'SK' - | 'SL' - | 'SM' - | 'SN' - | 'SO' - | 'SR' - | 'SS' - | 'ST' - | 'SV' - | 'SX' - | 'SY' - | 'SZ' - | 'TC' - | 'TD' - | 'TF' - | 'TG' - | 'TH' - | 'TJ' - | 'TK' - | 'TL' - | 'TM' - | 'TN' - | 'TO' - | 'TR' - | 'TT' - | 'TV' - | 'TW' - | 'TZ' - | 'UA' - | 'UG' - | 'UM' - | 'US' - | 'UY' - | 'UZ' - | 'VA' - | 'VC' - | 'VE' - | 'VG' - | 'VI' - | 'VN' - | 'VU' - | 'WF' - | 'WS' - | 'YE' - | 'YT' - | 'ZA' - | 'ZM' - | 'ZW'; +declare type Iso3166Alpha2Code = "AD" | "AE" | "AF" | "AG" | "AI" | "AL" | "AM" | "AO" | "AQ" | "AR" | "AS" | "AT" | "AU" | "AW" | "AX" | "AZ" | "BA" | "BB" | "BD" | "BE" | "BF" | "BG" | "BH" | "BI" | "BJ" | "BL" | "BM" | "BN" | "BO" | "BQ" | "BR" | "BS" | "BT" | "BV" | "BW" | "BY" | "BZ" | "CA" | "CC" | "CD" | "CF" | "CG" | "CH" | "CI" | "CK" | "CL" | "CM" | "CN" | "CO" | "CR" | "CU" | "CV" | "CW" | "CX" | "CY" | "CZ" | "DE" | "DJ" | "DK" | "DM" | "DO" | "DZ" | "EC" | "EE" | "EG" | "EH" | "ER" | "ES" | "ET" | "FI" | "FJ" | "FK" | "FM" | "FO" | "FR" | "GA" | "GB" | "GD" | "GE" | "GF" | "GG" | "GH" | "GI" | "GL" | "GM" | "GN" | "GP" | "GQ" | "GR" | "GS" | "GT" | "GU" | "GW" | "GY" | "HK" | "HM" | "HN" | "HR" | "HT" | "HU" | "ID" | "IE" | "IL" | "IM" | "IN" | "IO" | "IQ" | "IR" | "IS" | "IT" | "JE" | "JM" | "JO" | "JP" | "KE" | "KG" | "KH" | "KI" | "KM" | "KN" | "KP" | "KR" | "KW" | "KY" | "KZ" | "LA" | "LB" | "LC" | "LI" | "LK" | "LR" | "LS" | "LT" | "LU" | "LV" | "LY" | "MA" | "MC" | "MD" | "ME" | "MF" | "MG" | "MH" | "MK" | "ML" | "MM" | "MN" | "MO" | "MP" | "MQ" | "MR" | "MS" | "MT" | "MU" | "MV" | "MW" | "MX" | "MY" | "MZ" | "NA" | "NC" | "NE" | "NF" | "NG" | "NI" | "NL" | "NO" | "NP" | "NR" | "NU" | "NZ" | "OM" | "PA" | "PE" | "PF" | "PG" | "PH" | "PK" | "PL" | "PM" | "PN" | "PR" | "PS" | "PT" | "PW" | "PY" | "QA" | "RE" | "RO" | "RS" | "RU" | "RW" | "SA" | "SB" | "SC" | "SD" | "SE" | "SG" | "SH" | "SI" | "SJ" | "SK" | "SL" | "SM" | "SN" | "SO" | "SR" | "SS" | "ST" | "SV" | "SX" | "SY" | "SZ" | "TC" | "TD" | "TF" | "TG" | "TH" | "TJ" | "TK" | "TL" | "TM" | "TN" | "TO" | "TR" | "TT" | "TV" | "TW" | "TZ" | "UA" | "UG" | "UM" | "US" | "UY" | "UZ" | "VA" | "VC" | "VE" | "VG" | "VI" | "VN" | "VU" | "WF" | "WS" | "YE" | "YT" | "ZA" | "ZM" | "ZW"; /** The 2-letter continent codes Cloudflare uses */ -declare type ContinentCode = 'AF' | 'AN' | 'AS' | 'EU' | 'NA' | 'OC' | 'SA'; -type CfProperties = - | IncomingRequestCfProperties - | RequestInitCfProperties; +declare type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +type CfProperties = IncomingRequestCfProperties | RequestInitCfProperties; interface D1Meta { - duration: number; - size_after: number; - rows_read: number; - rows_written: number; - last_row_id: number; - changed_db: boolean; - changes: number; - /** - * The region of the database instance that executed the query. - */ - served_by_region?: string; - /** - * The three letters airport code of the colo that executed the query. - */ - served_by_colo?: string; - /** - * True if-and-only-if the database instance that executed the query was the primary. - */ - served_by_primary?: boolean; - timings?: { - /** - * The duration of the SQL query execution by the database instance. It doesn't include any network time. - */ - sql_duration_ms: number; - }; - /** - * Number of total attempts to execute the query, due to automatic retries. - * Note: All other fields in the response like `timings` only apply to the last attempt. - */ - total_attempts?: number; + duration: number; + size_after: number; + rows_read: number; + rows_written: number; + last_row_id: number; + changed_db: boolean; + changes: number; + /** + * The region of the database instance that executed the query. + */ + served_by_region?: string; + /** + * The three letters airport code of the colo that executed the query. + */ + served_by_colo?: string; + /** + * True if-and-only-if the database instance that executed the query was the primary. + */ + served_by_primary?: boolean; + timings?: { + /** + * The duration of the SQL query execution by the database instance. It doesn't include any network time. + */ + sql_duration_ms: number; + }; + /** + * Number of total attempts to execute the query, due to automatic retries. + * Note: All other fields in the response like `timings` only apply to the last attempt. + */ + total_attempts?: number; } interface D1Response { - success: true; - meta: D1Meta & Record; - error?: never; + success: true; + meta: D1Meta & Record; + error?: never; } type D1Result = D1Response & { - results: T[]; + results: T[]; }; interface D1ExecResult { - count: number; - duration: number; -} -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). - | 'first-primary' - // Indicates that the first query can go anywhere (primary or replica), 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). - | 'first-unconstrained'; + count: number; + duration: number; +} +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). +'first-primary' +// Indicates that the first query can go anywhere (primary or replica), 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). + | 'first-unconstrained'; type D1SessionBookmark = string; declare abstract class D1Database { - prepare(query: string): D1PreparedStatement; - batch(statements: D1PreparedStatement[]): Promise[]>; - exec(query: string): Promise; - /** - * Creates a new D1 Session anchored at the given constraint or the bookmark. - * All queries executed using the created session will have sequential consistency, - * meaning that all writes done through the session will be visible in subsequent reads. - * - * @param constraintOrBookmark Either the session constraint or the explicit bookmark to anchor the created session. - */ - withSession(constraintOrBookmark?: D1SessionBookmark | D1SessionConstraint): D1DatabaseSession; - /** - * @deprecated dump() will be removed soon, only applies to deprecated alpha v1 databases. - */ - dump(): Promise; + prepare(query: string): D1PreparedStatement; + batch(statements: D1PreparedStatement[]): Promise[]>; + exec(query: string): Promise; + /** + * Creates a new D1 Session anchored at the given constraint or the bookmark. + * All queries executed using the created session will have sequential consistency, + * meaning that all writes done through the session will be visible in subsequent reads. + * + * @param constraintOrBookmark Either the session constraint or the explicit bookmark to anchor the created session. + */ + withSession(constraintOrBookmark?: D1SessionBookmark | D1SessionConstraint): D1DatabaseSession; + /** + * @deprecated dump() will be removed soon, only applies to deprecated alpha v1 databases. + */ + dump(): Promise; } declare abstract class D1DatabaseSession { - prepare(query: string): D1PreparedStatement; - batch(statements: D1PreparedStatement[]): Promise[]>; - /** - * @returns The latest session bookmark across all executed queries on the session. - * If no query has been executed yet, `null` is returned. - */ - getBookmark(): D1SessionBookmark | null; + prepare(query: string): D1PreparedStatement; + batch(statements: D1PreparedStatement[]): Promise[]>; + /** + * @returns The latest session bookmark across all executed queries on the session. + * If no query has been executed yet, `null` is returned. + */ + getBookmark(): D1SessionBookmark | null; } declare abstract class D1PreparedStatement { - bind(...values: unknown[]): D1PreparedStatement; - first(colName: string): Promise; - first>(): Promise; - run>(): Promise>; - all>(): Promise>; - raw(options: { columnNames: true }): Promise<[string[], ...T[]]>; - raw(options?: { columnNames?: false }): Promise; + bind(...values: unknown[]): D1PreparedStatement; + first(colName: string): Promise; + first>(): Promise; + run>(): Promise>; + all>(): Promise>; + raw(options: { + columnNames: true; + }): Promise<[ + string[], + ...T[] + ]>; + raw(options?: { + columnNames?: false; + }): Promise; } // `Disposable` was added to TypeScript's standard lib types in version 5.2. // To support older TypeScript versions, define an empty `Disposable` interface. @@ -10500,1149 +9853,1015 @@ declare abstract class D1PreparedStatement { // but this will ensure type checking on older versions still passes. // TypeScript's interface merging will ensure our empty interface is effectively // ignored when `Disposable` is included in the standard lib. -interface Disposable {} +interface Disposable { +} /** * The returned data after sending an email */ interface EmailSendResult { - /** - * The Email Message ID - */ - messageId: string; + /** + * The Email Message ID + */ + messageId: string; } /** * An email message that can be sent from a Worker. */ interface EmailMessage { - /** - * Envelope From attribute of the email message. - */ - readonly from: string; - /** - * Envelope To attribute of the email message. - */ - readonly to: string; + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; } /** * An email message that is sent to a consumer Worker and can be rejected/forwarded. */ interface ForwardableEmailMessage extends EmailMessage { - /** - * Stream of the email message content. - */ - readonly raw: ReadableStream; - /** - * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). - */ - readonly headers: Headers; - /** - * Size of the email message content. - */ - readonly rawSize: number; - /** - * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. - * @param reason The reject reason. - * @returns void - */ - setReject(reason: string): void; - /** - * Forward this email message to a verified destination address of the account. - * @param rcptTo Verified destination address. - * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). - * @returns A promise that resolves when the email message is forwarded. - */ - forward(rcptTo: string, headers?: Headers): Promise; - /** - * Reply to the sender of this email message with a new EmailMessage object. - * @param message The reply message. - * @returns A promise that resolves when the email message is replied. - */ - reply(message: EmailMessage): Promise; + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise; + /** + * Reply to the sender of this email message with a new EmailMessage object. + * @param message The reply message. + * @returns A promise that resolves when the email message is replied. + */ + reply(message: EmailMessage): Promise; } /** A file attachment for an email message */ -type EmailAttachment = - | { - disposition: 'inline'; - contentId: string; - filename: string; - type: string; - content: string | ArrayBuffer | ArrayBufferView; - } - | { - disposition: 'attachment'; - contentId?: undefined; - filename: string; - type: string; - content: string | ArrayBuffer | ArrayBufferView; - }; +type EmailAttachment = { + disposition: 'inline'; + contentId: string; + filename: string; + type: string; + content: string | ArrayBuffer | ArrayBufferView; +} | { + disposition: 'attachment'; + contentId?: undefined; + filename: string; + type: string; + content: string | ArrayBuffer | ArrayBufferView; +}; /** An Email Address */ interface EmailAddress { - name: string; - email: string; + name: string; + email: string; } /** * A binding that allows a Worker to send email messages. */ interface SendEmail { - send(message: EmailMessage): Promise; - send(builder: { - from: string | EmailAddress; - to: string | string[]; - subject: string; - replyTo?: string | EmailAddress; - cc?: string | string[]; - bcc?: string | string[]; - headers?: Record; - text?: string; - html?: string; - attachments?: EmailAttachment[]; - }): Promise; + send(message: EmailMessage): Promise; + send(builder: { + from: string | EmailAddress; + to: string | string[]; + subject: string; + replyTo?: string | EmailAddress; + cc?: string | string[]; + bcc?: string | string[]; + headers?: Record; + text?: string; + html?: string; + attachments?: EmailAttachment[]; + }): Promise; } declare abstract class EmailEvent extends ExtendableEvent { - readonly message: ForwardableEmailMessage; -} -declare type EmailExportedHandler = ( - message: ForwardableEmailMessage, - env: Env, - ctx: ExecutionContext -) => void | Promise; -declare module 'cloudflare:email' { - let _EmailMessage: { - prototype: EmailMessage; - new (from: string, to: string, raw: ReadableStream | string): EmailMessage; - }; - export { _EmailMessage as EmailMessage }; + readonly message: ForwardableEmailMessage; +} +declare type EmailExportedHandler = (message: ForwardableEmailMessage, env: Env, ctx: ExecutionContext) => void | Promise; +declare module "cloudflare:email" { + let _EmailMessage: { + prototype: EmailMessage; + new (from: string, to: string, raw: ReadableStream | string): EmailMessage; + }; + export { _EmailMessage as EmailMessage }; } /** * Hello World binding to serve as an explanatory example. DO NOT USE */ interface HelloWorldBinding { - /** - * Retrieve the current stored value - */ - get(): Promise<{ - value: string; - ms?: number; - }>; - /** - * Set a new stored value - */ - set(value: string): Promise; + /** + * Retrieve the current stored value + */ + get(): Promise<{ + value: string; + ms?: number; + }>; + /** + * Set a new stored value + */ + set(value: string): Promise; } interface Hyperdrive { - /** - * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. - * - * Calling this method returns an identical socket to if you call - * `connect("host:port")` using the `host` and `port` fields from this object. - * Pick whichever approach works better with your preferred DB client library. - * - * Note that this socket is not yet authenticated -- it's expected that your - * code (or preferably, the client library of your choice) will authenticate - * using the information in this class's readonly fields. - */ - connect(): Socket; - /** - * A valid DB connection string that can be passed straight into the typical - * client library/driver/ORM. This will typically be the easiest way to use - * Hyperdrive. - */ - readonly connectionString: string; - /* - * A randomly generated hostname that is only valid within the context of the - * currently running Worker which, when passed into `connect()` function from - * the "cloudflare:sockets" module, will connect to the Hyperdrive instance - * for your database. - */ - readonly host: string; - /* - * The port that must be paired the the host field when connecting. - */ - readonly port: number; - /* - * The username to use when authenticating to your database via Hyperdrive. - * Unlike the host and password, this will be the same every time - */ - readonly user: string; - /* - * The randomly generated password to use when authenticating to your - * database via Hyperdrive. Like the host field, this password is only valid - * within the context of the currently running Worker instance from which - * it's read. - */ - readonly password: string; - /* - * The name of the database to connect to. - */ - readonly database: string; + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an identical socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: number; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; } // Copyright (c) 2024 Cloudflare, Inc. // Licensed under the Apache 2.0 license found in the LICENSE file or at: // https://opensource.org/licenses/Apache-2.0 -type ImageInfoResponse = - | { - format: 'image/svg+xml'; - } - | { - format: string; - fileSize: number; - width: number; - height: number; - }; +type ImageInfoResponse = { + format: 'image/svg+xml'; +} | { + format: string; + fileSize: number; + width: number; + height: number; +}; type ImageTransform = { - width?: number; - height?: number; - background?: string; - blur?: number; - border?: - | { + width?: number; + height?: number; + background?: string; + blur?: number; + border?: { color?: string; width?: number; - } - | { + } | { top?: number; bottom?: number; left?: number; right?: number; - }; - brightness?: number; - contrast?: number; - fit?: 'scale-down' | 'contain' | 'pad' | 'squeeze' | 'cover' | 'crop'; - flip?: 'h' | 'v' | 'hv'; - gamma?: number; - segment?: 'foreground'; - gravity?: - | 'face' - | 'left' - | 'right' - | 'top' - | 'bottom' - | 'center' - | 'auto' - | 'entropy' - | { + }; + brightness?: number; + contrast?: number; + fit?: 'scale-down' | 'contain' | 'pad' | 'squeeze' | 'cover' | 'crop'; + flip?: 'h' | 'v' | 'hv'; + gamma?: number; + segment?: 'foreground'; + gravity?: 'face' | 'left' | 'right' | 'top' | 'bottom' | 'center' | 'auto' | 'entropy' | { x?: number; y?: number; mode: 'remainder' | 'box-center'; - }; - rotate?: 0 | 90 | 180 | 270; - saturation?: number; - sharpen?: number; - trim?: - | 'border' - | { + }; + rotate?: 0 | 90 | 180 | 270; + saturation?: number; + sharpen?: number; + trim?: 'border' | { top?: number; bottom?: number; left?: number; right?: number; width?: number; height?: number; - border?: - | boolean - | { - color?: string; - tolerance?: number; - keep?: number; - }; - }; + border?: boolean | { + color?: string; + tolerance?: number; + keep?: number; + }; + }; }; type ImageDrawOptions = { - opacity?: number; - repeat?: boolean | string; - top?: number; - left?: number; - bottom?: number; - right?: number; + opacity?: number; + repeat?: boolean | string; + top?: number; + left?: number; + bottom?: number; + right?: number; }; type ImageInputOptions = { - encoding?: 'base64'; + encoding?: 'base64'; }; type ImageOutputOptions = { - format: 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp' | 'image/avif' | 'rgb' | 'rgba'; - quality?: number; - background?: string; - anim?: boolean; + format: 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp' | 'image/avif' | 'rgb' | 'rgba'; + quality?: number; + background?: string; + anim?: boolean; }; interface ImagesBinding { - /** - * Get image metadata (type, width and height) - * @throws {@link ImagesError} with code 9412 if input is not an image - * @param stream The image bytes - */ - info(stream: ReadableStream, options?: ImageInputOptions): Promise; - /** - * Begin applying a series of transformations to an image - * @param stream The image bytes - * @returns A transform handle - */ - input(stream: ReadableStream, options?: ImageInputOptions): ImageTransformer; + /** + * Get image metadata (type, width and height) + * @throws {@link ImagesError} with code 9412 if input is not an image + * @param stream The image bytes + */ + info(stream: ReadableStream, options?: ImageInputOptions): Promise; + /** + * Begin applying a series of transformations to an image + * @param stream The image bytes + * @returns A transform handle + */ + input(stream: ReadableStream, options?: ImageInputOptions): ImageTransformer; } interface ImageTransformer { - /** - * Apply transform next, returning a transform handle. - * You can then apply more transformations, draw, or retrieve the output. - * @param transform - */ - transform(transform: ImageTransform): ImageTransformer; - /** - * Draw an image on this transformer, returning a transform handle. - * You can then apply more transformations, draw, or retrieve the output. - * @param image The image (or transformer that will give the image) to draw - * @param options The options configuring how to draw the image - */ - draw( - image: ReadableStream | ImageTransformer, - options?: ImageDrawOptions - ): ImageTransformer; - /** - * Retrieve the image that results from applying the transforms to the - * provided input - * @param options Options that apply to the output e.g. output format - */ - output(options: ImageOutputOptions): Promise; + /** + * Apply transform next, returning a transform handle. + * You can then apply more transformations, draw, or retrieve the output. + * @param transform + */ + transform(transform: ImageTransform): ImageTransformer; + /** + * Draw an image on this transformer, returning a transform handle. + * You can then apply more transformations, draw, or retrieve the output. + * @param image The image (or transformer that will give the image) to draw + * @param options The options configuring how to draw the image + */ + draw(image: ReadableStream | ImageTransformer, options?: ImageDrawOptions): ImageTransformer; + /** + * Retrieve the image that results from applying the transforms to the + * provided input + * @param options Options that apply to the output e.g. output format + */ + output(options: ImageOutputOptions): Promise; } type ImageTransformationOutputOptions = { - encoding?: 'base64'; + encoding?: 'base64'; }; interface ImageTransformationResult { - /** - * The image as a response, ready to store in cache or return to users - */ - response(): Response; - /** - * The content type of the returned image - */ - contentType(): string; - /** - * The bytes of the response - */ - image(options?: ImageTransformationOutputOptions): ReadableStream; + /** + * The image as a response, ready to store in cache or return to users + */ + response(): Response; + /** + * The content type of the returned image + */ + contentType(): string; + /** + * The bytes of the response + */ + image(options?: ImageTransformationOutputOptions): ReadableStream; } interface ImagesError extends Error { - readonly code: number; - readonly message: string; - readonly stack?: string; + readonly code: number; + readonly message: string; + readonly stack?: string; } /** * Media binding for transforming media streams. * Provides the entry point for media transformation operations. */ interface MediaBinding { - /** - * Creates a media transformer from an input stream. - * @param media - The input media bytes - * @returns A MediaTransformer instance for applying transformations - */ - input(media: ReadableStream): MediaTransformer; + /** + * Creates a media transformer from an input stream. + * @param media - The input media bytes + * @returns A MediaTransformer instance for applying transformations + */ + input(media: ReadableStream): MediaTransformer; } /** * Media transformer for applying transformation operations to media content. * Handles sizing, fitting, and other input transformation parameters. */ interface MediaTransformer { - /** - * Applies transformation options to the media content. - * @param transform - Configuration for how the media should be transformed - * @returns A generator for producing the transformed media output - */ - transform(transform: MediaTransformationInputOptions): MediaTransformationGenerator; + /** + * Applies transformation options to the media content. + * @param transform - Configuration for how the media should be transformed + * @returns A generator for producing the transformed media output + */ + transform(transform?: MediaTransformationInputOptions): MediaTransformationGenerator; + /** + * Generates the final media output with specified options. + * @param output - Configuration for the output format and parameters + * @returns The final transformation result containing the transformed media + */ + output(output?: MediaTransformationOutputOptions): MediaTransformationResult; } /** * Generator for producing media transformation results. * Configures the output format and parameters for the transformed media. */ interface MediaTransformationGenerator { - /** - * Generates the final media output with specified options. - * @param output - Configuration for the output format and parameters - * @returns The final transformation result containing the transformed media - */ - output(output: MediaTransformationOutputOptions): MediaTransformationResult; + /** + * Generates the final media output with specified options. + * @param output - Configuration for the output format and parameters + * @returns The final transformation result containing the transformed media + */ + output(output?: MediaTransformationOutputOptions): MediaTransformationResult; } /** * Result of a media transformation operation. * Provides multiple ways to access the transformed media content. */ interface MediaTransformationResult { - /** - * Returns the transformed media as a readable stream of bytes. - * @returns A stream containing the transformed media data - */ - media(): ReadableStream; - /** - * Returns the transformed media as an HTTP response object. - * @returns The transformed media as a Response, ready to store in cache or return to users - */ - response(): Response; - /** - * Returns the MIME type of the transformed media. - * @returns The content type string (e.g., 'image/jpeg', 'video/mp4') - */ - contentType(): string; + /** + * Returns the transformed media as a readable stream of bytes. + * @returns A promise containing a readable stream with the transformed media + */ + media(): Promise>; + /** + * Returns the transformed media as an HTTP response object. + * @returns The transformed media as a Promise, ready to store in cache or return to users + */ + response(): Promise; + /** + * Returns the MIME type of the transformed media. + * @returns A promise containing the content type string (e.g., 'image/jpeg', 'video/mp4') + */ + contentType(): Promise; } /** * Configuration options for transforming media input. * Controls how the media should be resized and fitted. */ type MediaTransformationInputOptions = { - /** How the media should be resized to fit the specified dimensions */ - fit?: 'contain' | 'cover' | 'scale-down'; - /** Target width in pixels */ - width?: number; - /** Target height in pixels */ - height?: number; + /** How the media should be resized to fit the specified dimensions */ + fit?: 'contain' | 'cover' | 'scale-down'; + /** Target width in pixels */ + width?: number; + /** Target height in pixels */ + height?: number; }; /** * Configuration options for Media Transformations output. * Controls the format, timing, and type of the generated output. */ type MediaTransformationOutputOptions = { - /** - * Output mode determining the type of media to generate - */ - mode?: 'video' | 'spritesheet' | 'frame' | 'audio'; - /** Whether to include audio in the output */ - audio?: boolean; - /** - * Starting timestamp for frame extraction or start time for clips. (e.g. '2s'). - */ - time?: string; - /** - * Duration for video clips, audio extraction, and spritesheet generation (e.g. '5s'). - */ - duration?: string; - /** - * Number of frames in the spritesheet. - */ - imageCount?: number; - /** - * Output format for the generated media. - */ - format?: 'jpg' | 'png' | 'm4a'; + /** + * Output mode determining the type of media to generate + */ + mode?: 'video' | 'spritesheet' | 'frame' | 'audio'; + /** Whether to include audio in the output */ + audio?: boolean; + /** + * Starting timestamp for frame extraction or start time for clips. (e.g. '2s'). + */ + time?: string; + /** + * Duration for video clips, audio extraction, and spritesheet generation (e.g. '5s'). + */ + duration?: string; + /** + * Number of frames in the spritesheet. + */ + imageCount?: number; + /** + * Output format for the generated media. + */ + format?: 'jpg' | 'png' | 'm4a'; }; /** * Error object for media transformation operations. * Extends the standard Error interface with additional media-specific information. */ interface MediaError extends Error { - readonly code: number; - readonly message: string; - readonly stack?: string; + readonly code: number; + readonly message: string; + readonly stack?: string; } declare module 'cloudflare:node' { - interface NodeStyleServer { - listen(...args: unknown[]): this; - address(): { - port?: number | null | undefined; - }; - } - export function httpServerHandler(port: number): ExportedHandler; - export function httpServerHandler(options: { port: number }): ExportedHandler; - export function httpServerHandler(server: NodeStyleServer): ExportedHandler; + interface NodeStyleServer { + listen(...args: unknown[]): this; + address(): { + port?: number | null | undefined; + }; + } + export function httpServerHandler(port: number): ExportedHandler; + export function httpServerHandler(options: { + port: number; + }): ExportedHandler; + export function httpServerHandler(server: NodeStyleServer): ExportedHandler; } type Params

= Record; type EventContext = { - request: Request>; - functionPath: string; - waitUntil: (promise: Promise) => void; - passThroughOnException: () => void; - next: (input?: Request | string, init?: RequestInit) => Promise; - env: Env & { - ASSETS: { - fetch: typeof fetch; + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; }; - }; - params: Params

; - data: Data; -}; -type PagesFunction< - Env = unknown, - Params extends string = any, - Data extends Record = Record, -> = (context: EventContext) => Response | Promise; + params: Params

; + data: Data; +}; +type PagesFunction = Record> = (context: EventContext) => Response | Promise; type EventPluginContext = { - request: Request>; - functionPath: string; - waitUntil: (promise: Promise) => void; - passThroughOnException: () => void; - next: (input?: Request | string, init?: RequestInit) => Promise; - env: Env & { - ASSETS: { - fetch: typeof fetch; + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; }; - }; - params: Params

; - data: Data; - pluginArgs: PluginArgs; -}; -type PagesPluginFunction< - Env = unknown, - Params extends string = any, - Data extends Record = Record, - PluginArgs = unknown, -> = (context: EventPluginContext) => Response | Promise; -declare module 'assets:*' { - export const onRequest: PagesFunction; + params: Params

; + data: Data; + pluginArgs: PluginArgs; +}; +type PagesPluginFunction = Record, PluginArgs = unknown> = (context: EventPluginContext) => Response | Promise; +declare module "assets:*" { + export const onRequest: PagesFunction; } // Copyright (c) 2022-2023 Cloudflare, Inc. // Licensed under the Apache 2.0 license found in the LICENSE file or at: // https://opensource.org/licenses/Apache-2.0 -declare module 'cloudflare:pipelines' { - export abstract class PipelineTransformationEntrypoint< - Env = unknown, - I extends PipelineRecord = PipelineRecord, - O extends PipelineRecord = PipelineRecord, - > { - protected env: Env; - protected ctx: ExecutionContext; - constructor(ctx: ExecutionContext, env: Env); - /** - * run receives an array of PipelineRecord which can be - * transformed and returned to the pipeline - * @param records Incoming records from the pipeline to be transformed - * @param metadata Information about the specific pipeline calling the transformation entrypoint - * @returns A promise containing the transformed PipelineRecord array - */ - public run(records: I[], metadata: PipelineBatchMetadata): Promise; - } - export type PipelineRecord = Record; - export type PipelineBatchMetadata = { - pipelineId: string; - pipelineName: string; - }; - export interface Pipeline { - /** - * The Pipeline interface represents the type of a binding to a Pipeline - * - * @param records The records to send to the pipeline - */ - send(records: T[]): Promise; - } +declare module "cloudflare:pipelines" { + export abstract class PipelineTransformationEntrypoint { + protected env: Env; + protected ctx: ExecutionContext; + constructor(ctx: ExecutionContext, env: Env); + /** + * run receives an array of PipelineRecord which can be + * transformed and returned to the pipeline + * @param records Incoming records from the pipeline to be transformed + * @param metadata Information about the specific pipeline calling the transformation entrypoint + * @returns A promise containing the transformed PipelineRecord array + */ + public run(records: I[], metadata: PipelineBatchMetadata): Promise; + } + export type PipelineRecord = Record; + export type PipelineBatchMetadata = { + pipelineId: string; + pipelineName: string; + }; + export interface Pipeline { + /** + * The Pipeline interface represents the type of a binding to a Pipeline + * + * @param records The records to send to the pipeline + */ + send(records: T[]): Promise; + } } // PubSubMessage represents an incoming PubSub message. // The message includes metadata about the broker, the client, and the payload // itself. // https://developers.cloudflare.com/pub-sub/ interface PubSubMessage { - // Message ID - readonly mid: number; - // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT - readonly broker: string; - // The MQTT topic the message was sent on. - readonly topic: string; - // The client ID of the client that published this message. - readonly clientId: string; - // The unique identifier (JWT ID) used by the client to authenticate, if token - // auth was used. - readonly jti?: string; - // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker - // received the message from the client. - readonly receivedAt: number; - // An (optional) string with the MIME type of the payload, if set by the - // client. - readonly contentType: string; - // Set to 1 when the payload is a UTF-8 string - // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 - readonly payloadFormatIndicator: number; - // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. - // You can use payloadFormatIndicator to inspect this before decoding. - payload: string | Uint8Array; + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; } // JsonWebKey extended by kid parameter interface JsonWebKeyWithKid extends JsonWebKey { - // Key Identifier of the JWK - readonly kid: string; + // Key Identifier of the JWK + readonly kid: string; } interface RateLimitOptions { - key: string; + key: string; } interface RateLimitOutcome { - success: boolean; + success: boolean; } interface RateLimit { - /** - * Rate limit a request based on the provided options. - * @see https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/ - * @returns A promise that resolves with the outcome of the rate limit. - */ - limit(options: RateLimitOptions): Promise; + /** + * Rate limit a request based on the provided options. + * @see https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/ + * @returns A promise that resolves with the outcome of the rate limit. + */ + limit(options: RateLimitOptions): Promise; } // Namespace for RPC utility types. Unfortunately, we can't use a `module` here as these types need // to referenced by `Fetcher`. This is included in the "importable" version of the types which // strips all `module` blocks. declare namespace Rpc { - // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s. - // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`. - // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to - // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape) - export const __RPC_STUB_BRAND: '__RPC_STUB_BRAND'; - export const __RPC_TARGET_BRAND: '__RPC_TARGET_BRAND'; - export const __WORKER_ENTRYPOINT_BRAND: '__WORKER_ENTRYPOINT_BRAND'; - export const __DURABLE_OBJECT_BRAND: '__DURABLE_OBJECT_BRAND'; - export const __WORKFLOW_ENTRYPOINT_BRAND: '__WORKFLOW_ENTRYPOINT_BRAND'; - export interface RpcTargetBranded { - [__RPC_TARGET_BRAND]: never; - } - export interface WorkerEntrypointBranded { - [__WORKER_ENTRYPOINT_BRAND]: never; - } - export interface DurableObjectBranded { - [__DURABLE_OBJECT_BRAND]: never; - } - export interface WorkflowEntrypointBranded { - [__WORKFLOW_ENTRYPOINT_BRAND]: never; - } - export type EntrypointBranded = - | WorkerEntrypointBranded - | DurableObjectBranded - | WorkflowEntrypointBranded; - // Types that can be used through `Stub`s - export type Stubable = RpcTargetBranded | ((...args: any[]) => any); - // Types that can be passed over 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 = + // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s. + // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`. + // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to + // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape) + export const __RPC_STUB_BRAND: '__RPC_STUB_BRAND'; + export const __RPC_TARGET_BRAND: '__RPC_TARGET_BRAND'; + export const __WORKER_ENTRYPOINT_BRAND: '__WORKER_ENTRYPOINT_BRAND'; + export const __DURABLE_OBJECT_BRAND: '__DURABLE_OBJECT_BRAND'; + export const __WORKFLOW_ENTRYPOINT_BRAND: '__WORKFLOW_ENTRYPOINT_BRAND'; + export interface RpcTargetBranded { + [__RPC_TARGET_BRAND]: never; + } + export interface WorkerEntrypointBranded { + [__WORKER_ENTRYPOINT_BRAND]: never; + } + export interface DurableObjectBranded { + [__DURABLE_OBJECT_BRAND]: never; + } + export interface WorkflowEntrypointBranded { + [__WORKFLOW_ENTRYPOINT_BRAND]: never; + } + export type EntrypointBranded = WorkerEntrypointBranded | DurableObjectBranded | WorkflowEntrypointBranded; + // Types that can be used through `Stub`s + export type Stubable = RpcTargetBranded | ((...args: any[]) => any); + // Types that can be passed over 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 = // Structured cloneables - | BaseType + BaseType // Structured cloneable composites - | Map< - T extends Map ? Serializable : never, - T extends Map ? Serializable : never - > - | Set ? Serializable : never> - | ReadonlyArray ? Serializable : never> - | { + | Map ? Serializable : never, T extends Map ? Serializable : never> | Set ? Serializable : never> | ReadonlyArray ? Serializable : never> | { [K in keyof T]: K extends number | string ? Serializable : never; - } + } // Special types - | Stub + | Stub // Serialized as stubs, see `Stubify` - | Stubable; - // Base type for all RPC stubs, including common memory management methods. - // `T` is used as a marker type for unwrapping `Stub`s later. - interface StubBase extends Disposable { - [__RPC_STUB_BRAND]: T; - dup(): this; - } - export type Stub = Provider & StubBase; - // This represents all the types that can be sent as-is over an RPC boundary - type BaseType = - | void - | undefined - | null - | boolean - | number - | bigint - | string - | TypedArray - | ArrayBuffer - | DataView - | Date - | Error - | RegExp - | ReadableStream - | WritableStream - | Request - | Response - | Headers; - // Recursively rewrite all `Stubable` types with `Stub`s - // prettier-ignore - type Stubify = T extends Stubable ? Stub : T extends Map ? Map, Stubify> : T extends Set ? Set> : T extends Array ? Array> : T extends ReadonlyArray ? ReadonlyArray> : T extends BaseType ? T : T extends { + | Stubable; + // Base type for all RPC stubs, including common memory management methods. + // `T` is used as a marker type for unwrapping `Stub`s later. + interface StubBase extends Disposable { + [__RPC_STUB_BRAND]: T; + dup(): this; + } + export type Stub = Provider & StubBase; + // This represents all the types that can be sent as-is over an RPC boundary + type BaseType = void | undefined | null | boolean | number | bigint | string | TypedArray | ArrayBuffer | DataView | Date | Error | RegExp | ReadableStream | WritableStream | Request | Response | Headers; + // Recursively rewrite all `Stubable` types with `Stub`s + // prettier-ignore + type Stubify = T extends Stubable ? Stub : T extends Map ? Map, Stubify> : T extends Set ? Set> : T extends Array ? Array> : T extends ReadonlyArray ? ReadonlyArray> : T extends BaseType ? T : T extends { [key: string | number]: any; } ? { [K in keyof T]: Stubify; } : T; - // Recursively rewrite all `Stub`s with the corresponding `T`s. - // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies: - // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`. - // prettier-ignore - type Unstubify = T extends StubBase ? V : T extends Map ? Map, Unstubify> : T extends Set ? Set> : T extends Array ? Array> : T extends ReadonlyArray ? ReadonlyArray> : T extends BaseType ? T : T extends { + // Recursively rewrite all `Stub`s with the corresponding `T`s. + // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies: + // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`. + // prettier-ignore + type Unstubify = T extends StubBase ? V : T extends Map ? Map, Unstubify> : T extends Set ? Set> : T extends Array ? Array> : T extends ReadonlyArray ? ReadonlyArray> : T extends BaseType ? T : T extends { [key: string | number]: unknown; } ? { [K in keyof T]: Unstubify; } : T; - type UnstubifyAll = { - [I in keyof A]: Unstubify; - }; - // Utility type for adding `Provider`/`Disposable`s to `object` types only. - // Note `unknown & T` is equivalent to `T`. - type MaybeProvider = T extends object ? Provider : unknown; - type MaybeDisposable = T extends object ? Disposable : unknown; - // Type for method return or property on an RPC interface. - // - Stubable types are replaced by stubs. - // - Serializable types are passed by value, with stubable types replaced by stubs - // and a top-level `Disposer`. - // Everything else can't be passed over PRC. - // Technically, we use custom thenables here, but they quack like `Promise`s. - // Intersecting with `(Maybe)Provider` allows pipelining. - // prettier-ignore - type Result = R extends Stubable ? Promise> & Provider : R extends Serializable ? Promise & MaybeDisposable> & MaybeProvider : never; - // Type for method or property on an RPC interface. - // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s. - // Unwrapping `Stub`s allows calling with `Stubable` arguments. - // For properties, rewrite types to be `Result`s. - // In each case, unwrap `Promise`s. - type MethodOrProperty = V extends (...args: infer P) => infer R - ? (...args: UnstubifyAll

) => Result> - : Result>; - // Type for the callable part of an `Provider` if `T` is callable. - // This is intersected with methods/properties. - type MaybeCallableProvider = T extends (...args: any[]) => any ? MethodOrProperty : unknown; - // Base type for all other types providing RPC-like interfaces. - // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types. - // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC. - export type Provider< - T extends object, - Reserved extends string = never, - > = MaybeCallableProvider & - Pick< - { + type UnstubifyAll = { + [I in keyof A]: Unstubify; + }; + // Utility type for adding `Provider`/`Disposable`s to `object` types only. + // Note `unknown & T` is equivalent to `T`. + type MaybeProvider = T extends object ? Provider : unknown; + type MaybeDisposable = T extends object ? Disposable : unknown; + // Type for method return or property on an RPC interface. + // - Stubable types are replaced by stubs. + // - Serializable types are passed by value, with stubable types replaced by stubs + // and a top-level `Disposer`. + // Everything else can't be passed over PRC. + // Technically, we use custom thenables here, but they quack like `Promise`s. + // Intersecting with `(Maybe)Provider` allows pipelining. + // prettier-ignore + type Result = R extends Stubable ? Promise> & Provider : R extends Serializable ? Promise & MaybeDisposable> & MaybeProvider : never; + // Type for method or property on an RPC interface. + // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s. + // Unwrapping `Stub`s allows calling with `Stubable` arguments. + // For properties, rewrite types to be `Result`s. + // In each case, unwrap `Promise`s. + type MethodOrProperty = V extends (...args: infer P) => infer R ? (...args: UnstubifyAll

) => Result> : Result>; + // Type for the callable part of an `Provider` if `T` is callable. + // This is intersected with methods/properties. + type MaybeCallableProvider = T extends (...args: any[]) => any ? MethodOrProperty : unknown; + // Base type for all other types providing RPC-like interfaces. + // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types. + // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC. + export type Provider = MaybeCallableProvider & Pick<{ [K in keyof T]: MethodOrProperty; - }, - Exclude> - >; + }, Exclude>>; } declare namespace Cloudflare { - // Type of `env`. - // - // The specific project can extend `Env` by redeclaring it in project-specific files. Typescript - // will merge all declarations. - // - // You can use `wrangler types` to generate the `Env` type automatically. - interface Env {} - // Project-specific parameters used to inform types. - // - // This interface is, again, intended to be declared in project-specific files, and then that - // declaration will be merged with this one. - // - // A project should have a declaration like this: - // - // interface GlobalProps { - // // Declares the main module's exports. Used to populate Cloudflare.Exports aka the type - // // of `ctx.exports`. - // mainModule: typeof import("my-main-module"); - // - // // Declares which of the main module's exports are configured with durable storage, and - // // thus should behave as Durable Object namsepace bindings. - // durableNamespaces: "MyDurableObject" | "AnotherDurableObject"; - // } - // - // You can use `wrangler types` to generate `GlobalProps` automatically. - interface GlobalProps {} - // Evaluates to the type of a property in GlobalProps, defaulting to `Default` if it is not - // present. - type GlobalProp = K extends keyof GlobalProps - ? GlobalProps[K] - : Default; - // The type of the program's main module exports, if known. Requires `GlobalProps` to declare the - // `mainModule` property. - type MainModule = GlobalProp<'mainModule', {}>; - // The type of ctx.exports, which contains loopback bindings for all top-level exports. - type Exports = { - [K in keyof MainModule]: LoopbackForExport & - // If the export is listed in `durableNamespaces`, then it is also a - // DurableObjectNamespace. - (K extends GlobalProp<'durableNamespaces', never> - ? MainModule[K] extends new (...args: any[]) => infer DoInstance - ? DoInstance extends Rpc.DurableObjectBranded - ? DurableObjectNamespace - : DurableObjectNamespace - : DurableObjectNamespace - : {}); - }; + // Type of `env`. + // + // The specific project can extend `Env` by redeclaring it in project-specific files. Typescript + // will merge all declarations. + // + // You can use `wrangler types` to generate the `Env` type automatically. + interface Env { + } + // Project-specific parameters used to inform types. + // + // This interface is, again, intended to be declared in project-specific files, and then that + // declaration will be merged with this one. + // + // A project should have a declaration like this: + // + // interface GlobalProps { + // // Declares the main module's exports. Used to populate Cloudflare.Exports aka the type + // // of `ctx.exports`. + // mainModule: typeof import("my-main-module"); + // + // // Declares which of the main module's exports are configured with durable storage, and + // // thus should behave as Durable Object namsepace bindings. + // durableNamespaces: "MyDurableObject" | "AnotherDurableObject"; + // } + // + // You can use `wrangler types` to generate `GlobalProps` automatically. + interface GlobalProps { + } + // Evaluates to the type of a property in GlobalProps, defaulting to `Default` if it is not + // present. + type GlobalProp = K extends keyof GlobalProps ? GlobalProps[K] : Default; + // The type of the program's main module exports, if known. Requires `GlobalProps` to declare the + // `mainModule` property. + type MainModule = GlobalProp<"mainModule", {}>; + // The type of ctx.exports, which contains loopback bindings for all top-level exports. + type Exports = { + [K in keyof MainModule]: LoopbackForExport + // If the export is listed in `durableNamespaces`, then it is also a + // DurableObjectNamespace. + & (K extends GlobalProp<"durableNamespaces", never> ? MainModule[K] extends new (...args: any[]) => infer DoInstance ? DoInstance extends Rpc.DurableObjectBranded ? DurableObjectNamespace : DurableObjectNamespace : DurableObjectNamespace : {}); + }; } declare namespace CloudflareWorkersModule { - export type RpcStub = Rpc.Stub; - export const RpcStub: { - new (value: T): Rpc.Stub; - }; - export abstract class RpcTarget implements Rpc.RpcTargetBranded { - [Rpc.__RPC_TARGET_BRAND]: never; - } - // `protected` fields don't appear in `keyof`s, so can't be accessed over RPC - export abstract class WorkerEntrypoint - implements Rpc.WorkerEntrypointBranded - { - [Rpc.__WORKER_ENTRYPOINT_BRAND]: never; - protected ctx: ExecutionContext; - protected env: Env; - constructor(ctx: ExecutionContext, env: Env); - email?(message: ForwardableEmailMessage): void | Promise; - fetch?(request: Request): Response | Promise; - queue?(batch: MessageBatch): void | Promise; - scheduled?(controller: ScheduledController): void | Promise; - tail?(events: TraceItem[]): void | Promise; - tailStream?( - event: TailStream.TailEvent - ): TailStream.TailEventHandlerType | Promise; - test?(controller: TestController): void | Promise; - trace?(traces: TraceItem[]): void | Promise; - } - export abstract class DurableObject - implements Rpc.DurableObjectBranded - { - [Rpc.__DURABLE_OBJECT_BRAND]: never; - protected ctx: DurableObjectState; - protected env: Env; - constructor(ctx: DurableObjectState, env: Env); - alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise; - fetch?(request: Request): Response | Promise; - webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise; - webSocketClose?( - ws: WebSocket, - code: number, - reason: string, - wasClean: boolean - ): void | Promise; - webSocketError?(ws: WebSocket, error: unknown): void | Promise; - } - export type WorkflowDurationLabel = - | 'second' - | 'minute' - | 'hour' - | 'day' - | 'week' - | 'month' - | 'year'; - export type WorkflowSleepDuration = `${number} ${WorkflowDurationLabel}${'s' | ''}` | number; - export type WorkflowDelayDuration = WorkflowSleepDuration; - export type WorkflowTimeoutDuration = WorkflowSleepDuration; - export type WorkflowRetentionDuration = WorkflowSleepDuration; - export type WorkflowBackoff = 'constant' | 'linear' | 'exponential'; - export type WorkflowStepConfig = { - retries?: { - limit: number; - delay: WorkflowDelayDuration | number; - backoff?: WorkflowBackoff; + export type RpcStub = Rpc.Stub; + export const RpcStub: { + new (value: T): Rpc.Stub; }; - timeout?: WorkflowTimeoutDuration | number; - }; - export type WorkflowEvent = { - payload: Readonly; - timestamp: Date; - instanceId: string; - }; - export type WorkflowStepEvent = { - payload: Readonly; - timestamp: Date; - type: string; - }; - export abstract class WorkflowStep { - do>(name: string, callback: () => Promise): Promise; - do>( - name: string, - config: WorkflowStepConfig, - callback: () => Promise - ): Promise; - sleep: (name: string, duration: WorkflowSleepDuration) => Promise; - sleepUntil: (name: string, timestamp: Date | number) => Promise; - waitForEvent>( - name: string, - options: { - type: string; + export abstract class RpcTarget implements Rpc.RpcTargetBranded { + [Rpc.__RPC_TARGET_BRAND]: never; + } + // `protected` fields don't appear in `keyof`s, so can't be accessed over RPC + export abstract class WorkerEntrypoint implements Rpc.WorkerEntrypointBranded { + [Rpc.__WORKER_ENTRYPOINT_BRAND]: never; + protected ctx: ExecutionContext; + protected env: Env; + constructor(ctx: ExecutionContext, env: Env); + email?(message: ForwardableEmailMessage): void | Promise; + fetch?(request: Request): Response | Promise; + queue?(batch: MessageBatch): void | Promise; + scheduled?(controller: ScheduledController): void | Promise; + tail?(events: TraceItem[]): void | Promise; + tailStream?(event: TailStream.TailEvent): TailStream.TailEventHandlerType | Promise; + test?(controller: TestController): void | Promise; + trace?(traces: TraceItem[]): void | Promise; + } + export abstract class DurableObject implements Rpc.DurableObjectBranded { + [Rpc.__DURABLE_OBJECT_BRAND]: never; + protected ctx: DurableObjectState; + protected env: Env; + constructor(ctx: DurableObjectState, env: Env); + alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise; + fetch?(request: Request): Response | Promise; + webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise; + webSocketClose?(ws: WebSocket, code: number, reason: string, wasClean: boolean): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; + } + export type WorkflowDurationLabel = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; + export type WorkflowSleepDuration = `${number} ${WorkflowDurationLabel}${'s' | ''}` | number; + export type WorkflowDelayDuration = WorkflowSleepDuration; + export type WorkflowTimeoutDuration = WorkflowSleepDuration; + export type WorkflowRetentionDuration = WorkflowSleepDuration; + export type WorkflowBackoff = 'constant' | 'linear' | 'exponential'; + export type WorkflowStepConfig = { + retries?: { + limit: number; + delay: WorkflowDelayDuration | number; + backoff?: WorkflowBackoff; + }; timeout?: WorkflowTimeoutDuration | number; - } - ): Promise>; - } - export abstract class WorkflowEntrypoint< - Env = unknown, - T extends Rpc.Serializable | unknown = unknown, - > implements Rpc.WorkflowEntrypointBranded - { - [Rpc.__WORKFLOW_ENTRYPOINT_BRAND]: never; - protected ctx: ExecutionContext; - protected env: Env; - constructor(ctx: ExecutionContext, env: Env); - run(event: Readonly>, step: WorkflowStep): Promise; - } - export function waitUntil(promise: Promise): void; - export function withEnv(newEnv: unknown, fn: () => unknown): unknown; - export function withExports(newExports: unknown, fn: () => unknown): unknown; - export function withEnvAndExports( - newEnv: unknown, - newExports: unknown, - fn: () => unknown - ): unknown; - export const env: Cloudflare.Env; - export const exports: Cloudflare.Exports; + }; + export type WorkflowEvent = { + payload: Readonly; + timestamp: Date; + instanceId: string; + }; + export type WorkflowStepEvent = { + payload: Readonly; + timestamp: Date; + type: string; + }; + export abstract class WorkflowStep { + do>(name: string, callback: () => Promise): Promise; + do>(name: string, config: WorkflowStepConfig, callback: () => Promise): Promise; + sleep: (name: string, duration: WorkflowSleepDuration) => Promise; + sleepUntil: (name: string, timestamp: Date | number) => Promise; + waitForEvent>(name: string, options: { + type: string; + timeout?: WorkflowTimeoutDuration | number; + }): Promise>; + } + export type WorkflowInstanceStatus = 'queued' | 'running' | 'paused' | 'errored' | 'terminated' | 'complete' | 'waiting' | 'waitingForPause' | 'unknown'; + export abstract class WorkflowEntrypoint | unknown = unknown> implements Rpc.WorkflowEntrypointBranded { + [Rpc.__WORKFLOW_ENTRYPOINT_BRAND]: never; + protected ctx: ExecutionContext; + protected env: Env; + constructor(ctx: ExecutionContext, env: Env); + run(event: Readonly>, step: WorkflowStep): Promise; + } + export function waitUntil(promise: Promise): void; + export function withEnv(newEnv: unknown, fn: () => unknown): unknown; + export function withExports(newExports: unknown, fn: () => unknown): unknown; + export function withEnvAndExports(newEnv: unknown, newExports: unknown, fn: () => unknown): unknown; + export const env: Cloudflare.Env; + export const exports: Cloudflare.Exports; } declare module 'cloudflare:workers' { - export = CloudflareWorkersModule; + export = CloudflareWorkersModule; } interface SecretsStoreSecret { - /** - * Get a secret from the Secrets Store, returning a string of the secret value - * if it exists, or throws an error if it does not exist - */ - get(): Promise; + /** + * Get a secret from the Secrets Store, returning a string of the secret value + * if it exists, or throws an error if it does not exist + */ + get(): Promise; } -declare module 'cloudflare:sockets' { - function _connect(address: string | SocketAddress, options?: SocketOptions): Socket; - export { _connect as connect }; +declare module "cloudflare:sockets" { + function _connect(address: string | SocketAddress, options?: SocketOptions): Socket; + export { _connect as connect }; } type MarkdownDocument = { - name: string; - blob: Blob; -}; -type ConversionResponse = - | { - name: string; - mimeType: string; - format: 'markdown'; - tokens: number; - data: string; - } - | { - name: string; - mimeType: string; - format: 'error'; - error: string; - }; + name: string; + blob: Blob; +}; +type ConversionResponse = { + id: string; + name: string; + mimeType: string; + format: 'markdown'; + tokens: number; + data: string; +} | { + id: string; + name: string; + mimeType: string; + format: 'error'; + error: string; +}; type ImageConversionOptions = { - descriptionLanguage?: 'en' | 'es' | 'fr' | 'it' | 'pt' | 'de'; + descriptionLanguage?: 'en' | 'es' | 'fr' | 'it' | 'pt' | 'de'; }; type EmbeddedImageConversionOptions = ImageConversionOptions & { - convert?: boolean; - maxConvertedImages?: number; + convert?: boolean; + maxConvertedImages?: number; }; type ConversionOptions = { - html?: { - images?: EmbeddedImageConversionOptions & { - convertOGImage?: boolean; + html?: { + images?: EmbeddedImageConversionOptions & { + convertOGImage?: boolean; + }; + hostname?: string; + }; + docx?: { + images?: EmbeddedImageConversionOptions; + }; + image?: ImageConversionOptions; + pdf?: { + images?: EmbeddedImageConversionOptions; + metadata?: boolean; }; - }; - docx?: { - images?: EmbeddedImageConversionOptions; - }; - image?: ImageConversionOptions; - pdf?: { - images?: EmbeddedImageConversionOptions; - metadata?: boolean; - }; }; type ConversionRequestOptions = { - gateway?: GatewayOptions; - extraHeaders?: object; - conversionOptions?: ConversionOptions; + gateway?: GatewayOptions; + extraHeaders?: object; + conversionOptions?: ConversionOptions; }; type SupportedFileFormat = { - mimeType: string; - extension: string; + mimeType: string; + extension: string; }; declare abstract class ToMarkdownService { - transform( - files: MarkdownDocument[], - options?: ConversionRequestOptions - ): Promise; - transform( - files: MarkdownDocument, - options?: ConversionRequestOptions - ): Promise; - supported(): Promise; + transform(files: MarkdownDocument[], options?: ConversionRequestOptions): Promise; + transform(files: MarkdownDocument, options?: ConversionRequestOptions): Promise; + supported(): Promise; } declare namespace TailStream { - interface Header { - readonly name: string; - readonly value: string; - } - interface FetchEventInfo { - readonly type: 'fetch'; - readonly method: string; - readonly url: string; - readonly cfJson?: object; - readonly headers: Header[]; - } - interface JsRpcEventInfo { - readonly type: 'jsrpc'; - } - interface ScheduledEventInfo { - readonly type: 'scheduled'; - readonly scheduledTime: Date; - readonly cron: string; - } - interface AlarmEventInfo { - readonly type: 'alarm'; - readonly scheduledTime: Date; - } - interface QueueEventInfo { - readonly type: 'queue'; - readonly queueName: string; - readonly batchSize: number; - } - interface EmailEventInfo { - readonly type: 'email'; - readonly mailFrom: string; - readonly rcptTo: string; - readonly rawSize: number; - } - interface TraceEventInfo { - readonly type: 'trace'; - readonly traces: (string | null)[]; - } - interface HibernatableWebSocketEventInfoMessage { - readonly type: 'message'; - } - interface HibernatableWebSocketEventInfoError { - readonly type: 'error'; - } - interface HibernatableWebSocketEventInfoClose { - readonly type: 'close'; - readonly code: number; - readonly wasClean: boolean; - } - interface HibernatableWebSocketEventInfo { - readonly type: 'hibernatableWebSocket'; - readonly info: - | HibernatableWebSocketEventInfoClose - | HibernatableWebSocketEventInfoError - | HibernatableWebSocketEventInfoMessage; - } - interface CustomEventInfo { - readonly type: 'custom'; - } - interface FetchResponseInfo { - readonly type: 'fetch'; - readonly statusCode: number; - } - type EventOutcome = - | 'ok' - | 'canceled' - | 'exception' - | 'unknown' - | 'killSwitch' - | 'daemonDown' - | 'exceededCpu' - | 'exceededMemory' - | 'loadShed' - | 'responseStreamDisconnected' - | 'scriptNotFound'; - interface ScriptVersion { - readonly id: string; - readonly tag?: string; - readonly message?: string; - } - interface Onset { - readonly type: 'onset'; - readonly attributes: Attribute[]; - // id for the span being opened by this Onset event. - readonly spanId: string; - readonly dispatchNamespace?: string; - readonly entrypoint?: string; - readonly executionModel: string; - readonly scriptName?: string; - readonly scriptTags?: string[]; - readonly scriptVersion?: ScriptVersion; - readonly info: - | FetchEventInfo - | JsRpcEventInfo - | ScheduledEventInfo - | AlarmEventInfo - | QueueEventInfo - | EmailEventInfo - | TraceEventInfo - | HibernatableWebSocketEventInfo - | CustomEventInfo; - } - interface Outcome { - readonly type: 'outcome'; - readonly outcome: EventOutcome; - readonly cpuTime: number; - readonly wallTime: number; - } - interface SpanOpen { - readonly type: 'spanOpen'; - readonly name: string; - // id for the span being opened by this SpanOpen event. - readonly spanId: string; - readonly info?: FetchEventInfo | JsRpcEventInfo | Attributes; - } - interface SpanClose { - readonly type: 'spanClose'; - readonly outcome: EventOutcome; - } - interface DiagnosticChannelEvent { - readonly type: 'diagnosticChannel'; - readonly channel: string; - readonly message: any; - } - interface Exception { - readonly type: 'exception'; - readonly name: string; - readonly message: string; - readonly stack?: string; - } - interface Log { - readonly type: 'log'; - readonly level: 'debug' | 'error' | 'info' | 'log' | 'warn'; - readonly message: object; - } - // This marks the worker handler return information. - // This is separate from Outcome because the worker invocation can live for a long time after - // returning. For example - Websockets that return an http upgrade response but then continue - // streaming information or SSE http connections. - interface Return { - readonly type: 'return'; - readonly info?: FetchResponseInfo; - } - interface Attribute { - readonly name: string; - readonly value: string | string[] | boolean | boolean[] | number | number[] | bigint | bigint[]; - } - interface Attributes { - readonly type: 'attributes'; - readonly info: Attribute[]; - } - type EventType = - | Onset - | Outcome - | SpanOpen - | SpanClose - | DiagnosticChannelEvent - | Exception - | Log - | Return - | Attributes; - // Context in which this trace event lives. - interface SpanContext { - // Single id for the entire top-level invocation - // This should be a new traceId for the first worker stage invoked in the eyeball request and then - // same-account service-bindings should reuse the same traceId but cross-account service-bindings - // should use a new traceId. - readonly traceId: string; - // spanId in which this event is handled - // for Onset and SpanOpen events this would be the parent span id - // for Outcome and SpanClose these this would be the span id of the opening Onset and SpanOpen events - // For Hibernate and Mark this would be the span under which they were emitted. - // spanId is not set ONLY if: - // 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; - } - interface TailEvent { - // invocation id of the currently invoked worker stage. - // invocation id will always be unique to every Onset event and will be the same until the Outcome event. - readonly invocationId: string; - // Inherited spanContext for this event. - readonly spanContext: SpanContext; - readonly timestamp: Date; - readonly sequence: number; - readonly event: Event; - } - type TailEventHandler = ( - event: TailEvent - ) => void | Promise; - type TailEventHandlerObject = { - outcome?: TailEventHandler; - spanOpen?: TailEventHandler; - spanClose?: TailEventHandler; - diagnosticChannel?: TailEventHandler; - exception?: TailEventHandler; - log?: TailEventHandler; - return?: TailEventHandler; - attributes?: TailEventHandler; - }; - type TailEventHandlerType = TailEventHandler | TailEventHandlerObject; + interface Header { + readonly name: string; + readonly value: string; + } + interface FetchEventInfo { + readonly type: "fetch"; + readonly method: string; + readonly url: string; + readonly cfJson?: object; + readonly headers: Header[]; + } + interface JsRpcEventInfo { + readonly type: "jsrpc"; + } + interface ScheduledEventInfo { + readonly type: "scheduled"; + readonly scheduledTime: Date; + readonly cron: string; + } + interface AlarmEventInfo { + readonly type: "alarm"; + readonly scheduledTime: Date; + } + interface QueueEventInfo { + readonly type: "queue"; + readonly queueName: string; + readonly batchSize: number; + } + interface EmailEventInfo { + readonly type: "email"; + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; + } + interface TraceEventInfo { + readonly type: "trace"; + readonly traces: (string | null)[]; + } + interface HibernatableWebSocketEventInfoMessage { + readonly type: "message"; + } + interface HibernatableWebSocketEventInfoError { + readonly type: "error"; + } + interface HibernatableWebSocketEventInfoClose { + readonly type: "close"; + readonly code: number; + readonly wasClean: boolean; + } + interface HibernatableWebSocketEventInfo { + readonly type: "hibernatableWebSocket"; + readonly info: HibernatableWebSocketEventInfoClose | HibernatableWebSocketEventInfoError | HibernatableWebSocketEventInfoMessage; + } + interface CustomEventInfo { + readonly type: "custom"; + } + interface FetchResponseInfo { + readonly type: "fetch"; + readonly statusCode: number; + } + type EventOutcome = "ok" | "canceled" | "exception" | "unknown" | "killSwitch" | "daemonDown" | "exceededCpu" | "exceededMemory" | "loadShed" | "responseStreamDisconnected" | "scriptNotFound"; + interface ScriptVersion { + readonly id: string; + readonly tag?: string; + readonly message?: string; + } + interface Onset { + readonly type: "onset"; + readonly attributes: Attribute[]; + // id for the span being opened by this Onset event. + readonly spanId: string; + readonly dispatchNamespace?: string; + readonly entrypoint?: string; + readonly executionModel: string; + readonly scriptName?: string; + readonly scriptTags?: string[]; + readonly scriptVersion?: ScriptVersion; + readonly info: FetchEventInfo | JsRpcEventInfo | ScheduledEventInfo | AlarmEventInfo | QueueEventInfo | EmailEventInfo | TraceEventInfo | HibernatableWebSocketEventInfo | CustomEventInfo; + } + interface Outcome { + readonly type: "outcome"; + readonly outcome: EventOutcome; + readonly cpuTime: number; + readonly wallTime: number; + } + interface SpanOpen { + readonly type: "spanOpen"; + readonly name: string; + // id for the span being opened by this SpanOpen event. + readonly spanId: string; + readonly info?: FetchEventInfo | JsRpcEventInfo | Attributes; + } + interface SpanClose { + readonly type: "spanClose"; + readonly outcome: EventOutcome; + } + interface DiagnosticChannelEvent { + readonly type: "diagnosticChannel"; + readonly channel: string; + readonly message: any; + } + interface Exception { + readonly type: "exception"; + readonly name: string; + readonly message: string; + readonly stack?: string; + } + interface Log { + readonly type: "log"; + readonly level: "debug" | "error" | "info" | "log" | "warn"; + readonly message: object; + } + interface DroppedEventsDiagnostic { + readonly diagnosticsType: "droppedEvents"; + readonly count: number; + } + interface StreamDiagnostic { + readonly type: 'streamDiagnostic'; + // To add new diagnostic types, define a new interface and add it to this union type. + readonly diagnostic: DroppedEventsDiagnostic; + } + // This marks the worker handler return information. + // This is separate from Outcome because the worker invocation can live for a long time after + // returning. For example - Websockets that return an http upgrade response but then continue + // streaming information or SSE http connections. + interface Return { + readonly type: "return"; + readonly info?: FetchResponseInfo; + } + interface Attribute { + readonly name: string; + readonly value: string | string[] | boolean | boolean[] | number | number[] | bigint | bigint[]; + } + interface Attributes { + readonly type: "attributes"; + readonly info: Attribute[]; + } + type EventType = Onset | Outcome | SpanOpen | SpanClose | DiagnosticChannelEvent | Exception | Log | StreamDiagnostic | Return | Attributes; + // Context in which this trace event lives. + interface SpanContext { + // Single id for the entire top-level invocation + // This should be a new traceId for the first worker stage invoked in the eyeball request and then + // same-account service-bindings should reuse the same traceId but cross-account service-bindings + // should use a new traceId. + readonly traceId: string; + // spanId in which this event is handled + // for Onset and SpanOpen events this would be the parent span id + // for Outcome and SpanClose these this would be the span id of the opening Onset and SpanOpen events + // For Hibernate and Mark this would be the span under which they were emitted. + // spanId is not set ONLY if: + // 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; + } + interface TailEvent { + // invocation id of the currently invoked worker stage. + // invocation id will always be unique to every Onset event and will be the same until the Outcome event. + readonly invocationId: string; + // Inherited spanContext for this event. + readonly spanContext: SpanContext; + readonly timestamp: Date; + readonly sequence: number; + readonly event: Event; + } + type TailEventHandler = (event: TailEvent) => void | Promise; + type TailEventHandlerObject = { + outcome?: TailEventHandler; + spanOpen?: TailEventHandler; + spanClose?: TailEventHandler; + diagnosticChannel?: TailEventHandler; + exception?: TailEventHandler; + log?: TailEventHandler; + return?: TailEventHandler; + attributes?: TailEventHandler; + }; + type TailEventHandlerType = TailEventHandler | TailEventHandlerObject; } // Copyright (c) 2022-2023 Cloudflare, Inc. // Licensed under the Apache 2.0 license found in the LICENSE file or at: @@ -11654,13 +10873,11 @@ type VectorizeVectorMetadataValue = string | number | boolean | string[]; /** * Additional information to associate with a vector. */ -type VectorizeVectorMetadata = - | VectorizeVectorMetadataValue - | Record; +type VectorizeVectorMetadata = VectorizeVectorMetadataValue | Record; type VectorFloatArray = Float32Array | Float64Array; interface VectorizeError { - code?: number; - error: string; + code?: number; + error: string; } /** * Comparison logic/operation to use for metadata filtering. @@ -11673,27 +10890,17 @@ type VectorizeVectorMetadataFilterCollectionOp = '$in' | '$nin'; * Filter criteria for vector metadata used to limit the retrieved query result set. */ type VectorizeVectorMetadataFilter = { - [field: string]: - | Exclude - | null - | { - [Op in VectorizeVectorMetadataFilterOp]?: Exclude< - VectorizeVectorMetadataValue, - string[] - > | null; - } - | { - [Op in VectorizeVectorMetadataFilterCollectionOp]?: Exclude< - VectorizeVectorMetadataValue, - string[] - >[]; - }; + [field: string]: Exclude | null | { + [Op in VectorizeVectorMetadataFilterOp]?: Exclude | null; + } | { + [Op in VectorizeVectorMetadataFilterCollectionOp]?: Exclude[]; + }; }; /** * Supported distance metrics for an index. * Distance metrics determine how other "similar" vectors are determined. */ -type VectorizeDistanceMetric = 'euclidean' | 'cosine' | 'dot-product'; +type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; /** * Metadata return levels for a Vectorize query. * @@ -11703,25 +10910,23 @@ type VectorizeDistanceMetric = 'euclidean' | 'cosine' | 'dot-product'; * @property indexed Return all metadata fields configured for indexing in the vector return set. This level of retrieval is "free" in that no additional overhead is incurred returning this data. However, note that indexed metadata is subject to truncation (especially for larger strings). * @property none No indexed metadata will be returned. */ -type VectorizeMetadataRetrievalLevel = 'all' | 'indexed' | 'none'; +type VectorizeMetadataRetrievalLevel = "all" | "indexed" | "none"; interface VectorizeQueryOptions { - topK?: number; - namespace?: string; - returnValues?: boolean; - returnMetadata?: boolean | VectorizeMetadataRetrievalLevel; - filter?: VectorizeVectorMetadataFilter; + topK?: number; + namespace?: string; + returnValues?: boolean; + returnMetadata?: boolean | VectorizeMetadataRetrievalLevel; + filter?: VectorizeVectorMetadataFilter; } /** * Information about the configuration of an index. */ -type VectorizeIndexConfig = - | { - dimensions: number; - metric: VectorizeDistanceMetric; - } - | { - preset: string; // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity - }; +type VectorizeIndexConfig = { + dimensions: number; + metric: VectorizeDistanceMetric; +} | { + preset: string; // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity +}; /** * Metadata about an existing index. * @@ -11729,57 +10934,56 @@ type VectorizeIndexConfig = * See {@link VectorizeIndexInfo} for its post-beta equivalent. */ interface VectorizeIndexDetails { - /** The unique ID of the index */ - readonly id: string; - /** The name of the index. */ - name: string; - /** (optional) A human readable description for the index. */ - description?: string; - /** The index configuration, including the dimension size and distance metric. */ - config: VectorizeIndexConfig; - /** The number of records containing vectors within the index. */ - vectorsCount: number; + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; } /** * Metadata about an existing index. */ interface VectorizeIndexInfo { - /** The number of records containing vectors within the index. */ - vectorCount: number; - /** Number of dimensions the index has been configured for. */ - dimensions: number; - /** ISO 8601 datetime of the last processed mutation on in the index. All changes before this mutation will be reflected in the index state. */ - processedUpToDatetime: number; - /** UUIDv4 of the last mutation processed by the index. All changes before this mutation will be reflected in the index state. */ - processedUpToMutation: number; + /** The number of records containing vectors within the index. */ + vectorCount: number; + /** Number of dimensions the index has been configured for. */ + dimensions: number; + /** ISO 8601 datetime of the last processed mutation on in the index. All changes before this mutation will be reflected in the index state. */ + processedUpToDatetime: number; + /** UUIDv4 of the last mutation processed by the index. All changes before this mutation will be reflected in the index state. */ + processedUpToMutation: number; } /** * Represents a single vector value set along with its associated metadata. */ interface VectorizeVector { - /** The ID for the vector. This can be user-defined, and must be unique. It should uniquely identify the object, and is best set based on the ID of what the vector represents. */ - id: string; - /** The vector values */ - values: VectorFloatArray | number[]; - /** The namespace this vector belongs to. */ - namespace?: string; - /** Metadata associated with the vector. Includes the values of other fields and potentially additional details. */ - metadata?: Record; + /** The ID for the vector. This can be user-defined, and must be unique. It should uniquely identify the object, and is best set based on the ID of what the vector represents. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the vector. Includes the values of other fields and potentially additional details. */ + metadata?: Record; } /** * Represents a matched vector for a query along with its score and (if specified) the matching vector information. */ -type VectorizeMatch = Pick, 'values'> & - Omit & { +type VectorizeMatch = Pick, "values"> & Omit & { /** The score or rank for similarity, when returned as a result */ score: number; - }; +}; /** * A set of matching {@link VectorizeMatch} for a particular query. */ interface VectorizeMatches { - matches: VectorizeMatch[]; - count: number; + matches: VectorizeMatch[]; + count: number; } /** * Results of an operation that performed a mutation on a set of vectors. @@ -11789,18 +10993,18 @@ interface VectorizeMatches { * See {@link VectorizeAsyncMutation} for its post-beta equivalent. */ interface VectorizeVectorMutation { - /* List of ids of vectors that were successfully processed. */ - ids: string[]; - /* Total count of the number of processed vectors. */ - count: number; + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; } /** * Result type indicating a mutation on the Vectorize Index. * Actual mutations are processed async where the `mutationId` is the unique identifier for the operation. */ interface VectorizeAsyncMutation { - /** The unique identifier for the async mutation operation containing the changeset. */ - mutationId: string; + /** The unique identifier for the async mutation operation containing the changeset. */ + mutationId: string; } /** * A Vectorize Vector Search Index for querying vectors/embeddings. @@ -11809,45 +11013,42 @@ interface VectorizeAsyncMutation { * See {@link Vectorize} for its new implementation. */ declare abstract class VectorizeIndex { - /** - * Get information about the currently bound index. - * @returns A promise that resolves with information about the current index. - */ - public describe(): Promise; - /** - * Use the provided vector to perform a similarity search across the index. - * @param vector Input vector that will be used to drive the similarity search. - * @param options Configuration options to massage the returned data. - * @returns A promise that resolves with matched and scored vectors. - */ - public query( - vector: VectorFloatArray | number[], - options?: VectorizeQueryOptions - ): Promise; - /** - * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. - * @param vectors List of vectors that will be inserted. - * @returns A promise that resolves with the ids & count of records that were successfully processed. - */ - public insert(vectors: VectorizeVector[]): Promise; - /** - * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. - * @param vectors List of vectors that will be upserted. - * @returns A promise that resolves with the ids & count of records that were successfully processed. - */ - public upsert(vectors: VectorizeVector[]): Promise; - /** - * Delete a list of vectors with a matching id. - * @param ids List of vector ids that should be deleted. - * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). - */ - public deleteByIds(ids: string[]): Promise; - /** - * Get a list of vectors with a matching id. - * @param ids List of vector ids that should be returned. - * @returns A promise that resolves with the raw unscored vectors matching the id set. - */ - public getByIds(ids: string[]): Promise; + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query(vector: VectorFloatArray | number[], options?: VectorizeQueryOptions): Promise; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise; } /** * A Vectorize Vector Search Index for querying vectors/embeddings. @@ -11855,199 +11056,190 @@ declare abstract class VectorizeIndex { * Mutations in this version are async, returning a mutation id. */ declare abstract class Vectorize { - /** - * Get information about the currently bound index. - * @returns A promise that resolves with information about the current index. - */ - public describe(): Promise; - /** - * Use the provided vector to perform a similarity search across the index. - * @param vector Input vector that will be used to drive the similarity search. - * @param options Configuration options to massage the returned data. - * @returns A promise that resolves with matched and scored vectors. - */ - public query( - vector: VectorFloatArray | number[], - options?: VectorizeQueryOptions - ): Promise; - /** - * Use the provided vector-id to perform a similarity search across the index. - * @param vectorId Id for a vector in the index against which the index should be queried. - * @param options Configuration options to massage the returned data. - * @returns A promise that resolves with matched and scored vectors. - */ - public queryById(vectorId: string, options?: VectorizeQueryOptions): Promise; - /** - * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. - * @param vectors List of vectors that will be inserted. - * @returns A promise that resolves with a unique identifier of a mutation containing the insert changeset. - */ - public insert(vectors: VectorizeVector[]): Promise; - /** - * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. - * @param vectors List of vectors that will be upserted. - * @returns A promise that resolves with a unique identifier of a mutation containing the upsert changeset. - */ - public upsert(vectors: VectorizeVector[]): Promise; - /** - * Delete a list of vectors with a matching id. - * @param ids List of vector ids that should be deleted. - * @returns A promise that resolves with a unique identifier of a mutation containing the delete changeset. - */ - public deleteByIds(ids: string[]): Promise; - /** - * Get a list of vectors with a matching id. - * @param ids List of vector ids that should be returned. - * @returns A promise that resolves with the raw unscored vectors matching the id set. - */ - public getByIds(ids: string[]): Promise; + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query(vector: VectorFloatArray | number[], options?: VectorizeQueryOptions): Promise; + /** + * Use the provided vector-id to perform a similarity search across the index. + * @param vectorId Id for a vector in the index against which the index should be queried. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public queryById(vectorId: string, options?: VectorizeQueryOptions): Promise; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with a unique identifier of a mutation containing the insert changeset. + */ + public insert(vectors: VectorizeVector[]): Promise; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with a unique identifier of a mutation containing the upsert changeset. + */ + public upsert(vectors: VectorizeVector[]): Promise; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with a unique identifier of a mutation containing the delete changeset. + */ + public deleteByIds(ids: string[]): Promise; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise; } /** * The interface for "version_metadata" binding * providing metadata about the Worker Version using this binding. */ type WorkerVersionMetadata = { - /** The ID of the Worker Version using this binding */ - id: string; - /** The tag of the Worker Version using this binding */ - tag: string; - /** The timestamp of when the Worker Version was uploaded */ - timestamp: string; + /** The ID of the Worker Version using this binding */ + id: string; + /** The tag of the Worker Version using this binding */ + tag: string; + /** The timestamp of when the Worker Version was uploaded */ + timestamp: string; }; interface DynamicDispatchLimits { - /** - * Limit CPU time in milliseconds. - */ - cpuMs?: number; - /** - * Limit number of subrequests. - */ - subRequests?: number; + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; } interface DynamicDispatchOptions { - /** - * Limit resources of invoked Worker script. - */ - limits?: DynamicDispatchLimits; - /** - * Arguments for outbound Worker script, if configured. - */ - outbound?: { - [key: string]: any; - }; + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; } interface DispatchNamespace { - /** - * @param name Name of the Worker script. - * @param args Arguments to Worker script. - * @param options Options for Dynamic Dispatch invocation. - * @returns A Fetcher object that allows you to send requests to the Worker script. - * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. - */ - get( - name: string, - args?: { - [key: string]: any; - }, - options?: DynamicDispatchOptions - ): Fetcher; + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get(name: string, args?: { + [key: string]: any; + }, options?: DynamicDispatchOptions): Fetcher; } declare module 'cloudflare:workflows' { - /** - * NonRetryableError allows for a user to throw a fatal error - * that makes a Workflow instance fail immediately without triggering a retry - */ - export class NonRetryableError extends Error { - public constructor(message: string, name?: string); - } + /** + * NonRetryableError allows for a user to throw a fatal error + * that makes a Workflow instance fail immediately without triggering a retry + */ + export class NonRetryableError extends Error { + public constructor(message: string, name?: string); + } } declare abstract class Workflow { - /** - * Get a handle to an existing instance of the Workflow. - * @param id Id for the instance of this Workflow - * @returns A promise that resolves with a handle for the Instance - */ - public get(id: string): Promise; - /** - * Create a new instance and return a handle to it. If a provided id exists, an error will be thrown. - * @param options Options when creating an instance including id and params - * @returns A promise that resolves with a handle for the Instance - */ - public create(options?: WorkflowInstanceCreateOptions): Promise; - /** - * Create a batch of instances and return handle for all of them. If a provided id exists, an error will be thrown. - * `createBatch` is limited at 100 instances at a time or when the RPC limit for the batch (1MiB) is reached. - * @param batch List of Options when creating an instance including name and params - * @returns A promise that resolves with a list of handles for the created instances. - */ - public createBatch(batch: WorkflowInstanceCreateOptions[]): Promise; + /** + * Get a handle to an existing instance of the Workflow. + * @param id Id for the instance of this Workflow + * @returns A promise that resolves with a handle for the Instance + */ + public get(id: string): Promise; + /** + * Create a new instance and return a handle to it. If a provided id exists, an error will be thrown. + * @param options Options when creating an instance including id and params + * @returns A promise that resolves with a handle for the Instance + */ + public create(options?: WorkflowInstanceCreateOptions): Promise; + /** + * Create a batch of instances and return handle for all of them. If a provided id exists, an error will be thrown. + * `createBatch` is limited at 100 instances at a time or when the RPC limit for the batch (1MiB) is reached. + * @param batch List of Options when creating an instance including name and params + * @returns A promise that resolves with a list of handles for the created instances. + */ + public createBatch(batch: WorkflowInstanceCreateOptions[]): Promise; } type WorkflowDurationLabel = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; type WorkflowSleepDuration = `${number} ${WorkflowDurationLabel}${'s' | ''}` | number; type WorkflowRetentionDuration = WorkflowSleepDuration; interface WorkflowInstanceCreateOptions { - /** - * An id for your Workflow instance. Must be unique within the Workflow. - */ - id?: string; - /** - * The event payload the Workflow instance is triggered with - */ - params?: PARAMS; - /** - * The retention policy for Workflow instance. - * Defaults to the maximum retention period available for the owner's account. - */ - retention?: { - successRetention?: WorkflowRetentionDuration; - errorRetention?: WorkflowRetentionDuration; - }; + /** + * An id for your Workflow instance. Must be unique within the Workflow. + */ + id?: string; + /** + * The event payload the Workflow instance is triggered with + */ + params?: PARAMS; + /** + * The retention policy for Workflow instance. + * Defaults to the maximum retention period available for the owner's account. + */ + retention?: { + successRetention?: WorkflowRetentionDuration; + errorRetention?: WorkflowRetentionDuration; + }; } type InstanceStatus = { - status: - | 'queued' // means that instance is waiting to be started (see concurrency limits) - | 'running' - | 'paused' - | 'errored' - | 'terminated' // user terminated the instance while it was running - | 'complete' - | 'waiting' // instance is hibernating and waiting for sleep or event to finish - | 'waitingForPause' // instance is finishing the current work to pause - | 'unknown'; - error?: { - name: string; - message: string; - }; - output?: unknown; + status: 'queued' // means that instance is waiting to be started (see concurrency limits) + | 'running' | 'paused' | 'errored' | 'terminated' // user terminated the instance while it was running + | 'complete' | 'waiting' // instance is hibernating and waiting for sleep or event to finish + | 'waitingForPause' // instance is finishing the current work to pause + | 'unknown'; + error?: { + name: string; + message: string; + }; + output?: unknown; }; interface WorkflowError { - code?: number; - message: string; + code?: number; + message: string; } declare abstract class WorkflowInstance { - public id: string; - /** - * Pause the instance. - */ - public pause(): Promise; - /** - * Resume the instance. If it is already running, an error will be thrown. - */ - public resume(): Promise; - /** - * Terminate the instance. If it is errored, terminated or complete, an error will be thrown. - */ - public terminate(): Promise; - /** - * Restart the instance. - */ - public restart(): Promise; - /** - * Returns the current status of the instance. - */ - public status(): Promise; - /** - * Send an event to this instance. - */ - public sendEvent({ type, payload }: { type: string; payload: unknown }): Promise; + public id: string; + /** + * Pause the instance. + */ + public pause(): Promise; + /** + * Resume the instance. If it is already running, an error will be thrown. + */ + public resume(): Promise; + /** + * Terminate the instance. If it is errored, terminated or complete, an error will be thrown. + */ + public terminate(): Promise; + /** + * Restart the instance. + */ + public restart(): Promise; + /** + * Returns the current status of the instance. + */ + public status(): Promise; + /** + * Send an event to this instance. + */ + public sendEvent({ type, payload, }: { + type: string; + payload: unknown; + }): Promise; } diff --git a/cloudflare-gastown/wrangler.jsonc b/cloudflare-gastown/wrangler.jsonc index b9e534cf73..6eb7251a2b 100644 --- a/cloudflare-gastown/wrangler.jsonc +++ b/cloudflare-gastown/wrangler.jsonc @@ -49,7 +49,7 @@ "vars": { "ENVIRONMENT": "production", "CF_ACCESS_TEAM": "engineering-e11", - "CF_ACCESS_AUD": "f30e3fd893df52fa3ffc50fbdb5ee6a4f111625ae92234233429684e1429d809", + "CF_ACCESS_AUD": "7f6eda4c0714f6ea2afb74a3f055db65659b67571a913eab42468636a9b8c8be", "KILO_API_URL": "https://api.kilo.ai", "GASTOWN_API_URL": "https://gastown.kiloapps.io", }, @@ -68,9 +68,13 @@ "vars": { "ENVIRONMENT": "development", "CF_ACCESS_TEAM": "engineering-e11", - "CF_ACCESS_AUD": "f30e3fd893df52fa3ffc50fbdb5ee6a4f111625ae92234233429684e1429d809", - "KILO_API_URL": "http://host.docker.internal:3000", - "GASTOWN_API_URL": "http://host.docker.internal:8787", + "CF_ACCESS_AUD": "7f6eda4c0714f6ea2afb74a3f055db65659b67571a913eab42468636a9b8c8be", + // Wrangler's workerd-network doesn't get Docker Desktop's + // host.docker.internal → host proxy mapping. Use the Docker + // Desktop VM host gateway IP directly so containers can reach + // the host's dev servers. + "KILO_API_URL": "http://192.168.65.254:3000", + "GASTOWN_API_URL": "http://192.168.65.254:8787", }, "containers": [ { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d640065b6c..14f59890da 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1057,11 +1057,11 @@ importers: cloudflare-gastown/container: dependencies: '@kilocode/plugin': - specifier: 1.0.23 - version: 1.0.23 + specifier: 7.0.37 + version: 7.0.37 '@kilocode/sdk': - specifier: 1.0.23 - version: 1.0.23 + specifier: 7.0.37 + version: 7.0.37 hono: specifier: 'catalog:' version: 4.12.2 @@ -3456,11 +3456,11 @@ packages: '@jridgewell/trace-mapping@0.3.9': resolution: {integrity: sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==} - '@kilocode/plugin@1.0.23': - resolution: {integrity: sha512-iP273WjkN1veQF0ygpVEVGZviIl/bynxH7RXwmkyODKtlgHbs3QzxeUoLbd5r4ZDYDIcA5+4NITCTjcE3YlPEQ==} + '@kilocode/plugin@7.0.37': + resolution: {integrity: sha512-bDeLo2FLqFdQZmjezfiJ+Oyk5rb3Tzh9+nKAVp+2kHOhKDkwgOD71OFN+Ii0t3RvyChkLYnghw179FqHByNILQ==} - '@kilocode/sdk@1.0.23': - resolution: {integrity: sha512-4z7xdfHyoRm+iUwQtu0k+BMy1ovNhA3yCy+94Hwz0jH5329ZVmaTjoPq4QleWihMthzsxaJCVFx7bonphsr1PA==} + '@kilocode/sdk@7.0.37': + resolution: {integrity: sha512-t7HEjYpAuW3IdbEp+2VYQPFLhidYFSmWK3nl6vWri0QBNh+spQcotdMYENNmv/HQOAXr84pXgOFtc8YCEOz5wQ==} '@lottiefiles/dotlottie-react@0.17.7': resolution: {integrity: sha512-A6wO3zqkDx/t0ULfctcr1Bmb1f1hc4zUV3NcbKQOsBGAOIx1vABV/fRabFYElvbJl9lmOR24yMh//Z0fvvJV+Q==} @@ -14332,12 +14332,12 @@ snapshots: '@jridgewell/resolve-uri': 3.1.2 '@jridgewell/sourcemap-codec': 1.5.5 - '@kilocode/plugin@1.0.23': + '@kilocode/plugin@7.0.37': dependencies: - '@kilocode/sdk': 1.0.23 + '@kilocode/sdk': 7.0.37 zod: 4.1.8 - '@kilocode/sdk@1.0.23': {} + '@kilocode/sdk@7.0.37': {} '@lottiefiles/dotlottie-react@0.17.7(react@19.2.0)': dependencies: diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 30ef93c5f4..fdb22c24fe 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -74,6 +74,8 @@ minimumReleaseAgeExclude: - brace-expansion@5.0.2 # Security overrides for transitive dependencies - serialize-javascript@7.0.3 + - '@kilocode/plugin' + - '@kilocode/sdk' onlyBuiltDependencies: - '@swc/core' diff --git a/src/app/(app)/gastown/[townId]/TownOverviewPageClient.tsx b/src/app/(app)/gastown/[townId]/TownOverviewPageClient.tsx index d4dafb5217..fe271dd2db 100644 --- a/src/app/(app)/gastown/[townId]/TownOverviewPageClient.tsx +++ b/src/app/(app)/gastown/[townId]/TownOverviewPageClient.tsx @@ -290,7 +290,7 @@ export function TownOverviewPageClient({ townId }: TownOverviewPageClientProps) openDrawer({ type: 'event', event })} /> diff --git a/src/app/(app)/gastown/[townId]/settings/TownSettingsPageClient.tsx b/src/app/(app)/gastown/[townId]/settings/TownSettingsPageClient.tsx index 1117ca16fa..a32fc5a5b7 100644 --- a/src/app/(app)/gastown/[townId]/settings/TownSettingsPageClient.tsx +++ b/src/app/(app)/gastown/[townId]/settings/TownSettingsPageClient.tsx @@ -17,6 +17,7 @@ import { Save, Settings, GitBranch, + GitPullRequest, Bot, Shield, Variable, @@ -32,6 +33,7 @@ const SECTIONS = [ { id: 'git-auth', label: 'Git Authentication', icon: GitBranch }, { id: 'env-vars', label: 'Environment Variables', icon: Variable }, { id: 'agent-defaults', label: 'Agent Defaults', icon: Bot }, + { id: 'merge-strategy', label: 'Merge Strategy', icon: GitPullRequest }, { id: 'refinery', label: 'Refinery', icon: Shield }, ] as const; @@ -98,6 +100,7 @@ export function TownSettingsPageClient({ townId }: Props) { const [maxPolecats, setMaxPolecats] = useState(undefined); const [refineryGates, setRefineryGates] = useState([]); const [autoMerge, setAutoMerge] = useState(true); + const [mergeStrategy, setMergeStrategy] = useState<'direct' | 'pr'>('direct'); const [initialized, setInitialized] = useState(false); const [showTokens, setShowTokens] = useState(false); @@ -112,6 +115,7 @@ export function TownSettingsPageClient({ townId }: Props) { setMaxPolecats(cfg.max_polecats_per_rig); setRefineryGates(cfg.refinery?.gates ?? []); setAutoMerge(cfg.refinery?.auto_merge ?? true); + setMergeStrategy(cfg.merge_strategy === 'pr' ? 'pr' : 'direct'); setInitialized(true); } @@ -136,6 +140,7 @@ export function TownSettingsPageClient({ townId }: Props) { }, ...(defaultModel ? { default_model: defaultModel } : {}), ...(maxPolecats ? { max_polecats_per_rig: maxPolecats } : {}), + merge_strategy: mergeStrategy, refinery: { gates: refineryGates.filter(g => g.trim()), auto_merge: autoMerge, @@ -355,13 +360,37 @@ export function TownSettingsPageClient({ townId }: Props) { + {/* ── Merge Strategy ──────────────────────────────────── */} + +

+ + {/* ── Refinery (Quality Gates) ─────────────────────────── */} ); } + +function MergeStrategyOption({ + selected, + onSelect, + label, + description, +}: { + selected: boolean; + onSelect: () => void; + label: string; + description: string; +}) { + return ( + + ); +} diff --git a/src/components/gastown/ActivityFeed.tsx b/src/components/gastown/ActivityFeed.tsx index 04c79b89c1..1a13ce3463 100644 --- a/src/components/gastown/ActivityFeed.tsx +++ b/src/components/gastown/ActivityFeed.tsx @@ -148,7 +148,7 @@ export function ActivityFeedView({ ); } - // Newest first — events from the API come oldest-first, so reverse. + // Ensure newest-first ordering (API returns DESC but defensive sort). const sorted = [...effectiveEvents].sort( (a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime() ); @@ -216,6 +216,18 @@ export function ActivityFeedView({ export type { TownEvent }; +/** + * Extract a safe PR URL from bead metadata. + * Only allows https:// URLs to prevent XSS via javascript: protocol injection. + */ +export function extractPrUrl(metadata: unknown): string | null { + if (metadata && typeof metadata === 'object' && 'pr_url' in metadata) { + const url = metadata.pr_url; + if (typeof url === 'string' && url.startsWith('https://')) return url; + } + return null; +} + export function ActivityFeed({ townId }: { townId: string }) { return ; } diff --git a/src/components/gastown/BeadDetailDrawer.tsx b/src/components/gastown/BeadDetailDrawer.tsx index f16b2503e6..9db74546ef 100644 --- a/src/components/gastown/BeadDetailDrawer.tsx +++ b/src/components/gastown/BeadDetailDrawer.tsx @@ -3,11 +3,22 @@ import { Drawer } from 'vaul'; import { Badge } from '@/components/ui/badge'; import { Button } from '@/components/Button'; -import { BeadEventTimeline } from '@/components/gastown/ActivityFeed'; +import { BeadEventTimeline, extractPrUrl } from '@/components/gastown/ActivityFeed'; import type { inferRouterOutputs } from '@trpc/server'; import type { RootRouter } from '@/routers/root-router'; import { format } from 'date-fns'; -import { Clock, Flag, Hash, Tags, User, X, Hexagon, FileText, GitBranch } from 'lucide-react'; +import { + Clock, + Flag, + Hash, + Tags, + User, + X, + Hexagon, + FileText, + GitBranch, + ExternalLink, +} from 'lucide-react'; import ReactMarkdown from 'react-markdown'; import remarkGfm from 'remark-gfm'; @@ -49,6 +60,10 @@ export function BeadDetailDrawer({ ? agentNameById?.[bead.assignee_agent_bead_id] : null; + // Extract PR URL from metadata (set by the 'pr' merge strategy on merge_request beads). + // Only allow https:// URLs to prevent XSS via javascript: protocol injection. + const prUrl = extractPrUrl(bead?.metadata); + return ( @@ -150,6 +165,21 @@ export function BeadDetailDrawer({ )} + {/* PR link for merge_request beads */} + {bead.type === 'merge_request' && prUrl && ( + + )} + {/* Body */} {bead.body && bead.body.trim().length > 0 && (
diff --git a/src/components/gastown/CreateTownDialog.tsx b/src/components/gastown/CreateTownDialog.tsx index a247ab5c2d..1c6e189ae1 100644 --- a/src/components/gastown/CreateTownDialog.tsx +++ b/src/components/gastown/CreateTownDialog.tsx @@ -1,6 +1,7 @@ 'use client'; import { useState } from 'react'; +import { useRouter } from 'next/navigation'; import { useMutation, useQueryClient } from '@tanstack/react-query'; import { useTRPC } from '@/lib/trpc/utils'; import { @@ -21,16 +22,18 @@ type CreateTownDialogProps = { export function CreateTownDialog({ isOpen, onClose }: CreateTownDialogProps) { const [name, setName] = useState(''); + const router = useRouter(); const trpc = useTRPC(); const queryClient = useQueryClient(); const createTown = useMutation( trpc.gastown.createTown.mutationOptions({ - onSuccess: () => { + onSuccess: data => { void queryClient.invalidateQueries({ queryKey: trpc.gastown.listTowns.queryKey() }); toast.success('Town created'); setName(''); onClose(); + router.push(`/gastown/${data.id}`); }, onError: err => { toast.error(err.message); diff --git a/src/components/gastown/drawer-panels/BeadPanel.tsx b/src/components/gastown/drawer-panels/BeadPanel.tsx index 664cfe4088..be25307917 100644 --- a/src/components/gastown/drawer-panels/BeadPanel.tsx +++ b/src/components/gastown/drawer-panels/BeadPanel.tsx @@ -3,12 +3,13 @@ import { useQuery } from '@tanstack/react-query'; import { useTRPC } from '@/lib/trpc/utils'; import { Badge } from '@/components/ui/badge'; -import { BeadEventTimeline } from '@/components/gastown/ActivityFeed'; +import { BeadEventTimeline, extractPrUrl } from '@/components/gastown/ActivityFeed'; import type { ResourceRef } from '@/components/gastown/DrawerStack'; import { format } from 'date-fns'; import { Clock, + ExternalLink, Flag, Hash, Tags, @@ -70,6 +71,10 @@ export function BeadPanel({ const townId = rigQuery.data?.town_id; + // Extract PR URL from bead metadata (set by setReviewPrUrl for merge_request beads). + // Only allow https:// URLs to prevent XSS via javascript: protocol injection. + const prUrl = extractPrUrl(bead.metadata); + // Build related beads from the flat list (no extra API needed) const allBeads = beadsQuery.data ?? []; const relatedBeads = buildRelatedBeads(bead, allBeads); @@ -164,6 +169,21 @@ export function BeadPanel({ )}
+ {/* PR link for merge_request beads */} + {bead.type === 'merge_request' && prUrl && ( + + )} + {/* Related Beads DAG */} {relatedBeads.length > 0 && (
diff --git a/src/lib/gastown/gastown-client.ts b/src/lib/gastown/gastown-client.ts index 889b4fb28f..ed00e8854e 100644 --- a/src/lib/gastown/gastown-client.ts +++ b/src/lib/gastown/gastown-client.ts @@ -428,6 +428,7 @@ export const TownConfigSchema = z.object({ owner_user_id: z.string().optional(), default_model: z.string().optional(), max_polecats_per_rig: z.number().optional(), + merge_strategy: z.enum(['direct', 'pr']).default('direct'), refinery: z .object({ gates: z.array(z.string()), diff --git a/src/lib/providers/index.ts b/src/lib/providers/index.ts index b187503bae..0ef28e415f 100644 --- a/src/lib/providers/index.ts +++ b/src/lib/providers/index.ts @@ -190,6 +190,10 @@ function applyToolChoiceSetting( function getPreferredProviderOrder(requestedModel: string): OpenRouterInferenceProviderId[] { if (isAnthropicModel(requestedModel)) { + // Use `order` (set below in applyPreferredProvider) to preferentially + // route Anthropic models to Bedrock and Anthropic. Google Vertex doesn't + // support assistant message prefill, which causes 400 errors on tool + // calls when OpenRouter falls back to it. return [ OpenRouterInferenceProviderIdSchema.enum['amazon-bedrock'], OpenRouterInferenceProviderIdSchema.enum.anthropic, From 855c50b5e72606012103db5bdd3dcabac0544d5c Mon Sep 17 00:00:00 2001 From: John Fawcett Date: Wed, 4 Mar 2026 19:11:18 -0600 Subject: [PATCH 2/5] feat(gastown): replace CF Access with direct JWT validation (#717) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add kiloAuthMiddleware: validates Kilo user JWTs (NEXTAUTH_SECRET) via verifyKiloToken from @kilocode/worker-utils - Apply kiloAuthMiddleware to user-facing routes (/api/users/*, /api/towns/*/config, /api/towns/*/container/*, /api/towns/*/convoys/*, /api/towns/*/escalations/*, /api/towns/*/mayor/*) - Remove global CF Access middleware from all routes - Replace CF Access validation in WebSocket upgrade handler with Kilo JWT validation - Update gastown-client.ts to send Bearer token (via generateInternalServiceToken) instead of CF-Access-Client-Id/Secret headers - Add NEXTAUTH_SECRET binding to wrangler.jsonc secrets store - Add NEXTAUTH_SECRET to Env type in worker-configuration.d.ts - Keep existing agent JWT auth (GASTOWN_SESSION_TOKEN) for container→worker routes - Health and dashboard endpoints remain unauthenticated --- cloudflare-gastown/src/gastown.worker.ts | 64 +++++++++++-------- .../src/middleware/auth.middleware.ts | 1 + .../src/middleware/kilo-auth.middleware.ts | 35 ++++++++++ cloudflare-gastown/worker-configuration.d.ts | 2 + cloudflare-gastown/wrangler.jsonc | 5 ++ src/lib/gastown/gastown-client.ts | 17 ++--- 6 files changed, 90 insertions(+), 34 deletions(-) create mode 100644 cloudflare-gastown/src/middleware/kilo-auth.middleware.ts diff --git a/cloudflare-gastown/src/gastown.worker.ts b/cloudflare-gastown/src/gastown.worker.ts index 4e7b669663..86d5224420 100644 --- a/cloudflare-gastown/src/gastown.worker.ts +++ b/cloudflare-gastown/src/gastown.worker.ts @@ -3,13 +3,13 @@ import type { Context } from 'hono'; import { getTownContainerStub } from './dos/TownContainer.do'; import { resError } from './util/res.util'; import { dashboardHtml } from './ui/dashboard.ui'; -import { withCloudflareAccess, validateCfAccessRequest } from './middleware/cf-access.middleware'; import { authMiddleware, agentOnlyMiddleware, townIdMiddleware, type AuthVariables, } from './middleware/auth.middleware'; +import { kiloAuthMiddleware } from './middleware/kilo-auth.middleware'; import { handleCreateBead, handleListBeads, @@ -116,18 +116,6 @@ app.use('*', async (c, next) => { console.log(`${WORKER_LOG} <-- ${method} ${path} ${c.res.status} (${elapsed}ms)`); }); -// ── Cloudflare Access ─────────────────────────────────────────────────── -// Validate Cloudflare Access JWT for all requests; skip in development. - -app.use('*', async (c: Context, next) => - c.env.ENVIRONMENT === 'development' - ? next() - : withCloudflareAccess({ - team: c.env.CF_ACCESS_TEAM, - audience: c.env.CF_ACCESS_AUD, - })(c, next) -); - // ── Dashboard UI ──────────────────────────────────────────────────────── app.get('/', c => c.html(dashboardHtml())); @@ -247,6 +235,30 @@ app.post('/api/towns/:townId/rigs/:rigId/escalations', c => handleCreateEscalation(c, c.req.param()) ); +// ── Kilo User Auth ────────────────────────────────────────────────────── +// Validate Kilo user JWT (signed with NEXTAUTH_SECRET) for dashboard/user +// routes. Skip in development. Container→worker routes use the agent JWT +// middleware instead (authMiddleware above). + +app.use('/api/users/*', async (c: Context, next) => + c.env.ENVIRONMENT === 'development' ? next() : kiloAuthMiddleware(c, next) +); +app.use('/api/towns/:townId/convoys/*', async (c: Context, next) => + c.env.ENVIRONMENT === 'development' ? next() : kiloAuthMiddleware(c, next) +); +app.use('/api/towns/:townId/escalations/*', async (c: Context, next) => + c.env.ENVIRONMENT === 'development' ? next() : kiloAuthMiddleware(c, next) +); +app.use('/api/towns/:townId/config', async (c: Context, next) => + c.env.ENVIRONMENT === 'development' ? next() : kiloAuthMiddleware(c, next) +); +app.use('/api/towns/:townId/container/*', async (c: Context, next) => + c.env.ENVIRONMENT === 'development' ? next() : kiloAuthMiddleware(c, next) +); +app.use('/api/towns/:townId/mayor/*', async (c: Context, next) => + c.env.ENVIRONMENT === 'development' ? next() : kiloAuthMiddleware(c, next) +); + // ── Towns & Rigs ──────────────────────────────────────────────────────── // Town DO instances are keyed by owner_user_id. The userId path param routes // to the correct DO instance so each user's towns are isolated. @@ -377,20 +389,20 @@ export default { // Must bypass Hono — the DO returns a 101 + WebSocketPair that the // runtime handles directly. if (request.headers.get('Upgrade')?.toLowerCase() === 'websocket') { - // Validate CF Access JWT before forwarding — WebSocket upgrades + // Validate Kilo user JWT before forwarding — WebSocket upgrades // bypass Hono middleware so we must check auth inline. - if (env.ENVIRONMENT !== 'development') { - try { - await validateCfAccessRequest(request, { - team: env.CF_ACCESS_TEAM, - audience: env.CF_ACCESS_AUD, - }); - } catch (e) { - console.warn( - `[gastown-worker] WS CF Access auth failed: ${e instanceof Error ? e.message : 'unknown'}` - ); - return new Response('Unauthorized', { status: 401 }); - } + try { + const { verifyKiloToken, extractBearerToken } = await import('@kilocode/worker-utils'); + const { resolveSecret } = await import('./util/secret.util'); + const token = extractBearerToken(request.headers.get('Authorization')); + if (!token) throw new Error('Missing Authorization header'); + const secret = await resolveSecret(env.NEXTAUTH_SECRET); + await verifyKiloToken(token, secret); + } catch (e) { + console.warn( + `[gastown-worker] WS auth failed: ${e instanceof Error ? e.message : 'unknown'}` + ); + return new Response('Unauthorized', { status: 401 }); } const url = new URL(request.url); diff --git a/cloudflare-gastown/src/middleware/auth.middleware.ts b/cloudflare-gastown/src/middleware/auth.middleware.ts index 9508ba6388..78cc8b7573 100644 --- a/cloudflare-gastown/src/middleware/auth.middleware.ts +++ b/cloudflare-gastown/src/middleware/auth.middleware.ts @@ -8,6 +8,7 @@ import type { GastownEnv } from '../gastown.worker'; export type AuthVariables = { agentJWT: AgentJWTPayload; townId: string; + kiloUserId: string; }; import { resolveSecret } from '../util/secret.util'; diff --git a/cloudflare-gastown/src/middleware/kilo-auth.middleware.ts b/cloudflare-gastown/src/middleware/kilo-auth.middleware.ts new file mode 100644 index 0000000000..22c6b381b3 --- /dev/null +++ b/cloudflare-gastown/src/middleware/kilo-auth.middleware.ts @@ -0,0 +1,35 @@ +import { createMiddleware } from 'hono/factory'; +import { verifyKiloToken, extractBearerToken } from '@kilocode/worker-utils'; +import { resError } from '../util/res.util'; +import type { GastownEnv } from '../gastown.worker'; +import { resolveSecret } from '../util/secret.util'; + +/** + * Auth middleware that validates Kilo user JWTs (signed with NEXTAUTH_SECRET). + * Used for dashboard/user-facing routes where the Next.js app sends a + * Bearer token on behalf of the logged-in user. + * + * Sets `kiloUserId` on the Hono context. + */ +export const kiloAuthMiddleware = createMiddleware(async (c, next) => { + const token = extractBearerToken(c.req.header('Authorization')); + if (!token) { + return c.json(resError('Authentication required'), 401); + } + + const secret = await resolveSecret(c.env.NEXTAUTH_SECRET); + if (!secret) { + console.error('[kilo-auth] NEXTAUTH_SECRET not configured'); + return c.json(resError('Internal server error'), 500); + } + + try { + const payload = await verifyKiloToken(token, secret); + c.set('kiloUserId', payload.kiloUserId); + } catch (err) { + const message = err instanceof Error ? err.message : 'Invalid token'; + return c.json(resError(message), 401); + } + + return next(); +}); diff --git a/cloudflare-gastown/worker-configuration.d.ts b/cloudflare-gastown/worker-configuration.d.ts index e5d0b69246..78b3bf5de5 100644 --- a/cloudflare-gastown/worker-configuration.d.ts +++ b/cloudflare-gastown/worker-configuration.d.ts @@ -8,6 +8,7 @@ declare namespace Cloudflare { } interface DevEnv { GASTOWN_JWT_SECRET: SecretsStoreSecret; + NEXTAUTH_SECRET: SecretsStoreSecret; ENVIRONMENT: "development"; CF_ACCESS_TEAM: "engineering-e11"; CF_ACCESS_AUD: "7f6eda4c0714f6ea2afb74a3f055db65659b67571a913eab42468636a9b8c8be"; @@ -21,6 +22,7 @@ declare namespace Cloudflare { } interface Env { GASTOWN_JWT_SECRET: SecretsStoreSecret; + NEXTAUTH_SECRET: SecretsStoreSecret; ENVIRONMENT: "development" | "production"; CF_ACCESS_TEAM: "engineering-e11"; CF_ACCESS_AUD: "7f6eda4c0714f6ea2afb74a3f055db65659b67571a913eab42468636a9b8c8be"; diff --git a/cloudflare-gastown/wrangler.jsonc b/cloudflare-gastown/wrangler.jsonc index 6eb7251a2b..3a07d7eadc 100644 --- a/cloudflare-gastown/wrangler.jsonc +++ b/cloudflare-gastown/wrangler.jsonc @@ -61,6 +61,11 @@ "store_id": "342a86d9e3a94da698e82d0c6e2a36f0", "secret_name": "GASTOWN_JWT_SECRET_PROD", }, + { + "binding": "NEXTAUTH_SECRET", + "store_id": "342a86d9e3a94da698e82d0c6e2a36f0", + "secret_name": "NEXTAUTH_SECRET", + }, ], "env": { diff --git a/src/lib/gastown/gastown-client.ts b/src/lib/gastown/gastown-client.ts index ed00e8854e..41d18f5db7 100644 --- a/src/lib/gastown/gastown-client.ts +++ b/src/lib/gastown/gastown-client.ts @@ -1,9 +1,6 @@ import 'server-only'; -import { - GASTOWN_SERVICE_URL, - GASTOWN_CF_ACCESS_CLIENT_ID, - GASTOWN_CF_ACCESS_CLIENT_SECRET, -} from '@/lib/config.server'; +import { GASTOWN_SERVICE_URL } from '@/lib/config.server'; +import { generateInternalServiceToken } from '@/lib/tokens'; import { z } from 'zod'; // ── Response schemas ────────────────────────────────────────────────────── @@ -118,9 +115,13 @@ function getHeaders(): Record { 'Content-Type': 'application/json', }; - if (GASTOWN_CF_ACCESS_CLIENT_ID && GASTOWN_CF_ACCESS_CLIENT_SECRET) { - headers['CF-Access-Client-Id'] = GASTOWN_CF_ACCESS_CLIENT_ID; - headers['CF-Access-Client-Secret'] = GASTOWN_CF_ACCESS_CLIENT_SECRET; + // Authenticate to the Gastown worker with a short-lived internal service + // token signed with NEXTAUTH_SECRET. This replaces the old CF Access + // service token approach. Uses a fixed service identity since the actual + // user ID is passed in the URL path for user-scoped operations. + const token = generateInternalServiceToken('gastown-service'); + if (token) { + headers['Authorization'] = `Bearer ${token}`; } return headers; From f783c165db85f846a0eb415d775060dc9ca2ac34 Mon Sep 17 00:00:00 2001 From: John Fawcett Date: Wed, 4 Mar 2026 21:18:43 -0600 Subject: [PATCH 3/5] feat(gastown): browser talks directly to worker, removing Next.js tRPC proxy The gastown frontend now calls the Cloudflare Worker's tRPC endpoint directly instead of proxying through the Next.js backend. This removes a network hop and lets the worker handle auth end-to-end. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Key changes: - Add /api/gastown/token endpoint that mints short-lived JWTs with isAdmin and apiTokenPepper claims for browser→worker auth - Create standalone gastown tRPC client (src/lib/gastown/trpc.ts) with token management, GastownTRPCProvider, and gastownWsUrl helper - Add .output() schemas to all worker tRPC procedures for type-safe generated declarations - Add GIT_TOKEN_SERVICE binding to worker for git credential refresh (replaces server-side refreshTownGitCredentials) - Add configureRig/addRig calls to worker's createRig procedure - Add setTownId calls to ensure TownDO uses correct UUID for containers - Add CORS for /trpc/* routes and always-on kiloAuthMiddleware - Worker requireAdmin now checks JWT claims instead of DB lookup - WebSocket URLs returned as relative paths (frontend constructs full URL) - Update ~25 frontend files: useTRPC → useGastownTRPC - Remove gastown-router.ts, gastown-client.ts, and root-router registration --- cloudflare-gastown/.gitignore | 1 + cloudflare-gastown/package.json | 7 + cloudflare-gastown/src/gastown.worker.ts | 69 +- .../src/middleware/auth.middleware.ts | 2 + .../src/middleware/kilo-auth.middleware.ts | 9 +- cloudflare-gastown/src/trpc/init.ts | 25 + cloudflare-gastown/src/trpc/router.ts | 576 +++++++++++ cloudflare-gastown/src/trpc/schemas.ts | 152 +++ .../src/util/kilo-token.util.ts | 28 + cloudflare-gastown/src/util/user-db.util.ts | 24 + cloudflare-gastown/tsconfig.types.json | 11 + cloudflare-gastown/worker-configuration.d.ts | 24 +- cloudflare-gastown/wrangler.jsonc | 29 + packages/worker-utils/src/kilo-token.ts | 1 + pnpm-lock.yaml | 25 +- src/app/(app)/gastown/TownListPageClient.tsx | 4 +- .../[townId]/TownOverviewPageClient.tsx | 10 +- .../[townId]/agents/AgentsPageClient.tsx | 10 +- .../[townId]/beads/BeadsPageClient.tsx | 10 +- .../gastown/[townId]/mail/MailPageClient.tsx | 4 +- .../[townId]/merges/MergesPageClient.tsx | 4 +- .../observability/ObservabilityPageClient.tsx | 4 +- .../rigs/[rigId]/RigDetailPageClient.tsx | 4 +- .../settings/TownSettingsPageClient.tsx | 4 +- src/app/api/gastown/token/route.ts | 30 + src/components/Providers.tsx | 12 +- src/components/gastown/ActivityFeed.tsx | 14 +- src/components/gastown/AgentDetailDrawer.tsx | 12 +- src/components/gastown/AgentStream.tsx | 6 +- src/components/gastown/BeadDetailDrawer.tsx | 6 +- src/components/gastown/ConvoyTimeline.tsx | 6 +- src/components/gastown/CreateRigDialog.tsx | 10 +- src/components/gastown/CreateTownDialog.tsx | 4 +- .../gastown/GastownBeadDetailSheet.tsx | 6 +- src/components/gastown/GastownTownSidebar.tsx | 4 +- src/components/gastown/MayorChat.tsx | 4 +- src/components/gastown/SlingDialog.tsx | 4 +- src/components/gastown/SystemTopology.tsx | 10 +- src/components/gastown/TerminalBar.tsx | 10 +- .../gastown/drawer-panels/AgentPanel.tsx | 4 +- .../gastown/drawer-panels/BeadPanel.tsx | 4 +- src/components/gastown/useXtermPty.ts | 6 +- src/lib/constants.ts | 4 + src/lib/gastown/gastown-client.ts | 572 ----------- src/lib/gastown/trpc.ts | 97 ++ src/lib/gastown/types/README.md | 23 + src/lib/gastown/types/init.d.ts | 8 + src/lib/gastown/types/router.d.ts | 906 ++++++++++++++++++ src/lib/gastown/types/schemas.d.ts | 642 +++++++++++++ src/lib/tokens.ts | 1 + src/routers/gastown-router.ts | 583 ----------- src/routers/root-router.ts | 3 - 52 files changed, 2749 insertions(+), 1279 deletions(-) create mode 100644 cloudflare-gastown/src/trpc/init.ts create mode 100644 cloudflare-gastown/src/trpc/router.ts create mode 100644 cloudflare-gastown/src/trpc/schemas.ts create mode 100644 cloudflare-gastown/src/util/kilo-token.util.ts create mode 100644 cloudflare-gastown/src/util/user-db.util.ts create mode 100644 cloudflare-gastown/tsconfig.types.json create mode 100644 src/app/api/gastown/token/route.ts delete mode 100644 src/lib/gastown/gastown-client.ts create mode 100644 src/lib/gastown/trpc.ts create mode 100644 src/lib/gastown/types/README.md create mode 100644 src/lib/gastown/types/init.d.ts create mode 100644 src/lib/gastown/types/router.d.ts create mode 100644 src/lib/gastown/types/schemas.d.ts delete mode 100644 src/routers/gastown-router.ts diff --git a/cloudflare-gastown/.gitignore b/cloudflare-gastown/.gitignore index a1a55a7638..92b5408c55 100644 --- a/cloudflare-gastown/.gitignore +++ b/cloudflare-gastown/.gitignore @@ -1,2 +1,3 @@ .dev.vars container/dist/ +dist-types/ diff --git a/cloudflare-gastown/package.json b/cloudflare-gastown/package.json index f0726a3a4b..8b1beae624 100644 --- a/cloudflare-gastown/package.json +++ b/cloudflare-gastown/package.json @@ -17,11 +17,18 @@ "test:integration": "vitest run --config vitest.workers.config.ts", "test:integration:watch": "vitest --config vitest.workers.config.ts", "typecheck": "tsgo --noEmit --incremental false", + "build:types": "tsgo -p tsconfig.types.json || true", "lint": "eslint --config eslint.config.mjs --cache 'src/**/*.ts'" }, "dependencies": { "@cloudflare/containers": "^0.1.0", + "@hono/trpc-server": "^0.4.2", + "@kilocode/db": "workspace:*", + "drizzle-orm": "catalog:", + "jose": "catalog:", + "pg": "^8.16.3", "@kilocode/worker-utils": "workspace:*", + "@trpc/server": "^11.0.0", "hono": "catalog:", "itty-time": "^1.0.6", "jsonwebtoken": "catalog:", diff --git a/cloudflare-gastown/src/gastown.worker.ts b/cloudflare-gastown/src/gastown.worker.ts index 86d5224420..3f7425ec83 100644 --- a/cloudflare-gastown/src/gastown.worker.ts +++ b/cloudflare-gastown/src/gastown.worker.ts @@ -1,5 +1,6 @@ import { Hono } from 'hono'; import type { Context } from 'hono'; +import { cors } from 'hono/cors'; import { getTownContainerStub } from './dos/TownContainer.do'; import { resError } from './util/res.util'; import { dashboardHtml } from './ui/dashboard.ui'; @@ -10,6 +11,8 @@ import { type AuthVariables, } from './middleware/auth.middleware'; import { kiloAuthMiddleware } from './middleware/kilo-auth.middleware'; +import { trpcServer } from '@hono/trpc-server'; +import { wrappedGastownRouter } from './trpc/router'; import { handleCreateBead, handleListBeads, @@ -116,6 +119,30 @@ app.use('*', async (c, next) => { console.log(`${WORKER_LOG} <-- ${method} ${path} ${c.res.status} (${elapsed}ms)`); }); +// ── CORS ──────────────────────────────────────────────────────────────── +// Allow browser requests from the main Kilo app. In development, allow +// localhost origins for the Next.js dev server. + +const corsMiddleware = cors({ + origin: (origin, c: Context) => { + if (c.env.ENVIRONMENT === 'development') { + // Allow any localhost origin in dev + if (origin.startsWith('http://localhost:')) return origin; + } + // Production origins + const allowed = ['https://app.kilo.ai', 'https://kilo.ai']; + return allowed.includes(origin) ? origin : ''; + }, + allowHeaders: ['Content-Type', 'Authorization'], + allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], + exposeHeaders: ['Content-Length'], + maxAge: 3600, + credentials: true, +}); + +app.use('/api/*', corsMiddleware); +app.use('/trpc/*', corsMiddleware); + // ── Dashboard UI ──────────────────────────────────────────────────────── app.get('/', c => c.html(dashboardHtml())); @@ -365,6 +392,28 @@ app.get('/api/mayor/:townId/tools/rigs/:rigId/agents', c => ); app.post('/api/mayor/:townId/tools/mail', c => handleMayorSendMail(c, c.req.param())); +// ── tRPC ──────────────────────────────────────────────────────────────── +// Serve the gastown tRPC router directly. The frontend tRPC client +// connects here instead of going through the Next.js proxy layer. + +app.use('/trpc/*', kiloAuthMiddleware); +app.use( + '/trpc/*', + trpcServer({ + router: wrappedGastownRouter, + endpoint: '/trpc', + createContext: (_opts: unknown, c: Context) => ({ + env: c.env, + userId: c.get('kiloUserId') ?? '', + isAdmin: c.get('kiloIsAdmin') ?? false, + apiTokenPepper: c.get('kiloApiTokenPepper') ?? null, + }), + onError: ({ error, path }: { error: Error; path?: string }) => { + console.error(`[gastown-trpc] error on ${path ?? 'unknown'}:`, error.message); + }, + }) +); + // ── Error handling ────────────────────────────────────────────────────── app.notFound(c => c.json(resError('Not found'), 404)); @@ -389,22 +438,10 @@ export default { // Must bypass Hono — the DO returns a 101 + WebSocketPair that the // runtime handles directly. if (request.headers.get('Upgrade')?.toLowerCase() === 'websocket') { - // Validate Kilo user JWT before forwarding — WebSocket upgrades - // bypass Hono middleware so we must check auth inline. - try { - const { verifyKiloToken, extractBearerToken } = await import('@kilocode/worker-utils'); - const { resolveSecret } = await import('./util/secret.util'); - const token = extractBearerToken(request.headers.get('Authorization')); - if (!token) throw new Error('Missing Authorization header'); - const secret = await resolveSecret(env.NEXTAUTH_SECRET); - await verifyKiloToken(token, secret); - } catch (e) { - console.warn( - `[gastown-worker] WS auth failed: ${e instanceof Error ? e.message : 'unknown'}` - ); - return new Response('Unauthorized', { status: 401 }); - } - + // WebSocket upgrades use capability-token auth, not JWT headers. + // Browsers cannot send custom headers on WebSocket connections. + // The stream endpoint uses a ticket obtained via authenticated POST, + // and PTY uses a session ID obtained via authenticated POST. const url = new URL(request.url); // Agent event stream diff --git a/cloudflare-gastown/src/middleware/auth.middleware.ts b/cloudflare-gastown/src/middleware/auth.middleware.ts index 78cc8b7573..81c877b25a 100644 --- a/cloudflare-gastown/src/middleware/auth.middleware.ts +++ b/cloudflare-gastown/src/middleware/auth.middleware.ts @@ -9,6 +9,8 @@ export type AuthVariables = { agentJWT: AgentJWTPayload; townId: string; kiloUserId: string; + kiloIsAdmin: boolean; + kiloApiTokenPepper: string | null; }; import { resolveSecret } from '../util/secret.util'; diff --git a/cloudflare-gastown/src/middleware/kilo-auth.middleware.ts b/cloudflare-gastown/src/middleware/kilo-auth.middleware.ts index 22c6b381b3..d7483512c1 100644 --- a/cloudflare-gastown/src/middleware/kilo-auth.middleware.ts +++ b/cloudflare-gastown/src/middleware/kilo-auth.middleware.ts @@ -13,20 +13,25 @@ import { resolveSecret } from '../util/secret.util'; */ export const kiloAuthMiddleware = createMiddleware(async (c, next) => { const token = extractBearerToken(c.req.header('Authorization')); + if (!token) { return c.json(resError('Authentication required'), 401); } - const secret = await resolveSecret(c.env.NEXTAUTH_SECRET); - if (!secret) { + if (!c.env.NEXTAUTH_SECRET) { console.error('[kilo-auth] NEXTAUTH_SECRET not configured'); return c.json(resError('Internal server error'), 500); } + const secret = await resolveSecret(c.env.NEXTAUTH_SECRET); + console.log(secret); try { const payload = await verifyKiloToken(token, secret); c.set('kiloUserId', payload.kiloUserId); + c.set('kiloIsAdmin', payload.isAdmin === true); + c.set('kiloApiTokenPepper', payload.apiTokenPepper ?? null); } catch (err) { + console.log('error', err); const message = err instanceof Error ? err.message : 'Invalid token'; return c.json(resError(message), 401); } diff --git a/cloudflare-gastown/src/trpc/init.ts b/cloudflare-gastown/src/trpc/init.ts new file mode 100644 index 0000000000..3960f4a729 --- /dev/null +++ b/cloudflare-gastown/src/trpc/init.ts @@ -0,0 +1,25 @@ +import { initTRPC, TRPCError } from '@trpc/server'; + +export type TRPCContext = { + env: Env; + userId: string; + isAdmin: boolean; + apiTokenPepper: string | null; +}; + +const t = initTRPC.context().create(); + +export const router = t.router; + +/** + * Base procedure — requires a valid Kilo JWT (enforced by kiloAuthMiddleware + * running before tRPC). The userId is extracted from the JWT and set on the + * Hono context by kiloAuthMiddleware, then forwarded into the tRPC context + * by the createContext callback in gastown.worker.ts. + */ +export const procedure = t.procedure.use(async ({ ctx, next }) => { + if (!ctx.userId) { + throw new TRPCError({ code: 'UNAUTHORIZED', message: 'Authentication required' }); + } + return next({ ctx }); +}); diff --git a/cloudflare-gastown/src/trpc/router.ts b/cloudflare-gastown/src/trpc/router.ts new file mode 100644 index 0000000000..192078f95a --- /dev/null +++ b/cloudflare-gastown/src/trpc/router.ts @@ -0,0 +1,576 @@ +/** + * Gastown tRPC router — served directly by the Gastown worker. + * + * This replaces the Next.js proxy layer (src/routers/gastown-router.ts). + * The worker validates Kilo JWTs directly, resolves user data from + * Hyperdrive, and calls DO methods without an HTTP intermediary. + */ +/* eslint-disable @typescript-eslint/await-thenable -- DO RPC stubs return Rpc.Promisified which is thenable at runtime */ +import { TRPCError } from '@trpc/server'; +import { z } from 'zod'; +import { router, procedure } from './init'; +import { getTownDOStub } from '../dos/Town.do'; +import { getTownContainerStub } from '../dos/TownContainer.do'; +import { getGastownUserStub } from '../dos/GastownUser.do'; +import { generateKiloApiToken } from '../util/kilo-token.util'; +import { resolveSecret } from '../util/secret.util'; +import { TownConfigSchema } from '../types'; +import { + RpcTownOutput, + RpcRigOutput, + RpcBeadOutput, + RpcAgentOutput, + RpcBeadEventOutput, + RpcMayorSendResultOutput, + RpcMayorStatusOutput, + RpcStreamTicketOutput, + RpcPtySessionOutput, + RpcSlingResultOutput, + RpcRigDetailOutput, +} from './schemas'; +import type { TRPCContext } from './init'; + +// rpcSafe wrapper for TownConfigSchema (imported from ../types, not ./schemas) +const RpcTownConfigSchema = z.any().pipe(TownConfigSchema); + +// ── Git credential helpers ───────────────────────────────────────────── + +/** Extract 'owner/repo' from a GitHub URL, or null if not a GitHub URL. */ +function extractGithubRepo(gitUrl: string): string | null { + const m = gitUrl.match(/github\.com[/:]([^/]+\/[^/.]+)/); + return m ? m[1] : null; +} + +/** Best-effort refresh of git credentials for a town via the git-token-service. */ +async function refreshGitCredentials( + env: Env, + townId: string, + gitUrl: string, + userId: string +): Promise { + if (!env.GIT_TOKEN_SERVICE) return; + const githubRepo = extractGithubRepo(gitUrl); + if (!githubRepo) return; + + const result = await env.GIT_TOKEN_SERVICE.getTokenForRepo({ githubRepo, userId }); + if (!result.success) { + console.warn(`[gastown-trpc] git credential refresh failed: ${result.reason}`); + return; + } + + const townStub = getTownDOStub(env, townId); + await townStub.updateTownConfig({ + git_auth: { + github_token: result.token, + platform_integration_id: result.installationId, + }, + }); +} + +// ── Helpers ──────────────────────────────────────────────────────────── + +function requireAdmin(ctx: TRPCContext): { id: string; api_token_pepper: string | null } { + if (!ctx.isAdmin) { + throw new TRPCError({ code: 'FORBIDDEN', message: 'Admin access required' }); + } + return { id: ctx.userId, api_token_pepper: ctx.apiTokenPepper }; +} + +async function verifyTownOwnership(env: Env, userId: string, townId: string) { + const userStub = getGastownUserStub(env, userId); + const town = await userStub.getTownAsync(townId); + if (!town) { + throw new TRPCError({ code: 'NOT_FOUND', message: 'Town not found' }); + } + if (town.owner_user_id !== userId) { + throw new TRPCError({ code: 'FORBIDDEN', message: 'Not your town' }); + } + return town; +} + +async function verifyRigOwnership(env: Env, userId: string, rigId: string) { + const userStub = getGastownUserStub(env, userId); + const rig = await userStub.getRigAsync(rigId); + if (!rig) { + throw new TRPCError({ code: 'NOT_FOUND', message: 'Rig not found' }); + } + return rig; +} + +async function mintKilocodeToken(env: Env, user: { id: string; api_token_pepper: string | null }) { + if (!env.NEXTAUTH_SECRET) { + throw new TRPCError({ + code: 'INTERNAL_SERVER_ERROR', + message: 'NEXTAUTH_SECRET not configured', + }); + } + const secret = await resolveSecret(env.NEXTAUTH_SECRET); + return generateKiloApiToken(user, secret); +} + +// ── Router ───────────────────────────────────────────────────────────── + +export const gastownRouter = router({ + // ── Towns ─────────────────────────────────────────────────────────── + + createTown: procedure + .input(z.object({ name: z.string().min(1).max(64) })) + .output(RpcTownOutput) + .mutation(async ({ ctx, input }) => { + const user = requireAdmin(ctx); + const userStub = getGastownUserStub(ctx.env, user.id); + const town = await userStub.createTown({ name: input.name, owner_user_id: user.id }); + + // Store kilocode token so agents can auth with the Kilo LLM gateway + const kilocodeToken = await mintKilocodeToken(ctx.env, user); + const townStub = getTownDOStub(ctx.env, town.id); + await townStub.setTownId(town.id); + await townStub.updateTownConfig({ + kilocode_token: kilocodeToken, + owner_user_id: user.id, + }); + + return town; + }), + + listTowns: procedure.output(z.array(RpcTownOutput)).query(async ({ ctx }) => { + requireAdmin(ctx); + const userStub = getGastownUserStub(ctx.env, ctx.userId); + return userStub.listTowns(); + }), + + getTown: procedure + .input(z.object({ townId: z.string().uuid() })) + .output(RpcTownOutput) + .query(async ({ ctx, input }) => { + requireAdmin(ctx); + return verifyTownOwnership(ctx.env, ctx.userId, input.townId); + }), + + deleteTown: procedure + .input(z.object({ townId: z.string().uuid() })) + .mutation(async ({ ctx, input }) => { + requireAdmin(ctx); + await verifyTownOwnership(ctx.env, ctx.userId, input.townId); + const userStub = getGastownUserStub(ctx.env, ctx.userId); + await userStub.deleteTown(input.townId); + }), + + // ── Rigs ──────────────────────────────────────────────────────────── + + createRig: procedure + .input( + z.object({ + townId: z.string().uuid(), + name: z.string().min(1).max(64), + gitUrl: z.string().url(), + defaultBranch: z.string().default('main'), + platformIntegrationId: z.string().uuid().optional(), + }) + ) + .output(RpcRigOutput) + .mutation(async ({ ctx, input }) => { + const user = requireAdmin(ctx); + await verifyTownOwnership(ctx.env, user.id, input.townId); + + // Generate kilocode token for agent LLM gateway auth + const kilocodeToken = await mintKilocodeToken(ctx.env, user); + + // Store token on town config (used by container dispatch) + const townStub = getTownDOStub(ctx.env, input.townId); + await townStub.setTownId(input.townId); + await townStub.updateTownConfig({ kilocode_token: kilocodeToken }); + + const userStub = getGastownUserStub(ctx.env, user.id); + const rig = await userStub.createRig({ + town_id: input.townId, + name: input.name, + git_url: input.gitUrl, + default_branch: input.defaultBranch, + platform_integration_id: input.platformIntegrationId, + }); + + // Configure the Town DO with rig metadata so dispatchAgent can find it. + // If this fails, roll back the rig creation to avoid an orphaned record. + try { + await townStub.configureRig({ + rigId: rig.id, + townId: input.townId, + gitUrl: input.gitUrl, + defaultBranch: input.defaultBranch, + userId: user.id, + kilocodeToken, + platformIntegrationId: input.platformIntegrationId, + }); + await townStub.addRig({ + rigId: rig.id, + name: input.name, + gitUrl: input.gitUrl, + defaultBranch: input.defaultBranch, + }); + } catch (err) { + console.error( + `[gastown-trpc] createRig: Town DO configure FAILED for rig ${rig.id}, rolling back:`, + err + ); + try { + await userStub.deleteRig(rig.id); + } catch { + /* best effort rollback */ + } + throw new TRPCError({ code: 'INTERNAL_SERVER_ERROR', message: 'Failed to configure rig' }); + } + + // Best-effort: resolve git credentials from the git-token-service + try { + await refreshGitCredentials(ctx.env, input.townId, input.gitUrl, user.id); + } catch (err) { + console.warn('[gastown-trpc] createRig: git credential refresh failed', err); + } + + return rig; + }), + + listRigs: procedure + .input(z.object({ townId: z.string().uuid() })) + .output(z.array(RpcRigOutput)) + .query(async ({ ctx, input }) => { + requireAdmin(ctx); + await verifyTownOwnership(ctx.env, ctx.userId, input.townId); + const userStub = getGastownUserStub(ctx.env, ctx.userId); + return userStub.listRigs(input.townId); + }), + + getRig: procedure + .input(z.object({ rigId: z.string().uuid() })) + .output(RpcRigDetailOutput) + .query(async ({ ctx, input }) => { + requireAdmin(ctx); + const rig = await verifyRigOwnership(ctx.env, ctx.userId, input.rigId); + const townStub = getTownDOStub(ctx.env, rig.town_id); + // Sequential to avoid "excessively deep" type inference with Rpc.Promisified DO stubs. + const agentList = await townStub.listAgents({ rig_id: rig.id }); + const beadList = await townStub.listBeads({ rig_id: rig.id, status: 'in_progress' }); + return { ...rig, agents: agentList, beads: beadList }; + }), + + deleteRig: procedure + .input(z.object({ rigId: z.string().uuid() })) + .mutation(async ({ ctx, input }) => { + requireAdmin(ctx); + const userStub = getGastownUserStub(ctx.env, ctx.userId); + await userStub.deleteRig(input.rigId); + }), + + // ── Beads ─────────────────────────────────────────────────────────── + + listBeads: procedure + .input( + z.object({ + rigId: z.string().uuid(), + status: z.enum(['open', 'in_progress', 'closed', 'failed']).optional(), + }) + ) + .output(z.array(RpcBeadOutput)) + .query(async ({ ctx, input }) => { + requireAdmin(ctx); + const rig = await verifyRigOwnership(ctx.env, ctx.userId, input.rigId); + const townStub = getTownDOStub(ctx.env, rig.town_id); + return townStub.listBeads({ rig_id: rig.id, status: input.status }); + }), + + deleteBead: procedure + .input(z.object({ rigId: z.string().uuid(), beadId: z.string().uuid() })) + .mutation(async ({ ctx, input }) => { + requireAdmin(ctx); + const rig = await verifyRigOwnership(ctx.env, ctx.userId, input.rigId); + const townStub = getTownDOStub(ctx.env, rig.town_id); + await townStub.deleteBead(input.beadId); + }), + + // ── Agents ────────────────────────────────────────────────────────── + + listAgents: procedure + .input(z.object({ rigId: z.string().uuid() })) + .output(z.array(RpcAgentOutput)) + .query(async ({ ctx, input }) => { + requireAdmin(ctx); + const rig = await verifyRigOwnership(ctx.env, ctx.userId, input.rigId); + const townStub = getTownDOStub(ctx.env, rig.town_id); + return townStub.listAgents({ rig_id: rig.id }); + }), + + deleteAgent: procedure + .input(z.object({ rigId: z.string().uuid(), agentId: z.string().uuid() })) + .mutation(async ({ ctx, input }) => { + requireAdmin(ctx); + const rig = await verifyRigOwnership(ctx.env, ctx.userId, input.rigId); + const townStub = getTownDOStub(ctx.env, rig.town_id); + await townStub.deleteAgent(input.agentId); + }), + + // ── Work Assignment ───────────────────────────────────────────────── + + sling: procedure + .input( + z.object({ + rigId: z.string().uuid(), + title: z.string().min(1), + body: z.string().optional(), + model: z.string().default('kilo/auto'), + }) + ) + .output(RpcSlingResultOutput) + .mutation(async ({ ctx, input }) => { + const user = requireAdmin(ctx); + const rig = await verifyRigOwnership(ctx.env, user.id, input.rigId); + + // Best-effort: refresh git credentials before dispatching + try { + await refreshGitCredentials(ctx.env, rig.town_id, rig.git_url, user.id); + } catch (err) { + console.warn('[gastown-trpc] sling: git credential refresh failed', err); + } + + const townStub = getTownDOStub(ctx.env, rig.town_id); + await townStub.setTownId(rig.town_id); + return townStub.slingBead({ + rigId: rig.id, + title: input.title, + body: input.body, + metadata: { model: input.model, slung_by: user.id }, + }); + }), + + // ── Mayor ─────────────────────────────────────────────────────────── + + sendMessage: procedure + .input( + z.object({ + townId: z.string().uuid(), + message: z.string().min(1), + model: z.string().default('anthropic/claude-sonnet-4.6'), + rigId: z.string().uuid().optional(), + }) + ) + .output(RpcMayorSendResultOutput) + .mutation(async ({ ctx, input }) => { + requireAdmin(ctx); + await verifyTownOwnership(ctx.env, ctx.userId, input.townId); + + const townStub = getTownDOStub(ctx.env, input.townId); + await townStub.setTownId(input.townId); + return townStub.sendMayorMessage(input.message, input.model); + }), + + getMayorStatus: procedure + .input(z.object({ townId: z.string().uuid() })) + .output(RpcMayorStatusOutput) + .query(async ({ ctx, input }) => { + requireAdmin(ctx); + await verifyTownOwnership(ctx.env, ctx.userId, input.townId); + const townStub = getTownDOStub(ctx.env, input.townId); + await townStub.setTownId(input.townId); + return townStub.getMayorStatus(); + }), + + ensureMayor: procedure + .input(z.object({ townId: z.string().uuid() })) + .output(RpcMayorSendResultOutput) + .mutation(async ({ ctx, input }) => { + requireAdmin(ctx); + await verifyTownOwnership(ctx.env, ctx.userId, input.townId); + + // Best-effort: refresh git credentials from the first rig with a GitHub URL + try { + const userStub = getGastownUserStub(ctx.env, ctx.userId); + const rigList = await userStub.listRigs(input.townId); + for (const rig of rigList) { + if (extractGithubRepo(rig.git_url)) { + await refreshGitCredentials(ctx.env, input.townId, rig.git_url, ctx.userId); + break; + } + } + } catch (err) { + console.warn('[gastown-trpc] ensureMayor: git credential refresh failed', err); + } + + const townStub = getTownDOStub(ctx.env, input.townId); + await townStub.setTownId(input.townId); + return townStub.ensureMayor(); + }), + + // ── Agent Streams ─────────────────────────────────────────────────── + + getAgentStreamUrl: procedure + .input(z.object({ agentId: z.string().uuid(), townId: z.string().uuid() })) + .output(RpcStreamTicketOutput) + .query(async ({ ctx, input }) => { + requireAdmin(ctx); + await verifyTownOwnership(ctx.env, ctx.userId, input.townId); + + // Proxy to container control server to get a stream ticket + const containerStub = getTownContainerStub(ctx.env, input.townId); + const response = await containerStub.fetch( + `http://container/agents/${input.agentId}/stream-ticket`, + { method: 'POST' } + ); + if (!response.ok) { + throw new TRPCError({ + code: 'INTERNAL_SERVER_ERROR', + message: `Container error: ${response.status}`, + }); + } + const raw: unknown = await response.json(); + const ticketData = z.object({ ticket: z.string() }).parse(raw); + + // Return a relative path — the frontend constructs the full WS URL + // using its known GASTOWN_URL (avoids Docker-internal vs browser URL mismatch). + const url = `/api/towns/${input.townId}/container/agents/${input.agentId}/stream`; + + return { url, ticket: ticketData.ticket }; + }), + + // ── PTY ───────────────────────────────────────────────────────────── + + createPtySession: procedure + .input(z.object({ townId: z.string().uuid(), agentId: z.string().uuid() })) + .output(RpcPtySessionOutput) + .mutation(async ({ ctx, input }) => { + requireAdmin(ctx); + await verifyTownOwnership(ctx.env, ctx.userId, input.townId); + + // Proxy to container control server to create a PTY session + const containerStub = getTownContainerStub(ctx.env, input.townId); + const response = await containerStub.fetch(`http://container/agents/${input.agentId}/pty`, { + method: 'POST', + body: '{}', + headers: { 'Content-Type': 'application/json' }, + }); + if (!response.ok) { + throw new TRPCError({ + code: 'INTERNAL_SERVER_ERROR', + message: `Container error: ${response.status}`, + }); + } + const pty: unknown = await response.json(); + const ptyData = z.object({ id: z.string() }).passthrough().parse(pty); + + // Return a relative path — the frontend constructs the full WS URL + // using its known GASTOWN_URL (avoids Docker-internal vs browser URL mismatch). + const wsUrl = `/api/towns/${input.townId}/container/agents/${input.agentId}/pty/${ptyData.id}/connect`; + + return { pty: ptyData, wsUrl }; + }), + + resizePtySession: procedure + .input( + z.object({ + townId: z.string().uuid(), + agentId: z.string().uuid(), + ptyId: z.string().regex(/^[a-zA-Z0-9_-]+$/, 'Invalid ptyId'), + cols: z.number().int().min(1).max(500), + rows: z.number().int().min(1).max(200), + }) + ) + .mutation(async ({ ctx, input }) => { + requireAdmin(ctx); + await verifyTownOwnership(ctx.env, ctx.userId, input.townId); + + const containerStub = getTownContainerStub(ctx.env, input.townId); + const response = await containerStub.fetch( + `http://container/agents/${input.agentId}/pty/${input.ptyId}`, + { + method: 'PUT', + body: JSON.stringify({ size: { cols: input.cols, rows: input.rows } }), + headers: { 'Content-Type': 'application/json' }, + } + ); + if (!response.ok) { + throw new TRPCError({ + code: 'INTERNAL_SERVER_ERROR', + message: `Container error: ${response.status}`, + }); + } + }), + + // ── Town Configuration ────────────────────────────────────────────── + + getTownConfig: procedure + .input(z.object({ townId: z.string().uuid() })) + .output(RpcTownConfigSchema) + .query(async ({ ctx, input }) => { + requireAdmin(ctx); + await verifyTownOwnership(ctx.env, ctx.userId, input.townId); + const townStub = getTownDOStub(ctx.env, input.townId); + return townStub.getTownConfig(); + }), + + updateTownConfig: procedure + .input( + z.object({ + townId: z.string().uuid(), + config: z.record(z.string(), z.unknown()), + }) + ) + .output(RpcTownConfigSchema) + .mutation(async ({ ctx, input }) => { + requireAdmin(ctx); + await verifyTownOwnership(ctx.env, ctx.userId, input.townId); + const townStub = getTownDOStub(ctx.env, input.townId); + return townStub.updateTownConfig(input.config); + }), + + // ── Events ────────────────────────────────────────────────────────── + + getBeadEvents: procedure + .input( + z.object({ + rigId: z.string().uuid(), + beadId: z.string().uuid().optional(), + since: z.string().optional(), + limit: z.number().int().positive().max(500).default(100), + }) + ) + .output(z.array(RpcBeadEventOutput)) + .query(async ({ ctx, input }) => { + requireAdmin(ctx); + const rig = await verifyRigOwnership(ctx.env, ctx.userId, input.rigId); + const townStub = getTownDOStub(ctx.env, rig.town_id); + return townStub.listBeadEvents({ + beadId: input.beadId, + since: input.since, + limit: input.limit, + }); + }), + + getTownEvents: procedure + .input( + z.object({ + townId: z.string().uuid(), + since: z.string().optional(), + limit: z.number().int().positive().max(500).default(100), + }) + ) + .output(z.array(RpcBeadEventOutput)) + .query(async ({ ctx, input }) => { + requireAdmin(ctx); + await verifyTownOwnership(ctx.env, ctx.userId, input.townId); + const townStub = getTownDOStub(ctx.env, input.townId); + return townStub.listBeadEvents({ + since: input.since, + limit: input.limit, + }); + }), +}); + +export type GastownRouter = typeof gastownRouter; + +/** + * Wrapped router that nests gastownRouter under a `gastown` key. + * This preserves the `trpc.gastown.X` call pattern on the frontend, + * matching the existing RootRouter shape so components don't need + * to change their procedure paths. + */ +export const wrappedGastownRouter = router({ gastown: gastownRouter }); +export type WrappedGastownRouter = typeof wrappedGastownRouter; diff --git a/cloudflare-gastown/src/trpc/schemas.ts b/cloudflare-gastown/src/trpc/schemas.ts new file mode 100644 index 0000000000..5deface759 --- /dev/null +++ b/cloudflare-gastown/src/trpc/schemas.ts @@ -0,0 +1,152 @@ +import { z } from 'zod'; + +/** + * Wraps a Zod schema in z.any().pipe(schema) so the TS input type is `any` + * (avoiding "excessively deep" instantiation with Rpc.Promisified DO stubs) + * while still performing full runtime validation via the piped schema. + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function rpcSafe(schema: T): z.ZodPipe { + return z.any().pipe(schema); +} + +// Town (from GastownUserDO) +export const TownOutput = z.object({ + id: z.string(), + name: z.string(), + owner_user_id: z.string(), + created_at: z.string(), + updated_at: z.string(), +}); + +// Rig (from GastownUserDO) +export const RigOutput = z.object({ + id: z.string(), + town_id: z.string(), + name: z.string(), + git_url: z.string(), + default_branch: z.string(), + platform_integration_id: z.string().nullable().optional().default(null), + created_at: z.string(), + updated_at: z.string(), +}); + +// Bead (output shape, after transforms) +export const BeadOutput = z.object({ + bead_id: z.string(), + type: z.enum(['issue', 'message', 'escalation', 'merge_request', 'convoy', 'molecule', 'agent']), + status: z.enum(['open', 'in_progress', 'closed', 'failed']), + title: z.string(), + body: z.string().nullable(), + rig_id: z.string().nullable(), + parent_bead_id: z.string().nullable(), + assignee_agent_bead_id: z.string().nullable(), + priority: z.enum(['low', 'medium', 'high', 'critical']), + labels: z.array(z.string()), + metadata: z.record(z.string(), z.unknown()), + created_by: z.string().nullable(), + created_at: z.string(), + updated_at: z.string(), + closed_at: z.string().nullable(), +}); + +// Agent +export const AgentOutput = z.object({ + id: z.string(), + rig_id: z.string().nullable(), + role: z.enum(['polecat', 'refinery', 'mayor', 'witness']), + name: z.string(), + identity: z.string(), + status: z.enum(['idle', 'working', 'stalled', 'dead']), + current_hook_bead_id: z.string().nullable(), + dispatch_attempts: z.number().default(0), + last_activity_at: z.string().nullable(), + checkpoint: z.unknown().optional(), + created_at: z.string(), +}); + +// BeadEvent (output shape, after transforms) +export const BeadEventOutput = z.object({ + bead_event_id: z.string(), + bead_id: z.string(), + agent_id: z.string().nullable(), + event_type: z.string(), + old_value: z.string().nullable(), + new_value: z.string().nullable(), + metadata: z.record(z.string(), z.unknown()), + created_at: z.string(), + // Optional fields for town-level events that tag the rig + rig_id: z.string().optional(), + rig_name: z.string().optional(), +}); + +// MayorSendResult +export const MayorSendResultOutput = z.object({ + agentId: z.string(), + sessionStatus: z.enum(['idle', 'active', 'starting']), +}); + +// MayorStatus +export const MayorStatusOutput = z.object({ + configured: z.boolean(), + townId: z.string().nullable(), + session: z + .object({ + agentId: z.string(), + sessionId: z.string(), + status: z.enum(['idle', 'active', 'starting']), + lastActivityAt: z.string(), + }) + .nullable(), +}); + +// StreamTicket +export const StreamTicketOutput = z.object({ + url: z.string(), + ticket: z.string(), +}); + +// PtySession (passthrough for extra fields) +export const PtySessionOutput = z.object({ + pty: z.object({ id: z.string() }).passthrough(), + wsUrl: z.string(), +}); + +// SlingResult +export const SlingResultOutput = z.object({ + bead: BeadOutput, + agent: AgentOutput, +}); + +// getRig enriched result +export const RigDetailOutput = z.object({ + id: z.string(), + town_id: z.string(), + name: z.string(), + git_url: z.string(), + default_branch: z.string(), + platform_integration_id: z.string().nullable().optional().default(null), + created_at: z.string(), + updated_at: z.string(), + agents: z.array(AgentOutput), + beads: z.array(BeadOutput), +}); + +// ── rpcSafe wrappers ────────────────────────────────────────────────── +// tRPC's .output() forces TypeScript to check that the handler return type +// is assignable to the schema's input type. When handlers return values from +// Cloudflare Rpc.Promisified DO stubs, the deeply recursive proxy types +// exceed TS's instantiation depth limit. Wrapping with rpcSafe() (z.any().pipe) +// short-circuits the type check while preserving identical runtime validation. + +export const RpcTownOutput = rpcSafe(TownOutput); +export const RpcRigOutput = rpcSafe(RigOutput); +export const RpcBeadOutput = rpcSafe(BeadOutput); +export const RpcAgentOutput = rpcSafe(AgentOutput); +export const RpcBeadEventOutput = rpcSafe(BeadEventOutput); +export const RpcMayorSendResultOutput = rpcSafe(MayorSendResultOutput); +export const RpcMayorStatusOutput = rpcSafe(MayorStatusOutput); +export const RpcStreamTicketOutput = rpcSafe(StreamTicketOutput); +export const RpcPtySessionOutput = rpcSafe(PtySessionOutput); +export const RpcSlingResultOutput = rpcSafe(SlingResultOutput); +export const RpcRigDetailOutput = rpcSafe(RigDetailOutput); diff --git a/cloudflare-gastown/src/util/kilo-token.util.ts b/cloudflare-gastown/src/util/kilo-token.util.ts new file mode 100644 index 0000000000..302e1ac488 --- /dev/null +++ b/cloudflare-gastown/src/util/kilo-token.util.ts @@ -0,0 +1,28 @@ +import { SignJWT } from 'jose'; + +const JWT_TOKEN_VERSION = 3; +const THIRTY_DAYS_SECONDS = 30 * 24 * 60 * 60; + +/** + * Generate a Kilo API token for a user. Used to create kilocode_tokens + * for agents to authenticate with the Kilo LLM gateway. + * + * This is the CF Worker equivalent of generateApiToken() from src/lib/tokens.ts, + * using jose (Web Crypto) instead of jsonwebtoken (Node.js). + */ +export async function generateKiloApiToken( + user: { id: string; api_token_pepper: string | null }, + secret: string, + expiresInSeconds: number = THIRTY_DAYS_SECONDS +): Promise { + const now = Math.floor(Date.now() / 1000); + return new SignJWT({ + kiloUserId: user.id, + apiTokenPepper: user.api_token_pepper, + version: JWT_TOKEN_VERSION, + }) + .setProtectedHeader({ alg: 'HS256' }) + .setIssuedAt(now) + .setExpirationTime(now + expiresInSeconds) + .sign(new TextEncoder().encode(secret)); +} diff --git a/cloudflare-gastown/src/util/user-db.util.ts b/cloudflare-gastown/src/util/user-db.util.ts new file mode 100644 index 0000000000..1bfc07c7e0 --- /dev/null +++ b/cloudflare-gastown/src/util/user-db.util.ts @@ -0,0 +1,24 @@ +import { getWorkerDb } from '@kilocode/db/client'; +import { kilocode_users } from '@kilocode/db/schema'; +import { eq } from 'drizzle-orm'; + +/** + * Look up a user by their Kilo user ID. Returns the minimal fields + * needed for ownership checks and token generation. + */ +export async function findUserById( + connectionString: string, + userId: string +): Promise<{ id: string; api_token_pepper: string | null; is_admin: boolean } | null> { + const db = getWorkerDb(connectionString, { statement_timeout: 5_000 }); + const rows = await db + .select({ + id: kilocode_users.id, + api_token_pepper: kilocode_users.api_token_pepper, + is_admin: kilocode_users.is_admin, + }) + .from(kilocode_users) + .where(eq(kilocode_users.id, userId)) + .limit(1); + return rows[0] ?? null; +} diff --git a/cloudflare-gastown/tsconfig.types.json b/cloudflare-gastown/tsconfig.types.json new file mode 100644 index 0000000000..14416e8d15 --- /dev/null +++ b/cloudflare-gastown/tsconfig.types.json @@ -0,0 +1,11 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "declaration": true, + "emitDeclarationOnly": true, + "declarationDir": "./dist-types", + "noEmit": false, + "skipLibCheck": true + }, + "include": ["src/trpc/router.ts", "src/trpc/init.ts", "src/trpc/schemas.ts"] +} diff --git a/cloudflare-gastown/worker-configuration.d.ts b/cloudflare-gastown/worker-configuration.d.ts index 78b3bf5de5..88c81de7e8 100644 --- a/cloudflare-gastown/worker-configuration.d.ts +++ b/cloudflare-gastown/worker-configuration.d.ts @@ -1,14 +1,30 @@ /* eslint-disable */ -// Generated by Wrangler by running `wrangler types` (hash: 92be991b49e955fa61e3c3d593df5c1a) +// Generated by Wrangler by running `wrangler types` (hash: 94f56b10f188d507133e5a565a91884c) // Runtime types generated with workerd@1.20260302.0 2026-01-27 nodejs_compat +type GetTokenForRepoSuccess = { + success: true; + token: string; + installationId: string; + accountLogin: string; + appType: 'standard' | 'lite'; +}; +type GetTokenForRepoFailure = { + success: false; + reason: 'database_not_configured' | 'invalid_repo_format' | 'no_installation_found' | 'invalid_org_id'; +}; +type GetTokenForRepoResult = GetTokenForRepoSuccess | GetTokenForRepoFailure; +type GitTokenService = { + getTokenForRepo(params: { githubRepo: string; userId: string; orgId?: string }): Promise; + getToken(installationId: string, appType?: 'standard' | 'lite'): Promise; +}; declare namespace Cloudflare { interface GlobalProps { mainModule: typeof import("./src/gastown.worker"); durableNamespaces: "GastownUserDO" | "AgentIdentityDO" | "TownContainerDO" | "TownDO" | "AgentDO"; } interface DevEnv { + GIT_TOKEN_SERVICE?: GitTokenService; GASTOWN_JWT_SECRET: SecretsStoreSecret; - NEXTAUTH_SECRET: SecretsStoreSecret; ENVIRONMENT: "development"; CF_ACCESS_TEAM: "engineering-e11"; CF_ACCESS_AUD: "7f6eda4c0714f6ea2afb74a3f055db65659b67571a913eab42468636a9b8c8be"; @@ -21,8 +37,8 @@ declare namespace Cloudflare { AGENT: DurableObjectNamespace; } interface Env { + GIT_TOKEN_SERVICE?: GitTokenService; GASTOWN_JWT_SECRET: SecretsStoreSecret; - NEXTAUTH_SECRET: SecretsStoreSecret; ENVIRONMENT: "development" | "production"; CF_ACCESS_TEAM: "engineering-e11"; CF_ACCESS_AUD: "7f6eda4c0714f6ea2afb74a3f055db65659b67571a913eab42468636a9b8c8be"; @@ -33,6 +49,8 @@ declare namespace Cloudflare { TOWN: DurableObjectNamespace; TOWN_CONTAINER: DurableObjectNamespace; AGENT: DurableObjectNamespace; + HYPERDRIVE?: Hyperdrive; + NEXTAUTH_SECRET?: SecretsStoreSecret; } } interface Env extends Cloudflare.Env {} diff --git a/cloudflare-gastown/wrangler.jsonc b/cloudflare-gastown/wrangler.jsonc index 3a07d7eadc..be59c57976 100644 --- a/cloudflare-gastown/wrangler.jsonc +++ b/cloudflare-gastown/wrangler.jsonc @@ -54,6 +54,23 @@ "GASTOWN_API_URL": "https://gastown.kiloapps.io", }, + // Hyperdrive binding for Postgres (user lookups, token generation) + "hyperdrive": [ + { + "binding": "HYPERDRIVE", + "id": "624ec80650dd414199349f4e217ddb10", + "localConnectionString": "postgres://postgres:postgres@localhost:5432/postgres", + }, + ], + + "services": [ + { + "binding": "GIT_TOKEN_SERVICE", + "service": "git-token-service", + "entrypoint": "GitTokenRPCEntrypoint", + }, + ], + // PRODUCTION Secrets Store (shared Kilo secrets store) "secrets_store_secrets": [ { @@ -99,12 +116,24 @@ { "name": "AGENT", "class_name": "AgentDO" }, ], }, + "services": [ + { + "binding": "GIT_TOKEN_SERVICE", + "service": "git-token-service", + "entrypoint": "GitTokenRPCEntrypoint", + }, + ], "secrets_store_secrets": [ { "binding": "GASTOWN_JWT_SECRET", "store_id": "342a86d9e3a94da698e82d0c6e2a36f0", "secret_name": "GASTOWN_JWT_SECRET_PROD", }, + { + "binding": "NEXTAUTH_SECRET", + "store_id": "342a86d9e3a94da698e82d0c6e2a36f0", + "secret_name": "NEXTAUTH_SECRET", + }, ], }, }, diff --git a/packages/worker-utils/src/kilo-token.ts b/packages/worker-utils/src/kilo-token.ts index f9a265467d..12953cabe7 100644 --- a/packages/worker-utils/src/kilo-token.ts +++ b/packages/worker-utils/src/kilo-token.ts @@ -14,6 +14,7 @@ export const kiloTokenPayload = z.object({ apiTokenPepper: z.string().nullable().optional(), env: z.string().optional(), // Optional extras from JWTTokenExtraPayload + isAdmin: z.boolean().optional(), botId: z.string().optional(), organizationId: z.string().optional(), organizationRole: z.enum(['owner', 'member', 'billing_manager']).optional(), diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 14f59890da..24c4a6525b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1010,18 +1010,36 @@ importers: '@cloudflare/containers': specifier: ^0.1.0 version: 0.1.0 + '@hono/trpc-server': + specifier: ^0.4.2 + version: 0.4.2(@trpc/server@11.9.0(typescript@5.9.3))(hono@4.12.2) + '@kilocode/db': + specifier: workspace:* + version: link:../packages/db '@kilocode/worker-utils': specifier: workspace:* version: link:../packages/worker-utils + '@trpc/server': + specifier: ^11.0.0 + version: 11.9.0(typescript@5.9.3) + drizzle-orm: + specifier: 'catalog:' + version: 0.45.1(@cloudflare/workers-types@4.20260130.0)(@opentelemetry/api@1.9.0)(@types/pg@8.16.0)(bun-types@1.3.9)(pg@8.18.0) hono: specifier: 'catalog:' version: 4.12.2 itty-time: specifier: ^1.0.6 version: 1.0.6 + jose: + specifier: 'catalog:' + version: 6.1.3 jsonwebtoken: specifier: 'catalog:' version: 9.0.3 + pg: + specifier: ^8.16.3 + version: 8.18.0 zod: specifier: 'catalog:' version: 4.3.6 @@ -9928,9 +9946,6 @@ packages: peerDependencies: pg: '>=8.0' - pg-protocol@1.10.3: - resolution: {integrity: sha512-6DIBgBQaTKDJyxnXaLiLR8wBpQQcGWuAESkRBX/t6OwA8YsqP+iVSiond2EDy6Y/dsGk8rh/jtax3js5NeV7JQ==} - pg-protocol@1.11.0: resolution: {integrity: sha512-pfsxk2M9M3BuGgDOfuy37VNRRX3jmKgMjcvAcWqNDpZSf4cUmv8HSOl5ViRQFsfARFn0KuUQTgLxVMbNq5NW3g==} @@ -17270,7 +17285,7 @@ snapshots: '@types/pg@8.15.6': dependencies: '@types/node': 22.19.1 - pg-protocol: 1.10.3 + pg-protocol: 1.11.0 pg-types: 2.2.0 '@types/pg@8.16.0': @@ -22365,8 +22380,6 @@ snapshots: dependencies: pg: 8.18.0 - pg-protocol@1.10.3: {} - pg-protocol@1.11.0: {} pg-types@2.2.0: diff --git a/src/app/(app)/gastown/TownListPageClient.tsx b/src/app/(app)/gastown/TownListPageClient.tsx index 1ab7d96191..87060033d1 100644 --- a/src/app/(app)/gastown/TownListPageClient.tsx +++ b/src/app/(app)/gastown/TownListPageClient.tsx @@ -3,7 +3,7 @@ import { useState } from 'react'; import { useRouter } from 'next/navigation'; import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; -import { useTRPC } from '@/lib/trpc/utils'; +import { useGastownTRPC } from '@/lib/gastown/trpc'; import { PageContainer } from '@/components/layouts/PageContainer'; import { Button } from '@/components/Button'; import { Badge } from '@/components/ui/badge'; @@ -17,7 +17,7 @@ import { formatDistanceToNow } from 'date-fns'; export function TownListPageClient() { const router = useRouter(); - const trpc = useTRPC(); + const trpc = useGastownTRPC(); const [isCreateOpen, setIsCreateOpen] = useState(false); const queryClient = useQueryClient(); diff --git a/src/app/(app)/gastown/[townId]/TownOverviewPageClient.tsx b/src/app/(app)/gastown/[townId]/TownOverviewPageClient.tsx index fe271dd2db..34ca2ac7b9 100644 --- a/src/app/(app)/gastown/[townId]/TownOverviewPageClient.tsx +++ b/src/app/(app)/gastown/[townId]/TownOverviewPageClient.tsx @@ -3,7 +3,7 @@ import { useState, useMemo } from 'react'; import { useRouter } from 'next/navigation'; import { useQuery, useQueries, useMutation, useQueryClient } from '@tanstack/react-query'; -import { useTRPC } from '@/lib/trpc/utils'; +import { useGastownTRPC } from '@/lib/gastown/trpc'; import { Button } from '@/components/Button'; import { Skeleton } from '@/components/ui/skeleton'; import { CreateRigDialog } from '@/components/gastown/CreateRigDialog'; @@ -29,11 +29,9 @@ import { toast } from 'sonner'; import { formatDistanceToNow } from 'date-fns'; import { AreaChart, Area, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts'; import { motion, AnimatePresence } from 'motion/react'; -import type { inferRouterOutputs } from '@trpc/server'; -import type { RootRouter } from '@/routers/root-router'; +import type { GastownOutputs } from '@/lib/gastown/trpc'; -type RouterOutputs = inferRouterOutputs; -type Agent = RouterOutputs['gastown']['listAgents'][number]; +type Agent = GastownOutputs['gastown']['listAgents'][number]; type TownOverviewPageClientProps = { townId: string; @@ -80,7 +78,7 @@ function bucketEventsOverTime(events: Array<{ created_at: string }>, windowMinut export function TownOverviewPageClient({ townId }: TownOverviewPageClientProps) { const router = useRouter(); - const trpc = useTRPC(); + const trpc = useGastownTRPC(); const [isCreateRigOpen, setIsCreateRigOpen] = useState(false); const { open: openDrawer } = useDrawerStack(); diff --git a/src/app/(app)/gastown/[townId]/agents/AgentsPageClient.tsx b/src/app/(app)/gastown/[townId]/agents/AgentsPageClient.tsx index f3fd06f79a..ace11a4396 100644 --- a/src/app/(app)/gastown/[townId]/agents/AgentsPageClient.tsx +++ b/src/app/(app)/gastown/[townId]/agents/AgentsPageClient.tsx @@ -2,16 +2,14 @@ import { useMemo } from 'react'; import { useQuery, useQueries } from '@tanstack/react-query'; -import { useTRPC } from '@/lib/trpc/utils'; +import { useGastownTRPC } from '@/lib/gastown/trpc'; import { useDrawerStack } from '@/components/gastown/DrawerStack'; import { Bot, Crown, Shield, Eye, Clock, Hexagon } from 'lucide-react'; import { formatDistanceToNow } from 'date-fns'; import { motion, AnimatePresence } from 'motion/react'; -import type { inferRouterOutputs } from '@trpc/server'; -import type { RootRouter } from '@/routers/root-router'; +import type { GastownOutputs } from '@/lib/gastown/trpc'; -type RouterOutputs = inferRouterOutputs; -type Agent = RouterOutputs['gastown']['listAgents'][number]; +type Agent = GastownOutputs['gastown']['listAgents'][number]; const ROLE_ICONS: Record = { polecat: Bot, @@ -28,7 +26,7 @@ const STATUS_COLORS: Record = { }; export function AgentsPageClient({ townId }: { townId: string }) { - const trpc = useTRPC(); + const trpc = useGastownTRPC(); const { open: openDrawer } = useDrawerStack(); const rigsQuery = useQuery(trpc.gastown.listRigs.queryOptions({ townId })); diff --git a/src/app/(app)/gastown/[townId]/beads/BeadsPageClient.tsx b/src/app/(app)/gastown/[townId]/beads/BeadsPageClient.tsx index 50fbd2ec49..bd7a97e044 100644 --- a/src/app/(app)/gastown/[townId]/beads/BeadsPageClient.tsx +++ b/src/app/(app)/gastown/[townId]/beads/BeadsPageClient.tsx @@ -2,16 +2,14 @@ import { useState, useMemo } from 'react'; import { useQuery, useQueries } from '@tanstack/react-query'; -import { useTRPC } from '@/lib/trpc/utils'; +import { useGastownTRPC } from '@/lib/gastown/trpc'; import { useDrawerStack } from '@/components/gastown/DrawerStack'; import { Hexagon, Search } from 'lucide-react'; import { formatDistanceToNow } from 'date-fns'; -import type { inferRouterOutputs } from '@trpc/server'; -import type { RootRouter } from '@/routers/root-router'; import { motion, AnimatePresence } from 'motion/react'; +import type { GastownOutputs } from '@/lib/gastown/trpc'; -type RouterOutputs = inferRouterOutputs; -type Bead = RouterOutputs['gastown']['listBeads'][number]; +type Bead = GastownOutputs['gastown']['listBeads'][number]; type BeadsPageClientProps = { townId: string; @@ -25,7 +23,7 @@ const STATUS_DOT: Record = { }; export function BeadsPageClient({ townId }: BeadsPageClientProps) { - const trpc = useTRPC(); + const trpc = useGastownTRPC(); const { open: openDrawer } = useDrawerStack(); const [statusFilter, setStatusFilter] = useState(null); const [search, setSearch] = useState(''); diff --git a/src/app/(app)/gastown/[townId]/mail/MailPageClient.tsx b/src/app/(app)/gastown/[townId]/mail/MailPageClient.tsx index 8e58662831..565d4173f3 100644 --- a/src/app/(app)/gastown/[townId]/mail/MailPageClient.tsx +++ b/src/app/(app)/gastown/[townId]/mail/MailPageClient.tsx @@ -1,12 +1,12 @@ 'use client'; import { useQuery } from '@tanstack/react-query'; -import { useTRPC } from '@/lib/trpc/utils'; +import { useGastownTRPC } from '@/lib/gastown/trpc'; import { Mail } from 'lucide-react'; import { formatDistanceToNow } from 'date-fns'; export function MailPageClient({ townId }: { townId: string }) { - const trpc = useTRPC(); + const trpc = useGastownTRPC(); const eventsQuery = useQuery({ ...trpc.gastown.getTownEvents.queryOptions({ townId, limit: 200 }), diff --git a/src/app/(app)/gastown/[townId]/merges/MergesPageClient.tsx b/src/app/(app)/gastown/[townId]/merges/MergesPageClient.tsx index ce10b0347f..0b515a3481 100644 --- a/src/app/(app)/gastown/[townId]/merges/MergesPageClient.tsx +++ b/src/app/(app)/gastown/[townId]/merges/MergesPageClient.tsx @@ -1,12 +1,12 @@ 'use client'; import { useQuery } from '@tanstack/react-query'; -import { useTRPC } from '@/lib/trpc/utils'; +import { useGastownTRPC } from '@/lib/gastown/trpc'; import { GitMerge, CheckCircle } from 'lucide-react'; import { formatDistanceToNow } from 'date-fns'; export function MergesPageClient({ townId }: { townId: string }) { - const trpc = useTRPC(); + const trpc = useGastownTRPC(); const eventsQuery = useQuery({ ...trpc.gastown.getTownEvents.queryOptions({ townId, limit: 200 }), diff --git a/src/app/(app)/gastown/[townId]/observability/ObservabilityPageClient.tsx b/src/app/(app)/gastown/[townId]/observability/ObservabilityPageClient.tsx index 050f907089..5ccddd5b91 100644 --- a/src/app/(app)/gastown/[townId]/observability/ObservabilityPageClient.tsx +++ b/src/app/(app)/gastown/[townId]/observability/ObservabilityPageClient.tsx @@ -2,7 +2,7 @@ import { useMemo } from 'react'; import { useQuery } from '@tanstack/react-query'; -import { useTRPC } from '@/lib/trpc/utils'; +import { useGastownTRPC } from '@/lib/gastown/trpc'; import { Activity, Clock, Hexagon, Bot, GitMerge, AlertTriangle, Mail } from 'lucide-react'; import { formatDistanceToNow, format, subHours, differenceInMinutes } from 'date-fns'; import { @@ -20,7 +20,7 @@ import { type EventTypeCounts = Record; export function ObservabilityPageClient({ townId }: { townId: string }) { - const trpc = useTRPC(); + const trpc = useGastownTRPC(); const eventsQuery = useQuery({ ...trpc.gastown.getTownEvents.queryOptions({ townId, limit: 500 }), diff --git a/src/app/(app)/gastown/[townId]/rigs/[rigId]/RigDetailPageClient.tsx b/src/app/(app)/gastown/[townId]/rigs/[rigId]/RigDetailPageClient.tsx index 067d669da8..bb9f8021bf 100644 --- a/src/app/(app)/gastown/[townId]/rigs/[rigId]/RigDetailPageClient.tsx +++ b/src/app/(app)/gastown/[townId]/rigs/[rigId]/RigDetailPageClient.tsx @@ -2,7 +2,7 @@ import { useState } from 'react'; import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; -import { useTRPC } from '@/lib/trpc/utils'; +import { useGastownTRPC } from '@/lib/gastown/trpc'; import { toast } from 'sonner'; import { Button } from '@/components/Button'; import { Skeleton } from '@/components/ui/skeleton'; @@ -19,7 +19,7 @@ type RigDetailPageClientProps = { }; export function RigDetailPageClient({ townId, rigId }: RigDetailPageClientProps) { - const trpc = useTRPC(); + const trpc = useGastownTRPC(); const [isSlingOpen, setIsSlingOpen] = useState(false); const { open: openDrawer } = useDrawerStack(); diff --git a/src/app/(app)/gastown/[townId]/settings/TownSettingsPageClient.tsx b/src/app/(app)/gastown/[townId]/settings/TownSettingsPageClient.tsx index a32fc5a5b7..c48b7d0596 100644 --- a/src/app/(app)/gastown/[townId]/settings/TownSettingsPageClient.tsx +++ b/src/app/(app)/gastown/[townId]/settings/TownSettingsPageClient.tsx @@ -2,7 +2,7 @@ import { useState, useEffect } from 'react'; import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; -import { useTRPC } from '@/lib/trpc/utils'; +import { useGastownTRPC } from '@/lib/gastown/trpc'; import { Button } from '@/components/Button'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; @@ -73,7 +73,7 @@ function scrollToSection(id: string) { } export function TownSettingsPageClient({ townId }: Props) { - const trpc = useTRPC(); + const trpc = useGastownTRPC(); const queryClient = useQueryClient(); const townQuery = useQuery(trpc.gastown.getTown.queryOptions({ townId })); diff --git a/src/app/api/gastown/token/route.ts b/src/app/api/gastown/token/route.ts new file mode 100644 index 0000000000..40d4e3a7af --- /dev/null +++ b/src/app/api/gastown/token/route.ts @@ -0,0 +1,30 @@ +import 'server-only'; +import { NextResponse } from 'next/server'; +import { getUserFromAuth } from '@/lib/user.server'; +import { generateApiToken, TOKEN_EXPIRY } from '@/lib/tokens'; + +const ONE_HOUR_SECONDS = 60 * 60; + +/** + * POST /api/gastown/token + * + * Mints a short-lived (1 hour) Kilo JWT that the browser can use to + * authenticate directly with the Gastown Cloudflare Worker. + * + * The browser authenticates to this endpoint via the NextAuth session cookie + * (same-origin). The returned token is sent as `Authorization: Bearer ` + * to the worker's tRPC endpoint (cross-origin). + * + * The JWT includes `isAdmin` and `apiTokenPepper` so the worker can verify + * admin access and mint kilo API tokens without a DB round-trip. + */ +export async function POST() { + const { user, authFailedResponse } = await getUserFromAuth({ adminOnly: true }); + if (authFailedResponse) return authFailedResponse; + if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + + const token = generateApiToken(user, { isAdmin: true }, { expiresIn: ONE_HOUR_SECONDS }); + const expiresAt = new Date(Date.now() + 55 * 60 * 1000).toISOString(); // 55 min (5 min buffer before 1h expiry) + + return NextResponse.json({ token, expiresAt }); +} diff --git a/src/components/Providers.tsx b/src/components/Providers.tsx index 052b0b090f..82d9df45de 100644 --- a/src/components/Providers.tsx +++ b/src/components/Providers.tsx @@ -2,6 +2,7 @@ import { Toaster } from '@/components/ui/sonner'; import { TRPCContext } from '@/lib/trpc/client'; +import { GastownTRPCProvider, createGastownTRPCClient } from '@/lib/gastown/trpc'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { SessionProvider } from 'next-auth/react'; import type { PropsWithChildren } from 'react'; @@ -20,15 +21,18 @@ export function Providers({ children }: PropsWithChildren) { }, }) ); + const [gastownClient] = useState(() => createGastownTRPCClient()); return ( <> - - - {children} - + + + + {children} + + diff --git a/src/components/gastown/ActivityFeed.tsx b/src/components/gastown/ActivityFeed.tsx index 1a13ce3463..eef8e471d8 100644 --- a/src/components/gastown/ActivityFeed.tsx +++ b/src/components/gastown/ActivityFeed.tsx @@ -2,9 +2,8 @@ import { useState } from 'react'; import { useQuery } from '@tanstack/react-query'; -import { useTRPC } from '@/lib/trpc/utils'; -import type { inferRouterOutputs } from '@trpc/server'; -import type { RootRouter } from '@/routers/root-router'; +import { useGastownTRPC } from '@/lib/gastown/trpc'; +import type { GastownOutputs } from '@/lib/gastown/trpc'; import { formatDistanceToNow } from 'date-fns'; import { Activity, @@ -42,9 +41,8 @@ const EVENT_COLORS: Record = { mail_sent: 'text-sky-500', }; -type RouterOutputs = inferRouterOutputs; -type TownEvent = RouterOutputs['gastown']['getTownEvents'][number]; -type BeadEvent = RouterOutputs['gastown']['getBeadEvents'][number]; +type TownEvent = GastownOutputs['gastown']['getTownEvents'][number]; +type BeadEvent = GastownOutputs['gastown']['getBeadEvents'][number]; function eventDescription(event: { event_type: string; @@ -103,7 +101,7 @@ export function ActivityFeedView({ isLoading, onEventClick, }: ActivityFeedViewProps) { - const trpc = useTRPC(); + const trpc = useGastownTRPC(); const query = useQuery({ ...trpc.gastown.getTownEvents.queryOptions({ townId, limit: 50 }), refetchInterval: 5000, @@ -233,7 +231,7 @@ export function ActivityFeed({ townId }: { townId: string }) { } export function BeadEventTimeline({ rigId, beadId }: { rigId: string; beadId: string }) { - const trpc = useTRPC(); + const trpc = useGastownTRPC(); const { data: events, isLoading } = useQuery({ ...trpc.gastown.getBeadEvents.queryOptions({ rigId, beadId }), refetchInterval: 5000, diff --git a/src/components/gastown/AgentDetailDrawer.tsx b/src/components/gastown/AgentDetailDrawer.tsx index aa2600b1c0..2168a6479d 100644 --- a/src/components/gastown/AgentDetailDrawer.tsx +++ b/src/components/gastown/AgentDetailDrawer.tsx @@ -2,11 +2,10 @@ import { Drawer } from 'vaul'; import { useQuery } from '@tanstack/react-query'; -import { useTRPC } from '@/lib/trpc/utils'; +import { useGastownTRPC } from '@/lib/gastown/trpc'; +import type { GastownOutputs } from '@/lib/gastown/trpc'; import { Badge } from '@/components/ui/badge'; import { BeadEventTimeline } from '@/components/gastown/ActivityFeed'; -import type { inferRouterOutputs } from '@trpc/server'; -import type { RootRouter } from '@/routers/root-router'; import { format, formatDistanceToNow } from 'date-fns'; import { X, @@ -22,9 +21,8 @@ import { Activity, } from 'lucide-react'; -type RouterOutputs = inferRouterOutputs; -type Agent = RouterOutputs['gastown']['listAgents'][number]; -type Bead = RouterOutputs['gastown']['listBeads'][number]; +type Agent = GastownOutputs['gastown']['listAgents'][number]; +type Bead = GastownOutputs['gastown']['listBeads'][number]; type AgentDetailDrawerProps = { open: boolean; @@ -64,7 +62,7 @@ export function AgentDetailDrawer({ onConnect, onDelete, }: AgentDetailDrawerProps) { - const trpc = useTRPC(); + const trpc = useGastownTRPC(); // Fetch related beads for this agent const beadsQuery = useQuery({ diff --git a/src/components/gastown/AgentStream.tsx b/src/components/gastown/AgentStream.tsx index 897dca5766..da810be9b5 100644 --- a/src/components/gastown/AgentStream.tsx +++ b/src/components/gastown/AgentStream.tsx @@ -2,7 +2,7 @@ import { useEffect, useRef, useState, useCallback } from 'react'; import { useQuery } from '@tanstack/react-query'; -import { useTRPC } from '@/lib/trpc/utils'; +import { useGastownTRPC, gastownWsUrl } from '@/lib/gastown/trpc'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { Button } from '@/components/Button'; import { X, Radio } from 'lucide-react'; @@ -136,7 +136,7 @@ function toStreamEntry( } export function AgentStream({ townId, agentId, onClose }: AgentStreamProps) { - const trpc = useTRPC(); + const trpc = useGastownTRPC(); const [entries, setEntries] = useState([]); const [connected, setConnected] = useState(false); const [status, setStatus] = useState('Fetching ticket...'); @@ -185,7 +185,7 @@ export function AgentStream({ townId, agentId, onClose }: AgentStreamProps) { setStatus('Connecting...'); - const wsUrl = new URL(url); + const wsUrl = new URL(gastownWsUrl(url)); wsUrl.searchParams.set('ticket', ticket); const ws = new WebSocket(wsUrl.toString()); diff --git a/src/components/gastown/BeadDetailDrawer.tsx b/src/components/gastown/BeadDetailDrawer.tsx index 9db74546ef..1e6c0ebe22 100644 --- a/src/components/gastown/BeadDetailDrawer.tsx +++ b/src/components/gastown/BeadDetailDrawer.tsx @@ -4,8 +4,7 @@ import { Drawer } from 'vaul'; import { Badge } from '@/components/ui/badge'; import { Button } from '@/components/Button'; import { BeadEventTimeline, extractPrUrl } from '@/components/gastown/ActivityFeed'; -import type { inferRouterOutputs } from '@trpc/server'; -import type { RootRouter } from '@/routers/root-router'; +import type { GastownOutputs } from '@/lib/gastown/trpc'; import { format } from 'date-fns'; import { Clock, @@ -22,8 +21,7 @@ import { import ReactMarkdown from 'react-markdown'; import remarkGfm from 'remark-gfm'; -type RouterOutputs = inferRouterOutputs; -type Bead = RouterOutputs['gastown']['listBeads'][number]; +type Bead = GastownOutputs['gastown']['listBeads'][number]; type BeadDetailDrawerProps = { open: boolean; diff --git a/src/components/gastown/ConvoyTimeline.tsx b/src/components/gastown/ConvoyTimeline.tsx index 3d041d4785..c11c188a83 100644 --- a/src/components/gastown/ConvoyTimeline.tsx +++ b/src/components/gastown/ConvoyTimeline.tsx @@ -1,13 +1,11 @@ 'use client'; import { useMemo } from 'react'; -import type { inferRouterOutputs } from '@trpc/server'; -import type { RootRouter } from '@/routers/root-router'; +import type { GastownOutputs } from '@/lib/gastown/trpc'; import { Hexagon, AlertTriangle, CheckCircle, Loader2 } from 'lucide-react'; import { motion } from 'motion/react'; -type RouterOutputs = inferRouterOutputs; -type Bead = RouterOutputs['gastown']['listBeads'][number]; +type Bead = GastownOutputs['gastown']['listBeads'][number]; type ConvoyTimelineProps = { /** All beads from a rig (or across rigs) */ diff --git a/src/components/gastown/CreateRigDialog.tsx b/src/components/gastown/CreateRigDialog.tsx index e75614f9b2..f1f88cf113 100644 --- a/src/components/gastown/CreateRigDialog.tsx +++ b/src/components/gastown/CreateRigDialog.tsx @@ -2,6 +2,7 @@ import { useState, useMemo } from 'react'; import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; +import { useGastownTRPC } from '@/lib/gastown/trpc'; import { useTRPC } from '@/lib/trpc/utils'; import { Dialog, @@ -30,17 +31,18 @@ export function CreateRigDialog({ townId, isOpen, onClose }: CreateRigDialogProp const [mode, setMode] = useState('integration'); const [selectedRepo, setSelectedRepo] = useState(''); const [selectedPlatform, setSelectedPlatform] = useState<'github' | 'gitlab' | null>(null); - const trpc = useTRPC(); + const trpc = useGastownTRPC(); + const mainTrpc = useTRPC(); const queryClient = useQueryClient(); - // Fetch repos from integrations + // Fetch repos from integrations (via main tRPC — cloudAgent is not on the gastown router) const githubReposQuery = useQuery({ - ...trpc.cloudAgent.listGitHubRepositories.queryOptions({ forceRefresh: false }), + ...mainTrpc.cloudAgent.listGitHubRepositories.queryOptions({ forceRefresh: false }), enabled: isOpen && mode === 'integration', }); const gitlabReposQuery = useQuery({ - ...trpc.cloudAgent.listGitLabRepositories.queryOptions({ forceRefresh: false }), + ...mainTrpc.cloudAgent.listGitLabRepositories.queryOptions({ forceRefresh: false }), enabled: isOpen && mode === 'integration', }); diff --git a/src/components/gastown/CreateTownDialog.tsx b/src/components/gastown/CreateTownDialog.tsx index 1c6e189ae1..53964de318 100644 --- a/src/components/gastown/CreateTownDialog.tsx +++ b/src/components/gastown/CreateTownDialog.tsx @@ -3,7 +3,7 @@ import { useState } from 'react'; import { useRouter } from 'next/navigation'; import { useMutation, useQueryClient } from '@tanstack/react-query'; -import { useTRPC } from '@/lib/trpc/utils'; +import { useGastownTRPC } from '@/lib/gastown/trpc'; import { Dialog, DialogContent, @@ -23,7 +23,7 @@ type CreateTownDialogProps = { export function CreateTownDialog({ isOpen, onClose }: CreateTownDialogProps) { const [name, setName] = useState(''); const router = useRouter(); - const trpc = useTRPC(); + const trpc = useGastownTRPC(); const queryClient = useQueryClient(); const createTown = useMutation( diff --git a/src/components/gastown/GastownBeadDetailSheet.tsx b/src/components/gastown/GastownBeadDetailSheet.tsx index ef79058931..e128fd35a2 100644 --- a/src/components/gastown/GastownBeadDetailSheet.tsx +++ b/src/components/gastown/GastownBeadDetailSheet.tsx @@ -11,13 +11,11 @@ import { } from '@/components/ui/sheet'; import { BeadEventTimeline } from '@/components/gastown/ActivityFeed'; import { cn } from '@/lib/utils'; -import type { inferRouterOutputs } from '@trpc/server'; -import type { RootRouter } from '@/routers/root-router'; +import type { GastownOutputs } from '@/lib/gastown/trpc'; import { formatDistanceToNow } from 'date-fns'; import { Clock, Flag, Hash, Tags, User } from 'lucide-react'; -type RouterOutputs = inferRouterOutputs; -type Bead = RouterOutputs['gastown']['listBeads'][number]; +type Bead = GastownOutputs['gastown']['listBeads'][number]; type GastownBeadDetailSheetProps = { open: boolean; diff --git a/src/components/gastown/GastownTownSidebar.tsx b/src/components/gastown/GastownTownSidebar.tsx index 1c20ef626f..494f22c8cb 100644 --- a/src/components/gastown/GastownTownSidebar.tsx +++ b/src/components/gastown/GastownTownSidebar.tsx @@ -3,7 +3,7 @@ import { usePathname } from 'next/navigation'; import Link from 'next/link'; import { useQuery } from '@tanstack/react-query'; -import { useTRPC } from '@/lib/trpc/utils'; +import { useGastownTRPC } from '@/lib/gastown/trpc'; import { Sidebar, SidebarContent, @@ -35,7 +35,7 @@ type GastownTownSidebarProps = { export function GastownTownSidebar({ townId, ...sidebarProps }: GastownTownSidebarProps) { const pathname = usePathname(); - const trpc = useTRPC(); + const trpc = useGastownTRPC(); const townQuery = useQuery(trpc.gastown.getTown.queryOptions({ townId })); const rigsQuery = useQuery(trpc.gastown.listRigs.queryOptions({ townId })); diff --git a/src/components/gastown/MayorChat.tsx b/src/components/gastown/MayorChat.tsx index d0de430ebe..e84309fc19 100644 --- a/src/components/gastown/MayorChat.tsx +++ b/src/components/gastown/MayorChat.tsx @@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from 'react'; import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; -import { useTRPC } from '@/lib/trpc/utils'; +import { useGastownTRPC } from '@/lib/gastown/trpc'; import { useSidebar } from '@/components/ui/sidebar'; import { ChevronDown, ChevronUp, Terminal as TerminalIcon } from 'lucide-react'; import { useXtermPty } from './useXtermPty'; @@ -15,7 +15,7 @@ const COLLAPSED_HEIGHT = 40; // px — title bar only const EXPANDED_HEIGHT = 320; // px — terminal area export function MayorChat({ townId }: MayorChatProps) { - const trpc = useTRPC(); + const trpc = useGastownTRPC(); const queryClient = useQueryClient(); const [collapsed, setCollapsed] = useState(false); diff --git a/src/components/gastown/SlingDialog.tsx b/src/components/gastown/SlingDialog.tsx index b508548a5b..91b10b6620 100644 --- a/src/components/gastown/SlingDialog.tsx +++ b/src/components/gastown/SlingDialog.tsx @@ -2,7 +2,7 @@ import { useState } from 'react'; import { useMutation, useQueryClient } from '@tanstack/react-query'; -import { useTRPC } from '@/lib/trpc/utils'; +import { useGastownTRPC } from '@/lib/gastown/trpc'; import { Dialog, DialogContent, @@ -40,7 +40,7 @@ export function SlingDialog({ rigId, isOpen, onClose }: SlingDialogProps) { const [title, setTitle] = useState(''); const [body, setBody] = useState(''); const [model, setModel] = useState('kilo/auto'); - const trpc = useTRPC(); + const trpc = useGastownTRPC(); const queryClient = useQueryClient(); const sling = useMutation( diff --git a/src/components/gastown/SystemTopology.tsx b/src/components/gastown/SystemTopology.tsx index f423dffbdc..ea98b3c4da 100644 --- a/src/components/gastown/SystemTopology.tsx +++ b/src/components/gastown/SystemTopology.tsx @@ -1,15 +1,13 @@ 'use client'; import { useMemo, useRef, useEffect, useState } from 'react'; -import type { inferRouterOutputs } from '@trpc/server'; -import type { RootRouter } from '@/routers/root-router'; +import type { GastownOutputs } from '@/lib/gastown/trpc'; import { motion } from 'motion/react'; -type RouterOutputs = inferRouterOutputs; -type Rig = RouterOutputs['gastown']['listRigs'][number]; -type Agent = RouterOutputs['gastown']['listAgents'][number]; -type TownEvent = RouterOutputs['gastown']['getTownEvents'][number]; +type Rig = GastownOutputs['gastown']['listRigs'][number]; +type Agent = GastownOutputs['gastown']['listAgents'][number]; +type TownEvent = GastownOutputs['gastown']['getTownEvents'][number]; type SystemTopologyProps = { townName: string; diff --git a/src/components/gastown/TerminalBar.tsx b/src/components/gastown/TerminalBar.tsx index 090f93eaae..f7ce4a2878 100644 --- a/src/components/gastown/TerminalBar.tsx +++ b/src/components/gastown/TerminalBar.tsx @@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from 'react'; import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; -import { useTRPC } from '@/lib/trpc/utils'; +import { useGastownTRPC, gastownWsUrl } from '@/lib/gastown/trpc'; import { useSidebar } from '@/components/ui/sidebar'; import { useTerminalBar } from './TerminalBarContext'; import { ChevronDown, ChevronUp, Crown, Terminal as TerminalIcon, X } from 'lucide-react'; @@ -139,7 +139,7 @@ export function TerminalBar({ townId }: TerminalBarProps) { // ── Mayor Terminal Pane ────────────────────────────────────────────────── function MayorTerminalPane({ townId, collapsed }: { townId: string; collapsed: boolean }) { - const trpc = useTRPC(); + const trpc = useGastownTRPC(); const queryClient = useQueryClient(); const [connected, setConnected] = useState(false); const [status, setStatus] = useState('Initializing...'); @@ -271,7 +271,7 @@ function MayorTerminalPane({ townId, collapsed }: { townId: string; collapsed: b ptyRef.current = result.pty; setStatus('Connecting...'); - const ws = new WebSocket(result.wsUrl); + const ws = new WebSocket(gastownWsUrl(result.wsUrl)); ws.binaryType = 'arraybuffer'; wsRef.current = ws; @@ -361,7 +361,7 @@ function MayorTerminalPane({ townId, collapsed }: { townId: string; collapsed: b // ── Agent Terminal Pane ────────────────────────────────────────────────── function AgentTerminalPane({ townId, agentId }: { townId: string; agentId: string }) { - const trpc = useTRPC(); + const trpc = useGastownTRPC(); const terminalRef = useRef(null); const wsRef = useRef(null); const xtermRef = useRef(null); @@ -446,7 +446,7 @@ function AgentTerminalPane({ townId, agentId }: { townId: string; agentId: strin ptyRef.current = result.pty; setStatus('Connecting...'); - const ws = new WebSocket(result.wsUrl); + const ws = new WebSocket(gastownWsUrl(result.wsUrl)); ws.binaryType = 'arraybuffer'; wsRef.current = ws; diff --git a/src/components/gastown/drawer-panels/AgentPanel.tsx b/src/components/gastown/drawer-panels/AgentPanel.tsx index f038b75c36..99645f3a1f 100644 --- a/src/components/gastown/drawer-panels/AgentPanel.tsx +++ b/src/components/gastown/drawer-panels/AgentPanel.tsx @@ -1,7 +1,7 @@ 'use client'; import { useQuery } from '@tanstack/react-query'; -import { useTRPC } from '@/lib/trpc/utils'; +import { useGastownTRPC } from '@/lib/gastown/trpc'; import { BeadEventTimeline } from '@/components/gastown/ActivityFeed'; import { useTerminalBar } from '@/components/gastown/TerminalBarContext'; import type { ResourceRef } from '@/components/gastown/DrawerStack'; @@ -61,7 +61,7 @@ export function AgentPanel({ push: (ref: ResourceRef) => void; close: () => void; }) { - const trpc = useTRPC(); + const trpc = useGastownTRPC(); const { openAgentTab } = useTerminalBar(); const agentsQuery = useQuery(trpc.gastown.listAgents.queryOptions({ rigId })); diff --git a/src/components/gastown/drawer-panels/BeadPanel.tsx b/src/components/gastown/drawer-panels/BeadPanel.tsx index be25307917..f88a5fd378 100644 --- a/src/components/gastown/drawer-panels/BeadPanel.tsx +++ b/src/components/gastown/drawer-panels/BeadPanel.tsx @@ -1,7 +1,7 @@ 'use client'; import { useQuery } from '@tanstack/react-query'; -import { useTRPC } from '@/lib/trpc/utils'; +import { useGastownTRPC } from '@/lib/gastown/trpc'; import { Badge } from '@/components/ui/badge'; import { BeadEventTimeline, extractPrUrl } from '@/components/gastown/ActivityFeed'; import type { ResourceRef } from '@/components/gastown/DrawerStack'; @@ -50,7 +50,7 @@ export function BeadPanel({ rigId: string; push: (ref: ResourceRef) => void; }) { - const trpc = useTRPC(); + const trpc = useGastownTRPC(); const beadsQuery = useQuery(trpc.gastown.listBeads.queryOptions({ rigId })); const agentsQuery = useQuery(trpc.gastown.listAgents.queryOptions({ rigId })); const rigQuery = useQuery(trpc.gastown.getRig.queryOptions({ rigId })); diff --git a/src/components/gastown/useXtermPty.ts b/src/components/gastown/useXtermPty.ts index 363f7f7243..aea0f5d100 100644 --- a/src/components/gastown/useXtermPty.ts +++ b/src/components/gastown/useXtermPty.ts @@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from 'react'; import { useMutation } from '@tanstack/react-query'; -import { useTRPC } from '@/lib/trpc/utils'; +import { useGastownTRPC, gastownWsUrl } from '@/lib/gastown/trpc'; import type { Terminal } from '@xterm/xterm'; import type { FitAddon } from '@xterm/addon-fit'; @@ -35,7 +35,7 @@ export function useXtermPty({ retryDelay = 3_000, onStatusChange, }: XtermPtyOptions): XtermPtyResult { - const trpc = useTRPC(); + const trpc = useGastownTRPC(); const [connected, setConnected] = useState(false); const [status, setStatus] = useState('Initializing...'); @@ -153,7 +153,7 @@ export function useXtermPty({ ptyRef.current = result.pty; updateStatus('Connecting...'); - const ws = new WebSocket(result.wsUrl); + const ws = new WebSocket(gastownWsUrl(result.wsUrl)); ws.binaryType = 'arraybuffer'; wsRef.current = ws; diff --git a/src/lib/constants.ts b/src/lib/constants.ts index 7e11c8f3ad..f77834a6e8 100644 --- a/src/lib/constants.ts +++ b/src/lib/constants.ts @@ -43,6 +43,10 @@ export const CLOUD_AGENT_WS_URL = process.env.NEXT_PUBLIC_CLOUD_AGENT_WS_URL ?? // Separate URL for the new cloud-agent-next implementation export const CLOUD_AGENT_NEXT_WS_URL = process.env.NEXT_PUBLIC_CLOUD_AGENT_NEXT_WS_URL ?? ''; +// Gastown worker URL (client-side, inlined at build time) +// The browser talks directly to the gastown Cloudflare Worker for tRPC + WS. +export const GASTOWN_URL = process.env.NEXT_PUBLIC_GASTOWN_URL ?? ''; + // Free model rate limits (applies to both anonymous and authenticated users) export const FREE_MODEL_RATE_LIMIT_WINDOW_HOURS = 1; export const FREE_MODEL_MAX_REQUESTS_PER_WINDOW = 200; diff --git a/src/lib/gastown/gastown-client.ts b/src/lib/gastown/gastown-client.ts deleted file mode 100644 index 41d18f5db7..0000000000 --- a/src/lib/gastown/gastown-client.ts +++ /dev/null @@ -1,572 +0,0 @@ -import 'server-only'; -import { GASTOWN_SERVICE_URL } from '@/lib/config.server'; -import { generateInternalServiceToken } from '@/lib/tokens'; -import { z } from 'zod'; - -// ── Response schemas ────────────────────────────────────────────────────── - -const GastownErrorResponse = z.object({ - success: z.literal(false), - error: z.string(), -}); - -// ── Domain schemas ──────────────────────────────────────────────────────── -// Mirror the gastown worker's record schemas for validation at the IO boundary. - -function parseJsonOrIssue(v: string, ctx: z.RefinementCtx, label: string): unknown { - try { - return JSON.parse(v) as unknown; - } catch { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: `${label} is not valid JSON`, - }); - return z.NEVER; - } -} - -export const TownSchema = z.object({ - id: z.string(), - name: z.string(), - owner_user_id: z.string(), - created_at: z.string(), - updated_at: z.string(), -}); -export type Town = z.output; - -export const RigSchema = z.object({ - id: z.string(), - town_id: z.string(), - name: z.string(), - git_url: z.string(), - default_branch: z.string(), - platform_integration_id: z.string().nullable().optional().default(null), - created_at: z.string(), - updated_at: z.string(), -}); -export type Rig = z.output; - -export const BeadSchema = z.object({ - bead_id: z.string(), - type: z.enum(['issue', 'message', 'escalation', 'merge_request', 'convoy', 'molecule', 'agent']), - status: z.enum(['open', 'in_progress', 'closed', 'failed']), - title: z.string(), - body: z.string().nullable(), - rig_id: z.string().nullable(), - parent_bead_id: z.string().nullable(), - assignee_agent_bead_id: z.string().nullable(), - priority: z.enum(['low', 'medium', 'high', 'critical']), - labels: z.union([ - z.array(z.string()), - z - .string() - .transform((v, ctx) => parseJsonOrIssue(v, ctx, 'labels')) - .pipe(z.array(z.string())), - ]), - metadata: z.union([ - z.record(z.string(), z.unknown()), - z - .string() - .transform((v, ctx) => parseJsonOrIssue(v, ctx, 'metadata')) - .pipe(z.record(z.string(), z.unknown())), - ]), - created_by: z.string().nullable(), - created_at: z.string(), - updated_at: z.string(), - closed_at: z.string().nullable(), -}); -export type Bead = z.output; - -export const AgentSchema = z.object({ - id: z.string(), - rig_id: z.string().nullable(), - role: z.enum(['polecat', 'refinery', 'mayor', 'witness']), - name: z.string(), - identity: z.string(), - status: z.enum(['idle', 'working', 'stalled', 'dead']), - current_hook_bead_id: z.string().nullable(), - dispatch_attempts: z.number().default(0), - last_activity_at: z.string().nullable(), - checkpoint: z.unknown().optional(), - created_at: z.string(), -}); -export type Agent = z.output; - -export const StreamTicketSchema = z.object({ - url: z.string(), - ticket: z.string().optional(), -}); -export type StreamTicket = z.output; - -// ── Client ──────────────────────────────────────────────────────────────── - -export class GastownApiError extends Error { - constructor( - message: string, - public status: number - ) { - super(message); - this.name = 'GastownApiError'; - } -} - -function getHeaders(): Record { - const headers: Record = { - 'Content-Type': 'application/json', - }; - - // Authenticate to the Gastown worker with a short-lived internal service - // token signed with NEXTAUTH_SECRET. This replaces the old CF Access - // service token approach. Uses a fixed service identity since the actual - // user ID is passed in the URL path for user-scoped operations. - const token = generateInternalServiceToken('gastown-service'); - if (token) { - headers['Authorization'] = `Bearer ${token}`; - } - - return headers; -} - -const CLIENT_LOG = '[gastown-client]'; - -async function gastownFetch(path: string, init?: RequestInit): Promise { - if (!GASTOWN_SERVICE_URL) { - console.error(`${CLIENT_LOG} GASTOWN_SERVICE_URL is not configured!`); - throw new GastownApiError('GASTOWN_SERVICE_URL is not configured', 500); - } - - const url = `${GASTOWN_SERVICE_URL}${path}`; - const method = init?.method ?? 'GET'; - console.log(`${CLIENT_LOG} ${method} ${url}`); - if (init?.body && typeof init.body === 'string') { - try { - const bodyKeys = Object.keys(JSON.parse(init.body)); - console.log(`${CLIENT_LOG} ${method} ${path} bodyKeys=[${bodyKeys.join(',')}]`); - } catch { - // not JSON - } - } - if (init?.body) { - const safeBody = - typeof init.body === 'string' - ? init.body - .replace(/"kilocode_token":"[^"]*"/g, '"kilocode_token":"[REDACTED]"') - .slice(0, 500) - : '[non-string body]'; - console.log(`${CLIENT_LOG} body: ${safeBody}`); - } - - const startTime = Date.now(); - const response = await fetch(url, { - ...init, - headers: { - ...getHeaders(), - ...init?.headers, - }, - }); - const elapsed = Date.now() - startTime; - - console.log(`${CLIENT_LOG} ${method} ${path} -> ${response.status} (${elapsed}ms)`); - - let body: unknown; - try { - body = await response.json(); - } catch { - console.error(`${CLIENT_LOG} Non-JSON response from ${path}: status=${response.status}`); - throw new GastownApiError( - `Gastown returned non-JSON response (${response.status})`, - response.status - ); - } - - if (!response.ok) { - const parsed = GastownErrorResponse.safeParse(body); - const message = parsed.success ? parsed.data.error : `Gastown API error (${response.status})`; - console.error(`${CLIENT_LOG} Error from ${path}: ${response.status} - ${message}`); - console.error(`${CLIENT_LOG} Response body: ${JSON.stringify(body).slice(0, 500)}`); - throw new GastownApiError(message, response.status); - } - - console.log(`${CLIENT_LOG} ${method} ${path} response: ${JSON.stringify(body).slice(0, 300)}`); - return body; -} - -function parseSuccessData(body: unknown, schema: z.ZodType): T { - const envelope = z.object({ success: z.literal(true), data: schema }).parse(body); - return envelope.data; -} - -// ── Town operations ─────────────────────────────────────────────────────── - -export async function createTown(userId: string, name: string): Promise { - const body = await gastownFetch(`/api/users/${userId}/towns`, { - method: 'POST', - body: JSON.stringify({ name }), - }); - return parseSuccessData(body, TownSchema); -} - -export async function listTowns(userId: string): Promise { - const body = await gastownFetch(`/api/users/${userId}/towns`); - return parseSuccessData(body, TownSchema.array()); -} - -export async function getTown(userId: string, townId: string): Promise { - const body = await gastownFetch(`/api/users/${userId}/towns/${townId}`); - return parseSuccessData(body, TownSchema); -} - -// ── Rig operations ──────────────────────────────────────────────────────── - -export async function createRig( - userId: string, - input: { - town_id: string; - name: string; - git_url: string; - default_branch: string; - kilocode_token?: string; - platform_integration_id?: string; - } -): Promise { - const body = await gastownFetch(`/api/users/${userId}/rigs`, { - method: 'POST', - body: JSON.stringify(input), - }); - return parseSuccessData(body, RigSchema); -} - -export async function getRig(userId: string, rigId: string): Promise { - const body = await gastownFetch(`/api/users/${userId}/rigs/${rigId}`); - return parseSuccessData(body, RigSchema); -} - -export async function listRigs(userId: string, townId: string): Promise { - const body = await gastownFetch(`/api/users/${userId}/towns/${townId}/rigs`); - return parseSuccessData(body, RigSchema.array()); -} - -// ── Bead operations (via Rig DO) ────────────────────────────────────────── - -export async function createBead( - townId: string, - rigId: string, - input: { - type: string; - title: string; - body?: string; - priority?: string; - labels?: string[]; - metadata?: Record; - assignee_agent_id?: string; - } -): Promise { - const body = await gastownFetch(`/api/towns/${townId}/rigs/${rigId}/beads`, { - method: 'POST', - body: JSON.stringify(input), - }); - return parseSuccessData(body, BeadSchema); -} - -const SlingResultSchema = z.object({ - bead: BeadSchema, - agent: AgentSchema, -}); -export type SlingResult = z.output; - -export async function slingBead( - townId: string, - rigId: string, - input: { title: string; body?: string; metadata?: Record } -): Promise { - const body = await gastownFetch(`/api/towns/${townId}/rigs/${rigId}/sling`, { - method: 'POST', - body: JSON.stringify(input), - }); - return parseSuccessData(body, SlingResultSchema); -} - -export async function listBeads( - townId: string, - rigId: string, - filter?: { status?: string } -): Promise { - const params = new URLSearchParams(); - if (filter?.status) params.set('status', filter.status); - const qs = params.toString(); - const path = `/api/towns/${townId}/rigs/${rigId}/beads${qs ? `?${qs}` : ''}`; - const body = await gastownFetch(path); - return parseSuccessData(body, BeadSchema.array()); -} - -// ── Agent operations (via Rig DO) ───────────────────────────────────────── - -export async function registerAgent( - townId: string, - rigId: string, - input: { role: string; name: string; identity: string } -): Promise { - const body = await gastownFetch(`/api/towns/${townId}/rigs/${rigId}/agents`, { - method: 'POST', - body: JSON.stringify(input), - }); - return parseSuccessData(body, AgentSchema); -} - -export async function listAgents(townId: string, rigId: string): Promise { - const body = await gastownFetch(`/api/towns/${townId}/rigs/${rigId}/agents`); - return parseSuccessData(body, AgentSchema.array()); -} - -export async function getOrCreateAgent( - townId: string, - rigId: string, - role: string -): Promise { - const body = await gastownFetch(`/api/towns/${townId}/rigs/${rigId}/agents/get-or-create`, { - method: 'POST', - body: JSON.stringify({ role }), - }); - return parseSuccessData(body, AgentSchema); -} - -export async function hookBead( - townId: string, - rigId: string, - agentId: string, - beadId: string -): Promise { - await gastownFetch(`/api/towns/${townId}/rigs/${rigId}/agents/${agentId}/hook`, { - method: 'POST', - body: JSON.stringify({ bead_id: beadId }), - }); -} - -// ── Delete operations ────────────────────────────────────────────────────── - -export async function deleteTown(userId: string, townId: string): Promise { - await gastownFetch(`/api/users/${userId}/towns/${townId}`, { method: 'DELETE' }); -} - -export async function deleteRig(userId: string, rigId: string): Promise { - await gastownFetch(`/api/users/${userId}/rigs/${rigId}`, { method: 'DELETE' }); -} - -export async function deleteBead(townId: string, rigId: string, beadId: string): Promise { - await gastownFetch(`/api/towns/${townId}/rigs/${rigId}/beads/${beadId}`, { method: 'DELETE' }); -} - -export async function deleteAgent(townId: string, rigId: string, agentId: string): Promise { - await gastownFetch(`/api/towns/${townId}/rigs/${rigId}/agents/${agentId}`, { method: 'DELETE' }); -} - -// ── Event operations ────────────────────────────────────────────────────── - -export const BeadEventSchema = z.object({ - bead_event_id: z.string(), - bead_id: z.string(), - agent_id: z.string().nullable(), - event_type: z.string(), - old_value: z.string().nullable(), - new_value: z.string().nullable(), - metadata: z.union([ - z.record(z.string(), z.unknown()), - z - .string() - .transform((v, ctx) => parseJsonOrIssue(v, ctx, 'event metadata')) - .pipe(z.record(z.string(), z.unknown())), - ]), - created_at: z.string(), -}); -export type BeadEvent = z.output; - -export const TaggedBeadEventSchema = BeadEventSchema.extend({ - rig_id: z.string().optional(), - rig_name: z.string().optional(), -}); -export type TaggedBeadEvent = z.output; - -export async function listBeadEvents( - townId: string, - rigId: string, - options?: { beadId?: string; since?: string; limit?: number } -): Promise { - const params = new URLSearchParams(); - if (options?.beadId) params.set('bead_id', options.beadId); - if (options?.since) params.set('since', options.since); - if (options?.limit) params.set('limit', String(options.limit)); - const qs = params.toString(); - const path = `/api/towns/${townId}/rigs/${rigId}/events${qs ? `?${qs}` : ''}`; - const body = await gastownFetch(path); - return parseSuccessData(body, BeadEventSchema.array()); -} - -export async function listTownEvents( - userId: string, - townId: string, - options?: { since?: string; limit?: number } -): Promise { - const params = new URLSearchParams(); - if (options?.since) params.set('since', options.since); - if (options?.limit) params.set('limit', String(options.limit)); - const qs = params.toString(); - const path = `/api/users/${userId}/towns/${townId}/events${qs ? `?${qs}` : ''}`; - const body = await gastownFetch(path); - return parseSuccessData(body, TaggedBeadEventSchema.array()); -} - -// ── Town Configuration ──────────────────────────────────────────────────── - -export const TownConfigSchema = z.object({ - env_vars: z.record(z.string(), z.string()), - git_auth: z.object({ - github_token: z.string().optional(), - gitlab_token: z.string().optional(), - gitlab_instance_url: z.string().optional(), - platform_integration_id: z.string().optional(), - }), - kilocode_token: z.string().optional(), - owner_user_id: z.string().optional(), - default_model: z.string().optional(), - max_polecats_per_rig: z.number().optional(), - merge_strategy: z.enum(['direct', 'pr']).default('direct'), - refinery: z - .object({ - gates: z.array(z.string()), - auto_merge: z.boolean(), - require_clean_merge: z.boolean(), - }) - .optional(), - alarm_interval_active: z.number().optional(), - alarm_interval_idle: z.number().optional(), - container: z - .object({ - sleep_after_minutes: z.number().optional(), - }) - .optional(), -}); -export type TownConfigClient = z.output; - -export async function getTownConfig(townId: string): Promise { - const body = await gastownFetch(`/api/towns/${townId}/config`); - return parseSuccessData(body, TownConfigSchema); -} - -export async function updateTownConfig( - townId: string, - update: Partial -): Promise { - const body = await gastownFetch(`/api/towns/${townId}/config`, { - method: 'PATCH', - body: JSON.stringify(update), - }); - return parseSuccessData(body, TownConfigSchema); -} - -// ── Container operations (via Town Container DO) ────────────────────────── - -export async function getStreamTicket(townId: string, agentId: string): Promise { - const body = await gastownFetch( - `/api/towns/${townId}/container/agents/${agentId}/stream-ticket`, - { method: 'POST' } - ); - return parseSuccessData(body, StreamTicketSchema); -} - -// ── PTY operations (via Town Container DO) ──────────────────────────────── - -const PtySessionSchema = z.object({ - id: z.string(), - title: z.string(), - command: z.string(), - args: z.array(z.string()), - cwd: z.string(), - status: z.enum(['running', 'exited']), - pid: z.number(), -}); -export type PtySession = z.output; - -export async function createPtySession(townId: string, agentId: string): Promise { - const body = await gastownFetch(`/api/towns/${townId}/container/agents/${agentId}/pty`, { - method: 'POST', - body: JSON.stringify({}), - }); - return PtySessionSchema.parse(body); -} - -export async function resizePtySession( - townId: string, - agentId: string, - ptyId: string, - cols: number, - rows: number -): Promise { - await gastownFetch(`/api/towns/${townId}/container/agents/${agentId}/pty/${ptyId}`, { - method: 'PUT', - body: JSON.stringify({ size: { cols, rows } }), - }); -} - -// ── Mayor operations (via MayorDO) ──────────────────────────────────────── - -const MayorSendResultSchema = z.object({ - agentId: z.string(), - sessionStatus: z.enum(['idle', 'active', 'starting']), -}); -export type MayorSendResult = z.output; - -const MayorStatusSchema = z.object({ - configured: z.boolean(), - session: z - .object({ - agentId: z.string(), - sessionId: z.string(), - status: z.enum(['idle', 'active', 'starting']), - lastActivityAt: z.string(), - }) - .nullable(), - townId: z.string().nullable(), -}); -export type MayorStatus = z.output; - -export async function configureMayor( - townId: string, - config: { - userId: string; - kilocodeToken?: string; - gitUrl: string; - defaultBranch: string; - } -): Promise { - await gastownFetch(`/api/towns/${townId}/mayor/configure`, { - method: 'POST', - body: JSON.stringify({ ...config, townId }), - }); -} - -export async function sendMayorMessage( - townId: string, - message: string, - model?: string -): Promise { - const body = await gastownFetch(`/api/towns/${townId}/mayor/message`, { - method: 'POST', - body: JSON.stringify({ message, model }), - }); - return parseSuccessData(body, MayorSendResultSchema); -} - -export async function getMayorStatus(townId: string): Promise { - const body = await gastownFetch(`/api/towns/${townId}/mayor/status`); - return parseSuccessData(body, MayorStatusSchema); -} - -/** Eagerly ensure the mayor agent + container are running. */ -export async function ensureMayor(townId: string): Promise { - const body = await gastownFetch(`/api/towns/${townId}/mayor/ensure`, { method: 'POST' }); - return parseSuccessData(body, MayorSendResultSchema); -} - -export async function destroyMayor(townId: string): Promise { - await gastownFetch(`/api/towns/${townId}/mayor/destroy`, { method: 'POST' }); -} diff --git a/src/lib/gastown/trpc.ts b/src/lib/gastown/trpc.ts new file mode 100644 index 0000000000..f0c6feeda2 --- /dev/null +++ b/src/lib/gastown/trpc.ts @@ -0,0 +1,97 @@ +'use client'; + +/** + * Gastown tRPC client — talks directly to the Cloudflare Worker. + * + * This replaces the proxy path (browser → Next.js tRPC → gastown-client.ts → worker). + * The browser fetches a short-lived JWT from /api/gastown/token and sends it + * as Bearer auth to the worker's /trpc endpoint. + */ + +import { createTRPCClient, httpBatchLink, httpLink, splitLink } from '@trpc/client'; +import { createTRPCContext } from '@trpc/tanstack-react-query'; +import type { inferRouterOutputs } from '@trpc/server'; +import type { WrappedGastownRouter } from '@/lib/gastown/types/router'; +import { GASTOWN_URL } from '@/lib/constants'; + +// ── Type exports ────────────────────────────────────────────────────────── +// Re-export the router type so frontend components can extract output types +// without importing from the worker package directly. +export type { WrappedGastownRouter }; +export type GastownOutputs = inferRouterOutputs; + +// ── Token management ────────────────────────────────────────────────────── +// Fetches a short-lived JWT from /api/gastown/token (session-cookie-authed) +// and caches it in memory. Refreshes automatically when near expiry. + +let cachedToken: string | null = null; +let tokenExpiresAt: number = 0; +let inflightRequest: Promise | null = null; + +async function fetchToken(): Promise { + const res = await fetch('/api/gastown/token', { method: 'POST' }); + if (!res.ok) { + const body = await res.text().catch(() => ''); + throw new Error(`Failed to fetch gastown token: ${res.status} ${body}`); + } + const data: unknown = await res.json(); + const { token, expiresAt } = data as { token: string; expiresAt: string }; + cachedToken = token; + tokenExpiresAt = new Date(expiresAt).getTime(); + return token; +} + +async function getToken(): Promise { + // Return cached token if still fresh (5 min buffer) + if (cachedToken && Date.now() < tokenExpiresAt - 5 * 60 * 1000) { + return cachedToken; + } + // Deduplicate concurrent requests + if (!inflightRequest) { + inflightRequest = fetchToken().finally(() => { + inflightRequest = null; + }); + } + return inflightRequest; +} + +// ── WebSocket URL helper ────────────────────────────────────────────────── +// The worker returns relative paths for WebSocket endpoints (e.g. /api/towns/…/stream). +// The browser constructs the full ws(s):// URL using the known GASTOWN_URL. + +export function gastownWsUrl(relativePath: string): string { + const base = new URL(GASTOWN_URL); + const protocol = base.protocol === 'https:' ? 'wss:' : 'ws:'; + return `${protocol}//${base.host}${relativePath}`; +} + +// ── tRPC client ─────────────────────────────────────────────────────────── + +const gastownTrpcUrl = `${GASTOWN_URL}/trpc`; + +const headers = async () => { + const token = await getToken(); + return { Authorization: `Bearer ${token}` }; +}; + +export function createGastownTRPCClient() { + return createTRPCClient({ + links: [ + splitLink({ + condition: op => op.context.skipBatch === true, + true: httpLink({ url: gastownTrpcUrl, headers }), + false: httpBatchLink({ url: gastownTrpcUrl, headers }), + }), + ], + }); +} + +// ── React integration ───────────────────────────────────────────────────── +// Creates the same shape as the main tRPC utils (TRPCProvider, useTRPC, etc.) +// but typed against the Gastown router served by the worker. + +export const { + TRPCProvider: GastownTRPCProvider, + useTRPC: useGastownTRPC, + useTRPCClient: useGastownTRPCClient, +} = createTRPCContext(); diff --git a/src/lib/gastown/types/README.md b/src/lib/gastown/types/README.md new file mode 100644 index 0000000000..2451c3184b --- /dev/null +++ b/src/lib/gastown/types/README.md @@ -0,0 +1,23 @@ +# Gastown Worker Type Declarations + +These `.d.ts` files are **generated** from the `cloudflare-gastown` worker and should not be edited by hand. + +They exist because the Next.js app's TypeScript environment cannot resolve the worker's Cloudflare runtime types (`DurableObjectState`, `Env`, `cloudflare:workers`, etc.). The generated declarations contain only the tRPC router type signatures, stripped of those dependencies. + +**To regenerate** after changing the worker's tRPC router: + +```sh +cd cloudflare-gastown && pnpm build:types +``` + +Then copy the output and fix the import style for eslint: + +```sh +cp cloudflare-gastown/dist-types/trpc/router.d.ts src/lib/gastown/types/router.d.ts +cp cloudflare-gastown/dist-types/trpc/schemas.d.ts src/lib/gastown/types/schemas.d.ts +sed -i '' "s/^import { z }/import type { z }/" src/lib/gastown/types/schemas.d.ts +``` + +The `init.d.ts` is hand-maintained (replaces `Env` with `Record`). + +**These files are temporary.** Once the gastown UI moves into the `cloudflare-gastown` worker, the frontend and router will share a single TypeScript environment and these declarations won't be needed. diff --git a/src/lib/gastown/types/init.d.ts b/src/lib/gastown/types/init.d.ts new file mode 100644 index 0000000000..5c61d13948 --- /dev/null +++ b/src/lib/gastown/types/init.d.ts @@ -0,0 +1,8 @@ +/** + * Generated from cloudflare-gastown/src/trpc/init.ts + * Env replaced with Record to avoid CF Worker type dependency. + */ +export type TRPCContext = { + env: Record; + userId: string; +}; diff --git a/src/lib/gastown/types/router.d.ts b/src/lib/gastown/types/router.d.ts new file mode 100644 index 0000000000..70ffd0e369 --- /dev/null +++ b/src/lib/gastown/types/router.d.ts @@ -0,0 +1,906 @@ +/* eslint-disable @typescript-eslint/consistent-type-imports */ +import type { TRPCContext } from './init'; +export declare const gastownRouter: import('@trpc/server').TRPCBuiltRouter< + { + ctx: TRPCContext; + meta: object; + errorShape: import('@trpc/server').TRPCDefaultErrorShape; + transformer: false; + }, + import('@trpc/server').TRPCDecorateCreateRouterOptions<{ + createTown: import('@trpc/server').TRPCMutationProcedure<{ + input: { + name: string; + }; + output: { + id: string; + name: string; + owner_user_id: string; + created_at: string; + updated_at: string; + }; + meta: object; + }>; + listTowns: import('@trpc/server').TRPCQueryProcedure<{ + input: void; + output: { + id: string; + name: string; + owner_user_id: string; + created_at: string; + updated_at: string; + }[]; + meta: object; + }>; + getTown: import('@trpc/server').TRPCQueryProcedure<{ + input: { + townId: string; + }; + output: { + id: string; + name: string; + owner_user_id: string; + created_at: string; + updated_at: string; + }; + meta: object; + }>; + deleteTown: import('@trpc/server').TRPCMutationProcedure<{ + input: { + townId: string; + }; + output: void; + meta: object; + }>; + createRig: import('@trpc/server').TRPCMutationProcedure<{ + input: { + townId: string; + name: string; + gitUrl: string; + defaultBranch?: string; + platformIntegrationId?: string; + }; + output: { + id: string; + town_id: string; + name: string; + git_url: string; + default_branch: string; + platform_integration_id: string; + created_at: string; + updated_at: string; + }; + meta: object; + }>; + listRigs: import('@trpc/server').TRPCQueryProcedure<{ + input: { + townId: string; + }; + output: { + id: string; + town_id: string; + name: string; + git_url: string; + default_branch: string; + platform_integration_id: string; + created_at: string; + updated_at: string; + }[]; + meta: object; + }>; + getRig: import('@trpc/server').TRPCQueryProcedure<{ + input: { + rigId: string; + }; + output: { + id: string; + town_id: string; + name: string; + git_url: string; + default_branch: string; + platform_integration_id: string; + created_at: string; + updated_at: string; + agents: { + id: string; + rig_id: string | null; + role: 'mayor' | 'polecat' | 'refinery' | 'witness'; + name: string; + identity: string; + status: 'dead' | 'idle' | 'stalled' | 'working'; + current_hook_bead_id: string | null; + dispatch_attempts: number; + last_activity_at: string | null; + checkpoint?: unknown; + created_at: string; + }[]; + beads: { + bead_id: string; + type: + | 'agent' + | 'convoy' + | 'escalation' + | 'issue' + | 'merge_request' + | 'message' + | 'molecule'; + status: 'closed' | 'failed' | 'in_progress' | 'open'; + title: string; + body: string | null; + rig_id: string | null; + parent_bead_id: string | null; + assignee_agent_bead_id: string | null; + priority: 'critical' | 'high' | 'low' | 'medium'; + labels: string[]; + metadata: Record; + created_by: string | null; + created_at: string; + updated_at: string; + closed_at: string | null; + }[]; + }; + meta: object; + }>; + deleteRig: import('@trpc/server').TRPCMutationProcedure<{ + input: { + rigId: string; + }; + output: void; + meta: object; + }>; + listBeads: import('@trpc/server').TRPCQueryProcedure<{ + input: { + rigId: string; + status?: 'closed' | 'failed' | 'in_progress' | 'open'; + }; + output: { + bead_id: string; + type: + | 'agent' + | 'convoy' + | 'escalation' + | 'issue' + | 'merge_request' + | 'message' + | 'molecule'; + status: 'closed' | 'failed' | 'in_progress' | 'open'; + title: string; + body: string | null; + rig_id: string | null; + parent_bead_id: string | null; + assignee_agent_bead_id: string | null; + priority: 'critical' | 'high' | 'low' | 'medium'; + labels: string[]; + metadata: Record; + created_by: string | null; + created_at: string; + updated_at: string; + closed_at: string | null; + }[]; + meta: object; + }>; + deleteBead: import('@trpc/server').TRPCMutationProcedure<{ + input: { + rigId: string; + beadId: string; + }; + output: void; + meta: object; + }>; + listAgents: import('@trpc/server').TRPCQueryProcedure<{ + input: { + rigId: string; + }; + output: { + id: string; + rig_id: string | null; + role: 'mayor' | 'polecat' | 'refinery' | 'witness'; + name: string; + identity: string; + status: 'dead' | 'idle' | 'stalled' | 'working'; + current_hook_bead_id: string | null; + dispatch_attempts: number; + last_activity_at: string | null; + checkpoint?: unknown; + created_at: string; + }[]; + meta: object; + }>; + deleteAgent: import('@trpc/server').TRPCMutationProcedure<{ + input: { + rigId: string; + agentId: string; + }; + output: void; + meta: object; + }>; + sling: import('@trpc/server').TRPCMutationProcedure<{ + input: { + rigId: string; + title: string; + body?: string; + model?: string; + }; + output: { + bead: { + bead_id: string; + type: + | 'agent' + | 'convoy' + | 'escalation' + | 'issue' + | 'merge_request' + | 'message' + | 'molecule'; + status: 'closed' | 'failed' | 'in_progress' | 'open'; + title: string; + body: string | null; + rig_id: string | null; + parent_bead_id: string | null; + assignee_agent_bead_id: string | null; + priority: 'critical' | 'high' | 'low' | 'medium'; + labels: string[]; + metadata: Record; + created_by: string | null; + created_at: string; + updated_at: string; + closed_at: string | null; + }; + agent: { + id: string; + rig_id: string | null; + role: 'mayor' | 'polecat' | 'refinery' | 'witness'; + name: string; + identity: string; + status: 'dead' | 'idle' | 'stalled' | 'working'; + current_hook_bead_id: string | null; + dispatch_attempts: number; + last_activity_at: string | null; + checkpoint?: unknown; + created_at: string; + }; + }; + meta: object; + }>; + sendMessage: import('@trpc/server').TRPCMutationProcedure<{ + input: { + townId: string; + message: string; + model?: string; + rigId?: string; + }; + output: { + agentId: string; + sessionStatus: 'active' | 'idle' | 'starting'; + }; + meta: object; + }>; + getMayorStatus: import('@trpc/server').TRPCQueryProcedure<{ + input: { + townId: string; + }; + output: { + configured: boolean; + townId?: string; + session?: { + agentId: string; + sessionId: string; + status: 'active' | 'idle' | 'starting'; + lastActivityAt: string; + }; + }; + meta: object; + }>; + ensureMayor: import('@trpc/server').TRPCMutationProcedure<{ + input: { + townId: string; + }; + output: { + agentId: string; + sessionStatus: 'active' | 'idle' | 'starting'; + }; + meta: object; + }>; + getAgentStreamUrl: import('@trpc/server').TRPCQueryProcedure<{ + input: { + agentId: string; + townId: string; + }; + output: { + url: string; + ticket: string; + }; + meta: object; + }>; + createPtySession: import('@trpc/server').TRPCMutationProcedure<{ + input: { + townId: string; + agentId: string; + }; + output: { + pty: { + [x: string]: unknown; + id: string; + }; + wsUrl: string; + }; + meta: object; + }>; + resizePtySession: import('@trpc/server').TRPCMutationProcedure<{ + input: { + townId: string; + agentId: string; + ptyId: string; + cols: number; + rows: number; + }; + output: void; + meta: object; + }>; + getTownConfig: import('@trpc/server').TRPCQueryProcedure<{ + input: { + townId: string; + }; + output: { + env_vars: Record; + git_auth: { + github_token?: string; + gitlab_token?: string; + gitlab_instance_url?: string; + platform_integration_id?: string; + }; + owner_user_id?: string; + kilocode_token?: string; + default_model?: string; + small_model?: string; + max_polecats_per_rig?: number; + merge_strategy: 'direct' | 'pr'; + refinery?: { + gates: string[]; + auto_merge: boolean; + require_clean_merge: boolean; + }; + alarm_interval_active?: number; + alarm_interval_idle?: number; + container?: { + sleep_after_minutes?: number; + }; + }; + meta: object; + }>; + updateTownConfig: import('@trpc/server').TRPCMutationProcedure<{ + input: { + townId: string; + config: Record; + }; + output: { + env_vars: Record; + git_auth: { + github_token?: string; + gitlab_token?: string; + gitlab_instance_url?: string; + platform_integration_id?: string; + }; + owner_user_id?: string; + kilocode_token?: string; + default_model?: string; + small_model?: string; + max_polecats_per_rig?: number; + merge_strategy: 'direct' | 'pr'; + refinery?: { + gates: string[]; + auto_merge: boolean; + require_clean_merge: boolean; + }; + alarm_interval_active?: number; + alarm_interval_idle?: number; + container?: { + sleep_after_minutes?: number; + }; + }; + meta: object; + }>; + getBeadEvents: import('@trpc/server').TRPCQueryProcedure<{ + input: { + rigId: string; + beadId?: string; + since?: string; + limit?: number; + }; + output: { + bead_event_id: string; + bead_id: string; + agent_id: string | null; + event_type: string; + old_value: string | null; + new_value: string | null; + metadata: Record; + created_at: string; + rig_id: string | null; + rig_name?: string; + }[]; + meta: object; + }>; + getTownEvents: import('@trpc/server').TRPCQueryProcedure<{ + input: { + townId: string; + since?: string; + limit?: number; + }; + output: { + bead_event_id: string; + bead_id: string; + agent_id: string | null; + event_type: string; + old_value: string | null; + new_value: string | null; + metadata: Record; + created_at: string; + rig_id: string | null; + rig_name?: string; + }[]; + meta: object; + }>; + }> +>; +export type GastownRouter = typeof gastownRouter; +/** + * Wrapped router that nests gastownRouter under a `gastown` key. + * This preserves the `trpc.gastown.X` call pattern on the frontend, + * matching the existing RootRouter shape so components don't need + * to change their procedure paths. + */ +export declare const wrappedGastownRouter: import('@trpc/server').TRPCBuiltRouter< + { + ctx: TRPCContext; + meta: object; + errorShape: import('@trpc/server').TRPCDefaultErrorShape; + transformer: false; + }, + import('@trpc/server').TRPCDecorateCreateRouterOptions<{ + gastown: import('@trpc/server').TRPCBuiltRouter< + { + ctx: TRPCContext; + meta: object; + errorShape: import('@trpc/server').TRPCDefaultErrorShape; + transformer: false; + }, + import('@trpc/server').TRPCDecorateCreateRouterOptions<{ + createTown: import('@trpc/server').TRPCMutationProcedure<{ + input: { + name: string; + }; + output: { + id: string; + name: string; + owner_user_id: string; + created_at: string; + updated_at: string; + }; + meta: object; + }>; + listTowns: import('@trpc/server').TRPCQueryProcedure<{ + input: void; + output: { + id: string; + name: string; + owner_user_id: string; + created_at: string; + updated_at: string; + }[]; + meta: object; + }>; + getTown: import('@trpc/server').TRPCQueryProcedure<{ + input: { + townId: string; + }; + output: { + id: string; + name: string; + owner_user_id: string; + created_at: string; + updated_at: string; + }; + meta: object; + }>; + deleteTown: import('@trpc/server').TRPCMutationProcedure<{ + input: { + townId: string; + }; + output: void; + meta: object; + }>; + createRig: import('@trpc/server').TRPCMutationProcedure<{ + input: { + townId: string; + name: string; + gitUrl: string; + defaultBranch?: string; + platformIntegrationId?: string; + }; + output: { + id: string; + town_id: string; + name: string; + git_url: string; + default_branch: string; + platform_integration_id: string; + created_at: string; + updated_at: string; + }; + meta: object; + }>; + listRigs: import('@trpc/server').TRPCQueryProcedure<{ + input: { + townId: string; + }; + output: { + id: string; + town_id: string; + name: string; + git_url: string; + default_branch: string; + platform_integration_id: string; + created_at: string; + updated_at: string; + }[]; + meta: object; + }>; + getRig: import('@trpc/server').TRPCQueryProcedure<{ + input: { + rigId: string; + }; + output: { + id: string; + town_id: string; + name: string; + git_url: string; + default_branch: string; + platform_integration_id: string; + created_at: string; + updated_at: string; + agents: { + id: string; + rig_id: string | null; + role: 'mayor' | 'polecat' | 'refinery' | 'witness'; + name: string; + identity: string; + status: 'dead' | 'idle' | 'stalled' | 'working'; + current_hook_bead_id: string | null; + dispatch_attempts: number; + last_activity_at: string | null; + checkpoint?: unknown; + created_at: string; + }[]; + beads: { + bead_id: string; + type: + | 'agent' + | 'convoy' + | 'escalation' + | 'issue' + | 'merge_request' + | 'message' + | 'molecule'; + status: 'closed' | 'failed' | 'in_progress' | 'open'; + title: string; + body: string | null; + rig_id: string | null; + parent_bead_id: string | null; + assignee_agent_bead_id: string | null; + priority: 'critical' | 'high' | 'low' | 'medium'; + labels: string[]; + metadata: Record; + created_by: string | null; + created_at: string; + updated_at: string; + closed_at: string | null; + }[]; + }; + meta: object; + }>; + deleteRig: import('@trpc/server').TRPCMutationProcedure<{ + input: { + rigId: string; + }; + output: void; + meta: object; + }>; + listBeads: import('@trpc/server').TRPCQueryProcedure<{ + input: { + rigId: string; + status?: 'closed' | 'failed' | 'in_progress' | 'open'; + }; + output: { + bead_id: string; + type: + | 'agent' + | 'convoy' + | 'escalation' + | 'issue' + | 'merge_request' + | 'message' + | 'molecule'; + status: 'closed' | 'failed' | 'in_progress' | 'open'; + title: string; + body: string | null; + rig_id: string | null; + parent_bead_id: string | null; + assignee_agent_bead_id: string | null; + priority: 'critical' | 'high' | 'low' | 'medium'; + labels: string[]; + metadata: Record; + created_by: string | null; + created_at: string; + updated_at: string; + closed_at: string | null; + }[]; + meta: object; + }>; + deleteBead: import('@trpc/server').TRPCMutationProcedure<{ + input: { + rigId: string; + beadId: string; + }; + output: void; + meta: object; + }>; + listAgents: import('@trpc/server').TRPCQueryProcedure<{ + input: { + rigId: string; + }; + output: { + id: string; + rig_id: string | null; + role: 'mayor' | 'polecat' | 'refinery' | 'witness'; + name: string; + identity: string; + status: 'dead' | 'idle' | 'stalled' | 'working'; + current_hook_bead_id: string | null; + dispatch_attempts: number; + last_activity_at: string | null; + checkpoint?: unknown; + created_at: string; + }[]; + meta: object; + }>; + deleteAgent: import('@trpc/server').TRPCMutationProcedure<{ + input: { + rigId: string; + agentId: string; + }; + output: void; + meta: object; + }>; + sling: import('@trpc/server').TRPCMutationProcedure<{ + input: { + rigId: string; + title: string; + body?: string; + model?: string; + }; + output: { + bead: { + bead_id: string; + type: + | 'agent' + | 'convoy' + | 'escalation' + | 'issue' + | 'merge_request' + | 'message' + | 'molecule'; + status: 'closed' | 'failed' | 'in_progress' | 'open'; + title: string; + body: string | null; + rig_id: string | null; + parent_bead_id: string | null; + assignee_agent_bead_id: string | null; + priority: 'critical' | 'high' | 'low' | 'medium'; + labels: string[]; + metadata: Record; + created_by: string | null; + created_at: string; + updated_at: string; + closed_at: string | null; + }; + agent: { + id: string; + rig_id: string | null; + role: 'mayor' | 'polecat' | 'refinery' | 'witness'; + name: string; + identity: string; + status: 'dead' | 'idle' | 'stalled' | 'working'; + current_hook_bead_id: string | null; + dispatch_attempts: number; + last_activity_at: string | null; + checkpoint?: unknown; + created_at: string; + }; + }; + meta: object; + }>; + sendMessage: import('@trpc/server').TRPCMutationProcedure<{ + input: { + townId: string; + message: string; + model?: string; + rigId?: string; + }; + output: { + agentId: string; + sessionStatus: 'active' | 'idle' | 'starting'; + }; + meta: object; + }>; + getMayorStatus: import('@trpc/server').TRPCQueryProcedure<{ + input: { + townId: string; + }; + output: { + configured: boolean; + townId?: string; + session?: { + agentId: string; + sessionId: string; + status: 'active' | 'idle' | 'starting'; + lastActivityAt: string; + }; + }; + meta: object; + }>; + ensureMayor: import('@trpc/server').TRPCMutationProcedure<{ + input: { + townId: string; + }; + output: { + agentId: string; + sessionStatus: 'active' | 'idle' | 'starting'; + }; + meta: object; + }>; + getAgentStreamUrl: import('@trpc/server').TRPCQueryProcedure<{ + input: { + agentId: string; + townId: string; + }; + output: { + url: string; + ticket: string; + }; + meta: object; + }>; + createPtySession: import('@trpc/server').TRPCMutationProcedure<{ + input: { + townId: string; + agentId: string; + }; + output: { + pty: { + [x: string]: unknown; + id: string; + }; + wsUrl: string; + }; + meta: object; + }>; + resizePtySession: import('@trpc/server').TRPCMutationProcedure<{ + input: { + townId: string; + agentId: string; + ptyId: string; + cols: number; + rows: number; + }; + output: void; + meta: object; + }>; + getTownConfig: import('@trpc/server').TRPCQueryProcedure<{ + input: { + townId: string; + }; + output: { + env_vars: Record; + git_auth: { + github_token?: string; + gitlab_token?: string; + gitlab_instance_url?: string; + platform_integration_id?: string; + }; + owner_user_id?: string; + kilocode_token?: string; + default_model?: string; + small_model?: string; + max_polecats_per_rig?: number; + merge_strategy: 'direct' | 'pr'; + refinery?: { + gates: string[]; + auto_merge: boolean; + require_clean_merge: boolean; + }; + alarm_interval_active?: number; + alarm_interval_idle?: number; + container?: { + sleep_after_minutes?: number; + }; + }; + meta: object; + }>; + updateTownConfig: import('@trpc/server').TRPCMutationProcedure<{ + input: { + townId: string; + config: Record; + }; + output: { + env_vars: Record; + git_auth: { + github_token?: string; + gitlab_token?: string; + gitlab_instance_url?: string; + platform_integration_id?: string; + }; + owner_user_id?: string; + kilocode_token?: string; + default_model?: string; + small_model?: string; + max_polecats_per_rig?: number; + merge_strategy: 'direct' | 'pr'; + refinery?: { + gates: string[]; + auto_merge: boolean; + require_clean_merge: boolean; + }; + alarm_interval_active?: number; + alarm_interval_idle?: number; + container?: { + sleep_after_minutes?: number; + }; + }; + meta: object; + }>; + getBeadEvents: import('@trpc/server').TRPCQueryProcedure<{ + input: { + rigId: string; + beadId?: string; + since?: string; + limit?: number; + }; + output: { + bead_event_id: string; + bead_id: string; + agent_id: string | null; + event_type: string; + old_value: string | null; + new_value: string | null; + metadata: Record; + created_at: string; + rig_id: string | null; + rig_name?: string; + }[]; + meta: object; + }>; + getTownEvents: import('@trpc/server').TRPCQueryProcedure<{ + input: { + townId: string; + since?: string; + limit?: number; + }; + output: { + bead_event_id: string; + bead_id: string; + agent_id: string | null; + event_type: string; + old_value: string | null; + new_value: string | null; + metadata: Record; + created_at: string; + rig_id: string | null; + rig_name?: string; + }[]; + meta: object; + }>; + }> + >; + }> +>; +export type WrappedGastownRouter = typeof wrappedGastownRouter; diff --git a/src/lib/gastown/types/schemas.d.ts b/src/lib/gastown/types/schemas.d.ts new file mode 100644 index 0000000000..9a91ebadd5 --- /dev/null +++ b/src/lib/gastown/types/schemas.d.ts @@ -0,0 +1,642 @@ +import type { z } from 'zod'; +export declare const TownOutput: z.ZodObject< + { + id: z.ZodString; + name: z.ZodString; + owner_user_id: z.ZodString; + created_at: z.ZodString; + updated_at: z.ZodString; + }, + z.core.$strip +>; +export declare const RigOutput: z.ZodObject< + { + id: z.ZodString; + town_id: z.ZodString; + name: z.ZodString; + git_url: z.ZodString; + default_branch: z.ZodString; + platform_integration_id: z.ZodDefault>>; + created_at: z.ZodString; + updated_at: z.ZodString; + }, + z.core.$strip +>; +export declare const BeadOutput: z.ZodObject< + { + bead_id: z.ZodString; + type: z.ZodEnum<{ + agent: 'agent'; + convoy: 'convoy'; + escalation: 'escalation'; + issue: 'issue'; + merge_request: 'merge_request'; + message: 'message'; + molecule: 'molecule'; + }>; + status: z.ZodEnum<{ + closed: 'closed'; + failed: 'failed'; + in_progress: 'in_progress'; + open: 'open'; + }>; + title: z.ZodString; + body: z.ZodNullable; + rig_id: z.ZodNullable; + parent_bead_id: z.ZodNullable; + assignee_agent_bead_id: z.ZodNullable; + priority: z.ZodEnum<{ + critical: 'critical'; + high: 'high'; + low: 'low'; + medium: 'medium'; + }>; + labels: z.ZodArray; + metadata: z.ZodRecord; + created_by: z.ZodNullable; + created_at: z.ZodString; + updated_at: z.ZodString; + closed_at: z.ZodNullable; + }, + z.core.$strip +>; +export declare const AgentOutput: z.ZodObject< + { + id: z.ZodString; + rig_id: z.ZodNullable; + role: z.ZodEnum<{ + mayor: 'mayor'; + polecat: 'polecat'; + refinery: 'refinery'; + witness: 'witness'; + }>; + name: z.ZodString; + identity: z.ZodString; + status: z.ZodEnum<{ + dead: 'dead'; + idle: 'idle'; + stalled: 'stalled'; + working: 'working'; + }>; + current_hook_bead_id: z.ZodNullable; + dispatch_attempts: z.ZodDefault; + last_activity_at: z.ZodNullable; + checkpoint: z.ZodOptional; + created_at: z.ZodString; + }, + z.core.$strip +>; +export declare const BeadEventOutput: z.ZodObject< + { + bead_event_id: z.ZodString; + bead_id: z.ZodString; + agent_id: z.ZodNullable; + event_type: z.ZodString; + old_value: z.ZodNullable; + new_value: z.ZodNullable; + metadata: z.ZodRecord; + created_at: z.ZodString; + rig_id: z.ZodOptional; + rig_name: z.ZodOptional; + }, + z.core.$strip +>; +export declare const MayorSendResultOutput: z.ZodObject< + { + agentId: z.ZodString; + sessionStatus: z.ZodEnum<{ + active: 'active'; + idle: 'idle'; + starting: 'starting'; + }>; + }, + z.core.$strip +>; +export declare const MayorStatusOutput: z.ZodObject< + { + configured: z.ZodBoolean; + townId: z.ZodNullable; + session: z.ZodNullable< + z.ZodObject< + { + agentId: z.ZodString; + sessionId: z.ZodString; + status: z.ZodEnum<{ + active: 'active'; + idle: 'idle'; + starting: 'starting'; + }>; + lastActivityAt: z.ZodString; + }, + z.core.$strip + > + >; + }, + z.core.$strip +>; +export declare const StreamTicketOutput: z.ZodObject< + { + url: z.ZodString; + ticket: z.ZodString; + }, + z.core.$strip +>; +export declare const PtySessionOutput: z.ZodObject< + { + pty: z.ZodObject< + { + id: z.ZodString; + }, + z.core.$loose + >; + wsUrl: z.ZodString; + }, + z.core.$strip +>; +export declare const SlingResultOutput: z.ZodObject< + { + bead: z.ZodObject< + { + bead_id: z.ZodString; + type: z.ZodEnum<{ + agent: 'agent'; + convoy: 'convoy'; + escalation: 'escalation'; + issue: 'issue'; + merge_request: 'merge_request'; + message: 'message'; + molecule: 'molecule'; + }>; + status: z.ZodEnum<{ + closed: 'closed'; + failed: 'failed'; + in_progress: 'in_progress'; + open: 'open'; + }>; + title: z.ZodString; + body: z.ZodNullable; + rig_id: z.ZodNullable; + parent_bead_id: z.ZodNullable; + assignee_agent_bead_id: z.ZodNullable; + priority: z.ZodEnum<{ + critical: 'critical'; + high: 'high'; + low: 'low'; + medium: 'medium'; + }>; + labels: z.ZodArray; + metadata: z.ZodRecord; + created_by: z.ZodNullable; + created_at: z.ZodString; + updated_at: z.ZodString; + closed_at: z.ZodNullable; + }, + z.core.$strip + >; + agent: z.ZodObject< + { + id: z.ZodString; + rig_id: z.ZodNullable; + role: z.ZodEnum<{ + mayor: 'mayor'; + polecat: 'polecat'; + refinery: 'refinery'; + witness: 'witness'; + }>; + name: z.ZodString; + identity: z.ZodString; + status: z.ZodEnum<{ + dead: 'dead'; + idle: 'idle'; + stalled: 'stalled'; + working: 'working'; + }>; + current_hook_bead_id: z.ZodNullable; + dispatch_attempts: z.ZodDefault; + last_activity_at: z.ZodNullable; + checkpoint: z.ZodOptional; + created_at: z.ZodString; + }, + z.core.$strip + >; + }, + z.core.$strip +>; +export declare const RigDetailOutput: z.ZodObject< + { + id: z.ZodString; + town_id: z.ZodString; + name: z.ZodString; + git_url: z.ZodString; + default_branch: z.ZodString; + platform_integration_id: z.ZodDefault>>; + created_at: z.ZodString; + updated_at: z.ZodString; + agents: z.ZodArray< + z.ZodObject< + { + id: z.ZodString; + rig_id: z.ZodNullable; + role: z.ZodEnum<{ + mayor: 'mayor'; + polecat: 'polecat'; + refinery: 'refinery'; + witness: 'witness'; + }>; + name: z.ZodString; + identity: z.ZodString; + status: z.ZodEnum<{ + dead: 'dead'; + idle: 'idle'; + stalled: 'stalled'; + working: 'working'; + }>; + current_hook_bead_id: z.ZodNullable; + dispatch_attempts: z.ZodDefault; + last_activity_at: z.ZodNullable; + checkpoint: z.ZodOptional; + created_at: z.ZodString; + }, + z.core.$strip + > + >; + beads: z.ZodArray< + z.ZodObject< + { + bead_id: z.ZodString; + type: z.ZodEnum<{ + agent: 'agent'; + convoy: 'convoy'; + escalation: 'escalation'; + issue: 'issue'; + merge_request: 'merge_request'; + message: 'message'; + molecule: 'molecule'; + }>; + status: z.ZodEnum<{ + closed: 'closed'; + failed: 'failed'; + in_progress: 'in_progress'; + open: 'open'; + }>; + title: z.ZodString; + body: z.ZodNullable; + rig_id: z.ZodNullable; + parent_bead_id: z.ZodNullable; + assignee_agent_bead_id: z.ZodNullable; + priority: z.ZodEnum<{ + critical: 'critical'; + high: 'high'; + low: 'low'; + medium: 'medium'; + }>; + labels: z.ZodArray; + metadata: z.ZodRecord; + created_by: z.ZodNullable; + created_at: z.ZodString; + updated_at: z.ZodString; + closed_at: z.ZodNullable; + }, + z.core.$strip + > + >; + }, + z.core.$strip +>; +export declare const RpcTownOutput: z.ZodPipe< + z.ZodAny, + z.ZodObject< + { + id: z.ZodString; + name: z.ZodString; + owner_user_id: z.ZodString; + created_at: z.ZodString; + updated_at: z.ZodString; + }, + z.core.$strip + > +>; +export declare const RpcRigOutput: z.ZodPipe< + z.ZodAny, + z.ZodObject< + { + id: z.ZodString; + town_id: z.ZodString; + name: z.ZodString; + git_url: z.ZodString; + default_branch: z.ZodString; + platform_integration_id: z.ZodDefault>>; + created_at: z.ZodString; + updated_at: z.ZodString; + }, + z.core.$strip + > +>; +export declare const RpcBeadOutput: z.ZodPipe< + z.ZodAny, + z.ZodObject< + { + bead_id: z.ZodString; + type: z.ZodEnum<{ + agent: 'agent'; + convoy: 'convoy'; + escalation: 'escalation'; + issue: 'issue'; + merge_request: 'merge_request'; + message: 'message'; + molecule: 'molecule'; + }>; + status: z.ZodEnum<{ + closed: 'closed'; + failed: 'failed'; + in_progress: 'in_progress'; + open: 'open'; + }>; + title: z.ZodString; + body: z.ZodNullable; + rig_id: z.ZodNullable; + parent_bead_id: z.ZodNullable; + assignee_agent_bead_id: z.ZodNullable; + priority: z.ZodEnum<{ + critical: 'critical'; + high: 'high'; + low: 'low'; + medium: 'medium'; + }>; + labels: z.ZodArray; + metadata: z.ZodRecord; + created_by: z.ZodNullable; + created_at: z.ZodString; + updated_at: z.ZodString; + closed_at: z.ZodNullable; + }, + z.core.$strip + > +>; +export declare const RpcAgentOutput: z.ZodPipe< + z.ZodAny, + z.ZodObject< + { + id: z.ZodString; + rig_id: z.ZodNullable; + role: z.ZodEnum<{ + mayor: 'mayor'; + polecat: 'polecat'; + refinery: 'refinery'; + witness: 'witness'; + }>; + name: z.ZodString; + identity: z.ZodString; + status: z.ZodEnum<{ + dead: 'dead'; + idle: 'idle'; + stalled: 'stalled'; + working: 'working'; + }>; + current_hook_bead_id: z.ZodNullable; + dispatch_attempts: z.ZodDefault; + last_activity_at: z.ZodNullable; + checkpoint: z.ZodOptional; + created_at: z.ZodString; + }, + z.core.$strip + > +>; +export declare const RpcBeadEventOutput: z.ZodPipe< + z.ZodAny, + z.ZodObject< + { + bead_event_id: z.ZodString; + bead_id: z.ZodString; + agent_id: z.ZodNullable; + event_type: z.ZodString; + old_value: z.ZodNullable; + new_value: z.ZodNullable; + metadata: z.ZodRecord; + created_at: z.ZodString; + rig_id: z.ZodOptional; + rig_name: z.ZodOptional; + }, + z.core.$strip + > +>; +export declare const RpcMayorSendResultOutput: z.ZodPipe< + z.ZodAny, + z.ZodObject< + { + agentId: z.ZodString; + sessionStatus: z.ZodEnum<{ + active: 'active'; + idle: 'idle'; + starting: 'starting'; + }>; + }, + z.core.$strip + > +>; +export declare const RpcMayorStatusOutput: z.ZodPipe< + z.ZodAny, + z.ZodObject< + { + configured: z.ZodBoolean; + townId: z.ZodNullable; + session: z.ZodNullable< + z.ZodObject< + { + agentId: z.ZodString; + sessionId: z.ZodString; + status: z.ZodEnum<{ + active: 'active'; + idle: 'idle'; + starting: 'starting'; + }>; + lastActivityAt: z.ZodString; + }, + z.core.$strip + > + >; + }, + z.core.$strip + > +>; +export declare const RpcStreamTicketOutput: z.ZodPipe< + z.ZodAny, + z.ZodObject< + { + url: z.ZodString; + ticket: z.ZodString; + }, + z.core.$strip + > +>; +export declare const RpcPtySessionOutput: z.ZodPipe< + z.ZodAny, + z.ZodObject< + { + pty: z.ZodObject< + { + id: z.ZodString; + }, + z.core.$loose + >; + wsUrl: z.ZodString; + }, + z.core.$strip + > +>; +export declare const RpcSlingResultOutput: z.ZodPipe< + z.ZodAny, + z.ZodObject< + { + bead: z.ZodObject< + { + bead_id: z.ZodString; + type: z.ZodEnum<{ + agent: 'agent'; + convoy: 'convoy'; + escalation: 'escalation'; + issue: 'issue'; + merge_request: 'merge_request'; + message: 'message'; + molecule: 'molecule'; + }>; + status: z.ZodEnum<{ + closed: 'closed'; + failed: 'failed'; + in_progress: 'in_progress'; + open: 'open'; + }>; + title: z.ZodString; + body: z.ZodNullable; + rig_id: z.ZodNullable; + parent_bead_id: z.ZodNullable; + assignee_agent_bead_id: z.ZodNullable; + priority: z.ZodEnum<{ + critical: 'critical'; + high: 'high'; + low: 'low'; + medium: 'medium'; + }>; + labels: z.ZodArray; + metadata: z.ZodRecord; + created_by: z.ZodNullable; + created_at: z.ZodString; + updated_at: z.ZodString; + closed_at: z.ZodNullable; + }, + z.core.$strip + >; + agent: z.ZodObject< + { + id: z.ZodString; + rig_id: z.ZodNullable; + role: z.ZodEnum<{ + mayor: 'mayor'; + polecat: 'polecat'; + refinery: 'refinery'; + witness: 'witness'; + }>; + name: z.ZodString; + identity: z.ZodString; + status: z.ZodEnum<{ + dead: 'dead'; + idle: 'idle'; + stalled: 'stalled'; + working: 'working'; + }>; + current_hook_bead_id: z.ZodNullable; + dispatch_attempts: z.ZodDefault; + last_activity_at: z.ZodNullable; + checkpoint: z.ZodOptional; + created_at: z.ZodString; + }, + z.core.$strip + >; + }, + z.core.$strip + > +>; +export declare const RpcRigDetailOutput: z.ZodPipe< + z.ZodAny, + z.ZodObject< + { + id: z.ZodString; + town_id: z.ZodString; + name: z.ZodString; + git_url: z.ZodString; + default_branch: z.ZodString; + platform_integration_id: z.ZodDefault>>; + created_at: z.ZodString; + updated_at: z.ZodString; + agents: z.ZodArray< + z.ZodObject< + { + id: z.ZodString; + rig_id: z.ZodNullable; + role: z.ZodEnum<{ + mayor: 'mayor'; + polecat: 'polecat'; + refinery: 'refinery'; + witness: 'witness'; + }>; + name: z.ZodString; + identity: z.ZodString; + status: z.ZodEnum<{ + dead: 'dead'; + idle: 'idle'; + stalled: 'stalled'; + working: 'working'; + }>; + current_hook_bead_id: z.ZodNullable; + dispatch_attempts: z.ZodDefault; + last_activity_at: z.ZodNullable; + checkpoint: z.ZodOptional; + created_at: z.ZodString; + }, + z.core.$strip + > + >; + beads: z.ZodArray< + z.ZodObject< + { + bead_id: z.ZodString; + type: z.ZodEnum<{ + agent: 'agent'; + convoy: 'convoy'; + escalation: 'escalation'; + issue: 'issue'; + merge_request: 'merge_request'; + message: 'message'; + molecule: 'molecule'; + }>; + status: z.ZodEnum<{ + closed: 'closed'; + failed: 'failed'; + in_progress: 'in_progress'; + open: 'open'; + }>; + title: z.ZodString; + body: z.ZodNullable; + rig_id: z.ZodNullable; + parent_bead_id: z.ZodNullable; + assignee_agent_bead_id: z.ZodNullable; + priority: z.ZodEnum<{ + critical: 'critical'; + high: 'high'; + low: 'low'; + medium: 'medium'; + }>; + labels: z.ZodArray; + metadata: z.ZodRecord; + created_by: z.ZodNullable; + created_at: z.ZodString; + updated_at: z.ZodString; + closed_at: z.ZodNullable; + }, + z.core.$strip + > + >; + }, + z.core.$strip + > +>; diff --git a/src/lib/tokens.ts b/src/lib/tokens.ts index c0ccdd79fa..3ed0e6260c 100644 --- a/src/lib/tokens.ts +++ b/src/lib/tokens.ts @@ -13,6 +13,7 @@ export type JWTTokenExtraPayload = { organizationId?: string; organizationRole?: OrganizationRole; internalApiUse?: boolean; + isAdmin?: boolean; createdOnPlatform?: string; tokenSource?: string; }; diff --git a/src/routers/gastown-router.ts b/src/routers/gastown-router.ts deleted file mode 100644 index dd878a8c83..0000000000 --- a/src/routers/gastown-router.ts +++ /dev/null @@ -1,583 +0,0 @@ -import 'server-only'; -import { adminProcedure, createTRPCRouter } from '@/lib/trpc/init'; -import { TRPCError } from '@trpc/server'; -import { z } from 'zod'; -import * as gastown from '@/lib/gastown/gastown-client'; -import { GastownApiError } from '@/lib/gastown/gastown-client'; -import { generateApiToken, TOKEN_EXPIRY } from '@/lib/tokens'; -import { GASTOWN_SERVICE_URL } from '@/lib/config.server'; -import { - resolveGitCredentialsFromIntegration, - resolveIntegrationIdFromGitUrl, - refreshGitCredentials, -} from '@/lib/gastown/git-credentials'; - -const LOG_PREFIX = '[gastown-router]'; - -/** - * Refresh git credentials for a town, writing fresh tokens to the town config. - * Looks up the platform_integration_id from the town config first, falling - * back to the first rig that has one. This handles the case where createRig - * failed to write credentials to the town config initially. - */ -async function refreshTownGitCredentials(townId: string, userId: string): Promise { - const townConfig = await withGastownError(() => gastown.getTownConfig(townId)); - let integrationId = townConfig.git_auth.platform_integration_id; - - console.log( - `${LOG_PREFIX} refreshTownGitCredentials: town=${townId} configIntegration=${integrationId ?? 'none'} git_auth_keys=[${Object.entries( - townConfig.git_auth - ) - .filter(([, v]) => v) - .map(([k]) => k) - .join(',')}]` - ); - - if (!integrationId) { - const rigList = await withGastownError(() => gastown.listRigs(userId, townId)); - console.log( - `${LOG_PREFIX} refreshTownGitCredentials: checking ${rigList.length} rigs for platform_integration_id: ${rigList.map(r => `${r.id}=${r.platform_integration_id ?? 'null'}`).join(', ')}` - ); - const rigWithIntegration = rigList.find(r => r.platform_integration_id); - if (rigWithIntegration) { - integrationId = rigWithIntegration.platform_integration_id ?? undefined; - } - } - - if (!integrationId) { - console.warn( - `${LOG_PREFIX} refreshTownGitCredentials: no platform_integration_id found for town=${townId} — git credentials will not be refreshed` - ); - return; - } - - console.log( - `${LOG_PREFIX} refreshTownGitCredentials: refreshing credentials for integration=${integrationId}` - ); - const freshCredentials = await refreshGitCredentials(integrationId); - if (freshCredentials) { - await withGastownError(() => - gastown.updateTownConfig(townId, { - git_auth: { - ...freshCredentials, - platform_integration_id: integrationId, - }, - }) - ); - console.log( - `${LOG_PREFIX} refreshTownGitCredentials: wrote fresh credentials for town=${townId} hasGithub=${!!freshCredentials.github_token} hasGitlab=${!!freshCredentials.gitlab_token}` - ); - } else { - console.warn( - `${LOG_PREFIX} refreshTownGitCredentials: refreshGitCredentials returned null for integration=${integrationId}` - ); - } -} - -/** - * Wraps a gastown client call and converts GastownApiError into TRPCError - * with an appropriate code. - */ -async function withGastownError(fn: () => Promise): Promise { - try { - return await fn(); - } catch (err) { - if (err instanceof GastownApiError) { - console.error(`${LOG_PREFIX} GastownApiError: status=${err.status} message="${err.message}"`); - const code = - err.status === 404 - ? 'NOT_FOUND' - : err.status === 400 - ? 'BAD_REQUEST' - : err.status === 403 - ? 'FORBIDDEN' - : 'INTERNAL_SERVER_ERROR'; - throw new TRPCError({ code, message: err.message }); - } - console.error(`${LOG_PREFIX} Unexpected error:`, err); - throw err; - } -} - -export const gastownRouter = createTRPCRouter({ - // ── Towns ─────────────────────────────────────────────────────────────── - - createTown: adminProcedure - .input( - z.object({ - name: z.string().min(1).max(64), - }) - ) - .mutation(async ({ ctx, input }) => { - const town = await withGastownError(() => gastown.createTown(ctx.user.id, input.name)); - - // Store the user's API token on the town config so the mayor can - // authenticate with the Kilo gateway without needing a rig. - const kilocodeToken = generateApiToken(ctx.user, undefined, { - expiresIn: TOKEN_EXPIRY.thirtyDays, - }); - await withGastownError(() => - gastown.updateTownConfig(town.id, { - kilocode_token: kilocodeToken, - owner_user_id: ctx.user.id, - }) - ); - - return town; - }), - - listTowns: adminProcedure.query(async ({ ctx }) => { - return withGastownError(() => gastown.listTowns(ctx.user.id)); - }), - - getTown: adminProcedure - .input(z.object({ townId: z.string().uuid() })) - .query(async ({ ctx, input }) => { - const town = await withGastownError(() => gastown.getTown(ctx.user.id, input.townId)); - if (town.owner_user_id !== ctx.user.id) { - throw new TRPCError({ code: 'FORBIDDEN', message: 'Not your town' }); - } - return town; - }), - - // ── Rigs ──────────────────────────────────────────────────────────────── - - createRig: adminProcedure - .input( - z.object({ - townId: z.string().uuid(), - name: z.string().min(1).max(64), - gitUrl: z.string().url(), - defaultBranch: z.string().default('main'), - platformIntegrationId: z.string().uuid().optional(), - }) - ) - .mutation(async ({ ctx, input }) => { - // Verify ownership - const town = await withGastownError(() => gastown.getTown(ctx.user.id, input.townId)); - if (town.owner_user_id !== ctx.user.id) { - throw new TRPCError({ code: 'FORBIDDEN', message: 'Not your town' }); - } - - // Auto-detect the platform integration from the git URL when not - // explicitly provided. This is the server-side safety net that ensures - // agents always get git credentials even if the frontend omits the ID. - const platformIntegrationId = - input.platformIntegrationId ?? - (await resolveIntegrationIdFromGitUrl(ctx.user.id, input.gitUrl)); - - if (!input.platformIntegrationId && platformIntegrationId) { - console.log( - `${LOG_PREFIX} createRig: auto-resolved platformIntegrationId=${platformIntegrationId} from gitUrl=${input.gitUrl}` - ); - } - - // Generate a user API token so agents can route LLM calls through the - // Kilo gateway. Stored in RigConfig and injected into agent env vars. - // 30-day expiry to limit blast radius if leaked; refreshed on rig update. - const kilocodeToken = generateApiToken(ctx.user, undefined, { - expiresIn: TOKEN_EXPIRY.thirtyDays, - }); - console.log( - `[gastown-router] createRig: generating kilocodeToken for user=${ctx.user.id} tokenLength=${kilocodeToken?.length ?? 0}` - ); - - const rig = await withGastownError(() => - gastown.createRig(ctx.user.id, { - town_id: input.townId, - name: input.name, - git_url: input.gitUrl, - default_branch: input.defaultBranch, - kilocode_token: kilocodeToken, - platform_integration_id: platformIntegrationId, - }) - ); - - // Resolve git credentials from the platform integration and store - // them in the town config so agents can clone and push. - // This is a best-effort write: if it fails, the rig exists without - // git credentials. The container-side resolveGitCredentialsIfMissing - // and the refreshTownGitCredentials helper serve as recovery mechanisms. - if (platformIntegrationId) { - try { - const gitCredentials = await resolveGitCredentialsFromIntegration(platformIntegrationId); - if (gitCredentials) { - console.log( - `${LOG_PREFIX} createRig: resolved git credentials for integration=${platformIntegrationId} hasGithub=${!!gitCredentials.github_token} hasGitlab=${!!gitCredentials.gitlab_token}` - ); - await withGastownError(() => - gastown.updateTownConfig(input.townId, { - git_auth: { - ...gitCredentials, - // Store the integration ID so we can refresh tokens later - platform_integration_id: platformIntegrationId, - }, - }) - ); - } else { - console.warn( - `${LOG_PREFIX} createRig: could not resolve git credentials for integration=${platformIntegrationId}` - ); - } - } catch (credErr) { - // Rig was created successfully but git credentials could not be - // written. Log the error clearly — agents can still resolve - // credentials on-demand via the container's credential API, and - // refreshTownGitCredentials can retry later. - console.error( - `${LOG_PREFIX} createRig: rig=${rig.id} created but git credential write FAILED for integration=${platformIntegrationId}:`, - credErr - ); - } - } - - return rig; - }), - - listRigs: adminProcedure - .input(z.object({ townId: z.string().uuid() })) - .query(async ({ ctx, input }) => { - // Verify ownership - const town = await withGastownError(() => gastown.getTown(ctx.user.id, input.townId)); - if (town.owner_user_id !== ctx.user.id) { - throw new TRPCError({ code: 'FORBIDDEN', message: 'Not your town' }); - } - return withGastownError(() => gastown.listRigs(ctx.user.id, input.townId)); - }), - - getRig: adminProcedure - .input(z.object({ rigId: z.string().uuid() })) - .query(async ({ ctx, input }) => { - const rig = await withGastownError(() => gastown.getRig(ctx.user.id, input.rigId)); - const [agents, beads] = await Promise.all([ - withGastownError(() => gastown.listAgents(rig.town_id, rig.id)), - withGastownError(() => gastown.listBeads(rig.town_id, rig.id, { status: 'in_progress' })), - ]); - return { ...rig, agents, beads }; - }), - - // ── Beads ─────────────────────────────────────────────────────────────── - - listBeads: adminProcedure - .input( - z.object({ - rigId: z.string().uuid(), - status: z.enum(['open', 'in_progress', 'closed', 'failed']).optional(), - }) - ) - .query(async ({ ctx, input }) => { - // Verify the user owns the rig (getRig will 404 if wrong user) - const rig = await withGastownError(() => gastown.getRig(ctx.user.id, input.rigId)); - return withGastownError(() => - gastown.listBeads(rig.town_id, rig.id, { status: input.status }) - ); - }), - - // ── Agents ────────────────────────────────────────────────────────────── - - listAgents: adminProcedure - .input(z.object({ rigId: z.string().uuid() })) - .query(async ({ ctx, input }) => { - const rig = await withGastownError(() => gastown.getRig(ctx.user.id, input.rigId)); - return withGastownError(() => gastown.listAgents(rig.town_id, rig.id)); - }), - - // ── Work Assignment ───────────────────────────────────────────────────── - - sling: adminProcedure - .input( - z.object({ - rigId: z.string().uuid(), - title: z.string().min(1), - body: z.string().optional(), - model: z.string().default('kilo/auto'), - }) - ) - .mutation(async ({ ctx, input }) => { - console.log( - `${LOG_PREFIX} sling: rigId=${input.rigId} title="${input.title}" model=${input.model} userId=${ctx.user.id}` - ); - // Verify ownership - const rig = await withGastownError(() => gastown.getRig(ctx.user.id, input.rigId)); - console.log(`${LOG_PREFIX} sling: rig verified, name=${rig.name}`); - - // Refresh git credentials before dispatch. - await refreshTownGitCredentials(rig.town_id, ctx.user.id); - - // Atomic sling: creates bead, assigns/creates polecat, hooks them, - // and arms the alarm — all in a single Rig DO call to avoid TOCTOU races. - const result = await withGastownError(() => - gastown.slingBead(rig.town_id, rig.id, { - title: input.title, - body: input.body, - metadata: { model: input.model, slung_by: ctx.user.id }, - }) - ); - console.log( - `${LOG_PREFIX} sling: completed beadId=${result.bead.bead_id} agentId=${result.agent.id} agentRole=${result.agent.role} agentStatus=${result.agent.status}` - ); - return result; - }), - - // ── Mayor Communication ───────────────────────────────────────────────── - // Routes messages to MayorDO (town-level persistent conversational agent). - // No beads are created — the mayor decides when to delegate work via tools. - - sendMessage: adminProcedure - .input( - z.object({ - townId: z.string().uuid(), - message: z.string().min(1), - model: z.string().default('anthropic/claude-sonnet-4.6'), - // rigId kept for backward compat but no longer used for routing - rigId: z.string().uuid().optional(), - }) - ) - .mutation(async ({ ctx, input }) => { - console.log( - `${LOG_PREFIX} sendMessage: townId=${input.townId} message="${input.message.slice(0, 80)}" model=${input.model} userId=${ctx.user.id}` - ); - - // Verify ownership - const town = await withGastownError(() => gastown.getTown(ctx.user.id, input.townId)); - console.log( - `${LOG_PREFIX} sendMessage: town verified, name=${town.name} owner=${town.owner_user_id}` - ); - if (town.owner_user_id !== ctx.user.id) { - console.error(`${LOG_PREFIX} sendMessage: FORBIDDEN - town owner mismatch`); - throw new TRPCError({ code: 'FORBIDDEN', message: 'Not your town' }); - } - - // Refresh git credentials before mayor interaction. - await refreshTownGitCredentials(input.townId, ctx.user.id); - - // Send message directly to MayorDO — single DO call, no beads - console.log(`${LOG_PREFIX} sendMessage: routing to MayorDO for townId=${input.townId}`); - const result = await withGastownError(() => - gastown.sendMayorMessage(input.townId, input.message, input.model) - ); - console.log( - `${LOG_PREFIX} sendMessage: MayorDO responded agentId=${result.agentId} sessionStatus=${result.sessionStatus}` - ); - - return result; - }), - - // ── Mayor Status ────────────────────────────────────────────────────── - - getMayorStatus: adminProcedure - .input(z.object({ townId: z.string().uuid() })) - .query(async ({ ctx, input }) => { - // Verify ownership - const town = await withGastownError(() => gastown.getTown(ctx.user.id, input.townId)); - if (town.owner_user_id !== ctx.user.id) { - throw new TRPCError({ code: 'FORBIDDEN', message: 'Not your town' }); - } - return withGastownError(() => gastown.getMayorStatus(input.townId)); - }), - - ensureMayor: adminProcedure - .input(z.object({ townId: z.string().uuid() })) - .mutation(async ({ ctx, input }) => { - const town = await withGastownError(() => gastown.getTown(ctx.user.id, input.townId)); - if (town.owner_user_id !== ctx.user.id) { - throw new TRPCError({ code: 'FORBIDDEN', message: 'Not your town' }); - } - - // Best-effort refresh so polecats dispatched by the mayor's gt_sling - // tool have a fresh token. Failures must not block the mayor startup. - try { - await refreshTownGitCredentials(input.townId, ctx.user.id); - } catch (err) { - console.warn( - `${LOG_PREFIX} ensureMayor: git credential refresh failed (non-blocking)`, - err - ); - } - - return withGastownError(() => gastown.ensureMayor(input.townId)); - }), - - // ── Agent Streams ─────────────────────────────────────────────────────── - - getAgentStreamUrl: adminProcedure - .input( - z.object({ - agentId: z.string().uuid(), - townId: z.string().uuid(), - }) - ) - .query(async ({ ctx, input }) => { - // Verify ownership - const town = await withGastownError(() => gastown.getTown(ctx.user.id, input.townId)); - if (town.owner_user_id !== ctx.user.id) { - throw new TRPCError({ code: 'FORBIDDEN', message: 'Not your town' }); - } - - const ticket = await withGastownError(() => - gastown.getStreamTicket(input.townId, input.agentId) - ); - - // The gastown worker returns a relative path. Construct the full - // WebSocket URL using GASTOWN_SERVICE_URL so the browser connects - // directly to the gastown worker (not the Next.js server). - const baseUrl = new URL(GASTOWN_SERVICE_URL ?? 'http://localhost:8787'); - const wsProtocol = baseUrl.protocol === 'https:' ? 'wss:' : 'ws:'; - const fullUrl = `${wsProtocol}//${baseUrl.host}${ticket.url}`; - - return { ...ticket, url: fullUrl }; - }), - - // ── Agent Terminal (PTY) ────────────────────────────────────────────────── - - createPtySession: adminProcedure - .input( - z.object({ - townId: z.string().uuid(), - agentId: z.string().uuid(), - }) - ) - .mutation(async ({ ctx, input }) => { - // Verify ownership - const town = await withGastownError(() => gastown.getTown(ctx.user.id, input.townId)); - if (town.owner_user_id !== ctx.user.id) { - throw new TRPCError({ code: 'FORBIDDEN', message: 'Not your town' }); - } - - // Create a PTY session on the container via the worker - const pty = await withGastownError(() => - gastown.createPtySession(input.townId, input.agentId) - ); - - // Construct the WebSocket URL for the PTY connection - const baseUrl = new URL(GASTOWN_SERVICE_URL ?? 'http://localhost:8787'); - const wsProtocol = baseUrl.protocol === 'https:' ? 'wss:' : 'ws:'; - const wsUrl = `${wsProtocol}//${baseUrl.host}/api/towns/${input.townId}/container/agents/${input.agentId}/pty/${pty.id}/connect`; - - return { pty, wsUrl }; - }), - - resizePtySession: adminProcedure - .input( - z.object({ - townId: z.string().uuid(), - agentId: z.string().uuid(), - ptyId: z.string().regex(/^[a-zA-Z0-9_-]+$/, 'Invalid ptyId'), - cols: z.number().int().min(1).max(500), - rows: z.number().int().min(1).max(200), - }) - ) - .mutation(async ({ ctx, input }) => { - const town = await withGastownError(() => gastown.getTown(ctx.user.id, input.townId)); - if (town.owner_user_id !== ctx.user.id) { - throw new TRPCError({ code: 'FORBIDDEN', message: 'Not your town' }); - } - await withGastownError(() => - gastown.resizePtySession(input.townId, input.agentId, input.ptyId, input.cols, input.rows) - ); - }), - - // ── Town Configuration ────────────────────────────────────────────────── - - getTownConfig: adminProcedure - .input(z.object({ townId: z.string().uuid() })) - .query(async ({ ctx, input }) => { - const town = await withGastownError(() => gastown.getTown(ctx.user.id, input.townId)); - if (town.owner_user_id !== ctx.user.id) { - throw new TRPCError({ code: 'FORBIDDEN', message: 'Not your town' }); - } - return withGastownError(() => gastown.getTownConfig(input.townId)); - }), - - updateTownConfig: adminProcedure - .input( - z.object({ - townId: z.string().uuid(), - config: gastown.TownConfigSchema.partial(), - }) - ) - .mutation(async ({ ctx, input }) => { - const town = await withGastownError(() => gastown.getTown(ctx.user.id, input.townId)); - if (town.owner_user_id !== ctx.user.id) { - throw new TRPCError({ code: 'FORBIDDEN', message: 'Not your town' }); - } - return withGastownError(() => gastown.updateTownConfig(input.townId, input.config)); - }), - - // ── Events ───────────────────────────────────────────────────────────── - - getBeadEvents: adminProcedure - .input( - z.object({ - rigId: z.string().uuid(), - beadId: z.string().uuid().optional(), - since: z.string().optional(), - limit: z.number().int().positive().max(500).default(100), - }) - ) - .query(async ({ ctx, input }) => { - const rig = await withGastownError(() => gastown.getRig(ctx.user.id, input.rigId)); - return withGastownError(() => - gastown.listBeadEvents(rig.town_id, rig.id, { - beadId: input.beadId, - since: input.since, - limit: input.limit, - }) - ); - }), - - getTownEvents: adminProcedure - .input( - z.object({ - townId: z.string().uuid(), - since: z.string().optional(), - limit: z.number().int().positive().max(500).default(100), - }) - ) - .query(async ({ ctx, input }) => { - const town = await withGastownError(() => gastown.getTown(ctx.user.id, input.townId)); - if (town.owner_user_id !== ctx.user.id) { - throw new TRPCError({ code: 'FORBIDDEN', message: 'Not your town' }); - } - return withGastownError(() => - gastown.listTownEvents(ctx.user.id, input.townId, { - since: input.since, - limit: input.limit, - }) - ); - }), - - // ── Deletes ──────────────────────────────────────────────────────────── - - deleteTown: adminProcedure - .input(z.object({ townId: z.string().uuid() })) - .mutation(async ({ ctx, input }) => { - const town = await withGastownError(() => gastown.getTown(ctx.user.id, input.townId)); - if (town.owner_user_id !== ctx.user.id) { - throw new TRPCError({ code: 'FORBIDDEN', message: 'Not your town' }); - } - await withGastownError(() => gastown.deleteTown(ctx.user.id, input.townId)); - }), - - deleteRig: adminProcedure - .input(z.object({ rigId: z.string().uuid() })) - .mutation(async ({ ctx, input }) => { - await withGastownError(() => gastown.deleteRig(ctx.user.id, input.rigId)); - }), - - deleteBead: adminProcedure - .input(z.object({ rigId: z.string().uuid(), beadId: z.string().uuid() })) - .mutation(async ({ ctx, input }) => { - // Verify the caller owns this rig before deleting - const rig = await withGastownError(() => gastown.getRig(ctx.user.id, input.rigId)); - await withGastownError(() => gastown.deleteBead(rig.town_id, rig.id, input.beadId)); - }), - - deleteAgent: adminProcedure - .input(z.object({ rigId: z.string().uuid(), agentId: z.string().uuid() })) - .mutation(async ({ ctx, input }) => { - // Verify the caller owns this rig before deleting - const rig = await withGastownError(() => gastown.getRig(ctx.user.id, input.rigId)); - await withGastownError(() => gastown.deleteAgent(rig.town_id, rig.id, input.agentId)); - }), -}); diff --git a/src/routers/root-router.ts b/src/routers/root-router.ts index c940ee12a4..648152f60c 100644 --- a/src/routers/root-router.ts +++ b/src/routers/root-router.ts @@ -34,8 +34,6 @@ import { appBuilderFeedbackRouter } from '@/routers/app-builder-feedback-router' import { cloudAgentNextFeedbackRouter } from '@/routers/cloud-agent-next-feedback-router'; import { kiloclawRouter } from '@/routers/kiloclaw-router'; import { unifiedSessionsRouter } from '@/routers/unified-sessions-router'; -import { gastownRouter } from '@/routers/gastown-router'; - export const rootRouter = createTRPCRouter({ test: testRouter, organizations: organizationsRouter, @@ -71,7 +69,6 @@ export const rootRouter = createTRPCRouter({ cloudAgentNextFeedback: cloudAgentNextFeedbackRouter, kiloclaw: kiloclawRouter, unifiedSessions: unifiedSessionsRouter, - gastown: gastownRouter, }); // export type definition of API export type RootRouter = typeof rootRouter; From 68eb9bd2cf3ca8e5f219e2f1123fdee5cff03be7 Mon Sep 17 00:00:00 2001 From: John Fawcett Date: Thu, 5 Mar 2026 13:10:15 -0600 Subject: [PATCH 4/5] =?UTF-8?q?fix(gastown):=20address=20PR=20review=20fee?= =?UTF-8?q?dback=20=E2=80=94=20security,=20validation,=20and=20robustness?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Remove console.log(secret) that leaked NEXTAUTH_SECRET to stdout - Replace raw error logging with sanitized message in kilo-auth middleware - Add verifyRigOwnership check to deleteRig tRPC procedure - Use TownConfigUpdateSchema instead of z.record for updateTownConfig input - Validate GitLab host in checkPRStatus before sending PRIVATE-TOKEN - Handle empty model strings in kiloModel with fallback to kilo/auto - Replace 'as' cast with Zod validation in gastown trpc.ts fetchToken - Add warning log for unrecognized PR URL formats in checkPRStatus - Handle HTTP 422 (duplicate PR) in createGitHubPR by fetching existing PR - Add console.warn for label application failures instead of silent catch - Emit pr_creation_failed event when refinery provides invalid pr_url - Add git status instruction to refinery prompt per reviewer feedback - Use MergeStrategy type import in refinery prompt instead of inline union - Strip workspace: references from dependencies (not just devDependencies) - Remove unused TOKEN_EXPIRY import to fix lint error --- .../container/src/agent-runner.ts | 4 +- .../scripts/prepare-container.mjs | 10 ++-- cloudflare-gastown/src/dos/Town.do.ts | 19 ++++++- .../src/dos/town/review-queue.ts | 6 +++ .../src/middleware/kilo-auth.middleware.ts | 9 ++-- .../src/prompts/refinery-system.prompt.ts | 5 +- cloudflare-gastown/src/trpc/router.ts | 5 +- .../src/util/platform-pr.util.ts | 51 ++++++++++++++++++- src/app/api/gastown/token/route.ts | 2 +- src/lib/gastown/trpc.ts | 9 ++-- 10 files changed, 100 insertions(+), 20 deletions(-) diff --git a/cloudflare-gastown/container/src/agent-runner.ts b/cloudflare-gastown/container/src/agent-runner.ts index 2477c8ef4c..3e2ff5097c 100644 --- a/cloudflare-gastown/container/src/agent-runner.ts +++ b/cloudflare-gastown/container/src/agent-runner.ts @@ -17,7 +17,9 @@ function resolveEnv(request: StartAgentRequest, key: string): string | undefined /** Prepend the kilo provider prefix to an OpenRouter-style model ID. */ function kiloModel(openrouterModel: string): string { - return openrouterModel.startsWith('kilo/') ? openrouterModel : `kilo/${openrouterModel}`; + const trimmed = openrouterModel.trim(); + if (!trimmed) return 'kilo/auto'; + return trimmed.startsWith('kilo/') ? trimmed : `kilo/${trimmed}`; } const HEADLESS_PERMISSIONS = { diff --git a/cloudflare-gastown/scripts/prepare-container.mjs b/cloudflare-gastown/scripts/prepare-container.mjs index 3774e7fe75..c8297fe91c 100644 --- a/cloudflare-gastown/scripts/prepare-container.mjs +++ b/cloudflare-gastown/scripts/prepare-container.mjs @@ -44,10 +44,12 @@ writeFileSync(resolve(containerDir, 'pnpm-workspace.yaml'), catalogLines.join('\ // Create a production-only package.json that strips workspace: references // (they can't be resolved outside the monorepo). const pkg = JSON.parse(readFileSync(resolve(containerDir, 'package.json'), 'utf8')); -if (pkg.devDependencies) { - for (const [name, version] of Object.entries(pkg.devDependencies)) { - if (typeof version === 'string' && version.startsWith('workspace:')) { - delete pkg.devDependencies[name]; +for (const depKey of ['dependencies', 'devDependencies']) { + if (pkg[depKey]) { + for (const [name, version] of Object.entries(pkg[depKey])) { + if (typeof version === 'string' && version.startsWith('workspace:')) { + delete pkg[depKey][name]; + } } } } diff --git a/cloudflare-gastown/src/dos/Town.do.ts b/cloudflare-gastown/src/dos/Town.do.ts index 37b9e90005..420bd838c2 100644 --- a/cloudflare-gastown/src/dos/Town.do.ts +++ b/cloudflare-gastown/src/dos/Town.do.ts @@ -1622,7 +1622,23 @@ export class TownDO extends DurableObject { if (glMatch) { const [, instanceUrl, projectPath, iidStr] = glMatch; const token = townConfig.git_auth.gitlab_token; - if (!token) return null; + if (!token) { + console.warn(`${TOWN_LOG} checkPRStatus: no gitlab_token configured, cannot poll ${prUrl}`); + return null; + } + + // Validate the host against known GitLab hosts to prevent SSRF/token leak. + // Only send the PRIVATE-TOKEN to gitlab.com or the configured instance URL. + const prHost = new URL(instanceUrl).hostname; + const configuredHost = townConfig.git_auth.gitlab_instance_url + ? new URL(townConfig.git_auth.gitlab_instance_url).hostname + : null; + if (prHost !== 'gitlab.com' && prHost !== configuredHost) { + console.warn( + `${TOWN_LOG} checkPRStatus: refusing to send gitlab_token to unknown host: ${prHost}` + ); + return null; + } const encodedPath = encodeURIComponent(projectPath); const response = await fetch( @@ -1643,6 +1659,7 @@ export class TownDO extends DurableObject { return 'open'; } + console.warn(`${TOWN_LOG} checkPRStatus: unrecognized PR URL format: ${prUrl}`); return null; } diff --git a/cloudflare-gastown/src/dos/town/review-queue.ts b/cloudflare-gastown/src/dos/town/review-queue.ts index 779e8f1ee2..991751180d 100644 --- a/cloudflare-gastown/src/dos/town/review-queue.ts +++ b/cloudflare-gastown/src/dos/town/review-queue.ts @@ -393,6 +393,12 @@ export function agentDone(sql: SqlStorage, agentId: string, input: AgentDoneInpu status: 'failed', message: `Refinery provided invalid pr_url: ${input.pr_url}`, }); + logBeadEvent(sql, { + beadId: mrBeadId, + agentId, + eventType: 'pr_creation_failed', + metadata: { pr_url: input.pr_url, reason: 'invalid_url' }, + }); } } else { // Direct strategy: refinery already merged and pushed diff --git a/cloudflare-gastown/src/middleware/kilo-auth.middleware.ts b/cloudflare-gastown/src/middleware/kilo-auth.middleware.ts index d7483512c1..ccda056a3d 100644 --- a/cloudflare-gastown/src/middleware/kilo-auth.middleware.ts +++ b/cloudflare-gastown/src/middleware/kilo-auth.middleware.ts @@ -23,7 +23,6 @@ export const kiloAuthMiddleware = createMiddleware(async (c, next) = return c.json(resError('Internal server error'), 500); } const secret = await resolveSecret(c.env.NEXTAUTH_SECRET); - console.log(secret); try { const payload = await verifyKiloToken(token, secret); @@ -31,9 +30,11 @@ export const kiloAuthMiddleware = createMiddleware(async (c, next) = c.set('kiloIsAdmin', payload.isAdmin === true); c.set('kiloApiTokenPepper', payload.apiTokenPepper ?? null); } catch (err) { - console.log('error', err); - const message = err instanceof Error ? err.message : 'Invalid token'; - return c.json(resError(message), 401); + console.warn( + '[kilo-auth] token verification failed:', + err instanceof Error ? err.message : 'unknown error' + ); + return c.json(resError('Invalid token'), 401); } return next(); diff --git a/cloudflare-gastown/src/prompts/refinery-system.prompt.ts b/cloudflare-gastown/src/prompts/refinery-system.prompt.ts index 00bf59da62..025e832d47 100644 --- a/cloudflare-gastown/src/prompts/refinery-system.prompt.ts +++ b/cloudflare-gastown/src/prompts/refinery-system.prompt.ts @@ -1,3 +1,5 @@ +import type { MergeStrategy } from '../types'; + /** * Build the system prompt for a refinery agent. * @@ -12,7 +14,7 @@ export function buildRefinerySystemPrompt(params: { branch: string; targetBranch: string; polecatAgentId: string; - mergeStrategy: 'direct' | 'pr'; + mergeStrategy: MergeStrategy; }): string { const gateList = params.gates.length > 0 @@ -75,6 +77,7 @@ ${mergeInstructions} - \`gt_checkpoint\` — Save progress for crash recovery ## Important +- Before any git operation, run \`git status\` first to understand the current state of the working tree. This significantly reduces errors from unexpected dirty state or wrong branch. - Be specific in rework requests. "Fix the tests" is not actionable. "Test \`calculateTotal\` in \`tests/cart.test.ts\` fails because the discount logic in \`src/cart.ts:47\` doesn't handle the zero-quantity case" is actionable. - Do not modify the code yourself. Your job is to review, merge/create PRs, and decide — not to fix code. - If you cannot determine whether the code is correct (e.g., you don't understand the domain), escalate with severity "medium" instead of guessing. diff --git a/cloudflare-gastown/src/trpc/router.ts b/cloudflare-gastown/src/trpc/router.ts index 192078f95a..b32dcdc4ce 100644 --- a/cloudflare-gastown/src/trpc/router.ts +++ b/cloudflare-gastown/src/trpc/router.ts @@ -14,7 +14,7 @@ import { getTownContainerStub } from '../dos/TownContainer.do'; import { getGastownUserStub } from '../dos/GastownUser.do'; import { generateKiloApiToken } from '../util/kilo-token.util'; import { resolveSecret } from '../util/secret.util'; -import { TownConfigSchema } from '../types'; +import { TownConfigSchema, TownConfigUpdateSchema } from '../types'; import { RpcTownOutput, RpcRigOutput, @@ -258,6 +258,7 @@ export const gastownRouter = router({ .input(z.object({ rigId: z.string().uuid() })) .mutation(async ({ ctx, input }) => { requireAdmin(ctx); + await verifyRigOwnership(ctx.env, ctx.userId, input.rigId); const userStub = getGastownUserStub(ctx.env, ctx.userId); await userStub.deleteRig(input.rigId); }), @@ -510,7 +511,7 @@ export const gastownRouter = router({ .input( z.object({ townId: z.string().uuid(), - config: z.record(z.string(), z.unknown()), + config: TownConfigUpdateSchema, }) ) .output(RpcTownConfigSchema) diff --git a/cloudflare-gastown/src/util/platform-pr.util.ts b/cloudflare-gastown/src/util/platform-pr.util.ts index 6aef0fa359..727318c623 100644 --- a/cloudflare-gastown/src/util/platform-pr.util.ts +++ b/cloudflare-gastown/src/util/platform-pr.util.ts @@ -189,6 +189,42 @@ const GitHubPRResponse = z.object({ state: z.string(), }); +/** Fetch an existing open PR for the same head→base pair (used on 422 duplicate). */ +async function fetchExistingGitHubPR(params: { + owner: string; + repo: string; + token: string; + head: string; + base: string; +}): Promise<{ pr_url: string; pr_number: number } | null> { + try { + const qs = new URLSearchParams({ + head: `${params.owner}:${params.head}`, + base: params.base, + state: 'open', + }); + const response = await fetch( + `https://api.github.com/repos/${params.owner}/${params.repo}/pulls?${qs}`, + { + headers: { + Authorization: `token ${params.token}`, + Accept: 'application/vnd.github.v3+json', + 'User-Agent': 'Gastown-Refinery/1.0', + }, + } + ); + if (!response.ok) return null; + const data: unknown = await response.json(); + const prs = z.array(GitHubPRResponse).parse(data); + if (prs.length > 0) { + return { pr_url: prs[0].html_url, pr_number: prs[0].number }; + } + } catch { + // Best-effort — caller will throw the original 422 error + } + return null; +} + export async function createGitHubPR(params: { owner: string; repo: string; @@ -219,6 +255,17 @@ export async function createGitHubPR(params: { ); if (!response.ok) { + // HTTP 422 with "A pull request already exists" means a PR for this + // head→base combination already exists. Fetch the existing PR URL + // instead of failing the entire merge request flow. + if (response.status === 422) { + const errorBody = await response.text().catch(() => ''); + if (errorBody.includes('A pull request already exists')) { + const existingPR = await fetchExistingGitHubPR(params); + if (existingPR) return existingPR; + } + throw new Error(`GitHub PR creation failed (422): ${errorBody.slice(0, 500)}`); + } const text = await response.text().catch(() => '(unreadable)'); throw new Error(`GitHub PR creation failed (${response.status}): ${text.slice(0, 500)}`); } @@ -240,8 +287,8 @@ export async function createGitHubPR(params: { }, body: JSON.stringify({ labels: params.labels }), } - ).catch(() => { - // Best-effort label application + ).catch(err => { + console.warn(`[platform-pr] Failed to apply labels to PR #${parsed.number}:`, err); }); } diff --git a/src/app/api/gastown/token/route.ts b/src/app/api/gastown/token/route.ts index 40d4e3a7af..6dad4dfbd8 100644 --- a/src/app/api/gastown/token/route.ts +++ b/src/app/api/gastown/token/route.ts @@ -1,7 +1,7 @@ import 'server-only'; import { NextResponse } from 'next/server'; import { getUserFromAuth } from '@/lib/user.server'; -import { generateApiToken, TOKEN_EXPIRY } from '@/lib/tokens'; +import { generateApiToken } from '@/lib/tokens'; const ONE_HOUR_SECONDS = 60 * 60; diff --git a/src/lib/gastown/trpc.ts b/src/lib/gastown/trpc.ts index f0c6feeda2..5c9c53a5d9 100644 --- a/src/lib/gastown/trpc.ts +++ b/src/lib/gastown/trpc.ts @@ -9,6 +9,7 @@ */ import { createTRPCClient, httpBatchLink, httpLink, splitLink } from '@trpc/client'; +import { z } from 'zod'; import { createTRPCContext } from '@trpc/tanstack-react-query'; import type { inferRouterOutputs } from '@trpc/server'; import type { WrappedGastownRouter } from '@/lib/gastown/types/router'; @@ -35,10 +36,10 @@ async function fetchToken(): Promise { throw new Error(`Failed to fetch gastown token: ${res.status} ${body}`); } const data: unknown = await res.json(); - const { token, expiresAt } = data as { token: string; expiresAt: string }; - cachedToken = token; - tokenExpiresAt = new Date(expiresAt).getTime(); - return token; + const parsed = z.object({ token: z.string(), expiresAt: z.string() }).parse(data); + cachedToken = parsed.token; + tokenExpiresAt = new Date(parsed.expiresAt).getTime(); + return parsed.token; } async function getToken(): Promise { From 0bae0001db0c4405ab6e95c7dab480a24ac2c94f Mon Sep 17 00:00:00 2001 From: John Fawcett Date: Thu, 5 Mar 2026 13:21:39 -0600 Subject: [PATCH 5/5] fix(gastown): address follow-up review comments - Add SSRF protection to createGitLabMR: validate instanceUrl host against gitlab.com or configured instance URL before sending PRIVATE-TOKEN - Log HTTP error status codes in checkPRStatus for both GitHub and GitLab API responses instead of silently returning null - Add TownConfigUpdateSchema tests verifying no phantom defaults are injected on empty input --- cloudflare-gastown/src/dos/Town.do.ts | 14 +++++++++++-- .../src/util/platform-pr.util.ts | 16 +++++++++++++++ .../test/unit/merge-strategy.test.ts | 20 ++++++++++++++++++- 3 files changed, 47 insertions(+), 3 deletions(-) diff --git a/cloudflare-gastown/src/dos/Town.do.ts b/cloudflare-gastown/src/dos/Town.do.ts index 420bd838c2..e2c356abb2 100644 --- a/cloudflare-gastown/src/dos/Town.do.ts +++ b/cloudflare-gastown/src/dos/Town.do.ts @@ -1605,7 +1605,12 @@ export class TownDO extends DurableObject { }, } ); - if (!response.ok) return null; + if (!response.ok) { + console.warn( + `${TOWN_LOG} checkPRStatus: GitHub API returned ${response.status} for ${prUrl}` + ); + return null; + } const json = await response.json().catch(() => null); if (!json) return null; @@ -1647,7 +1652,12 @@ export class TownDO extends DurableObject { headers: { 'PRIVATE-TOKEN': token }, } ); - if (!response.ok) return null; + if (!response.ok) { + console.warn( + `${TOWN_LOG} checkPRStatus: GitLab API returned ${response.status} for ${prUrl}` + ); + return null; + } const glJson = await response.json().catch(() => null); if (!glJson) return null; diff --git a/cloudflare-gastown/src/util/platform-pr.util.ts b/cloudflare-gastown/src/util/platform-pr.util.ts index 727318c623..c322bae5fa 100644 --- a/cloudflare-gastown/src/util/platform-pr.util.ts +++ b/cloudflare-gastown/src/util/platform-pr.util.ts @@ -312,7 +312,23 @@ export async function createGitLabMR(params: { source_branch: string; target_branch: string; labels?: string[]; + /** Optional: configured GitLab instance URL for host validation. */ + configuredInstanceUrl?: string; }): Promise<{ mr_url: string; mr_iid: number }> { + // Validate the instance URL host to prevent SSRF/token exfiltration. + // Only send PRIVATE-TOKEN to gitlab.com or the configured instance URL. + const targetHost = hostnameOf(params.instanceUrl); + if (targetHost && targetHost !== 'gitlab.com') { + const configuredHost = params.configuredInstanceUrl + ? hostnameOf(params.configuredInstanceUrl) + : null; + if (targetHost !== configuredHost) { + throw new Error( + `GitLab MR creation refused: instance URL host "${targetHost}" does not match configured host "${configuredHost ?? '(none)'}"` + ); + } + } + const encodedPath = encodeURIComponent(params.projectPath); const baseUrl = params.instanceUrl.replace(/\/$/, ''); diff --git a/cloudflare-gastown/test/unit/merge-strategy.test.ts b/cloudflare-gastown/test/unit/merge-strategy.test.ts index 55a49936e8..46b8d3672d 100644 --- a/cloudflare-gastown/test/unit/merge-strategy.test.ts +++ b/cloudflare-gastown/test/unit/merge-strategy.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { TownConfigSchema, MergeStrategy } from '../../src/types'; +import { TownConfigSchema, TownConfigUpdateSchema, MergeStrategy } from '../../src/types'; import { resolveMergeStrategy } from '../../src/dos/town/config'; import { parseGitUrl, buildPRBody, type QualityGateResult } from '../../src/util/platform-pr.util'; @@ -30,6 +30,24 @@ describe('merge strategy', () => { }); }); + describe('TownConfigUpdateSchema', () => { + it('does not inject merge_strategy default on empty input', () => { + const update = TownConfigUpdateSchema.parse({}); + expect(update.merge_strategy).toBeUndefined(); + }); + + it('preserves merge_strategy when explicitly provided', () => { + const update = TownConfigUpdateSchema.parse({ merge_strategy: 'pr' }); + expect(update.merge_strategy).toBe('pr'); + }); + + it('does not inject any defaults on empty input', () => { + const update = TownConfigUpdateSchema.parse({}); + // All fields should be undefined — no phantom defaults + expect(Object.values(update).every(v => v === undefined)).toBe(true); + }); + }); + describe('MergeStrategy enum', () => { it('parses "direct"', () => { expect(MergeStrategy.parse('direct')).toBe('direct');