diff --git a/.changeset/api-key-automatic-mode.md b/.changeset/api-key-automatic-mode.md
new file mode 100644
index 0000000000..c85c7037a3
--- /dev/null
+++ b/.changeset/api-key-automatic-mode.md
@@ -0,0 +1,8 @@
+---
+"@executor-js/mcp-auth": patch
+---
+
+API keys at the plain `/mcp` URL now use `automatic` approval mode, as a new
+sign-in there does: Executor accepts approvals at once and the agent's own
+permission prompt is the check. A URL that names a mode keeps it; add
+`?elicitation_mode=model`, `native` or `browser` to have approvals pause.
diff --git a/.changeset/automatic-approval-mode.md b/.changeset/automatic-approval-mode.md
index b4557de919..d9929c753a 100644
--- a/.changeset/automatic-approval-mode.md
+++ b/.changeset/automatic-approval-mode.md
@@ -10,5 +10,4 @@ agent's own permission prompt for `call` or `execute` is the check. Questions a
running tool asks still reach the agent, as in `model` mode. The sign-in page
now preselects it for the plain `/mcp` URL, on hosted and local; local's
sign-in page now offers the approval choice too. Existing grants keep their
-mode, and personal access tokens still use `model` mode at the plain URL. Use
-`?elicitation_mode=automatic` to choose it with a token.
+mode.
diff --git a/.changeset/execute-entry-skill-once.md b/.changeset/execute-entry-skill-once.md
new file mode 100644
index 0000000000..90ecc56757
--- /dev/null
+++ b/.changeset/execute-entry-skill-once.md
@@ -0,0 +1,9 @@
+---
+"@executor-js/mcp": patch
+---
+
+The `execute` and `skills` descriptions no longer tell agents to read the
+Executor app's entry skill first. The server instructions are that skill, so an
+agent that received them would fetch the same text again; the descriptions now
+say so and name the `skills` call only for clients that do not show server
+instructions.
diff --git a/.changeset/mcp-call-teardown.md b/.changeset/mcp-call-teardown.md
new file mode 100644
index 0000000000..0bbd1a3a22
--- /dev/null
+++ b/.changeset/mcp-call-teardown.md
@@ -0,0 +1,8 @@
+---
+"apps": patch
+---
+
+A completed MCP tool call no longer sends `notifications/cancelled` for itself when its client
+closes, and its result returns without waiting for the server to acknowledge the session's
+`DELETE`. The session still ends after the reply, within the invocation, through the host's
+background runner; a failed or cancelled call ends its session before returning, as before.
diff --git a/.changeset/oauth-declared-pkce-false.md b/.changeset/oauth-declared-pkce-false.md
new file mode 100644
index 0000000000..e7a37db061
--- /dev/null
+++ b/.changeset/oauth-declared-pkce-false.md
@@ -0,0 +1,12 @@
+---
+"apps": patch
+"@executor-js/sdk": patch
+"@executor-js/app-templates": patch
+---
+
+Declared `oauth2()` endpoints accept `pkce: false` for a service whose token endpoint refuses a
+confidential client's `code_verifier`. LinkedIn's web flow answers such a request with 401
+`invalid_client`, so every LinkedIn sign-in failed at the code exchange whatever secret was saved.
+With the declaration, sign-in sends no `code_challenge` and no `code_verifier`. Only a secret
+`tokenEndpointAuthMethod` may declare it; without one the build fails. Every other provider keeps
+PKCE S256.
diff --git a/.changeset/self-host-mcp-clients.md b/.changeset/self-host-mcp-clients.md
new file mode 100644
index 0000000000..5f7b9eb4f9
--- /dev/null
+++ b/.changeset/self-host-mcp-clients.md
@@ -0,0 +1,15 @@
+---
+"@executor-js/hosted-self-host": patch
+---
+
+Self-host no longer refuses new MCP clients after 256 API keys or OAuth grants
+have been used within half an hour. It keeps up to 512 clients
+(`EXECUTOR_MCP_CLIENTS`), and when a new one would pass that it forgets the
+least recently used client that has no request in flight and no program waiting
+for approval. That client's next request gets `404` and it must initialize a
+new session; a client that does not do so on its own needs reconnecting. One member holds at
+most 256 of them (`EXECUTOR_MCP_CLIENTS_PER_USER`), so one member's
+clients cannot push out everyone else's. When every client that could make room
+owns work, a new client gets `503` with `Retry-After: 1`.
+A setting that is not a whole number of at least 1 stops the server with an
+error naming the setting.
diff --git a/.changeset/self-host-runtime-root.md b/.changeset/self-host-runtime-root.md
new file mode 100644
index 0000000000..51afe079be
--- /dev/null
+++ b/.changeset/self-host-runtime-root.md
@@ -0,0 +1,7 @@
+---
+"@executor-js/hosted-self-host": patch
+---
+
+The self-host image's runtime under `/app`, such as `product.mjs`,
+`workerd.capnp` and the workerd binary, now belongs to root and is read-only to
+the user the server runs as. Only the data directories are that user's.
diff --git a/.github/workflows/fork-ci.yml b/.github/workflows/fork-ci.yml
index d4675b2a20..0783a7e0e9 100644
--- a/.github/workflows/fork-ci.yml
+++ b/.github/workflows/fork-ci.yml
@@ -91,14 +91,20 @@ jobs:
# "App dependency registry" suite's only scenario is selected by the private-fetch prefix.
- name: Security scenarios
run: |
- bun run e2e:self-host -- --test-name 'application_type|fetch without a User-Agent names Executor|cannot create an all-apps connection|cannot widen a connection or mint|fails to load fails only its own reads|with private fetch off, a build|App dependency registry|keeps renewing grants that hold a scope|own Google client still signs in gmail.modify'
+ bun run e2e:self-host -- --test-name 'application_type|fetch without a User-Agent names Executor|cannot create an all-apps connection|cannot widen a connection or mint|fails to load fails only its own reads|with private fetch off, a build|keeps renewing grants that hold a scope|own Google client still signs in gmail.modify'
# A parked program outlives the request that started it: the entry must hold through idle
# deadlines until its batch finishes, and a crash must report the program lost, not missing.
- name: Parked MCP program scenarios
run: |
bun run e2e:self-host --test-name 'Self-host MCP (resumes all three|reports a crashed parked)|PAT MCP approvals bind|PAT MCP model-mode resume' --workers 1
- name: Person-only approval scenarios
- run: bun run e2e:self-host --test-name 'a tool that requires a person refuses the agent|owner of an automatic-mode grant approves' --workers 1
+ run: bun run e2e:self-host --test-name 'a tool that requires a person refuses the agent|owner of an automatic-mode grant approves|A plain-URL API key in automatic mode' --workers 1
+ - name: MCP Skills extension and client bounds
+ run: |
+ bun run e2e:self-host --test-name 'Skills extension|Self-host MCP (admits|never forgets) a' --workers 1
+ bun run e2e:local --test-name 'Skills extension' --workers 1
+ - name: Member managed keys
+ run: bun run e2e:self-host --test-name "Executor app's managed key is recreated after an admin becomes a member|Executor installs each user" --workers 1
# A failed default-app install names its tagged cause in the log, never the registry's URL.
- name: Provisioning failure scenarios
run: |
diff --git a/.oxlintrc.jsonc b/.oxlintrc.jsonc
index 4f237ed955..c98bcfb390 100644
--- a/.oxlintrc.jsonc
+++ b/.oxlintrc.jsonc
@@ -21,6 +21,28 @@
],
},
"overrides": [
+ {
+ // Snapshots are assertions a person reads (e2e/README.md, "Snapshots"): small enough to read,
+ // never built from interpolated values, and inline beside the code, never in a .snap file.
+ // The plugin's other default rules that fire here do not know `it.effect` from
+ // @effect/vitest is a test, so they read every scenario's expect as outside one.
+ "files": ["e2e/**"],
+ "plugins": ["vitest"],
+ "rules": {
+ "vitest/no-large-snapshots": ["error", { "maxSize": 30, "inlineMaxSize": 30 }],
+ "vitest/no-interpolation-in-snapshots": "error",
+ "vitest/no-restricted-matchers": [
+ "error",
+ {
+ "toMatchSnapshot": "Use toMatchInlineSnapshot, beside the code that produced the value.",
+ "toThrowErrorMatchingSnapshot": "Use toThrowErrorMatchingInlineSnapshot.",
+ },
+ ],
+ "vitest/no-standalone-expect": "off",
+ "vitest/valid-expect": "off",
+ "vitest/require-awaited-expect-poll": "off",
+ },
+ },
{
// The live host protocol reaches these patterns, and its record is compared with every
// released protocol's, flags included; see notes/apps-publishing.md.
diff --git a/AGENTS.md b/AGENTS.md
index 86975d9c65..78d7fa80a7 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -141,6 +141,11 @@ CI runs it in the `collector-native` job when the crate, its build script
on Ubuntu 22.04. A run on main saves it to the cache under its identity; a pull request's run
restores main's entry when the identity matches and otherwise builds from scratch, saving nothing.
+A snapshot (`toMatchInlineSnapshot`) is an assertion. Use one when the whole text is the
+behaviour; read every line of a changed one as a changed assertion. No run writes one unless
+asked: record it locally with `--update-snapshots --test-name '
'`, which CI refuses
+([Snapshots](e2e/README.md#snapshots)).
+
Tests are not sacred. Delete a scenario when it no longer proves behavior a user
or public API caller depends on, or when other scenarios already cover it. Say
what it covered and why that coverage is not needed. Deletion is not a fix for
@@ -171,6 +176,16 @@ private and out of tool output.
Run `bun run format` before committing. `bun run check` runs the format check,
`oxlint`, and the typecheck; CI-style verification should use it.
+Before every push to a pull request, run `bun run pr:check` (`--description ` before the
+pull request is open): it runs some of the cheap gates CI applies, with CI's own code, in about 25
+seconds: `bun run check`, the `select` job's check of this branch's `e2e` block and of each other
+open stack layer's (each on a checkout of its local head, so a spec file it names must exist in its
+own tree, and a `skip` with no open layer above fails), bun.lock, the apps version bump, the host
+protocols and the Release-note lines of the squashed commit. It does not check, and says so at the
+end of every run: a `skip` layer's check that the layer above's CI run was computed on it, `site`
+(the build, links and Worker size budgets), `apps-package`, `tooling`, the native and collector
+jobs, any E2E scenario or release lane, and line coverage. It needs the network (origin, and `gh`
+signed in, with gh-stack for a stack) and fails with a message saying so when it cannot reach them.
`packages/apps/protocols/*.json` are generated records of the app host
protocols. Never read, grep or edit them; run `bun run apps:protocols` and read
@@ -229,6 +244,33 @@ TypeScript 7 has no JavaScript compiler API. The `packages/apps` build scripts
and `e2e/check-boundary.ts` import TypeScript 5.9 as `typescript-5` for it;
do not use that package to typecheck.
+## Release notes
+
+A public release lists only the changes whose squashed commit has a line
+`Release-note: `; pull request titles are never published. For a change a
+user of the CLI, the desktop app or the self-host image would notice, put one
+such line, one plain sentence for users, at the start of a line of its own (not
+indented or quoted) in the body of a commit message on the pull request's
+branch: the squashed commit's body is its commits' messages, not the pull
+request's description. A message that holds `<`, `[`, `$`, ` ``` ` or `~~~`
+anywhere has no notes, so keep HTML, links, math and code blocks out of it. The
+one exception is a line that is only a co-author trailer,
+`Co-authored-by: Name ` (a bot's name may end `[bot]`), with nothing
+after it, anywhere in the message.
+Every such line is listed. Start the note with its kind, `Feature: `, `Improvement: ` or `Fix: `
+(the word, a colon and exactly one space; a tab or two spaces leave the note refused), as in
+`Release-note: Feature: Teams can be renamed.`: Cloud's What's new leads only with a feature
+or an improvement, the kind is cut off before the rules below are applied and is never published,
+and a note without one is a fix. Mark a note for what it is, and never reword a fix to sound like a
+feature. A note, after its kind, is plain prose of at most 300 characters:
+ASCII letters, digits, spaces and `.,;:!?'"()-`, starting with a letter or
+digit, with no `@`, `#`, `/`, URL, host name, code, Markdown, `GH-123` or whole
+word of 7 or more hex characters or digits; any other is left out whole. Name no
+customer, organization or reporter, use no internal names, and say nothing
+about a security problem not yet fixed and disclosed. Write none for tests, CI,
+tooling or internal refactors. The rules are in
+[Release notes](RELEASING.md#release-notes).
+
## CI
`.github/workflows/ci.yml` runs on pull requests, pushes to `main` and manual
@@ -237,15 +279,30 @@ A PR run on an earlier head is cancelled by the new head's run; two runs on the
same head both run, one after the other. Each push to `main` has its own
concurrency group, so every push finishes a run and gives each merge a baseline,
even when merges come in a burst. A stack that lands in one push gets one run, at
-its top commit. Overlapping `main` runs share no deployed stage, database or
+its top commit; `gh stack merge` lands it that way. Overlapping `main` runs share no deployed stage, database or
secret. They do read the npm registry and create hosted emulators.dev instances,
each named with a random UUID, so they do not interfere. The jobs live in `.github/workflows/checks.yml`,
a `workflow_call` workflow, so another repository can call the same jobs.
### Choosing a PR's E2E scenarios
-A pull request runs only the E2E scenarios it selects. Pushes to `main` run the
-full suite. The selection reaches the jobs as title patterns; no value it puts in
+A draft pull request runs only the E2E scenarios it selects. Once it is ready for
+review, it runs the full suite, unless everything it changes since `main` is in the
+narrowing table in [`e2e/narrowing.ts`](e2e/narrowing.ts) (notes, the repository's
+documents and skills, spec files); then it keeps its selection. Marking it ready starts
+that run, and the merge waits for it, so mark a pull request ready when you push the
+head you mean to merge, not after its draft run passes. Whether it is a draft is read
+live when `select` runs, so re-running a draft's run on a ready pull request runs it as
+ready. A draft's `e2e` job is named `e2e (draft)` and never reports the required
+`checks / e2e`, so a draft's green cannot stand for the merge. A stack's top layer is
+compared with `main`, so a tests layer above a code layer runs the full suite, and every
+spec file any layer changed runs on it. A ready pull request
+also runs its new local and self-host scenarios (those of the spec files the stack changed
+that `main`'s `e2e/test-plan.ts` does not name) four more times, each on its own runner and
+the last with half the cores busy; any failure fails it, so a new scenario that passes only
+sometimes never reaches `main`. Fix the race; never add a retry or a longer deadline. At
+most 60 repeat, the first by title, and the run summary says when there were more. Pushes to `main`
+run the full suite. The selection reaches the jobs as title patterns; no value it puts in
an environment variable or argument may approach Linux's 128 KiB limit, and a case in
`e2e/tests/ci-selection.spec.ts` fails at a quarter of it, naming the value. Make room by
splitting (more shards) or by passing it through a file: scenario titles are not a budget,
@@ -285,7 +342,9 @@ them; run it before merging. A scenario new to the deployed suite (one main's `e
does not name) first runs on a deployed stage after merge even when managed local Cloud runs it
here, so the `select` job fails until the description has a line `Verified on a deployed stage:`
saying what ran and its result, for example the `bun run e2e:deployed --database planetscale
---test-name '…'` command the failure prints. Write `none` for a change no scenario exercises, such as documentation. Write each name as it appears in
+--test-name '…'` command the failure prints. A scenario is known by its exact title, so renaming one, even
+cosmetically and only in `e2e/test-plan.ts`, makes it new and needs that line; moving a scenario to
+another file under the same title does not. Write `none` for a change no scenario exercises, such as documentation. Write each name as it appears in
`e2e/tests/`, optionally prefixed with `e2e/tests/`. The `select` job fails when the
description has no block, a name is not a spec file there, or a named file is one these
jobs never run: the release, desktop, billing and PGlite suites have their own
@@ -321,15 +380,30 @@ open PR targets the layer's branch, so a lone PR or the top layer cannot skip. T
`select` job waits up to 3 minutes for that PR to open, so open the stack's layers together
(`gh stack submit` does). It then checks that that PR's latest run on its head was built on
this layer's head and compared Worker sizes with the base the stack ends on
-([`e2e/ci-skip-check.ts`](e2e/ci-skip-check.ts)). For now it only logs what it would
-decide (`skip-check` in the select log and summary); once enforced, it fails and says which command
-runs the layer above again. Never write `skip` on a long-lived branch's PR into `main`: it must be
-compared with `main` itself.
+([`e2e/ci-skip-check.ts`](e2e/ci-skip-check.ts)). On a layer that is ready for review the
+check is enforced and stricter, because a ready layer can be merged alone: it passes only when a
+ready layer above has a run on its head that contains this layer's head and finished green, its
+`checks / check` and `checks / e2e` passed, having run the full suite (or the narrowing table's
+selection, which is what that layer merges on), or when the ready skip layer above passed this same
+check. Its `select` waits up to 50 minutes for that run, so mark the whole stack ready together,
+top included; a draft above never passes it. On a draft it only logs what it would decide
+(`skip-check` in the select log and summary): a draft cannot be merged. Never write `skip` on a
+long-lived branch's PR into `main`: it must be compared with `main` itself.
After changing a lower layer, rebase the layers above it so the top runs again.
-Merge the stack only when the top layer passes, bottom first, without pausing between
-layers: each merge deploys production.
-
-Choose from the actual callers of the changed code. Search `e2e/tests/` for the
+Land a stack only when the top layer passes, and only with `gh stack merge --yes
+--squash`, never layer by layer. It merges every layer in one operation and one push to
+`main`, so `main` runs CI, Deploy and the public export once, on the top commit, with no
+commit in between that has a code layer without its tests (checked with #5035 and #5036 on
+18 Nov 2026, `notes/ci.md`). A lower layer merged by itself lands untested by the run that
+covered it; `main`'s CI then warns "Stack layer landed alone".
+`gh stack merge` merges only the GitHub stack its argument is in, into that stack's base. First
+check that every layer is in one stack based on `main`: `gh api
+repos/UsefulSoftwareCo/executor-next/pulls/ --jq .stack` shows its number, size and base.
+If the layers sit in two stacks, run `gh stack unstack ` and then `gh stack link `, which changes no branch or base (done for #4989 to #5002 on 18 Nov 2026).
+
+The draft's selection is for fast answers while you work; the ready run is the one that
+cannot miss. Choose from the actual callers of the changed code. Search `e2e/tests/` for the
routes, tools and UI the change touches, and include every file that exercises them
on any target. A tests PR on top of a stack gets its own new or changed spec files
for free; add the existing files that cover the code layers below it. `main` runs the
@@ -388,7 +462,15 @@ REST or GraphQL API to get around a refusal, and no change to the ruleset. Only
Rhys turns it off, in an emergency. See [CI configuration](notes/ci.md#the-main-ruleset).
A failure on `main` is a regression or a flake that a PR selection missed. Fixing
-it takes priority over new work that touches the same area.
+it takes priority over new work that touches the same area. While CI on `main` is red, the
+paced Windows check is red, or a beta release is held for more than six hours (or by five
+failed attempts in a day), one open issue labelled `main-health` says so: the failed jobs and
+scenarios, the commits since the last green run, and why the beta is held. Main health
+(`.github/workflows/main-health.yml`) is its only writer; each run rewrites it whole from
+those three facts, closes it once each is known to be fine, and while one cannot be read
+(no run yet, no recent Beta decision) opens or closes nothing. It touches only issues
+github-actions opened with its marker; an older `main-red` issue is closed by hand. Read it
+before investigating.
A PR run takes at most about seven minutes. Wait for it once; do not poll post-merge
suites before handing off. When a job fails in a scenario the change does not
diff --git a/RELEASING.md b/RELEASING.md
index 71fae25b71..88e3bc4331 100644
--- a/RELEASING.md
+++ b/RELEASING.md
@@ -130,7 +130,8 @@ not.
## Publish beta
The **Beta** workflow (`.github/workflows/beta.yml`) publishes betas. It checks
-on every push to `main` and on a schedule at minutes 8 and 38, and
+on every push to `main`, when CI passes on a push to `main`, and on a schedule
+at minutes 8 and 38, and
`scripts/releases/beta-due.ts` decides from npm, the release runs and main's
history. Before deciding, each tick runs `scripts/releases/lock-repair.sh`, which
pushes `Refresh bun.lock [skip ci]` when main's bun.lock is not what
@@ -159,6 +160,18 @@ run. A push and a scheduled tick decide alike:
`gh workflow run release-artifacts.yml --ref main -f channel=build`. A run still
pacing or building holds nothing, since the publishing run tests every platform
on the commit it publishes and publishes only when all pass.
+- **Release check** also starts the installed CLI suite on Windows, a narrowed
+ build (`jobs=cli`, `targets=win32-x64`, about USD 1.40 and 13 minutes), on a
+ decision of its own (`e2e/release-check.ts`, `windows`): it compares main with
+ the last commit a Windows check tested, or will, never with the Linux check's, so
+ a commit the Linux check already covers still gets its Windows run. It starts at
+ most once every four hours; a decision inside that wait skips it and keeps the
+ comparison where it was, so the first push or hourly backstop after the four
+ hours starts it for every commit since. A decision that fails starts it. It runs
+ from the `ci/windows-check` branch, which the step sets to main's commit, so it
+ never shares a concurrency group with a publication from `main`, and Beta
+ neither waits for it nor counts it. A red one shows a Windows-only failure hours
+ before a publishing run would; the red-main issue reports it.
- A build run can be narrowed, to prove one job on one platform without paying
for the whole matrix (a full build costs about USD 7; the installed CLI suite
on Windows alone about USD 1.40):
@@ -178,13 +191,33 @@ run. A push and a scheduled tick decide alike:
it commits `Release 2.0.0-beta.N+1` to `main` and dispatches **Executor
releases** with channel **beta**.
- When npm lacks the committed version, it publishes it again instead of
- skipping it. An attempt that failed in its build or test jobs is dispatched
- again on the next tick. After two failures in a row, the next attempt waits
- six hours after the last one and for a new commit on `main`, or a day, so a
- broken `main` costs at most five publishing runs a day. An attempt that failed
- in its publish job has its failed jobs re-run once from its own artifacts;
- after that, inspect it as below. Each skipped retry leaves a warning on the
- Beta run, and the failed release runs stay red.
+ skipping it. At most five publishing attempts a day fail: once five failed in
+ the last 24 hours, counting each re-run of a run as an attempt of its own, no
+ tick starts or re-runs another, a manual dispatch of Beta
+ included, until one of them is a day old (dispatch **Executor releases** with
+ channel **beta** by hand to publish sooner, after inspecting them). It finds
+ them by when they ran: the release runs of the last month (GitHub re-runs a
+ run only within 30 days), and the earlier attempts of those re-run in the last
+ day, stopping once five are known. When ten requests cannot tell, the tick
+ holds. Within that
+ bound, an attempt that failed before publishing is dispatched again on the next
+ tick. After two failures in a row, the next attempt waits six hours after the
+ last one and for a new commit on `main`, or a day, unless CI has passed on a
+ `main` commit after the last attempt's: a failure that a merge fixed is retried
+ as soon as `main` is green again. Beta also ticks when CI finishes green on a
+ push to `main`, so that retry starts within minutes.
+- An attempt that failed in a step that publishes anything is never retried that
+ way: it has its failed jobs re-run once from its own artifacts; after that,
+ inspect it as below. It is judged by the step, not the job's name: every step
+ of `release-artifacts.yml` and `bun-runtime.yml` declares in its `env` whether
+ it publishes, `PUBLISHES: "yes"` (every step of the `publish` job, the docker
+ job's architecture push, the dispatch of Deploy and the Bun runtime's release)
+ or `PUBLISHES: "no"`, and `e2e/tests/beta-due.spec.ts` fails a step that
+ declares neither, so give every new step one. A run's job is found by the job id
+ at the start of its name, which GitHub cuts short for a long matrix job; a job or
+ step that cannot be found counts as publishing
+ (`scripts/releases/publishing-steps.ts`). Each skipped retry leaves a warning
+ on the Beta run, and the failed release runs stay red.
- Only publishing runs count as attempts. A dispatch with channel **build**
does not publish, so it neither adds to a failure streak nor counts as a
success, though it still makes the tick wait while it runs.
@@ -327,5 +360,131 @@ cannot race or replace a newer main export. Both use
A main export also merges the public pull requests that main ports, named by
`Public-PR` lines in its commit messages; a release export merges none, because
no pull request targets `v2-releases`.
-Public release notes come from the product README, not private PR titles or
-GitHub's generated changelog.
+
+## Release notes
+
+Each public release's notes list what changed since the release before it, then
+the install instructions at the top of
+[the release scripts' README](scripts/releases/README.md). The metadata job of a
+publishing run writes them with `scripts/releases/release-notes.ts`, before any
+build, and the publish job creates the release with them. They are not GitHub's
+generated changelog, which would list private pull requests and their titles.
+
+The notes list only changes whose squashed commit on main has a line
+`Release-note: `, and that text is all they say about the change. Pull
+request titles stay private: the notes never print one, nor does any warning
+the script writes. `Release-note: none` is the same as no line.
+
+A line counts only when `Release-note:` starts a line of the message's body:
+not indented, not quoted with `>` (as a revert may quote the message it
+reverts) and not inline. A commit message that holds `<`, `[`, `$`, ` ``` ` or
+`~~~` anywhere, title included, has no notes at all, because HTML, a link
+definition, math or a code fence can hide a line from whoever reads the message
+rendered; the job log warns with the commit and the character. The one
+exception is a line that is a co-author trailer and nothing else, anywhere in
+the message, since a squash joins its commits' messages and a port's own
+trailers sit in the middle: `Co-authored-by: ` (the key in any
+case), then only spaces, where the name holds no `<`, `>`, `[`, `]`, `$`,
+backtick or control character but may end `[bot]`, and the address, the line's
+only `<...>`, is `` with a local part of letters, digits and
+`._+-` (a bot's ending `[bot]`) and a host of letters, digits, dots and hyphens.
+Any other `<` or `[`, even on a line that only starts like a trailer, still
+drops the notes. So write an
+example note in words, not in a code block or comment. Any other line that
+holds `Release-note:` is not counted, and the job log warns with its commit and
+line number. When a change has several lines that count, each is listed, once,
+in the order written; `none` among them is skipped. A line cannot be withdrawn
+by a later one, so reword or drop the commit before merging instead.
+
+A note may start with the kind of change it is: `Feature: `, `Improvement: `
+or `Fix: ` (the word in any case, then a colon and exactly one space, not a
+tab or two spaces, which leave the note refused), as in
+`Release-note: Improvement: Search answers faster.` The kind is not part of the
+note: it is cut off first, and the rules below apply to the text after it,
+which must itself start with a letter or a digit and is counted against the
+300 characters without the kind. It is never published, in the release, the
+desktop feed, Cloud's notes or anywhere else. A note without one is a fix. A
+kind with no note after it, or with `none`, is refused. Cloud's What's new
+leads with the newest feature or improvement of its notes, never a fix; with
+neither it shows a plain line, and its panel lists every note, fixes included,
+in order. So write `Feature: ` for something new and `Improvement: ` for
+something that already worked and now works better, and `Fix: ` or nothing
+for something that was broken. Mark a note for what it is, and never reword a
+fix to sound like a feature. `--check` prints the kind it counted for each
+line. `scripts/releases/note-kinds.ts` gives one note merged before kinds
+could be written its kind by hand, since a commit message on main cannot change;
+it is a stopgap, so never add to it, and delete it once that commit leaves
+Cloud's 30 days (the file says when).
+
+A note is published only when it is plain prose, and then exactly as written.
+It may hold only ASCII letters, digits, spaces and these punctuation marks:
+`.` `,` `;` `:` `!` `?` `'` `"` `(` `)` `-`. It must also:
+
+- start with a letter or a digit, and not like a numbered list (`1.`, `1)`);
+- have a colon only before a space or at its end, so no `:emoji:` or `scheme:`;
+- have a dot only at the end of a sentence or between digits (`1.5`), never
+ inside a word as in a host name (`example.com`, `www.x`);
+- join no letters to digits with a hyphen (`GH-123`, `ABC-123`);
+- hold no whole word of 7 or more hex characters or digits, which GitHub links
+ when it names a commit (so `deadbeef`, `defaced` and `1234567` are refused,
+ and a number is written `1,000,000`); a word that only holds such a run, such
+ as `feedback`, is fine, because GitHub links a commit only as a whole word;
+- name no `GHSA-` advisory and no private repository;
+- be at most 300 characters.
+
+So a note holds no `@`, `#`, `/`, `<`, `>`, `[`, `]`, `&`, `*`, `_`, `~`, `|`,
+backslash, backtick, typographic quote or dash, accented or non-Latin letter,
+emoji or invisible character: no mention, issue or pull request reference,
+`owner/repo`, URL, email address, code, HTML or Markdown. Write a command or a
+name in words. Any other note is left out whole, never rewritten or cut, and
+the job log warns with its commit, its line number and the first rule it
+breaks. All listed lines together hold at most 10,000 characters: once a
+change's lines would pass that, it and every later change are left out and
+counted, with a warning. Neither stops the release, because a commit message on
+main cannot be changed.
+
+`e2e/tests/release-notes-render.spec.ts` (CI's tooling job, with the job's
+token) sends a corpus of accepted notes, as the script writes them, to GitHub's
+Markdown API and checks that each comes back as its text alone, inside nothing
+but the notes' headings, list and paragraph. It also renders the refused corpus
+and checks that the forms review found active still render as links, mentions,
+an emoji image or markup. The corpora are in `e2e/release-notes-repositories.ts`.
+
+A change with a line is listed when it changed a package the CLI, the desktop
+app or the self-host image is built from, other than its scripts, tests,
+fixtures and Markdown, under All installs, CLI and desktop, or Self-host by the
+packages it changed. A line on a change to nothing a release ships, such as
+Cloud-only code, CI or tooling, is not listed, and the job log warns with the
+commit. A port of a public pull request with a line links it and thanks its
+contributors by GitHub handle. That credit is the one place the notes hold a
+link and a mention, and it is safe because it is built only from a `Public-PR:`
+line that names `UsefulSoftwareCo/executor#` exactly and from handles
+in `users.noreply.github.com` co-author addresses that match GitHub's handle
+rule, never from free text, so it can only point at a public pull request and
+the people who wrote it. Anything else gets no credit and a warning in the job
+log, and the note is listed as if the change were no port. A revert and the change it reverts cancel when
+both are in the release, newest first, so a reverted revert cancels nothing and
+the change it restored is listed. Every change not listed is counted in one
+line. A release with no line at all says "No release notes were written for
+this release." and still publishes. The notes link nothing else: no compare
+view, commit or private pull request.
+
+Warnings go to the publishing run's job log and its annotations in this
+private repository, and name commits only, never a title or a note's text. The
+notes themselves reach the public repository only as the release's body: the
+`release-notes` artifact is downloaded outside `.local/publish`, so it is never
+uploaded as a release asset.
+
+Write the line for a change a user of the CLI, the desktop app or the self-host
+image would notice: one plain sentence saying what changed for them, in the
+words above. Name no
+customer, organization or reporter, use no internal names, and say nothing about
+a security problem not yet fixed and disclosed. Put it in the body of a commit
+message on the pull request's branch, not only in the pull request's
+description: this repository squashes with the commits' messages as the body
+(`squash_merge_commit_message: COMMIT_MESSAGES`), so the description never
+reaches main.
+
+To see a release's notes without publishing, run
+`node scripts/releases/release-notes.ts --version --to `
+from a checkout of main.
diff --git a/apps/cli/CHANGELOG.md b/apps/cli/CHANGELOG.md
index 7783f070a5..b856c5a4b8 100644
--- a/apps/cli/CHANGELOG.md
+++ b/apps/cli/CHANGELOG.md
@@ -1,5 +1,53 @@
# executor
+## 2.0.0-beta.71
+
+Beta of the Executor local runtime, CLI, desktop, and self-host Docker image.
+
+## 2.0.0-beta.70
+
+Beta of the Executor local runtime, CLI, desktop, and self-host Docker image.
+
+## 2.0.0-beta.69
+
+Beta of the Executor local runtime, CLI, desktop, and self-host Docker image.
+
+## 2.0.0-beta.68
+
+Beta of the Executor local runtime, CLI, desktop, and self-host Docker image.
+
+## 2.0.0-beta.67
+
+Beta of the Executor local runtime, CLI, desktop, and self-host Docker image.
+
+## 2.0.0-beta.66
+
+Beta of the Executor local runtime, CLI, desktop, and self-host Docker image.
+
+## 2.0.0-beta.65
+
+Beta of the Executor local runtime, CLI, desktop, and self-host Docker image.
+
+## 2.0.0-beta.64
+
+Beta of the Executor local runtime, CLI, desktop, and self-host Docker image.
+
+## 2.0.0-beta.63
+
+Beta of the Executor local runtime, CLI, desktop, and self-host Docker image.
+
+## 2.0.0-beta.62
+
+Beta of the Executor local runtime, CLI, desktop, and self-host Docker image.
+
+## 2.0.0-beta.61
+
+Beta of the Executor local runtime, CLI, desktop, and self-host Docker image.
+
+## 2.0.0-beta.60
+
+Beta of the Executor local runtime, CLI, desktop, and self-host Docker image.
+
## 2.0.0-beta.59
Beta of the Executor local runtime, CLI, desktop, and self-host Docker image.
diff --git a/apps/cli/package.json b/apps/cli/package.json
index f5ad0bd42e..0dc59cb4c1 100644
--- a/apps/cli/package.json
+++ b/apps/cli/package.json
@@ -1,6 +1,6 @@
{
"name": "executor",
- "version": "2.0.0-beta.59",
+ "version": "2.0.0-beta.71",
"private": true,
"description": "Run Executor locally and connect your agents to your apps.",
"homepage": "https://executor.sh",
diff --git a/apps/docs/content/api-keys.md b/apps/docs/content/api-keys.md
index 3a4b59d132..238fa6ae1e 100644
--- a/apps/docs/content/api-keys.md
+++ b/apps/docs/content/api-keys.md
@@ -85,10 +85,16 @@ extra configuration. A full-account token on `/mcp` must say which organization
to use with an `X-Executor-Organization` header. A token limited to one
organization is rejected on any other organization's URL.
-The same token works with model, native, browser, and automatic approval
-delivery. The plain MCP URL uses model mode; add `?elicitation_mode=native`,
-`?elicitation_mode=browser`, or `?elicitation_mode=automatic` when needed. Tool approval rules still apply. Browser approvals require the token
-owner to sign in. Revocation or expiry stops new MCP calls and continuations,
+The same token works with automatic, model, native, and browser approval
+delivery. The plain MCP URL uses automatic mode: Executor accepts approvals at
+once, and your agent's own permission prompt for `call` or `execute` is the
+check. A question a running tool asks still reaches the agent. To have
+approvals pause instead, add `?elicitation_mode=model` (the agent asks you and
+resumes), `?elicitation_mode=native` (your client's own prompt) or
+`?elicitation_mode=browser` (a signed-in page) to the URL. A token used by a
+script or an unattended agent runs approval-gated tools without asking at the
+plain URL, so give it one of these modes if a person should confirm them.
+Browser approvals require the token owner to sign in. Revocation or expiry stops new MCP calls and continuations,
including on already-connected clients.
PATs do not require an OAuth sign-in flow. The existing [browser OAuth flow](/mcp-clients)
diff --git a/apps/docs/content/mcp.md b/apps/docs/content/mcp.md
index e1222a1a20..1a1e2b80ca 100644
--- a/apps/docs/content/mcp.md
+++ b/apps/docs/content/mcp.md
@@ -193,7 +193,7 @@ which the grant then keeps. The sign-in page preselects `automatic` for the plai
| Mode | URL | Where you answer |
| ----------- | --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `automatic` | `/mcp?elicitation_mode=automatic` | Nowhere. Executor approves tool calls at once; your agent's own permission prompt for `call` or `execute` is the check. A question a running tool asks still reaches the agent, as in `model` mode. |
-| `model` | `/mcp` | The agent shows you the request and calls `resume` with your answer. |
+| `model` | `/mcp?elicitation_mode=model` | The agent shows you the request and calls `resume` with your answer. |
| `native` | `/mcp?elicitation_mode=native` | Your MCP client's own prompt. The `call` or `execute` request stays open and continues. There is no `resume`. `call` approvals are the client's confirmation of the call itself. |
| `browser` | `/mcp?elicitation_mode=browser` | A signed-in page in your browser. The result carries an `approvalUrl`; the agent calls `resume({ requestId })` to collect your answer. |
@@ -202,7 +202,8 @@ one to use when you do not want the agent to be the one holding the question.
The mode is part of the grant, not the URL. Changing the query string after
signing in does not change the mode. A personal access token has no grant, so it
-takes its mode from the URL on each request: `model` at the plain `/mcp` URL.
+takes its mode from the URL on each request: `automatic` at the plain `/mcp` URL,
+and the named mode with `elicitation_mode`.
## From a shell
diff --git a/apps/docs/content/run/self-host.mdx b/apps/docs/content/run/self-host.mdx
index 6d8a7116c7..b09c5008dd 100644
--- a/apps/docs/content/run/self-host.mdx
+++ b/apps/docs/content/run/self-host.mdx
@@ -30,6 +30,10 @@ These settings override the defaults:
| `EXECUTOR_TRUSTED_PROXIES` | no | Comma-separated addresses of your reverse proxies, so rate limits count each client behind them. List only proxies. See below. |
| `EXECUTOR_APP_WORKERS` | no | Most app and data Workers kept loaded at once. The default is `64`. See below. |
| `EXECUTOR_APP_WORKER_IDLE_SECONDS` | no | Unload an app or data Worker not called for this long; `0` keeps idle Workers loaded up to the limit. The default is `300`. See below. |
+| `EXECUTOR_MCP_CLIENTS` | no | Most MCP clients the server keeps state for at once; each API key or OAuth grant in use is one. The default is `512`. See [Connect an agent](#connect-an-agent). |
+| `EXECUTOR_MCP_CLIENTS_PER_USER` | no | Most of those one member may hold. The default is `256`. |
+| `EXECUTOR_HOST_STALL_SECONDS` | no | Busy seconds of the main thread with no answer before the server counts as stalled, from `0`, which turns the check off, to `3600`. The default is `60`. See [When the server stops answering](#when-the-server-stops-answering). |
+| `EXECUTOR_HOST_STALL_RESTART` | no | `true` restarts a stalled server instead of only logging it. Off by default. See [When the server stops answering](#when-the-server-stops-answering). |
| `EXECUTOR_OAUTH_CLIENT_METADATA_URL` | no | Identify Executor to OAuth services by a client metadata document instead of registering a client. Off by default. See below. |
| `EXECUTOR_CATALOG_URL` | no | `index.json` of the official app feed that onboarding and **Add app** list. The default is `https://catalog.executor.sh/index.json`; `off` lists only the built-in Executor app, for an instance without outbound internet access. |
| `EXECUTOR_REGISTRY_URL` | no | Origin of the public app registry. The default is `https://api.executor.sh`. |
@@ -40,6 +44,7 @@ These settings override the defaults:
| `EXECUTOR_TOOL_LISTING_LOAD_SECONDS` | no | Stop evaluating an app's tool list after this long when no request is waiting for it; capped at the maximum age. The default is `45`. |
| `EXECUTOR_EVALUATION_MEMORY_MB` | no | Memory for kept tool lists and app declarations. The default is `256`. |
| `EXECUTOR_NPM_REGISTRY` | no | npm registry that app builds install packages from. The default is `https://registry.npmjs.org`. |
+| `EXECUTOR_NO_UPDATE_CHECK` | no | Set to `1` to turn off the daily check for a newer release. See [Updates](#updates). |
| `DO_NOT_TRACK` or `EXECUTOR_DISABLE_ANALYTICS` | no | Set to `1` to turn off anonymous usage analytics and feedback. See [usage analytics](/run/usage-analytics). |
| `SSO_DISCOVERY_URL` | no | OIDC discovery document. Leave it empty to keep SSO off. |
| `SSO_CLIENT_ID`, `SSO_CLIENT_SECRET` | no | Credentials for that identity provider. |
@@ -214,11 +219,53 @@ still fail now and then; only three failures in a row count. Give your own probe
later, or 60 to 90 seconds once its connections are refused, plus the pod's termination grace
period.
+ On a very slow disk the first start, which creates the database, can outlast that: with the disk
+ limited to 5 writes a second it took 204 seconds. On storage that slow, raise the startup probe's
+ `failureThreshold`, for example to 36 for about six minutes.
+
- **Railway** checks `/health` only while a deployment starts, to decide when to send it traffic,
and does not probe a running service. Set the path to `/health` and the timeout to 120 seconds.
- **Docker Compose or another supervisor** with its own check: allow 30 seconds a probe and three
failures, for example `timeout: 30s`, `interval: 30s` and `retries: 3`.
+## When the server stops answering
+
+Everything the server does runs on one thread, so app code that never returns, or any other fault
+that holds that thread, stops the whole instance from answering. The image's health check only
+marks such a container unhealthy; Docker does not restart an unhealthy container.
+
+Once the server is ready, the image's host checks every second whether the server answered and how
+its main thread spent that second. It decides the server has stalled when, since its last answer,
+the thread was busy in `EXECUTOR_HOST_STALL_SECONDS` of those seconds (60 by default), or sleeping or
+stopped in five times as many. A busy second is one in which the thread used at least half a
+CPU-second, or proportionally less when the container may use less than one CPU: a quarter of a
+CPU-second at half a CPU. Seconds the thread spends waiting on disk count toward neither, so a slow
+disk does not trip it; nor does a paused container or a sleeping host, since the check counts only
+the seconds it was itself running. `0` turns the check off; the most it accepts is `3600`.
+
+By default the check only logs. Its line starts with `Executor stopped responding:` and gives the
+rule, the counts, the CPU the thread used, the thread states it saw and what it would have done; if
+the server answers again, a line starting with `Executor answered again` follows. Set
+`EXECUTOR_HOST_STALL_RESTART=true` to have it act instead: the host stops the server and exits with
+an error, and the container's restart policy starts it again, which took a few seconds in our tests.
+Restart is off by default. It needs a restart policy, or the container stays stopped, and a restart
+ends every open session, call in progress and paused approval; stored data is kept.
+
+The check cannot tell a long stretch of real work from a server that will never answer: in both, the
+thread stays busy without answering. So before turning restart on, run with the default, which only
+logs, through a period of normal use and watch for the `Executor stopped responding:` line. If
+`Executor answered again` follows it, the server answered after the reported stall. Long-running
+work can cause this too; restarting may interrupt it again if it is retried. If normal work needs
+longer, raise `EXECUTOR_HOST_STALL_SECONDS` or leave restart off. If no recovery line appears while
+the check is still running, it has not observed another answer. If the server remains unresponsive,
+restart it to try to restore service. In two earlier loaded test runs, the check reached the default
+limit; neither retained log recorded an answer again before the test ended.
+
+Use `--restart unless-stopped` or `always` rather than `--restart on-failure`. `on-failure` restarts
+only a container that exits with an error, and the server can exit cleanly without Docker asking it
+to stop, for example when something else in the container sends its runtime a stop signal; the
+container then stays stopped.
+
## Deploy on Railway
@@ -311,6 +358,34 @@ the same key source across upgrades. If a saved key is missing or invalid for
an existing database, startup fails instead of creating a replacement. Restore
the original key. Changing the encryption key makes existing credentials unreadable.
+### Updates
+
+The server checks once a day whether a newer Executor release exists, and shows
+owners and admins an **Update available** note at the bottom of the sidebar, with
+how to update. Members see nothing. It sends one `GET` of
+`/-/package/executor/dist-tags` to the npm registry the server already installs
+app packages from: `EXECUTOR_NPM_REGISTRY`, by default `https://registry.npmjs.org`.
+That request has no query string, cookie or header of its own, and nothing that
+identifies this instance, its version, its organizations or its users. The app
+runtime that installs app packages sends it, in the image and on the native
+server built from source alike, so it reaches the registry exactly as installs
+do: a mirror that installs can use, on a private network or over plain HTTP,
+works for the check too, and both connect directly, without reading `HTTP_PROXY`
+or `HTTPS_PROXY`. It follows no redirect and gives up after 5 seconds. Each attempt is saved with the instance's
+data before the request goes out, so it asks at most once a day: a failed or
+unanswered request, or a restart, doesn't ask again within the day. If the
+attempt can't be saved, the check is off: the server doesn't ask, and logs one
+warning that says where it tried to save it, then one line once saving works
+again. With `EXECUTOR_NPM_REGISTRY` set it asks only your mirror, never the
+public registry. Members' browsers never contact the registry; they ask only
+this server. A beta image compares against betas and newer stable releases; a
+stable image compares against stable releases only. The server keeps the last
+answer it got, with the time of its last check, with the instance's data. When
+the registry can't be reached, it keeps showing the newer release from that
+answer, since that release still exists, and logs one debug line; startup and
+requests never wait for it. Set `EXECUTOR_NO_UPDATE_CHECK=1`
+to turn the check off, as for the CLI: the server then makes no request at all.
+
Back up by snapshotting that volume. Do not remove it when you update the image.
Before updating, stop the container and back up the volume. Pull the new image,
remove only the stopped container with `docker rm executor-v2`, and repeat the
@@ -353,6 +428,22 @@ command.
The MCP endpoint is `/mcp`. Sign-in happens in the browser, the
same way as hosted. See [Add an MCP client](/mcp-clients).
+The server keeps each MCP client's state in memory, one client for each API key
+or OAuth grant in use. A connected client holds about 200 KB, so the default
+of 512 clients takes about 120 MB. It keeps at most `EXECUTOR_MCP_CLIENTS` of
+them. When a new client would pass that, the server forgets the one used least
+recently. The forgotten client's next request is answered `404` (session not
+found), and the client must initialize a new session, as after a server
+restart. Some clients do not do that on their own and keep getting `404`, so
+their tool calls fail until you reconnect them, for example by restarting the
+agent or reconnecting its MCP server. A member who already holds
+`EXECUTOR_MCP_CLIENTS_PER_USER` clients loses their own least recently used one instead, so one member cannot
+push everyone else's out. A client with a request in flight or a program
+waiting for approval is never forgotten. When no client can be, a new one gets
+`503` with `Retry-After: 1` until one finishes. A client unused for 30 minutes
+is forgotten anyway. Raise the limit with care: with about 800 clients kept,
+tool calls took several times as long on a 16-core machine.
+
## Move from a local Executor
A self-hosted server starts empty. Nothing is copied from the local Executor
diff --git a/apps/hosted/cloud/scripts/check-deploy-settings.ts b/apps/hosted/cloud/scripts/check-deploy-settings.ts
index b7bb3902dd..215265aa4e 100644
--- a/apps/hosted/cloud/scripts/check-deploy-settings.ts
+++ b/apps/hosted/cloud/scripts/check-deploy-settings.ts
@@ -2,16 +2,21 @@
* The deploy workflow's first step: refuse settings the stage's Worker would refuse at startup,
* before anything builds or deploys. `alchemy.run.ts` runs the same checks for every deploy, and
* reads the public origin (`BETTER_AUTH_URL` outside test stages) the same way.
- * Reads the stage from `ALCHEMY_STAGE` and the settings from the environment.
+ * Reads the stage from `ALCHEMY_STAGE` and the settings from the environment, Cloud's notes file
+ * (`EXECUTOR_CLOUD_RELEASE_NOTES_FILE`) included, which production must have.
*/
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
+import * as NodeServices from "@effect/platform-node/NodeServices";
import { Console, Effect } from "effect";
import { productionOAuthProxyCheck } from "../src/infrastructure/deploy-settings.ts";
+import { cloudReleaseNotesInput } from "../src/infrastructure/release-notes.ts";
import { cloudOrigin } from "../src/infrastructure/stage.ts";
NodeRuntime.runMain(
productionOAuthProxyCheck.pipe(
Effect.andThen(cloudOrigin),
+ Effect.andThen(cloudReleaseNotesInput),
Effect.andThen(Console.log("Deploy settings are valid.")),
+ Effect.provide(NodeServices.layer),
),
);
diff --git a/apps/hosted/cloud/scripts/edge-contract.ts b/apps/hosted/cloud/scripts/edge-contract.ts
deleted file mode 100644
index e8a477cbb4..0000000000
--- a/apps/hosted/cloud/scripts/edge-contract.ts
+++ /dev/null
@@ -1,218 +0,0 @@
-/**
- * Publish what v1's edge on `executor.sh` forwards to v2 (`productionEdgeForwards`) as
- * `src/contracts/edge-contract.json`: the rules, production's telemetry paths and state prefix,
- * and example requests with whether v1 forwards each. v1 keeps a verbatim copy and tests its own
- * edge against every example, so the two lists cannot drift apart unnoticed: a change here
- * changes the file, and v1's copy must change with it.
- *
- * Every example must agree with `productionEdgeForwards`, and every rule must forward at least
- * one example, so a new rule cannot ship without one. The slashed form of each page in
- * `slashRedirectedSitePages` is not forwarded: v1 redirects it to the page, which is, and every
- * such page has an example. Pass --check to fail when the file is stale.
- */
-import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
-import * as NodeServices from "@effect/platform-node/NodeServices";
-import { Effect, FileSystem, Option, Path, Schema } from "effect";
-import {
- accountOAuthStatePrefix,
- forwardsToV2,
- productionEdgeForwards,
- productionSiteTelemetry,
- slashRedirectedSitePages,
-} from "../src/contracts/edge-paths.ts";
-
-class EdgeContractInvalid extends Schema.TaggedError()("EdgeContractInvalid", {
- reason: Schema.String,
-}) {
- override get message() {
- return this.reason;
- }
-}
-
-const origin = "https://executor.sh";
-const { analyticsProxy, errorTunnel } = productionSiteTelemetry;
-
-/** Example requests without cookies: a path and query, and whether v1 forwards it to v2. */
-const forwarded: ReadonlyArray = [
- ["GET", "/.well-known/oauth-authorization-server/api/auth"],
- ["GET", "/api/auth/callback/google?code=c&state=s"],
- ["GET", "/api/auth/callback/github"],
- ["GET", `/api/oauth/callback?code=c&state=${accountOAuthStatePrefix}abc`],
- ["GET", "/oauth/client-metadata.json"],
- ["GET", "/favicon.png"],
- ["GET", "/git/acme/site.git/info/refs?service=git-upload-pack"],
- ["POST", "/git/acme/site.git/git-receive-pack"],
- ["GET", "/"],
- ["GET", "/home"],
- ["GET", "/pricing"],
- ["GET", "/pricing.md"],
- ["GET", "/index.md"],
- ["GET", "/setup-prompt.md"],
- ["GET", "/llms.txt"],
- ["GET", "/about-executor"],
- ["GET", "/google-workspace"],
- ["GET", "/blog"],
- ["GET", "/blog/"],
- ["GET", "/blog/a-post"],
- ["GET", "/docs"],
- ["GET", "/docs/"],
- ["GET", "/docs/quickstart"],
- ["GET", "/apps"],
- ["GET", "/apps/detail"],
- ["GET", "/experiments/hero/a"],
- ["GET", "/experiments/demo/posthog"],
- ["GET", "/_astro/page.abc123.js"],
- ["GET", "/authors/author.png"],
- ["GET", "/og-image.png"],
- ["GET", "/pattern-graph-paper.svg"],
- ["GET", "/.well-known/agent-skills/index.json"],
- ["GET", "/.well-known/security.txt"],
- ["POST", `${analyticsProxy}/e/?ip=0`],
- ["GET", `${analyticsProxy}/static/array.js`],
- ["POST", errorTunnel],
-];
-
-const kept: ReadonlyArray = [
- ["GET", "/api/auth/.well-known/openid-configuration"],
- ["GET", "/.well-known/oauth-authorization-server"],
- ["GET", "/.well-known/oauth-protected-resource"],
- ["GET", "/api/auth/callback?code=c&state=s"],
- ["GET", "/api/auth/callback/google/extra"],
- ["GET", "/api/auth/login"],
- ["GET", "/api/oauth/callback?code=c&state=abc"],
- ["GET", "/api/oauth/callback?code=c"],
- ["GET", "/oauth/client-id-metadata.json"],
- ["GET", "/git"],
- ["GET", "/gitlab/repo"],
- ["GET", "/demo"],
- ["GET", "/demo/posthog"],
- ["GET", "/experiments"],
- ["GET", "/privacy"],
- ["GET", "/terms"],
- ["GET", "/google-oauth"],
- ["GET", "/_v1-marketing/style.css"],
- ["GET", "/favicon-32.png"],
- ["GET", "/favicon-192.png"],
- ["GET", "/apple-touch-icon.png"],
- ["GET", "/favicon.ico"],
- ["GET", "/pricing/extra"],
- ["GET", "/home/extra"],
- ["GET", "/about-executor/extra"],
- ["GET", "/google-workspace/extra"],
- // Only a page's `GET` or `HEAD` slashed form redirects; see `slashRedirects`.
- ["POST", "/pricing/"],
- ["GET", "/login"],
- ["GET", "/sign-up"],
- ["GET", "/signup"],
- ["POST", "/mcp"],
- ["POST", "/acme/mcp"],
- ["GET", "/acme"],
- ["GET", analyticsProxy],
- ["GET", errorTunnel.replace(/\/submit$/u, "")],
- ["POST", `${errorTunnel}/extra`],
- ["GET", "/api/0123456789abcdef/e/"],
- ["POST", "/api/webhooks/workos"],
-];
-
-/** Slashed pages v1 redirects (308) to the page itself, query kept, and the redirect's target. */
-const slashRedirects: ReadonlyArray = [
- ["/pricing/", "/pricing"],
- ["/pricing/?ref=hn", "/pricing?ref=hn"],
- ["/home/", "/home"],
- ["/about-executor/", "/about-executor"],
- ["/google-workspace/", "/google-workspace"],
-];
-
-const EdgeContract = Schema.Struct({
- source: Schema.String,
- origin: Schema.String,
- oauthStatePrefix: Schema.String,
- telemetry: Schema.Struct({ analyticsProxy: Schema.String, errorTunnel: Schema.String }),
- rules: Schema.Array(Schema.String),
- cases: Schema.Array(
- Schema.Struct({ method: Schema.String, target: Schema.String, forwards: Schema.Boolean }),
- ),
- slashRedirects: Schema.Struct({
- rule: Schema.String,
- pages: Schema.Array(Schema.String),
- cases: Schema.Array(Schema.Struct({ target: Schema.String, location: Schema.String })),
- }),
-});
-
-NodeRuntime.runMain(
- Effect.gen(function* () {
- const fs = yield* FileSystem.FileSystem;
- const path = yield* Path.Path;
- const cases = [
- ...forwarded.map(([method, target]) => ({ method, target, forwards: true })),
- ...kept.map(([method, target]) => ({ method, target, forwards: false })),
- ];
- for (const example of cases)
- if (
- forwardsToV2(productionEdgeForwards, new URL(example.target, origin)) !== example.forwards
- )
- return yield* new EdgeContractInvalid({
- reason: `${example.method} ${example.target} should ${example.forwards ? "" : "not "}forward`,
- });
- for (const [target, location] of slashRedirects) {
- const url = new URL(target, origin);
- const page = url.pathname.slice(0, -1);
- const expected = new URL(location, origin);
- if (
- !url.pathname.endsWith("/") ||
- !slashRedirectedSitePages.some((redirected) => redirected === page) ||
- forwardsToV2(productionEdgeForwards, url) ||
- !forwardsToV2(productionEdgeForwards, expected) ||
- expected.pathname !== page ||
- expected.search !== url.search
- )
- return yield* new EdgeContractInvalid({
- reason: `GET ${target} is not the slashed form of a forwarded page redirecting to ${location}`,
- });
- }
- for (const page of slashRedirectedSitePages)
- if (!slashRedirects.some(([target]) => new URL(target, origin).pathname === `${page}/`))
- return yield* new EdgeContractInvalid({
- reason: `No slash redirect example covers ${page}/`,
- });
- for (const forward of productionEdgeForwards)
- if (!forwarded.some(([, target]) => forward.matches(new URL(target, origin))))
- return yield* new EdgeContractInvalid({
- reason: `No forwarded example covers the rule ${forward.rule}`,
- });
- const contract: typeof EdgeContract.Type = {
- source:
- "Executor v2: apps/hosted/cloud/src/contracts/edge-contract.json, generated by " +
- "apps/hosted/cloud/scripts/edge-contract.ts from productionEdgeForwards",
- origin,
- oauthStatePrefix: accountOAuthStatePrefix,
- telemetry: { analyticsProxy, errorTunnel },
- rules: productionEdgeForwards.map((forward) => forward.rule),
- cases,
- slashRedirects: {
- rule: "GET or HEAD / answers 308 to , query kept, for each of pages",
- pages: [...slashRedirectedSitePages],
- cases: slashRedirects.map(([target, location]) => ({ target, location })),
- },
- };
- const output = path.join(
- yield* path.fromFileUrl(new URL("../src/contracts/", import.meta.url)),
- "edge-contract.json",
- );
- if (!process.argv.includes("--check")) {
- yield* fs.writeFileString(output, `${JSON.stringify(contract, null, 2)}\n`);
- return;
- }
- // Compared as data, so formatting the file does not make it stale.
- const current = yield* fs
- .readFileString(output)
- .pipe(
- Effect.flatMap(Schema.decodeUnknownEffect(Schema.fromJsonString(EdgeContract))),
- Effect.option,
- );
- if (Option.isNone(current) || JSON.stringify(current.value) !== JSON.stringify(contract))
- return yield* new EdgeContractInvalid({
- reason: "edge-contract.json is stale. Run: bun run edge:contract, then copy it to v1",
- });
- }).pipe(Effect.provide(NodeServices.layer)),
-);
diff --git a/apps/hosted/cloud/scripts/no-release-notes.json b/apps/hosted/cloud/scripts/no-release-notes.json
new file mode 100644
index 0000000000..80da034600
--- /dev/null
+++ b/apps/hosted/cloud/scripts/no-release-notes.json
@@ -0,0 +1 @@
+{ "notes": [] }
diff --git a/apps/hosted/cloud/scripts/test-stage-domain-cleanup.ts b/apps/hosted/cloud/scripts/test-stage-domain-cleanup.ts
new file mode 100644
index 0000000000..c9856de977
--- /dev/null
+++ b/apps/hosted/cloud/scripts/test-stage-domain-cleanup.ts
@@ -0,0 +1,77 @@
+/**
+ * Run test-stage cleanup's deletion of one `AppDomains` record (`TestStageDomainCleanup`) against
+ * the Alchemy records given, as `alchemy destroy alchemy.test-cleanup.ts` does for a stage. Prints
+ * `{"deleted": true}`; a failure prints its tag and exits 1.
+ *
+ * node scripts/test-stage-domain-cleanup.ts --stage test- --records --olds
+ *
+ * `--records` is a JSON object of the stage's Alchemy records by logical ID, encoded as Alchemy
+ * stores them; `--olds` the record's props. `test-stage-domain-cleanup.spec.ts` runs it against a local stand-in for Cloudflare's API
+ * and the stage's drain endpoint.
+ */
+import { readFileSync } from "node:fs";
+import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
+import * as Provider from "alchemy/Provider";
+import { noopSession } from "alchemy/Report";
+import { StackContext } from "alchemy/StackContext";
+import { Stage } from "alchemy/Stage";
+import { inMemoryState } from "alchemy/State/InMemoryState";
+import type { ResourceState } from "alchemy/State/ResourceState";
+import { reviveState } from "alchemy/State/StateEncoding";
+import { Console, Effect } from "effect";
+import { FetchHttpClient } from "effect/http";
+import { AppDomainLifecycle } from "../src/infrastructure/app-domain-lifecycle.ts";
+import { TestStageDomainCleanup } from "../src/infrastructure/test-stage-cleanup-providers.ts";
+
+const option = (name: string) => {
+ const at = process.argv.indexOf(name);
+ const value = at === -1 ? undefined : process.argv[at + 1];
+ if (value === undefined) throw new Error(`Pass ${name}.`);
+ return value;
+};
+const stack = "executor-next-hosted";
+const stage = option("--stage");
+// Read as Alchemy's state store reads its records, so a `__redacted__` value is a Redacted again.
+const records: Record = JSON.parse(
+ readFileSync(option("--records"), "utf8"),
+ reviveState,
+);
+const olds = JSON.parse(readFileSync(option("--olds"), "utf8"));
+
+NodeRuntime.runMain(
+ Effect.gen(function* () {
+ const provider = yield* Provider.findProvider(AppDomainLifecycle);
+ yield* provider.delete({
+ id: "AppDomains",
+ fqn: "AppDomains",
+ instanceId: "AppDomains",
+ olds,
+ output: { origin: olds.origin },
+ session: { ...noopSession, note: () => Effect.void },
+ bindings: [],
+ });
+ yield* Console.log(JSON.stringify({ deleted: true }));
+ }).pipe(
+ Effect.provide(TestStageDomainCleanup()),
+ // Alchemy's engine provides the stage's state to a deletion, as it does here.
+ Effect.provide(inMemoryState({ [stack]: { [stage]: records } })),
+ Effect.provideService(Stage, stage),
+ Effect.provideService(StackContext, {
+ name: stack,
+ stage,
+ resources: {},
+ bindings: {},
+ actions: {},
+ }),
+ Effect.provide(FetchHttpClient.layer),
+ Effect.catchCause((cause) =>
+ Console.error(`Deletion failed: ${cause.toString().split("\n")[0]}`).pipe(
+ Effect.andThen(
+ Effect.sync(() => {
+ process.exitCode = 1;
+ }),
+ ),
+ ),
+ ),
+ ),
+);
diff --git a/apps/hosted/cloud/scripts/worker-builds.ts b/apps/hosted/cloud/scripts/worker-builds.ts
index 1de5adad8f..b4817a543a 100644
--- a/apps/hosted/cloud/scripts/worker-builds.ts
+++ b/apps/hosted/cloud/scripts/worker-builds.ts
@@ -9,6 +9,7 @@
* The dashboard Worker bundles the site, so each stage's site is built first, with the
* environment the stack's `Site` resource gives that stage's deploy.
*/
+import { fileURLToPath } from "node:url";
import * as Alchemy from "alchemy";
import * as Cloudflare from "alchemy/Cloudflare";
import * as Command from "alchemy/Command";
@@ -144,6 +145,11 @@ export const production: Target = {
SENTRY_ENABLED: "true",
POSTHOG_ENABLED: "true",
SENTRY_URL: "https://sentry.io",
+ // A production deploy builds only with Cloud's notes file (src/infrastructure/release-notes.ts).
+ // This build publishes nothing, so it stands in one with no notes: no "What's new" block.
+ EXECUTOR_CLOUD_RELEASE_NOTES_FILE: fileURLToPath(
+ new URL("./no-release-notes.json", import.meta.url),
+ ),
},
};
diff --git a/apps/hosted/cloud/src/app-data.ts b/apps/hosted/cloud/src/app-data.ts
index 6f13f38f00..ee2d5a002a 100644
--- a/apps/hosted/cloud/src/app-data.ts
+++ b/apps/hosted/cloud/src/app-data.ts
@@ -175,6 +175,7 @@ const runnerBindings = Effect.gen(function* () {
Effect.orDie,
),
outbound: yield* credentials.outbound,
+ outboundGroup: credentials.outboundGroup,
credentialKey: credentials.key,
data: options.data,
waitUntil: options.waitUntil,
diff --git a/apps/hosted/cloud/src/contracts/edge-contract.json b/apps/hosted/cloud/src/contracts/edge-contract.json
deleted file mode 100644
index ce16279c74..0000000000
--- a/apps/hosted/cloud/src/contracts/edge-contract.json
+++ /dev/null
@@ -1,439 +0,0 @@
-{
- "source": "Executor v2: apps/hosted/cloud/src/contracts/edge-contract.json, generated by apps/hosted/cloud/scripts/edge-contract.ts from productionEdgeForwards",
- "origin": "https://executor.sh",
- "oauthStatePrefix": "x2.",
- "telemetry": {
- "analyticsProxy": "/api/00e2e1f082a6ef17",
- "errorTunnel": "/api/fd6fab1fbb4883e1/submit"
- },
- "rules": [
- "/.well-known/oauth-authorization-server/api/auth",
- "/api/auth/callback/",
- "/api/oauth/callback, when state starts with x2.",
- "/oauth/client-metadata.json",
- "/git/*",
- "/ (without a v1 session)",
- "/home",
- "/pricing",
- "/pricing.md",
- "/index.md",
- "/setup-prompt.md",
- "/llms.txt",
- "/about-executor",
- "/google-workspace",
- "/blog",
- "/blog/*",
- "/docs",
- "/docs/*",
- "/apps",
- "/apps/*",
- "/experiments/*",
- "/_astro/*",
- "/authors/*",
- "/og-image.png",
- "/pattern-graph-paper.svg",
- "/.well-known/security.txt",
- "/favicon.png",
- "/.well-known/agent-skills/*",
- "/api/00e2e1f082a6ef17/*",
- "/api/fd6fab1fbb4883e1/submit"
- ],
- "cases": [
- {
- "method": "GET",
- "target": "/.well-known/oauth-authorization-server/api/auth",
- "forwards": true
- },
- {
- "method": "GET",
- "target": "/api/auth/callback/google?code=c&state=s",
- "forwards": true
- },
- {
- "method": "GET",
- "target": "/api/auth/callback/github",
- "forwards": true
- },
- {
- "method": "GET",
- "target": "/api/oauth/callback?code=c&state=x2.abc",
- "forwards": true
- },
- {
- "method": "GET",
- "target": "/oauth/client-metadata.json",
- "forwards": true
- },
- {
- "method": "GET",
- "target": "/favicon.png",
- "forwards": true
- },
- {
- "method": "GET",
- "target": "/git/acme/site.git/info/refs?service=git-upload-pack",
- "forwards": true
- },
- {
- "method": "POST",
- "target": "/git/acme/site.git/git-receive-pack",
- "forwards": true
- },
- {
- "method": "GET",
- "target": "/",
- "forwards": true
- },
- {
- "method": "GET",
- "target": "/home",
- "forwards": true
- },
- {
- "method": "GET",
- "target": "/pricing",
- "forwards": true
- },
- {
- "method": "GET",
- "target": "/pricing.md",
- "forwards": true
- },
- {
- "method": "GET",
- "target": "/index.md",
- "forwards": true
- },
- {
- "method": "GET",
- "target": "/setup-prompt.md",
- "forwards": true
- },
- {
- "method": "GET",
- "target": "/llms.txt",
- "forwards": true
- },
- {
- "method": "GET",
- "target": "/about-executor",
- "forwards": true
- },
- {
- "method": "GET",
- "target": "/google-workspace",
- "forwards": true
- },
- {
- "method": "GET",
- "target": "/blog",
- "forwards": true
- },
- {
- "method": "GET",
- "target": "/blog/",
- "forwards": true
- },
- {
- "method": "GET",
- "target": "/blog/a-post",
- "forwards": true
- },
- {
- "method": "GET",
- "target": "/docs",
- "forwards": true
- },
- {
- "method": "GET",
- "target": "/docs/",
- "forwards": true
- },
- {
- "method": "GET",
- "target": "/docs/quickstart",
- "forwards": true
- },
- {
- "method": "GET",
- "target": "/apps",
- "forwards": true
- },
- {
- "method": "GET",
- "target": "/apps/detail",
- "forwards": true
- },
- {
- "method": "GET",
- "target": "/experiments/hero/a",
- "forwards": true
- },
- {
- "method": "GET",
- "target": "/experiments/demo/posthog",
- "forwards": true
- },
- {
- "method": "GET",
- "target": "/_astro/page.abc123.js",
- "forwards": true
- },
- {
- "method": "GET",
- "target": "/authors/author.png",
- "forwards": true
- },
- {
- "method": "GET",
- "target": "/og-image.png",
- "forwards": true
- },
- {
- "method": "GET",
- "target": "/pattern-graph-paper.svg",
- "forwards": true
- },
- {
- "method": "GET",
- "target": "/.well-known/agent-skills/index.json",
- "forwards": true
- },
- {
- "method": "GET",
- "target": "/.well-known/security.txt",
- "forwards": true
- },
- {
- "method": "POST",
- "target": "/api/00e2e1f082a6ef17/e/?ip=0",
- "forwards": true
- },
- {
- "method": "GET",
- "target": "/api/00e2e1f082a6ef17/static/array.js",
- "forwards": true
- },
- {
- "method": "POST",
- "target": "/api/fd6fab1fbb4883e1/submit",
- "forwards": true
- },
- {
- "method": "GET",
- "target": "/api/auth/.well-known/openid-configuration",
- "forwards": false
- },
- {
- "method": "GET",
- "target": "/.well-known/oauth-authorization-server",
- "forwards": false
- },
- {
- "method": "GET",
- "target": "/.well-known/oauth-protected-resource",
- "forwards": false
- },
- {
- "method": "GET",
- "target": "/api/auth/callback?code=c&state=s",
- "forwards": false
- },
- {
- "method": "GET",
- "target": "/api/auth/callback/google/extra",
- "forwards": false
- },
- {
- "method": "GET",
- "target": "/api/auth/login",
- "forwards": false
- },
- {
- "method": "GET",
- "target": "/api/oauth/callback?code=c&state=abc",
- "forwards": false
- },
- {
- "method": "GET",
- "target": "/api/oauth/callback?code=c",
- "forwards": false
- },
- {
- "method": "GET",
- "target": "/oauth/client-id-metadata.json",
- "forwards": false
- },
- {
- "method": "GET",
- "target": "/git",
- "forwards": false
- },
- {
- "method": "GET",
- "target": "/gitlab/repo",
- "forwards": false
- },
- {
- "method": "GET",
- "target": "/demo",
- "forwards": false
- },
- {
- "method": "GET",
- "target": "/demo/posthog",
- "forwards": false
- },
- {
- "method": "GET",
- "target": "/experiments",
- "forwards": false
- },
- {
- "method": "GET",
- "target": "/privacy",
- "forwards": false
- },
- {
- "method": "GET",
- "target": "/terms",
- "forwards": false
- },
- {
- "method": "GET",
- "target": "/google-oauth",
- "forwards": false
- },
- {
- "method": "GET",
- "target": "/_v1-marketing/style.css",
- "forwards": false
- },
- {
- "method": "GET",
- "target": "/favicon-32.png",
- "forwards": false
- },
- {
- "method": "GET",
- "target": "/favicon-192.png",
- "forwards": false
- },
- {
- "method": "GET",
- "target": "/apple-touch-icon.png",
- "forwards": false
- },
- {
- "method": "GET",
- "target": "/favicon.ico",
- "forwards": false
- },
- {
- "method": "GET",
- "target": "/pricing/extra",
- "forwards": false
- },
- {
- "method": "GET",
- "target": "/home/extra",
- "forwards": false
- },
- {
- "method": "GET",
- "target": "/about-executor/extra",
- "forwards": false
- },
- {
- "method": "GET",
- "target": "/google-workspace/extra",
- "forwards": false
- },
- {
- "method": "POST",
- "target": "/pricing/",
- "forwards": false
- },
- {
- "method": "GET",
- "target": "/login",
- "forwards": false
- },
- {
- "method": "GET",
- "target": "/sign-up",
- "forwards": false
- },
- {
- "method": "GET",
- "target": "/signup",
- "forwards": false
- },
- {
- "method": "POST",
- "target": "/mcp",
- "forwards": false
- },
- {
- "method": "POST",
- "target": "/acme/mcp",
- "forwards": false
- },
- {
- "method": "GET",
- "target": "/acme",
- "forwards": false
- },
- {
- "method": "GET",
- "target": "/api/00e2e1f082a6ef17",
- "forwards": false
- },
- {
- "method": "GET",
- "target": "/api/fd6fab1fbb4883e1",
- "forwards": false
- },
- {
- "method": "POST",
- "target": "/api/fd6fab1fbb4883e1/submit/extra",
- "forwards": false
- },
- {
- "method": "GET",
- "target": "/api/0123456789abcdef/e/",
- "forwards": false
- },
- {
- "method": "POST",
- "target": "/api/webhooks/workos",
- "forwards": false
- }
- ],
- "slashRedirects": {
- "rule": "GET or HEAD / answers 308 to , query kept, for each of pages",
- "pages": ["/home", "/pricing", "/about-executor", "/google-workspace"],
- "cases": [
- {
- "target": "/pricing/",
- "location": "/pricing"
- },
- {
- "target": "/pricing/?ref=hn",
- "location": "/pricing?ref=hn"
- },
- {
- "target": "/home/",
- "location": "/home"
- },
- {
- "target": "/about-executor/",
- "location": "/about-executor"
- },
- {
- "target": "/google-workspace/",
- "location": "/google-workspace"
- }
- ]
- }
-}
diff --git a/apps/hosted/cloud/src/contracts/edge-paths.ts b/apps/hosted/cloud/src/contracts/edge-paths.ts
index 93ace49725..4284a22397 100644
--- a/apps/hosted/cloud/src/contracts/edge-paths.ts
+++ b/apps/hosted/cloud/src/contracts/edge-paths.ts
@@ -1,8 +1,8 @@
/**
* The requests v1's edge on `executor.sh` forwards to v2 through its service binding, with the
* original URL (`notes/cloud-domains.md`). v1 owns every other path. A test stage's forwarding
- * Worker forwards exactly these, v2's edge router serves them, and production's list is the
- * contract v1 implements.
+ * Worker forwards exactly these and v2's edge router serves them. Production no longer goes
+ * through v1's edge: v2's gateway serves `executor.sh` itself (`notes/v1-shutdown.md`).
*/
/**
@@ -21,7 +21,6 @@ import {
sitePages,
v1SiteFiles,
v1SitePages,
- type SitePattern,
} from "./site-paths.ts";
/** One forwarded request shape, with the form v1's edge documents it in. */
@@ -103,29 +102,6 @@ const routedEdgeForwards: ReadonlyArray = [
site(agentSkills),
];
-/**
- * Production's forwards: the contract v1's edge implements. `edge-contract.json` publishes it
- * with example requests (`scripts/edge-contract.ts`); v1 tests its edge against a pinned copy.
- */
-export const productionEdgeForwards = edgeForwardsFor({
- analyticsProxy: Option.some(productionSiteTelemetry.analyticsProxy),
- errorTunnel: Option.some(productionSiteTelemetry.errorTunnel),
-});
-
-/**
- * Forwarded site pages that match only themselves, such as `/pricing`. v1's edge answers a `GET`
- * or `HEAD` for one's slashed form (`/pricing/`) with a 308 to the page, query kept, as the site's
- * own build does on v2's hosts (`scripts/build-site.ts`), and forwards that. Pages with a
- * forwarded `/x/*` already forward their slashed form; deeper paths stay v1's.
- */
-export const slashRedirectedSitePages: ReadonlyArray = sitePages.filter(
- (page) =>
- !page.endsWith("/*") &&
- !page.includes(".") &&
- !v1SitePages.includes(page) &&
- !sitePages.includes(`${page}/*`),
-);
-
/** Whether `forwards` include `url`. */
export const forwardsToV2 = (forwards: ReadonlyArray, url: URL) =>
forwards.some((forward) => forward.matches(url));
diff --git a/apps/hosted/cloud/src/implementation/app-outbound-relay.ts b/apps/hosted/cloud/src/implementation/app-outbound-relay.ts
new file mode 100644
index 0000000000..89f4ce55c4
--- /dev/null
+++ b/apps/hosted/cloud/src/implementation/app-outbound-relay.ts
@@ -0,0 +1,74 @@
+/**
+ * The relay objects AppData sends app requests through when no direct slot frees in time; see
+ * `app-outbound-routes.ts`. It imports nothing, so a check can load it into workerd as it is.
+ */
+
+/**
+ * `AppOutboundRelay`'s code: objects that send one app request each on the same network as
+ * `AppOutbound`. A request to a Durable Object runs in that object's invocation, with its own limit
+ * of six connections waiting for response headers, and the caller's wait for the object does not
+ * count against the caller's six (measured on Cloudflare, November 2026); see
+ * `app-outbound-routes.ts` for when a request goes this way.
+ *
+ * `send` takes the request without its signal, which RPC does not carry, and `cancel`, a function
+ * of the caller's that settles when the app aborts the request and rejects once the caller is gone;
+ * either stops the wait for headers. After the headers, cancelling the response body reaches the
+ * service through the stream. The default entrypoint answers nothing.
+ */
+export const relayScript = `import { DurableObject } from "cloudflare:workers";
+export default {
+ fetch() { return new Response(null, { status: 404 }); }
+};
+export class AppOutboundRelay extends DurableObject {
+ async send(request, cancel) {
+ const controller = new AbortController();
+ let answered = false;
+ const stop = () => { if (!answered) controller.abort(); };
+ cancel.aborted().then(stop, stop);
+ const response = await fetch(new Request(request, { signal: controller.signal }));
+ answered = true;
+ return response;
+ }
+}`;
+
+/** What a relay object answers: `send` in `relayScript`. */
+export interface Relay {
+ send(request: Request, cancel: RelayCancel): Promise;
+}
+
+/** The relay Worker's object namespace, as AppData binds it. */
+export interface RelayObjects {
+ idFromName(name: string): unknown;
+ get(id: unknown): Relay;
+}
+
+/**
+ * Settles when the app aborts its request; a relay object stops waiting for headers then. RPC
+ * passes the function as a stub, so a lost caller rejects the object's call to it.
+ */
+export interface RelayCancel {
+ readonly aborted: () => Promise;
+}
+const relayCancel = (signal: AbortSignal): RelayCancel => ({
+ aborted: () =>
+ new Promise((resolve) => {
+ if (signal.aborted) resolve();
+ else signal.addEventListener("abort", () => resolve(), { once: true });
+ }),
+});
+
+/** Relay objects are named by slot within this isolate, so no other isolate's requests share one. */
+const relayName = (() => {
+ // Named on first use: a Worker may not generate random values at startup.
+ let isolate: string | undefined;
+ return (slot: number) => `${(isolate ??= crypto.randomUUID())}:${slot}`;
+})();
+
+/** Send `request` through the relay object in `slot`. */
+export const relayed = (objects: RelayObjects, slot: number, request: Request) => {
+ // RPC carries no AbortSignal; the object hears of an abort through `RelayCancel`.
+ const unsignalled = new Request(request, { signal: null });
+ return objects
+ .get(objects.idFromName(relayName(slot)))
+ .send(unsignalled, relayCancel(request.signal));
+};
diff --git a/apps/hosted/cloud/src/implementation/app-outbound-routes.ts b/apps/hosted/cloud/src/implementation/app-outbound-routes.ts
new file mode 100644
index 0000000000..1ac87e25e5
--- /dev/null
+++ b/apps/hosted/cloud/src/implementation/app-outbound-routes.ts
@@ -0,0 +1,264 @@
+/**
+ * Which route each app request of one incoming request takes on Cloud: the direct network, or a
+ * relay object with its own connection limit.
+ *
+ * Cloudflare lets one incoming request have six connections waiting for response headers and queues
+ * the rest until one is answered. Every app call that request makes counts against it, and so does
+ * the host's own work for it (storage, service calls, build reads). A request to a Durable Object
+ * waits on the object's own limit instead, at a cost: 10-15 ms on an object in use, 300-450 ms when
+ * the object starts (measured on a test stage, November 2026).
+ *
+ * So a request goes direct while its incoming request has fewer than `directLimit` app requests
+ * waiting for headers, which leaves the sixth connection to the host. Otherwise it waits for a
+ * direct slot, holding no connection: against a fast service one frees within milliseconds. A
+ * request still waiting after `relayAfter` goes through a relay object instead; it was going to
+ * wait behind slow requests, so an object's start costs it little. While this isolate's direct
+ * route is not known to be answering, it waits `relayColdAfter` instead (see there). At most
+ * `relayLimit` requests of one incoming request are in relay objects at once; past that they wait
+ * for either route.
+ *
+ * Requests are counted by the group the host names for the incoming request
+ * (`AppInvocation.outboundGroup`), and only while that group lives: while a call of it runs, or a
+ * request it counted still waits, for headers on either route or for a route. So a group app code
+ * names itself counts for nothing and its requests go direct, as every request did before relays,
+ * and a later call of an incoming request counts the requests an earlier call left waiting. Every
+ * counted request is released however it ends.
+ * Waiters are resumed through native promises, never Effect primitives, so each continues in its
+ * own request's I/O context (see `handoff.ts` in the SDK).
+ */
+
+/** App requests one incoming request may have waiting for headers directly; Cloudflare allows six. */
+export const directLimit = 5;
+/** How long a request waits for a direct slot before it goes through a relay object, in ms. */
+export const relayAfter = 50;
+/**
+ * How long a request waits for a direct slot instead, in ms, while this isolate's direct route is
+ * not known to be answering: no direct request of it has had headers in the last `answeringFor`.
+ * A slow first answer then is the Worker starting, not a slow service, and a relay object starting
+ * (300-450 ms) would not answer sooner. After 60 s idle, programs of 6 to 10 calls to a 20 ms
+ * service relayed in 6 of 6 with the 50 ms wait (slowest call 127-243 ms behind the fastest), and
+ * in none of 20 with this one (at most 5 ms behind; test stages, November 2026).
+ */
+export const relayColdAfter = 500;
+/** How long after a direct request's headers the direct route counts as answering, in ms. */
+export const answeringFor = 30_000;
+/** App requests one incoming request may have in relay objects at once. */
+export const relayLimit = 50;
+
+export type Route = "direct" | "relay";
+
+/** A route taken; `release` once the request's headers arrive or it fails. */
+export interface Taken {
+ readonly route: Route;
+ /** The relay object's slot, for a relayed request. */
+ readonly slot: number | undefined;
+ /** How long the request waited for its route, in milliseconds. */
+ readonly waited: number;
+ readonly release: () => void;
+}
+
+/**
+ * Relay object slots of one AppData isolate. An object carries one request at a time until its
+ * headers arrive (one object given ten at once answered them in four steps), so a freed slot is
+ * reused before a new one is named.
+ */
+class Slots {
+ readonly #free: Array = [];
+ #next = 0;
+ acquire() {
+ return this.#free.pop() ?? this.#next++;
+ }
+ release(slot: number) {
+ this.#free.push(slot);
+ }
+}
+
+interface Waiter {
+ /** False for a request a relay cannot carry (a WebSocket upgrade). */
+ readonly relayable: boolean;
+ /** Waited `relayAfter` without a direct slot. */
+ waited: boolean;
+ readonly grant: (route: Route) => void;
+}
+
+/** The app requests of one incoming request. */
+class Group {
+ holds = 0;
+ direct = 0;
+ relayed = 0;
+ readonly waiting: Array = [];
+
+ constructor(
+ readonly slots: Slots,
+ /** Called whenever a count falls, so the group is forgotten once it is idle. */
+ readonly settled: () => void,
+ ) {}
+
+ /** No call holds the group and none of its requests is counted. */
+ get idle() {
+ return this.holds === 0 && this.direct === 0 && this.relayed === 0 && this.waiting.length === 0;
+ }
+
+ take(route: Route, waited: number): Taken {
+ const slot = route === "relay" ? this.slots.acquire() : undefined;
+ if (slot === undefined) this.direct++;
+ else this.relayed++;
+ let released = false;
+ return {
+ route,
+ slot,
+ waited,
+ release: () => {
+ if (released) return;
+ released = true;
+ if (slot === undefined) {
+ this.direct--;
+ this.waiting.shift()?.grant("direct");
+ } else {
+ this.relayed--;
+ this.slots.release(slot);
+ this.relayWaiters();
+ }
+ this.settled();
+ },
+ };
+ }
+
+ /** Relay the waiters that waited `relayAfter`, oldest first, while relay room remains. */
+ relayWaiters() {
+ let index = 0;
+ while (index < this.waiting.length && this.relayed < relayLimit) {
+ const waiter = this.waiting[index];
+ if (waiter?.relayable === true && waiter.waited) {
+ this.waiting.splice(index, 1);
+ waiter.grant("relay");
+ } else index++;
+ }
+ }
+}
+
+/** How a request is sent on each route. */
+export interface Transport {
+ readonly direct: (request: Request) => Promise;
+ readonly relay: (slot: number, request: Request) => Promise;
+}
+
+/** How one request was sent, for its span: the route, the wait for it and the wait for headers. */
+export type Sent = Record;
+
+/** The groups of one AppData isolate's outbound requests. */
+export const appOutboundRoutes = () => {
+ const groups = new Map();
+ const slots = new Slots();
+ /** When a direct request of this isolate last had headers (`Date.now()`). */
+ let answeredAt = Number.NEGATIVE_INFINITY;
+ const directAnswering = () => Date.now() - answeredAt < answeringFor;
+ const answered = () => {
+ answeredAt = Date.now();
+ };
+ /**
+ * The route for one request of `group`, once it is free. A request whose group does not live
+ * (no call holds it and none of its requests is counted) goes direct and is not counted. A request a relay cannot carry (`relayable` false) waits for a
+ * direct slot however long that takes. Rejects with the signal's reason when the request is
+ * cancelled while it waits.
+ */
+ const take = (name: string | null, relayable: boolean, signal: AbortSignal): Promise => {
+ const group = name === null ? undefined : groups.get(name);
+ if (group === undefined)
+ return Promise.resolve({
+ route: "direct",
+ slot: undefined,
+ waited: 0,
+ release: () => undefined,
+ });
+ if (group.waiting.length === 0 && group.direct < directLimit)
+ return Promise.resolve(group.take("direct", 0));
+ if (signal.aborted) return Promise.reject(signal.reason);
+ const started = performance.now();
+ return new Promise((resolve, reject) => {
+ let timer: ReturnType | undefined;
+ const cancelled = () => {
+ clearTimeout(timer);
+ const index = group.waiting.indexOf(waiter);
+ if (index >= 0) group.waiting.splice(index, 1);
+ group.settled();
+ reject(signal.reason);
+ };
+ const waiter: Waiter = {
+ relayable,
+ waited: false,
+ grant: (route) => {
+ clearTimeout(timer);
+ signal.removeEventListener("abort", cancelled);
+ resolve(group.take(route, performance.now() - started));
+ },
+ };
+ group.waiting.push(waiter);
+ signal.addEventListener("abort", cancelled, { once: true });
+ if (relayable)
+ timer = setTimeout(
+ () => {
+ waiter.waited = true;
+ group.relayWaiters();
+ },
+ directAnswering() ? relayAfter : relayColdAfter,
+ );
+ });
+ };
+ return {
+ /** A direct request has had its headers: the direct route is answering. */
+ answered,
+ /**
+ * Count requests named `group` until the returned function is called. Calls of one incoming
+ * request hold it together; once none holds it and none of its requests is counted, the name
+ * is forgotten.
+ */
+ hold: (name: string) => {
+ let group = groups.get(name);
+ if (group === undefined) {
+ const created = new Group(slots, () => {
+ if (created.idle && groups.get(name) === created) groups.delete(name);
+ });
+ group = created;
+ groups.set(name, group);
+ }
+ const held = group;
+ held.holds++;
+ let released = false;
+ return () => {
+ if (released) return;
+ released = true;
+ held.holds--;
+ held.settled();
+ };
+ },
+ take,
+ /**
+ * Send one request of `group` on the route it takes, recording how in `sent`. Its route is
+ * released once its headers arrive or it fails, however it fails: a send that throws before
+ * returning a promise included.
+ */
+ send: async (
+ name: string | null,
+ request: Request,
+ transport: Transport,
+ sent: Array,
+ ): Promise => {
+ // A relay cannot carry a WebSocket upgrade, so one waits for a direct slot.
+ const taken = await take(name, !request.headers.has("upgrade"), request.signal);
+ const record: Sent = { route: taken.route, wait_ms: Math.round(taken.waited) };
+ sent.push(record);
+ const started = performance.now();
+ try {
+ const response = await (taken.slot === undefined
+ ? transport.direct(request)
+ : transport.relay(taken.slot, request));
+ record.headers_ms = Math.round(performance.now() - started);
+ if (taken.route === "direct") answered();
+ return response;
+ } finally {
+ taken.release();
+ }
+ },
+ };
+};
diff --git a/apps/hosted/cloud/src/implementation/onboarding-store.ts b/apps/hosted/cloud/src/implementation/onboarding-store.ts
index 638e1bafe6..c820ff3f92 100644
--- a/apps/hosted/cloud/src/implementation/onboarding-store.ts
+++ b/apps/hosted/cloud/src/implementation/onboarding-store.ts
@@ -3,6 +3,7 @@ import { SqlClient } from "effect/sql";
import { fumadb } from "fumadb-effect";
import { column, idColumn, schema, table } from "fumadb-effect/schema";
import { sqlAdapter } from "fumadb-effect/sql";
+import { invitingRoles } from "@executor-js/hosted-server";
import { SetupOrder, SetupSkip } from "@executor-js/hosted-server/setup";
import {
CompanyProfile,
@@ -65,7 +66,8 @@ export const makeOnboardingStore = Effect.gen(function* () {
Effect.map((rows) => rows[0]),
);
// This statement must follow the user lock so a waiting request sees the
- // previous transaction's committed membership under READ COMMITTED.
+ // previous transaction's committed membership under READ COMMITTED. The invitation is one that
+ // can still be accepted: its inviter still holds a role that may invite (`inviterMayInvite`).
const state = (id: string, email: string) =>
sql`select
coalesce((select jsonb_agg(jsonb_build_object(
@@ -73,8 +75,11 @@ export const makeOnboardingStore = Effect.gen(function* () {
) order by o."createdAt", o.id) from organization o join member m on m."organizationId" = o.id
where m."userId" = ${id}
and not exists (select 1 from hosted_organization_removal r where r.organization_id = o.id)), '[]'::jsonb) as organizations,
- (select id from invitation where lower(email) = lower(${email}) and status = 'pending'
- and "expiresAt" > now() order by "expiresAt", id limit 1) as invitation,
+ (select i.id from invitation i where lower(i.email) = lower(${email}) and i.status = 'pending'
+ and i."expiresAt" > now()
+ and exists (select 1 from member im where im."userId" = i."inviterId"
+ and im."organizationId" = i."organizationId" and im.role in ${sql.in(invitingRoles)})
+ order by i."expiresAt", i.id limit 1) as invitation,
(exists(select 1 from cloud_organization_setup where user_id = ${id})
or exists(select 1 from invitation where lower(email) = lower(${email}) and status = 'accepted')) as provisioned
`.pipe(
diff --git a/apps/hosted/cloud/src/implementation/sso.ts b/apps/hosted/cloud/src/implementation/sso.ts
index 64d7e0b85f..6e7b238c33 100644
--- a/apps/hosted/cloud/src/implementation/sso.ts
+++ b/apps/hosted/cloud/src/implementation/sso.ts
@@ -3,6 +3,7 @@ import type { AuthContext, BetterAuthPlugin, GenericEndpointContext } from "bett
import { getCurrentAdapter } from "better-auth";
import { APIError, createAuthMiddleware, getSessionFromCtx } from "better-auth/api";
import { symmetricDecrypt, symmetricEncrypt } from "better-auth/crypto";
+import { inviterMayInvite } from "@executor-js/hosted-server";
import { Option, Schema } from "effect";
import type { CloudBillingHooks } from "./auth-options.ts";
@@ -148,19 +149,18 @@ export const cloudSso = (billing?: CloudBillingHooks) => {
})
)
return;
- // An explicit invitation owns its role and must still be accepted.
- if (
- await database.findOne({
- model: "invitation",
- where: [
- { field: "organizationId", value: provider.organizationId },
- { field: "email", value: user.email.toLowerCase() },
- { field: "status", value: "pending" },
- { field: "expiresAt", value: new Date(), operator: "gt" },
- ],
- })
- )
- return;
+ // An explicit invitation owns its role and must still be accepted, if it still can be.
+ const invitations = await database.findMany<{ organizationId: string; inviterId: string }>({
+ model: "invitation",
+ where: [
+ { field: "organizationId", value: provider.organizationId },
+ { field: "email", value: user.email.toLowerCase() },
+ { field: "status", value: "pending" },
+ { field: "expiresAt", value: new Date(), operator: "gt" },
+ ],
+ });
+ for (const invitation of invitations)
+ if (await inviterMayInvite(database, invitation)) return;
const count = await database.count({
model: "member",
where: [{ field: "organizationId", value: provider.organizationId }],
diff --git a/apps/hosted/cloud/src/implementation/test-stage-branch.ts b/apps/hosted/cloud/src/implementation/test-stage-branch.ts
index 3021c9646b..51f4cdb9e8 100644
--- a/apps/hosted/cloud/src/implementation/test-stage-branch.ts
+++ b/apps/hosted/cloud/src/implementation/test-stage-branch.ts
@@ -6,7 +6,9 @@
* that never became ready, a killed process), destroy logs that the branch "exists in the cloud but
* is not owned by this stack" and leaves it, billing, while the run looks finished.
*
- * What this may delete, and nothing else:
+ * It reads the branch `test-` for any stage in the registry, so a manually deployed
+ * PlanetScale stage whose branch the destroy removed reads 404 and its lease goes. What it may
+ * delete, and nothing else:
* - one branch, named exactly `test-` for the stage being destroyed, where the slug is a
* deployed E2E run's (`e2e-` and 1-13 lowercase letters or digits, `e2e/sdk/deployment.ts`). The
* name is derived from the slug; it is never taken from a branch list or matched by a pattern;
@@ -24,6 +26,7 @@
import { Config, Duration, Effect, Option, Redacted, Schedule, Schema } from "effect";
import { HttpClient, HttpClientRequest } from "effect/http";
import { planetScaleApi } from "./test-stage-orphans.ts";
+import { TestStageSlug } from "../contracts/test-stage-lifetime.ts";
/** A deployed E2E run's slug (`e2e/sdk/deployment.ts`). */
const e2eSlug = /^e2e-[a-z0-9]{1,13}$/u;
@@ -39,6 +42,17 @@ export const stageBranchFor = (
? { branch: `test-${slug}` }
: { refused: `"${slug}" is not a deployed E2E run's slug (e2e- and 1-13 letters or digits)` };
+/**
+ * The branch a stage's teardown reads: `test-` for any test stage's slug, which only a
+ * deployed E2E run's may also delete. Anything that is not a slug is refused before any request.
+ */
+const stageBranchToRead = (
+ slug: string,
+): { readonly branch: string; readonly mayDelete: boolean } | { readonly refused: string } =>
+ Schema.is(TestStageSlug)(slug)
+ ? { branch: `test-${slug}`, mayDelete: e2eSlug.test(slug) }
+ : { refused: `"${slug}" is not a test stage's slug` };
+
/** Whether `name` is exactly the branch `stageBranchFor(slug)` derives. */
export const isStageBranch = (name: string, slug: string) => {
const derived = stageBranchFor(slug);
@@ -50,6 +64,11 @@ export type BranchOutcome =
| { readonly _tag: "Refused"; readonly reason: string }
/** PlanetScale answered 404 before any delete was sent: nothing to remove. */
| { readonly _tag: "Absent" }
+ /**
+ * The branch is still there after the destroy, and it is not a deployed E2E run's, so no delete
+ * was sent.
+ */
+ | { readonly _tag: "NotDeleted"; readonly reason: string }
/** A production branch; no delete was sent. */
| { readonly _tag: "Production" }
/** The branch could not be read (an answer other than 200 or 404, or none in time); no delete was sent. */
@@ -74,6 +93,8 @@ export const branchOutcomeMessage = (branch: string, outcome: BranchOutcome) =>
switch (outcome._tag) {
case "Refused":
return `Not deleting PlanetScale branch ${branch}: ${outcome.reason}. No request was sent.`;
+ case "NotDeleted":
+ return `PlanetScale branch ${branch} is still there after the destroy. ${outcome.reason}, so no delete was sent. ${remover}.`;
case "Absent":
return `PlanetScale branch ${branch} is gone (PlanetScale answers 404). No delete was needed.`;
case "Deleted":
@@ -113,7 +134,7 @@ const confirmPolls = 24;
*/
export const removeStageBranch = (slug: string) =>
Effect.gen(function* () {
- const derived = stageBranchFor(slug);
+ const derived = stageBranchToRead(slug);
if ("refused" in derived)
return Option.some({ _tag: "Refused", reason: derived.refused });
const database = yield* Config.option(Config.NonEmptyString("TEST_STAGE_DATABASE"));
@@ -165,6 +186,11 @@ export const removeStageBranch = (slug: string) =>
if (found.value.production) return Option.some({ _tag: "Production" });
// The destroy's own delete may still be landing: give it time before sending one.
if (yield* gone(settlePolls)) return Option.some({ _tag: "Absent" });
+ if (!derived.mayDelete)
+ return Option.some({
+ _tag: "NotDeleted",
+ reason: `Only a deployed E2E run's branch is deleted by name (e2e- and 1-13 letters or digits)`,
+ });
const deleted = yield* call(HttpClientRequest.delete(url));
if (Option.isNone(deleted)) return Option.some({ _tag: "DeleteUnanswered" });
diff --git a/apps/hosted/cloud/src/implementation/test-stage-capacity.ts b/apps/hosted/cloud/src/implementation/test-stage-capacity.ts
new file mode 100644
index 0000000000..28b8fd0b64
--- /dev/null
+++ b/apps/hosted/cloud/src/implementation/test-stage-capacity.ts
@@ -0,0 +1,182 @@
+/**
+ * Durable Object classes and Workers are account quotas: each Durable Object class a Worker exports
+ * is one namespace, and Cloudflare documents at most 500 classes and 500 Workers per Workers Paid
+ * account. Every test stage uses several of each, and production and other stacks share the account.
+ * A deploy of a new stage past a quota fails part way through Alchemy's apply, for whoever creates
+ * the one too many.
+ *
+ * An account's quotas can be raised, and nothing the API returns says what they are, so the
+ * documented figures only warn. A quota is enforced only when its variable gives the account's real
+ * one; then a stage past it is refused before anything is evicted, reserved or built.
+ */
+import { Config, Effect, Option, Schema } from "effect";
+import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
+import { TestStageFailed } from "../contracts/test-stage-lifetime.ts";
+
+/** The two quotas, Cloudflare's documented Workers Paid figure for each, and what sets the real one. */
+const quotas = {
+ classes: {
+ counted: "Durable Object namespaces",
+ limited: "Durable Object classes",
+ documented: 500,
+ variable: "TEST_STAGE_DURABLE_OBJECT_CLASS_LIMIT",
+ },
+ workers: {
+ counted: "Workers",
+ limited: "Workers",
+ documented: 500,
+ variable: "TEST_STAGE_WORKER_LIMIT",
+ },
+} as const;
+type Quota = keyof typeof quotas;
+
+/** The namespace listing pages by `page` and `per_page` and gives `total_count`, not a page count. */
+const Namespaces = Schema.Struct({
+ success: Schema.Literal(true),
+ result: Schema.Array(Schema.Struct({ script: Schema.optional(Schema.NullOr(Schema.String)) })),
+ result_info: Schema.Struct({ total_count: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)) }),
+});
+/** The Worker listing returns every Worker in one answer, as test-stage discovery reads it. */
+const Scripts = Schema.Struct({
+ success: Schema.Literal(true),
+ result: Schema.Array(
+ Schema.Struct({ id: Schema.String, tags: Schema.NullOr(Schema.Array(Schema.String)) }),
+ ),
+ result_info: Schema.optional(
+ Schema.Struct({ total_pages: Schema.optional(Schema.Int.check(Schema.isGreaterThan(0))) }),
+ ),
+});
+
+/** How many of one kind the account has, and how many each test stage holds. */
+interface Count {
+ readonly total: number;
+ readonly byStage: ReadonlyMap;
+}
+/** The account's Durable Object namespaces and Workers. */
+export type AccountUsage = Readonly>;
+
+/** Read the account's namespaces and Workers. It only reads. */
+export const accountUsage = Effect.gen(function* () {
+ const account = yield* Config.NonEmptyString("CLOUDFLARE_ACCOUNT_ID");
+ const token = yield* Config.Redacted("CLOUDFLARE_API_TOKEN");
+ // A recorded copy of the API can stand in for it (`test-stage-unreadable.spec.ts`).
+ const api = yield* Config.String("TEST_STAGE_CLOUDFLARE_API").pipe(
+ Config.withDefault("https://api.cloudflare.com"),
+ );
+ const http = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk);
+ const get = (path: string, schema: S) =>
+ http
+ .execute(
+ HttpClientRequest.get(
+ `${api}/client/v4/accounts/${encodeURIComponent(account)}${path}`,
+ ).pipe(HttpClientRequest.bearerToken(token)),
+ )
+ .pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(schema)));
+ const namespaces = Effect.gen(function* () {
+ const items: Array<(typeof Namespaces.Type)["result"][number]> = [];
+ for (let page = 1; ; page += 1) {
+ const body = yield* get(
+ `/workers/durable_objects/namespaces?page=${page}&per_page=1000`,
+ Namespaces,
+ );
+ items.push(...body.result);
+ if (items.length >= body.result_info.total_count || body.result.length === 0) {
+ // A count that falls short of the total it states would understate the account's use.
+ if (items.length < body.result_info.total_count)
+ return yield* Effect.fail(new Error("The namespace listing ended before its total."));
+ return items;
+ }
+ }
+ });
+ const scripts = Effect.gen(function* () {
+ const items: Array<(typeof Scripts.Type)["result"][number]> = [];
+ for (let page = 1, total = 1; page <= total; page += 1) {
+ const body = yield* get(`/workers/scripts?page=${page}&per_page=100`, Scripts);
+ items.push(...body.result);
+ total = body.result_info?.total_pages ?? 1;
+ }
+ return items;
+ });
+ const [namespaceList, scriptList] = yield* Effect.all([namespaces, scripts], {
+ concurrency: 2,
+ });
+ const stageOf = new Map();
+ for (const script of scriptList) {
+ if (script.tags === null || !script.tags.includes("alchemy:stack:executor-next-hosted"))
+ continue;
+ const stage = script.tags.find((tag) => tag.startsWith("alchemy:stage:test-"));
+ if (stage !== undefined) stageOf.set(script.id, stage.slice("alchemy:stage:test-".length));
+ }
+ const classes = new Map();
+ for (const namespace of namespaceList) {
+ const slug =
+ namespace.script === undefined || namespace.script === null
+ ? undefined
+ : stageOf.get(namespace.script);
+ if (slug !== undefined) classes.set(slug, (classes.get(slug) ?? 0) + 1);
+ }
+ const workers = new Map();
+ for (const slug of stageOf.values()) workers.set(slug, (workers.get(slug) ?? 0) + 1);
+ return {
+ classes: { total: namespaceList.length, byStage: classes },
+ workers: { total: scriptList.length, byStage: workers },
+ } satisfies AccountUsage;
+}).pipe(
+ Effect.timeout("30 seconds"),
+ Effect.mapError(
+ () =>
+ new TestStageFailed({
+ message:
+ "Could not count the account's Workers and Durable Object namespaces, so a new test stage was not started. Check Cloudflare access.",
+ }),
+ ),
+);
+
+/** Each quota's real figure, where the account owner set one. */
+export const accountLimits = Effect.all({
+ classes: Config.option(Config.Int(quotas.classes.variable)),
+ workers: Config.option(Config.Int(quotas.workers.variable)),
+});
+export type AccountLimits = Readonly>>;
+
+/**
+ * What a new stage would do to each quota. A new stage is taken to need as many as the largest test
+ * stage holds now; the stages it evicts free theirs first. A quota with a configured figure refuses
+ * past it; one without warns past Cloudflare's documented figure and lets the deploy go on.
+ */
+export const capacityCheck = (
+ usage: AccountUsage,
+ limits: AccountLimits,
+ slug: string,
+ evicting: ReadonlyArray,
+ /** Whether evictions already ran and one failed, so the text says so. */
+ afterFailedEviction = false,
+) => {
+ const refusals: string[] = [];
+ const warnings: string[] = [];
+ for (const quota of ["classes", "workers"] as const) {
+ const { counted, limited, documented, variable } = quotas[quota];
+ const { total, byStage } = usage[quota];
+ const perStage = Math.max(0, ...byStage.values());
+ const freed = evicting.reduce((sum, stage) => sum + (byStage.get(stage) ?? 0), 0);
+ const after = total - freed + perStage;
+ const counts = `${total} now${freed > 0 ? `, ${freed} freed by ${evicting.length === 1 ? "the evicted stage" : `the ${evicting.length} evicted stages`}` : ""}, up to ${perStage} for a test stage`;
+ const limit = limits[quota];
+ if (Option.isSome(limit)) {
+ if (after > limit.value)
+ refusals.push(
+ `about ${after} ${counted} (${counts}), over the ${variable} limit of ${limit.value} ${limited}`,
+ );
+ } else if (after > documented)
+ warnings.push(
+ `Deploying ${slug} brings the account to about ${after} ${counted} (${counts}), past Cloudflare's documented limit of ${documented} ${limited} per Workers Paid account. This account's real limit is unknown and may have been raised, so the deploy goes on; if it is lower, the deploy fails part way through. Set ${variable} to the account's limit to refuse such a deploy instead.`,
+ );
+ }
+ return {
+ refusal:
+ refusals.length === 0
+ ? undefined
+ : `Deploying ${slug} would bring the account to ${refusals.join("; and to ")}. ${afterFailedEviction ? "An eviction failed, so this deploy stopped; nothing was reserved or deployed." : "Nothing was evicted, reserved, deployed or destroyed."} Destroy test stages you own, or redeploy one instead of a new slug.`,
+ warning: warnings.length === 0 ? undefined : warnings.join("\n"),
+ };
+};
diff --git a/apps/hosted/cloud/src/implementation/test-stage-commands.ts b/apps/hosted/cloud/src/implementation/test-stage-commands.ts
index c6ae1881cd..fb2dce80c2 100644
--- a/apps/hosted/cloud/src/implementation/test-stage-commands.ts
+++ b/apps/hosted/cloud/src/implementation/test-stage-commands.ts
@@ -1,6 +1,18 @@
/** Deploy isolated previews with explicit database, retention and background policies. */
import { createHash } from "node:crypto";
-import { Clock, Config, Console, Effect, FileSystem, Option, Path, Result, Schema } from "effect";
+import {
+ Clock,
+ Config,
+ Console,
+ Duration,
+ Effect,
+ FileSystem,
+ Option,
+ Path,
+ Result,
+ Schema,
+ Stream,
+} from "effect";
import { Argument, Command, Flag } from "effect/cli";
import { ChildProcess, ChildProcessSpawner } from "effect/process";
import { testStagePrefix } from "../infrastructure/stage.ts";
@@ -18,9 +30,11 @@ import {
import { ReleaseRefusal, releaseRefusalReport } from "../contracts/release-guard.ts";
import { withStageAdmin } from "./test-stage-inventory.ts";
import { discoverTestStages } from "./test-stage-discovery.ts";
+import { accountLimits, accountUsage, capacityCheck } from "./test-stage-capacity.ts";
import { findOrphanBranches } from "./test-stage-orphans.ts";
import { branchGone, branchOutcomeMessage, removeStageBranch } from "./test-stage-branch.ts";
import { awaitStageRollout } from "./test-stage-rollout.ts";
+import { isDeployOutcomeLine, retrySignature } from "./test-stage-deploy-retry.ts";
import {
destroyUnreadableStage,
inventoryCount,
@@ -58,6 +72,57 @@ const runChild = (command: ChildProcess.Command) =>
const code = Number(yield* spawner.exitCode(command));
if (code !== 0) return yield* failure(`The child command exited with status ${code}.`);
});
+/**
+ * Run a child, passing its output through as it comes, and return its exit status with the lines
+ * of Alchemy's outcome (its failed resources and summary) that a retry is decided on.
+ */
+const runChildReading = (command: ChildProcess.Command) =>
+ Effect.gen(function* () {
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
+ const child = yield* spawner.spawn(command);
+ const pass = (stream: Stream.Stream, to: NodeJS.WriteStream) =>
+ stream.pipe(
+ Stream.tap((chunk) => Effect.sync(() => to.write(chunk))),
+ Stream.decodeText(),
+ Stream.splitLines,
+ Stream.filter(isDeployOutcomeLine),
+ Stream.runCollect,
+ );
+ const [out, err, code] = yield* Effect.all(
+ [pass(child.stdout, process.stdout), pass(child.stderr, process.stderr), child.exitCode],
+ { concurrency: "unbounded" },
+ );
+ return { code: Number(code), lines: [...out, ...err] };
+ }).pipe(Effect.scoped);
+/**
+ * Deploy a stage this run created. A deploy that fails only with one of `retrySignatures` runs
+ * once more, after a short wait for the Hyperdrive origin. Any other failure, a release guard's
+ * refusal and a second failure stop it as before, with every attempt's output in the log.
+ */
+const deployNewStage = (command: ChildProcess.Command, report: string) =>
+ Effect.gen(function* () {
+ const stopped = (code: number) =>
+ Effect.gen(function* () {
+ const refusal = yield* releaseRefusal(report);
+ return yield* Option.isSome(refusal)
+ ? refusal.value
+ : failure(`The child command exited with status ${code}.`);
+ });
+ const first = yield* runChildReading(command);
+ if (first.code === 0) return;
+ const signature = retrySignature(first.lines);
+ if (signature === undefined || Option.isSome(yield* releaseRefusal(report)))
+ return yield* stopped(first.code);
+ const wait = yield* Config.Duration("TEST_STAGE_DEPLOY_RETRY_WAIT").pipe(
+ Config.withDefault(Duration.seconds(60)),
+ );
+ yield* Console.log(
+ `Retrying the deploy once (${signature.name}): its first attempt failed only because ${signature.description}; waiting ${Duration.format(wait)} first.`,
+ );
+ yield* Effect.sleep(wait);
+ const second = yield* runChildReading(command);
+ if (second.code !== 0) return yield* stopped(second.code);
+ });
/** A release guard's refusal recorded by the Alchemy process, if it stopped the deploy. */
const releaseRefusal = (report: string) =>
Effect.gen(function* () {
@@ -235,6 +300,11 @@ const operation = (name: "deploy" | "plan") =>
telemetry: Flag.Literals("telemetry", ["export", "off"]).pipe(Flag.withDefault("off")),
noInput: Flag.Boolean("no-input").pipe(Flag.withDefault(false)),
yes: Flag.Boolean("yes").pipe(Flag.withDefault(false)),
+ // `deploy` only: refuse, rather than evict, a deploy that would replace another test stage.
+ // `plan` has no such flag, as before.
+ ...(name === "deploy"
+ ? { noEvict: Flag.Boolean("no-evict").pipe(Flag.withDefault(false)) }
+ : {}),
},
(input) =>
withStageAdmin((admin) =>
@@ -266,27 +336,61 @@ const operation = (name: "deploy" | "plan") =>
// A new stage replaces the oldest ones beyond the limit, before it creates resources.
// An eviction that fails does not stop this deploy, whose author did not cause it, but
// it is reported where they look: the log, a run annotation and the job summary.
+ const evictions =
+ existing === undefined ? stagesToEvict(yield* admin.list, input.slug) : [];
+ // With `--no-evict`, the same list at the same instant refuses the deploy instead, before
+ // it reserves, builds, deploys or destroys anything.
+ if ("noEvict" in input && input.noEvict === true && evictions.length > 0)
+ return yield* failure(
+ `Deploying ${input.slug} would evict ${evictions.length} test stage${evictions.length === 1 ? "" : "s"} to stay within ${testStageLimit}: ${evictions.map((stage) => `${stage.slug} (${oneLine(stage.owner)})`).join(", ")}. --no-evict refuses it, so nothing was reserved, deployed or destroyed. Destroy test stages you own, then deploy again.`,
+ );
+ // A new stage adds Workers and Durable Object classes, both account quotas. One past a
+ // configured quota is refused here rather than failing part way through Alchemy's apply;
+ // past only Cloudflare's documented figure, it warns and goes on. The stages it evicts are
+ // counted as freed, and checked again below with only the evictions that succeeded.
+ const usage = existing === undefined ? yield* accountUsage : undefined;
+ const limits = yield* accountLimits;
+ const capacity =
+ usage === undefined
+ ? undefined
+ : capacityCheck(
+ usage,
+ limits,
+ input.slug,
+ evictions.map((stage) => stage.slug),
+ );
+ if (capacity?.refusal !== undefined) return yield* failure(capacity.refusal);
+ if (capacity?.warning !== undefined) yield* Console.error(capacity.warning);
+ const evicted: string[] = [];
if (existing === undefined)
- for (const stage of stagesToEvict(yield* admin.list, input.slug)) {
+ for (const stage of evictions) {
yield* Console.log(
`${name === "deploy" ? "Evicting" : "Deploying will evict"} the oldest test stage, ${stage.slug} (${oneLine(stage.owner)}), to stay within ${testStageLimit}.`,
);
if (name !== "deploy") continue;
- const evicted = yield* destroy(stage.slug, {
+ const outcome = yield* destroy(stage.slug, {
automatic: false,
expectedOwner: Option.none(),
byName: false,
}).pipe(Effect.result);
- if (Result.isSuccess(evicted)) yield* Console.log(`Evicted ${stage.slug}.`);
- else
+ if (Result.isSuccess(outcome)) {
+ evicted.push(stage.slug);
+ yield* Console.log(`Evicted ${stage.slug}.`);
+ } else
yield* reportEvictionFailure(
stage,
- Schema.is(TestStageFailed)(evicted.failure)
- ? evicted.failure.message
+ Schema.is(TestStageFailed)(outcome.failure)
+ ? outcome.failure.message
: "its teardown failed",
(yield* admin.list).length + 1,
);
}
+ if (name === "deploy" && usage !== undefined && evicted.length < evictions.length) {
+ const again = capacityCheck(usage, limits, input.slug, evicted, true);
+ if (again.refusal !== undefined) return yield* failure(again.refusal);
+ if (again.warning !== undefined && capacity?.warning === undefined)
+ yield* Console.error(again.warning);
+ }
const lease =
name === "deploy"
? yield* admin.reserve(metadata)
@@ -333,7 +437,7 @@ const operation = (name: "deploy" | "plan") =>
yield* (yield* FileSystem.FileSystem).makeTempDirectoryScoped(),
"release-refusal.json",
);
- yield* runChild(
+ const alchemy = (output: "inherit" | "pipe") =>
ChildProcess.make(
"alchemy",
[name, ...(input.noInput ? ["--no-input"] : []), ...(input.yes ? ["--yes"] : [])],
@@ -341,18 +445,24 @@ const operation = (name: "deploy" | "plan") =>
env: { ...env, ...apps, [releaseRefusalReport]: report },
extendEnv: true,
stdin: "inherit",
- stdout: "inherit",
- stderr: "inherit",
+ stdout: output,
+ stderr: output,
},
- ),
- ).pipe(
- Effect.catchTag("TestStageFailed", (failed) =>
- Effect.gen(function* () {
- const refusal = yield* releaseRefusal(report);
- return yield* Option.isSome(refusal) ? refusal.value : failed;
- }),
- ),
- );
+ );
+ // Only a stage this run created is retried; a redeploy and a plan run as before. Its
+ // output is read only when it is not a terminal, where Alchemy is non-interactive
+ // already (CI), so reading it changes nothing Alchemy shows or asks.
+ if (name === "deploy" && existing === undefined && process.stdout.isTTY !== true)
+ yield* deployNewStage(alchemy("pipe"), report);
+ else
+ yield* runChild(alchemy("inherit")).pipe(
+ Effect.catchTag("TestStageFailed", (failed) =>
+ Effect.gen(function* () {
+ const refusal = yield* releaseRefusal(report);
+ return yield* Option.isSome(refusal) ? refusal.value : failed;
+ }),
+ ),
+ );
}).pipe(Effect.scoped, Effect.timeout(testStageDeployMilliseconds));
if (name === "deploy") {
const domain = yield* Config.String("TEST_STAGE_DOMAIN").pipe(
diff --git a/apps/hosted/cloud/src/implementation/test-stage-deploy-retry.ts b/apps/hosted/cloud/src/implementation/test-stage-deploy-retry.ts
new file mode 100644
index 0000000000..fcf5327023
--- /dev/null
+++ b/apps/hosted/cloud/src/implementation/test-stage-deploy-retry.ts
@@ -0,0 +1,68 @@
+/**
+ * A transient Cloudflare answer makes a new test stage's `alchemy deploy` fail through no fault of
+ * the change under test. `test-stage deploy` retries a new stage's deploy once when its failed
+ * output shows it and nothing else (notes/test-stages.md, "Retrying a new stage's
+ * deploy"). Alchemy's plain log has one `[] fail — ` line for each failed resource and
+ * ends with `Failed: succeeded, failed` (alchemy `Cli/LoggingCli.ts`).
+ */
+
+/** Why a failed deploy is retried. */
+export interface RetrySignature {
+ readonly name: "hyperdrive-origin";
+ /** What failed, for the one log line that says the deploy was retried. */
+ readonly description: string;
+ /** Whether a failed resource's message is this signature's. */
+ readonly matches: (message: string) => boolean;
+ /** A resource that must be among the failed ones, as the failure's cause. */
+ readonly cause: string;
+}
+
+/**
+ * Cloudflare checks a Hyperdrive config's origin when it is created. On a new PlanetScale branch
+ * the pooled origin can still refuse that check after migrations reached the branch directly.
+ * Resources that depend on the config fail with the same message.
+ */
+const hyperdriveOrigin: RetrySignature = {
+ name: "hyperdrive-origin",
+ description:
+ "Hyperdrive config DatabaseConnection could not reach the new database's pooled origin",
+ matches: (message) =>
+ message.includes("BadRequest: Network connection to the provided database timed out."),
+ cause: "DatabaseConnection",
+};
+
+export const retrySignatures: ReadonlyArray = [hyperdriveOrigin];
+
+// oxlint-disable-next-line no-control-regex -- Alchemy colours its status lines.
+const colour = /\u001b\[[0-9;]*m/gu;
+const failed = /\[([^\]\s]+)\] fail(?= |$)(.*)$/u;
+const summary = /\bFailed: \d+ succeeded, (\d+) failed\b/u;
+
+/** Whether a line of the deploy's output is one the signatures are read from. */
+export const isDeployOutcomeLine = (line: string) => {
+ const plain = line.replaceAll(colour, "");
+ return failed.test(plain) || summary.test(plain);
+};
+
+/**
+ * The signature a failed deploy's output shows, if every failed resource failed with it and the
+ * summary counts no other failure. Anything else, or an output without a summary, is not retried.
+ */
+export const retrySignature = (lines: ReadonlyArray): RetrySignature | undefined => {
+ const plain = lines.map((line) => line.replaceAll(colour, ""));
+ const counted = plain.flatMap((line) => {
+ const match = summary.exec(line);
+ return match === null ? [] : [Number(match[1])];
+ });
+ if (counted.length !== 1) return undefined;
+ const failures = new Map>();
+ for (const line of plain) {
+ const match = failed.exec(line);
+ if (match !== null) failures.set(match[1]!, [...(failures.get(match[1]!) ?? []), match[2]!]);
+ }
+ if (failures.size === 0 || failures.size !== counted[0]) return undefined;
+ const messages = [...failures.values()].flat();
+ return retrySignatures.find(
+ (signature) => messages.every(signature.matches) && failures.has(signature.cause),
+ );
+};
diff --git a/apps/hosted/cloud/src/implementation/test-stage-unreadable.ts b/apps/hosted/cloud/src/implementation/test-stage-unreadable.ts
index 18f2e007e9..b16ba5e0d0 100644
--- a/apps/hosted/cloud/src/implementation/test-stage-unreadable.ts
+++ b/apps/hosted/cloud/src/implementation/test-stage-unreadable.ts
@@ -47,6 +47,7 @@ const workerIds = [
"AppData",
"AppDomainController",
"AppOutbound",
+ "AppOutboundRelay",
"AppPages",
"ArtifactsCredentials",
"Authoring",
diff --git a/apps/hosted/cloud/src/implementation/v1-legacy-mcp.ts b/apps/hosted/cloud/src/implementation/v1-legacy-mcp.ts
index 9c7067cfe3..b076e5f3b4 100644
--- a/apps/hosted/cloud/src/implementation/v1-legacy-mcp.ts
+++ b/apps/hosted/cloud/src/implementation/v1-legacy-mcp.ts
@@ -18,6 +18,7 @@ import {
McpForbidden,
McpUnauthorized,
OrganizationId,
+ patConnectionPolicy,
patGrantId,
patGrantOf,
recordAuthFailure,
@@ -29,10 +30,10 @@ import {
legacyMcpResourceMetadataUrl,
legacyMcpTarget,
requestedMcpAddress,
+ namedApprovalMode,
type LegacyMcpPath,
type ResourceOrigins,
} from "@executor-js/mcp-auth";
-import { ConnectionPolicy, connectionGrantPolicy } from "@executor-js/mcp-auth/connections";
import { ApprovalMode } from "@executor-js/mcp-auth/grants";
import { APIError } from "better-auth/api";
import { Clock, Effect, Option, Schema } from "effect";
@@ -225,7 +226,9 @@ export const legacyMcp = (
const resolved = yield* lookup(withSql, resolvePath(path));
if (Option.isNone(resolved)) return mcpNotFound;
const organization = resolved.value.organization;
- const query = address.mode === "model" ? "" : `?elicitation_mode=${address.mode}`;
+ // Forward the mode only when the legacy URL spells one out, so a key there keeps its default.
+ const named = namedApprovalMode(url);
+ const query = named === undefined ? "" : `?elicitation_mode=${named}`;
const target = Option.match(organization, {
onNone: () => `/mcp${query}`,
onSome: (found) => `/org/${encodeURIComponent(found.v2)}/mcp${query}`,
@@ -265,13 +268,6 @@ export const legacyMcp = (
: response;
});
-const ConnectionRow = Schema.Struct({
- userId: Schema.String,
- resource: Schema.NullOr(Schema.String),
- policy: Schema.String,
- revoked: Schema.Boolean,
-});
-
/**
* The access a request rewritten from a v1 toolkit URL has: the caller's own copy of the toolkit.
* An OAuth grant must be the copy's own, which a grant made for the URL is; another is refused as
@@ -298,16 +294,13 @@ export const legacyToolkitAccess = (headers: Headers, access: McpAccess) =>
});
if (Option.isNone(copy)) return yield* refuse;
const sql = yield* SqlClient.SqlClient;
- const rows = yield* sql`
- select "userId", resource, policy, revoked from "mcpConnection" where id = ${copy.value}`;
- const row = (yield* Schema.decodeUnknownEffect(Schema.Array(ConnectionRow))(rows))[0];
- if (
- row === undefined ||
- row.revoked ||
- row.userId !== access.userId ||
- row.resource !== access.access.organization
- )
- return yield* refuse;
+ const scope = yield* patConnectionPolicy(
+ sql,
+ copy.value,
+ access.userId,
+ access.access.organization,
+ );
+ if (Option.isNone(scope)) return yield* refuse;
const target = access.grant.target;
const pat = patGrantOf(access.grant.id);
if (Option.isNone(pat)) {
@@ -320,11 +313,10 @@ export const legacyToolkitAccess = (headers: Headers, access: McpAccess) =>
const mode = target.kind === "mcp" ? target.mode : "model";
return McpAccess.make({
...access,
+ connectionRevision: scope.value.revision,
grant: {
id: patGrantId({ ...pat.value, connection: copy.value }),
- policy: connectionGrantPolicy(
- yield* Schema.decodeUnknownEffect(Schema.fromJsonString(ConnectionPolicy))(row.policy),
- ),
+ policy: scope.value.policy,
target: { kind: "mcp", mode, connection: copy.value },
},
});
diff --git a/apps/hosted/cloud/src/implementation/v1-mcp-forward.ts b/apps/hosted/cloud/src/implementation/v1-mcp-forward.ts
index 639e15c66c..402d58180d 100644
--- a/apps/hosted/cloud/src/implementation/v1-mcp-forward.ts
+++ b/apps/hosted/cloud/src/implementation/v1-mcp-forward.ts
@@ -19,6 +19,7 @@ import {
McpApprovalForbidden,
McpForbidden,
McpUnauthorized,
+ mcpConnectionRevision,
OrganizationId,
OrganizationRole,
organizationOwner,
@@ -153,16 +154,22 @@ const verify = (secret: Redacted.Redacted, token: string) =>
return claims;
});
+const storedConnectionFields = {
+ connectionUser: Schema.NullOr(Schema.String),
+ connectionResource: Schema.NullOr(Schema.String),
+ connectionPolicy: Schema.NullOr(Schema.String),
+ connectionRevoked: Schema.NullOr(Schema.Boolean),
+ connectionCreatedAt: Schema.NullOr(Schema.Number),
+ connectionUpdatedAt: Schema.NullOr(Schema.Number),
+};
+
const Row = Schema.Struct({
userId: Schema.NullOr(Schema.String),
organization: Schema.NullOr(Schema.String),
slug: Schema.NullOr(Schema.String),
role: Schema.NullOr(Schema.String),
toolkitConnection: Schema.NullOr(Schema.String),
- connectionUser: Schema.NullOr(Schema.String),
- connectionResource: Schema.NullOr(Schema.String),
- connectionPolicy: Schema.NullOr(Schema.String),
- connectionRevoked: Schema.NullOr(Schema.Boolean),
+ ...storedConnectionFields,
});
/** Everything one check reads, in one statement: the mapped user and organization and the rest. */
@@ -190,7 +197,9 @@ const load = (sql: SqlClient.SqlClient, claims: Claims) =>
mc."userId" as "connectionUser",
mc.resource as "connectionResource",
mc.policy as "connectionPolicy",
- mc.revoked as "connectionRevoked"
+ mc.revoked as "connectionRevoked",
+ floor(extract(epoch from mc."createdAt") * 1000)::float8 as "connectionCreatedAt",
+ floor(extract(epoch from mc."updatedAt") * 1000)::float8 as "connectionUpdatedAt"
from (select 1) one
left join "mcpConnection" mc on mc.id = (select v2_id from t)`.pipe(
Effect.flatMap((rows) => Schema.decodeUnknownEffect(Row)(rows[0])),
@@ -203,6 +212,8 @@ interface StoredConnection {
readonly resource: string | null;
readonly policy: string | null;
readonly revoked: boolean | null;
+ readonly createdAt: number | null;
+ readonly updatedAt: number | null;
}
/**
@@ -230,6 +241,7 @@ const grantedAccess = (
);
const stored = input.connection;
let policy: GrantPolicy = { kind: "all" };
+ let connectionRevision: string | undefined;
if (stored !== undefined) {
if (
stored.revoked !== false ||
@@ -237,8 +249,16 @@ const grantedAccess = (
stored.resource !== organization
)
return yield* Effect.fail(refuse);
- policy = connectionGrantPolicy(
- yield* Schema.decodeUnknownEffect(Schema.fromJsonString(ConnectionPolicy))(stored.policy),
+ const livePolicy = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(ConnectionPolicy))(
+ stored.policy,
+ );
+ policy = connectionGrantPolicy(livePolicy);
+ if (stored.createdAt === null || stored.updatedAt === null)
+ return yield* new AuthenticationUnavailable();
+ connectionRevision = yield* mcpConnectionRevision(
+ stored.createdAt,
+ stored.updatedAt,
+ livePolicy,
);
}
const connection = stored?.id;
@@ -246,6 +266,8 @@ const grantedAccess = (
return McpAccess.make({
userId: input.user,
clientId: v1ForwardClient,
+ ...(connection === undefined ? {} : { verifiedConnection: connection }),
+ ...(connectionRevision === undefined ? {} : { connectionRevision }),
grant: {
id: grantId({ user: input.user, organization, mode: input.mode, connection }),
policy,
@@ -335,6 +357,8 @@ export const v1ForwardAccess = (
resource: row.connectionResource,
policy: row.connectionPolicy,
revoked: row.connectionRevoked,
+ createdAt: row.connectionCreatedAt,
+ updatedAt: row.connectionUpdatedAt,
},
address: claims.connection,
},
@@ -359,10 +383,7 @@ export const isV1ForwardGrant = (id: string) => id.startsWith(grantPrefix);
const BrowserRow = Schema.Struct({
role: Schema.NullOr(Schema.String),
- connectionUser: Schema.NullOr(Schema.String),
- connectionResource: Schema.NullOr(Schema.String),
- connectionPolicy: Schema.NullOr(Schema.String),
- connectionRevoked: Schema.NullOr(Schema.Boolean),
+ ...storedConnectionFields,
});
/**
@@ -392,7 +413,9 @@ export const v1ForwardBrowserAccess = (id: string, sessionUser: string | undefin
mc."userId" as "connectionUser",
mc.resource as "connectionResource",
mc.policy as "connectionPolicy",
- mc.revoked as "connectionRevoked"
+ mc.revoked as "connectionRevoked",
+ floor(extract(epoch from mc."createdAt") * 1000)::float8 as "connectionCreatedAt",
+ floor(extract(epoch from mc."updatedAt") * 1000)::float8 as "connectionUpdatedAt"
from (select 1) one
left join "mcpConnection" mc on mc.id = ${connection}`;
const row = yield* Schema.decodeUnknownEffect(BrowserRow)(rows[0]);
@@ -411,6 +434,8 @@ export const v1ForwardBrowserAccess = (id: string, sessionUser: string | undefin
resource: row.connectionResource,
policy: row.connectionPolicy,
revoked: row.connectionRevoked,
+ createdAt: row.connectionCreatedAt,
+ updatedAt: row.connectionUpdatedAt,
},
},
refuse,
diff --git a/apps/hosted/cloud/src/infrastructure/app-outbound.ts b/apps/hosted/cloud/src/infrastructure/app-outbound.ts
index fdca680b00..d187b0b4d9 100644
--- a/apps/hosted/cloud/src/infrastructure/app-outbound.ts
+++ b/apps/hosted/cloud/src/infrastructure/app-outbound.ts
@@ -2,7 +2,7 @@
import * as Cloudflare from "alchemy/Cloudflare";
import { AlchemyContext } from "alchemy/AlchemyContext";
import { Random } from "alchemy";
-import { Cause, Effect, Redacted, Schema } from "effect";
+import { Cause, Effect, Option, Redacted, Schema } from "effect";
import { HttpServerRequest, HttpServerResponse } from "effect/http";
import { recordRoute } from "@executor-js/telemetry";
import type { Fetcher } from "@cloudflare/workers-types";
@@ -12,10 +12,14 @@ import {
HostApiCheck,
NetworkUnreachable,
networkUnreachableResponse,
+ outboundGroupHeader,
} from "@executor-js/sdk/workerd";
import { type AppEgressFailed, egressFailure } from "../implementation/app-egress.ts";
+import { type RelayObjects, relayed, relayScript } from "../implementation/app-outbound-relay.ts";
+import { appOutboundRoutes, type Sent } from "../implementation/app-outbound-routes.ts";
import { cloudSentry, reportCloudFailure } from "../implementation/error-reporting.ts";
import { platformObservability } from "./telemetry.ts";
+import { cloudHosts } from "./stage.ts";
export const AppOutbound = Effect.gen(function* () {
if (globalThis.__ALCHEMY_RUNTIME__) return yield* Cloudflare.Worker.ref("AppOutbound");
@@ -33,6 +37,26 @@ export const AppOutbound = Effect.gen(function* () {
});
});
+/**
+ * The relay's own Worker, with `AppOutbound`'s flags and no bindings or credentials besides its
+ * objects. It is a Worker of its own so that removing it is the last step of a deploy that stops
+ * using it: Alchemy deletes a removed Worker, and its class with it, after updating the Workers
+ * that bound it, so a plain revert never deletes the class while AppData still sends to it.
+ */
+export const AppOutboundRelay = Effect.gen(function* () {
+ if (globalThis.__ALCHEMY_RUNTIME__) return yield* Cloudflare.Worker.ref("AppOutboundRelay");
+ return yield* Cloudflare.Worker("AppOutboundRelay", {
+ workersDev: false,
+ compatibility: {
+ date: "2026-09-08",
+ flags: ["global_fetch_strictly_public", "no_brotli_content_encoding"],
+ },
+ script: relayScript,
+ env: { AppOutboundRelay: Cloudflare.DurableObject("AppOutboundRelay") },
+ ...(yield* platformObservability),
+ });
+});
+
/**
* Worker props for the Worker that serves app requests. Deployed, `AppOutbound`'s public-only
* network refuses private, loopback and internal destinations with Cloudflare's own 403 or 530,
@@ -60,6 +84,26 @@ const NativeNetwork = Schema.declare(
"fetch" in value &&
typeof value.fetch === "function",
);
+const NativeRelayObjects = Schema.declare(
+ (value): value is RelayObjects =>
+ typeof value === "object" &&
+ value !== null &&
+ "idFromName" in value &&
+ typeof value.idFromName === "function" &&
+ "get" in value &&
+ typeof value.get === "function",
+);
+
+/** The routes of this isolate's app requests; see `app-outbound-routes.ts`. */
+const routes = appOutboundRoutes();
+
+/** `request` without the group's name, with its body, signal and redirect mode. */
+const withoutGroup = (request: Request) => {
+ const headers = new Headers(request.headers);
+ headers.delete(outboundGroupHeader);
+ return new Request(request, { headers });
+};
+
type Loopback = (options: { readonly props: typeof OutboundProps.Type }) => Fetcher;
const Exports = Schema.Struct({
exports: Schema.Struct({
@@ -76,11 +120,30 @@ const Exports = Schema.Struct({
*/
export const appCredentialOutbound = Effect.gen(function* () {
const network = yield* AppOutbound;
+ const relay = yield* AppOutboundRelay;
const worker = yield* Cloudflare.Worker;
yield* worker.bind`${network}`({
bindings: [{ type: "service", name: "AppOutbound", service: network.workerName }],
});
+ yield* worker.bind`${relay}`({
+ bindings: [
+ {
+ type: "durable_object_namespace",
+ name: "AppOutboundRelay",
+ className: "AppOutboundRelay",
+ scriptName: relay.workerName,
+ },
+ ],
+ });
const environment = yield* Cloudflare.WorkerEnvironment;
+ const { resourceOrigins, roles } = yield* cloudHosts.pipe(Effect.orDie);
+ const hostOrigins = [
+ ...resourceOrigins.api,
+ ...resourceOrigins.mcp,
+ ...(resourceOrigins.legacyMcp === undefined ? [] : [resourceOrigins.legacyMcp]),
+ // The app role serves the dashboard API even when browser pages run on deployment.
+ ...(Option.isSome(roles) ? [roles.value.origins.app] : []),
+ ];
// The runner and this Worker's outbound entrypoint share it; app code never receives it.
const secret = yield* (yield* Random("AppCredentialKey")).text;
const key = secret.pipe(Effect.flatMap((value) => credentialKey(Redacted.value(value))));
@@ -96,6 +159,15 @@ export const appCredentialOutbound = Effect.gen(function* () {
);
return {
key,
+ /**
+ * Count the app requests of calls naming `group` against one incoming request, for as long as
+ * the scope; see `app-outbound-routes.ts`.
+ */
+ outboundGroup: (group: string) =>
+ Effect.acquireRelease(
+ Effect.sync(() => routes.hold(group)),
+ (release) => Effect.sync(release),
+ ).pipe(Effect.asVoid),
/** The network one app's isolates use for global `fetch`. */
outbound: Effect.gen(function* () {
const exports = yield* loopback;
@@ -122,12 +194,28 @@ export const appCredentialOutbound = Effect.gen(function* () {
if (props._tag === "None") return yield* handler;
// The path is the app's request to its upstream, so its span records none of it.
yield* recordRoute("/:upstream");
+ // Which app sent it, so its route can be read with the app's other spans.
+ yield* Effect.annotateCurrentSpan("executor.app.id", props.value.appOutbound);
const request = yield* HttpServerRequest.HttpServerRequest;
- const source = request.source;
- if (!(source instanceof Request)) return yield* Effect.die("App request is not a Request");
- const send = yield* Schema.decodeUnknownEffect(NativeNetwork)(environment.AppOutbound).pipe(
- Effect.orDie,
- );
+ const received = request.source;
+ if (!(received instanceof Request))
+ return yield* Effect.die("App request is not a Request");
+ // The group the runner named for the call's incoming request goes no further.
+ const group = received.headers.get(outboundGroupHeader);
+ const source = group === null ? received : withoutGroup(received);
+ const network = yield* Schema.decodeUnknownEffect(NativeNetwork)(
+ environment.AppOutbound,
+ ).pipe(Effect.orDie);
+ const relay = yield* Schema.decodeUnknownEffect(NativeRelayObjects)(
+ environment.AppOutboundRelay,
+ ).pipe(Effect.orDie);
+ // How each request was sent, for the span once the app's request is answered.
+ const sent: Array = [];
+ const transport = {
+ direct: (request: Request) => network.fetch(request),
+ relay: (slot: number, request: Request) => relayed(relay, slot, request),
+ };
+ const send = (request: Request) => routes.send(group, request, transport, sent);
// The secret is read from this event's Worker environment.
const sealing = yield* key;
const privateFetch = yield* Schema.decodeUnknownEffect(Schema.Boolean)(
@@ -144,10 +232,11 @@ export const appCredentialOutbound = Effect.gen(function* () {
? {}
: { callerConnection: props.value.callerConnection }),
key: sealing,
+ hostOrigins,
// Cloud's own origin is public, so it needs no exemption.
egress: { refusePrivateAddresses: !privateFetch, selfOrigin: undefined },
send: (request) =>
- send.fetch(request).catch((error: unknown) => {
+ send(request).catch((error: unknown) => {
if (!source.signal.aborted) unsent = egressFailure("send", error);
throw error;
}),
@@ -164,6 +253,13 @@ export const appCredentialOutbound = Effect.gen(function* () {
),
),
);
+ const last = sent.at(-1);
+ if (last !== undefined)
+ yield* Effect.annotateCurrentSpan(
+ Object.fromEntries(
+ Object.entries(last).map(([name, value]) => [`executor.outbound.${name}`, value]),
+ ),
+ );
if (unsent !== undefined) yield* report(unsent);
return HttpServerResponse.fromWeb(response);
}),
diff --git a/apps/hosted/cloud/src/infrastructure/data-steps.ts b/apps/hosted/cloud/src/infrastructure/data-steps.ts
index 5928c75b5c..3867d7c2fa 100644
--- a/apps/hosted/cloud/src/infrastructure/data-steps.ts
+++ b/apps/hosted/cloud/src/infrastructure/data-steps.ts
@@ -9,9 +9,14 @@
* Each tick's outcome counts the items it handled: `partial` or `failed` when some or all of them
* ended with an outcome their step retries. A tick that only waited for a lease or a backoff, or
* ran out of time, records `completed`.
+ *
+ * The catalog-copy rebuild applies in stages: `CLOUD_CATALOG_COPY_REBUILD_SCOPE` names the copies
+ * a stage may change (none when unset), and `CLOUD_CATALOG_COPY_REBUILD_PACE` the compiler builds
+ * one tick starts for it, in report and apply alike. See notes/catalog-copy-rebuild.md.
*/
import { AppManagementHost } from "@executor-js/app-management";
import {
+ catalogCopyRebuildScope,
hostDataSteps,
runDataSteps,
type AgentGrantExpiry,
@@ -31,6 +36,18 @@ import { jobUnitCounts } from "../contracts/job-outcome.ts";
/** A tick stops starting items after this long, then resumes from its cursor on the next tick. */
const tickBudgetMs = 20_000;
+/**
+ * The compiler builds one tick starts for the catalog-copy rebuild when no deploy sets a pace.
+ * Measured on a test stage (notes/catalog-copy-rebuild.md, "Load").
+ */
+const catalogCopyRebuildPace = 2;
+
+/**
+ * Retry passes before a catalog copy still failing is recorded `gave-up`: about 30 seconds,
+ * doubling to an hour, so about a day of retries.
+ */
+const catalogCopyRebuildPasses = 24;
+
/**
* The last step that `apply` applies when no deploy names one. Steps after it report however
* `CLOUD_DATA_STEPS` is set, so a new step ships in report mode even where earlier steps apply.
@@ -68,6 +85,21 @@ export const cloudDataSteps = (agentGrants: AgentGrantExpiry) =>
Config.withDefault(""),
);
const applyThrough = named === "" ? reviewedThrough : named;
+ const scopeText = yield* Config.String("CLOUD_CATALOG_COPY_REBUILD_SCOPE").pipe(
+ Config.withDefault(""),
+ );
+ // An unreadable scope selects nothing rather than a guess at what was meant.
+ const scope = yield* catalogCopyRebuildScope(scopeText).pipe(
+ Effect.catchTag("CatalogCopyRebuildScopeInvalid", (error) =>
+ Effect.logError("CLOUD_CATALOG_COPY_REBUILD_SCOPE cannot be read", error.token).pipe(
+ Effect.andThen(catalogCopyRebuildScope("")),
+ ),
+ ),
+ );
+ const paceText = yield* Config.String("CLOUD_CATALOG_COPY_REBUILD_PACE").pipe(
+ Config.withDefault(""),
+ );
+ const pace = /^\d+$/u.test(paceText) ? Number(paceText) : catalogCopyRebuildPace;
// The build framework step rewrites retained builds in the same bucket the executor reads.
const blobs = yield* cloudBlobs;
return Effect.gen(function* () {
@@ -82,6 +114,13 @@ export const cloudDataSteps = (agentGrants: AgentGrantExpiry) =>
agentGrants,
executorAppRedeployed: executorDefaultRedeployed(wake),
appCopies: hostedAppCopies(executor),
+ // Cloud lists the catalog-copy rebuild; it reports until a deploy names it (above).
+ catalogCopyRebuild: {
+ rebuilt: () => wake,
+ scope,
+ pace,
+ passes: catalogCopyRebuildPasses,
+ },
});
const run = (selected: typeof steps, selectedMode: typeof mode) =>
runDataSteps(selected, {
@@ -104,7 +143,12 @@ export const cloudDataSteps = (agentGrants: AgentGrantExpiry) =>
: tickOutcome(applied);
}).pipe(
Effect.withSpan("job.data-steps", {
- attributes: { "data_step.mode": mode, "data_step.apply_through": applyThrough },
+ attributes: {
+ "data_step.mode": mode,
+ "data_step.apply_through": applyThrough,
+ "data_step.catalog_rebuild_run": scope.run,
+ "data_step.catalog_rebuild_pace": pace,
+ },
}),
);
}).pipe(Effect.orDie);
diff --git a/apps/hosted/cloud/src/infrastructure/executor.ts b/apps/hosted/cloud/src/infrastructure/executor.ts
index 4ca61a6fb0..7014479557 100644
--- a/apps/hosted/cloud/src/infrastructure/executor.ts
+++ b/apps/hosted/cloud/src/infrastructure/executor.ts
@@ -37,7 +37,13 @@ import { InvocationDatabase } from "./invocation-database.ts";
import { backgroundWait, CurrentRequest, ownTelemetryScope } from "./served-request.ts";
import { TelemetryDrainScope, TelemetryWaitReport } from "@executor-js/telemetry";
import { cloudSecrets } from "./secrets.ts";
-import { cloudOrigin, cloudResourceOrigins, productionStage, stageName } from "./stage.ts";
+import {
+ cloudOrigin,
+ cloudOwnerRevocationBudget,
+ cloudResourceOrigins,
+ productionStage,
+ stageName,
+} from "./stage.ts";
import { cloudEmulators } from "./emulators.ts";
import { missingFirstPartyGitHubClient } from "./first-party-oauth-settings.ts";
import { cloudAccountSignIns } from "../implementation/oauth-proxy-settings.ts";
@@ -113,6 +119,10 @@ export const cloudExecutor = Effect.fn(function* (
// The same tool listing settings as the other hosts; a stage deployed without them keeps the
// defaults. Memory limits are not read: every executor shares the isolate's store.
const { toolListings } = yield* declarationConfig.pipe(Effect.orDie);
+ // Only `alchemy dev` binds the switch; see `cloudOwnerRevocationBudget`.
+ const ownerRevocationBudget = yield* cloudOwnerRevocationBudget(
+ (yield* Cloudflare.WorkerEnvironment).REMOVAL_REVOCATION_BUDGET_SWITCH === true,
+ ).pipe(Effect.orDie);
const makeRuntime = yield* cloudRuntime(origin, databases);
const workflows = yield* cloudWorkflows;
const blobs = yield* cloudBlobs;
@@ -235,6 +245,7 @@ export const cloudExecutor = Effect.fn(function* (
// A tool listing nobody waits for runs until the event's background work ends, and is
// remembered as timed out if it has not finished by then.
background,
+ ...(ownerRevocationBudget === undefined ? {} : { ownerRevocationBudget }),
events: {
sender: httpEventSender(egress),
// The same event's client, which hosted permission checks already share.
diff --git a/apps/hosted/cloud/src/infrastructure/release-notes.ts b/apps/hosted/cloud/src/infrastructure/release-notes.ts
new file mode 100644
index 0000000000..63e8f4c498
--- /dev/null
+++ b/apps/hosted/cloud/src/infrastructure/release-notes.ts
@@ -0,0 +1,51 @@
+/**
+ * Cloud's "what's new" for a deploy. Writing the notes is a step of its own, which reads main's
+ * history (`scripts/releases/release-notes.ts --cloud `); the deploy names that file in
+ * `EXECUTOR_CLOUD_RELEASE_NOTES_FILE`, and the dashboard's build takes its notes as
+ * `EXECUTOR_CLOUD_RELEASE_NOTES` (apps/hosted/cloud/web/release-notes.ts).
+ *
+ * Production, which every Cloud user sees, must have them: a production deploy without the file,
+ * or with one that holds no such notes, stops here before anything builds. Any other stage,
+ * development and a checkout's own builds take the notes when a file is named, and otherwise build
+ * with none, which shows no "What's new".
+ */
+import { Config, Effect, FileSystem, Option, Schema } from "effect";
+import { CloudReleaseNotes } from "@executor-js/utils/release-notes";
+import { DeploySettingRejected } from "./deploy-settings.ts";
+import { productionStage, stageName } from "./stage.ts";
+
+const notesFile = "EXECUTOR_CLOUD_RELEASE_NOTES_FILE";
+
+/** The notes JSON the dashboard's build takes, or none for a build given no notes file. */
+export const cloudReleaseNotesInput = Effect.gen(function* () {
+ const file = yield* Config.String(notesFile).pipe(Config.option);
+ if (Option.isNone(file)) {
+ if (Option.getOrUndefined(yield* stageName) !== productionStage) return Option.none();
+ return yield* new DeploySettingRejected({
+ message:
+ `${notesFile} is unset; a production deploy builds Cloud's "What's new" from the notes ` +
+ "file the deploy workflow writes first (scripts/releases/release-notes.ts --cloud). " +
+ "Write it and name it, then deploy again. Nothing was deployed.",
+ });
+ }
+ const fs = yield* FileSystem.FileSystem;
+ const text = yield* fs.readFileString(file.value).pipe(
+ Effect.mapError(
+ () =>
+ new DeploySettingRejected({
+ message: `${notesFile} names ${file.value}, which cannot be read. Nothing was deployed.`,
+ }),
+ ),
+ );
+ const notes = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(CloudReleaseNotes))(
+ text,
+ ).pipe(
+ Effect.mapError(
+ () =>
+ new DeploySettingRejected({
+ message: `${file.value} (${notesFile}) does not hold Cloud's notes as scripts/releases/release-notes.ts --cloud writes them. Nothing was deployed.`,
+ }),
+ ),
+ );
+ return Option.some(JSON.stringify(notes));
+});
diff --git a/apps/hosted/cloud/src/infrastructure/runtime.ts b/apps/hosted/cloud/src/infrastructure/runtime.ts
index 8e76aeff52..5ec3fd2996 100644
--- a/apps/hosted/cloud/src/infrastructure/runtime.ts
+++ b/apps/hosted/cloud/src/infrastructure/runtime.ts
@@ -16,6 +16,7 @@ import {
assembleWorkerBundle,
declarationFailed,
remoteAppRunner,
+ RunnerUnanswered,
runsInFacet,
} from "@executor-js/sdk/workerd";
import { HostRequirementsError, DeclaredRequirements, HostResponse } from "apps/contracts";
@@ -29,6 +30,7 @@ import type { DurableObjectNamespace } from "@cloudflare/workers-types";
import { CloudCompileResult } from "../contracts/builds.ts";
import { AppCompiler } from "./compiler.ts";
import { AppData } from "./app-data-worker.ts";
+import { CurrentRequest } from "./served-request.ts";
import type { AppDataSupervisor } from "./app-data.ts";
import {
loadCloudBuildRecord,
@@ -84,6 +86,23 @@ const NativeNamespace = Schema.declare(
*/
const SupervisorRun = Schema.UndefinedOr(Schema.String);
+/** The group each incoming request's app calls name; see `AppInvocation.outboundGroup`. */
+const outboundGroups = new WeakMap