diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f2d503446..9b882c870 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,6 +19,9 @@ jobs: - name: Install dependencies run: npm ci + - name: Check MCP App HTML is fresh + run: npm run app:check + - name: Check formatting run: npm run format:check diff --git a/.gitignore b/.gitignore index 8fa91f764..7d8d81d6e 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ node_modules dist/ *.log .worktrees/ +.mcp-apps-build/ diff --git a/.oxfmtrc.json b/.oxfmtrc.json index 19a7ede2b..855b92549 100644 --- a/.oxfmtrc.json +++ b/.oxfmtrc.json @@ -4,6 +4,7 @@ "semi": false, "trailingComma": "none", "ignorePatterns": [ - "src/generated/**" + "src/generated/**", + "src/*/app-html.generated.ts" ] } diff --git a/AGENTS.md b/AGENTS.md index 11236e71f..586e9c04a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -22,6 +22,8 @@ cloudflare-mcp/ │ ├── mcp-handler.ts # Stateless MCP HTTP handler & deployment guards │ ├── server.ts # MCP server setup & tool registration │ ├── events/ # Stateless MCP Events mapping to ANS policies and Vega automations +│ ├── mcp-apps/ # Shared MCP Apps: defineMcpApp, read-only apiReader, registry, app-shell +│ ├── threshold-alert/ # Shared threshold alert Apps: presets, model, collector, policy writes │ ├── executor.ts # Code executor (Worker Loader API) │ ├── spec-processor.ts # OpenAPI spec $ref resolution & splitting merged paths │ ├── spec-release.ts # The pinned spec release and its artifact names @@ -67,6 +69,7 @@ cloudflare-mcp/ ├── scripts/ │ ├── cloudflare-account.ts # The account scripts run cf against │ ├── seed-r2.ts # Seed skills to R2 (cf r2 objects put) +│ ├── build-mcp-apps.ts # Build every src//app into app-html.generated.ts │ ├── generate-tools.ts # Regenerate src/generated/forge-mcp with forge │ ├── schema-mismatch-report.ts # Response schema mismatches by product, for teams │ └── bench-response-validation.ts # Cost of response schema checks on the generated schemas @@ -103,6 +106,7 @@ Node 22+ required. | `npm run deploy` | Deploy to staging | | `npm run deploy:prod` | Deploy to production by hand (merging to `main` already deploys) | | `npm run deploy:forge-tools` / `deploy:forge-tools:prod` | Deploy the forge tools service to staging / production | +| `npm run app:build` | Build every MCP App's HTML (`-- ` for one) | | `npm run generate:tools` | Regenerate `src/generated/forge-mcp` with the pinned `@cloudflare/forge` | | `npm run types` | Generate worker type definitions | | `npm run typecheck` | TypeScript type checking (no emit) | @@ -163,6 +167,26 @@ The core innovation: instead of 2,500 MCP tools (~244K tokens), two tools handle - `src/events/callback.ts` opens the sealed destination secret ANS presents, checks the KV subscription record and synchronously signs the MCP callback, with no Cloudflare API call. ANS owns retries. - `npm run test:events` runs local workerd coverage with simulated external HTTP endpoints. See `docs/mcp-events.md` for live tests and lifecycle constraints. +### Threshold alert Apps + +`src/threshold-alert/` is what every "history of one number + a line + who to tell" App shares: `defineThresholdAlertApp()` (the read-only collector: history, `available_alerts`, existing policies), the model per cadence (rolling 7 days or calendar month), the presets (each an `alert_type`, its policy body, how it recognises an existing policy, its copy) and the generated `alerting_policies_*` writes. One tool per preset, sharing the view; `workers_billing_alert` is the `billing_usage_alert` preset. + +### Workers usage alert App + +`src/workers-usage-alert/` is the `workers_usage_alert` MCP App, registered in `MCP_APPS`. It charts 89 days of Workers requests and previews an hourly `custom_analytics` monitor on a rolling 7 days. The tool only reads; the App's Create alert button creates the policy with the generated `alerting_policies_create` through `callServerTool`, which Code Mode lists, for the App only, to an MCP Apps host (`appTools`). + +### MCP Apps + +`src/mcp-apps/` holds what every MCP App shares: `defineMcpApp()` (a tool plus its static `ui://` HTML resource, served in both tool modes, and `appTools`, the generated tools its view writes with, which Code Mode lists app-only), `apiReader()` (bounded, read-only Cloudflare API and GraphQL reads with the direct tools' refusal explanations and step-up), `MCP_APPS` in `registry.ts` (the one list an App is added to) and `app-shell/` (the browser-side host connection and Kumo base CSS). Each App lives in `src//`, with its React/Kumo view in `src//app/`, built into `app-html.generated.ts` by `npm run app:build`; never hand-edit those. `npm run check` verifies they are fresh and type-checks the view with `tsconfig.app.json`. Keep raw customer prompts, account output and host screenshots outside this public repository. + +Apps are served only to a client that declares them (`src/mcp-apps/capability.ts`): a 2026-07-28 request whose `_meta` envelope lists `text/html;profile=mcp-app` under `extensions["io.modelcontextprotocol/ui"].mimeTypes`, as the Apps spec asks ("Servers SHOULD check client capabilities before registering UI-enabled tools"). `mcp-handler.ts` parses the body once more to decide (`RequestContext.mcpApps`) and hands it to `isLegacyRequest`. The MIME type is compared ignoring whitespace and case. A 2025-era request sends capabilities only in `initialize`, which this stateless server never sees again, so it always counts as not declaring them, and a 2025-era host that renders Apps loses them (accepted); in production (November 2026) 98% of `tools/list` requests, and nearly all of Claude's and ChatGPT's, were 2026-07-28. For any other client: + +- Each App's tool is listed as a plain tool, with no `_meta.ui` or `ui/resourceUri` (`withoutAppView`). Its JSON text result is the spec's text-only fallback. +- Code Mode doesn't register the `appTools`, so they are neither listed nor callable (about 25 KB: Code Mode's `tools/list` goes from ~46 KB to ~21 KB). The direct tools list every generated tool anyway. +- `resources/list` leaves out the `ui://` pages; `resources/read` still serves them, since they are static. + +The server declares `io.modelcontextprotocol/ui` in its capabilities to every client. A 1% sample of 2026-07-28 `tools/list` and `tools/call` requests logs `mcp_apps : declared= client=""` (plus `tool=` for calls), to check that the hosts that render Apps declare them on both, including the view's own write calls. + ### Worker Loader API Code execution uses Cloudflare's Worker Loader API to dynamically create isolated worker instances. The API token is passed via props (never enters user code isolate). A `globalOutbound` service restricts network access. @@ -273,7 +297,7 @@ What the server does: - **Holds** (`holdOf`): every response becomes at most one hold, the time requests under the same limit should wait. Below a reserve of 5% of the quota it is the time the bucket takes to refill to the reserve, at most 5 seconds, so a run settles at the refill rate without emptying the bucket. On a 429 it is the wait Cloudflare gives. - **Scope** (`holdScope`): a response names its limit, not the other endpoints under it, and nothing is guessed. `default` holds every request, also when a 429 names it as exhausted next to another limit. Any other limit holds the operation that reported it, on the same account or zone, found in the spec. A limit that covers more costs one 429 per further operation. - **`execute`**: `GlobalOutbound` passes the hold in `X-Cloudflare-MCP-Rate-Limit`, and the sandbox's `fetch` wrapper applies it for the rest of the run. It waits out a hold of 5 seconds or less and answers a request under a longer one itself with a 429 the error calls "not sent". A run waits 30 seconds in total, counting a hold that requests sent together wait out at the same time once; after that a held request is not sent either, so the call returns an error that says how far it got before the TypeScript SDK's 60-second request timeout cuts it off with nothing. A "not sent" answer involves no I/O, so code that retries a held request in a loop would spin until the Worker runs out of CPU or memory (two `exceededMemory` outcomes in the first hour of #391, which was rolled back). Each answer therefore yields to the event loop, and after 1,000 of them the run is stopped with an error. A stopped run sends and answers nothing more, whatever its code is still doing. A hold only stops requests not yet sent, so the wrapper lets at most 20 requests of a run wait for Cloudflare's answer at once (`MOST_IN_FLIGHT`): a batch sent under an exhausted limit has at most 20 refused, and a hundred healthy requests go out in five rounds. Workers' own limit of six open connections does not do this, since each request is its own `GlobalOutbound` invocation: code that sent 125 R2 requests with `Promise.all` had every one refused before the first 429 came back (`limited=125 not_sent=0`, about 4,400 refusals in six minutes from one client). Each run a limit touched logs `execute rate limits: limited=<429s> not_sent= waited_ms=`. -- **Retries**: the sandbox's `fetch` wrapper sends a request Cloudflare answered with a 429 again, up to three times, once the hold that 429 set is over. A 429 with no wait (D1, KV, URL Scanner) is held for a backoff of 1, 2 and 4 seconds. `GlobalOutbound` retries no 429 itself (`retryRateLimited: false`): a wait there held back none of the run's other requests and was not counted in its budget, so a loop over a product limit slept up to 7 seconds per request until the client gave up. When the hold is longer than 5 seconds or the budget is spent, the code gets the 429. The direct tools make one request and still retry in `fetchWithRetry` (`src/utils/fetch-retry.ts`): after the server's wait when it is 5 seconds or less, with backoff when the server gives none, and not at all when it asks for longer. +- **Retries**: the sandbox's `fetch` wrapper sends a request Cloudflare answered with a 429 again, up to three times, once the hold that 429 set is over. A 429 with no wait (D1, KV, URL Scanner) is held for a backoff of 1, 2 and 4 seconds. `GlobalOutbound` retries no 429 itself (`retryRateLimited: false`): a wait there held back none of the run's other requests and was not counted in its budget, so a loop over a product limit slept up to 7 seconds per request until the client gave up. When the hold is longer than 5 seconds or the budget is spent, the code gets the 429. The direct tools make one request and still retry in `fetchWithRetry` (`src/utils/fetch-retry.ts`): after the server's wait when it is 5 seconds or less, with backoff when the server gives none, and not at all when it asks for longer. A POST or PATCH that fails on the network is not sent again (`retryNetworkErrors: false`): it may have reached Cloudflare, and a second create would make a second resource. - **Hints** (`rateLimitHint`): every 429 tool error, in Code Mode and the direct tools, says how long Cloudflare asks to wait. The wait is in headers the agent never sees. - **Identity probes** (`src/auth/api-token-mode.ts`): a direct credential whose probe Cloudflare refuses is held in `OAUTH_KV` (`api-token-rate-limited:v1:`, only the refusal and the time the hold ends), and requests with it are answered from the hold without asking Cloudflare. A rate-limited credential is held for the `Retry-After` it got and answered `429 temporarily_unavailable` with what is left of the wait. A credential Cloudflare doesn't recognise is held for a minute and answered `401 invalid_token`; `429 10502` counts as that, since it is Cloudflare's answer to a token that keeps failing. Answering it as a rate limit told clients to try again later, and each try was two more failures. Each held request logs `api_token_identity_probe held:`. - **Not done**: nothing about API calls is remembered between tool calls, so a direct tool call is never paced and an agent that ignores the hint gets one 429 per call. Remembering would need KV or a Durable Object per credential to copy a counter the API already keeps; one isolate serves every user, so it can't live in the isolate. diff --git a/package-lock.json b/package-lock.json index 23d3f9d75..e848a6d10 100644 --- a/package-lock.json +++ b/package-lock.json @@ -17,20 +17,100 @@ }, "devDependencies": { "@cloudflare/forge": "https://pkg.pr.new/cloudflare/forge/@cloudflare/forge@f6720c19250f90fe5b395ef2c38d488aaba31641", + "@cloudflare/kumo": "2.19.0", "@cloudflare/vitest-plugin": "^1.4.9", "@modelcontextprotocol/client": "2.3.1", + "@modelcontextprotocol/ext-apps": "2.0.4", + "@phosphor-icons/react": "2.1.10", + "@tailwindcss/vite": "4.3.5", "@types/node": "^25.0.6", + "@types/react": "19.3.0", + "@types/react-dom": "19.3.0", "msw": "^2.14.6", "oxfmt": "^0.74.0", "oxlint": "^1.46.0", + "react": "19.3.1", + "react-dom": "19.3.1", + "tailwindcss": "4.3.5", "tsx": "^4.22.4", "typescript": "^5.7.0", + "vite": "8.3.8", + "vite-plugin-singlefile": "2.3.4", "vitest": "^4.1.12", "workers-oauth-provider-0-10-2": "npm:@cloudflare/workers-oauth-provider@^0.10.2", "workers-oauth-provider-1-1-0": "npm:@cloudflare/workers-oauth-provider@^1.1.0", "wrangler": "^4.154.0" } }, + "node_modules/@babel/runtime": { + "version": "8.1.2", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-8.1.2.tgz", + "integrity": "sha512-Ay6HdEKZJAeGs6KKJ/ezCK5ssjFmkvUiR0TEGv/B1abyjLWrQ2RU+M507Ppk0NikhvVFhlEFC1/rHfCiYqSUcw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@base-ui/react": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@base-ui/react/-/react-1.9.0.tgz", + "integrity": "sha512-S8CSYosASBKtpL8SWUfS78rFElfLijiCgA7oHOK22jCJ95FULsYyKwBNFOgudt0RA+/7yNc7F81bOvQnRgbBiQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.29.7 || ^8.0.0", + "@base-ui/utils": "0.5.0", + "@floating-ui/react-dom": "^2.1.9", + "@floating-ui/utils": "^0.2.12", + "use-sync-external-store": "^1.7.0" + }, + "engines": { + "node": ">=14.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/mui-org" + }, + "peerDependencies": { + "@date-fns/tz": "^1.2.0", + "@types/react": "^17 || ^18 || ^19", + "date-fns": "^4.0.0", + "react": "^17 || ^18 || ^19", + "react-dom": "^17 || ^18 || ^19" + }, + "peerDependenciesMeta": { + "@date-fns/tz": { + "optional": true + }, + "@types/react": { + "optional": true + }, + "date-fns": { + "optional": true + } + } + }, + "node_modules/@base-ui/utils": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/@base-ui/utils/-/utils-0.5.0.tgz", + "integrity": "sha512-dYGGcEttjkYiMoa5nHm8vLaJ2UcuTWxo3BFAwOYXeRg/q7UVVvA6cacEIXEs3FgBfK1CGtW1ptElqs7wsx+t9A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.29.7 || ^8.0.0", + "@floating-ui/utils": "^0.2.12", + "reselect": "^5.3.0", + "use-sync-external-store": "^1.7.0" + }, + "peerDependencies": { + "@types/react": "^17 || ^18 || ^19", + "react": "^17 || ^18 || ^19", + "react-dom": "^17 || ^18 || ^19" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, "node_modules/@cfworker/json-schema": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/@cfworker/json-schema/-/json-schema-4.1.1.tgz", @@ -58,6 +138,42 @@ } } }, + "node_modules/@cloudflare/kumo": { + "version": "2.19.0", + "resolved": "https://registry.npmjs.org/@cloudflare/kumo/-/kumo-2.19.0.tgz", + "integrity": "sha512-r6fQduVNZzRAIEATQLnIbCkYjbfBiELp51donxYkly2a1JE1GW3y+8HRmzp66s0s7xhwAbk9Wp6xFnZmbf6eoA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@base-ui/react": "^1.9.0", + "@shikijs/langs": "^4.0.0", + "@shikijs/themes": "^4.0.0", + "cn": "0.4.0", + "d3-geo": "^3.1.1", + "motion": "^12.34.1", + "react-day-picker": "^9.13.2", + "shiki": "^4.0.0", + "use-sync-external-store": "^1.6.0" + }, + "bin": { + "kumo": "bin/kumo.js" + }, + "peerDependencies": { + "@phosphor-icons/react": "^2.1.10", + "echarts": "^6.0.0", + "react": "^18.0.0 || ^19.0.0", + "react-dom": "^18.0.0 || ^19.0.0", + "zod": "^4.0.0" + }, + "peerDependenciesMeta": { + "echarts": { + "optional": true + }, + "zod": { + "optional": true + } + } + }, "node_modules/@cloudflare/kv-asset-handler": { "version": "0.5.0", "resolved": "https://registry.npmjs.org/@cloudflare/kv-asset-handler/-/kv-asset-handler-0.5.0.tgz", @@ -205,6 +321,25 @@ "node": ">=12" } }, + "node_modules/@date-fns/tz": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@date-fns/tz/-/tz-1.5.0.tgz", + "integrity": "sha512-lwYN/vDPeNRULcepoE/LO2Pgx+7/RV+S9ARfbc9lr2DtGkOD7pAiruHvbR1RX3Qyf6ja47EWJDMsNK5vK08DJg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@emnapi/core": { + "version": "2.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.2.tgz", + "integrity": "sha512-MzCVoWtcg4Pm2B3je5mMvYMvj3MmBKw+fU7vbsJc9/iT8ip6/eYIHo/Dsm/mr+wsHB6SEyJDuxB09Yy6r/8+4A==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "2.2.0", + "tslib": "^2.4.0" + } + }, "node_modules/@emnapi/runtime": { "version": "1.11.3", "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", @@ -216,6 +351,17 @@ "tslib": "^2.4.0" } }, + "node_modules/@emnapi/wasi-threads": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.2.0.tgz", + "integrity": "sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, "node_modules/@esbuild/aix-ppc64": { "version": "0.28.2", "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", @@ -658,6 +804,48 @@ "node": ">=18" } }, + "node_modules/@floating-ui/core": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.8.0.tgz", + "integrity": "sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@floating-ui/utils": "^0.2.12" + } + }, + "node_modules/@floating-ui/dom": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.8.0.tgz", + "integrity": "sha512-yXSrzeHZBTZadLOlfyhCkJHNeLJnHRnRInwdZ40L7ZiaAtrBwoYlsDrX3v5zB1Utk7CLfzcOVnVVWoXEky7Ceg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@floating-ui/core": "^1.8.0", + "@floating-ui/utils": "^0.2.12" + } + }, + "node_modules/@floating-ui/react-dom": { + "version": "2.1.9", + "resolved": "https://registry.npmjs.org/@floating-ui/react-dom/-/react-dom-2.1.9.tgz", + "integrity": "sha512-JDjEFGCpImxDCA7JJKviA0M9+RtmJdj0m/NVU5IMgBK+AmZouAQQ7/+2GLH0GXXY0YMw9oXPB8hKdbPYg5QLYg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@floating-ui/dom": "^1.8.0" + }, + "peerDependencies": { + "react": ">=16.8.0", + "react-dom": ">=16.8.0" + } + }, + "node_modules/@floating-ui/utils": { + "version": "0.2.12", + "resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.12.tgz", + "integrity": "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==", + "dev": true, + "license": "MIT" + }, "node_modules/@img/colour": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", @@ -1320,6 +1508,50 @@ } } }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/gen-mapping/node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping/node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, "node_modules/@jridgewell/resolve-uri": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", @@ -1331,9 +1563,9 @@ } }, "node_modules/@jridgewell/sourcemap-codec": { - "version": "1.5.5", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", - "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", "dev": true, "license": "MIT" }, @@ -1379,6 +1611,41 @@ "node": ">=20" } }, + "node_modules/@modelcontextprotocol/ext-apps": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/ext-apps/-/ext-apps-2.0.4.tgz", + "integrity": "sha512-B+PcbuGiaf0e5I3uy4iO5tS3Abo+5w8JvZFzHMzQdq9yVwP836zJkw2+KCGOQ0r4TM1fuQi4JdnbuWjkS4aBvg==", + "dev": true, + "license": "MIT", + "workspaces": [ + "examples/*" + ], + "dependencies": { + "@standard-schema/spec": "^1.1.0" + }, + "engines": { + "node": ">=20" + }, + "peerDependencies": { + "@modelcontextprotocol/client": "^2.0.0", + "@modelcontextprotocol/core": "^2.0.0", + "@modelcontextprotocol/server": "^2.0.0", + "react": "^17.0.0 || ^18.0.0 || ^19.0.0", + "react-dom": "^17.0.0 || ^18.0.0 || ^19.0.0", + "zod": "^4.2.0" + }, + "peerDependenciesMeta": { + "@modelcontextprotocol/server": { + "optional": true + }, + "react": { + "optional": true + }, + "react-dom": { + "optional": true + } + } + }, "node_modules/@modelcontextprotocol/server": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/@modelcontextprotocol/server/-/server-2.3.1.tgz", @@ -1417,6 +1684,28 @@ "dev": true, "license": "MIT" }, + "node_modules/@napi-rs/wasm-runtime": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.6.tgz", + "integrity": "sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@tybys/wasm-util": "^0.10.3" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1 || 2.0.0-beta.2", + "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2" + } + }, "node_modules/@open-draft/deferred-promise": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/@open-draft/deferred-promise/-/deferred-promise-3.0.0.tgz", @@ -1443,9 +1732,9 @@ "license": "MIT" }, "node_modules/@oxc-project/types": { - "version": "0.155.0", - "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.155.0.tgz", - "integrity": "sha512-SeE8JPwW1xs1tHeNycjUtUBdhorRa8o4jlvjwk49R7/Z291i+4DQa7JJIgOm/TaYQZx+QrPQbVJ/9c8dMIZN8Q==", + "version": "0.156.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.156.0.tgz", + "integrity": "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==", "dev": true, "license": "MIT", "funding": { @@ -2122,6 +2411,20 @@ "node": "^20.19.0 || >=22.12.0" } }, + "node_modules/@phosphor-icons/react": { + "version": "2.1.10", + "resolved": "https://registry.npmjs.org/@phosphor-icons/react/-/react-2.1.10.tgz", + "integrity": "sha512-vt8Tvq8GLjheAZZYa+YG/pW7HDbov8El/MANW8pOAz4eGxrwhnbfrQZq0Cp4q8zBEu8NIhHdnr+r8thnfRSNYA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "react": ">= 16.8", + "react-dom": ">= 16.8" + } + }, "node_modules/@poppinss/colors": { "version": "4.1.6", "resolved": "https://registry.npmjs.org/@poppinss/colors/-/colors-4.1.6.tgz", @@ -2152,9 +2455,9 @@ "license": "MIT" }, "node_modules/@rolldown/binding-android-arm-eabi": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.15.tgz", - "integrity": "sha512-aLcgK9gIJ3YRvrrtfSBbRa27F5WrpiTaPulnFpsHPxpUHgFlSgnU4854MHwoRGEBhfRJDWCS2WQ7lIjskE9Olw==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.19.tgz", + "integrity": "sha512-e+Ebe0WT+9tbXmNKPIiC8YrWAHYwug3m6i4p3rZGGulfZri1jtI4HslT+OZnFf/OIHowWF71DTlHwXBP2SiA7A==", "cpu": [ "arm" ], @@ -2169,9 +2472,9 @@ } }, "node_modules/@rolldown/binding-android-arm64": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.15.tgz", - "integrity": "sha512-xD7DdZCrbThKuxNg7ooQmvp07ys4J/pnSEMTG3/OdOWl6daC67m/Q4fL78sRHMxTH/N4fGUbYhcPM0MF5WFHkg==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.19.tgz", + "integrity": "sha512-hOombrTJ+szt2ciEzS7oCA78lMPBgF5UMQWCJIyNfnrI7GLl8HYoFqCnpL2gcPOaXMqryGCU5ExdQKyDDcC+yA==", "cpu": [ "arm64" ], @@ -2186,9 +2489,9 @@ } }, "node_modules/@rolldown/binding-darwin-arm64": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.15.tgz", - "integrity": "sha512-m2WuQ6r0B4OTYxyPpNLtXaMRbRDUbG8YQV2Q3KTdSSK8Th6KHCnC8jVCJt8bvYeSB5WivkkNbc85mKadaSdOxA==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.19.tgz", + "integrity": "sha512-XoMA2pwCKGTQzUjPgtRwkedH4WmXhdIPKT6l6oOxd1PUbNodGI6DcBekgN7EC//+x3pfBYX/qL1gNmZAqivw5g==", "cpu": [ "arm64" ], @@ -2203,9 +2506,9 @@ } }, "node_modules/@rolldown/binding-darwin-x64": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.15.tgz", - "integrity": "sha512-5RtnsHM36nodM9WbMy+zip0LGS/G+y5wro5RHrpOlr4ac24+1zSi9kiV2MP1myZeZ/ifEHfulQcWjnAXzc2C2A==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.19.tgz", + "integrity": "sha512-zo8EsSSwMZCY/e+fRnGaX02YGgvJD0yvhNi/9hpGPA2MJ9ZF8dPCw75UGfpI6OpQ/myR/dIYmogRvqiZD0TrXg==", "cpu": [ "x64" ], @@ -2220,9 +2523,9 @@ } }, "node_modules/@rolldown/binding-freebsd-x64": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.15.tgz", - "integrity": "sha512-g3l09pyFqhu+135JKkbkwiKGQmwU5hUMUPJ4VdBADvuqR8d33L6H578rh8m7rtxbdp+VmX/+nzI7nvhSZlzpUQ==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.19.tgz", + "integrity": "sha512-O8ISAOfI1nj7AuBPd30FSF47z7f7lzlk5poQVGgiikvQuGEBFYvW8ki+UEnT+YJPnNGjQzn304klt4O9FUE7mA==", "cpu": [ "x64" ], @@ -2237,9 +2540,9 @@ } }, "node_modules/@rolldown/binding-linux-arm-gnueabihf": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.15.tgz", - "integrity": "sha512-nIe3VugI97nGQtspPxDqA4sXMUpeiocKIP/CqpY/u/vgbT+alX+cVxu1C/oVBPKg4feNTmYovE91v4DgXvXNwQ==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.19.tgz", + "integrity": "sha512-/lYCba5NO0yq4S0jGMH8QTBtkvQxoXjoQWzF5BcWp9MjB9jxVRD1GQDNofkVjcOj30DWyhLIN/4Oe60JKzaONw==", "cpu": [ "arm" ], @@ -2254,9 +2557,9 @@ } }, "node_modules/@rolldown/binding-linux-arm64-gnu": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.15.tgz", - "integrity": "sha512-iTBjXx+B5QSvgI89lJfmqh4wTh8NabR1YZIIN3hNx4zSG0EVfVqkOvLulNpG4251pbd6/IAmZ/LefVk1Y4rPhw==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.19.tgz", + "integrity": "sha512-pm/apFMBnSbFb3O6nG5pHO1iqHhZrjGDFEjSm+ot9J17XXPvH9L90y5h+jgfHCE+Qdlsvy8qKEcU4VKxgjD+vA==", "cpu": [ "arm64" ], @@ -2274,9 +2577,9 @@ } }, "node_modules/@rolldown/binding-linux-arm64-musl": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.15.tgz", - "integrity": "sha512-uN26XOnVR7rqQupG3V9oAG2EGGatWjcJHOeDOHUFCh4TBWmP2tHTFoVN13aYbwfm0aHqJAEmcwhAu6sooIjfqQ==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.19.tgz", + "integrity": "sha512-K1SmQp3FFichn8oqrNIwvFoZ5wcvjC7goBzpaMNvLf9FZc+QB/QvLmnpJZgAAGHiD980tP8FZZnXk2K94rvlxg==", "cpu": [ "arm64" ], @@ -2294,9 +2597,9 @@ } }, "node_modules/@rolldown/binding-linux-ppc64-gnu": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.15.tgz", - "integrity": "sha512-9nWkcdd+H+XhaA3fQIwpHnKIrfx/PQ6rO0pivr78Og07tXlUlctBBJoEYLPfhTmCR/QxEVdn6uPjHV5SymPhdw==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.19.tgz", + "integrity": "sha512-I0xwD57jP/3A7+5UPZin2w8Y7XHEmEM5zqpYZOcQ45MlNW6tUJUziymV3yRr7rL4vwyfEcRsRksC4a7Kc08p5Q==", "cpu": [ "ppc64" ], @@ -2314,9 +2617,9 @@ } }, "node_modules/@rolldown/binding-linux-s390x-gnu": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.15.tgz", - "integrity": "sha512-Ggh0ciFjLwIusLSLz7LZYEaGdxOAUJXI+Qu5JCbhPJJHEt8vP+IjRATTJheiJsdzzTYgUiHUiw3X1Ea3ZpMBdA==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.19.tgz", + "integrity": "sha512-BrtEHT24SNXj9HiXqy+s/kXiSiQGt6EKCPUlRirAoIioVxKGnbXBUEkbZASAei7iZJB0/Ynm+0JP00Ipx7AnSw==", "cpu": [ "s390x" ], @@ -2334,9 +2637,9 @@ } }, "node_modules/@rolldown/binding-linux-x64-gnu": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.15.tgz", - "integrity": "sha512-FHg60rS6DBePAYZ9X9F67x+JObFdmgn6tupA1C/a3B+CufFmTD4mX+e8M75tCiAO3foR/6xwVBI0KQiI7sn/rw==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.19.tgz", + "integrity": "sha512-rm75/9DkHKeU2WnA8w4X94WGYgLlDCFCfkQC+4bguVJmC/jvDRv2B+2wLOYhyE0fVuv7//Ckk39OoOufyCu76Q==", "cpu": [ "x64" ], @@ -2354,9 +2657,9 @@ } }, "node_modules/@rolldown/binding-linux-x64-musl": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.15.tgz", - "integrity": "sha512-/cvV/7v5VGz/moiz0XKRj2dE8DzsKyhIu1KpOvJGPjRywg3yscON889UGvAe8zfiJLHup7VLjBduoGWi3HusWQ==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.19.tgz", + "integrity": "sha512-irh/4+iYFM4GAzpluDErgjz89bj6NDtqqMAG/6O1LG38Ed3NpyebzCpcVNkFW8uhy+/3/BocUvnXDR33CXWe9A==", "cpu": [ "x64" ], @@ -2374,9 +2677,9 @@ } }, "node_modules/@rolldown/binding-openharmony-arm64": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.15.tgz", - "integrity": "sha512-MyzC5Hrv/sm+Z7TSGKP/j8001RO2xQm1zOpCNVL4j0cY/VhBZviludA2YFQ7i4lH6ZAXxQm0lcMdBzM+99mE7w==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.19.tgz", + "integrity": "sha512-+KWTWNoPt+CfSq94CiceWu3yPE+QzkaG+phPyz9G60tmZLwfQkcA4AeksafzvJAw4pvg1mcd5a1TkUqVv0s4JA==", "cpu": [ "arm64" ], @@ -2390,10 +2693,40 @@ "node": "^20.19.0 || >=22.12.0" } }, + "node_modules/@rolldown/binding-wasm32-wasi": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.2.19.tgz", + "integrity": "sha512-7EH+skOsl5qpWnK0vzamgJFhOv1cwxQpsxm8tI883K9fur5c27p8q87fzEO6BbBPabA2/+s/zR63/pLc137iOg==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "2.0.0-beta.2", + "@emnapi/runtime": "2.0.0-beta.2", + "@napi-rs/wasm-runtime": "1.2.6" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + } + }, + "node_modules/@rolldown/binding-wasm32-wasi/node_modules/@emnapi/runtime": { + "version": "2.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-beta.2.tgz", + "integrity": "sha512-JcrSPzPvZuNZvJqPTF9Fw25LbOJ8avzFVlaf2grmH4Cku0oGP47tRgqPZadcfj3YoZMHkFVnCYFbQM8I+i5QEw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, "node_modules/@rolldown/binding-win32-arm64-msvc": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.15.tgz", - "integrity": "sha512-+PgYiS+AH5omy6L45ZLxybasauJaj3M8buoT83D+nzPmCayXlxUV9hydhciCKVyIg0B/v0BtXPDE1uGqNwCPpg==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.19.tgz", + "integrity": "sha512-3Q1Yg1Q7tEvBWoZf5rFvG/GKZQPgwfru+p4wBajDfJFBs0SHCpL++dfTjW9gyAKd1T7ZpIYvdaUax7Pa/IhFVQ==", "cpu": [ "arm64" ], @@ -2408,9 +2741,9 @@ } }, "node_modules/@rolldown/binding-win32-x64-msvc": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.15.tgz", - "integrity": "sha512-HFZd2QNQYn1JbIi+Hpd7H+r/lkWxcfIu28nirZ6eCn2LafuvmExMlb/P96Sfx5tf7pPArw39IdhmCF8vmV+NhQ==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.19.tgz", + "integrity": "sha512-y/sqRRc6d7hECzOFc5n3LSeqctmIp9mMjY1Kq4s14uLPd/LZ4z7i1zrW6fMtp2mPeuQIC4e6ULMcwQzMomqQag==", "cpu": [ "x64" ], @@ -2425,9 +2758,117 @@ } }, "node_modules/@rolldown/pluginutils": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", - "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.1.1.tgz", + "integrity": "sha512-glFIJDvLNDtJhT9qrMFWLPbvS+skxgt4L0K8Ei2YtnhPysAJnsI7nyxSJxKj4ADeKX0OLjC4ntRkwpLOoS3rwA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@shikijs/core": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/core/-/core-4.6.0.tgz", + "integrity": "sha512-bfd4OKgvoyXYiYmMRuleA656P4V7M/Du9lcTl38Ngm6KszMj7bq4J1IGZwSYR4c95Tv5UQALtYNWUwaI9UT3xw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/primitive": "4.6.0", + "@shikijs/types": "4.6.0", + "@shikijs/vscode-textmate": "^10.1.0", + "@types/hast": "^3.0.5", + "hast-util-to-html": "^9.0.6" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@shikijs/engine-javascript": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/engine-javascript/-/engine-javascript-4.6.0.tgz", + "integrity": "sha512-K0oqxFoL+kEMdz89mHLFO15Tsbv3kFZ6WR1cXZKMvLSc+oqaM00A6pyga1qSeXB22dP0tTiSApRcGBaKWsEccg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/types": "4.6.0", + "@shikijs/vscode-textmate": "^10.1.0", + "oniguruma-to-es": "^4.3.6" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@shikijs/engine-oniguruma": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/engine-oniguruma/-/engine-oniguruma-4.6.0.tgz", + "integrity": "sha512-aggd6Q7SuJOXNnsUbfG2XesxBJKBMAw/PDTUo9PyRjMaaJJ2dNrI+q0C+25ARXAK9yLHAlwxc9oRT2u68YKZ7w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/types": "4.6.0", + "@shikijs/vscode-textmate": "^10.1.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@shikijs/langs": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/langs/-/langs-4.6.0.tgz", + "integrity": "sha512-1yMEX3oCVV54LUq/ovfpRkDQoYDkcvjSWFFa/YLUDMiSoRzMi2uxLJYbv41ahT8Lu9lFMaa7hecd3Q39trqUyg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/types": "4.6.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@shikijs/primitive": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/primitive/-/primitive-4.6.0.tgz", + "integrity": "sha512-c54+TQEo9ToqgfL/AU8FpjnV09+GA9Oa7M5ROkkXteZfp5XzpAJGXjjvZQFQioJOwm/w/6Z3lIzQstAkl8coag==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/types": "4.6.0", + "@shikijs/vscode-textmate": "^10.1.0", + "@types/hast": "^3.0.5" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@shikijs/themes": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/themes/-/themes-4.6.0.tgz", + "integrity": "sha512-qHAVAs80RiGD+IRuH9G+JPDOEc9A/kHsng4EzCUCwB9bLzW6Z0y9WETh2YyCcADJBmfrIaJ1Jp7KBNP6FHkgtQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/types": "4.6.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@shikijs/types": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/types/-/types-4.6.0.tgz", + "integrity": "sha512-+ENG1adsKt/X7cRYw1Nl7BEpBmPOjmQ7bR/eGmHuMlT8gtOFf3KEi5l31DJYyAWhW6Y6bjP1plU7FmaxWGENFw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/vscode-textmate": "^10.1.0", + "@types/hast": "^3.0.5" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@shikijs/vscode-textmate": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/@shikijs/vscode-textmate/-/vscode-textmate-10.1.0.tgz", + "integrity": "sha512-cVBuhDQjBZaNMTwBquYfPydrUP+E3hE6oYGasx8h6ZrODIM7/r+gxLDXdd66oszbrggZHEntdE6j+5gYIVyMWQ==", "dev": true, "license": "MIT" }, @@ -2458,39 +2899,460 @@ "dev": true, "license": "MIT" }, - "node_modules/@types/chai": { - "version": "5.2.3", - "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", - "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "node_modules/@tabby_ai/hijri-converter": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/@tabby_ai/hijri-converter/-/hijri-converter-1.0.5.tgz", + "integrity": "sha512-r5bClKrcIusDoo049dSL8CawnHR6mRdDwhlQuIgZRNty68q0x8k3Lf1BtPAMxRf/GgnHBnIO4ujd3+GQdLWzxQ==", "dev": true, "license": "MIT", - "dependencies": { - "@types/deep-eql": "*", - "assertion-error": "^2.0.1" + "engines": { + "node": ">=16.0.0" } }, - "node_modules/@types/deep-eql": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", - "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/estree": { - "version": "1.0.9", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", - "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "node_modules/@tailwindcss/node": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.3.5.tgz", + "integrity": "sha512-yT53FzV4ke0cr/BguDxhWMpm5MJu1O2muzk+tKw6lKHjODAsYArBbWwFbJiaksfzFv1tpkO9QHGzmfs1hJT66g==", "dev": true, - "license": "MIT" + "license": "MIT", + "dependencies": { + "@jridgewell/remapping": "^2.3.5", + "enhanced-resolve": "^5.24.5", + "jiti": "^2.7.0", + "lightningcss": "1.33.0", + "magic-string": "^1.1.0", + "source-map-js": "^1.2.1", + "tailwindcss": "4.3.5" + } }, - "node_modules/@types/node": { - "version": "25.0.6", - "resolved": "https://registry.npmjs.org/@types/node/-/node-25.0.6.tgz", - "integrity": "sha512-NNu0sjyNxpoiW3YuVFfNz7mxSQ+S4X2G28uqg2s+CzoqoQjLPsWSbsFFyztIAqt2vb8kfEAsJNepMGPTxFDx3Q==", + "node_modules/@tailwindcss/node/node_modules/magic-string": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz", + "integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==", "dev": true, "license": "MIT", "dependencies": { - "undici-types": "~7.16.0" + "@jridgewell/sourcemap-codec": "^1.6.0" + } + }, + "node_modules/@tailwindcss/oxide": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide/-/oxide-4.3.5.tgz", + "integrity": "sha512-PynqGLZsZvwM9tqD/CUxkOIfyd6K5elZ2MooauzJryP/UqXYgi3yYbtt3N0Xe+MHV/eFKPFQCEfIKAqlAS1CBg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 20" + }, + "optionalDependencies": { + "@tailwindcss/oxide-android-arm64": "4.3.5", + "@tailwindcss/oxide-darwin-arm64": "4.3.5", + "@tailwindcss/oxide-darwin-x64": "4.3.5", + "@tailwindcss/oxide-freebsd-x64": "4.3.5", + "@tailwindcss/oxide-linux-arm-gnueabihf": "4.3.5", + "@tailwindcss/oxide-linux-arm64-gnu": "4.3.5", + "@tailwindcss/oxide-linux-arm64-musl": "4.3.5", + "@tailwindcss/oxide-linux-x64-gnu": "4.3.5", + "@tailwindcss/oxide-linux-x64-musl": "4.3.5", + "@tailwindcss/oxide-wasm32-wasi": "4.3.5", + "@tailwindcss/oxide-win32-arm64-msvc": "4.3.5", + "@tailwindcss/oxide-win32-x64-msvc": "4.3.5" + } + }, + "node_modules/@tailwindcss/oxide-android-arm64": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-android-arm64/-/oxide-android-arm64-4.3.5.tgz", + "integrity": "sha512-Se0z5xMqcSQanJD1IYmO0cGpK3iv0fp3ZsIT7xRJZ1Da5PghvNoc46zz4jIQn+aan3dV9T8AermFNN9QPmsh0Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-darwin-arm64": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-arm64/-/oxide-darwin-arm64-4.3.5.tgz", + "integrity": "sha512-UPrgTDuUbvmqGMZuCnmI3FKee/tYKzKdp00/kuB4oSGB213VYg8QTdF7lVhnPoBXq/mIfJ+ILoBFqNOboWcMwQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-darwin-x64": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-x64/-/oxide-darwin-x64-4.3.5.tgz", + "integrity": "sha512-E+p7HEtjI0b8D7kbbWxH067cGui6d4c79COGko9fAPVE3rwc1E7ld2HFCbaG86AOGWS5VKQYqZOaf38ya4uxTQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-freebsd-x64": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-freebsd-x64/-/oxide-freebsd-x64-4.3.5.tgz", + "integrity": "sha512-yWEWcWyAG7rWOcTpJTjdhQ3pcaFY2h+0bqTRfgU3G2fz87ZU3AKdvdZKhslD+kyHnjBUWKvNdRYwIYC5dI1tIg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm-gnueabihf": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm-gnueabihf/-/oxide-linux-arm-gnueabihf-4.3.5.tgz", + "integrity": "sha512-WmeVjtJhZlr+smpqcdR2kQkkn6arHIJnUIBxTO2EJcTLGY1ecVXNo2hbSn8xc0IH2aEtys936iMWKGyj0GaKnA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm64-gnu": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-gnu/-/oxide-linux-arm64-gnu-4.3.5.tgz", + "integrity": "sha512-DTCSyucc6ShMp1QMqV5R94Z7xlgNgUzkGmFF1rL5HH2Qjy4eSmEqy+YLGkqqYvWa4sILtgrBt1JjRKbneQtiFQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm64-musl": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-musl/-/oxide-linux-arm64-musl-4.3.5.tgz", + "integrity": "sha512-H9lsvO4x9E4nE4Hi8h7NHHw0O/kcVSu+iOyFHNGdYzazGgDjFHZbE6S3hQ8kMcbNXSBlMdNi67LV5EVqtpaJtw==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-x64-gnu": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-gnu/-/oxide-linux-x64-gnu-4.3.5.tgz", + "integrity": "sha512-4uxQvtBvPuIdl13WfUBj9xMZHH14PtHZ8OZdtLmdyDtG66sCa1t599NZT+jagkUzRtWhuul1qRZQ1nAJscXN5g==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-x64-musl": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-musl/-/oxide-linux-x64-musl-4.3.5.tgz", + "integrity": "sha512-0JQAzs7jwbA7O6+z/adU+Jk3AXwsu3npAhtr5escXS7TqEqWcaDV7qHuI+0Vy/KQRuVGnLQREcSJWYauyV3oqg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-wasm32-wasi/-/oxide-wasm32-wasi-4.3.5.tgz", + "integrity": "sha512-OJhFmlEfdzMr+avACdi40RPtnkW0B6hXyxL/8r+tnEHBWZji36CYRjEXrrvgBmaYsD3oEOBqwYFRKsYvzFe7Bw==", + "bundleDependencies": [ + "@napi-rs/wasm-runtime", + "@emnapi/core", + "@emnapi/runtime", + "@tybys/wasm-util", + "@emnapi/wasi-threads", + "tslib" + ], + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "^1.11.3", + "@emnapi/runtime": "^1.11.3", + "@emnapi/wasi-threads": "^1.2.3", + "@napi-rs/wasm-runtime": "^1.2.2", + "@tybys/wasm-util": "^0.10.3", + "tslib": "^2.8.1" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core": { + "version": "1.11.3", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "1.2.3", + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime": { + "version": "1.11.3", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads": { + "version": "1.2.3", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime": { + "version": "1.2.2", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@tybys/wasm-util": "^0.10.3" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1 || ^2.0.0-alpha.3", + "@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.3" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util": { + "version": "0.10.3", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib": { + "version": "2.8.1", + "dev": true, + "inBundle": true, + "license": "0BSD", + "optional": true + }, + "node_modules/@tailwindcss/oxide-win32-arm64-msvc": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.3.5.tgz", + "integrity": "sha512-9o8jgthi+QE5eandnboiJT64VQfnIArfZzSTdgbhEK5aafdiu2jTW9Honi/mwYHxBZuH1vAC57IFyrh+0iK5Gg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-win32-x64-msvc": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-x64-msvc/-/oxide-win32-x64-msvc-4.3.5.tgz", + "integrity": "sha512-XiKFfIy1RWe7qK4WqByxNW7Oz1/nkOy8o/BWhHminyV1PmpUd8Eedj5v2A8h2kpqeVlz6xRnwk9Fr/ZXNLcZfg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/vite": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/vite/-/vite-4.3.5.tgz", + "integrity": "sha512-BCNiY0a1ZjdOHVqw7kyb7U72BwfMF3dfUuN+tQsLWky/J5JOI/r7abibglXfygrZhVO/3u3V+E25kkKTeMkXaQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@tailwindcss/node": "4.3.5", + "@tailwindcss/oxide": "4.3.5", + "tailwindcss": "4.3.5" + }, + "peerDependencies": { + "vite": "^5.2.0 || ^6 || ^7 || ^8" + } + }, + "node_modules/@tybys/wasm-util": { + "version": "0.10.5", + "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.5.tgz", + "integrity": "sha512-dOGOPxlaNV+G046mZzN+9C0dAcQZeSKcXiVaM0TYy/LM4ttTmgSBDxYfovcYI8Em3+eAbiAYpvWLOv8+ZVRJKA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/hast": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.5.tgz", + "integrity": "sha512-rp/ezSWaD1m44dPKICGhiskI13nVr7qTloFwDa/IYkhhf5nzwP+zIQcIJh3WIFSBOy/H1PzB40jPjMDksN4F+g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "*" + } + }, + "node_modules/@types/mdast": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-4.0.4.tgz", + "integrity": "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "*" + } + }, + "node_modules/@types/node": { + "version": "25.0.6", + "resolved": "https://registry.npmjs.org/@types/node/-/node-25.0.6.tgz", + "integrity": "sha512-NNu0sjyNxpoiW3YuVFfNz7mxSQ+S4X2G28uqg2s+CzoqoQjLPsWSbsFFyztIAqt2vb8kfEAsJNepMGPTxFDx3Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~7.16.0" + } + }, + "node_modules/@types/react": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz", + "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==", + "dev": true, + "license": "MIT", + "dependencies": { + "csstype": "^3.2.2" + } + }, + "node_modules/@types/react-dom": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.3.0.tgz", + "integrity": "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "^19.3.0" } }, "node_modules/@types/set-cookie-parser": { @@ -2510,6 +3372,20 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/unist": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz", + "integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/@ungap/structured-clone": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.4.0.tgz", + "integrity": "sha512-1mEZtMKPM09vDmQt5y7YvmN2+DFTP7Tg0EWXdic8/C6VRnpb33e4ghisCIE3WZjsE2N8mf+QV1Zqh7ZFYLWInQ==", + "dev": true, + "license": "ISC" + }, "node_modules/@vitest/expect": { "version": "4.1.12", "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.12.tgz", @@ -2666,6 +3542,17 @@ "dev": true, "license": "MIT" }, + "node_modules/ccount": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/ccount/-/ccount-2.0.1.tgz", + "integrity": "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/chai": { "version": "6.3.0", "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz", @@ -2676,6 +3563,28 @@ "node": ">=18" } }, + "node_modules/character-entities-html4": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/character-entities-html4/-/character-entities-html4-2.1.0.tgz", + "integrity": "sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/character-entities-legacy": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/character-entities-legacy/-/character-entities-legacy-3.0.0.tgz", + "integrity": "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/cjs-module-lexer": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-1.2.3.tgz", @@ -2708,6 +3617,19 @@ "node": ">=12" } }, + "node_modules/cn": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/cn/-/cn-0.4.0.tgz", + "integrity": "sha512-qOAeUhPwPzBxx6jaeQdo646XIKliKHc2j1ZF7Ngb1o0pJZKH5gq8FkA0aVdUdPFUDXNXyUCXpCtoJISo6dhizg==", + "dev": true, + "license": "MIT", + "bin": { + "cn": "bin/cn.mjs" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/color-convert": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", @@ -2728,6 +3650,17 @@ "dev": true, "license": "MIT" }, + "node_modules/comma-separated-tokens": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz", + "integrity": "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/convert-source-map": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", @@ -2764,6 +3697,67 @@ "node": ">= 8" } }, + "node_modules/csstype": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.4.tgz", + "integrity": "sha512-PoKaoPzQapnEoqUSnHx1u6W6ku8CVEgKsnpmmzU3m1nwkidpPBQ8V/Zq2+bWNrsOKoKLwTGdbx6xF7BXP1zLVQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/d3-array": { + "version": "3.2.5", + "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.5.tgz", + "integrity": "sha512-Th8qGXoBalmWsstpkuhmBuTsBQIFqYOJtjlBvNVvBfJ8E3uYusBUwUR8HU20U0qKKQkgCvKyR1YjiozWadk5QA==", + "dev": true, + "license": "ISC", + "dependencies": { + "internmap": "1 - 2" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-geo": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/d3-geo/-/d3-geo-3.1.2.tgz", + "integrity": "sha512-5R8ZgDQorIxmauv7R6gpE/ndz+Z0qAZssigq0aXFdvPHdY41RqtW02jrRUQAL724NdPABYXo1+gQEGBBr7uKNg==", + "dev": true, + "license": "ISC", + "dependencies": { + "d3-array": "2.5.0 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/date-fns": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/date-fns/-/date-fns-4.4.0.tgz", + "integrity": "sha512-+1UMbeh68lH1SegH83CGWwpb6OHHbpSgr3+s5Eww5M4CAgswBpoWS0AjTOfEJ33HiYKz1hdj/KTFprzXHmq/6w==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/kossnocorp" + } + }, + "node_modules/date-fns-jalali": { + "version": "4.1.0-0", + "resolved": "https://registry.npmjs.org/date-fns-jalali/-/date-fns-jalali-4.1.0-0.tgz", + "integrity": "sha512-hTIP/z+t+qKwBDcmmsnmjWTduxCg+5KfdqWQvb2X/8C9+knYY6epN/pfxdDuyVlSVeFz0sM5eEfwIUQ70U4ckg==", + "dev": true, + "license": "MIT" + }, + "node_modules/dequal": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", + "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/detect-libc": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", @@ -2774,6 +3768,20 @@ "node": ">=8" } }, + "node_modules/devlop": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/devlop/-/devlop-1.1.0.tgz", + "integrity": "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==", + "dev": true, + "license": "MIT", + "dependencies": { + "dequal": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/emoji-regex": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", @@ -2781,6 +3789,20 @@ "dev": true, "license": "MIT" }, + "node_modules/enhanced-resolve": { + "version": "5.27.0", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.27.0.tgz", + "integrity": "sha512-Do6BB2xzlcc/odFg+XEYyneAx4T/WfywO71yw9ePS2tVfRsf7JVR4mUeELadIeHzixkzbG5DpluiEFPi2WGfYQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.4", + "tapable": "^2.3.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, "node_modules/error-stack-parser-es": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/error-stack-parser-es/-/error-stack-parser-es-1.0.5.tgz", @@ -2938,6 +3960,34 @@ } } }, + "node_modules/framer-motion": { + "version": "12.43.0", + "resolved": "https://registry.npmjs.org/framer-motion/-/framer-motion-12.43.0.tgz", + "integrity": "sha512-1eaL3RvR/kAlbG7UYcpMptEyzPoENO0c6w7ZnB3/hh2vSAz/6uGAFn6fdoqTBguNstf3MsFhJHsD/0DHiclG+g==", + "dev": true, + "license": "MIT", + "dependencies": { + "motion-dom": "^12.43.0", + "motion-utils": "^12.39.0", + "tslib": "^2.4.0" + }, + "peerDependencies": { + "@emotion/is-prop-valid": "*", + "react": "^18.0.0 || ^19.0.0", + "react-dom": "^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@emotion/is-prop-valid": { + "optional": true + }, + "react": { + "optional": true + }, + "react-dom": { + "optional": true + } + } + }, "node_modules/fsevents": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", @@ -2963,6 +4013,13 @@ "node": "6.* || 8.* || >= 10.*" } }, + "node_modules/graceful-fs": { + "version": "4.2.12", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.12.tgz", + "integrity": "sha512-iuyGF2E4oafQfPsRrG2wtY2ILupMhvtdrhzrxB+0VcjsPpSPttpfYdjnGFGsTi5MaJFjI1jOKHPQ6UTbTj9TAw==", + "dev": true, + "license": "BlueOak-1.0.0" + }, "node_modules/graphql": { "version": "16.14.1", "resolved": "https://registry.npmjs.org/graphql/-/graphql-16.14.1.tgz", @@ -2973,6 +4030,44 @@ "node": "^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0" } }, + "node_modules/hast-util-to-html": { + "version": "9.0.7", + "resolved": "https://registry.npmjs.org/hast-util-to-html/-/hast-util-to-html-9.0.7.tgz", + "integrity": "sha512-HYNDA3qdnzUPitY/LcQm1nWs8z0cWFNH1Nz09jdI/tXifAqF7h3+jrLl4S/b9Mi4VSjn0Dsn54ctuTV6zhBthA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "@types/unist": "^3.0.0", + "ccount": "^2.0.0", + "comma-separated-tokens": "^2.0.0", + "hast-util-whitespace": "^3.0.0", + "html-void-elements": "^3.0.0", + "mdast-util-to-hast": "^13.0.0", + "property-information": "^7.0.0", + "space-separated-tokens": "^2.0.0", + "stringify-entities": "^4.0.0", + "zwitch": "^2.0.4" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-whitespace": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/hast-util-whitespace/-/hast-util-whitespace-3.0.0.tgz", + "integrity": "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/headers-polyfill": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/headers-polyfill/-/headers-polyfill-5.0.1.tgz", @@ -2993,6 +4088,27 @@ "node": ">=16.9.0" } }, + "node_modules/html-void-elements": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/html-void-elements/-/html-void-elements-3.0.0.tgz", + "integrity": "sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/internmap": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/internmap/-/internmap-2.0.3.tgz", + "integrity": "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=12" + } + }, "node_modules/is-fullwidth-code-point": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", @@ -3017,6 +4133,16 @@ "dev": true, "license": "ISC" }, + "node_modules/jiti": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz", + "integrity": "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==", + "dev": true, + "license": "MIT", + "bin": { + "jiti": "lib/jiti-cli.mjs" + } + }, "node_modules/jose": { "version": "6.1.3", "resolved": "https://registry.npmjs.org/jose/-/jose-6.1.3.tgz", @@ -3302,24 +4428,140 @@ "os": [ "win32" ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/mdast-util-to-hast": { + "version": "13.2.2", + "resolved": "https://registry.npmjs.org/mdast-util-to-hast/-/mdast-util-to-hast-13.2.2.tgz", + "integrity": "sha512-l2pnmOuqs+SGLVpTVXnRLQu5v1AzvDe181404fbXzzqObVxrAnnVxapAP27pUwzLBL/ABIkgUhGlPVU7QSvIFg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "@types/mdast": "^4.0.0", + "@ungap/structured-clone": "^1.0.0", + "devlop": "^1.0.0", + "micromark-util-sanitize-uri": "^2.0.0", + "trim-lines": "^3.0.0", + "unist-util-position": "^5.0.0", + "unist-util-visit": "^5.0.0", + "vfile": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/micromark-util-character": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/micromark-util-character/-/micromark-util-character-2.1.1.tgz", + "integrity": "sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" } }, - "node_modules/magic-string": { - "version": "0.30.21", - "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", - "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "node_modules/micromark-util-encode": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-encode/-/micromark-util-encode-2.0.1.tgz", + "integrity": "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-sanitize-uri": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-2.0.1.tgz", + "integrity": "sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ==", "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], "license": "MIT", "dependencies": { - "@jridgewell/sourcemap-codec": "^1.5.5" + "micromark-util-character": "^2.0.0", + "micromark-util-encode": "^2.0.0", + "micromark-util-symbol": "^2.0.0" } }, + "node_modules/micromark-util-symbol": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-symbol/-/micromark-util-symbol-2.0.1.tgz", + "integrity": "sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-types": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/micromark-util-types/-/micromark-util-types-2.0.3.tgz", + "integrity": "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, "node_modules/miniflare": { "version": "5.20261023.1-beta", "resolved": "https://registry.npmjs.org/miniflare/-/miniflare-5.20261023.1-beta.tgz", @@ -3338,6 +4580,50 @@ "node": ">=22.0.0" } }, + "node_modules/motion": { + "version": "12.43.0", + "resolved": "https://registry.npmjs.org/motion/-/motion-12.43.0.tgz", + "integrity": "sha512-BQgQbSa9Hn3/mtbib0MK53y6JSANa+YKUKlaYnWzAVDH424RYQ5LVpV3pNiWH00BA2z4ojsSdMzqT7g2FQwjuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "framer-motion": "^12.43.0", + "tslib": "^2.4.0" + }, + "peerDependencies": { + "@emotion/is-prop-valid": "*", + "react": "^18.0.0 || ^19.0.0", + "react-dom": "^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@emotion/is-prop-valid": { + "optional": true + }, + "react": { + "optional": true + }, + "react-dom": { + "optional": true + } + } + }, + "node_modules/motion-dom": { + "version": "12.43.0", + "resolved": "https://registry.npmjs.org/motion-dom/-/motion-dom-12.43.0.tgz", + "integrity": "sha512-azKON4d9S65PEoFUiQTMTgPheEmzf2QngdRc50AKfJp9Q9mmcBVw22c8eMq9k8kxOFHdL7+WZY7N/5F/lwiDag==", + "dev": true, + "license": "MIT", + "dependencies": { + "motion-utils": "^12.39.0" + } + }, + "node_modules/motion-utils": { + "version": "12.39.0", + "resolved": "https://registry.npmjs.org/motion-utils/-/motion-utils-12.39.0.tgz", + "integrity": "sha512-8nadJAJjTtqRkmRF36FoJTrywK9nnFmnPwnSMyxaOCU7GDjN9RTMJIxx9De8ErM+vpPhMccr/6fo5WciyQLnMQ==", + "dev": true, + "license": "MIT" + }, "node_modules/msw": { "version": "2.14.6", "resolved": "https://registry.npmjs.org/msw/-/msw-2.14.6.tgz", @@ -3426,6 +4712,25 @@ "node": ">=12.20.0" } }, + "node_modules/oniguruma-parser": { + "version": "0.12.2", + "resolved": "https://registry.npmjs.org/oniguruma-parser/-/oniguruma-parser-0.12.2.tgz", + "integrity": "sha512-6HVa5oIrgMC6aA6WF6XyyqbhRPJrKR02L20+2+zpDtO5QAzGHAUGw5TKQvwi5vctNnRHkJYmjAhRVQF2EKdTQw==", + "dev": true, + "license": "MIT" + }, + "node_modules/oniguruma-to-es": { + "version": "4.3.6", + "resolved": "https://registry.npmjs.org/oniguruma-to-es/-/oniguruma-to-es-4.3.6.tgz", + "integrity": "sha512-csuQ9x3Yr0cEIs/Zgx/OEt9iBw9vqIunAPQkx19R/fiMq2oGVTgcMqO/V3Ybqefr1TBvosI6jU539ksaBULJyA==", + "dev": true, + "license": "MIT", + "dependencies": { + "oniguruma-parser": "^0.12.2", + "regex": "^6.1.0", + "regex-recursion": "^6.0.2" + } + }, "node_modules/outvariant": { "version": "1.4.3", "resolved": "https://registry.npmjs.org/outvariant/-/outvariant-1.4.3.tgz", @@ -3589,9 +4894,9 @@ } }, "node_modules/postcss": { - "version": "8.5.31", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.31.tgz", - "integrity": "sha512-YUbWYCgErwnMAVkjUnYa+KlMBzGpHwiIt/DE7f0G33AuX2LH9UcTk6KgWxd3zRU+pN3u/C+Xl3EnMLM4Hea7Sg==", + "version": "8.5.33", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.33.tgz", + "integrity": "sha512-RVHEU9/Pp1Fnjr/MpAJsZoADukCKhfIi15OunEYiGktIkYLkPVvC1sioWolGDS7XByMTx9m/IGbro0Js13zhnQ==", "dev": true, "funding": [ { @@ -3617,6 +4922,90 @@ "node": "^10 || ^12 || >=14" } }, + "node_modules/property-information": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/property-information/-/property-information-7.2.0.tgz", + "integrity": "sha512-IAtzIB6sUiWaJYrX9smp3V46pBGbBeLFRGdh25kg1334VcBlD8HzhPeNIWQH9zhGmo2itIe25EHt9dQP7G5hmg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/react": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react/-/react-19.3.1.tgz", + "integrity": "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-day-picker": { + "version": "9.14.0", + "resolved": "https://registry.npmjs.org/react-day-picker/-/react-day-picker-9.14.0.tgz", + "integrity": "sha512-tBaoDWjPwe0M5pGrum4H0SR6Lyk+BO9oHnp9JbKpGKW2mlraNPgP9BMfsg5pWpwrssARmeqk7YBl2oXutZTaHA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@date-fns/tz": "^1.4.1", + "@tabby_ai/hijri-converter": "1.0.5", + "date-fns": "^4.1.0", + "date-fns-jalali": "4.1.0-0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "individual", + "url": "https://github.com/sponsors/gpbl" + }, + "peerDependencies": { + "react": ">=16.8.0" + } + }, + "node_modules/react-dom": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.1.tgz", + "integrity": "sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "scheduler": "^0.28.0" + }, + "peerDependencies": { + "react": "^19.3.1" + } + }, + "node_modules/regex": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/regex/-/regex-6.1.0.tgz", + "integrity": "sha512-6VwtthbV4o/7+OaAF9I5L5V3llLEsoPyq9P1JVXkedTP33c7MfCG0/5NOPcSJn0TzXcG9YUrR0gQSWioew3LDg==", + "dev": true, + "license": "MIT", + "dependencies": { + "regex-utilities": "^2.3.0" + } + }, + "node_modules/regex-recursion": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/regex-recursion/-/regex-recursion-6.0.2.tgz", + "integrity": "sha512-0YCaSCq2VRIebiaUviZNs0cBz1kg5kVS2UKUfNIx8YVs1cN3AV7NTctO5FOKBA+UT2BPJIWZauYHPqJODG50cg==", + "dev": true, + "license": "MIT", + "dependencies": { + "regex-utilities": "^2.3.0" + } + }, + "node_modules/regex-utilities": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/regex-utilities/-/regex-utilities-2.3.0.tgz", + "integrity": "sha512-8VhliFJAWRaUiVvREIiW2NXXTmHs4vMNnSzuJVhscgmGav3g9VDxLrQndI3dZZVVdp0ZO/5v0xmX516/7M9cng==", + "dev": true, + "license": "MIT" + }, "node_modules/require-directory": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", @@ -3627,6 +5016,13 @@ "node": ">=0.10.0" } }, + "node_modules/reselect": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/reselect/-/reselect-5.3.0.tgz", + "integrity": "sha512-XGoLeRAVzUTcJ1qkxPQhDJyIZ5d6zzZD9nT7AEZOaaU9UbWclhycElmhO+VD5bFeLuzhPBaOV2oXC8uG35ZSpg==", + "dev": true, + "license": "MIT" + }, "node_modules/rettime": { "version": "0.11.11", "resolved": "https://registry.npmjs.org/rettime/-/rettime-0.11.11.tgz", @@ -3635,13 +5031,13 @@ "license": "MIT" }, "node_modules/rolldown": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.15.tgz", - "integrity": "sha512-6odND+fel5zVw3I4Yc2e69gvguDnX0CAAGiNDZSq4ik5WUcaLrkD2GLuog0XcODbor31hZ5ayEMgVDno+KPV5g==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.19.tgz", + "integrity": "sha512-QIiV1J9d0pzN4jeeTH4sjPy0AZ6cAy2cG0ExeoE1+U8Rvj+hR3gYkokx0YbeUNGlZqiQJJ2utcETe0oKXwzsuA==", "dev": true, "license": "MIT", "dependencies": { - "@oxc-project/types": "=0.155.0", + "@oxc-project/types": "=0.156.0", "@rolldown/pluginutils": "^1.0.0" }, "bin": { @@ -3651,22 +5047,30 @@ "node": "^20.19.0 || >=22.12.0" }, "optionalDependencies": { - "@rolldown/binding-android-arm-eabi": "1.2.15", - "@rolldown/binding-android-arm64": "1.2.15", - "@rolldown/binding-darwin-arm64": "1.2.15", - "@rolldown/binding-darwin-x64": "1.2.15", - "@rolldown/binding-freebsd-x64": "1.2.15", - "@rolldown/binding-linux-arm-gnueabihf": "1.2.15", - "@rolldown/binding-linux-arm64-gnu": "1.2.15", - "@rolldown/binding-linux-arm64-musl": "1.2.15", - "@rolldown/binding-linux-ppc64-gnu": "1.2.15", - "@rolldown/binding-linux-s390x-gnu": "1.2.15", - "@rolldown/binding-linux-x64-gnu": "1.2.15", - "@rolldown/binding-linux-x64-musl": "1.2.15", - "@rolldown/binding-openharmony-arm64": "1.2.15", - "@rolldown/binding-win32-arm64-msvc": "1.2.15", - "@rolldown/binding-win32-x64-msvc": "1.2.15" - } + "@rolldown/binding-android-arm-eabi": "1.2.19", + "@rolldown/binding-android-arm64": "1.2.19", + "@rolldown/binding-darwin-arm64": "1.2.19", + "@rolldown/binding-darwin-x64": "1.2.19", + "@rolldown/binding-freebsd-x64": "1.2.19", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.19", + "@rolldown/binding-linux-arm64-gnu": "1.2.19", + "@rolldown/binding-linux-arm64-musl": "1.2.19", + "@rolldown/binding-linux-ppc64-gnu": "1.2.19", + "@rolldown/binding-linux-s390x-gnu": "1.2.19", + "@rolldown/binding-linux-x64-gnu": "1.2.19", + "@rolldown/binding-linux-x64-musl": "1.2.19", + "@rolldown/binding-openharmony-arm64": "1.2.19", + "@rolldown/binding-wasm32-wasi": "1.2.19", + "@rolldown/binding-win32-arm64-msvc": "1.2.19", + "@rolldown/binding-win32-x64-msvc": "1.2.19" + } + }, + "node_modules/scheduler": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz", + "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==", + "dev": true, + "license": "MIT" }, "node_modules/semver": { "version": "7.8.5", @@ -3761,6 +5165,26 @@ "node": ">=8" } }, + "node_modules/shiki": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/shiki/-/shiki-4.6.0.tgz", + "integrity": "sha512-imjLsVHgPuWhvpU3P+zOekvMYqnel7QmKsFC4Sn0fCuAvaaalBsxwKEsrU8Ko5BdFnZA6Go/8a0RzahS634UgA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/core": "4.6.0", + "@shikijs/engine-javascript": "4.6.0", + "@shikijs/engine-oniguruma": "4.6.0", + "@shikijs/langs": "4.6.0", + "@shikijs/themes": "4.6.0", + "@shikijs/types": "4.6.0", + "@shikijs/vscode-textmate": "^10.1.0", + "@types/hast": "^3.0.5" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/siginfo": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", @@ -3782,15 +5206,26 @@ } }, "node_modules/source-map-js": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", - "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.3.tgz", + "integrity": "sha512-xj+WrAkyv5Qp+t7r9N5HvCBu7g1qOe6CKRNpq22X1GGcPEQADFU54v5qsPVs3/vrUFQ7XivFrcAVKA2stI0kWA==", "dev": true, "license": "BSD-3-Clause", "engines": { "node": ">=0.10.0" } }, + "node_modules/space-separated-tokens": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-2.0.2.tgz", + "integrity": "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/stackback": { "version": "0.0.2", "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", @@ -3837,6 +5272,21 @@ "node": ">=8" } }, + "node_modules/stringify-entities": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/stringify-entities/-/stringify-entities-4.0.4.tgz", + "integrity": "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==", + "dev": true, + "license": "MIT", + "dependencies": { + "character-entities-html4": "^2.0.0", + "character-entities-legacy": "^3.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/strip-ansi": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", @@ -3876,6 +5326,27 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/tailwindcss": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.3.5.tgz", + "integrity": "sha512-FcQk9BuffmEHJP2G0XmB2SplU1aLTI7j07Kunk+U74Ny+XiWOtzXz9aujFZ/avntw1e2cOv/3PkgzflQ7gX2vQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/tapable": { + "version": "2.3.4", + "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.3.4.tgz", + "integrity": "sha512-NHFiWnAbMJxNNpBwiO7jJVGDuqMxT9/oV8v57RR+fgBQShkJil5inGD8/xWy0hjLyHQyX1tu27QANhlz3KBqCg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, "node_modules/tinybench": { "version": "2.9.0", "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", @@ -3963,13 +5434,23 @@ "node": ">=16" } }, + "node_modules/trim-lines": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz", + "integrity": "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/tslib": { "version": "2.8.1", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", "dev": true, - "license": "0BSD", - "optional": true + "license": "0BSD" }, "node_modules/tsx": { "version": "4.22.4", @@ -4047,6 +5528,79 @@ "pathe": "^2.0.3" } }, + "node_modules/unist-util-is": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-6.0.1.tgz", + "integrity": "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-position": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/unist-util-position/-/unist-util-position-5.0.0.tgz", + "integrity": "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-stringify-position": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/unist-util-stringify-position/-/unist-util-stringify-position-4.0.0.tgz", + "integrity": "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-visit": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-5.2.0.tgz", + "integrity": "sha512-fpsYs/VVoZxfGY9/j3FQpZmN8wdLJaV1Pt38AaJNZu9uKIHcFU3halCdBveEq1HGKO1OEfJY65w1zvoFV1b3qQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-is": "^6.0.0", + "unist-util-visit-parents": "^6.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-visit-parents": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.1.0.tgz", + "integrity": "sha512-vKXxz6O38sKDj1mtx/k2cWvkkFBuYGx6uGrlzBkVeWCRF/F8sdI0j3Wbkz/5rVNRRuVc8UrgRdbCxNhmYXgP3w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-is": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/until-async": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/until-async/-/until-async-3.0.2.tgz", @@ -4057,17 +5611,57 @@ "url": "https://github.com/sponsors/kettanaito" } }, + "node_modules/use-sync-external-store": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.7.0.tgz", + "integrity": "sha512-6L+EeigHMQhdaIPNIFUKwfWJSwWFQ8gJbJ2DLOs5sDIegTwR9fRxvnM3uciHKjIZhFz+KAv2emhWMRvDmMcY8A==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, + "node_modules/vfile": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/vfile/-/vfile-6.0.3.tgz", + "integrity": "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "vfile-message": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/vfile-message": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/vfile-message/-/vfile-message-4.0.4.tgz", + "integrity": "sha512-66ycRswIkNmHH9PHku7ADtv5RVwgIrOcuv3J8Svz6h4qgGRrKVa+9/neuKyJZUXyOpYwLTvS+whZ4R2urHHgQg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-stringify-position": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/vite": { - "version": "8.3.5", - "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.5.tgz", - "integrity": "sha512-z1YpjieJ9g0ebTmQpLBv/oq9E3F9EIlOe+7LahW8SrE3LTiG3udBRUXQOlYXP9b+IC2q2phHeVxj9xGlw34OEQ==", + "version": "8.3.8", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.8.tgz", + "integrity": "sha512-LzOn3h9rG/0vhLdXrV4yJ4QFA9eEoqCl+Yx+kGJd7aB9w6nfNgVHKSYwLPZUHrz4ZGa+t+kXjV9itvcHDLQouA==", "dev": true, "license": "MIT", "dependencies": { "lightningcss": "^1.33.0", "picomatch": "^4.0.7", - "postcss": "^8.5.30", - "rolldown": "~1.2.14", + "postcss": "^8.5.32", + "rolldown": "~1.2.18", "tinyglobby": "^0.2.17" }, "bin": { @@ -4135,6 +5729,28 @@ } } }, + "node_modules/vite-plugin-singlefile": { + "version": "2.3.4", + "resolved": "https://registry.npmjs.org/vite-plugin-singlefile/-/vite-plugin-singlefile-2.3.4.tgz", + "integrity": "sha512-1FAhlTCL6KJDpSUudrVU+gspapvS+tmKCg70vwNaAU6tyXn3E/C6+NnwQIze06byhBRv7VggZ78K0h+J/Rsdrg==", + "dev": true, + "license": "MIT", + "dependencies": { + "picomatch": "^4.0.7" + }, + "engines": { + "node": ">18.0.0" + }, + "peerDependencies": { + "rollup": "^4.59.0", + "vite": "^5.4.21 || ^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, "node_modules/vitest": { "version": "4.1.12", "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.12.tgz", @@ -4458,6 +6074,17 @@ "funding": { "url": "https://github.com/sponsors/colinhacks" } + }, + "node_modules/zwitch": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz", + "integrity": "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } } } } diff --git a/package.json b/package.json index d0f2a322b..4161e03d8 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,7 @@ "deploy:forge-tools:prod": "wrangler deploy -c wrangler.forge-tools.jsonc --env production", "deploy:prod": "wrangler deploy --env production", "types": "wrangler types --env-file .env_example -c wrangler.jsonc -c wrangler.forge-tools.jsonc", - "typecheck": "tsc --noEmit", + "typecheck": "tsc --noEmit && tsc -p tsconfig.app.json", "lint": "oxlint src/ --ignore-pattern 'src/generated/**'", "format": "oxfmt --write src/ tests/ scripts/ vitest.config.ts", "generate:tools": "tsx scripts/generate-tools.ts", @@ -19,10 +19,12 @@ "test:events": "vitest run tests/events-e2e.test.ts tests/ans-bridge.test.ts", "events:receiver": "node scripts/mcp-events-receiver.mjs", "test:watch": "vitest", - "check": "npm run format:check && npm run lint && npm run typecheck && npm run test", + "check": "npm run app:check && npm run format:check && npm run lint && npm run typecheck && npm run test", "seed:staging": "tsx scripts/seed-r2.ts staging", "seed:prod": "tsx scripts/seed-r2.ts production", - "report:schema-mismatches": "tsx scripts/schema-mismatch-report.ts" + "report:schema-mismatches": "tsx scripts/schema-mismatch-report.ts", + "app:build": "tsx scripts/build-mcp-apps.ts", + "app:check": "tsx scripts/build-mcp-apps.ts --check" }, "dependencies": { "@cfworker/json-schema": "^4.1.1", @@ -45,6 +47,17 @@ "vitest": "^4.1.12", "workers-oauth-provider-0-10-2": "npm:@cloudflare/workers-oauth-provider@^0.10.2", "workers-oauth-provider-1-1-0": "npm:@cloudflare/workers-oauth-provider@^1.1.0", - "wrangler": "^4.154.0" + "wrangler": "^4.154.0", + "@cloudflare/kumo": "2.19.0", + "@modelcontextprotocol/ext-apps": "2.0.4", + "@phosphor-icons/react": "2.1.10", + "@tailwindcss/vite": "4.3.5", + "@types/react": "19.3.0", + "@types/react-dom": "19.3.0", + "react": "19.3.1", + "react-dom": "19.3.1", + "tailwindcss": "4.3.5", + "vite": "8.3.8", + "vite-plugin-singlefile": "2.3.4" } } diff --git a/scripts/build-mcp-apps.ts b/scripts/build-mcp-apps.ts new file mode 100644 index 000000000..758e7b7a1 --- /dev/null +++ b/scripts/build-mcp-apps.ts @@ -0,0 +1,105 @@ +import { build, type Plugin, type Rollup } from 'vite' +import tailwindcss from '@tailwindcss/vite' +import { viteSingleFile } from 'vite-plugin-singlefile' +import { mkdir, readdir, readFile, rm, writeFile } from 'node:fs/promises' +import { existsSync } from 'node:fs' +import path from 'node:path' + +/** + * Build every MCP App into one self-contained HTML file, written as a text + * module the Worker serves (`src//app-html.generated.ts`). + * + * An App is any `src//app/index.html`. `--check` fails when a committed + * module is stale, so `npm run check` catches an App edited without a rebuild. + * + * npm run app:build # every App + * npm run app:build -- # one App, by its src/ directory name + * + * Each App builds twice. The first build finds the JavaScript the view really + * ships; Tailwind then scans only that, plus the App's own sources, so the + * stylesheet holds the classes the view can render and not every Kumo + * component's (175 KB of CSS became 69 KB for the Workers usage alert). + */ +const check = process.argv.includes('--check') +const only = process.argv.slice(2).filter((arg) => !arg.startsWith('--')) + +/** What Tailwind scans for Kumo's classes, in place of every Kumo module; see `app-shell/base.css`. */ +const SHIPPED_JS = path.resolve('.mcp-apps-build/shipped') + +/** + * Kumo's `Button` imports its `Tooltip` for a `title` prop, and the tooltip + * brings floating-ui and Base UI's popup stores: about 80 KB of the view's + * JavaScript, for a prop no App passes. This swaps it for a stub that throws, + * so a `title` on a Button fails loudly in the view rather than quietly + * rendering no tooltip. Any other import of the tooltip is left alone. + */ +function withoutButtonTooltip(): Plugin { + const stub = '\0mcp-apps:kumo-button-tooltip' + return { + name: 'mcp-apps:without-button-tooltip', + enforce: 'pre', + resolveId(source, importer) { + if ( + importer?.includes('/@cloudflare/kumo/dist/chunks/button-') && + /\/tooltip-[a-z0-9]+\.js$/.test(source) + ) + return stub + }, + load(id) { + if (id === stub) + return `export const t = () => { + throw new Error('MCP Apps build Kumo Button without Tooltip: pass aria-label or aria-description, not title.') +}` + } + } +} + +const apps = (await readdir('src', { withFileTypes: true })) + .filter( + (entry) => entry.isDirectory() && existsSync(path.join('src', entry.name, 'app/index.html')) + ) + .map((entry) => entry.name) + .filter((name) => only.length === 0 || only.includes(name)) + .sort() + +const output = (result: Awaited>) => + (Array.isArray(result) ? result : [result as Rollup.RolldownOutput]).flatMap((r) => r.output) + +const stale: string[] = [] +for (const name of apps) { + const root = path.join('src', name, 'app') + const outDir = path.resolve('.mcp-apps-build', name) + + // 1. The JavaScript the view ships, unminified so Tailwind can read its class strings. + await rm(SHIPPED_JS, { recursive: true, force: true }) + await mkdir(SHIPPED_JS, { recursive: true }) + const scan = await build({ + configFile: false, + logLevel: 'error', + root, + plugins: [withoutButtonTooltip(), tailwindcss()], + build: { write: false, minify: false } + }) + const chunks = output(scan).filter((o): o is Rollup.OutputChunk => o.type === 'chunk') + await writeFile(path.join(SHIPPED_JS, 'view.js'), chunks.map((c) => c.code).join('\n')) + + // 2. The App, its stylesheet generated from what step 1 shipped. + await build({ + configFile: false, + logLevel: 'error', + root, + plugins: [withoutButtonTooltip(), tailwindcss(), viteSingleFile()], + build: { outDir, emptyOutDir: true, minify: true } + }) + const html = await readFile(path.join(outDir, 'index.html'), 'utf8') + const generated = `// Generated by npm run app:build. Do not edit.\nexport const appHtml = ${JSON.stringify(html)}\n` + const target = path.join('src', name, 'app-html.generated.ts') + if (check) { + const current = existsSync(target) ? await readFile(target, 'utf8') : '' + if (current !== generated) stale.push(target) + } else { + await writeFile(target, generated) + console.log(`built ${target} (${Math.round(html.length / 1024)} KB)`) + } +} +if (stale.length) throw new Error(`Stale MCP App HTML: ${stale.join(', ')}. Run npm run app:build.`) diff --git a/src/forge-tools/cloudflare.ts b/src/forge-tools/cloudflare.ts index a81ad5135..f0931d311 100644 --- a/src/forge-tools/cloudflare.ts +++ b/src/forge-tools/cloudflare.ts @@ -1,6 +1,5 @@ import type { JSONObject } from '@modelcontextprotocol/server' -import { operation } from '../generated/forge-mcp' -import type { Tool } from '../generated/forge-mcp/_/tool' +import { operation, type Tool } from '../generated/forge-mcp/_/tool' import { ACCOUNT_OR_ZONE_ID_DESCRIPTION, FORGE_ACCOUNT_ID_DESCRIPTION, diff --git a/src/lib/isolate-json-schema.ts b/src/lib/isolate-json-schema.ts index 42400ee1b..df146f257 100644 --- a/src/lib/isolate-json-schema.ts +++ b/src/lib/isolate-json-schema.ts @@ -10,9 +10,14 @@ import { isolate } from './isolate' * schema through zod's `~standard` setter. The SDK only reads the result. * * @param schema - A schema defined once at module scope, never per request. + * @param post - Applied to each conversion once, before it is cached, such as + * `compactJsonSchema` for an MCP App's listed schemas. Defaults to none. * @returns The same schema, with its JSON Schema conversion cached. */ -export function withCachedJsonSchema(schema: T): T { +export function withCachedJsonSchema( + schema: T, + post: (json: Record) => Record = (json) => json +): T { const standard = schema['~standard'] const { jsonSchema } = standard const converted = isolate.map>() @@ -21,7 +26,7 @@ export function withCachedJsonSchema(schema: T): T { (options: Parameters[0]): Record => converted.getOrSet( `${io}:${options.target}:${JSON.stringify(options.libraryOptions ?? {})}`, - () => jsonSchema[io](options) + () => post(jsonSchema[io](options)) ) schema['~standard'] = { ...standard, diff --git a/src/mcp-apps/api-read.ts b/src/mcp-apps/api-read.ts new file mode 100644 index 000000000..c9fdace04 --- /dev/null +++ b/src/mcp-apps/api-read.ts @@ -0,0 +1,203 @@ +import { z } from 'zod' +import { env } from 'cloudflare:workers' +import type { CallToolResult } from '@modelcontextprotocol/server' +import { acceptedPermissions, authorize, explainRefusal, findOperation } from '../api-permissions' +import { getPermissionPaths } from '../isolate-cache' +import { apiCallResult } from '../tools/api-call-result' +import { WWW_AUTHENTICATE_META_KEY } from '../scope-challenge' +import { truncateResponse } from '../truncate' +import { fetchWithRetry } from '../utils/fetch-retry' +import type { AppContext } from './define' + +/** The most an App reads from one response. Apps show summaries, not pages of records. */ +export const MAX_READ_BYTES = 1024 * 1024 + +/** + * Cloudflare refused or failed a read. `result` is the tool error the direct + * tools would give for the same request: method, path, status, Cloudflare's + * errors, an explanation and, for a missing OAuth scope, the step-up `_meta`. + */ +export class ApiReadError extends Error { + constructor(readonly result: CallToolResult) { + super('Cloudflare API read refused or failed') + } + /** The tool error's text. */ + get text(): string { + const text = this.result.content.find((c) => c.type === 'text') + return text?.type === 'text' ? text.text : this.message + } +} + +/** A response larger than {@link MAX_READ_BYTES}, or not JSON. */ +export class ApiReadUnsupported extends Error {} + +/** The GraphQL Analytics API, which the spec doesn't list, and the permission each dataset kind needs. */ +const GRAPHQL_PERMISSIONS = { + zone: ['Analytics Read'], + account: ['Account Analytics Read'] +} as const + +/** + * Whether GraphQL errors say the credential lacks the dataset's analytics + * permission. A zone dataset names the permission; an account dataset says + * only `authorization denied`. Kept in step with `graphqlRefusal` in + * `src/tools/execute.ts`. + */ +export function graphqlRefused( + messages: readonly string[], + dataset: keyof typeof GRAPHQL_PERMISSIONS +): boolean { + return dataset === 'zone' + ? messages.some((m) => m.includes("'com.cloudflare.api.account.zone.analytics.read'")) + : messages.some( + (m) => + /^authorization denied$/i.test(m.trim()) || + m.includes("'com.cloudflare.api.account.analytics.read'") + ) +} + +async function readBounded(response: Response): Promise { + const reader = response.body?.getReader() + const chunks: Uint8Array[] = [] + let bytes = 0 + if (reader) + for (;;) { + const part = await reader.read() + if (part.done) break + bytes += part.value.byteLength + if (bytes > MAX_READ_BYTES) { + await reader.cancel() + throw new ApiReadUnsupported('Response exceeded the 1 MB App read limit.') + } + chunks.push(part.value) + } + const raw = new Uint8Array(bytes) + let offset = 0 + for (const chunk of chunks) { + raw.set(chunk, offset) + offset += chunk.length + } + try { + return JSON.parse(new TextDecoder().decode(raw)) + } catch { + throw new ApiReadUnsupported('Cloudflare returned a non-JSON response.') + } +} + +/** + * Read-only Cloudflare API access for one App call. Every read is a GET to a + * fixed path, or a GraphQL Analytics query (which has no mutations), sent with + * the request's credential from this Worker: the token never reaches the App. + */ +export interface ApiReader { + /** + * GET `path` below the API base and parse its body with `schema`. + * + * @throws {ApiReadError} for a refusal or failure, explained like the direct tools. + * @throws {ApiReadUnsupported} for an oversized or non-JSON body. + * @throws {z.ZodError} when the body doesn't match `schema`. + */ + get(path: string, schema: S): Promise> + /** + * POST a GraphQL Analytics query and parse its `data` with `schema`. + * + * @param dataset - Which permission the query's datasets need: `account` or `zone`. + * @throws {ApiReadError} when it returns errors, with or without data, explained as a refusal of the analytics permission when it is one. + */ + graphql( + query: string, + variables: Record, + dataset: keyof typeof GRAPHQL_PERMISSIONS, + schema: S + ): Promise> +} + +/** + * Create the reader for one App call. + * + * @param context - The request's credential, connection and step-up challenge. + * @param signal - Aborts every read when the call is cancelled. + * @param caller - Names the App in `fetchWithRetry` logs. + */ +export function apiReader(context: AppContext, signal: AbortSignal, caller: string): ApiReader { + const base = env.CLOUDFLARE_API_BASE.replace(/\/$/, '') + const basePath = new URL(base).pathname + const send = (path: string, init: RequestInit) => + fetchWithRetry( + base + path, + { + ...init, + redirect: 'manual', + signal, + headers: { + ...init.headers, + authorization: `Bearer ${context.props.accessToken}`, + accept: 'application/json' + } + }, + { caller } + ) + + return { + async get(path, schema) { + const response = await send(path, { method: 'GET' }) + const body = await readBounded(response) + const requestPath = new URL(base + path).pathname.slice(basePath.length) + const match = findOperation(getPermissionPaths(), 'GET', requestPath) + const result = apiCallResult( + { + method: 'GET', + path: requestPath, + template: match?.template ?? requestPath, + permissions: acceptedPermissions(match?.operation), + status: response.status, + body + }, + [], + { ...context, formatResult: truncateResponse } + ) + if (result.isError) throw new ApiReadError(result) + return schema.parse(body) + }, + + async graphql(query, variables, dataset, schema) { + const response = await send('/graphql', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ query, variables }) + }) + const body = (await readBounded(response)) as { data?: unknown; errors?: unknown } + const errors = Array.isArray(body?.errors) ? (body.errors as { message?: unknown }[]) : [] + // Data with errors is partial: one alias failed (a quota, a timeout) and is missing. A + // summary read from it would show a missing window as no traffic, so it fails as a whole. + if (response.ok && body?.data != null && !errors.length) return schema.parse(body.data) + const messages = errors.map((e) => String(e.message ?? '')).filter(Boolean) + // The API answers a missing permission with 200 and `data: null`, as it + // does a quota or a bad query, so only a permission message is a refusal. + const refused = graphqlRefused(messages, dataset) + const authorization = refused + ? authorize( + context.connection, + { method: 'POST', path: '/graphql' }, + GRAPHQL_PERMISSIONS[dataset] + ) + : undefined + const text = [ + `Cloudflare API error: POST /graphql returned HTTP ${response.status} with ${body?.data == null ? 'no data' : 'partial data'}.`, + truncateResponse(messages), + authorization && explainRefusal(403, authorization) + ] + .filter(Boolean) + .join('\n\n') + const challenge = + authorization?.kind === 'missing' && authorization.scope + ? context.scopeChallenge.require(authorization.scope) + : undefined + throw new ApiReadError({ + isError: true, + content: [{ type: 'text', text }], + ...(challenge ? { _meta: { [WWW_AUTHENTICATE_META_KEY]: [challenge] } } : {}) + }) + } + } +} diff --git a/src/mcp-apps/app-shell/apply-locale.ts b/src/mcp-apps/app-shell/apply-locale.ts new file mode 100644 index 000000000..c3820e3cb --- /dev/null +++ b/src/mcp-apps/app-shell/apply-locale.ts @@ -0,0 +1,16 @@ +import type { AppLocale } from './locale' + +let current: AppLocale = { lang: 'en', dir: 'ltr', formats: 'en' } + +/** The locale `mountMcpApp` applied; formatters read it at render time. */ +export const appLocale = (): AppLocale => current + +/** Set `lang` and `dir` on the document, so logical properties and `:dir()` follow. True when it changed. */ +export function applyLocale(locale: AppLocale): boolean { + const changed = + locale.lang !== current.lang || locale.dir !== current.dir || locale.formats !== current.formats + current = locale + document.documentElement.lang = locale.lang + document.documentElement.dir = locale.dir + return changed +} diff --git a/src/mcp-apps/app-shell/base.css b/src/mcp-apps/app-shell/base.css new file mode 100644 index 000000000..eb3c61a07 --- /dev/null +++ b/src/mcp-apps/app-shell/base.css @@ -0,0 +1,30 @@ +/* + * Shared base for every MCP App. Each App's own CSS imports this first: + * @import '../../mcp-apps/app-shell/base.css'; + * @source './.tsx'; + * Kumo tokens come from @cloudflare/kumo; the host's theme sets data-mode. + * + * Kumo's classes are scanned from the JavaScript the view ships, which + * `scripts/build-mcp-apps.ts` writes to `.mcp-apps-build/shipped/` before it + * builds the App, not from every Kumo module: the view renders a handful of + * components, and the full scan put every component's classes in its CSS. + */ +@import '@cloudflare/kumo/styles/tailwind'; +@import 'tailwindcss' source(none); +@source '../../../.mcp-apps-build/shipped'; + +html, +body { + margin: 0; + padding: 0; + background: transparent; + color: var(--text-color-kumo-default); + font: + 14px/1.5 ui-sans-serif, + system-ui, + sans-serif; + -webkit-font-smoothing: antialiased; +} +#root { + padding: 12px; +} diff --git a/src/mcp-apps/app-shell/locale.ts b/src/mcp-apps/app-shell/locale.ts new file mode 100644 index 000000000..e7106ed26 --- /dev/null +++ b/src/mcp-apps/app-shell/locale.ts @@ -0,0 +1,64 @@ +/** + * Which language an App shows, which way it runs, and how it formats numbers + * and dates, from the host's `locale` (BCP 47, in the host context). No + * catalog: the copy is the App's, the formats are the browser's `Intl`. + * + * - **Language and direction** follow the copy the App actually has. English + * copy is `lang="en"`, left to right, in an Arabic host too: mirroring + * English text would misdeclare it to screen readers. When an App gains + * copy in a right-to-left language, the same host locale turns it around. + * - **Formats** follow the host's region (`de-DE` → `en-DE`: "1,35B"), so + * every number is the user's while the words stay in one language. + * - **`-XB` pseudo-locales** (`ar-XB`, `he-XB`), as Android and Chromium use + * them: the App's own copy laid out right to left, with that language's + * formats ("١٫٣٥ مليار"), to test mirroring and bidirectional text without + * translations. + */ +export interface AppLocale { + /** The copy's language, for `lang`. */ + readonly lang: string + readonly dir: 'ltr' | 'rtl' + /** The locale numbers and dates are formatted in. */ + readonly formats: string +} + +/** Scripts written right to left, by ISO 15924 code. */ +const RTL_SCRIPTS = new Set([ + 'Adlm', + 'Arab', + 'Hebr', + 'Mand', + 'Nkoo', + 'Rohg', + 'Samr', + 'Syrc', + 'Thaa' +]) +const PSEUDO = 'XB' + +const directionOf = (tag: string): AppLocale['dir'] => + RTL_SCRIPTS.has(new Intl.Locale(tag).maximize().script ?? '') ? 'rtl' : 'ltr' + +function parse(tag: string | undefined): Intl.Locale | undefined { + try { + return tag ? new Intl.Locale(tag) : undefined + } catch { + return undefined + } +} + +/** + * @param requested the host's `locale`, if it sent one + * @param languages the languages the App has copy for, the default first + */ +export function resolveLocale( + requested: string | undefined, + languages: readonly [string, ...string[]] +): AppLocale { + const host = parse(requested) + const fallback = languages[0] + if (host?.region === PSEUDO) + return { lang: fallback, dir: directionOf(host.language), formats: host.language } + const lang = host && languages.includes(host.language) ? host.language : fallback + return { lang, dir: directionOf(lang), formats: host?.region ? `${lang}-${host.region}` : lang } +} diff --git a/src/mcp-apps/app-shell/mount.tsx b/src/mcp-apps/app-shell/mount.tsx new file mode 100644 index 000000000..8ea763c11 --- /dev/null +++ b/src/mcp-apps/app-shell/mount.tsx @@ -0,0 +1,136 @@ +import type { ReactNode } from 'react' +import { createRoot } from 'react-dom/client' +import { App } from '@modelcontextprotocol/ext-apps' +import type { CallToolResult } from '@modelcontextprotocol/client' +import type { z } from 'zod' +import { applyLocale } from './apply-locale' +import { resolveLocale } from './locale' + +/** How the host's state reaches the App's view. */ +export interface MountedApp { + /** The connected host bridge, for `callServerTool`, `sendMessage` and `updateModelContext`. */ + readonly app: App +} + +export interface MountOptions { + /** Shown to the host in `ui/initialize`. */ + readonly name: string + readonly version?: string + /** The tool's output schema; a result that doesn't match is shown as malformed, never guessed at. */ + readonly output: Output + /** Render a validated result. */ + readonly render: (value: z.output, mounted: MountedApp) => ReactNode + /** + * Render while the tool runs. Defaults to `copy.pending` as text. `toolName` + * is the host's `toolInfo`, for an App one view serves for several tools; + * it is absent until the host connects. + */ + readonly renderPending?: (toolName: string | undefined) => ReactNode + /** + * Render a tool error (`isError`), with its text. `retry` calls the tool + * again with the same arguments, through the host, and renders what it + * returns; it is absent when the host can't call server tools. + */ + readonly renderError?: ( + text: string, + retry: (() => void) | undefined, + toolName: string | undefined + ) => ReactNode + /** Copy for the states no tool result describes. Defaults are generic. */ + readonly copy?: Partial> + /** + * The languages the App's copy is in, the default first. The host's + * `locale` picks one (and so `lang` and `dir`); its region picks the number + * and date formats. Defaults to English only. See `./locale.ts`. + */ + readonly languages?: readonly [string, ...string[]] +} + +function applyTheme(mode: string | undefined) { + if (!mode) return + document.documentElement.dataset.mode = mode + document.documentElement.style.colorScheme = mode +} + +/** + * Mount an MCP App into `#root`: connect to the host, follow its theme and locale, and + * render each tool result that matches the output schema. + * + * Apps hold no credentials and make no network requests; everything they show + * comes from the tool result. A result that fails validation, a cancelled call + * and a lost host connection each get a plain message pointing at the tool's + * text result, which every host shows. + */ +export function mountMcpApp(options: MountOptions): void { + const copy = { + pending: 'Loading…', + cancelled: 'Cancelled.', + malformed: 'This result could not be displayed. Check the tool’s text result.', + disconnected: 'Could not connect to the host. The text result remains available.', + ...options.copy + } + const root = createRoot(document.getElementById('root')!) + const app = new App({ name: options.name, version: options.version ?? '1.0.0' }, {}) + const mounted: MountedApp = { app } + + // The last thing drawn, so a locale change re-renders it in the new formats and direction. + let last: () => ReactNode = () => null + const draw = (node: () => ReactNode) => { + last = () => { + drawnFor = toolName() + return node() + } + root.render(last()) + } + const toolName = () => app.getHostContext()?.toolInfo?.tool.name + // The tool name last drawn with: the pending and error views depend on it, and it can arrive late. + let drawnFor: string | undefined + const followHost = () => { + const context = app.getHostContext() + applyTheme(context?.theme) + const relocalised = applyLocale(resolveLocale(context?.locale, options.languages ?? ['en'])) + if (relocalised || toolName() !== drawnFor) root.render(last()) + } + const pending = () => + draw(() => options.renderPending?.(toolName()) ??

{copy.pending}

) + let input: Record | undefined + const show = (result: CallToolResult) => { + if (result.isError && options.renderError) { + const text = result.content.flatMap((c) => (c.type === 'text' ? [c.text] : [])).join('\n') + // Decided at each draw, from the host's current context: `toolInfo` can arrive after the error. + const retryFor = (name: string | undefined) => + name && app.getHostCapabilities()?.serverTools + ? () => { + pending() + app + .callServerTool({ name, arguments: input ?? {} }) + .then(show) + .catch((error: unknown) => + show({ isError: true, content: [{ type: 'text', text: String(error) }] }) + ) + } + : undefined + return draw(() => options.renderError!(text, retryFor(toolName()), toolName())) + } + const parsed = options.output.safeParse(result.structuredContent) + draw(() => + parsed.success ? options.render(parsed.data, mounted) :

{copy.malformed}

+ ) + } + + pending() + app.onhostcontextchanged = followHost + app.ontoolinput = (params) => { + input = params.arguments + } + app.ontoolresult = (result) => { + followHost() + show(result) + } + app.ontoolcancelled = () => draw(() =>

{copy.cancelled}

) + app + .connect() + // With the host's `toolInfo` now known, `followHost` redraws the pending view for its tool. + .then(followHost) + .catch(() => draw(() =>

{copy.disconnected}

)) +} diff --git a/src/mcp-apps/capability.ts b/src/mcp-apps/capability.ts new file mode 100644 index 000000000..f4653224e --- /dev/null +++ b/src/mcp-apps/capability.ts @@ -0,0 +1,76 @@ +import { + CLIENT_CAPABILITIES_META_KEY, + PROTOCOL_VERSION_META_KEY, + type Tool +} from '@modelcontextprotocol/server' +import { MCP_APP_MIME } from './define' + +/** The MCP Apps extension a host declares in its capabilities, and this server in its own. */ +export const MCP_APPS_EXTENSION_ID = 'io.modelcontextprotocol/ui' + +function record(value: unknown): Record | undefined { + return typeof value === 'object' && value !== null && !Array.isArray(value) + ? (value as Record) + : undefined +} + +/** + * Whether a request's client declares that it renders MCP Apps: a 2026-07-28 + * request whose `_meta` envelope lists `text/html;profile=mcp-app` under + * `extensions["io.modelcontextprotocol/ui"].mimeTypes`. + * + * 2025-era requests send capabilities only in `initialize`, which a stateless + * server never sees again, so they always count as not declaring it. Production + * logs (November 2026) put 98% of `tools/list` requests, and nearly all of + * Claude's and ChatGPT's, on 2026-07-28. + * + * @param body - The parsed JSON-RPC body, or `undefined` when it wasn't read. + */ +export function declaresMcpApps(body: unknown): boolean { + const meta = record(record(record(body)?.params)?._meta) + if (typeof meta?.[PROTOCOL_VERSION_META_KEY] !== 'string') return false + const extensions = record(record(meta[CLIENT_CAPABILITIES_META_KEY])?.extensions) + const mimeTypes = record(extensions?.[MCP_APPS_EXTENSION_ID])?.mimeTypes + return ( + Array.isArray(mimeTypes) && + mimeTypes.some( + (type) => typeof type === 'string' && type.replace(/\s+/g, '').toLowerCase() === MCP_APP_MIME + ) + ) +} + +function quoted(value: string): string { + return JSON.stringify(value.slice(0, 64)) +} + +/** + * The log line recording whether a 2026-07-28 `tools/list` or `tools/call` + * declared MCP Apps, by client, or `undefined` for any other request. Names + * are the client's own strings, so each is cut to 64 characters and quoted. + */ +export function mcpAppsLogLine(body: unknown, declared: boolean): string | undefined { + const message = record(body) + const params = record(message?.params) + const meta = record(params?._meta) + if (typeof meta?.[PROTOCOL_VERSION_META_KEY] !== 'string') return undefined + const method = message?.method + if (method !== 'tools/list' && method !== 'tools/call') return undefined + const name = record(meta['io.modelcontextprotocol/clientInfo'])?.name + const client = typeof name === 'string' ? quoted(name) : '' + const tool = + method === 'tools/call' && typeof params?.name === 'string' + ? ` tool=${quoted(params.name)}` + : '' + return `mcp_apps ${method}: declared=${declared} client=${client}${tool}` +} + +/** + * An App's tool as a client without MCP Apps lists it: a plain tool whose + * result is the same JSON text, without the `_meta` that links it to its view. + */ +export function withoutAppView(tool: Tool): Tool { + if (!tool._meta) return tool + const { ui: _ui, 'ui/resourceUri': _uri, ...meta } = tool._meta + const { _meta: _dropped, ...rest } = tool + return Object.keys(meta).length > 0 ? { ...rest, _meta: meta } : rest +} diff --git a/src/mcp-apps/define.ts b/src/mcp-apps/define.ts new file mode 100644 index 000000000..60f4cce51 --- /dev/null +++ b/src/mcp-apps/define.ts @@ -0,0 +1,208 @@ +import type { + CallToolResult, + ServerContext, + Tool, + ToolAnnotations +} from '@modelcontextprotocol/server' +import { z } from 'zod' +import type { AuthProps } from '../auth/types' +import type { Connection } from '../api-permissions' +import type { ScopeChallenge } from '../scope-challenge' +import type { StaticResource } from '../skills/handlers' +import { withCachedJsonSchema } from '../lib/isolate-json-schema' +import type { Tool as GeneratedTool } from '../generated/forge-mcp/_/tool' + +/** The MIME type MCP Apps hosts render as an App. */ +export const MCP_APP_MIME = 'text/html;profile=mcp-app' + +/** What an App's collector gets from the authenticated request. */ +export interface AppContext { + /** The request's validated credential. Its token never reaches the App's HTML. */ + readonly props: AuthProps + /** What the credential may do, for explaining refused API reads. */ + readonly connection: Connection + /** Where a refused read records a missing OAuth scope, for step-up. */ + readonly scopeChallenge: ScopeChallenge + /** + * Whether the client declared MCP Apps, so a view renders the result. Only + * then may the result's text leave out what only the view shows + * ({@link McpAppDefinition.modelText}); a text-only host has nothing else. + */ + readonly view?: boolean +} + +/** What an App's collector returns: its validated result, or a tool error. */ +export type AppOutcome = + | { readonly ok: true; readonly value: Output; readonly meta?: CallToolResult['_meta'] } + | { readonly ok: false; readonly text: string; readonly meta?: CallToolResult['_meta'] } + +/** An App's tool and its HTML resource, served in both tool modes. */ +export interface McpApp { + /** The tool as `tools/list` sends it, for the direct tools' hand-written listing. */ + readonly tool: Tool + /** The App's HTML, served through `resources/list` and `resources/read`. */ + readonly resource: StaticResource + /** The generated tools the App's view calls with `callServerTool`; see {@link McpAppDefinition.appTools}. */ + readonly appTools: readonly GeneratedTool[] + /** The zod schemas Code Mode registers, JSON Schema conversion cached per isolate. */ + readonly inputSchema: z.ZodObject + readonly outputSchema: z.ZodType + /** Validate the arguments, run the collector and shape the result. */ + call(args: unknown, context: AppContext, ctx: ServerContext): Promise +} + +export interface McpAppDefinition { + /** The tool name, such as `workers_deployment_status`. A permanent contract. */ + readonly name: string + readonly title: string + /** When to call the tool, what it reads and what it doesn't prove. Hosts route on this. */ + readonly description: string + readonly annotations: ToolAnnotations + readonly input: Input + readonly output: Output + readonly resource: { + /** `ui://cloudflare/.html`. */ + readonly uri: `ui://${string}` + readonly name: string + /** The self-contained HTML `npm run app:build` generates. */ + readonly html: string + } + /** + * Generated tools (such as `alerting_policies_create`, imported from its + * group in `src/generated/forge-mcp`) the App's view calls with + * `callServerTool` when the user clicks for a write. The direct tools + * already list every one. Code Mode lists only these, with + * `_meta.ui.visibility: ['app']` so the model never sees them, and serves + * them through the forge tools service like the direct tools, so a write + * needs no tool of its own. Import the group's `tools.ts`, never the index: + * the index pulls in every generated tool. + */ + readonly appTools?: readonly GeneratedTool[] + /** + * The result's text for a client that renders the view, which the model + * reads and re-reads on every later turn. Defaults to the whole result as + * JSON. An App whose view needs more than the model does (a chart's series) + * returns a smaller JSON here: the view still gets the whole result as + * `structuredContent`, validated against the output schema. A client + * without Apps always gets the whole result as text, the spec's fallback. + */ + readonly modelText?: (value: z.output) => string + /** Collect the result. Reads must stop when `signal` aborts. */ + run( + input: z.output, + context: AppContext, + signal: AbortSignal + ): Promise>> +} + +/** zod's bounds for `.int()`, which say nothing a JSON number doesn't. */ +const SAFE_INTEGER_BOUNDS = [Number.MAX_SAFE_INTEGER, Number.MIN_SAFE_INTEGER] + +/** + * An App's JSON Schema as clients list it, without what zod adds that no + * client needs: the `$schema` URI, the regex it writes beside each + * `format: date` and `date-time` (500 characters apiece, the same rule the + * format names), and the safe-integer bounds of every `.int()`. About a + * fifth of each App tool's listing (1.1 KB of 5.2 KB), sent on every + * `tools/list`; the input schema's share also reaches the model with the + * tool. The server still validates every argument and result with the zod + * schema itself, so nothing is checked less. + */ +export function compactJsonSchema(schema: T): T { + if (Array.isArray(schema)) return schema.map(compactJsonSchema) as T + if (!schema || typeof schema !== 'object') return schema + const out: Record = {} + const node = schema as Record + for (const [key, value] of Object.entries(node)) { + if (key === '$schema') continue + if (key === 'pattern' && (node.format === 'date' || node.format === 'date-time')) continue + if ((key === 'maximum' || key === 'minimum') && SAFE_INTEGER_BOUNDS.includes(value as number)) + continue + out[key] = compactJsonSchema(value) + } + return out as T +} + +function listedJsonSchema(schema: z.ZodType): Record { + return compactJsonSchema(z.toJSONSchema(schema) as Record) +} + +/** + * The signal a tool call stops on: the MCP request's, and the HTTP request's + * when the client disconnects. + */ +export function toolSignal(ctx: ServerContext): AbortSignal { + return ctx.http?.req + ? AbortSignal.any([ctx.mcpReq.signal, ctx.http.req.signal]) + : ctx.mcpReq.signal +} + +/** + * Define an MCP App: a tool whose result an MCP Apps host renders with a + * static HTML resource, and that clients without Apps read as JSON text and + * `structuredContent`. + * + * Call it once at module scope. The App's HTML holds no account data or + * credentials and makes no network requests (its CSP allows none); everything + * it shows comes from the tool result. + * + * @param definition - The tool's contract, its HTML and its collector. + * @returns The App, for `MCP_APPS` in `src/mcp-apps/registry.ts`. + */ +export function defineMcpApp( + definition: McpAppDefinition +): McpApp { + const { uri, name: resourceName, html } = definition.resource + const meta = { ui: { resourceUri: uri }, 'ui/resourceUri': uri } + const tool: Tool = { + name: definition.name, + title: definition.title, + description: definition.description, + annotations: definition.annotations, + _meta: meta, + inputSchema: listedJsonSchema(definition.input) as Tool['inputSchema'], + outputSchema: listedJsonSchema(definition.output) as Tool['outputSchema'] + } + const resource: StaticResource = { + descriptor: { uri, name: resourceName, mimeType: MCP_APP_MIME }, + content: { + uri, + mimeType: MCP_APP_MIME, + text: html, + _meta: { ui: { csp: { connectDomains: [], resourceDomains: [] } } } + } + } + return { + tool, + resource, + appTools: definition.appTools ?? [], + inputSchema: withCachedJsonSchema(definition.input, compactJsonSchema), + outputSchema: withCachedJsonSchema(definition.output, compactJsonSchema), + async call(args, context, ctx) { + const parsed = definition.input.safeParse(args) + if (!parsed.success) + return { + isError: true, + content: [ + { + type: 'text', + text: `Invalid arguments for tool ${definition.name}: ${z.prettifyError(parsed.error)}` + } + ] + } + const outcome = await definition.run(parsed.data, context, toolSignal(ctx)) + const meta = outcome.meta ? { _meta: outcome.meta } : {} + if (!outcome.ok) + return { isError: true, content: [{ type: 'text', text: outcome.text }], ...meta } + const output = definition.output.parse(outcome.value) + const value = output as Record + const text = + context.view && definition.modelText ? definition.modelText(output) : JSON.stringify(value) + return { + content: [{ type: 'text', text }], + structuredContent: value, + ...meta + } + } + } +} diff --git a/src/mcp-apps/registry.ts b/src/mcp-apps/registry.ts new file mode 100644 index 000000000..bc7c9e526 --- /dev/null +++ b/src/mcp-apps/registry.ts @@ -0,0 +1,84 @@ +import type { McpServer, Tool } from '@modelcontextprotocol/server' +import { cloudflareTool } from '../forge-tools/cloudflare' +import type { StaticResource } from '../skills/handlers' +// App imports, one per line. +import { workersBillingAlertApp, workersUsageAlertApp } from '../workers-usage-alert/tool' +import type { AppContext, McpApp } from './define' +import { withoutAppView } from './capability' + +const apps: McpApp[] = [] +// Each App adds its import above and one push here; nothing else in the server +// changes. One statement per App, on either side of this comment, so Apps in +// flight at once merge in any order. +apps.push(workersUsageAlertApp) +apps.push(workersBillingAlertApp) + +/** Every MCP App this Worker serves, in listing order. */ +export const MCP_APPS: readonly McpApp[] = apps + +/** The Apps' tools, for the direct tools' hand-written `tools/list` to clients that declare MCP Apps. */ +export const MCP_APP_TOOLS: readonly Tool[] = MCP_APPS.map((app) => app.tool) + +/** The Apps' tools as clients without MCP Apps list them: plain tools, with no view. */ +export const MCP_APP_TEXT_TOOLS: readonly Tool[] = MCP_APP_TOOLS.map(withoutAppView) + +/** The Apps' HTML, served next to the skills' files. */ +export const MCP_APP_RESOURCES: readonly StaticResource[] = MCP_APPS.map((app) => app.resource) + +const BY_NAME: ReadonlyMap = new Map(MCP_APPS.map((app) => [app.tool.name, app])) + +/** The App whose tool is `name`, for the direct tools' `tools/call`. */ +export function mcpAppNamed(name: string): McpApp | undefined { + return BY_NAME.get(name) +} + +/** + * Every generated tool an App's view calls, once each, as Code Mode lists it: + * with the Cloudflare policy the direct tools have, and app-only. + */ +export const MCP_APP_GENERATED_TOOLS: readonly Tool[] = [ + ...new Map(MCP_APPS.flatMap((app) => app.appTools).map((tool) => [tool.name, tool])).values() +].map((tool) => appOnly(cloudflareTool(tool))) + +/** A generated tool as an App's view sees it in Code Mode: listed for the App only. */ +export function appOnly(tool: T): T { + const meta = tool._meta ?? {} + const ui = (meta.ui ?? {}) as Record + return { ...tool, _meta: { ...meta, ui: { ...ui, visibility: ['app'] } } } +} + +/** + * Register every App's tool on a Code Mode server. The direct tools serve + * them through `registerForgeTools` instead. + * + * @param server - The per-request MCP server. + * @param context - The request's credential, connection and step-up challenge. + * @param apps - Defaults to {@link MCP_APPS}; tests pass their own. + * @param options.view - Whether the client declared MCP Apps. Without it each + * tool is listed as a plain tool (`withoutAppView`), whose JSON text result + * is the spec's text-only fallback. + */ +export function registerMcpApps( + server: McpServer, + context: AppContext, + apps: readonly McpApp[] = MCP_APPS, + { view = true }: { view?: boolean } = {} +): void { + for (const app of apps) { + const { name, title, description, annotations, _meta } = view + ? app.tool + : withoutAppView(app.tool) + server.registerTool( + name, + { + title, + description, + annotations: { ...annotations }, + ...(_meta && { _meta }), + inputSchema: app.inputSchema, + outputSchema: app.outputSchema + }, + (args, ctx) => app.call(args, { ...context, view }, ctx) + ) + } +} diff --git a/src/mcp-handler.ts b/src/mcp-handler.ts index a9379ebd5..a88d442af 100644 --- a/src/mcp-handler.ts +++ b/src/mcp-handler.ts @@ -10,7 +10,8 @@ import { hostHeaderValidationResponse, localhostAllowedHostnames, localhostAllowedOrigins, - originValidationResponse + originValidationResponse, + readRequestBody } from '@modelcontextprotocol/server' import type { McpServer } from '@modelcontextprotocol/server' import { createServer, type RequestContext, type ServerOptions } from './server' @@ -20,6 +21,7 @@ import { identifyClient, type ClientBehavior } from './clients' import { AuthProps as AuthPropsSchema, type AuthProps } from './auth/types' import { cachedToolListResponse } from './tools/tool-list-response' import { getForgeToolList } from './isolate-cache' +import { declaresMcpApps, mcpAppsLogLine } from './mcp-apps/capability' export const MCP_ROUTE = '/mcp' @@ -62,6 +64,23 @@ function challengeDeliveryOverride(url: string): ClientBehavior['scopeChallenge' return value === 'http' || value === 'tool' ? value : undefined } +/** The share of requests `mcpAppsLogLine` is logged for. */ +const MCP_APPS_LOG_SAMPLE_RATE = 0.01 + +/** + * A POST's JSON-RPC body, read from a clone so the request stays readable, or + * `undefined` when it isn't JSON or is too large; the SDK answers those. + */ +async function parsedBodyOf(request: Request): Promise { + if (request.method !== 'POST') return undefined + try { + const read = await readRequestBody(request.clone()) + return read.tooLarge || read.text.length === 0 ? undefined : JSON.parse(read.text) + } catch { + return undefined + } +} + function createAuthenticatedHandler(props: AuthProps, context: RequestContext) { return createMcpHandler(({ requestInfo }) => { if (!requestInfo) { @@ -215,6 +234,14 @@ export async function handleAuthenticatedMcpRequest( const listed = await cachedToolListResponse(request, () => getForgeToolList()) if (listed) return withCors(listed, request) } + const body = await parsedBodyOf(request) + const mcpApps = declaresMcpApps(body) + // A 1% sample of which clients declare MCP Apps, to check that the hosts + // that render them (Claude, ChatGPT) do. + if (Math.random() < MCP_APPS_LOG_SAMPLE_RATE) { + const line = mcpAppsLogLine(body, mcpApps) + if (line) console.log(line) + } const connection = connectionFromAuth(auth) // Only tokens this server issued can step up; their tools can ask for a scope. const issued = connection.kind === 'oauth' ? auth : undefined @@ -223,6 +250,7 @@ export async function handleAuthenticatedMcpRequest( const context: RequestContext = { connection, scopeChallenge, + mcpApps, ...(env && { events: { env, @@ -232,7 +260,7 @@ export async function handleAuthenticatedMcpRequest( } const response = - request.method === 'POST' && (await isLegacyRequest(request)) + request.method === 'POST' && (await isLegacyRequest(request, body)) ? await serveLegacyAsJson(request, createServer(props, options, context)) : await createAuthenticatedHandler(props, context).fetch(request) diff --git a/src/server.ts b/src/server.ts index 5167f4bdc..315dbeee4 100644 --- a/src/server.ts +++ b/src/server.ts @@ -1,11 +1,13 @@ import { McpServer } from '@modelcontextprotocol/server' import { registerDocsTool } from './tools/docs-search' -import { registerForgeTools } from './tools/forge-tools' +import { registerAppGeneratedTools, registerForgeTools } from './tools/forge-tools' import { registerSearchTool } from './tools/search' import { registerExecuteTool } from './tools/execute' import { registerWhoamiTool } from './tools/whoami' import { registerSubmitFeedbackTool } from './tools/submit-feedback' import { registerSkills } from './skills/handlers' +import { MCP_APP_RESOURCES, registerMcpApps } from './mcp-apps/registry' +import { MCP_APPS_EXTENSION_ID } from './mcp-apps/capability' import { attachMetrics } from './metrics' import { SERVER_INFO } from './constants' import { stringifyResponse, truncateResponse } from './truncate' @@ -19,8 +21,9 @@ import { ScopeChallenge } from './scope-challenge' export interface ServerOptions { /** * Register the Code Mode tools (`search`, `execute`). When `false`, register - * the direct tools forge generates, one per API method, instead. `docs` and - * `whoami` are registered in both modes. Defaults to `true`. + * the direct tools forge generates, one per API method, instead. `docs`, + * `whoami` and the MCP Apps (`src/mcp-apps/registry.ts`) are registered in + * both modes; see {@link RequestContext.mcpApps}. Defaults to `true`. */ readonly codemode?: boolean /** @@ -49,6 +52,13 @@ export interface RequestContext { readonly scopeChallenge: ScopeChallenge /** MCP Events, served when the Worker environment is available. */ readonly events?: { readonly env: EventEnvironment; readonly bearer: string } + /** + * Whether the request's client declared MCP Apps (`declaresMcpApps`). Only + * then are the Apps' views linked, their `ui://` pages listed and, in Code + * Mode, the generated tools their views write with registered. Defaults to + * `false`. + */ + readonly mcpApps?: boolean } /** A request whose credential can't step up and that serves no events, e.g. in tests. */ @@ -71,20 +81,29 @@ export function createServer( experimentalOutputSchema = false, truncateToolResult = codemode }: ServerOptions = {}, - { connection, scopeChallenge, events }: RequestContext = directRequestContext() + { connection, scopeChallenge, events, mcpApps = false }: RequestContext = directRequestContext() ): McpServer { const server = new McpServer(SERVER_INFO) // The tool set is fixed for the life of each per-request server, so this // server never sends notifications/tools/list_changed. Declare that before // registerTool can default the capability to true. - server.server.registerCapabilities({ tools: { listChanged: false } }) + // MCP Apps are declared to every client; what each request gets depends on + // whether its client declared them too (`mcpApps`). + server.server.registerCapabilities({ + tools: { listChanged: false }, + extensions: { [MCP_APPS_EXTENSION_ID]: {} } + }) // Skills (io.modelcontextprotocol/skills) are served in both tool modes. - registerSkills(server) + // MCP Apps' HTML resources are served next to the skills' files, listed only + // to clients that declared MCP Apps. Reading one always works: the HTML is + // static and the same for everyone. + registerSkills(server, MCP_APP_RESOURCES, { listStatic: mcpApps }) if (events) registerEventMethods(server, events.env, props, events.bearer) if (!codemode) { const formatResult = truncateToolResult ? truncateResponse : stringifyResponse registerForgeTools(server, props, formatResult, connection, scopeChallenge, { - outputSchema: experimentalOutputSchema + outputSchema: experimentalOutputSchema, + mcpApps }) return server } @@ -97,6 +116,11 @@ export function createServer( registerExecuteTool(server, props, truncateToolResult, connection, scopeChallenge) registerWhoamiTool(server, props) registerSubmitFeedbackTool(server, props) + // Without MCP Apps, the Apps' tools are plain tools whose JSON text result is + // the text-only fallback, and the writes only their views make aren't + // registered: about 25 KB of `tools/list` the model must not call. + registerMcpApps(server, { props, connection, scopeChallenge }, undefined, { view: mcpApps }) + if (mcpApps) registerAppGeneratedTools(server, { props, connection, scopeChallenge }) return server } diff --git a/src/skills/handlers.ts b/src/skills/handlers.ts index 4b18ca877..cb8e3e9a2 100644 --- a/src/skills/handlers.ts +++ b/src/skills/handlers.ts @@ -3,7 +3,9 @@ import { ProtocolError, ProtocolErrorCode, ResourceNotFoundError, - type McpServer + type McpServer, + type ReadResourceResult, + type Resource } from '@modelcontextprotocol/server' import { getSkills, readSkillFile } from '../isolate-cache' import { SKILLS_EXTENSION_ID } from './types' @@ -24,6 +26,17 @@ function toBase64(bytes: Uint8Array): string { return btoa(binary) } +/** + * A resource that ships with the Worker and is the same for every user, such + * as an MCP App's HTML. Served next to the skills' files. + */ +export interface StaticResource { + /** The entry in `resources/list`. */ + readonly descriptor: Resource + /** The content `resources/read` returns for the descriptor's URI. */ + readonly content: ReadResourceResult['contents'][number] +} + const ListSkillsParams = z.looseObject({ cursor: z.string().optional() }).optional() const GetSkillParams = z.looseObject({ uri: z.string() }) @@ -39,8 +52,17 @@ const GetSkillParams = z.looseObject({ uri: z.string() }) * * The capability is declared without `directoryRead`: every entry carries a * complete manifest, which the spec lets hosts answer directory questions from. + * + * @param server - The per-request MCP server. + * @param staticResources - Resources that ship with the Worker, read through + * the same handlers. + * @param options.listStatic - Whether `resources/list` lists them too. Defaults to `true`. */ -export function registerSkills(server: McpServer): void { +export function registerSkills( + server: McpServer, + staticResources: readonly StaticResource[] = [], + { listStatic = true }: { listStatic?: boolean } = {} +): void { server.server.registerCapabilities({ resources: {}, extensions: { [SKILLS_EXTENSION_ID]: {} } @@ -66,12 +88,15 @@ export function registerSkills(server: McpServer): void { server.server.setRequestHandler('resources/list', async () => { const { skills } = await getSkills() return { - resources: skills.map((skill) => ({ - uri: skill.uri, - name: skill.frontmatter.name, - description: skill.frontmatter.description, - mimeType: 'text/markdown' - })), + resources: [ + ...skills.map((skill) => ({ + uri: skill.uri, + name: skill.frontmatter.name, + description: skill.frontmatter.description, + mimeType: 'text/markdown' + })), + ...(listStatic ? staticResources.map((resource) => resource.descriptor) : []) + ], ...SKILLS_CACHE } }) @@ -83,6 +108,8 @@ export function registerSkills(server: McpServer): void { server.server.setRequestHandler('resources/read', async (request) => { const { uri } = request.params + const shipped = staticResources.find((resource) => resource.descriptor.uri === uri) + if (shipped) return { contents: [shipped.content], ...SKILLS_CACHE } const file = (await getSkills()).filesByUri.get(uri) if (!file) throw new ResourceNotFoundError(uri, `No resource is served at ${uri}`) const bytes = await readSkillFile(file) diff --git a/src/threshold-alert/contract.ts b/src/threshold-alert/contract.ts new file mode 100644 index 000000000..f12e0d328 --- /dev/null +++ b/src/threshold-alert/contract.ts @@ -0,0 +1,48 @@ +/** + * The schemas every threshold alert's contract is built from. Pure: the + * App's view imports them, so nothing here may reach server code. + */ +import { z } from 'zod' + +/** What the shared input carries; every threshold alert takes these. */ +export interface ThresholdAlertInput { + readonly account_id?: string + readonly limit?: number + readonly as_of?: string +} + +/** + * The input every threshold alert takes. `limit` is described in the + * preset's unit, so the model passes a number the user named. + */ +export function thresholdAlertInput(limitDescription: string, historyDays: number) { + return z.strictObject({ + account_id: z + .string() + .regex(/^[a-f0-9]{32}$/i) + .optional() + .describe('Account to read. Optional when the connection has exactly one account.'), + limit: z.number().int().positive().optional().describe(limitDescription), + as_of: z.iso + .date() + .optional() + .describe( + `Treat this UTC date as today. Defaults to the current date. Analytics older than ${historyDays} complete days cannot be read.` + ) + }) +} + +/** An alert already on the account that watches the same number. */ +export const ExistingAlertSchema = z.object({ + id: z.string(), + name: z.string(), + enabled: z.boolean(), + /** `monitor`: a `custom_analytics` policy on `events.workersInvocations`. `billing`: a `billing_usage_alert` on `worker_requests`. */ + kind: z.enum(['monitor', 'billing']), + /** Its threshold, when it has one. */ + limit: z.number().optional() +}) +export type ExistingAlert = z.infer + +/** One complete UTC day's value. */ +export const DaySchema = z.tuple([z.iso.date(), z.number().int().nonnegative()]) diff --git a/src/threshold-alert/create.ts b/src/threshold-alert/create.ts new file mode 100644 index 000000000..09a5e6f7f --- /dev/null +++ b/src/threshold-alert/create.ts @@ -0,0 +1,96 @@ +import type { PolicyBody } from './presets' + +/** + * The generated tools the App's buttons call. Create alert: + * `POST /accounts/{account_id}/alerting/v3/policies`. Save alert, on an alert + * the click just made: `PUT …/policies/{policy_id}`. Undo: + * `DELETE …/policies/{policy_id}`. The direct tools list them for everyone; + * Code Mode lists them for threshold alert Apps only (`appTools` in + * `define.ts`), so no tool is added for the writes. + */ +export const CREATE_POLICY_TOOL = 'alerting_policies_create' +export const UPDATE_POLICY_TOOL = 'alerting_policies_update' +export const DELETE_POLICY_TOOL = 'alerting_policies_delete' +export const POLICY_WRITE_TOOLS = [CREATE_POLICY_TOOL, UPDATE_POLICY_TOOL, DELETE_POLICY_TOOL] + +type Policy = PolicyBody +type ToolResult = { isError?: boolean; content?: readonly { type: string; text?: string }[] } +/** The host's `callServerTool`: `app.callServerTool` in the App, a direct `tools/call` in tests. */ +export type CallTool = (call: { + name: string + arguments: Record +}) => Promise + +/** + * What a write did. `done` (with the new policy's id, for a create); + * `refused` with Cloudflare's reason; `unavailable` when the connection lists + * no such tool. + */ +export type WriteResult = + | { status: 'done'; id?: string } + | { status: 'refused'; error: string } + /** No answer from Cloudflare: the write may have been made, so it isn't safe to send again. */ + | { status: 'unknown'; error: string } + | { status: 'unavailable' } + +const text = (r: ToolResult) => r.content?.find((c) => c.type === 'text')?.text ?? '' +const notFound = (s: string) => /\btool\b.*\bnot found\b|unknown tool/i.test(s) + +/** One call to a generated tool. Nothing is retried: each click is one request. */ +async function write( + call: CallTool, + name: string, + args: Record +): Promise { + let r: ToolResult + try { + r = await call({ name, arguments: args }) + } catch (error) { + const message = error instanceof Error ? error.message : String(error) + return notFound(message) ? { status: 'unavailable' } : { status: 'unknown', error: message } + } + if (r.isError) { + if (notFound(text(r))) return { status: 'unavailable' } + // Cloudflare refused: its 4xx answer is the tool error's first line. Anything else has no + // answer the write wasn't made: a lost connection, a timeout, or a 5xx, which a gateway can + // send after the API saved it. + const first = text(r).split('\n', 1)[0] + return first.startsWith('Cloudflare API error:') && !/\breturned HTTP 5\d\d\b/.test(first) + ? { status: 'refused', error: text(r) } + : { status: 'unknown', error: text(r) } + } + const id = createdId(text(r)) + return { status: 'done', ...(id && { id }) } +} + +/** The policy id in a write's result: the envelope's `result.id`, as the tool returns the body. */ +function createdId(body: string): string | undefined { + try { + const id = (JSON.parse(body) as { result?: { id?: unknown } } | null)?.result?.id + return typeof id === 'string' && id ? id : undefined + } catch { + return undefined + } +} + +/** + * Create the policy the user confirmed by clicking Create alert, exactly as + * the App shows it. A connection that doesn't list the tool is `unavailable`, + * so the App hands the policy to the chat instead. + */ +export function createPolicy(call: CallTool, accountId: string, policy: Policy) { + return write(call, CREATE_POLICY_TOOL, { path: { account_id: accountId }, body: policy }) +} + +/** Save alert: replace the alert the App created with the policy it now shows. */ +export function updatePolicy(call: CallTool, accountId: string, policyId: string, policy: Policy) { + return write(call, UPDATE_POLICY_TOOL, { + path: { account_id: accountId, policy_id: policyId }, + body: policy + }) +} + +/** Undo: delete the alert the App just created, by the id the create returned. */ +export function deletePolicy(call: CallTool, accountId: string, policyId: string) { + return write(call, DELETE_POLICY_TOOL, { path: { account_id: accountId, policy_id: policyId } }) +} diff --git a/src/threshold-alert/define.ts b/src/threshold-alert/define.ts new file mode 100644 index 000000000..44b1b373f --- /dev/null +++ b/src/threshold-alert/define.ts @@ -0,0 +1,275 @@ +/** + * `defineThresholdAlertApp()`: an MCP App that charts the history of one + * number, previews an alert on it and lets the user create the alert from + * the card. Each preset (`presets.ts`) says what the alert is; each App says + * how to read its history and how to name its output. + * + * The collector only reads: the history, `available_alerts` and the existing + * policies. The view's Create alert, Save alert and Undo call the generated + * `alerting_policies_*` tools (`create.ts`), so no App adds a write tool. + */ +import type { ToolAnnotations } from '@modelcontextprotocol/server' +import { z } from 'zod' +import { autoResolvedAccountId, missingAccountMessage } from '../auth/account-access' +import { ScopeChallenge } from '../scope-challenge' +import { ApiReadError, ApiReadUnsupported, apiReader, type ApiReader } from '../mcp-apps/api-read' +import { defineMcpApp, type AppContext, type AppOutcome, type McpApp } from '../mcp-apps/define' +import { tools as alertingPolicyTools } from '../generated/forge-mcp/alerting/policies/tools' +import { POLICY_WRITE_TOOLS } from './create' +import { clamp, deriveModel, type Day, type Model } from './model' +import { recogniseAmong, type ExistingKind, type ThresholdAlertPreset } from './presets' +import type { ExistingAlert, ThresholdAlertInput } from './contract' + +export { DaySchema, ExistingAlertSchema, thresholdAlertInput } from './contract' +export type { ExistingAlert, ThresholdAlertInput } from './contract' + +/** What every threshold alert's collector established, before the App names it. */ +export interface Collected { + readonly checkedAt: string + readonly accountId: string + readonly userEmail?: string + readonly today: string + readonly days: Day[] + readonly model: Model + /** The input `limit`, clamped to the chart, or the model's suggestion. `null` with no typical period and no input. */ + readonly suggestedLimit: number | null + readonly alertAvailable: boolean | null + readonly existingAlerts: ExistingAlert[] | null + readonly otherPolicies: Record + readonly limitations: string[] +} + +/** A history read: complete days, oldest first, or a tool error. */ +export type HistoryOutcome = + | { readonly ok: true; readonly days: Day[]; readonly limitations?: readonly string[] } + | { readonly ok: false; readonly text: string; readonly meta?: Record } + +export interface ThresholdAlertAppDefinition { + readonly preset: ThresholdAlertPreset + /** + * Presets whose policies count as already on this account, including this + * one. Other policies are only counted by type. + */ + readonly related: readonly ThresholdAlertPreset[] + readonly title: string + readonly description: string + readonly annotations: ToolAnnotations + readonly input: Input + readonly output: Output + readonly resource: { + readonly uri: `ui://${string}` + readonly name: string + readonly html: string + } + /** Always true of the result: what the numbers are and what the alert doesn't do. */ + readonly limitations: readonly string[] + /** Read the history. A failure is the tool's error: without history there is nothing to preview. */ + readHistory( + accountId: string, + today: string, + reader: ApiReader, + signal: AbortSignal + ): Promise + /** Name the collected facts in the App's output. */ + shape(collected: Collected): z.output +} + +const AvailableAlerts = z.object({ + result: z.record(z.string(), z.array(z.object({ type: z.string() }))) +}) + +const Policies = z.object({ + result: z.array( + z.object({ + id: z.string(), + name: z.string(), + enabled: z.boolean(), + alert_type: z.string(), + filters: z.record(z.string(), z.array(z.string())).optional() + }) + ) +}) + +/** + * The result as the model reads it: everything but the daily series, which + * only the chart draws. The model summarises the history from `summary` (the + * descriptions ask it not to repeat the daily data), and re-reads the result + * on every later turn, so 89 days of counts there are ~2 KB it never uses. + * `days` becomes the range read, in the same place, so the model still knows + * what the summary covers and that the card has the rest. + */ +export function thresholdAlertModelText(value: { readonly days: readonly Day[] }): string { + const { days } = value + return JSON.stringify({ + ...value, + days: days.length + ? { from: days[0][0], to: days[days.length - 1][0], count: days.length } + : { count: 0 } + }) +} + +/** + * Define a threshold alert App: the preset's tool, its static view and a + * read-only collector. The generated policy write tools are its `appTools`. + * + * @returns The App, for `MCP_APPS` in `src/mcp-apps/registry.ts`. + */ +export function defineThresholdAlertApp( + definition: ThresholdAlertAppDefinition +): McpApp { + const { preset } = definition + async function collect( + input: z.output, + context: AppContext, + signal: AbortSignal + ): Promise>> { + const { account_id, limit, as_of } = input as ThresholdAlertInput + const accountId = account_id ?? autoResolvedAccountId(context.props) + if (!accountId) + return { ok: false, text: missingAccountMessage(context.props, 'Use GET /accounts.') } + + const now = new Date() + const today = as_of ?? now.toISOString().slice(0, 10) + const reader = apiReader(context, signal, preset.toolName) + const limitations = [...definition.limitations] + + // Alerting reads only add context. A refusal is noted, not fatal, and + // never reads as "no alerts exist". They never ask for a scope: a step-up + // would replace the whole preview with a 403 for clients that take it over + // HTTP, though the history it needs was read. Create alert asks for the + // scope it needs when the user clicks it. + // + // The three reads are independent, so they go out together: the call takes + // the slowest of them, not their sum (about 370 ms against 545 ms measured). + // A failed history ends the call, so it stops the alerting reads too. + const stopAlerting = new AbortController() + const alertingSignal = AbortSignal.any([signal, stopAlerting.signal]) + const contextReader = apiReader( + { ...context, scopeChallenge: new ScopeChallenge(undefined) }, + alertingSignal, + preset.toolName + ) + // Kept apart until the history is read, so the history's notes come first as before. + const alertingNotes: string[] = [] + const optional = async (read: () => Promise, what: string): Promise => { + try { + return await read() + } catch (error) { + if (alertingSignal.aborted) throw error + if (error instanceof ApiReadError) { + alertingNotes.push(`${what} could not be read: ${error.text}`) + } else if (error instanceof ApiReadUnsupported || error instanceof z.ZodError) { + alertingNotes.push( + `${what} could not be read: Cloudflare returned an unsupported response.` + ) + } else throw error + return null + } + } + const prefix = `/accounts/${accountId}/alerting/v3` + const alerting = Promise.all([ + optional( + () => contextReader.get(`${prefix}/available_alerts`, AvailableAlerts), + 'Available alert types' + ), + optional( + () => contextReader.get(`${prefix}/policies`, Policies), + 'Existing notification policies' + ) + ]) + // Handled now, so an early return below leaves no rejection unhandled; the await rethrows. + alerting.catch(() => {}) + const history = await definition + .readHistory(accountId, today, reader, signal) + .catch((error: unknown) => { + stopAlerting.abort() + throw error + }) + if (!history.ok) { + stopAlerting.abort() + return history + } + const [available, policies] = await alerting + limitations.push(...(history.limitations ?? []), ...alertingNotes) + + const otherPolicies: Record = {} + const existingAlerts = policies + ? policies.result.flatMap((policy): ExistingAlert[] => { + const watch = recogniseAmong(definition.related, policy) + if (!watch) { + otherPolicies[policy.alert_type] = (otherPolicies[policy.alert_type] ?? 0) + 1 + return [] + } + return [ + { + id: policy.id, + name: policy.name, + enabled: policy.enabled, + kind: watch.kind satisfies ExistingKind, + ...(Number.isFinite(watch.limit) ? { limit: watch.limit } : {}) + } + ] + }) + : null + + const days = history.days + const model = deriveModel(days, today, preset.cadence) + if (days.length && days.length < 7) + limitations.push( + `Only ${days.length} days of history: under a week, so there is no typical ${preset.copy.bucket} to compare against.` + ) + // The line starts a tenth over the busiest period. On a rolling monitor, a number the user named + // moves it only when it is above that period: one below would already have emailed, so it can't + // be what they meant by "clearly bigger", and the card would open over the bars with the alert + // firing. A monthly alert starts over each billing period, and crossing a number most months + // (the included requests) is the point, so a named number is kept and the overlap is said. + const monthly = preset.cadence.kind === 'month' + const named = limit != null && (monthly || limit > model.peak) + if (limit != null && monthly && limit <= model.peak) + limitations.push( + `The busiest ${preset.copy.bucket} charted (${Math.round(model.peak).toLocaleString('en')}, counting this ${preset.copy.bucket} projected to its end) is at or above ${limit.toLocaleString('en')}, so this alert would email in a ${preset.copy.bucket} like it. Say so in one sentence.` + ) + if (limit != null && !named) + limitations.push( + `The line starts a tenth above the busiest ${preset.copy.bucket}, not at the number named (${limit.toLocaleString('en')}): that number is at or below the busiest ${preset.copy.bucket} (${Math.round(model.peak).toLocaleString('en')}), so it would already have emailed. Lead with this in one sentence and point to the card, where the user drags the line; don't ask for a number in chat.` + ) + const clamped = named ? clamp(limit, model.minLimit, model.maxLimit) : null + if (named && clamped !== limit) + limitations.push( + `The line starts at ${clamped!.toLocaleString('en')}, not at the number named (${limit.toLocaleString('en')}): that is the ${clamped! > limit ? 'lowest' : 'highest'} the card's line reaches for this history. Say so in one sentence.` + ) + const suggested = clamped ?? model.suggested + const value = definition.shape({ + checkedAt: now.toISOString(), + accountId, + ...(context.props.type === 'user_token' ? { userEmail: context.props.user.email } : {}), + today, + days, + model, + suggestedLimit: model.typical == null && !named ? null : suggested, + alertAvailable: available + ? Object.values(available.result).some((types) => + types.some((type) => type.type === preset.alertType) + ) + : null, + existingAlerts, + otherPolicies, + limitations + }) + return { ok: true, value } + } + + return defineMcpApp({ + name: preset.toolName, + title: definition.title, + description: definition.description, + annotations: definition.annotations, + input: definition.input, + output: definition.output, + resource: definition.resource, + // Create alert, Save alert and Undo call the generated tools; see `create.ts`. + appTools: alertingPolicyTools.filter((tool) => POLICY_WRITE_TOOLS.includes(tool.name)), + modelText: thresholdAlertModelText, + run: collect + }) +} diff --git a/src/threshold-alert/model.ts b/src/threshold-alert/model.ts new file mode 100644 index 000000000..0192fe2a1 --- /dev/null +++ b/src/threshold-alert/model.ts @@ -0,0 +1,377 @@ +/** + * A threshold alert's arithmetic: a daily history of one number, the rule the + * alert applies to it, and the chart that shows both. Shared by every + * preset's collector and the view, so the model's text and the chart agree. + * Pure: no clock, no DOM. + * + * A preset picks a {@link Cadence}: what the alert compares with its line + * each day, and the buckets the chart draws. Every number here is in the + * cadence's unit (requests in 7 days, requests in a month). + */ + +/** One complete UTC day: `[YYYY-MM-DD, value]`. */ +export type Day = [string, number] + +const DAY_MS = 864e5 +/** Days of history before there is a typical period to compare against. */ +const MIN_DAYS = 7 +/** An average month, for the typical month. */ +const MONTH_DAYS = 365.25 / 12 + +export const isoDay = (ms: number) => new Date(ms).toISOString().slice(0, 10) +export const dayMs = (date: string) => Date.parse(`${date}T00:00:00Z`) +const dayNumber = (date: string) => Math.round(dayMs(date) / DAY_MS) + +/** + * What the alert measures, and how the chart groups days. + * + * - `rolling`: every day it compares the last `days` days with the line, and + * emails again every `days` days while over (a `custom_analytics` monitor + * with a `168h` window and `alert_interval`). The chart draws weeks. + * - `month`: it compares the total since the month began, emails once when + * that passes the line, and starts again next month (billing alerts). The + * chart draws calendar months. + */ +export type Cadence = { readonly kind: 'rolling'; readonly days: 7 } | { readonly kind: 'month' } + +export const ROLLING_7_DAYS: Cadence = { kind: 'rolling', days: 7 } +export const CALENDAR_MONTH: Cadence = { kind: 'month' } + +/** Days in a typical period: what a median day is multiplied by. */ +const typicalDays = (cadence: Cadence) => (cadence.kind === 'rolling' ? cadence.days : MONTH_DAYS) + +// ── Scale: nice numbers, 1, 2, 5 × 10ⁿ, so steps and ticks suit any account size ── + +export function nice(x: number, set: readonly number[] = [1, 2, 5]): number { + const e = 10 ** Math.floor(Math.log10(x)) + return (set.find((m) => m * e >= x * 0.9999) ?? 10) * e +} +/** Drag and arrow-key precision: about 30 stops per axis. */ +export const stepOf = (top: number) => Math.max(1, nice(top / 30)) +/** Gridline spacing: 2 to 5 lines. */ +export const tickOf = (top: number) => Math.max(1, nice(top / 5, [1, 2, 2.5, 5])) +/** The axis top for a value: the next half tick above it. */ +export function niceTop(value: number): number { + const v = Math.max(value, 10) + const half = tickOf(v) / 2 + return Math.ceil(v / half - 1e-9) * half +} +export const clamp = (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, v)) +export const snapTo = (v: number, step: number) => Math.round(v / step) * step + +// ── The alert's rule ── + +/** The 7-day total at the end of each day from the seventh on: what the monitor's query returns then. */ +export function rolling7(days: readonly Day[]): Map { + return measured(days, ROLLING_7_DAYS) +} + +/** + * What the alert compares with its line at the end of each day: the last + * `days` days from the first full window on (`rolling`), or the total since + * the month began (`month`). + */ +export function measured(days: readonly Day[], cadence: Cadence): Map { + const out = new Map() + let total = 0 + if (cadence.kind === 'month') { + let month = '' + for (const [date, n] of days) { + if (date.slice(0, 7) !== month) { + month = date.slice(0, 7) + total = 0 + } + total += n + out.set(date, total) + } + return out + } + const period = cadence.days + days.forEach(([date, n], i) => { + total += n + if (i >= period) total -= days[i - period][1] + if (i >= period - 1) out.set(date, total) + }) + return out +} + +/** + * The median day × the period's days. An account idle most days falls back + * to the mean, so only true silence, or under a week of history, has no + * typical period. + */ +export function typicalPeriod(days: readonly Day[], cadence: Cadence = ROLLING_7_DAYS) { + if (days.length < MIN_DAYS) return null + const sorted = days.map(([, n]) => n).sort((a, b) => a - b) + const median = sorted[sorted.length >> 1] + const mean = sorted.reduce((a, b) => a + b, 0) / sorted.length + return (median || mean) * typicalDays(cadence) || null +} + +/** The median day × 7. */ +export const typicalWeek = (days: readonly Day[]) => typicalPeriod(days, ROLLING_7_DAYS) + +export interface Email { + readonly date: string + /** The first email of a run over the line, rather than a repeat while it stays over. */ + readonly first: boolean +} + +/** + * Replay the alert over the history. `rolling`: an email when the window + * first passes `limit`, then every `days` days while it stays over. `month`: + * one email the day the month's total passes `limit`. + */ +export function replayEmails( + days: readonly Day[], + values: ReadonlyMap, + limit: number, + cadence: Cadence = ROLLING_7_DAYS +): Email[] { + const out: Email[] = [] + if (cadence.kind === 'month') { + let sent = '' + for (const [date] of days) { + const total = values.get(date) + const month = date.slice(0, 7) + if (total == null || total < limit || sent === month) continue + out.push({ date, first: true }) + sent = month + } + return out + } + let last: string | null = null + for (const [date] of days) { + const total = values.get(date) + if (total == null) continue + if (total < limit) { + last = null + continue + } + if (last == null || dayNumber(date) - dayNumber(last) >= cadence.days) { + out.push({ date, first: last == null }) + last = date + } + } + return out +} + +// ── The chart's model ── + +/** One column: a Monday-to-Sunday week, or a calendar month. */ +export interface Bucket { + readonly start: string + readonly end: string + /** Days the bucket spans: 7, or the month's. */ + readonly length: number + /** The bucket's last day with data. */ + readonly lastDay: string | null + /** Measured values, and the estimate for the bucket's remaining days. */ + readonly rawActual: number + readonly rawEstimate: number + /** Day offset from the first bucket's start, for placing the column. */ + readonly offset: number + readonly daysActual: number + readonly daysEstimate: number + /** Heights on the alert's scale: the bucket's average day × its length. */ + readonly actual: number + readonly estimate: number + readonly total: number + /** What the alert measured at `lastDay`. */ + readonly rolling: number | null + /** A bucket the read window cuts, drawn as an outline. */ + readonly partial: boolean +} +/** The weekly cadence's bucket. */ +export type Week = Bucket + +export interface Month { + /** `YYYY-MM`. */ + readonly key: string + /** Day offsets the month covers on the chart. */ + readonly from: number + readonly to: number +} + +export interface Model { + readonly cadence: Cadence + readonly days: readonly Day[] + readonly weeks: readonly Bucket[] + readonly months: readonly Month[] + /** Days the chart spans, from the first bucket's start. */ + readonly span: number + /** What the alert measured at the end of each day. */ + readonly rolling: ReadonlyMap + readonly typical: number | null + /** What the alert measures now: the last 7 complete days, or this month so far. */ + readonly current: number + /** The busiest period in the history. */ + readonly peak: number + /** The highest normal bucket: one far above the rest runs off the top instead of flattening the others. */ + readonly dataTop: number + /** The fitted axis top, and the range the line can reach. */ + readonly base: number + readonly minTop: number + readonly minLimit: number + readonly maxLimit: number + /** + * "Clearly bigger than normal": a tenth above the busiest period in the + * history or the tallest bar, whichever is higher, rounded up on the axis's step. Nothing in the history would + * have emailed, and the chart scales up to show the line above every bucket. + */ + readonly suggested: number | null +} + +/** The suggested threshold over the busiest period. */ +export const SUGGESTED_OVER_BUSIEST = 1.1 + +/** Headroom above whichever is higher, the normal buckets or the line. */ +export const fitTop = (model: Model, limit: number) => + niceTop(Math.max(model.dataTop, limit) * 1.15) + +const mondayOf = (ms: number) => ms - ((new Date(ms).getUTCDay() + 6) % 7) * DAY_MS +const monthOf = (ms: number) => { + const d = new Date(ms) + return Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), 1) +} +const nextMonth = (ms: number) => { + const d = new Date(ms) + return Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + 1, 1) +} + +/** `[start, length]` of each bucket from the one holding `first` to the one holding `today`. */ +function buckets(cadence: Cadence, first: number, today: number): [number, number][] { + const out: [number, number][] = [] + if (cadence.kind === 'rolling') + for (let w = mondayOf(first); w <= today; w += 7 * DAY_MS) out.push([w, 7]) + else + for (let m = monthOf(first); m <= today; m = nextMonth(m)) + out.push([m, Math.round((nextMonth(m) - m) / DAY_MS)]) + return out +} + +/** + * Derive everything the card shows from the complete days. + * + * @param days - Complete UTC days, oldest first, with no gaps. + * @param today - The first day not in `days`; the current bucket's rest is estimated from the last 7 days' pace. + * @param cadence - The alert's rule. Defaults to the rolling 7 days the Workers monitor uses. + */ +export function deriveModel( + days: readonly Day[], + today: string, + cadence: Cadence = ROLLING_7_DAYS +): Model { + const rolling = measured(days, cadence) + const pace = days.length + ? days.slice(-MIN_DAYS).reduce((a, [, n]) => a + n, 0) / Math.min(MIN_DAYS, days.length) + : 0 + const values = new Map(days) + const weeks: Bucket[] = [] + if (days.length) { + const lastActual = days[days.length - 1][0] + const all = buckets(cadence, dayMs(days[0][0]), dayMs(today)) + const origin = all[0]?.[0] ?? 0 + for (const [w, length] of all) { + let actual = 0 + let nActual = 0 + let estimate = 0 + let nEstimate = 0 + let lastDay: string | null = null + for (let i = 0; i < length; i++) { + const date = isoDay(w + i * DAY_MS) + const n = values.get(date) + if (n != null) { + actual += n + nActual++ + lastDay = date + } else if (date > lastActual) { + estimate += pace + nEstimate++ + } + } + const n = nActual + nEstimate + if (!n) continue + weeks.push({ + start: isoDay(w), + end: isoDay(w + (length - 1) * DAY_MS), + length, + lastDay, + rawActual: actual, + rawEstimate: estimate, + offset: Math.round((w - origin) / DAY_MS), + daysActual: nActual, + daysEstimate: nEstimate, + actual: (actual / n) * length, + estimate: (estimate / n) * length, + total: ((actual + estimate) / n) * length, + rolling: lastDay ? (rolling.get(lastDay) ?? null) : null, + partial: n < length && !nEstimate + }) + } + } + // The window opens mid-bucket: start the chart at the first day with data. + const shift = weeks[0]?.offset ?? 0 + const placed = weeks.map((w) => ({ ...w, offset: w.offset - shift })) + const lastBucket = placed[placed.length - 1] + const span = lastBucket ? lastBucket.offset + lastBucket.length : 1 + const origin = placed.length ? dayMs(placed[0].start) : 0 + const offsetOf = (date: string) => Math.round((dayMs(date) - origin) / DAY_MS) + + const months: Month[] = [] + for (const [date] of days) { + const key = date.slice(0, 7) + const at = Math.max(0, offsetOf(date)) + const last = months[months.length - 1] + if (last?.key === key) months[months.length - 1] = { ...last, to: at + 1 } + else months.push({ key, from: at, to: at + 1 }) + } + + const typical = typicalPeriod(days, cadence) + const lastDate = days[days.length - 1]?.[0] + const current = !days.length + ? 0 + : cadence.kind === 'rolling' + ? (rolling.get(lastDate) ?? pace * cadence.days) + : // Yesterday's month total, or 0 when today starts a new month. + lastDate.slice(0, 7) === today.slice(0, 7) + ? (rolling.get(lastDate) ?? 0) + : 0 + // The busiest period: the most the alert measured on any day, and, by month, this month + // projected to its end. A month the window cuts counts as far as it was read, a lower bound. + const projected = + cadence.kind === 'month' ? placed.filter((w) => !w.partial).map((w) => w.total) : [] + const peak = Math.max(0, ...rolling.values(), ...projected) + const totals = placed.map((w) => w.total).sort((a, b) => b - a) + const dataTop = Math.max( + current, + totals.length > 3 && totals[0] > 1.6 * totals[1] ? totals[1] : (totals[0] ?? 0) + ) + const base = niceTop(dataTop * 1.15) + const minTop = Math.max(10, niceTop(base / 100)) + const minLimit = stepOf(minTop) + const maxLimit = niceTop(Math.max(dataTop * 100, peak * 10, 10)) + // A tenth over the tallest thing on the chart: the busiest period, or a bar drawn taller than it + // (this period's estimate, a cut bucket scaled to its length), so the line opens above every bar. + const over = Math.max(peak, ...placed.map((w) => w.total)) * SUGGESTED_OVER_BUSIEST + const step = stepOf(niceTop(over)) + const suggested = + typical == null ? null : clamp(Math.ceil(over / step) * step, minLimit, maxLimit) + return { + cadence, + days, + weeks: placed, + months, + span, + rolling, + typical, + current, + peak, + dataTop, + base, + minTop, + minLimit, + maxLimit, + suggested + } +} diff --git a/src/threshold-alert/presets.ts b/src/threshold-alert/presets.ts new file mode 100644 index 000000000..93be77961 --- /dev/null +++ b/src/threshold-alert/presets.ts @@ -0,0 +1,208 @@ +/** + * Threshold alert presets: everything about one kind of "history of one + * number + a line + who to tell" alert that the view and the collector share. + * Pure (no reads, no DOM), so the App's view imports it too. + * + * Every preset creates one notification policy with the generated + * `alerting_policies_create`; only `alert_type`, the threshold filter and the + * history differ. The server half (the history reader) is in each App's + * `tool.ts`; see `defineThresholdAlertApp`. + */ +import { CALENDAR_MONTH, ROLLING_7_DAYS, type Cadence } from './model' + +/** Every registered preset. */ +export type PresetId = 'workers-requests-monitor' | 'workers-requests-billing' + +/** How an existing policy is reported: by the preset that would have created it. */ +export type ExistingKind = 'monitor' | 'billing' + +/** A policy as `GET …/alerting/v3/policies` lists it, as far as recognising one needs. */ +export interface ListedPolicy { + readonly alert_type: string + readonly filters?: Readonly> +} + +/** The policy body `alerting_policies_create` sends, exactly as the App shows it. */ +export interface PolicyBody { + readonly name: string + readonly alert_type: string + readonly enabled: true + readonly filters: Readonly> + readonly alert_interval?: string + readonly mechanisms: { readonly email: readonly { readonly id: string }[] } +} + +/** What the threshold counts, for the slider and the sentences that name it. */ +export interface Unit { + /** `'requests'`. Shown after a number: "about 800 million requests". */ + readonly noun: string +} + +/** The view's copy. `{limit}` is the formatted threshold. */ +export interface PresetCopy { + /** The alert, in a sentence: "Workers usage alert". */ + readonly label: string + /** The card's title: what the alert does, in the user's words. */ + readonly title: string + /** The chart's accessible name. */ + readonly chartLabel: string + /** The slider's accessible name. */ + readonly sliderLabel: string + /** The period the threshold is per, after a number: "in 7 days", "in a billing period". */ + readonly per: string + /** A bucket: "week", "month". */ + readonly bucket: string + /** The current period: "Last 7 days", "This month". */ + readonly current: string + /** The over-the-line warning: when it emails if it is already over. */ + readonly alreadyOver: string + /** What didn't answer when the read failed: "Workers analytics". */ + readonly source: string + /** The card's message when `available_alerts` lacks the type: it replaces the chart and the form. */ + readonly unavailable: { readonly title: string; readonly body: string } +} + +export interface ThresholdAlertPreset { + readonly id: PresetId + /** The tool that serves it; also how `updateModelContext` names the App. */ + readonly toolName: string + /** The policy's `alert_type`, which `available_alerts` must list. */ + readonly alertType: string + /** How this preset's existing policies are reported. */ + readonly existingKind: ExistingKind + readonly cadence: Cadence + readonly unit: Unit + readonly copy: PresetCopy + /** The policy Create alert sends. */ + policy(accountId: string, limit: number, email: string, name: string): PolicyBody + /** The policy's name, from the formatted threshold. */ + name(limit: string): string + /** Whether a listed policy is one of this preset's, and its threshold. */ + recognise(policy: ListedPolicy): { readonly limit: number } | null +} + +const first = (policy: ListedPolicy, key: string) => Number(policy.filters?.[key]?.[0]) + +// ── workers-requests-monitor: today's behaviour ── + +/** The SQL the monitor runs every hour. Its daily counts match the GraphQL read. */ +export function monitorQuery(accountId: string): string { + return `SELECT COUNT(*) AS value +FROM events.workersInvocations +WHERE accountTag = '${accountId}' + AND timestamp >= NOW() - INTERVAL '7' DAY` +} + +/** The `custom_analytics` policy the Workers usage alert shows and, on Create alert, creates. */ +export function monitorPolicy(accountId: string, limit: number, email: string, name: string) { + return { + name, + alert_type: 'custom_analytics', + enabled: true as const, + filters: { + source: ['sql_api'], + selectors: [monitorQuery(accountId)], + alert_trigger_preferences: ['threshold'], + alert_trigger_preferences_operator: ['>='], + alert_trigger_preferences_value: [String(limit)], + alert_trigger_preferences_short_window: ['168h'], + execution_interval: ['1h'] + }, + alert_interval: '168h', + mechanisms: { email: [{ id: email }] } + } +} + +const WORKERS_REQUESTS: Unit = { noun: 'requests' } + +export const WORKERS_REQUESTS_MONITOR: ThresholdAlertPreset = { + id: 'workers-requests-monitor', + toolName: 'workers_usage_alert', + alertType: 'custom_analytics', + existingKind: 'monitor', + cadence: ROLLING_7_DAYS, + unit: WORKERS_REQUESTS, + copy: { + label: 'Workers usage alert', + title: 'Email me when 7 days of Workers requests pass the line', + chartLabel: 'Workers requests per week, with the 7-day alert threshold', + sliderLabel: 'Alert threshold, requests in 7 days', + per: 'in 7 days', + bucket: 'week', + current: 'Last 7 days', + alreadyOver: 'Already over: emails within the hour', + source: 'Workers analytics', + unavailable: { + title: 'Usage alerts aren’t on this plan', + body: 'This account can’t create custom analytics alerts, so there’s nothing to set up here.' + } + }, + policy: monitorPolicy, + name: (limit) => `Workers requests over ${limit} in 7 days`, + recognise: (policy) => + policy.alert_type === 'custom_analytics' && + policy.filters?.selectors?.some((sql) => /\bevents\.workersInvocations\b/i.test(sql)) + ? { limit: first(policy, 'alert_trigger_preferences_value') } + : null +} + +// ── workers-requests-billing: a billing_usage_alert on worker_requests ── + +/** The `billing_usage_alert` product for Workers requests, as the dashboard's Usage Based Billing form sends it. */ +export const WORKER_REQUESTS_PRODUCT = 'worker_requests' + +export function billingUsagePolicy(_accountId: string, limit: number, email: string, name: string) { + return { + name, + alert_type: 'billing_usage_alert', + enabled: true as const, + filters: { product: [WORKER_REQUESTS_PRODUCT], limit: [String(limit)] }, + mechanisms: { email: [{ id: email }] } + } +} + +export const WORKERS_REQUESTS_BILLING: ThresholdAlertPreset = { + id: 'workers-requests-billing', + toolName: 'workers_billing_alert', + alertType: 'billing_usage_alert', + existingKind: 'billing', + cadence: CALENDAR_MONTH, + unit: WORKERS_REQUESTS, + copy: { + label: 'Workers billing usage alert', + title: 'Email me when billed Workers requests pass the line', + chartLabel: 'Workers requests per month, with the billing usage threshold', + sliderLabel: 'Alert threshold, billed requests in a billing period', + per: 'in a billing period', + bucket: 'month', + current: 'This month', + alreadyOver: 'Likely over this month: emails once billing counts it', + source: 'Workers analytics', + unavailable: { + title: 'Billing alerts aren’t on this plan', + body: 'This account can’t create usage-based billing alerts, so there’s nothing to set up here.' + } + }, + policy: billingUsagePolicy, + name: (limit) => `Billed Workers requests over ${limit}`, + recognise: (policy) => + policy.alert_type === 'billing_usage_alert' && + policy.filters?.product?.includes(WORKER_REQUESTS_PRODUCT) + ? { limit: first(policy, 'limit') } + : null +} + +/** Every registered preset, by id. */ +export const PRESETS: Readonly> = { + 'workers-requests-monitor': WORKERS_REQUESTS_MONITOR, + 'workers-requests-billing': WORKERS_REQUESTS_BILLING +} + +/** Which preset's policy a listed one is, if any, among `presets`. */ +export function recogniseAmong(presets: readonly ThresholdAlertPreset[], policy: ListedPolicy) { + for (const preset of presets) { + const hit = preset.recognise(policy) + if (hit) return { kind: preset.existingKind, limit: hit.limit } + } + return null +} diff --git a/src/tools/forge-tools.ts b/src/tools/forge-tools.ts index 4b8cf7e53..91370df32 100644 --- a/src/tools/forge-tools.ts +++ b/src/tools/forge-tools.ts @@ -1,7 +1,13 @@ import { z } from 'zod' import { env } from 'cloudflare:workers' import { PROTOCOL_VERSION_META_KEY } from '@modelcontextprotocol/server' -import type { McpServer, CallToolResult, ServerContext } from '@modelcontextprotocol/server' +import type { + McpServer, + CallToolResult, + ServerContext, + StandardSchemaWithJSON, + Tool +} from '@modelcontextprotocol/server' import type { FormatToolResult } from '../truncate' import { fetchWithRetry } from '../utils/fetch-retry' import { rateLimitHint } from '../rate-limit' @@ -16,6 +22,14 @@ import { checkResponse } from '../response-validation' import { DOCS_TOOL, runDocsTool } from './docs-search' import { WHOAMI_TOOL, WhoamiInputSchema, runWhoamiTool } from './whoami' import { SUBMIT_FEEDBACK_TOOL, feedbackTools, runSubmitFeedbackTool } from './submit-feedback' +import { + MCP_APP_GENERATED_TOOLS, + MCP_APP_TEXT_TOOLS, + MCP_APP_TOOLS, + mcpAppNamed +} from '../mcp-apps/registry' +import type { AppContext } from '../mcp-apps/define' +import { stringifyResponse } from '../truncate' import type { AuthProps } from '../auth/types' import { acceptedPermissions, type Connection } from '../api-permissions' import { apiCallResult } from './api-call-result' @@ -26,6 +40,22 @@ import type { CallPlan } from '../forge-tools/plan' import { FORGE_ACCOUNT_DISCOVERY_GUIDANCE, PERMISSIONS_EXTENSION } from '../forge-tools/policy' import { policyRefusalHint } from '../policy-guards' +/** + * The tools this Worker serves itself in direct mode, listed before the + * generated ones: `docs`, `whoami`, `submit_feedback` when it is configured, + * and the MCP Apps, linked to their views only for a client that declared MCP + * Apps. Both `tools/list` paths (the SDK's and `cachedToolListResponse`) send + * this list. + */ +export function localDirectTools({ mcpApps = false }: { mcpApps?: boolean } = {}): Tool[] { + return [ + DOCS_TOOL, + WHOAMI_TOOL, + ...feedbackTools(), + ...(mcpApps ? MCP_APP_TOOLS : MCP_APP_TEXT_TOOLS) + ] +} + /** The forge tools service, which holds the generated tools (`src/forge-tools/worker.ts`). */ function forgeTools() { return env.FORGE_TOOLS @@ -54,13 +84,11 @@ export function registerForgeTools( formatResult: FormatToolResult, connection: Connection, scopeChallenge: ScopeChallenge, - { outputSchema = false }: { outputSchema?: boolean } = {} + { outputSchema = false, mcpApps = false }: { outputSchema?: boolean; mcpApps?: boolean } = {} ): void { server.server.setRequestHandler('tools/list', async (_request, ctx) => ({ tools: [ - DOCS_TOOL, - WHOAMI_TOOL, - ...feedbackTools(), + ...localDirectTools({ mcpApps }), ...(await getForgeToolList({ outputSchema: outputSchema && isModern(ctx) })) ] })) @@ -83,13 +111,14 @@ export function registerForgeTools( : toolError(`Invalid arguments for tool ${name}: ${parsed.error.message}`) } else if (name === SUBMIT_FEEDBACK_TOOL.name && feedbackTools().length > 0) { result = await runSubmitFeedbackTool(args, 'direct', props) + } else if (mcpAppNamed(name)) { + result = await mcpAppNamed(name)!.call( + args, + { props, connection, scopeChallenge, view: mcpApps }, + ctx + ) } else { - const sessionAccountId = autoResolvedAccountId(props) - const plan = (await forgeTools().plan(name, args, { - baseUrl: env.CLOUDFLARE_API_BASE, - ...(sessionAccountId && { sessionAccountId }) - })) as CallPlan - result = await callForgeTool(name, plan, props, formatResult, { + result = await callGeneratedTool(name, args, props, formatResult, { connection, scopeChallenge, structured: outputSchema && isModern(ctx) @@ -104,6 +133,76 @@ export function registerForgeTools( }) } +/** + * Call one generated tool: the forge tools service plans the request from + * `args`, checked against the tool's input schema, and this Worker sends it + * with the session's token. The direct tools call every generated tool this + * way, and Code Mode the few an MCP App's view calls (`appTools`). + */ +export async function callGeneratedTool( + name: string, + args: Record, + props: AuthProps, + formatResult: FormatToolResult, + options: { connection: Connection; scopeChallenge: ScopeChallenge; structured: boolean } +): Promise { + const sessionAccountId = autoResolvedAccountId(props) + const plan = (await forgeTools().plan(name, args, { + baseUrl: env.CLOUDFLARE_API_BASE, + ...(sessionAccountId && { sessionAccountId }) + })) as CallPlan + return callForgeTool(name, plan, props, formatResult, options) +} + +/** + * Register, on a Code Mode server, the generated tools MCP Apps' views call + * (`appTools` in `defineMcpApp`), app-only so the model never sees them. + * Each is served as the direct tools serve it: planned and checked against + * its input schema by the forge tools service, sent with the session's token, + * with the same refusal explanations and step-up, and never truncated, since + * the view reads the result. + */ +export function registerAppGeneratedTools( + server: McpServer, + context: AppContext, + tools: readonly Tool[] = MCP_APP_GENERATED_TOOLS +): void { + for (const tool of tools) { + server.registerTool( + tool.name, + { + ...(tool.title !== undefined && { title: tool.title }), + ...(tool.description !== undefined && { description: tool.description }), + ...(tool.annotations && { annotations: { ...tool.annotations } }), + ...(tool._meta && { _meta: tool._meta }), + inputSchema: listedAs(tool.inputSchema) + }, + (args: Record) => + callGeneratedTool(tool.name, args, context.props, stringifyResponse, { + connection: context.connection, + scopeChallenge: context.scopeChallenge, + structured: false + }) + ) + } +} + +/** + * A generated tool's JSON Schema as the SDK takes an input schema: listed as + * it is, and accepting every value, since the forge tools service checks the + * arguments when it plans the call, as it does for the direct tools. + */ +function listedAs(schema: Tool['inputSchema']): StandardSchemaWithJSON> { + return { + '~standard': { + version: 1, + vendor: 'cloudflare-mcp', + validate: (value) => ({ value: value as Record }), + jsonSchema: { input: () => schema, output: () => schema } + } + } +} + async function callForgeTool( name: string, plan: CallPlan, @@ -140,7 +239,11 @@ async function callForgeTool( headers: { ...plan.headers, authorization: `Bearer ${props.accessToken}` }, body: plan.body }, - { caller: 'forge_tool_call' } + { + caller: 'forge_tool_call', + // A POST or PATCH that may have reached Cloudflare isn't sent again: it could create a second policy. + retryNetworkErrors: !['POST', 'PATCH'].includes(plan.method.toUpperCase()) + } ) // A 429's headers say how long to wait; the agent only sees the body. const rateLimit = rateLimitHint(response.status, response.headers) diff --git a/src/tools/tool-list-response.ts b/src/tools/tool-list-response.ts index 614e6a01c..12c6dc1bf 100644 --- a/src/tools/tool-list-response.ts +++ b/src/tools/tool-list-response.ts @@ -1,8 +1,6 @@ import { isLegacyRequest, SUPPORTED_PROTOCOL_VERSIONS } from '@modelcontextprotocol/server' import type { Tool } from '@modelcontextprotocol/server' -import { DOCS_TOOL } from './docs-search' -import { WHOAMI_TOOL } from './whoami' -import { feedbackTools } from './submit-feedback' +import { localDirectTools } from './forge-tools' import { isolate } from '../lib/isolate' /** @@ -15,10 +13,11 @@ const MAX_BODY_BYTES = 4096 * Each direct-tool listing as UTF-8 JSON, encoded once per cached listing and * so again whenever the listing's own cache reloads. Bytes, not a string: * building and encoding a 3.7 MB string per response costs about as much as - * the stringify this replaces. + * the stringify this replaces. A 2025-era request never declares MCP Apps, so + * the Apps are listed without their views. */ const toolsJson = isolate.derived((tools: readonly Tool[]) => - new TextEncoder().encode(JSON.stringify([DOCS_TOOL, WHOAMI_TOOL, ...feedbackTools(), ...tools])) + new TextEncoder().encode(JSON.stringify([...localDirectTools(), ...tools])) ) /** A lone 2025-era `tools/list` request for the first page, or `undefined` for anything else. */ @@ -64,13 +63,14 @@ async function plainToolListRequestId(request: Request): Promise> = { // wait is worse than failing fast with the server's Retry-After. maxDelayMs: 5_000, jitter: true, - retryRateLimited: true + retryRateLimited: true, + retryNetworkErrors: true } /** @@ -164,6 +171,13 @@ export async function fetchWithRetry( } } catch (error) { lastError = error + // Even after a 429: this attempt is a new request, and it may have reached the server. + if (!opts.retryNetworkErrors) { + console.warn( + `fetchWithRetry: network error${caller} url=${url}, not retried: the request may have been received: ${error instanceof Error ? error.message : error}` + ) + throw error + } if (attempt < opts.maxRetries) { const delay = computeRetryDelay(attempt, opts) diff --git a/src/workers-usage-alert/app-html.generated.ts b/src/workers-usage-alert/app-html.generated.ts new file mode 100644 index 000000000..cb5e8e3d8 --- /dev/null +++ b/src/workers-usage-alert/app-html.generated.ts @@ -0,0 +1,2 @@ +// Generated by npm run app:build. Do not edit. +export const appHtml = "\n\n \n \n \n Workers usage alert\n \n \n \n \n
\n \n\n" diff --git a/src/workers-usage-alert/app/format.ts b/src/workers-usage-alert/app/format.ts new file mode 100644 index 000000000..73e4c9a97 --- /dev/null +++ b/src/workers-usage-alert/app/format.ts @@ -0,0 +1,57 @@ +import { appLocale } from '../../mcp-apps/app-shell/apply-locale' + +/** + * Counts and dates in the host's formats, from the browser's `Intl`: no + * catalog, and every locale's separators, digits and compact units for free + * ("1.35B", "1,35B", "١٫٣٥B"). Formatters are built once per locale. + * + * `fmt` is a value the user picked (a multiple of a nice step), in its + * shortest exact form; `sig` a measured value to `n` significant digits; + * `approx` either with the locale's "about" sign; `words` the long form for + * screen readers ("1.35 billion"). + */ +const cache = new Map() +function cached( + key: string, + make: (lang: string) => T +): T { + const lang = appLocale().formats + const k = `${lang}|${key}` + let f = cache.get(k) as T | undefined + if (!f) cache.set(k, (f = make(lang))) + return f +} +const number = (key: string, options: Intl.NumberFormatOptions) => + cached(key, (lang) => new Intl.NumberFormat(lang, { notation: 'compact', ...options })) +const date = (key: string, options: Intl.DateTimeFormatOptions) => + cached( + key, + (lang) => new Intl.DateTimeFormat(lang, { calendar: 'gregory', timeZone: 'UTC', ...options }) + ) + +export const fmt = (v: number) => number('fmt', { maximumFractionDigits: 3 }).format(v) +export const sig = (v: number, n = 2) => + number(`sig${n}`, { maximumSignificantDigits: n }).format(v) +/** "~1.35B": `formatRange` of one value is the locale's approximate form. */ +export const approx = (v: number, n?: number) => + number( + n ? `sig${n}` : 'fmt', + n ? { maximumSignificantDigits: n } : { maximumFractionDigits: 3 } + ).formatRange(v, v) +export const words = (v: number) => + number('words', { compactDisplay: 'long', maximumFractionDigits: 3 }).format(v) + +const utc = (d: string) => new Date(`${d}T00:00:00Z`) +/** `2026-11-03` → `Nov 3` (`3 Nov` in en-GB). */ +export const fmtDay = (d: string) => date('day', { month: 'short', day: 'numeric' }).format(utc(d)) +/** `2026-11-03`, `2026-11-09` → `Nov 3 – 9`, the month once when both share it. */ +export const fmtDays = (from: string, to: string) => + date('day', { month: 'short', day: 'numeric' }).formatRange(utc(from), utc(to)) +/** `2026-11` → `Nov`. */ +export const monthShort = (k: string) => date('month', { month: 'short' }).format(utc(`${k}-15`)) + +/** The threshold in a policy's name ("Workers requests over 1.35B in 7 days"): stored, so never localized. */ +const POLICY = new Intl.NumberFormat('en', { notation: 'compact', maximumFractionDigits: 3 }) +export const fmtPolicy = (v: number) => POLICY.format(v) + +export const EMAIL = /^[^@\s]+@[^@\s]+\.[^@\s]+$/ diff --git a/src/workers-usage-alert/app/index.html b/src/workers-usage-alert/app/index.html new file mode 100644 index 000000000..9bc30608a --- /dev/null +++ b/src/workers-usage-alert/app/index.html @@ -0,0 +1,12 @@ + + + + + + Workers usage alert + + +
+ + + diff --git a/src/workers-usage-alert/app/usage-alert-app.tsx b/src/workers-usage-alert/app/usage-alert-app.tsx new file mode 100644 index 000000000..25d50226f --- /dev/null +++ b/src/workers-usage-alert/app/usage-alert-app.tsx @@ -0,0 +1,1142 @@ +import { + useCallback, + useEffect, + useId, + useLayoutEffect, + useMemo, + useRef, + useState, + type CSSProperties, + type KeyboardEvent, + type PointerEvent +} from 'react' +import { Button, CloudflareLogo, Collapsible, LayerCard } from '@cloudflare/kumo' +import type { App } from '@modelcontextprotocol/ext-apps' +import { mountMcpApp } from '../../mcp-apps/app-shell/mount' +import { WorkersThresholdPreviewSchema, type WorkersThresholdPreview } from '../contract' +import { + clamp, + deriveModel, + fitTop, + replayEmails, + snapTo, + stepOf, + tickOf, + type Model, + type Week +} from '../../threshold-alert/model' +import { + WORKERS_REQUESTS_BILLING, + WORKERS_REQUESTS_MONITOR, + type ThresholdAlertPreset +} from '../../threshold-alert/presets' +import { + createPolicy, + deletePolicy, + updatePolicy, + type CallTool +} from '../../threshold-alert/create' +import { EMAIL, approx, fmt, fmtDay, fmtDays, fmtPolicy, monthShort, sig, words } from './format' +import './usage-alert.css' + +/** + * Where the form is, with what only that step knows. The click is the user's + * confirmation, so the App creates the policy itself with a tool this server + * already lists (`createPolicy`): `created`. A host that can't call server + * tools gets the alert handed to the chat (`sent`), or else the request to + * send (`review`). + */ +type Phase = + /** `deleted`: Undo just deleted the alert this card made; the field says so until the next edit. */ + | { readonly kind: 'editing'; readonly deleted?: true } + | { readonly kind: 'sending' } + /** `undo`: Undo is deleting it, or Cloudflare refused, with the reason. */ + | { readonly kind: 'created'; readonly undo?: 'deleting' | { readonly failed: string } } + /** + * A refused write, with Cloudflare's reason, or one that got no answer + * (`unconfirmed`): that create may have been made, so the card never says nothing was. + */ + | { readonly kind: 'failed'; readonly reason: string; readonly unconfirmed: boolean } + | { readonly kind: 'sent' } + | { readonly kind: 'review' } +const EDITING: Phase = { kind: 'editing' } +type Tone = '' | 'hit' | 'now' | 'warn' | 'bad' +/** Plain text, or a figure shown bold and direction-isolated. */ +type FactPart = string | { readonly b: string } +type Fact = readonly [Tone, readonly FactPart[]] + +const reduceMotion = () => matchMedia('(prefers-reduced-motion: reduce)').matches +const canHover = () => matchMedia('(hover: hover) and (pointer: fine)').matches +// Drag past an edge to grow or shrink the axis, like a list scrolling when you drag past its end: +// px zone inside each edge, px to full speed, e-folds per second. Settling eases with time constant TAU (s). +const EDGE = 10 +const RAMP = 110 +const GROW = 1.8 +const TAU = 0.055 + +/** Two short facts under the chart, verdict first (BLUF), each sized to fit one line at 320px. */ +function outcome(m: Model, limit: number, preset: ThresholdAlertPreset): [Fact, Fact] { + const { bucket, current, alreadyOver } = preset.copy + const sent = replayEmails(m.days, m.rolling, limit, m.cadence) + const first = sent.find((e) => e.first) + // By month, the replay is Workers analytics by calendar month, not billing's count in its + // period: an estimate, and said as one. + const about = m.cadence.kind === 'month' ? 'About ' : '' + const none = m.cadence.kind === 'month' ? 'No crossings charted' : 'No past emails' + const past: Fact = + m.typical && limit < m.typical + ? ['warn', [`Below a typical ${bucket} (`, { b: approx(m.typical, 2) }, ')']] + : sent.length && first + ? [ + 'hit', + [ + about, + { b: String(sent.length) }, + ` past ${sent.length === 1 ? 'email' : 'emails'}, first `, + { b: fmtDay(first.date) } + ] + ] + : limit >= 2 * m.peak + ? ['', [`${none}; `, { b: `${sig(limit / m.peak)}×` }, ` the busiest ${bucket}`]] + : ['', [`${none}; busiest ${bucket} `, { b: sig(m.peak) }]] + const now: Fact = + m.current >= limit ? ['warn', [alreadyOver]] : ['now', [`${current}: `, { b: sig(m.current) }]] + return [past, now] +} + +function FactLine({ fact, slot }: { fact: Fact; slot: 'past' | 'now' }) { + return ( + +